@t2000/cli 0.22.26 → 0.23.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.
- package/README.md +11 -97
- package/dist/{ccip-JEEJV65M.js → ccip-XP27NGI7.js} +3 -3
- package/dist/{chunk-A5X4KG7U.js → chunk-3I6VJOM6.js} +210 -970
- package/dist/chunk-3I6VJOM6.js.map +1 -0
- package/dist/chunk-4N76GQCL.js +35382 -0
- package/dist/chunk-4N76GQCL.js.map +1 -0
- package/dist/{chunk-XOAZJ42V.js → chunk-DWOZSUBE.js} +588 -584
- package/dist/{chunk-XOAZJ42V.js.map → chunk-DWOZSUBE.js.map} +1 -1
- package/dist/chunk-EI3GHTKX.js +968 -0
- package/dist/chunk-EI3GHTKX.js.map +1 -0
- package/dist/{chunk-EEPD7SHV.js → chunk-TYYJRUQI.js} +15755 -15918
- package/dist/chunk-TYYJRUQI.js.map +1 -0
- package/dist/client-5KJQTN5X.js +84 -0
- package/dist/client-5KJQTN5X.js.map +1 -0
- package/dist/{client-R3NRAXMD.js → client-IXUBQ3HM.js} +334 -638
- package/dist/client-IXUBQ3HM.js.map +1 -0
- package/dist/{dist-NBWIWHHS.js → dist-E7HUP73Q.js} +5 -29
- package/dist/{dist-KJM2NT74.js → dist-W4Q4YXD7.js} +4200 -603
- package/dist/dist-W4Q4YXD7.js.map +1 -0
- package/dist/index.js +29 -1016
- package/dist/index.js.map +1 -1
- package/package.json +4 -5
- package/dist/chunk-3WKGZRWT.js +0 -77733
- package/dist/chunk-3WKGZRWT.js.map +0 -1
- package/dist/chunk-77SWBATH.js +0 -204
- package/dist/chunk-77SWBATH.js.map +0 -1
- package/dist/chunk-A5X4KG7U.js.map +0 -1
- package/dist/chunk-EEPD7SHV.js.map +0 -1
- package/dist/client-CK5OR2TP.js +0 -746
- package/dist/client-CK5OR2TP.js.map +0 -1
- package/dist/client-R3NRAXMD.js.map +0 -1
- package/dist/dist-KJM2NT74.js.map +0 -1
- /package/dist/{ccip-JEEJV65M.js.map → ccip-XP27NGI7.js.map} +0 -0
- /package/dist/{dist-NBWIWHHS.js.map → dist-E7HUP73Q.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/getAction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/log.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/abi/encodeEventTopics.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/filters/createFilterRequestScope.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/createContractEventFilter.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/errors/getContractError.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/accounts/utils/publicKeyToAddress.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/signature/recoverPublicKey.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/signature/recoverAddress.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/encoding/toRlp.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/authorization/hashAuthorization.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/authorization/recoverAuthorizationAddress.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/estimateGas.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/errors/getEstimateGasError.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/fee.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/block.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/formatters/transaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/formatters/block.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getBlock.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getGasPrice.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/estimateMaxPriorityFeePerGas.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/estimateFeesPerGas.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getTransactionCount.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/blob/blobsToCommitments.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/blob/blobsToProofs.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/hash/sha256.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/blob/commitmentToVersionedHash.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/blob/commitmentsToVersionedHashes.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/constants/blob.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/constants/kzg.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/blob.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/blob/toBlobs.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/blob/toBlobSidecars.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/transaction/getTransactionType.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/errors/getTransactionError.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getChainId.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/fillTransaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/prepareTransactionRequest.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/estimateGas.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/formatters/log.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/abi/decodeEventLog.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/abi/parseEventLogs.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getLogs.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getContractEvents.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/readContract.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/observe.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/wait.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/poll.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/promise/withCache.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getBlockNumber.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getFilterChanges.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/uninstallFilter.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/watchContractEvent.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/account.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/chain/assertCurrentChain.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/sendRawTransaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/sendTransaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/writeContract.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/calls.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/promise/withRetry.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/formatters/transactionReceipt.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/sendCalls.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/getCallsStatus.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/waitForCallsStatus.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/uid.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/clients/createClient.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getCode.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/transaction/assertTransaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/transaction/serializeAccessList.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/transaction/serializeTransaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/authorization/serializeAuthorizationList.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/authorization/verifyAuthorization.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/promise/withDedupe.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/buildRequest.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/chain/defineChain.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/encoding/fromRlp.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/hash/isHash.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/promise/withTimeout.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/rpc/id.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/rpc/http.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/typedData.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/typedData.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/erc8010/SignatureErc8010.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/internal/lru.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Caches.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Hash.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/PublicKey.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Address.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Solidity.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/internal/abiParameters.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/internal/cursor.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/AbiParameters.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Rlp.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Signature.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Authorization.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Secp256k1.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/transaction/getSerializedTransactionType.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/transaction/parseTransaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/unit.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/unit/parseUnits.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getTransaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/getTransactionReceipt.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/multicall.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/constants/address.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/erc6492/SignatureErc6492.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/utils/signature/serializeSignature.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/verifyHash.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/watchBlockNumber.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/public/waitForTransactionReceipt.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/sendRawTransactionSync.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/sendCallsSync.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/sendTransactionSync.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/signTransaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/signTypedData.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/actions/wallet/writeContractSync.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/clients/transports/createTransport.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/errors/transport.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/clients/transports/http.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/stripe/Methods.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/stripe/client/Charge.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/stripe/client/Methods.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/SignatureEnvelope.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/P256.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Base64.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/webauthn/Authentication.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/WebAuthnP256.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/TempoAddress.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/AuthorizationTempo.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/KeyAuthorization.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/PoolId.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/TokenId.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/TokenRole.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/Transaction.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Transaction.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/TransactionRequest.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/TransactionRequest.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/TxEnvelopeTempo.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/AccessList.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/Value.ts","../../../node_modules/.pnpm/ox@0.14.5_typescript@5.9.3_zod@4.3.6/node_modules/ox/core/TxEnvelope.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/Transaction.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/Formatters.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/internal/concurrent.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/chainConfig.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/chains/definitions/tempo.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/Abis.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/Account.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/Addresses.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/index.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/accessKey.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/internal/utils.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/amm.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/dex.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/faucet.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/fee.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/nonce.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/policy.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/reward.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/token.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/actions/validator.ts","../../../node_modules/.pnpm/viem@2.47.5_typescript@5.9.3_zod@4.3.6/node_modules/viem/tempo/Transport.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/viem/Account.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/viem/Client.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/Attribution.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/internal/address.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/internal/defaults.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/internal/auto-swap.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/Methods.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/client/Charge.ts","../../../node_modules/.pnpm/ox@0.14.10_typescript@5.9.3_zod@4.3.6/node_modules/ox/tempo/SignatureEnvelope.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/session/Voucher.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/session/Channel.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/session/escrow.abi.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/session/Chain.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/client/ChannelOps.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/client/Session.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/client/internal/Fetch.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/session/Receipt.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/session/Sse.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/client/SessionManager.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/tempo/client/Methods.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/client/Mppx.ts","../../../node_modules/.pnpm/mppx@0.4.9_@modelcontextprotocol+sdk@1.28.0_zod@4.3.6__express@5.2.1_hono@4.12.9_openap_c4e524ef2c460fde6664b2d190f6f806/node_modules/mppx/src/client/Transport.ts"],"sourcesContent":["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 { BaseError } from './base.js'\n\nexport type FilterTypeNotSupportedErrorType = FilterTypeNotSupportedError & {\n name: 'FilterTypeNotSupportedError'\n}\nexport class FilterTypeNotSupportedError extends BaseError {\n constructor(type: string) {\n super(`Filter type \"${type}\" is not supported.`, {\n name: 'FilterTypeNotSupportedError',\n })\n }\n}\n","import type {\n Abi,\n AbiParameter,\n AbiParameterToPrimitiveType,\n ExtractAbiEvents,\n} from 'abitype'\n\nimport {\n AbiEventNotFoundError,\n type AbiEventNotFoundErrorType,\n} from '../../errors/abi.js'\nimport {\n FilterTypeNotSupportedError,\n type FilterTypeNotSupportedErrorType,\n} from '../../errors/log.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { IsNarrowable, UnionEvaluate } from '../../types/utils.js'\nimport { type ToBytesErrorType, toBytes } from '../encoding/toBytes.js'\nimport { type Keccak256ErrorType, keccak256 } from '../hash/keccak256.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type EncodeAbiParametersErrorType,\n encodeAbiParameters,\n} from './encodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\nimport { type GetAbiItemErrorType, getAbiItem } from './getAbiItem.js'\n\nconst docsPath = '/docs/contract/encodeEventTopics'\n\nexport type EncodeEventTopicsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n ///\n hasEvents = abi extends Abi\n ? Abi extends abi\n ? true\n : [ExtractAbiEvents<abi>] extends [never]\n ? false\n : true\n : true,\n allArgs = ContractEventArgs<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>\n >,\n allErrorNames = ContractEventName<abi>,\n> = {\n abi: abi\n args?: allArgs | undefined\n} & UnionEvaluate<\n IsNarrowable<abi, Abi> extends true\n ? abi['length'] extends 1\n ? { eventName?: eventName | allErrorNames | undefined }\n : { eventName: eventName | allErrorNames }\n : { eventName?: eventName | allErrorNames | undefined }\n> &\n (hasEvents extends true ? unknown : never)\n\nexport type EncodeEventTopicsReturnType = [Hex, ...(Hex | Hex[] | null)[]]\n\nexport type EncodeEventTopicsErrorType =\n | AbiEventNotFoundErrorType\n | EncodeArgErrorType\n | FormatAbiItemErrorType\n | GetAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nexport function encodeEventTopics<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n>(\n parameters: EncodeEventTopicsParameters<abi, eventName>,\n): EncodeEventTopicsReturnType {\n const { abi, eventName, args } = parameters as EncodeEventTopicsParameters\n\n let abiItem = abi[0]\n if (eventName) {\n const item = getAbiItem({ abi, name: eventName })\n if (!item) throw new AbiEventNotFoundError(eventName, { docsPath })\n abiItem = item\n }\n\n if (abiItem.type !== 'event')\n throw new AbiEventNotFoundError(undefined, { docsPath })\n\n const definition = formatAbiItem(abiItem)\n const signature = toEventSelector(definition as EventDefinition)\n\n let topics: (Hex | Hex[] | null)[] = []\n if (args && 'inputs' in abiItem) {\n const indexedInputs = abiItem.inputs?.filter(\n (param) => 'indexed' in param && param.indexed,\n )\n const args_ = Array.isArray(args)\n ? args\n : Object.values(args).length > 0\n ? (indexedInputs?.map((x: any) => (args as any)[x.name]) ?? [])\n : []\n\n if (args_.length > 0) {\n topics =\n indexedInputs?.map((param, i) => {\n if (Array.isArray(args_[i]))\n return args_[i].map((_: any, j: number) =>\n encodeArg({ param, value: args_[i][j] }),\n )\n return typeof args_[i] !== 'undefined' && args_[i] !== null\n ? encodeArg({ param, value: args_[i] })\n : null\n }) ?? []\n }\n }\n return [signature, ...topics]\n}\n\nexport type EncodeArgErrorType =\n | Keccak256ErrorType\n | ToBytesErrorType\n | EncodeAbiParametersErrorType\n | FilterTypeNotSupportedErrorType\n | ErrorType\n\nfunction encodeArg({\n param,\n value,\n}: {\n param: AbiParameter\n value: AbiParameterToPrimitiveType<AbiParameter>\n}) {\n if (param.type === 'string' || param.type === 'bytes')\n return keccak256(toBytes(value as string))\n if (param.type === 'tuple' || param.type.match(/^(.*)\\[(\\d+)?\\]$/))\n throw new FilterTypeNotSupportedError(param.type)\n return encodeAbiParameters([param], [value])\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { OnResponseFn } from '../../clients/transports/fallback.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { EIP1193RequestFn, PublicRpcSchema } from '../../types/eip1193.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { Filter } from '../../types/utils.js'\n\ntype CreateFilterRequestScopeParameters = {\n method:\n | 'eth_newFilter'\n | 'eth_newPendingTransactionFilter'\n | 'eth_newBlockFilter'\n}\n\ntype FilterRpcSchema = Filter<\n PublicRpcSchema,\n { Method: 'eth_getFilterLogs' | 'eth_getFilterChanges' }\n>\n\ntype CreateFilterRequestScopeReturnType = (\n id: Hex,\n) => EIP1193RequestFn<FilterRpcSchema>\n\n/**\n * Scopes `request` to the filter ID. If the client is a fallback, it will\n * listen for responses and scope the child transport `request` function\n * to the successful filter ID.\n */\nexport function createFilterRequestScope<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { method }: CreateFilterRequestScopeParameters,\n): CreateFilterRequestScopeReturnType {\n const requestMap: Record<Hex, EIP1193RequestFn> = {}\n\n if (client.transport.type === 'fallback')\n client.transport.onResponse?.(\n ({\n method: method_,\n response: id,\n status,\n transport,\n }: Parameters<OnResponseFn>[0]) => {\n if (status === 'success' && method === method_)\n requestMap[id as Hex] = transport.request\n },\n )\n\n return ((id) =>\n requestMap[id] || client.request) as CreateFilterRequestScopeReturnType\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Hex } from '../../types/misc.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { createFilterRequestScope } from '../../utils/filters/createFilterRequestScope.js'\n\nexport type CreateContractEventFilterParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi<abi, eventName>\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n address?: Address | Address[] | undefined\n abi: abi\n eventName?: eventName | ContractEventName<abi> | undefined\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments in the event ABI item.\n * @default false\n */\n strict?: strict | boolean | undefined\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n} & (undefined extends eventName\n ? {\n args?: undefined\n }\n : MaybeExtractEventArgsFromAbi<abi, eventName> extends infer eventFilterArgs\n ? {\n args?:\n | eventFilterArgs\n | (args extends eventFilterArgs ? args : never)\n | undefined\n }\n : {\n args?: undefined\n })\n\nexport type CreateContractEventFilterReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = undefined,\n args extends\n | MaybeExtractEventArgsFromAbi<abi, eventName>\n | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = Filter<'event', abi, eventName, args, strict, fromBlock, toBlock>\n\nexport type CreateContractEventFilterErrorType =\n | EncodeEventTopicsErrorType\n | RequestErrorType\n | NumberToHexErrorType\n | ErrorType\n\n/**\n * Creates a Filter to retrieve event logs that can be used with [`getFilterChanges`](https://viem.sh/docs/actions/public/getFilterChanges) or [`getFilterLogs`](https://viem.sh/docs/actions/public/getFilterLogs).\n *\n * - Docs: https://viem.sh/docs/contract/createContractEventFilter\n *\n * @param client - Client to use\n * @param parameters - {@link CreateContractEventFilterParameters}\n * @returns [`Filter`](https://viem.sh/docs/glossary/types#filter). {@link CreateContractEventFilterReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * })\n */\nexport async function createContractEventFilter<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined,\n args extends MaybeExtractEventArgsFromAbi<abi, eventName> | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client<Transport, chain>,\n parameters: CreateContractEventFilterParameters<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const { address, abi, args, eventName, fromBlock, strict, toBlock } =\n parameters as CreateContractEventFilterParameters\n\n const getRequest = createFilterRequestScope(client, {\n method: 'eth_newFilter',\n })\n\n const topics = eventName\n ? encodeEventTopics({\n abi,\n args,\n eventName,\n } as unknown as EncodeEventTopicsParameters)\n : undefined\n const id: Hex = await client.request({\n method: 'eth_newFilter',\n params: [\n {\n address,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n topics,\n },\n ],\n })\n\n return {\n abi,\n args,\n eventName,\n id,\n request: getRequest(id),\n strict: Boolean(strict),\n type: 'event',\n } as unknown as CreateContractEventFilterReturnType<\n abi,\n eventName,\n args,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi, Address } from 'abitype'\n\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport {\n ContractFunctionExecutionError,\n type ContractFunctionExecutionErrorType,\n ContractFunctionRevertedError,\n type ContractFunctionRevertedErrorType,\n ContractFunctionZeroDataError,\n type ContractFunctionZeroDataErrorType,\n RawContractError,\n} from '../../errors/contract.js'\nimport { 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, cause: err })\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 cause: err,\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'\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 { 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 { 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 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 { 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 { 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 { 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 { 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 { 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 { 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 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 { 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 { 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 { 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","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 { 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 { 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 { 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 && !request.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 request.type !== 'legacy' &&\n request.type !== 'eip2930'\n ? { maxFeePerBlobGas }\n : {}),\n ...(typeof maxFeePerGas !== 'undefined' &&\n request.type !== 'legacy' &&\n request.type !== 'eip2930'\n ? { maxFeePerGas }\n : {}),\n ...(typeof maxPriorityFeePerGas !== 'undefined' &&\n request.type !== 'legacy' &&\n request.type !== 'eip2930'\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 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 { 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 { Abi, AbiParameter } from 'abitype'\n\nimport {\n AbiDecodingDataSizeTooSmallError,\n type AbiDecodingDataSizeTooSmallErrorType,\n AbiEventSignatureEmptyTopicsError,\n type AbiEventSignatureEmptyTopicsErrorType,\n AbiEventSignatureNotFoundError,\n type AbiEventSignatureNotFoundErrorType,\n DecodeLogDataMismatch,\n type DecodeLogDataMismatchErrorType,\n DecodeLogTopicsMismatch,\n type DecodeLogTopicsMismatchErrorType,\n} from '../../errors/abi.js'\nimport { PositionOutOfBoundsError } from '../../errors/cursor.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n ContractEventArgsFromTopics,\n ContractEventName,\n EventDefinition,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n IsNarrowable,\n Prettify,\n UnionEvaluate,\n} from '../../types/utils.js'\nimport { size } from '../data/size.js'\nimport {\n type ToEventSelectorErrorType,\n toEventSelector,\n} from '../hash/toEventSelector.js'\nimport {\n type DecodeAbiParametersErrorType,\n decodeAbiParameters,\n} from './decodeAbiParameters.js'\nimport { type FormatAbiItemErrorType, formatAbiItem } from './formatAbiItem.js'\n\nexport type DecodeEventLogParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n> = {\n abi: abi\n data?: data | undefined\n eventName?: eventName | ContractEventName<abi> | undefined\n strict?: strict | boolean | undefined\n topics: [signature: Hex, ...args: topics] | []\n}\n\nexport type DecodeEventLogReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n ///\n allEventNames extends\n ContractEventName<abi> = eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>,\n> = IsNarrowable<abi, Abi> extends true\n ? {\n [name in allEventNames]: Prettify<\n {\n eventName: name\n } & UnionEvaluate<\n ContractEventArgsFromTopics<abi, name, strict> extends infer allArgs\n ? topics extends readonly []\n ? data extends undefined\n ? { args?: undefined }\n : { args?: allArgs | undefined }\n : { args: allArgs }\n : never\n >\n >\n }[allEventNames]\n : {\n eventName: eventName\n args: readonly unknown[] | undefined\n }\n\nexport type DecodeEventLogErrorType =\n | AbiDecodingDataSizeTooSmallErrorType\n | AbiEventSignatureEmptyTopicsErrorType\n | AbiEventSignatureNotFoundErrorType\n | DecodeAbiParametersErrorType\n | DecodeLogTopicsMismatchErrorType\n | DecodeLogDataMismatchErrorType\n | FormatAbiItemErrorType\n | ToEventSelectorErrorType\n | ErrorType\n\nconst docsPath = '/docs/contract/decodeEventLog'\n\nexport function decodeEventLog<\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n topics extends Hex[] = Hex[],\n data extends Hex | undefined = undefined,\n strict extends boolean = true,\n>(\n parameters: DecodeEventLogParameters<abi, eventName, topics, data, strict>,\n): DecodeEventLogReturnType<abi, eventName, topics, data, strict> {\n const {\n abi,\n data,\n strict: strict_,\n topics,\n } = parameters as DecodeEventLogParameters\n\n const strict = strict_ ?? true\n const [signature, ...argTopics] = topics\n if (!signature) throw new AbiEventSignatureEmptyTopicsError({ docsPath })\n\n const abiItem = abi.find(\n (x) =>\n x.type === 'event' &&\n signature === toEventSelector(formatAbiItem(x) as EventDefinition),\n )\n\n if (!(abiItem && 'name' in abiItem) || abiItem.type !== 'event')\n throw new AbiEventSignatureNotFoundError(signature, { docsPath })\n\n const { name, inputs } = abiItem\n const isUnnamed = inputs?.some((x) => !('name' in x && x.name))\n\n const args: any = isUnnamed ? [] : {}\n\n // Decode topics (indexed args).\n const indexedInputs = inputs\n .map((x, i) => [x, i] as const)\n .filter(([x]) => 'indexed' in x && x.indexed)\n\n const missingIndexedInputs: [AbiParameter, number][] = []\n\n for (let i = 0; i < indexedInputs.length; i++) {\n const [param, argIndex] = indexedInputs[i]\n const topic = argTopics[i]\n if (!topic) {\n if (strict)\n throw new DecodeLogTopicsMismatch({\n abiItem,\n param: param as AbiParameter & { indexed: boolean },\n })\n // Track missing indexed inputs to decode from data when strict is false\n missingIndexedInputs.push([param, argIndex])\n continue\n }\n args[isUnnamed ? argIndex : param.name || argIndex] = decodeTopic({\n param,\n value: topic,\n })\n }\n\n // Decode data (non-indexed args + missing indexed args when strict is false).\n const nonIndexedInputs = inputs.filter((x) => !('indexed' in x && x.indexed))\n\n // When strict is false, missing indexed inputs should be decoded from data\n const inputsToDecode = strict\n ? nonIndexedInputs\n : [...missingIndexedInputs.map(([param]) => param), ...nonIndexedInputs]\n\n if (inputsToDecode.length > 0) {\n if (data && data !== '0x') {\n try {\n const decodedData = decodeAbiParameters(\n inputsToDecode,\n data,\n ) as unknown[]\n if (decodedData) {\n let dataIndex = 0\n // First, assign missing indexed parameters (when strict is false)\n if (!strict) {\n for (const [param, argIndex] of missingIndexedInputs) {\n args[isUnnamed ? argIndex : param.name || argIndex] =\n decodedData[dataIndex++]\n }\n }\n // Then, assign non-indexed parameters\n if (isUnnamed) {\n for (let i = 0; i < inputs.length; i++)\n if (args[i] === undefined && dataIndex < decodedData.length)\n args[i] = decodedData[dataIndex++]\n } else\n for (let i = 0; i < nonIndexedInputs.length; i++)\n args[nonIndexedInputs[i].name!] = decodedData[dataIndex++]\n }\n } catch (err) {\n if (strict) {\n if (\n err instanceof AbiDecodingDataSizeTooSmallError ||\n err instanceof PositionOutOfBoundsError\n )\n throw new DecodeLogDataMismatch({\n abiItem,\n data: data,\n params: inputsToDecode,\n size: size(data),\n })\n throw err\n }\n }\n } else if (strict) {\n throw new DecodeLogDataMismatch({\n abiItem,\n data: '0x',\n params: inputsToDecode,\n size: 0,\n })\n }\n }\n\n return {\n eventName: name,\n args: Object.values(args).length > 0 ? args : undefined,\n } as unknown as DecodeEventLogReturnType<abi, eventName, topics, data, strict>\n}\n\nfunction decodeTopic({ param, value }: { param: AbiParameter; value: Hex }) {\n if (\n param.type === 'string' ||\n param.type === 'bytes' ||\n param.type === 'tuple' ||\n param.type.match(/^(.*)\\[(\\d+)?\\]$/)\n )\n return value\n const decodedArg = decodeAbiParameters([param], value) || []\n return decodedArg[0]\n}\n","// TODO(v3): checksum address.\n\nimport type { Abi, AbiEvent, AbiEventParameter, Address } from 'abitype'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { ContractEventName, GetEventArgs } from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport { isAddressEqual } from '../address/isAddressEqual.js'\nimport { toBytes } from '../encoding/toBytes.js'\nimport { formatLog } from '../formatters/log.js'\nimport { keccak256 } from '../hash/keccak256.js'\nimport { toEventSelector } from '../hash/toEventSelector.js'\nimport {\n type DecodeEventLogErrorType,\n decodeEventLog,\n} from './decodeEventLog.js'\n\nexport type ParseEventLogsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName<abi>\n | ContractEventName<abi>[]\n | undefined = ContractEventName<abi>,\n strict extends boolean | undefined = boolean | undefined,\n ///\n allArgs = GetEventArgs<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>,\n {\n EnableUnion: true\n IndexedOnly: false\n Required: false\n }\n >,\n> = {\n /** Contract ABI. */\n abi: abi\n /** Arguments for the event. */\n args?: allArgs | undefined\n /** Contract event. */\n eventName?:\n | eventName\n | ContractEventName<abi>\n | ContractEventName<abi>[]\n | undefined\n /** List of logs. */\n logs: (Log | RpcLog)[]\n strict?: strict | boolean | undefined\n}\n\nexport type ParseEventLogsReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends\n | ContractEventName<abi>\n | ContractEventName<abi>[]\n | undefined = ContractEventName<abi>,\n strict extends boolean | undefined = boolean | undefined,\n ///\n derivedEventName extends\n | ContractEventName<abi>\n | undefined = eventName extends ContractEventName<abi>[]\n ? eventName[number]\n : eventName,\n> = Log<bigint, number, false, undefined, strict, abi, derivedEventName>[]\n\nexport type ParseEventLogsErrorType = DecodeEventLogErrorType | ErrorType\n\n/**\n * Extracts & decodes logs matching the provided signature(s) (`abi` + optional `eventName`)\n * from a set of opaque logs.\n *\n * @param parameters - {@link ParseEventLogsParameters}\n * @returns The logs. {@link ParseEventLogsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { parseEventLogs } from 'viem/op-stack'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n *\n * const receipt = await getTransactionReceipt(client, {\n * hash: '0xec23b2ba4bc59ba61554507c1b1bc91649e6586eb2dd00c728e8ed0db8bb37ea',\n * })\n *\n * const logs = parseEventLogs({ logs: receipt.logs })\n * // [{ args: { ... }, eventName: 'TransactionDeposited', ... }, ...]\n */\nexport function parseEventLogs<\n abi extends Abi | readonly unknown[],\n strict extends boolean | undefined = true,\n eventName extends\n | ContractEventName<abi>\n | ContractEventName<abi>[]\n | undefined = undefined,\n>(\n parameters: ParseEventLogsParameters<abi, eventName, strict>,\n): ParseEventLogsReturnType<abi, eventName, strict> {\n const { abi, args, logs, strict = true } = parameters\n\n const eventName = (() => {\n if (!parameters.eventName) return undefined\n if (Array.isArray(parameters.eventName)) return parameters.eventName\n return [parameters.eventName as string]\n })()\n\n const abiTopics = (abi as Abi)\n .filter((abiItem) => abiItem.type === 'event')\n .map((abiItem) => ({\n abi: abiItem,\n selector: toEventSelector(abiItem),\n }))\n\n return logs\n .map((log) => {\n // Normalize RpcLog (hex-encoded quantities) to Log (bigint/number).\n // When logs come directly from an RPC response (e.g. eth_getLogs),\n // fields like blockNumber are hex strings instead of bigints.\n const formattedLog =\n typeof log.blockNumber === 'string' ? formatLog(log as RpcLog) : log\n\n // Find all matching ABI items with the same selector.\n // Multiple events can share the same selector but differ in indexed parameters\n // (e.g., ERC20 vs ERC721 Transfer events).\n const abiItems = abiTopics.filter(\n (abiTopic) => formattedLog.topics[0] === abiTopic.selector,\n )\n if (abiItems.length === 0) return null\n\n // Try each matching ABI item until one successfully decodes.\n let event: { eventName: string; args: unknown } | undefined\n let abiItem: { abi: AbiEvent; selector: Address } | undefined\n\n for (const item of abiItems) {\n try {\n event = decodeEventLog({\n ...formattedLog,\n abi: [item.abi],\n strict: true,\n })\n abiItem = item\n break\n } catch {\n // Try next ABI item\n }\n }\n\n // If strict decoding failed for all, and we're in non-strict mode,\n // fall back to the first matching ABI item.\n if (!event && !strict) {\n abiItem = abiItems[0]\n try {\n event = decodeEventLog({\n data: formattedLog.data,\n topics: formattedLog.topics,\n abi: [abiItem.abi],\n strict: false,\n })\n } catch {\n // If decoding still fails, return partial log in non-strict mode.\n const isUnnamed = abiItem.abi.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n return {\n ...formattedLog,\n args: isUnnamed ? [] : {},\n eventName: abiItem.abi.name,\n }\n }\n }\n\n // If no event was found, return null.\n if (!event || !abiItem) return null\n\n // Check that the decoded event name matches the provided event name.\n if (eventName && !eventName.includes(event.eventName)) return null\n\n // Check that the decoded event args match the provided args.\n if (\n !includesArgs({\n args: event.args,\n inputs: abiItem.abi.inputs,\n matchArgs: args,\n })\n )\n return null\n\n return { ...event, ...formattedLog }\n })\n .filter(Boolean) as unknown as ParseEventLogsReturnType<\n abi,\n eventName,\n strict\n >\n}\n\nfunction includesArgs(parameters: {\n args: unknown\n inputs: AbiEvent['inputs']\n matchArgs: unknown\n}) {\n const { args, inputs, matchArgs } = parameters\n\n if (!matchArgs) return true\n if (!args) return false\n\n function isEqual(input: AbiEventParameter, value: unknown, arg: unknown) {\n try {\n if (input.type === 'address')\n return isAddressEqual(value as Address, arg as Address)\n if (input.type === 'string' || input.type === 'bytes')\n return keccak256(toBytes(value as string)) === arg\n return value === arg\n } catch {\n return false\n }\n }\n\n if (Array.isArray(args) && Array.isArray(matchArgs)) {\n return matchArgs.every((value, index) => {\n if (value === null || value === undefined) return true\n const input = inputs[index]\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) => isEqual(input, value, args[index]))\n })\n }\n\n if (\n typeof args === 'object' &&\n !Array.isArray(args) &&\n typeof matchArgs === 'object' &&\n !Array.isArray(matchArgs)\n )\n return Object.entries(matchArgs).every(([key, value]) => {\n if (value === null || value === undefined) return true\n const input = inputs.find((input) => input.name === key)\n if (!input) return false\n const value_ = Array.isArray(value) ? value : [value]\n return value_.some((value) =>\n isEqual(input, value, (args as Record<string, unknown>)[key]),\n )\n })\n\n return false\n}\n","import type { AbiEvent, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n MaybeAbiEventName,\n MaybeExtractEventArgsFromAbi,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash, LogTopic } from '../../types/misc.js'\nimport type { RpcLog } from '../../types/rpc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsErrorType,\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetLogsParameters<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n> = {\n /** Address or list of addresses from which logs originated */\n address?: Address | Address[] | undefined\n} & (\n | {\n event: abiEvent\n events?: undefined\n args?: MaybeExtractEventArgsFromAbi<abiEvents, _eventName> | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events: abiEvents\n args?: undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | undefined\n }\n | {\n event?: undefined\n events?: undefined\n args?: undefined\n strict?: undefined\n }\n) &\n (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n )\n\nexport type GetLogsReturnType<\n abiEvent extends AbiEvent | undefined = undefined,\n abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n //\n _eventName extends string | undefined = MaybeAbiEventName<abiEvent>,\n _pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log<bigint, number, _pending, abiEvent, strict, abiEvents, _eventName>[]\n\nexport type GetLogsErrorType =\n | DecodeEventLogErrorType\n | EncodeEventTopicsErrorType\n | FormatLogErrorType\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs matching the provided parameters.\n *\n * - Docs: https://viem.sh/docs/actions/public/getLogs\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/logs_event-logs\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetLogsParameters}\n * @returns A list of event logs. {@link GetLogsReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getLogs } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getLogs(client)\n */\nexport async function getLogs<\n chain extends Chain | undefined,\n const abiEvent extends AbiEvent | undefined = undefined,\n const abiEvents extends\n | readonly AbiEvent[]\n | readonly unknown[]\n | undefined = abiEvent extends AbiEvent ? [abiEvent] : undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client<Transport, chain>,\n {\n address,\n blockHash,\n fromBlock,\n toBlock,\n event,\n events: events_,\n args,\n strict: strict_,\n }: GetLogsParameters<abiEvent, abiEvents, strict, fromBlock, toBlock> = {},\n): Promise<GetLogsReturnType<abiEvent, abiEvents, strict, fromBlock, toBlock>> {\n const strict = strict_ ?? false\n const events = events_ ?? (event ? [event] : undefined)\n\n let topics: LogTopic[] = []\n if (events) {\n const encoded = (events as AbiEvent[]).flatMap((event) =>\n encodeEventTopics({\n abi: [event],\n eventName: (event as AbiEvent).name,\n args: events_ ? undefined : args,\n } as EncodeEventTopicsParameters),\n )\n // TODO: Clean up type casting\n topics = [encoded as LogTopic]\n if (event) topics = topics[0] as LogTopic[]\n }\n\n let logs: RpcLog[]\n if (blockHash) {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [{ address, topics, blockHash }],\n })\n } else {\n logs = await client.request({\n method: 'eth_getLogs',\n params: [\n {\n address,\n topics,\n fromBlock:\n typeof fromBlock === 'bigint' ? numberToHex(fromBlock) : fromBlock,\n toBlock: typeof toBlock === 'bigint' ? numberToHex(toBlock) : toBlock,\n },\n ],\n })\n }\n\n const formattedLogs = logs.map((log) => formatLog(log))\n if (!events)\n return formattedLogs as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: events,\n args: args as any,\n logs: formattedLogs,\n strict,\n }) as unknown as GetLogsReturnType<\n abiEvent,\n abiEvents,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi, Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport {\n type GetAbiItemErrorType,\n type GetAbiItemParameters,\n getAbiItem,\n} from '../../utils/abi/getAbiItem.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type GetLogsErrorType,\n type GetLogsParameters,\n getLogs,\n} from './getLogs.js'\n\nexport type GetContractEventsParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined =\n | ContractEventName<abi>\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName<abi> | undefined\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & (\n | {\n /** Block number or tag after which to include logs */\n fromBlock?: fromBlock | BlockNumber | BlockTag | undefined\n /** Block number or tag before which to include logs */\n toBlock?: toBlock | BlockNumber | BlockTag | undefined\n blockHash?: undefined\n }\n | {\n fromBlock?: undefined\n toBlock?: undefined\n /** Hash of block to include logs from */\n blockHash?: Hash | undefined\n }\n)\n\nexport type GetContractEventsReturnType<\n abi extends Abi | readonly unknown[] = readonly unknown[],\n eventName extends ContractEventName<abi> | undefined =\n | ContractEventName<abi>\n | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n ///\n isPending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = Log<bigint, number, isPending, undefined, strict, abi, eventName>[]\n\nexport type GetContractEventsErrorType =\n | GetAbiItemErrorType\n | GetLogsErrorType\n | ErrorType\n\n/**\n * Returns a list of event logs emitted by a contract.\n *\n * - Docs: https://viem.sh/docs/contract/getContractEvents#getcontractevents\n * - JSON-RPC Methods: [`eth_getLogs`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getlogs)\n *\n * @param client - Client to use\n * @param parameters - {@link GetContractEventsParameters}\n * @returns A list of event logs. {@link GetContractEventsReturnType}\n *\n * @example\n * import { createClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getContractEvents } from 'viem/public'\n * import { wagmiAbi } from './abi'\n *\n * const client = createClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const logs = await getContractEvents(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: wagmiAbi,\n * eventName: 'Transfer'\n * })\n */\nexport async function getContractEvents<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n client: Client<Transport, chain>,\n parameters: GetContractEventsParameters<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetContractEventsReturnType<abi, eventName, strict, fromBlock, toBlock>\n> {\n const {\n abi,\n address,\n args,\n blockHash,\n eventName,\n fromBlock,\n toBlock,\n strict,\n } = parameters\n const event = eventName\n ? getAbiItem({ abi, name: eventName } as GetAbiItemParameters)\n : undefined\n const events = !event\n ? (abi as Abi).filter((x) => x.type === 'event')\n : undefined\n return getAction(\n client,\n getLogs,\n 'getLogs',\n )({\n address,\n args,\n blockHash,\n event,\n events,\n fromBlock,\n toBlock,\n strict,\n } as {} as GetLogsParameters) as unknown as GetContractEventsReturnType<\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Abi } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseError } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionParameters,\n ContractFunctionReturnType,\n} from '../../types/contract.js'\nimport type { UnionEvaluate } from '../../types/utils.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n type EncodeFunctionDataParameters,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\n\nimport { type CallErrorType, type CallParameters, call } from './call.js'\n\nexport type ReadContractParameters<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName<abi, 'pure' | 'view'>,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs<abi, 'pure' | 'view', functionName>,\n> = UnionEvaluate<\n Pick<\n CallParameters,\n | 'account'\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'factory'\n | 'factoryData'\n | 'stateOverride'\n >\n> &\n ContractFunctionParameters<abi, 'pure' | 'view', functionName, args, boolean>\n\nexport type ReadContractReturnType<\n abi extends Abi | readonly unknown[] = Abi,\n functionName extends ContractFunctionName<\n abi,\n 'pure' | 'view'\n > = ContractFunctionName<abi, 'pure' | 'view'>,\n args extends ContractFunctionArgs<\n abi,\n 'pure' | 'view',\n functionName\n > = ContractFunctionArgs<abi, 'pure' | 'view', functionName>,\n> = ContractFunctionReturnType<abi, 'pure' | 'view', functionName, args>\n\nexport type ReadContractErrorType = GetContractErrorReturnType<\n CallErrorType | EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n>\n\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await readContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n functionName extends ContractFunctionName<abi, 'pure' | 'view'>,\n const args extends ContractFunctionArgs<abi, 'pure' | 'view', functionName>,\n>(\n client: Client<Transport, chain>,\n parameters: ReadContractParameters<abi, functionName, args>,\n): Promise<ReadContractReturnType<abi, functionName, args>> {\n const { abi, address, args, functionName, ...rest } =\n parameters as ReadContractParameters\n const calldata = encodeFunctionData({\n abi,\n args,\n functionName,\n } as EncodeFunctionDataParameters)\n try {\n const { data } = await getAction(\n client,\n call,\n 'call',\n )({\n ...(rest as CallParameters),\n data: calldata,\n to: address!,\n })\n return decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n }) as ReadContractReturnType<abi, functionName>\n } catch (error) {\n throw getContractError(error as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/readContract',\n functionName,\n })\n }\n}\n","import type { ErrorType } from '../errors/utils.js'\nimport type { MaybePromise } from '../types/utils.js'\n\ntype Callback = ((...args: any[]) => any) | undefined\ntype Callbacks = Record<string, Callback>\n\nexport type ObserveErrorType = ErrorType\n\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, AbiEvent, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { RpcLog } from '../../index.js'\nimport type { BlockNumber, BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter, FilterType } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { Hash } from '../../types/misc.js'\nimport type { DecodeEventLogErrorType } from '../../utils/abi/decodeEventLog.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type FormatLogErrorType,\n formatLog,\n} from '../../utils/formatters/log.js'\n\nexport type GetFilterChangesParameters<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n> = {\n filter: Filter<filterType, abi, eventName, any, strict, fromBlock, toBlock>\n}\n\nexport type GetFilterChangesReturnType<\n filterType extends FilterType = FilterType,\n abi extends Abi | readonly unknown[] | undefined = undefined,\n eventName extends string | undefined = undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n _AbiEvent extends AbiEvent | undefined = abi extends Abi\n ? eventName extends string\n ? ExtractAbiEvent<abi, eventName>\n : undefined\n : undefined,\n _Pending extends boolean =\n | (fromBlock extends 'pending' ? true : false)\n | (toBlock extends 'pending' ? true : false),\n> = filterType extends 'event'\n ? Log<bigint, number, _Pending, _AbiEvent, strict, abi, eventName>[]\n : Hash[]\n\nexport type GetFilterChangesErrorType =\n | RequestErrorType\n | DecodeEventLogErrorType\n | FormatLogErrorType\n | ErrorType\n\n/**\n * Returns a list of logs or hashes based on a [Filter](/docs/glossary/terms#filter) since the last time it was called.\n *\n * - Docs: https://viem.sh/docs/actions/public/getFilterChanges\n * - JSON-RPC Methods: [`eth_getFilterChanges`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getfilterchanges)\n *\n * A Filter can be created from the following actions:\n *\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createContractEventFilter`](https://viem.sh/docs/contract/createContractEventFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * Depending on the type of filter, the return value will be different:\n *\n * - If the filter was created with `createContractEventFilter` or `createEventFilter`, it returns a list of logs.\n * - If the filter was created with `createPendingTransactionFilter`, it returns a list of transaction hashes.\n * - If the filter was created with `createBlockFilter`, it returns a list of block hashes.\n *\n * @param client - Client to use\n * @param parameters - {@link GetFilterChangesParameters}\n * @returns Logs or hashes. {@link GetFilterChangesReturnType}\n *\n * @example\n * // Blocks\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createBlockFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createBlockFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n *\n * @example\n * // Contract Events\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createContractEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createContractEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * abi: parseAbi(['event Transfer(address indexed, address indexed, uint256)']),\n * eventName: 'Transfer',\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Raw Events\n * import { createPublicClient, http, parseAbiItem } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createEventFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createEventFilter(client, {\n * address: '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48',\n * event: parseAbiItem('event Transfer(address indexed, address indexed, uint256)'),\n * })\n * const logs = await getFilterChanges(client, { filter })\n *\n * @example\n * // Transactions\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, getFilterChanges } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const filter = await createPendingTransactionFilter(client)\n * const hashes = await getFilterChanges(client, { filter })\n */\nexport async function getFilterChanges<\n transport extends Transport,\n chain extends Chain | undefined,\n filterType extends FilterType,\n const abi extends Abi | readonly unknown[] | undefined,\n eventName extends string | undefined,\n strict extends boolean | undefined = undefined,\n fromBlock extends BlockNumber | BlockTag | undefined = undefined,\n toBlock extends BlockNumber | BlockTag | undefined = undefined,\n>(\n _client: Client<transport, chain>,\n {\n filter,\n }: GetFilterChangesParameters<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >,\n): Promise<\n GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n> {\n const strict = 'strict' in filter && filter.strict\n\n const logs = await filter.request({\n method: 'eth_getFilterChanges',\n params: [filter.id],\n })\n\n if (typeof logs[0] === 'string')\n return logs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n\n const formattedLogs = logs.map((log) => formatLog(log as RpcLog))\n if (!('abi' in filter) || !filter.abi)\n return formattedLogs as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n return parseEventLogs({\n abi: filter.abi,\n logs: formattedLogs,\n strict,\n }) as unknown as GetFilterChangesReturnType<\n filterType,\n abi,\n eventName,\n strict,\n fromBlock,\n toBlock\n >\n}\n","import type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\n\nexport type UninstallFilterParameters = {\n filter: Filter<any>\n}\nexport type UninstallFilterReturnType = boolean\n\nexport type UninstallFilterErrorType = RequestErrorType | ErrorType\n\n/**\n * Destroys a [`Filter`](https://viem.sh/docs/glossary/types#filter).\n *\n * - Docs: https://viem.sh/docs/actions/public/uninstallFilter\n * - JSON-RPC Methods: [`eth_uninstallFilter`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_uninstallFilter)\n *\n * Destroys a Filter that was created from one of the following Actions:\n * - [`createBlockFilter`](https://viem.sh/docs/actions/public/createBlockFilter)\n * - [`createEventFilter`](https://viem.sh/docs/actions/public/createEventFilter)\n * - [`createPendingTransactionFilter`](https://viem.sh/docs/actions/public/createPendingTransactionFilter)\n *\n * @param client - Client to use\n * @param parameters - {@link UninstallFilterParameters}\n * @returns A boolean indicating if the Filter was successfully uninstalled. {@link UninstallFilterReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { createPendingTransactionFilter, uninstallFilter } from 'viem/public'\n *\n * const filter = await createPendingTransactionFilter(client)\n * const uninstalled = await uninstallFilter(client, { filter })\n * // true\n */\nexport async function uninstallFilter<\n transport extends Transport,\n chain extends Chain | undefined,\n>(\n _client: Client<transport, chain>,\n { filter }: UninstallFilterParameters,\n): Promise<UninstallFilterReturnType> {\n return filter.request({\n method: 'eth_uninstallFilter',\n params: [filter.id],\n })\n}\n","import type { Abi, Address, ExtractAbiEvent } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n DecodeLogDataMismatch,\n DecodeLogTopicsMismatch,\n} from '../../errors/abi.js'\nimport { InvalidInputRpcError } from '../../errors/rpc.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockNumber } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type {\n ContractEventArgs,\n ContractEventName,\n} from '../../types/contract.js'\nimport type { Filter } from '../../types/filter.js'\nimport type { Log } from '../../types/log.js'\nimport type { LogTopic } from '../../types/misc.js'\nimport type { GetPollOptions } from '../../types/transport.js'\nimport { decodeEventLog } from '../../utils/abi/decodeEventLog.js'\nimport {\n type EncodeEventTopicsParameters,\n encodeEventTopics,\n} from '../../utils/abi/encodeEventTopics.js'\nimport { formatLog } from '../../utils/formatters/log.js'\nimport { getAction } from '../../utils/getAction.js'\nimport { type ObserveErrorType, observe } from '../../utils/observe.js'\nimport { poll } from '../../utils/poll.js'\nimport { type StringifyErrorType, stringify } from '../../utils/stringify.js'\nimport { createContractEventFilter } from './createContractEventFilter.js'\nimport { getBlockNumber } from './getBlockNumber.js'\nimport {\n type GetContractEventsParameters,\n getContractEvents,\n} from './getContractEvents.js'\nimport { getFilterChanges } from './getFilterChanges.js'\nimport { uninstallFilter } from './uninstallFilter.js'\n\nexport type WatchContractEventOnLogsParameter<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> = ContractEventName<abi>,\n strict extends boolean | undefined = undefined,\n> = abi extends Abi\n ? Abi extends abi\n ? Log[]\n : Log<bigint, number, false, ExtractAbiEvent<abi, eventName>, strict>[]\n : Log[]\n\nexport type WatchContractEventOnLogsFn<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> = ContractEventName<abi>,\n strict extends boolean | undefined = undefined,\n> = (logs: WatchContractEventOnLogsParameter<abi, eventName, strict>) => void\n\nexport type WatchContractEventParameters<\n abi extends Abi | readonly unknown[] = Abi,\n eventName extends ContractEventName<abi> | undefined = ContractEventName<abi>,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n> = {\n /** The address of the contract. */\n address?: Address | Address[] | undefined\n /** Contract ABI. */\n abi: abi\n args?:\n | ContractEventArgs<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>\n >\n | undefined\n /** Contract event. */\n eventName?: eventName | ContractEventName<abi> | undefined\n /** Block to start listening from. */\n fromBlock?: BlockNumber<bigint> | undefined\n /** The callback to call when an error occurred when trying to get for a new block. */\n onError?: ((error: Error) => void) | undefined\n /** The callback to call when new event logs are received. */\n onLogs: WatchContractEventOnLogsFn<\n abi,\n eventName extends ContractEventName<abi>\n ? eventName\n : ContractEventName<abi>,\n strict\n >\n /**\n * Whether or not the logs must match the indexed/non-indexed arguments on `event`.\n * @default false\n */\n strict?: strict | boolean | undefined\n} & GetPollOptions<transport>\n\nexport type WatchContractEventReturnType = () => void\n\nexport type WatchContractEventErrorType =\n | StringifyErrorType\n | ObserveErrorType\n | ErrorType\n\n/**\n * Watches and returns emitted contract event logs.\n *\n * - Docs: https://viem.sh/docs/contract/watchContractEvent\n *\n * This Action will batch up all the event logs found within the [`pollingInterval`](https://viem.sh/docs/contract/watchContractEvent#pollinginterval-optional), and invoke them via [`onLogs`](https://viem.sh/docs/contract/watchContractEvent#onLogs).\n *\n * `watchContractEvent` will attempt to create an [Event Filter](https://viem.sh/docs/contract/createContractEventFilter) and listen to changes to the Filter per polling interval, however, if the RPC Provider does not support Filters (e.g. `eth_newFilter`), then `watchContractEvent` will fall back to using [`getLogs`](https://viem.sh/docs/actions/public/getLogs) instead.\n *\n * @param client - Client to use\n * @param parameters - {@link WatchContractEventParameters}\n * @returns A function that can be invoked to stop watching for new event logs. {@link WatchContractEventReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { watchContractEvent } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const unwatch = watchContractEvent(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['event Transfer(address indexed from, address indexed to, uint256 value)']),\n * eventName: 'Transfer',\n * args: { from: '0xc961145a54C96E3aE9bAA048c4F4D6b04C13916b' },\n * onLogs: (logs) => console.log(logs),\n * })\n */\nexport function watchContractEvent<\n chain extends Chain | undefined,\n const abi extends Abi | readonly unknown[],\n eventName extends ContractEventName<abi> | undefined = undefined,\n strict extends boolean | undefined = undefined,\n transport extends Transport = Transport,\n>(\n client: Client<transport, chain>,\n parameters: WatchContractEventParameters<abi, eventName, strict, transport>,\n): WatchContractEventReturnType {\n const {\n abi,\n address,\n args,\n batch = true,\n eventName,\n fromBlock,\n onError,\n onLogs,\n poll: poll_,\n pollingInterval = client.pollingInterval,\n strict: strict_,\n } = parameters\n\n const enablePolling = (() => {\n if (typeof poll_ !== 'undefined') return poll_\n if (typeof fromBlock === 'bigint') return true\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 const pollContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n fromBlock,\n ])\n\n return observe(observerId, { onLogs, onError }, (emit) => {\n let previousBlockNumber: bigint\n if (fromBlock !== undefined) previousBlockNumber = fromBlock - 1n\n let filter: Filter<'event', abi, eventName> | undefined\n let initialized = false\n\n const unwatch = poll(\n async () => {\n if (!initialized) {\n try {\n filter = (await getAction(\n client,\n createContractEventFilter,\n 'createContractEventFilter',\n )({\n abi,\n address,\n args: args as any,\n eventName: eventName as any,\n strict: strict as any,\n fromBlock,\n })) as Filter<'event', abi, eventName>\n } catch {}\n initialized = true\n return\n }\n\n try {\n let logs: Log[]\n if (filter) {\n logs = await getAction(\n client,\n getFilterChanges,\n 'getFilterChanges',\n )({ filter })\n } else {\n // If the filter doesn't exist, we will fall back to use `getLogs`.\n // The fall back exists because some RPC Providers do not support filters.\n\n // Fetch the block number to use for `getLogs`.\n const blockNumber = await getAction(\n client,\n getBlockNumber,\n 'getBlockNumber',\n )({})\n\n // If the block number has changed, we will need to fetch the logs.\n // If the block number doesn't exist, we are yet to reach the first poll interval,\n // so do not emit any logs.\n if (previousBlockNumber && previousBlockNumber < blockNumber) {\n logs = await getAction(\n client,\n getContractEvents,\n 'getContractEvents',\n )({\n abi,\n address,\n args,\n eventName,\n fromBlock: previousBlockNumber + 1n,\n toBlock: blockNumber,\n strict,\n } as {} as GetContractEventsParameters)\n } else {\n logs = []\n }\n previousBlockNumber = blockNumber\n }\n\n if (logs.length === 0) return\n if (batch) emit.onLogs(logs as any)\n else for (const log of logs) emit.onLogs([log] as any)\n } catch (err) {\n // If a filter has been set and gets uninstalled, providers will throw an InvalidInput error.\n // Reinitialize the filter when this occurs\n if (filter && err instanceof InvalidInputRpcError)\n initialized = false\n emit.onError?.(err as Error)\n }\n },\n {\n emitOnBegin: true,\n interval: pollingInterval,\n },\n )\n\n return async () => {\n if (filter)\n await getAction(\n client,\n uninstallFilter,\n 'uninstallFilter',\n )({ filter })\n unwatch()\n }\n })\n }\n\n const subscribeContractEvent = () => {\n const strict = strict_ ?? false\n const observerId = stringify([\n 'watchContractEvent',\n address,\n args,\n batch,\n client.uid,\n eventName,\n pollingInterval,\n strict,\n ])\n\n let active = true\n let unsubscribe = () => (active = false)\n return observe(observerId, { onLogs, onError }, (emit) => {\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 topics: LogTopic[] = eventName\n ? encodeEventTopics({\n abi: abi,\n eventName: eventName,\n args,\n } as EncodeEventTopicsParameters)\n : []\n\n const { unsubscribe: unsubscribe_ } = await transport.subscribe({\n params: ['logs', { address, topics }],\n onData(data: any) {\n if (!active) return\n const log = data.result\n try {\n const { eventName, args } = decodeEventLog({\n abi: abi,\n data: log.data,\n topics: log.topics as any,\n strict: strict_,\n })\n const formatted = formatLog(log, {\n args,\n eventName: eventName as string,\n })\n emit.onLogs([formatted] as any)\n } catch (err) {\n let eventName: string | undefined\n let isUnnamed: boolean | undefined\n if (\n err instanceof DecodeLogDataMismatch ||\n err instanceof DecodeLogTopicsMismatch\n ) {\n // If strict mode is on, and log data/topics do not match event definition, skip.\n if (strict_) return\n eventName = err.abiItem.name\n isUnnamed = err.abiItem.inputs?.some(\n (x) => !('name' in x && x.name),\n )\n }\n\n // Set args to empty if there is an error decoding (e.g. indexed/non-indexed params mismatch).\n const formatted = formatLog(log, {\n args: isUnnamed ? [] : {},\n eventName,\n })\n emit.onLogs([formatted] as any)\n }\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 ? pollContractEvent() : subscribeContractEvent()\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 {\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 { 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 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 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 { 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 { 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 { 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","const size = 256\nlet index = size\nlet buffer: string\n\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = ''\n index = 0\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1)\n }\n }\n return buffer.substring(index, index++ + length)\n}\n","import type { Address } from 'abitype'\n\nimport type { JsonRpcAccount } from '../accounts/types.js'\nimport {\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","import type { Address } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { BlockTag } from '../../types/block.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { RequestErrorType } from '../../utils/buildRequest.js'\nimport {\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\n\nexport type GetCodeParameters = {\n address: Address\n} & (\n | {\n blockNumber?: undefined\n blockTag?: BlockTag | undefined\n }\n | {\n blockNumber?: bigint | undefined\n blockTag?: undefined\n }\n)\n\nexport type GetCodeReturnType = Hex | undefined\n\nexport type GetCodeErrorType =\n | NumberToHexErrorType\n | RequestErrorType\n | ErrorType\n\n/**\n * Retrieves the bytecode at an address.\n *\n * - Docs: https://viem.sh/docs/contract/getCode\n * - JSON-RPC Methods: [`eth_getCode`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_getcode)\n *\n * @param client - Client to use\n * @param parameters - {@link GetCodeParameters}\n * @returns The contract's bytecode. {@link GetCodeReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getCode } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const code = await getCode(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * })\n */\nexport async function getCode<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n { address, blockNumber, blockTag = 'latest' }: GetCodeParameters,\n): Promise<GetCodeReturnType> {\n const blockNumberHex =\n blockNumber !== undefined ? numberToHex(blockNumber) : undefined\n const hex = await client.request(\n {\n method: 'eth_getCode',\n params: [address, blockNumberHex || blockTag],\n },\n { dedupe: Boolean(blockNumberHex) },\n )\n if (hex === '0x') return undefined\n return hex\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 {\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 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 type { Address } from 'abitype'\n\nimport type { ErrorType } from '../../errors/utils.js'\nimport { type GetAddressErrorType, getAddress } from '../address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../address/isAddressEqual.js'\nimport {\n type RecoverAuthorizationAddressErrorType,\n type RecoverAuthorizationAddressParameters,\n recoverAuthorizationAddress,\n} from './recoverAuthorizationAddress.js'\n\nexport type VerifyAuthorizationParameters =\n RecoverAuthorizationAddressParameters & {\n /** The address that signed the Authorization object. */\n address: Address\n }\n\nexport type VerifyAuthorizationReturnType = boolean\n\nexport type VerifyAuthorizationErrorType =\n | IsAddressEqualErrorType\n | GetAddressErrorType\n | RecoverAuthorizationAddressErrorType\n | ErrorType\n\n/**\n * Verify that an Authorization object was signed by the provided address.\n *\n * - Docs {@link https://viem.sh/docs/utilities/verifyAuthorization}\n *\n * @param parameters - {@link VerifyAuthorizationParameters}\n * @returns Whether or not the signature is valid. {@link VerifyAuthorizationReturnType}\n */\nexport async function verifyAuthorization({\n address,\n authorization,\n signature,\n}: VerifyAuthorizationParameters): Promise<VerifyAuthorizationReturnType> {\n return isAddressEqual(\n getAddress(address),\n await recoverAuthorizationAddress({\n authorization,\n signature,\n }),\n )\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 { 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 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","import { BaseError, type BaseErrorType } from '../../errors/base.js'\nimport {\n InvalidHexValueError,\n type InvalidHexValueErrorType,\n} from '../../errors/encoding.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'\nimport { type HexToBytesErrorType, hexToBytes } from './toBytes.js'\nimport { type BytesToHexErrorType, bytesToHex } from './toHex.js'\n\nimport type { RecursiveArray } from './toRlp.js'\n\ntype To = 'hex' | 'bytes'\n\nexport type FromRlpReturnType<to extends To> =\n | (to extends 'bytes' ? RecursiveArray<ByteArray> : never)\n | (to extends 'hex' ? RecursiveArray<Hex> : never)\n\nexport type FromRlpErrorType =\n | CreateCursorErrorType\n | FromRlpCursorErrorType\n | HexToBytesErrorType\n | InvalidHexValueErrorType\n | ErrorType\n\nexport function fromRlp<to extends To = 'hex'>(\n value: ByteArray | Hex,\n to: to | To | undefined = 'hex',\n): FromRlpReturnType<to> {\n const bytes = (() => {\n if (typeof value === 'string') {\n if (value.length > 3 && value.length % 2 !== 0)\n throw new InvalidHexValueError(value)\n return hexToBytes(value)\n }\n return value\n })()\n\n const cursor = createCursor(bytes, {\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n })\n const result = fromRlpCursor(cursor, to)\n\n return result as FromRlpReturnType<to>\n}\n\ntype FromRlpCursorErrorType =\n | BytesToHexErrorType\n | ReadLengthErrorType\n | ReadListErrorType\n | ErrorType\n\nfunction fromRlpCursor<to extends To = 'hex'>(\n cursor: Cursor,\n to: to | To | undefined = 'hex',\n): FromRlpReturnType<to> {\n if (cursor.bytes.length === 0)\n return (\n to === 'hex' ? bytesToHex(cursor.bytes) : cursor.bytes\n ) as FromRlpReturnType<to>\n\n const prefix = cursor.readByte()\n if (prefix < 0x80) cursor.decrementPosition(1)\n\n // bytes\n if (prefix < 0xc0) {\n const length = readLength(cursor, prefix, 0x80)\n const bytes = cursor.readBytes(length)\n return (to === 'hex' ? bytesToHex(bytes) : bytes) as FromRlpReturnType<to>\n }\n\n // list\n const length = readLength(cursor, prefix, 0xc0)\n return readList(cursor, length, to) as {} as FromRlpReturnType<to>\n}\n\ntype ReadLengthErrorType = BaseErrorType | ErrorType\n\nfunction readLength(cursor: Cursor, prefix: number, offset: number) {\n if (offset === 0x80 && prefix < 0x80) return 1\n if (prefix <= offset + 55) return prefix - offset\n if (prefix === offset + 55 + 1) return cursor.readUint8()\n if (prefix === offset + 55 + 2) return cursor.readUint16()\n if (prefix === offset + 55 + 3) return cursor.readUint24()\n if (prefix === offset + 55 + 4) return cursor.readUint32()\n throw new BaseError('Invalid RLP prefix')\n}\n\ntype ReadListErrorType = ErrorType\n\nfunction readList<to extends To>(cursor: Cursor, length: number, to: to | To) {\n const position = cursor.position\n const value: FromRlpReturnType<to>[] = []\n while (cursor.position - position < length)\n value.push(fromRlpCursor(cursor, to))\n return value\n}\n","import type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../types/misc.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type SizeErrorType, size } from '../data/size.js'\n\nexport type IsHashErrorType = IsHexErrorType | SizeErrorType | ErrorType\n\nexport function isHash(hash: string): hash is Hex {\n return isHex(hash) && size(hash) === 32\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 {\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 { 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 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 * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Authorization from '../core/Authorization.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport * as Secp256k1 from '../core/Secp256k1.js'\nimport * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-8010 signature. */\nexport type Unwrapped = {\n /** Authorization signed by the delegatee. */\n authorization: Authorization.Authorization<true>\n /** Data to initialize the delegation. */\n data?: Hex.Hex | undefined\n /** The original signature. */\n signature: Hex.Hex\n /** Address of the initializer. */\n to?: Address.Address | undefined\n}\n\n/** Wrapped ERC-8010 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-8010 wrapped signatures.\n */\nexport const magicBytes =\n '0x8010801080108010801080108010801080108010801080108010801080108010' as const\n\n/** Suffix ABI parameters for the ERC-8010 wrapped signature. */\nexport const suffixParameters = AbiParameters.from(\n '(uint256 chainId, address delegation, uint256 nonce, uint8 yParity, uint256 r, uint256 s), address to, bytes data',\n)\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * SignatureErc8010.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-8010 wrapped signature.\n * ```\n *\n * @param value - The value to assert.\n */\nexport function assert(value: Unwrapped | Wrapped) {\n if (typeof value === 'string') {\n if (Hex.slice(value, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(value)\n } else Signature.assert(value.authorization)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc8010.from('0x...') // [!code focus]\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc8010.from({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * })\n * // @log: { authorization: { ... }, data: '0x...', signature: { ... } }\n * ```\n *\n * @param value - Value to parse.\n * @returns Parsed value.\n */\nexport function from(value: Unwrapped | Wrapped): Unwrapped {\n if (typeof value === 'string') return unwrap(value)\n return value\n}\n\nexport declare namespace from {\n type ErrorType = unwrap.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Unwraps an [ERC-8010 wrapped signature](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const { authorization, data, signature } = SignatureErc8010.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to unwrap.\n * @returns Unwrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const suffixLength = Hex.toNumber(Hex.slice(wrapped, -64, -32))\n const suffix = Hex.slice(wrapped, -suffixLength - 64, -64)\n const signature = Hex.slice(wrapped, 0, -suffixLength - 64)\n\n const [auth, to, data] = AbiParameters.decode(suffixParameters, suffix)\n\n const authorization = Authorization.from({\n address: auth.delegation,\n chainId: Number(auth.chainId),\n nonce: auth.nonce,\n yParity: auth.yParity,\n r: auth.r,\n s: auth.s,\n })\n\n return {\n authorization,\n signature,\n ...(data && data !== '0x' ? { data, to } : {}),\n }\n}\n\nexport declare namespace unwrap {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Wraps a signature into [ERC-8010 format](https://github.com/jxom/ERCs/blob/16f7e3891fff2e1e9c25dea0485497739db8a816/ERCS/erc-8010.md).\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc8010 } from 'ox/erc8010' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc8010.wrap({ // [!code focus]\n * authorization: { ... }, // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Values to wrap.\n * @returns Wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature } = value\n\n assert(value)\n\n const self = Secp256k1.recoverAddress({\n payload: Authorization.getSignPayload(value.authorization),\n signature: Signature.from(value.authorization),\n })\n\n const suffix = AbiParameters.encode(suffixParameters, [\n {\n ...value.authorization,\n delegation: value.authorization.address,\n chainId: BigInt(value.authorization.chainId),\n },\n value.to ?? self,\n data ?? '0x',\n ])\n const suffixLength = Hex.fromNumber(Hex.size(suffix), { size: 32 })\n return Hex.concat(signature, suffix, suffixLength, magicBytes)\n}\n\nexport declare namespace wrap {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc8010 } from 'ox/erc8010'\n *\n * const valid = SignatureErc8010.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param value - The value to validate.\n * @returns `true` if the value is valid, `false` otherwise.\n */\nexport function validate(value: Unwrapped | Wrapped): boolean {\n try {\n assert(value)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-8010 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc8010.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-8010 wrapped signature.`)\n }\n}\n","/**\n * @internal\n *\n * Map with a LRU (Least recently used) policy.\n * @see 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 * as Address from './Address.js'\nimport { LruMap } from './internal/lru.js'\n\nconst caches = {\n checksum: /*#__PURE__*/ new LruMap<Address.Address>(8192),\n}\n\nexport const checksum = caches.checksum\n\n/**\n * Clears all global caches.\n *\n * @example\n * ```ts\n * import { Caches } from 'ox'\n * Caches.clear()\n * ```\n */\nexport function clear() {\n for (const cache of Object.values(caches)) cache.clear()\n}\n","import { hmac } from '@noble/hashes/hmac'\nimport { ripemd160 as noble_ripemd160 } from '@noble/hashes/ripemd160'\nimport { keccak_256 as noble_keccak256 } from '@noble/hashes/sha3'\nimport { sha256 as noble_sha256 } from '@noble/hashes/sha256'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\n/**\n * Calculates the [Keccak256](https://en.wikipedia.org/wiki/SHA-3) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `keccak_256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef')\n * // @log: '0xd4fd4e189132273036449fc9e11198c739161b4c0116a9a2dccdfa1c492006f1'\n * ```\n *\n * @example\n * ### Calculate Hash of a String\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.keccak256(Hex.fromString('hello world'))\n * // @log: '0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.keccak256('0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Keccak256 hash.\n */\nexport function keccak256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: keccak256.Options<as> = {},\n): keccak256.ReturnType<as> {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_keccak256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace keccak256 {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [HMAC-SHA256](https://en.wikipedia.org/wiki/HMAC) of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `hmac` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef')\n * // @log: '0x...'\n * ```\n *\n * @example\n * ### Configure Return Type\n *\n * ```ts twoslash\n * import { Hash, Hex } from 'ox'\n *\n * Hash.hmac256(Hex.fromString('key'), '0xdeadbeef', { as: 'Bytes' })\n * // @log: Uint8Array [...]\n * ```\n *\n * @param key - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} key.\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns HMAC-SHA256 hash.\n */\nexport function hmac256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n key: Hex.Hex | Bytes.Bytes,\n value: value | Hex.Hex | Bytes.Bytes,\n options: hmac256.Options<as> = {},\n): hmac256.ReturnType<as> {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = hmac(noble_sha256, Bytes.from(key), Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace hmac256 {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Ripemd160](https://en.wikipedia.org/wiki/RIPEMD) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `ripemd160` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.ripemd160('0xdeadbeef')\n * // '0x226821c2f5423e11fe9af68bd285c249db2e4b5a'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Ripemd160 hash.\n */\nexport function ripemd160<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: ripemd160.Options<as> = {},\n): ripemd160.ReturnType<as> {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_ripemd160(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace ripemd160 {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Calculates the [Sha256](https://en.wikipedia.org/wiki/SHA-256) hash of a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n *\n * This function is a re-export of `sha256` from [`@noble/hashes`](https://github.com/paulmillr/noble-hashes), an audited & minimal JS hashing library.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.sha256('0xdeadbeef')\n * // '0x5f78c33274e43fa9de5659265c1d917e25c03722dcb0b8d27db8d5feaa813953'\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value.\n * @param options - Options.\n * @returns Sha256 hash.\n */\nexport function sha256<\n value extends Hex.Hex | Bytes.Bytes,\n as extends 'Hex' | 'Bytes' =\n | (value extends Hex.Hex ? 'Hex' : never)\n | (value extends Bytes.Bytes ? 'Bytes' : never),\n>(\n value: value | Hex.Hex | Bytes.Bytes,\n options: sha256.Options<as> = {},\n): sha256.ReturnType<as> {\n const { as = typeof value === 'string' ? 'Hex' : 'Bytes' } = options\n const bytes = noble_sha256(Bytes.from(value))\n if (as === 'Bytes') return bytes as never\n return Hex.fromBytes(bytes) as never\n}\n\nexport declare namespace sha256 {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = {\n /** The return type. @default 'Hex' */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Bytes.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if a string is a valid hash value.\n *\n * @example\n * ```ts twoslash\n * import { Hash } from 'ox'\n *\n * Hash.validate('0x')\n * // @log: false\n *\n * Hash.validate('0x3ea2f1d0abf3fc66cf29eebb70cbd4e7fe762ef8a09bcc06c8edf641230afec0')\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns Whether the value is a valid hash.\n */\nexport function validate(value: string): value is Hex.Hex {\n return Hex.validate(value) && Hex.size(value) === 32\n}\n\nexport declare namespace validate {\n type ErrorType =\n | Hex.validate.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial } from './internal/types.js'\nimport * as Json from './Json.js'\n\n/** Root type for an ECDSA Public Key. */\nexport type PublicKey<\n compressed extends boolean = false,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n compressed extends true\n ? {\n prefix: numberType\n x: bigintType\n y?: undefined\n }\n : {\n prefix: numberType\n x: bigintType\n y: bigintType\n }\n>\n\n/**\n * Asserts that a {@link ox#PublicKey.PublicKey} is valid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @error: PublicKey.InvalidError: Value \\`{\"y\":\"1\"}\\` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function assert(\n publicKey: ExactPartial<PublicKey>,\n options: assert.Options = {},\n): asserts publicKey is PublicKey {\n const { compressed } = options\n const { prefix, x, y } = publicKey\n\n // Uncompressed\n if (\n compressed === false ||\n (typeof x === 'bigint' && typeof y === 'bigint')\n ) {\n if (prefix !== 4)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidUncompressedPrefixError(),\n })\n return\n }\n\n // Compressed\n if (\n compressed === true ||\n (typeof x === 'bigint' && typeof y === 'undefined')\n ) {\n if (prefix !== 3 && prefix !== 2)\n throw new InvalidPrefixError({\n prefix,\n cause: new InvalidCompressedPrefixError(),\n })\n return\n }\n\n // Unknown/invalid\n throw new InvalidError({ publicKey })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = InvalidError | InvalidPrefixError | Errors.GlobalErrorType\n}\n\n/**\n * Compresses a {@link ox#PublicKey.PublicKey}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const compressed = PublicKey.compress(publicKey) // [!code focus]\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The public key to compress.\n * @returns The compressed public key.\n */\nexport function compress(publicKey: PublicKey<false>): PublicKey<true> {\n const { x, y } = publicKey\n return {\n prefix: y % 2n === 0n ? 2 : 3,\n x,\n }\n}\n\nexport declare namespace compress {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#PublicKey.PublicKey} object from a {@link ox#PublicKey.PublicKey}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from('0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param value - The public key value to instantiate.\n * @returns The instantiated {@link ox#PublicKey.PublicKey}.\n */\nexport function from<\n const publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes,\n>(value: from.Value<publicKey>): from.ReturnType<publicKey> {\n const publicKey = (() => {\n if (Hex.validate(value)) return fromHex(value)\n if (Bytes.validate(value)) return fromBytes(value)\n\n const { prefix, x, y } = value\n if (typeof x === 'bigint' && typeof y === 'bigint')\n return { prefix: prefix ?? 0x04, x, y }\n return { prefix, x }\n })()\n\n assert(publicKey)\n\n return publicKey as never\n}\n\n/** @internal */\ntype CompressedPublicKey = PublicKey<true>\n\n/** @internal */\ntype UncompressedPublicKey = Omit<PublicKey<false>, 'prefix'> & {\n prefix?: PublicKey['prefix'] | undefined\n}\n\nexport declare namespace from {\n type Value<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey | CompressedPublicKey | UncompressedPublicKey\n\n type ReturnType<\n publicKey extends\n | CompressedPublicKey\n | UncompressedPublicKey\n | Hex.Hex\n | Bytes.Bytes = PublicKey,\n > = publicKey extends CompressedPublicKey | UncompressedPublicKey\n ? publicKey extends UncompressedPublicKey\n ? Compute<publicKey & { readonly prefix: 0x04 }>\n : publicKey\n : PublicKey\n\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromBytes(publicKey: Bytes.Bytes): PublicKey {\n return fromHex(Hex.fromBytes(publicKey))\n}\n\nexport declare namespace fromBytes {\n type ErrorType =\n | fromHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#PublicKey.PublicKey} from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x8318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5')\n * // @log: {\n * // @log: prefix: 4,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * // @log: }\n * ```\n *\n * @example\n * ### Deserializing a Compressed Public Key\n *\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.fromHex('0x038318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed75')\n * // @log: {\n * // @log: prefix: 3,\n * // @log: x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * // @log: }\n * ```\n *\n * @param publicKey - The serialized public key.\n * @returns The deserialized public key.\n */\nexport function fromHex(publicKey: Hex.Hex): PublicKey {\n if (\n publicKey.length !== 132 &&\n publicKey.length !== 130 &&\n publicKey.length !== 68\n )\n throw new InvalidSerializedSizeError({ publicKey })\n\n if (publicKey.length === 130) {\n const x = BigInt(Hex.slice(publicKey, 0, 32))\n const y = BigInt(Hex.slice(publicKey, 32, 64))\n return {\n prefix: 4,\n x,\n y,\n } as never\n }\n\n if (publicKey.length === 132) {\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n const y = BigInt(Hex.slice(publicKey, 33, 65))\n return {\n prefix,\n x,\n y,\n } as never\n }\n\n const prefix = Number(Hex.slice(publicKey, 0, 1))\n const x = BigInt(Hex.slice(publicKey, 1, 33))\n return {\n prefix,\n x,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType = Hex.slice.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const bytes = PublicKey.toBytes(publicKey) // [!code focus]\n * // @log: Uint8Array [128, 3, 131, ...]\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toBytes(\n publicKey: PublicKey<boolean>,\n options: toBytes.Options = {},\n): Bytes.Bytes {\n return Bytes.fromHex(toHex(publicKey, options))\n}\n\nexport declare namespace toBytes {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#PublicKey.PublicKey} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from({\n * prefix: 4,\n * x: 59295962801117472859457908919941473389380284132224861839820747729565200149877n,\n * y: 24099691209996290925259367678540227198235484593389470330605641003500238088869n,\n * })\n *\n * const hex = PublicKey.toHex(publicKey) // [!code focus]\n * // @log: '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5'\n * ```\n *\n * @param publicKey - The public key to serialize.\n * @returns The serialized public key.\n */\nexport function toHex(\n publicKey: PublicKey<boolean>,\n options: toHex.Options = {},\n): Hex.Hex {\n assert(publicKey)\n\n const { prefix, x, y } = publicKey\n const { includePrefix = true } = options\n\n const publicKey_ = Hex.concat(\n includePrefix ? Hex.fromNumber(prefix, { size: 1 }) : '0x',\n Hex.fromNumber(x, { size: 32 }),\n // If the public key is not compressed, add the y coordinate.\n typeof y === 'bigint' ? Hex.fromNumber(y, { size: 32 }) : '0x',\n )\n\n return publicKey_\n}\n\nexport declare namespace toHex {\n type Options = {\n /**\n * Whether to include the prefix in the serialized public key.\n * @default true\n */\n includePrefix?: boolean | undefined\n }\n\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Validates a {@link ox#PublicKey.PublicKey}. Returns `true` if valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * const valid = PublicKey.validate({\n * prefix: 4,\n * y: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * })\n * // @log: false\n * ```\n *\n * @param publicKey - The public key object to assert.\n */\nexport function validate(\n publicKey: ExactPartial<PublicKey>,\n options: validate.Options = {},\n): boolean {\n try {\n assert(publicKey, options)\n return true\n } catch (_error) {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the public key should be compressed. */\n compressed?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when a public key is invalid.\n *\n * @example\n * ```ts twoslash\n * import { PublicKey } from 'ox'\n *\n * PublicKey.assert({ y: 1n })\n * // @error: PublicKey.InvalidError: Value `{\"y\":1n}` is not a valid public key.\n * // @error: Public key must contain:\n * // @error: - an `x` and `prefix` value (compressed)\n * // @error: - an `x`, `y`, and `prefix` value (uncompressed)\n * ```\n */\nexport class InvalidError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidError'\n\n constructor({ publicKey }: { publicKey: unknown }) {\n super(`Value \\`${Json.stringify(publicKey)}\\` is not a valid public key.`, {\n metaMessages: [\n 'Public key must contain:',\n '- an `x` and `prefix` value (compressed)',\n '- an `x`, `y`, and `prefix` value (uncompressed)',\n ],\n })\n }\n}\n\n/** Thrown when a public key has an invalid prefix. */\nexport class InvalidPrefixError<\n cause extends InvalidCompressedPrefixError | InvalidUncompressedPrefixError =\n | InvalidCompressedPrefixError\n | InvalidUncompressedPrefixError,\n> extends Errors.BaseError<cause> {\n override readonly name = 'PublicKey.InvalidPrefixError'\n\n constructor({ prefix, cause }: { prefix: number | undefined; cause: cause }) {\n super(`Prefix \"${prefix}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when the public key has an invalid prefix for a compressed public key. */\nexport class InvalidCompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidCompressedPrefixError'\n\n constructor() {\n super('Prefix must be 2 or 3 for compressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid prefix for an uncompressed public key. */\nexport class InvalidUncompressedPrefixError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidUncompressedPrefixError'\n\n constructor() {\n super('Prefix must be 4 for uncompressed public keys.')\n }\n}\n\n/** Thrown when the public key has an invalid serialized size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'PublicKey.InvalidSerializedSizeError'\n\n constructor({ publicKey }: { publicKey: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${publicKey}\\` is an invalid public key size.`, {\n metaMessages: [\n 'Expected: 33 bytes (compressed + prefix), 64 bytes (uncompressed) or 65 bytes (uncompressed + prefix).',\n `Received ${Hex.size(Hex.from(publicKey))} bytes.`,\n ],\n })\n }\n}\n","import type { Address as abitype_Address } from 'abitype'\nimport * as Bytes from './Bytes.js'\nimport * as Caches from './Caches.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as PublicKey from './PublicKey.js'\n\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/\n\n/** Root type for Address. */\nexport type Address = abitype_Address\n\n/**\n * Asserts that the given value is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.assert('0xdeadbeef')\n * // @error: InvalidAddressError: Address \"0xdeadbeef\" is invalid.\n * ```\n *\n * @param value - Value to assert if it is a valid address.\n * @param options - Assertion options.\n */\nexport function assert(\n value: string,\n options: assert.Options = {},\n): asserts value is Address {\n const { strict = true } = options\n\n if (!addressRegex.test(value))\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidInputError(),\n })\n\n if (strict) {\n if (value.toLowerCase() === value) return\n if (checksum(value as Address) !== value)\n throw new InvalidAddressError({\n address: value,\n cause: new InvalidChecksumError(),\n })\n }\n}\n\nexport declare namespace assert {\n type Options = {\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\n type ErrorType = InvalidAddressError | Errors.GlobalErrorType\n}\n\n/**\n * Computes the checksum address for the given {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.checksum('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @param address - The address to compute the checksum for.\n * @returns The checksummed address.\n */\nexport function checksum(address: string): Address {\n if (Caches.checksum.has(address)) return Caches.checksum.get(address)!\n\n assert(address, { strict: false })\n\n const hexAddress = address.substring(2).toLowerCase()\n const hash = Hash.keccak256(Bytes.fromString(hexAddress), { as: 'Bytes' })\n\n const characters = hexAddress.split('')\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1]! >> 4 >= 8 && characters[i]) {\n characters[i] = characters[i]!.toUpperCase()\n }\n if ((hash[i >> 1]! & 0x0f) >= 8 && characters[i + 1]) {\n characters[i + 1] = characters[i + 1]!.toUpperCase()\n }\n }\n\n const result = `0x${characters.join('')}` as const\n Caches.checksum.set(address, result)\n return result\n}\n\nexport declare namespace checksum {\n type ErrorType =\n | assert.ErrorType\n | Hash.keccak256.ErrorType\n | Bytes.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a stringified address to a typed (optionally checksummed) {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e')\n * // @log: '0xa0cf798816d4b9b9866b5330eea46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0xa0cf798816d4b9b9866b5330eea46a18382f251e', {\n * checksum: true\n * })\n * // @log: '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('hello')\n * // @error: InvalidAddressError: Address \"0xa\" is invalid.\n * ```\n *\n * @param address - An address string to convert to a typed Address.\n * @param options - Conversion options.\n * @returns The typed Address.\n */\nexport function from(address: string, options: from.Options = {}): Address {\n const { checksum: checksumVal = false } = options\n assert(address)\n if (checksumVal) return checksum(address)\n return address as Address\n}\n\nexport declare namespace from {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | assert.ErrorType\n | checksum.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an ECDSA public key to an {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address, PublicKey } from 'ox'\n *\n * const publicKey = PublicKey.from(\n * '0x048318535b54105d4a7aae60c08fc45f9687181b4fdfc625bd1a753fa7397fed753547f11ca8696646f2f3acb08e31016afac23e630c5d11f59f61fef57b0d2aa5',\n * )\n * const address = Address.fromPublicKey(publicKey)\n * // @log: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266'\n * ```\n *\n * @param publicKey - The ECDSA public key to convert to an {@link ox#Address.Address}.\n * @param options - Conversion options.\n * @returns The {@link ox#Address.Address} corresponding to the public key.\n */\nexport function fromPublicKey(\n publicKey: PublicKey.PublicKey,\n options: fromPublicKey.Options = {},\n): Address {\n const address = Hash.keccak256(\n `0x${PublicKey.toHex(publicKey).slice(4)}`,\n ).substring(26)\n return from(`0x${address}`, options)\n}\n\nexport declare namespace fromPublicKey {\n type Options = {\n /**\n * Whether to checksum the address.\n *\n * @default false\n */\n checksum?: boolean | undefined\n }\n\n type ErrorType =\n | Hash.keccak256.ErrorType\n | PublicKey.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Checks if two {@link ox#Address.Address} are equal.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'\n * )\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.isEqual(\n * '0xa0cf798816d4b9b9866b5330eea46a18382f251e',\n * '0xA0Cf798816D4b9b9866b5330EEa46a18382f251f'\n * )\n * // @log: false\n * ```\n *\n * @param addressA - The first address to compare.\n * @param addressB - The second address to compare.\n * @returns Whether the addresses are equal.\n */\nexport function isEqual(addressA: Address, addressB: Address): boolean {\n assert(addressA, { strict: false })\n assert(addressB, { strict: false })\n return addressA.toLowerCase() === addressB.toLowerCase()\n}\n\nexport declare namespace isEqual {\n type ErrorType = assert.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Checks if the given address is a valid {@link ox#Address.Address}.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xA0Cf798816D4b9b9866b5330EEa46a18382f251e')\n * // @log: true\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param address - Value to check if it is a valid address.\n * @param options - Check options.\n * @returns Whether the address is a valid address.\n */\nexport function validate(\n address: string,\n options: validate.Options = {},\n): address is Address {\n const { strict = true } = options ?? {}\n try {\n assert(address, { strict })\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\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}\n\n/**\n * Thrown when an address is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Address } from 'ox'\n *\n * Address.from('0x123')\n * // @error: Address.InvalidAddressError: Address `0x123` is invalid.\n * ```\n */\nexport class InvalidAddressError<\n cause extends InvalidInputError | InvalidChecksumError =\n | InvalidInputError\n | InvalidChecksumError,\n> extends Errors.BaseError<cause> {\n override readonly name = 'Address.InvalidAddressError'\n\n constructor({ address, cause }: { address: string; cause: cause }) {\n super(`Address \"${address}\" is invalid.`, {\n cause,\n })\n }\n}\n\n/** Thrown when an address is not a 20 byte (40 hexadecimal character) value. */\nexport class InvalidInputError extends Errors.BaseError {\n override readonly name = 'Address.InvalidInputError'\n\n constructor() {\n super('Address is not a 20 byte (40 hexadecimal character) value.')\n }\n}\n\n/** Thrown when an address does not match its checksum counterpart. */\nexport class InvalidChecksumError extends Errors.BaseError {\n override readonly name = 'Address.InvalidChecksumError'\n\n constructor() {\n super('Address does not match its checksum counterpart.')\n }\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\nexport 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 type {\n AbiParameter,\n AbiParameterKind,\n AbiParametersToPrimitiveTypes,\n AbiParameterToPrimitiveType,\n} from 'abitype'\nimport * as AbiParameters from '../AbiParameters.js'\nimport * as Address from '../Address.js'\nimport * as Bytes from '../Bytes.js'\nimport * as Errors from '../Errors.js'\nimport * as Hex from '../Hex.js'\nimport { integerRegex } from '../Solidity.js'\nimport type * as Cursor from './cursor.js'\nimport type { Compute, IsNarrowable, UnionToIntersection } from './types.js'\n\n/** @internal */\nexport type ParameterToPrimitiveType<\n abiParameter extends AbiParameter | { name: string; type: unknown },\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParameterToPrimitiveType<abiParameter, abiParameterKind>\n\n/** @internal */\nexport type PreparedParameter = { dynamic: boolean; encoded: Hex.Hex }\n\n/** @internal */\nexport type ToObject<\n parameters extends readonly AbiParameter[],\n kind extends AbiParameterKind = AbiParameterKind,\n> = IsNarrowable<parameters, AbiParameters.AbiParameters> extends true\n ? Compute<\n UnionToIntersection<\n {\n [index in keyof parameters]: parameters[index] extends {\n name: infer name extends string\n }\n ? {\n [key in name]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n : {\n [key in index]: AbiParameterToPrimitiveType<\n parameters[index],\n kind\n >\n }\n }[number]\n >\n >\n : unknown\n\n/** @internal */\nexport type ToPrimitiveTypes<\n abiParameters extends readonly AbiParameter[],\n abiParameterKind extends AbiParameterKind = AbiParameterKind,\n> = AbiParametersToPrimitiveTypes<abiParameters, abiParameterKind>\n\n/** @internal */\nexport type Tuple = ParameterToPrimitiveType<TupleAbiParameter>\n\n/** @internal */\nexport function decodeParameter(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\n const arrayComponents = getArrayComponents(param.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return decodeArray(\n cursor,\n { ...param, type },\n { checksumAddress, length, staticPosition },\n )\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param as TupleAbiParameter, {\n checksumAddress,\n staticPosition,\n })\n if (param.type === 'address')\n return decodeAddress(cursor, { checksum: checksumAddress })\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 AbiParameters.InvalidTypeError(param.type)\n}\n\nexport declare namespace decodeParameter {\n type ErrorType =\n | decodeArray.ErrorType\n | decodeTuple.ErrorType\n | decodeAddress.ErrorType\n | decodeBool.ErrorType\n | decodeBytes.ErrorType\n | decodeNumber.ErrorType\n | decodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\nconst sizeOfLength = 32\nconst sizeOfOffset = 32\n\n/** @internal */\nexport function decodeAddress(\n cursor: Cursor.Cursor,\n options: { checksum?: boolean | undefined } = {},\n) {\n const { checksum = false } = options\n const value = cursor.readBytes(32)\n const wrap = (address: Hex.Hex) =>\n checksum ? Address.checksum(address) : address\n return [wrap(Hex.fromBytes(Bytes.slice(value, -20))), 32]\n}\n\nexport declare namespace decodeAddress {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeArray(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n staticPosition: number\n },\n) {\n const { checksumAddress, length, staticPosition } = options\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 = Bytes.toNumber(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 = Bytes.toNumber(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 checksumAddress,\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition: staticPosition + consumed,\n })\n consumed += consumed_\n value.push(data)\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeArray {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBool(cursor: Cursor.Cursor) {\n return [Bytes.toBoolean(cursor.readBytes(32), { size: 32 }), 32]\n}\n\nexport declare namespace decodeBool {\n type ErrorType = Bytes.toBoolean.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeBytes(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\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 = Bytes.toNumber(cursor.readBytes(32))\n\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset)\n\n const length = Bytes.toNumber(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 [Hex.fromBytes(data), 32]\n }\n\n const value = Hex.fromBytes(cursor.readBytes(Number.parseInt(size, 10), 32))\n return [value, 32]\n}\n\nexport declare namespace decodeBytes {\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | Bytes.toNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeNumber(\n cursor: Cursor.Cursor,\n param: AbiParameters.Parameter,\n) {\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 ? Bytes.toBigInt(value, { signed })\n : Bytes.toNumber(value, { signed }),\n 32,\n ]\n}\n\nexport declare namespace decodeNumber {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport type TupleAbiParameter = AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n}\n\n/** @internal */\nexport function decodeTuple(\n cursor: Cursor.Cursor,\n param: TupleAbiParameter,\n options: { checksumAddress?: boolean | undefined; staticPosition: number },\n) {\n const { checksumAddress, staticPosition } = options\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 = Bytes.toNumber(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 checksumAddress,\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 checksumAddress,\n staticPosition,\n })\n value[hasUnnamedChild ? i : component?.name!] = data\n consumed += consumed_\n }\n return [value, consumed]\n}\n\nexport declare namespace decodeTuple {\n type ErrorType = Bytes.toNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function decodeString(\n cursor: Cursor.Cursor,\n { staticPosition }: { staticPosition: number },\n) {\n // Get offset to start of string data.\n const offset = Bytes.toNumber(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 = Bytes.toNumber(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 = Bytes.toString(Bytes.trimLeft(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\nexport declare namespace decodeString {\n type ErrorType =\n | Bytes.toNumber.ErrorType\n | Bytes.toString.ErrorType\n | Bytes.trimLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameters<\n const parameters extends AbiParameters.AbiParameters,\n>({\n checksumAddress,\n parameters,\n values,\n}: {\n checksumAddress?: boolean | undefined\n parameters: parameters\n values: parameters extends AbiParameters.AbiParameters\n ? ToPrimitiveTypes<parameters>\n : never\n}) {\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameters.length; i++) {\n preparedParameters.push(\n prepareParameter({\n checksumAddress,\n parameter: parameters[i]!,\n value: values[i],\n }),\n )\n }\n return preparedParameters\n}\n\n/** @internal */\nexport declare namespace prepareParameters {\n type ErrorType = prepareParameter.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function prepareParameter<\n const parameter extends AbiParameters.Parameter,\n>({\n checksumAddress = false,\n parameter: parameter_,\n value,\n}: {\n parameter: parameter\n value: parameter extends AbiParameters.Parameter\n ? ParameterToPrimitiveType<parameter>\n : never\n checksumAddress?: boolean | undefined\n}): PreparedParameter {\n const parameter = parameter_ as AbiParameters.Parameter\n\n const arrayComponents = getArrayComponents(parameter.type)\n if (arrayComponents) {\n const [length, type] = arrayComponents\n return encodeArray(value, {\n checksumAddress,\n length,\n parameter: {\n ...parameter,\n type,\n },\n })\n }\n if (parameter.type === 'tuple') {\n return encodeTuple(value as unknown as Tuple, {\n checksumAddress,\n parameter: parameter as TupleAbiParameter,\n })\n }\n if (parameter.type === 'address') {\n return encodeAddress(value as unknown as Hex.Hex, {\n checksum: checksumAddress,\n })\n }\n if (parameter.type === 'bool') {\n return encodeBoolean(value as unknown as boolean)\n }\n if (parameter.type.startsWith('uint') || parameter.type.startsWith('int')) {\n const signed = parameter.type.startsWith('int')\n const [, , size = '256'] = integerRegex.exec(parameter.type) ?? []\n return encodeNumber(value as unknown as number, {\n signed,\n size: Number(size),\n })\n }\n if (parameter.type.startsWith('bytes')) {\n return encodeBytes(value as unknown as Hex.Hex, { type: parameter.type })\n }\n if (parameter.type === 'string') {\n return encodeString(value as unknown as string)\n }\n throw new AbiParameters.InvalidTypeError(parameter.type)\n}\n\n/** @internal */\nexport declare namespace prepareParameter {\n type ErrorType =\n | encodeArray.ErrorType\n | encodeTuple.ErrorType\n | encodeAddress.ErrorType\n | encodeBoolean.ErrorType\n | encodeBytes.ErrorType\n | encodeString.ErrorType\n | AbiParameters.InvalidTypeError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encode(preparedParameters: PreparedParameter[]): Hex.Hex {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) staticSize += 32\n else staticSize += Hex.size(encoded)\n }\n\n // 2. Split the parameters into static and dynamic parts.\n const staticParameters: Hex.Hex[] = []\n const dynamicParameters: Hex.Hex[] = []\n let dynamicSize = 0\n for (let i = 0; i < preparedParameters.length; i++) {\n const { dynamic, encoded } = preparedParameters[i]!\n if (dynamic) {\n staticParameters.push(\n Hex.fromNumber(staticSize + dynamicSize, { size: 32 }),\n )\n dynamicParameters.push(encoded)\n dynamicSize += Hex.size(encoded)\n } else {\n staticParameters.push(encoded)\n }\n }\n\n // 3. Concatenate static and dynamic parts.\n return Hex.concat(...staticParameters, ...dynamicParameters)\n}\n\n/** @internal */\nexport declare namespace encode {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeAddress(\n value: Hex.Hex,\n options: { checksum: boolean },\n): PreparedParameter {\n const { checksum = false } = options\n Address.assert(value, { strict: checksum })\n return {\n dynamic: false,\n encoded: Hex.padLeft(value.toLowerCase() as Hex.Hex),\n }\n}\n\n/** @internal */\nexport declare namespace encodeAddress {\n type ErrorType =\n | Address.assert.ErrorType\n | Hex.padLeft.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeArray<const parameter extends AbiParameters.Parameter>(\n value: ParameterToPrimitiveType<parameter>,\n options: {\n checksumAddress?: boolean | undefined\n length: number | null\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, length, parameter } = options\n\n const dynamic = length === null\n\n if (!Array.isArray(value)) throw new AbiParameters.InvalidArrayError(value)\n if (!dynamic && value.length !== length)\n throw new AbiParameters.ArrayLengthMismatchError({\n expectedLength: length!,\n givenLength: value.length,\n type: `${parameter.type}[${length}]`,\n })\n\n let dynamicChild = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter,\n value: value[i],\n })\n if (preparedParam.dynamic) dynamicChild = true\n preparedParameters.push(preparedParam)\n }\n\n if (dynamic || dynamicChild) {\n const data = encode(preparedParameters)\n if (dynamic) {\n const length = Hex.fromNumber(preparedParameters.length, { size: 32 })\n return {\n dynamic: true,\n encoded:\n preparedParameters.length > 0 ? Hex.concat(length, data) : length,\n }\n }\n if (dynamicChild) return { dynamic: true, encoded: data }\n }\n return {\n dynamic: false,\n encoded: Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeArray {\n type ErrorType =\n | AbiParameters.InvalidArrayError\n | AbiParameters.ArrayLengthMismatchError\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBytes(\n value: Hex.Hex,\n { type }: { type: string },\n): PreparedParameter {\n const [, parametersize] = type.split('bytes')\n const bytesSize = Hex.size(value)\n if (!parametersize) {\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_ = Hex.padRight(value_, Math.ceil((value.length - 2) / 2 / 32) * 32)\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padLeft(Hex.fromNumber(bytesSize, { size: 32 })),\n value_,\n ),\n }\n }\n if (bytesSize !== Number.parseInt(parametersize, 10))\n throw new AbiParameters.BytesSizeMismatchError({\n expectedSize: Number.parseInt(parametersize, 10),\n value,\n })\n return { dynamic: false, encoded: Hex.padRight(value) }\n}\n\n/** @internal */\nexport declare namespace encodeBytes {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.padRight.ErrorType\n | Hex.fromNumber.ErrorType\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeBoolean(value: boolean): PreparedParameter {\n if (typeof value !== 'boolean')\n throw new Errors.BaseError(\n `Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`,\n )\n return { dynamic: false, encoded: Hex.padLeft(Hex.fromBoolean(value)) }\n}\n\n/** @internal */\nexport declare namespace encodeBoolean {\n type ErrorType =\n | Hex.padLeft.ErrorType\n | Hex.fromBoolean.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeNumber(\n value: number,\n { signed, size }: { signed: boolean; size: number },\n): PreparedParameter {\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 Hex.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: Hex.fromNumber(value, {\n size: 32,\n signed,\n }),\n }\n}\n\n/** @internal */\nexport declare namespace encodeNumber {\n type ErrorType = Hex.fromNumber.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeString(value: string): PreparedParameter {\n const hexValue = Hex.fromString(value)\n const partsLength = Math.ceil(Hex.size(hexValue) / 32)\n const parts: Hex.Hex[] = []\n for (let i = 0; i < partsLength; i++) {\n parts.push(Hex.padRight(Hex.slice(hexValue, i * 32, (i + 1) * 32)))\n }\n return {\n dynamic: true,\n encoded: Hex.concat(\n Hex.padRight(Hex.fromNumber(Hex.size(hexValue), { size: 32 })),\n ...parts,\n ),\n }\n}\n\n/** @internal */\nexport declare namespace encodeString {\n type ErrorType =\n | Hex.fromNumber.ErrorType\n | Hex.padRight.ErrorType\n | Hex.slice.ErrorType\n | Hex.size.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function encodeTuple<\n const parameter extends AbiParameters.Parameter & {\n components: readonly AbiParameters.Parameter[]\n },\n>(\n value: ParameterToPrimitiveType<parameter>,\n options: {\n checksumAddress?: boolean | undefined\n parameter: parameter\n },\n): PreparedParameter {\n const { checksumAddress, parameter } = options\n\n let dynamic = false\n const preparedParameters: PreparedParameter[] = []\n for (let i = 0; i < parameter.components.length; i++) {\n const param_ = parameter.components[i]!\n const index = Array.isArray(value) ? i : param_.name\n const preparedParam = prepareParameter({\n checksumAddress,\n parameter: param_,\n value: (value as any)[index!] as readonly unknown[],\n })\n preparedParameters.push(preparedParam)\n if (preparedParam.dynamic) dynamic = true\n }\n return {\n dynamic,\n encoded: dynamic\n ? encode(preparedParameters)\n : Hex.concat(...preparedParameters.map(({ encoded }) => encoded)),\n }\n}\n\n/** @internal */\nexport declare namespace encodeTuple {\n type ErrorType = Hex.concat.ErrorType | Errors.GlobalErrorType\n}\n\n/** @internal */\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\n/** @internal */\nexport function hasDynamicChild(param: AbiParameters.Parameter) {\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({\n ...param,\n type: arrayComponents[1],\n } as AbiParameters.Parameter)\n )\n return true\n\n return false\n}\n","import type { Bytes } from '../Bytes.js'\nimport * as Errors from '../Errors.js'\n\n/** @internal */\nexport type Cursor = {\n bytes: Bytes\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): Bytes[number]\n inspectBytes(length: number, position?: number): Bytes\n inspectUint8(position?: number): number\n inspectUint16(position?: number): number\n inspectUint24(position?: number): number\n inspectUint32(position?: number): number\n pushByte(byte: Bytes[number]): void\n pushBytes(bytes: Bytes): void\n pushUint8(value: number): void\n pushUint16(value: number): void\n pushUint24(value: number): void\n pushUint32(value: number): void\n readByte(): Bytes[number]\n readBytes(length: number, size?: number): Bytes\n readUint8(): number\n readUint16(): number\n readUint24(): number\n readUint32(): number\n setPosition(position: number): () => void\n _touch(): void\n}\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: Bytes[number]) {\n this.assertPosition(this.position)\n this.bytes[this.position] = byte\n this.position++\n },\n pushBytes(bytes: Bytes) {\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\n/** @internal */\nexport function create(\n bytes: Bytes,\n { recursiveReadLimit = 8_192 }: create.Config = {},\n): Cursor {\n const cursor: Cursor = Object.create(staticCursor)\n cursor.bytes = bytes\n cursor.dataView = new DataView(\n bytes.buffer,\n bytes.byteOffset,\n bytes.byteLength,\n )\n cursor.positionReadCount = new Map()\n cursor.recursiveReadLimit = recursiveReadLimit\n return cursor\n}\n\n/** @internal */\nexport declare namespace create {\n type Config = { recursiveReadLimit?: number | undefined }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** @internal */\nexport class NegativeOffsetError extends Errors.BaseError {\n override readonly name = 'Cursor.NegativeOffsetError'\n\n constructor({ offset }: { offset: number }) {\n super(`Offset \\`${offset}\\` cannot be negative.`)\n }\n}\n\n/** @internal */\nexport class PositionOutOfBoundsError extends Errors.BaseError {\n override readonly name = 'Cursor.PositionOutOfBoundsError'\n\n constructor({ length, position }: { length: number; position: number }) {\n super(\n `Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`,\n )\n }\n}\n\n/** @internal */\nexport class RecursiveReadLimitExceededError extends Errors.BaseError {\n override readonly name = 'Cursor.RecursiveReadLimitExceededError'\n\n constructor({ count, limit }: { count: number; limit: number }) {\n super(\n `Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`,\n )\n }\n}\n","import * as abitype from 'abitype'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as internal from './internal/abiParameters.js'\nimport * as Cursor from './internal/cursor.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for ABI parameters. */\nexport type AbiParameters = readonly abitype.AbiParameter[]\n\n/** A parameter on an {@link ox#AbiParameters.AbiParameters}. */\nexport type Parameter = abitype.AbiParameter\n\n/** A packed ABI type. */\nexport type PackedAbiType =\n | abitype.SolidityAddress\n | abitype.SolidityBool\n | abitype.SolidityBytes\n | abitype.SolidityInt\n | abitype.SolidityString\n | abitype.SolidityArrayWithoutTuple\n\n/**\n * Decodes ABI-encoded data into its respective primitive values based on ABI Parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * You can pass **JSON ABI** Parameters:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.decode(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' },\n * ],\n * '0x000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000001a4000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000057761676d69000000000000000000000000000000000000000000000000000000',\n * )\n * // @log: ['wagmi', 420n, true]\n * ```\n *\n * @param parameters - The set of ABI parameters to decode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param data - ABI encoded data.\n * @param options - Decoding options.\n * @returns Array of decoded values.\n */\nexport function decode<\n const parameters extends AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n>(\n parameters: parameters,\n data: Bytes.Bytes | Hex.Hex,\n options?: decode.Options<as>,\n): decode.ReturnType<parameters, as>\n\n// eslint-disable-next-line jsdoc/require-jsdoc\nexport function decode(\n parameters: AbiParameters,\n data: Bytes.Bytes | Hex.Hex,\n options: {\n as?: 'Array' | 'Object' | undefined\n checksumAddress?: boolean | undefined\n } = {},\n): readonly unknown[] | Record<string, unknown> {\n const { as = 'Array', checksumAddress = false } = options\n\n const bytes = typeof data === 'string' ? Bytes.fromHex(data) : data\n const cursor = Cursor.create(bytes)\n\n if (Bytes.size(bytes) === 0 && parameters.length > 0)\n throw new ZeroDataError()\n if (Bytes.size(bytes) && Bytes.size(bytes) < 32)\n throw new DataSizeTooSmallError({\n data: typeof data === 'string' ? data : Hex.fromBytes(data),\n parameters: parameters as readonly Parameter[],\n size: Bytes.size(bytes),\n })\n\n let consumed = 0\n const values: any = as === 'Array' ? [] : {}\n for (let i = 0; i < parameters.length; ++i) {\n const param = parameters[i] as Parameter\n cursor.setPosition(consumed)\n const [data, consumed_] = internal.decodeParameter(cursor, param, {\n checksumAddress,\n staticPosition: 0,\n })\n consumed += consumed_\n if (as === 'Array') values.push(data)\n else values[param.name ?? i] = data\n }\n return values\n}\n\nexport declare namespace decode {\n type Options<as extends 'Object' | 'Array'> = {\n /**\n * Whether the decoded values should be returned as an `Object` or `Array`.\n *\n * @default \"Array\"\n */\n as?: as | 'Object' | 'Array' | undefined\n /**\n * Whether decoded addresses should be checksummed.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n\n type ReturnType<\n parameters extends AbiParameters = AbiParameters,\n as extends 'Object' | 'Array' = 'Array',\n > = parameters extends readonly []\n ? as extends 'Object'\n ? {}\n : []\n : as extends 'Object'\n ? internal.ToObject<parameters>\n : internal.ToPrimitiveTypes<parameters>\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | internal.decodeParameter.ErrorType\n | ZeroDataError\n | DataSizeTooSmallError\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes primitive values into ABI encoded data as per the [Application Binary Interface (ABI) Specification](https://docs.soliditylang.org/en/latest/abi-spec).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * AbiParameters.from(['string', 'uint', 'bool']),\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @example\n * ### JSON Parameters\n *\n * Specify **JSON ABI** Parameters as schema:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const data = AbiParameters.encode(\n * [\n * { type: 'string', name: 'name' },\n * { type: 'uint', name: 'age' },\n * { type: 'bool', name: 'isOwner' },\n * ],\n * ['wagmi', 420n, true],\n * )\n * ```\n *\n * @param parameters - The set of ABI parameters to encode, in the shape of the `inputs` or `outputs` attribute of an ABI Item. These parameters must include valid [ABI types](https://docs.soliditylang.org/en/latest/types.html).\n * @param values - The set of primitive values that correspond to the ABI types defined in `parameters`.\n * @returns ABI encoded data.\n */\nexport function encode<\n const parameters extends AbiParameters | readonly unknown[],\n>(\n parameters: parameters,\n values: parameters extends AbiParameters\n ? internal.ToPrimitiveTypes<parameters>\n : never,\n options?: encode.Options,\n): Hex.Hex {\n const { checksumAddress = false } = options ?? {}\n\n if (parameters.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: parameters.length as number,\n givenLength: values.length as any,\n })\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParameters = internal.prepareParameters({\n checksumAddress,\n parameters: parameters as readonly Parameter[],\n values: values as any,\n })\n const data = internal.encode(preparedParameters)\n if (data.length === 0) return '0x'\n return data\n}\n\nexport declare namespace encode {\n type ErrorType =\n | LengthMismatchError\n | internal.encode.ErrorType\n | internal.prepareParameters.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /**\n * Whether addresses should be checked against their checksum.\n *\n * @default false\n */\n checksumAddress?: boolean | undefined\n }\n}\n\n/**\n * Encodes an array of primitive values to a [packed ABI encoding](https://docs.soliditylang.org/en/latest/abi-spec.html#non-standard-packed-mode).\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const encoded = AbiParameters.encodePacked(\n * ['address', 'string'],\n * ['0xd8da6bf26964af9d7eed9e03e53415d37aa96045', 'hello world'],\n * )\n * // @log: '0xd8da6bf26964af9d7eed9e03e53415d37aa9604568656c6c6f20776f726c64'\n * ```\n *\n * @param types - Set of ABI types to pack encode.\n * @param values - The set of primitive values that correspond to the ABI types defined in `types`.\n * @returns The encoded packed data.\n */\nexport function encodePacked<\n const packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n>(types: packedAbiTypes, values: encodePacked.Values<packedAbiTypes>): Hex.Hex {\n if (types.length !== values.length)\n throw new LengthMismatchError({\n expectedLength: types.length as number,\n givenLength: values.length as number,\n })\n\n const data: Hex.Hex[] = []\n for (let i = 0; i < (types as unknown[]).length; i++) {\n const type = types[i]\n const value = values[i]\n data.push(encodePacked.encode(type, value))\n }\n return Hex.concat(...data)\n}\n\nexport namespace encodePacked {\n export type ErrorType =\n | Hex.concat.ErrorType\n | LengthMismatchError\n | Errors.GlobalErrorType\n\n export type Values<\n packedAbiTypes extends readonly PackedAbiType[] | readonly unknown[],\n > = {\n [key in keyof packedAbiTypes]: packedAbiTypes[key] extends abitype.AbiType\n ? abitype.AbiParameterToPrimitiveType<{ type: packedAbiTypes[key] }>\n : unknown\n }\n\n // eslint-disable-next-line jsdoc/require-jsdoc\n export function encode<const packedAbiType extends PackedAbiType | unknown>(\n type: packedAbiType,\n value: Values<[packedAbiType]>[0],\n isArray = false,\n ): Hex.Hex {\n if (type === 'address') {\n const address = value as Address.Address\n Address.assert(address)\n return Hex.padLeft(\n address.toLowerCase() as Hex.Hex,\n isArray ? 32 : 0,\n ) as Address.Address\n }\n if (type === 'string') return Hex.fromString(value as string)\n if (type === 'bytes') return value as Hex.Hex\n if (type === 'bool')\n return Hex.padLeft(Hex.fromBoolean(value as boolean), isArray ? 32 : 1)\n\n const intMatch = (type as string).match(Solidity.integerRegex)\n if (intMatch) {\n const [_type, baseType, bits = '256'] = intMatch\n const size = Number.parseInt(bits, 10) / 8\n return Hex.fromNumber(value as number, {\n size: isArray ? 32 : size,\n signed: baseType === 'int',\n })\n }\n\n const bytesMatch = (type as string).match(Solidity.bytesRegex)\n if (bytesMatch) {\n const [_type, size] = bytesMatch\n if (Number.parseInt(size!, 10) !== ((value as Hex.Hex).length - 2) / 2)\n throw new BytesSizeMismatchError({\n expectedSize: Number.parseInt(size!, 10),\n value: value as Hex.Hex,\n })\n return Hex.padRight(value as Hex.Hex, isArray ? 32 : 0) as Hex.Hex\n }\n\n const arrayMatch = (type as string).match(Solidity.arrayRegex)\n if (arrayMatch && Array.isArray(value)) {\n const [_type, childType] = arrayMatch\n const data: Hex.Hex[] = []\n for (let i = 0; i < value.length; i++) {\n data.push(encode(childType, value[i], true))\n }\n if (data.length === 0) return '0x'\n return Hex.concat(...data)\n }\n\n throw new InvalidTypeError(type as string)\n }\n}\n\n/**\n * Formats {@link ox#AbiParameters.AbiParameters} into **Human Readable ABI Parameters**.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const formatted = AbiParameters.format([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * formatted\n * // ^?\n *\n *\n * ```\n *\n * @param parameters - The ABI Parameters to format.\n * @returns The formatted ABI Parameters .\n */\nexport function format<\n const parameters extends readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n>(\n parameters:\n | parameters\n | readonly [\n Parameter | abitype.AbiEventParameter,\n ...(readonly (Parameter | abitype.AbiEventParameter)[]),\n ],\n): abitype.FormatAbiParameters<parameters> {\n return abitype.formatAbiParameters(parameters)\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses arbitrary **JSON ABI Parameters** or **Human Readable ABI Parameters** into typed {@link ox#AbiParameters.AbiParameters}.\n *\n * @example\n * ### JSON Parameters\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * {\n * name: 'spender',\n * type: 'address',\n * },\n * {\n * name: 'amount',\n * type: 'uint256',\n * },\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * ### Human Readable Parameters\n *\n * Human Readable ABI Parameters can be parsed into a typed {@link ox#AbiParameters.AbiParameters}:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from('address spender, uint256 amount')\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n * @example\n * It is possible to specify `struct`s along with your definitions:\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * const parameters = AbiParameters.from([\n * 'struct Foo { address spender; uint256 amount; }', // [!code hl]\n * 'Foo foo, address bar',\n * ])\n *\n * parameters\n * //^?\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n *\n * ```\n *\n *\n *\n * @param parameters - The ABI Parameters to parse.\n * @returns The typed ABI Parameters.\n */\nexport function from<\n const parameters extends AbiParameters | string | readonly string[],\n>(\n parameters: parameters | AbiParameters | string | readonly string[],\n): from.ReturnType<parameters> {\n if (Array.isArray(parameters) && typeof parameters[0] === 'string')\n return abitype.parseAbiParameters(parameters) as never\n if (typeof parameters === 'string')\n return abitype.parseAbiParameters(parameters) as never\n return parameters as never\n}\n\nexport declare namespace from {\n type ReturnType<\n parameters extends AbiParameters | string | readonly string[],\n > = parameters extends string\n ? abitype.ParseAbiParameters<parameters>\n : parameters extends readonly string[]\n ? abitype.ParseAbiParameters<parameters>\n : parameters\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Throws when the data size is too small for the given parameters.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x010f')\n * // ↑ ❌ 2 bytes\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass a valid data size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class DataSizeTooSmallError extends Errors.BaseError {\n override readonly name = 'AbiParameters.DataSizeTooSmallError'\n constructor({\n data,\n parameters,\n size,\n }: { data: Hex.Hex; parameters: readonly Parameter[]; size: number }) {\n super(`Data size of ${size} bytes is too small for given parameters.`, {\n metaMessages: [\n `Params: (${abitype.formatAbiParameters(parameters as readonly [Parameter])})`,\n `Data: ${data} (${size} bytes)`,\n ],\n })\n }\n}\n\n/**\n * Throws when zero data is provided, but data is expected.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x')\n * // ↑ ❌ zero data\n * // @error: AbiParameters.DataSizeTooSmallError: Data size of 2 bytes is too small for given parameters.\n * // @error: Params: (uint256)\n * // @error: Data: 0x010f (2 bytes)\n * ```\n *\n * ### Solution\n *\n * Pass valid data.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'uint256' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ✅ 32 bytes\n * ```\n */\nexport class ZeroDataError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ZeroDataError'\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.')\n }\n}\n\n/**\n * The length of the array value does not match the length specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('uint256[3]'), [[69n, 420n]])\n * // ↑ expected: 3 ↑ ❌ length: 2\n * // @error: AbiParameters.ArrayLengthMismatchError: ABI encoding array length mismatch\n * // @error: for type `uint256[3]`. Expected: `3`. Given: `2`.\n * ```\n *\n * ### Solution\n *\n * Pass an array of the correct length.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [[69n, 420n, 69n]])\n * // ↑ ✅ length: 3\n * ```\n */\nexport class ArrayLengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.ArrayLengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n type,\n }: { expectedLength: number; givenLength: number; type: string }) {\n super(\n `Array length mismatch for type \\`${type}\\`. Expected: \\`${expectedLength}\\`. Given: \\`${givenLength}\\`.`,\n )\n }\n}\n\n/**\n * The size of the bytes value does not match the size specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from('bytes8'), [['0xdeadbeefdeadbeefdeadbeef']])\n * // ↑ expected: 8 bytes ↑ ❌ size: 12 bytes\n * // @error: BytesSizeMismatchError: Size of bytes \"0xdeadbeefdeadbeefdeadbeef\"\n * // @error: (bytes12) does not match expected size (bytes8).\n * ```\n *\n * ### Solution\n *\n * Pass a bytes value of the correct size.\n *\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['bytes8']), ['0xdeadbeefdeadbeef'])\n * // ↑ ✅ size: 8 bytes\n * ```\n */\nexport class BytesSizeMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.BytesSizeMismatchError'\n constructor({\n expectedSize,\n value,\n }: { expectedSize: number; value: Hex.Hex }) {\n super(\n `Size of bytes \"${value}\" (bytes${Hex.size(\n value,\n )}) does not match expected size (bytes${expectedSize}).`,\n )\n }\n}\n\n/**\n * The length of the values to encode does not match the length of the ABI parameters.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['string', 'uint256']), ['hello'])\n * // @error: LengthMismatchError: ABI encoding params/values length mismatch.\n * // @error: Expected length (params): 2\n * // @error: Given length (values): 1\n * ```\n *\n * ### Solution\n *\n * Pass the correct number of values to encode.\n *\n * ### Solution\n *\n * Pass a [valid ABI type](https://docs.soliditylang.org/en/develop/abi-spec.html#types).\n */\nexport class LengthMismatchError extends Errors.BaseError {\n override readonly name = 'AbiParameters.LengthMismatchError'\n constructor({\n expectedLength,\n givenLength,\n }: { expectedLength: number; givenLength: number }) {\n super(\n [\n 'ABI encoding parameters/values length mismatch.',\n `Expected length (parameters): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'),\n )\n }\n}\n\n/**\n * The value provided is not a valid array as specified in the corresponding ABI parameter.\n *\n * ### Example\n *\n * ```ts twoslash\n * // @noErrors\n * import { AbiParameters } from 'ox'\n * // ---cut---\n * AbiParameters.encode(AbiParameters.from(['uint256[3]']), [69])\n * ```\n *\n * ### Solution\n *\n * Pass an array value.\n */\nexport class InvalidArrayError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidArrayError'\n constructor(value: unknown) {\n super(`Value \\`${value}\\` is not a valid array.`)\n }\n}\n\n/**\n * Throws when the ABI parameter type is invalid.\n *\n * @example\n * ```ts twoslash\n * import { AbiParameters } from 'ox'\n *\n * AbiParameters.decode([{ type: 'lol' }], '0x00000000000000000000000000000000000000000000000000000000000010f')\n * // ↑ ❌ invalid type\n * // @error: AbiParameters.InvalidTypeError: Type `lol` is not a valid ABI Type.\n * ```\n */\nexport class InvalidTypeError extends Errors.BaseError {\n override readonly name = 'AbiParameters.InvalidTypeError'\n constructor(type: string) {\n super(`Type \\`${type}\\` is not a valid ABI Type.`)\n }\n}\n","import * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Cursor from './internal/cursor.js'\nimport type { ExactPartial, RecursiveArray } from './internal/types.js'\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toBytes('0x8b68656c6c6f20776f726c64')\n * // Uint8Array([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Bytes.Bytes} value.\n */\nexport function toBytes(\n value: Bytes.Bytes | Hex.Hex,\n): RecursiveArray<Bytes.Bytes> {\n return to(value, 'Bytes')\n}\n\nexport declare namespace toBytes {\n type ErrorType = to.ErrorType\n}\n\n/**\n * Decodes a Recursive-Length Prefix (RLP) value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n * Rlp.toHex('0x8b68656c6c6f20776f726c64')\n * // 0x68656c6c6f20776f726c64\n * ```\n *\n * @param value - The value to decode.\n * @returns The decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value: Bytes.Bytes | Hex.Hex): RecursiveArray<Hex.Hex> {\n return to(value, 'Hex')\n}\n\nexport declare namespace toHex {\n type ErrorType = to.ErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\n/////////////////////////////////////////////////////////////////////////////////\n\n/** @internal */\nexport function to<\n value extends Bytes.Bytes | Hex.Hex,\n to extends 'Hex' | 'Bytes',\n>(value: value, to: to | 'Hex' | 'Bytes'): to.ReturnType<to> {\n const to_ = to ?? (typeof value === 'string' ? 'Hex' : 'Bytes')\n\n const bytes = (() => {\n if (typeof value === 'string') {\n if (value.length > 3 && value.length % 2 !== 0)\n throw new Hex.InvalidLengthError(value)\n return Bytes.fromHex(value)\n }\n return value as Bytes.Bytes\n })()\n\n const cursor = Cursor.create(bytes, {\n recursiveReadLimit: Number.POSITIVE_INFINITY,\n })\n const result = decodeRlpCursor(cursor, to_)\n\n return result as to.ReturnType<to>\n}\n\n/** @internal */\nexport declare namespace to {\n type ReturnType<to extends 'Hex' | 'Bytes' = 'Hex' | 'Bytes'> =\n | (to extends 'Bytes' ? RecursiveArray<Bytes.Bytes> : never)\n | (to extends 'Hex' ? RecursiveArray<Hex.Hex> : never)\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | decodeRlpCursor.ErrorType\n | Cursor.create.ErrorType\n | Hex.InvalidLengthError\n | Errors.GlobalErrorType\n}\n\n/** @internal */\n\n/** @internal */\nexport function decodeRlpCursor<to extends 'Hex' | 'Bytes' = 'Hex'>(\n cursor: Cursor.Cursor,\n to: to | 'Hex' | 'Bytes' | undefined = 'Hex',\n): decodeRlpCursor.ReturnType<to> {\n if (cursor.bytes.length === 0)\n return (\n to === 'Hex' ? Hex.fromBytes(cursor.bytes) : cursor.bytes\n ) as decodeRlpCursor.ReturnType<to>\n\n const prefix = cursor.readByte()\n if (prefix < 0x80) cursor.decrementPosition(1)\n\n // bytes\n if (prefix < 0xc0) {\n const length = readLength(cursor, prefix, 0x80)\n const bytes = cursor.readBytes(length)\n return (\n to === 'Hex' ? Hex.fromBytes(bytes) : bytes\n ) as decodeRlpCursor.ReturnType<to>\n }\n\n // list\n const length = readLength(cursor, prefix, 0xc0)\n return readList(cursor, length, to) as {} as decodeRlpCursor.ReturnType<to>\n}\n\n/** @internal */\nexport declare namespace decodeRlpCursor {\n type ReturnType<to extends 'Hex' | 'Bytes' = 'Hex'> = to.ReturnType<to>\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | readLength.ErrorType\n | readList.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readLength(\n cursor: Cursor.Cursor,\n prefix: number,\n offset: number,\n) {\n if (offset === 0x80 && prefix < 0x80) return 1\n if (prefix <= offset + 55) return prefix - offset\n if (prefix === offset + 55 + 1) return cursor.readUint8()\n if (prefix === offset + 55 + 2) return cursor.readUint16()\n if (prefix === offset + 55 + 3) return cursor.readUint24()\n if (prefix === offset + 55 + 4) return cursor.readUint32()\n throw new Errors.BaseError('Invalid RLP prefix')\n}\n\n/** @internal */\nexport declare namespace readLength {\n type ErrorType = Errors.BaseError | Errors.GlobalErrorType\n}\n\n/** @internal */\nexport function readList<to extends 'Hex' | 'Bytes'>(\n cursor: Cursor.Cursor,\n length: number,\n to: to | 'Hex' | 'Bytes',\n) {\n const position = cursor.position\n const value: decodeRlpCursor.ReturnType<to>[] = []\n while (cursor.position - position < length)\n value.push(decodeRlpCursor(cursor, to))\n return value\n}\n\n/** @internal */\nexport declare namespace readList {\n type ErrorType = Errors.GlobalErrorType\n}\n\ntype Encodable = {\n length: number\n encode(cursor: Cursor.Cursor): void\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.from('0x68656c6c6f20776f726c64', { as: 'Hex' })\n * // @log: 0x8b68656c6c6f20776f726c64\n *\n * Rlp.from(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]), { as: 'Bytes' })\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} or {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function from<as extends 'Hex' | 'Bytes'>(\n value: RecursiveArray<Bytes.Bytes> | RecursiveArray<Hex.Hex>,\n options: from.Options<as>,\n): from.ReturnType<as> {\n const { as } = options\n\n const encodable = getEncodable(value)\n const cursor = Cursor.create(new Uint8Array(encodable.length))\n encodable.encode(cursor)\n\n if (as === 'Hex') return Hex.fromBytes(cursor.bytes) as from.ReturnType<as>\n return cursor.bytes as from.ReturnType<as>\n}\n\nexport declare namespace from {\n type Options<as extends 'Hex' | 'Bytes'> = {\n /** The type to convert the RLP value to. */\n as: as | 'Hex' | 'Bytes'\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Cursor.create.ErrorType\n | Hex.fromBytes.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Rlp } from 'ox'\n *\n * Rlp.fromBytes(Bytes.from([139, 104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100]))\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromBytes<as extends 'Hex' | 'Bytes' = 'Bytes'>(\n bytes: RecursiveArray<Bytes.Bytes>,\n options: fromBytes.Options<as> = {},\n): fromBytes.ReturnType<as> {\n const { as = 'Bytes' } = options\n return from(bytes, { as }) as never\n}\n\nexport declare namespace fromBytes {\n type Options<as extends 'Hex' | 'Bytes' = 'Bytes'> = ExactPartial<\n from.Options<as>\n >\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Bytes'> = from.ReturnType<as>\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} value into a Recursive-Length Prefix (RLP) value.\n *\n * @example\n * ```ts twoslash\n * import { Rlp } from 'ox'\n *\n * Rlp.fromHex('0x68656c6c6f20776f726c64')\n * // @log: 0x8b68656c6c6f20776f726c64\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to encode.\n * @param options - Options.\n * @returns The RLP value.\n */\nexport function fromHex<as extends 'Hex' | 'Bytes' = 'Hex'>(\n hex: RecursiveArray<Hex.Hex>,\n options: fromHex.Options<as> = {},\n): fromHex.ReturnType<as> {\n const { as = 'Hex' } = options\n return from(hex, { as }) as never\n}\n\nexport declare namespace fromHex {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = ExactPartial<\n from.Options<as>\n >\n\n type ReturnType<as extends 'Hex' | 'Bytes' = 'Hex'> = from.ReturnType<as>\n\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/////////////////////////////////////////////////////////////////////////////////\n// Internal\n/////////////////////////////////////////////////////////////////////////////////\n\nfunction getEncodable(\n bytes: RecursiveArray<Bytes.Bytes> | RecursiveArray<Hex.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.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: Bytes.Bytes | Hex.Hex): Encodable {\n const bytes =\n typeof bytesOrHex === 'string' ? Bytes.fromHex(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.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 <= 0xff) return 1\n if (length <= 0xff_ff) return 2\n if (length <= 0xff_ff_ff) return 3\n if (length <= 0xff_ff_ff_ff) return 4\n throw new Errors.BaseError('Length is too large.')\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Bytes from './Bytes.js'\nimport * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, ExactPartial, OneOf } from './internal/types.js'\nimport * as Json from './Json.js'\nimport * as Solidity from './Solidity.js'\n\n/** Root type for an ECDSA signature. */\nexport type Signature<\n recovered extends boolean = true,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n recovered extends true\n ? {\n r: bigintType\n s: bigintType\n yParity: numberType\n }\n : {\n r: bigintType\n s: bigintType\n yParity?: numberType | undefined\n }\n>\n\n/** RPC-formatted ECDSA signature. */\nexport type Rpc<recovered extends boolean = true> = Signature<\n recovered,\n Hex.Hex,\n Hex.Hex\n>\n\n/** (Legacy) ECDSA signature. */\nexport type Legacy<bigintType = bigint, numberType = number> = {\n r: bigintType\n s: bigintType\n v: numberType\n}\n\n/** RPC-formatted (Legacy) ECDSA signature. */\nexport type LegacyRpc = Legacy<Hex.Hex, Hex.Hex>\n\nexport type Tuple = readonly [yParity: Hex.Hex, r: Hex.Hex, s: Hex.Hex]\n\n/**\n * Asserts that a Signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.assert({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @error: InvalidSignatureRError:\n * // @error: Value `-549...n` is an invalid r value.\n * // @error: r must be a positive integer less than 2^256.\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function assert(\n signature: ExactPartial<Signature>,\n options: assert.Options = {},\n): asserts signature is Signature {\n const { recovered } = options\n if (typeof signature.r === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (typeof signature.s === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (recovered && typeof signature.yParity === 'undefined')\n throw new MissingPropertiesError({ signature })\n if (signature.r < 0n || signature.r > Solidity.maxUint256)\n throw new InvalidRError({ value: signature.r })\n if (signature.s < 0n || signature.s > Solidity.maxUint256)\n throw new InvalidSError({ value: signature.s })\n if (\n typeof signature.yParity === 'number' &&\n signature.yParity !== 0 &&\n signature.yParity !== 1\n )\n throw new InvalidYParityError({ value: signature.yParity })\n}\n\nexport declare namespace assert {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType =\n | MissingPropertiesError\n | InvalidRError\n | InvalidSError\n | InvalidYParityError\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Bytes.Bytes} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.fromBytes(new Uint8Array([128, 3, 131, ...]))\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param signature - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromBytes(signature: Bytes.Bytes): Signature {\n return fromHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#Hex.Hex} signature into a structured {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.fromHex('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c')\n * // @log: { r: 5231...n, s: 3522...n, yParity: 0 }\n * ```\n *\n * @param serialized - The serialized signature.\n * @returns The deserialized {@link ox#Signature.Signature}.\n */\nexport function fromHex(signature: Hex.Hex): Signature {\n if (signature.length !== 130 && signature.length !== 132)\n throw new InvalidSerializedSizeError({ signature })\n\n const r = BigInt(Hex.slice(signature, 0, 32))\n const s = BigInt(Hex.slice(signature, 32, 64))\n\n const yParity = (() => {\n const yParity = Number(`0x${signature.slice(130)}`)\n if (Number.isNaN(yParity)) return undefined\n try {\n return vToYParity(yParity)\n } catch {\n throw new InvalidYParityError({ value: yParity })\n }\n })()\n\n if (typeof yParity === 'undefined')\n return {\n r,\n s,\n } as never\n return {\n r,\n s,\n yParity,\n } as never\n}\n\nexport declare namespace fromHex {\n type ErrorType =\n | Hex.from.ErrorType\n | InvalidSerializedSizeError\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts a {@link ox#Signature.Signature} from an arbitrary object that may include signature properties.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * Signature.extract({\n * baz: 'barry',\n * foo: 'bar',\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * zebra: 'stripes',\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @param value - The arbitrary object to extract the signature from.\n * @returns The extracted {@link ox#Signature.Signature}.\n */\nexport function extract(value: extract.Value): Signature | undefined {\n if (typeof value.r === 'undefined') return undefined\n if (typeof value.s === 'undefined') return undefined\n return from(value as any)\n}\n\nexport declare namespace extract {\n type Value = {\n r?: bigint | Hex.Hex | undefined\n s?: bigint | Hex.Hex | undefined\n yParity?: number | Hex.Hex | undefined\n v?: number | Hex.Hex | undefined\n }\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Instantiates a typed {@link ox#Signature.Signature} object from a {@link ox#Signature.Signature}, {@link ox#Signature.Legacy}, {@link ox#Bytes.Bytes}, or {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from('0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db801')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @example\n * ### From Legacy\n *\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * Signature.from({\n * r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * v: 27,\n * })\n * // @log: {\n * // @log: r: 47323457007453657207889730243826965761922296599680473886588287015755652701072n,\n * // @log: s: 57228803202727131502949358313456071280488184270258293674242124340113824882788n,\n * // @log: yParity: 0\n * // @log: }\n * ```\n *\n * @param signature - The signature value to instantiate.\n * @returns The instantiated {@link ox#Signature.Signature}.\n */\nexport function from<\n const signature extends\n | OneOf<Signature<boolean> | Rpc<boolean> | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n>(\n signature:\n | signature\n | OneOf<Signature<boolean> | Rpc<boolean> | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n): from.ReturnType<signature> {\n const signature_ = (() => {\n if (typeof signature === 'string') return fromHex(signature)\n if (signature instanceof Uint8Array) return fromBytes(signature)\n if (typeof signature.r === 'string') return fromRpc(signature)\n if (signature.v) return fromLegacy(signature)\n return {\n r: signature.r,\n s: signature.s,\n ...(typeof signature.yParity !== 'undefined'\n ? { yParity: signature.yParity }\n : {}),\n }\n })()\n assert(signature_)\n return signature_ as never\n}\n\nexport declare namespace from {\n type ReturnType<\n signature extends\n | OneOf<Signature<boolean> | Rpc<boolean> | Legacy | LegacyRpc>\n | Hex.Hex\n | Bytes.Bytes,\n > = signature extends Signature<boolean> & { v?: undefined }\n ? signature\n : Signature\n\n type ErrorType =\n | assert.ErrorType\n | fromBytes.ErrorType\n | fromHex.ErrorType\n | vToYParity.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerBytes(new Uint8Array([132, 51, 23, ...]))\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerBytes(signature: Bytes.Bytes): Signature<false> {\n return fromDerHex(Hex.fromBytes(signature))\n}\n\nexport declare namespace fromDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a DER-encoded signature to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromDerHex('0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8')\n * // @log: {\n * // @log: r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * // @log: s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * // @log: }\n * ```\n *\n * @param signature - The DER-encoded signature to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromDerHex(signature: Hex.Hex): Signature<false> {\n const { r, s } = secp256k1.Signature.fromDER(Hex.from(signature).slice(2))\n return { r, s }\n}\n\nexport declare namespace fromDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Legacy} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.fromLegacy({ r: 1n, s: 2n, v: 28 })\n * // @log: { r: 1n, s: 2n, yParity: 1 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Legacy} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromLegacy(signature: Legacy): Signature {\n return {\n r: signature.r,\n s: signature.s,\n yParity: vToYParity(signature.v),\n }\n}\n\nexport declare namespace fromLegacy {\n type ErrorType = vToYParity.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Rpc} into a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromRpc({\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Rpc} to convert.\n * @returns The converted {@link ox#Signature.Signature}.\n */\nexport function fromRpc(signature: {\n r: Hex.Hex\n s: Hex.Hex\n yParity?: Hex.Hex | undefined\n v?: Hex.Hex | undefined\n}): Signature {\n const yParity = (() => {\n const v = signature.v ? Number(signature.v) : undefined\n let yParity = signature.yParity ? Number(signature.yParity) : undefined\n if (typeof v === 'number' && typeof yParity !== 'number')\n yParity = vToYParity(v)\n if (typeof yParity !== 'number')\n throw new InvalidYParityError({ value: signature.yParity })\n return yParity\n })()\n\n return {\n r: BigInt(signature.r),\n s: BigInt(signature.s),\n yParity,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Tuple} to a {@link ox#Signature.Signature}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.fromTuple(['0x01', '0x7b', '0x1c8'])\n * // @log: {\n * // @log: r: 123n,\n * // @log: s: 456n,\n * // @log: yParity: 1,\n * // @log: }\n * ```\n *\n * @param tuple - The {@link ox#Signature.Tuple} to convert.\n * @returns The {@link ox#Signature.Signature}.\n */\nexport function fromTuple(tuple: Tuple): Signature {\n const [yParity, r, s] = tuple\n return from({\n r: r === '0x' ? 0n : BigInt(r),\n s: s === '0x' ? 0n : BigInt(s),\n yParity: yParity === '0x' ? 0 : Number(yParity),\n })\n}\n\nexport declare namespace fromTuple {\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toBytes({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: Uint8Array [102, 16, 10, ...]\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toBytes(signature: Signature<boolean>): Bytes.Bytes {\n return Bytes.fromHex(toHex(signature))\n}\n\nexport declare namespace toBytes {\n type ErrorType =\n | toHex.ErrorType\n | Bytes.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#Signature.Signature} to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toHex({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * // @log: '0x6e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf4a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db81c'\n * ```\n *\n * @param signature - The signature to serialize.\n * @returns The serialized signature.\n */\nexport function toHex(signature: Signature<boolean>): Hex.Hex {\n assert(signature)\n\n const r = signature.r\n const s = signature.s\n\n const signature_ = Hex.concat(\n Hex.fromNumber(r, { size: 32 }),\n Hex.fromNumber(s, { size: 32 }),\n // If the signature is recovered, add the recovery byte to the signature.\n typeof signature.yParity === 'number'\n ? Hex.fromNumber(yParityToV(signature.yParity), { size: 1 })\n : '0x',\n )\n\n return signature_\n}\n\nexport declare namespace toHex {\n type ErrorType =\n | Hex.concat.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerBytes(signature)\n * // @log: Uint8Array [132, 51, 23, ...]\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerBytes(signature: Signature<boolean>): Bytes.Bytes {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return sig.toDERRawBytes()\n}\n\nexport declare namespace toDerBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to DER-encoded format.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.from({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * })\n *\n * const signature_der = Signature.toDerHex(signature)\n * // @log: '0x304402206e100a352ec6ad1b70802290e18aeed190704973570f3b8ed42cb9808e2ea6bf02204a90a229a244495b41890987806fcbd2d5d23fc0dbe5f5256c2613c039d76db8'\n * ```\n *\n * @param signature - The signature to convert.\n * @returns The DER-encoded signature.\n */\nexport function toDerHex(signature: Signature<boolean>): Hex.Hex {\n const sig = new secp256k1.Signature(signature.r, signature.s)\n return `0x${sig.toDERHex()}`\n}\n\nexport declare namespace toDerHex {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Legacy}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const legacy = Signature.toLegacy({ r: 1n, s: 2n, yParity: 1 })\n * // @log: { r: 1n, s: 2n, v: 28 }\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Legacy}.\n */\nexport function toLegacy(signature: Signature): Legacy {\n return {\n r: signature.r,\n s: signature.s,\n v: yParityToV(signature.yParity),\n }\n}\n\nexport declare namespace toLegacy {\n type ErrorType = yParityToV.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} into a {@link ox#Signature.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signature = Signature.toRpc({\n * r: 49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1\n * })\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The converted {@link ox#Signature.Rpc}.\n */\nexport function toRpc(signature: Signature): Rpc {\n const { r, s, yParity } = signature\n return {\n r: Hex.fromNumber(r, { size: 32 }),\n s: Hex.fromNumber(s, { size: 32 }),\n yParity: yParity === 0 ? '0x0' : '0x1',\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#Signature.Signature} to a serialized {@link ox#Signature.Tuple} to be used for signatures in Transaction Envelopes, EIP-7702 Authorization Lists, etc.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const signatureTuple = Signature.toTuple({\n * r: 123n,\n * s: 456n,\n * yParity: 1,\n * })\n * // @log: [yParity: '0x01', r: '0x7b', s: '0x1c8']\n * ```\n *\n * @param signature - The {@link ox#Signature.Signature} to convert.\n * @returns The {@link ox#Signature.Tuple}.\n */\nexport function toTuple(signature: Signature): Tuple {\n const { r, s, yParity } = signature\n\n return [\n yParity ? '0x01' : '0x',\n r === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(r!)),\n s === 0n ? '0x' : Hex.trimLeft(Hex.fromNumber(s!)),\n ] as const\n}\n\nexport declare namespace toTuple {\n type ErrorType =\n | Hex.trimLeft.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a Signature. Returns `true` if the signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const valid = Signature.validate({\n * r: -49782753348462494199823712700004552394425719014458918871452329774910450607807n,\n * s: 33726695977844476214676913201140481102225469284307016937915595756355928419768n,\n * yParity: 1,\n * })\n * // @log: false\n * ```\n *\n * @param signature - The signature object to assert.\n */\nexport function validate(\n signature: ExactPartial<Signature>,\n options: validate.Options = {},\n): boolean {\n try {\n assert(signature, options)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type Options = {\n /** Whether or not the signature should be recovered (contain `yParity`). */\n recovered?: boolean\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const yParity = Signature.vToYParity(28)\n * // @log: 1\n * ```\n *\n * @param v - The ECDSA `v` value to convert.\n * @returns The `yParity` value.\n */\nexport function vToYParity(v: number): Signature['yParity'] {\n if (v === 0 || v === 27) return 0\n if (v === 1 || v === 28) return 1\n if (v >= 35) return v % 2 === 0 ? 1 : 0\n throw new InvalidVError({ value: v })\n}\n\nexport declare namespace vToYParity {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/**\n * Converts a ECDSA `v` value to a `yParity` value.\n *\n * @example\n * ```ts twoslash\n * import { Signature } from 'ox'\n *\n * const v = Signature.yParityToV(1)\n * // @log: 28\n * ```\n *\n * @param yParity - The ECDSA `yParity` value to convert.\n * @returns The `v` value.\n */\nexport function yParityToV(yParity: number): number {\n if (yParity === 0) return 27\n if (yParity === 1) return 28\n throw new InvalidYParityError({ value: yParity })\n}\n\nexport declare namespace yParityToV {\n type ErrorType = InvalidVError | Errors.GlobalErrorType\n}\n\n/** Thrown when the serialized signature is of an invalid size. */\nexport class InvalidSerializedSizeError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSerializedSizeError'\n\n constructor({ signature }: { signature: Hex.Hex | Bytes.Bytes }) {\n super(`Value \\`${signature}\\` is an invalid signature size.`, {\n metaMessages: [\n 'Expected: 64 bytes or 65 bytes.',\n `Received ${Hex.size(Hex.from(signature))} bytes.`,\n ],\n })\n }\n}\n\n/** Thrown when the signature is missing either an `r`, `s`, or `yParity` property. */\nexport class MissingPropertiesError extends Errors.BaseError {\n override readonly name = 'Signature.MissingPropertiesError'\n\n constructor({ signature }: { signature: unknown }) {\n super(\n `Signature \\`${Json.stringify(signature)}\\` is missing either an \\`r\\`, \\`s\\`, or \\`yParity\\` property.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `r` value. */\nexport class InvalidRError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidRError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid r value. r must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `s` value. */\nexport class InvalidSError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidSError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid s value. s must be a positive integer less than 2^256.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `yParity` value. */\nexport class InvalidYParityError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidYParityError'\n\n constructor({ value }: { value: unknown }) {\n super(\n `Value \\`${value}\\` is an invalid y-parity value. Y-parity must be 0 or 1.`,\n )\n }\n}\n\n/** Thrown when the signature has an invalid `v` value. */\nexport class InvalidVError extends Errors.BaseError {\n override readonly name = 'Signature.InvalidVError'\n\n constructor({ value }: { value: number }) {\n super(`Value \\`${value}\\` is an invalid v value. v must be 27, 28 or >=35.`)\n }\n}\n","import type * as Address from './Address.js'\nimport type * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, Mutable, Undefined } from './internal/types.js'\nimport * as Rlp from './Rlp.js'\nimport * as Signature from './Signature.js'\n\n/** Root type for an EIP-7702 Authorization. */\nexport type Authorization<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n {\n /** Address of the contract to set as code for the Authority. */\n address: Address.Address\n /** Chain ID to authorize. */\n chainId: numberType\n /** Nonce of the Authority to authorize. */\n nonce: bigintType\n } & (signed extends true\n ? Signature.Signature<true, bigintType, numberType>\n : Undefined<Signature.Signature>)\n>\n\n/** RPC representation of an {@link ox#Authorization.Authorization}. */\nexport type Rpc = Authorization<true, Hex.Hex, Hex.Hex>\n\n/** List of {@link ox#Authorization.Authorization}. */\nexport type List<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<readonly Authorization<signed, bigintType, numberType>[]>\n\n/** RPC representation of an {@link ox#Authorization.List}. */\nexport type ListRpc = List<true, Hex.Hex, Hex.Hex>\n\n/** Signed representation of a list of {@link ox#Authorization.Authorization}. */\nexport type ListSigned<bigintType = bigint, numberType = number> = List<\n true,\n bigintType,\n numberType\n>\n\n/** Signed representation of an {@link ox#Authorization.Authorization}. */\nexport type Signed<bigintType = bigint, numberType = number> = Authorization<\n true,\n bigintType,\n numberType\n>\n\n/** Tuple representation of an {@link ox#Authorization.Authorization}. */\nexport type Tuple<signed extends boolean = boolean> = signed extends true\n ? readonly [\n chainId: Hex.Hex,\n address: Hex.Hex,\n nonce: Hex.Hex,\n yParity: Hex.Hex,\n r: Hex.Hex,\n s: Hex.Hex,\n ]\n : readonly [chainId: Hex.Hex, address: Hex.Hex, nonce: Hex.Hex]\n\n/** Tuple representation of a signed {@link ox#Authorization.Authorization}. */\nexport type TupleSigned = Tuple<true>\n\n/** Tuple representation of a list of {@link ox#Authorization.Authorization}. */\nexport type TupleList<signed extends boolean = boolean> =\n readonly Tuple<signed>[]\n\n/** Tuple representation of a list of signed {@link ox#Authorization.Authorization}. */\nexport type TupleListSigned = TupleList<true>\n\n/**\n * Converts an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization object into a typed {@link ox#Authorization.Authorization}.\n *\n * @example\n * An Authorization can be instantiated from an [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * ```\n *\n * @example\n * ### Attaching Signatures\n *\n * A {@link ox#Signature.Signature} can be attached with the `signature` option. The example below demonstrates signing\n * an Authorization with {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: Authorization.getSignPayload(authorization),\n * privateKey: '0x...',\n * })\n *\n * const authorization_signed = Authorization.from(authorization, { signature }) // [!code focus]\n * ```\n *\n * @param authorization - An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple in object format.\n * @param options - Authorization options.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function from<\n const authorization extends Authorization | Rpc,\n const signature extends Signature.Signature | undefined = undefined,\n>(\n authorization: authorization | Authorization,\n options: from.Options<signature> = {},\n): from.ReturnType<authorization, signature> {\n if (typeof authorization.chainId === 'string')\n return fromRpc(authorization) as never\n return { ...authorization, ...options.signature } as never\n}\n\nexport declare namespace from {\n type Options<\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = {\n /** The {@link ox#Signature.Signature} to attach to the Authorization. */\n signature?: signature | Signature.Signature | undefined\n }\n\n type ReturnType<\n authorization extends Authorization | Rpc = Authorization,\n signature extends Signature.Signature | undefined =\n | Signature.Signature\n | undefined,\n > = Compute<\n authorization extends Rpc\n ? Signed\n : authorization &\n (signature extends Signature.Signature ? Readonly<signature> : {})\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Rpc} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * })\n * ```\n *\n * @param authorization - The RPC-formatted Authorization.\n * @returns A signed {@link ox#Authorization.Authorization}.\n */\nexport function fromRpc(authorization: Rpc): Signed {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)!\n\n return {\n address,\n chainId: Number(chainId),\n nonce: BigInt(nonce),\n ...signature,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.ListRpc} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * }])\n * ```\n *\n * @param authorizationList - The RPC-formatted Authorization list.\n * @returns A signed {@link ox#Authorization.List}.\n */\nexport function fromRpcList(authorizationList: ListRpc): ListSigned {\n return authorizationList.map(fromRpc)\n}\n\nexport declare namespace fromRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Tuple} to an {@link ox#Authorization.Authorization}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3'\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: }\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3',\n * '0x1',\n * '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90',\n * '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064',\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: }\n * ```\n *\n * @param tuple - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n * @returns The {@link ox#Authorization.Authorization}.\n */\nexport function fromTuple<const tuple extends Tuple>(\n tuple: tuple,\n): fromTuple.ReturnType<tuple> {\n const [chainId, address, nonce, yParity, r, s] = tuple\n let args = {\n address,\n chainId: chainId === '0x' ? 0 : Number(chainId),\n nonce: nonce === '0x' ? 0n : BigInt(nonce),\n }\n if (yParity && r && s)\n args = { ...args, ...Signature.fromTuple([yParity, r, s]) }\n return from(args) as never\n}\n\nexport declare namespace fromTuple {\n type ReturnType<authorization extends Tuple = Tuple> = Compute<\n Authorization<authorization extends Tuple<true> ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.TupleList} to an {@link ox#Authorization.List}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @example\n * It is also possible to append a Signature tuple to the end of an Authorization tuple.\n *\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorizationList = Authorization.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14', '0x1', '0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90', '0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @param tupleList - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n * @returns An {@link ox#Authorization.List}.\n */\nexport function fromTupleList<const tupleList extends TupleList>(\n tupleList: tupleList,\n): fromTupleList.ReturnType<tupleList> {\n const list: Mutable<List> = []\n for (const tuple of tupleList) list.push(fromTuple(tuple))\n return list as never\n}\n\nexport declare namespace fromTupleList {\n type ReturnType<tupleList extends TupleList> = Compute<\n TupleList<tupleList extends TupleList<true> ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the sign payload for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * The example below demonstrates computing the sign payload for an {@link ox#Authorization.Authorization}. This payload\n * can then be passed to signing functions like {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * import { Authorization, Secp256k1 } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const payload = Authorization.getSignPayload(authorization) // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload,\n * privateKey: '0x...',\n * })\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The sign payload.\n */\nexport function getSignPayload(authorization: Authorization): Hex.Hex {\n return hash(authorization, { presign: true })\n}\n\nexport declare namespace getSignPayload {\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the hash for an {@link ox#Authorization.Authorization} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const hash = Authorization.hash(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns The hash.\n */\nexport function hash(\n authorization: Authorization,\n options: hash.Options = {},\n): Hex.Hex {\n const { presign } = options\n return Hash.keccak256(\n Hex.concat(\n '0x05',\n Rlp.fromHex(\n toTuple(\n presign\n ? {\n address: authorization.address,\n chainId: authorization.chainId,\n nonce: authorization.nonce,\n }\n : authorization,\n ),\n ),\n ),\n )\n}\n\nexport declare namespace hash {\n type ErrorType =\n | toTuple.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.concat.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /** Whether to hash this authorization for signing. @default false */\n presign?: boolean | undefined\n }\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpc({\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * })\n * ```\n *\n * @param authorization - An Authorization.\n * @returns An RPC-formatted Authorization.\n */\nexport function toRpc(authorization: Signed): Rpc {\n const { address, chainId, nonce, ...signature } = authorization\n\n return {\n address,\n chainId: Hex.fromNumber(chainId),\n nonce: Hex.fromNumber(nonce),\n ...Signature.toRpc(signature),\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.ListRpc}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.toRpcList([{\n * address: '0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * }])\n * ```\n *\n * @param authorizationList - An Authorization List.\n * @returns An RPC-formatted Authorization List.\n */\nexport function toRpcList(authorizationList: ListSigned): ListRpc {\n return authorizationList.map(toRpc)\n}\n\nexport declare namespace toRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.Authorization} to an {@link ox#Authorization.Tuple}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const tuple = Authorization.toTuple(authorization) // [!code focus]\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ]\n * ```\n *\n * @param authorization - The {@link ox#Authorization.Authorization}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple.\n */\nexport function toTuple<const authorization extends Authorization>(\n authorization: authorization,\n): toTuple.ReturnType<authorization> {\n const { address, chainId, nonce } = authorization\n const signature = Signature.extract(authorization)\n return [\n chainId ? Hex.fromNumber(chainId) : '0x',\n address,\n nonce ? Hex.fromNumber(nonce) : '0x',\n ...(signature ? Signature.toTuple(signature) : []),\n ] as never\n}\n\nexport declare namespace toTuple {\n type ReturnType<authorization extends Authorization = Authorization> =\n Compute<Tuple<authorization extends Signature.Signature ? true : false>>\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Authorization.List} to an {@link ox#Authorization.TupleList}.\n *\n * @example\n * ```ts twoslash\n * import { Authorization } from 'ox'\n *\n * const authorization_1 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * const authorization_2 = Authorization.from({\n * address: '0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 3,\n * nonce: 20n,\n * })\n *\n * const tuple = Authorization.toTupleList([authorization_1, authorization_2]) // [!code focus]\n * // @log: [\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ],\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: ],\n * // @log: ]\n * ```\n *\n * @param list - An {@link ox#Authorization.List}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Authorization tuple list.\n */\nexport function toTupleList<\n const list extends\n | readonly Authorization<true>[]\n | readonly Authorization<false>[],\n>(list?: list | undefined): toTupleList.ReturnType<list> {\n if (!list || list.length === 0) return []\n\n const tupleList: Mutable<TupleList> = []\n for (const authorization of list) tupleList.push(toTuple(authorization))\n\n return tupleList as never\n}\n\nexport declare namespace toTupleList {\n type ReturnType<\n list extends\n | readonly Authorization<true>[]\n | readonly Authorization<false>[],\n > = Compute<\n TupleList<list extends readonly Authorization<true>[] ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import { secp256k1 } from '@noble/curves/secp256k1'\nimport * as Address from './Address.js'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Entropy from './internal/entropy.js'\nimport type { OneOf } from './internal/types.js'\nimport * as PublicKey from './PublicKey.js'\nimport type * as Signature from './Signature.js'\n\n/** Re-export of noble/curves secp256k1 utilities. */\nexport const noble = secp256k1\n\n/**\n * Creates a new secp256k1 ECDSA key pair consisting of a private key and its corresponding public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey, publicKey } = Secp256k1.createKeyPair()\n * ```\n *\n * @param options - The options to generate the key pair.\n * @returns The generated key pair containing both private and public keys.\n */\nexport function createKeyPair<as extends 'Hex' | 'Bytes' = 'Hex'>(\n options: createKeyPair.Options<as> = {},\n): createKeyPair.ReturnType<as> {\n const { as = 'Hex' } = options\n const privateKey = randomPrivateKey({ as })\n const publicKey = getPublicKey({ privateKey })\n\n return {\n privateKey: privateKey as never,\n publicKey,\n }\n}\n\nexport declare namespace createKeyPair {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes'> = {\n privateKey:\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n publicKey: PublicKey.PublicKey\n }\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the secp256k1 ECDSA public key from a provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const publicKey = Secp256k1.getPublicKey({ privateKey: '0x...' })\n * ```\n *\n * @param options - The options to compute the public key.\n * @returns The computed public key.\n */\nexport function getPublicKey(\n options: getPublicKey.Options,\n): PublicKey.PublicKey {\n const { privateKey } = options\n const point = secp256k1.ProjectivePoint.fromPrivateKey(\n Hex.from(privateKey).slice(2),\n )\n return PublicKey.from(point)\n}\n\nexport declare namespace getPublicKey {\n type Options = {\n /**\n * Private key to compute the public key from.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes a shared secret using ECDH (Elliptic Curve Diffie-Hellman) between a private key and a public key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const { privateKey: privateKeyA } = Secp256k1.createKeyPair()\n * const { publicKey: publicKeyB } = Secp256k1.createKeyPair()\n *\n * const sharedSecret = Secp256k1.getSharedSecret({\n * privateKey: privateKeyA,\n * publicKey: publicKeyB\n * })\n * ```\n *\n * @param options - The options to compute the shared secret.\n * @returns The computed shared secret.\n */\nexport function getSharedSecret<as extends 'Hex' | 'Bytes' = 'Hex'>(\n options: getSharedSecret.Options<as>,\n): getSharedSecret.ReturnType<as> {\n const { as = 'Hex', privateKey, publicKey } = options\n const point = secp256k1.ProjectivePoint.fromHex(\n PublicKey.toHex(publicKey).slice(2),\n )\n const sharedPoint = point.multiply(\n secp256k1.utils.normPrivateKeyToScalar(Hex.from(privateKey).slice(2)),\n )\n const sharedSecret = sharedPoint.toRawBytes(true) // compressed format\n if (as === 'Hex') return Hex.fromBytes(sharedSecret) as never\n return sharedSecret as never\n}\n\nexport declare namespace getSharedSecret {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = {\n /**\n * Format of the returned shared secret.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n /**\n * Private key to use for the shared secret computation.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n /**\n * Public key to use for the shared secret computation.\n */\n publicKey: PublicKey.PublicKey<boolean>\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Hex.from.ErrorType\n | PublicKey.toHex.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random ECDSA private key on the secp256k1 curve.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * ```\n *\n * @param options - The options to generate the private key.\n * @returns The generated private key.\n */\nexport function randomPrivateKey<as extends 'Hex' | 'Bytes' = 'Hex'>(\n options: randomPrivateKey.Options<as> = {},\n): randomPrivateKey.ReturnType<as> {\n const { as = 'Hex' } = options\n const bytes = secp256k1.utils.randomPrivateKey()\n if (as === 'Hex') return Hex.fromBytes(bytes) as never\n return bytes as never\n}\n\nexport declare namespace randomPrivateKey {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing address from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const address = Secp256k1.recoverAddress({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered address.\n */\nexport function recoverAddress(\n options: recoverAddress.Options,\n): recoverAddress.ReturnType {\n return Address.fromPublicKey(recoverPublicKey(options))\n}\n\nexport declare namespace recoverAddress {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ReturnType = Address.Address\n\n type ErrorType =\n | Address.fromPublicKey.ErrorType\n | recoverPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing public key from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const publicKey = Secp256k1.recoverPublicKey({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered public key.\n */\nexport function recoverPublicKey(\n options: recoverPublicKey.Options,\n): PublicKey.PublicKey {\n const { payload, signature } = options\n const { r, s, yParity } = signature\n const signature_ = new secp256k1.Signature(\n BigInt(r),\n BigInt(s),\n ).addRecoveryBit(yParity)\n const point = signature_.recoverPublicKey(Hex.from(payload).substring(2))\n return PublicKey.from(point)\n}\n\nexport declare namespace recoverPublicKey {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ErrorType =\n | PublicKey.from.ErrorType\n | Hex.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Signs the payload with the provided private key.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * privateKey: '0x...' // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The signing options.\n * @returns The ECDSA {@link ox#Signature.Signature}.\n */\nexport function sign(options: sign.Options): Signature.Signature {\n const {\n extraEntropy = Entropy.extraEntropy,\n hash,\n payload,\n privateKey,\n } = options\n const { r, s, recovery } = secp256k1.sign(\n Bytes.from(payload),\n Bytes.from(privateKey),\n {\n extraEntropy:\n typeof extraEntropy === 'boolean'\n ? extraEntropy\n : Hex.from(extraEntropy).slice(2),\n lowS: true,\n ...(hash ? { prehash: true } : {}),\n },\n )\n return {\n r,\n s,\n yParity: recovery,\n }\n}\n\nexport declare namespace sign {\n type Options = {\n /**\n * Extra entropy to add to the signing process. Setting to `false` will disable it.\n * @default true\n */\n extraEntropy?: boolean | Hex.Hex | Bytes.Bytes | undefined\n /**\n * If set to `true`, the payload will be hashed (sha256) before being signed.\n */\n hash?: boolean | undefined\n /**\n * Payload to sign.\n */\n payload: Hex.Hex | Bytes.Bytes\n /**\n * ECDSA private key.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType = Bytes.from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Verifies a payload was signed by the provided address.\n *\n * @example\n * ### Verify with Ethereum Address\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * address: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266', // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### Verify with Public Key\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = '0x...'\n * const publicKey = Secp256k1.getPublicKey({ privateKey })\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const verified = Secp256k1.verify({ // [!code focus]\n * publicKey, // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The verification options.\n * @returns Whether the payload was signed by the provided address.\n */\nexport function verify(options: verify.Options): boolean {\n const { address, hash, payload, publicKey, signature } = options\n if (address)\n return Address.isEqual(address, recoverAddress({ payload, signature }))\n return secp256k1.verify(\n signature,\n Bytes.from(payload),\n PublicKey.toBytes(publicKey),\n ...(hash ? [{ prehash: true, lowS: true }] : []),\n )\n}\n\nexport declare namespace verify {\n type Options = {\n /** If set to `true`, the payload will be hashed (sha256) before being verified. */\n hash?: boolean | undefined\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n } & OneOf<\n | {\n /** Address that signed the payload. */\n address: Address.Address\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n | {\n /** Public key that signed the payload. */\n publicKey: PublicKey.PublicKey<boolean>\n /** Signature of the payload. */\n signature: Signature.Signature<false>\n }\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import {\n InvalidSerializedTransactionTypeError,\n type InvalidSerializedTransactionTypeErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Hex } from '../../index.js'\nimport type {\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedGeneric,\n TransactionSerializedLegacy,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { IsNarrowable, IsNever } from '../../types/utils.js'\nimport { type SliceHexErrorType, sliceHex } from '../data/slice.js'\nimport { type HexToNumberErrorType, hexToNumber } from '../encoding/fromHex.js'\n\nexport type GetSerializedTransactionType<\n serializedTransaction extends\n TransactionSerializedGeneric = TransactionSerialized,\n result =\n | (serializedTransaction extends TransactionSerializedEIP1559\n ? 'eip1559'\n : never)\n | (serializedTransaction extends TransactionSerializedEIP2930\n ? 'eip2930'\n : never)\n | (serializedTransaction extends TransactionSerializedEIP4844\n ? 'eip4844'\n : never)\n | (serializedTransaction extends TransactionSerializedEIP7702\n ? 'eip7702'\n : never)\n | (serializedTransaction extends TransactionSerializedLegacy\n ? 'legacy'\n : never),\n> = IsNarrowable<serializedTransaction, Hex> extends true\n ? IsNever<result> extends false\n ? result\n : 'legacy'\n : TransactionType\n\nexport type GetSerializedTransactionTypeErrorType =\n | HexToNumberErrorType\n | InvalidSerializedTransactionTypeErrorType\n | SliceHexErrorType\n | ErrorType\n\nexport function getSerializedTransactionType<\n const serializedTransaction extends TransactionSerializedGeneric,\n>(\n serializedTransaction: serializedTransaction,\n): GetSerializedTransactionType<serializedTransaction> {\n const serializedType = sliceHex(serializedTransaction, 0, 1)\n\n if (serializedType === '0x04')\n return 'eip7702' as GetSerializedTransactionType<serializedTransaction>\n\n if (serializedType === '0x03')\n return 'eip4844' as GetSerializedTransactionType<serializedTransaction>\n\n if (serializedType === '0x02')\n return 'eip1559' as GetSerializedTransactionType<serializedTransaction>\n\n if (serializedType === '0x01')\n return 'eip2930' as GetSerializedTransactionType<serializedTransaction>\n\n if (serializedType !== '0x' && hexToNumber(serializedType) >= 0xc0)\n return 'legacy' as GetSerializedTransactionType<serializedTransaction>\n\n throw new InvalidSerializedTransactionTypeError({ serializedType })\n}\n","import {\n InvalidAddressError,\n type InvalidAddressErrorType,\n} from '../../errors/address.js'\nimport {\n InvalidLegacyVError,\n type InvalidLegacyVErrorType,\n InvalidSerializedTransactionError,\n type InvalidSerializedTransactionErrorType,\n} from '../../errors/transaction.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type {\n SerializedAuthorizationList,\n SignedAuthorizationList,\n} from '../../types/authorization.js'\nimport type { Hex, Signature } from '../../types/misc.js'\nimport type {\n AccessList,\n TransactionRequestEIP2930,\n TransactionRequestLegacy,\n TransactionSerializable,\n TransactionSerializableEIP1559,\n TransactionSerializableEIP2930,\n TransactionSerializableEIP4844,\n TransactionSerializableEIP7702,\n TransactionSerializableLegacy,\n TransactionSerialized,\n TransactionSerializedEIP1559,\n TransactionSerializedEIP2930,\n TransactionSerializedEIP4844,\n TransactionSerializedEIP7702,\n TransactionSerializedGeneric,\n TransactionType,\n} from '../../types/transaction.js'\nimport type { IsNarrowable, Mutable } from '../../types/utils.js'\nimport { type IsAddressErrorType, isAddress } from '../address/isAddress.js'\nimport { toBlobSidecars } from '../blob/toBlobSidecars.js'\nimport { type IsHexErrorType, isHex } from '../data/isHex.js'\nimport { type PadHexErrorType, padHex } from '../data/pad.js'\nimport { trim } from '../data/trim.js'\nimport {\n type HexToBigIntErrorType,\n type HexToNumberErrorType,\n hexToBigInt,\n hexToNumber,\n} from '../encoding/fromHex.js'\nimport { type FromRlpErrorType, fromRlp } from '../encoding/fromRlp.js'\nimport type { RecursiveArray } from '../encoding/toRlp.js'\nimport { isHash } from '../hash/isHash.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 GetSerializedTransactionType,\n type GetSerializedTransactionTypeErrorType,\n getSerializedTransactionType,\n} from './getSerializedTransactionType.js'\n\nexport type ParseTransactionReturnType<\n serialized extends TransactionSerializedGeneric = TransactionSerialized,\n type extends TransactionType = GetSerializedTransactionType<serialized>,\n> = IsNarrowable<serialized, Hex> extends true\n ?\n | (type extends 'eip1559' ? TransactionSerializableEIP1559 : never)\n | (type extends 'eip2930' ? TransactionSerializableEIP2930 : never)\n | (type extends 'eip4844'\n ? TransactionSerializableEIP4844<bigint, number, false>\n : never)\n | (type extends 'eip7702' ? TransactionSerializableEIP7702 : never)\n | (type extends 'legacy' ? TransactionSerializableLegacy : never)\n : TransactionSerializable\n\nexport type ParseTransactionErrorType =\n | GetSerializedTransactionTypeErrorType\n | ParseTransactionEIP1559ErrorType\n | ParseTransactionEIP2930ErrorType\n | ParseTransactionEIP4844ErrorType\n | ParseTransactionEIP7702ErrorType\n | ParseTransactionLegacyErrorType\n\nexport function parseTransaction<\n const serialized extends TransactionSerializedGeneric,\n>(serializedTransaction: serialized): ParseTransactionReturnType<serialized> {\n const type = getSerializedTransactionType(serializedTransaction)\n\n if (type === 'eip1559')\n return parseTransactionEIP1559(\n serializedTransaction as TransactionSerializedEIP1559,\n ) as ParseTransactionReturnType<serialized>\n\n if (type === 'eip2930')\n return parseTransactionEIP2930(\n serializedTransaction as TransactionSerializedEIP2930,\n ) as ParseTransactionReturnType<serialized>\n\n if (type === 'eip4844')\n return parseTransactionEIP4844(\n serializedTransaction as TransactionSerializedEIP4844,\n ) as ParseTransactionReturnType<serialized>\n\n if (type === 'eip7702')\n return parseTransactionEIP7702(\n serializedTransaction as TransactionSerializedEIP7702,\n ) as ParseTransactionReturnType<serialized>\n\n return parseTransactionLegacy(\n serializedTransaction,\n ) as ParseTransactionReturnType<serialized>\n}\n\ntype ParseTransactionEIP7702ErrorType =\n | ToTransactionArrayErrorType\n | AssertTransactionEIP7702ErrorType\n | ToTransactionArrayErrorType\n | HexToBigIntErrorType\n | HexToNumberErrorType\n | InvalidLegacyVErrorType\n | InvalidSerializedTransactionErrorType\n | IsHexErrorType\n | ParseAuthorizationListErrorType\n | ParseEIP155SignatureErrorType\n | ErrorType\n\nfunction parseTransactionEIP7702(\n serializedTransaction: TransactionSerializedEIP7702,\n): TransactionSerializableEIP7702 {\n const transactionArray = toTransactionArray(serializedTransaction)\n\n const [\n chainId,\n nonce,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gas,\n to,\n value,\n data,\n accessList,\n authorizationList,\n v,\n r,\n s,\n ] = transactionArray\n\n if (transactionArray.length !== 10 && transactionArray.length !== 13)\n throw new InvalidSerializedTransactionError({\n attributes: {\n chainId,\n nonce,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gas,\n to,\n value,\n data,\n accessList,\n authorizationList,\n ...(transactionArray.length > 9\n ? {\n v,\n r,\n s,\n }\n : {}),\n },\n serializedTransaction,\n type: 'eip7702',\n })\n\n const transaction = {\n chainId: hexToNumber(chainId as Hex),\n type: 'eip7702',\n } as TransactionSerializableEIP7702\n if (isHex(to) && to !== '0x') transaction.to = to\n if (isHex(gas) && gas !== '0x') transaction.gas = hexToBigInt(gas)\n if (isHex(data) && data !== '0x') transaction.data = data\n if (isHex(nonce)) transaction.nonce = nonce === '0x' ? 0 : hexToNumber(nonce)\n if (isHex(value) && value !== '0x') transaction.value = hexToBigInt(value)\n if (isHex(maxFeePerGas) && maxFeePerGas !== '0x')\n transaction.maxFeePerGas = hexToBigInt(maxFeePerGas)\n if (isHex(maxPriorityFeePerGas) && maxPriorityFeePerGas !== '0x')\n transaction.maxPriorityFeePerGas = hexToBigInt(maxPriorityFeePerGas)\n if (accessList.length !== 0 && accessList !== '0x')\n transaction.accessList = parseAccessList(accessList as RecursiveArray<Hex>)\n if (authorizationList.length !== 0 && authorizationList !== '0x')\n transaction.authorizationList = parseAuthorizationList(\n authorizationList as SerializedAuthorizationList,\n )\n\n assertTransactionEIP7702(transaction)\n\n const signature =\n transactionArray.length === 13\n ? parseEIP155Signature(transactionArray as RecursiveArray<Hex>)\n : undefined\n\n return { ...signature, ...transaction }\n}\n\ntype ParseTransactionEIP4844ErrorType =\n | ToTransactionArrayErrorType\n | AssertTransactionEIP4844ErrorType\n | ToTransactionArrayErrorType\n | HexToBigIntErrorType\n | HexToNumberErrorType\n | InvalidLegacyVErrorType\n | InvalidSerializedTransactionErrorType\n | IsHexErrorType\n | ParseEIP155SignatureErrorType\n | ErrorType\n\nfunction parseTransactionEIP4844(\n serializedTransaction: TransactionSerializedEIP4844,\n): TransactionSerializableEIP4844 {\n const transactionOrWrapperArray = toTransactionArray(serializedTransaction)\n\n const hasNetworkWrapper = transactionOrWrapperArray.length === 4\n\n const transactionArray = hasNetworkWrapper\n ? transactionOrWrapperArray[0]\n : transactionOrWrapperArray\n const wrapperArray = hasNetworkWrapper\n ? transactionOrWrapperArray.slice(1)\n : []\n\n const [\n chainId,\n nonce,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gas,\n to,\n value,\n data,\n accessList,\n maxFeePerBlobGas,\n blobVersionedHashes,\n v,\n r,\n s,\n ] = transactionArray\n const [blobs, commitments, proofs] = wrapperArray\n\n if (!(transactionArray.length === 11 || transactionArray.length === 14))\n throw new InvalidSerializedTransactionError({\n attributes: {\n chainId,\n nonce,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gas,\n to,\n value,\n data,\n accessList,\n ...(transactionArray.length > 9\n ? {\n v,\n r,\n s,\n }\n : {}),\n },\n serializedTransaction,\n type: 'eip4844',\n })\n\n const transaction = {\n blobVersionedHashes: blobVersionedHashes as Hex[],\n chainId: hexToNumber(chainId as Hex),\n to,\n type: 'eip4844',\n } as TransactionSerializableEIP4844\n if (isHex(gas) && gas !== '0x') transaction.gas = hexToBigInt(gas)\n if (isHex(data) && data !== '0x') transaction.data = data\n if (isHex(nonce)) transaction.nonce = nonce === '0x' ? 0 : hexToNumber(nonce)\n if (isHex(value) && value !== '0x') transaction.value = hexToBigInt(value)\n if (isHex(maxFeePerBlobGas) && maxFeePerBlobGas !== '0x')\n transaction.maxFeePerBlobGas = hexToBigInt(maxFeePerBlobGas)\n if (isHex(maxFeePerGas) && maxFeePerGas !== '0x')\n transaction.maxFeePerGas = hexToBigInt(maxFeePerGas)\n if (isHex(maxPriorityFeePerGas) && maxPriorityFeePerGas !== '0x')\n transaction.maxPriorityFeePerGas = hexToBigInt(maxPriorityFeePerGas)\n if (accessList.length !== 0 && accessList !== '0x')\n transaction.accessList = parseAccessList(accessList as RecursiveArray<Hex>)\n if (blobs && commitments && proofs)\n transaction.sidecars = toBlobSidecars({\n blobs: blobs as Hex[],\n commitments: commitments as Hex[],\n proofs: proofs as Hex[],\n })\n\n assertTransactionEIP4844(transaction)\n\n const signature =\n transactionArray.length === 14\n ? parseEIP155Signature(transactionArray as RecursiveArray<Hex>)\n : undefined\n\n return { ...signature, ...transaction }\n}\n\ntype ParseTransactionEIP1559ErrorType =\n | ToTransactionArrayErrorType\n | AssertTransactionEIP1559ErrorType\n | ToTransactionArrayErrorType\n | HexToBigIntErrorType\n | HexToNumberErrorType\n | InvalidLegacyVErrorType\n | InvalidSerializedTransactionErrorType\n | IsHexErrorType\n | ParseEIP155SignatureErrorType\n | ParseAccessListErrorType\n | ErrorType\n\nfunction parseTransactionEIP1559(\n serializedTransaction: TransactionSerializedEIP1559,\n): TransactionSerializableEIP1559 {\n const transactionArray = toTransactionArray(serializedTransaction)\n\n const [\n chainId,\n nonce,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gas,\n to,\n value,\n data,\n accessList,\n v,\n r,\n s,\n ] = transactionArray\n\n if (!(transactionArray.length === 9 || transactionArray.length === 12))\n throw new InvalidSerializedTransactionError({\n attributes: {\n chainId,\n nonce,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gas,\n to,\n value,\n data,\n accessList,\n ...(transactionArray.length > 9\n ? {\n v,\n r,\n s,\n }\n : {}),\n },\n serializedTransaction,\n type: 'eip1559',\n })\n\n const transaction: TransactionSerializableEIP1559 = {\n chainId: hexToNumber(chainId as Hex),\n type: 'eip1559',\n }\n if (isHex(to) && to !== '0x') transaction.to = to\n if (isHex(gas) && gas !== '0x') transaction.gas = hexToBigInt(gas)\n if (isHex(data) && data !== '0x') transaction.data = data\n if (isHex(nonce)) transaction.nonce = nonce === '0x' ? 0 : hexToNumber(nonce)\n if (isHex(value) && value !== '0x') transaction.value = hexToBigInt(value)\n if (isHex(maxFeePerGas) && maxFeePerGas !== '0x')\n transaction.maxFeePerGas = hexToBigInt(maxFeePerGas)\n if (isHex(maxPriorityFeePerGas) && maxPriorityFeePerGas !== '0x')\n transaction.maxPriorityFeePerGas = hexToBigInt(maxPriorityFeePerGas)\n if (accessList.length !== 0 && accessList !== '0x')\n transaction.accessList = parseAccessList(accessList as RecursiveArray<Hex>)\n\n assertTransactionEIP1559(transaction)\n\n const signature =\n transactionArray.length === 12\n ? parseEIP155Signature(transactionArray)\n : undefined\n\n return { ...signature, ...transaction }\n}\n\ntype ParseTransactionEIP2930ErrorType =\n | ToTransactionArrayErrorType\n | AssertTransactionEIP2930ErrorType\n | ToTransactionArrayErrorType\n | HexToBigIntErrorType\n | HexToNumberErrorType\n | InvalidLegacyVErrorType\n | InvalidSerializedTransactionErrorType\n | IsHexErrorType\n | ParseEIP155SignatureErrorType\n | ParseAccessListErrorType\n | ErrorType\n\nfunction parseTransactionEIP2930(\n serializedTransaction: TransactionSerializedEIP2930,\n): Omit<TransactionRequestEIP2930, 'from'> &\n ({ chainId: number } | ({ chainId: number } & Signature)) {\n const transactionArray = toTransactionArray(serializedTransaction)\n\n const [chainId, nonce, gasPrice, gas, to, value, data, accessList, v, r, s] =\n transactionArray\n\n if (!(transactionArray.length === 8 || transactionArray.length === 11))\n throw new InvalidSerializedTransactionError({\n attributes: {\n chainId,\n nonce,\n gasPrice,\n gas,\n to,\n value,\n data,\n accessList,\n ...(transactionArray.length > 8\n ? {\n v,\n r,\n s,\n }\n : {}),\n },\n serializedTransaction,\n type: 'eip2930',\n })\n\n const transaction: TransactionSerializableEIP2930 = {\n chainId: hexToNumber(chainId as Hex),\n type: 'eip2930',\n }\n if (isHex(to) && to !== '0x') transaction.to = to\n if (isHex(gas) && gas !== '0x') transaction.gas = hexToBigInt(gas)\n if (isHex(data) && data !== '0x') transaction.data = data\n if (isHex(nonce)) transaction.nonce = nonce === '0x' ? 0 : hexToNumber(nonce)\n if (isHex(value) && value !== '0x') transaction.value = hexToBigInt(value)\n if (isHex(gasPrice) && gasPrice !== '0x')\n transaction.gasPrice = hexToBigInt(gasPrice)\n if (accessList.length !== 0 && accessList !== '0x')\n transaction.accessList = parseAccessList(accessList as RecursiveArray<Hex>)\n\n assertTransactionEIP2930(transaction)\n\n const signature =\n transactionArray.length === 11\n ? parseEIP155Signature(transactionArray)\n : undefined\n\n return { ...signature, ...transaction }\n}\n\ntype ParseTransactionLegacyErrorType =\n | AssertTransactionLegacyErrorType\n | FromRlpErrorType\n | HexToBigIntErrorType\n | HexToNumberErrorType\n | InvalidLegacyVErrorType\n | InvalidSerializedTransactionErrorType\n | IsHexErrorType\n | ErrorType\n\nfunction parseTransactionLegacy(\n serializedTransaction: Hex,\n): Omit<TransactionRequestLegacy, 'from'> &\n ({ chainId?: number | undefined } | ({ chainId: number } & Signature)) {\n const transactionArray = fromRlp(serializedTransaction, 'hex')\n\n const [nonce, gasPrice, gas, to, value, data, chainIdOrV_, r, s] =\n transactionArray\n\n if (!(transactionArray.length === 6 || transactionArray.length === 9))\n throw new InvalidSerializedTransactionError({\n attributes: {\n nonce,\n gasPrice,\n gas,\n to,\n value,\n data,\n ...(transactionArray.length > 6\n ? {\n v: chainIdOrV_,\n r,\n s,\n }\n : {}),\n },\n serializedTransaction,\n type: 'legacy',\n })\n\n const transaction: TransactionSerializableLegacy = {\n type: 'legacy',\n }\n if (isHex(to) && to !== '0x') transaction.to = to\n if (isHex(gas) && gas !== '0x') transaction.gas = hexToBigInt(gas)\n if (isHex(data) && data !== '0x') transaction.data = data\n if (isHex(nonce)) transaction.nonce = nonce === '0x' ? 0 : hexToNumber(nonce)\n if (isHex(value) && value !== '0x') transaction.value = hexToBigInt(value)\n if (isHex(gasPrice) && gasPrice !== '0x')\n transaction.gasPrice = hexToBigInt(gasPrice)\n\n assertTransactionLegacy(transaction)\n\n if (transactionArray.length === 6) return transaction\n\n const chainIdOrV =\n isHex(chainIdOrV_) && chainIdOrV_ !== '0x'\n ? hexToBigInt(chainIdOrV_ as Hex)\n : 0n\n\n if (s === '0x' && r === '0x') {\n if (chainIdOrV > 0) transaction.chainId = Number(chainIdOrV)\n return transaction\n }\n\n const v = chainIdOrV\n\n const chainId: number | undefined = Number((v - 35n) / 2n)\n if (chainId > 0) transaction.chainId = chainId\n else if (v !== 27n && v !== 28n) throw new InvalidLegacyVError({ v })\n\n transaction.v = v\n transaction.s = s as Hex\n transaction.r = r as Hex\n transaction.yParity = v % 2n === 0n ? 1 : 0\n\n return transaction\n}\n\ntype ToTransactionArrayErrorType = FromRlpErrorType | ErrorType\n\nexport function toTransactionArray(serializedTransaction: string) {\n return fromRlp(`0x${serializedTransaction.slice(4)}` as Hex, 'hex')\n}\n\ntype ParseAccessListErrorType =\n | InvalidAddressErrorType\n | IsAddressErrorType\n | ErrorType\n\nexport function parseAccessList(accessList_: RecursiveArray<Hex>): AccessList {\n const accessList: Mutable<AccessList> = []\n for (let i = 0; i < accessList_.length; i++) {\n const [address, storageKeys] = accessList_[i] as [Hex, Hex[]]\n\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address })\n\n accessList.push({\n address: address,\n storageKeys: storageKeys.map((key) => (isHash(key) ? key : trim(key))),\n })\n }\n return accessList\n}\n\ntype ParseAuthorizationListErrorType =\n | HexToNumberErrorType\n | ParseEIP155SignatureErrorType\n | ErrorType\n\nfunction parseAuthorizationList(\n serializedAuthorizationList: SerializedAuthorizationList,\n): SignedAuthorizationList {\n const authorizationList: Mutable<SignedAuthorizationList> = []\n for (let i = 0; i < serializedAuthorizationList.length; i++) {\n const [chainId, address, nonce, yParity, r, s] =\n serializedAuthorizationList[i]\n\n authorizationList.push({\n address,\n chainId: chainId === '0x' ? 0 : hexToNumber(chainId),\n nonce: nonce === '0x' ? 0 : hexToNumber(nonce),\n ...parseEIP155Signature([yParity, r, s]),\n })\n }\n return authorizationList\n}\n\ntype ParseEIP155SignatureErrorType =\n | HexToBigIntErrorType\n | PadHexErrorType\n | ErrorType\n\nfunction parseEIP155Signature(\n transactionArray: RecursiveArray<Hex>,\n): Signature & { yParity: number } {\n const signature = transactionArray.slice(-3)\n const v =\n signature[0] === '0x' || hexToBigInt(signature[0] as Hex) === 0n ? 27n : 28n\n return {\n r: padHex(signature[1] as Hex, { size: 32 }),\n s: padHex(signature[2] as Hex, { size: 32 }),\n v,\n yParity: v === 27n ? 0 : 1,\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 type { AbiStateMutability, Address, Narrow } from 'abitype'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { multicall3Abi } from '../../constants/abis.js'\nimport { multicall3Bytecode } from '../../constants/contracts.js'\nimport { AbiDecodingZeroDataError } from '../../errors/abi.js'\nimport { BaseError } from '../../errors/base.js'\nimport { RawContractError } from '../../errors/contract.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ContractFunctionParameters } from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport type {\n MulticallContracts,\n MulticallResults,\n} from '../../types/multicall.js'\nimport {\n type DecodeFunctionResultErrorType,\n decodeFunctionResult,\n} from '../../utils/abi/decodeFunctionResult.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetChainContractAddressErrorType,\n getChainContractAddress,\n} from '../../utils/chain/getChainContractAddress.js'\nimport {\n type GetContractErrorReturnType,\n getContractError,\n} from '../../utils/errors/getContractError.js'\nimport { getAction } from '../../utils/getAction.js'\nimport type { CallParameters } from './call.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type MulticallParameters<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n optional?: boolean\n properties?: Record<string, any>\n } = {},\n> = Pick<\n CallParameters,\n | 'authorizationList'\n | 'blockNumber'\n | 'blockOverrides'\n | 'blockTag'\n | 'stateOverride'\n> & {\n /** The account to use for the multicall. */\n account?: Address | undefined\n /** Whether to allow failures. */\n allowFailure?: allowFailure | boolean | undefined\n /** The size of each batch of calls. */\n batchSize?: number | undefined\n /** Enable deployless multicall. */\n deployless?: boolean | undefined\n /** The contracts to call. */\n contracts: MulticallContracts<\n Narrow<contracts>,\n { mutability: AbiStateMutability } & options\n >\n /** The address of the multicall3 contract to use. */\n multicallAddress?: Address | undefined\n}\n\nexport type MulticallReturnType<\n contracts extends readonly unknown[] = readonly ContractFunctionParameters[],\n allowFailure extends boolean = true,\n options extends {\n error?: Error\n } = { error: Error },\n> = MulticallResults<\n Narrow<contracts>,\n allowFailure,\n { mutability: AbiStateMutability } & options\n>\n\nexport type MulticallErrorType =\n | GetChainContractAddressErrorType\n | ReadContractErrorType\n | GetContractErrorReturnType<\n EncodeFunctionDataErrorType | DecodeFunctionResultErrorType\n >\n | ErrorType\n\n/**\n * Similar to [`readContract`](https://viem.sh/docs/contract/readContract), but batches up multiple functions on a contract in a single RPC call via the [`multicall3` contract](https://github.com/mds1/multicall).\n *\n * - Docs: https://viem.sh/docs/contract/multicall\n *\n * @param client - Client to use\n * @param parameters - {@link MulticallParameters}\n * @returns An array of results with accompanying status. {@link MulticallReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { multicall } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const abi = parseAbi([\n * 'function balanceOf(address) view returns (uint256)',\n * 'function totalSupply() view returns (uint256)',\n * ])\n * const results = await multicall(client, {\n * contracts: [\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * },\n * {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi,\n * functionName: 'totalSupply',\n * },\n * ],\n * })\n * // [{ result: 424122n, status: 'success' }, { result: 1000000n, status: 'success' }]\n */\nexport async function multicall<\n const contracts extends readonly unknown[],\n chain extends Chain | undefined,\n allowFailure extends boolean = true,\n>(\n client: Client<Transport, chain>,\n parameters: MulticallParameters<contracts, allowFailure>,\n): Promise<MulticallReturnType<contracts, allowFailure>> {\n const {\n account,\n authorizationList,\n allowFailure = true,\n blockNumber,\n blockOverrides,\n blockTag,\n stateOverride,\n } = parameters\n const contracts = parameters.contracts as ContractFunctionParameters[]\n\n const {\n batchSize = parameters.batchSize ?? 1024,\n deployless = parameters.deployless ?? false,\n } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {}\n\n const multicallAddress = (() => {\n if (parameters.multicallAddress) return parameters.multicallAddress\n if (deployless) return null\n if (client.chain) {\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n })\n }\n throw new Error(\n 'client chain not configured. multicallAddress is required.',\n )\n })()\n\n type Aggregate3Calls = {\n allowFailure: boolean\n callData: Hex\n target: Address\n }[]\n\n const chunkedCalls: Aggregate3Calls[] = [[]]\n let currentChunk = 0\n let currentChunkSize = 0\n for (let i = 0; i < contracts.length; i++) {\n const { abi, address, args, functionName } = contracts[i]\n try {\n const callData = encodeFunctionData({ abi, args, functionName })\n\n currentChunkSize += (callData.length - 2) / 2\n // Check to see if we need to create a new chunk.\n if (\n // Check if batching is enabled.\n batchSize > 0 &&\n // Check if the current size of the batch exceeds the size limit.\n currentChunkSize > batchSize &&\n // Check if the current chunk is not already empty.\n chunkedCalls[currentChunk].length > 0\n ) {\n currentChunk++\n currentChunkSize = (callData.length - 2) / 2\n chunkedCalls[currentChunk] = []\n }\n\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData,\n target: address,\n },\n ]\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n sender: account,\n })\n if (!allowFailure) throw error\n chunkedCalls[currentChunk] = [\n ...chunkedCalls[currentChunk],\n {\n allowFailure: true,\n callData: '0x' as Hex,\n target: address,\n },\n ]\n }\n }\n\n const aggregate3Results = await Promise.allSettled(\n chunkedCalls.map((calls) =>\n getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress === null\n ? { code: multicall3Bytecode }\n : { address: multicallAddress }),\n abi: multicall3Abi,\n account,\n args: [calls],\n authorizationList,\n blockNumber,\n blockOverrides,\n blockTag,\n functionName: 'aggregate3',\n stateOverride,\n }),\n ),\n )\n\n const results = []\n for (let i = 0; i < aggregate3Results.length; i++) {\n const result = aggregate3Results[i]\n\n // If an error occurred in a `readContract` invocation (ie. network error),\n // then append the failure reason to each contract result.\n if (result.status === 'rejected') {\n if (!allowFailure) throw result.reason\n for (let j = 0; j < chunkedCalls[i].length; j++) {\n results.push({\n status: 'failure',\n error: result.reason,\n result: undefined,\n })\n }\n continue\n }\n\n // If the `readContract` call was successful, then decode the results.\n const aggregate3Result = result.value\n for (let j = 0; j < aggregate3Result.length; j++) {\n // Extract the response from `readContract`\n const { returnData, success } = aggregate3Result[j]\n\n // Extract the request call data from the original call.\n const { callData } = chunkedCalls[i][j]\n\n // Extract the contract config for this call from the `contracts` argument\n // for decoding.\n const { abi, address, functionName, args } = contracts[\n results.length\n ] as ContractFunctionParameters\n\n try {\n if (callData === '0x') throw new AbiDecodingZeroDataError()\n if (!success) throw new RawContractError({ data: returnData })\n const result = decodeFunctionResult({\n abi,\n args,\n data: returnData,\n functionName,\n })\n results.push(allowFailure ? { result, status: 'success' } : result)\n } catch (err) {\n const error = getContractError(err as BaseError, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/multicall',\n functionName,\n })\n if (!allowFailure) throw error\n results.push({ error, result: undefined, status: 'failure' })\n }\n }\n }\n\n if (results.length !== contracts.length)\n throw new BaseError('multicall results mismatch')\n return results as MulticallReturnType<contracts, allowFailure>\n}\n","export const ethAddress = '0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee' as const\n\nexport const zeroAddress = '0x0000000000000000000000000000000000000000' as const\n","import type * as Abi from '../core/Abi.js'\nimport * as AbiParameters from '../core/AbiParameters.js'\nimport type * as Address from '../core/Address.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type * as Signature from '../core/Signature.js'\n\n/** Unwrapped ERC-6492 signature. */\nexport type Unwrapped = {\n /** Calldata to pass to the target address for counterfactual verification. */\n data: Hex.Hex\n /** The original signature. */\n signature: Hex.Hex\n /** The target address to use for counterfactual verification. */\n to: Address.Address\n}\n\n/** Wrapped ERC-6492 signature. */\nexport type Wrapped = Hex.Hex\n\n/**\n * Magic bytes used to identify ERC-6492 wrapped signatures.\n */\nexport const magicBytes =\n '0x6492649264926492649264926492649264926492649264926492649264926492' as const\n\n/**\n * Deployless ERC-6492 signature verification bytecode.\n */\nexport const universalSignatureValidatorBytecode =\n '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572'\n\n/**\n * ABI for the ERC-6492 universal deployless signature validator contract.\n *\n * Constructor return value is `0x1` (valid) or `0x0` (invalid).\n */\nexport const universalSignatureValidatorAbi = [\n {\n inputs: [\n {\n name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n {\n inputs: [\n {\n name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n name: 'isValidSig',\n },\n] as const satisfies Abi.Abi\n\n/**\n * Asserts that the wrapped signature is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * SignatureErc6492.assert('0xdeadbeef')\n * // @error: InvalidWrappedSignatureError: Value `0xdeadbeef` is an invalid ERC-6492 wrapped signature.\n * ```\n *\n * @param wrapped - The wrapped signature to assert.\n */\nexport function assert(wrapped: Wrapped) {\n if (Hex.slice(wrapped, -32) !== magicBytes)\n throw new InvalidWrappedSignatureError(wrapped)\n}\n\nexport declare namespace assert {\n type ErrorType =\n | InvalidWrappedSignatureError\n | Hex.slice.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * // Instantiate from serialized format. // [!code focus]\n * const wrapped = SignatureErc6492.from('0x...') // [!code focus]\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', } // [!code focus]\n *\n * // Instantiate from constituent parts. // [!code focus]\n * const wrapped = SignatureErc6492.from({ // [!code focus]\n * data: '0x...', // [!code focus]\n * signature, // [!code focus]\n * to: '0x...', // [!code focus]\n * })\n * // @log: { data: '0x...', signature: { ... }, to: '0x...', }\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function from(wrapped: Unwrapped | Wrapped): Unwrapped {\n if (typeof wrapped === 'string') return unwrap(wrapped)\n return wrapped\n}\n\nexport declare namespace from {\n type ReturnType = Unwrapped\n\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Parses an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification) into its constituent parts.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const { data, signature, to } = SignatureErc6492.unwrap('0x...')\n * ```\n *\n * @param wrapped - Wrapped signature to parse.\n * @returns Wrapped signature.\n */\nexport function unwrap(wrapped: Wrapped): Unwrapped {\n assert(wrapped)\n\n const [to, data, signature] = AbiParameters.decode(\n AbiParameters.from('address, bytes, bytes'),\n wrapped,\n )\n\n return { data, signature, to }\n}\n\nexport declare namespace unwrap {\n type ErrorType =\n | AbiParameters.from.ErrorType\n | AbiParameters.decode.ErrorType\n | Signature.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes an [ERC-6492 wrapped signature](https://eips.ethereum.org/EIPS/eip-6492#specification).\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1, Signature } from 'ox'\n * import { SignatureErc6492 } from 'ox/erc6492' // [!code focus]\n *\n * const signature = Secp256k1.sign({\n * payload: '0x...',\n * privateKey: '0x...',\n * })\n *\n * const wrapped = SignatureErc6492.wrap({ // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * signature: Signature.toHex(signature), // [!code focus]\n * to: '0x00000000219ab540356cBB839Cbe05303d7705Fa', // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param value - Wrapped signature to serialize.\n * @returns Serialized wrapped signature.\n */\nexport function wrap(value: Unwrapped): Wrapped {\n const { data, signature, to } = value\n\n return Hex.concat(\n AbiParameters.encode(AbiParameters.from('address, bytes, bytes'), [\n to,\n data,\n signature,\n ]),\n magicBytes,\n )\n}\n\nexport declare namespace wrap {\n type ErrorType =\n | AbiParameters.encode.ErrorType\n | Hex.concat.ErrorType\n | Signature.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a wrapped signature. Returns `true` if the wrapped signature is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureErc6492 } from 'ox/erc6492'\n *\n * const valid = SignatureErc6492.validate('0xdeadbeef')\n * // @log: false\n * ```\n *\n * @param wrapped - The wrapped signature to validate.\n * @returns `true` if the wrapped signature is valid, `false` otherwise.\n */\nexport function validate(wrapped: Wrapped): boolean {\n try {\n assert(wrapped)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/** Thrown when the ERC-6492 wrapped signature is invalid. */\nexport class InvalidWrappedSignatureError extends Errors.BaseError {\n override readonly name = 'SignatureErc6492.InvalidWrappedSignatureError'\n\n constructor(wrapped: Wrapped) {\n super(`Value \\`${wrapped}\\` is an invalid ERC-6492 wrapped signature.`)\n }\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 { Address } from 'abitype'\nimport { SignatureErc6492 } from 'ox/erc6492'\nimport { SignatureErc8010 } from 'ox/erc8010'\n\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport {\n erc1271Abi,\n erc6492SignatureValidatorAbi,\n multicall3Abi,\n} from '../../constants/abis.js'\nimport {\n erc6492SignatureValidatorByteCode,\n multicall3Bytecode,\n} from '../../constants/contracts.js'\nimport {\n CallExecutionError,\n ContractFunctionExecutionError,\n} from '../../errors/contract.js'\nimport type { InvalidHexBooleanError } from '../../errors/encoding.js'\nimport type { ErrorType } from '../../errors/utils.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ByteArray, Hex, Signature } from '../../types/misc.js'\nimport type { OneOf } from '../../types/utils.js'\nimport {\n type EncodeDeployDataErrorType,\n encodeDeployData,\n} from '../../utils/abi/encodeDeployData.js'\nimport {\n type EncodeFunctionDataErrorType,\n encodeFunctionData,\n} from '../../utils/abi/encodeFunctionData.js'\nimport {\n type GetAddressErrorType,\n getAddress,\n} from '../../utils/address/getAddress.js'\nimport {\n type IsAddressEqualErrorType,\n isAddressEqual,\n} from '../../utils/address/isAddressEqual.js'\nimport { verifyAuthorization } from '../../utils/authorization/verifyAuthorization.js'\nimport { type ConcatHexErrorType, concatHex } from '../../utils/data/concat.js'\nimport { type IsHexErrorType, isHex } from '../../utils/data/isHex.js'\nimport { hexToBool } from '../../utils/encoding/fromHex.js'\nimport {\n type BytesToHexErrorType,\n bytesToHex,\n type NumberToHexErrorType,\n numberToHex,\n} from '../../utils/encoding/toHex.js'\nimport { getAction } from '../../utils/getAction.js'\nimport {\n type RecoverAddressErrorType,\n recoverAddress,\n} from '../../utils/signature/recoverAddress.js'\nimport {\n type SerializeSignatureErrorType,\n serializeSignature,\n} from '../../utils/signature/serializeSignature.js'\nimport { type CallErrorType, type CallParameters, call } from './call.js'\nimport { type GetCodeErrorType, getCode } from './getCode.js'\nimport { type ReadContractErrorType, readContract } from './readContract.js'\n\nexport type VerifyHashParameters = Pick<\n CallParameters,\n 'blockNumber' | 'blockTag'\n> & {\n /** The address that signed the original message. */\n address: Address\n /** The chain to use. */\n chain?: Chain | null | undefined\n /** The address of the ERC-6492 signature verifier contract. */\n erc6492VerifierAddress?: Address | undefined\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex | ByteArray | Signature\n /** @deprecated use `erc6492VerifierAddress` instead. */\n universalSignatureVerifierAddress?: Address | undefined\n} & OneOf<{ factory: Address; factoryData: Hex } | {}>\n\nexport type VerifyHashReturnType = boolean\n\nexport type VerifyHashErrorType =\n | BytesToHexErrorType\n | CallErrorType\n | ConcatHexErrorType\n | EncodeDeployDataErrorType\n | EncodeFunctionDataErrorType\n | ErrorType\n | GetAddressErrorType\n | GetCodeErrorType\n | InvalidHexBooleanError\n | IsAddressEqualErrorType\n | IsHexErrorType\n | NumberToHexErrorType\n | ReadContractErrorType\n | RecoverAddressErrorType\n | SerializeSignatureErrorType\n\n/**\n * Verifies a message hash onchain using ERC-6492.\n *\n * @param client - Client to use.\n * @param parameters - {@link VerifyHashParameters}\n * @returns Whether or not the signature is valid. {@link VerifyHashReturnType}\n */\nexport async function verifyHash<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: VerifyHashParameters,\n): Promise<VerifyHashReturnType> {\n const {\n address,\n chain = client.chain,\n hash,\n erc6492VerifierAddress:\n verifierAddress = parameters.universalSignatureVerifierAddress ??\n chain?.contracts?.erc6492Verifier?.address,\n multicallAddress = parameters.multicallAddress ??\n chain?.contracts?.multicall3?.address,\n } = parameters\n\n if (chain?.verifyHash) return await chain.verifyHash(client, parameters)\n\n const signature = (() => {\n const signature = parameters.signature\n if (isHex(signature)) return signature\n if (typeof signature === 'object' && 'r' in signature && 's' in signature)\n return serializeSignature(signature)\n return bytesToHex(signature)\n })()\n\n try {\n if (SignatureErc8010.validate(signature))\n return await verifyErc8010(client, {\n ...parameters,\n multicallAddress,\n signature,\n })\n return await verifyErc6492(client, {\n ...parameters,\n verifierAddress,\n signature,\n })\n } catch (error) {\n // Fallback attempt to verify the signature via ECDSA recovery.\n try {\n const verified = isAddressEqual(\n getAddress(address),\n await recoverAddress({ hash, signature }),\n )\n if (verified) return true\n } catch {}\n\n if (error instanceof VerificationError) {\n // if the execution fails, the signature was not valid and an internal method inside of the validator reverted\n // this can happen for many reasons, for example if signer can not be recovered from the signature\n // or if the signature has no valid format\n return false\n }\n\n throw error\n }\n}\n\n/** @internal */\nexport async function verifyErc8010(\n client: Client,\n parameters: verifyErc8010.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, multicallAddress } = parameters\n\n const {\n authorization: authorization_ox,\n data: initData,\n signature,\n to,\n } = SignatureErc8010.unwrap(parameters.signature)\n\n // Check if already delegated\n const code = await getCode(client, {\n address,\n blockNumber,\n blockTag,\n } as never)\n\n // If already delegated, perform standard ERC-1271 verification.\n if (code === concatHex(['0xef0100', authorization_ox.address]))\n return await verifyErc1271(client, {\n address,\n blockNumber,\n blockTag,\n hash,\n signature,\n })\n\n const authorization = {\n address: authorization_ox.address,\n chainId: Number(authorization_ox.chainId),\n nonce: Number(authorization_ox.nonce),\n r: numberToHex(authorization_ox.r, { size: 32 }),\n s: numberToHex(authorization_ox.s, { size: 32 }),\n yParity: authorization_ox.yParity,\n } as const\n\n const valid = await verifyAuthorization({\n address,\n authorization,\n })\n if (!valid) throw new VerificationError()\n\n // Deployless verification.\n const results = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n ...(multicallAddress\n ? { address: multicallAddress }\n : { code: multicall3Bytecode }),\n authorizationList: [authorization],\n abi: multicall3Abi,\n blockNumber,\n blockTag: 'pending',\n functionName: 'aggregate3',\n args: [\n [\n ...(initData\n ? ([\n {\n allowFailure: true,\n target: to ?? address,\n callData: initData,\n },\n ] as const)\n : []),\n {\n allowFailure: true,\n target: address,\n callData: encodeFunctionData({\n abi: erc1271Abi,\n functionName: 'isValidSignature',\n args: [hash, signature],\n }),\n },\n ],\n ],\n })\n\n const data = results[results.length - 1]?.returnData\n\n if (data?.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc8010 {\n export type Parameters = Pick<CallParameters, 'blockNumber' | 'blockTag'> & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** Multicall3 address for ERC-8010 verification. */\n multicallAddress?: Address | undefined\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\n/** @internal */\n// biome-ignore lint/correctness/noUnusedVariables: _\nasync function verifyErc6492(\n client: Client,\n parameters: verifyErc6492.Parameters,\n) {\n const {\n address,\n factory,\n factoryData,\n hash,\n signature,\n verifierAddress,\n ...rest\n } = parameters\n\n const wrappedSignature = await (async () => {\n // If no `factory` or `factoryData` is provided, it is assumed that the\n // address is not a Smart Account, or the Smart Account is already deployed.\n if (!factory && !factoryData) return signature\n\n // If the signature is already wrapped, return the signature.\n if (SignatureErc6492.validate(signature)) return signature\n\n // If the Smart Account is not deployed, wrap the signature with a 6492 wrapper\n // to perform counterfactual validation.\n return SignatureErc6492.wrap({\n data: factoryData!,\n signature,\n to: factory!,\n })\n })()\n\n const args = verifierAddress\n ? ({\n to: verifierAddress,\n data: encodeFunctionData({\n abi: erc6492SignatureValidatorAbi,\n functionName: 'isValidSig',\n args: [address, hash, wrappedSignature],\n }),\n ...rest,\n } as unknown as CallParameters)\n : ({\n data: encodeDeployData({\n abi: erc6492SignatureValidatorAbi,\n args: [address, hash, wrappedSignature],\n bytecode: erc6492SignatureValidatorByteCode,\n }),\n ...rest,\n } as unknown as CallParameters)\n\n const { data } = await getAction(\n client,\n call,\n 'call',\n )(args).catch((error) => {\n if (error instanceof CallExecutionError) throw new VerificationError()\n throw error\n })\n\n if (hexToBool(data ?? '0x0')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc6492 {\n export type Parameters = Pick<CallParameters, 'blockNumber' | 'blockTag'> & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n /** The address of the ERC-6492 signature verifier contract. */\n verifierAddress?: Address | undefined\n } & OneOf<{ factory: Address; factoryData: Hex } | {}>\n}\n\n/** @internal */\nexport async function verifyErc1271(\n client: Client,\n parameters: verifyErc1271.Parameters,\n) {\n const { address, blockNumber, blockTag, hash, signature } = parameters\n\n const result = await getAction(\n client,\n readContract,\n 'readContract',\n )({\n address,\n abi: erc1271Abi,\n args: [hash, signature],\n blockNumber,\n blockTag,\n functionName: 'isValidSignature',\n }).catch((error) => {\n if (error instanceof ContractFunctionExecutionError)\n throw new VerificationError()\n throw error\n })\n\n if (result.startsWith('0x1626ba7e')) return true\n throw new VerificationError()\n}\n\nexport namespace verifyErc1271 {\n export type Parameters = Pick<CallParameters, 'blockNumber' | 'blockTag'> & {\n /** The address that signed the original message. */\n address: Address\n /** The hash to be verified. */\n hash: Hex\n /** The signature that was generated by signing the message with the address's private key. */\n signature: Hex\n }\n}\n\nclass VerificationError extends Error {}\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 { 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 { 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 type { FormattedTransactionReceipt } 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, 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 { 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 { 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 { 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 { 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 { 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","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 { parseUnits } from 'viem'\n\nimport * as Method from '../Method.js'\nimport * as z from '../zod.js'\n\n/**\n * Stripe charge intent for one-time payments via Shared Payment Tokens (SPTs).\n *\n * @see https://github.com/tempoxyz/payment-auth-spec/blob/main/specs/methods/stripe/draft-stripe-charge-00.md\n */\nexport const charge = Method.from({\n name: 'stripe',\n intent: 'charge',\n schema: {\n credential: {\n payload: z.object({\n externalId: z.optional(z.string()),\n spt: z.string(),\n }),\n },\n request: z.pipe(\n z.object({\n amount: z.amount(),\n currency: z.string(),\n decimals: z.number(),\n description: z.optional(z.string()),\n externalId: z.optional(z.string()),\n metadata: z.optional(z.record(z.string(), z.string())),\n networkId: z.string(),\n paymentMethodTypes: z.array(z.string()).check(z.minLength(1)),\n recipient: z.optional(z.string()),\n }),\n z.transform(({ amount, decimals, metadata, networkId, paymentMethodTypes, ...rest }) => ({\n ...rest,\n amount: parseUnits(amount, decimals).toString(),\n methodDetails: {\n networkId,\n paymentMethodTypes,\n ...(metadata !== undefined && { metadata }),\n },\n })),\n ),\n },\n})\n","import type * as Challenge from '../../Challenge.js'\nimport * as Credential from '../../Credential.js'\nimport * as Method from '../../Method.js'\nimport * as z from '../../zod.js'\nimport type { StripeJs } from '../internal/types.js'\nimport * as Methods from '../Methods.js'\n\n/**\n * Creates a Stripe charge method intent for usage on the client.\n *\n * Accepts a `createToken` callback that handles SPT creation (requires\n * a secret key, so typically proxied through a server endpoint) and\n * returns a credential for retrying the request.\n *\n * The `paymentMethod` (e.g. from Stripe Elements) can be provided at\n * initialization or at credential-creation time via `context`.\n *\n * Optionally accepts a `client` (a Stripe.js instance from `@stripe/stripe-js`)\n * which is forwarded to the `createToken` callback for use with Elements.\n *\n * @example\n * ```ts\n * import { loadStripe } from '@stripe/stripe-js'\n * import { stripe } from 'mppx/client'\n *\n * const stripeJs = await loadStripe('pk_...')\n *\n * const charge = stripe.charge({\n * client: stripeJs,\n * createToken: async ({ amount, currency, expiresAt, metadata, networkId, paymentMethod }) => {\n * const res = await fetch('/api/create-spt', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify({ paymentMethod, amount, currency, networkId, expiresAt, metadata }),\n * })\n * const { spt } = await res.json()\n * return spt\n * },\n * })\n * ```\n */\nexport function charge(parameters: charge.Parameters) {\n const { client, createToken, externalId, paymentMethod: defaultPaymentMethod } = parameters\n\n return Method.toClient(Methods.charge, {\n context: z.object({\n paymentMethod: z.optional(z.string()),\n }),\n\n async createCredential({ challenge, context }) {\n const paymentMethod = context?.paymentMethod ?? defaultPaymentMethod\n if (!paymentMethod) {\n throw new Error('paymentMethod is required (pass via context or parameters)')\n }\n\n const amount = challenge.request.amount as string\n const currency = challenge.request.currency as string\n const networkId = challenge.request.methodDetails?.networkId as string | undefined\n if (!networkId) throw new Error('networkId is required in challenge.methodDetails')\n const metadata = challenge.request.methodDetails?.metadata as\n | Record<string, string>\n | undefined\n if (metadata?.externalId) {\n throw new Error(\n 'methodDetails.metadata.externalId is reserved; use credential externalId instead',\n )\n }\n\n const expiresAt = challenge.expires\n ? Math.floor(new Date(challenge.expires).getTime() / 1000)\n : Math.floor(Date.now() / 1000) + 3600\n\n const spt = await createToken({\n amount,\n challenge,\n client,\n currency,\n expiresAt,\n metadata,\n networkId,\n paymentMethod,\n })\n\n return Credential.serialize({\n challenge,\n payload: {\n spt,\n ...(externalId ? { externalId } : {}),\n },\n })\n },\n })\n}\n\nexport declare namespace charge {\n type Parameters = {\n /** Stripe.js instance from `@stripe/stripe-js`. Forwarded to `createToken` for use with Elements. */\n client?: StripeJs | undefined\n /** Called when a Stripe challenge is received. Create an SPT to retry. */\n createToken: (parameters: OnChallengeParameters) => Promise<string>\n /** Optional client-side external reference ID for the credential payload. */\n externalId?: string | undefined\n /** Default payment method ID. Overridden by `context.paymentMethod`. */\n paymentMethod?: string | undefined\n }\n\n type OnChallengeParameters = {\n /** Payment amount (in smallest currency unit). */\n amount: string\n challenge: Challenge.Challenge<\n z.output<typeof Methods.charge.schema.request>,\n typeof Methods.charge.intent,\n typeof Methods.charge.name\n >\n /** Stripe.js instance, if provided to `stripe.charge()`. */\n client?: StripeJs | undefined\n /** Three-letter ISO currency code. */\n currency: string\n /** SPT expiration as a Unix timestamp (seconds). */\n expiresAt: number\n /** Optional metadata to associate with the SPT. */\n metadata?: Record<string, string> | undefined\n /** Stripe Business Network profile ID. */\n networkId: string | undefined\n /** Stripe payment method ID (e.g. from Stripe Elements). */\n paymentMethod?: string | undefined\n }\n}\n","import { charge as charge_ } from './Charge.js'\n\n/**\n * Creates a Stripe `charge` client method.\n *\n * @example\n * ```ts\n * import { Mppx, stripe } from 'mppx/client'\n *\n * const mppx = Mppx.create({\n * methods: [\n * stripe({\n * createToken: async (params) => {\n * const res = await fetch('/api/create-spt', {\n * method: 'POST',\n * headers: { 'Content-Type': 'application/json' },\n * body: JSON.stringify(params),\n * })\n * const { spt } = await res.json()\n * return spt\n * },\n * paymentMethod: 'pm_card_visa',\n * }),\n * ],\n * })\n * ```\n */\nexport function stripe(parameters: stripe.Parameters) {\n return [charge_(parameters)] as const\n}\n\nexport namespace stripe {\n export type Parameters = charge_.Parameters\n\n /** Creates a Stripe `charge` client method for SPT-based payments. */\n export const charge = charge_\n}\n","import * as Address from '../core/Address.js'\nimport type * as Bytes from '../core/Bytes.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type {\n Assign,\n Compute,\n IsNarrowable,\n OneOf,\n PartialBy,\n UnionPartialBy,\n} from '../core/internal/types.js'\nimport * as Json from '../core/Json.js'\nimport * as ox_P256 from '../core/P256.js'\nimport type * as PublicKey from '../core/PublicKey.js'\nimport * as ox_Secp256k1 from '../core/Secp256k1.js'\nimport * as Signature from '../core/Signature.js'\nimport type * as WebAuthnP256 from '../core/WebAuthnP256.js'\nimport * as ox_WebAuthnP256 from '../core/WebAuthnP256.js'\n\n/** Signature type identifiers for encoding/decoding */\nconst serializedP256Type = '0x01'\nconst serializedWebAuthnType = '0x02'\nconst serializedKeychainType = '0x03'\nconst serializedKeychainV2Type = '0x04'\n\n/** Serialized magic identifier for Tempo signature envelopes. */\nexport const magicBytes =\n '0x7777777777777777777777777777777777777777777777777777777777777777' // 32 \"T\"s\n\n/**\n * Statically determines the signature type of an envelope at compile time.\n *\n * @example\n * ```ts twoslash\n * import type { SignatureEnvelope } from 'ox/tempo'\n *\n * type Type = SignatureEnvelope.GetType<{ r: bigint; s: bigint; yParity: number }>\n * // @log: 'secp256k1'\n * ```\n */\nexport type GetType<\n envelope extends PartialBy<SignatureEnvelope, 'type'> | unknown,\n> = unknown extends envelope\n ? envelope extends unknown\n ? Type\n : never\n : envelope extends { type: infer T extends Type }\n ? T\n : envelope extends {\n signature: { r: bigint; s: bigint }\n prehash: boolean\n publicKey: PublicKey.PublicKey\n }\n ? 'p256'\n : envelope extends {\n signature: { r: bigint; s: bigint }\n metadata: any\n publicKey: PublicKey.PublicKey\n }\n ? 'webAuthn'\n : envelope extends { r: bigint; s: bigint; yParity: number }\n ? 'secp256k1'\n : envelope extends {\n signature: { r: bigint; s: bigint; yParity: number }\n }\n ? 'secp256k1'\n : envelope extends {\n userAddress: Address.Address\n }\n ? 'keychain'\n : never\n\n/**\n * Represents a signature envelope that can contain different signature types.\n *\n * Tempo transactions support multiple signature types, each with different wire formats:\n *\n * - **secp256k1** (no type prefix, 65 bytes): Standard Ethereum ECDSA signature. The sender\n * address is recovered via `ecrecover`. Base transaction cost: 21,000 gas.\n *\n * - **p256** (type `0x01`, 130 bytes): P256/secp256r1 curve signature for passkey accounts.\n * Includes embedded public key (64 bytes) and prehash flag. Enables native WebCrypto\n * key support. Additional gas cost: +5,000 gas over secp256k1.\n *\n * - **webAuthn** (type `0x02`, 129-2049 bytes): WebAuthn signature with authenticator data\n * and clientDataJSON. Enables browser passkey authentication. The signature is also\n * charged as calldata (16 gas/non-zero byte, 4 gas/zero byte).\n *\n * - **keychain** (type `0x03` V1, `0x04` V2): Access key signature that wraps an inner signature\n * (secp256k1, p256, or webAuthn). Format: type byte + user_address (20 bytes) + inner signature.\n * V2 binds the signature to the user account via `keccak256(sigHash || userAddress)`.\n * The protocol validates the access key authorization via the AccountKeychain precompile.\n *\n * [Signature Types Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#signature-types)\n */\nexport type SignatureEnvelope<bigintType = bigint, numberType = number> = OneOf<\n | Secp256k1<bigintType, numberType>\n | P256<bigintType, numberType>\n | WebAuthn<bigintType, numberType>\n | Keychain<bigintType, numberType>\n>\n\n/**\n * RPC-formatted signature envelope.\n */\nexport type SignatureEnvelopeRpc = OneOf<\n Secp256k1Rpc | P256Rpc | WebAuthnRpc | KeychainRpc\n>\n\n/**\n * Keychain signature version.\n *\n * - `'v1'`: Legacy format. Inner signature signs the raw `sig_hash` directly. Deprecated at T1C.\n * - `'v2'`: Inner signature signs `keccak256(sig_hash || user_address)`, binding the signature\n * to the specific user account.\n */\nexport type KeychainVersion = 'v1' | 'v2'\n\nexport type Keychain<bigintType = bigint, numberType = number> = {\n /** Root account address that this transaction is being executed for */\n userAddress: Address.Address\n /** The actual signature from the access key (can be Secp256k1, P256, or WebAuthn) */\n inner: SignatureEnvelope<bigintType, numberType>\n /** The access key address (recovered address of the access key signer). */\n keyId?: Address.Address | undefined\n type: 'keychain'\n /** Keychain signature version. @default 'v1' */\n version?: KeychainVersion | undefined\n}\n\nexport type KeychainRpc = {\n type: 'keychain'\n userAddress: Address.Address\n keyId?: Address.Address | undefined\n signature: SignatureEnvelopeRpc\n version?: KeychainVersion | undefined\n}\n\nexport type P256<bigintType = bigint, numberType = number> = {\n prehash: boolean\n publicKey: PublicKey.PublicKey\n signature: Signature.Signature<false, bigintType, numberType>\n type: 'p256'\n}\n\nexport type P256Rpc = {\n preHash: boolean\n pubKeyX: Hex.Hex\n pubKeyY: Hex.Hex\n r: Hex.Hex\n s: Hex.Hex\n type: 'p256'\n}\n\nexport type Secp256k1<bigintType = bigint, numberType = number> = {\n signature: Signature.Signature<true, bigintType, numberType>\n type: 'secp256k1'\n}\n\nexport type Secp256k1Rpc = Compute<\n Signature.Rpc<true> & {\n v?: Hex.Hex | undefined\n type: 'secp256k1'\n }\n>\n\nexport type Secp256k1Flat<\n bigintType = bigint,\n numberType = number,\n> = Signature.Signature<true, bigintType, numberType> & {\n type?: 'secp256k1' | undefined\n}\n\nexport type WebAuthn<bigintType = bigint, numberType = number> = {\n metadata: Pick<\n WebAuthnP256.SignMetadata,\n 'authenticatorData' | 'clientDataJSON'\n >\n signature: Signature.Signature<false, bigintType, numberType>\n publicKey: PublicKey.PublicKey\n type: 'webAuthn'\n}\n\nexport type WebAuthnRpc = {\n pubKeyX: Hex.Hex\n pubKeyY: Hex.Hex\n r: Hex.Hex\n s: Hex.Hex\n type: 'webAuthn'\n webauthnData: Hex.Hex\n}\n\n/** Hex-encoded serialized signature envelope. */\nexport type Serialized = Hex.Hex\n\n/** List of supported signature types. */\nexport const types = ['secp256k1', 'p256', 'webAuthn'] as const\n\n/** Union type of supported signature types. */\nexport type Type = (typeof types)[number]\n\n/**\n * Asserts that a {@link ox#SignatureEnvelope.SignatureEnvelope} is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * SignatureEnvelope.assert({\n * type: 'secp256k1',\n * signature: {\n * r: 0n,\n * s: 0n,\n * yParity: 0,\n * },\n * })\n * ```\n *\n * @param envelope - The signature envelope to assert.\n * @throws `CoercionError` if the envelope type cannot be determined.\n */\nexport function assert(envelope: PartialBy<SignatureEnvelope, 'type'>): void {\n const type = getType(envelope)\n\n if (type === 'secp256k1') {\n const secp256k1 = envelope as Secp256k1\n Signature.assert(secp256k1.signature)\n return\n }\n\n if (type === 'p256') {\n const p256 = envelope as P256\n const missing: string[] = []\n\n if (typeof p256.signature?.r !== 'bigint') missing.push('signature.r')\n if (typeof p256.signature?.s !== 'bigint') missing.push('signature.s')\n if (typeof p256.prehash !== 'boolean') missing.push('prehash')\n if (!p256.publicKey) missing.push('publicKey')\n else {\n if (typeof p256.publicKey.x !== 'bigint') missing.push('publicKey.x')\n if (typeof p256.publicKey.y !== 'bigint') missing.push('publicKey.y')\n }\n\n if (missing.length > 0)\n throw new MissingPropertiesError({ envelope, missing, type: 'p256' })\n return\n }\n\n if (type === 'webAuthn') {\n const webauthn = envelope as WebAuthn\n const missing: string[] = []\n\n if (typeof webauthn.signature?.r !== 'bigint') missing.push('signature.r')\n if (typeof webauthn.signature?.s !== 'bigint') missing.push('signature.s')\n if (!webauthn.metadata) missing.push('metadata')\n else {\n if (!webauthn.metadata.authenticatorData)\n missing.push('metadata.authenticatorData')\n if (!webauthn.metadata.clientDataJSON)\n missing.push('metadata.clientDataJSON')\n }\n if (!webauthn.publicKey) missing.push('publicKey')\n else {\n if (typeof webauthn.publicKey.x !== 'bigint') missing.push('publicKey.x')\n if (typeof webauthn.publicKey.y !== 'bigint') missing.push('publicKey.y')\n }\n\n if (missing.length > 0)\n throw new MissingPropertiesError({ envelope, missing, type: 'webAuthn' })\n return\n }\n\n if (type === 'keychain') {\n const keychain = envelope as Keychain\n assert(keychain.inner)\n return\n }\n}\n\nexport declare namespace assert {\n type ErrorType =\n | CoercionError\n | MissingPropertiesError\n | Signature.assert.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts the address of the signer from a {@link ox#SignatureEnvelope.SignatureEnvelope}.\n *\n * - **secp256k1**: Recovers the address from the payload via `ecrecover`.\n * - **p256** / **webAuthn**: Derives the address from the embedded public key.\n * - **keychain**: Extracts from the inner signature (or returns `userAddress` if `user` is `true`).\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const payload = '0xdeadbeef'\n * const signature = Secp256k1.sign({ payload, privateKey: '0x...' })\n * const envelope = SignatureEnvelope.from(signature)\n *\n * const address = SignatureEnvelope.extractAddress({ // [!code focus]\n * payload, // [!code focus]\n * signature: envelope, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The extraction options.\n * @returns The signer address.\n */\nexport function extractAddress(\n options: extractAddress.Options,\n): extractAddress.ReturnType {\n const { signature, root } = options\n if (signature.type === 'keychain') {\n if (root) return signature.userAddress\n return extractAddress({ ...options, signature: signature.inner })\n }\n return Address.fromPublicKey(extractPublicKey(options))\n}\n\nexport declare namespace extractAddress {\n type Options = {\n /** The sign payload that was signed (only required for secp256k1 signatures). */\n payload: Hex.Hex | Bytes.Bytes\n /** The signature envelope. */\n signature: SignatureEnvelope\n /** Whether to return the root `userAddress` for keychain signatures instead of extracting from the inner signature. */\n root?: boolean | undefined\n }\n\n type ReturnType = Address.Address\n\n type ErrorType =\n | Address.fromPublicKey.ErrorType\n | extractPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts the public key of the signer from a {@link ox#SignatureEnvelope.SignatureEnvelope}.\n *\n * - **secp256k1**: Recovers the public key from the payload via `ecrecover`.\n * - **p256** / **webAuthn**: Returns the embedded public key.\n * - **keychain**: Extracts from the inner signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const payload = '0xdeadbeef'\n * const signature = Secp256k1.sign({ payload, privateKey: '0x...' })\n * const envelope = SignatureEnvelope.from(signature)\n *\n * const publicKey = SignatureEnvelope.extractPublicKey({ // [!code focus]\n * payload, // [!code focus]\n * signature: envelope, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The extraction options.\n * @returns The signer's public key.\n */\nexport function extractPublicKey(\n options: extractPublicKey.Options,\n): extractPublicKey.ReturnType {\n const { payload, signature } = options\n\n switch (signature.type) {\n case 'secp256k1':\n return ox_Secp256k1.recoverPublicKey({\n payload,\n signature: signature.signature,\n })\n case 'p256':\n case 'webAuthn':\n return signature.publicKey\n case 'keychain':\n return extractPublicKey({ payload, signature: signature.inner })\n }\n}\n\nexport declare namespace extractPublicKey {\n type Options = {\n /** The sign payload that was signed (only required for secp256k1 signatures). */\n payload: Hex.Hex | Bytes.Bytes\n /** The signature envelope. */\n signature: SignatureEnvelope\n }\n\n type ReturnType = PublicKey.PublicKey\n\n type ErrorType =\n | ox_Secp256k1.recoverPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a hex-encoded signature envelope into a typed signature object.\n *\n * Wire format detection:\n * - 65 bytes (no prefix): secp256k1 signature\n * - Type `0x01` + 129 bytes: P256 signature (r, s, pubKeyX, pubKeyY, prehash)\n * - Type `0x02` + variable: WebAuthn signature (webauthnData, r, s, pubKeyX, pubKeyY)\n * - Type `0x03` + 20 bytes + inner: Keychain V1 signature (userAddress + inner signature)\n * - Type `0x04` + 20 bytes + inner: Keychain V2 signature (userAddress + inner signature)\n *\n * [Signature Types](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#signature-types)\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const envelope = SignatureEnvelope.deserialize('0x...')\n * ```\n *\n * @param serialized - The hex-encoded signature envelope to deserialize.\n * @returns The deserialized signature envelope.\n * @throws `CoercionError` if the serialized value cannot be coerced to a valid signature envelope.\n */\nexport function deserialize(value: Serialized): SignatureEnvelope {\n const serialized = value.endsWith(magicBytes.slice(2))\n ? Hex.slice(value, 0, -Hex.size(magicBytes))\n : value\n\n const size = Hex.size(serialized)\n\n // Backward compatibility: 65 bytes means secp256k1 without type identifier\n if (size === 65) {\n const signature = Signature.fromHex(serialized)\n Signature.assert(signature)\n return { signature, type: 'secp256k1' } satisfies Secp256k1\n }\n\n // For all other lengths, first byte is the type identifier\n const typeId = Hex.slice(serialized, 0, 1)\n const data = Hex.slice(serialized, 1)\n const dataSize = Hex.size(data)\n\n if (typeId === serializedP256Type) {\n // P256: 32 (r) + 32 (s) + 32 (pubKeyX) + 32 (pubKeyY) + 1 (prehash) = 129 bytes\n if (dataSize !== 129)\n throw new InvalidSerializedError({\n reason: `Invalid P256 signature envelope size: expected 129 bytes, got ${dataSize} bytes`,\n serialized,\n })\n\n return {\n publicKey: {\n prefix: 4,\n x: Hex.toBigInt(Hex.slice(data, 64, 96)),\n y: Hex.toBigInt(Hex.slice(data, 96, 128)),\n },\n prehash: Hex.toNumber(Hex.slice(data, 128, 129)) !== 0,\n signature: {\n r: Hex.toBigInt(Hex.slice(data, 0, 32)),\n s: Hex.toBigInt(Hex.slice(data, 32, 64)),\n },\n type: 'p256',\n } satisfies P256\n }\n\n if (typeId === serializedWebAuthnType) {\n // WebAuthn: variable (webauthnData) + 32 (r) + 32 (s) + 32 (pubKeyX) + 32 (pubKeyY)\n // Minimum: 128 bytes (at least some authenticator data + signature components)\n if (dataSize < 128)\n throw new InvalidSerializedError({\n reason: `Invalid WebAuthn signature envelope size: expected at least 128 bytes, got ${dataSize} bytes`,\n serialized,\n })\n\n const webauthnDataSize = dataSize - 128\n const webauthnData = Hex.slice(data, 0, webauthnDataSize)\n\n // Parse webauthnData into authenticatorData and clientDataJSON\n // According to the Rust code, it's authenticatorData || clientDataJSON\n // We need to find the split point (minimum authenticatorData is 37 bytes)\n let authenticatorData: Hex.Hex | undefined\n let clientDataJSON: string | undefined\n\n // Try to find the JSON start (clientDataJSON should start with '{')\n for (let split = 37; split < webauthnDataSize; split++) {\n const potentialJson = Hex.toString(Hex.slice(webauthnData, split))\n if (potentialJson.startsWith('{') && potentialJson.endsWith('}')) {\n try {\n JSON.parse(potentialJson)\n authenticatorData = Hex.slice(webauthnData, 0, split)\n clientDataJSON = potentialJson\n break\n } catch {}\n }\n }\n\n if (!authenticatorData || !clientDataJSON)\n throw new InvalidSerializedError({\n reason:\n 'Unable to parse WebAuthn metadata: could not extract valid authenticatorData and clientDataJSON',\n serialized,\n })\n\n return {\n publicKey: {\n prefix: 4,\n x: Hex.toBigInt(\n Hex.slice(data, webauthnDataSize + 64, webauthnDataSize + 96),\n ),\n y: Hex.toBigInt(\n Hex.slice(data, webauthnDataSize + 96, webauthnDataSize + 128),\n ),\n },\n metadata: {\n authenticatorData,\n clientDataJSON,\n },\n signature: {\n r: Hex.toBigInt(\n Hex.slice(data, webauthnDataSize, webauthnDataSize + 32),\n ),\n s: Hex.toBigInt(\n Hex.slice(data, webauthnDataSize + 32, webauthnDataSize + 64),\n ),\n },\n type: 'webAuthn',\n } satisfies WebAuthn\n }\n\n if (\n typeId === serializedKeychainType ||\n typeId === serializedKeychainV2Type\n ) {\n const userAddress = Hex.slice(data, 0, 20)\n const inner = deserialize(Hex.slice(data, 20))\n\n return {\n userAddress,\n inner,\n type: 'keychain',\n version: typeId === serializedKeychainV2Type ? 'v2' : 'v1',\n } satisfies Keychain\n }\n\n throw new InvalidSerializedError({\n reason: `Unknown signature type identifier: ${typeId}. Expected ${serializedP256Type} (P256), ${serializedWebAuthnType} (WebAuthn), ${serializedKeychainType} (Keychain V1), or ${serializedKeychainV2Type} (Keychain V2)`,\n serialized,\n })\n}\n\n/**\n * Coerces a value to a signature envelope.\n *\n * Accepts either a serialized hex string or an existing signature envelope object.\n * Use this to wrap raw signatures from {@link ox#Secp256k1.(sign:function)}, {@link ox#P256.(sign:function)},\n * {@link ox#WebCryptoP256.(sign:function)}, or {@link ox#WebAuthnP256.(sign:function)} into the envelope format\n * required by Tempo transactions.\n *\n * [Signature Types](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#signature-types)\n *\n * @example\n * ### Secp256k1\n *\n * Standard Ethereum ECDSA signature using the secp256k1 curve.\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const envelope = SignatureEnvelope.from(signature)\n * ```\n *\n * @example\n * ### P256\n *\n * ECDSA signature using the P-256 (secp256r1) curve. Requires embedding the\n * public key.\n *\n * ```ts twoslash\n * import { P256 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const { privateKey, publicKey } = P256.createKeyPair()\n * const signature = P256.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const envelope = SignatureEnvelope.from({\n * signature,\n * publicKey,\n * })\n * ```\n *\n * @example\n * ### P256 (WebCrypto)\n *\n * When using WebCrypto keys, `prehash` must be `true` since WebCrypto always\n * SHA256 hashes the digest before signing.\n *\n * ```ts twoslash\n * // @noErrors\n * import { WebCryptoP256 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const { privateKey, publicKey } = await WebCryptoP256.createKeyPair()\n * const signature = await WebCryptoP256.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const envelope = SignatureEnvelope.from({\n * signature,\n * publicKey,\n * prehash: true,\n * })\n * ```\n *\n * @example\n * ### WebAuthn\n *\n * Passkey-based signature using WebAuthn. Includes authenticator metadata\n * (authenticatorData and clientDataJSON) along with the P-256 signature and\n * public key.\n *\n * ```ts twoslash\n * // @noErrors\n * import { WebAuthnP256 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const credential = await WebAuthnP256.createCredential({\n * name: 'Example',\n * })\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * challenge: '0xdeadbeef',\n * credentialId: credential.id,\n * })\n *\n * const envelope = SignatureEnvelope.from({\n * signature,\n * publicKey: credential.publicKey,\n * metadata,\n * })\n * ```\n *\n * @example\n * ### Keychain\n *\n * Wraps another signature type with a user address, used for delegated signing\n * via access keys on behalf of a root account.\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const envelope = SignatureEnvelope.from({\n * userAddress: '0x1234567890123456789012345678901234567890',\n * inner: SignatureEnvelope.from(signature),\n * })\n * ```\n *\n * @param value - The value to coerce (either a hex string or signature envelope).\n * @returns The signature envelope.\n */\nexport function from<const value extends from.Value>(\n value: value | from.Value,\n options?: from.Options | undefined,\n): from.ReturnValue<value> {\n if (typeof value === 'string') return deserialize(value) as never\n\n if (\n typeof value === 'object' &&\n value !== null &&\n 'r' in value &&\n 's' in value &&\n 'yParity' in value\n )\n return { signature: value, type: 'secp256k1' } as never\n\n const type = getType(value)\n return {\n ...value,\n ...(type === 'p256' ? { prehash: value.prehash } : {}),\n ...(type === 'keychain'\n ? {\n ...(!(\n typeof value === 'object' &&\n value !== null &&\n 'version' in value &&\n value.version\n )\n ? { version: 'v2' }\n : {}),\n ...(!(typeof value === 'object' && 'keyId' in value && value.keyId)\n ? (() => {\n const inner = (value as Keychain).inner\n if (inner.type === 'p256' || inner.type === 'webAuthn')\n return { keyId: Address.fromPublicKey(inner.publicKey) }\n if (inner.type === 'secp256k1' && options?.payload)\n return {\n keyId: Address.fromPublicKey(\n ox_Secp256k1.recoverPublicKey({\n payload: options.payload,\n signature: inner.signature,\n }),\n ),\n }\n return {}\n })()\n : {}),\n }\n : {}),\n type,\n } as never\n}\n\nexport declare namespace from {\n type Options = {\n /** Payload that was signed. Used to recover `keyId` for keychain envelopes with secp256k1 inner signatures. */\n payload?: Hex.Hex | Bytes.Bytes | undefined\n }\n\n type Value =\n | UnionPartialBy<SignatureEnvelope, 'prehash' | 'type'>\n | Secp256k1Flat\n | Serialized\n\n type ReturnValue<value extends Value> = Compute<\n OneOf<\n value extends Serialized\n ? SignatureEnvelope\n : value extends Secp256k1Flat\n ? Secp256k1\n : IsNarrowable<value, SignatureEnvelope> extends true\n ? SignatureEnvelope\n : Assign<\n value,\n {\n readonly type: GetType<value>\n } & (GetType<value> extends 'keychain'\n ? { keyId?: Address.Address | undefined }\n : {})\n >\n >\n >\n}\n\n/**\n * Converts an RPC-formatted signature envelope to a typed signature envelope.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const envelope = SignatureEnvelope.fromRpc({\n * r: '0x0',\n * s: '0x0',\n * yParity: '0x0',\n * type: 'secp256k1',\n * })\n * ```\n *\n * @param envelope - The RPC signature envelope to convert.\n * @returns The signature envelope with bigint values.\n */\nexport function fromRpc(envelope: SignatureEnvelopeRpc): SignatureEnvelope {\n if (envelope.type === 'secp256k1')\n return {\n signature: Signature.fromRpc(envelope),\n type: 'secp256k1',\n }\n\n if (envelope.type === 'p256') {\n return {\n prehash: envelope.preHash,\n publicKey: {\n prefix: 4,\n x: Hex.toBigInt(envelope.pubKeyX),\n y: Hex.toBigInt(envelope.pubKeyY),\n },\n signature: {\n r: Hex.toBigInt(envelope.r),\n s: Hex.toBigInt(envelope.s),\n },\n type: 'p256',\n }\n }\n\n if (envelope.type === 'webAuthn') {\n const webauthnData = envelope.webauthnData\n const webauthnDataSize = Hex.size(webauthnData)\n\n // Parse webauthnData into authenticatorData and clientDataJSON\n let authenticatorData: Hex.Hex | undefined\n let clientDataJSON: string | undefined\n\n // Try to find the JSON start (clientDataJSON should start with '{')\n for (let split = 37; split < webauthnDataSize; split++) {\n const potentialJson = Hex.toString(Hex.slice(webauthnData, split))\n if (potentialJson.startsWith('{') && potentialJson.endsWith('}')) {\n try {\n JSON.parse(potentialJson)\n authenticatorData = Hex.slice(webauthnData, 0, split)\n clientDataJSON = potentialJson\n break\n } catch {}\n }\n }\n\n if (!authenticatorData || !clientDataJSON)\n throw new InvalidSerializedError({\n reason:\n 'Unable to parse WebAuthn metadata: could not extract valid authenticatorData and clientDataJSON',\n serialized: webauthnData,\n })\n\n return {\n metadata: {\n authenticatorData,\n clientDataJSON,\n },\n publicKey: {\n prefix: 4,\n x: Hex.toBigInt(envelope.pubKeyX),\n y: Hex.toBigInt(envelope.pubKeyY),\n },\n signature: {\n r: Hex.toBigInt(envelope.r),\n s: Hex.toBigInt(envelope.s),\n },\n type: 'webAuthn',\n }\n }\n\n if (\n envelope.type === 'keychain' ||\n ('userAddress' in envelope && 'signature' in envelope)\n )\n return {\n type: 'keychain',\n userAddress: envelope.userAddress,\n inner: fromRpc(envelope.signature),\n ...(envelope.keyId ? { keyId: envelope.keyId } : {}),\n ...(envelope.version ? { version: envelope.version } : {}),\n }\n\n throw new CoercionError({ envelope })\n}\n\nexport declare namespace fromRpc {\n type ErrorType =\n | CoercionError\n | InvalidSerializedError\n | Signature.fromRpc.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Determines the signature type of an envelope.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const type = SignatureEnvelope.getType({\n * signature: { r: 0n, s: 0n, yParity: 0 },\n * })\n * // @log: 'secp256k1'\n * ```\n *\n * @param envelope - The signature envelope to inspect.\n * @returns The signature type ('secp256k1', 'p256', or 'webAuthn').\n * @throws `CoercionError` if the envelope type cannot be determined.\n */\nexport function getType<\n envelope extends\n | PartialBy<SignatureEnvelope, 'type'>\n | Secp256k1Flat\n | unknown,\n>(envelope: envelope): GetType<envelope> {\n if (typeof envelope !== 'object' || envelope === null)\n throw new CoercionError({ envelope })\n\n if ('type' in envelope && envelope.type) return envelope.type as never\n\n // Detect secp256k1 signature (backwards compatibility: also support flat structure)\n if (\n 'signature' in envelope &&\n !('publicKey' in envelope) &&\n typeof envelope.signature === 'object' &&\n envelope.signature !== null &&\n 'r' in envelope.signature &&\n 's' in envelope.signature &&\n 'yParity' in envelope.signature\n )\n return 'secp256k1' as never\n\n // Detect secp256k1 signature (flat structure)\n if ('r' in envelope && 's' in envelope && 'yParity' in envelope)\n return 'secp256k1' as never\n\n // Detect P256 signature\n if (\n 'signature' in envelope &&\n 'prehash' in envelope &&\n 'publicKey' in envelope &&\n typeof envelope.prehash === 'boolean'\n )\n return 'p256' as never\n\n // Detect WebAuthn signature\n if (\n 'signature' in envelope &&\n 'metadata' in envelope &&\n 'publicKey' in envelope\n )\n return 'webAuthn' as never\n\n // Detect Keychain signature\n if ('userAddress' in envelope && 'inner' in envelope)\n return 'keychain' as never\n\n throw new CoercionError({\n envelope,\n })\n}\n\n/**\n * Serializes a signature envelope to a hex-encoded string.\n *\n * Wire format:\n * - secp256k1: 65 bytes (no type prefix, for backward compatibility)\n * - P256: `0x01` + r (32) + s (32) + pubKeyX (32) + pubKeyY (32) + prehash (1) = 130 bytes\n * - WebAuthn: `0x02` + webauthnData (variable) + r (32) + s (32) + pubKeyX (32) + pubKeyY (32)\n * - Keychain V1: `0x03` + userAddress (20) + inner signature (recursive)\n * - Keychain V2: `0x04` + userAddress (20) + inner signature (recursive)\n *\n * [Signature Types](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#signature-types)\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const serialized = SignatureEnvelope.serialize({\n * signature: { r: 0n, s: 0n, yParity: 0 },\n * type: 'secp256k1',\n * })\n * ```\n *\n * @param envelope - The signature envelope to serialize.\n * @returns The hex-encoded serialized signature.\n * @throws `CoercionError` if the envelope cannot be serialized.\n */\nexport function serialize(\n envelope: UnionPartialBy<SignatureEnvelope, 'prehash'>,\n options: serialize.Options = {},\n): Serialized {\n const type = getType(envelope)\n\n // Backward compatibility: no type identifier for secp256k1\n if (type === 'secp256k1') {\n const secp256k1 = envelope as Secp256k1\n return Hex.concat(\n Signature.toHex(secp256k1.signature),\n options.magic ? magicBytes : '0x',\n )\n }\n\n if (type === 'p256') {\n const p256 = envelope as P256\n // Format: 1 byte (type) + 32 (r) + 32 (s) + 32 (pubKeyX) + 32 (pubKeyY) + 1 (prehash)\n return Hex.concat(\n serializedP256Type,\n Hex.fromNumber(p256.signature.r, { size: 32 }),\n Hex.fromNumber(p256.signature.s, { size: 32 }),\n Hex.fromNumber(p256.publicKey.x, { size: 32 }),\n Hex.fromNumber(p256.publicKey.y, { size: 32 }),\n Hex.fromNumber(p256.prehash ? 1 : 0, { size: 1 }),\n options.magic ? magicBytes : '0x',\n )\n }\n\n if (type === 'webAuthn') {\n const webauthn = envelope as WebAuthn\n // Format: 1 byte (type) + variable (authenticatorData || clientDataJSON) + 32 (r) + 32 (s) + 32 (pubKeyX) + 32 (pubKeyY)\n const webauthnData = Hex.concat(\n webauthn.metadata.authenticatorData,\n Hex.fromString(webauthn.metadata.clientDataJSON),\n )\n\n return Hex.concat(\n serializedWebAuthnType,\n webauthnData,\n Hex.fromNumber(webauthn.signature.r, { size: 32 }),\n Hex.fromNumber(webauthn.signature.s, { size: 32 }),\n Hex.fromNumber(webauthn.publicKey.x, { size: 32 }),\n Hex.fromNumber(webauthn.publicKey.y, { size: 32 }),\n options.magic ? magicBytes : '0x',\n )\n }\n\n if (type === 'keychain') {\n const keychain = envelope as Keychain\n const keychainTypeId =\n keychain.version === 'v1'\n ? serializedKeychainType\n : serializedKeychainV2Type\n return Hex.concat(\n keychainTypeId,\n keychain.userAddress,\n serialize(keychain.inner),\n options.magic ? magicBytes : '0x',\n )\n }\n\n throw new CoercionError({ envelope })\n}\n\nexport declare namespace serialize {\n type Options = {\n /**\n * Whether to serialize the signature envelope with the Tempo magic identifier.\n * This is useful for being able to distinguish between Tempo and non-Tempo (e.g. ERC-1271) signatures.\n */\n magic?: boolean | undefined\n }\n}\n\n/**\n * Converts a signature envelope to RPC format.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const rpc = SignatureEnvelope.toRpc({\n * signature: { r: 0n, s: 0n, yParity: 0 },\n * type: 'secp256k1',\n * })\n * ```\n *\n * @param envelope - The signature envelope to convert.\n * @returns The RPC signature envelope with hex values.\n */\nexport function toRpc(envelope: SignatureEnvelope): SignatureEnvelopeRpc {\n const type = getType(envelope)\n\n if (type === 'secp256k1') {\n const secp256k1 = envelope as Secp256k1\n return {\n ...Signature.toRpc(secp256k1.signature),\n type: 'secp256k1',\n }\n }\n\n if (type === 'p256') {\n const p256 = envelope as P256\n return {\n preHash: p256.prehash,\n pubKeyX: Hex.fromNumber(p256.publicKey.x, { size: 32 }),\n pubKeyY: Hex.fromNumber(p256.publicKey.y, { size: 32 }),\n r: Hex.fromNumber(p256.signature.r, { size: 32 }),\n s: Hex.fromNumber(p256.signature.s, { size: 32 }),\n type: 'p256',\n }\n }\n\n if (type === 'webAuthn') {\n const webauthn = envelope as WebAuthn\n const webauthnData = Hex.concat(\n webauthn.metadata.authenticatorData,\n Hex.fromString(webauthn.metadata.clientDataJSON),\n )\n\n return {\n pubKeyX: Hex.fromNumber(webauthn.publicKey.x, { size: 32 }),\n pubKeyY: Hex.fromNumber(webauthn.publicKey.y, { size: 32 }),\n r: Hex.fromNumber(webauthn.signature.r, { size: 32 }),\n s: Hex.fromNumber(webauthn.signature.s, { size: 32 }),\n type: 'webAuthn',\n webauthnData,\n }\n }\n\n if (type === 'keychain') {\n const keychain = envelope as Keychain\n return {\n type: 'keychain',\n userAddress: keychain.userAddress,\n signature: toRpc(keychain.inner),\n ...(keychain.keyId ? { keyId: keychain.keyId } : {}),\n ...(keychain.version ? { version: keychain.version } : {}),\n }\n }\n\n throw new CoercionError({ envelope })\n}\n\nexport declare namespace toRpc {\n type ErrorType =\n | CoercionError\n | Signature.toRpc.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a signature envelope. Returns `true` if the envelope is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const valid = SignatureEnvelope.validate({\n * signature: { r: 0n, s: 0n, yParity: 0 },\n * type: 'secp256k1',\n * })\n * // @log: true\n * ```\n *\n * @param envelope - The signature envelope to validate.\n * @returns `true` if valid, `false` otherwise.\n */\nexport function validate(\n envelope: PartialBy<SignatureEnvelope, 'type'>,\n): boolean {\n try {\n assert(envelope)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Verifies a signature envelope against a digest/payload.\n *\n * Supports `secp256k1`, `p256`, and `webAuthn` signature types.\n *\n * :::warning\n * `keychain` signatures are not supported and will throw an error.\n * :::\n *\n * @example\n * ### Secp256k1\n *\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * const publicKey = Secp256k1.getPublicKey({ privateKey })\n * const payload = '0xdeadbeef'\n *\n * const signature = Secp256k1.sign({ payload, privateKey })\n * const envelope = SignatureEnvelope.from(signature)\n *\n * const valid = SignatureEnvelope.verify(envelope, {\n * payload,\n * publicKey,\n * })\n * // @log: true\n * ```\n *\n * @example\n * ### P256\n *\n * For P256 signatures, the `address` or `publicKey` must match the embedded\n * public key in the signature envelope.\n *\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n * import { P256 } from 'ox'\n *\n * const privateKey = P256.randomPrivateKey()\n * const publicKey = P256.getPublicKey({ privateKey })\n * const payload = '0xdeadbeef'\n *\n * const signature = P256.sign({ payload, privateKey })\n * const envelope = SignatureEnvelope.from({ prehash: false, publicKey, signature })\n *\n * const valid = SignatureEnvelope.verify(envelope, {\n * payload,\n * publicKey,\n * })\n * // @log: true\n * ```\n *\n * @example\n * ### WebCryptoP256\n *\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n * import { WebCryptoP256 } from 'ox'\n *\n * const { privateKey, publicKey } = await WebCryptoP256.createKeyPair()\n * const payload = '0xdeadbeef'\n *\n * const signature = await WebCryptoP256.sign({ payload, privateKey })\n * const envelope = SignatureEnvelope.from({ prehash: true, publicKey, signature })\n *\n * const valid = SignatureEnvelope.verify(envelope, {\n * payload,\n * publicKey,\n * })\n * // @log: true\n * ```\n *\n * @example\n * ### WebAuthnP256\n *\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n * import { WebAuthnP256 } from 'ox'\n *\n * const credential = await WebAuthnP256.createCredential({ name: 'Example' })\n * const payload = '0xdeadbeef'\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * challenge: payload,\n * credentialId: credential.id,\n * })\n * const envelope = SignatureEnvelope.from({\n * metadata,\n * signature,\n * publicKey: credential.publicKey,\n * })\n *\n * const valid = SignatureEnvelope.verify(envelope, {\n * payload,\n * publicKey: credential.publicKey,\n * })\n * // @log: true\n * ```\n *\n * @param parameters - Verification parameters.\n * @returns `true` if the signature is valid, `false` otherwise.\n */\nexport function verify(\n signature: SignatureEnvelope,\n parameters: verify.Parameters,\n): boolean {\n const { payload } = parameters\n\n const address = (() => {\n if (parameters.address) return parameters.address\n if (parameters.publicKey) return Address.fromPublicKey(parameters.publicKey)\n return undefined\n })()\n if (!address) return false\n\n const envelope = from(signature)\n\n if (envelope.type === 'secp256k1') {\n if (!address) return false\n return ox_Secp256k1.verify({\n address,\n payload,\n signature: envelope.signature,\n })\n }\n\n if (envelope.type === 'p256') {\n const envelopeAddress = Address.fromPublicKey(envelope.publicKey)\n if (!Address.isEqual(envelopeAddress, address)) return false\n return ox_P256.verify({\n hash: envelope.prehash,\n publicKey: envelope.publicKey,\n payload,\n signature: envelope.signature,\n })\n }\n\n if (envelope.type === 'webAuthn') {\n const envelopeAddress = Address.fromPublicKey(envelope.publicKey)\n if (!Address.isEqual(envelopeAddress, address)) return false\n return ox_WebAuthnP256.verify({\n challenge: Hex.from(payload),\n metadata: envelope.metadata,\n publicKey: envelope.publicKey,\n signature: envelope.signature,\n })\n }\n\n throw new VerificationError(\n `Unable to verify signature envelope of type \"${envelope.type}\".`,\n )\n}\n\nexport declare namespace verify {\n type Parameters = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n } & OneOf<\n | {\n /** Public key that signed the payload. */\n publicKey: PublicKey.PublicKey\n }\n | {\n /** Address that signed the payload. */\n address: Address.Address\n }\n >\n}\n\n/**\n * Error thrown when a signature envelope cannot be coerced to a valid type.\n */\nexport class CoercionError extends Errors.BaseError {\n override readonly name = 'SignatureEnvelope.CoercionError'\n constructor({ envelope }: { envelope: unknown }) {\n super(\n `Unable to coerce value (\\`${Json.stringify(envelope)}\\`) to a valid signature envelope.`,\n )\n }\n}\n\n/**\n * Error thrown when a signature envelope is missing required properties.\n */\nexport class MissingPropertiesError extends Errors.BaseError {\n override readonly name = 'SignatureEnvelope.MissingPropertiesError'\n constructor({\n envelope,\n missing,\n type,\n }: {\n envelope: unknown\n missing: string[]\n type: Type\n }) {\n super(\n `Signature envelope of type \"${type}\" is missing required properties: ${missing.map((m) => `\\`${m}\\``).join(', ')}.\\n\\nProvided: ${Json.stringify(envelope)}`,\n )\n }\n}\n\n/**\n * Error thrown when a serialized signature envelope cannot be deserialized.\n */\nexport class InvalidSerializedError extends Errors.BaseError {\n override readonly name = 'SignatureEnvelope.InvalidSerializedError'\n constructor({\n reason,\n serialized,\n }: {\n reason: string\n serialized: Hex.Hex\n }) {\n super(`Unable to deserialize signature envelope: ${reason}`, {\n metaMessages: [`Serialized: ${serialized}`],\n })\n }\n}\n\n/**\n * Error thrown when a signature envelope fails to verify.\n */\nexport class VerificationError extends Errors.BaseError {\n override readonly name = 'SignatureEnvelope.VerificationError'\n}\n","import { secp256r1 } from '@noble/curves/p256'\nimport * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport * as Entropy from './internal/entropy.js'\nimport * as PublicKey from './PublicKey.js'\nimport type * as Signature from './Signature.js'\n\n/** Re-export of noble/curves P256 utilities. */\nexport const noble = secp256r1\n\n/**\n * Creates a new P256 ECDSA key pair consisting of a private key and its corresponding public key.\n *\n * @example\n * ```ts twoslash\n * import { P256 } from 'ox'\n *\n * const { privateKey, publicKey } = P256.createKeyPair()\n * ```\n *\n * @param options - The options to generate the key pair.\n * @returns The generated key pair containing both private and public keys.\n */\nexport function createKeyPair<as extends 'Hex' | 'Bytes' = 'Hex'>(\n options: createKeyPair.Options<as> = {},\n): createKeyPair.ReturnType<as> {\n const { as = 'Hex' } = options\n const privateKey = randomPrivateKey({ as })\n const publicKey = getPublicKey({ privateKey })\n\n return {\n privateKey: privateKey as never,\n publicKey,\n }\n}\n\nexport declare namespace createKeyPair {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes'> = {\n privateKey:\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n publicKey: PublicKey.PublicKey\n }\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | PublicKey.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the P256 ECDSA public key from a provided private key.\n *\n * @example\n * ```ts twoslash\n * import { P256 } from 'ox'\n *\n * const publicKey = P256.getPublicKey({ privateKey: '0x...' })\n * ```\n *\n * @param options - The options to compute the public key.\n * @returns The computed public key.\n */\nexport function getPublicKey(\n options: getPublicKey.Options,\n): PublicKey.PublicKey {\n const { privateKey } = options\n const point = secp256r1.ProjectivePoint.fromPrivateKey(\n typeof privateKey === 'string'\n ? privateKey.slice(2)\n : Hex.fromBytes(privateKey).slice(2),\n )\n return PublicKey.from(point)\n}\n\nexport declare namespace getPublicKey {\n type Options = {\n /**\n * Private key to compute the public key from.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes a shared secret using ECDH (Elliptic Curve Diffie-Hellman) between a private key and a public key.\n *\n * @example\n * ```ts twoslash\n * import { P256 } from 'ox'\n *\n * const { privateKey: privateKeyA } = P256.createKeyPair()\n * const { publicKey: publicKeyB } = P256.createKeyPair()\n *\n * const sharedSecret = P256.getSharedSecret({\n * privateKey: privateKeyA,\n * publicKey: publicKeyB\n * })\n * ```\n *\n * @param options - The options to compute the shared secret.\n * @returns The computed shared secret.\n */\nexport function getSharedSecret<as extends 'Hex' | 'Bytes' = 'Hex'>(\n options: getSharedSecret.Options<as>,\n): getSharedSecret.ReturnType<as> {\n const { as = 'Hex', privateKey, publicKey } = options\n const point = secp256r1.ProjectivePoint.fromHex(\n PublicKey.toHex(publicKey).slice(2),\n )\n const privateKeyHex =\n typeof privateKey === 'string'\n ? privateKey.slice(2)\n : Hex.fromBytes(privateKey).slice(2)\n const sharedPoint = point.multiply(\n secp256r1.utils.normPrivateKeyToScalar(privateKeyHex),\n )\n const sharedSecret = sharedPoint.toRawBytes(true) // compressed format\n if (as === 'Hex') return Hex.fromBytes(sharedSecret) as never\n return sharedSecret as never\n}\n\nexport declare namespace getSharedSecret {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = {\n /**\n * Format of the returned shared secret.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n /**\n * Private key to use for the shared secret computation.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n /**\n * Public key to use for the shared secret computation.\n */\n publicKey: PublicKey.PublicKey<boolean>\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | PublicKey.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Generates a random P256 ECDSA private key.\n *\n * @example\n * ```ts twoslash\n * import { P256 } from 'ox'\n *\n * const privateKey = P256.randomPrivateKey()\n * ```\n *\n * @param options - The options to generate the private key.\n * @returns The generated private key.\n */\nexport function randomPrivateKey<as extends 'Hex' | 'Bytes' = 'Hex'>(\n options: randomPrivateKey.Options<as> = {},\n): randomPrivateKey.ReturnType<as> {\n const { as = 'Hex' } = options\n const bytes = secp256r1.utils.randomPrivateKey()\n if (as === 'Hex') return Hex.fromBytes(bytes) as never\n return bytes as never\n}\n\nexport declare namespace randomPrivateKey {\n type Options<as extends 'Hex' | 'Bytes' = 'Hex'> = {\n /**\n * Format of the returned private key.\n * @default 'Hex'\n */\n as?: as | 'Hex' | 'Bytes' | undefined\n }\n\n type ReturnType<as extends 'Hex' | 'Bytes'> =\n | (as extends 'Bytes' ? Bytes.Bytes : never)\n | (as extends 'Hex' ? Hex.Hex : never)\n\n type ErrorType = Hex.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Recovers the signing public key from the signed payload and signature.\n *\n * @example\n * ```ts twoslash\n * import { P256 } from 'ox'\n *\n * const signature = P256.sign({ payload: '0xdeadbeef', privateKey: '0x...' })\n *\n * const publicKey = P256.recoverPublicKey({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The recovery options.\n * @returns The recovered public key.\n */\nexport function recoverPublicKey(\n options: recoverPublicKey.Options,\n): PublicKey.PublicKey {\n const { payload, signature } = options\n const { r, s, yParity } = signature\n const signature_ = new secp256r1.Signature(\n BigInt(r),\n BigInt(s),\n ).addRecoveryBit(yParity)\n const payload_ =\n payload instanceof Uint8Array ? Hex.fromBytes(payload) : payload\n const point = signature_.recoverPublicKey(payload_.substring(2))\n return PublicKey.from(point)\n}\n\nexport declare namespace recoverPublicKey {\n type Options = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Signature of the payload. */\n signature: Signature.Signature\n }\n\n type ErrorType =\n | PublicKey.from.ErrorType\n | Hex.fromBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Signs the payload with the provided private key and returns a P256 signature.\n *\n * @example\n * ```ts twoslash\n * import { P256 } from 'ox'\n *\n * const signature = P256.sign({ // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * privateKey: '0x...' // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The signing options.\n * @returns The ECDSA {@link ox#Signature.Signature}.\n */\nexport function sign(options: sign.Options): Signature.Signature {\n const {\n extraEntropy = Entropy.extraEntropy,\n hash,\n payload,\n privateKey,\n } = options\n const { r, s, recovery } = secp256r1.sign(\n payload instanceof Uint8Array ? payload : Bytes.fromHex(payload),\n privateKey instanceof Uint8Array ? privateKey : Bytes.fromHex(privateKey),\n {\n extraEntropy:\n typeof extraEntropy === 'boolean'\n ? extraEntropy\n : Hex.from(extraEntropy).slice(2),\n lowS: true,\n ...(hash ? { prehash: true } : {}),\n },\n )\n return {\n r,\n s,\n yParity: recovery,\n }\n}\n\nexport declare namespace sign {\n type Options = {\n /**\n * Extra entropy to add to the signing process. Setting to `false` will disable it.\n * @default true\n */\n extraEntropy?: boolean | Hex.Hex | Bytes.Bytes | undefined\n /**\n * If set to `true`, the payload will be hashed (sha256) before being signed.\n */\n hash?: boolean | undefined\n /**\n * Payload to sign.\n */\n payload: Hex.Hex | Bytes.Bytes\n /**\n * ECDSA private key.\n */\n privateKey: Hex.Hex | Bytes.Bytes\n }\n\n type ErrorType = Bytes.fromHex.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Verifies a payload was signed by the provided public key.\n *\n * @example\n *\n * ```ts twoslash\n * import { P256 } from 'ox'\n *\n * const { privateKey, publicKey } = P256.createKeyPair()\n * const signature = P256.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const verified = P256.verify({ // [!code focus]\n * publicKey, // [!code focus]\n * payload: '0xdeadbeef', // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The verification options.\n * @returns Whether the payload was signed by the provided public key.\n */\nexport function verify(options: verify.Options): boolean {\n const { hash, payload, publicKey, signature } = options\n return secp256r1.verify(\n signature,\n payload instanceof Uint8Array ? payload : Bytes.fromHex(payload),\n PublicKey.toHex(publicKey).substring(2),\n { lowS: true, ...(hash ? { prehash: true } : {}) },\n )\n}\n\nexport declare namespace verify {\n type Options = {\n /** If set to `true`, the payload will be hashed (sha256) before being verified. */\n hash?: boolean | undefined\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n /** Public key that signed the payload. */\n publicKey: PublicKey.PublicKey<boolean>\n /** Signature of the payload. */\n signature: Signature.Signature<boolean>\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import * as Bytes from './Bytes.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\n\nconst encoder = /*#__PURE__*/ new TextEncoder()\nconst decoder = /*#__PURE__*/ new TextDecoder()\n\nconst integerToCharacter = /*#__PURE__*/ Object.fromEntries(\n Array.from(\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n ).map((a, i) => [i, a.charCodeAt(0)]),\n)\n\nconst characterToInteger = {\n ...Object.fromEntries(\n Array.from(\n 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n ).map((a, i) => [a.charCodeAt(0), i]),\n ),\n ['='.charCodeAt(0)]: 0,\n ['-'.charCodeAt(0)]: 62,\n ['_'.charCodeAt(0)]: 63,\n} as Record<number, number>\n\n/**\n * Encodes a {@link ox#Bytes.Bytes} to a Base64-encoded string (with optional padding and/or URL-safe characters).\n *\n * @example\n * ```ts twoslash\n * import { Base64, Bytes } from 'ox'\n *\n * const value = Base64.fromBytes(Bytes.fromString('hello world'))\n * // @log: 'aGVsbG8gd29ybGQ='\n * ```\n *\n * @example\n * ### No Padding\n *\n * Turn off [padding of encoded data](https://datatracker.ietf.org/doc/html/rfc4648#section-3.2) with the `pad` option:\n *\n * ```ts twoslash\n * import { Base64, Bytes } from 'ox'\n *\n * const value = Base64.fromBytes(Bytes.fromString('hello world'), { pad: false })\n * // @log: 'aGVsbG8gd29ybGQ'\n * ```\n *\n * ### URL-safe Encoding\n *\n * Turn on [URL-safe encoding](https://datatracker.ietf.org/doc/html/rfc4648#section-5) (Base64 URL) with the `url` option:\n *\n * ```ts twoslash\n * import { Base64, Bytes } from 'ox'\n *\n * const value = Base64.fromBytes(Bytes.fromString('hello wod'), { url: true })\n * // @log: 'aGVsbG8gd29_77-9ZA=='\n * ```\n *\n * @param value - The byte array to encode.\n * @param options - Encoding options.\n * @returns The Base64 encoded string.\n */\nexport function fromBytes(value: Bytes.Bytes, options: fromBytes.Options = {}) {\n const { pad = true, url = false } = options\n\n const encoded = new Uint8Array(Math.ceil(value.length / 3) * 4)\n\n for (let i = 0, j = 0; j < value.length; i += 4, j += 3) {\n const y = (value[j]! << 16) + (value[j + 1]! << 8) + (value[j + 2]! | 0)\n encoded[i] = integerToCharacter[y >> 18]!\n encoded[i + 1] = integerToCharacter[(y >> 12) & 0x3f]!\n encoded[i + 2] = integerToCharacter[(y >> 6) & 0x3f]!\n encoded[i + 3] = integerToCharacter[y & 0x3f]!\n }\n\n const k = value.length % 3\n const end = Math.floor(value.length / 3) * 4 + (k && k + 1)\n let base64 = decoder.decode(new Uint8Array(encoded.buffer, 0, end))\n if (pad && k === 1) base64 += '=='\n if (pad && k === 2) base64 += '='\n if (url) base64 = base64.replaceAll('+', '-').replaceAll('/', '_')\n return base64\n}\n\nexport declare namespace fromBytes {\n type Options = {\n /**\n * Whether to [pad](https://datatracker.ietf.org/doc/html/rfc4648#section-3.2) the Base64 encoded string.\n *\n * @default true\n */\n pad?: boolean | undefined\n /**\n * Whether to Base64 encode with [URL safe characters](https://datatracker.ietf.org/doc/html/rfc4648#section-5).\n *\n * @default false\n */\n url?: boolean | undefined\n }\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Encodes a {@link ox#Hex.Hex} to a Base64-encoded string (with optional padding and/or URL-safe characters).\n *\n * @example\n * ```ts twoslash\n * import { Base64, Hex } from 'ox'\n *\n * const value = Base64.fromHex(Hex.fromString('hello world'))\n * // @log: 'aGVsbG8gd29ybGQ='\n * ```\n *\n * @example\n * ### No Padding\n *\n * Turn off [padding of encoded data](https://datatracker.ietf.org/doc/html/rfc4648#section-3.2) with the `pad` option:\n *\n * ```ts twoslash\n * import { Base64, Hex } from 'ox'\n *\n * const value = Base64.fromHex(Hex.fromString('hello world'), { pad: false })\n * // @log: 'aGVsbG8gd29ybGQ'\n * ```\n *\n * ### URL-safe Encoding\n *\n * Turn on [URL-safe encoding](https://datatracker.ietf.org/doc/html/rfc4648#section-5) (Base64 URL) with the `url` option:\n *\n * ```ts twoslash\n * import { Base64, Hex } from 'ox'\n *\n * const value = Base64.fromHex(Hex.fromString('hello wod'), { url: true })\n * // @log: 'aGVsbG8gd29_77-9ZA=='\n * ```\n *\n * @param value - The hex value to encode.\n * @param options - Encoding options.\n * @returns The Base64 encoded string.\n */\nexport function fromHex(value: Hex.Hex, options: fromHex.Options = {}) {\n return fromBytes(Bytes.fromHex(value), options)\n}\n\nexport declare namespace fromHex {\n type Options = {\n /**\n * Whether to [pad](https://datatracker.ietf.org/doc/html/rfc4648#section-3.2) the Base64 encoded string.\n *\n * @default true\n */\n pad?: boolean | undefined\n /**\n * Whether to Base64 encode with [URL safe characters](https://datatracker.ietf.org/doc/html/rfc4648#section-5).\n *\n * @default false\n */\n url?: boolean | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Encodes a string to a Base64-encoded string (with optional padding and/or URL-safe characters).\n *\n * @example\n * ```ts twoslash\n * import { Base64 } from 'ox'\n *\n * const value = Base64.fromString('hello world')\n * // @log: 'aGVsbG8gd29ybGQ='\n * ```\n *\n * @example\n * ### No Padding\n *\n * Turn off [padding of encoded data](https://datatracker.ietf.org/doc/html/rfc4648#section-3.2) with the `pad` option:\n *\n * ```ts twoslash\n * import { Base64 } from 'ox'\n *\n * const value = Base64.fromString('hello world', { pad: false })\n * // @log: 'aGVsbG8gd29ybGQ'\n * ```\n *\n * ### URL-safe Encoding\n *\n * Turn on [URL-safe encoding](https://datatracker.ietf.org/doc/html/rfc4648#section-5) (Base64 URL) with the `url` option:\n *\n * ```ts twoslash\n * import { Base64 } from 'ox'\n *\n * const value = Base64.fromString('hello wod', { url: true })\n * // @log: 'aGVsbG8gd29_77-9ZA=='\n * ```\n *\n * @param value - The string to encode.\n * @param options - Encoding options.\n * @returns The Base64 encoded string.\n */\nexport function fromString(value: string, options: fromString.Options = {}) {\n return fromBytes(Bytes.fromString(value), options)\n}\n\nexport declare namespace fromString {\n type Options = {\n /**\n * Whether to [pad](https://datatracker.ietf.org/doc/html/rfc4648#section-3.2) the Base64 encoded string.\n *\n * @default true\n */\n pad?: boolean | undefined\n /**\n * Whether to Base64 encode with [URL safe characters](https://datatracker.ietf.org/doc/html/rfc4648#section-5).\n *\n * @default false\n */\n url?: boolean | undefined\n }\n\n type ErrorType = fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a Base64-encoded string (with optional padding and/or URL-safe characters) to {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Base64, Bytes } from 'ox'\n *\n * const value = Base64.toBytes('aGVsbG8gd29ybGQ=')\n * // @log: Uint8Array([104, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100])\n * ```\n *\n * @param value - The string, hex value, or byte array to encode.\n * @returns The Base64 decoded {@link ox#Bytes.Bytes}.\n */\nexport function toBytes(value: string): Bytes.Bytes {\n const base64 = value.replace(/=+$/, '')\n\n const size = base64.length\n\n const decoded = new Uint8Array(size + 3)\n encoder.encodeInto(base64 + '===', decoded)\n\n for (let i = 0, j = 0; i < base64.length; i += 4, j += 3) {\n const x =\n (characterToInteger[decoded[i]!]! << 18) +\n (characterToInteger[decoded[i + 1]!]! << 12) +\n (characterToInteger[decoded[i + 2]!]! << 6) +\n characterToInteger[decoded[i + 3]!]!\n decoded[j] = x >> 16\n decoded[j + 1] = (x >> 8) & 0xff\n decoded[j + 2] = x & 0xff\n }\n\n const decodedSize = (size >> 2) * 3 + (size % 4 && (size % 4) - 1)\n return new Uint8Array(decoded.buffer, 0, decodedSize)\n}\n\nexport declare namespace toBytes {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Decodes a Base64-encoded string (with optional padding and/or URL-safe characters) to {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Base64, Hex } from 'ox'\n *\n * const value = Base64.toHex('aGVsbG8gd29ybGQ=')\n * // @log: 0x68656c6c6f20776f726c64\n * ```\n *\n * @param value - The string, hex value, or byte array to encode.\n * @returns The Base64 decoded {@link ox#Hex.Hex}.\n */\nexport function toHex(value: string): Hex.Hex {\n return Hex.fromBytes(toBytes(value))\n}\n\nexport declare namespace toHex {\n type ErrorType = toBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Decodes a Base64-encoded string (with optional padding and/or URL-safe characters) to a string.\n *\n * @example\n * ```ts twoslash\n * import { Base64 } from 'ox'\n *\n * const value = Base64.toString('aGVsbG8gd29ybGQ=')\n * // @log: 'hello world'\n * ```\n *\n * @param value - The string, hex value, or byte array to encode.\n * @returns The Base64 decoded string.\n */\nexport function toString(value: string): string {\n return Bytes.toString(toBytes(value))\n}\n\nexport declare namespace toString {\n type ErrorType = toBytes.ErrorType | Errors.GlobalErrorType\n}\n","import * as Base64 from '../core/Base64.js'\nimport * as Bytes from '../core/Bytes.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hash from '../core/Hash.js'\nimport * as Hex from '../core/Hex.js'\nimport type { OneOf } from '../core/internal/types.js'\nimport * as internal from '../core/internal/webauthn.js'\nimport * as P256 from '../core/P256.js'\nimport type * as PublicKey from '../core/PublicKey.js'\nimport * as Signature from '../core/Signature.js'\nimport { getAuthenticatorData, getClientDataJSON } from './Authenticator.js'\nimport type * as Credential_ from './Credential.js'\nimport {\n base64UrlOptions,\n bufferSourceToBytes,\n bytesToArrayBuffer,\n deserializeExtensions,\n responseKeys,\n serializeExtensions,\n} from './internal/utils.js'\nimport type * as Types from './Types.js'\n\n/** Response from a WebAuthn authentication ceremony. */\nexport type Response<serialized extends boolean = false> = {\n id: string\n metadata: Credential_.SignMetadata\n raw: Types.PublicKeyCredential<serialized>\n signature: serialized extends true ? Hex.Hex : Signature.Signature<false>\n}\n\n/**\n * Deserializes credential request options that can be passed to\n * `navigator.credentials.get()`.\n *\n * @example\n * ```ts twoslash\n * import { Authentication } from 'ox/webauthn'\n *\n * const options = Authentication.getOptions({\n * challenge: '0xdeadbeef',\n * })\n * const serialized = Authentication.serializeOptions(options)\n *\n * // ... send to server and back ...\n *\n * const deserialized = Authentication.deserializeOptions(serialized) // [!code focus]\n * const credential = await window.navigator.credentials.get(deserialized)\n * ```\n *\n * @param options - The serialized credential request options.\n * @returns The deserialized credential request options.\n */\nexport function deserializeOptions(\n options: Types.CredentialRequestOptions<true>,\n): Types.CredentialRequestOptions {\n const { publicKey, ...rest } = options\n if (!publicKey) return { ...rest }\n\n const { allowCredentials, challenge, extensions, ...publicKeyRest } =\n publicKey\n\n return {\n ...rest,\n publicKey: {\n ...publicKeyRest,\n challenge: Bytes.fromHex(challenge),\n ...(allowCredentials && {\n allowCredentials: allowCredentials.map(({ id, ...rest }) => ({\n ...rest,\n id: Base64.toBytes(id),\n })),\n }),\n ...(extensions && {\n extensions: deserializeExtensions(extensions),\n }),\n },\n }\n}\n\nexport declare namespace deserializeOptions {\n type ErrorType = Base64.toBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a serialized authentication response.\n *\n * @example\n * ```ts twoslash\n * import { Authentication } from 'ox/webauthn'\n *\n * const response = Authentication.deserializeResponse({ // [!code focus]\n * id: 'm1-bMPuAqpWhCxHZQZTT6e-lSPntQbh3opIoGe7g4Qs', // [!code focus]\n * metadata: { // [!code focus]\n * authenticatorData: '0x49960de5...', // [!code focus]\n * clientDataJSON: '{\"type\":\"webauthn.get\",...}', // [!code focus]\n * challengeIndex: 23, // [!code focus]\n * typeIndex: 1, // [!code focus]\n * userVerificationRequired: true, // [!code focus]\n * }, // [!code focus]\n * raw: { // [!code focus]\n * id: 'm1-bMPuAqpWhCxHZQZTT6e-lSPntQbh3opIoGe7g4Qs', // [!code focus]\n * type: 'public-key', // [!code focus]\n * authenticatorAttachment: 'platform', // [!code focus]\n * rawId: 'm1-bMPuAqpWhCxHZQZTT6e-lSPntQbh3opIoGe7g4Qs', // [!code focus]\n * response: { clientDataJSON: 'eyJ0eXBlIjoid2ViYXV0aG4uZ2V0In0' }, // [!code focus]\n * }, // [!code focus]\n * signature: '0x...', // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param response - The serialized authentication response.\n * @returns The deserialized authentication response.\n */\nexport function deserializeResponse(response: Response<true>): Response {\n const { id, metadata, raw, signature } = response\n\n const rawResponse: Record<string, ArrayBuffer> = {}\n for (const [key, value] of Object.entries(raw.response))\n rawResponse[key] = bytesToArrayBuffer(Base64.toBytes(value))\n\n return {\n id,\n metadata,\n raw: {\n id: raw.id,\n type: raw.type,\n authenticatorAttachment: raw.authenticatorAttachment,\n rawId: bytesToArrayBuffer(Base64.toBytes(raw.rawId)),\n response: rawResponse as unknown as Types.AuthenticatorResponse,\n getClientExtensionResults: () => ({}),\n },\n signature: Signature.from(signature),\n }\n}\n\nexport declare namespace deserializeResponse {\n type ErrorType =\n | Base64.toBytes.ErrorType\n | Signature.from.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Returns the request options to sign a challenge with the Web Authentication API.\n *\n * @example\n * ```ts twoslash\n * import { Authentication } from 'ox/webauthn'\n *\n * const options = Authentication.getOptions({\n * challenge: '0xdeadbeef',\n * })\n *\n * const credential = await window.navigator.credentials.get(options)\n * ```\n *\n * @param options - Options.\n * @returns The credential request options.\n */\nexport function getOptions(\n options: getOptions.Options,\n): Types.CredentialRequestOptions {\n const {\n credentialId,\n challenge,\n extensions,\n rpId = window.location.hostname,\n userVerification = 'required',\n } = options\n return {\n publicKey: {\n ...(credentialId\n ? {\n allowCredentials: Array.isArray(credentialId)\n ? credentialId.map((id) => ({\n id: Base64.toBytes(id),\n type: 'public-key',\n }))\n : [\n {\n id: Base64.toBytes(credentialId),\n type: 'public-key',\n },\n ],\n }\n : {}),\n challenge: Bytes.fromHex(challenge),\n ...(extensions && { extensions }),\n rpId,\n userVerification,\n },\n }\n}\n\nexport declare namespace getOptions {\n type Options = {\n /** The credential ID to use. */\n credentialId?: string | string[] | undefined\n /** The challenge to sign. */\n challenge: Hex.Hex\n /** List of Web Authentication API credentials to use during creation or authentication. */\n extensions?:\n | Types.PublicKeyCredentialRequestOptions['extensions']\n | undefined\n /** The relying party identifier to use. */\n rpId?: Types.PublicKeyCredentialRequestOptions['rpId'] | undefined\n /** The user verification requirement. */\n userVerification?:\n | Types.PublicKeyCredentialRequestOptions['userVerification']\n | undefined\n }\n\n type ErrorType =\n | Bytes.fromHex.ErrorType\n | Base64.toBytes.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Constructs the final digest that was signed and computed by the authenticator. This payload includes\n * the cryptographic `challenge`, as well as authenticator metadata (`authenticatorData` + `clientDataJSON`).\n * This value can be also used with raw P256 verification (such as `P256.verify` or\n * `WebCryptoP256.verify`).\n *\n * :::warning\n *\n * This function is mainly for testing purposes or for manually constructing\n * signing payloads. In most cases you will not need this function and\n * instead use `Authentication.sign`.\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { Authentication } from 'ox/webauthn'\n * import { WebCryptoP256 } from 'ox'\n *\n * const { metadata, payload } = Authentication.getSignPayload({ // [!code focus]\n * challenge: '0xdeadbeef', // [!code focus]\n * }) // [!code focus]\n *\n * const { publicKey, privateKey } = await WebCryptoP256.createKeyPair()\n *\n * const signature = await WebCryptoP256.sign({\n * payload,\n * privateKey,\n * })\n * ```\n *\n * @param options - Options to construct the signing payload.\n * @returns The signing payload.\n */\nexport function getSignPayload(\n options: getSignPayload.Options,\n): getSignPayload.ReturnType {\n const {\n challenge,\n crossOrigin,\n extraClientData,\n flag,\n origin,\n rpId,\n signCount,\n userVerification = 'required',\n } = options\n\n const authenticatorData = getAuthenticatorData({\n flag,\n rpId,\n signCount,\n })\n const clientDataJSON = getClientDataJSON({\n challenge,\n crossOrigin,\n extraClientData,\n origin,\n })\n const clientDataJSONHash = Hash.sha256(Hex.fromString(clientDataJSON))\n\n const challengeIndex = clientDataJSON.indexOf('\"challenge\"')\n const typeIndex = clientDataJSON.indexOf('\"type\"')\n\n const metadata = {\n authenticatorData,\n clientDataJSON,\n challengeIndex,\n typeIndex,\n userVerificationRequired: userVerification === 'required',\n }\n\n const payload = Hex.concat(authenticatorData, clientDataJSONHash)\n\n return { metadata, payload }\n}\n\nexport declare namespace getSignPayload {\n type Options = {\n /** The challenge to sign. */\n challenge: Hex.Hex\n /** If set to `true`, it means that the calling context is an `<iframe>` that is not same origin with its ancestor frames. */\n crossOrigin?: boolean | undefined\n /** Additional client data to include in the client data JSON. */\n extraClientData?: Record<string, unknown> | undefined\n /** If set to `true`, the payload will be hashed before being returned. */\n hash?: boolean | undefined\n /** A bitfield that indicates various attributes that were asserted by the authenticator. [Read more](https://developer.mozilla.org/en-US/docs/Web/API/Web_Authentication_API/Authenticator_data#flags) */\n flag?: number | undefined\n /** The fully qualified origin of the relying party which has been given by the client/browser to the authenticator. */\n origin?: string | undefined\n /** The [Relying Party ID](https://w3c.github.io/webauthn/#relying-party-identifier) that the credential is scoped to. */\n rpId?: Types.PublicKeyCredentialRequestOptions['rpId'] | undefined\n /** A signature counter, if supported by the authenticator (set to 0 otherwise). */\n signCount?: number | undefined\n /** The user verification requirement that the authenticator will enforce. */\n userVerification?:\n | Types.PublicKeyCredentialRequestOptions['userVerification']\n | undefined\n }\n\n type ReturnType = {\n metadata: Credential_.SignMetadata\n payload: Hex.Hex\n }\n\n type ErrorType =\n | Hash.sha256.ErrorType\n | Hex.concat.ErrorType\n | Hex.fromString.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes credential request options into a JSON-serializable\n * format, converting `BufferSource` fields to base64url strings.\n *\n * @example\n * ```ts twoslash\n * import { Authentication } from 'ox/webauthn'\n *\n * const options = Authentication.getOptions({\n * challenge: '0xdeadbeef',\n * })\n *\n * const serialized = Authentication.serializeOptions(options) // [!code focus]\n *\n * // `serialized` is JSON-serializable — send it to a server, store it, etc.\n * const json = JSON.stringify(serialized)\n * ```\n *\n * @param options - The credential request options to serialize.\n * @returns The serialized credential request options.\n */\nexport function serializeOptions(\n options: Types.CredentialRequestOptions,\n): Types.CredentialRequestOptions<true> {\n const { publicKey, signal: _, ...rest } = options\n if (!publicKey) return { ...rest }\n\n const { allowCredentials, challenge, extensions, ...publicKeyRest } =\n publicKey\n\n return {\n ...rest,\n publicKey: {\n ...publicKeyRest,\n challenge: Hex.fromBytes(bufferSourceToBytes(challenge)),\n ...(allowCredentials && {\n allowCredentials: allowCredentials.map(({ id, ...rest }) => ({\n ...rest,\n id: Base64.fromBytes(bufferSourceToBytes(id), base64UrlOptions),\n })),\n }),\n ...(extensions && {\n extensions: serializeExtensions(extensions),\n }),\n },\n }\n}\n\nexport declare namespace serializeOptions {\n type ErrorType = Base64.fromBytes.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Serializes an authentication response into a JSON-serializable\n * format, converting `BufferSource` fields to base64url strings\n * and the signature to a hex string.\n *\n * @example\n * ```ts twoslash\n * import { Authentication } from 'ox/webauthn'\n *\n * const response = await Authentication.sign({\n * challenge: '0xdeadbeef',\n * })\n *\n * const serialized = Authentication.serializeResponse(response) // [!code focus]\n *\n * // `serialized` is JSON-serializable — send it to a server, store it, etc.\n * const json = JSON.stringify(serialized)\n * ```\n *\n * @param response - The authentication response to serialize.\n * @returns The serialized authentication response.\n */\nexport function serializeResponse(response: Response): Response<true> {\n const { id, metadata, raw, signature } = response\n\n const rawResponse = {} as Record<string, string>\n for (const key of responseKeys) {\n const value = (raw.response as unknown as Record<string, unknown>)[key]\n if (value instanceof ArrayBuffer)\n rawResponse[key] = Base64.fromBytes(\n new Uint8Array(value),\n base64UrlOptions,\n )\n }\n\n return {\n id,\n metadata,\n raw: {\n id: raw.id,\n type: raw.type,\n authenticatorAttachment: raw.authenticatorAttachment,\n rawId: Base64.fromBytes(bufferSourceToBytes(raw.rawId), base64UrlOptions),\n response: rawResponse as unknown as Types.AuthenticatorResponse<true>,\n },\n signature: Signature.toHex(signature),\n }\n}\n\nexport declare namespace serializeResponse {\n type ErrorType =\n | Base64.fromBytes.ErrorType\n | Signature.toHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Signs a challenge using a stored WebAuthn P256 Credential. If no Credential is provided,\n * a prompt will be displayed for the user to select an existing Credential\n * that was previously registered.\n *\n * @example\n * ```ts twoslash\n * import { Registration, Authentication } from 'ox/webauthn'\n *\n * const credential = await Registration.create({\n * name: 'Example',\n * })\n *\n * const { metadata, signature } = await Authentication.sign({ // [!code focus]\n * credentialId: credential.id, // [!code focus]\n * challenge: '0xdeadbeef', // [!code focus]\n * }) // [!code focus]\n * // @log: {\n * // @log: metadata: {\n * // @log: authenticatorData: '0x49960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d97630500000000',\n * // @log: clientDataJSON: '{\"type\":\"webauthn.get\",\"challenge\":\"9jEFijuhEWrM4SOW-tChJbUEHEP44VcjcJ-Bqo1fTM8\",\"origin\":\"http://localhost:5173\",\"crossOrigin\":false}',\n * // @log: challengeIndex: 23,\n * // @log: typeIndex: 1,\n * // @log: userVerificationRequired: true,\n * // @log: },\n * // @log: signature: { r: 51231...4215n, s: 12345...6789n },\n * // @log: }\n * ```\n *\n * @param options - Options.\n * @returns The signature.\n */\nexport async function sign(options: sign.Options): Promise<sign.ReturnType> {\n const {\n getFn = (opts: Types.CredentialRequestOptions | undefined) =>\n window.navigator.credentials.get(opts as never),\n ...rest\n } = options\n const requestOptions =\n 'publicKey' in rest\n ? (rest as Types.CredentialRequestOptions)\n : getOptions(rest as never)\n try {\n const credential = (await getFn(\n requestOptions as never,\n )) as Types.PublicKeyCredential\n if (!credential) throw new SignFailedError()\n const response = credential.response as AuthenticatorAssertionResponse\n\n // Eagerly copy ArrayBuffer data to avoid cross-origin access errors\n // when browser extensions (e.g. 1Password on Firefox) replace\n // `navigator.credentials` with a cross-compartment proxy.\n const clientDataJSONBytes = new Uint8Array(response.clientDataJSON)\n const authenticatorDataBytes = new Uint8Array(response.authenticatorData)\n const signatureBytes = new Uint8Array(response.signature)\n const id = credential.id\n\n const clientDataJSON = String.fromCharCode(...clientDataJSONBytes)\n const challengeIndex = clientDataJSON.indexOf('\"challenge\"')\n const typeIndex = clientDataJSON.indexOf('\"type\"')\n\n const signature = internal.parseAsn1Signature(signatureBytes)\n\n return {\n id,\n metadata: {\n authenticatorData: Hex.fromBytes(authenticatorDataBytes),\n clientDataJSON,\n challengeIndex,\n typeIndex,\n userVerificationRequired:\n requestOptions.publicKey!.userVerification === 'required',\n },\n signature,\n raw: credential,\n }\n } catch (error) {\n throw new SignFailedError({\n cause: error as Error,\n })\n }\n}\n\nexport declare namespace sign {\n type Options = OneOf<\n | (getOptions.Options & {\n /**\n * Credential request function. Useful for environments that do not support\n * the WebAuthn API natively (i.e. React Native or testing environments).\n *\n * @default window.navigator.credentials.get\n */\n getFn?:\n | ((\n options?: Types.CredentialRequestOptions | undefined,\n ) => Promise<Types.Credential | null>)\n | undefined\n })\n | Types.CredentialRequestOptions\n >\n\n type ReturnType = Response\n\n type ErrorType =\n | Hex.fromBytes.ErrorType\n | getOptions.ErrorType\n | Errors.GlobalErrorType\n}\n\n/** Thrown when a WebAuthn P256 credential request fails. */\nexport class SignFailedError extends Errors.BaseError<Error> {\n override readonly name = 'Authentication.SignFailedError'\n\n constructor({ cause }: { cause?: Error | undefined } = {}) {\n super('Failed to request credential.', {\n cause,\n })\n }\n}\n\n/**\n * Verifies a signature using the Credential's public key and the challenge which was signed.\n *\n * @example\n * ```ts twoslash\n * import { Registration, Authentication } from 'ox/webauthn'\n *\n * const credential = await Registration.create({\n * name: 'Example',\n * })\n *\n * const { metadata, signature } = await Authentication.sign({\n * credentialId: credential.id,\n * challenge: '0xdeadbeef',\n * })\n *\n * const result = Authentication.verify({ // [!code focus]\n * metadata, // [!code focus]\n * challenge: '0xdeadbeef', // [!code focus]\n * publicKey: credential.publicKey, // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * // @log: true\n * ```\n *\n * @param options - Options.\n * @returns Whether the signature is valid.\n */\nexport function verify(options: verify.Options): boolean {\n const { challenge, metadata, origin, publicKey, rpId, signature } = options\n const { authenticatorData, clientDataJSON, userVerificationRequired } =\n metadata\n\n const authenticatorDataBytes = Bytes.fromHex(authenticatorData)\n\n // Check length of `authenticatorData`.\n if (authenticatorDataBytes.length < 37) return false\n\n // If rpId is provided, validate the rpIdHash in authenticatorData.\n if (rpId !== undefined) {\n const rpIdHash = authenticatorDataBytes.slice(0, 32)\n const expectedRpIdHash = Hash.sha256(Hex.fromString(rpId), { as: 'Bytes' })\n if (!Bytes.isEqual(rpIdHash, expectedRpIdHash)) return false\n }\n\n const flag = authenticatorDataBytes[32]!\n\n // Verify that the UP bit of the flags in authData is set.\n if ((flag & 0x01) !== 0x01) return false\n\n // If user verification was determined to be required, verify that\n // the UV bit of the flags in authData is set. Otherwise, ignore the\n // value of the UV flag.\n if (userVerificationRequired && (flag & 0x04) !== 0x04) return false\n\n // If the BE bit of the flags in authData is not set, verify that\n // the BS bit is not set.\n if ((flag & 0x08) !== 0x08 && (flag & 0x10) === 0x10) return false\n\n // Parse clientDataJSON for validation.\n const clientData = JSON.parse(clientDataJSON)\n\n // Verify that response is for an authentication assertion.\n if (clientData.type !== 'webauthn.get') return false\n\n // Validate the challenge in the clientDataJSON.\n if (\n !clientData.challenge ||\n Hex.fromBytes(Base64.toBytes(clientData.challenge)) !== challenge\n )\n return false\n\n // If origin is provided, validate origin.\n if (origin !== undefined) {\n const origins = Array.isArray(origin) ? origin : [origin]\n if (!origins.includes(clientData.origin)) return false\n }\n\n const clientDataJSONHash = Hash.sha256(Bytes.fromString(clientDataJSON), {\n as: 'Bytes',\n })\n const payload = Bytes.concat(authenticatorDataBytes, clientDataJSONHash)\n\n return P256.verify({\n hash: true,\n payload,\n publicKey,\n signature,\n })\n}\n\nexport declare namespace verify {\n type Options = {\n /** The challenge to verify. */\n challenge: Hex.Hex\n /** The public key to verify the signature with. */\n publicKey: PublicKey.PublicKey\n /** The signature to verify. */\n signature: Signature.Signature<false>\n /** The metadata to verify the signature with. */\n metadata: Credential_.SignMetadata\n /** Expected origin(s). If provided, the `clientDataJSON` origin will be validated. */\n origin?: string | string[] | undefined\n /** Expected relying party ID. If provided, the `rpIdHash` in `authenticatorData` will be validated. */\n rpId?: string | undefined\n }\n\n type ErrorType =\n | Base64.toBytes.ErrorType\n | Bytes.concat.ErrorType\n | Bytes.fromHex.ErrorType\n | Bytes.isEqual.ErrorType\n | Hash.sha256.ErrorType\n | Hex.fromString.ErrorType\n | P256.verify.ErrorType\n | Errors.GlobalErrorType\n}\n","import * as Authentication from '../webauthn/Authentication.js'\nimport * as Authenticator from '../webauthn/Authenticator.js'\nimport type * as Credential_ from '../webauthn/Credential.js'\nimport * as Registration from '../webauthn/Registration.js'\n\n/** A WebAuthn-flavored P256 credential. */\nexport type P256Credential = Credential_.Credential\n\n/** Metadata for a WebAuthn P256 signature. */\nexport type SignMetadata = Credential_.SignMetadata\n\nexport const createChallenge = Registration.createChallenge\n\n/**\n * Creates a new WebAuthn P256 Credential, which can be stored and later used for signing.\n *\n * @example\n * ```ts twoslash\n * import { WebAuthnP256 } from 'ox'\n *\n * const credential = await WebAuthnP256.createCredential({ name: 'Example' }) // [!code focus]\n * // @log: {\n * // @log: id: 'oZ48...',\n * // @log: publicKey: { x: 51421...5123n, y: 12345...6789n },\n * // @log: raw: PublicKeyCredential {},\n * // @log: }\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * credentialId: credential.id,\n * challenge: '0xdeadbeef',\n * })\n * ```\n *\n * @param options - Credential creation options.\n * @returns A WebAuthn P256 credential.\n */\nexport async function createCredential(\n options: createCredential.Options,\n): Promise<P256Credential> {\n return Registration.create(options)\n}\n\nexport declare namespace createCredential {\n type Options = Registration.create.Options\n type ErrorType = Registration.create.ErrorType\n}\n\n/**\n * Gets the authenticator data which contains information about the\n * processing of an authenticator request (ie. from `WebAuthnP256.sign`).\n *\n * :::warning\n *\n * This function is mainly for testing purposes or for manually constructing\n * autenticator data. In most cases you will not need this function.\n * `authenticatorData` is typically returned as part of the\n * {@link ox#WebAuthnP256.(sign:function)} response (ie. an authenticator response).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { WebAuthnP256 } from 'ox'\n *\n * const authenticatorData = WebAuthnP256.getAuthenticatorData({\n * rpId: 'example.com',\n * signCount: 420,\n * })\n * // @log: \"0xa379a6f6eeafb9a55e378c118034e2751e682fab9f2d30ab13d2125586ce194705000001a4\"\n * ```\n *\n * @example\n * ### With Attested Credential Data\n *\n * Include a credential ID and public key in the authenticator data (for registration responses):\n *\n * ```ts twoslash\n * import { P256, WebAuthnP256 } from 'ox'\n *\n * const { publicKey } = P256.createKeyPair()\n *\n * const authenticatorData = WebAuthnP256.getAuthenticatorData({\n * rpId: 'example.com',\n * flag: 0x41, // UP + AT\n * credential: {\n * id: new Uint8Array(32),\n * publicKey,\n * },\n * })\n * ```\n *\n * @param options - Options to construct the authenticator data.\n * @returns The authenticator data.\n */\nexport const getAuthenticatorData = Authenticator.getAuthenticatorData\n\nexport declare namespace getAuthenticatorData {\n type Options = Authenticator.getAuthenticatorData.Options\n\n type ErrorType = Authenticator.getAuthenticatorData.ErrorType\n}\n\n/**\n * Constructs the Client Data in stringified JSON format which represents client data that\n * was passed to `credentials.get()` in {@link ox#WebAuthnP256.(sign:function)}.\n *\n * :::warning\n *\n * This function is mainly for testing purposes or for manually constructing\n * client data. In most cases you will not need this function.\n * `clientDataJSON` is typically returned as part of the\n * {@link ox#WebAuthnP256.(sign:function)} response (ie. an authenticator response).\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { WebAuthnP256 } from 'ox'\n *\n * const clientDataJSON = WebAuthnP256.getClientDataJSON({\n * challenge: '0xdeadbeef',\n * origin: 'https://example.com',\n * })\n * // @log: \"{\"type\":\"webauthn.get\",\"challenge\":\"3q2-7w\",\"origin\":\"https://example.com\",\"crossOrigin\":false}\"\n * ```\n *\n * @param options - Options to construct the client data.\n * @returns The client data.\n */\nexport const getClientDataJSON = Authenticator.getClientDataJSON\n\nexport declare namespace getClientDataJSON {\n type Options = Authenticator.getClientDataJSON.Options\n\n type ErrorType = Authenticator.getClientDataJSON.ErrorType\n}\n\n/**\n * Constructs a CBOR-encoded attestation object for testing WebAuthn registration\n * verification. Combines the authenticator data with an attestation statement.\n *\n * :::warning\n *\n * This function is mainly for testing purposes. In production, the attestation\n * object is returned by the authenticator during `navigator.credentials.create()`.\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { P256, WebAuthnP256 } from 'ox'\n *\n * const { publicKey } = P256.createKeyPair()\n *\n * const attestationObject = WebAuthnP256.getAttestationObject({\n * authData: WebAuthnP256.getAuthenticatorData({\n * rpId: 'example.com',\n * flag: 0x41,\n * credential: { id: new Uint8Array(32), publicKey },\n * }),\n * })\n * ```\n *\n * @param options - Options to construct the attestation object.\n * @returns The CBOR-encoded attestation object as a Hex string.\n */\nexport const getAttestationObject = Authenticator.getAttestationObject\n\nexport declare namespace getAttestationObject {\n type Options = Authenticator.getAttestationObject.Options\n\n type ErrorType = Authenticator.getAttestationObject.ErrorType\n}\n\n/**\n * Returns the creation options for a P256 WebAuthn Credential to be used with\n * the Web Authentication API.\n *\n * @example\n * ```ts twoslash\n * import { WebAuthnP256 } from 'ox'\n *\n * const options = WebAuthnP256.getCredentialCreationOptions({ name: 'Example' })\n *\n * const credential = await window.navigator.credentials.create(options)\n * ```\n *\n * @param options - Options.\n * @returns The credential creation options.\n */\nexport const getCredentialCreationOptions = Registration.getOptions\n\nexport declare namespace getCredentialCreationOptions {\n type Options = Registration.getOptions.Options\n\n type ErrorType = Registration.getOptions.ErrorType\n}\n\n/**\n * Returns the request options to sign a challenge with the Web Authentication API.\n *\n * @example\n * ```ts twoslash\n * import { WebAuthnP256 } from 'ox'\n *\n * const options = WebAuthnP256.getCredentialRequestOptions({\n * challenge: '0xdeadbeef',\n * })\n *\n * const credential = await window.navigator.credentials.get(options)\n * ```\n *\n * @param options - Options.\n * @returns The credential request options.\n */\nexport const getCredentialRequestOptions = Authentication.getOptions\n\nexport declare namespace getCredentialRequestOptions {\n type Options = Authentication.getOptions.Options\n type ErrorType = Authentication.getOptions.ErrorType\n}\n\n/**\n * Constructs the final digest that was signed and computed by the authenticator. This payload includes\n * the cryptographic `challenge`, as well as authenticator metadata (`authenticatorData` + `clientDataJSON`).\n * This value can be also used with raw P256 verification (such as {@link ox#P256.(verify:function)} or\n * {@link ox#WebCryptoP256.(verify:function)}).\n *\n * :::warning\n *\n * This function is mainly for testing purposes or for manually constructing\n * signing payloads. In most cases you will not need this function and\n * instead use {@link ox#WebAuthnP256.(sign:function)}.\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { WebAuthnP256, WebCryptoP256 } from 'ox'\n *\n * const { metadata, payload } = WebAuthnP256.getSignPayload({ // [!code focus]\n * challenge: '0xdeadbeef', // [!code focus]\n * }) // [!code focus]\n * // @log: {\n * // @log: metadata: {\n * // @log: authenticatorData: \"0x49960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d97630500000000\",\n * // @log: challengeIndex: 23,\n * // @log: clientDataJSON: \"{\"type\":\"webauthn.get\",\"challenge\":\"9jEFijuhEWrM4SOW-tChJbUEHEP44VcjcJ-Bqo1fTM8\",\"origin\":\"http://localhost:5173\",\"crossOrigin\":false}\",\n * // @log: typeIndex: 1,\n * // @log: userVerificationRequired: true,\n * // @log: },\n * // @log: payload: \"0x49960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d9763050000000045086dcb06a5f234db625bcdc94e657f86b76b6fd3eb9c30543eabc1e577a4b0\",\n * // @log: }\n *\n * const { publicKey, privateKey } = await WebCryptoP256.createKeyPair()\n *\n * const signature = await WebCryptoP256.sign({\n * payload,\n * privateKey,\n * })\n * ```\n *\n * @param options - Options to construct the signing payload.\n * @returns The signing payload.\n */\nexport const getSignPayload = Authentication.getSignPayload\n\nexport declare namespace getSignPayload {\n type Options = Authentication.getSignPayload.Options\n\n type ReturnType = Authentication.getSignPayload.ReturnType\n\n type ErrorType = Authentication.getSignPayload.ErrorType\n}\n\n/**\n * Signs a challenge using a stored WebAuthn P256 Credential. If no Credential is provided,\n * a prompt will be displayed for the user to select an existing Credential\n * that was previously registered.\n *\n * @example\n * ```ts twoslash\n * import { WebAuthnP256 } from 'ox'\n *\n * const credential = await WebAuthnP256.createCredential({\n * name: 'Example',\n * })\n *\n * const { metadata, signature } = await WebAuthnP256.sign({ // [!code focus]\n * credentialId: credential.id, // [!code focus]\n * challenge: '0xdeadbeef', // [!code focus]\n * }) // [!code focus]\n * // @log: {\n * // @log: metadata: {\n * // @log: authenticatorData: '0x49960de5880e8c687434170f6476605b8fe4aeb9a28632c7995cf3ba831d97630500000000',\n * // @log: clientDataJSON: '{\"type\":\"webauthn.get\",\"challenge\":\"9jEFijuhEWrM4SOW-tChJbUEHEP44VcjcJ-Bqo1fTM8\",\"origin\":\"http://localhost:5173\",\"crossOrigin\":false}',\n * // @log: challengeIndex: 23,\n * // @log: typeIndex: 1,\n * // @log: userVerificationRequired: true,\n * // @log: },\n * // @log: signature: { r: 51231...4215n, s: 12345...6789n },\n * // @log: }\n * ```\n *\n * @param options - Options.\n * @returns The signature.\n */\nexport async function sign(options: sign.Options): Promise<sign.ReturnType> {\n return Authentication.sign(options)\n}\n\nexport declare namespace sign {\n type Options = Authentication.sign.Options\n\n type ReturnType = Authentication.sign.ReturnType\n\n type ErrorType = Authentication.sign.ErrorType\n}\n\n/**\n * Verifies a signature using the Credential's public key and the challenge which was signed.\n *\n * @example\n * ```ts twoslash\n * import { WebAuthnP256 } from 'ox'\n *\n * const credential = await WebAuthnP256.createCredential({\n * name: 'Example',\n * })\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * credentialId: credential.id,\n * challenge: '0xdeadbeef',\n * })\n *\n * const result = await WebAuthnP256.verify({ // [!code focus]\n * metadata, // [!code focus]\n * challenge: '0xdeadbeef', // [!code focus]\n * publicKey: credential.publicKey, // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * // @log: true\n * ```\n *\n * @param options - Options.\n * @returns Whether the signature is valid.\n */\nexport function verify(options: verify.Options): boolean {\n return Authentication.verify(options)\n}\n\nexport declare namespace verify {\n type Options = Authentication.verify.Options\n\n type ErrorType = Authentication.verify.ErrorType\n}\n\n// Export types required for inference.\nexport type {\n AttestationConveyancePreference,\n AuthenticationExtensionsClientInputs,\n AuthenticatorAttachment,\n AuthenticatorSelectionCriteria,\n AuthenticatorTransport,\n BufferSource,\n COSEAlgorithmIdentifier,\n Credential,\n CredentialCreationOptions,\n CredentialMediationRequirement,\n CredentialRequestOptions,\n LargeBlobSupport,\n PrfExtension,\n PublicKeyCredential,\n PublicKeyCredentialCreationOptions,\n PublicKeyCredentialDescriptor,\n PublicKeyCredentialEntity,\n PublicKeyCredentialParameters,\n PublicKeyCredentialRequestOptions,\n PublicKeyCredentialRpEntity,\n PublicKeyCredentialType,\n PublicKeyCredentialUserEntity,\n ResidentKeyRequirement,\n UserVerificationRequirement,\n} from '../webauthn/Types.js'\n","import * as core_Address from '../core/Address.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type { Compute } from '../core/internal/types.js'\n\n/** An address that can be either an Ethereum hex address or a Tempo address. */\nexport type Address = core_Address.Address | Tempo\n\n/** Root type for a Tempo Address. */\nexport type Tempo = Compute<`tempox${string}`>\n\n/**\n * Resolves an address input (either an Ethereum hex address or a Tempo address)\n * to an Ethereum hex address.\n *\n * @example\n * ```ts twoslash\n * import { TempoAddress } from 'ox/tempo'\n *\n * const address = TempoAddress.resolve('tempox0x742d35cc6634c0532925a3b844bc9e7595f2bd28')\n * // @log: '0x742d35CC6634c0532925a3B844bc9e7595F2Bd28'\n * ```\n *\n * @example\n * ### Hex Address Passthrough\n * ```ts twoslash\n * import { TempoAddress } from 'ox/tempo'\n *\n * const address = TempoAddress.resolve('0x742d35Cc6634C0532925a3b844Bc9e7595f2bD28')\n * // @log: '0x742d35CC6634c0532925a3B844bc9e7595F2Bd28'\n * ```\n *\n * @param address - An Ethereum hex address or Tempo address.\n * @returns The resolved Ethereum hex address.\n */\nexport function resolve(address: Address): core_Address.Address {\n if (address.startsWith('tempo')) return parse(address).address\n return address as core_Address.Address\n}\n\n/**\n * Formats a raw Ethereum address into a Tempo address string.\n *\n * @example\n * ```ts twoslash\n * import { TempoAddress } from 'ox/tempo'\n *\n * const address = TempoAddress.format('0x742d35Cc6634C0532925a3b844Bc9e7595f2bD28')\n * // @log: 'tempox0x742d35cc6634c0532925a3b844bc9e7595f2bd28'\n * ```\n *\n * @param address - The raw 20-byte Ethereum address.\n * @returns The encoded Tempo address string.\n */\nexport function format(address: Address): Tempo {\n const resolved = resolve(address)\n return `tempox${resolved.toLowerCase()}` as Tempo\n}\n\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses a Tempo address string into a raw Ethereum address.\n *\n * @example\n * ```ts twoslash\n * import { TempoAddress } from 'ox/tempo'\n *\n * const result = TempoAddress.parse(\n * 'tempox0x742d35cc6634c0532925a3b844bc9e7595f2bd28',\n * )\n * // @log: { address: '0x742d35CC6634c0532925a3B844bc9e7595F2Bd28' }\n * ```\n *\n * @param tempoAddress - The Tempo address string to parse.\n * @returns The parsed raw address.\n */\nexport function parse(tempoAddress: string): parse.ReturnType {\n if (!tempoAddress.startsWith('tempox'))\n throw new InvalidPrefixError({ address: tempoAddress })\n\n const hex = tempoAddress.slice('tempox'.length)\n Hex.assert(hex, { strict: true })\n\n const address = core_Address.checksum(hex)\n\n return { address }\n}\n\nexport declare namespace parse {\n type ReturnType = {\n /** The raw 20-byte Ethereum address. */\n address: core_Address.Address\n }\n\n type ErrorType = InvalidPrefixError | Errors.GlobalErrorType\n}\n\n/**\n * Validates a Tempo address string.\n *\n * @example\n * ```ts twoslash\n * import { TempoAddress } from 'ox/tempo'\n *\n * const valid = TempoAddress.validate(\n * 'tempox0x742d35cc6634c0532925a3b844bc9e7595f2bd28',\n * )\n * // @log: true\n * ```\n *\n * @param tempoAddress - The Tempo address string to validate.\n * @returns Whether the address is valid.\n */\nexport function validate(tempoAddress: string): boolean {\n try {\n parse(tempoAddress)\n return true\n } catch {\n return false\n }\n}\n\n/** Thrown when a Tempo address has an invalid prefix. */\nexport class InvalidPrefixError extends Errors.BaseError {\n override readonly name = 'TempoAddress.InvalidPrefixError'\n\n constructor({ address }: { address: string }) {\n super(\n `Tempo address \"${address}\" has an invalid prefix. Expected \"tempox\".`,\n )\n }\n}\n","import type * as Errors from '../core/Errors.js'\nimport * as Hash from '../core/Hash.js'\nimport * as Hex from '../core/Hex.js'\nimport type { Compute, Mutable } from '../core/internal/types.js'\nimport * as Rlp from '../core/Rlp.js'\nimport * as SignatureEnvelope from './SignatureEnvelope.js'\nimport * as TempoAddress from './TempoAddress.js'\n\n/**\n * Root type for a Tempo Authorization.\n *\n * Tempo extends EIP-7702 to support secp256k1, P256, and WebAuthn signature types,\n * enabling passkey-based account delegation.\n *\n * [Tempo Authorization Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#tempo-authorization-list)\n */\nexport type AuthorizationTempo<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n {\n /** Address of the contract to set as code for the Authority. */\n address: TempoAddress.Address\n /** Chain ID to authorize. */\n chainId: numberType\n /** Nonce of the Authority to authorize. */\n nonce: bigintType\n } & (signed extends true\n ? { signature: SignatureEnvelope.SignatureEnvelope<bigintType, numberType> }\n : {\n signature?:\n | SignatureEnvelope.SignatureEnvelope<bigintType, numberType>\n | undefined\n })\n>\n\n/** RPC representation of an {@link ox#AuthorizationTempo.AuthorizationTempo}. */\nexport type Rpc = Omit<\n AuthorizationTempo<false, Hex.Hex, Hex.Hex>,\n 'signature'\n> & {\n signature: SignatureEnvelope.SignatureEnvelopeRpc\n}\n\n/** List of {@link ox#AuthorizationTempo.AuthorizationTempo}. */\nexport type List<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<readonly AuthorizationTempo<signed, bigintType, numberType>[]>\n\n/** RPC representation of a list of AA Authorizations. */\nexport type ListRpc = readonly Rpc[]\n\n/** Signed representation of a list of AA Authorizations. */\nexport type ListSigned<bigintType = bigint, numberType = number> = List<\n true,\n bigintType,\n numberType\n>\n\n/** Signed representation of an AA Authorization. */\nexport type Signed<\n bigintType = bigint,\n numberType = number,\n> = AuthorizationTempo<true, bigintType, numberType>\n\n/** Tuple representation of an AA Authorization. */\nexport type Tuple<signed extends boolean = boolean> = signed extends true\n ? readonly [\n chainId: Hex.Hex,\n address: Hex.Hex,\n nonce: Hex.Hex,\n signature: Hex.Hex,\n ]\n : readonly [chainId: Hex.Hex, address: Hex.Hex, nonce: Hex.Hex]\n\n/** Tuple representation of a signed {@link ox#AuthorizationTempo.AuthorizationTempo}. */\nexport type TupleSigned = Tuple<true>\n\n/** Tuple representation of a list of {@link ox#AuthorizationTempo.AuthorizationTempo}. */\nexport type TupleList<signed extends boolean = boolean> =\n readonly Tuple<signed>[]\n\n/** Tuple representation of a list of signed {@link ox#AuthorizationTempo.AuthorizationTempo}. */\nexport type TupleListSigned = TupleList<true>\n\n/**\n * Converts an EIP-7702 Authorization object into a typed {@link ox#AuthorizationTempo.AuthorizationTempo}.\n *\n * Tempo extends EIP-7702 to support secp256k1, P256, and WebAuthn signature types.\n *\n * [Tempo Authorization Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#tempo-authorization-list)\n *\n * @example\n * An Authorization can be instantiated from an EIP-7702 Authorization tuple in object format.\n *\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * ```\n *\n * @example\n * ### Attaching Signatures (Secp256k1)\n *\n * Standard Ethereum ECDSA signature using the secp256k1 curve.\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: AuthorizationTempo.getSignPayload(authorization),\n * privateKey,\n * })\n *\n * const authorization_signed = AuthorizationTempo.from(\n * authorization,\n * { signature }, // [!code focus]\n * )\n * ```\n *\n * @example\n * ### Attaching Signatures (P256)\n *\n * ECDSA signature using the P-256 (secp256r1) curve. Requires embedding the\n * public key and a `prehash` flag indicating whether the payload was hashed\n * before signing.\n *\n * ```ts twoslash\n * import { P256 } from 'ox'\n * import { AuthorizationTempo, SignatureEnvelope } from 'ox/tempo'\n *\n * const { privateKey, publicKey } = P256.createKeyPair()\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const signature = P256.sign({\n * payload: AuthorizationTempo.getSignPayload(authorization),\n * privateKey,\n * })\n * const signatureEnvelope = SignatureEnvelope.from({\n * signature,\n * publicKey,\n * prehash: false,\n * })\n *\n * const authorization_signed = AuthorizationTempo.from(\n * authorization,\n * { signature: signatureEnvelope }, // [!code focus]\n * )\n * ```\n *\n * @example\n * ### Attaching Signatures (P256 WebCrypto)\n *\n * When using WebCrypto keys, `prehash` must be `true` since WebCrypto always\n * hashes the payload internally before signing.\n *\n * ```ts twoslash\n * // @noErrors\n * import { WebCryptoP256 } from 'ox'\n * import { AuthorizationTempo, SignatureEnvelope } from 'ox/tempo'\n *\n * const { privateKey, publicKey } = await WebCryptoP256.createKeyPair()\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const signature = await WebCryptoP256.sign({\n * payload: AuthorizationTempo.getSignPayload(authorization),\n * privateKey,\n * })\n * const signatureEnvelope = SignatureEnvelope.from({\n * signature,\n * publicKey,\n * prehash: true,\n * })\n *\n * const authorization_signed = AuthorizationTempo.from(\n * authorization,\n * { signature: signatureEnvelope }, // [!code focus]\n * )\n * ```\n *\n * @example\n * ### Attaching Signatures (WebAuthn)\n *\n * Passkey-based signature using WebAuthn. Includes authenticator metadata\n * (authenticatorData and clientDataJSON) along with the P-256 signature and\n * public key.\n *\n * ```ts twoslash\n * // @noErrors\n * import { WebAuthnP256 } from 'ox'\n * import { AuthorizationTempo, SignatureEnvelope } from 'ox/tempo'\n *\n * const credential = await WebAuthnP256.createCredential({ name: 'Example' })\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 1,\n * nonce: 40n,\n * })\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * challenge: AuthorizationTempo.getSignPayload(authorization),\n * credentialId: credential.id,\n * })\n * const signatureEnvelope = SignatureEnvelope.from({\n * signature,\n * publicKey: credential.publicKey,\n * metadata,\n * })\n *\n * const authorization_signed = AuthorizationTempo.from(\n * authorization,\n * { signature: signatureEnvelope }, // [!code focus]\n * )\n * ```\n *\n * @param authorization - An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) AA Authorization tuple in object format.\n * @param options - AA Authorization options.\n * @returns The {@link ox#AuthorizationTempo.AuthorizationTempo}.\n */\nexport function from<\n const authorization extends AuthorizationTempo | Rpc,\n const signature extends SignatureEnvelope.from.Value | undefined = undefined,\n>(\n authorization: authorization | AuthorizationTempo,\n options: from.Options<signature> = {},\n): from.ReturnType<authorization, signature> {\n if (typeof authorization.chainId === 'string')\n return fromRpc(authorization as Rpc) as never\n const resolved = {\n ...authorization,\n address: TempoAddress.resolve(\n authorization.address as TempoAddress.Address,\n ),\n }\n if (options.signature) {\n return { ...resolved, signature: options.signature } as never\n }\n return resolved as never\n}\n\nexport declare namespace from {\n type Options<\n signature extends SignatureEnvelope.from.Value | undefined =\n | SignatureEnvelope.from.Value\n | undefined,\n > = {\n /** The {@link ox#SignatureEnvelope.SignatureEnvelope} to attach to the AA Authorization. */\n signature?: signature | SignatureEnvelope.SignatureEnvelope | undefined\n }\n\n type ReturnType<\n authorization extends AuthorizationTempo | Rpc = AuthorizationTempo,\n signature extends SignatureEnvelope.from.Value | undefined =\n | SignatureEnvelope.from.Value\n | undefined,\n > = Compute<\n authorization extends Rpc\n ? Signed\n : authorization &\n (signature extends SignatureEnvelope.from.Value\n ? { signature: SignatureEnvelope.from.ReturnValue<signature> }\n : {})\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.Rpc} to an {@link ox#AuthorizationTempo.AuthorizationTempo}.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization = AuthorizationTempo.fromRpc({\n * address: 'tempox0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * signature: {\n * type: 'secp256k1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * },\n * })\n * ```\n *\n * @param authorization - The RPC-formatted AA Authorization.\n * @returns A signed {@link ox#AuthorizationTempo.AuthorizationTempo}.\n */\nexport function fromRpc(authorization: Rpc): Signed {\n const { address, chainId, nonce } = authorization\n const signature = SignatureEnvelope.fromRpc(authorization.signature)\n return {\n address,\n chainId: Number(chainId),\n nonce: BigInt(nonce),\n signature,\n } as never\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.ListRpc} to an {@link ox#AuthorizationTempo.List}.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorizationList = AuthorizationTempo.fromRpcList([{\n * address: 'tempox0x0000000000000000000000000000000000000000',\n * chainId: '0x1',\n * nonce: '0x1',\n * signature: {\n * type: 'secp256k1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * },\n * }])\n * ```\n *\n * @param authorizationList - The RPC-formatted AA Authorization list.\n * @returns A signed {@link ox#AuthorizationTempo.List}.\n */\nexport function fromRpcList(authorizationList: ListRpc): ListSigned {\n return authorizationList.map((x) => fromRpc(x as unknown as Rpc))\n}\n\nexport declare namespace fromRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.Tuple} to an {@link ox#AuthorizationTempo.AuthorizationTempo}.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization = AuthorizationTempo.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3'\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: }\n * ```\n *\n * @example\n * It is also possible to append a serialized SignatureEnvelope to the end of an AA Authorization tuple.\n *\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization = AuthorizationTempo.fromTuple([\n * '0x1',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x3',\n * '0x01a068a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b907e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064',\n * ])\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n\n * // @log: signature: {\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: }\n * ```\n *\n * @param tuple - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) AA Authorization tuple.\n * @returns The {@link ox#AuthorizationTempo.AuthorizationTempo}.\n */\nexport function fromTuple<const tuple extends Tuple>(\n tuple: tuple,\n): fromTuple.ReturnType<tuple> {\n const [chainId, address, nonce, signatureSerialized] = tuple\n const args: AuthorizationTempo = {\n address,\n chainId: chainId === '0x' ? 0 : Number(chainId),\n nonce: nonce === '0x' ? 0n : BigInt(nonce),\n }\n if (signatureSerialized)\n args.signature = SignatureEnvelope.deserialize(signatureSerialized)\n return from(args) as never\n}\n\nexport declare namespace fromTuple {\n type ReturnType<authorization extends Tuple = Tuple> = Compute<\n AuthorizationTempo<authorization extends Tuple<true> ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.TupleList} to an {@link ox#AuthorizationTempo.List}.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorizationList = AuthorizationTempo.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: },\n * // @log: ]\n * ```\n *\n * @example\n * It is also possible to append a serialized SignatureEnvelope to the end of an AA Authorization tuple.\n *\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorizationList = AuthorizationTempo.fromTupleList([\n * ['0x1', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x3', '0x01a068a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b907e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ['0x3', '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c', '0x14', '0x01a068a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b907e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 1,\n * // @log: nonce: 3n,\n * // @log: signature: {\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: },\n * // @log: {\n * // @log: address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: signature: {\n * // @log: r: BigInt('0x68a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b90'),\n * // @log: s: BigInt('0x7e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064'),\n * // @log: yParity: 0,\n * // @log: },\n * // @log: },\n * // @log: ]\n * ```\n *\n * @param tupleList - The [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) AA Authorization tuple list.\n * @returns An {@link ox#AuthorizationTempo.List}.\n */\nexport function fromTupleList<const tupleList extends TupleList>(\n tupleList: tupleList,\n): fromTupleList.ReturnType<tupleList> {\n const list: Mutable<List> = []\n for (const tuple of tupleList) list.push(fromTuple(tuple))\n return list as never\n}\n\nexport declare namespace fromTupleList {\n type ReturnType<tupleList extends TupleList> = Compute<\n TupleList<tupleList extends TupleList<true> ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the sign payload for an {@link ox#AuthorizationTempo.AuthorizationTempo} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * ### Secp256k1\n *\n * Standard Ethereum ECDSA signature using the secp256k1 curve.\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const payload = AuthorizationTempo.getSignPayload(authorization) // [!code focus]\n *\n * const signature = Secp256k1.sign({ payload, privateKey })\n * const authorization_signed = AuthorizationTempo.from(\n * authorization,\n * { signature }\n * )\n * ```\n *\n * @example\n * ### P256\n *\n * ECDSA signature using the P-256 (secp256r1) curve. Requires embedding the\n * public key and a `prehash` flag indicating whether the payload was hashed\n * before signing.\n *\n * ```ts twoslash\n * import { P256 } from 'ox'\n * import { AuthorizationTempo, SignatureEnvelope } from 'ox/tempo'\n *\n * const { privateKey, publicKey } = P256.createKeyPair()\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const payload = AuthorizationTempo.getSignPayload(authorization) // [!code focus]\n *\n * const signature = P256.sign({ payload, privateKey })\n * const signatureEnvelope = SignatureEnvelope.from({\n * prehash: false,\n * publicKey,\n * signature,\n * })\n * const authorization_signed = AuthorizationTempo.from(\n * authorization,\n * { signature: signatureEnvelope }\n * )\n * ```\n *\n * @example\n * ### P256 (WebCrypto)\n *\n * When using WebCrypto keys, `prehash` must be `true` since WebCrypto always\n * hashes the payload internally before signing.\n *\n * ```ts twoslash\n * // @noErrors\n * import { WebCryptoP256 } from 'ox'\n * import { AuthorizationTempo, SignatureEnvelope } from 'ox/tempo'\n *\n * const { privateKey, publicKey } = await WebCryptoP256.createKeyPair()\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const payload = AuthorizationTempo.getSignPayload(authorization) // [!code focus]\n *\n * const signature = await WebCryptoP256.sign({ payload, privateKey })\n * const signatureEnvelope = SignatureEnvelope.from({\n * prehash: true,\n * publicKey,\n * signature,\n * })\n * const authorization_signed = AuthorizationTempo.from(\n * authorization,\n * { signature: signatureEnvelope }\n * )\n * ```\n *\n * @example\n * ### WebAuthn\n *\n * Passkey-based signature using WebAuthn. Includes authenticator metadata\n * (authenticatorData and clientDataJSON) along with the P-256 signature and\n * public key.\n *\n * ```ts twoslash\n * // @noErrors\n * import { WebAuthnP256 } from 'ox'\n * import { AuthorizationTempo, SignatureEnvelope } from 'ox/tempo'\n *\n * const credential = await WebAuthnP256.createCredential({ name: 'Example' })\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const challenge = AuthorizationTempo.getSignPayload(authorization) // [!code focus]\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * challenge,\n * credentialId: credential.id,\n * })\n * const signatureEnvelope = SignatureEnvelope.from({\n * signature,\n * publicKey: credential.publicKey,\n * metadata,\n * })\n * const authorization_signed = AuthorizationTempo.from(\n * authorization,\n * { signature: signatureEnvelope }\n * )\n * ```\n *\n * @param authorization - The {@link ox#AuthorizationTempo.AuthorizationTempo}.\n * @returns The sign payload.\n */\nexport function getSignPayload(authorization: AuthorizationTempo): Hex.Hex {\n return hash(authorization, { presign: true })\n}\n\nexport declare namespace getSignPayload {\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Computes the hash for an {@link ox#AuthorizationTempo.AuthorizationTempo} in [EIP-7702 format](https://eips.ethereum.org/EIPS/eip-7702): `keccak256('0x05' || rlp([chain_id, address, nonce]))`.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const hash = AuthorizationTempo.hash(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#AuthorizationTempo.AuthorizationTempo}.\n * @returns The hash.\n */\nexport function hash(\n authorization: AuthorizationTempo,\n options: hash.Options = {},\n): Hex.Hex {\n const { presign } = options\n return Hash.keccak256(\n Hex.concat(\n '0x05',\n Rlp.fromHex(\n toTuple(\n presign\n ? {\n address: authorization.address,\n chainId: authorization.chainId,\n nonce: authorization.nonce,\n }\n : authorization,\n ),\n ),\n ),\n )\n}\n\nexport declare namespace hash {\n type ErrorType =\n | toTuple.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.concat.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n\n type Options = {\n /** Whether to hash this authorization for signing. @default false */\n presign?: boolean | undefined\n }\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.AuthorizationTempo} to an {@link ox#AuthorizationTempo.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization = AuthorizationTempo.toRpc({\n * address: 'tempox0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * signature: {\n * type: 'secp256k1',\n * signature: {\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * },\n * },\n * })\n * ```\n *\n * @param authorization - An AA Authorization.\n * @returns An RPC-formatted AA Authorization.\n */\nexport function toRpc(authorization: Signed): Rpc {\n const { address, chainId, nonce, signature } = authorization\n\n return {\n address,\n chainId: Hex.fromNumber(chainId),\n nonce: Hex.fromNumber(nonce),\n signature: SignatureEnvelope.toRpc(signature),\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.List} to an {@link ox#AuthorizationTempo.ListRpc}.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization = AuthorizationTempo.toRpcList([{\n * address: 'tempox0x0000000000000000000000000000000000000000',\n * chainId: 1,\n * nonce: 1n,\n * signature: {\n * type: 'secp256k1',\n * signature: {\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * },\n * },\n * }])\n * ```\n *\n * @param authorizationList - An AA Authorization List.\n * @returns An RPC-formatted AA Authorization List.\n */\nexport function toRpcList(authorizationList: ListSigned): ListRpc {\n return authorizationList.map((x) => toRpc(x as unknown as Signed)) as never\n}\n\nexport declare namespace toRpcList {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.AuthorizationTempo} to an {@link ox#AuthorizationTempo.Tuple}.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n *\n * const tuple = AuthorizationTempo.toTuple(authorization) // [!code focus]\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ]\n * ```\n *\n * @param authorization - The {@link ox#AuthorizationTempo.AuthorizationTempo}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) AA Authorization tuple.\n */\nexport function toTuple<const authorization extends AuthorizationTempo>(\n authorization: authorization,\n): toTuple.ReturnType<authorization> {\n const { address, chainId, nonce } = authorization\n const signature = authorization.signature\n ? SignatureEnvelope.serialize(authorization.signature)\n : undefined\n return [\n chainId ? Hex.fromNumber(chainId) : '0x',\n address,\n nonce ? Hex.fromNumber(nonce) : '0x',\n ...(signature ? [signature] : []),\n ] as never\n}\n\nexport declare namespace toTuple {\n type ReturnType<\n authorization extends AuthorizationTempo = AuthorizationTempo,\n > = Compute<\n Tuple<authorization extends AuthorizationTempo<true> ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.List} to an {@link ox#AuthorizationTempo.TupleList}.\n *\n * @example\n * ```ts twoslash\n * import { AuthorizationTempo } from 'ox/tempo'\n *\n * const authorization_1 = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 1,\n * nonce: 69n,\n * })\n * const authorization_2 = AuthorizationTempo.from({\n * address: 'tempox0x1234567890abcdef1234567890abcdef12345678',\n * chainId: 3,\n * nonce: 20n,\n * })\n *\n * const tuple = AuthorizationTempo.toTupleList([authorization_1, authorization_2]) // [!code focus]\n * // @log: [\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 1,\n * // @log: nonce: 69n,\n * // @log: ],\n * // @log: [\n * // @log: address: '0x1234567890abcdef1234567890abcdef12345678',\n * // @log: chainId: 3,\n * // @log: nonce: 20n,\n * // @log: ],\n * // @log: ]\n * ```\n *\n * @param list - An {@link ox#AuthorizationTempo.List}.\n * @returns An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) AA Authorization tuple list.\n */\nexport function toTupleList<\n const list extends\n | readonly AuthorizationTempo<true>[]\n | readonly AuthorizationTempo<false>[],\n>(list?: list | undefined): toTupleList.ReturnType<list> {\n if (!list || list.length === 0) return []\n\n const tupleList: Mutable<TupleList> = []\n for (const authorization of list) tupleList.push(toTuple(authorization))\n\n return tupleList as never\n}\n\nexport declare namespace toTupleList {\n type ReturnType<\n list extends\n | readonly AuthorizationTempo<true>[]\n | readonly AuthorizationTempo<false>[],\n > = Compute<\n TupleList<list extends readonly AuthorizationTempo<true>[] ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n","import type * as Address from '../core/Address.js'\nimport type * as Errors from '../core/Errors.js'\nimport * as Hash from '../core/Hash.js'\nimport * as Hex from '../core/Hex.js'\nimport type { Compute } from '../core/internal/types.js'\nimport * as Rlp from '../core/Rlp.js'\nimport * as SignatureEnvelope from './SignatureEnvelope.js'\nimport * as TempoAddress from './TempoAddress.js'\n\n/**\n * Key authorization for provisioning access keys.\n *\n * Access keys allow a root key (e.g., a passkey) to delegate transaction signing to secondary\n * keys with customizable permissions including expiry timestamps and per-TIP-20 token spending\n * limits. This enables a user to sign transactions without repeated passkey prompts.\n *\n * The root key signs a `KeyAuthorization` to grant an access key permission to sign transactions\n * on its behalf. The authorization is attached to a transaction (which can be signed by the access\n * key itself), and the protocol validates the authorization before storing the key in the\n * AccountKeychain precompile.\n *\n * Key authorization fields:\n * - `address`: Address derived from the access key's public key (the \"key ID\")\n * - `chainId`: Chain ID for replay protection (0 = valid on any chain)\n * - `expiry`: Unix timestamp when the key expires (undefined = never expires)\n * - `limits`: Per-TIP-20 token spending limits (only applies to `transfer()` and `approve()` calls)\n * - `type`: Key type (`secp256k1`, `p256`, or `webAuthn`)\n *\n * [Access Keys Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#access-keys)\n */\nexport type KeyAuthorization<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = {\n /** Address derived from the public key of the key type. */\n address: TempoAddress.Address\n /** Chain ID for replay protection. */\n chainId: bigintType\n /** Unix timestamp when key expires (0 = never expires). */\n expiry?: numberType | null | undefined\n /** TIP20 spending limits for this key. */\n limits?: readonly TokenLimit<bigintType>[] | undefined\n /** Key type. (secp256k1, P256, WebAuthn). */\n type: SignatureEnvelope.Type\n} & (signed extends true\n ? { signature: SignatureEnvelope.SignatureEnvelope<bigintType, numberType> }\n : {\n signature?:\n | SignatureEnvelope.SignatureEnvelope<bigintType, numberType>\n | undefined\n })\n\n/** RPC representation of an {@link ox#KeyAuthorization.KeyAuthorization}. */\nexport type Rpc = Omit<\n KeyAuthorization<false, Hex.Hex, Hex.Hex>,\n 'address' | 'signature' | 'type'\n> & {\n keyId: Address.Address\n keyType: SignatureEnvelope.Type\n signature: SignatureEnvelope.SignatureEnvelopeRpc\n}\n\n/** Signed representation of a Key Authorization. */\nexport type Signed<bigintType = bigint, numberType = number> = KeyAuthorization<\n true,\n bigintType,\n numberType\n>\n\ntype BaseTuple = readonly [\n chainId: Hex.Hex,\n keyType: Hex.Hex,\n keyId: Address.Address,\n]\n\n/** Tuple representation of a Key Authorization. */\nexport type Tuple<signed extends boolean = boolean> = signed extends true\n ? readonly [\n authorization:\n | BaseTuple\n | readonly [...BaseTuple, expiry: Hex.Hex]\n | readonly [\n ...BaseTuple,\n expiry: Hex.Hex,\n limits: readonly [token: Address.Address, limit: Hex.Hex][],\n ],\n signature: Hex.Hex,\n ]\n : readonly [\n authorization:\n | BaseTuple\n | readonly [...BaseTuple, expiry: Hex.Hex]\n | readonly [\n ...BaseTuple,\n expiry: Hex.Hex,\n limits: readonly [token: Address.Address, limit: Hex.Hex][],\n ],\n ]\n\n/**\n * Token spending limit for access keys.\n *\n * Defines a per-TIP-20 token spending limit for an access key. Limits deplete as tokens\n * are spent and can be updated by the root key via `updateSpendingLimit()`.\n *\n * [Access Keys Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#access-keys)\n */\nexport type TokenLimit<bigintType = bigint> = {\n /** Address of the TIP-20 token. */\n token: TempoAddress.Address\n /** Maximum spending amount for this token (enforced over the key's lifetime). */\n limit: bigintType\n}\n\n/**\n * Converts a Key Authorization object into a typed {@link ox#KeyAuthorization.KeyAuthorization}.\n *\n * Use this to create an unsigned key authorization, then sign it with the root key using\n * {@link ox#KeyAuthorization.(getSignPayload:function)} and attach the signature. The signed authorization\n * can be included in a {@link ox#TxEnvelopeTempo.TxEnvelopeTempo} via the\n * `keyAuthorization` field to provision the access key on-chain.\n *\n * [Access Keys Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#access-keys)\n *\n * @example\n * ### Secp256k1 Key\n *\n * Standard Ethereum ECDSA key using the secp256k1 curve.\n *\n * ```ts twoslash\n * import { Address, Secp256k1, Value } from 'ox'\n * import { KeyAuthorization } from 'ox/tempo'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * const address = Address.fromPublicKey(Secp256k1.getPublicKey({ privateKey }))\n *\n * const authorization = KeyAuthorization.from({\n * address,\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'secp256k1',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6),\n * }],\n * })\n * ```\n *\n * @example\n * ### WebCryptoP256 Key\n *\n * ```ts twoslash\n * import { Address, WebCryptoP256, Value } from 'ox'\n * import { KeyAuthorization } from 'ox/tempo'\n *\n * const keyPair = await WebCryptoP256.createKeyPair()\n * const address = Address.fromPublicKey(keyPair.publicKey)\n *\n * const authorization = KeyAuthorization.from({\n * address,\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'p256',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6),\n * }],\n * })\n * ```\n *\n * @example\n * ### Attaching Signatures (Secp256k1)\n *\n * Attach a signature to a Key Authorization using a Secp256k1 private key to\n * authorize another Secp256k1 key on the account.\n *\n * ```ts twoslash\n * import { Address, Secp256k1, Value } from 'ox'\n * import { KeyAuthorization } from 'ox/tempo'\n *\n * const privateKey = '0x...'\n * const address = Address.fromPublicKey(Secp256k1.getPublicKey({ privateKey }))\n *\n * const authorization = KeyAuthorization.from({\n * address,\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'secp256k1',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6),\n * }],\n * })\n *\n * const rootPrivateKey = '0x...'\n * const signature = Secp256k1.sign({\n * payload: KeyAuthorization.getSignPayload(authorization),\n * privateKey: rootPrivateKey,\n * })\n *\n * const authorization_signed = KeyAuthorization.from(authorization, { signature })\n * ```\n *\n * @example\n * ### Attaching Signatures (WebAuthn)\n *\n * Attach a signature to a Key Authorization using a WebAuthn credential to\n * authorize a new WebCryptoP256 key on the account.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Address, Value, WebCryptoP256, WebAuthnP256 } from 'ox'\n * import { KeyAuthorization, SignatureEnvelope } from 'ox/tempo'\n *\n * const keyPair = await WebCryptoP256.createKeyPair()\n * const address = Address.fromPublicKey(keyPair.publicKey)\n *\n * const authorization = KeyAuthorization.from({\n * address,\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'p256',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6),\n * }],\n * })\n *\n * const credential = await WebAuthnP256.createCredential({ name: 'Example' })\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * challenge: KeyAuthorization.getSignPayload(authorization),\n * credentialId: credential.id,\n * })\n *\n * const signatureEnvelope = SignatureEnvelope.from({ // [!code focus]\n * signature, // [!code focus]\n * publicKey: credential.publicKey, // [!code focus]\n * metadata, // [!code focus]\n * })\n * const authorization_signed = KeyAuthorization.from(\n * authorization,\n * { signature: signatureEnvelope }, // [!code focus]\n * )\n * ```\n *\n * @param authorization - A Key Authorization tuple in object format.\n * @param options - Key Authorization options.\n * @returns The {@link ox#KeyAuthorization.KeyAuthorization}.\n */\nexport function from<\n const authorization extends KeyAuthorization | Rpc,\n const signature extends SignatureEnvelope.from.Value | undefined = undefined,\n>(\n authorization: authorization | KeyAuthorization,\n options: from.Options<signature> = {},\n): from.ReturnType<authorization, signature> {\n if ('keyId' in authorization) return fromRpc(authorization as Rpc) as never\n const auth = authorization as KeyAuthorization & {\n limits?: readonly { token: TempoAddress.Address; limit: bigint }[]\n }\n const resolved = {\n ...auth,\n address: TempoAddress.resolve(auth.address as TempoAddress.Address),\n ...(auth.limits\n ? {\n limits: auth.limits.map((l) => ({\n ...l,\n token: TempoAddress.resolve(l.token as TempoAddress.Address),\n })),\n }\n : {}),\n }\n if (options.signature)\n return {\n ...resolved,\n signature: SignatureEnvelope.from(options.signature),\n } as never\n return resolved as never\n}\n\nexport declare namespace from {\n type Options<\n signature extends SignatureEnvelope.from.Value | undefined =\n | SignatureEnvelope.from.Value\n | undefined,\n > = {\n /** The {@link ox#SignatureEnvelope.SignatureEnvelope} to attach to the Key Authorization. */\n signature?: signature | SignatureEnvelope.SignatureEnvelope | undefined\n }\n\n type ReturnType<\n authorization extends KeyAuthorization | Rpc = KeyAuthorization,\n signature extends SignatureEnvelope.from.Value | undefined =\n | SignatureEnvelope.from.Value\n | undefined,\n > = Compute<\n authorization extends Rpc\n ? Signed\n : authorization &\n (signature extends SignatureEnvelope.from.Value\n ? { signature: SignatureEnvelope.from.ReturnValue<signature> }\n : {})\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#AuthorizationTempo.Rpc} to an {@link ox#AuthorizationTempo.AuthorizationTempo}.\n *\n * @example\n * ```ts twoslash\n * import { KeyAuthorization } from 'ox/tempo'\n *\n * const keyAuthorization = KeyAuthorization.fromRpc({\n * chainId: '0x1079',\n * expiry: '0x174876e800',\n * keyId: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * keyType: 'secp256k1',\n * limits: [{ token: '0x20c0000000000000000000000000000000000001', limit: '0xf4240' }],\n * signature: {\n * type: 'secp256k1',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0'\n * },\n * })\n * ```\n *\n * @param authorization - The RPC-formatted Key Authorization.\n * @returns A signed {@link ox#AuthorizationTempo.AuthorizationTempo}.\n */\nexport function fromRpc(authorization: Rpc): Signed {\n const { chainId, keyId, expiry = 0, limits, keyType } = authorization\n const signature = SignatureEnvelope.fromRpc(authorization.signature)\n return {\n address: keyId,\n chainId: chainId === '0x' ? 0n : Hex.toBigInt(chainId),\n expiry: Number(expiry),\n limits: limits?.map((limit) => ({\n token: limit.token,\n limit: BigInt(limit.limit),\n })),\n signature,\n type: keyType,\n }\n}\n\nexport declare namespace fromRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#KeyAuthorization.Tuple} to an {@link ox#KeyAuthorization.KeyAuthorization}.\n *\n * @example\n * ```ts twoslash\n * import { KeyAuthorization } from 'ox/tempo'\n *\n * const authorization = KeyAuthorization.fromTuple([\n * [\n * '0x',\n * '0x00',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x174876e800',\n * [['0x20c0000000000000000000000000000000000001', '0xf4240']],\n * ],\n * '0x01a068a020a209d3d56c46f38cc50a33f704f4a9a10a59377f8dd762ac66910e9b907e865ad05c4035ab5792787d4a0297a43617ae897930a6fe4d822b8faea52064',\n * ])\n * ```\n *\n * @example\n * Unsigned Key Authorization tuple (no signature):\n *\n * ```ts twoslash\n * import { KeyAuthorization } from 'ox/tempo'\n *\n * const authorization = KeyAuthorization.fromTuple([\n * [\n * '0x',\n * '0x00',\n * '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * '0x174876e800',\n * [['0x20c0000000000000000000000000000000000001', '0xf4240']],\n * ],\n * ])\n * ```\n *\n * @param tuple - The Key Authorization tuple.\n * @returns The {@link ox#KeyAuthorization.KeyAuthorization}.\n */\nexport function fromTuple<const tuple extends Tuple>(\n tuple: tuple,\n): fromTuple.ReturnType<tuple> {\n const [authorization, signatureSerialized] = tuple\n const [chainId, keyType_hex, keyId, expiry, limits] = authorization\n const keyType = (() => {\n switch (keyType_hex) {\n case '0x':\n case '0x00':\n return 'secp256k1'\n case '0x01':\n return 'p256'\n case '0x02':\n return 'webAuthn'\n default:\n throw new Error(`Invalid key type: ${keyType_hex}`)\n }\n })()\n const args: KeyAuthorization = {\n address: keyId,\n expiry: typeof expiry !== 'undefined' ? hexToNumber(expiry) : undefined,\n type: keyType,\n chainId: chainId === '0x' ? 0n : Hex.toBigInt(chainId),\n ...(typeof expiry !== 'undefined' ? { expiry: hexToNumber(expiry) } : {}),\n ...(typeof limits !== 'undefined'\n ? {\n limits: limits.map(([token, limit]) => ({\n token,\n limit: hexToBigint(limit),\n })),\n }\n : {}),\n }\n if (signatureSerialized)\n args.signature = SignatureEnvelope.deserialize(signatureSerialized)\n return from(args) as never\n}\n\nexport declare namespace fromTuple {\n type ReturnType<authorization extends Tuple = Tuple> = Compute<\n KeyAuthorization<authorization extends Tuple<true> ? true : false>\n >\n\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Computes the sign payload for an {@link ox#KeyAuthorization.KeyAuthorization}.\n *\n * The root key must sign this payload to authorize the access key. The resulting signature\n * is attached to the key authorization via {@link ox#KeyAuthorization.(from:function)} with the\n * `signature` option.\n *\n * [Access Keys Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#access-keys)\n *\n * @example\n * ```ts twoslash\n * import { Address, Secp256k1, Value } from 'ox'\n * import { KeyAuthorization } from 'ox/tempo'\n *\n * const privateKey = '0x...'\n * const address = Address.fromPublicKey(Secp256k1.getPublicKey({ privateKey }))\n *\n * const authorization = KeyAuthorization.from({\n * address,\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'secp256k1',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6),\n * }],\n * })\n *\n * const payload = KeyAuthorization.getSignPayload(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#KeyAuthorization.KeyAuthorization}.\n * @returns The sign payload.\n */\nexport function getSignPayload(authorization: KeyAuthorization): Hex.Hex {\n return hash(authorization)\n}\n\nexport declare namespace getSignPayload {\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes an RLP-encoded {@link ox#KeyAuthorization.KeyAuthorization}.\n *\n * @example\n * ```ts twoslash\n * import { KeyAuthorization } from 'ox/tempo'\n * import { Value } from 'ox'\n *\n * const authorization = KeyAuthorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'secp256k1',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6)\n * }],\n * })\n *\n * const serialized = KeyAuthorization.serialize(authorization)\n * const deserialized = KeyAuthorization.deserialize(serialized) // [!code focus]\n * ```\n *\n * @param serialized - The RLP-encoded Key Authorization.\n * @returns The {@link ox#KeyAuthorization.KeyAuthorization}.\n */\nexport function deserialize(serialized: Hex.Hex): KeyAuthorization {\n const tuple = Rlp.toHex(serialized) as unknown as Tuple\n return fromTuple(tuple)\n}\n\nexport declare namespace deserialize {\n type ErrorType =\n | Rlp.toHex.ErrorType\n | fromTuple.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Computes the hash for an {@link ox#KeyAuthorization.KeyAuthorization}.\n *\n * @example\n * ```ts twoslash\n * import { KeyAuthorization } from 'ox/tempo'\n * import { Value } from 'ox'\n *\n * const authorization = KeyAuthorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'secp256k1',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6)\n * }],\n * })\n *\n * const hash = KeyAuthorization.hash(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#KeyAuthorization.KeyAuthorization}.\n * @returns The hash.\n */\nexport function hash(authorization: KeyAuthorization): Hex.Hex {\n const [authorizationTuple] = toTuple(authorization)\n const serialized = Rlp.fromHex(authorizationTuple)\n return Hash.keccak256(serialized)\n}\n\nexport declare namespace hash {\n type ErrorType =\n | toTuple.ErrorType\n | Hash.keccak256.ErrorType\n | Hex.concat.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#KeyAuthorization.KeyAuthorization} to RLP-encoded hex.\n *\n * @example\n * ```ts twoslash\n * import { KeyAuthorization } from 'ox/tempo'\n * import { Value } from 'ox'\n *\n * const authorization = KeyAuthorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'secp256k1',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6)\n * }],\n * })\n *\n * const serialized = KeyAuthorization.serialize(authorization) // [!code focus]\n * ```\n *\n * @param authorization - The {@link ox#KeyAuthorization.KeyAuthorization}.\n * @returns The RLP-encoded Key Authorization.\n */\nexport function serialize(authorization: KeyAuthorization): Hex.Hex {\n const tuple = toTuple(authorization)\n return Rlp.fromHex(tuple as any)\n}\n\nexport declare namespace serialize {\n type ErrorType =\n | toTuple.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#KeyAuthorization.KeyAuthorization} to an {@link ox#KeyAuthorization.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { KeyAuthorization } from 'ox/tempo'\n * import { Value } from 'ox'\n *\n * const authorization = KeyAuthorization.toRpc({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'secp256k1',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6)\n * }],\n * signature: {\n * type: 'secp256k1',\n * signature: {\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * },\n * },\n * })\n * ```\n *\n * @param authorization - A Key Authorization.\n * @returns An RPC-formatted Key Authorization.\n */\nexport function toRpc(authorization: Signed): Rpc {\n const { address, chainId, expiry, limits, type, signature } = authorization\n\n return {\n chainId: chainId === 0n ? '0x' : Hex.fromNumber(chainId),\n expiry: typeof expiry === 'number' ? Hex.fromNumber(expiry) : null,\n limits: limits?.map(({ token, limit }) => ({\n token,\n limit: Hex.fromNumber(limit),\n })),\n keyId: TempoAddress.resolve(address),\n signature: SignatureEnvelope.toRpc(signature),\n keyType: type,\n }\n}\n\nexport declare namespace toRpc {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#KeyAuthorization.KeyAuthorization} to an {@link ox#KeyAuthorization.Tuple}.\n *\n * @example\n * ```ts twoslash\n * import { KeyAuthorization } from 'ox/tempo'\n * import { Value } from 'ox'\n *\n * const authorization = KeyAuthorization.from({\n * address: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * chainId: 4217n,\n * expiry: 1234567890,\n * type: 'secp256k1',\n * limits: [{\n * token: '0x20c0000000000000000000000000000000000001',\n * limit: Value.from('10', 6)\n * }],\n * })\n *\n * const tuple = KeyAuthorization.toTuple(authorization) // [!code focus]\n * // @log: [\n * // @log: '0x174876e800',\n * // @log: [['0x20c0000000000000000000000000000000000001', '0xf4240']],\n * // @log: '0xbe95c3f554e9fc85ec51be69a3d807a0d55bcf2c',\n * // @log: 'secp256k1',\n * // @log: ]\n * ```\n *\n * @param authorization - The {@link ox#KeyAuthorization.KeyAuthorization}.\n * @returns A Tempo Key Authorization tuple.\n */\nexport function toTuple<const authorization extends KeyAuthorization>(\n authorization: authorization,\n): toTuple.ReturnType<authorization> {\n const { address, chainId, expiry, limits } = authorization\n const signature = authorization.signature\n ? SignatureEnvelope.serialize(authorization.signature)\n : undefined\n const type = (() => {\n switch (authorization.type) {\n case 'secp256k1':\n return '0x'\n case 'p256':\n return '0x01'\n case 'webAuthn':\n return '0x02'\n default:\n throw new Error(`Invalid key type: ${authorization.type}`)\n }\n })()\n const limitsValue = limits?.map((limit) => [\n limit.token,\n bigintToHex(limit.limit),\n ])\n const authorizationTuple = [\n bigintToHex(chainId),\n type,\n address,\n // expiry is required in the tuple when limits are present\n typeof expiry === 'number' || limitsValue\n ? numberToHex(expiry ?? 0)\n : undefined,\n limitsValue,\n ].filter(Boolean)\n return [authorizationTuple, ...(signature ? [signature] : [])] as never\n}\n\nexport declare namespace toTuple {\n type ReturnType<authorization extends KeyAuthorization = KeyAuthorization> =\n Compute<Tuple<authorization extends KeyAuthorization<true> ? true : false>>\n\n type ErrorType = Errors.GlobalErrorType\n}\n\nfunction bigintToHex(value: bigint): Hex.Hex {\n return value === 0n ? '0x' : Hex.fromNumber(value)\n}\n\nfunction numberToHex(value: number): Hex.Hex {\n return value === 0 ? '0x' : Hex.fromNumber(value)\n}\n\nfunction hexToBigint(hex: Hex.Hex): bigint {\n return hex === '0x' ? 0n : BigInt(hex)\n}\n\nfunction hexToNumber(hex: Hex.Hex): number {\n return hex === '0x' ? 0 : Hex.toNumber(hex)\n}\n","import * as Hash from '../core/Hash.js'\nimport * as Hex from '../core/Hex.js'\nimport * as TokenId from './TokenId.js'\n\n/**\n * Converts a user token and validator token to a pool ID.\n *\n * Pool IDs are deterministic keys derived from two token addresses (order-independent)\n * used to identify trading pairs on Tempo's enshrined stablecoin DEX.\n *\n * [Stablecoin DEX Specification](https://docs.tempo.xyz/protocol/exchange/spec)\n *\n * @example\n * ```ts twoslash\n * import { PoolId } from 'ox/tempo'\n *\n * const poolId = PoolId.from({\n * userToken: 1n,\n * validatorToken: 2n,\n * })\n * ```\n *\n * @param value - User token and validator token.\n * @returns The pool ID.\n */\nexport function from(value: from.Value): Hex.Hex {\n return Hash.keccak256(\n Hex.concat(\n Hex.padLeft(TokenId.toAddress(value.userToken), 32),\n Hex.padLeft(TokenId.toAddress(value.validatorToken), 32),\n ),\n )\n}\n\nexport declare namespace from {\n export type Value = {\n /** User token. */\n userToken: TokenId.TokenIdOrAddress\n /** Validator token. */\n validatorToken: TokenId.TokenIdOrAddress\n }\n}\n","import * as AbiParameters from '../core/AbiParameters.js'\nimport * as Address from '../core/Address.js'\nimport * as Hash from '../core/Hash.js'\nimport * as Hex from '../core/Hex.js'\nimport * as TempoAddress from './TempoAddress.js'\n\nconst tip20Prefix = '0x20c0'\n\nexport type TokenId = bigint\nexport type TokenIdOrAddress = TokenId | TempoAddress.Address\n\n/**\n * Converts a token ID or address to a token ID.\n *\n * TIP-20 is Tempo's native token standard for stablecoins with deterministic addresses\n * derived from sequential token IDs (prefix `0x20c0`).\n *\n * [TIP-20 Token Standard](https://docs.tempo.xyz/protocol/tip20/overview)\n *\n * @example\n * ```ts twoslash\n * import { TokenId } from 'ox/tempo'\n *\n * const tokenId = TokenId.from(1n)\n * ```\n *\n * @param tokenIdOrAddress - The token ID or address.\n * @returns The token ID.\n */\nexport function from(tokenIdOrAddress: TokenIdOrAddress | number): TokenId {\n if (\n typeof tokenIdOrAddress === 'bigint' ||\n typeof tokenIdOrAddress === 'number'\n )\n return BigInt(tokenIdOrAddress)\n return fromAddress(tokenIdOrAddress)\n}\n\n/**\n * Converts a TIP-20 token address to a token ID.\n *\n * [TIP-20 Token Standard](https://docs.tempo.xyz/protocol/tip20/overview)\n *\n * @example\n * ```ts twoslash\n * import { TokenId } from 'ox/tempo'\n *\n * const tokenId = TokenId.fromAddress('0x20c0000000000000000000000000000000000001')\n * ```\n *\n * @param address - The token address.\n * @returns The token ID.\n */\nexport function fromAddress(address: TempoAddress.Address): TokenId {\n const resolved = TempoAddress.resolve(address)\n if (!resolved.toLowerCase().startsWith(tip20Prefix))\n throw new Error('invalid tip20 address.')\n return Hex.toBigInt(Hex.slice(resolved, tip20Prefix.length))\n}\n\n/**\n * Converts a TIP-20 token ID to an address.\n *\n * [TIP-20 Token Standard](https://docs.tempo.xyz/protocol/tip20/overview)\n *\n * @example\n * ```ts twoslash\n * import { TokenId } from 'ox/tempo'\n *\n * const address = TokenId.toAddress(1n)\n * ```\n *\n * @param tokenId - The token ID.\n * @returns The address.\n */\nexport function toAddress(tokenId: TokenIdOrAddress): Address.Address {\n if (typeof tokenId === 'string') {\n const resolved = TempoAddress.resolve(tokenId as TempoAddress.Address)\n Address.assert(resolved)\n return resolved\n }\n\n const tokenIdHex = Hex.fromNumber(tokenId, { size: 18 })\n return Hex.concat(tip20Prefix, tokenIdHex)\n}\n\n/**\n * Computes a deterministic TIP-20 token address from a sender address and salt.\n *\n * The address is computed as: `TIP20_PREFIX (12 bytes) || keccak256(abi.encode(sender, salt))[:8]`\n *\n * [TIP-20 Token Standard](https://docs.tempo.xyz/protocol/tip20/overview)\n *\n * @example\n * ```ts twoslash\n * import { TokenId } from 'ox/tempo'\n *\n * const id = TokenId.compute({\n * sender: '0x1234567890123456789012345678901234567890',\n * salt: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * })\n * ```\n *\n * @param value - The sender address and salt.\n * @returns The computed TIP-20 token id.\n */\nexport function compute(value: compute.Value): bigint {\n const hash = Hash.keccak256(\n AbiParameters.encode(AbiParameters.from('address, bytes32'), [\n TempoAddress.resolve(value.sender),\n value.salt,\n ]),\n )\n return Hex.toBigInt(Hex.slice(hash, 0, 8))\n}\n\nexport declare namespace compute {\n export type Value = {\n /** The salt (32 bytes). */\n salt: Hex.Hex\n /** The sender address. Accepts both hex and Tempo bech32m addresses. */\n sender: TempoAddress.Address\n }\n}\n","import * as Hash from '../core/Hash.js'\nimport * as Hex from '../core/Hex.js'\n\nexport const roles = [\n 'defaultAdmin',\n 'pause',\n 'unpause',\n 'issuer',\n 'burnBlocked',\n] as const\nexport type TokenRole = (typeof roles)[number]\n\nexport const toPreHashed = {\n defaultAdmin: 'DEFAULT_ADMIN_ROLE',\n pause: 'PAUSE_ROLE',\n unpause: 'UNPAUSE_ROLE',\n issuer: 'ISSUER_ROLE',\n burnBlocked: 'BURN_BLOCKED_ROLE',\n} as const satisfies Record<TokenRole, string>\n\n/**\n * Serializes a token role to its keccak256 hash representation.\n *\n * TIP-20 includes a built-in RBAC system with roles like `ISSUER_ROLE` (mint/burn),\n * `PAUSE_ROLE`/`UNPAUSE_ROLE` (emergency controls), and `BURN_BLOCKED_ROLE` (compliance).\n *\n * [TIP-20 RBAC](https://docs.tempo.xyz/protocol/tip20/overview#role-based-access-control-rbac)\n *\n * @example\n * ```ts twoslash\n * import { TokenRole } from 'ox/tempo'\n *\n * const hash = TokenRole.serialize('issuer')\n * ```\n *\n * @param role - The token role to serialize.\n * @returns The keccak256 hash of the role.\n */\nexport function serialize(role: TokenRole) {\n if (role === 'defaultAdmin')\n return '0x0000000000000000000000000000000000000000000000000000000000000000'\n return Hash.keccak256(\n Hex.fromString(toPreHashed[role as keyof typeof toPreHashed] ?? role),\n )\n}\n","import type * as AccessList from '../core/AccessList.js'\nimport type * as Address from '../core/Address.js'\nimport type * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type { Compute, OneOf, UnionCompute } from '../core/internal/types.js'\nimport * as Signature from '../core/Signature.js'\nimport * as ox_Transaction from '../core/Transaction.js'\nimport * as AuthorizationTempo from './AuthorizationTempo.js'\nimport * as KeyAuthorization from './KeyAuthorization.js'\nimport * as SignatureEnvelope from './SignatureEnvelope.js'\nimport type { Call } from './TxEnvelopeTempo.js'\n\n/**\n * A Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml).\n *\n * @see {@link https://docs.tempo.xyz/protocol/transactions}\n */\nexport type Transaction<\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n> = UnionCompute<\n OneOf<\n | Tempo<pending, bigintType, numberType>\n | ox_Transaction.Transaction<pending, bigintType, numberType>\n >\n>\n\n/**\n * An RPC Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml).\n */\nexport type Rpc<pending extends boolean = false> = UnionCompute<\n OneOf<TempoRpc<pending> | ox_Transaction.Rpc<pending>>\n>\n\n/**\n * Native account abstraction transaction (type `0x76`).\n *\n * Features configurable fee tokens, call batching, fee sponsorship, access keys,\n * parallelizable nonces, and scheduled execution via `validAfter`/`validBefore`.\n *\n * @see {@link https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction}\n */\nexport type Tempo<\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n type extends string = 'tempo',\n> = Compute<\n Omit<\n ox_Transaction.Base<type, pending, bigintType, numberType>,\n // Tempo transactions don't have these properties.\n 'input' | 'to' | 'value' | 'v' | 'r' | 's' | 'yParity'\n > & {\n /** EIP-2930 Access List. */\n accessList: AccessList.AccessList\n /** EIP-7702 Authorization list for the transaction. */\n authorizationList?:\n | AuthorizationTempo.ListSigned<bigintType, numberType>\n | undefined\n /** Array of calls to execute. */\n calls: readonly Call<bigintType>[]\n /** Fee payer signature. */\n feePayerSignature?:\n | {\n /** ECDSA signature r. */\n r: bigintType\n /** ECDSA signature s. */\n s: bigintType\n /** ECDSA signature yParity. */\n yParity: numberType\n /** @deprecated ECDSA signature v (for backwards compatibility). */\n v?: numberType | undefined\n }\n | undefined\n /** Fee token preference. */\n feeToken: Address.Address\n /** Effective gas price paid by the sender in wei. */\n gasPrice?: bigintType | undefined\n /** Key authorization for provisioning a new access key. */\n keyAuthorization?:\n | KeyAuthorization.KeyAuthorization<true, bigintType, numberType>\n | undefined\n /** Total fee per gas in wei (gasPrice/baseFeePerGas + maxPriorityFeePerGas). */\n maxFeePerGas: bigintType\n /** Max priority fee per gas (in wei). */\n maxPriorityFeePerGas: bigintType\n /** Nonce key for 2D nonce system (192 bits). */\n nonceKey?: bigintType | undefined\n /** Sender signature. */\n signature: SignatureEnvelope.SignatureEnvelope<bigintType, numberType>\n /** Transaction can only be included in a block before this timestamp. */\n validBefore?: numberType | undefined\n /** Transaction can only be included in a block after this timestamp. */\n validAfter?: numberType | undefined\n }\n>\n\n/**\n * Native account abstraction transaction in RPC format.\n */\nexport type TempoRpc<pending extends boolean = false> = Compute<\n Omit<\n Tempo<pending, Hex.Hex, Hex.Hex, ToRpcType['tempo']>,\n 'authorizationList' | 'calls' | 'keyAuthorization' | 'signature'\n > & {\n aaAuthorizationList?: AuthorizationTempo.ListRpc | undefined\n calls:\n | readonly {\n input?: Hex.Hex | undefined\n to?: Hex.Hex | undefined\n value?: Hex.Hex | undefined\n }[]\n | undefined\n keyAuthorization?: KeyAuthorization.Rpc | undefined\n signature: SignatureEnvelope.SignatureEnvelopeRpc\n }\n>\n\n/** Type to RPC Type mapping. */\nexport const toRpcType = {\n ...ox_Transaction.toRpcType,\n tempo: '0x76',\n} as const\n\n/** Type to RPC Type mapping. */\nexport type ToRpcType = typeof toRpcType & {\n [type: string]: `0x${string}`\n}\n\n/** RPC Type to Type mapping. */\nexport const fromRpcType = {\n ...ox_Transaction.fromRpcType,\n '0x76': 'tempo',\n} as const\n\n/** RPC Type to Type mapping. */\n\nexport type FromRpcType = typeof fromRpcType & {\n [type: `0x${string}`]: string\n}\n\n/**\n * Converts an {@link ox#Transaction.Rpc} to an {@link ox#Transaction.Transaction}.\n *\n * @example\n * ```ts twoslash\n * import { Transaction } from 'ox/tempo'\n *\n * const transaction = Transaction.fromRpc({\n * hash: '0x353fdfc38a2f26115daadee9f5b8392ce62b84f410957967e2ed56b35338cdd0',\n * nonce: '0x357',\n * blockHash:\n * '0xc350d807505fb835650f0013632c5515592987ba169bbc6626d9fc54d91f0f0b',\n * blockNumber: '0x12f296f',\n * calls: [\n * {\n * input: '0xdeadbeef',\n * to: '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad',\n * value: '0x9b6e64a8ec60000',\n * },\n * ],\n * feeToken: '0x20c0000000000000000000000000000000000000',\n * transactionIndex: '0x2',\n * from: '0x814e5e0e31016b9a7f138c76b7e7b2bb5c1ab6a6',\n * value: '0x9b6e64a8ec60000',\n * gas: '0x43f5d',\n * maxFeePerGas: '0x2ca6ae494',\n * maxPriorityFeePerGas: '0x41cc3c0',\n * input:\n * '0x3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000006643504700000000000000000000000000000000000000000000000000000000000000040b080604000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000009b6e64a8ec600000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000009b6e64a8ec60000000000000000000000000000000000000000000000000000019124bb5ae978c000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b80000000000000000000000000000000000000000000000000000000000000060000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b8000000000000000000000000000000fee13a103a10d593b9ae06b3e05f2e7e1c00000000000000000000000000000000000000000000000000000000000000190000000000000000000000000000000000000000000000000000000000000060000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b800000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000190240001b9872b',\n * signature: {\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * type: 'secp256k1',\n * yParity: '0x0',\n * },\n * chainId: '0x1',\n * accessList: [],\n * type: '0x76',\n * })\n * ```\n *\n * @param transaction - The RPC transaction to convert.\n * @returns An instantiated {@link ox#Transaction.Transaction}.\n */\nexport function fromRpc<\n const transaction extends Rpc | null,\n pending extends boolean = false,\n>(\n transaction: transaction | Rpc<pending> | null,\n _options: fromRpc.Options<pending> = {},\n): transaction extends Rpc<pending> ? Transaction<pending> : null {\n if (!transaction) return null as never\n\n const transaction_ = ox_Transaction.fromRpc(\n transaction as ox_Transaction.Rpc<pending>,\n ) as Transaction<pending>\n\n transaction_.type = fromRpcType[transaction.type as keyof typeof fromRpcType]\n\n if (transaction.aaAuthorizationList) {\n transaction_.authorizationList = AuthorizationTempo.fromRpcList(\n transaction.aaAuthorizationList,\n )\n delete (transaction_ as any).aaAuthorizationList\n }\n if (transaction.calls)\n transaction_.calls = transaction.calls.map((call) => ({\n to: call.to,\n value: call.value && call.value !== '0x' ? BigInt(call.value) : undefined,\n // @ts-expect-error\n data: call.input || call.data || '0x',\n }))\n if (transaction.feeToken) transaction_.feeToken = transaction.feeToken\n if (transaction.nonceKey) transaction_.nonceKey = BigInt(transaction.nonceKey)\n if (transaction.signature)\n transaction_.signature = SignatureEnvelope.fromRpc(transaction.signature)\n if (transaction.validAfter)\n transaction_.validAfter = Number(transaction.validAfter)\n if (transaction.validBefore)\n transaction_.validBefore = Number(transaction.validBefore)\n if (transaction.keyAuthorization)\n transaction_.keyAuthorization = KeyAuthorization.fromRpc(\n transaction.keyAuthorization,\n )\n if (transaction.feePayerSignature) {\n transaction_.feePayerSignature = Signature.fromRpc(\n transaction.feePayerSignature,\n )\n ;(transaction_.feePayerSignature as any).v = Signature.yParityToV(\n transaction_.feePayerSignature.yParity,\n )\n }\n\n return transaction_ as never\n}\n\nexport declare namespace fromRpc {\n type Options<pending extends boolean = false> = {\n pending?: pending | boolean | undefined\n }\n\n type ErrorType = ox_Transaction.fromRpc.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Transaction.Transaction} to an {@link ox#Transaction.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Transaction } from 'ox/tempo'\n *\n * const transaction = Transaction.toRpc({\n * accessList: [],\n * blockHash:\n * '0xc350d807505fb835650f0013632c5515592987ba169bbc6626d9fc54d91f0f0b',\n * blockNumber: 19868015n,\n * calls: [\n * {\n * data: '0xdeadbeef',\n * to: '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad',\n * value: 700000000000000000n,\n * },\n * ],\n * chainId: 1,\n * feeToken: '0x20c0000000000000000000000000000000000000',\n * from: '0x814e5e0e31016b9a7f138c76b7e7b2bb5c1ab6a6',\n * gas: 278365n,\n * hash: '0x353fdfc38a2f26115daadee9f5b8392ce62b84f410957967e2ed56b35338cdd0',\n * input:\n * '0x3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000006643504700000000000000000000000000000000000000000000000000000000000000040b080604000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000009b6e64a8ec600000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000009b6e64a8ec60000000000000000000000000000000000000000000000000000019124bb5ae978c000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b80000000000000000000000000000000000000000000000000000000000000060000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b8000000000000000000000000000000fee13a103a10d593b9ae06b3e05f2e7e1c00000000000000000000000000000000000000000000000000000000000000190000000000000000000000000000000000000000000000000000000000000060000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b800000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000190240001b9872b',\n * maxFeePerGas: 11985937556n,\n * maxPriorityFeePerGas: 68993984n,\n * nonce: 855n,\n * signature: {\n * signature: {\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * yParity: 0,\n * },\n * type: 'secp256k1',\n * },\n * transactionIndex: 2,\n * type: 'tempo',\n * })\n * ```\n *\n * @param transaction - The transaction to convert.\n * @returns An RPC-formatted transaction.\n */\nexport function toRpc<pending extends boolean = false>(\n transaction: Transaction<pending>,\n _options?: toRpc.Options<pending>,\n): Rpc<pending> {\n const rpc = ox_Transaction.toRpc(\n transaction as ox_Transaction.Transaction<pending>,\n ) as Rpc<pending>\n\n rpc.type = toRpcType[transaction.type as keyof typeof toRpcType]\n\n if (transaction.authorizationList)\n rpc.aaAuthorizationList = AuthorizationTempo.toRpcList(\n transaction.authorizationList as AuthorizationTempo.ListSigned,\n )\n if (transaction.calls)\n rpc.calls = transaction.calls.map((call) => ({\n to: call.to,\n value: call.value ? Hex.fromNumber(call.value) : undefined,\n data: call.data,\n }))\n if (transaction.feeToken) rpc.feeToken = transaction.feeToken\n if (transaction.keyAuthorization)\n rpc.keyAuthorization = KeyAuthorization.toRpc(transaction.keyAuthorization)\n if (transaction.feePayerSignature) {\n rpc.feePayerSignature = Signature.toRpc(\n transaction.feePayerSignature,\n ) as any\n ;(rpc.feePayerSignature as any).v = Hex.fromNumber(\n Signature.yParityToV(transaction.feePayerSignature?.yParity),\n )\n }\n if (transaction.signature)\n rpc.signature = SignatureEnvelope.toRpc(transaction.signature)\n if (typeof transaction.validAfter === 'number')\n rpc.validAfter = Hex.fromNumber(transaction.validAfter)\n if (typeof transaction.validBefore === 'number')\n rpc.validBefore = Hex.fromNumber(transaction.validBefore)\n\n return rpc as Rpc<pending>\n}\n\nexport declare namespace toRpc {\n type Options<pending extends boolean = false> = {\n pending?: pending | boolean | undefined\n }\n\n type ErrorType = ox_Transaction.toRpc.ErrorType | Errors.GlobalErrorType\n}\n","import type * as AccessList from './AccessList.js'\nimport type * as Address from './Address.js'\nimport * as Authorization from './Authorization.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, OneOf, UnionCompute } from './internal/types.js'\nimport * as Signature from './Signature.js'\n\n/**\n * A Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml).\n */\nexport type Transaction<\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n> = UnionCompute<\n OneOf<\n | Legacy<pending, bigintType, numberType>\n | Eip1559<pending, bigintType, numberType>\n | Eip2930<pending, bigintType, numberType>\n | Eip4844<pending, bigintType, numberType>\n | Eip7702<pending, bigintType, numberType>\n | (Base & { type: Hex.Hex })\n >\n>\n\n/**\n * An RPC Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml).\n */\nexport type Rpc<pending extends boolean = false> = UnionCompute<\n OneOf<\n | LegacyRpc<pending>\n | Eip1559Rpc<pending>\n | Eip2930Rpc<pending>\n | Eip4844Rpc<pending>\n | Eip7702Rpc<pending>\n | (BaseRpc & { type: Hex.Hex })\n >\n>\n\n/** Base properties of a Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Base<\n type extends string = string,\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n> = Compute<{\n /** Hash of the block that contains this transaction, or `null` if pending. */\n blockHash: pending extends true ? null : Hex.Hex\n /** Number of block containing this transaction or `null` if pending */\n blockNumber: pending extends true ? null : bigintType\n /** Chain ID that this transaction is valid on. */\n chainId: numberType\n /** @alias `input` Added for TransactionEnvelope - Transaction compatibility. */\n data?: Hex.Hex | undefined\n /** Sender of this transaction */\n from: Address.Address\n /** Hash of this transaction */\n hash: Hex.Hex\n /** Contract code or a hashed method call with encoded args */\n input: Hex.Hex\n /** Gas provided for transaction execution */\n gas: bigintType\n /** Unique number identifying this transaction */\n nonce: bigintType\n /** Transaction recipient. `null` if the transaction is a contract creation. */\n to: Address.Address | null\n /** Index of this transaction in the block or `null` if pending */\n transactionIndex: pending extends true ? null : numberType\n /** Transaction type */\n type: type\n /** Value in wei sent with this transaction */\n value: bigintType\n /** ECDSA signature r. */\n r: bigintType\n /** ECDSA signature s. */\n s: bigintType\n /** ECDSA signature yParity. */\n yParity: numberType\n /** @deprecated ECDSA signature v (for backwards compatibility). */\n v?: numberType | undefined\n}>\n\n/** Base properties of an RPC Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type BaseRpc<\n type extends string = string,\n pending extends boolean = false,\n> = Base<type, pending, Hex.Hex, Hex.Hex>\n\n/** An [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Eip1559<\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n type extends string = 'eip1559',\n> = Compute<\n Base<type, pending, bigintType, numberType> & {\n /** EIP-2930 Access List. */\n accessList: AccessList.AccessList\n /** Effective gas price paid by the sender in wei. */\n gasPrice?: bigintType | undefined\n /** Total fee per gas in wei (gasPrice/baseFeePerGas + maxPriorityFeePerGas). */\n maxFeePerGas: bigintType\n /** Max priority fee per gas (in wei). */\n maxPriorityFeePerGas: bigintType\n }\n>\n\n/** An [EIP-1559](https://eips.ethereum.org/EIPS/eip-1559) RPC Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Eip1559Rpc<pending extends boolean = false> = Compute<\n Eip1559<pending, Hex.Hex, Hex.Hex, ToRpcType['eip1559']>\n>\n\n/** An [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Eip2930<\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n type extends string = 'eip2930',\n> = Compute<\n Base<type, pending, bigintType, numberType> & {\n /** EIP-2930 Access List. */\n accessList: AccessList.AccessList\n /** The gas price willing to be paid by the sender (in wei). */\n gasPrice: bigintType\n }\n>\n\n/** An RPC [EIP-2930](https://eips.ethereum.org/EIPS/eip-2930) Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Eip2930Rpc<pending extends boolean = false> = Compute<\n Eip2930<pending, Hex.Hex, Hex.Hex, ToRpcType['eip2930']>\n>\n\n/** An [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Eip4844<\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n type extends string = 'eip4844',\n> = Compute<\n Base<type, pending, bigintType, numberType> & {\n /** EIP-2930 Access List. */\n accessList: AccessList.AccessList\n /** List of versioned blob hashes associated with the transaction's blobs. */\n blobVersionedHashes: readonly Hex.Hex[]\n /** Total fee per blob gas in wei. */\n maxFeePerBlobGas: bigintType\n /** Total fee per gas in wei (gasPrice/baseFeePerGas + maxPriorityFeePerGas). */\n maxFeePerGas: bigintType\n /** Max priority fee per gas (in wei). */\n maxPriorityFeePerGas: bigintType\n }\n>\n\n/** An RPC [EIP-4844](https://eips.ethereum.org/EIPS/eip-4844) Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Eip4844Rpc<pending extends boolean = false> = Compute<\n Eip4844<pending, Hex.Hex, Hex.Hex, ToRpcType['eip4844']>\n>\n\n/** An [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Eip7702<\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n type extends string = 'eip7702',\n> = Compute<\n Base<type, pending, bigintType, numberType> & {\n /** EIP-2930 Access List. */\n accessList: AccessList.AccessList\n /** EIP-7702 Authorization list for the transaction. */\n authorizationList: Authorization.ListSigned<bigintType, numberType>\n /** Total fee per gas in wei (gasPrice/baseFeePerGas + maxPriorityFeePerGas). */\n maxFeePerGas: bigintType\n /** Max priority fee per gas (in wei). */\n maxPriorityFeePerGas: bigintType\n }\n>\n\n/** An RPC [EIP-7702](https://eips.ethereum.org/EIPS/eip-7702) Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Eip7702Rpc<pending extends boolean = false> = Compute<\n Eip7702<pending, Hex.Hex, Hex.Hex, ToRpcType['eip7702']>\n>\n\n/** An legacy Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type Legacy<\n pending extends boolean = false,\n bigintType = bigint,\n numberType = number,\n type extends string = 'legacy',\n> = Compute<\n Omit<\n Base<type, pending, bigintType, numberType>,\n 'chainId' | 'v' | 'yParity'\n > & {\n chainId?: numberType | undefined\n /** The gas price willing to be paid by the sender (in wei). */\n gasPrice: bigintType\n /** ECDSA signature v. */\n v: numberType\n /** ECDSA signature yParity. */\n yParity?: numberType | undefined\n }\n>\n\n/** A legacy RPC Transaction as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/main/src/schemas/transaction.yaml). */\nexport type LegacyRpc<pending extends boolean = false> = Compute<\n Legacy<pending, Hex.Hex, Hex.Hex, ToRpcType['legacy']>\n>\n\n/** Type to RPC Type mapping. */\nexport const toRpcType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n} as const\n\n/** Type to RPC Type mapping. */\nexport type ToRpcType = typeof toRpcType & {\n [type: string]: `0x${string}`\n}\n\n/** RPC Type to Type mapping. */\nexport const fromRpcType = {\n '0x0': 'legacy',\n '0x1': 'eip2930',\n '0x2': 'eip1559',\n '0x3': 'eip4844',\n '0x4': 'eip7702',\n} as const\n\n/** RPC Type to Type mapping. */\n\nexport type FromRpcType = typeof fromRpcType & {\n [type: `0x${string}`]: string\n}\n\n/**\n * Converts an {@link ox#Transaction.Rpc} to an {@link ox#Transaction.Transaction}.\n *\n * @example\n * ```ts twoslash\n * import { Transaction } from 'ox'\n *\n * const transaction = Transaction.fromRpc({\n * hash: '0x353fdfc38a2f26115daadee9f5b8392ce62b84f410957967e2ed56b35338cdd0',\n * nonce: '0x357',\n * blockHash:\n * '0xc350d807505fb835650f0013632c5515592987ba169bbc6626d9fc54d91f0f0b',\n * blockNumber: '0x12f296f',\n * transactionIndex: '0x2',\n * from: '0x814e5e0e31016b9a7f138c76b7e7b2bb5c1ab6a6',\n * to: '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad',\n * value: '0x9b6e64a8ec60000',\n * gas: '0x43f5d',\n * maxFeePerGas: '0x2ca6ae494',\n * maxPriorityFeePerGas: '0x41cc3c0',\n * input:\n * '0x3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000006643504700000000000000000000000000000000000000000000000000000000000000040b080604000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000009b6e64a8ec600000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000009b6e64a8ec60000000000000000000000000000000000000000000000000000019124bb5ae978c000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b80000000000000000000000000000000000000000000000000000000000000060000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b8000000000000000000000000000000fee13a103a10d593b9ae06b3e05f2e7e1c00000000000000000000000000000000000000000000000000000000000000190000000000000000000000000000000000000000000000000000000000000060000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b800000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000190240001b9872b',\n * r: '0x635dc2033e60185bb36709c29c75d64ea51dfbd91c32ef4be198e4ceb169fb4d',\n * s: '0x50c2667ac4c771072746acfdcf1f1483336dcca8bd2df47cd83175dbe60f0540',\n * yParity: '0x0',\n * chainId: '0x1',\n * accessList: [],\n * type: '0x2',\n * })\n * ```\n *\n * @param transaction - The RPC transaction to convert.\n * @returns An instantiated {@link ox#Transaction.Transaction}.\n */\nexport function fromRpc<\n const transaction extends Rpc | null,\n pending extends boolean = false,\n>(\n transaction: transaction | Rpc<pending> | null,\n _options: fromRpc.Options<pending> = {},\n): transaction extends Rpc<pending> ? Transaction<pending> : null {\n if (!transaction) return null as never\n\n const signature = Signature.extract(transaction)\n\n const transaction_ = {\n ...transaction,\n ...signature,\n } as unknown as Transaction<boolean>\n\n transaction_.blockNumber = transaction.blockNumber\n ? BigInt(transaction.blockNumber)\n : null\n transaction_.data = transaction.input\n transaction_.gas = BigInt(transaction.gas ?? 0n)\n transaction_.nonce = BigInt(transaction.nonce ?? 0n)\n transaction_.transactionIndex = transaction.transactionIndex\n ? Number(transaction.transactionIndex)\n : null\n transaction_.value = BigInt(transaction.value ?? 0n)\n\n if (transaction.authorizationList)\n transaction_.authorizationList = Authorization.fromRpcList(\n transaction.authorizationList,\n )\n if (transaction.chainId) transaction_.chainId = Number(transaction.chainId)\n if (transaction.gasPrice) transaction_.gasPrice = BigInt(transaction.gasPrice)\n if (transaction.maxFeePerBlobGas)\n transaction_.maxFeePerBlobGas = BigInt(transaction.maxFeePerBlobGas)\n if (transaction.maxFeePerGas)\n transaction_.maxFeePerGas = BigInt(transaction.maxFeePerGas)\n if (transaction.maxPriorityFeePerGas)\n transaction_.maxPriorityFeePerGas = BigInt(transaction.maxPriorityFeePerGas)\n if (transaction.type)\n transaction_.type =\n (fromRpcType as any)[transaction.type] ?? transaction.type\n if (signature) transaction_.v = Signature.yParityToV(signature.yParity)\n\n return transaction_ as never\n}\n\nexport declare namespace fromRpc {\n type Options<pending extends boolean = false> = {\n pending?: pending | boolean | undefined\n }\n\n type ErrorType = Signature.extract.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Converts an {@link ox#Transaction.Transaction} to an {@link ox#Transaction.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Transaction } from 'ox'\n *\n * const transaction = Transaction.toRpc({\n * accessList: [],\n * blockHash:\n * '0xc350d807505fb835650f0013632c5515592987ba169bbc6626d9fc54d91f0f0b',\n * blockNumber: 19868015n,\n * chainId: 1,\n * from: '0x814e5e0e31016b9a7f138c76b7e7b2bb5c1ab6a6',\n * gas: 278365n,\n * hash: '0x353fdfc38a2f26115daadee9f5b8392ce62b84f410957967e2ed56b35338cdd0',\n * input:\n * '0x3593564c000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a0000000000000000000000000000000000000000000000000000000006643504700000000000000000000000000000000000000000000000000000000000000040b080604000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002800000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000009b6e64a8ec600000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000009b6e64a8ec60000000000000000000000000000000000000000000000000000019124bb5ae978c000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000c02aaa39b223fe8d0a0e5c4f27ead9083c756cc2000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b80000000000000000000000000000000000000000000000000000000000000060000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b8000000000000000000000000000000fee13a103a10d593b9ae06b3e05f2e7e1c00000000000000000000000000000000000000000000000000000000000000190000000000000000000000000000000000000000000000000000000000000060000000000000000000000000c56c7a0eaa804f854b536a5f3d5f49d2ec4b12b800000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000190240001b9872b',\n * maxFeePerGas: 11985937556n,\n * maxPriorityFeePerGas: 68993984n,\n * nonce: 855n,\n * r: 44944627813007772897391531230081695102703289123332187696115181104739239197517n,\n * s: 36528503505192438307355164441104001310566505351980369085208178712678799181120n,\n * to: '0x3fc91a3afd70395cd496c647d5a6cc9d4b2b7fad',\n * transactionIndex: 2,\n * type: 'eip1559',\n * v: 27,\n * value: 700000000000000000n,\n * yParity: 0,\n * })\n * ```\n *\n * @param transaction - The transaction to convert.\n * @returns An RPC-formatted transaction.\n */\nexport function toRpc<pending extends boolean = false>(\n transaction: Transaction<pending>,\n _options?: toRpc.Options<pending>,\n): Rpc<pending> {\n const rpc = {} as Rpc<boolean>\n\n rpc.blockHash = transaction.blockHash\n rpc.blockNumber =\n typeof transaction.blockNumber === 'bigint'\n ? Hex.fromNumber(transaction.blockNumber)\n : null\n rpc.from = transaction.from\n rpc.gas = Hex.fromNumber(transaction.gas ?? 0n)\n rpc.hash = transaction.hash\n rpc.input = transaction.input\n rpc.nonce = Hex.fromNumber(transaction.nonce ?? 0n)\n rpc.to = transaction.to\n rpc.transactionIndex = transaction.transactionIndex\n ? Hex.fromNumber(transaction.transactionIndex)\n : null\n rpc.type = (toRpcType as any)[transaction.type] ?? transaction.type\n rpc.value = Hex.fromNumber(transaction.value ?? 0n)\n\n if (transaction.accessList) rpc.accessList = transaction.accessList\n if (transaction.authorizationList)\n rpc.authorizationList = Authorization.toRpcList(\n transaction.authorizationList,\n )\n if (transaction.blobVersionedHashes)\n rpc.blobVersionedHashes = transaction.blobVersionedHashes\n if (transaction.chainId) rpc.chainId = Hex.fromNumber(transaction.chainId)\n if (typeof transaction.gasPrice === 'bigint')\n rpc.gasPrice = Hex.fromNumber(transaction.gasPrice)\n if (typeof transaction.maxFeePerBlobGas === 'bigint')\n rpc.maxFeePerBlobGas = Hex.fromNumber(transaction.maxFeePerBlobGas)\n if (typeof transaction.maxFeePerGas === 'bigint')\n rpc.maxFeePerGas = Hex.fromNumber(transaction.maxFeePerGas)\n if (typeof transaction.maxPriorityFeePerGas === 'bigint')\n rpc.maxPriorityFeePerGas = Hex.fromNumber(transaction.maxPriorityFeePerGas)\n if (typeof transaction.r === 'bigint')\n rpc.r = Hex.fromNumber(transaction.r, { size: 32 })\n if (typeof transaction.s === 'bigint')\n rpc.s = Hex.fromNumber(transaction.s, { size: 32 })\n if (typeof transaction.v === 'number')\n rpc.v = Hex.fromNumber(transaction.v, { size: 1 })\n if (typeof transaction.yParity === 'number')\n rpc.yParity = transaction.yParity === 0 ? '0x0' : '0x1'\n\n return rpc as Rpc<pending>\n}\n\nexport declare namespace toRpc {\n type Options<pending extends boolean = false> = {\n pending?: pending | boolean | undefined\n }\n\n type ErrorType = Signature.extract.ErrorType | Errors.GlobalErrorType\n}\n","import type * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type { Compute } from '../core/internal/types.js'\nimport * as ox_TransactionRequest from '../core/TransactionRequest.js'\nimport * as AuthorizationTempo from './AuthorizationTempo.js'\nimport * as KeyAuthorization from './KeyAuthorization.js'\nimport * as TempoAddress from './TempoAddress.js'\nimport * as TokenId from './TokenId.js'\nimport * as Transaction from './Transaction.js'\nimport type { Call } from './TxEnvelopeTempo.js'\n\ntype KeyType = 'secp256k1' | 'p256' | 'webAuthn'\n\n/**\n * A Transaction Request that is generic to all transaction types.\n *\n * Extends the [Execution API specification](https://github.com/ethereum/execution-apis/blob/4aca1d7a3e5aab24c8f6437131289ad386944eaa/src/schemas/transaction.yaml#L358-L423)\n * with Tempo-specific fields for batched calls, fee tokens, access keys, and scheduled execution.\n *\n * @see {@link https://docs.tempo.xyz/protocol/transactions}\n */\nexport type TransactionRequest<\n bigintType = bigint,\n numberType = number,\n type extends string = string,\n> = Compute<\n Omit<\n ox_TransactionRequest.TransactionRequest<bigintType, numberType, type>,\n 'authorizationList'\n > & {\n authorizationList?:\n | AuthorizationTempo.ListSigned<bigintType, numberType>\n | undefined\n calls?: readonly Call<bigintType, TempoAddress.Address>[] | undefined\n keyAuthorization?: KeyAuthorization.KeyAuthorization<true> | undefined\n keyData?: Hex.Hex | undefined\n keyType?: KeyType | undefined\n feeToken?: TokenId.TokenIdOrAddress | undefined\n nonceKey?: 'random' | bigintType | undefined\n validBefore?: numberType | undefined\n validAfter?: numberType | undefined\n }\n>\n\n/** RPC representation of a {@link ox#TransactionRequest.TransactionRequest}. */\nexport type Rpc = Omit<\n TransactionRequest<Hex.Hex, Hex.Hex, string>,\n 'authorizationList' | 'keyAuthorization'\n> & {\n authorizationList?: AuthorizationTempo.ListRpc | undefined\n keyAuthorization?: KeyAuthorization.Rpc | undefined\n nonceKey?: Hex.Hex | undefined\n}\n\n/**\n * Converts a {@link ox#TransactionRequest.TransactionRequest} to a {@link ox#TransactionRequest.Rpc}.\n *\n * @see {@link https://docs.tempo.xyz/protocol/transactions}\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n * import { TransactionRequest } from 'ox/tempo'\n *\n * const request = TransactionRequest.toRpc({\n * calls: [{\n * data: '0xdeadbeef',\n * to: '0xcafebabecafebabecafebabecafebabecafebabe',\n * }],\n * feeToken: '0x20c0000000000000000000000000000000000000',\n * })\n * ```\n *\n * @example\n * ### Using with a Provider\n *\n * You can use {@link ox#Provider.(from:function)} to instantiate an EIP-1193 Provider and\n * send a transaction to the Wallet using the `eth_sendTransaction` method.\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Provider, Value } from 'ox'\n * import { TransactionRequest } from 'ox/tempo'\n *\n * const provider = Provider.from(window.ethereum!)\n *\n * const request = TransactionRequest.toRpc({\n * calls: [{\n * data: '0xdeadbeef',\n * to: '0xcafebabecafebabecafebabecafebabecafebabe',\n * }],\n * feeToken: '0x20c0000000000000000000000000000000000000',\n * })\n *\n * const hash = await provider.request({ // [!code focus]\n * method: 'eth_sendTransaction', // [!code focus]\n * params: [request], // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param request - The request to convert.\n * @returns An RPC request.\n */\nexport function toRpc(request: TransactionRequest): Rpc {\n const request_rpc = ox_TransactionRequest.toRpc({\n ...request,\n authorizationList: undefined,\n }) as Rpc\n\n if (request.authorizationList)\n request_rpc.authorizationList = AuthorizationTempo.toRpcList(\n request.authorizationList,\n )\n if (request.calls)\n request_rpc.calls = request.calls.map((call) => ({\n to: call.to ? TempoAddress.resolve(call.to) : call.to,\n value: call.value ? Hex.fromNumber(call.value) : '0x',\n data: call.data ?? '0x',\n }))\n if (typeof request.feeToken !== 'undefined')\n request_rpc.feeToken = TokenId.toAddress(request.feeToken)\n if (request.keyAuthorization)\n request_rpc.keyAuthorization = KeyAuthorization.toRpc(\n request.keyAuthorization,\n )\n if (typeof request.validBefore !== 'undefined')\n request_rpc.validBefore = Hex.fromNumber(request.validBefore)\n if (typeof request.validAfter !== 'undefined')\n request_rpc.validAfter = Hex.fromNumber(request.validAfter)\n\n const nonceKey = (() => {\n if (request.nonceKey === 'random') return Hex.random(6)\n if (typeof request.nonceKey === 'bigint')\n return Hex.fromNumber(request.nonceKey)\n return undefined\n })()\n if (nonceKey) request_rpc.nonceKey = nonceKey\n\n if (\n typeof request.calls !== 'undefined' ||\n typeof request.feeToken !== 'undefined' ||\n typeof request.keyAuthorization !== 'undefined' ||\n typeof request.nonceKey !== 'undefined' ||\n typeof request.validBefore !== 'undefined' ||\n typeof request.validAfter !== 'undefined' ||\n request.type === 'tempo'\n ) {\n request_rpc.type = Transaction.toRpcType.tempo\n delete request_rpc.data\n delete request_rpc.input\n delete request_rpc.to\n delete request_rpc.value\n }\n\n return request_rpc\n}\n\nexport declare namespace toRpc {\n export type ErrorType =\n | AuthorizationTempo.toRpcList.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n","import type * as AccessList from './AccessList.js'\nimport type * as Address from './Address.js'\nimport * as Authorization from './Authorization.js'\nimport type * as Errors from './Errors.js'\nimport * as Hex from './Hex.js'\nimport type { Compute } from './internal/types.js'\nimport * as Transaction from './Transaction.js'\n\n/** A Transaction Request that is generic to all transaction types, as defined in the [Execution API specification](https://github.com/ethereum/execution-apis/blob/4aca1d7a3e5aab24c8f6437131289ad386944eaa/src/schemas/transaction.yaml#L358-L423). */\nexport type TransactionRequest<\n bigintType = bigint,\n numberType = number,\n type extends string = string,\n> = Compute<{\n /** EIP-2930 Access List. */\n accessList?: AccessList.AccessList | undefined\n /** EIP-7702 Authorization List. */\n authorizationList?:\n | Authorization.ListSigned<bigintType, numberType>\n | undefined\n /** Versioned hashes of blobs to be included in the transaction. */\n blobVersionedHashes?: readonly Hex.Hex[]\n /** Raw blob data. */\n blobs?: readonly Hex.Hex[] | undefined\n /** EIP-155 Chain ID. */\n chainId?: numberType | undefined\n /** Contract code or a hashed method call with encoded args */\n data?: Hex.Hex | undefined\n /** @alias `data` – added for TransactionEnvelope - Transaction compatibility. */\n input?: Hex.Hex | undefined\n /** Sender of the transaction. */\n from?: Address.Address | undefined\n /** Gas provided for transaction execution */\n gas?: bigintType | undefined\n /** Base fee per gas. */\n gasPrice?: bigintType | undefined\n /** Maximum total fee per gas sender is willing to pay for blob gas (in wei). */\n maxFeePerBlobGas?: bigintType | undefined\n /** Total fee per gas in wei (gasPrice/baseFeePerGas + maxPriorityFeePerGas). */\n maxFeePerGas?: bigintType | undefined\n /** Max priority fee per gas (in wei). */\n maxPriorityFeePerGas?: bigintType | undefined\n /** Unique number identifying this transaction */\n nonce?: bigintType | undefined\n /** Transaction recipient */\n to?: Address.Address | null | undefined\n /** Transaction type */\n type?: type | undefined\n /** Value in wei sent with this transaction */\n value?: bigintType | undefined\n}>\n\n/** RPC representation of a {@link ox#TransactionRequest.TransactionRequest}. */\nexport type Rpc = TransactionRequest<Hex.Hex, Hex.Hex, string>\n\n/**\n * Converts a {@link ox#TransactionRequest.Rpc} to a {@link ox#TransactionRequest.TransactionRequest}.\n *\n * @example\n * ```ts twoslash\n * import { TransactionRequest } from 'ox'\n *\n * const request = TransactionRequest.fromRpc({\n * to: '0x0000000000000000000000000000000000000000',\n * value: '0x2386f26fc10000',\n * })\n * ```\n *\n * @param request - The RPC request to convert.\n * @returns A transaction request.\n */\nexport function fromRpc(request: Rpc): TransactionRequest {\n const request_ = request as TransactionRequest\n\n if (typeof request.authorizationList !== 'undefined')\n request_.authorizationList = Authorization.fromRpcList(\n request.authorizationList,\n )\n if (typeof request.chainId !== 'undefined')\n request_.chainId = Hex.toNumber(request.chainId)\n if (typeof request.gas !== 'undefined')\n request_.gas = Hex.toBigInt(request.gas)\n if (typeof request.gasPrice !== 'undefined')\n request_.gasPrice = Hex.toBigInt(request.gasPrice)\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n request_.maxFeePerBlobGas = Hex.toBigInt(request.maxFeePerBlobGas)\n if (typeof request.maxFeePerGas !== 'undefined')\n request_.maxFeePerGas = Hex.toBigInt(request.maxFeePerGas)\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n request_.maxPriorityFeePerGas = Hex.toBigInt(request.maxPriorityFeePerGas)\n if (typeof request.nonce !== 'undefined')\n request_.nonce = Hex.toBigInt(request.nonce)\n if (typeof request.type !== 'undefined')\n request_.type =\n Transaction.fromRpcType[\n request.type as keyof typeof Transaction.fromRpcType\n ] || request.type\n if (typeof request.value !== 'undefined')\n request_.value = Hex.toBigInt(request.value)\n\n return request_\n}\n\nexport declare namespace fromRpc {\n export type ErrorType =\n | Authorization.fromRpcList.ErrorType\n | Hex.toNumber.ErrorType\n | Hex.toBigInt.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Converts a {@link ox#TransactionRequest.TransactionRequest} to a {@link ox#TransactionRequest.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { TransactionRequest, Value } from 'ox'\n *\n * const request = TransactionRequest.toRpc({\n * to: '0x0000000000000000000000000000000000000000',\n * value: Value.fromEther('0.01'),\n * })\n * ```\n *\n * @example\n * ### Using with a Provider\n *\n * You can use {@link ox#Provider.(from:function)} to instantiate an EIP-1193 Provider and\n * send a transaction to the Wallet using the `eth_sendTransaction` method.\n *\n * ```ts twoslash\n * import 'ox/window'\n * import { Provider, TransactionRequest, Value } from 'ox'\n *\n * const provider = Provider.from(window.ethereum!)\n *\n * const request = TransactionRequest.toRpc({\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * value: Value.fromEther('0.01'),\n * })\n *\n * const hash = await provider.request({ // [!code focus]\n * method: 'eth_sendTransaction', // [!code focus]\n * params: [request], // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param request - The request to convert.\n * @returns An RPC request.\n */\nexport function toRpc(request: TransactionRequest): Rpc {\n const request_rpc: Rpc = {}\n\n if (typeof request.accessList !== 'undefined')\n request_rpc.accessList = request.accessList\n if (typeof request.authorizationList !== 'undefined')\n request_rpc.authorizationList = Authorization.toRpcList(\n request.authorizationList,\n )\n if (typeof request.blobVersionedHashes !== 'undefined')\n request_rpc.blobVersionedHashes = request.blobVersionedHashes\n if (typeof request.blobs !== 'undefined') request_rpc.blobs = request.blobs\n if (typeof request.chainId !== 'undefined')\n request_rpc.chainId = Hex.fromNumber(request.chainId)\n if (typeof request.data !== 'undefined') {\n request_rpc.data = request.data\n request_rpc.input = request.data\n } else if (typeof request.input !== 'undefined') {\n request_rpc.data = request.input\n request_rpc.input = request.input\n }\n if (typeof request.from !== 'undefined') request_rpc.from = request.from\n if (typeof request.gas !== 'undefined')\n request_rpc.gas = Hex.fromNumber(request.gas)\n if (typeof request.gasPrice !== 'undefined')\n request_rpc.gasPrice = Hex.fromNumber(request.gasPrice)\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n request_rpc.maxFeePerBlobGas = Hex.fromNumber(request.maxFeePerBlobGas)\n if (typeof request.maxFeePerGas !== 'undefined')\n request_rpc.maxFeePerGas = Hex.fromNumber(request.maxFeePerGas)\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n request_rpc.maxPriorityFeePerGas = Hex.fromNumber(\n request.maxPriorityFeePerGas,\n )\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n request_rpc.maxPriorityFeePerGas = Hex.fromNumber(\n request.maxPriorityFeePerGas,\n )\n if (typeof request.nonce !== 'undefined')\n request_rpc.nonce = Hex.fromNumber(request.nonce)\n if (typeof request.to !== 'undefined') request_rpc.to = request.to\n if (typeof request.type !== 'undefined')\n request_rpc.type =\n Transaction.toRpcType[\n request.type as keyof typeof Transaction.toRpcType\n ] || request.type\n if (typeof request.value !== 'undefined')\n request_rpc.value = Hex.fromNumber(request.value)\n\n return request_rpc\n}\n\nexport declare namespace toRpc {\n export type ErrorType =\n | Authorization.toRpcList.ErrorType\n | Hex.fromNumber.ErrorType\n | Errors.GlobalErrorType\n}\n","import * as AccessList from '../core/AccessList.js'\nimport * as Address from '../core/Address.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hash from '../core/Hash.js'\nimport * as Hex from '../core/Hex.js'\nimport type {\n Assign,\n Compute,\n OneOf,\n PartialBy,\n UnionPartialBy,\n} from '../core/internal/types.js'\nimport * as Rlp from '../core/Rlp.js'\nimport * as Secp256k1 from '../core/Secp256k1.js'\nimport * as Signature from '../core/Signature.js'\nimport * as TransactionEnvelope from '../core/TxEnvelope.js'\nimport * as AuthorizationTempo from './AuthorizationTempo.js'\nimport * as KeyAuthorization from './KeyAuthorization.js'\nimport * as SignatureEnvelope from './SignatureEnvelope.js'\nimport * as TempoAddress from './TempoAddress.js'\nimport * as TokenId from './TokenId.js'\n\n/**\n * Represents a single call within a Tempo transaction.\n *\n * Tempo transactions support batching multiple calls for atomic execution.\n *\n * [Batch Calls](https://docs.tempo.xyz/protocol/transactions#batch-calls)\n */\nexport type Call<bigintType = bigint, addressType = Address.Address> = {\n /** Call data. */\n data?: Hex.Hex | undefined\n /** The target address or contract creation. */\n to?: addressType | undefined\n /** Value to send (in wei). */\n value?: bigintType | undefined\n}\n\n/**\n * Tempo transaction envelope (type `0x76`).\n *\n * A new EIP-2718 transaction type exclusively available on Tempo, designed for payment\n * use cases with the following features:\n *\n * - **Configurable Fee Tokens**: Pay transaction fees with any USD-denominated TIP-20 token.\n * The Fee AMM automatically converts to the validator's preferred token.\n *\n * - **Fee Sponsorship**: A third-party fee payer can pay fees on behalf of the sender using\n * a dual-signature scheme (sender signs tx, fee payer signs over tx + sender address).\n *\n * - **Batch Calls**: Execute multiple operations atomically in a single transaction via\n * the `calls` array, reducing overhead and simplifying wallet management.\n *\n * - **Access Keys**: Delegate signing to secondary keys with expiry and per-TIP-20 spending\n * limits via `keyAuthorization`. Enables passkey UX without repeated prompts.\n *\n * - **Parallelizable Nonces**: Use different `nonceKey` values to submit multiple transactions\n * in parallel without waiting for sequential nonce confirmation.\n *\n * - **Scheduled Transactions**: Set `validAfter` and `validBefore` timestamps to define a\n * time window for when the transaction can be included in a block.\n *\n * - **Multi-Signature Support**: Sign with secp256k1, P256 (passkeys), or WebAuthn credentials.\n *\n * [Tempo Transaction Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction)\n */\nexport type TxEnvelopeTempo<\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n type extends string = Type,\n> = Compute<\n {\n /** EIP-2930 Access List. */\n accessList?: AccessList.AccessList | undefined\n /** EIP-7702 (Tempo) Authorization list for the transaction. */\n authorizationList?:\n | AuthorizationTempo.ListSigned<bigintType, numberType>\n | undefined\n /** Array of calls to execute. */\n calls: readonly Call<bigintType, TempoAddress.Address>[]\n /** EIP-155 Chain ID. */\n chainId: numberType\n /** Sender of the transaction. */\n from?: TempoAddress.Address | undefined\n /** Gas provided for transaction execution */\n gas?: bigintType | undefined\n /** Fee payer signature. */\n feePayerSignature?:\n | Signature.Signature<true, bigintType, numberType>\n | null\n | undefined\n /** Fee token preference. Address or ID of the TIP-20 token. */\n feeToken?: TokenId.TokenIdOrAddress | undefined\n /**\n * Key authorization for provisioning a new access key.\n *\n * When present, this transaction will add the specified key to the AccountKeychain precompile,\n * before verifying the transaction signature.\n * The authorization must be signed with the root key, the tx can be signed by the Keychain signature.\n */\n keyAuthorization?:\n | KeyAuthorization.Signed<bigintType, numberType>\n | undefined\n /** Total fee per gas in wei (gasPrice/baseFeePerGas + maxPriorityFeePerGas). */\n maxFeePerGas?: bigintType | undefined\n /** Max priority fee per gas (in wei). */\n maxPriorityFeePerGas?: bigintType | undefined\n /** Nonce key for 2D nonce system (192 bits). */\n nonceKey?: bigintType | undefined\n /** Unique number identifying this transaction */\n nonce?: bigintType | undefined\n /** Transaction type */\n type: type\n /** Transaction can only be included in a block before this timestamp. */\n validBefore?: numberType | undefined\n /** Transaction can only be included in a block after this timestamp. */\n validAfter?: numberType | undefined\n } & (signed extends true\n ? {\n signature: SignatureEnvelope.SignatureEnvelope<bigintType, numberType>\n }\n : {\n signature?:\n | SignatureEnvelope.SignatureEnvelope<bigintType, numberType>\n | undefined\n })\n>\n\nexport type Rpc<signed extends boolean = boolean> = TxEnvelopeTempo<\n signed,\n Hex.Hex,\n Hex.Hex,\n '0x76'\n>\n\nexport const feePayerMagic = '0x78' as const\nexport type FeePayerMagic = typeof feePayerMagic\n\nexport type Serialized = `${SerializedType}${string}`\n\nexport type Signed = TxEnvelopeTempo<true>\n\nexport const serializedType = '0x76' as const\nexport type SerializedType = typeof serializedType\n\nexport const type = 'tempo' as const\nexport type Type = typeof type\n\n/**\n * Asserts a {@link ox#TxEnvelopeTempo.TxEnvelopeTempo} is valid.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * TxEnvelopeTempo.assert({\n * calls: [{ to: 'tempox0x0000000000000000000000000000000000000000', value: 0n }],\n * chainId: 1,\n * maxFeePerGas: 1000000000n,\n * })\n * ```\n *\n * @param envelope - The transaction envelope to assert.\n */\nexport function assert(envelope: PartialBy<TxEnvelopeTempo, 'type'>) {\n const {\n calls,\n chainId,\n maxFeePerGas,\n maxPriorityFeePerGas,\n validBefore,\n validAfter,\n } = envelope\n\n // Calls must not be empty\n if (!calls || calls.length === 0) throw new CallsEmptyError()\n\n // validBefore must be greater than validAfter if both are set\n if (\n typeof validBefore === 'number' &&\n typeof validAfter === 'number' &&\n validBefore <= validAfter\n ) {\n throw new InvalidValidityWindowError({\n validBefore: validBefore,\n validAfter: validAfter,\n })\n }\n\n // Validate each call\n if (calls)\n for (const call of calls)\n if (call.to) Address.assert(call.to, { strict: false })\n\n // Validate chain ID\n if (chainId <= 0)\n throw new TransactionEnvelope.InvalidChainIdError({ chainId })\n\n // Validate max fee per gas\n if (maxFeePerGas && BigInt(maxFeePerGas) > 2n ** 256n - 1n)\n throw new TransactionEnvelope.FeeCapTooHighError({\n feeCap: maxFeePerGas,\n })\n\n if (\n maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas\n )\n throw new TransactionEnvelope.TipAboveFeeCapError({\n maxFeePerGas,\n maxPriorityFeePerGas,\n })\n}\n\nexport declare namespace assert {\n type ErrorType =\n | Address.assert.ErrorType\n | CallsEmptyError\n | InvalidValidityWindowError\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a {@link ox#TxEnvelopeTempo.TxEnvelopeTempo} from its serialized form.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.deserialize('0x76f84a0182031184773594008477359400809470997970c51812dc3a010c7d01b50e0d17dc79c8880de0b6b3a764000080c0808080')\n * // @log: {\n * // @log: type: 'tempo',\n * // @log: nonce: 785n,\n * // @log: maxFeePerGas: 2000000000n,\n * // @log: gas: 1000000n,\n * // @log: calls: [{ to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8', value: 1000000000000000000n }],\n * // @log: }\n * ```\n *\n * @param serialized - The serialized transaction.\n * @returns Deserialized Transaction Envelope.\n */\nexport function deserialize(serialized: Serialized): Compute<TxEnvelopeTempo> {\n const transactionArray = Rlp.toHex(Hex.slice(serialized, 1))\n\n const [\n chainId,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gas,\n calls,\n accessList,\n nonceKey,\n nonce,\n validBefore,\n validAfter,\n feeToken,\n feePayerSignatureOrSender,\n authorizationList,\n keyAuthorizationOrSignature,\n maybeSignature,\n ] = transactionArray as readonly Hex.Hex[]\n\n const keyAuthorization = Array.isArray(keyAuthorizationOrSignature)\n ? keyAuthorizationOrSignature\n : undefined\n const signature = keyAuthorization\n ? maybeSignature\n : keyAuthorizationOrSignature\n\n if (\n !(\n transactionArray.length === 13 ||\n transactionArray.length === 14 ||\n transactionArray.length === 15\n )\n )\n throw new TransactionEnvelope.InvalidSerializedError({\n attributes: {\n authorizationList,\n chainId,\n maxPriorityFeePerGas,\n maxFeePerGas,\n gas,\n calls,\n accessList,\n keyAuthorization,\n nonceKey,\n nonce,\n validBefore,\n validAfter,\n feeToken,\n feePayerSignatureOrSender,\n ...(transactionArray.length > 12\n ? {\n signature,\n }\n : {}),\n },\n serialized,\n type,\n })\n\n let transaction = {\n chainId: Number(chainId),\n type,\n } as TxEnvelopeTempo\n\n if (Hex.validate(gas) && gas !== '0x') transaction.gas = BigInt(gas)\n if (Hex.validate(nonce))\n transaction.nonce = nonce === '0x' ? 0n : BigInt(nonce)\n if (Hex.validate(maxFeePerGas) && maxFeePerGas !== '0x')\n transaction.maxFeePerGas = BigInt(maxFeePerGas)\n if (Hex.validate(maxPriorityFeePerGas) && maxPriorityFeePerGas !== '0x')\n transaction.maxPriorityFeePerGas = BigInt(maxPriorityFeePerGas)\n if (Hex.validate(nonceKey))\n transaction.nonceKey = nonceKey === '0x' ? 0n : BigInt(nonceKey)\n if (Hex.validate(validBefore) && validBefore !== '0x')\n transaction.validBefore = Number(validBefore)\n if (Hex.validate(validAfter) && validAfter !== '0x')\n transaction.validAfter = Number(validAfter)\n if (Hex.validate(feeToken) && feeToken !== '0x')\n transaction.feeToken = feeToken\n\n // Parse calls array\n if (calls && calls !== '0x') {\n const callsArray = calls as unknown as readonly Hex.Hex[][]\n transaction.calls = callsArray.map((callTuple) => {\n const [to, value, data] = callTuple\n const call: Call = {}\n if (to && to !== '0x') call.to = to\n if (value && value !== '0x') call.value = BigInt(value)\n if (data && data !== '0x') call.data = data\n return call\n })\n }\n\n if (accessList?.length !== 0 && accessList !== '0x')\n transaction.accessList = AccessList.fromTupleList(accessList as never)\n\n if (authorizationList?.length !== 0 && authorizationList !== '0x')\n transaction.authorizationList = AuthorizationTempo.fromTupleList(\n authorizationList as never,\n )\n\n if (\n feePayerSignatureOrSender !== '0x' &&\n feePayerSignatureOrSender !== undefined\n ) {\n if (\n feePayerSignatureOrSender === '0x00' ||\n Address.validate(feePayerSignatureOrSender)\n ) {\n transaction.feePayerSignature = null\n if (Address.validate(feePayerSignatureOrSender))\n transaction.from = feePayerSignatureOrSender\n } else\n transaction.feePayerSignature = Signature.fromTuple(\n feePayerSignatureOrSender as never,\n )\n }\n\n if (keyAuthorization)\n transaction.keyAuthorization = KeyAuthorization.fromTuple(\n keyAuthorization as never,\n )\n\n const signatureEnvelope = signature\n ? SignatureEnvelope.deserialize(signature)\n : undefined\n if (signatureEnvelope)\n transaction = {\n ...transaction,\n signature: signatureEnvelope,\n }\n\n // Recover sender address from the signature if not already set.\n if (!transaction.from && signatureEnvelope) {\n try {\n transaction.from = SignatureEnvelope.extractAddress({\n payload: getSignPayload(from(transaction)),\n signature: signatureEnvelope,\n root: true,\n })\n } catch {}\n }\n\n assert(transaction)\n\n return transaction\n}\n\nexport declare namespace deserialize {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Converts an arbitrary transaction object into a Tempo Transaction Envelope.\n *\n * Use this to create transaction envelopes with Tempo-specific features like batched calls,\n * fee tokens, access keys, and scheduled execution. Attach a signature using the `signature`\n * option after signing with {@link ox#TxEnvelopeTempo.(getSignPayload:function)}.\n *\n * [Tempo Transaction Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction)\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from({ // [!code focus]\n * chainId: 1, // [!code focus]\n * calls: [{ // [!code focus]\n * data: '0xdeadbeef', // [!code focus]\n * to: 'tempox0x0000000000000000000000000000000000000000', // [!code focus]\n * }], // [!code focus]\n * maxFeePerGas: Value.fromGwei('10'), // [!code focus]\n * maxPriorityFeePerGas: Value.fromGwei('1'), // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @example\n * ### Attaching Signatures\n *\n * It is possible to attach a `signature` to the transaction envelope.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1, Value } from 'ox'\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from({\n * chainId: 1,\n * calls: [{\n * data: '0xdeadbeef',\n * to: 'tempox0x0000000000000000000000000000000000000000',\n * }],\n * maxFeePerGas: Value.fromGwei('10'),\n * maxPriorityFeePerGas: Value.fromGwei('1'),\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: TxEnvelopeTempo.getSignPayload(envelope),\n * privateKey: '0x...',\n * })\n *\n * const envelope_signed = TxEnvelopeTempo.from(envelope, { // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n * // @log: {\n * // @log: chainId: 1,\n * // @log: calls: [{ to: '0x0000000000000000000000000000000000000000', value: 1000000000000000000n }],\n * // @log: maxFeePerGas: 10000000000n,\n * // @log: maxPriorityFeePerGas: 1000000000n,\n * // @log: type: 'tempo',\n * // @log: r: 125...n,\n * // @log: s: 642...n,\n * // @log: yParity: 0,\n * // @log: }\n * ```\n *\n * @example\n * ### From Serialized\n *\n * It is possible to instantiate a Tempo Transaction Envelope from a {@link ox#TxEnvelopeTempo.Serialized} value.\n *\n * ```ts twoslash\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from('0x76f84a0182031184773594008477359400809470997970c51812dc3a010c7d01b50e0d17dc79c8880de0b6b3a764000080c0808080')\n * // @log: {\n * // @log: chainId: 1,\n * // @log: calls: [{\n * // @log: data: '0xdeadbeef',\n * // @log: to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * // @log: }],\n * // @log: maxFeePerGas: 10000000000n,\n * // @log: type: 'tempo',\n * // @log: }\n * ```\n *\n * @param envelope - The transaction object to convert.\n * @param options - Options.\n * @returns A Tempo Transaction Envelope.\n */\nexport function from<\n const envelope extends UnionPartialBy<TxEnvelopeTempo, 'type'> | Serialized,\n const signature extends SignatureEnvelope.from.Value | undefined = undefined,\n>(\n envelope: envelope | UnionPartialBy<TxEnvelopeTempo, 'type'> | Serialized,\n options: from.Options<signature> = {},\n): from.ReturnValue<envelope, signature> {\n const { feePayerSignature, signature } = options\n\n const envelope_ = (\n typeof envelope === 'string' ? deserialize(envelope) : envelope\n ) as TxEnvelopeTempo\n\n // Resolve TempoAddress inputs to hex addresses.\n if (envelope_.from)\n envelope_.from = TempoAddress.resolve(\n envelope_.from as TempoAddress.Address,\n )\n if (envelope_.calls)\n envelope_.calls = (envelope_.calls as readonly Call[]).map((call) => ({\n ...call,\n ...(call.to\n ? { to: TempoAddress.resolve(call.to as TempoAddress.Address) }\n : {}),\n })) as readonly Call[]\n\n assert(envelope_)\n\n return {\n ...envelope_,\n ...(signature ? { signature: SignatureEnvelope.from(signature) } : {}),\n ...(feePayerSignature\n ? { feePayerSignature: Signature.from(feePayerSignature) }\n : {}),\n type: 'tempo',\n } as never\n}\n\nexport declare namespace from {\n type Options<\n signature extends SignatureEnvelope.from.Value | undefined = undefined,\n > = {\n feePayerSignature?: Signature.Signature | null | undefined\n signature?: signature | SignatureEnvelope.from.Value | undefined\n }\n\n type ReturnValue<\n envelope extends UnionPartialBy<TxEnvelopeTempo, 'type'> | Hex.Hex =\n | TxEnvelopeTempo\n | Hex.Hex,\n signature extends SignatureEnvelope.from.Value | undefined = undefined,\n > = Compute<\n envelope extends Hex.Hex\n ? TxEnvelopeTempo\n : Assign<\n envelope,\n (signature extends SignatureEnvelope.from.Value\n ? { signature: SignatureEnvelope.from.ReturnValue<signature> }\n : {}) & {\n readonly type: 'tempo'\n }\n >\n >\n\n type ErrorType =\n | deserialize.ErrorType\n | assert.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Serializes a {@link ox#TxEnvelopeTempo.TxEnvelopeTempo}.\n *\n * RLP-encodes the transaction with type prefix `0x76`. For fee sponsorship, use `format: 'feePayer'`\n * to serialize with the fee payer magic `0x78` and the sender address.\n *\n * [RLP Encoding](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#rlp-encoding)\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Value } from 'ox'\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from({\n * chainId: 1,\n * calls: [{\n * data: '0xdeadbeef',\n * to: 'tempox0x0000000000000000000000000000000000000000',\n * }],\n * maxFeePerGas: Value.fromGwei('10'),\n * })\n *\n * const serialized = TxEnvelopeTempo.serialize(envelope) // [!code focus]\n * ```\n *\n * @example\n * ### Attaching Signatures\n *\n * It is possible to attach a `signature` to the serialized Transaction Envelope.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1, Value } from 'ox'\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from({\n * chainId: 1,\n * calls: [{\n * data: '0xdeadbeef',\n * to: 'tempox0x0000000000000000000000000000000000000000',\n * }],\n * maxFeePerGas: Value.fromGwei('10'),\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: TxEnvelopeTempo.getSignPayload(envelope),\n * privateKey: '0x...',\n * })\n *\n * const serialized = TxEnvelopeTempo.serialize(envelope, { // [!code focus]\n * signature, // [!code focus]\n * }) // [!code focus]\n *\n * // ... send `serialized` transaction to JSON-RPC `eth_sendRawTransaction`\n * ```\n *\n * @param envelope - The Transaction Envelope to serialize.\n * @param options - Options.\n * @returns The serialized Transaction Envelope.\n */\nexport function serialize(\n envelope: PartialBy<TxEnvelopeTempo, 'type'>,\n options: serialize.Options = {},\n): Serialized {\n const {\n accessList,\n authorizationList,\n calls,\n chainId,\n feeToken,\n gas,\n keyAuthorization,\n nonce,\n nonceKey,\n maxFeePerGas,\n maxPriorityFeePerGas,\n validBefore,\n validAfter,\n } = envelope\n\n assert(envelope)\n\n const accessTupleList = AccessList.toTupleList(accessList)\n const signature = options.signature || envelope.signature\n\n const authorizationTupleList =\n AuthorizationTempo.toTupleList(authorizationList)\n\n // Encode calls as RLP list of [to, value, data] tuples\n const callsTupleList = calls.map((call) => [\n call.to ? TempoAddress.resolve(call.to) : '0x',\n call.value ? Hex.fromNumber(call.value) : '0x',\n call.data ?? '0x',\n ])\n\n let skipFeeToken = false\n const feePayerSignatureOrSender = (() => {\n // Explicit sender address provided — use as-is.\n if (options.sender) return options.sender\n\n // When serializing in fee payer format and a signature is present,\n // derive the sender address from the signature so the fee payer proxy\n // knows which account to cover fees for.\n //\n // - secp256k1: recover address via ecrecover from the sign payload.\n // - p256/webAuthn: derive address from the embedded public key.\n // - keychain: use the explicit `userAddress` on the signature.\n if (options.format === 'feePayer' && signature) {\n const sig = SignatureEnvelope.from(signature)\n if (sig.type === 'keychain') return sig.userAddress\n if (sig.type === 'p256' || sig.type === 'webAuthn')\n return Address.fromPublicKey(sig.publicKey)\n if (sig.type === 'secp256k1')\n return Secp256k1.recoverAddress({\n payload: getSignPayload(from(envelope)),\n signature: sig.signature,\n })\n }\n\n const feePayerSignature =\n typeof options.feePayerSignature !== 'undefined'\n ? options.feePayerSignature\n : envelope.feePayerSignature\n // `null` indicates the envelope is intended to be signed by a fee payer\n // but hasn't been signed yet — encode as a single zero byte marker.\n // The sender does not commit to feeToken, so skip it.\n if (feePayerSignature === null) {\n skipFeeToken = true\n return '0x00'\n }\n // No fee payer involvement — omit from the envelope.\n if (!feePayerSignature) return '0x'\n // Fee payer has signed — encode the signature as an RLP tuple.\n return Signature.toTuple(feePayerSignature)\n })()\n\n const serialized = [\n Hex.fromNumber(chainId),\n maxPriorityFeePerGas ? Hex.fromNumber(maxPriorityFeePerGas) : '0x',\n maxFeePerGas ? Hex.fromNumber(maxFeePerGas) : '0x',\n gas ? Hex.fromNumber(gas) : '0x',\n callsTupleList,\n accessTupleList,\n nonceKey ? Hex.fromNumber(nonceKey) : '0x',\n nonce ? Hex.fromNumber(nonce) : '0x',\n typeof validBefore === 'number' ? Hex.fromNumber(validBefore) : '0x',\n typeof validAfter === 'number' ? Hex.fromNumber(validAfter) : '0x',\n !skipFeeToken &&\n (typeof feeToken === 'bigint' || typeof feeToken === 'string')\n ? TokenId.toAddress(feeToken)\n : '0x',\n feePayerSignatureOrSender,\n authorizationTupleList,\n ...(keyAuthorization ? [KeyAuthorization.toTuple(keyAuthorization)] : []),\n ...(signature\n ? [SignatureEnvelope.serialize(SignatureEnvelope.from(signature))]\n : []),\n ] as const\n\n return Hex.concat(\n options.format === 'feePayer' ? feePayerMagic : serializedType,\n Rlp.fromHex(serialized),\n ) as Serialized\n}\n\nexport declare namespace serialize {\n type Options = {\n /**\n * Sender signature to append to the serialized envelope.\n */\n signature?: SignatureEnvelope.from.Value | undefined\n } & OneOf<\n | {\n /**\n * Sender address to cover the fee of.\n *\n * If not provided and a signature is present, the sender will be\n * automatically derived from the signature.\n */\n sender?: Address.Address | undefined\n /**\n * Whether to serialize the transaction in the fee payer format.\n *\n * - If `'feePayer'`, then the transaction will be serialized in the fee payer format.\n * - If `undefined` (default), then the transaction will be serialized in the normal format.\n */\n format: 'feePayer'\n }\n | {\n /**\n * Fee payer signature or the sender to cover the fee of.\n *\n * - If `Signature.Signature`, then this is the fee payer signature.\n * - If `null`, then this indicates the envelope is intended to be signed by a fee payer.\n */\n feePayerSignature?: Signature.Signature | null | undefined\n format?: undefined\n }\n >\n\n type ErrorType =\n | assert.ErrorType\n | Hex.fromNumber.ErrorType\n | Signature.toTuple.ErrorType\n | Hex.concat.ErrorType\n | Rlp.fromHex.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Returns the payload to sign for a {@link ox#TxEnvelopeTempo.TxEnvelopeTempo}.\n *\n * Computes the keccak256 hash of the unsigned serialized transaction. Sign this payload\n * with secp256k1, P256, or WebAuthn, then attach the signature via {@link ox#TxEnvelopeTempo.(from:function)}.\n *\n * [Tempo Transaction Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction)\n *\n * @example\n * The example below demonstrates how to compute the sign payload which can be used\n * with ECDSA signing utilities like {@link ox#Secp256k1.(sign:function)}.\n *\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from({\n * chainId: 1,\n * calls: [{\n * data: '0xdeadbeef',\n * to: 'tempox0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * }],\n * nonce: 0n,\n * maxFeePerGas: 1000000000n,\n * gas: 21000n,\n * })\n *\n * const payload = TxEnvelopeTempo.getSignPayload(envelope) // [!code focus]\n * // @log: '0x...'\n *\n * const signature = Secp256k1.sign({ payload, privateKey: '0x...' })\n * ```\n *\n * @example\n * ### Access Keys\n *\n * When signing as an access key on behalf of a root account, pass the\n * `from` option with the root account address. This computes\n * `keccak256(0x04 || sigHash || from)` which binds the signature to the\n * specific user account (V2 keychain format).\n *\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { TxEnvelopeTempo, SignatureEnvelope } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from({\n * chainId: 1,\n * calls: [{\n * data: '0xdeadbeef',\n * to: 'tempox0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * }],\n * nonce: 0n,\n * maxFeePerGas: 1000000000n,\n * gas: 21000n,\n * })\n *\n * const payload = TxEnvelopeTempo.getSignPayload(envelope, { from: '0x...' }) // [!code focus]\n *\n * const signature = Secp256k1.sign({ payload, privateKey: '0x...' })\n *\n * const signed = TxEnvelopeTempo.serialize(envelope, {\n * signature: SignatureEnvelope.from({\n * userAddress: from,\n * inner: SignatureEnvelope.from(signature),\n * }),\n * })\n * ```\n *\n * @param envelope - The transaction envelope to get the sign payload for.\n * @param options - Options.\n * @returns The sign payload.\n */\nexport function getSignPayload(\n envelope: TxEnvelopeTempo,\n options: getSignPayload.Options = {},\n): getSignPayload.ReturnValue {\n const sigHash = hash(envelope, { presign: true })\n if (options.from)\n return Hash.keccak256(\n Hex.concat('0x04', sigHash, TempoAddress.resolve(options.from)),\n )\n return sigHash\n}\n\nexport declare namespace getSignPayload {\n type Options = {\n /**\n * The root account address for access key signing.\n *\n * When provided, computes `keccak256(0x04 || sigHash || from)` instead of\n * the raw `sigHash`, binding the access key signature to the specific user account.\n */\n from?: TempoAddress.Address | undefined\n }\n\n type ReturnValue = Hex.Hex\n\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Hashes a {@link ox#TxEnvelopeTempo.TxEnvelopeTempo}. This is the \"transaction hash\".\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from({\n * chainId: 1,\n * calls: [{\n * data: '0xdeadbeef',\n * to: 'tempox0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * }],\n * nonce: 0n,\n * maxFeePerGas: 1000000000n,\n * gas: 21000n,\n * })\n *\n * const signature = Secp256k1.sign({\n * payload: TxEnvelopeTempo.getSignPayload(envelope),\n * privateKey: '0x...'\n * })\n *\n * const envelope_signed = TxEnvelopeTempo.from(envelope, { signature })\n *\n * const hash = TxEnvelopeTempo.hash(envelope_signed) // [!code focus]\n * ```\n *\n * @param envelope - The Tempo Transaction Envelope to hash.\n * @param options - Options.\n * @returns The hash of the transaction envelope.\n */\nexport function hash<presign extends boolean = false>(\n envelope: TxEnvelopeTempo<presign extends true ? false : true>,\n options: hash.Options<presign> = {},\n): hash.ReturnValue {\n const serialized = serialize({\n ...envelope,\n ...(options.presign\n ? {\n signature: undefined,\n // When a fee payer signature is present, normalize to `null`\n // (the presign marker).\n ...(envelope.feePayerSignature !== undefined\n ? { feePayerSignature: null }\n : {}),\n }\n : {}),\n })\n return Hash.keccak256(serialized)\n}\n\nexport declare namespace hash {\n type Options<presign extends boolean = false> = {\n /**\n * Whether to hash this transaction for signing.\n *\n * @default false\n */\n presign?: presign | boolean | undefined\n }\n\n type ReturnValue = Hex.Hex\n\n type ErrorType =\n | Hash.keccak256.ErrorType\n | serialize.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Returns the fee payer payload to sign for a {@link ox#TxEnvelopeTempo.TxEnvelopeTempo}.\n *\n * Fee sponsorship uses a dual-signature scheme: the sender signs the transaction, then a fee payer\n * signs over the transaction with the sender's address to commit to paying fees. The fee payer's\n * signature includes the `feeToken` and `sender_address`, using magic byte `0x78` for domain separation.\n *\n * [Fee Payer Signature](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#fee-payer-signature)\n * [Fee Sponsorship Guide](https://docs.tempo.xyz/protocol/transactions#fee-sponsorship)\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Secp256k1 } from 'ox'\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const envelope = TxEnvelopeTempo.from({\n * chainId: 1,\n * calls: [{\n * data: '0xdeadbeef',\n * to: 'tempox0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * }],\n * nonce: 0n,\n * maxFeePerGas: 1000000000n,\n * gas: 21000n,\n * })\n *\n * const payload = TxEnvelopeTempo.getFeePayerSignPayload(envelope, {\n * sender: 'tempox0xd8da6bf26964af9d7eed9e03e53415d37aa96045'\n * }) // [!code focus]\n * // @log: '0x...'\n *\n * const signature = Secp256k1.sign({ payload, privateKey: '0x...' })\n * ```\n *\n * @param envelope - The transaction envelope to get the fee payer sign payload for.\n * @param options - Options.\n * @returns The fee payer sign payload.\n */\nexport function getFeePayerSignPayload(\n envelope: TxEnvelopeTempo,\n options: getFeePayerSignPayload.Options,\n): getFeePayerSignPayload.ReturnValue {\n const sender = TempoAddress.resolve(options.sender)\n const serialized = serialize(\n { ...envelope, signature: undefined },\n {\n sender,\n format: 'feePayer',\n },\n )\n return Hash.keccak256(serialized)\n}\n\nexport declare namespace getFeePayerSignPayload {\n type Options = {\n /**\n * Sender address to cover the fee of.\n */\n sender: TempoAddress.Address\n }\n\n type ReturnValue = Hex.Hex\n\n type ErrorType = hash.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Validates a {@link ox#TxEnvelopeTempo.TxEnvelopeTempo}. Returns `true` if the envelope is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * const valid = TxEnvelopeTempo.validate({\n * calls: [{\n * data: '0xdeadbeef',\n * to: 'tempox0x0000000000000000000000000000000000000000',\n * }],\n * chainId: 1,\n * maxFeePerGas: 1000000000n,\n * })\n * // @log: true\n * ```\n *\n * @param envelope - The transaction envelope to validate.\n */\nexport function validate(envelope: PartialBy<TxEnvelopeTempo, 'type'>) {\n try {\n assert(envelope)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Thrown when a transaction's calls list is empty.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * TxEnvelopeTempo.assert({\n * calls: [],\n * chainId: 1,\n * })\n * // @error: TxEnvelopeTempo.CallsEmptyError: Calls list cannot be empty.\n * ```\n */\nexport class CallsEmptyError extends Errors.BaseError {\n override readonly name = 'TxEnvelopeTempo.CallsEmptyError'\n constructor() {\n super('Calls list cannot be empty.')\n }\n}\n\n/**\n * Thrown when validBefore is not greater than validAfter.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeTempo } from 'ox/tempo'\n *\n * TxEnvelopeTempo.assert({\n * calls: [{ to: 'tempox0x0000000000000000000000000000000000000000' }],\n * chainId: 1,\n * validBefore: 100,\n * validAfter: 200,\n * })\n * // @error: TxEnvelopeTempo.InvalidValidityWindowError: validBefore (100) must be greater than validAfter (200).\n * ```\n */\nexport class InvalidValidityWindowError extends Errors.BaseError {\n override readonly name = 'TxEnvelopeTempo.InvalidValidityWindowError'\n constructor({\n validBefore,\n validAfter,\n }: {\n validBefore: number\n validAfter: number\n }) {\n super(\n `validBefore (${validBefore}) must be greater than validAfter (${validAfter}).`,\n )\n }\n}\n","import * as Address from './Address.js'\nimport * as Errors from './Errors.js'\nimport * as Hash from './Hash.js'\nimport * as Hex from './Hex.js'\nimport type { Compute, Mutable } from './internal/types.js'\n\nexport type AccessList = Compute<readonly Item[]>\n\nexport type Item = Compute<{\n address: Address.Address\n storageKeys: readonly Hex.Hex[]\n}>\n\nexport type ItemTuple = Compute<\n [address: Address.Address, storageKeys: readonly Hex.Hex[]]\n>\n\nexport type Tuple = readonly ItemTuple[]\n\n/**\n * Converts a list of Access List tuples into a object-formatted list.\n *\n * @example\n * ```ts twoslash\n * import { AccessList } from 'ox'\n *\n * const accessList = AccessList.fromTupleList([\n * [\n * '0x0000000000000000000000000000000000000000',\n * [\n * '0x0000000000000000000000000000000000000000000000000000000000000001',\n * '0x60fdd29ff912ce880cd3edaf9f932dc61d3dae823ea77e0323f94adb9f6a72fe',\n * ],\n * ],\n * ])\n * // @log: [\n * // @log: {\n * // @log: address: '0x0000000000000000000000000000000000000000',\n * // @log: storageKeys: [\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * // @log: '0x60fdd29ff912ce880cd3edaf9f932dc61d3dae823ea77e0323f94adb9f6a72fe',\n * // @log: ],\n * // @log: },\n * // @log: ]\n * ```\n *\n * @param accessList - List of tuples.\n * @returns Access list.\n */\nexport function fromTupleList(accessList: Tuple): AccessList {\n const list: Mutable<AccessList> = []\n for (let i = 0; i < accessList.length; i++) {\n const [address, storageKeys] = accessList[i] as [Hex.Hex, Hex.Hex[]]\n\n if (address) Address.assert(address, { strict: false })\n\n list.push({\n address: address,\n storageKeys: storageKeys.map((key) =>\n Hash.validate(key) ? key : Hex.trimLeft(key),\n ),\n })\n }\n return list\n}\n\n/**\n * Converts a structured Access List into a list of tuples.\n *\n * @example\n * ```ts twoslash\n * import { AccessList } from 'ox'\n *\n * const accessList = AccessList.toTupleList([\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * storageKeys: [\n * '0x0000000000000000000000000000000000000000000000000000000000000001',\n * '0x60fdd29ff912ce880cd3edaf9f932dc61d3dae823ea77e0323f94adb9f6a72fe'],\n * },\n * ])\n * // @log: [\n * // @log: [\n * // @log: '0x0000000000000000000000000000000000000000',\n * // @log: [\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001',\n * // @log: '0x60fdd29ff912ce880cd3edaf9f932dc61d3dae823ea77e0323f94adb9f6a72fe',\n * // @log: ],\n * // @log: ],\n * // @log: ]\n * ```\n *\n * @param accessList - Access list.\n * @returns List of tuples.\n */\nexport function toTupleList(\n accessList?: AccessList | undefined,\n): Compute<Tuple> {\n if (!accessList || accessList.length === 0) return []\n\n const tuple: Mutable<Tuple> = []\n for (const { address, storageKeys } of accessList) {\n for (let j = 0; j < storageKeys.length; j++)\n if (Hex.size(storageKeys[j]!) !== 32)\n throw new InvalidStorageKeySizeError({\n storageKey: storageKeys[j]!,\n })\n\n if (address) Address.assert(address, { strict: false })\n\n tuple.push([address, storageKeys])\n }\n return tuple\n}\n\n/** Thrown when the size of a storage key is invalid. */\nexport class InvalidStorageKeySizeError extends Errors.BaseError {\n override readonly name = 'AccessList.InvalidStorageKeySizeError'\n constructor({ storageKey }: { storageKey: Hex.Hex }) {\n super(\n `Size for storage key \"${storageKey}\" is invalid. Expected 32 bytes. Got ${Hex.size(storageKey)} bytes.`,\n )\n }\n}\n","import * as Errors from './Errors.js'\n\n/** @see https://ethereum.github.io/yellowpaper/paper.pdf */\nexport const exponents = {\n wei: 0,\n gwei: 9,\n szabo: 12,\n finney: 15,\n ether: 18,\n} as const\n\n/**\n * Formats a `bigint` Value to its string representation (divided by the given exponent).\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.format(420_000_000_000n, 9)\n * // @log: '420'\n * ```\n *\n * @param value - The `bigint` Value to format.\n * @param decimals - The exponent to divide the `bigint` Value by.\n * @returns The string representation of the Value.\n */\nexport function format(value: bigint, decimals = 0) {\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\nexport declare namespace format {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Formats a `bigint` Value (default: wei) to a string representation of Ether.\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.formatEther(1_000_000_000_000_000_000n)\n * // @log: '1'\n * ```\n *\n * @param wei - The Value to format.\n * @param unit - The unit to format the Value in. @default 'wei'.\n * @returns The Ether string representation of the Value.\n */\nexport function formatEther(\n wei: bigint,\n unit: 'wei' | 'gwei' | 'szabo' | 'finney' = 'wei',\n) {\n return format(wei, exponents.ether - exponents[unit])\n}\n\nexport declare namespace formatEther {\n type ErrorType = format.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Formats a `bigint` Value (default: wei) to a string representation of Gwei.\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.formatGwei(1_000_000_000n)\n * // @log: '1'\n * ```\n *\n * @param wei - The Value to format.\n * @param unit - The unit to format the Value in. @default 'wei'.\n * @returns The Gwei string representation of the Value.\n */\nexport function formatGwei(wei: bigint, unit: 'wei' = 'wei') {\n return format(wei, exponents.gwei - exponents[unit])\n}\n\nexport declare namespace formatGwei {\n type ErrorType = format.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Parses a `string` representation of a Value to `bigint` (multiplied by the given exponent).\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.from('420', 9)\n * // @log: 420000000000n\n * ```\n *\n * @param value - The string representation of the Value.\n * @param decimals - The exponent to multiply the Value by.\n * @returns The `bigint` representation of the Value.\n */\nexport function from(value: string, decimals = 0) {\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\nexport declare namespace from {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Parses a string representation of Ether to a `bigint` Value (default: wei).\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.fromEther('420')\n * // @log: 420000000000000000000n\n * ```\n *\n * @param ether - String representation of Ether.\n * @param unit - The unit to parse to. @default 'wei'.\n * @returns A `bigint` Value.\n */\nexport function fromEther(\n ether: string,\n unit: 'wei' | 'gwei' | 'szabo' | 'finney' = 'wei',\n) {\n return from(ether, exponents.ether - exponents[unit])\n}\n\nexport declare namespace fromEther {\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Parses a string representation of Gwei to a `bigint` Value (default: wei).\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.fromGwei('420')\n * // @log: 420000000000n\n * ```\n *\n * @param gwei - String representation of Gwei.\n * @param unit - The unit to parse to. @default 'wei'.\n * @returns A `bigint` Value.\n */\nexport function fromGwei(gwei: string, unit: 'wei' = 'wei') {\n return from(gwei, exponents.gwei - exponents[unit])\n}\n\nexport declare namespace fromGwei {\n type ErrorType = from.ErrorType | Errors.GlobalErrorType\n}\n\n/**\n * Thrown when a value is not a valid decimal number.\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.fromEther('123.456.789')\n * // @error: Value.InvalidDecimalNumberError: Value `123.456.789` is not a valid decimal number.\n * ```\n */\nexport class InvalidDecimalNumberError extends Errors.BaseError {\n override readonly name = 'Value.InvalidDecimalNumberError'\n constructor({ value }: { value: string }) {\n super(`Value \\`${value}\\` is not a valid decimal number.`)\n }\n}\n","import type * as Address from './Address.js'\nimport * as Errors from './Errors.js'\nimport type * as Hex from './Hex.js'\nimport type { Compute } from './internal/types.js'\nimport * as Value from './Value.js'\n\n/** Base type for a Transaction Envelope. Transaction Envelopes inherit this type. */\nexport type Base<\n type extends string = string,\n signed extends boolean = boolean,\n bigintType = bigint,\n numberType = number,\n> = Compute<\n {\n /** EIP-155 Chain ID. */\n chainId: numberType\n /** Contract code or a hashed method call with encoded args */\n data?: Hex.Hex | undefined\n /** @alias `data` – added for TransactionEnvelope - Transaction compatibility. */\n input?: Hex.Hex | undefined\n /** Sender of the transaction. */\n from?: Address.Address | undefined\n /** Gas provided for transaction execution */\n gas?: bigintType | undefined\n /** Unique number identifying this transaction */\n nonce?: bigintType | undefined\n /** Transaction recipient */\n to?: Address.Address | null | undefined\n /** Transaction type */\n type: type\n /** Value in wei sent with this transaction */\n value?: bigintType | undefined\n /** ECDSA signature r. */\n r?: bigintType | undefined\n /** ECDSA signature s. */\n s?: bigintType | undefined\n /** ECDSA signature yParity. */\n yParity?: numberType | undefined\n /** @deprecated ECDSA signature v (for backwards compatibility). */\n v?: numberType | undefined\n } & (signed extends true ? { r: bigintType; s: bigintType } : {})\n>\n\n/** RPC representation of a {@link ox#(TransactionEnvelope:namespace).Base}. */\nexport type BaseRpc<\n type extends string = string,\n signed extends boolean = boolean,\n> = Base<type, signed, Hex.Hex, Hex.Hex>\n\n/** Signed representation of a {@link ox#(TransactionEnvelope:namespace).Base}. */\nexport type BaseSigned<type extends string = string> = Base<type, true>\n\n/**\n * Thrown when a fee cap is too high.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeEip1559 } from 'ox'\n *\n * TxEnvelopeEip1559.assert({\n * maxFeePerGas: 2n ** 256n - 1n + 1n,\n * chainId: 1,\n * })\n * // @error: TransactionEnvelope.FeeCapTooHighError: The fee cap (`maxFeePerGas`/`maxPriorityFeePerGas` = 115792089237316195423570985008687907853269984665640564039457584007913.129639936 gwei) cannot be higher than the maximum allowed value (2^256-1).\n * ```\n */\nexport class FeeCapTooHighError extends Errors.BaseError {\n override readonly name = 'TransactionEnvelope.FeeCapTooHighError'\n constructor({\n feeCap,\n }: {\n feeCap?: bigint | undefined\n } = {}) {\n super(\n `The fee cap (\\`maxFeePerGas\\`/\\`maxPriorityFeePerGas\\`${\n feeCap ? ` = ${Value.formatGwei(feeCap)} gwei` : ''\n }) cannot be higher than the maximum allowed value (2^256-1).`,\n )\n }\n}\n\n/**\n * Thrown when a gas price is too high.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeLegacy } from 'ox'\n *\n * TxEnvelopeLegacy.assert({\n * gasPrice: 2n ** 256n - 1n + 1n,\n * chainId: 1,\n * })\n * // @error: TransactionEnvelope.GasPriceTooHighError: The gas price (`gasPrice` = 115792089237316195423570985008687907853269984665640564039457584007913.129639936 gwei) cannot be higher than the maximum allowed value (2^256-1).\n * ```\n */\nexport class GasPriceTooHighError extends Errors.BaseError {\n override readonly name = 'TransactionEnvelope.GasPriceTooHighError'\n constructor({\n gasPrice,\n }: {\n gasPrice?: bigint | undefined\n } = {}) {\n super(\n `The gas price (\\`gasPrice\\`${\n gasPrice ? ` = ${Value.formatGwei(gasPrice)} gwei` : ''\n }) cannot be higher than the maximum allowed value (2^256-1).`,\n )\n }\n}\n\n/**\n * Thrown when a chain ID is invalid.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeEip1559 } from 'ox'\n *\n * TxEnvelopeEip1559.assert({ chainId: 0 })\n * // @error: TransactionEnvelope.InvalidChainIdError: Chain ID \"0\" is invalid.\n * ```\n */\nexport class InvalidChainIdError extends Errors.BaseError {\n override readonly name = 'TransactionEnvelope.InvalidChainIdError'\n constructor({ chainId }: { chainId?: number | undefined }) {\n super(\n typeof chainId !== 'undefined'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.',\n )\n }\n}\n\n/**\n * Thrown when a serialized transaction is invalid.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeEip1559 } from 'ox'\n *\n * TxEnvelopeEip1559.deserialize('0x02c0')\n * // @error: TransactionEnvelope.InvalidSerializedError: Invalid serialized transaction of type \"eip1559\" was provided.\n * // @error: Serialized Transaction: \"0x02c0\"\n * // @error: Missing Attributes: chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gas, to, value, data, accessList\n * ```\n */\nexport class InvalidSerializedError extends Errors.BaseError {\n override readonly name = 'TransactionEnvelope.InvalidSerializedError'\n constructor({\n attributes,\n serialized,\n type,\n }: {\n attributes: Record<string, unknown>\n serialized: Hex.Hex\n type: string\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: \"${serialized}\"`,\n missing.length > 0 ? `Missing Attributes: ${missing.join(', ')}` : '',\n ].filter(Boolean),\n })\n }\n}\n\n/**\n * Thrown when a tip is higher than a fee cap.\n *\n * @example\n * ```ts twoslash\n * import { TxEnvelopeEip1559 } from 'ox'\n *\n * TxEnvelopeEip1559.assert({\n * chainId: 1,\n * maxFeePerGas: 10n,\n * maxPriorityFeePerGas: 11n,\n * })\n * // @error: TransactionEnvelope.TipAboveFeeCapError: The provided tip (`maxPriorityFeePerGas` = 11 gwei) cannot be higher than the fee cap (`maxFeePerGas` = 10 gwei).\n * ```\n */\nexport class TipAboveFeeCapError extends Errors.BaseError {\n override readonly name = 'TransactionEnvelope.TipAboveFeeCapError'\n constructor({\n maxPriorityFeePerGas,\n maxFeePerGas,\n }: {\n maxPriorityFeePerGas?: bigint | undefined\n maxFeePerGas?: bigint | undefined\n } = {}) {\n super(\n [\n `The provided tip (\\`maxPriorityFeePerGas\\`${\n maxPriorityFeePerGas\n ? ` = ${Value.formatGwei(maxPriorityFeePerGas)} gwei`\n : ''\n }) cannot be higher than the fee cap (\\`maxFeePerGas\\`${\n maxFeePerGas ? ` = ${Value.formatGwei(maxFeePerGas)} gwei` : ''\n }).`,\n ].join('\\n'),\n )\n }\n}\n","// TODO: Find opportunities to make this file less duplicated + more simplified with Viem v3.\n\nimport type { Address } from 'abitype'\nimport * as Hex from 'ox/Hex'\nimport * as Secp256k1 from 'ox/Secp256k1'\nimport * as Signature from 'ox/Signature'\nimport {\n type AuthorizationTempo,\n type KeyAuthorization,\n type TransactionReceipt as ox_TransactionReceipt,\n SignatureEnvelope,\n type TempoAddress,\n TxEnvelopeTempo as TxTempo,\n} from 'ox/tempo'\nimport type { Account } from '../accounts/types.js'\nimport type { FeeValuesEIP1559 } from '../types/fee.js'\nimport type { Signature as viem_Signature } from '../types/misc.js'\nimport type {\n RpcTransaction as viem_RpcTransaction,\n RpcTransactionRequest as viem_RpcTransactionRequest,\n} from '../types/rpc.js'\nimport type {\n AccessList,\n TransactionBase,\n TransactionRequestBase,\n TransactionSerializableBase,\n TransactionSerializedGeneric,\n Transaction as viem_Transaction,\n TransactionReceipt as viem_TransactionReceipt,\n TransactionRequest as viem_TransactionRequest,\n TransactionSerializable as viem_TransactionSerializable,\n TransactionSerialized as viem_TransactionSerialized,\n TransactionType as viem_TransactionType,\n} from '../types/transaction.js'\nimport type { ExactPartial, OneOf, PartialBy } from '../types/utils.js'\nimport { getTransactionType as viem_getTransactionType } from '../utils/transaction/getTransactionType.js'\nimport {\n type ParseTransactionReturnType,\n parseTransaction as viem_parseTransaction,\n} from '../utils/transaction/parseTransaction.js'\nimport { serializeTransaction as viem_serializeTransaction } from '../utils/transaction/serializeTransaction.js'\n\nexport type Transaction<\n bigintType = bigint,\n numberType = number,\n pending extends boolean = false,\n> = OneOf<\n | viem_Transaction<bigintType, numberType, pending>\n | TransactionTempo<bigintType, numberType, pending>\n>\nexport type TransactionRpc<pending extends boolean = false> = OneOf<\n | viem_RpcTransaction<pending>\n | (Omit<\n TransactionTempo<Hex.Hex, Hex.Hex, pending, '0x76'>,\n 'authorizationList' | 'keyAuthorization' | 'signature'\n > & {\n authorizationList?: AuthorizationTempo.ListRpc | undefined\n keyAuthorization?: KeyAuthorization.Rpc | null | undefined\n signature: SignatureEnvelope.SignatureEnvelopeRpc\n })\n>\n\nexport type TransactionTempo<\n quantity = bigint,\n index = number,\n isPending extends boolean = boolean,\n type = 'tempo',\n> = PartialBy<\n Omit<TransactionBase<quantity, index, isPending>, 'input' | 'value' | 'to'>,\n 'r' | 's' | 'v' | 'yParity'\n> & {\n accessList: AccessList\n authorizationList?: AuthorizationTempo.ListSigned<quantity, index> | undefined\n calls: readonly TxTempo.Call<quantity>[]\n chainId: index\n feeToken?: TempoAddress.Address | undefined\n feePayerSignature?: viem_Signature | undefined\n keyAuthorization?: KeyAuthorization.Signed<quantity, index> | null | undefined\n nonceKey?: quantity | undefined\n signature: SignatureEnvelope.SignatureEnvelope\n type: type\n validBefore?: index | undefined\n validAfter?: index | undefined\n} & FeeValuesEIP1559<quantity>\n\nexport type TransactionRequest<\n bigintType = bigint,\n numberType = number,\n> = OneOf<\n | viem_TransactionRequest<bigintType, numberType>\n | TransactionRequestTempo<bigintType, numberType>\n>\nexport type TransactionRequestRpc = OneOf<\n viem_RpcTransactionRequest | TransactionRequestTempo<Hex.Hex, Hex.Hex, '0x76'>\n>\n\nexport type TransactionReceipt<\n quantity = bigint,\n index = number,\n status = 'success' | 'reverted',\n type = TransactionType,\n> = viem_TransactionReceipt<quantity, index, status, type> & {\n feePayer?: TempoAddress.Address | undefined\n feeToken?: TempoAddress.Address | undefined\n}\n\nexport type TransactionReceiptRpc = TransactionReceipt<\n Hex.Hex,\n Hex.Hex,\n ox_TransactionReceipt.RpcStatus,\n ox_TransactionReceipt.RpcType\n>\n\nexport type TransactionRequestTempo<\n quantity = bigint,\n index = number,\n type = 'tempo',\n> = TransactionRequestBase<quantity, index, type> &\n ExactPartial<FeeValuesEIP1559<quantity>> & {\n accessList?: AccessList | undefined\n keyAuthorization?: KeyAuthorization.Signed<quantity, index> | undefined\n calls?: readonly TxTempo.Call<quantity, TempoAddress.Address>[] | undefined\n feePayer?: Account | true | undefined\n feeToken?: TempoAddress.Address | bigint | undefined\n nonceKey?: 'expiring' | quantity | undefined\n validBefore?: index | undefined\n validAfter?: index | undefined\n }\n\nexport type TransactionSerializable = OneOf<\n viem_TransactionSerializable | TransactionSerializableTempo\n>\n\nexport type TransactionSerializableTempo<\n quantity = bigint,\n index = number,\n> = TransactionSerializableBase<quantity, index> &\n ExactPartial<FeeValuesEIP1559<quantity>> & {\n accessList?: AccessList | undefined\n calls: readonly TxTempo.Call<quantity, TempoAddress.Address>[]\n chainId: number\n feeToken?: TempoAddress.Address | bigint | undefined\n feePayerSignature?: viem_Signature | null | undefined\n from?: TempoAddress.Address | undefined\n keyAuthorization?: KeyAuthorization.Signed<quantity, index> | undefined\n nonceKey?: quantity | undefined\n signature?: SignatureEnvelope.SignatureEnvelope<quantity, index> | undefined\n validBefore?: index | undefined\n validAfter?: index | undefined\n type?: 'tempo' | undefined\n }\n\nexport type TransactionSerialized<\n type extends TransactionType = TransactionType,\n> = viem_TransactionSerialized<type> | TransactionSerializedTempo\n\nexport type TransactionSerializedTempo = `0x76${string}`\nexport type TransactionSerializedFeePayer = `0x78${string}`\n\nexport type TransactionType = viem_TransactionType | 'tempo'\n\nexport function getType(\n transaction: Record<string, unknown>,\n): Transaction['type'] {\n const account = transaction.account as\n | { keyType?: string | undefined }\n | undefined\n if (\n (account?.keyType && account.keyType !== 'secp256k1') ||\n typeof transaction.calls !== 'undefined' ||\n typeof transaction.feePayer !== 'undefined' ||\n typeof transaction.feeToken !== 'undefined' ||\n typeof transaction.keyAuthorization !== 'undefined' ||\n typeof transaction.nonceKey !== 'undefined' ||\n typeof transaction.signature !== 'undefined' ||\n typeof transaction.validBefore !== 'undefined' ||\n typeof transaction.validAfter !== 'undefined'\n )\n return 'tempo' as never\n if (transaction.type) return transaction.type as never\n return viem_getTransactionType(transaction) as never\n}\n\nexport function isTempo(transaction: Record<string, unknown>) {\n try {\n const type = getType(transaction)\n return type === 'tempo'\n } catch {\n return false\n }\n}\n\nexport function deserialize<\n const serialized extends TransactionSerializedGeneric,\n>(serializedTransaction: serialized): deserialize.ReturnValue<serialized> {\n const type = Hex.slice(serializedTransaction, 0, 1)\n if (type === '0x76' || type === '0x78')\n return deserializeTempo(serializedTransaction as `0x76${string}`) as never\n return viem_parseTransaction(serializedTransaction) as never\n}\n\nexport declare namespace deserialize {\n export type ReturnValue<\n serialized extends\n TransactionSerializedGeneric = TransactionSerializedGeneric,\n > = serialized extends TransactionSerializedTempo\n ? TransactionSerializableTempo\n : serialized extends TransactionSerializedFeePayer\n ? TransactionSerializableTempo\n : ParseTransactionReturnType<serialized>\n}\n\nexport async function serialize(\n transaction: TransactionSerializable & {\n feePayer?: Account | true | undefined\n from?: TempoAddress.Address | undefined\n },\n signature?:\n | OneOf<SignatureEnvelope.SignatureEnvelope | viem_Signature>\n | undefined,\n) {\n // If the transaction is not a Tempo transaction, route to Viem serializer.\n if (!isTempo(transaction)) {\n if (signature && 'type' in signature && signature.type !== 'secp256k1')\n throw new Error(\n 'Unsupported signature type. Expected `secp256k1` but got `' +\n signature.type +\n '`.',\n )\n if (signature && 'type' in signature) {\n const { r, s, yParity } = signature?.signature!\n return viem_serializeTransaction(transaction as never, {\n r: Hex.fromNumber(r, { size: 32 }),\n s: Hex.fromNumber(s, { size: 32 }),\n yParity,\n })\n }\n return viem_serializeTransaction(transaction as never, signature)\n }\n\n const type = getType(transaction)\n if (type === 'tempo') return serializeTempo(transaction as never, signature)\n\n throw new Error('Unsupported transaction type')\n}\n\n////////////////////////////////////////////////////////////////////////////////////\n// Internal\n\n/** @internal */\nfunction deserializeTempo(\n serializedTransaction: TransactionSerializedTempo,\n): TransactionSerializableTempo {\n const { feePayerSignature, nonce, ...tx } = TxTempo.deserialize(\n serializedTransaction,\n )\n return {\n ...tx,\n nonce: Number(nonce ?? 0n),\n feePayerSignature: feePayerSignature\n ? {\n r: Hex.fromNumber(feePayerSignature.r, { size: 32 }),\n s: Hex.fromNumber(feePayerSignature.s, { size: 32 }),\n yParity: feePayerSignature.yParity,\n }\n : feePayerSignature,\n } satisfies TransactionSerializableTempo\n}\n\n/** @internal */\nasync function serializeTempo(\n transaction: TransactionSerializableTempo & {\n feePayer?: Account | true | undefined\n from?: Address | undefined\n },\n sig?: OneOf<SignatureEnvelope.SignatureEnvelope | viem_Signature> | undefined,\n) {\n const signature = (() => {\n if (transaction.signature) return transaction.signature\n if (sig && 'type' in sig) return sig as SignatureEnvelope.SignatureEnvelope\n if (sig)\n return SignatureEnvelope.from({\n r: BigInt(sig.r!),\n s: BigInt(sig.s!),\n yParity: Number(sig.yParity!),\n })\n return undefined\n })()\n\n const { chainId, feePayer, feePayerSignature, nonce, ...rest } = transaction\n\n const transaction_ox = {\n ...rest,\n calls: rest.calls?.length\n ? rest.calls\n : [\n {\n to:\n rest.to ||\n (!rest.data || rest.data === '0x'\n ? '0x0000000000000000000000000000000000000000'\n : undefined),\n value: rest.value,\n data: rest.data,\n },\n ],\n chainId: Number(chainId),\n feePayerSignature: feePayerSignature\n ? {\n r: BigInt(feePayerSignature.r!),\n s: BigInt(feePayerSignature.s!),\n yParity: Number(feePayerSignature.yParity),\n }\n : feePayer\n ? null\n : undefined,\n type: 'tempo',\n ...(nonce ? { nonce: BigInt(nonce) } : {}),\n } satisfies TxTempo.TxEnvelopeTempo\n\n // If we have marked the transaction as intended to be paid\n // by a fee payer (feePayer: true), we will not use the fee token\n // as the fee payer will choose their fee token.\n if (feePayer === true) delete transaction_ox.feeToken\n\n if (signature && typeof transaction.feePayer === 'object') {\n const tx = TxTempo.from(transaction_ox, {\n signature,\n })\n\n const sender = (() => {\n if (transaction.from) return transaction.from\n if (signature.type === 'secp256k1')\n return Secp256k1.recoverAddress({\n payload: TxTempo.getSignPayload(tx),\n signature: signature.signature,\n })\n throw new Error('Unable to extract sender from transaction or signature.')\n })()\n\n const hash = TxTempo.getFeePayerSignPayload(tx, {\n sender,\n })\n\n const feePayerSignature = await transaction.feePayer.sign!({\n hash,\n })\n\n return TxTempo.serialize(tx, {\n feePayerSignature: Signature.from(feePayerSignature),\n })\n }\n\n if (feePayer === true) {\n if (signature)\n return TxTempo.serialize(transaction_ox, {\n format: 'feePayer',\n sender: transaction.from,\n signature,\n })\n return TxTempo.serialize(transaction_ox, {\n feePayerSignature: null,\n })\n }\n\n return TxTempo.serialize(\n // If we have specified a fee payer, the user will not be signing over the fee token.\n // Defer the fee token signing to the fee payer.\n { ...transaction_ox, ...(feePayer ? { feeToken: undefined } : {}) },\n {\n feePayerSignature: undefined,\n signature,\n },\n )\n}\n\n// Export types required for inference.\n// biome-ignore lint/performance/noBarrelFile: _\nexport {\n /** @deprecated */\n KeyAuthorization as z_KeyAuthorization,\n /** @deprecated */\n SignatureEnvelope as z_SignatureEnvelope,\n /** @deprecated */\n TxEnvelopeTempo as z_TxEnvelopeTempo,\n} from 'ox/tempo'\n","// TODO: Find opportunities to make this file less duplicated + more simplified with Viem v3.\n\nimport type { Address } from 'abitype'\nimport * as Hex from 'ox/Hex'\nimport {\n Transaction as ox_Transaction,\n TransactionRequest as ox_TransactionRequest,\n} from 'ox/tempo'\nimport type { Account as viem_Account } from '../accounts/types.js'\nimport { parseAccount } from '../accounts/utils/parseAccount.js'\nimport { formatTransaction as viem_formatTransaction } from '../utils/formatters/transaction.js'\nimport { formatTransactionReceipt as viem_formatTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport { formatTransactionRequest as viem_formatTransactionRequest } from '../utils/formatters/transactionRequest.js'\nimport type { Account } from './Account.js'\nimport {\n isTempo,\n type Transaction,\n type TransactionReceipt,\n type TransactionReceiptRpc,\n type TransactionRequest,\n type TransactionRequestRpc,\n type TransactionRpc,\n} from './Transaction.js'\n\nexport function formatTransaction(\n transaction: TransactionRpc,\n): Transaction<bigint, number, boolean> {\n if (!isTempo(transaction)) return viem_formatTransaction(transaction as never)\n\n const {\n feePayerSignature,\n gasPrice: _,\n nonce,\n ...tx\n } = ox_Transaction.fromRpc(transaction as never) as ox_Transaction.Tempo\n\n return {\n ...tx,\n accessList: tx.accessList!,\n feePayerSignature: feePayerSignature\n ? {\n r: Hex.fromNumber(feePayerSignature.r, { size: 32 }),\n s: Hex.fromNumber(feePayerSignature.s, { size: 32 }),\n v: BigInt(feePayerSignature.v ?? 27),\n yParity: feePayerSignature.yParity,\n }\n : undefined,\n nonce: Number(nonce),\n typeHex:\n ox_Transaction.toRpcType[\n tx.type as keyof typeof ox_Transaction.toRpcType\n ],\n type: tx.type as 'tempo',\n }\n}\n\nexport function formatTransactionReceipt(\n receipt: TransactionReceiptRpc,\n): TransactionReceipt {\n return viem_formatTransactionReceipt(receipt as never)\n}\n\nexport function formatTransactionRequest(\n r: TransactionRequest,\n action?: string | undefined,\n): TransactionRequestRpc {\n const request = r as TransactionRequest & {\n account?: viem_Account | Address | undefined\n }\n const account = request.account\n ? parseAccount<Account | viem_Account | Address>(request.account)\n : undefined\n\n // If the request is not a Tempo transaction, route to Viem formatter.\n if (!isTempo(request))\n return viem_formatTransactionRequest(\n r as never,\n action,\n ) as TransactionRequestRpc\n\n if (action)\n request.calls = request.calls ?? [\n {\n to:\n r.to ||\n (!r.data || r.data === '0x'\n ? '0x0000000000000000000000000000000000000000'\n : undefined),\n value: r.value,\n data: r.data,\n },\n ]\n\n // If we have marked the transaction as intended to be paid\n // by a fee payer (feePayer: true), we will not use the fee token\n // as the fee payer will choose their fee token.\n if (request.feePayer === true) delete request.feeToken\n\n const rpc = ox_TransactionRequest.toRpc({\n ...request,\n type: 'tempo',\n } as never)\n\n if (action === 'estimateGas') {\n rpc.maxFeePerGas = undefined\n rpc.maxPriorityFeePerGas = undefined\n }\n\n rpc.to = undefined\n rpc.data = undefined\n rpc.value = undefined\n\n const [keyType, keyData] = (() => {\n const type =\n account && 'keyType' in account ? account.keyType : account?.source\n if (!type) return [undefined, undefined]\n if (type === 'webAuthn')\n // TODO: derive correct bytes size of key data based on webauthn create metadata.\n return ['webAuthn', `0x${'ff'.repeat(1400)}`]\n if (['p256', 'secp256k1'].includes(type)) return [type, undefined]\n return [undefined, undefined]\n })()\n\n const keyId =\n account && 'accessKeyAddress' in account\n ? account.accessKeyAddress\n : undefined\n\n return {\n ...rpc,\n ...(keyData ? { keyData } : {}),\n ...(keyId ? { keyId } : {}),\n ...(keyType ? { keyType } : {}),\n ...(request.feePayer\n ? {\n feePayer:\n typeof request.feePayer === 'object'\n ? parseAccount(request.feePayer)\n : request.feePayer,\n }\n : {}),\n } as never\n}\n","const concurrentCounts = new Map<string, number>()\n\n/**\n * Detects if there are concurrent tasks occuring for a given key\n * within the same event loop tick. Registers the request, yields to allow\n * other concurrent calls to register, then returns whether multiple requests\n * were detected.\n *\n * @example\n * ```ts\n * const isConcurrent = await Concurrent.detect(address)\n * ```\n */\nexport async function detect(key: string): Promise<boolean> {\n concurrentCounts.set(key, (concurrentCounts.get(key) ?? 0) + 1)\n await Promise.resolve()\n const isConcurrent = (concurrentCounts.get(key) ?? 0) > 1\n queueMicrotask(() => {\n const count = concurrentCounts.get(key) ?? 0\n if (count <= 1) concurrentCounts.delete(key)\n else concurrentCounts.set(key, count - 1)\n })\n return isConcurrent\n}\n","import { SignatureEnvelope, type TokenId } from 'ox/tempo'\nimport { getCode } from '../actions/public/getCode.js'\nimport { verifyHash } from '../actions/public/verifyHash.js'\nimport { maxUint256 } from '../constants/number.js'\nimport type { Chain, ChainConfig as viem_ChainConfig } from '../types/chain.js'\nimport { extendSchema } from '../utils/chain/defineChain.js'\nimport { defineTransaction } from '../utils/formatters/transaction.js'\nimport { defineTransactionReceipt } from '../utils/formatters/transactionReceipt.js'\nimport { defineTransactionRequest } from '../utils/formatters/transactionRequest.js'\nimport { getAction } from '../utils/getAction.js'\nimport type { SerializeTransactionFn } from '../utils/transaction/serializeTransaction.js'\nimport type { Account } from './Account.js'\nimport * as Formatters from './Formatters.js'\nimport * as Concurrent from './internal/concurrent.js'\nimport * as Transaction from './Transaction.js'\n\nconst maxExpirySecs = 25\n\nexport const chainConfig = {\n blockTime: 1_000,\n extendSchema: extendSchema<{\n feeToken?: TokenId.TokenIdOrAddress | undefined\n }>(),\n formatters: {\n transaction: defineTransaction({\n exclude: ['aaAuthorizationList' as never],\n format: Formatters.formatTransaction,\n }),\n transactionReceipt: defineTransactionReceipt({\n format: Formatters.formatTransactionReceipt,\n }),\n transactionRequest: defineTransactionRequest({\n format: Formatters.formatTransactionRequest,\n }),\n },\n prepareTransactionRequest: [\n async (r, { phase }) => {\n const request = r as Transaction.TransactionRequest & {\n account?: Account | undefined\n chain?:\n | (Chain & { feeToken?: TokenId.TokenIdOrAddress | undefined })\n | undefined\n }\n\n // FIXME: node does not account for fee payer + key authorization combinartion; bump gas for now.\n if (phase === 'afterFillParameters') {\n if (\n request.feePayer &&\n request.keyAuthorization?.signature.type === 'webAuthn'\n )\n request.gas = (request.gas ?? 0n) + 20_000n\n return request as unknown as typeof r\n }\n\n // Use expiring nonces for concurrent transactions (TIP-1009).\n // When nonceKey is 'expiring', feePayer is specified, or concurrent requests\n // are detected, we use expiring nonces (nonceKey = uint256.max) with a\n // validBefore timestamp.\n const useExpiringNonce = await (async () => {\n if (request.nonceKey === 'expiring') return true\n if (request.feePayer && typeof request.nonceKey === 'undefined')\n return true\n const address = request.account?.address\n if (address && typeof request.nonceKey === 'undefined')\n return await Concurrent.detect(address)\n return false\n })()\n\n if (useExpiringNonce) {\n request.nonceKey = maxUint256\n request.nonce = 0\n if (typeof request.validBefore === 'undefined')\n request.validBefore = Math.floor(Date.now() / 1000) + maxExpirySecs\n } else if (typeof request.nonceKey !== 'undefined') {\n // Explicit nonceKey provided (2D nonce mode)\n request.nonce = typeof request.nonce === 'number' ? request.nonce : 0\n }\n\n if (!request.feeToken && request.chain?.feeToken)\n request.feeToken = request.chain.feeToken\n\n return request as unknown as typeof r\n },\n { runAt: ['beforeFillTransaction', 'afterFillParameters'] },\n ],\n serializers: {\n // TODO: casting to satisfy viem – viem v3 to have more flexible serializer type.\n transaction: ((transaction, signature) =>\n Transaction.serialize(transaction, signature)) as SerializeTransactionFn,\n },\n async verifyHash(client, parameters) {\n const { address, hash, signature } = parameters\n\n // `verifyHash` supports \"signature envelopes\" (a Tempo proposal) to natively verify arbitrary\n // envelope-compatible (WebAuthn, P256, etc.) signatures.\n // We can directly verify stateless, non-keychain signature envelopes without a\n // network request to the chain.\n if (\n typeof signature === 'string' &&\n signature.endsWith(SignatureEnvelope.magicBytes.slice(2))\n ) {\n const envelope = SignatureEnvelope.deserialize(signature)\n if (envelope.type !== 'keychain') {\n const code = await getCode(client, {\n address,\n blockNumber: parameters.blockNumber,\n blockTag: parameters.blockTag,\n } as never)\n // Check if EOA, if not, we want to go down the ERC-1271 flow.\n if (\n // not a contract (EOA)\n !code ||\n // default delegation (tempo EOA)\n code === '0xef01007702c00000000000000000000000000000000000'\n )\n return SignatureEnvelope.verify(envelope, {\n address,\n payload: hash,\n })\n }\n }\n\n return await getAction(\n client,\n verifyHash,\n 'verifyHash',\n )({ ...parameters, chain: null })\n },\n} as const satisfies viem_ChainConfig & { blockTime: number }\n\nexport type ChainConfig = typeof chainConfig\n","import { chainConfig } from '../../tempo/chainConfig.js'\nimport { defineChain } from '../../utils/chain/defineChain.js'\n\nexport const tempo = /*#__PURE__*/ defineChain({\n ...chainConfig,\n id: 4217,\n blockExplorers: {\n default: {\n name: 'Tempo Explorer',\n url: 'https://explore.tempo.xyz',\n },\n },\n name: 'Tempo Mainnet',\n nativeCurrency: {\n name: 'USD',\n symbol: 'USD',\n decimals: 6,\n },\n rpcUrls: {\n default: {\n http: ['https://rpc.presto.tempo.xyz'],\n webSocket: ['wss://rpc.presto.tempo.xyz'],\n },\n },\n})\n","// Generated with `pnpm gen:abis`. Do not modify manually.\n\nexport const tip20 = [\n {\n name: 'name',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'string' }],\n },\n {\n name: 'symbol',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'string' }],\n },\n {\n name: 'decimals',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint8' }],\n },\n {\n name: 'totalSupply',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'quoteToken',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'nextQuoteToken',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'balanceOf',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'address', name: 'account' }],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'transfer',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'to' },\n { type: 'uint256', name: 'amount' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'approve',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'spender' },\n { type: 'uint256', name: 'amount' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'allowance',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'owner' },\n { type: 'address', name: 'spender' },\n ],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'transferFrom',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'from' },\n { type: 'address', name: 'to' },\n { type: 'uint256', name: 'amount' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'mint',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'to' },\n { type: 'uint256', name: 'amount' },\n ],\n outputs: [],\n },\n {\n name: 'burn',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'uint256', name: 'amount' }],\n outputs: [],\n },\n {\n name: 'currency',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'string' }],\n },\n {\n name: 'supplyCap',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'paused',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'transferPolicyId',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint64' }],\n },\n {\n name: 'burnBlocked',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'from' },\n { type: 'uint256', name: 'amount' },\n ],\n outputs: [],\n },\n {\n name: 'mintWithMemo',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'to' },\n { type: 'uint256', name: 'amount' },\n { type: 'bytes32', name: 'memo' },\n ],\n outputs: [],\n },\n {\n name: 'burnWithMemo',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'uint256', name: 'amount' },\n { type: 'bytes32', name: 'memo' },\n ],\n outputs: [],\n },\n {\n name: 'transferWithMemo',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'to' },\n { type: 'uint256', name: 'amount' },\n { type: 'bytes32', name: 'memo' },\n ],\n outputs: [],\n },\n {\n name: 'transferFromWithMemo',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'from' },\n { type: 'address', name: 'to' },\n { type: 'uint256', name: 'amount' },\n { type: 'bytes32', name: 'memo' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'changeTransferPolicyId',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'uint64', name: 'newPolicyId' }],\n outputs: [],\n },\n {\n name: 'setSupplyCap',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'uint256', name: 'newSupplyCap' }],\n outputs: [],\n },\n {\n name: 'pause',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [],\n outputs: [],\n },\n {\n name: 'unpause',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [],\n outputs: [],\n },\n {\n name: 'setNextQuoteToken',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'address', name: 'newQuoteToken' }],\n outputs: [],\n },\n {\n name: 'completeQuoteTokenUpdate',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [],\n outputs: [],\n },\n {\n name: 'PAUSE_ROLE',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'UNPAUSE_ROLE',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'ISSUER_ROLE',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'BURN_BLOCKED_ROLE',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'distributeReward',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'uint256', name: 'amount' }],\n outputs: [],\n },\n {\n name: 'setRewardRecipient',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'address', name: 'recipient' }],\n outputs: [],\n },\n {\n name: 'claimRewards',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'optedInSupply',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint128' }],\n },\n {\n name: 'globalRewardPerToken',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'userRewardInfo',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'address', name: 'account' }],\n outputs: [\n {\n type: 'tuple',\n components: [\n { type: 'address', name: 'rewardRecipient' },\n { type: 'uint256', name: 'rewardPerToken' },\n { type: 'uint256', name: 'rewardBalance' },\n ],\n },\n ],\n },\n {\n name: 'getPendingRewards',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'address', name: 'account' }],\n outputs: [{ type: 'uint128' }],\n },\n {\n name: 'Transfer',\n type: 'event',\n inputs: [\n { type: 'address', name: 'from', indexed: true },\n { type: 'address', name: 'to', indexed: true },\n { type: 'uint256', name: 'amount' },\n ],\n },\n {\n name: 'Approval',\n type: 'event',\n inputs: [\n { type: 'address', name: 'owner', indexed: true },\n { type: 'address', name: 'spender', indexed: true },\n { type: 'uint256', name: 'amount' },\n ],\n },\n {\n name: 'Mint',\n type: 'event',\n inputs: [\n { type: 'address', name: 'to', indexed: true },\n { type: 'uint256', name: 'amount' },\n ],\n },\n {\n name: 'Burn',\n type: 'event',\n inputs: [\n { type: 'address', name: 'from', indexed: true },\n { type: 'uint256', name: 'amount' },\n ],\n },\n {\n name: 'BurnBlocked',\n type: 'event',\n inputs: [\n { type: 'address', name: 'from', indexed: true },\n { type: 'uint256', name: 'amount' },\n ],\n },\n {\n name: 'TransferWithMemo',\n type: 'event',\n inputs: [\n { type: 'address', name: 'from', indexed: true },\n { type: 'address', name: 'to', indexed: true },\n { type: 'uint256', name: 'amount' },\n { type: 'bytes32', name: 'memo', indexed: true },\n ],\n },\n {\n name: 'TransferPolicyUpdate',\n type: 'event',\n inputs: [\n { type: 'address', name: 'updater', indexed: true },\n { type: 'uint64', name: 'newPolicyId', indexed: true },\n ],\n },\n {\n name: 'SupplyCapUpdate',\n type: 'event',\n inputs: [\n { type: 'address', name: 'updater', indexed: true },\n { type: 'uint256', name: 'newSupplyCap', indexed: true },\n ],\n },\n {\n name: 'PauseStateUpdate',\n type: 'event',\n inputs: [\n { type: 'address', name: 'updater', indexed: true },\n { type: 'bool', name: 'isPaused' },\n ],\n },\n {\n name: 'NextQuoteTokenSet',\n type: 'event',\n inputs: [\n { type: 'address', name: 'updater', indexed: true },\n { type: 'address', name: 'nextQuoteToken', indexed: true },\n ],\n },\n {\n name: 'QuoteTokenUpdate',\n type: 'event',\n inputs: [\n { type: 'address', name: 'updater', indexed: true },\n { type: 'address', name: 'newQuoteToken', indexed: true },\n ],\n },\n {\n name: 'RewardDistributed',\n type: 'event',\n inputs: [\n { type: 'address', name: 'funder', indexed: true },\n { type: 'uint256', name: 'amount' },\n ],\n },\n {\n name: 'RewardRecipientSet',\n type: 'event',\n inputs: [\n { type: 'address', name: 'holder', indexed: true },\n { type: 'address', name: 'recipient', indexed: true },\n ],\n },\n {\n name: 'InsufficientBalance',\n type: 'error',\n inputs: [\n { type: 'uint256', name: 'available' },\n { type: 'uint256', name: 'required' },\n { type: 'address', name: 'token' },\n ],\n },\n { name: 'InsufficientAllowance', type: 'error', inputs: [] },\n { name: 'SupplyCapExceeded', type: 'error', inputs: [] },\n { name: 'InvalidSupplyCap', type: 'error', inputs: [] },\n { name: 'InvalidPayload', type: 'error', inputs: [] },\n { name: 'StringTooLong', type: 'error', inputs: [] },\n { name: 'PolicyForbids', type: 'error', inputs: [] },\n { name: 'InvalidRecipient', type: 'error', inputs: [] },\n { name: 'ContractPaused', type: 'error', inputs: [] },\n { name: 'InvalidCurrency', type: 'error', inputs: [] },\n { name: 'InvalidQuoteToken', type: 'error', inputs: [] },\n { name: 'TransfersDisabled', type: 'error', inputs: [] },\n { name: 'InvalidAmount', type: 'error', inputs: [] },\n { name: 'NoOptedInSupply', type: 'error', inputs: [] },\n { name: 'Unauthorized', type: 'error', inputs: [] },\n { name: 'ProtectedAddress', type: 'error', inputs: [] },\n { name: 'InvalidToken', type: 'error', inputs: [] },\n { name: 'Uninitialized', type: 'error', inputs: [] },\n { name: 'InvalidTransferPolicyId', type: 'error', inputs: [] },\n {\n name: 'hasRole',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'account' },\n { type: 'bytes32', name: 'role' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'getRoleAdmin',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32', name: 'role' }],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'grantRole',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'bytes32', name: 'role' },\n { type: 'address', name: 'account' },\n ],\n outputs: [],\n },\n {\n name: 'revokeRole',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'bytes32', name: 'role' },\n { type: 'address', name: 'account' },\n ],\n outputs: [],\n },\n {\n name: 'renounceRole',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'bytes32', name: 'role' }],\n outputs: [],\n },\n {\n name: 'setRoleAdmin',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'bytes32', name: 'role' },\n { type: 'bytes32', name: 'adminRole' },\n ],\n outputs: [],\n },\n {\n name: 'RoleMembershipUpdated',\n type: 'event',\n inputs: [\n { type: 'bytes32', name: 'role', indexed: true },\n { type: 'address', name: 'account', indexed: true },\n { type: 'address', name: 'sender', indexed: true },\n { type: 'bool', name: 'hasRole' },\n ],\n },\n {\n name: 'RoleAdminUpdated',\n type: 'event',\n inputs: [\n { type: 'bytes32', name: 'role', indexed: true },\n { type: 'bytes32', name: 'newAdminRole', indexed: true },\n { type: 'address', name: 'sender', indexed: true },\n ],\n },\n { name: 'Unauthorized', type: 'error', inputs: [] },\n] as const\n\nexport const stablecoinDex = [\n {\n name: 'createPair',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'address', name: 'base' }],\n outputs: [{ type: 'bytes32', name: 'key' }],\n },\n {\n name: 'place',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'token' },\n { type: 'uint128', name: 'amount' },\n { type: 'bool', name: 'isBid' },\n { type: 'int16', name: 'tick' },\n ],\n outputs: [{ type: 'uint128', name: 'orderId' }],\n },\n {\n name: 'placeFlip',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'token' },\n { type: 'uint128', name: 'amount' },\n { type: 'bool', name: 'isBid' },\n { type: 'int16', name: 'tick' },\n { type: 'int16', name: 'flipTick' },\n ],\n outputs: [{ type: 'uint128', name: 'orderId' }],\n },\n {\n name: 'cancel',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'uint128', name: 'orderId' }],\n outputs: [],\n },\n {\n name: 'cancelStaleOrder',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'uint128', name: 'orderId' }],\n outputs: [],\n },\n {\n name: 'swapExactAmountIn',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'tokenIn' },\n { type: 'address', name: 'tokenOut' },\n { type: 'uint128', name: 'amountIn' },\n { type: 'uint128', name: 'minAmountOut' },\n ],\n outputs: [{ type: 'uint128', name: 'amountOut' }],\n },\n {\n name: 'swapExactAmountOut',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'tokenIn' },\n { type: 'address', name: 'tokenOut' },\n { type: 'uint128', name: 'amountOut' },\n { type: 'uint128', name: 'maxAmountIn' },\n ],\n outputs: [{ type: 'uint128', name: 'amountIn' }],\n },\n {\n name: 'quoteSwapExactAmountIn',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'tokenIn' },\n { type: 'address', name: 'tokenOut' },\n { type: 'uint128', name: 'amountIn' },\n ],\n outputs: [{ type: 'uint128', name: 'amountOut' }],\n },\n {\n name: 'quoteSwapExactAmountOut',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'tokenIn' },\n { type: 'address', name: 'tokenOut' },\n { type: 'uint128', name: 'amountOut' },\n ],\n outputs: [{ type: 'uint128', name: 'amountIn' }],\n },\n {\n name: 'balanceOf',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'user' },\n { type: 'address', name: 'token' },\n ],\n outputs: [{ type: 'uint128' }],\n },\n {\n name: 'withdraw',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'token' },\n { type: 'uint128', name: 'amount' },\n ],\n outputs: [],\n },\n {\n name: 'getOrder',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'uint128', name: 'orderId' }],\n outputs: [\n {\n type: 'tuple',\n components: [\n { type: 'uint128', name: 'orderId' },\n { type: 'address', name: 'maker' },\n { type: 'bytes32', name: 'bookKey' },\n { type: 'bool', name: 'isBid' },\n { type: 'int16', name: 'tick' },\n { type: 'uint128', name: 'amount' },\n { type: 'uint128', name: 'remaining' },\n { type: 'uint128', name: 'prev' },\n { type: 'uint128', name: 'next' },\n { type: 'bool', name: 'isFlip' },\n { type: 'int16', name: 'flipTick' },\n ],\n },\n ],\n },\n {\n name: 'getTickLevel',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'base' },\n { type: 'int16', name: 'tick' },\n { type: 'bool', name: 'isBid' },\n ],\n outputs: [\n { type: 'uint128', name: 'head' },\n { type: 'uint128', name: 'tail' },\n { type: 'uint128', name: 'totalLiquidity' },\n ],\n },\n {\n name: 'pairKey',\n type: 'function',\n stateMutability: 'pure',\n inputs: [\n { type: 'address', name: 'tokenA' },\n { type: 'address', name: 'tokenB' },\n ],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'nextOrderId',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint128' }],\n },\n {\n name: 'books',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32', name: 'pairKey' }],\n outputs: [\n {\n type: 'tuple',\n components: [\n { type: 'address', name: 'base' },\n { type: 'address', name: 'quote' },\n { type: 'int16', name: 'bestBidTick' },\n { type: 'int16', name: 'bestAskTick' },\n ],\n },\n ],\n },\n {\n name: 'MIN_TICK',\n type: 'function',\n stateMutability: 'pure',\n inputs: [],\n outputs: [{ type: 'int16' }],\n },\n {\n name: 'MAX_TICK',\n type: 'function',\n stateMutability: 'pure',\n inputs: [],\n outputs: [{ type: 'int16' }],\n },\n {\n name: 'TICK_SPACING',\n type: 'function',\n stateMutability: 'pure',\n inputs: [],\n outputs: [{ type: 'int16' }],\n },\n {\n name: 'PRICE_SCALE',\n type: 'function',\n stateMutability: 'pure',\n inputs: [],\n outputs: [{ type: 'uint32' }],\n },\n {\n name: 'MIN_ORDER_AMOUNT',\n type: 'function',\n stateMutability: 'pure',\n inputs: [],\n outputs: [{ type: 'uint128' }],\n },\n {\n name: 'MIN_PRICE',\n type: 'function',\n stateMutability: 'pure',\n inputs: [],\n outputs: [{ type: 'uint32' }],\n },\n {\n name: 'MAX_PRICE',\n type: 'function',\n stateMutability: 'pure',\n inputs: [],\n outputs: [{ type: 'uint32' }],\n },\n {\n name: 'tickToPrice',\n type: 'function',\n stateMutability: 'pure',\n inputs: [{ type: 'int16', name: 'tick' }],\n outputs: [{ type: 'uint32', name: 'price' }],\n },\n {\n name: 'priceToTick',\n type: 'function',\n stateMutability: 'pure',\n inputs: [{ type: 'uint32', name: 'price' }],\n outputs: [{ type: 'int16', name: 'tick' }],\n },\n {\n name: 'PairCreated',\n type: 'event',\n inputs: [\n { type: 'bytes32', name: 'key', indexed: true },\n { type: 'address', name: 'base', indexed: true },\n { type: 'address', name: 'quote', indexed: true },\n ],\n },\n {\n name: 'OrderPlaced',\n type: 'event',\n inputs: [\n { type: 'uint128', name: 'orderId', indexed: true },\n { type: 'address', name: 'maker', indexed: true },\n { type: 'address', name: 'token', indexed: true },\n { type: 'uint128', name: 'amount' },\n { type: 'bool', name: 'isBid' },\n { type: 'int16', name: 'tick' },\n { type: 'bool', name: 'isFlipOrder' },\n { type: 'int16', name: 'flipTick' },\n ],\n },\n {\n name: 'OrderFilled',\n type: 'event',\n inputs: [\n { type: 'uint128', name: 'orderId', indexed: true },\n { type: 'address', name: 'maker', indexed: true },\n { type: 'address', name: 'taker', indexed: true },\n { type: 'uint128', name: 'amountFilled' },\n { type: 'bool', name: 'partialFill' },\n ],\n },\n {\n name: 'OrderCancelled',\n type: 'event',\n inputs: [{ type: 'uint128', name: 'orderId', indexed: true }],\n },\n { name: 'Unauthorized', type: 'error', inputs: [] },\n { name: 'PairDoesNotExist', type: 'error', inputs: [] },\n { name: 'PairAlreadyExists', type: 'error', inputs: [] },\n { name: 'OrderDoesNotExist', type: 'error', inputs: [] },\n { name: 'IdenticalTokens', type: 'error', inputs: [] },\n { name: 'InvalidToken', type: 'error', inputs: [] },\n {\n name: 'TickOutOfBounds',\n type: 'error',\n inputs: [{ type: 'int16', name: 'tick' }],\n },\n { name: 'InvalidTick', type: 'error', inputs: [] },\n { name: 'InvalidFlipTick', type: 'error', inputs: [] },\n { name: 'InsufficientBalance', type: 'error', inputs: [] },\n { name: 'InsufficientLiquidity', type: 'error', inputs: [] },\n { name: 'InsufficientOutput', type: 'error', inputs: [] },\n { name: 'MaxInputExceeded', type: 'error', inputs: [] },\n {\n name: 'BelowMinimumOrderSize',\n type: 'error',\n inputs: [{ type: 'uint128', name: 'amount' }],\n },\n { name: 'InvalidBaseToken', type: 'error', inputs: [] },\n { name: 'OrderNotStale', type: 'error', inputs: [] },\n] as const\n\nexport const feeManager = [\n {\n name: 'userTokens',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'address', name: 'user' }],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'validatorTokens',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'address', name: 'validator' }],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'setUserToken',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'address', name: 'token' }],\n outputs: [],\n },\n {\n name: 'setValidatorToken',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'address', name: 'token' }],\n outputs: [],\n },\n {\n name: 'distributeFees',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'validator' },\n { type: 'address', name: 'token' },\n ],\n outputs: [],\n },\n {\n name: 'collectedFees',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'validator' },\n { type: 'address', name: 'token' },\n ],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'UserTokenSet',\n type: 'event',\n inputs: [\n { type: 'address', name: 'user', indexed: true },\n { type: 'address', name: 'token', indexed: true },\n ],\n },\n {\n name: 'ValidatorTokenSet',\n type: 'event',\n inputs: [\n { type: 'address', name: 'validator', indexed: true },\n { type: 'address', name: 'token', indexed: true },\n ],\n },\n {\n name: 'FeesDistributed',\n type: 'event',\n inputs: [\n { type: 'address', name: 'validator', indexed: true },\n { type: 'address', name: 'token', indexed: true },\n { type: 'uint256', name: 'amount' },\n ],\n },\n { name: 'OnlyValidator', type: 'error', inputs: [] },\n { name: 'OnlySystemContract', type: 'error', inputs: [] },\n { name: 'InvalidToken', type: 'error', inputs: [] },\n { name: 'PoolDoesNotExist', type: 'error', inputs: [] },\n { name: 'InsufficientFeeTokenBalance', type: 'error', inputs: [] },\n { name: 'InternalError', type: 'error', inputs: [] },\n { name: 'CannotChangeWithinBlock', type: 'error', inputs: [] },\n { name: 'CannotChangeWithPendingFees', type: 'error', inputs: [] },\n { name: 'TokenPolicyForbids', type: 'error', inputs: [] },\n] as const\n\nexport const feeAmm = [\n {\n name: 'M',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'N',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'SCALE',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'MIN_LIQUIDITY',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'getPoolId',\n type: 'function',\n stateMutability: 'pure',\n inputs: [\n { type: 'address', name: 'userToken' },\n { type: 'address', name: 'validatorToken' },\n ],\n outputs: [{ type: 'bytes32' }],\n },\n {\n name: 'getPool',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'userToken' },\n { type: 'address', name: 'validatorToken' },\n ],\n outputs: [\n {\n type: 'tuple',\n components: [\n { type: 'uint128', name: 'reserveUserToken' },\n { type: 'uint128', name: 'reserveValidatorToken' },\n ],\n },\n ],\n },\n {\n name: 'pools',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32', name: 'poolId' }],\n outputs: [\n {\n type: 'tuple',\n components: [\n { type: 'uint128', name: 'reserveUserToken' },\n { type: 'uint128', name: 'reserveValidatorToken' },\n ],\n },\n ],\n },\n {\n name: 'mint',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'userToken' },\n { type: 'address', name: 'validatorToken' },\n { type: 'uint256', name: 'amountValidatorToken' },\n { type: 'address', name: 'to' },\n ],\n outputs: [{ type: 'uint256', name: 'liquidity' }],\n },\n {\n name: 'burn',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'userToken' },\n { type: 'address', name: 'validatorToken' },\n { type: 'uint256', name: 'liquidity' },\n { type: 'address', name: 'to' },\n ],\n outputs: [\n { type: 'uint256', name: 'amountUserToken' },\n { type: 'uint256', name: 'amountValidatorToken' },\n ],\n },\n {\n name: 'totalSupply',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'bytes32', name: 'poolId' }],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'liquidityBalances',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes32', name: 'poolId' },\n { type: 'address', name: 'user' },\n ],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'rebalanceSwap',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'userToken' },\n { type: 'address', name: 'validatorToken' },\n { type: 'uint256', name: 'amountOut' },\n { type: 'address', name: 'to' },\n ],\n outputs: [{ type: 'uint256', name: 'amountIn' }],\n },\n {\n name: 'Mint',\n type: 'event',\n inputs: [\n { type: 'address', name: 'sender' },\n { type: 'address', name: 'to', indexed: true },\n { type: 'address', name: 'userToken', indexed: true },\n { type: 'address', name: 'validatorToken', indexed: true },\n { type: 'uint256', name: 'amountValidatorToken' },\n { type: 'uint256', name: 'liquidity' },\n ],\n },\n {\n name: 'Burn',\n type: 'event',\n inputs: [\n { type: 'address', name: 'sender', indexed: true },\n { type: 'address', name: 'userToken', indexed: true },\n { type: 'address', name: 'validatorToken', indexed: true },\n { type: 'uint256', name: 'amountUserToken' },\n { type: 'uint256', name: 'amountValidatorToken' },\n { type: 'uint256', name: 'liquidity' },\n { type: 'address', name: 'to' },\n ],\n },\n {\n name: 'RebalanceSwap',\n type: 'event',\n inputs: [\n { type: 'address', name: 'userToken', indexed: true },\n { type: 'address', name: 'validatorToken', indexed: true },\n { type: 'address', name: 'swapper', indexed: true },\n { type: 'uint256', name: 'amountIn' },\n { type: 'uint256', name: 'amountOut' },\n ],\n },\n { name: 'IdenticalAddresses', type: 'error', inputs: [] },\n { name: 'InvalidToken', type: 'error', inputs: [] },\n { name: 'InsufficientLiquidity', type: 'error', inputs: [] },\n { name: 'InsufficientReserves', type: 'error', inputs: [] },\n { name: 'InvalidAmount', type: 'error', inputs: [] },\n { name: 'DivisionByZero', type: 'error', inputs: [] },\n { name: 'InvalidSwapCalculation', type: 'error', inputs: [] },\n] as const\n\nexport const accountKeychain = [\n {\n name: 'authorizeKey',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'keyId' },\n { type: 'uint8', name: 'signatureType' },\n { type: 'uint64', name: 'expiry' },\n { type: 'bool', name: 'enforceLimits' },\n {\n type: 'tuple[]',\n name: 'limits',\n components: [\n { type: 'address', name: 'token' },\n { type: 'uint256', name: 'amount' },\n ],\n },\n ],\n outputs: [],\n },\n {\n name: 'revokeKey',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'address', name: 'keyId' }],\n outputs: [],\n },\n {\n name: 'updateSpendingLimit',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'keyId' },\n { type: 'address', name: 'token' },\n { type: 'uint256', name: 'newLimit' },\n ],\n outputs: [],\n },\n {\n name: 'getKey',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'account' },\n { type: 'address', name: 'keyId' },\n ],\n outputs: [\n {\n type: 'tuple',\n components: [\n { type: 'uint8', name: 'signatureType' },\n { type: 'address', name: 'keyId' },\n { type: 'uint64', name: 'expiry' },\n { type: 'bool', name: 'enforceLimits' },\n { type: 'bool', name: 'isRevoked' },\n ],\n },\n ],\n },\n {\n name: 'getRemainingLimit',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'account' },\n { type: 'address', name: 'keyId' },\n { type: 'address', name: 'token' },\n ],\n outputs: [{ type: 'uint256' }],\n },\n {\n name: 'getTransactionKey',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'KeyAuthorized',\n type: 'event',\n inputs: [\n { type: 'address', name: 'account', indexed: true },\n { type: 'address', name: 'publicKey', indexed: true },\n { type: 'uint8', name: 'signatureType' },\n { type: 'uint64', name: 'expiry' },\n ],\n },\n {\n name: 'KeyRevoked',\n type: 'event',\n inputs: [\n { type: 'address', name: 'account', indexed: true },\n { type: 'address', name: 'publicKey', indexed: true },\n ],\n },\n {\n name: 'SpendingLimitUpdated',\n type: 'event',\n inputs: [\n { type: 'address', name: 'account', indexed: true },\n { type: 'address', name: 'publicKey', indexed: true },\n { type: 'address', name: 'token', indexed: true },\n { type: 'uint256', name: 'newLimit' },\n ],\n },\n { name: 'UnauthorizedCaller', type: 'error', inputs: [] },\n { name: 'KeyAlreadyExists', type: 'error', inputs: [] },\n { name: 'KeyNotFound', type: 'error', inputs: [] },\n { name: 'KeyExpired', type: 'error', inputs: [] },\n { name: 'SpendingLimitExceeded', type: 'error', inputs: [] },\n { name: 'InvalidSignatureType', type: 'error', inputs: [] },\n { name: 'ZeroPublicKey', type: 'error', inputs: [] },\n { name: 'ExpiryInPast', type: 'error', inputs: [] },\n { name: 'KeyAlreadyRevoked', type: 'error', inputs: [] },\n] as const\n\nexport const nonce = [\n {\n name: 'getNonce',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'account' },\n { type: 'uint256', name: 'nonceKey' },\n ],\n outputs: [{ type: 'uint64', name: 'nonce' }],\n },\n {\n name: 'NonceIncremented',\n type: 'event',\n inputs: [\n { type: 'address', name: 'account', indexed: true },\n { type: 'uint256', name: 'nonceKey', indexed: true },\n { type: 'uint64', name: 'newNonce' },\n ],\n },\n { name: 'ProtocolNonceNotSupported', type: 'error', inputs: [] },\n { name: 'InvalidNonceKey', type: 'error', inputs: [] },\n { name: 'NonceOverflow', type: 'error', inputs: [] },\n] as const\n\nexport const tip20Factory = [\n {\n name: 'createToken',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'string', name: 'name' },\n { type: 'string', name: 'symbol' },\n { type: 'string', name: 'currency' },\n { type: 'address', name: 'quoteToken' },\n { type: 'address', name: 'admin' },\n { type: 'bytes32', name: 'salt' },\n ],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'isTIP20',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'address', name: 'token' }],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'getTokenAddress',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'address', name: 'sender' },\n { type: 'bytes32', name: 'salt' },\n ],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'TokenCreated',\n type: 'event',\n inputs: [\n { type: 'address', name: 'token', indexed: true },\n { type: 'string', name: 'name' },\n { type: 'string', name: 'symbol' },\n { type: 'string', name: 'currency' },\n { type: 'address', name: 'quoteToken' },\n { type: 'address', name: 'admin' },\n { type: 'bytes32', name: 'salt' },\n ],\n },\n { name: 'AddressReserved', type: 'error', inputs: [] },\n { name: 'AddressNotReserved', type: 'error', inputs: [] },\n { name: 'InvalidQuoteToken', type: 'error', inputs: [] },\n {\n name: 'TokenAlreadyExists',\n type: 'error',\n inputs: [{ type: 'address', name: 'token' }],\n },\n] as const\n\nexport const tip403Registry = [\n {\n name: 'policyIdCounter',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint64' }],\n },\n {\n name: 'policyExists',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'uint64', name: 'policyId' }],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'policyData',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'uint64', name: 'policyId' }],\n outputs: [\n { type: 'uint8', name: 'policyType' },\n { type: 'address', name: 'admin' },\n ],\n },\n {\n name: 'isAuthorized',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'uint64', name: 'policyId' },\n { type: 'address', name: 'user' },\n ],\n outputs: [{ type: 'bool' }],\n },\n {\n name: 'createPolicy',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'admin' },\n { type: 'uint8', name: 'policyType' },\n ],\n outputs: [{ type: 'uint64' }],\n },\n {\n name: 'createPolicyWithAccounts',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'admin' },\n { type: 'uint8', name: 'policyType' },\n { type: 'address[]', name: 'accounts' },\n ],\n outputs: [{ type: 'uint64' }],\n },\n {\n name: 'setPolicyAdmin',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'uint64', name: 'policyId' },\n { type: 'address', name: 'admin' },\n ],\n outputs: [],\n },\n {\n name: 'modifyPolicyWhitelist',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'uint64', name: 'policyId' },\n { type: 'address', name: 'account' },\n { type: 'bool', name: 'allowed' },\n ],\n outputs: [],\n },\n {\n name: 'modifyPolicyBlacklist',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'uint64', name: 'policyId' },\n { type: 'address', name: 'account' },\n { type: 'bool', name: 'restricted' },\n ],\n outputs: [],\n },\n {\n name: 'PolicyAdminUpdated',\n type: 'event',\n inputs: [\n { type: 'uint64', name: 'policyId', indexed: true },\n { type: 'address', name: 'updater', indexed: true },\n { type: 'address', name: 'admin', indexed: true },\n ],\n },\n {\n name: 'PolicyCreated',\n type: 'event',\n inputs: [\n { type: 'uint64', name: 'policyId', indexed: true },\n { type: 'address', name: 'updater', indexed: true },\n { type: 'uint8', name: 'policyType' },\n ],\n },\n {\n name: 'WhitelistUpdated',\n type: 'event',\n inputs: [\n { type: 'uint64', name: 'policyId', indexed: true },\n { type: 'address', name: 'updater', indexed: true },\n { type: 'address', name: 'account', indexed: true },\n { type: 'bool', name: 'allowed' },\n ],\n },\n {\n name: 'BlacklistUpdated',\n type: 'event',\n inputs: [\n { type: 'uint64', name: 'policyId', indexed: true },\n { type: 'address', name: 'updater', indexed: true },\n { type: 'address', name: 'account', indexed: true },\n { type: 'bool', name: 'restricted' },\n ],\n },\n { name: 'Unauthorized', type: 'error', inputs: [] },\n { name: 'IncompatiblePolicyType', type: 'error', inputs: [] },\n { name: 'PolicyNotFound', type: 'error', inputs: [] },\n] as const\n\nexport const validator = [\n {\n name: 'getValidators',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'tuple[]',\n name: 'validators',\n components: [\n { type: 'bytes32', name: 'publicKey' },\n { type: 'bool', name: 'active' },\n { type: 'uint64', name: 'index' },\n { type: 'address', name: 'validatorAddress' },\n { type: 'string', name: 'inboundAddress' },\n { type: 'string', name: 'outboundAddress' },\n ],\n },\n ],\n },\n {\n name: 'addValidator',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'newValidatorAddress' },\n { type: 'bytes32', name: 'publicKey' },\n { type: 'bool', name: 'active' },\n { type: 'string', name: 'inboundAddress' },\n { type: 'string', name: 'outboundAddress' },\n ],\n outputs: [],\n },\n {\n name: 'updateValidator',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'newValidatorAddress' },\n { type: 'bytes32', name: 'publicKey' },\n { type: 'string', name: 'inboundAddress' },\n { type: 'string', name: 'outboundAddress' },\n ],\n outputs: [],\n },\n {\n name: 'changeValidatorStatus',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [\n { type: 'address', name: 'validator' },\n { type: 'bool', name: 'active' },\n ],\n outputs: [],\n },\n {\n name: 'owner',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'changeOwner',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'address', name: 'newOwner' }],\n outputs: [],\n },\n {\n name: 'getNextFullDkgCeremony',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint64' }],\n },\n {\n name: 'setNextFullDkgCeremony',\n type: 'function',\n stateMutability: 'nonpayable',\n inputs: [{ type: 'uint64', name: 'epoch' }],\n outputs: [],\n },\n {\n name: 'validatorsArray',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'uint256', name: 'index' }],\n outputs: [{ type: 'address' }],\n },\n {\n name: 'validators',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ type: 'address', name: 'validator' }],\n outputs: [\n {\n type: 'tuple',\n components: [\n { type: 'bytes32', name: 'publicKey' },\n { type: 'bool', name: 'active' },\n { type: 'uint64', name: 'index' },\n { type: 'address', name: 'validatorAddress' },\n { type: 'string', name: 'inboundAddress' },\n { type: 'string', name: 'outboundAddress' },\n ],\n },\n ],\n },\n {\n name: 'validatorCount',\n type: 'function',\n stateMutability: 'view',\n inputs: [],\n outputs: [{ type: 'uint64' }],\n },\n { name: 'Unauthorized', type: 'error', inputs: [] },\n { name: 'ValidatorAlreadyExists', type: 'error', inputs: [] },\n { name: 'ValidatorNotFound', type: 'error', inputs: [] },\n { name: 'InvalidPublicKey', type: 'error', inputs: [] },\n {\n name: 'NotHostPort',\n type: 'error',\n inputs: [\n { type: 'string', name: 'field' },\n { type: 'string', name: 'input' },\n { type: 'string', name: 'backtrace' },\n ],\n },\n {\n name: 'NotIpPort',\n type: 'error',\n inputs: [\n { type: 'string', name: 'field' },\n { type: 'string', name: 'input' },\n { type: 'string', name: 'backtrace' },\n ],\n },\n] as const\n","import * as Address from 'ox/Address'\nimport * as Hex from 'ox/Hex'\nimport * as P256 from 'ox/P256'\nimport * as PublicKey from 'ox/PublicKey'\nimport * as Secp256k1 from 'ox/Secp256k1'\nimport * as Signature from 'ox/Signature'\nimport { KeyAuthorization, SignatureEnvelope } from 'ox/tempo'\nimport * as WebAuthnP256 from 'ox/WebAuthnP256'\nimport * as WebCryptoP256 from 'ox/WebCryptoP256'\nimport type {\n LocalAccount,\n Account as viem_Account,\n} from '../accounts/types.js'\nimport { parseAccount } from '../accounts/utils/parseAccount.js'\nimport type { TransactionSerializable } from '../types/transaction.js'\nimport type { OneOf, RequiredBy } from '../types/utils.js'\nimport { hashAuthorization } from '../utils/authorization/hashAuthorization.js'\nimport { keccak256 } from '../utils/hash/keccak256.js'\nimport { hashMessage } from '../utils/signature/hashMessage.js'\nimport { hashTypedData } from '../utils/signature/hashTypedData.js'\nimport type { SerializeTransactionFn } from '../utils/transaction/serializeTransaction.js'\nimport * as Transaction from './Transaction.js'\n\nexport type Account_base<source extends string = string> = RequiredBy<\n LocalAccount<source>,\n 'sign' | 'signAuthorization' | 'signTransaction'\n> & {\n /** Key type. */\n keyType: SignatureEnvelope.Type\n /** Sign transaction fn. */\n signTransaction: <\n serializer extends\n SerializeTransactionFn<TransactionSerializable> = SerializeTransactionFn<Transaction.TransactionSerializableTempo>,\n transaction extends Parameters<serializer>[0] = Parameters<serializer>[0],\n >(\n transaction: transaction,\n options?:\n | {\n serializer?: serializer | undefined\n }\n | undefined,\n ) => Promise<Hex.Hex>\n}\n\nexport type RootAccount = Account_base<'root'> & {\n /** Sign key authorization. */\n signKeyAuthorization: (\n key: Pick<AccessKeyAccount, 'accessKeyAddress' | 'keyType'>,\n parameters: Pick<\n KeyAuthorization.KeyAuthorization,\n 'chainId' | 'expiry' | 'limits'\n >,\n ) => Promise<KeyAuthorization.Signed>\n}\n\nexport type AccessKeyAccount = Account_base<'accessKey'> & {\n /** Access key ID. */\n accessKeyAddress: Address.Address\n}\n\nexport type Account = OneOf<RootAccount | AccessKeyAccount>\n\n/** Instantiates an Account. */\nexport function from<const parameters extends from.Parameters>(\n parameters: parameters | from.Parameters,\n): from.ReturnValue<parameters> {\n const { access } = parameters\n if (access) return fromAccessKey(parameters) as never\n return fromRoot(parameters) as never\n}\n\nexport declare namespace from {\n export type Parameters = OneOf<fromRoot.Parameters | fromAccessKey.Parameters>\n\n export type ReturnValue<\n parameters extends {\n access?: fromAccessKey.Parameters['access'] | undefined\n } = {\n access?: fromAccessKey.Parameters['access'] | undefined\n },\n > = parameters extends {\n access: fromAccessKey.Parameters['access']\n }\n ? AccessKeyAccount\n : RootAccount\n}\n\n/**\n * Instantiates an Account from a headless WebAuthn credential (P256 private key).\n *\n * @example\n * ```ts\n * import { Account } from 'viem/tempo'\n *\n * const account = Account.fromHeadlessWebAuthn('0x...')\n * ```\n *\n * @param privateKey P256 private key.\n * @returns Account.\n */\nexport function fromHeadlessWebAuthn<\n const options extends fromHeadlessWebAuthn.Options,\n>(\n privateKey: Hex.Hex,\n options: options | fromHeadlessWebAuthn.Options,\n): fromHeadlessWebAuthn.ReturnValue<options> {\n const { access, rpId, origin, internal_version } = options\n\n const publicKey = P256.getPublicKey({ privateKey })\n\n return from({\n access,\n internal_version,\n keyType: 'webAuthn',\n publicKey,\n async sign({ hash }) {\n const { metadata, payload } = WebAuthnP256.getSignPayload({\n ...options,\n challenge: hash,\n rpId,\n origin,\n })\n const signature = P256.sign({\n payload,\n privateKey,\n hash: true,\n })\n return SignatureEnvelope.serialize({\n metadata,\n signature,\n publicKey,\n type: 'webAuthn',\n })\n },\n }) as never\n}\n\nexport declare namespace fromHeadlessWebAuthn {\n export type Options = Omit<\n WebAuthnP256.getSignPayload.Options,\n 'challenge' | 'rpId' | 'origin'\n > &\n Pick<from.Parameters, 'access' | 'internal_version'> & {\n rpId: string\n origin: string\n }\n\n export type ReturnValue<options extends Options = Options> =\n from.ReturnValue<options>\n}\n\n/**\n * Instantiates an Account from a P256 private key.\n *\n * @example\n * ```ts\n * import { Account } from 'viem/tempo'\n *\n * const account = Account.fromP256('0x...')\n * ```\n *\n * @param privateKey P256 private key.\n * @returns Account.\n */\nexport function fromP256<const options extends fromP256.Options>(\n privateKey: Hex.Hex,\n options: options | fromP256.Options = {},\n): fromP256.ReturnValue<options> {\n const { access, internal_version } = options\n const publicKey = P256.getPublicKey({ privateKey })\n\n return from({\n access,\n internal_version,\n keyType: 'p256',\n publicKey,\n async sign({ hash }) {\n const signature = P256.sign({ payload: hash, privateKey })\n return SignatureEnvelope.serialize({\n signature,\n publicKey,\n type: 'p256',\n })\n },\n }) as never\n}\n\nexport declare namespace fromP256 {\n export type Options = Pick<from.Parameters, 'access' | 'internal_version'>\n\n export type ReturnValue<options extends Options = Options> =\n from.ReturnValue<options>\n}\n\n/**\n * Instantiates an Account from a Secp256k1 private key.\n *\n * @example\n * ```ts\n * import { Account } from 'viem/tempo'\n *\n * const account = Account.fromSecp256k1('0x...')\n * ```\n *\n * @param privateKey Secp256k1 private key.\n * @returns Account.\n */\nexport function fromSecp256k1<const options extends fromSecp256k1.Options>(\n privateKey: Hex.Hex,\n options: options | fromSecp256k1.Options = {},\n): fromSecp256k1.ReturnValue<options> {\n const { access, internal_version } = options\n const publicKey = Secp256k1.getPublicKey({ privateKey })\n\n return from({\n access,\n internal_version,\n keyType: 'secp256k1',\n publicKey,\n async sign(parameters) {\n const { hash } = parameters\n const signature = Secp256k1.sign({ payload: hash, privateKey })\n return Signature.toHex(signature)\n },\n }) as never\n}\n\nexport declare namespace fromSecp256k1 {\n export type Options = Pick<from.Parameters, 'access' | 'internal_version'>\n\n export type ReturnValue<options extends Options = Options> =\n from.ReturnValue<options>\n}\n\n/**\n * Instantiates an Account from a WebAuthn credential.\n *\n * @example\n *\n * ### Create Passkey + Instantiate Account\n *\n * Create a credential with `WebAuthnP256.createCredential` and then instantiate\n * a Viem Account with `Account.fromWebAuthnP256`.\n *\n * It is highly recommended to store the credential's public key in an external store\n * for future use (ie. for future calls to `WebAuthnP256.getCredential`).\n *\n * ```ts\n * import { Account, WebAuthnP256 } from 'viem/tempo'\n * import { publicKeyStore } from './store'\n *\n * // 1. Create credential\n * const credential = await WebAuthnP256.createCredential({ name: 'Example' })\n *\n * // 2. Instantiate account\n * const account = Account.fromWebAuthnP256(credential)\n *\n * // 3. Store public key\n * await publicKeyStore.set(credential.id, credential.publicKey)\n *\n * ```\n *\n * @example\n *\n * ### Get Credential + Instantiate Account\n *\n * Gets a credential from `WebAuthnP256.getCredential` and then instantiates\n * an account with `Account.fromWebAuthnP256`.\n *\n * The `getPublicKey` function is required to fetch the public key paired with the credential\n * from an external store. The public key is required to derive the account's address.\n *\n * ```ts\n * import { Account, WebAuthnP256 } from 'viem/tempo'\n * import { publicKeyStore } from './store'\n *\n * // 1. Get credential\n * const credential = await WebAuthnP256.getCredential({\n * async getPublicKey(credential) {\n * // 2. Get public key from external store.\n * return await publicKeyStore.get(credential.id)\n * }\n * })\n *\n * // 3. Instantiate account\n * const account = Account.fromWebAuthnP256(credential)\n * ```\n *\n * @param credential WebAuthnP256 credential.\n * @returns Account.\n */\nexport function fromWebAuthnP256(\n credential: fromWebAuthnP256.Credential,\n options: fromWebAuthnP256.Options = {},\n): fromWebAuthnP256.ReturnValue {\n const { id } = credential\n const publicKey = PublicKey.fromHex(credential.publicKey)\n return from({\n keyType: 'webAuthn',\n publicKey,\n async sign({ hash }) {\n const { metadata, signature } = await WebAuthnP256.sign({\n ...options,\n challenge: hash,\n credentialId: id,\n })\n return SignatureEnvelope.serialize({\n publicKey,\n metadata,\n signature,\n type: 'webAuthn',\n })\n },\n })\n}\n\nexport declare namespace fromWebAuthnP256 {\n export type Credential = {\n id: WebAuthnP256.P256Credential['id']\n publicKey: Hex.Hex\n }\n\n export type Options = {\n getFn?: WebAuthnP256.sign.Options['getFn'] | undefined\n rpId?: WebAuthnP256.sign.Options['rpId'] | undefined\n }\n\n export type ReturnValue = from.ReturnValue\n}\n\n/**\n * Instantiates an Account from a P256 private key.\n *\n * @example\n * ```ts\n * import { Account } from 'viem/tempo'\n * import { WebCryptoP256 } from 'ox'\n *\n * const keyPair = await WebCryptoP256.createKeyPair()\n *\n * const account = Account.fromWebCryptoP256(keyPair)\n * ```\n *\n * @param keyPair WebCryptoP256 key pair.\n * @returns Account.\n */\nexport function fromWebCryptoP256<\n const options extends fromWebCryptoP256.Options,\n>(\n keyPair: Awaited<ReturnType<typeof WebCryptoP256.createKeyPair>>,\n options: options | fromWebCryptoP256.Options = {},\n): fromWebCryptoP256.ReturnValue<options> {\n const { access, internal_version } = options\n const { publicKey, privateKey } = keyPair\n\n return from({\n access,\n internal_version,\n keyType: 'p256',\n publicKey,\n async sign({ hash }) {\n const signature = await WebCryptoP256.sign({ payload: hash, privateKey })\n return SignatureEnvelope.serialize({\n signature,\n prehash: true,\n publicKey,\n type: 'p256',\n })\n },\n }) as never\n}\n\nexport declare namespace fromWebCryptoP256 {\n export type Options = Pick<from.Parameters, 'access' | 'internal_version'>\n\n export type ReturnValue<options extends Options = Options> =\n from.ReturnValue<options>\n}\n\nexport async function signKeyAuthorization(\n account: LocalAccount,\n parameters: signKeyAuthorization.Parameters,\n): Promise<signKeyAuthorization.ReturnValue> {\n const { chainId, key, expiry, limits } = parameters\n const { accessKeyAddress, keyType: type } = key\n\n const signature = await account.sign!({\n hash: KeyAuthorization.getSignPayload({\n address: accessKeyAddress,\n chainId,\n expiry,\n limits,\n type,\n }),\n })\n return KeyAuthorization.from({\n address: accessKeyAddress,\n chainId,\n expiry,\n limits,\n signature: SignatureEnvelope.from(signature),\n type,\n })\n}\n\nexport declare namespace signKeyAuthorization {\n type Parameters = Pick<\n KeyAuthorization.KeyAuthorization,\n 'chainId' | 'expiry' | 'limits'\n > & {\n key: Pick<AccessKeyAccount, 'accessKeyAddress' | 'keyType'>\n }\n\n type ReturnValue = KeyAuthorization.Signed\n}\n\n/** @internal */\n// biome-ignore lint/correctness/noUnusedVariables: _\nfunction fromBase(parameters: fromBase.Parameters): Account_base {\n const {\n keyType = 'secp256k1',\n parentAddress,\n source = 'privateKey',\n internal_version = 'v2',\n } = parameters\n\n const address = parentAddress ?? Address.fromPublicKey(parameters.publicKey)\n const publicKey = PublicKey.toHex(parameters.publicKey, {\n includePrefix: false,\n })\n\n async function sign({ hash }: { hash: Hex.Hex }) {\n const innerHash =\n parentAddress && internal_version === 'v2'\n ? keccak256(Hex.concat('0x04', hash, parentAddress))\n : hash\n const signature = await parameters.sign({ hash: innerHash })\n if (parentAddress)\n return SignatureEnvelope.serialize(\n SignatureEnvelope.from({\n userAddress: parentAddress,\n inner: SignatureEnvelope.from(signature),\n type: 'keychain',\n version: internal_version,\n }),\n )\n // Don't need to append magic bytes to secp256k1 signatures as they are\n // backwards compatible with existing verification logic.\n if (keyType === 'secp256k1') return signature\n return Hex.concat(signature, SignatureEnvelope.magicBytes)\n }\n\n return {\n address: Address.checksum(address),\n keyType,\n sign,\n async signAuthorization(parameters) {\n const { chainId, nonce } = parameters\n const address = parameters.contractAddress ?? parameters.address\n const signature = await sign({\n hash: hashAuthorization({ address, chainId, nonce }),\n })\n const envelope = SignatureEnvelope.from(signature)\n if (envelope.type !== 'secp256k1')\n throw new Error(\n 'Unsupported signature type. Expected `secp256k1` but got `' +\n envelope.type +\n '`.',\n )\n const { r, s, yParity } = envelope.signature\n return {\n address,\n chainId,\n nonce,\n r: Hex.fromNumber(r, { size: 32 }),\n s: Hex.fromNumber(s, { size: 32 }),\n yParity,\n }\n },\n async signMessage(parameters) {\n const { message } = parameters\n return await sign({ hash: hashMessage(message) })\n },\n async signTransaction(transaction, options) {\n const { serializer = Transaction.serialize } = options ?? {}\n const signature = await sign({\n hash: keccak256(await serializer(transaction)),\n })\n const envelope = SignatureEnvelope.from(signature)\n return await serializer(transaction, envelope as never)\n },\n async signTypedData(typedData) {\n return await sign({ hash: hashTypedData(typedData) })\n },\n publicKey,\n source,\n type: 'local',\n }\n}\n\ndeclare namespace fromBase {\n export type Parameters = {\n /** Parent address. */\n parentAddress?: Address.Address | undefined\n /** Public key. */\n publicKey: PublicKey.PublicKey\n /** Key type. */\n keyType?: SignatureEnvelope.Type | undefined\n /** Sign function. */\n sign: NonNullable<LocalAccount['sign']>\n /** Source. */\n source?: string | undefined\n /** Access key version. Will be removed in a future release. @deprecated @internal */\n internal_version?: 'v1' | 'v2' | undefined\n }\n\n export type ReturnValue = Account_base\n}\n\n/** @internal */\n// biome-ignore lint/correctness/noUnusedVariables: _\nfunction fromRoot(parameters: fromRoot.Parameters): RootAccount {\n const account = fromBase(parameters)\n return {\n ...account,\n source: 'root',\n async signKeyAuthorization(key, parameters) {\n const { chainId, expiry, limits } = parameters\n const { accessKeyAddress, keyType: type } = key\n\n const signature = await account.sign({\n hash: KeyAuthorization.getSignPayload({\n address: accessKeyAddress,\n chainId,\n expiry,\n limits,\n type,\n }),\n })\n const keyAuthorization = KeyAuthorization.from({\n address: accessKeyAddress,\n chainId,\n expiry,\n limits,\n signature: SignatureEnvelope.from(signature),\n type,\n })\n return keyAuthorization\n },\n }\n}\n\ndeclare namespace fromRoot {\n export type Parameters = fromBase.Parameters\n\n export type ReturnValue = RootAccount\n}\n\n// biome-ignore lint/correctness/noUnusedVariables: _\nfunction fromAccessKey(parameters: fromAccessKey.Parameters): AccessKeyAccount {\n const { access } = parameters\n const { address: parentAddress } = parseAccount(access)\n const account = fromBase({ ...parameters, parentAddress })\n return {\n ...account,\n accessKeyAddress: Address.fromPublicKey(parameters.publicKey),\n source: 'accessKey',\n }\n}\n\ndeclare namespace fromAccessKey {\n export type Parameters = fromBase.Parameters & {\n /**\n * Parent account to access.\n * If defined, this account will act as an \"access key\", and use\n * the parent account's address as the keychain address.\n */\n access: viem_Account | Address.Address\n }\n\n export type ReturnValue = AccessKeyAccount\n}\n\n// Export types required for inference.\n// biome-ignore lint/performance/noBarrelFile: _\nexport {\n /** @deprecated */\n KeyAuthorization as z_KeyAuthorization,\n /** @deprecated */\n SignatureEnvelope as z_SignatureEnvelope,\n /** @deprecated */\n TxEnvelopeTempo as z_TxEnvelopeTempo,\n} from 'ox/tempo'\n","export const accountImplementation =\n '0x7702c00000000000000000000000000000000000'\nexport const accountKeychain = '0xaAAAaaAA00000000000000000000000000000000'\nexport const accountRegistrar = '0x7702ac0000000000000000000000000000000000'\nexport const feeManager = '0xfeec000000000000000000000000000000000000'\nexport const nonceManager = '0x4e4F4E4345000000000000000000000000000000'\nexport const pathUsd = '0x20c0000000000000000000000000000000000000'\nexport const stablecoinDex = '0xdec0000000000000000000000000000000000000'\nexport const tip20Factory = '0x20fc000000000000000000000000000000000000'\nexport const tip403Registry = '0x403c000000000000000000000000000000000000'\nexport const validator = '0xcccccccc00000000000000000000000000000000'\n","// biome-ignore lint/performance/noBarrelFile: _\nexport * as accessKey from './accessKey.js'\nexport * as amm from './amm.js'\nexport * as dex from './dex.js'\nexport * as faucet from './faucet.js'\nexport * as fee from './fee.js'\nexport * as nonce from './nonce.js'\nexport * as policy from './policy.js'\nexport * as reward from './reward.js'\nexport * as token from './token.js'\nexport * as validator from './validator.js'\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { ReadContractReturnType } from '../../actions/public/readContract.js'\nimport { readContract } from '../../actions/public/readContract.js'\nimport { sendTransaction } from '../../actions/wallet/sendTransaction.js'\nimport { sendTransactionSync } from '../../actions/wallet/sendTransactionSync.js'\nimport type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'\nimport { writeContract } from '../../actions/wallet/writeContract.js'\nimport { writeContractSync } from '../../actions/wallet/writeContractSync.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseErrorType } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { GetEventArgs } from '../../types/contract.js'\nimport type { Log } from '../../types/log.js'\nimport type { Compute } from '../../types/utils.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport * as Abis from '../Abis.js'\nimport type { AccessKeyAccount } from '../Account.js'\nimport { signKeyAuthorization } from '../Account.js'\nimport * as Addresses from '../Addresses.js'\nimport type {\n GetAccountParameter,\n ReadParameters,\n WriteParameters,\n} from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\nimport type { TransactionReceipt } from '../Transaction.js'\n\n/** @internal */\nconst signatureTypes = {\n 0: 'secp256k1',\n 1: 'p256',\n 2: 'webAuthn',\n} as const satisfies Record<number, string>\n\n/** @internal */\nconst spendPolicies = {\n true: 'limited',\n false: 'unlimited',\n} as const\n\n/**\n * Authorizes an access key by signing a key authorization and sending a transaction.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions, Account } from 'viem/tempo'\n * import { generatePrivateKey } from 'viem/accounts'\n *\n * const account = Account.from({ privateKey: '0x...' })\n * const client = createClient({\n * account,\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const accessKey = Account.fromP256(generatePrivateKey(), {\n * access: account,\n * })\n *\n * const hash = await Actions.accessKey.authorize(client, {\n * accessKey,\n * expiry: Math.floor((Date.now() + 30_000) / 1000),\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function authorize<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: authorize.Parameters<chain, account>,\n): Promise<authorize.ReturnValue> {\n return authorize.inner(sendTransaction, client, parameters)\n}\n\nexport namespace authorize {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** The access key to authorize. */\n accessKey: Pick<AccessKeyAccount, 'accessKeyAddress' | 'keyType'>\n /** The chain ID. */\n chainId?: number | undefined\n /** Unix timestamp when the key expires. */\n expiry?: number | undefined\n /** Spending limits per token. */\n limits?: { token: Address; limit: bigint }[] | undefined\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof sendTransaction | typeof sendTransactionSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: authorize.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const {\n accessKey,\n chainId = client.chain?.id,\n expiry,\n limits,\n ...rest\n } = parameters\n const account_ = rest.account ?? client.account\n if (!account_) throw new Error('account is required.')\n if (!chainId) throw new Error('chainId is required.')\n const parsed = parseAccount(account_)\n const keyAuthorization = await signKeyAuthorization(parsed as never, {\n chainId: BigInt(chainId),\n key: accessKey,\n expiry,\n limits,\n })\n return (await action(client, {\n ...rest,\n keyAuthorization,\n } as never)) as never\n }\n\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.accountKeychain,\n logs,\n eventName: 'KeyAuthorized',\n strict: true,\n })\n if (!log) throw new Error('`KeyAuthorized` event not found.')\n return log\n }\n}\n\n/**\n * Authorizes an access key and waits for the transaction receipt.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions, Account } from 'viem/tempo'\n * import { generatePrivateKey } from 'viem/accounts'\n *\n * const account = Account.from({ privateKey: '0x...' })\n * const client = createClient({\n * account,\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const accessKey = Account.fromP256(generatePrivateKey(), {\n * access: account,\n * })\n *\n * const { receipt, ...result } = await Actions.accessKey.authorizeSync(client, {\n * accessKey,\n * expiry: Math.floor((Date.now() + 30_000) / 1000),\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function authorizeSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: authorizeSync.Parameters<chain, account>,\n): Promise<authorizeSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await authorize.inner(sendTransactionSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = authorize.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace authorizeSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = authorize.Parameters<chain, account>\n\n export type Args = authorize.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.accountKeychain,\n 'KeyAuthorized',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Revokes an authorized access key.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hash = await Actions.accessKey.revoke(client, {\n * accessKey: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function revoke<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: revoke.Parameters<chain, account>,\n): Promise<revoke.ReturnValue> {\n return revoke.inner(writeContract, client, parameters)\n}\n\nexport namespace revoke {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** The access key to revoke. */\n accessKey: Address | AccessKeyAccount\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: revoke.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { accessKey, ...rest } = parameters\n const call = revoke.call({ accessKey })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `revokeKey` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * }).extend(walletActions)\n *\n * const hash = await client.sendTransaction({\n * calls: [\n * Actions.accessKey.revoke.call({ accessKey: '0x...' }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { accessKey } = args\n return defineCall({\n address: Addresses.accountKeychain,\n abi: Abis.accountKeychain,\n functionName: 'revokeKey',\n args: [resolveAccessKey(accessKey)],\n })\n }\n\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.accountKeychain,\n logs,\n eventName: 'KeyRevoked',\n strict: true,\n })\n if (!log) throw new Error('`KeyRevoked` event not found.')\n return log\n }\n}\n\n/**\n * Revokes an authorized access key and waits for the transaction receipt.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await Actions.accessKey.revokeSync(client, {\n * accessKey: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function revokeSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: revokeSync.Parameters<chain, account>,\n): Promise<revokeSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await revoke.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = revoke.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace revokeSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = revoke.Parameters<chain, account>\n\n export type Args = revoke.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.accountKeychain,\n 'KeyRevoked',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Updates the spending limit for a specific token on an authorized access key.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hash = await Actions.accessKey.updateLimit(client, {\n * accessKey: '0x...',\n * token: '0x...',\n * limit: 1000000000000000000n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function updateLimit<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: updateLimit.Parameters<chain, account>,\n): Promise<updateLimit.ReturnValue> {\n return updateLimit.inner(writeContract, client, parameters)\n}\n\nexport namespace updateLimit {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** The access key to update. */\n accessKey: Address | AccessKeyAccount\n /** The token address. */\n token: Address\n /** The new spending limit. */\n limit: bigint\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: updateLimit.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { accessKey, token, limit, ...rest } = parameters\n const call = updateLimit.call({ accessKey, token, limit })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `updateSpendingLimit` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * }).extend(walletActions)\n *\n * const hash = await client.sendTransaction({\n * calls: [\n * Actions.accessKey.updateLimit.call({\n * accessKey: '0x...',\n * token: '0x...',\n * limit: 1000000000000000000n,\n * }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { accessKey, token, limit } = args\n return defineCall({\n address: Addresses.accountKeychain,\n abi: Abis.accountKeychain,\n functionName: 'updateSpendingLimit',\n args: [resolveAccessKey(accessKey), token, limit],\n })\n }\n\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.accountKeychain,\n logs,\n eventName: 'SpendingLimitUpdated',\n strict: true,\n })\n if (!log) throw new Error('`SpendingLimitUpdated` event not found.')\n return log\n }\n}\n\n/**\n * Updates the spending limit and waits for the transaction receipt.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await Actions.accessKey.updateLimitSync(client, {\n * accessKey: '0x...',\n * token: '0x...',\n * limit: 1000000000000000000n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function updateLimitSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: updateLimitSync.Parameters<chain, account>,\n): Promise<updateLimitSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await updateLimit.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = updateLimit.extractEvent(receipt.logs)\n return {\n account: args.account,\n publicKey: args.publicKey,\n token: args.token,\n limit: args.newLimit,\n receipt,\n }\n}\n\nexport namespace updateLimitSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = updateLimit.Parameters<chain, account>\n\n export type Args = updateLimit.Args\n\n export type ReturnValue = {\n /** The account that owns the key. */\n account: Address\n /** The access key address. */\n publicKey: Address\n /** The token address. */\n token: Address\n /** The new spending limit. */\n limit: bigint\n /** The transaction receipt. */\n receipt: TransactionReceipt\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Gets access key information.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const key = await Actions.accessKey.getMetadata(client, {\n * account: '0x...',\n * accessKey: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The key information.\n */\nexport async function getMetadata<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getMetadata.Parameters<account>,\n): Promise<getMetadata.ReturnValue> {\n const { account: account_ = client.account, accessKey, ...rest } = parameters\n if (!account_) throw new Error('account is required.')\n const account = parseAccount(account_)\n const result = await readContract(client, {\n ...rest,\n ...getMetadata.call({ account: account.address, accessKey }),\n })\n return {\n address: result.keyId,\n keyType:\n signatureTypes[result.signatureType as keyof typeof signatureTypes] ??\n 'secp256k1',\n expiry: result.expiry,\n spendPolicy: spendPolicies[`${result.enforceLimits}`],\n isRevoked: result.isRevoked,\n }\n}\n\nexport namespace getMetadata {\n export type Parameters<\n account extends Account | undefined = Account | undefined,\n > = ReadParameters & GetAccountParameter<account> & Pick<Args, 'accessKey'>\n\n export type Args = {\n /** Account address. */\n account: Address\n /** The access key. */\n accessKey: Address | AccessKeyAccount\n }\n\n export type ReturnValue = {\n /** The access key address. */\n address: Address\n /** The key type. */\n keyType: 'secp256k1' | 'p256' | 'webAuthn'\n /** The expiry timestamp. */\n expiry: bigint\n /** The spending policy. */\n spendPolicy: 'limited' | 'unlimited'\n /** Whether the key is revoked. */\n isRevoked: boolean\n }\n\n /**\n * Defines a call to the `getKey` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, accessKey } = args\n return defineCall({\n address: Addresses.accountKeychain,\n abi: Abis.accountKeychain,\n functionName: 'getKey',\n args: [account, resolveAccessKey(accessKey)],\n })\n }\n}\n\n/**\n * Gets the remaining spending limit for a key-token pair.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const remaining = await Actions.accessKey.getRemainingLimit(client, {\n * account: '0x...',\n * accessKey: '0x...',\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The remaining spending amount.\n */\nexport async function getRemainingLimit<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getRemainingLimit.Parameters<account>,\n): Promise<getRemainingLimit.ReturnValue> {\n const {\n account: account_ = client.account,\n accessKey,\n token,\n ...rest\n } = parameters\n if (!account_) throw new Error('account is required.')\n const account = parseAccount(account_)\n return readContract(client, {\n ...rest,\n ...getRemainingLimit.call({ account: account.address, accessKey, token }),\n })\n}\n\nexport namespace getRemainingLimit {\n export type Parameters<\n account extends Account | undefined = Account | undefined,\n > = ReadParameters &\n GetAccountParameter<account> &\n Pick<Args, 'accessKey' | 'token'>\n\n export type Args = {\n /** Account address. */\n account: Address\n /** The access key. */\n accessKey: Address | AccessKeyAccount\n /** The token address. */\n token: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.accountKeychain,\n 'getRemainingLimit',\n never\n >\n\n /**\n * Defines a call to the `getRemainingLimit` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, accessKey, token } = args\n return defineCall({\n address: Addresses.accountKeychain,\n abi: Abis.accountKeychain,\n functionName: 'getRemainingLimit',\n args: [account, resolveAccessKey(accessKey), token],\n })\n }\n}\n\n/**\n * Signs a key authorization for an access key.\n *\n * @example\n * ```ts\n * import { generatePrivateKey } from 'viem/accounts'\n * import { Account, Actions } from 'viem/tempo'\n *\n * const account = Account.from({ privateKey: '0x...' })\n * const accessKey = Account.fromP256(generatePrivateKey(), {\n * access: account,\n * })\n *\n * const keyAuthorization = await Actions.accessKey.signAuthorization(\n * client,\n * {\n * account,\n * accessKey,\n * expiry: Math.floor((Date.now() + 30_000) / 1000),\n * },\n * )\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The signed key authorization.\n */\nexport async function signAuthorization<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: signAuthorization.Parameters<account>,\n): Promise<signAuthorization.ReturnValue> {\n const { accessKey, chainId = client.chain?.id, ...rest } = parameters\n const account_ = rest.account ?? client.account\n if (!account_) throw new Error('account is required.')\n if (!chainId) throw new Error('chainId is required.')\n const parsed = parseAccount(account_)\n return signKeyAuthorization(parsed as never, {\n chainId: BigInt(chainId),\n key: accessKey,\n ...rest,\n })\n}\n\nexport namespace signAuthorization {\n export type Parameters<\n account extends Account | undefined = Account | undefined,\n > = GetAccountParameter<account> & {\n /** The access key to authorize. */\n accessKey: Pick<AccessKeyAccount, 'accessKeyAddress' | 'keyType'>\n /** The chain ID. */\n chainId?: number | undefined\n /** Unix timestamp when the key expires. */\n expiry?: number | undefined\n /** Spending limits per token. */\n limits?: { token: Address; limit: bigint }[] | undefined\n }\n\n export type ReturnValue = Awaited<ReturnType<typeof signKeyAuthorization>>\n}\n\n/** @internal */\nfunction resolveAccessKey(accessKey: Address | AccessKeyAccount): Address {\n if (typeof accessKey === 'string') return accessKey\n return accessKey.accessKeyAddress\n}\n","import type { Abi, AbiStateMutability, Address } from 'abitype'\nimport type {\n ContractFunctionName,\n ContractFunctionParameters,\n ExtractAbiItem,\n} from '../../types/contract.js'\nimport type { Hex } from '../../types/misc.js'\nimport { encodeFunctionData } from '../../utils/index.js'\n\nexport function defineCall<\n const abi extends Abi,\n const functionName extends ContractFunctionName<abi, AbiStateMutability>,\n call extends ContractFunctionParameters<\n abi,\n AbiStateMutability,\n functionName\n >,\n>(\n call:\n | call\n | ContractFunctionParameters<abi, AbiStateMutability, functionName>,\n): ContractFunctionParameters<\n [ExtractAbiItem<abi, functionName>],\n AbiStateMutability,\n functionName\n> & {\n data: Hex\n to: Address\n} {\n return {\n ...(call as any),\n data: encodeFunctionData(call as never),\n to: call.address,\n } as const\n}\n\n/**\n * Normalizes a value into a structured-clone compatible format.\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone\n * @internal\n */\nexport function normalizeValue<type>(value: type): type {\n if (Array.isArray(value)) return value.map(normalizeValue) as never\n if (typeof value === 'function') return undefined as never\n if (typeof value !== 'object' || value === null) return value\n if (Object.getPrototypeOf(value) !== Object.prototype)\n try {\n return structuredClone(value)\n } catch {\n return undefined as never\n }\n\n const normalized: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(value)) normalized[k] = normalizeValue(v)\n return normalized as never\n}\n","import type { Address } from 'abitype'\nimport { PoolId, TokenId } from 'ox/tempo'\nimport type { Account } from '../../accounts/types.js'\nimport type { MulticallParameters } from '../../actions/public/multicall.js'\nimport { multicall } from '../../actions/public/multicall.js'\nimport type { ReadContractReturnType } from '../../actions/public/readContract.js'\nimport { readContract } from '../../actions/public/readContract.js'\nimport type { WatchContractEventParameters } from '../../actions/public/watchContractEvent.js'\nimport { watchContractEvent } from '../../actions/public/watchContractEvent.js'\nimport type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'\nimport { writeContract } from '../../actions/wallet/writeContract.js'\nimport { writeContractSync } from '../../actions/wallet/writeContractSync.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 { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'\nimport type { Log, Log as viem_Log } from '../../types/log.js'\nimport type { Hex } from '../../types/misc.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport type { Compute, OneOf, UnionOmit } from '../../types/utils.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport * as Abis from '../Abis.js'\nimport * as Addresses from '../Addresses.js'\nimport type { ReadParameters, WriteParameters } from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\n\n/**\n * Gets the reserves for a liquidity pool.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const pool = await Actions.amm.getPool(client, {\n * userToken: '0x...',\n * validatorToken: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The pool reserves.\n */\nexport async function getPool<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getPool.Parameters,\n): Promise<getPool.ReturnValue> {\n const { userToken, validatorToken, ...rest } = parameters\n const [pool, totalSupply] = await multicall(client, {\n ...rest,\n contracts: getPool.calls({ userToken, validatorToken }),\n allowFailure: false,\n deployless: true,\n })\n return {\n reserveUserToken: pool.reserveUserToken,\n reserveValidatorToken: pool.reserveValidatorToken,\n totalSupply,\n }\n}\n\nexport namespace getPool {\n export type Parameters = UnionOmit<\n MulticallParameters,\n 'allowFailure' | 'contracts' | 'deployless'\n > &\n Args\n\n export type Args = {\n /** Address or ID of the user token. */\n userToken: TokenId.TokenIdOrAddress\n /** Address or ID of the validator token. */\n validatorToken: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = Compute<{\n /** Reserve of user token. */\n reserveUserToken: bigint\n /** Reserve of validator token. */\n reserveValidatorToken: bigint\n /** Total supply of LP tokens. */\n totalSupply: bigint\n }>\n\n /**\n * Defines calls to the `getPool` and `totalSupply` functions.\n *\n * @param args - Arguments.\n * @returns The calls.\n */\n export function calls(args: Args) {\n const { userToken, validatorToken } = args\n return [\n defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n args: [TokenId.toAddress(userToken), TokenId.toAddress(validatorToken)],\n functionName: 'getPool',\n }),\n defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n args: [PoolId.from({ userToken, validatorToken })],\n functionName: 'totalSupply',\n }),\n ] as const\n }\n}\n\n/**\n * Gets the LP token balance for an account in a specific pool.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const poolId = await Actions.amm.getPoolId(client, {\n * userToken: '0x...',\n * validatorToken: '0x...',\n * })\n *\n * const balance = await Actions.amm.getLiquidityBalance(client, {\n * poolId,\n * address: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The LP token balance.\n */\nexport async function getLiquidityBalance<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getLiquidityBalance.Parameters,\n): Promise<getLiquidityBalance.ReturnValue> {\n const { address, poolId, userToken, validatorToken, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...getLiquidityBalance.call({\n address,\n poolId,\n userToken,\n validatorToken,\n } as never),\n })\n}\n\nexport namespace getLiquidityBalance {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Address to check balance for. */\n address: Address\n } & OneOf<\n | {\n /** Pool ID. */\n poolId: Hex\n }\n | {\n /** User token. */\n userToken: TokenId.TokenIdOrAddress\n /** Validator token. */\n validatorToken: TokenId.TokenIdOrAddress\n }\n >\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.feeAmm,\n 'liquidityBalances',\n never\n >\n\n /**\n * Defines a call to the `liquidityBalances` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { address } = args\n const poolId = (() => {\n if ('poolId' in args && args.poolId) return args.poolId!\n if ('userToken' in args && 'validatorToken' in args)\n return PoolId.from({\n userToken: args.userToken,\n validatorToken: args.validatorToken,\n })\n throw new Error(\n '`poolId`, or `userToken` and `validatorToken` must be provided.',\n )\n })()\n return defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n args: [poolId, address],\n functionName: 'liquidityBalances',\n })\n }\n}\n\n/**\n * Performs a rebalance swap from validator token to user token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.amm.rebalanceSwap(client, {\n * userToken: '0x...',\n * validatorToken: '0x...',\n * amountOut: 100n,\n * to: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function rebalanceSwap<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: rebalanceSwap.Parameters<chain, account>,\n): Promise<rebalanceSwap.ReturnValue> {\n return rebalanceSwap.inner(writeContract, client, parameters)\n}\n\nexport namespace rebalanceSwap {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of user token to receive. */\n amountOut: bigint\n /** Address to send the user token to. */\n to: Address\n /** Address or ID of the user token. */\n userToken: TokenId.TokenIdOrAddress\n /** Address or ID of the validator token. */\n validatorToken: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: rebalanceSwap.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { userToken, validatorToken, amountOut, to, ...rest } = parameters\n const call = rebalanceSwap.call({\n userToken,\n validatorToken,\n amountOut,\n to,\n })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `rebalanceSwap` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.amm.rebalanceSwap.call({\n * userToken: '0x20c0...beef',\n * validatorToken: '0x20c0...babe',\n * amountOut: 100n,\n * to: '0xfeed...fede',\n * }),\n * actions.amm.rebalanceSwap.call({\n * userToken: '0x20c0...babe',\n * validatorToken: '0x20c0...babe',\n * amountOut: 100n,\n * to: '0xfeed...fede',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { userToken, validatorToken, amountOut, to } = args\n return defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n functionName: 'rebalanceSwap',\n args: [\n TokenId.toAddress(userToken),\n TokenId.toAddress(validatorToken),\n amountOut,\n to,\n ],\n })\n }\n\n /**\n * Extracts the `RebalanceSwap` event from logs.\n *\n * @param logs - The logs.\n * @returns The `RebalanceSwap` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.feeAmm,\n logs,\n eventName: 'RebalanceSwap',\n strict: true,\n })\n if (!log) throw new Error('`RebalanceSwap` event not found.')\n return log\n }\n}\n\n/**\n * Performs a rebalance swap from validator token to user token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.amm.rebalanceSwapSync(client, {\n * userToken: '0x...',\n * validatorToken: '0x...',\n * amountOut: 100n,\n * to: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function rebalanceSwapSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: rebalanceSwapSync.Parameters<chain, account>,\n): Promise<rebalanceSwapSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await rebalanceSwap.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = rebalanceSwap.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace rebalanceSwapSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = rebalanceSwap.Parameters<chain, account>\n\n export type Args = rebalanceSwap.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.feeAmm,\n 'RebalanceSwap',\n { IndexedOnly: false; Required: true }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n}\n\n/**\n * Adds liquidity to a pool.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.amm.mint(client, {\n * userTokenAddress: '0x20c0...beef',\n * validatorTokenAddress: '0x20c0...babe',\n * validatorTokenAmount: 100n,\n * to: '0xfeed...fede',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function mint<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: mint.Parameters<chain, account>,\n): Promise<mint.ReturnValue> {\n return mint.inner(writeContract, client, parameters)\n}\n\nexport namespace mint {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Address to mint LP tokens to. */\n to: Address\n /** User token address. */\n userTokenAddress: TokenId.TokenIdOrAddress\n /** Validator token address. */\n validatorTokenAddress: TokenId.TokenIdOrAddress\n /** Amount of validator token to add. */\n validatorTokenAmount: bigint\n }\n\n export type ReturnValue = WriteContractReturnType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: mint.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const {\n to,\n userTokenAddress,\n validatorTokenAddress,\n validatorTokenAmount,\n ...rest\n } = parameters\n const call = mint.call({\n to,\n userTokenAddress,\n validatorTokenAddress,\n validatorTokenAmount,\n })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `mint` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.amm.mint.call({\n * userTokenAddress: '0x20c0...beef',\n * validatorTokenAddress: '0x20c0...babe',\n * validatorTokenAmount: 100n,\n * to: '0xfeed...fede',\n * }),\n * actions.amm.mint.call({\n * userTokenAddress: '0x20c0...babe',\n * validatorTokenAddress: '0x20c0...babe',\n * validatorTokenAmount: 100n,\n * to: '0xfeed...fede',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const {\n to,\n userTokenAddress,\n validatorTokenAddress,\n validatorTokenAmount,\n } = args\n return defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n functionName: 'mint',\n args: [\n TokenId.toAddress(userTokenAddress),\n TokenId.toAddress(validatorTokenAddress),\n validatorTokenAmount,\n to,\n ],\n })\n }\n\n /**\n * Extracts the `Mint` event from logs.\n *\n * @param logs - The logs.\n * @returns The `Mint` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.feeAmm,\n logs,\n eventName: 'Mint',\n strict: true,\n })\n if (!log) throw new Error('`Mint` event not found.')\n return log\n }\n}\n\n/**\n * Adds liquidity to a pool.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.amm.mint(client, {\n * userTokenAddress: '0x20c0...beef',\n * validatorTokenAddress: '0x20c0...babe',\n * validatorTokenAmount: 100n,\n * to: '0xfeed...fede',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function mintSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: mintSync.Parameters<chain, account>,\n): Promise<mintSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await mint.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = mint.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace mintSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = mint.Parameters<chain, account>\n\n export type Args = mint.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.feeAmm,\n 'Mint',\n { IndexedOnly: false; Required: true }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n}\n\n/**\n * Removes liquidity from a pool.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.amm.burn(client, {\n * userToken: '0x20c0...beef',\n * validatorToken: '0x20c0...babe',\n * liquidity: 50n,\n * to: '0xfeed...fede',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function burn<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: burn.Parameters<chain, account>,\n): Promise<burn.ReturnValue> {\n return burn.inner(writeContract, client, parameters)\n}\n\nexport namespace burn {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of LP tokens to burn. */\n liquidity: bigint\n /** Address to send tokens to. */\n to: Address\n /** Address or ID of the user token. */\n userToken: TokenId.TokenIdOrAddress\n /** Address or ID of the validator token. */\n validatorToken: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: burn.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { liquidity, to, userToken, validatorToken, ...rest } = parameters\n const call = burn.call({ liquidity, to, userToken, validatorToken })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `burn` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.amm.burn.call({\n * liquidity: 100n,\n * to: '0xfeed...fede',\n * userToken: '0x20c0...beef',\n * validatorToken: '0x20c0...babe',\n * }),\n * actions.amm.burn.call({\n * liquidity: 100n,\n * to: '0xfeed...fede',\n * userToken: '0x20c0...babe',\n * validatorToken: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { liquidity, to, userToken, validatorToken } = args\n return defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n functionName: 'burn',\n args: [\n TokenId.toAddress(userToken),\n TokenId.toAddress(validatorToken),\n liquidity,\n to,\n ],\n })\n }\n\n /**\n * Extracts the `Burn` event from logs.\n *\n * @param logs - The logs.\n * @returns The `Burn` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.feeAmm,\n logs,\n eventName: 'Burn',\n strict: true,\n })\n if (!log) throw new Error('`Burn` event not found.')\n return log\n }\n}\n\n/**\n * Removes liquidity from a pool.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.amm.burnSync(client, {\n * userToken: '0x20c0...beef',\n * validatorToken: '0x20c0...babe',\n * liquidity: 50n,\n * to: '0xfeed...fede',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function burnSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: burnSync.Parameters<chain, account>,\n): Promise<burnSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await burn.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = burn.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace burnSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = burn.Parameters<chain, account>\n\n export type Args = burn.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.feeAmm,\n 'Burn',\n { IndexedOnly: false; Required: true }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n}\n\n/**\n * Watches for rebalance swap events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.amm.watchRebalanceSwap(client, {\n * onRebalanceSwap: (args, log) => {\n * console.log('Rebalance swap:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchRebalanceSwap<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchRebalanceSwap.Parameters,\n) {\n const { onRebalanceSwap, userToken, validatorToken, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n eventName: 'RebalanceSwap',\n args:\n userToken !== undefined && validatorToken !== undefined\n ? {\n userToken: TokenId.toAddress(userToken),\n validatorToken: TokenId.toAddress(validatorToken),\n }\n : undefined,\n onLogs: (logs) => {\n for (const log of logs) onRebalanceSwap(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchRebalanceSwap {\n export type Args = GetEventArgs<\n typeof Abis.feeAmm,\n 'RebalanceSwap',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.feeAmm, 'RebalanceSwap'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.feeAmm, 'RebalanceSwap', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a rebalance swap occurs. */\n onRebalanceSwap: (args: Args, log: Log) => void\n /** Address or ID of the user token to filter events. */\n userToken?: TokenId.TokenIdOrAddress | undefined\n /** Address or ID of the validator token to filter events. */\n validatorToken?: TokenId.TokenIdOrAddress | undefined\n }\n}\n\n/**\n * Watches for liquidity mint events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.amm.watchMint(client, {\n * onMint: (args, log) => {\n * console.log('Liquidity added:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchMint<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>, parameters: watchMint.Parameters) {\n const { onMint, to, userToken, validatorToken, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n eventName: 'Mint',\n args: {\n to,\n ...(userToken !== undefined && {\n userToken: TokenId.toAddress(userToken),\n }),\n ...(validatorToken !== undefined && {\n validatorToken: TokenId.toAddress(validatorToken),\n }),\n },\n onLogs: (logs) => {\n for (const log of logs) onMint(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchMint {\n export type Args = GetEventArgs<\n typeof Abis.feeAmm,\n 'Mint',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.feeAmm, 'Mint'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.feeAmm, 'Mint', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when liquidity is added. */\n onMint: (args: Args, log: Log) => void\n /** Address of the sender to filter events. */\n sender?: Address | undefined\n /** Address of the recipient to filter events. */\n to?: Address | undefined\n /** Address or ID of the user token to filter events. */\n userToken?: TokenId.TokenIdOrAddress | undefined\n /** Address or ID of the validator token to filter events. */\n validatorToken?: TokenId.TokenIdOrAddress | undefined\n }\n}\n\n/**\n * Watches for liquidity burn events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.amm.watchBurn(client, {\n * onBurn: (args, log) => {\n * console.log('Liquidity removed:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchBurn<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>, parameters: watchBurn.Parameters) {\n const { onBurn, userToken, validatorToken, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.feeManager,\n abi: Abis.feeAmm,\n eventName: 'Burn',\n args:\n userToken !== undefined && validatorToken !== undefined\n ? {\n userToken: TokenId.toAddress(userToken),\n validatorToken: TokenId.toAddress(validatorToken),\n }\n : undefined,\n onLogs: (logs) => {\n for (const log of logs) onBurn(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchBurn {\n export type Args = GetEventArgs<\n typeof Abis.feeAmm,\n 'Burn',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.feeAmm, 'Burn'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.feeAmm, 'Burn', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when liquidity is removed. */\n onBurn: (args: Args, log: Log) => void\n /** Address or ID of the user token to filter events. */\n userToken?: TokenId.TokenIdOrAddress | undefined\n /** Address or ID of the validator token to filter events. */\n validatorToken?: TokenId.TokenIdOrAddress | undefined\n }\n}\n","import type { Address } from 'abitype'\nimport * as Hash from 'ox/Hash'\nimport * as Hex from 'ox/Hex'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport {\n type ReadContractReturnType,\n readContract,\n} from '../../actions/public/readContract.js'\nimport {\n type WatchContractEventParameters,\n watchContractEvent,\n} from '../../actions/public/watchContractEvent.js'\nimport {\n type WriteContractReturnType,\n writeContract,\n} from '../../actions/wallet/writeContract.js'\nimport { writeContractSync } from '../../actions/wallet/writeContractSync.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseErrorType } from '../../errors/base.js'\nimport type { Account } from '../../types/account.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'\nimport type { Log as viem_Log } from '../../types/log.js'\nimport type { Compute, UnionOmit } from '../../types/utils.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport * as Abis from '../Abis.js'\nimport * as Addresses from '../Addresses.js'\nimport type {\n GetAccountParameter,\n ReadParameters,\n WriteParameters,\n} from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\nimport type { TransactionReceipt } from '../Transaction.js'\n\n/**\n * Order type for limit orders.\n */\ntype OrderType = 'buy' | 'sell'\n\n/**\n * Buys a specific amount of tokens.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.dex.buy(client, {\n * tokenIn: '0x20c...11',\n * tokenOut: '0x20c...20',\n * amountOut: parseUnits('100', 6),\n * maxAmountIn: parseUnits('105', 6),\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function buy<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: buy.Parameters<chain, account>,\n): Promise<buy.ReturnValue> {\n return buy.inner(writeContract, client, parameters)\n}\n\nexport namespace buy {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokenOut to buy. */\n amountOut: bigint\n /** Maximum amount of tokenIn to spend. */\n maxAmountIn: bigint\n /** Address of the token to spend. */\n tokenIn: Address\n /** Address of the token to buy. */\n tokenOut: Address\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: buy.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { tokenIn, tokenOut, amountOut, maxAmountIn, ...rest } = parameters\n const call = buy.call({ tokenIn, tokenOut, amountOut, maxAmountIn })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `swapExactAmountOut` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.dex.buy.call({\n * tokenIn: '0x20c0...beef',\n * tokenOut: '0x20c0...babe',\n * amountOut: parseUnits('100', 6),\n * maxAmountIn: parseUnits('105', 6),\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { tokenIn, tokenOut, amountOut, maxAmountIn } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n functionName: 'swapExactAmountOut',\n args: [tokenIn, tokenOut, amountOut, maxAmountIn],\n })\n }\n}\n\n/**\n * Buys a specific amount of tokens.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.dex.buySync(client, {\n * tokenIn: '0x20c...11',\n * tokenOut: '0x20c...20',\n * amountOut: parseUnits('100', 6),\n * maxAmountIn: parseUnits('105', 6),\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt.\n */\nexport async function buySync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: buySync.Parameters<chain, account>,\n): Promise<buySync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await buy.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n return { receipt }\n}\n\nexport namespace buySync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = buy.Parameters<chain, account>\n\n export type Args = buy.Args\n\n export type ReturnValue = Compute<{\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }>\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Cancels an order from the orderbook.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.dex.cancel(client, {\n * orderId: 123n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function cancel<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: cancel.Parameters<chain, account>,\n): Promise<cancel.ReturnValue> {\n return cancel.inner(writeContract, client, parameters)\n}\n\nexport namespace cancel {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Order ID to cancel. */\n orderId: bigint\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: cancel.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { orderId, ...rest } = parameters\n const call = cancel.call({ orderId })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `cancel` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.dex.cancel.call({\n * orderId: 123n,\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { orderId } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n functionName: 'cancel',\n args: [orderId],\n })\n }\n\n /**\n * Extracts the `OrderCancelled` event from logs.\n *\n * @param logs - The logs.\n * @returns The `OrderCancelled` event.\n */\n export function extractEvent(logs: viem_Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.stablecoinDex,\n logs,\n eventName: 'OrderCancelled',\n strict: true,\n })\n if (!log) throw new Error('`OrderCancelled` event not found.')\n return log\n }\n}\n\n/**\n * Cancels an order from the orderbook.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.dex.cancelSync(client, {\n * orderId: 123n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function cancelSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: cancelSync.Parameters<chain, account>,\n): Promise<cancelSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await cancel.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = cancel.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace cancelSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = cancel.Parameters<chain, account>\n\n export type Args = cancel.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.stablecoinDex,\n 'OrderCancelled',\n { IndexedOnly: false; Required: true }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Cancels a stale order from the orderbook.\n *\n * A stale order is one where the owner's balance or allowance has dropped\n * below the order amount.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.dex.cancelStale(client, {\n * orderId: 123n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function cancelStale<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: cancelStale.Parameters<chain, account>,\n): Promise<cancelStale.ReturnValue> {\n return cancelStale.inner(writeContract, client, parameters)\n}\n\nexport namespace cancelStale {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Order ID to cancel. */\n orderId: bigint\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: cancelStale.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { orderId, ...rest } = parameters\n const call = cancelStale.call({ orderId })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `cancelStaleOrder` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.dex.cancelStale.call({\n * orderId: 123n,\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { orderId } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n functionName: 'cancelStaleOrder',\n args: [orderId],\n })\n }\n\n /**\n * Extracts the `OrderCancelled` event from logs.\n *\n * @param logs - The logs.\n * @returns The `OrderCancelled` event.\n */\n export function extractEvent(logs: viem_Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.stablecoinDex,\n logs,\n eventName: 'OrderCancelled',\n strict: true,\n })\n if (!log) throw new Error('`OrderCancelled` event not found.')\n return log\n }\n}\n\n/**\n * Cancels a stale order from the orderbook and waits for confirmation.\n *\n * A stale order is one where the owner's balance or allowance has dropped\n * below the order amount.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.dex.cancelStaleSync(client, {\n * orderId: 123n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function cancelStaleSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: cancelStaleSync.Parameters<chain, account>,\n): Promise<cancelStaleSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await cancelStale.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = cancelStale.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace cancelStaleSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = cancelStale.Parameters<chain, account>\n\n export type Args = cancelStale.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.stablecoinDex,\n 'OrderCancelled',\n { IndexedOnly: false; Required: true }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Creates a new trading pair on the DEX.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.dex.createPair(client, {\n * base: '0x20c...11',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function createPair<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: createPair.Parameters<chain, account>,\n): Promise<createPair.ReturnValue> {\n return createPair.inner(writeContract, client, parameters)\n}\n\nexport namespace createPair {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Address of the base token for the pair. */\n base: Address\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: createPair.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { base, ...rest } = parameters\n const call = createPair.call({ base })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `createPair` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.dex.createPair.call({\n * base: '0x20c0...beef',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { base } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n functionName: 'createPair',\n args: [base],\n })\n }\n\n /**\n * Extracts the `PairCreated` event from logs.\n *\n * @param logs - The logs.\n * @returns The `PairCreated` event.\n */\n export function extractEvent(logs: viem_Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.stablecoinDex,\n logs,\n eventName: 'PairCreated',\n strict: true,\n })\n if (!log) throw new Error('`PairCreated` event not found.')\n return log\n }\n}\n\n/**\n * Creates a new trading pair on the DEX.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.dex.createPairSync(client, {\n * base: '0x20c...11',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function createPairSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: createPairSync.Parameters<chain, account>,\n): Promise<createPairSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await createPair.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = createPair.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace createPairSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = createPair.Parameters<chain, account>\n\n export type Args = createPair.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.stablecoinDex,\n 'PairCreated',\n { IndexedOnly: false; Required: true }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Gets a user's token balance on the DEX.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const balance = await Actions.dex.getBalance(client, {\n * account: '0x...',\n * token: '0x20c...11',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The user's token balance on the DEX.\n */\nexport async function getBalance<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getBalance.Parameters<account>,\n): Promise<getBalance.ReturnValue> {\n const { account: acc = client.account, token, ...rest } = parameters\n const address = acc ? parseAccount(acc).address : undefined\n if (!address) throw new Error('account is required.')\n return readContract(client, {\n ...rest,\n ...getBalance.call({ account: address, token }),\n })\n}\n\nexport namespace getBalance {\n export type Parameters<\n account extends Account | undefined = Account | undefined,\n > = ReadParameters & GetAccountParameter<account> & Args\n\n export type Args = {\n /** Address of the account. */\n account: Address\n /** Address of the token. */\n token: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.stablecoinDex,\n 'balanceOf',\n never\n >\n\n /**\n * Defines a call to the `balanceOf` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, token } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n args: [account, token],\n functionName: 'balanceOf',\n })\n }\n}\n\n/**\n * Gets the quote for buying a specific amount of tokens.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const amountIn = await Actions.dex.getBuyQuote(client, {\n * amountOut: parseUnits('100', 6),\n * tokenIn: '0x20c...11',\n * tokenOut: '0x20c...20',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The amount of tokenIn needed to buy the specified amountOut.\n */\nexport async function getBuyQuote<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getBuyQuote.Parameters,\n): Promise<getBuyQuote.ReturnValue> {\n const { tokenIn, tokenOut, amountOut, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...getBuyQuote.call({ tokenIn, tokenOut, amountOut }),\n })\n}\n\nexport namespace getBuyQuote {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Amount of tokenOut to buy. */\n amountOut: bigint\n /** Address of the token to spend. */\n tokenIn: Address\n /** Address of the token to buy. */\n tokenOut: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.stablecoinDex,\n 'quoteSwapExactAmountOut',\n never\n >\n\n /**\n * Defines a call to the `quoteSwapExactAmountOut` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { tokenIn, tokenOut, amountOut } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n args: [tokenIn, tokenOut, amountOut],\n functionName: 'quoteSwapExactAmountOut',\n })\n }\n}\n\n/**\n * Gets an order's details from the orderbook.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const order = await Actions.dex.getOrder(client, {\n * orderId: 123n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The order details.\n */\nexport async function getOrder<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getOrder.Parameters,\n): Promise<getOrder.ReturnValue> {\n const { orderId, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...getOrder.call({ orderId }),\n })\n}\n\nexport namespace getOrder {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Order ID to query. */\n orderId: bigint\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.stablecoinDex,\n 'getOrder',\n never\n >\n\n /**\n * Defines a call to the `getOrder` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { orderId } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n args: [orderId],\n functionName: 'getOrder',\n })\n }\n}\n\n/**\n * Gets orderbook information for a trading pair.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const book = await Actions.dex.getOrderbook(client, {\n * base: '0x20c...11',\n * quote: '0x20c...20',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The orderbook information.\n */\nexport async function getOrderbook<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getOrderbook.Parameters,\n): Promise<getOrderbook.ReturnValue> {\n const { base, quote, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...getOrderbook.call({ base, quote }),\n })\n}\n\nexport namespace getOrderbook {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Address of the base token. */\n base: Address\n /** Address of the quote token. */\n quote: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.stablecoinDex,\n 'books',\n never\n >\n\n /**\n * Defines a call to the `books` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { base, quote } = args\n const pairKey = getPairKey(base, quote)\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n args: [pairKey],\n functionName: 'books',\n })\n }\n}\n\n/**\n * Gets the price level information at a specific tick.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions, Tick } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const level = await Actions.dex.getTickLevel(client, {\n * base: '0x20c...11',\n * tick: Tick.fromPrice('1.001'),\n * isBid: true,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The price level information.\n */\nexport async function getTickLevel<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getTickLevel.Parameters,\n): Promise<getTickLevel.ReturnValue> {\n const { base, tick, isBid, ...rest } = parameters\n const [head, tail, totalLiquidity] = await readContract(client, {\n ...rest,\n ...getTickLevel.call({ base, tick, isBid }),\n })\n return { head, tail, totalLiquidity }\n}\n\nexport namespace getTickLevel {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Address of the base token. */\n base: Address\n /** Whether to query the bid side (true) or ask side (false). */\n isBid: boolean\n /** Price tick to query. */\n tick: number\n }\n\n export type ReturnValue = {\n /** Order ID of the first order at this tick (0 if empty) */\n head: bigint\n /** Order ID of the last order at this tick (0 if empty) */\n tail: bigint\n /** Total liquidity available at this tick level */\n totalLiquidity: bigint\n }\n\n /**\n * Defines a call to the `getTickLevel` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { base, tick, isBid } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n args: [base, tick, isBid],\n functionName: 'getTickLevel',\n })\n }\n}\n\n/**\n * Gets the quote for selling a specific amount of tokens.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const amountOut = await Actions.dex.getSellQuote(client, {\n * amountIn: parseUnits('100', 6),\n * tokenIn: '0x20c...11',\n * tokenOut: '0x20c...20',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The amount of tokenOut received for selling the specified amountIn.\n */\nexport async function getSellQuote<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getSellQuote.Parameters,\n): Promise<getSellQuote.ReturnValue> {\n const { tokenIn, tokenOut, amountIn, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...getSellQuote.call({ tokenIn, tokenOut, amountIn }),\n })\n}\n\nexport namespace getSellQuote {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Amount of tokenIn to sell. */\n amountIn: bigint\n /** Address of the token to sell. */\n tokenIn: Address\n /** Address of the token to receive. */\n tokenOut: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.stablecoinDex,\n 'quoteSwapExactAmountIn',\n never\n >\n\n /**\n * Defines a call to the `quoteSwapExactAmountIn` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { tokenIn, tokenOut, amountIn } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n args: [tokenIn, tokenOut, amountIn],\n functionName: 'quoteSwapExactAmountIn',\n })\n }\n}\n\n/**\n * Places a limit order on the orderbook.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions, Tick } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.dex.place(client, {\n * amount: parseUnits('100', 6),\n * tick: Tick.fromPrice('0.99'),\n * token: '0x20c...11',\n * type: 'buy',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function place<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: place.Parameters<chain, account>,\n): Promise<place.ReturnValue> {\n return place.inner(writeContract, client, parameters)\n}\n\nexport namespace place {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokens to place in the order. */\n amount: bigint\n /** Price tick for the order. */\n tick: number\n /** Address of the base token. */\n token: Address\n /** Order type - 'buy' to buy the token, 'sell' to sell it. */\n type: OrderType\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: place.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { amount, token, type, tick, ...rest } = parameters\n const call = place.call({ amount, token, type, tick })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `place` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions, Tick } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.dex.place.call({\n * amount: parseUnits('100', 6),\n * tick: Tick.fromPrice('0.99'),\n * token: '0x20c0...beef',\n * type: 'buy',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, amount, type, tick } = args\n const isBid = type === 'buy'\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n functionName: 'place',\n args: [token, amount, isBid, tick],\n })\n }\n\n /**\n * Extracts the `OrderPlaced` event from logs.\n *\n * @param logs - The logs.\n * @returns The `OrderPlaced` event.\n */\n export function extractEvent(logs: viem_Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.stablecoinDex,\n logs,\n eventName: 'OrderPlaced',\n strict: true,\n })\n if (!log) throw new Error('`OrderPlaced` event not found.')\n return log\n }\n}\n\n/**\n * Places a flip order that automatically flips when filled.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions, Tick } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.dex.placeFlip(client, {\n * amount: parseUnits('100', 6),\n * flipTick: Tick.fromPrice('1.01'),\n * tick: Tick.fromPrice('0.99'),\n * token: '0x20c...11',\n * type: 'buy',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function placeFlip<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: placeFlip.Parameters<chain, account>,\n): Promise<placeFlip.ReturnValue> {\n return placeFlip.inner(writeContract, client, parameters)\n}\n\nexport namespace placeFlip {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokens to place in the order. */\n amount: bigint\n /** Target tick to flip to when order is filled. */\n flipTick: number\n /** Price tick for the order. */\n tick: number\n /** Address of the base token. */\n token: Address\n /** Order type - 'buy' to buy the token, 'sell' to sell it. */\n type: OrderType\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: placeFlip.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { amount, flipTick, tick, token, type, ...rest } = parameters\n const call = placeFlip.call({ amount, flipTick, tick, token, type })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `placeFlip` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions, Tick } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.dex.placeFlip.call({\n * amount: parseUnits('100', 6),\n * flipTick: Tick.fromPrice('1.01'),\n * tick: Tick.fromPrice('0.99'),\n * token: '0x20c0...beef',\n * type: 'buy',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, amount, type, tick, flipTick } = args\n const isBid = type === 'buy'\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n functionName: 'placeFlip',\n args: [token, amount, isBid, tick, flipTick],\n })\n }\n\n /**\n * Extracts the `OrderPlaced` event (with `isFlipOrder: true`) from logs.\n *\n * @param logs - The logs.\n * @returns The `OrderPlaced` event for a flip order.\n */\n export function extractEvent(logs: viem_Log[]) {\n const parsedLogs = parseEventLogs({\n abi: Abis.stablecoinDex,\n logs,\n eventName: 'OrderPlaced',\n strict: true,\n })\n const log = parsedLogs.find((l) => l.args.isFlipOrder)\n if (!log) throw new Error('`OrderPlaced` event (flip order) not found.')\n return log\n }\n}\n\n/**\n * Places a flip order that automatically flips when filled.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions, Tick } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.dex.placeFlipSync(client, {\n * amount: parseUnits('100', 6),\n * flipTick: Tick.fromPrice('1.01'),\n * tick: Tick.fromPrice('0.99'),\n * token: '0x20c...11',\n * type: 'buy',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function placeFlipSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: placeFlipSync.Parameters<chain, account>,\n): Promise<placeFlipSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await placeFlip.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = placeFlip.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace placeFlipSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = placeFlip.Parameters<chain, account>\n\n export type Args = placeFlip.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.stablecoinDex,\n 'OrderPlaced',\n { IndexedOnly: false; Required: true }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Places a limit order on the orderbook.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions, Tick } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.dex.placeSync(client, {\n * amount: parseUnits('100', 6),\n * tick: Tick.fromPrice('0.99'),\n * token: '0x20c...11',\n * type: 'buy',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function placeSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: placeSync.Parameters<chain, account>,\n): Promise<placeSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await place.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = place.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace placeSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = place.Parameters<chain, account>\n\n export type Args = place.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.stablecoinDex,\n 'OrderPlaced',\n { IndexedOnly: false; Required: true }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Sells a specific amount of tokens.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.dex.sell(client, {\n * amountIn: parseUnits('100', 6),\n * minAmountOut: parseUnits('95', 6),\n * tokenIn: '0x20c...11',\n * tokenOut: '0x20c...20',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function sell<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: sell.Parameters<chain, account>,\n): Promise<sell.ReturnValue> {\n return sell.inner(writeContract, client, parameters)\n}\n\nexport namespace sell {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokenIn to sell. */\n amountIn: bigint\n /** Minimum amount of tokenOut to receive. */\n minAmountOut: bigint\n /** Address of the token to sell. */\n tokenIn: Address\n /** Address of the token to receive. */\n tokenOut: Address\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: sell.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { tokenIn, tokenOut, amountIn, minAmountOut, ...rest } = parameters\n const call = sell.call({ tokenIn, tokenOut, amountIn, minAmountOut })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `swapExactAmountIn` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.dex.sell.call({\n * amountIn: parseUnits('100', 6),\n * minAmountOut: parseUnits('95', 6),\n * tokenIn: '0x20c0...beef',\n * tokenOut: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { tokenIn, tokenOut, amountIn, minAmountOut } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n functionName: 'swapExactAmountIn',\n args: [tokenIn, tokenOut, amountIn, minAmountOut],\n })\n }\n}\n\n/**\n * Sells a specific amount of tokens.\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.dex.sellSync(client, {\n * amountIn: parseUnits('100', 6),\n * minAmountOut: parseUnits('95', 6),\n * tokenIn: '0x20c...11',\n * tokenOut: '0x20c...20',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt.\n */\nexport async function sellSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: sellSync.Parameters<chain, account>,\n): Promise<sellSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await sell.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n return { receipt }\n}\n\nexport namespace sellSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = sell.Parameters<chain, account>\n\n export type Args = sell.Args\n\n export type ReturnValue = Compute<{\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }>\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Watches for flip order placed events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = Actions.dex.watchFlipOrderPlaced(client, {\n * onFlipOrderPlaced: (args, log) => {\n * console.log('Flip order placed:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchFlipOrderPlaced<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchFlipOrderPlaced.Parameters,\n) {\n const { onFlipOrderPlaced, maker, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n eventName: 'OrderPlaced',\n args: {\n ...(maker !== undefined && { maker }),\n ...(token !== undefined && { token }),\n },\n onLogs: (logs) => {\n for (const log of logs) {\n if (log.args.isFlipOrder) onFlipOrderPlaced(log.args, log)\n }\n },\n strict: true,\n })\n}\n\nexport declare namespace watchFlipOrderPlaced {\n export type Args = GetEventArgs<\n typeof Abis.stablecoinDex,\n 'OrderPlaced',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.stablecoinDex, 'OrderPlaced'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.stablecoinDex,\n 'OrderPlaced',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Address of the maker to filter events. */\n maker?: Address | undefined\n /** Callback to invoke when a flip order is placed. */\n onFlipOrderPlaced: (args: Args, log: Log) => void\n /** Address of the token to filter events. */\n token?: Address | undefined\n }\n}\n\n/**\n * Watches for order cancelled events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = Actions.dex.watchOrderCancelled(client, {\n * onOrderCancelled: (args, log) => {\n * console.log('Order cancelled:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchOrderCancelled<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchOrderCancelled.Parameters,\n) {\n const { onOrderCancelled, orderId, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n eventName: 'OrderCancelled',\n args: orderId !== undefined ? { orderId } : undefined,\n onLogs: (logs) => {\n for (const log of logs) onOrderCancelled(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchOrderCancelled {\n export type Args = GetEventArgs<\n typeof Abis.stablecoinDex,\n 'OrderCancelled',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.stablecoinDex, 'OrderCancelled'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.stablecoinDex,\n 'OrderCancelled',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when an order is cancelled. */\n onOrderCancelled: (args: Args, log: Log) => void\n /** Order ID to filter events. */\n orderId?: bigint | undefined\n }\n}\n\n/**\n * Watches for order filled events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = Actions.dex.watchOrderFilled(client, {\n * onOrderFilled: (args, log) => {\n * console.log('Order filled:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchOrderFilled<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchOrderFilled.Parameters,\n) {\n const { onOrderFilled, maker, taker, orderId, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n eventName: 'OrderFilled',\n args: {\n ...(orderId !== undefined && { orderId }),\n ...(maker !== undefined && { maker }),\n ...(taker !== undefined && { taker }),\n },\n onLogs: (logs) => {\n for (const log of logs) onOrderFilled(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchOrderFilled {\n export type Args = GetEventArgs<\n typeof Abis.stablecoinDex,\n 'OrderFilled',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.stablecoinDex, 'OrderFilled'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.stablecoinDex,\n 'OrderFilled',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Address of the maker to filter events. */\n maker?: Address | undefined\n /** Callback to invoke when an order is filled. */\n onOrderFilled: (args: Args, log: Log) => void\n /** Order ID to filter events. */\n orderId?: bigint | undefined\n /** Address of the taker to filter events. */\n taker?: Address | undefined\n }\n}\n\n/**\n * Watches for order placed events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = Actions.dex.watchOrderPlaced(client, {\n * onOrderPlaced: (args, log) => {\n * console.log('Order placed:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchOrderPlaced<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchOrderPlaced.Parameters,\n) {\n const { onOrderPlaced, maker, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n eventName: 'OrderPlaced',\n args: {\n ...(maker !== undefined && { maker }),\n ...(token !== undefined && { token }),\n },\n onLogs: (logs) => {\n for (const log of logs) onOrderPlaced(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchOrderPlaced {\n export type Args = GetEventArgs<\n typeof Abis.stablecoinDex,\n 'OrderPlaced',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.stablecoinDex, 'OrderPlaced'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.stablecoinDex,\n 'OrderPlaced',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Address of the maker to filter events. */\n maker?: Address | undefined\n /** Callback to invoke when an order is placed. */\n onOrderPlaced: (args: Args, log: Log) => void\n /** Address of the token to filter events. */\n token?: Address | undefined\n }\n}\n\n/**\n * Withdraws tokens from the DEX to the caller's wallet.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.dex.withdraw(client, {\n * amount: 100n,\n * token: '0x20c...11',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function withdraw<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: withdraw.Parameters<chain, account>,\n): Promise<withdraw.ReturnValue> {\n return withdraw.inner(writeContract, client, parameters)\n}\n\nexport namespace withdraw {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount to withdraw. */\n amount: bigint\n /** Address of the token to withdraw. */\n token: Address\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: withdraw.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { token, amount, ...rest } = parameters\n const call = withdraw.call({ token, amount })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `withdraw` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, parseUnits, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.dex.withdraw.call({\n * amount: parseUnits('100', 6),\n * token: '0x20c0...beef',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, amount } = args\n return defineCall({\n address: Addresses.stablecoinDex,\n abi: Abis.stablecoinDex,\n functionName: 'withdraw',\n args: [token, amount],\n })\n }\n}\n\n/**\n * Withdraws tokens from the DEX to the caller's wallet.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { privateKeyToAccount } from 'viem/accounts'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.dex.withdrawSync(client, {\n * amount: 100n,\n * token: '0x20c...11',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt.\n */\nexport async function withdrawSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: withdrawSync.Parameters<chain, account>,\n): Promise<withdrawSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await withdraw.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n return { receipt }\n}\n\nexport namespace withdrawSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = withdraw.Parameters<chain, account>\n\n export type Args = withdraw.Args\n\n export type ReturnValue = Compute<{\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }>\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\nfunction getPairKey(base: Address, quote: Address) {\n return Hash.keccak256(Hex.concat(base, quote))\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport { waitForTransactionReceipt } from '../../actions/public/waitForTransactionReceipt.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 { Hash } from '../../types/misc.js'\nimport type { TransactionReceipt } from '../Transaction.js'\n\n/**\n * Funds an account with an initial amount of set token(s)\n * on Tempo's testnet.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hashes = await Actions.faucet.fund(client, {\n * account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function fund<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: fund.Parameters,\n): Promise<fund.ReturnValue> {\n const account = parseAccount(parameters.account)\n return client.request<{\n Method: 'tempo_fundAddress'\n Parameters: [address: Address]\n ReturnType: readonly Hash[]\n }>({\n method: 'tempo_fundAddress',\n params: [account.address],\n })\n}\n\nexport declare namespace fund {\n export type Parameters = {\n /** Account to fund. */\n account: Account | Address\n }\n\n export type ReturnValue = readonly Hash[]\n}\n\n/**\n * Funds an account with an initial amount of set token(s)\n * on Tempo's testnet. Waits for the transactions to be included\n * on a block before returning a response.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hashes = await Actions.faucet.fundSync(client, {\n * account: '0xdeadbeefdeadbeefdeadbeefdeadbeefdeadbeef',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function fundSync<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: fundSync.Parameters,\n): Promise<fundSync.ReturnValue> {\n const { timeout = 10_000 } = parameters\n const account = parseAccount(parameters.account)\n const hashes = await client.request<{\n Method: 'tempo_fundAddress'\n Parameters: [address: Address]\n ReturnType: readonly Hash[]\n }>({\n method: 'tempo_fundAddress',\n params: [account.address],\n })\n const receipts = await Promise.all(\n hashes.map((hash) =>\n waitForTransactionReceipt(client, {\n hash,\n checkReplacement: false,\n timeout,\n }),\n ),\n )\n return receipts\n}\n\nexport declare namespace fundSync {\n export type Parameters = {\n /** Account to fund. */\n account: Account | Address\n /** Timeout. */\n timeout?: number | undefined\n }\n\n export type ReturnValue = readonly TransactionReceipt[]\n}\n","import type { Address } from 'abitype'\nimport { TokenId } from 'ox/tempo'\nimport type { Account } from '../../accounts/types.js'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport { readContract } from '../../actions/public/readContract.js'\nimport type { WatchContractEventParameters } from '../../actions/public/watchContractEvent.js'\nimport { watchContractEvent } from '../../actions/public/watchContractEvent.js'\nimport type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'\nimport { writeContract } from '../../actions/wallet/writeContract.js'\nimport { writeContractSync } from '../../actions/wallet/writeContractSync.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport { zeroAddress } from '../../constants/address.js'\nimport type { BaseErrorType } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'\nimport type { Log, Log as viem_Log } from '../../types/log.js'\nimport type { Compute, UnionOmit } from '../../types/utils.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport * as Abis from '../Abis.js'\nimport * as Addresses from '../Addresses.js'\nimport type {\n GetAccountParameter,\n ReadParameters,\n WriteParameters,\n} from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\nimport type { TransactionReceipt } from '../Transaction.js'\n\n/**\n * Gets the user's default fee token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const { address, id } = await Actions.fee.getUserToken(client)\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function getUserToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n ...parameters: account extends Account\n ? [getUserToken.Parameters<account>] | []\n : [getUserToken.Parameters<account>]\n): Promise<getUserToken.ReturnValue> {\n const { account: account_ = client.account, ...rest } = parameters[0] ?? {}\n if (!account_) throw new Error('account is required.')\n const account = parseAccount(account_)\n const address = await readContract(client, {\n ...rest,\n ...getUserToken.call({ account: account.address }),\n })\n if (address === zeroAddress) return null\n return {\n address,\n id: TokenId.fromAddress(address),\n }\n}\n\nexport namespace getUserToken {\n export type Parameters<\n account extends Account | undefined = Account | undefined,\n > = ReadParameters & GetAccountParameter<account>\n\n export type Args = {\n /** Account address. */\n account: Address\n }\n\n export type ReturnValue = Compute<{\n address: Address\n id: bigint\n } | null>\n\n /**\n * Defines a call to the `userTokens` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account } = args\n return defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeManager,\n args: [account],\n functionName: 'userTokens',\n })\n }\n}\n\n/**\n * Sets the user's default fee token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.fee.setUserToken(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function setUserToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setUserToken.Parameters<chain, account>,\n): Promise<setUserToken.ReturnValue> {\n return setUserToken.inner(writeContract, client, parameters)\n}\n\nexport namespace setUserToken {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: setUserToken.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { token, ...rest } = parameters\n const call = setUserToken.call({ token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `setUserToken` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.fee.setUserToken.call({\n * token: '0x20c0...beef',\n * }),\n * actions.fee.setUserToken.call({\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token } = args\n return defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeManager,\n functionName: 'setUserToken',\n args: [TokenId.toAddress(token)],\n })\n }\n\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.feeManager,\n logs,\n eventName: 'UserTokenSet',\n strict: true,\n })\n if (!log) throw new Error('`UserTokenSet` event not found.')\n return log\n }\n}\n\n/**\n * Sets the user's default fee token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.fee.setUserTokenSync(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function setUserTokenSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setUserTokenSync.Parameters<chain, account>,\n): Promise<setUserTokenSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await setUserToken.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = setUserToken.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace setUserTokenSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = setUserToken.Parameters<chain, account>\n\n export type Args = setUserToken.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.feeManager,\n 'UserTokenSet',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Watches for user token set events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.fee.watchSetUserToken(client, {\n * onUserTokenSet: (args, log) => {\n * console.log('User token set:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchSetUserToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchSetUserToken.Parameters,\n) {\n const { onUserTokenSet, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.feeManager,\n abi: Abis.feeManager,\n eventName: 'UserTokenSet',\n onLogs: (logs) => {\n for (const log of logs) onUserTokenSet(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchSetUserToken {\n export type Args = GetEventArgs<\n typeof Abis.feeManager,\n 'UserTokenSet',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.feeManager, 'UserTokenSet'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.feeManager, 'UserTokenSet', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a user token is set. */\n onUserTokenSet: (args: Args, log: Log) => void\n }\n}\n\n/**\n * Gets the validator's preferred fee token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const { address, id } = await Actions.fee.getValidatorToken(client, {\n * validator: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The validator's preferred fee token, or null if not set.\n */\nexport async function getValidatorToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getValidatorToken.Parameters,\n): Promise<getValidatorToken.ReturnValue> {\n const { validator, ...rest } = parameters\n const address = await readContract(client, {\n ...rest,\n ...getValidatorToken.call({ validator }),\n })\n if (address === zeroAddress) return null\n return {\n address,\n id: TokenId.fromAddress(address),\n }\n}\n\nexport namespace getValidatorToken {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Validator address. */\n validator: Address\n }\n\n export type ReturnValue = Compute<{\n address: Address\n id: bigint\n } | null>\n\n /**\n * Defines a call to the `validatorTokens` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { validator } = args\n return defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeManager,\n args: [validator],\n functionName: 'validatorTokens',\n })\n }\n}\n\n/**\n * Sets the validator's preferred fee token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.fee.setValidatorToken(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function setValidatorToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setValidatorToken.Parameters<chain, account>,\n): Promise<setValidatorToken.ReturnValue> {\n return setValidatorToken.inner(writeContract, client, parameters)\n}\n\nexport namespace setValidatorToken {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: setValidatorToken.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { token, ...rest } = parameters\n const call = setValidatorToken.call({ token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `setValidatorToken` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.fee.setValidatorToken.call({\n * token: '0x20c0...beef',\n * }),\n * actions.fee.setValidatorToken.call({\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token } = args\n return defineCall({\n address: Addresses.feeManager,\n abi: Abis.feeManager,\n functionName: 'setValidatorToken',\n args: [TokenId.toAddress(token)],\n })\n }\n\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.feeManager,\n logs,\n eventName: 'ValidatorTokenSet',\n strict: true,\n })\n if (!log) throw new Error('`ValidatorTokenSet` event not found.')\n return log\n }\n}\n\n/**\n * Sets the validator's preferred fee token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.fee.setValidatorTokenSync(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function setValidatorTokenSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setValidatorTokenSync.Parameters<chain, account>,\n): Promise<setValidatorTokenSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await setValidatorToken.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = setValidatorToken.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace setValidatorTokenSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = setValidatorToken.Parameters<chain, account>\n\n export type Args = setValidatorToken.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.feeManager,\n 'ValidatorTokenSet',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Watches for validator token set events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.fee.watchSetValidatorToken(client, {\n * onValidatorTokenSet: (args, log) => {\n * console.log('Validator token set:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchSetValidatorToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchSetValidatorToken.Parameters,\n) {\n const { onValidatorTokenSet, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.feeManager,\n abi: Abis.feeManager,\n eventName: 'ValidatorTokenSet',\n onLogs: (logs) => {\n for (const log of logs) onValidatorTokenSet(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchSetValidatorToken {\n export type Args = GetEventArgs<\n typeof Abis.feeManager,\n 'ValidatorTokenSet',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.feeManager, 'ValidatorTokenSet'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.feeManager,\n 'ValidatorTokenSet',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a validator token is set. */\n onValidatorTokenSet: (args: Args, log: Log) => void\n }\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport type { ReadContractReturnType } from '../../actions/public/readContract.js'\nimport { readContract } from '../../actions/public/readContract.js'\nimport type { WatchContractEventParameters } from '../../actions/public/watchContractEvent.js'\nimport { watchContractEvent } from '../../actions/public/watchContractEvent.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 { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'\nimport type { Log as viem_Log } from '../../types/log.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport * as Abis from '../Abis.js'\nimport * as Addresses from '../Addresses.js'\nimport type { ReadParameters } from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\n\n/**\n * Gets the nonce for an account and nonce key.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const nonce = await Actions.nonce.getNonce(client, {\n * account: '0x...',\n * nonceKey: 1n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The nonce value.\n */\nexport async function getNonce<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getNonce.Parameters,\n): Promise<getNonce.ReturnValue> {\n const { account, nonceKey, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...getNonce.call({ account, nonceKey }),\n })\n}\n\nexport namespace getNonce {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Account address. */\n account: Address\n /** Nonce key (must be > 0, key 0 is reserved for protocol nonces). */\n nonceKey: bigint\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.nonce,\n 'getNonce',\n never\n >\n\n /**\n * Defines a call to the `getNonce` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`multicall`](https://viem.sh/docs/contract/multicall): execute multiple calls in parallel\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await client.multicall({\n * contracts: [\n * Actions.nonce.getNonce.call({ account: '0x...', nonceKey: 1n }),\n * Actions.nonce.getNonce.call({ account: '0x...', nonceKey: 2n }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, nonceKey } = args\n return defineCall({\n address: Addresses.nonceManager,\n abi: Abis.nonce,\n args: [account, nonceKey],\n functionName: 'getNonce',\n })\n }\n}\n\nexport function watchNonceIncremented<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchNonceIncremented.Parameters,\n) {\n const { onNonceIncremented, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.nonceManager,\n abi: Abis.nonce,\n eventName: 'NonceIncremented',\n onLogs: (logs) => {\n for (const log of logs) onNonceIncremented(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchNonceIncremented {\n export type Args = GetEventArgs<\n typeof Abis.nonce,\n 'NonceIncremented',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.nonce, 'NonceIncremented'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.nonce, 'NonceIncremented', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a nonce is incremented. */\n onNonceIncremented: (args: Args, log: Log) => void\n }\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport type { ReadContractReturnType } from '../../actions/public/readContract.js'\nimport { readContract } from '../../actions/public/readContract.js'\nimport type { WatchContractEventParameters } from '../../actions/public/watchContractEvent.js'\nimport { watchContractEvent } from '../../actions/public/watchContractEvent.js'\nimport type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'\nimport { writeContract } from '../../actions/wallet/writeContract.js'\nimport { writeContractSync } from '../../actions/wallet/writeContractSync.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseErrorType } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'\nimport type { Log, Log as viem_Log } from '../../types/log.js'\nimport type { Compute, UnionOmit } from '../../types/utils.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport * as Abis from '../Abis.js'\nimport * as Addresses from '../Addresses.js'\nimport type { ReadParameters, WriteParameters } from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\nimport type { TransactionReceipt } from '../Transaction.js'\n\nexport type PolicyType = 'whitelist' | 'blacklist'\n\nconst policyTypeMap = {\n whitelist: 0,\n blacklist: 1,\n} as const\n\n/**\n * Creates a new policy.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const { hash, policyId } = await Actions.policy.create(client, {\n * admin: '0x...',\n * type: 'whitelist',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash and policy ID.\n */\nexport async function create<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: create.Parameters<chain, account>,\n): Promise<create.ReturnValue> {\n return create.inner(writeContract, client, parameters)\n}\n\nexport namespace create {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> &\n Omit<Args, 'admin'> & {\n /** Address of the policy admin. */\n admin?: Address | undefined\n }\n\n export type Args = {\n /** Optional array of accounts to initialize the policy with. */\n addresses?: readonly Address[] | undefined\n /** Address of the policy admin. */\n admin: Address\n /** Type of policy to create. */\n type: PolicyType\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const {\n account = client.account,\n addresses,\n chain = client.chain,\n type,\n ...rest\n } = parameters\n\n if (!account) throw new Error('`account` is required')\n\n const admin = parseAccount(account).address!\n\n const call = create.call({ admin, type, addresses })\n return action(client, {\n ...rest,\n account,\n chain,\n ...call,\n } as never) as never\n }\n\n /**\n * Defines a call to the `createPolicy` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.policy.create.call({\n * admin: '0xfeed...fede',\n * type: 'whitelist',\n * }),\n * actions.policy.create.call({\n * admin: '0xfeed...fede',\n * type: 'blacklist',\n * addresses: ['0x20c0...beef', '0x20c0...babe'],\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { admin, type, addresses } = args\n const config = (() => {\n if (addresses)\n return {\n functionName: 'createPolicyWithAccounts',\n args: [admin, policyTypeMap[type], addresses],\n } as const\n return {\n functionName: 'createPolicy',\n args: [admin, policyTypeMap[type]],\n } as const\n })()\n return defineCall({\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n ...config,\n })\n }\n\n /**\n * Extracts the `PolicyCreated` event from logs.\n *\n * @param logs - The logs.\n * @returns The `PolicyCreated` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip403Registry,\n logs,\n eventName: 'PolicyCreated',\n strict: true,\n })\n if (!log) throw new Error('`PolicyCreated` event not found.')\n return log\n }\n}\n\n/**\n * Creates a new policy.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.policy.createSync(client, {\n * admin: '0x...',\n * type: 'whitelist',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function createSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: createSync.Parameters<chain, account>,\n): Promise<createSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await create.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = create.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace createSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = create.Parameters<chain, account>\n\n export type Args = create.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip403Registry,\n 'PolicyCreated',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Sets the admin for a policy.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.policy.setAdmin(client, {\n * policyId: 2n,\n * admin: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function setAdmin<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setAdmin.Parameters<chain, account>,\n): Promise<setAdmin.ReturnValue> {\n return setAdmin.inner(writeContract, client, parameters)\n}\n\nexport namespace setAdmin {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** New admin address. */\n admin: Address\n /** Policy ID. */\n policyId: bigint\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: setAdmin.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { policyId, admin, ...rest } = parameters\n const call = setAdmin.call({ policyId, admin })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `setPolicyAdmin` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.policy.setAdmin.call({\n * policyId: 2n,\n * admin: '0xfeed...fede',\n * }),\n * actions.policy.setAdmin.call({\n * policyId: 3n,\n * admin: '0xfeed...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { policyId, admin } = args\n return defineCall({\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n functionName: 'setPolicyAdmin',\n args: [policyId, admin],\n })\n }\n\n /**\n * Extracts the `PolicyAdminUpdated` event from logs.\n *\n * @param logs - The logs.\n * @returns The `PolicyAdminUpdated` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip403Registry,\n logs,\n eventName: 'PolicyAdminUpdated',\n strict: true,\n })\n if (!log) throw new Error('`PolicyAdminUpdated` event not found.')\n return log\n }\n}\n\n/**\n * Sets the admin for a policy.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.policy.setAdminSync(client, {\n * policyId: 2n,\n * admin: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function setAdminSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setAdminSync.Parameters<chain, account>,\n): Promise<setAdminSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await setAdmin.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = setAdmin.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace setAdminSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = setAdmin.Parameters<chain, account>\n\n export type Args = setAdmin.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip403Registry,\n 'PolicyAdminUpdated',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Modifies a policy whitelist.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.policy.modifyWhitelist(client, {\n * policyId: 2n,\n * account: '0x...',\n * allowed: true,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function modifyWhitelist<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: modifyWhitelist.Parameters<chain, account>,\n): Promise<modifyWhitelist.ReturnValue> {\n return modifyWhitelist.inner(writeContract, client, parameters)\n}\n\nexport namespace modifyWhitelist {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Target account address. */\n address: Address\n /** Whether the account is allowed. */\n allowed: boolean\n /** Policy ID. */\n policyId: bigint\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: modifyWhitelist.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { address: targetAccount, allowed, policyId, ...rest } = parameters\n const call = modifyWhitelist.call({\n address: targetAccount,\n allowed,\n policyId,\n })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `modifyPolicyWhitelist` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.policy.modifyWhitelist.call({\n * policyId: 2n,\n * address: '0x20c0...beef',\n * allowed: true,\n * }),\n * actions.policy.modifyWhitelist.call({\n * policyId: 2n,\n * address: '0x20c0...babe',\n * allowed: false,\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { policyId, address, allowed } = args\n return defineCall({\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n functionName: 'modifyPolicyWhitelist',\n args: [policyId, address, allowed],\n })\n }\n\n /**\n * Extracts the `WhitelistUpdated` event from logs.\n *\n * @param logs - The logs.\n * @returns The `WhitelistUpdated` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip403Registry,\n logs,\n eventName: 'WhitelistUpdated',\n strict: true,\n })\n if (!log) throw new Error('`WhitelistUpdated` event not found.')\n return log\n }\n}\n\n/**\n * Modifies a policy whitelist.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.policy.modifyWhitelistSync(client, {\n * policyId: 2n,\n * account: '0x...',\n * allowed: true,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function modifyWhitelistSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: modifyWhitelistSync.Parameters<chain, account>,\n): Promise<modifyWhitelistSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await modifyWhitelist.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = modifyWhitelist.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace modifyWhitelistSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = modifyWhitelist.Parameters<chain, account>\n\n export type Args = modifyWhitelist.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip403Registry,\n 'WhitelistUpdated',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Modifies a policy blacklist.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.policy.modifyBlacklist(client, {\n * policyId: 2n,\n * account: '0x...',\n * restricted: true,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function modifyBlacklist<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: modifyBlacklist.Parameters<chain, account>,\n): Promise<modifyBlacklist.ReturnValue> {\n return modifyBlacklist.inner(writeContract, client, parameters)\n}\n\nexport namespace modifyBlacklist {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Target account address. */\n address: Address\n /** Policy ID. */\n policyId: bigint\n /** Whether the account is restricted. */\n restricted: boolean\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: modifyBlacklist.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { address: targetAccount, policyId, restricted, ...rest } = parameters\n const call = modifyBlacklist.call({\n address: targetAccount,\n policyId,\n restricted,\n })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `modifyPolicyBlacklist` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.policy.modifyBlacklist.call({\n * policyId: 2n,\n * address: '0x20c0...beef',\n * restricted: true,\n * }),\n * actions.policy.modifyBlacklist.call({\n * policyId: 2n,\n * address: '0x20c0...babe',\n * restricted: false,\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { policyId, address, restricted } = args\n return defineCall({\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n functionName: 'modifyPolicyBlacklist',\n args: [policyId, address, restricted],\n })\n }\n\n /**\n * Extracts the `BlacklistUpdated` event from logs.\n *\n * @param logs - The logs.\n * @returns The `BlacklistUpdated` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip403Registry,\n logs,\n eventName: 'BlacklistUpdated',\n strict: true,\n })\n if (!log) throw new Error('`BlacklistUpdated` event not found.')\n return log\n }\n}\n\n/**\n * Modifies a policy blacklist.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.policy.modifyBlacklistSync(client, {\n * policyId: 2n,\n * account: '0x...',\n * restricted: true,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function modifyBlacklistSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: modifyBlacklistSync.Parameters<chain, account>,\n): Promise<modifyBlacklistSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await modifyBlacklist.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = modifyBlacklist.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace modifyBlacklistSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = modifyBlacklist.Parameters<chain, account>\n\n export type Args = modifyBlacklist.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip403Registry,\n 'BlacklistUpdated',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Gets policy data.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const data = await Actions.policy.getData(client, {\n * policyId: 2n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The policy data.\n */\nexport async function getData<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getData.Parameters,\n): Promise<getData.ReturnValue> {\n const { policyId, ...rest } = parameters\n const result = await readContract(client, {\n ...rest,\n ...getData.call({ policyId }),\n })\n return {\n admin: result[1],\n type: result[0] === 0 ? 'whitelist' : 'blacklist',\n }\n}\n\nexport namespace getData {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Policy ID. */\n policyId: bigint\n }\n\n export type ReturnValue = Compute<{\n /** Admin address. */\n admin: Address\n /** Policy type. */\n type: PolicyType\n }>\n\n /**\n * Defines a call to the `policyData` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { policyId } = args\n return defineCall({\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n args: [policyId],\n functionName: 'policyData',\n })\n }\n}\n\n/**\n * Checks if a user is authorized by a policy.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const authorized = await Actions.policy.isAuthorized(client, {\n * policyId: 2n,\n * user: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns Whether the user is authorized.\n */\nexport async function isAuthorized<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: isAuthorized.Parameters,\n): Promise<isAuthorized.ReturnValue> {\n const { policyId, user, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...isAuthorized.call({ policyId, user }),\n })\n}\n\nexport namespace isAuthorized {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Policy ID. */\n policyId: bigint\n /** User address to check. */\n user: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.tip403Registry,\n 'isAuthorized',\n never\n >\n\n /**\n * Defines a call to the `isAuthorized` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { policyId, user } = args\n return defineCall({\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n args: [policyId, user],\n functionName: 'isAuthorized',\n })\n }\n}\n\n/**\n * Watches for policy creation events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.policy.watchCreate(client, {\n * onPolicyCreated: (args, log) => {\n * console.log('Policy created:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchCreate<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchCreate.Parameters,\n) {\n const { onPolicyCreated, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n eventName: 'PolicyCreated',\n onLogs: (logs) => {\n for (const log of logs)\n onPolicyCreated(\n {\n ...log.args,\n type: log.args.policyType === 0 ? 'whitelist' : 'blacklist',\n },\n log,\n )\n },\n strict: true,\n })\n}\n\nexport declare namespace watchCreate {\n export type Args = Compute<{\n policyId: bigint\n updater: Address\n type: PolicyType\n }>\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip403Registry, 'PolicyCreated'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.tip403Registry,\n 'PolicyCreated',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a policy is created. */\n onPolicyCreated: (args: Args, log: Log) => void\n }\n}\n\n/**\n * Watches for policy admin update events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.policy.watchAdminUpdated(client, {\n * onAdminUpdated: (args, log) => {\n * console.log('Policy admin updated:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchAdminUpdated<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchAdminUpdated.Parameters,\n) {\n const { onAdminUpdated, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n eventName: 'PolicyAdminUpdated',\n onLogs: (logs) => {\n for (const log of logs) onAdminUpdated(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchAdminUpdated {\n export type Args = GetEventArgs<\n typeof Abis.tip403Registry,\n 'PolicyAdminUpdated',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip403Registry, 'PolicyAdminUpdated'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.tip403Registry,\n 'PolicyAdminUpdated',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a policy admin is updated. */\n onAdminUpdated: (args: Args, log: Log) => void\n }\n}\n\n/**\n * Watches for whitelist update events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.policy.watchWhitelistUpdated(client, {\n * onWhitelistUpdated: (args, log) => {\n * console.log('Whitelist updated:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchWhitelistUpdated<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchWhitelistUpdated.Parameters,\n) {\n const { onWhitelistUpdated, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n eventName: 'WhitelistUpdated',\n onLogs: (logs) => {\n for (const log of logs) onWhitelistUpdated(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchWhitelistUpdated {\n export type Args = GetEventArgs<\n typeof Abis.tip403Registry,\n 'WhitelistUpdated',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip403Registry, 'WhitelistUpdated'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.tip403Registry,\n 'WhitelistUpdated',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a whitelist is updated. */\n onWhitelistUpdated: (args: Args, log: Log) => void\n }\n}\n\n/**\n * Watches for blacklist update events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.policy.watchBlacklistUpdated(client, {\n * onBlacklistUpdated: (args, log) => {\n * console.log('Blacklist updated:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchBlacklistUpdated<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchBlacklistUpdated.Parameters,\n) {\n const { onBlacklistUpdated, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.tip403Registry,\n abi: Abis.tip403Registry,\n eventName: 'BlacklistUpdated',\n onLogs: (logs) => {\n for (const log of logs) onBlacklistUpdated(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchBlacklistUpdated {\n export type Args = GetEventArgs<\n typeof Abis.tip403Registry,\n 'BlacklistUpdated',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip403Registry, 'BlacklistUpdated'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.tip403Registry,\n 'BlacklistUpdated',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a blacklist is updated. */\n onBlacklistUpdated: (args: Args, log: Log) => void\n }\n}\n","import type { Address } from 'abitype'\nimport type { Account } from '../../accounts/types.js'\nimport type { ReadContractReturnType } from '../../actions/public/readContract.js'\nimport { readContract } from '../../actions/public/readContract.js'\nimport type {\n WatchContractEventParameters,\n WatchContractEventReturnType,\n} from '../../actions/public/watchContractEvent.js'\nimport { watchContractEvent } from '../../actions/public/watchContractEvent.js'\nimport type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'\nimport { writeContract } from '../../actions/wallet/writeContract.js'\nimport { writeContractSync } from '../../actions/wallet/writeContractSync.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseErrorType } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'\nimport type { Log, Log as viem_Log } from '../../types/log.js'\nimport type { UnionOmit } from '../../types/utils.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport * as Abis from '../Abis.js'\nimport type { ReadParameters, WriteParameters } from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\n\n/**\n * Claims accumulated rewards for a recipient.\n *\n * This function allows a reward recipient to claim their accumulated rewards\n * and receive them as token transfers to their own balance.\n *\n * - Accrues all pending rewards up to the current block timestamp.\n * - Updates the caller's reward accounting.\n * - Transfers the caller's accumulated `rewardBalance` from the token contract to the caller.\n * - If the contract's balance is insufficient, claims up to the available amount.\n * - Returns the actual amount claimed.\n *\n * Notes:\n * - Reverts with `Paused` if the token is paused.\n * - Reverts with `PolicyForbids` if the caller is not authorized to receive tokens under TIP-403.\n * - If opted in, the claimed amount is added back to `optedInSupply` since it goes to the recipient's balance.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.reward.claim(client, {\n * token: '0x20c0000000000000000000000000000000000001',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function claim<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: claim.Parameters<chain, account>,\n): Promise<claim.ReturnValue> {\n return claim.inner(writeContract, client, parameters)\n}\n\nexport namespace claim {\n export type Args = {\n /** The TIP20 token address */\n token: Address\n }\n\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { token, ...rest } = parameters\n const call = claim.call({ token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `claimRewards` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const hash = await client.sendTransaction({\n * calls: [actions.reward.claim.call({\n * token: '0x20c0000000000000000000000000000000000001',\n * })],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token } = args\n return defineCall({\n address: token,\n abi: Abis.tip20,\n args: [],\n functionName: 'claimRewards',\n })\n }\n}\n\n/**\n * Claims accumulated rewards for a recipient and waits for confirmation.\n *\n * This function allows a reward recipient to claim their accumulated rewards\n * and receive them as token transfers to their own balance.\n *\n * Behavior:\n * - Accrues all pending rewards up to the current block timestamp.\n * - Updates the caller's reward accounting.\n * - Transfers the caller's accumulated `rewardBalance` from the token contract to the caller.\n * - If the contract's balance is insufficient, claims up to the available amount.\n *\n * Notes:\n * - Reverts with `Paused` if the token is paused.\n * - Reverts with `PolicyForbids` if the caller is not authorized to receive tokens under TIP-403.\n * - If opted in, the claimed amount is added back to `optedInSupply` since it goes to the recipient's balance.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const { receipt } = await Actions.reward.claimSync(client, {\n * token: '0x20c0000000000000000000000000000000000001',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The amount claimed and transaction receipt.\n */\nexport async function claimSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: claimSync.Parameters<chain, account>,\n): Promise<claimSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await claim.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n return {\n receipt,\n } as never\n}\n\nexport namespace claimSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & claim.Args\n\n export type ReturnValue = {\n /** The transaction receipt */\n receipt: Awaited<ReturnType<typeof writeContractSync>>\n }\n\n export type ErrorType = claim.ErrorType\n}\n\n/**\n * Distributes rewards to opted-in token holders.\n *\n * This function transfers `amount` of tokens from the caller into the token contract's\n * reward pool and immediately distributes them to current opted-in holders by increasing\n * `globalRewardPerToken`.\n *\n * Notes:\n * - Reverts with `InvalidAmount` if `amount == 0`.\n * - The transfer from caller to pool is subject to TIP-403 policy checks.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.reward.distribute(client, {\n * amount: 100000000000000000000n,\n * token: '0x20c0000000000000000000000000000000000001',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function distribute<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: distribute.Parameters<chain, account>,\n): Promise<distribute.ReturnValue> {\n return distribute.inner(writeContract, client, parameters)\n}\n\n/**\n * Distributes rewards to opted-in token holders and waits for confirmation.\n *\n * This function transfers `amount` of tokens from the caller into the token contract's\n * reward pool and immediately distributes them to current opted-in holders by increasing\n * `globalRewardPerToken`.\n *\n * Notes:\n * - Reverts with `InvalidAmount` if `amount == 0`.\n * - The transfer from caller to pool is subject to TIP-403 policy checks.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const { amount, funder, receipt } = await Actions.reward.distributeSync(client, {\n * amount: 100000000000000000000n,\n * token: '0x20c0000000000000000000000000000000000001',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The funder, amount, and transaction receipt.\n */\nexport async function distributeSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: distributeSync.Parameters<chain, account>,\n): Promise<distributeSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await distribute.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = distribute.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace distribute {\n export type Args = {\n /** The amount of tokens to distribute (must be > 0) */\n amount: bigint\n /** The TIP20 token address */\n token: Address\n }\n\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { amount, token, ...rest } = parameters\n const call = distribute.call({ amount, token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `distributeReward` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const hash = await client.sendTransaction({\n * calls: [actions.reward.distribute.call({\n * amount: 100000000000000000000n,\n * token: '0x20c0000000000000000000000000000000000001',\n * })],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { amount, token } = args\n return defineCall({\n address: token,\n abi: Abis.tip20,\n args: [amount],\n functionName: 'distributeReward',\n })\n }\n\n /**\n * Extracts the `RewardDistributed` event from logs.\n *\n * @param logs - The logs.\n * @returns The `RewardDistributed` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'RewardDistributed',\n strict: true,\n })\n if (!log) throw new Error('`RewardDistributed` event not found.')\n return log\n }\n}\n\nexport declare namespace distributeSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & distribute.Args\n\n export type ReturnValue = {\n /** The amount distributed */\n amount: bigint\n /** The address that funded the distribution */\n funder: Address\n /** The transaction receipt */\n receipt: Awaited<ReturnType<typeof writeContractSync>>\n }\n\n export type ErrorType = distribute.ErrorType\n}\n\n/**\n * Gets the global reward per token value.\n *\n * Returns the current global reward per token value scaled by `ACC_PRECISION` (1e18).\n * This value increases each time rewards are distributed.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const rewardPerToken = await Actions.reward.getGlobalRewardPerToken(client, {\n * token: '0x20c0000000000000000000000000000000000001',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The global reward per token (scaled by 1e18).\n */\nexport async function getGlobalRewardPerToken<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getGlobalRewardPerToken.Parameters,\n): Promise<getGlobalRewardPerToken.ReturnValue> {\n return readContract(client, {\n ...parameters,\n ...getGlobalRewardPerToken.call(parameters),\n })\n}\n\nexport namespace getGlobalRewardPerToken {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** The TIP20 token address */\n token: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.tip20,\n 'globalRewardPerToken',\n never\n >\n\n /**\n * Defines a call to the `globalRewardPerToken` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token } = args\n return defineCall({\n address: token,\n abi: Abis.tip20,\n args: [],\n functionName: 'globalRewardPerToken',\n })\n }\n}\n\n/**\n * Calculates the pending claimable rewards for an account without modifying state.\n *\n * Returns the total pending claimable reward amount, including stored balance and newly accrued rewards.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const pending = await Actions.reward.getPendingRewards(client, {\n * token: '0x20c0000000000000000000000000000000000001',\n * account: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The total pending claimable reward amount.\n */\nexport async function getPendingRewards<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getPendingRewards.Parameters,\n): Promise<getPendingRewards.ReturnValue> {\n return readContract(client, {\n ...parameters,\n ...getPendingRewards.call(parameters),\n })\n}\n\nexport namespace getPendingRewards {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** The account address to query pending rewards for */\n account: Address\n /** The TIP20 token address */\n token: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.tip20,\n 'getPendingRewards',\n never\n >\n\n /**\n * Defines a call to the `getPendingRewards` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, token } = args\n return defineCall({\n address: token,\n abi: Abis.tip20,\n args: [account],\n functionName: 'getPendingRewards',\n })\n }\n}\n\n/**\n * Gets the reward information for a specific account.\n *\n * Returns the reward recipient address, reward per token value, and accumulated reward balance for the specified account.\n * This information includes:\n * - `rewardRecipient`: The address designated to receive rewards (zero address if opted out)\n * - `rewardPerToken`: The reward per token value for this account\n * - `rewardBalance`: The accumulated reward balance waiting to be claimed\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const info = await Actions.reward.getUserRewardInfo(client, {\n * token: '0x20c0000000000000000000000000000000000001',\n * account: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The user's reward information (recipient, rewardPerToken, rewardBalance).\n */\nexport async function getUserRewardInfo<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getUserRewardInfo.Parameters,\n): Promise<getUserRewardInfo.ReturnValue> {\n return readContract(client, {\n ...parameters,\n ...getUserRewardInfo.call(parameters),\n })\n}\n\nexport namespace getUserRewardInfo {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** The account address to query reward info for */\n account: Address\n /** The TIP20 token address */\n token: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.tip20,\n 'userRewardInfo',\n never\n >\n\n /**\n * Defines a call to the `userRewardInfo` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, token } = args\n return defineCall({\n address: token,\n abi: Abis.tip20,\n args: [account],\n functionName: 'userRewardInfo',\n })\n }\n}\n\n/**\n * Sets or changes the reward recipient for a token holder.\n *\n * This function allows a token holder to designate who should receive their share of rewards:\n * - If `recipient` is the zero address, opts out from rewards distribution.\n * - Otherwise, opts in and sets `recipient` as the address that will receive accrued rewards.\n * - Can be called with `recipient == msg.sender` to receive rewards directly.\n * - Automatically distributes any accrued rewards to the current recipient before changing.\n *\n * TIP-403 Policy:\n * - Reverts with `PolicyForbids` if `recipient` is not the zero address and either the holder or recipient is not authorized to receive tokens under the token's transfer policy.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hash = await Actions.reward.setRecipient(client, {\n * recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\n * token: '0x20c0000000000000000000000000000000000001',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function setRecipient<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setRecipient.Parameters<chain, account>,\n): Promise<setRecipient.ReturnValue> {\n return setRecipient.inner(writeContract, client, parameters)\n}\n\n/**\n * Sets or changes the reward recipient for a token holder and waits for confirmation.\n *\n * This function allows a token holder to designate who should receive their share of rewards:\n * - If `recipient` is the zero address, opts out from rewards distribution.\n * - Otherwise, opts in and sets `recipient` as the address that will receive accrued rewards.\n * - Can be called with `recipient == msg.sender` to receive rewards directly.\n * - Automatically distributes any accrued rewards to the current recipient before changing.\n *\n * TIP-403 Policy:\n * - Reverts with `PolicyForbids` if `recipient` is not the zero address and either the holder or recipient is not authorized to receive tokens under the token's transfer policy.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const { holder, recipient, receipt } = await Actions.reward.setRecipientSync(client, {\n * recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\n * token: '0x20c0000000000000000000000000000000000001',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The holder, recipient, and transaction receipt.\n */\nexport async function setRecipientSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setRecipientSync.Parameters<chain, account>,\n): Promise<setRecipientSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await setRecipient.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = setRecipient.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace setRecipient {\n export type Args = {\n /** The reward recipient address (use zero address to opt out of rewards) */\n recipient: Address\n /** The TIP20 token address */\n token: Address\n }\n\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { recipient, token, ...rest } = parameters\n const call = setRecipient.call({ recipient, token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `setRewardRecipient` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const hash = await client.sendTransaction({\n * calls: [actions.reward.setRecipient.call({\n * recipient: '0xa5cc3c03994DB5b0d9A5eEdD10CabaB0813678AC',\n * token: '0x20c0000000000000000000000000000000000001',\n * })],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { recipient, token } = args\n return defineCall({\n address: token,\n abi: Abis.tip20,\n args: [recipient],\n functionName: 'setRewardRecipient',\n })\n }\n\n /**\n * Extracts the `RewardRecipientSet` event from logs.\n *\n * @param logs - The logs.\n * @returns The `RewardRecipientSet` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'RewardRecipientSet',\n strict: true,\n })\n if (!log) throw new Error('`RewardRecipientSet` event not found.')\n return log\n }\n}\n\nexport declare namespace setRecipientSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & setRecipient.Args\n\n export type ReturnValue = {\n /** The token holder address who set their reward recipient */\n holder: Address\n /** The transaction receipt */\n receipt: Awaited<ReturnType<typeof writeContractSync>>\n /** The reward recipient address (zero address indicates opt-out) */\n recipient: Address\n }\n\n export type ErrorType = setRecipient.ErrorType\n}\n\n/**\n * Watches for reward distributed events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = Actions.reward.watchRewardDistributed(client, {\n * token: '0x20c0000000000000000000000000000000000001',\n * onRewardDistributed: (args, log) => {\n * console.log('Reward distributed:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchRewardDistributed<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchRewardDistributed.Parameters,\n) {\n const { onRewardDistributed, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: token,\n abi: Abis.tip20,\n eventName: 'RewardDistributed',\n onLogs: (logs) => {\n for (const log of logs) onRewardDistributed(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchRewardDistributed {\n export type Args = GetEventArgs<\n typeof Abis.tip20,\n 'RewardDistributed',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20, 'RewardDistributed'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.tip20, 'RewardDistributed', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when rewards are distributed. */\n onRewardDistributed: (args: Args, log: Log) => void\n /** The TIP20 token address */\n token: Address\n }\n\n export type ReturnValue = WatchContractEventReturnType\n}\n\n/**\n * Watches for reward recipient set events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = Actions.reward.watchRewardRecipientSet(client, {\n * token: '0x20c0000000000000000000000000000000000001',\n * onRewardRecipientSet: (args, log) => {\n * console.log('Reward recipient set:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchRewardRecipientSet<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchRewardRecipientSet.Parameters,\n) {\n const { onRewardRecipientSet, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: token,\n abi: Abis.tip20,\n eventName: 'RewardRecipientSet',\n onLogs: (logs) => {\n for (const log of logs) onRewardRecipientSet(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchRewardRecipientSet {\n export type Args = GetEventArgs<\n typeof Abis.tip20,\n 'RewardRecipientSet',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20, 'RewardRecipientSet'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.tip20, 'RewardRecipientSet', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a reward recipient is set. */\n onRewardRecipientSet: (args: Args, log: Log) => void\n /** The TIP20 token address */\n token: Address\n }\n\n export type ReturnValue = WatchContractEventReturnType\n}\n","import type { Address } from 'abitype'\nimport * as Hex from 'ox/Hex'\nimport { TokenId, TokenRole } from 'ox/tempo'\nimport type { Account } from '../../accounts/types.js'\nimport { parseAccount } from '../../accounts/utils/parseAccount.js'\nimport { multicall } from '../../actions/public/multicall.js'\nimport type { ReadContractReturnType } from '../../actions/public/readContract.js'\nimport { readContract } from '../../actions/public/readContract.js'\nimport type {\n WatchContractEventParameters,\n WatchContractEventReturnType,\n} from '../../actions/public/watchContractEvent.js'\nimport { watchContractEvent } from '../../actions/public/watchContractEvent.js'\nimport { sendTransaction } from '../../actions/wallet/sendTransaction.js'\nimport {\n type SendTransactionSyncParameters,\n sendTransactionSync,\n} from '../../actions/wallet/sendTransactionSync.js'\nimport type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'\nimport { writeContract } from '../../actions/wallet/writeContract.js'\nimport { writeContractSync } from '../../actions/wallet/writeContractSync.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseErrorType } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { ExtractAbiItem, GetEventArgs } from '../../types/contract.js'\nimport type { Log, Log as viem_Log } from '../../types/log.js'\nimport type { Compute, OneOf, UnionOmit } from '../../types/utils.js'\nimport { encodeFunctionData } from '../../utils/abi/encodeFunctionData.js'\nimport { parseEventLogs } from '../../utils/abi/parseEventLogs.js'\nimport * as Abis from '../Abis.js'\nimport * as Addresses from '../Addresses.js'\nimport type {\n GetAccountParameter,\n ReadParameters,\n WriteParameters,\n} from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\nimport type { TransactionReceipt } from '../Transaction.js'\n\n/**\n * Approves a spender to transfer TIP20 tokens on behalf of the caller.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.approve(client, {\n * spender: '0x...',\n * amount: 100n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function approve<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: approve.Parameters<chain, account>,\n): Promise<approve.ReturnValue> {\n const { token, ...rest } = parameters\n return approve.inner(writeContract, client, parameters, { ...rest, token })\n}\n\nexport namespace approve {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokens to approve. */\n amount: bigint\n /** Address of the spender. */\n spender: Address\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: approve.Parameters<chain, account>,\n args: Args,\n ): Promise<ReturnType<action>> {\n const call = approve.call(args)\n return (await action(client, {\n ...parameters,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `approve` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.approve.call({\n * spender: '0x20c0...beef',\n * amount: 100n,\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { spender, amount, token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'approve',\n args: [spender, amount],\n })\n }\n\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'Approval',\n })\n if (!log) throw new Error('`Approval` event not found.')\n return log\n }\n}\n\n/**\n * Approves a spender to transfer TIP20 tokens on behalf of the caller.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.approveSync(client, {\n * spender: '0x...',\n * amount: 100n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function approveSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: approveSync.Parameters<chain, account>,\n): Promise<approveSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await approve.inner(\n writeContractSync,\n client,\n { ...parameters, throwOnReceiptRevert } as never,\n rest,\n )\n const { args } = approve.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace approveSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = approve.Parameters<chain, account>\n\n export type Args = approve.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip20,\n 'Approval',\n {\n IndexedOnly: false\n Required: true\n }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Burns TIP20 tokens from a blocked address.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.burnBlocked(client, {\n * from: '0x...',\n * amount: 100n,\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function burnBlocked<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: burnBlocked.Parameters<chain, account>,\n): Promise<burnBlocked.ReturnValue> {\n return burnBlocked.inner(writeContract, client, parameters)\n}\n\nexport namespace burnBlocked {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokens to burn. */\n amount: bigint\n /** Address to burn tokens from. */\n from: Address\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: burnBlocked.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { amount, from, token, ...rest } = parameters\n const call = burnBlocked.call({ amount, from, token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `burnBlocked` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.burnBlocked.call({\n * from: '0x20c0...beef',\n * amount: 100n,\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { from, amount, token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'burnBlocked',\n args: [from, amount],\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'BurnBlocked',\n })\n if (!log) throw new Error('`BurnBlocked` event not found.')\n return log\n }\n}\n\n/**\n * Burns TIP20 tokens from a blocked address.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.burnBlockedSync(client, {\n * from: '0x...',\n * amount: 100n,\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function burnBlockedSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: burnBlockedSync.Parameters<chain, account>,\n): Promise<burnBlockedSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await burnBlocked.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = burnBlocked.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace burnBlockedSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = burnBlocked.Parameters<chain, account>\n\n export type Args = burnBlocked.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip20,\n 'BurnBlocked',\n {\n IndexedOnly: false\n Required: true\n }\n > & {\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Burns TIP20 tokens from the caller's balance.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.burn(client, {\n * amount: 100n,\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function burn<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: burn.Parameters<chain, account>,\n): Promise<burn.ReturnValue> {\n return burn.inner(writeContract, client, parameters)\n}\n\nexport namespace burn {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokens to burn. */\n amount: bigint\n /** Memo to include in the transfer. */\n memo?: Hex.Hex | undefined\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: burn.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { amount, memo, token, ...rest } = parameters\n const call = burn.call({ amount, memo, token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `burn` or `burnWithMemo` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.burn.call({\n * amount: 100n,\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { amount, memo, token } = args\n const callArgs = memo\n ? ({\n functionName: 'burnWithMemo',\n args: [amount, Hex.padLeft(memo, 32)],\n } as const)\n : ({\n functionName: 'burn',\n args: [amount],\n } as const)\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n ...callArgs,\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'Burn',\n })\n if (!log) throw new Error('`Burn` event not found.')\n return log\n }\n}\n\n/**\n * Burns TIP20 tokens from the caller's balance.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.burnSync(client, {\n * amount: 100n,\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function burnSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: burnSync.Parameters<chain, account>,\n): Promise<burnSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await burn.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = burn.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace burnSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = burn.Parameters<chain, account>\n\n export type Args = burn.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip20,\n 'Burn',\n {\n IndexedOnly: false\n Required: true\n }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Changes the transfer policy ID for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.changeTransferPolicy(client, {\n * token: '0x...',\n * policyId: 1n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function changeTransferPolicy<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: changeTransferPolicy.Parameters<chain, account>,\n): Promise<changeTransferPolicy.ReturnValue> {\n return changeTransferPolicy.inner(writeContract, client, parameters)\n}\n\nexport namespace changeTransferPolicy {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** New transfer policy ID. */\n policyId: bigint\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: changeTransferPolicy.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { policyId, token, ...rest } = parameters\n const call = changeTransferPolicy.call({ policyId, token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `changeTransferPolicyId` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.changeTransferPolicy.call({\n * token: '0x20c0...babe',\n * policyId: 1n,\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, policyId } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'changeTransferPolicyId',\n args: [policyId],\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'TransferPolicyUpdate',\n })\n if (!log) throw new Error('`TransferPolicyUpdate` event not found.')\n return log\n }\n}\n\n/**\n * Changes the transfer policy ID for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.changeTransferPolicySync(client, {\n * token: '0x...',\n * policyId: 1n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function changeTransferPolicySync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: changeTransferPolicySync.Parameters<chain, account>,\n): Promise<changeTransferPolicySync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await changeTransferPolicy.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = changeTransferPolicy.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace changeTransferPolicySync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = changeTransferPolicy.Parameters<chain, account>\n\n export type Args = changeTransferPolicy.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip20,\n 'TransferPolicyUpdate',\n {\n IndexedOnly: false\n Required: true\n }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Creates a new TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.create(client, {\n * name: 'My Token',\n * symbol: 'MTK',\n * currency: 'USD',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function create<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: create.Parameters<chain, account>,\n): Promise<create.ReturnValue> {\n return create.inner(writeContract, client, parameters)\n}\n\nexport namespace create {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> &\n Omit<Args, 'admin'> &\n (account extends Account\n ? { admin?: Account | Address | undefined }\n : { admin: Account | Address })\n\n export type Args = {\n /** Admin address. */\n admin: Address\n /** Currency (e.g. \"USD\"). */\n currency: string\n /** Token name. */\n name: string\n /** Quote token. */\n quoteToken?: TokenId.TokenIdOrAddress | undefined\n /** Unique salt. @default Hex.random(32) */\n salt?: Hex.Hex | undefined\n /** Token symbol. */\n symbol: string\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: any,\n ): Promise<ReturnType<action>> {\n const {\n account = client.account,\n admin: admin_ = client.account,\n chain = client.chain,\n ...rest\n } = parameters\n const admin = admin_ ? parseAccount(admin_) : undefined\n if (!admin) throw new Error('admin is required.')\n\n const call = create.call({ ...rest, admin: admin.address })\n\n return (await action(\n client as never,\n {\n ...parameters,\n account,\n chain,\n ...call,\n } as never,\n )) as never\n }\n\n /**\n * Defines a call to the `createToken` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.create.call({\n * name: 'My Token',\n * symbol: 'MTK',\n * currency: 'USD',\n * admin: '0xfeed...fede',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const {\n name,\n symbol,\n currency,\n quoteToken = Addresses.pathUsd,\n admin,\n salt = Hex.random(32),\n } = args\n return defineCall({\n address: Addresses.tip20Factory,\n abi: Abis.tip20Factory,\n args: [\n name,\n symbol,\n currency,\n TokenId.toAddress(quoteToken),\n admin,\n salt,\n ],\n functionName: 'createToken',\n })\n }\n\n /**\n * Extracts the `TokenCreated` event from logs.\n *\n * @param logs - The logs.\n * @returns The `TokenCreated` event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20Factory,\n logs,\n eventName: 'TokenCreated',\n strict: true,\n })\n if (!log) throw new Error('`TokenCreated` event not found.')\n return log\n }\n}\n\n/**\n * Creates a new TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.createSync(client, {\n * name: 'My Token',\n * symbol: 'MTK',\n * currency: 'USD',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function createSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: createSync.Parameters<chain, account>,\n): Promise<createSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await create.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n\n const { args } = create.extractEvent(receipt.logs)\n const tokenId = TokenId.fromAddress(args.token)\n\n return {\n ...args,\n receipt,\n tokenId,\n } as never\n}\n\nexport namespace createSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = create.Parameters<chain, account>\n\n export type Args = create.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip20Factory,\n 'TokenCreated',\n { IndexedOnly: false; Required: true }\n > & {\n /** Token ID. */\n tokenId: TokenId.TokenId\n /** Transaction receipt. */\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Gets TIP20 token allowance.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const allowance = await Actions.token.getAllowance(client, {\n * spender: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The token allowance.\n */\nexport async function getAllowance<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getAllowance.Parameters<account>,\n): Promise<getAllowance.ReturnValue> {\n const { account = client.account } = parameters\n const address = account ? parseAccount(account).address : undefined\n if (!address) throw new Error('account is required.')\n return readContract(client, {\n ...parameters,\n ...getAllowance.call({ ...parameters, account: address }),\n })\n}\n\nexport namespace getAllowance {\n export type Parameters<\n account extends Account | undefined = Account | undefined,\n > = ReadParameters & GetAccountParameter<account> & Omit<Args, 'account'> & {}\n\n export type Args = {\n /** Account address. */\n account: Address\n /** Address of the spender. */\n spender: Address\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.tip20,\n 'allowance',\n never\n >\n\n /**\n * Defines a call to the `allowance` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, spender, token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'allowance',\n args: [account, spender],\n })\n }\n}\n\n/**\n * Gets TIP20 token balance for an address.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const balance = await Actions.token.getBalance(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The token balance.\n */\nexport async function getBalance<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getBalance.Parameters<account>,\n): Promise<getBalance.ReturnValue> {\n const { account = client.account, ...rest } = parameters\n const address = account ? parseAccount(account).address : undefined\n if (!address) throw new Error('account is required.')\n return readContract(client, {\n ...rest,\n ...getBalance.call({ account: address, ...rest }),\n })\n}\n\nexport namespace getBalance {\n export type Parameters<\n account extends Account | undefined = Account | undefined,\n > = ReadParameters & GetAccountParameter<account> & Omit<Args, 'account'>\n\n export type Args = {\n /** Account address. */\n account: Address\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.tip20,\n 'balanceOf',\n never\n >\n\n /**\n * Defines a call to the `balanceOf` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'balanceOf',\n args: [account],\n })\n }\n}\n\n/**\n * Gets TIP20 token metadata including name, symbol, currency, decimals, and total supply.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const metadata = await Actions.token.getMetadata(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The token metadata.\n */\nexport async function getMetadata<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getMetadata.Parameters,\n): Promise<getMetadata.ReturnValue> {\n const { token, ...rest } = parameters\n const address = TokenId.toAddress(token)\n const abi = Abis.tip20\n\n if (TokenId.from(token) === TokenId.fromAddress(Addresses.pathUsd))\n return multicall(client, {\n ...rest,\n contracts: [\n {\n address,\n abi,\n functionName: 'currency',\n },\n {\n address,\n abi,\n functionName: 'decimals',\n },\n {\n address,\n abi,\n functionName: 'name',\n },\n {\n address,\n abi,\n functionName: 'symbol',\n },\n {\n address,\n abi,\n functionName: 'totalSupply',\n },\n ] as const,\n allowFailure: false,\n deployless: true,\n }).then(([currency, decimals, name, symbol, totalSupply]) => ({\n name,\n symbol,\n currency,\n decimals,\n totalSupply,\n }))\n\n return multicall(client, {\n ...rest,\n contracts: [\n {\n address,\n abi,\n functionName: 'currency',\n },\n {\n address,\n abi,\n functionName: 'decimals',\n },\n {\n address,\n abi,\n functionName: 'quoteToken',\n },\n {\n address,\n abi,\n functionName: 'name',\n },\n {\n address,\n abi,\n functionName: 'paused',\n },\n {\n address,\n abi,\n functionName: 'supplyCap',\n },\n {\n address,\n abi,\n functionName: 'symbol',\n },\n {\n address,\n abi,\n functionName: 'totalSupply',\n },\n {\n address,\n abi,\n functionName: 'transferPolicyId',\n },\n ] as const,\n allowFailure: false,\n deployless: true,\n }).then(\n ([\n currency,\n decimals,\n quoteToken,\n name,\n paused,\n supplyCap,\n symbol,\n totalSupply,\n transferPolicyId,\n ]) => ({\n name,\n symbol,\n currency,\n decimals,\n quoteToken,\n totalSupply,\n paused,\n supplyCap,\n transferPolicyId,\n }),\n )\n}\n\nexport declare namespace getMetadata {\n export type Parameters = {\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = Compute<{\n /**\n * Currency (e.g. \"USD\").\n */\n currency: string\n /**\n * Decimals of the token.\n */\n decimals: number\n /**\n * Quote token.\n *\n * Returns `undefined` for the default quote token (`0x20c...0000`).\n */\n quoteToken?: Address | undefined\n /**\n * Name of the token.\n */\n name: string\n /**\n * Whether the token is paused.\n *\n * Returns `undefined` for the default quote token (`0x20c...0000`).\n */\n paused?: boolean | undefined\n /**\n * Supply cap.\n *\n * Returns `undefined` for the default quote token (`0x20c...0000`).\n */\n supplyCap?: bigint | undefined\n /**\n * Symbol of the token.\n */\n symbol: string\n /**\n * Total supply of the token.\n */\n totalSupply: bigint\n /**\n * Transfer policy ID.\n * 0=\"always-reject\", 1=\"always-allow\", >2=custom policy\n *\n * Returns `undefined` for the default quote token (`0x20c...0000`).\n */\n transferPolicyId?: bigint | undefined\n }>\n}\n\n/**\n * Gets the admin role for a specific role in a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const adminRole = await Actions.token.getRoleAdmin(client, {\n * role: 'issuer',\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The admin role hash.\n */\nexport async function getRoleAdmin<chain extends Chain | undefined>(\n client: Client<Transport, chain>,\n parameters: getRoleAdmin.Parameters,\n): Promise<getRoleAdmin.ReturnValue> {\n return readContract(client, {\n ...parameters,\n ...getRoleAdmin.call(parameters),\n })\n}\n\nexport namespace getRoleAdmin {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Role to get admin for. */\n role: TokenRole.TokenRole\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.tip20,\n 'getRoleAdmin',\n never\n >\n\n /**\n * Defines a call to the `getRoleAdmin` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { role, token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'getRoleAdmin',\n args: [TokenRole.serialize(role)],\n })\n }\n}\n\n/**\n * Checks if an account has a specific role for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const hasRole = await Actions.token.hasRole(client, {\n * account: '0x...',\n * role: 'issuer',\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns Whether the account has the role.\n */\nexport async function hasRole<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: hasRole.Parameters<account>,\n): Promise<hasRole.ReturnValue> {\n const { account = client.account } = parameters\n const address = account ? parseAccount(account).address : undefined\n if (!address) throw new Error('account is required.')\n return readContract(client, {\n ...parameters,\n ...hasRole.call({ ...parameters, account: address }),\n })\n}\n\nexport namespace hasRole {\n export type Parameters<\n account extends Account | undefined = Account | undefined,\n > = ReadParameters & Omit<Args, 'account'> & GetAccountParameter<account>\n\n export type Args = {\n /** Account address to check. */\n account: Address\n /** Role to check. */\n role: TokenRole.TokenRole\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.tip20,\n 'hasRole',\n never\n >\n\n /**\n * Defines a call to the `hasRole` function.\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { account, role, token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'hasRole',\n args: [account, TokenRole.serialize(role)],\n })\n }\n}\n\n/**\n * Grants a role for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.grantRoles(client, {\n * token: '0x...',\n * to: '0x...',\n * roles: ['issuer'],\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function grantRoles<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: grantRoles.Parameters<chain, account>,\n): Promise<grantRoles.ReturnValue> {\n return grantRoles.inner(sendTransaction, client, parameters)\n}\n\nexport namespace grantRoles {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> &\n Omit<Args, 'role'> & {\n /** Role to grant. */\n roles: readonly TokenRole.TokenRole[]\n }\n\n export type Args = {\n /** Role to grant. */\n role: TokenRole.TokenRole\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n /** Address to grant the role to. */\n to: Address\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof sendTransaction | typeof sendTransactionSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: grantRoles.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n return (await action(client, {\n ...parameters,\n calls: parameters.roles.map((role) => {\n const call = grantRoles.call({ ...parameters, role })\n return {\n ...call,\n data: encodeFunctionData(call),\n }\n }),\n } as never)) as never\n }\n\n /**\n * Defines a call to the `grantRole` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.grantRoles.call({\n * token: '0x20c0...babe',\n * to: '0x20c0...beef',\n * role: 'issuer',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, to, role } = args\n const roleHash = TokenRole.serialize(role)\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'grantRole',\n args: [roleHash, to],\n })\n }\n\n /**\n * Extracts the events from the logs.\n *\n * @param logs - Logs.\n * @returns The events.\n */\n export function extractEvents(logs: Log[]) {\n const events = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'RoleMembershipUpdated',\n })\n if (events.length === 0)\n throw new Error('`RoleMembershipUpdated` events not found.')\n return events\n }\n}\n\n/**\n * Grants a role for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.grantRolesSync(client, {\n * token: '0x...',\n * to: '0x...',\n * roles: ['issuer'],\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function grantRolesSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: grantRolesSync.Parameters<chain, account>,\n): Promise<grantRolesSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await grantRoles.inner(sendTransactionSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const events = grantRoles.extractEvents(receipt.logs)\n const value = events.map((event) => event.args)\n return {\n receipt,\n value,\n }\n}\n\nexport namespace grantRolesSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = grantRoles.Parameters<chain, account>\n\n export type Args = grantRoles.Args\n\n export type ReturnValue = {\n receipt: TransactionReceipt\n value: readonly GetEventArgs<\n typeof Abis.tip20,\n 'RoleMembershipUpdated',\n { IndexedOnly: false; Required: true }\n >[]\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Mints TIP20 tokens to an address.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.mint(client, {\n * to: '0x...',\n * amount: 100n,\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function mint<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: mint.Parameters<chain, account>,\n): Promise<mint.ReturnValue> {\n return mint.inner(writeContract, client, parameters)\n}\n\nexport namespace mint {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokens to mint. */\n amount: bigint\n /** Memo to include in the mint. */\n memo?: Hex.Hex | undefined\n /** Address to mint tokens to. */\n to: Address\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: any,\n ): Promise<ReturnType<action>> {\n const call = mint.call(parameters)\n return (await action(client, {\n ...parameters,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `mint` or `mintWithMemo` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.mint.call({\n * to: '0x20c0...beef',\n * amount: 100n,\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { to, amount, memo, token } = args\n const callArgs = memo\n ? ({\n functionName: 'mintWithMemo',\n args: [to, amount, Hex.padLeft(memo, 32)],\n } as const)\n : ({\n functionName: 'mint',\n args: [to, amount],\n } as const)\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n ...callArgs,\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'Mint',\n })\n if (!log) throw new Error('`Mint` event not found.')\n return log\n }\n}\n\n/**\n * Mints TIP20 tokens to an address.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.mintSync(client, {\n * to: '0x...',\n * amount: 100n,\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function mintSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: mintSync.Parameters<chain, account>,\n): Promise<mintSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await mint.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = mint.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace mintSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = mint.Parameters<chain, account>\n\n export type Args = mint.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip20,\n 'Mint',\n {\n IndexedOnly: false\n Required: true\n }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Pauses a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.pause(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function pause<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: pause.Parameters<chain, account>,\n): Promise<pause.ReturnValue> {\n return pause.inner(writeContract, client, parameters)\n}\n\nexport namespace pause {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: pause.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { token, ...rest } = parameters\n const call = pause.call({ token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `pause` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.pause.call({\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'pause',\n args: [],\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'PauseStateUpdate',\n })\n if (!log) throw new Error('`PauseStateUpdate` event not found.')\n return log\n }\n}\n\n/**\n * Pauses a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.pauseSync(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function pauseSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: pauseSync.Parameters<chain, account>,\n): Promise<pauseSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await pause.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = pause.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n }\n}\n\nexport namespace pauseSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = pause.Parameters<chain, account>\n\n export type Args = pause.Args\n\n export type ReturnValue = GetEventArgs<\n typeof Abis.tip20,\n 'PauseStateUpdate',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Renounces a role for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.renounceRoles(client, {\n * token: '0x...',\n * roles: ['issuer'],\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function renounceRoles<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: renounceRoles.Parameters<chain, account>,\n): Promise<renounceRoles.ReturnValue> {\n return renounceRoles.inner(sendTransaction, client, parameters)\n}\n\nexport namespace renounceRoles {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> &\n Omit<Args, 'role'> & {\n /** Roles to renounce. */\n roles: readonly TokenRole.TokenRole[]\n }\n\n export type Args = {\n /** Role to renounce. */\n role: TokenRole.TokenRole\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof sendTransaction | typeof sendTransactionSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: renounceRoles.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n return (await action(client, {\n ...parameters,\n calls: parameters.roles.map((role) => {\n const call = renounceRoles.call({ ...parameters, role })\n return {\n ...call,\n data: encodeFunctionData(call),\n }\n }),\n } as never)) as never\n }\n\n /**\n * Defines a call to the `renounceRole` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.renounceRoles.call({\n * token: '0x20c0...babe',\n * role: 'issuer',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, role } = args\n const roleHash = TokenRole.serialize(role)\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'renounceRole',\n args: [roleHash],\n })\n }\n\n /**\n * Extracts the events from the logs.\n *\n * @param logs - Logs.\n * @returns The events.\n */\n export function extractEvents(logs: Log[]) {\n const events = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'RoleMembershipUpdated',\n })\n if (events.length === 0)\n throw new Error('`RoleMembershipUpdated` events not found.')\n return events\n }\n}\n\n/**\n * Renounces a role for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.renounceRolesSync(client, {\n * token: '0x...',\n * roles: ['issuer'],\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function renounceRolesSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: renounceRolesSync.Parameters<chain, account>,\n): Promise<renounceRolesSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await renounceRoles.inner(sendTransactionSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const events = renounceRoles.extractEvents(receipt.logs)\n const value = events.map((event) => event.args)\n return {\n receipt,\n value,\n }\n}\n\nexport namespace renounceRolesSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = renounceRoles.Parameters<chain, account>\n\n export type Args = renounceRoles.Args\n\n export type ReturnValue = {\n receipt: TransactionReceipt\n value: readonly GetEventArgs<\n typeof Abis.tip20,\n 'RoleMembershipUpdated',\n { IndexedOnly: false; Required: true }\n >[]\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Revokes a role for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.revokeRoles(client, {\n * token: '0x...',\n * from: '0x...',\n * roles: ['issuer'],\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function revokeRoles<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: revokeRoles.Parameters<chain, account>,\n): Promise<revokeRoles.ReturnValue> {\n return revokeRoles.inner(sendTransaction, client, parameters)\n}\n\nexport namespace revokeRoles {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = SendTransactionSyncParameters<chain, account> &\n Omit<Args, 'role'> & {\n /** Role to revoke. */\n roles: readonly TokenRole.TokenRole[]\n }\n\n export type Args = {\n /** Address to revoke the role from. */\n from: Address\n /** Role to revoke. */\n role: TokenRole.TokenRole\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof sendTransaction | typeof sendTransactionSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: revokeRoles.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n return (await action(client, {\n ...parameters,\n calls: parameters.roles.map((role) => {\n const call = revokeRoles.call({ ...parameters, role })\n return {\n ...call,\n data: encodeFunctionData(call),\n }\n }),\n } as never)) as never\n }\n\n /**\n * Defines a call to the `revokeRole` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.revokeRoles.call({\n * token: '0x20c0...babe',\n * from: '0x20c0...beef',\n * role: 'issuer',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, from, role } = args\n const roleHash = TokenRole.serialize(role)\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'revokeRole',\n args: [roleHash, from],\n })\n }\n\n /**\n * Extracts the events from the logs.\n *\n * @param logs - Logs.\n * @returns The events.\n */\n export function extractEvents(logs: Log[]) {\n const events = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'RoleMembershipUpdated',\n })\n if (events.length === 0)\n throw new Error('`RoleMembershipUpdated` events not found.')\n return events\n }\n}\n\n/**\n * Revokes a role for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.revokeRolesSync(client, {\n * token: '0x...',\n * from: '0x...',\n * roles: ['issuer'],\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function revokeRolesSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: revokeRolesSync.Parameters<chain, account>,\n): Promise<revokeRolesSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await revokeRoles.inner(sendTransactionSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const events = revokeRoles.extractEvents(receipt.logs)\n const value = events.map((event) => event.args)\n return {\n receipt,\n value,\n }\n}\n\nexport namespace revokeRolesSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = revokeRoles.Parameters<chain, account>\n\n export type Args = revokeRoles.Args\n\n export type ReturnValue = {\n receipt: TransactionReceipt\n value: readonly GetEventArgs<\n typeof Abis.tip20,\n 'RoleMembershipUpdated',\n { IndexedOnly: false; Required: true }\n >[]\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Sets the supply cap for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.setSupplyCap(client, {\n * token: '0x...',\n * supplyCap: 1000000n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function setSupplyCap<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setSupplyCap.Parameters<chain, account>,\n): Promise<setSupplyCap.ReturnValue> {\n return setSupplyCap.inner(writeContract, client, parameters)\n}\n\nexport namespace setSupplyCap {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** New supply cap. */\n supplyCap: bigint\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: setSupplyCap.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { supplyCap, token, ...rest } = parameters\n const call = setSupplyCap.call({ supplyCap, token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `setSupplyCap` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.setSupplyCap.call({\n * token: '0x20c0...babe',\n * supplyCap: 1000000n,\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, supplyCap } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'setSupplyCap',\n args: [supplyCap],\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'SupplyCapUpdate',\n })\n if (!log) throw new Error('`SupplyCapUpdate` event not found.')\n return log\n }\n}\n\n/**\n * Sets the supply cap for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.setSupplyCapSync(client, {\n * token: '0x...',\n * supplyCap: 1000000n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function setSupplyCapSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setSupplyCapSync.Parameters<chain, account>,\n): Promise<setSupplyCapSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await setSupplyCap.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = setSupplyCap.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace setSupplyCapSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = setSupplyCap.Parameters<chain, account>\n\n export type Args = setSupplyCap.Args\n\n export type ReturnValue = GetEventArgs<\n typeof Abis.tip20,\n 'SupplyCapUpdate',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Sets the admin role for a specific role in a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.setRoleAdmin(client, {\n * token: '0x...',\n * role: 'issuer',\n * adminRole: 'admin',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function setRoleAdmin<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setRoleAdmin.Parameters<chain, account>,\n): Promise<setRoleAdmin.ReturnValue> {\n return setRoleAdmin.inner(writeContract, client, parameters)\n}\n\nexport namespace setRoleAdmin {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** New admin role. */\n adminRole: TokenRole.TokenRole\n /** Role to set admin for. */\n role: TokenRole.TokenRole\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: setRoleAdmin.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { adminRole, role, token, ...rest } = parameters\n const call = setRoleAdmin.call({ adminRole, role, token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `setRoleAdmin` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.setRoleAdmin.call({\n * token: '0x20c0...babe',\n * role: 'issuer',\n * adminRole: 'admin',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, role, adminRole } = args\n const roleHash = TokenRole.serialize(role)\n const adminRoleHash = TokenRole.serialize(adminRole)\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'setRoleAdmin',\n args: [roleHash, adminRoleHash],\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'RoleAdminUpdated',\n })\n if (!log) throw new Error('`RoleAdminUpdated` event not found.')\n return log\n }\n}\n\n/**\n * Sets the admin role for a specific role in a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.setRoleAdminSync(client, {\n * token: '0x...',\n * role: 'issuer',\n * adminRole: 'admin',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function setRoleAdminSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setRoleAdminSync.Parameters<chain, account>,\n): Promise<setRoleAdminSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await setRoleAdmin.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = setRoleAdmin.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace setRoleAdminSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = setRoleAdmin.Parameters<chain, account>\n\n export type Args = setRoleAdmin.Args\n\n export type ReturnValue = GetEventArgs<\n typeof Abis.tip20,\n 'RoleAdminUpdated',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Transfers TIP20 tokens to another address.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.transfer(client, {\n * to: '0x...',\n * amount: 100n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function transfer<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: transfer.Parameters<chain, account>,\n): Promise<transfer.ReturnValue> {\n return transfer.inner(writeContract, client, parameters)\n}\n\nexport namespace transfer {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Amount of tokens to transfer. */\n amount: bigint\n /** Address to transfer tokens from. */\n from?: Address | undefined\n /** Memo to include in the transfer. */\n memo?: Hex.Hex | undefined\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n /** Address to transfer tokens to. */\n to: Address\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: transfer.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { amount, from, memo, token, to, ...rest } = parameters\n const call = transfer.call({ amount, from, memo, token, to })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `transfer`, `transferFrom`, `transferWithMemo`, or `transferFromWithMemo` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.transfer.call({\n * to: '0x20c0...beef',\n * amount: 100n,\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { amount, from, memo, token, to } = args\n const callArgs = (() => {\n if (memo && from)\n return {\n functionName: 'transferFromWithMemo',\n args: [from, to, amount, Hex.padLeft(memo, 32)],\n } as const\n if (memo)\n return {\n functionName: 'transferWithMemo',\n args: [to, amount, Hex.padLeft(memo, 32)],\n } as const\n if (from)\n return {\n functionName: 'transferFrom',\n args: [from, to, amount],\n } as const\n return {\n functionName: 'transfer',\n args: [to, amount],\n } as const\n })()\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n ...callArgs,\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'Transfer',\n })\n if (!log) throw new Error('`Transfer` event not found.')\n return log\n }\n}\n\n/**\n * Transfers TIP20 tokens to another address.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.transferSync(client, {\n * to: '0x...',\n * amount: 100n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function transferSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: transferSync.Parameters<chain, account>,\n): Promise<transferSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await transfer.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = transfer.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace transferSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = transfer.Parameters<chain, account>\n\n export type Args = transfer.Args\n\n export type ReturnValue = GetEventArgs<\n typeof Abis.tip20,\n 'Transfer',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Unpauses a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.unpause(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function unpause<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: unpause.Parameters<chain, account>,\n): Promise<unpause.ReturnValue> {\n return unpause.inner(writeContract, client, parameters)\n}\n\nexport namespace unpause {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: unpause.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { token, ...rest } = parameters\n const call = unpause.call({ token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `unpause` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.unpause.call({\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'unpause',\n args: [],\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'PauseStateUpdate',\n })\n if (!log) throw new Error('`PauseStateUpdate` event not found.')\n return log\n }\n}\n\n/**\n * Unpauses a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.unpauseSync(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function unpauseSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: unpauseSync.Parameters<chain, account>,\n): Promise<unpauseSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await unpause.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n const { args } = unpause.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace unpauseSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = unpause.Parameters<chain, account>\n\n export type Args = unpause.Args\n\n export type ReturnValue = GetEventArgs<\n typeof Abis.tip20,\n 'PauseStateUpdate',\n { IndexedOnly: false; Required: true }\n > & {\n receipt: TransactionReceipt\n }\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Updates the quote token for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.prepareUpdateQuoteToken(client, {\n * token: '0x...',\n * quoteToken: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function prepareUpdateQuoteToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: prepareUpdateQuoteToken.Parameters<chain, account>,\n): Promise<prepareUpdateQuoteToken.ReturnValue> {\n return prepareUpdateQuoteToken.inner(writeContract, client, parameters)\n}\n\nexport namespace prepareUpdateQuoteToken {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** New quote token address. */\n quoteToken: TokenId.TokenIdOrAddress\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: prepareUpdateQuoteToken.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { quoteToken, token, ...rest } = parameters\n const call = prepareUpdateQuoteToken.call({ quoteToken, token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `prepareUpdateQuoteToken` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.prepareUpdateQuoteToken.call({\n * token: '0x20c0...babe',\n * quoteToken: '0x20c0...cafe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token, quoteToken } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'setNextQuoteToken',\n args: [TokenId.toAddress(quoteToken)],\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'NextQuoteTokenSet',\n })\n if (!log) throw new Error('`NextQuoteTokenSet` event not found.')\n return log\n }\n}\n\n/**\n * Updates the quote token for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.prepareUpdateQuoteTokenSync(client, {\n * token: '0x...',\n * quoteToken: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function prepareUpdateQuoteTokenSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: prepareUpdateQuoteTokenSync.Parameters<chain, account>,\n): Promise<prepareUpdateQuoteTokenSync.ReturnValue> {\n const receipt = await prepareUpdateQuoteToken.inner(\n writeContractSync,\n client,\n parameters,\n )\n const { args } = prepareUpdateQuoteToken.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace prepareUpdateQuoteTokenSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = prepareUpdateQuoteToken.Parameters<chain, account>\n\n export type Args = prepareUpdateQuoteToken.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip20,\n 'NextQuoteTokenSet',\n {\n IndexedOnly: false\n Required: true\n }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Updates the quote token for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.updateQuoteToken(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function updateQuoteToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: updateQuoteToken.Parameters<chain, account>,\n): Promise<updateQuoteToken.ReturnValue> {\n return updateQuoteToken.inner(writeContract, client, parameters)\n}\n\nexport namespace updateQuoteToken {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: updateQuoteToken.Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { token, ...rest } = parameters\n const call = updateQuoteToken.call({ token })\n return (await action(client, {\n ...rest,\n ...call,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `updateQuoteToken` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * actions.token.updateQuoteToken.call({\n * token: '0x20c0...babe',\n * }),\n * ]\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { token } = args\n return defineCall({\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n functionName: 'completeQuoteTokenUpdate',\n args: [],\n })\n }\n\n /**\n * Extracts the event from the logs.\n *\n * @param logs - Logs.\n * @returns The event.\n */\n export function extractEvent(logs: Log[]) {\n const [log] = parseEventLogs({\n abi: Abis.tip20,\n logs,\n eventName: 'QuoteTokenUpdate',\n })\n if (!log) throw new Error('`QuoteTokenUpdateCompleted` event not found.')\n return log\n }\n}\n\n/**\n * Updates the quote token for a TIP20 token.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const result = await Actions.token.updateQuoteTokenSync(client, {\n * token: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt and event data.\n */\nexport async function updateQuoteTokenSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: updateQuoteTokenSync.Parameters<chain, account>,\n): Promise<updateQuoteTokenSync.ReturnValue> {\n const receipt = await updateQuoteToken.inner(\n writeContractSync,\n client,\n parameters,\n )\n const { args } = updateQuoteToken.extractEvent(receipt.logs)\n return {\n ...args,\n receipt,\n } as never\n}\n\nexport namespace updateQuoteTokenSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = updateQuoteToken.Parameters<chain, account>\n\n export type Args = updateQuoteToken.Args\n\n export type ReturnValue = Compute<\n GetEventArgs<\n typeof Abis.tip20,\n 'QuoteTokenUpdate',\n {\n IndexedOnly: false\n Required: true\n }\n > & {\n receipt: TransactionReceipt\n }\n >\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n}\n\n/**\n * Watches for TIP20 token approval events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.token.watchApprove(client, {\n * onApproval: (args, log) => {\n * console.log('Approval:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchApprove<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchApprove.Parameters,\n) {\n const { onApproval, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n eventName: 'Approval',\n onLogs: (logs) => {\n for (const log of logs) onApproval(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchApprove {\n export type Args = GetEventArgs<\n typeof Abis.tip20,\n 'Approval',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20, 'Approval'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.tip20, 'Approval', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when tokens are approved. */\n onApproval: (args: Args, log: Log) => void\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n}\n\n/**\n * Watches for TIP20 token burn events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.token.watchBurn(client, {\n * onBurn: (args, log) => {\n * console.log('Burn:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchBurn<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>, parameters: watchBurn.Parameters) {\n const { onBurn, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n eventName: 'Burn',\n onLogs: (logs) => {\n for (const log of logs) onBurn(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchBurn {\n export type Args = GetEventArgs<\n typeof Abis.tip20,\n 'Burn',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20, 'Burn'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.tip20, 'Burn', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when tokens are burned. */\n onBurn: (args: Args, log: Log) => void\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n}\n\n/**\n * Watches for new TIP20 tokens created.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.token.watchCreate(client, {\n * onTokenCreated: (args, log) => {\n * console.log('Token created:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchCreate<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchCreate.Parameters,\n) {\n const { onTokenCreated, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: Addresses.tip20Factory,\n abi: Abis.tip20Factory,\n eventName: 'TokenCreated',\n onLogs: (logs) => {\n for (const log of logs) onTokenCreated(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchCreate {\n export type Args = GetEventArgs<\n typeof Abis.tip20Factory,\n 'TokenCreated',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20Factory, 'TokenCreated'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.tip20Factory,\n 'TokenCreated',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a new TIP20 token is created. */\n onTokenCreated: (args: Args, log: Log) => void\n }\n}\n\n/**\n * Watches for TIP20 token mint events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.token.watchMint(client, {\n * onMint: (args, log) => {\n * console.log('Mint:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchMint<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>, parameters: watchMint.Parameters) {\n const { onMint, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n eventName: 'Mint',\n onLogs: (logs) => {\n for (const log of logs) onMint(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchMint {\n export type Args = GetEventArgs<\n typeof Abis.tip20,\n 'Mint',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20, 'Mint'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.tip20, 'Mint', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when tokens are minted. */\n onMint: (args: Args, log: Log) => void\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n\n export type ReturnValue = WatchContractEventReturnType\n}\n\n/**\n * Watches for TIP20 token role admin updates.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.token.watchAdminRole(client, {\n * onRoleAdminUpdated: (args, log) => {\n * console.log('Role admin updated:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchAdminRole<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchAdminRole.Parameters,\n) {\n const { onRoleAdminUpdated, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n eventName: 'RoleAdminUpdated',\n onLogs: (logs) => {\n for (const log of logs) onRoleAdminUpdated(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchAdminRole {\n export type Args = GetEventArgs<\n typeof Abis.tip20,\n 'RoleAdminUpdated',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20, 'RoleAdminUpdated'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.tip20, 'RoleAdminUpdated', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a role admin is updated. */\n onRoleAdminUpdated: (args: Args, log: Log) => void\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n}\n\n/**\n * Watches for TIP20 token role membership updates.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.token.watchRole(client, {\n * onRoleUpdated: (args, log) => {\n * console.log('Role updated:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchRole<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(client: Client<Transport, chain, account>, parameters: watchRole.Parameters) {\n const { onRoleUpdated, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n eventName: 'RoleMembershipUpdated',\n onLogs: (logs) => {\n for (const log of logs) {\n const type = log.args.hasRole ? 'granted' : 'revoked'\n onRoleUpdated({ ...log.args, type }, log)\n }\n },\n strict: true,\n })\n}\n\nexport declare namespace watchRole {\n export type Args = GetEventArgs<\n typeof Abis.tip20,\n 'RoleMembershipUpdated',\n { IndexedOnly: false; Required: true }\n > & {\n /** Type of role update. */\n type: 'granted' | 'revoked'\n }\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20, 'RoleMembershipUpdated'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<\n typeof Abis.tip20,\n 'RoleMembershipUpdated',\n true\n >,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a role membership is updated. */\n onRoleUpdated: (args: Args, log: Log) => void\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n}\n\n/**\n * Watches for TIP20 token transfer events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.token.watchTransfer(client, {\n * onTransfer: (args, log) => {\n * console.log('Transfer:', args)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchTransfer<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchTransfer.Parameters,\n) {\n const { onTransfer, token, ...rest } = parameters\n return watchContractEvent(client, {\n ...rest,\n address: TokenId.toAddress(token),\n abi: Abis.tip20,\n eventName: 'Transfer',\n onLogs: (logs) => {\n for (const log of logs) onTransfer(log.args, log)\n },\n strict: true,\n })\n}\n\nexport declare namespace watchTransfer {\n export type Args = GetEventArgs<\n typeof Abis.tip20,\n 'Transfer',\n { IndexedOnly: false; Required: true }\n >\n\n export type Log = viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<typeof Abis.tip20, 'Transfer'>,\n true\n >\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.tip20, 'Transfer', true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when tokens are transferred. */\n onTransfer: (args: Args, log: Log) => void\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n}\n\n/**\n * Watches for TIP20 token quote token update events.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' })\n * transport: http(),\n * })\n *\n * const unwatch = actions.token.watchUpdateQuoteToken(client, {\n * onUpdateQuoteToken: (args, log) => {\n * if (args.completed)\n * console.log('quote token update completed:', args.newQuoteToken)\n * else\n * console.log('quote token update proposed:', args.newQuoteToken)\n * },\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns A function to unsubscribe from the event.\n */\nexport function watchUpdateQuoteToken<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: watchUpdateQuoteToken.Parameters,\n) {\n const { onUpdateQuoteToken, token, ...rest } = parameters\n const address = TokenId.toAddress(token)\n\n return watchContractEvent(client, {\n ...rest,\n address,\n abi: Abis.tip20,\n onLogs: (\n logs: viem_Log<\n bigint,\n number,\n false,\n ExtractAbiItem<\n typeof Abis.tip20,\n 'NextQuoteTokenSet' | 'QuoteTokenUpdate'\n >,\n true\n >[],\n ) => {\n for (const log of logs) {\n if (\n log.eventName !== 'NextQuoteTokenSet' &&\n log.eventName !== 'QuoteTokenUpdate'\n )\n continue\n\n onUpdateQuoteToken(\n {\n ...log.args,\n completed: log.eventName === 'QuoteTokenUpdate',\n },\n log,\n )\n }\n },\n strict: true,\n } as never)\n}\n\nexport declare namespace watchUpdateQuoteToken {\n export type Args = OneOf<\n | GetEventArgs<\n typeof Abis.tip20,\n 'NextQuoteTokenSet',\n { IndexedOnly: false; Required: true }\n >\n | GetEventArgs<\n typeof Abis.tip20,\n 'QuoteTokenUpdate',\n { IndexedOnly: false; Required: true }\n >\n > & {\n /** Whether the update has been completed. */\n completed: boolean\n }\n\n export type Log = viem_Log\n\n export type Parameters = UnionOmit<\n WatchContractEventParameters<typeof Abis.tip20, any, true>,\n 'abi' | 'address' | 'batch' | 'eventName' | 'onLogs' | 'strict'\n > & {\n /** Callback to invoke when a quote token update is proposed or completed. */\n onUpdateQuoteToken: (args: Args, log: Log) => void\n /** Address or ID of the TIP20 token. */\n token: TokenId.TokenIdOrAddress\n }\n}\n","import type { Address } from 'abitype'\nimport type { Hex } from 'ox/Hex'\nimport type { Account } from '../../accounts/types.js'\nimport type { ReadContractReturnType } from '../../actions/public/readContract.js'\nimport { readContract } from '../../actions/public/readContract.js'\nimport type { WriteContractReturnType } from '../../actions/wallet/writeContract.js'\nimport { writeContract } from '../../actions/wallet/writeContract.js'\nimport { writeContractSync } from '../../actions/wallet/writeContractSync.js'\nimport type { Client } from '../../clients/createClient.js'\nimport type { Transport } from '../../clients/transports/createTransport.js'\nimport type { BaseErrorType } from '../../errors/base.js'\nimport type { Chain } from '../../types/chain.js'\nimport type { TransactionReceipt } from '../../types/transaction.js'\nimport * as Abis from '../Abis.js'\nimport * as Addresses from '../Addresses.js'\nimport type { ReadParameters, WriteParameters } from '../internal/types.js'\nimport { defineCall } from '../internal/utils.js'\n\n/**\n * Adds a new validator (owner only).\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hash = await Actions.validator.add(client, {\n * newValidatorAddress: '0x...',\n * publicKey: '0x...',\n * active: true,\n * inboundAddress: '192.168.1.1:8080',\n * outboundAddress: '192.168.1.1:8080',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function add<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: add.Parameters<chain, account>,\n): Promise<add.ReturnValue> {\n return add.inner(writeContract, client, parameters)\n}\n\nexport namespace add {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** The address of the new validator. */\n newValidatorAddress: Address\n /** The validator's communication public key. */\n publicKey: Hex\n /** Whether the validator should be active. */\n active: boolean\n /** The validator's inbound address `<hostname|ip>:<port>` for incoming connections. */\n inboundAddress: string\n /** The validator's outbound IP address `<ip>:<port>` for firewall whitelisting (IP only, no hostnames). */\n outboundAddress: string\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const {\n newValidatorAddress,\n publicKey,\n active,\n inboundAddress,\n outboundAddress,\n ...rest\n } = parameters\n const callData = add.call({\n newValidatorAddress,\n publicKey,\n active,\n inboundAddress,\n outboundAddress,\n })\n return (await action(client, {\n ...rest,\n ...callData,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `addValidator` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.validator.add.call({\n * newValidatorAddress: '0x...',\n * publicKey: '0x...',\n * active: true,\n * inboundAddress: '192.168.1.1:8080',\n * outboundAddress: '192.168.1.1:8080',\n * }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const {\n newValidatorAddress,\n publicKey,\n active,\n inboundAddress,\n outboundAddress,\n } = args\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [\n newValidatorAddress,\n publicKey,\n active,\n inboundAddress,\n outboundAddress,\n ],\n functionName: 'addValidator',\n })\n }\n}\n\n/**\n * Adds a new validator (owner only) and waits for the transaction receipt.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const { receipt } = await Actions.validator.addSync(client, {\n * newValidatorAddress: '0x...',\n * publicKey: '0x...',\n * active: true,\n * inboundAddress: '192.168.1.1:8080',\n * outboundAddress: '192.168.1.1:8080',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt.\n */\nexport async function addSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: addSync.Parameters<chain, account>,\n): Promise<addSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await add.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n return { receipt }\n}\n\nexport namespace addSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = add.Parameters<chain, account>\n\n export type Args = add.Args\n\n export type ReturnValue = {\n receipt: TransactionReceipt\n }\n}\n\n/**\n * Changes the owner of the validator config precompile.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hash = await Actions.validator.changeOwner(client, {\n * newOwner: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function changeOwner<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: changeOwner.Parameters<chain, account>,\n): Promise<changeOwner.ReturnValue> {\n return changeOwner.inner(writeContract, client, parameters)\n}\n\nexport namespace changeOwner {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** The new owner address. */\n newOwner: Address\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { newOwner, ...rest } = parameters\n const callData = changeOwner.call({ newOwner })\n return (await action(client, {\n ...rest,\n ...callData,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `changeOwner` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.validator.changeOwner.call({\n * newOwner: '0x...',\n * }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { newOwner } = args\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [newOwner],\n functionName: 'changeOwner',\n })\n }\n}\n\n/**\n * Changes the owner and waits for the transaction receipt.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const { receipt } = await Actions.validator.changeOwnerSync(client, {\n * newOwner: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt.\n */\nexport async function changeOwnerSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: changeOwnerSync.Parameters<chain, account>,\n): Promise<changeOwnerSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await changeOwner.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n return { receipt }\n}\n\nexport namespace changeOwnerSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = changeOwner.Parameters<chain, account>\n\n export type Args = changeOwner.Args\n\n export type ReturnValue = {\n receipt: TransactionReceipt\n }\n}\n\n/**\n * Changes validator active status (owner only).\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hash = await Actions.validator.changeStatus(client, {\n * validator: '0x...',\n * active: false,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function changeStatus<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: changeStatus.Parameters<chain, account>,\n): Promise<changeStatus.ReturnValue> {\n return changeStatus.inner(writeContract, client, parameters)\n}\n\nexport namespace changeStatus {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** The validator address. */\n validator: Address\n /** Whether the validator should be active. */\n active: boolean\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { validator, active, ...rest } = parameters\n const callData = changeStatus.call({ validator, active })\n return (await action(client, {\n ...rest,\n ...callData,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `changeValidatorStatus` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.validator.changeStatus.call({\n * validator: '0x...',\n * active: false,\n * }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { validator, active } = args\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [validator, active],\n functionName: 'changeValidatorStatus',\n })\n }\n}\n\n/**\n * Changes validator active status and waits for the transaction receipt.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const { receipt } = await Actions.validator.changeStatusSync(client, {\n * validator: '0x...',\n * active: false,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt.\n */\nexport async function changeStatusSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: changeStatusSync.Parameters<chain, account>,\n): Promise<changeStatusSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await changeStatus.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n return { receipt }\n}\n\nexport namespace changeStatusSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = changeStatus.Parameters<chain, account>\n\n export type Args = changeStatus.Args\n\n export type ReturnValue = {\n receipt: TransactionReceipt\n }\n}\n\n/**\n * Gets the next epoch for a full DKG ceremony.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const epoch = await Actions.validator.getNextFullDkgCeremony(client)\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The epoch number for the next full DKG ceremony.\n */\nexport async function getNextFullDkgCeremony<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getNextFullDkgCeremony.Parameters = {},\n): Promise<getNextFullDkgCeremony.ReturnValue> {\n return readContract(client, {\n ...parameters,\n ...getNextFullDkgCeremony.call(),\n })\n}\n\nexport namespace getNextFullDkgCeremony {\n export type Parameters = ReadParameters\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.validator,\n 'getNextFullDkgCeremony',\n never\n >\n\n /**\n * Defines a call to the `getNextFullDkgCeremony` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`multicall`](https://viem.sh/docs/contract/multicall): execute multiple calls in parallel\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await client.multicall({\n * contracts: [Actions.validator.getNextFullDkgCeremony.call()],\n * })\n * ```\n *\n * @returns The call.\n */\n export function call() {\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [],\n functionName: 'getNextFullDkgCeremony',\n })\n }\n}\n\n/**\n * Gets the contract owner.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const owner = await Actions.validator.getOwner(client)\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The owner address.\n */\nexport async function getOwner<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getOwner.Parameters = {},\n): Promise<getOwner.ReturnValue> {\n return readContract(client, {\n ...parameters,\n ...getOwner.call(),\n })\n}\n\nexport namespace getOwner {\n export type Parameters = ReadParameters\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.validator,\n 'owner',\n never\n >\n\n /**\n * Defines a call to the `owner` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`multicall`](https://viem.sh/docs/contract/multicall): execute multiple calls in parallel\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await client.multicall({\n * contracts: [Actions.validator.getOwner.call()],\n * })\n * ```\n *\n * @returns The call.\n */\n export function call() {\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [],\n functionName: 'owner',\n })\n }\n}\n\n/**\n * Gets validator information by address.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const validator = await Actions.validator.get(client, {\n * validator: '0x...',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The validator information.\n */\nexport async function get<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: get.Parameters,\n): Promise<get.ReturnValue> {\n const { validator, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...get.call({ validator }),\n })\n}\n\nexport namespace get {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Validator address. */\n validator: Address\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.validator,\n 'validators',\n never\n >\n\n /**\n * Defines a call to the `validators` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`multicall`](https://viem.sh/docs/contract/multicall): execute multiple calls in parallel\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await client.multicall({\n * contracts: [\n * Actions.validator.get.call({ validator: '0x...' }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { validator } = args\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [validator],\n functionName: 'validators',\n })\n }\n}\n\n/**\n * Gets validator address by index.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const validatorAddress = await Actions.validator.getByIndex(client, {\n * index: 0n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The validator address at the given index.\n */\nexport async function getByIndex<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getByIndex.Parameters,\n): Promise<getByIndex.ReturnValue> {\n const { index, ...rest } = parameters\n return readContract(client, {\n ...rest,\n ...getByIndex.call({ index }),\n })\n}\n\nexport namespace getByIndex {\n export type Parameters = ReadParameters & Args\n\n export type Args = {\n /** Validator index. */\n index: bigint\n }\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.validator,\n 'validatorsArray',\n never\n >\n\n /**\n * Defines a call to the `validatorsArray` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`multicall`](https://viem.sh/docs/contract/multicall): execute multiple calls in parallel\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await client.multicall({\n * contracts: [\n * Actions.validator.getByIndex.call({ index: 0n }),\n * Actions.validator.getByIndex.call({ index: 1n }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { index } = args\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [index],\n functionName: 'validatorsArray',\n })\n }\n}\n\n/**\n * Gets the total number of validators.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const count = await Actions.validator.getCount(client)\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The total number of validators.\n */\nexport async function getCount<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: getCount.Parameters = {},\n): Promise<getCount.ReturnValue> {\n return readContract(client, {\n ...parameters,\n ...getCount.call(),\n })\n}\n\nexport namespace getCount {\n export type Parameters = ReadParameters\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.validator,\n 'validatorCount',\n never\n >\n\n /**\n * Defines a call to the `validatorCount` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`multicall`](https://viem.sh/docs/contract/multicall): execute multiple calls in parallel\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await client.multicall({\n * contracts: [Actions.validator.getCount.call()],\n * })\n * ```\n *\n * @returns The call.\n */\n export function call() {\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [],\n functionName: 'validatorCount',\n })\n }\n}\n\n/**\n * Gets the complete set of validators.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const validators = await Actions.validator.list(client)\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns Array of all validators with their information.\n */\nexport async function list<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: list.Parameters = {},\n): Promise<list.ReturnValue> {\n return readContract(client, {\n ...parameters,\n ...list.call(),\n })\n}\n\nexport namespace list {\n export type Parameters = ReadParameters\n\n export type ReturnValue = ReadContractReturnType<\n typeof Abis.validator,\n 'getValidators',\n never\n >\n\n /**\n * Defines a call to the `getValidators` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`multicall`](https://viem.sh/docs/contract/multicall): execute multiple calls in parallel\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const result = await client.multicall({\n * contracts: [Actions.validator.list.call()],\n * })\n * ```\n *\n * @returns The call.\n */\n export function call() {\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [],\n functionName: 'getValidators',\n })\n }\n}\n\n/**\n * Sets the next epoch for a full DKG ceremony.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hash = await Actions.validator.setNextFullDkgCeremony(client, {\n * epoch: 100n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function setNextFullDkgCeremony<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setNextFullDkgCeremony.Parameters<chain, account>,\n): Promise<setNextFullDkgCeremony.ReturnValue> {\n return setNextFullDkgCeremony.inner(writeContract, client, parameters)\n}\n\nexport namespace setNextFullDkgCeremony {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** The epoch number for the next full DKG ceremony. */\n epoch: bigint\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const { epoch, ...rest } = parameters\n const callData = setNextFullDkgCeremony.call({ epoch })\n return (await action(client, {\n ...rest,\n ...callData,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `setNextFullDkgCeremony` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.validator.setNextFullDkgCeremony.call({\n * epoch: 100n,\n * }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { epoch } = args\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [epoch],\n functionName: 'setNextFullDkgCeremony',\n })\n }\n}\n\n/**\n * Sets the next epoch for a full DKG ceremony and waits for the transaction receipt.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const { receipt } = await Actions.validator.setNextFullDkgCeremonySync(client, {\n * epoch: 100n,\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt.\n */\nexport async function setNextFullDkgCeremonySync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: setNextFullDkgCeremonySync.Parameters<chain, account>,\n): Promise<setNextFullDkgCeremonySync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await setNextFullDkgCeremony.inner(\n writeContractSync,\n client,\n {\n ...rest,\n throwOnReceiptRevert,\n } as never,\n )\n return { receipt }\n}\n\nexport namespace setNextFullDkgCeremonySync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = setNextFullDkgCeremony.Parameters<chain, account>\n\n export type Args = setNextFullDkgCeremony.Args\n\n export type ReturnValue = {\n receipt: TransactionReceipt\n }\n}\n\n/**\n * Updates validator information (only callable by the validator themselves).\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const hash = await Actions.validator.update(client, {\n * newValidatorAddress: '0x...',\n * publicKey: '0x...',\n * inboundAddress: '192.168.1.1:8080',\n * outboundAddress: '192.168.1.1:8080',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction hash.\n */\nexport async function update<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: update.Parameters<chain, account>,\n): Promise<update.ReturnValue> {\n return update.inner(writeContract, client, parameters)\n}\n\nexport namespace update {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = WriteParameters<chain, account> & Args\n\n export type Args = {\n /** The new address for this validator. */\n newValidatorAddress: Address\n /** The validator's new communication public key. */\n publicKey: Hex\n /** The validator's inbound address `<hostname|ip>:<port>` for incoming connections. */\n inboundAddress: string\n /** The validator's outbound IP address `<ip>:<port>` for firewall whitelisting (IP only, no hostnames). */\n outboundAddress: string\n }\n\n export type ReturnValue = WriteContractReturnType\n\n // TODO: exhaustive error type\n export type ErrorType = BaseErrorType\n\n /** @internal */\n export async function inner<\n action extends typeof writeContract | typeof writeContractSync,\n chain extends Chain | undefined,\n account extends Account | undefined,\n >(\n action: action,\n client: Client<Transport, chain, account>,\n parameters: Parameters<chain, account>,\n ): Promise<ReturnType<action>> {\n const {\n newValidatorAddress,\n publicKey,\n inboundAddress,\n outboundAddress,\n ...rest\n } = parameters\n const callData = update.call({\n newValidatorAddress,\n publicKey,\n inboundAddress,\n outboundAddress,\n })\n return (await action(client, {\n ...rest,\n ...callData,\n } as never)) as never\n }\n\n /**\n * Defines a call to the `updateValidator` function.\n *\n * Can be passed as a parameter to:\n * - [`estimateContractGas`](https://viem.sh/docs/contract/estimateContractGas): estimate the gas cost of the call\n * - [`simulateContract`](https://viem.sh/docs/contract/simulateContract): simulate the call\n * - [`sendCalls`](https://viem.sh/docs/actions/wallet/sendCalls): send multiple calls\n *\n * @example\n * ```ts\n * import { createClient, http, walletActions } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n *\n * const client = createClient({\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * }).extend(walletActions)\n *\n * const { result } = await client.sendCalls({\n * calls: [\n * Actions.validator.update.call({\n * newValidatorAddress: '0x...',\n * publicKey: '0x...',\n * inboundAddress: '192.168.1.1:8080',\n * outboundAddress: '192.168.1.1:8080',\n * }),\n * ],\n * })\n * ```\n *\n * @param args - Arguments.\n * @returns The call.\n */\n export function call(args: Args) {\n const { newValidatorAddress, publicKey, inboundAddress, outboundAddress } =\n args\n return defineCall({\n address: Addresses.validator,\n abi: Abis.validator,\n args: [newValidatorAddress, publicKey, inboundAddress, outboundAddress],\n functionName: 'updateValidator',\n })\n }\n}\n\n/**\n * Updates validator information and waits for the transaction receipt.\n *\n * @example\n * ```ts\n * import { createClient, http } from 'viem'\n * import { tempo } from 'viem/chains'\n * import { Actions } from 'viem/tempo'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const client = createClient({\n * account: privateKeyToAccount('0x...'),\n * chain: tempo({ feeToken: '0x20c0000000000000000000000000000000000001' }),\n * transport: http(),\n * })\n *\n * const { receipt } = await Actions.validator.updateSync(client, {\n * newValidatorAddress: '0x...',\n * publicKey: '0x...',\n * inboundAddress: '192.168.1.1:8080',\n * outboundAddress: '192.168.1.1:8080',\n * })\n * ```\n *\n * @param client - Client.\n * @param parameters - Parameters.\n * @returns The transaction receipt.\n */\nexport async function updateSync<\n chain extends Chain | undefined,\n account extends Account | undefined,\n>(\n client: Client<Transport, chain, account>,\n parameters: updateSync.Parameters<chain, account>,\n): Promise<updateSync.ReturnValue> {\n const { throwOnReceiptRevert = true, ...rest } = parameters\n const receipt = await update.inner(writeContractSync, client, {\n ...rest,\n throwOnReceiptRevert,\n } as never)\n return { receipt }\n}\n\nexport namespace updateSync {\n export type Parameters<\n chain extends Chain | undefined = Chain | undefined,\n account extends Account | undefined = Account | undefined,\n > = update.Parameters<chain, account>\n\n export type Args = update.Args\n\n export type ReturnValue = {\n receipt: TransactionReceipt\n }\n}\n","import * as Address from 'ox/Address'\nimport * as Hash from 'ox/Hash'\nimport * as Hex from 'ox/Hex'\nimport * as Provider from 'ox/Provider'\nimport * as RpcRequest from 'ox/RpcRequest'\nimport type { LocalAccount } from '../accounts/types.js'\nimport { getTransactionReceipt } from '../actions/public/getTransactionReceipt.js'\nimport { sendTransaction } from '../actions/wallet/sendTransaction.js'\nimport { sendTransactionSync } from '../actions/wallet/sendTransactionSync.js'\nimport { createClient } from '../clients/createClient.js'\nimport {\n createTransport,\n type Transport,\n} from '../clients/transports/createTransport.js'\nimport type { Chain } from '../types/chain.js'\nimport type { ChainConfig } from './chainConfig.js'\nimport * as Transaction from './Transaction.js'\n\nexport type FeePayer = Transport<typeof withFeePayer.type>\n\n/**\n * Creates a fee payer transport that routes requests between\n * the default transport or the fee payer transport.\n *\n * The policy parameter controls how the fee payer handles transactions:\n * - `'sign-only'`: Fee payer co-signs the transaction and returns it to the client transport, which then broadcasts it via the default transport\n * - `'sign-and-broadcast'`: Fee payer co-signs and broadcasts the transaction directly\n *\n * @param defaultTransport - The default transport to use.\n * @param feePayerTransport - The fee payer transport to use.\n * @param parameters - Configuration parameters.\n * @returns A relay transport.\n */\nexport function withFeePayer(\n defaultTransport: Transport,\n relayTransport: Transport,\n parameters?: withFeePayer.Parameters,\n): withFeePayer.ReturnValue {\n const { policy = 'sign-only' } = parameters ?? {}\n\n return (config) => {\n const transport_default = defaultTransport(config)\n const transport_relay = relayTransport(config)\n\n return createTransport({\n key: withFeePayer.type,\n name: 'Relay Proxy',\n async request({ method, params }, options) {\n if (\n method === 'eth_sendRawTransactionSync' ||\n method === 'eth_sendRawTransaction'\n ) {\n const serialized = (params as any)[0] as `0x76${string}`\n const transaction = Transaction.deserialize(serialized)\n\n // If the transaction is intended to be sponsored, forward it to the relay.\n if (transaction.feePayerSignature === null) {\n // For 'sign-and-broadcast', relay signs and broadcasts\n if (policy === 'sign-and-broadcast')\n return transport_relay.request(\n { method, params },\n options,\n ) as never\n\n // For 'sign-only', request signature from relay using eth_signRawTransaction\n {\n // Request signature from relay using eth_signRawTransaction\n const signedTransaction = await transport_relay.request(\n {\n method: 'eth_signRawTransaction',\n params: [serialized],\n },\n options,\n )\n\n // Broadcast the signed transaction via the default transport\n return transport_default.request(\n { method, params: [signedTransaction] },\n options,\n ) as never\n }\n }\n }\n return (await transport_default.request(\n { method, params },\n options,\n )) as never\n },\n type: withFeePayer.type,\n })\n }\n}\n\nexport declare namespace withFeePayer {\n export const type = 'feePayer'\n\n export type Parameters = {\n /** Policy for how the fee payer should handle transactions. Defaults to `'sign-only'`. */\n policy?: 'sign-only' | 'sign-and-broadcast' | undefined\n }\n\n export type ReturnValue = FeePayer\n}\n\n/**\n * Creates a transport that instruments a compatibility layer for\n * `wallet_` RPC actions (`sendCalls`, `getCallsStatus`, etc).\n *\n * @param transport - Transport to wrap.\n * @returns Transport.\n */\nexport function walletNamespaceCompat(\n transport: Transport,\n options: walletNamespaceCompat.Parameters,\n): Transport {\n const { account } = options\n\n const sendCallsMagic = Hash.keccak256(Hex.fromString('TEMPO_5792'))\n\n return (options) => {\n const t = transport(options)\n\n const chain = options.chain as Chain & ChainConfig\n\n return {\n ...t,\n async request(args: never) {\n const request = RpcRequest.from(args)\n\n const client = createClient({\n chain,\n transport,\n })\n\n if (request.method === 'wallet_sendCalls') {\n const params = request.params[0] ?? {}\n const { capabilities, chainId, from } = params\n const { sync, ...properties } = capabilities ?? {}\n\n if (!chainId) throw new Provider.UnsupportedChainIdError()\n if (Number(chainId) !== client.chain.id)\n throw new Provider.UnsupportedChainIdError()\n if (from && !Address.isEqual(from, account.address))\n throw new Provider.DisconnectedError()\n\n const calls = (params.calls ?? []).map((call) => ({\n to: call.to,\n value: call.value ? BigInt(call.value) : undefined,\n data: call.data,\n }))\n\n const hash = await (async () => {\n if (!sync)\n return sendTransaction(client, {\n account,\n ...(properties ? properties : {}),\n calls,\n })\n\n const { transactionHash } = await sendTransactionSync(client, {\n account,\n ...(properties ? properties : {}),\n calls,\n })\n return transactionHash\n })()\n\n const id = Hex.concat(hash, Hex.padLeft(chainId, 32), sendCallsMagic)\n\n return {\n capabilities: { sync },\n id,\n }\n }\n\n if (request.method === 'wallet_getCallsStatus') {\n const [id] = request.params ?? []\n if (!id) throw new Error('`id` not found')\n if (!id.endsWith(sendCallsMagic.slice(2)))\n throw new Error('`id` not supported')\n Hex.assert(id)\n\n const hash = Hex.slice(id, 0, 32)\n const chainId = Hex.slice(id, 32, 64)\n\n const receipt = await getTransactionReceipt(client, { hash })\n return {\n atomic: true,\n chainId: Number(chainId),\n id,\n receipts: [receipt],\n status: receipt.status === 'success' ? 200 : 500,\n version: '2.0.0',\n }\n }\n\n return t.request(args)\n },\n } as never\n }\n}\n\nexport declare namespace walletNamespaceCompat {\n export type Parameters = {\n account: LocalAccount\n }\n}\n","import type { Address, Client, Account as viem_Account } from 'viem'\nimport { parseAccount } from 'viem/accounts'\n\nexport type Account = viem_Account\n\nexport function getResolver(parameters: getResolver.Parameters = {}) {\n const { account: defaultAccount } = parameters\n\n return (\n client: Client,\n { account: override }: { account?: Account | Address | undefined } = {},\n ): Account => {\n const account = override ?? defaultAccount\n\n if (!account) {\n if (!client.account)\n throw new Error('No `account` provided. Pass `account` to parameters or context.')\n return client.account\n }\n\n return parseAccount(account)\n }\n}\n\nexport declare namespace getResolver {\n type Parameters = {\n /** Account to use for signing. If an Address is provided, it must match the client's account. */\n account?: Account | Address | undefined\n }\n}\n","import { type Chain, type Client, createClient, http } from 'viem'\nimport { withFeePayer } from 'viem/tempo'\n\nimport type { MaybePromise } from '../internal/types.js'\n\nexport function getResolver(\n parameters: getResolver.Parameters & {\n /** Default chain to use if not provided. */\n chain?: Chain | undefined\n /** Fee payer relay URL. When set, the transport is wrapped with `withFeePayer`. */\n feePayerUrl?: string | undefined\n /** RPC URLs keyed by chain ID. */\n rpcUrl?: ({ [chainId: number]: string } & object) | undefined\n },\n): (parameters: { chainId?: number | undefined }) => MaybePromise<Client> {\n const { chain, feePayerUrl, getClient, rpcUrl } = parameters\n\n if (getClient) {\n // When a default chain with serializers is provided (e.g. Tempo chain config),\n // ensure user-provided clients inherit those serializers. Without this, clients\n // created without the Tempo chain config will use the default viem serializer,\n // causing errors like \"maxFeePerGas is not a valid Legacy Transaction attribute\".\n if (!chain?.serializers && !feePayerUrl) return getClient\n return async (params) => {\n const client = await getClient(params)\n\n // Wrap the client's transport with `withFeePayer` when a fee payer URL is provided.\n if (feePayerUrl && client.transport.key !== 'feePayer') {\n const url = (client.transport as { url?: string }).url\n if (url) {\n const wrapped = createClient({\n chain: client.chain,\n transport: withFeePayer(http(url), http(feePayerUrl)),\n })\n Object.assign(client, { transport: wrapped.transport, request: wrapped.request })\n }\n }\n\n if (!chain?.serializers || client.chain?.serializers?.transaction) return client\n return Object.assign({}, client, {\n chain: {\n ...chain,\n ...client.chain,\n formatters: client.chain?.formatters ?? chain.formatters,\n prepareTransactionRequest:\n client.chain?.prepareTransactionRequest ?? chain.prepareTransactionRequest,\n serializers: client.chain?.serializers?.transaction\n ? client.chain.serializers\n : chain.serializers,\n } as typeof client.chain,\n })\n }\n }\n\n return ({ chainId }: { chainId?: number | undefined }) => {\n if (!rpcUrl) throw new Error('No `rpcUrl` provided.')\n const resolvedChainId = chainId || Number(Object.keys(rpcUrl)[0])!\n const url = rpcUrl[resolvedChainId as keyof typeof rpcUrl]\n if (!url) throw new Error(`No \\`rpcUrl\\` configured for \\`chainId\\` (${resolvedChainId}).`)\n const transport = feePayerUrl ? withFeePayer(http(url), http(feePayerUrl)) : http(url)\n return createClient({\n chain: { ...chain, id: resolvedChainId } as never,\n transport,\n })\n }\n}\n\nexport declare namespace getResolver {\n type Parameters = {\n /** Function that returns a client for the given chain ID. */\n getClient?: ((parameters: { chainId?: number | undefined }) => MaybePromise<Client>) | undefined\n }\n}\n","import { Bytes, Hash, Hex } from 'ox'\n\n/**\n * MPP attribution memo encoding for TIP-20 `transferWithMemo`.\n *\n * When no user-provided memo is present, the SDK auto-generates an\n * attribution memo so MPP transactions are identifiable on-chain.\n *\n * ## Byte Layout (32 bytes)\n *\n * | Offset | Size | Field |\n * |--------|------|-------------------------------------------|\n * | 0..3 | 4 | TAG = keccak256(\"mpp\")[0..3] |\n * | 4 | 1 | version (0x01) |\n * | 5..14 | 10 | serverId = keccak256(serverId)[0..9] |\n * | 15..24 | 10 | clientId = keccak256(clientId)[0..9] or 0s |\n * | 25..31 | 7 | nonce (random bytes) |\n *\n * The TAG prefix makes MPP transactions trivially distinguishable\n * from arbitrary memos via `TransferWithMemo` event topic filtering.\n *\n * @module\n */\n\n/** First 4 bytes of keccak256(\"mpp\") — the on-chain MPP tag. */\nexport const tag = Hex.slice(Hash.keccak256(Bytes.fromString('mpp'), { as: 'Hex' }), 0, 4)\n\n/** Current memo version. */\nconst version = 0x01\n\n/** 10 zero bytes representing an anonymous (no clientId) client. */\nexport const anonymous = '0x00000000000000000000' as const\n\n/**\n * Computes a 10-byte fingerprint from a string via keccak256.\n * @internal\n */\nfunction fingerprint(value: string): Uint8Array {\n const hash = Hash.keccak256(Bytes.fromString(value), { as: 'Hex' })\n return Hex.toBytes(Hex.slice(hash, 0, 10))\n}\n\n/**\n * Encodes an MPP attribution memo as a `bytes32` hex string.\n *\n * @param parameters - The serverId (server identity) and optional clientId.\n * @returns A `0x`-prefixed 64-char hex string (32 bytes).\n *\n * @example\n * ```ts\n * import * as Attribution from './Attribution.js'\n *\n * const memo = Attribution.encode({ serverId: 'api.example.com', clientId: 'my-app' })\n * ```\n */\nexport function encode(parameters: encode.Parameters) {\n const { serverId, clientId } = parameters\n const buf = new Uint8Array(32)\n\n buf.set(Hex.toBytes(tag), 0)\n buf[4] = version\n buf.set(fingerprint(serverId), 5)\n if (clientId) buf.set(fingerprint(clientId), 15)\n\n const nonce = crypto.getRandomValues(new Uint8Array(7))\n buf.set(nonce, 25)\n\n return Hex.fromBytes(buf)\n}\n\nexport declare namespace encode {\n type Parameters = {\n /** Server identity used to derive the server fingerprint. */\n serverId: string\n /** Optional client identity used to derive the client fingerprint. */\n clientId?: string | undefined\n }\n}\n\n/**\n * Checks whether a memo was generated by the MPP attribution system.\n *\n * @param memo - A `0x`-prefixed hex string (bytes32).\n * @returns `true` if the memo starts with the MPP tag and version byte.\n *\n * @example\n * ```ts\n * import * as Attribution from './Attribution.js'\n *\n * Attribution.isMppMemo(Attribution.encode({ serverId: 'api.example.com' })) // true\n * Attribution.isMppMemo('0x0000...0000') // false\n * ```\n */\nexport function isMppMemo(memo: `0x${string}`): boolean {\n if (memo.length !== 66) return false\n const memoTag = memo.slice(0, 10) as `0x${string}`\n const memoVersion = Number.parseInt(memo.slice(10, 12), 16)\n return memoTag.toLowerCase() === tag.toLowerCase() && memoVersion === version\n}\n\n/**\n * Verifies that a memo's server fingerprint matches the given serverId.\n *\n * Checks TAG, version byte, and that bytes 5–14 equal keccak256(serverId)[0..9].\n *\n * @param memo - A `0x`-prefixed hex string (bytes32).\n * @param serverId - The expected server identity.\n * @returns `true` if the memo has a valid MPP tag and matching server fingerprint.\n */\nexport function verifyServer(memo: `0x${string}`, serverId: string): boolean {\n if (!isMppMemo(memo)) return false\n const memoServerHex = `0x${memo.slice(12, 32)}` as `0x${string}`\n const expectedHex = Hex.fromBytes(fingerprint(serverId)) as `0x${string}`\n return memoServerHex.toLowerCase() === expectedHex.toLowerCase()\n}\n\n/**\n * Decodes an MPP attribution memo into its constituent parts.\n *\n * @param memo - A `0x`-prefixed hex string (bytes32).\n * @returns The decoded fields, or `null` if the memo is not an MPP memo.\n *\n * @example\n * ```ts\n * import * as Attribution from './Attribution.js'\n *\n * const memo = Attribution.encode({ serverId: 'api.example.com', clientId: 'my-app' })\n * const decoded = Attribution.decode(memo)\n * // { version: 1, serverFingerprint: '0x...', clientFingerprint: '0x...', nonce: '0x...' }\n * ```\n */\nexport function decode(memo: `0x${string}`): decode.Result | null {\n if (!isMppMemo(memo)) return null\n\n const memoVersion = Number.parseInt(memo.slice(10, 12), 16)\n const serverFingerprint = `0x${memo.slice(12, 32)}` as `0x${string}`\n const clientHex = `0x${memo.slice(32, 52)}` as `0x${string}`\n const nonce = `0x${memo.slice(52)}` as `0x${string}`\n\n const clientFingerprint = clientHex.toLowerCase() === anonymous.toLowerCase() ? null : clientHex\n\n return { version: memoVersion, serverFingerprint, clientFingerprint, nonce }\n}\n\nexport declare namespace decode {\n type Result = {\n /** Memo version (currently always 1). */\n version: number\n /** 10-byte server fingerprint hex (keccak256(serverId)[0..9]). */\n serverFingerprint: `0x${string}`\n /** 10-byte client fingerprint hex, or `null` if anonymous. */\n clientFingerprint: `0x${string}` | null\n /** 7-byte random nonce hex. */\n nonce: `0x${string}`\n }\n}\n","// TODO: Add `isEqual` to `TempoAddress`.\nimport type { TempoAddress } from 'ox/tempo'\n\nexport function isEqual(a: TempoAddress.Address, b: TempoAddress.Address) {\n return a.toLowerCase() === b.toLowerCase()\n}\n","import type { ValueOf } from '../../internal/types.js'\n\nexport const chainId = {\n mainnet: 4217,\n testnet: 42431,\n} as const\nexport type ChainId = ValueOf<typeof chainId>\n\n/** Token addresses. */\nexport const tokens = {\n /** USDC (USDC.e) token address. */\n usdc: '0x20C000000000000000000000b9537d11c60E8b50',\n /** pathUSD token address. */\n pathUsd: '0x20c0000000000000000000000000000000000000',\n} as const\n\n/** Chain ID → default currency. */\nexport const currency = {\n [chainId.mainnet]: tokens.usdc,\n [chainId.testnet]: tokens.pathUsd,\n} as const satisfies Record<ChainId, string>\n\n/**\n * Default token decimals for TIP-20 stablecoins (e.g. pathUSD, USDC).\n *\n * All TIP-20 tokens on Tempo use 6 decimals, so there is no risk of\n * client/server mismatch within the Tempo ecosystem. Other chains and\n * runtimes should set `decimals` explicitly to match their token.\n */\nexport const decimals = 6\n\n/** Default payment-channel escrow contract addresses per chain. */\nexport const escrowContract = {\n [chainId.mainnet]: '0x33b901018174DDabE4841042ab76ba85D4e24f25',\n [chainId.testnet]: '0xe1c4d3dce17bc111181ddf716f75bae49e61a336',\n} as const satisfies Record<ChainId, string>\n\n/** Default RPC URLs for each Tempo chain. */\nexport const rpcUrl = {\n [chainId.mainnet]: 'https://rpc.tempo.xyz',\n [chainId.testnet]: 'https://rpc.moderato.tempo.xyz',\n} as const satisfies Record<ChainId, string>\n\n/** Resolves the default currency. */\nexport function resolveCurrency(parameters: {\n /** Chain ID. */\n chainId?: number | undefined\n /** Whether in testnet mode. */\n testnet?: boolean | undefined\n}): string {\n const id = parameters.chainId ?? (parameters.testnet ? chainId.testnet : chainId.mainnet)\n return currency[id as keyof typeof currency] ?? tokens.pathUsd\n}\n","import type { Address, Client } from 'viem'\nimport { readContract } from 'viem/actions'\nimport { Actions, Addresses } from 'viem/tempo'\n\nimport * as TempoAddress from './address.js'\nimport * as defaults from './defaults.js'\n\n/** Basis-point denominator (100% = 10 000 bps). */\nconst bps = 10_000n\n\n/** Default fallback currencies for auto-swap, in priority order. */\nexport const defaultCurrencies: readonly Address[] = [\n defaults.tokens.pathUsd as Address,\n defaults.tokens.usdc as Address,\n]\n\n/**\n * Finds the optimal swap calls to acquire `amountOut` of `tokenOut`,\n * returning an approve + buy call sequence if a viable route is found.\n *\n * Returns `undefined` if the account already holds enough of `tokenOut`\n * or no viable swap route exists from the given input tokens.\n */\nexport async function findCalls(\n client: Client,\n parameters: findCalls.Parameters,\n): Promise<findCalls.ReturnType> {\n const { account, amountOut, tokenOut, tokenIn, slippage } = parameters\n\n const candidates = tokenIn.filter((t) => !TempoAddress.isEqual(t, tokenOut))\n\n const balanceResults = await Promise.allSettled([\n readContract(client, Actions.token.getBalance.call({ account, token: tokenOut }) as never),\n ...candidates.map((t) =>\n readContract(client, Actions.token.getBalance.call({ account, token: t }) as never),\n ),\n ])\n\n // If the account already has enough of the target token, no swap needed.\n const targetBalance = balanceResults[0]!\n if (targetBalance.status === 'fulfilled' && (targetBalance.value as bigint) >= amountOut)\n return undefined\n\n // Find first candidate with enough balance to cover a swap.\n for (let i = 0; i < candidates.length; i++) {\n const result = balanceResults[i + 1]!\n if (result.status !== 'fulfilled') continue\n\n const balance = result.value as bigint\n if (balance <= 0n) continue\n\n const tokenIn = candidates[i]!\n\n try {\n const quotedAmountIn = await Actions.dex.getBuyQuote(client as never, {\n tokenIn,\n tokenOut,\n amountOut,\n })\n\n if (balance >= quotedAmountIn) {\n const maxAmountIn =\n quotedAmountIn + (quotedAmountIn * BigInt(Math.round(slippage * 100))) / bps\n return [\n Actions.token.approve.call({\n token: tokenIn,\n spender: Addresses.stablecoinDex,\n amount: maxAmountIn,\n }),\n Actions.dex.buy.call({\n tokenIn,\n tokenOut,\n amountOut,\n maxAmountIn,\n }),\n ]\n }\n } catch {}\n }\n\n throw new InsufficientFundsError({ currency: tokenOut })\n}\n\nexport declare namespace findCalls {\n type Parameters = {\n /** Address of the account to check balances for. */\n account: Address\n /** Amount of the target token needed. */\n amountOut: bigint\n /** Candidate input tokens to swap from, in priority order. */\n tokenIn: readonly Address[]\n /** Max slippage tolerance as a percentage (e.g. `1` = 1%). */\n slippage: number\n /** Address of the target token to acquire. */\n tokenOut: Address\n }\n\n /** `undefined` when no swap is needed (account has sufficient balance). */\n type ReturnType = readonly object[] | undefined\n}\n\n/** Resolves an auto-swap configuration value into concrete currencies and slippage. */\nexport function resolve(\n value: resolve.Value | undefined,\n defaultCurrencies: readonly Address[],\n): resolve.Resolved | false {\n if (!value) return false\n if (value === true) return { tokenIn: defaultCurrencies, slippage: 1 }\n const tokenIn = value.tokenIn\n ? [\n ...value.tokenIn,\n ...defaultCurrencies.filter((d) => !value.tokenIn!.some((c) => TempoAddress.isEqual(c, d))),\n ]\n : defaultCurrencies\n return {\n tokenIn,\n slippage: value.slippage ?? 1,\n }\n}\n\nexport declare namespace resolve {\n type Options = {\n /** Fallback tokens to try swapping from, in priority order. */\n tokenIn?: Address[] | undefined\n /** Max slippage tolerance as a percentage (e.g. `1` = 1%). @default 1 */\n slippage?: number | undefined\n }\n\n type Value = boolean | Options\n\n type Resolved = { tokenIn: readonly Address[]; slippage: number }\n}\n\nexport class InsufficientFundsError extends Error {\n override readonly name = 'InsufficientFundsError'\n\n constructor({ currency }: { currency: Address }) {\n super(\n `Insufficient funds: no balance in ${currency} and no viable swap route from fallback currencies.`,\n )\n }\n}\n","import type { Account } from 'viem'\nimport { parseUnits } from 'viem'\n\nimport * as Method from '../Method.js'\nimport * as z from '../zod.js'\n\n/**\n * Tempo charge intent for one-time TIP-20 token transfers.\n *\n * @see https://github.com/tempoxyz/payment-auth-spec/blob/main/specs/methods/tempo/draft-tempo-charge-00.md\n */\nexport const charge = Method.from({\n name: 'tempo',\n intent: 'charge',\n schema: {\n credential: {\n payload: z.discriminatedUnion('type', [\n z.object({ hash: z.hash(), type: z.literal('hash') }),\n z.object({ signature: z.signature(), type: z.literal('transaction') }),\n ]),\n },\n request: z.pipe(\n z.object({\n amount: z.amount(),\n chainId: z.optional(z.number()),\n currency: z.string(),\n decimals: z.number(),\n description: z.optional(z.string()),\n externalId: z.optional(z.string()),\n feePayer: z.optional(\n z.pipe(\n z.union([z.boolean(), z.custom<Account>()]),\n z.transform((v): boolean => (typeof v === 'object' ? true : v)),\n ),\n ),\n memo: z.optional(z.hash()),\n recipient: z.optional(z.string()),\n }),\n z.transform(({ amount, chainId, decimals, feePayer, memo, ...rest }) => ({\n ...rest,\n amount: parseUnits(amount, decimals).toString(),\n ...(chainId !== undefined || feePayer !== undefined || memo !== undefined\n ? {\n methodDetails: {\n ...(chainId !== undefined && { chainId }),\n ...(feePayer !== undefined && { feePayer }),\n ...(memo !== undefined && { memo }),\n },\n }\n : {}),\n })),\n ),\n },\n})\n\n/**\n * Tempo session intent for pay-as-you-go streaming payments.\n *\n * Uses cumulative vouchers over a payment channel. Credential payloads\n * are a discriminated union on `action`: open, topUp, voucher, close.\n */\nexport const session = Method.from({\n name: 'tempo',\n intent: 'session',\n schema: {\n credential: {\n payload: z.discriminatedUnion('action', [\n z.object({\n action: z.literal('open'),\n authorizedSigner: z.optional(z.string()),\n channelId: z.hash(),\n cumulativeAmount: z.amount(),\n signature: z.signature(),\n transaction: z.signature(),\n type: z.literal('transaction'),\n }),\n z.object({\n action: z.literal('topUp'),\n additionalDeposit: z.amount(),\n channelId: z.hash(),\n transaction: z.signature(),\n type: z.literal('transaction'),\n }),\n z.object({\n action: z.literal('voucher'),\n channelId: z.hash(),\n cumulativeAmount: z.amount(),\n signature: z.signature(),\n }),\n z.object({\n action: z.literal('close'),\n channelId: z.hash(),\n cumulativeAmount: z.amount(),\n signature: z.signature(),\n }),\n ]),\n },\n request: z.pipe(\n z.object({\n amount: z.amount(),\n chainId: z.optional(z.number()),\n channelId: z.optional(z.hash()),\n currency: z.string(),\n decimals: z.number(),\n escrowContract: z.optional(z.string()),\n feePayer: z.optional(\n z.pipe(\n z.union([z.boolean(), z.custom<Account>()]),\n z.transform((v): boolean => (typeof v === 'object' ? true : v)),\n ),\n ),\n minVoucherDelta: z.optional(z.amount()),\n recipient: z.optional(z.string()),\n suggestedDeposit: z.optional(z.amount()),\n unitType: z.string(),\n }),\n z.transform(\n ({\n amount,\n chainId,\n channelId,\n decimals,\n escrowContract,\n feePayer,\n minVoucherDelta,\n suggestedDeposit,\n ...rest\n }) => ({\n ...rest,\n amount: parseUnits(amount, decimals).toString(),\n ...(suggestedDeposit\n ? {\n suggestedDeposit: parseUnits(suggestedDeposit, decimals).toString(),\n }\n : {}),\n methodDetails: {\n escrowContract,\n ...(channelId !== undefined && { channelId }),\n ...(minVoucherDelta !== undefined && {\n minVoucherDelta: parseUnits(minVoucherDelta, decimals).toString(),\n }),\n ...(chainId !== undefined && { chainId }),\n ...(feePayer !== undefined && { feePayer }),\n },\n }),\n ),\n ),\n },\n})\n","import type * as Hex from 'ox/Hex'\nimport type { Address } from 'viem'\nimport { prepareTransactionRequest, sendCallsSync, signTransaction } from 'viem/actions'\nimport { tempo as tempo_chain } from 'viem/chains'\nimport { Actions } from 'viem/tempo'\n\nimport * as Credential from '../../Credential.js'\nimport * as Method from '../../Method.js'\nimport * as Account from '../../viem/Account.js'\nimport * as Client from '../../viem/Client.js'\nimport * as z from '../../zod.js'\nimport * as Attribution from '../Attribution.js'\nimport * as AutoSwap from '../internal/auto-swap.js'\nimport * as defaults from '../internal/defaults.js'\nimport * as Methods from '../Methods.js'\n\n/**\n * Creates a Tempo charge method intent for usage on the client.\n *\n * @example\n * ```ts\n * import { tempo } from 'mppx/client'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const charge = tempo.charge({\n * account: privateKeyToAccount('0x...'),\n * })\n * ```\n */\nexport function charge(parameters: charge.Parameters = {}) {\n const { clientId } = parameters\n const getClient = Client.getResolver({\n chain: tempo_chain,\n getClient: parameters.getClient,\n rpcUrl: defaults.rpcUrl,\n })\n const getAccount = Account.getResolver({ account: parameters.account })\n\n return Method.toClient(Methods.charge, {\n context: z.object({\n account: z.optional(z.custom<Account.getResolver.Parameters['account']>()),\n autoSwap: z.optional(z.custom<charge.AutoSwap>()),\n mode: z.optional(z.enum(['push', 'pull'])),\n }),\n\n async createCredential({ challenge, context }) {\n const chainId = challenge.request.methodDetails?.chainId\n const client = await getClient({ chainId })\n const account = getAccount(client, context)\n\n const mode =\n context?.mode ?? parameters.mode ?? (account.type === 'json-rpc' ? 'push' : 'pull')\n\n const { request } = challenge\n const { amount, methodDetails } = request\n const currency = request.currency as Address\n const recipient = request.recipient as Address\n\n const memo = methodDetails?.memo\n ? (methodDetails.memo as Hex.Hex)\n : Attribution.encode({ serverId: challenge.realm, clientId })\n\n const transferCall = Actions.token.transfer.call({\n amount: BigInt(amount),\n memo,\n to: recipient,\n token: currency,\n })\n\n const autoSwap = AutoSwap.resolve(\n context?.autoSwap ?? parameters.autoSwap,\n AutoSwap.defaultCurrencies,\n )\n\n const swapCalls = autoSwap\n ? await AutoSwap.findCalls(client, {\n account: account.address,\n amountOut: BigInt(amount),\n tokenOut: currency,\n tokenIn: autoSwap.tokenIn,\n slippage: autoSwap.slippage,\n })\n : undefined\n\n const calls = [...(swapCalls ?? []), transferCall]\n\n if (mode === 'push') {\n const { receipts } = await sendCallsSync(client, {\n account,\n calls: calls as never,\n experimental_fallback: true,\n })\n const hash = receipts?.[0]?.transactionHash\n if (!hash) throw new Error('No transaction receipt returned.')\n return Credential.serialize({\n challenge,\n payload: { hash, type: 'hash' },\n source: `did:pkh:eip155:${chainId}:${account.address}`,\n })\n }\n\n const prepared = await prepareTransactionRequest(client, {\n account,\n calls,\n ...(methodDetails?.feePayer && { feePayer: true }),\n nonceKey: 'expiring',\n } as never)\n // FIXME: figure out gas estimation issue for fee payer tx\n prepared.gas = prepared.gas! + 5_000n\n const signature = await signTransaction(client, prepared as never)\n\n return Credential.serialize({\n challenge,\n payload: { signature, type: 'transaction' },\n source: `did:pkh:eip155:${chainId}:${account.address}`,\n })\n },\n })\n}\n\nexport declare namespace charge {\n type AutoSwap = AutoSwap.resolve.Value\n\n type Parameters = {\n /**\n * Automatically swap from a fallback currency (pathUsd, USDC.e) via the\n * Tempo DEX when the user lacks sufficient balance of the target currency.\n *\n * @default false\n */\n autoSwap?: AutoSwap | undefined\n /** Client identifier used to derive the client fingerprint in attribution memos. */\n clientId?: string | undefined\n /**\n * Controls how the charge transaction is submitted.\n *\n * - `'push'`: Client broadcasts the transaction and sends the tx hash to the server.\n * - `'pull'`: Client signs the transaction and sends the serialized tx to the server for broadcast.\n *\n * @default `'push'` for JSON-RPC accounts, `'pull'` for local accounts.\n */\n mode?: 'push' | 'pull' | undefined\n } & Account.getResolver.Parameters &\n Client.getResolver.Parameters\n}\n","import * as Address from '../core/Address.js'\nimport type * as Bytes from '../core/Bytes.js'\nimport * as Errors from '../core/Errors.js'\nimport * as Hex from '../core/Hex.js'\nimport type {\n Assign,\n Compute,\n IsNarrowable,\n OneOf,\n PartialBy,\n UnionPartialBy,\n} from '../core/internal/types.js'\nimport * as Json from '../core/Json.js'\nimport * as ox_P256 from '../core/P256.js'\nimport type * as PublicKey from '../core/PublicKey.js'\nimport * as ox_Secp256k1 from '../core/Secp256k1.js'\nimport * as Signature from '../core/Signature.js'\nimport type * as WebAuthnP256 from '../core/WebAuthnP256.js'\nimport * as ox_WebAuthnP256 from '../core/WebAuthnP256.js'\n\n/** Signature type identifiers for encoding/decoding */\nconst serializedP256Type = '0x01'\nconst serializedWebAuthnType = '0x02'\nconst serializedKeychainType = '0x03'\nconst serializedKeychainV2Type = '0x04'\n\n/** Serialized magic identifier for Tempo signature envelopes. */\nexport const magicBytes =\n '0x7777777777777777777777777777777777777777777777777777777777777777' // 32 \"T\"s\n\n/**\n * Statically determines the signature type of an envelope at compile time.\n *\n * @example\n * ```ts twoslash\n * import type { SignatureEnvelope } from 'ox/tempo'\n *\n * type Type = SignatureEnvelope.GetType<{ r: bigint; s: bigint; yParity: number }>\n * // @log: 'secp256k1'\n * ```\n */\nexport type GetType<\n envelope extends PartialBy<SignatureEnvelope, 'type'> | unknown,\n> = unknown extends envelope\n ? envelope extends unknown\n ? Type\n : never\n : envelope extends { type: infer T extends Type }\n ? T\n : envelope extends {\n signature: { r: bigint; s: bigint }\n prehash: boolean\n publicKey: PublicKey.PublicKey\n }\n ? 'p256'\n : envelope extends {\n signature: { r: bigint; s: bigint }\n metadata: any\n publicKey: PublicKey.PublicKey\n }\n ? 'webAuthn'\n : envelope extends { r: bigint; s: bigint; yParity: number }\n ? 'secp256k1'\n : envelope extends {\n signature: { r: bigint; s: bigint; yParity: number }\n }\n ? 'secp256k1'\n : envelope extends {\n userAddress: Address.Address\n }\n ? 'keychain'\n : never\n\n/**\n * Represents a signature envelope that can contain different signature types.\n *\n * Tempo transactions support multiple signature types, each with different wire formats:\n *\n * - **secp256k1** (no type prefix, 65 bytes): Standard Ethereum ECDSA signature. The sender\n * address is recovered via `ecrecover`. Base transaction cost: 21,000 gas.\n *\n * - **p256** (type `0x01`, 130 bytes): P256/secp256r1 curve signature for passkey accounts.\n * Includes embedded public key (64 bytes) and prehash flag. Enables native WebCrypto\n * key support. Additional gas cost: +5,000 gas over secp256k1.\n *\n * - **webAuthn** (type `0x02`, 129-2049 bytes): WebAuthn signature with authenticator data\n * and clientDataJSON. Enables browser passkey authentication. The signature is also\n * charged as calldata (16 gas/non-zero byte, 4 gas/zero byte).\n *\n * - **keychain** (type `0x03` V1, `0x04` V2): Access key signature that wraps an inner signature\n * (secp256k1, p256, or webAuthn). Format: type byte + user_address (20 bytes) + inner signature.\n * V2 binds the signature to the user account via `keccak256(sigHash || userAddress)`.\n * The protocol validates the access key authorization via the AccountKeychain precompile.\n *\n * [Signature Types Specification](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#signature-types)\n */\nexport type SignatureEnvelope<bigintType = bigint, numberType = number> = OneOf<\n | Secp256k1<bigintType, numberType>\n | P256<bigintType, numberType>\n | WebAuthn<bigintType, numberType>\n | Keychain<bigintType, numberType>\n>\n\n/**\n * RPC-formatted signature envelope.\n */\nexport type SignatureEnvelopeRpc = OneOf<\n Secp256k1Rpc | P256Rpc | WebAuthnRpc | KeychainRpc\n>\n\n/**\n * Keychain signature version.\n *\n * - `'v1'`: Legacy format. Inner signature signs the raw `sig_hash` directly. Deprecated at T1C.\n * - `'v2'`: Inner signature signs `keccak256(sig_hash || user_address)`, binding the signature\n * to the specific user account.\n */\nexport type KeychainVersion = 'v1' | 'v2'\n\nexport type Keychain<bigintType = bigint, numberType = number> = {\n /** Root account address that this transaction is being executed for */\n userAddress: Address.Address\n /** The actual signature from the access key (can be Secp256k1, P256, or WebAuthn) */\n inner: SignatureEnvelope<bigintType, numberType>\n /** The access key address (recovered address of the access key signer). */\n keyId?: Address.Address | undefined\n type: 'keychain'\n /** Keychain signature version. @default 'v1' */\n version?: KeychainVersion | undefined\n}\n\nexport type KeychainRpc = {\n type: 'keychain'\n userAddress: Address.Address\n keyId?: Address.Address | undefined\n signature: SignatureEnvelopeRpc\n version?: KeychainVersion | undefined\n}\n\nexport type P256<bigintType = bigint, numberType = number> = {\n prehash: boolean\n publicKey: PublicKey.PublicKey\n signature: Signature.Signature<false, bigintType, numberType>\n type: 'p256'\n}\n\nexport type P256Rpc = {\n preHash: boolean\n pubKeyX: Hex.Hex\n pubKeyY: Hex.Hex\n r: Hex.Hex\n s: Hex.Hex\n type: 'p256'\n}\n\nexport type Secp256k1<bigintType = bigint, numberType = number> = {\n signature: Signature.Signature<true, bigintType, numberType>\n type: 'secp256k1'\n}\n\nexport type Secp256k1Rpc = Compute<\n Signature.Rpc<true> & {\n v?: Hex.Hex | undefined\n type: 'secp256k1'\n }\n>\n\nexport type Secp256k1Flat<\n bigintType = bigint,\n numberType = number,\n> = Signature.Signature<true, bigintType, numberType> & {\n type?: 'secp256k1' | undefined\n}\n\nexport type WebAuthn<bigintType = bigint, numberType = number> = {\n metadata: Pick<\n WebAuthnP256.SignMetadata,\n 'authenticatorData' | 'clientDataJSON'\n >\n signature: Signature.Signature<false, bigintType, numberType>\n publicKey: PublicKey.PublicKey\n type: 'webAuthn'\n}\n\nexport type WebAuthnRpc = {\n pubKeyX: Hex.Hex\n pubKeyY: Hex.Hex\n r: Hex.Hex\n s: Hex.Hex\n type: 'webAuthn'\n webauthnData: Hex.Hex\n}\n\n/** Hex-encoded serialized signature envelope. */\nexport type Serialized = Hex.Hex\n\n/** List of supported signature types. */\nexport const types = ['secp256k1', 'p256', 'webAuthn'] as const\n\n/** Union type of supported signature types. */\nexport type Type = (typeof types)[number]\n\n/**\n * Asserts that a {@link ox#SignatureEnvelope.SignatureEnvelope} is valid.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * SignatureEnvelope.assert({\n * type: 'secp256k1',\n * signature: {\n * r: 0n,\n * s: 0n,\n * yParity: 0,\n * },\n * })\n * ```\n *\n * @param envelope - The signature envelope to assert.\n * @throws `CoercionError` if the envelope type cannot be determined.\n */\nexport function assert(envelope: PartialBy<SignatureEnvelope, 'type'>): void {\n const type = getType(envelope)\n\n if (type === 'secp256k1') {\n const secp256k1 = envelope as Secp256k1\n Signature.assert(secp256k1.signature)\n return\n }\n\n if (type === 'p256') {\n const p256 = envelope as P256\n const missing: string[] = []\n\n if (typeof p256.signature?.r !== 'bigint') missing.push('signature.r')\n if (typeof p256.signature?.s !== 'bigint') missing.push('signature.s')\n if (typeof p256.prehash !== 'boolean') missing.push('prehash')\n if (!p256.publicKey) missing.push('publicKey')\n else {\n if (typeof p256.publicKey.x !== 'bigint') missing.push('publicKey.x')\n if (typeof p256.publicKey.y !== 'bigint') missing.push('publicKey.y')\n }\n\n if (missing.length > 0)\n throw new MissingPropertiesError({ envelope, missing, type: 'p256' })\n return\n }\n\n if (type === 'webAuthn') {\n const webauthn = envelope as WebAuthn\n const missing: string[] = []\n\n if (typeof webauthn.signature?.r !== 'bigint') missing.push('signature.r')\n if (typeof webauthn.signature?.s !== 'bigint') missing.push('signature.s')\n if (!webauthn.metadata) missing.push('metadata')\n else {\n if (!webauthn.metadata.authenticatorData)\n missing.push('metadata.authenticatorData')\n if (!webauthn.metadata.clientDataJSON)\n missing.push('metadata.clientDataJSON')\n }\n if (!webauthn.publicKey) missing.push('publicKey')\n else {\n if (typeof webauthn.publicKey.x !== 'bigint') missing.push('publicKey.x')\n if (typeof webauthn.publicKey.y !== 'bigint') missing.push('publicKey.y')\n }\n\n if (missing.length > 0)\n throw new MissingPropertiesError({ envelope, missing, type: 'webAuthn' })\n return\n }\n\n if (type === 'keychain') {\n const keychain = envelope as Keychain\n assert(keychain.inner)\n return\n }\n}\n\nexport declare namespace assert {\n type ErrorType =\n | CoercionError\n | MissingPropertiesError\n | Signature.assert.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts the address of the signer from a {@link ox#SignatureEnvelope.SignatureEnvelope}.\n *\n * - **secp256k1**: Recovers the address from the payload via `ecrecover`.\n * - **p256** / **webAuthn**: Derives the address from the embedded public key.\n * - **keychain**: Extracts from the inner signature (or returns `userAddress` if `user` is `true`).\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const payload = '0xdeadbeef'\n * const signature = Secp256k1.sign({ payload, privateKey: '0x...' })\n * const envelope = SignatureEnvelope.from(signature)\n *\n * const address = SignatureEnvelope.extractAddress({ // [!code focus]\n * payload, // [!code focus]\n * signature: envelope, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The extraction options.\n * @returns The signer address.\n */\nexport function extractAddress(\n options: extractAddress.Options,\n): extractAddress.ReturnType {\n const { signature, root } = options\n if (signature.type === 'keychain') {\n if (root) return signature.userAddress\n return extractAddress({ ...options, signature: signature.inner })\n }\n return Address.fromPublicKey(extractPublicKey(options))\n}\n\nexport declare namespace extractAddress {\n type Options = {\n /** The sign payload that was signed (only required for secp256k1 signatures). */\n payload: Hex.Hex | Bytes.Bytes\n /** The signature envelope. */\n signature: SignatureEnvelope\n /** Whether to return the root `userAddress` for keychain signatures instead of extracting from the inner signature. */\n root?: boolean | undefined\n }\n\n type ReturnType = Address.Address\n\n type ErrorType =\n | Address.fromPublicKey.ErrorType\n | extractPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Extracts the public key of the signer from a {@link ox#SignatureEnvelope.SignatureEnvelope}.\n *\n * - **secp256k1**: Recovers the public key from the payload via `ecrecover`.\n * - **p256** / **webAuthn**: Returns the embedded public key.\n * - **keychain**: Extracts from the inner signature.\n *\n * @example\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const payload = '0xdeadbeef'\n * const signature = Secp256k1.sign({ payload, privateKey: '0x...' })\n * const envelope = SignatureEnvelope.from(signature)\n *\n * const publicKey = SignatureEnvelope.extractPublicKey({ // [!code focus]\n * payload, // [!code focus]\n * signature: envelope, // [!code focus]\n * }) // [!code focus]\n * ```\n *\n * @param options - The extraction options.\n * @returns The signer's public key.\n */\nexport function extractPublicKey(\n options: extractPublicKey.Options,\n): extractPublicKey.ReturnType {\n const { payload, signature } = options\n\n switch (signature.type) {\n case 'secp256k1':\n return ox_Secp256k1.recoverPublicKey({\n payload,\n signature: signature.signature,\n })\n case 'p256':\n case 'webAuthn':\n return signature.publicKey\n case 'keychain':\n return extractPublicKey({ payload, signature: signature.inner })\n }\n}\n\nexport declare namespace extractPublicKey {\n type Options = {\n /** The sign payload that was signed (only required for secp256k1 signatures). */\n payload: Hex.Hex | Bytes.Bytes\n /** The signature envelope. */\n signature: SignatureEnvelope\n }\n\n type ReturnType = PublicKey.PublicKey\n\n type ErrorType =\n | ox_Secp256k1.recoverPublicKey.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Deserializes a hex-encoded signature envelope into a typed signature object.\n *\n * Wire format detection:\n * - 65 bytes (no prefix): secp256k1 signature\n * - Type `0x01` + 129 bytes: P256 signature (r, s, pubKeyX, pubKeyY, prehash)\n * - Type `0x02` + variable: WebAuthn signature (webauthnData, r, s, pubKeyX, pubKeyY)\n * - Type `0x03` + 20 bytes + inner: Keychain V1 signature (userAddress + inner signature)\n * - Type `0x04` + 20 bytes + inner: Keychain V2 signature (userAddress + inner signature)\n *\n * [Signature Types](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#signature-types)\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const envelope = SignatureEnvelope.deserialize('0x...')\n * ```\n *\n * @param serialized - The hex-encoded signature envelope to deserialize.\n * @returns The deserialized signature envelope.\n * @throws `CoercionError` if the serialized value cannot be coerced to a valid signature envelope.\n */\nexport function deserialize(value: Serialized): SignatureEnvelope {\n const serialized = value.endsWith(magicBytes.slice(2))\n ? Hex.slice(value, 0, -Hex.size(magicBytes))\n : value\n\n const size = Hex.size(serialized)\n\n // Backward compatibility: 65 bytes means secp256k1 without type identifier\n if (size === 65) {\n const signature = Signature.fromHex(serialized)\n Signature.assert(signature)\n return { signature, type: 'secp256k1' } satisfies Secp256k1\n }\n\n // For all other lengths, first byte is the type identifier\n const typeId = Hex.slice(serialized, 0, 1)\n const data = Hex.slice(serialized, 1)\n const dataSize = Hex.size(data)\n\n if (typeId === serializedP256Type) {\n // P256: 32 (r) + 32 (s) + 32 (pubKeyX) + 32 (pubKeyY) + 1 (prehash) = 129 bytes\n if (dataSize !== 129)\n throw new InvalidSerializedError({\n reason: `Invalid P256 signature envelope size: expected 129 bytes, got ${dataSize} bytes`,\n serialized,\n })\n\n return {\n publicKey: {\n prefix: 4,\n x: Hex.toBigInt(Hex.slice(data, 64, 96)),\n y: Hex.toBigInt(Hex.slice(data, 96, 128)),\n },\n prehash: Hex.toNumber(Hex.slice(data, 128, 129)) !== 0,\n signature: {\n r: Hex.toBigInt(Hex.slice(data, 0, 32)),\n s: Hex.toBigInt(Hex.slice(data, 32, 64)),\n },\n type: 'p256',\n } satisfies P256\n }\n\n if (typeId === serializedWebAuthnType) {\n // WebAuthn: variable (webauthnData) + 32 (r) + 32 (s) + 32 (pubKeyX) + 32 (pubKeyY)\n // Minimum: 128 bytes (at least some authenticator data + signature components)\n if (dataSize < 128)\n throw new InvalidSerializedError({\n reason: `Invalid WebAuthn signature envelope size: expected at least 128 bytes, got ${dataSize} bytes`,\n serialized,\n })\n\n const webauthnDataSize = dataSize - 128\n const webauthnData = Hex.slice(data, 0, webauthnDataSize)\n\n // Parse webauthnData into authenticatorData and clientDataJSON\n // According to the Rust code, it's authenticatorData || clientDataJSON\n // We need to find the split point (minimum authenticatorData is 37 bytes)\n let authenticatorData: Hex.Hex | undefined\n let clientDataJSON: string | undefined\n\n // Try to find the JSON start (clientDataJSON should start with '{')\n for (let split = 37; split < webauthnDataSize; split++) {\n const potentialJson = Hex.toString(Hex.slice(webauthnData, split))\n if (potentialJson.startsWith('{') && potentialJson.endsWith('}')) {\n try {\n JSON.parse(potentialJson)\n authenticatorData = Hex.slice(webauthnData, 0, split)\n clientDataJSON = potentialJson\n break\n } catch {}\n }\n }\n\n if (!authenticatorData || !clientDataJSON)\n throw new InvalidSerializedError({\n reason:\n 'Unable to parse WebAuthn metadata: could not extract valid authenticatorData and clientDataJSON',\n serialized,\n })\n\n return {\n publicKey: {\n prefix: 4,\n x: Hex.toBigInt(\n Hex.slice(data, webauthnDataSize + 64, webauthnDataSize + 96),\n ),\n y: Hex.toBigInt(\n Hex.slice(data, webauthnDataSize + 96, webauthnDataSize + 128),\n ),\n },\n metadata: {\n authenticatorData,\n clientDataJSON,\n },\n signature: {\n r: Hex.toBigInt(\n Hex.slice(data, webauthnDataSize, webauthnDataSize + 32),\n ),\n s: Hex.toBigInt(\n Hex.slice(data, webauthnDataSize + 32, webauthnDataSize + 64),\n ),\n },\n type: 'webAuthn',\n } satisfies WebAuthn\n }\n\n if (\n typeId === serializedKeychainType ||\n typeId === serializedKeychainV2Type\n ) {\n const userAddress = Hex.slice(data, 0, 20)\n const inner = deserialize(Hex.slice(data, 20))\n\n return {\n userAddress,\n inner,\n type: 'keychain',\n version: typeId === serializedKeychainV2Type ? 'v2' : 'v1',\n } satisfies Keychain\n }\n\n throw new InvalidSerializedError({\n reason: `Unknown signature type identifier: ${typeId}. Expected ${serializedP256Type} (P256), ${serializedWebAuthnType} (WebAuthn), ${serializedKeychainType} (Keychain V1), or ${serializedKeychainV2Type} (Keychain V2)`,\n serialized,\n })\n}\n\n/**\n * Coerces a value to a signature envelope.\n *\n * Accepts either a serialized hex string or an existing signature envelope object.\n * Use this to wrap raw signatures from {@link ox#Secp256k1.(sign:function)}, {@link ox#P256.(sign:function)},\n * {@link ox#WebCryptoP256.(sign:function)}, or {@link ox#WebAuthnP256.(sign:function)} into the envelope format\n * required by Tempo transactions.\n *\n * [Signature Types](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#signature-types)\n *\n * @example\n * ### Secp256k1\n *\n * Standard Ethereum ECDSA signature using the secp256k1 curve.\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const envelope = SignatureEnvelope.from(signature)\n * ```\n *\n * @example\n * ### P256\n *\n * ECDSA signature using the P-256 (secp256r1) curve. Requires embedding the\n * public key.\n *\n * ```ts twoslash\n * import { P256 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const { privateKey, publicKey } = P256.createKeyPair()\n * const signature = P256.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const envelope = SignatureEnvelope.from({\n * signature,\n * publicKey,\n * })\n * ```\n *\n * @example\n * ### P256 (WebCrypto)\n *\n * When using WebCrypto keys, `prehash` must be `true` since WebCrypto always\n * SHA256 hashes the digest before signing.\n *\n * ```ts twoslash\n * // @noErrors\n * import { WebCryptoP256 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const { privateKey, publicKey } = await WebCryptoP256.createKeyPair()\n * const signature = await WebCryptoP256.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const envelope = SignatureEnvelope.from({\n * signature,\n * publicKey,\n * prehash: true,\n * })\n * ```\n *\n * @example\n * ### WebAuthn\n *\n * Passkey-based signature using WebAuthn. Includes authenticator metadata\n * (authenticatorData and clientDataJSON) along with the P-256 signature and\n * public key.\n *\n * ```ts twoslash\n * // @noErrors\n * import { WebAuthnP256 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const credential = await WebAuthnP256.createCredential({\n * name: 'Example',\n * })\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * challenge: '0xdeadbeef',\n * credentialId: credential.id,\n * })\n *\n * const envelope = SignatureEnvelope.from({\n * signature,\n * publicKey: credential.publicKey,\n * metadata,\n * })\n * ```\n *\n * @example\n * ### Keychain\n *\n * Wraps another signature type with a user address, used for delegated signing\n * via access keys on behalf of a root account.\n *\n * ```ts twoslash\n * import { Secp256k1 } from 'ox'\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * const signature = Secp256k1.sign({ payload: '0xdeadbeef', privateKey })\n *\n * const envelope = SignatureEnvelope.from({\n * userAddress: '0x1234567890123456789012345678901234567890',\n * inner: SignatureEnvelope.from(signature),\n * })\n * ```\n *\n * @param value - The value to coerce (either a hex string or signature envelope).\n * @returns The signature envelope.\n */\nexport function from<const value extends from.Value>(\n value: value | from.Value,\n options?: from.Options | undefined,\n): from.ReturnValue<value> {\n if (typeof value === 'string') return deserialize(value) as never\n\n if (\n typeof value === 'object' &&\n value !== null &&\n 'r' in value &&\n 's' in value &&\n 'yParity' in value\n )\n return { signature: value, type: 'secp256k1' } as never\n\n const type = getType(value)\n return {\n ...value,\n ...(type === 'p256' ? { prehash: value.prehash } : {}),\n ...(type === 'keychain'\n ? {\n ...(!(\n typeof value === 'object' &&\n value !== null &&\n 'version' in value &&\n value.version\n )\n ? { version: 'v2' }\n : {}),\n ...(!(typeof value === 'object' && 'keyId' in value && value.keyId)\n ? (() => {\n const inner = (value as Keychain).inner\n if (inner.type === 'p256' || inner.type === 'webAuthn')\n return { keyId: Address.fromPublicKey(inner.publicKey) }\n if (inner.type === 'secp256k1' && options?.payload)\n return {\n keyId: Address.fromPublicKey(\n ox_Secp256k1.recoverPublicKey({\n payload: options.payload,\n signature: inner.signature,\n }),\n ),\n }\n return {}\n })()\n : {}),\n }\n : {}),\n type,\n } as never\n}\n\nexport declare namespace from {\n type Options = {\n /** Payload that was signed. Used to recover `keyId` for keychain envelopes with secp256k1 inner signatures. */\n payload?: Hex.Hex | Bytes.Bytes | undefined\n }\n\n type Value =\n | UnionPartialBy<SignatureEnvelope, 'prehash' | 'type'>\n | Secp256k1Flat\n | Serialized\n\n type ReturnValue<value extends Value> = Compute<\n OneOf<\n value extends Serialized\n ? SignatureEnvelope\n : value extends Secp256k1Flat\n ? Secp256k1\n : IsNarrowable<value, SignatureEnvelope> extends true\n ? SignatureEnvelope\n : Assign<\n value,\n {\n readonly type: GetType<value>\n } & (GetType<value> extends 'keychain'\n ? { keyId?: Address.Address | undefined }\n : {})\n >\n >\n >\n}\n\n/**\n * Converts an RPC-formatted signature envelope to a typed signature envelope.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const envelope = SignatureEnvelope.fromRpc({\n * r: '0x0',\n * s: '0x0',\n * yParity: '0x0',\n * type: 'secp256k1',\n * })\n * ```\n *\n * @param envelope - The RPC signature envelope to convert.\n * @returns The signature envelope with bigint values.\n */\nexport function fromRpc(envelope: SignatureEnvelopeRpc): SignatureEnvelope {\n if (envelope.type === 'secp256k1')\n return {\n signature: Signature.fromRpc(envelope),\n type: 'secp256k1',\n }\n\n if (envelope.type === 'p256') {\n return {\n prehash: envelope.preHash,\n publicKey: {\n prefix: 4,\n x: Hex.toBigInt(envelope.pubKeyX),\n y: Hex.toBigInt(envelope.pubKeyY),\n },\n signature: {\n r: Hex.toBigInt(envelope.r),\n s: Hex.toBigInt(envelope.s),\n },\n type: 'p256',\n }\n }\n\n if (envelope.type === 'webAuthn') {\n const webauthnData = envelope.webauthnData\n const webauthnDataSize = Hex.size(webauthnData)\n\n // Parse webauthnData into authenticatorData and clientDataJSON\n let authenticatorData: Hex.Hex | undefined\n let clientDataJSON: string | undefined\n\n // Try to find the JSON start (clientDataJSON should start with '{')\n for (let split = 37; split < webauthnDataSize; split++) {\n const potentialJson = Hex.toString(Hex.slice(webauthnData, split))\n if (potentialJson.startsWith('{') && potentialJson.endsWith('}')) {\n try {\n JSON.parse(potentialJson)\n authenticatorData = Hex.slice(webauthnData, 0, split)\n clientDataJSON = potentialJson\n break\n } catch {}\n }\n }\n\n if (!authenticatorData || !clientDataJSON)\n throw new InvalidSerializedError({\n reason:\n 'Unable to parse WebAuthn metadata: could not extract valid authenticatorData and clientDataJSON',\n serialized: webauthnData,\n })\n\n return {\n metadata: {\n authenticatorData,\n clientDataJSON,\n },\n publicKey: {\n prefix: 4,\n x: Hex.toBigInt(envelope.pubKeyX),\n y: Hex.toBigInt(envelope.pubKeyY),\n },\n signature: {\n r: Hex.toBigInt(envelope.r),\n s: Hex.toBigInt(envelope.s),\n },\n type: 'webAuthn',\n }\n }\n\n if (\n envelope.type === 'keychain' ||\n ('userAddress' in envelope && 'signature' in envelope)\n )\n return {\n type: 'keychain',\n userAddress: envelope.userAddress,\n inner: fromRpc(envelope.signature),\n ...(envelope.keyId ? { keyId: envelope.keyId } : {}),\n ...(envelope.version ? { version: envelope.version } : {}),\n }\n\n throw new CoercionError({ envelope })\n}\n\nexport declare namespace fromRpc {\n type ErrorType =\n | CoercionError\n | InvalidSerializedError\n | Signature.fromRpc.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Determines the signature type of an envelope.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const type = SignatureEnvelope.getType({\n * signature: { r: 0n, s: 0n, yParity: 0 },\n * })\n * // @log: 'secp256k1'\n * ```\n *\n * @param envelope - The signature envelope to inspect.\n * @returns The signature type ('secp256k1', 'p256', or 'webAuthn').\n * @throws `CoercionError` if the envelope type cannot be determined.\n */\nexport function getType<\n envelope extends\n | PartialBy<SignatureEnvelope, 'type'>\n | Secp256k1Flat\n | unknown,\n>(envelope: envelope): GetType<envelope> {\n if (typeof envelope !== 'object' || envelope === null)\n throw new CoercionError({ envelope })\n\n if ('type' in envelope && envelope.type) return envelope.type as never\n\n // Detect secp256k1 signature (backwards compatibility: also support flat structure)\n if (\n 'signature' in envelope &&\n !('publicKey' in envelope) &&\n typeof envelope.signature === 'object' &&\n envelope.signature !== null &&\n 'r' in envelope.signature &&\n 's' in envelope.signature &&\n 'yParity' in envelope.signature\n )\n return 'secp256k1' as never\n\n // Detect secp256k1 signature (flat structure)\n if ('r' in envelope && 's' in envelope && 'yParity' in envelope)\n return 'secp256k1' as never\n\n // Detect P256 signature\n if (\n 'signature' in envelope &&\n 'prehash' in envelope &&\n 'publicKey' in envelope &&\n typeof envelope.prehash === 'boolean'\n )\n return 'p256' as never\n\n // Detect WebAuthn signature\n if (\n 'signature' in envelope &&\n 'metadata' in envelope &&\n 'publicKey' in envelope\n )\n return 'webAuthn' as never\n\n // Detect Keychain signature\n if ('userAddress' in envelope && 'inner' in envelope)\n return 'keychain' as never\n\n throw new CoercionError({\n envelope,\n })\n}\n\n/**\n * Serializes a signature envelope to a hex-encoded string.\n *\n * Wire format:\n * - secp256k1: 65 bytes (no type prefix, for backward compatibility)\n * - P256: `0x01` + r (32) + s (32) + pubKeyX (32) + pubKeyY (32) + prehash (1) = 130 bytes\n * - WebAuthn: `0x02` + webauthnData (variable) + r (32) + s (32) + pubKeyX (32) + pubKeyY (32)\n * - Keychain V1: `0x03` + userAddress (20) + inner signature (recursive)\n * - Keychain V2: `0x04` + userAddress (20) + inner signature (recursive)\n *\n * [Signature Types](https://docs.tempo.xyz/protocol/transactions/spec-tempo-transaction#signature-types)\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const serialized = SignatureEnvelope.serialize({\n * signature: { r: 0n, s: 0n, yParity: 0 },\n * type: 'secp256k1',\n * })\n * ```\n *\n * @param envelope - The signature envelope to serialize.\n * @returns The hex-encoded serialized signature.\n * @throws `CoercionError` if the envelope cannot be serialized.\n */\nexport function serialize(\n envelope: UnionPartialBy<SignatureEnvelope, 'prehash'>,\n options: serialize.Options = {},\n): Serialized {\n const type = getType(envelope)\n\n // Backward compatibility: no type identifier for secp256k1\n if (type === 'secp256k1') {\n const secp256k1 = envelope as Secp256k1\n return Hex.concat(\n Signature.toHex(secp256k1.signature),\n options.magic ? magicBytes : '0x',\n )\n }\n\n if (type === 'p256') {\n const p256 = envelope as P256\n // Format: 1 byte (type) + 32 (r) + 32 (s) + 32 (pubKeyX) + 32 (pubKeyY) + 1 (prehash)\n return Hex.concat(\n serializedP256Type,\n Hex.fromNumber(p256.signature.r, { size: 32 }),\n Hex.fromNumber(p256.signature.s, { size: 32 }),\n Hex.fromNumber(p256.publicKey.x, { size: 32 }),\n Hex.fromNumber(p256.publicKey.y, { size: 32 }),\n Hex.fromNumber(p256.prehash ? 1 : 0, { size: 1 }),\n options.magic ? magicBytes : '0x',\n )\n }\n\n if (type === 'webAuthn') {\n const webauthn = envelope as WebAuthn\n // Format: 1 byte (type) + variable (authenticatorData || clientDataJSON) + 32 (r) + 32 (s) + 32 (pubKeyX) + 32 (pubKeyY)\n const webauthnData = Hex.concat(\n webauthn.metadata.authenticatorData,\n Hex.fromString(webauthn.metadata.clientDataJSON),\n )\n\n return Hex.concat(\n serializedWebAuthnType,\n webauthnData,\n Hex.fromNumber(webauthn.signature.r, { size: 32 }),\n Hex.fromNumber(webauthn.signature.s, { size: 32 }),\n Hex.fromNumber(webauthn.publicKey.x, { size: 32 }),\n Hex.fromNumber(webauthn.publicKey.y, { size: 32 }),\n options.magic ? magicBytes : '0x',\n )\n }\n\n if (type === 'keychain') {\n const keychain = envelope as Keychain\n const keychainTypeId =\n keychain.version === 'v1'\n ? serializedKeychainType\n : serializedKeychainV2Type\n return Hex.concat(\n keychainTypeId,\n keychain.userAddress,\n serialize(keychain.inner),\n options.magic ? magicBytes : '0x',\n )\n }\n\n throw new CoercionError({ envelope })\n}\n\nexport declare namespace serialize {\n type Options = {\n /**\n * Whether to serialize the signature envelope with the Tempo magic identifier.\n * This is useful for being able to distinguish between Tempo and non-Tempo (e.g. ERC-1271) signatures.\n */\n magic?: boolean | undefined\n }\n}\n\n/**\n * Converts a signature envelope to RPC format.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const rpc = SignatureEnvelope.toRpc({\n * signature: { r: 0n, s: 0n, yParity: 0 },\n * type: 'secp256k1',\n * })\n * ```\n *\n * @param envelope - The signature envelope to convert.\n * @returns The RPC signature envelope with hex values.\n */\nexport function toRpc(envelope: SignatureEnvelope): SignatureEnvelopeRpc {\n const type = getType(envelope)\n\n if (type === 'secp256k1') {\n const secp256k1 = envelope as Secp256k1\n return {\n ...Signature.toRpc(secp256k1.signature),\n type: 'secp256k1',\n }\n }\n\n if (type === 'p256') {\n const p256 = envelope as P256\n return {\n preHash: p256.prehash,\n pubKeyX: Hex.fromNumber(p256.publicKey.x, { size: 32 }),\n pubKeyY: Hex.fromNumber(p256.publicKey.y, { size: 32 }),\n r: Hex.fromNumber(p256.signature.r, { size: 32 }),\n s: Hex.fromNumber(p256.signature.s, { size: 32 }),\n type: 'p256',\n }\n }\n\n if (type === 'webAuthn') {\n const webauthn = envelope as WebAuthn\n const webauthnData = Hex.concat(\n webauthn.metadata.authenticatorData,\n Hex.fromString(webauthn.metadata.clientDataJSON),\n )\n\n return {\n pubKeyX: Hex.fromNumber(webauthn.publicKey.x, { size: 32 }),\n pubKeyY: Hex.fromNumber(webauthn.publicKey.y, { size: 32 }),\n r: Hex.fromNumber(webauthn.signature.r, { size: 32 }),\n s: Hex.fromNumber(webauthn.signature.s, { size: 32 }),\n type: 'webAuthn',\n webauthnData,\n }\n }\n\n if (type === 'keychain') {\n const keychain = envelope as Keychain\n return {\n type: 'keychain',\n userAddress: keychain.userAddress,\n signature: toRpc(keychain.inner),\n ...(keychain.keyId ? { keyId: keychain.keyId } : {}),\n ...(keychain.version ? { version: keychain.version } : {}),\n }\n }\n\n throw new CoercionError({ envelope })\n}\n\nexport declare namespace toRpc {\n type ErrorType =\n | CoercionError\n | Signature.toRpc.ErrorType\n | Errors.GlobalErrorType\n}\n\n/**\n * Validates a signature envelope. Returns `true` if the envelope is valid, `false` otherwise.\n *\n * @example\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n *\n * const valid = SignatureEnvelope.validate({\n * signature: { r: 0n, s: 0n, yParity: 0 },\n * type: 'secp256k1',\n * })\n * // @log: true\n * ```\n *\n * @param envelope - The signature envelope to validate.\n * @returns `true` if valid, `false` otherwise.\n */\nexport function validate(\n envelope: PartialBy<SignatureEnvelope, 'type'>,\n): boolean {\n try {\n assert(envelope)\n return true\n } catch {\n return false\n }\n}\n\nexport declare namespace validate {\n type ErrorType = Errors.GlobalErrorType\n}\n\n/**\n * Verifies a signature envelope against a digest/payload.\n *\n * Supports `secp256k1`, `p256`, and `webAuthn` signature types.\n *\n * :::warning\n * `keychain` signatures are not supported and will throw an error.\n * :::\n *\n * @example\n * ### Secp256k1\n *\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n * import { Secp256k1 } from 'ox'\n *\n * const privateKey = Secp256k1.randomPrivateKey()\n * const publicKey = Secp256k1.getPublicKey({ privateKey })\n * const payload = '0xdeadbeef'\n *\n * const signature = Secp256k1.sign({ payload, privateKey })\n * const envelope = SignatureEnvelope.from(signature)\n *\n * const valid = SignatureEnvelope.verify(envelope, {\n * payload,\n * publicKey,\n * })\n * // @log: true\n * ```\n *\n * @example\n * ### P256\n *\n * For P256 signatures, the `address` or `publicKey` must match the embedded\n * public key in the signature envelope.\n *\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n * import { P256 } from 'ox'\n *\n * const privateKey = P256.randomPrivateKey()\n * const publicKey = P256.getPublicKey({ privateKey })\n * const payload = '0xdeadbeef'\n *\n * const signature = P256.sign({ payload, privateKey })\n * const envelope = SignatureEnvelope.from({ prehash: false, publicKey, signature })\n *\n * const valid = SignatureEnvelope.verify(envelope, {\n * payload,\n * publicKey,\n * })\n * // @log: true\n * ```\n *\n * @example\n * ### WebCryptoP256\n *\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n * import { WebCryptoP256 } from 'ox'\n *\n * const { privateKey, publicKey } = await WebCryptoP256.createKeyPair()\n * const payload = '0xdeadbeef'\n *\n * const signature = await WebCryptoP256.sign({ payload, privateKey })\n * const envelope = SignatureEnvelope.from({ prehash: true, publicKey, signature })\n *\n * const valid = SignatureEnvelope.verify(envelope, {\n * payload,\n * publicKey,\n * })\n * // @log: true\n * ```\n *\n * @example\n * ### WebAuthnP256\n *\n * ```ts twoslash\n * import { SignatureEnvelope } from 'ox/tempo'\n * import { WebAuthnP256 } from 'ox'\n *\n * const credential = await WebAuthnP256.createCredential({ name: 'Example' })\n * const payload = '0xdeadbeef'\n *\n * const { metadata, signature } = await WebAuthnP256.sign({\n * challenge: payload,\n * credentialId: credential.id,\n * })\n * const envelope = SignatureEnvelope.from({\n * metadata,\n * signature,\n * publicKey: credential.publicKey,\n * })\n *\n * const valid = SignatureEnvelope.verify(envelope, {\n * payload,\n * publicKey: credential.publicKey,\n * })\n * // @log: true\n * ```\n *\n * @param parameters - Verification parameters.\n * @returns `true` if the signature is valid, `false` otherwise.\n */\nexport function verify(\n signature: SignatureEnvelope,\n parameters: verify.Parameters,\n): boolean {\n const { payload } = parameters\n\n const address = (() => {\n if (parameters.address) return parameters.address\n if (parameters.publicKey) return Address.fromPublicKey(parameters.publicKey)\n return undefined\n })()\n if (!address) return false\n\n const envelope = from(signature)\n\n if (envelope.type === 'secp256k1') {\n if (!address) return false\n return ox_Secp256k1.verify({\n address,\n payload,\n signature: envelope.signature,\n })\n }\n\n if (envelope.type === 'p256') {\n const envelopeAddress = Address.fromPublicKey(envelope.publicKey)\n if (!Address.isEqual(envelopeAddress, address)) return false\n return ox_P256.verify({\n hash: envelope.prehash,\n publicKey: envelope.publicKey,\n payload,\n signature: envelope.signature,\n })\n }\n\n if (envelope.type === 'webAuthn') {\n const envelopeAddress = Address.fromPublicKey(envelope.publicKey)\n if (!Address.isEqual(envelopeAddress, address)) return false\n return ox_WebAuthnP256.verify({\n challenge: Hex.from(payload),\n metadata: envelope.metadata,\n publicKey: envelope.publicKey,\n signature: envelope.signature,\n })\n }\n\n throw new VerificationError(\n `Unable to verify signature envelope of type \"${envelope.type}\".`,\n )\n}\n\nexport declare namespace verify {\n type Parameters = {\n /** Payload that was signed. */\n payload: Hex.Hex | Bytes.Bytes\n } & OneOf<\n | {\n /** Public key that signed the payload. */\n publicKey: PublicKey.PublicKey\n }\n | {\n /** Address that signed the payload. */\n address: Address.Address\n }\n >\n}\n\n/**\n * Error thrown when a signature envelope cannot be coerced to a valid type.\n */\nexport class CoercionError extends Errors.BaseError {\n override readonly name = 'SignatureEnvelope.CoercionError'\n constructor({ envelope }: { envelope: unknown }) {\n super(\n `Unable to coerce value (\\`${Json.stringify(envelope)}\\`) to a valid signature envelope.`,\n )\n }\n}\n\n/**\n * Error thrown when a signature envelope is missing required properties.\n */\nexport class MissingPropertiesError extends Errors.BaseError {\n override readonly name = 'SignatureEnvelope.MissingPropertiesError'\n constructor({\n envelope,\n missing,\n type,\n }: {\n envelope: unknown\n missing: string[]\n type: Type\n }) {\n super(\n `Signature envelope of type \"${type}\" is missing required properties: ${missing.map((m) => `\\`${m}\\``).join(', ')}.\\n\\nProvided: ${Json.stringify(envelope)}`,\n )\n }\n}\n\n/**\n * Error thrown when a serialized signature envelope cannot be deserialized.\n */\nexport class InvalidSerializedError extends Errors.BaseError {\n override readonly name = 'SignatureEnvelope.InvalidSerializedError'\n constructor({\n reason,\n serialized,\n }: {\n reason: string\n serialized: Hex.Hex\n }) {\n super(`Unable to deserialize signature envelope: ${reason}`, {\n metaMessages: [`Serialized: ${serialized}`],\n })\n }\n}\n\n/**\n * Error thrown when a signature envelope fails to verify.\n */\nexport class VerificationError extends Errors.BaseError {\n override readonly name = 'SignatureEnvelope.VerificationError'\n}\n","import { type Address, Signature } from 'ox'\nimport { SignatureEnvelope } from 'ox/tempo'\nimport type { Account, Client, Hex } from 'viem'\nimport { recoverTypedDataAddress } from 'viem'\nimport { signTypedData } from 'viem/actions'\n\nimport * as TempoAddress from '../internal/address.js'\nimport type { SignedVoucher, Voucher } from './Types.js'\n\n/** Must match the on-chain TempoStreamChannel DOMAIN_SEPARATOR name. */\nconst DOMAIN_NAME = 'Tempo Stream Channel'\n/** Must match the on-chain TempoStreamChannel DOMAIN_SEPARATOR version. */\nconst DOMAIN_VERSION = '1'\n\n/**\n * EIP-712 domain for voucher signing.\n */\nfunction getVoucherDomain(escrowContract: Address.Address, chainId: number) {\n return {\n name: DOMAIN_NAME,\n version: DOMAIN_VERSION,\n chainId,\n verifyingContract: escrowContract,\n } as const\n}\n\n/**\n * EIP-712 types for voucher signing.\n * Matches @tempo/stream-channels/voucher and on-chain VOUCHER_TYPEHASH.\n */\nconst voucherTypes = {\n Voucher: [\n { name: 'channelId', type: 'bytes32' },\n { name: 'cumulativeAmount', type: 'uint128' },\n ],\n} as const\n\n/**\n * Sign a voucher with an account.\n */\nexport async function signVoucher(\n client: Client,\n account: Account,\n message: Voucher,\n escrowContract: Address.Address,\n chainId: number,\n authorizedSigner?: Address.Address | undefined,\n): Promise<Hex> {\n const signature = await signTypedData(client, {\n account,\n domain: getVoucherDomain(escrowContract, chainId),\n types: voucherTypes,\n primaryType: 'Voucher',\n message: {\n channelId: message.channelId,\n cumulativeAmount: message.cumulativeAmount,\n },\n })\n\n // When a separate authorizedSigner is used (e.g. access key), unwrap the\n // keychain envelope — the escrow contract verifies raw ECDSA signatures\n // against authorizedSigner, not keychain-wrapped ones.\n // TODO: when TIP-1020 is implemented, we can remove this.\n if (authorizedSigner) {\n try {\n const envelope = SignatureEnvelope.from(signature as SignatureEnvelope.Serialized)\n if (envelope.type === 'keychain' && envelope.inner.type === 'secp256k1')\n return Signature.toHex(envelope.inner.signature)\n } catch {}\n }\n\n return signature\n}\n\n/**\n * Verify a voucher signature matches the expected signer.\n *\n * Only accepts raw secp256k1 signatures — the escrow contract verifies\n * via ecrecover. Keychain, p256, and webAuthn signatures are rejected.\n */\nexport async function verifyVoucher(\n escrowContract: Address.Address,\n chainId: number,\n voucher: SignedVoucher,\n expectedSigner: Address.Address,\n): Promise<boolean> {\n try {\n const domain = getVoucherDomain(escrowContract, chainId)\n const message = {\n channelId: voucher.channelId,\n cumulativeAmount: voucher.cumulativeAmount,\n }\n\n const envelope = SignatureEnvelope.from(voucher.signature)\n\n // Reject keychain signatures — the escrow contract verifies raw ECDSA\n // signatures against authorizedSigner, not keychain-wrapped ones.\n if (envelope.type === 'keychain') return false\n\n // Reject non-secp256k1 signatures (p256, webAuthn) — the escrow contract\n // only supports ecrecover-based verification.\n // TODO: remove this once TIP-1020 is implemented\n if (envelope.type !== 'secp256k1') return false\n\n const signer = await recoverTypedDataAddress({\n domain,\n types: voucherTypes,\n primaryType: 'Voucher',\n message,\n signature: voucher.signature,\n })\n return TempoAddress.isEqual(signer, expectedSigner)\n } catch {\n return false\n }\n}\n\n/**\n * Parse a voucher from credential payload.\n */\nexport function parseVoucherFromPayload(\n channelId: Hex,\n cumulativeAmount: string,\n signature: Hex,\n): SignedVoucher {\n return {\n channelId,\n cumulativeAmount: BigInt(cumulativeAmount),\n signature,\n }\n}\n","import { AbiParameters, Hash } from 'ox'\nimport type * as Hex from 'ox/Hex'\n\n/**\n * Computes a channel ID from its parameters.\n *\n * Mirrors the onchain `computeChannelId` function: `keccak256(abi.encode(payer, payee, token, salt, authorizedSigner, escrowContract, chainId))`.\n */\nexport function computeId(parameters: computeId.Parameters): Hex.Hex {\n const encoded = AbiParameters.encode(\n AbiParameters.from([\n 'address payer',\n 'address payee',\n 'address token',\n 'bytes32 salt',\n 'address authorizedSigner',\n 'address escrowContract',\n 'uint256 chainId',\n ]),\n [\n parameters.payer,\n parameters.payee,\n parameters.token,\n parameters.salt,\n parameters.authorizedSigner,\n parameters.escrowContract,\n BigInt(parameters.chainId),\n ],\n )\n return Hash.keccak256(encoded)\n}\n\nexport declare namespace computeId {\n type Parameters = {\n /** Address authorized to sign vouchers on behalf of the payer. */\n authorizedSigner: Hex.Hex\n /** Chain ID of the network the escrow contract is deployed on. */\n chainId: number\n /** Address of the escrow contract. */\n escrowContract: Hex.Hex\n /** Address of the payee (recipient). */\n payee: Hex.Hex\n /** Address of the payer (sender). */\n payer: Hex.Hex\n /** Unique salt to differentiate channels with the same parameters. */\n salt: Hex.Hex\n /** Address of the token used for payment. */\n token: Hex.Hex\n }\n}\n","export const escrowAbi = [\n {\n type: 'function',\n name: 'CLOSE_GRACE_PERIOD',\n inputs: [],\n outputs: [\n {\n name: '',\n type: 'uint64',\n internalType: 'uint64',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'VOUCHER_TYPEHASH',\n inputs: [],\n outputs: [\n {\n name: '',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'channels',\n inputs: [\n {\n name: '',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n outputs: [\n {\n name: 'finalized',\n type: 'bool',\n internalType: 'bool',\n },\n {\n name: 'closeRequestedAt',\n type: 'uint64',\n internalType: 'uint64',\n },\n {\n name: 'payer',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'token',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'authorizedSigner',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'deposit',\n type: 'uint128',\n internalType: 'uint128',\n },\n {\n name: 'settled',\n type: 'uint128',\n internalType: 'uint128',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'close',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n {\n name: 'cumulativeAmount',\n type: 'uint128',\n internalType: 'uint128',\n },\n {\n name: 'signature',\n type: 'bytes',\n internalType: 'bytes',\n },\n ],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n name: 'computeChannelId',\n inputs: [\n {\n name: 'payer',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'token',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'salt',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n {\n name: 'authorizedSigner',\n type: 'address',\n internalType: 'address',\n },\n ],\n outputs: [\n {\n name: '',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'domainSeparator',\n inputs: [],\n outputs: [\n {\n name: '',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'eip712Domain',\n inputs: [],\n outputs: [\n {\n name: 'fields',\n type: 'bytes1',\n internalType: 'bytes1',\n },\n {\n name: 'name',\n type: 'string',\n internalType: 'string',\n },\n {\n name: 'version',\n type: 'string',\n internalType: 'string',\n },\n {\n name: 'chainId',\n type: 'uint256',\n internalType: 'uint256',\n },\n {\n name: 'verifyingContract',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'salt',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n {\n name: 'extensions',\n type: 'uint256[]',\n internalType: 'uint256[]',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'getChannel',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n outputs: [\n {\n name: '',\n type: 'tuple',\n internalType: 'struct TempoStreamChannel.Channel',\n components: [\n {\n name: 'finalized',\n type: 'bool',\n internalType: 'bool',\n },\n {\n name: 'closeRequestedAt',\n type: 'uint64',\n internalType: 'uint64',\n },\n {\n name: 'payer',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'token',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'authorizedSigner',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'deposit',\n type: 'uint128',\n internalType: 'uint128',\n },\n {\n name: 'settled',\n type: 'uint128',\n internalType: 'uint128',\n },\n ],\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'getChannelsBatch',\n inputs: [\n {\n name: 'channelIds',\n type: 'bytes32[]',\n internalType: 'bytes32[]',\n },\n ],\n outputs: [\n {\n name: 'channelStates',\n type: 'tuple[]',\n internalType: 'struct TempoStreamChannel.Channel[]',\n components: [\n {\n name: 'finalized',\n type: 'bool',\n internalType: 'bool',\n },\n {\n name: 'closeRequestedAt',\n type: 'uint64',\n internalType: 'uint64',\n },\n {\n name: 'payer',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'token',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'authorizedSigner',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'deposit',\n type: 'uint128',\n internalType: 'uint128',\n },\n {\n name: 'settled',\n type: 'uint128',\n internalType: 'uint128',\n },\n ],\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'getVoucherDigest',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n {\n name: 'cumulativeAmount',\n type: 'uint128',\n internalType: 'uint128',\n },\n ],\n outputs: [\n {\n name: '',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n stateMutability: 'view',\n },\n {\n type: 'function',\n name: 'open',\n inputs: [\n {\n name: 'payee',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'token',\n type: 'address',\n internalType: 'address',\n },\n {\n name: 'deposit',\n type: 'uint128',\n internalType: 'uint128',\n },\n {\n name: 'salt',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n {\n name: 'authorizedSigner',\n type: 'address',\n internalType: 'address',\n },\n ],\n outputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n name: 'requestClose',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n name: 'settle',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n {\n name: 'cumulativeAmount',\n type: 'uint128',\n internalType: 'uint128',\n },\n {\n name: 'signature',\n type: 'bytes',\n internalType: 'bytes',\n },\n ],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n name: 'topUp',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n {\n name: 'additionalDeposit',\n type: 'uint256',\n internalType: 'uint256',\n },\n ],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'function',\n name: 'withdraw',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n internalType: 'bytes32',\n },\n ],\n outputs: [],\n stateMutability: 'nonpayable',\n },\n {\n type: 'event',\n name: 'ChannelClosed',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n indexed: true,\n internalType: 'bytes32',\n },\n {\n name: 'payer',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'settledToPayee',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n {\n name: 'refundedToPayer',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n ],\n anonymous: false,\n },\n {\n type: 'event',\n name: 'ChannelExpired',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n indexed: true,\n internalType: 'bytes32',\n },\n {\n name: 'payer',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n ],\n anonymous: false,\n },\n {\n type: 'event',\n name: 'ChannelOpened',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n indexed: true,\n internalType: 'bytes32',\n },\n {\n name: 'payer',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'token',\n type: 'address',\n indexed: false,\n internalType: 'address',\n },\n {\n name: 'authorizedSigner',\n type: 'address',\n indexed: false,\n internalType: 'address',\n },\n {\n name: 'salt',\n type: 'bytes32',\n indexed: false,\n internalType: 'bytes32',\n },\n {\n name: 'deposit',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n ],\n anonymous: false,\n },\n {\n type: 'event',\n name: 'CloseRequestCancelled',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n indexed: true,\n internalType: 'bytes32',\n },\n {\n name: 'payer',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n ],\n anonymous: false,\n },\n {\n type: 'event',\n name: 'CloseRequested',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n indexed: true,\n internalType: 'bytes32',\n },\n {\n name: 'payer',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'closeGraceEnd',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n ],\n anonymous: false,\n },\n {\n type: 'event',\n name: 'Settled',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n indexed: true,\n internalType: 'bytes32',\n },\n {\n name: 'payer',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'cumulativeAmount',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n {\n name: 'deltaPaid',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n {\n name: 'newSettled',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n ],\n anonymous: false,\n },\n {\n type: 'event',\n name: 'TopUp',\n inputs: [\n {\n name: 'channelId',\n type: 'bytes32',\n indexed: true,\n internalType: 'bytes32',\n },\n {\n name: 'payer',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'payee',\n type: 'address',\n indexed: true,\n internalType: 'address',\n },\n {\n name: 'additionalDeposit',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n {\n name: 'newDeposit',\n type: 'uint256',\n indexed: false,\n internalType: 'uint256',\n },\n ],\n anonymous: false,\n },\n {\n type: 'error',\n name: 'AmountExceedsDeposit',\n inputs: [],\n },\n {\n type: 'error',\n name: 'AmountNotIncreasing',\n inputs: [],\n },\n {\n type: 'error',\n name: 'ChannelAlreadyExists',\n inputs: [],\n },\n {\n type: 'error',\n name: 'ChannelFinalized',\n inputs: [],\n },\n {\n type: 'error',\n name: 'ChannelNotFound',\n inputs: [],\n },\n {\n type: 'error',\n name: 'CloseNotReady',\n inputs: [],\n },\n {\n type: 'error',\n name: 'DepositOverflow',\n inputs: [],\n },\n {\n type: 'error',\n name: 'InvalidPayee',\n inputs: [],\n },\n {\n type: 'error',\n name: 'InvalidSignature',\n inputs: [],\n },\n {\n type: 'error',\n name: 'NotPayee',\n inputs: [],\n },\n {\n type: 'error',\n name: 'NotPayer',\n inputs: [],\n },\n {\n type: 'error',\n name: 'TransferFailed',\n inputs: [],\n },\n] as const\n","import {\n type Account,\n type Address,\n type Client,\n decodeFunctionData,\n encodeFunctionData,\n getAbiItem,\n type Hex,\n type ReadContractReturnType,\n toFunctionSelector,\n} from 'viem'\nimport {\n call,\n prepareTransactionRequest,\n readContract,\n sendRawTransaction,\n sendRawTransactionSync,\n signTransaction,\n writeContract,\n} from 'viem/actions'\nimport { Transaction } from 'viem/tempo'\n\nimport { BadRequestError, ChannelClosedError, VerificationFailedError } from '../../Errors.js'\nimport * as TempoAddress from '../internal/address.js'\nimport * as defaults from '../internal/defaults.js'\nimport { isTempoTransaction } from '../internal/fee-payer.js'\nimport * as Channel from './Channel.js'\nimport { escrowAbi } from './escrow.abi.js'\nimport type { SignedVoucher } from './Types.js'\n\nexport { escrowAbi }\n\n/**\n * Asserts that a deserialized transaction has an existing sender signature —\n * required before fee payer co-signing to prevent the fee payer from becoming\n * the sender.\n */\nfunction assertSenderSigned(transaction: any): void {\n if (!transaction.signature || !transaction.from)\n throw new BadRequestError({\n reason: 'Transaction must be signed by the sender before fee payer co-signing',\n })\n}\n\nconst UINT128_MAX = 2n ** 128n - 1n\n\n/**\n * On-chain channel state from the escrow contract.\n */\nexport type OnChainChannel = ReadContractReturnType<typeof escrowAbi, 'getChannel'>\n\n/**\n * Read channel state from the escrow contract.\n */\nexport async function getOnChainChannel(\n client: Client,\n escrowContract: Address,\n channelId: Hex,\n): Promise<OnChainChannel> {\n return readContract(client, {\n address: escrowContract,\n abi: escrowAbi,\n functionName: 'getChannel',\n args: [channelId],\n })\n}\n\n/**\n * Verify a topUp by re-reading on-chain channel state.\n */\nexport async function verifyTopUpTransaction(\n client: Client,\n escrowContract: Address,\n channelId: Hex,\n previousDeposit: bigint,\n): Promise<{ deposit: bigint }> {\n const channel = await getOnChainChannel(client, escrowContract, channelId)\n\n if (channel.finalized) {\n throw new ChannelClosedError({ reason: 'channel is finalized on-chain' })\n }\n\n if (channel.deposit <= previousDeposit) {\n throw new VerificationFailedError({ reason: 'channel deposit did not increase' })\n }\n\n return { deposit: channel.deposit }\n}\n\nfunction assertUint128(amount: bigint): void {\n if (amount < 0n || amount > UINT128_MAX) {\n throw new VerificationFailedError({ reason: 'cumulativeAmount exceeds uint128 range' })\n }\n}\n\n/**\n * Submit a settle transaction on-chain.\n */\nexport async function settleOnChain(\n client: Client,\n escrowContract: Address,\n voucher: SignedVoucher,\n feePayer?: Account | undefined,\n): Promise<Hex> {\n assertUint128(voucher.cumulativeAmount)\n const args = [voucher.channelId, voucher.cumulativeAmount, voucher.signature] as const\n if (feePayer) {\n const data = encodeFunctionData({ abi: escrowAbi, functionName: 'settle', args })\n return sendFeePayerTx(client, feePayer, escrowContract, data, 'settle')\n }\n return writeContract(client, {\n account: client.account!,\n chain: client.chain,\n address: escrowContract,\n abi: escrowAbi,\n functionName: 'settle',\n args,\n })\n}\n\n/**\n * Submit a close transaction on-chain.\n */\nexport async function closeOnChain(\n client: Client,\n escrowContract: Address,\n voucher: SignedVoucher,\n account?: Account,\n feePayer?: Account | undefined,\n): Promise<Hex> {\n assertUint128(voucher.cumulativeAmount)\n const resolved = account ?? client.account\n if (!resolved)\n throw new Error(\n 'Cannot close channel: no account available. Provide an `account` in the session config or a `getClient` that returns an account-bearing client.',\n )\n const args = [voucher.channelId, voucher.cumulativeAmount, voucher.signature] as const\n if (feePayer) {\n const data = encodeFunctionData({ abi: escrowAbi, functionName: 'close', args })\n return sendFeePayerTx(client, feePayer, escrowContract, data, 'close')\n }\n return writeContract(client, {\n account: resolved,\n chain: client.chain,\n address: escrowContract,\n abi: escrowAbi,\n functionName: 'close',\n args,\n })\n}\n\n/**\n * Build, sign, and broadcast a fee-sponsored type-0x76 transaction.\n *\n * Follows the same signTransaction + sendRawTransactionSync pattern used\n * by broadcastOpenTransaction / broadcastTopUpTransaction, but originates\n * the transaction server-side (estimating gas and fees first).\n */\nasync function sendFeePayerTx(\n client: Client,\n feePayer: Account,\n to: Address,\n data: Hex,\n label: string,\n): Promise<Hex> {\n // Resolve the fee token for this chain so the tx pays gas in the correct\n // token. `feePayer: true` tells the prepare hook to use expiring nonces but\n // does NOT set feeToken automatically, so we must provide it explicitly.\n const chainId = client.chain?.id\n const feeToken = chainId\n ? defaults.currency[chainId as keyof typeof defaults.currency]\n : undefined\n\n const prepared = await prepareTransactionRequest(client, {\n account: feePayer,\n calls: [{ to, data }],\n feePayer: true,\n ...(feeToken ? { feeToken } : {}),\n } as never)\n\n const serialized = (await signTransaction(client, {\n ...prepared,\n account: feePayer,\n feePayer,\n } as never)) as Hex\n\n const receipt = await sendRawTransactionSync(client, {\n serializedTransaction: serialized as Transaction.TransactionSerializedTempo,\n })\n\n if (receipt.status !== 'success') {\n throw new VerificationFailedError({\n reason: `${label} transaction reverted: ${receipt.transactionHash}`,\n })\n }\n\n return receipt.transactionHash\n}\n\nconst escrowOpenSelector = /*#__PURE__*/ toFunctionSelector(\n getAbiItem({ abi: escrowAbi, name: 'open' }),\n)\n\nconst escrowTopUpSelector = /*#__PURE__*/ toFunctionSelector(\n getAbiItem({ abi: escrowAbi, name: 'topUp' }),\n)\n\nconst erc20ApproveSelector = /*#__PURE__*/ toFunctionSelector(\n 'function approve(address spender, uint256 amount)',\n)\n\nexport type BroadcastResult = {\n txHash: Hex | undefined\n onChain: OnChainChannel\n}\n\nexport async function broadcastOpenTransaction(parameters: {\n client: Client\n serializedTransaction: Hex\n escrowContract: Address\n channelId: Hex\n recipient: Address\n currency: Address\n feePayer?: Account | undefined\n /** When false, simulates instead of waiting for confirmation and returns derived on-chain state. @default true */\n waitForConfirmation?: boolean | undefined\n}): Promise<BroadcastResult> {\n const {\n client,\n serializedTransaction,\n escrowContract,\n channelId,\n recipient,\n currency,\n feePayer,\n waitForConfirmation = true,\n } = parameters\n\n if (feePayer && !isTempoTransaction(serializedTransaction))\n throw new BadRequestError({\n reason: 'Only Tempo (0x76/0x78) transactions are supported',\n })\n\n const transaction = Transaction.deserialize(\n serializedTransaction as Transaction.TransactionSerializedTempo,\n )\n\n if (feePayer) assertSenderSigned(transaction)\n\n const calls = transaction.calls ?? []\n\n const openCall = calls.find((call) => {\n if (!call.to || !TempoAddress.isEqual(call.to, escrowContract)) return false\n if (!call.data) return false\n return call.data.slice(0, 10) === escrowOpenSelector\n })\n\n if (!openCall)\n throw new BadRequestError({\n reason: 'transaction does not contain a valid escrow open call',\n })\n\n if (feePayer) {\n for (const call of calls) {\n if (!call.to || !call.data) {\n throw new BadRequestError({\n reason: 'fee-sponsored transactions must not contain calls without target or data',\n })\n }\n const selector = call.data.slice(0, 10)\n const isEscrowOpen =\n TempoAddress.isEqual(call.to, escrowContract) && selector === escrowOpenSelector\n const isTokenApprove =\n TempoAddress.isEqual(call.to, currency) && selector === erc20ApproveSelector\n if (!isEscrowOpen && !isTokenApprove) {\n throw new BadRequestError({\n reason: 'fee-sponsored open transaction contains an unauthorized call',\n })\n }\n }\n }\n\n const { args: openArgs } = decodeFunctionData({ abi: escrowAbi, data: openCall.data! })\n const [payee, token, deposit, salt, authorizedSigner] = openArgs as readonly [\n Address,\n Address,\n bigint,\n Hex,\n Address,\n ]\n\n if (!TempoAddress.isEqual(payee, recipient)) {\n throw new VerificationFailedError({\n reason: 'open transaction payee does not match server recipient',\n })\n }\n if (!TempoAddress.isEqual(token, currency)) {\n throw new VerificationFailedError({\n reason: 'open transaction token does not match server currency',\n })\n }\n\n if (!transaction.from) throw new BadRequestError({ reason: 'open transaction has no sender' })\n\n const derivedChannelId = Channel.computeId({\n payer: transaction.from as `0x${string}`,\n payee,\n token,\n salt,\n authorizedSigner,\n escrowContract,\n chainId: client.chain!.id,\n })\n if (derivedChannelId.toLowerCase() !== channelId.toLowerCase())\n throw new VerificationFailedError({\n reason: 'open transaction does not match claimed channelId',\n })\n\n const resolvedFeeToken =\n transaction.feeToken ?? defaults.currency[client.chain?.id as keyof typeof defaults.currency]\n\n const serializedTransaction_final = await (async () => {\n if (feePayer) {\n return signTransaction(client, {\n ...transaction,\n account: feePayer,\n feePayer,\n feeToken: resolvedFeeToken,\n } as never)\n }\n return serializedTransaction\n })()\n\n if (!waitForConfirmation) {\n await call(client, {\n ...transaction,\n account: transaction.from,\n feeToken: resolvedFeeToken,\n calls,\n } as never)\n const txHash = await sendRawTransaction(client, {\n serializedTransaction: serializedTransaction_final as Transaction.TransactionSerializedTempo,\n })\n\n return {\n txHash,\n onChain: {\n finalized: false,\n closeRequestedAt: 0n,\n payer: transaction.from,\n payee,\n token,\n authorizedSigner,\n deposit,\n settled: 0n,\n } as OnChainChannel,\n }\n }\n\n let txHash: Hex | undefined\n try {\n const receipt = await sendRawTransactionSync(client, {\n serializedTransaction: serializedTransaction_final as Transaction.TransactionSerializedTempo,\n })\n\n if (receipt.status !== 'success') {\n throw new VerificationFailedError({\n reason: `open transaction reverted: ${receipt.transactionHash}`,\n })\n }\n\n txHash = receipt.transactionHash\n } catch (error) {\n const onChain = await getOnChainChannel(client, escrowContract, channelId)\n if (onChain.deposit > 0n) {\n return { txHash: undefined, onChain }\n }\n throw error\n }\n\n const onChain = await getOnChainChannel(client, escrowContract, channelId)\n\n return { txHash, onChain }\n}\n\nexport async function broadcastTopUpTransaction(parameters: {\n client: Client\n serializedTransaction: Hex\n escrowContract: Address\n channelId: Hex\n currency: Address\n declaredDeposit: bigint\n previousDeposit: bigint\n feePayer?: Account | undefined\n}): Promise<{ txHash: Hex; newDeposit: bigint }> {\n const {\n client,\n serializedTransaction,\n escrowContract,\n channelId,\n currency,\n declaredDeposit,\n previousDeposit,\n feePayer,\n } = parameters\n\n if (feePayer && !isTempoTransaction(serializedTransaction))\n throw new BadRequestError({\n reason: 'Only Tempo (0x76/0x78) transactions are supported',\n })\n\n const transaction = Transaction.deserialize(\n serializedTransaction as Transaction.TransactionSerializedTempo,\n )\n\n if (feePayer) assertSenderSigned(transaction)\n\n const calls = transaction.calls ?? []\n\n const topUpCall = calls.find((call) => {\n if (!call.to || !TempoAddress.isEqual(call.to, escrowContract)) return false\n if (!call.data) return false\n return call.data.slice(0, 10) === escrowTopUpSelector\n })\n\n if (!topUpCall)\n throw new BadRequestError({\n reason: 'transaction does not contain a valid escrow topUp call',\n })\n\n if (feePayer) {\n for (const call of calls) {\n if (!call.to || !call.data) {\n throw new BadRequestError({\n reason: 'fee-sponsored transactions must not contain calls without target or data',\n })\n }\n const selector = call.data.slice(0, 10)\n const isEscrowTopUp =\n TempoAddress.isEqual(call.to, escrowContract) && selector === escrowTopUpSelector\n const isTokenApprove =\n TempoAddress.isEqual(call.to, currency) && selector === erc20ApproveSelector\n if (!isEscrowTopUp && !isTokenApprove) {\n throw new BadRequestError({\n reason: 'fee-sponsored topUp transaction contains an unauthorized call',\n })\n }\n }\n }\n\n const { args: topUpArgs } = decodeFunctionData({ abi: escrowAbi, data: topUpCall.data! })\n const [txChannelId, txAmount] = topUpArgs as [Hex, bigint]\n\n if (txChannelId.toLowerCase() !== channelId.toLowerCase()) {\n throw new VerificationFailedError({\n reason: 'topUp transaction channelId does not match payload channelId',\n })\n }\n if (BigInt(txAmount) !== declaredDeposit) {\n throw new VerificationFailedError({\n reason: `topUp transaction amount (${txAmount}) does not match declared additionalDeposit (${declaredDeposit})`,\n })\n }\n\n const serializedTransaction_final = await (async () => {\n if (feePayer) {\n return signTransaction(client, {\n ...transaction,\n account: feePayer,\n feePayer,\n feeToken:\n transaction.feeToken ??\n defaults.currency[client.chain?.id as keyof typeof defaults.currency],\n } as never)\n }\n return serializedTransaction\n })()\n\n const receipt = await sendRawTransactionSync(client, {\n serializedTransaction: serializedTransaction_final as Transaction.TransactionSerializedTempo,\n })\n\n if (receipt.status !== 'success') {\n throw new VerificationFailedError({\n reason: `topUp transaction reverted: ${receipt.transactionHash}`,\n })\n }\n\n const onChain = await getOnChainChannel(client, escrowContract, channelId)\n\n if (onChain.deposit <= previousDeposit) {\n throw new VerificationFailedError({ reason: 'channel deposit did not increase after topUp' })\n }\n\n return { txHash: receipt.transactionHash, newDeposit: onChain.deposit }\n}\n","/**\n * Shared client-side channel operations.\n *\n * Provides the low-level helpers that both `session()`\n * and `sessionManager()` (orchestrator) rely on: escrow resolution, channel\n * ID computation, on-chain open/voucher/close payload construction, channel\n * recovery from on-chain state, and credential serialization.\n */\nimport { Hex } from 'ox'\nimport {\n type Address,\n encodeFunctionData,\n type Account as viem_Account,\n type Client as viem_Client,\n} from 'viem'\nimport { prepareTransactionRequest, signTransaction } from 'viem/actions'\nimport { Abis } from 'viem/tempo'\n\nimport type { Challenge } from '../../Challenge.js'\nimport * as Credential from '../../Credential.js'\nimport * as defaults from '../internal/defaults.js'\nimport { escrowAbi, getOnChainChannel } from '../session/Chain.js'\nimport * as Channel from '../session/Channel.js'\nimport type { SessionCredentialPayload } from '../session/Types.js'\nimport { signVoucher } from '../session/Voucher.js'\n\nexport type ChannelEntry = {\n channelId: Hex.Hex\n salt: Hex.Hex\n cumulativeAmount: bigint\n escrowContract: Address\n chainId: number\n opened: boolean\n}\n\nexport function resolveChainId(challenge: Challenge): number {\n const md = challenge.request.methodDetails as { chainId?: number } | undefined\n return md?.chainId ?? 0\n}\n\nexport function resolveEscrow(\n challenge: { request: { methodDetails?: unknown } },\n chainId: number,\n escrowContractOverride?: Address,\n): Address {\n const challengeEscrow = (challenge.request.methodDetails as { escrowContract?: string })\n ?.escrowContract as Address | undefined\n const escrow =\n challengeEscrow ??\n escrowContractOverride ??\n defaults.escrowContract[chainId as keyof typeof defaults.escrowContract]\n if (!escrow)\n throw new Error(\n 'No `escrowContract` available. Provide it in parameters or ensure the server challenge includes it.',\n )\n return escrow\n}\n\nexport function serializeCredential(\n challenge: Challenge,\n payload: SessionCredentialPayload,\n chainId: number,\n account: viem_Account,\n): string {\n return Credential.serialize({\n challenge,\n payload,\n source: `did:pkh:eip155:${chainId}:${account.address}`,\n })\n}\n\nexport async function createVoucherPayload(\n client: viem_Client,\n account: viem_Account,\n channelId: Hex.Hex,\n cumulativeAmount: bigint,\n escrowContract: Address,\n chainId: number,\n authorizedSigner?: Address | undefined,\n): Promise<SessionCredentialPayload> {\n const signature = await signVoucher(\n client,\n account,\n { channelId, cumulativeAmount },\n escrowContract,\n chainId,\n authorizedSigner,\n )\n return {\n action: 'voucher',\n channelId,\n cumulativeAmount: cumulativeAmount.toString(),\n signature,\n }\n}\n\nexport async function createClosePayload(\n client: viem_Client,\n account: viem_Account,\n channelId: Hex.Hex,\n cumulativeAmount: bigint,\n escrowContract: Address,\n chainId: number,\n authorizedSigner?: Address | undefined,\n): Promise<SessionCredentialPayload> {\n const signature = await signVoucher(\n client,\n account,\n { channelId, cumulativeAmount },\n escrowContract,\n chainId,\n authorizedSigner,\n )\n return {\n action: 'close',\n channelId,\n cumulativeAmount: cumulativeAmount.toString(),\n signature,\n }\n}\n\nexport async function createOpenPayload(\n client: viem_Client,\n account: viem_Account,\n options: {\n authorizedSigner?: Address | undefined\n escrowContract: Address\n payee: Address\n currency: Address\n deposit: bigint\n initialAmount: bigint\n chainId: number\n feePayer?: boolean | undefined\n },\n): Promise<{ entry: ChannelEntry; payload: SessionCredentialPayload }> {\n const { escrowContract, payee, currency, deposit, initialAmount, chainId, feePayer } = options\n const authorizedSigner = options.authorizedSigner ?? account.address\n\n const salt = Hex.random(32)\n const channelId = Channel.computeId({\n authorizedSigner,\n chainId,\n escrowContract,\n payee,\n payer: account.address,\n salt,\n token: currency,\n })\n\n const approveData = encodeFunctionData({\n abi: Abis.tip20,\n functionName: 'approve',\n args: [escrowContract, deposit],\n })\n const openData = encodeFunctionData({\n abi: escrowAbi,\n functionName: 'open',\n args: [payee, currency, deposit, salt, authorizedSigner],\n })\n\n const prepared = await prepareTransactionRequest(client, {\n account,\n calls: [\n { to: currency, data: approveData },\n { to: escrowContract, data: openData },\n ],\n ...(feePayer && { feePayer: true }),\n feeToken: currency,\n } as never)\n prepared.gas = prepared.gas! + 5_000n\n const transaction = (await signTransaction(client, prepared as never)) as Hex.Hex\n\n const signature = await signVoucher(\n client,\n account,\n { channelId, cumulativeAmount: initialAmount },\n escrowContract,\n chainId,\n options.authorizedSigner,\n )\n\n return {\n entry: {\n channelId,\n salt,\n cumulativeAmount: initialAmount,\n escrowContract,\n chainId,\n opened: true,\n },\n payload: {\n action: 'open',\n type: 'transaction',\n channelId,\n transaction,\n authorizedSigner,\n cumulativeAmount: initialAmount.toString(),\n signature,\n },\n }\n}\n\n/**\n * Attempt to recover an existing on-chain channel by reading its state.\n *\n * If the channel has a positive deposit and is not finalized, returns a\n * {@link ChannelEntry} with `cumulativeAmount` set to the on-chain settled\n * amount (the safe starting point for new vouchers).\n *\n * Returns `undefined` if the channel doesn't exist, has zero deposit,\n * or is already finalized.\n */\nexport async function tryRecoverChannel(\n client: viem_Client,\n escrowContract: Address,\n channelId: Hex.Hex,\n chainId: number,\n): Promise<ChannelEntry | undefined> {\n try {\n const onChain = await getOnChainChannel(client, escrowContract, channelId)\n\n if (onChain.deposit > 0n && !onChain.finalized) {\n return {\n channelId,\n salt: '0x' as Hex.Hex,\n cumulativeAmount: onChain.settled,\n escrowContract,\n chainId,\n opened: true,\n }\n }\n } catch {}\n\n return undefined\n}\n","import type { Hex } from 'ox'\nimport { type Address, parseUnits, type Account as viem_Account } from 'viem'\nimport { tempo as tempo_chain } from 'viem/chains'\n\nimport type * as Challenge from '../../Challenge.js'\nimport * as Method from '../../Method.js'\nimport * as Account from '../../viem/Account.js'\nimport * as Client from '../../viem/Client.js'\nimport * as z from '../../zod.js'\nimport * as defaults from '../internal/defaults.js'\nimport * as Methods from '../Methods.js'\nimport type { SessionCredentialPayload } from '../session/Types.js'\nimport { signVoucher } from '../session/Voucher.js'\nimport {\n type ChannelEntry,\n createOpenPayload,\n createVoucherPayload,\n resolveEscrow,\n serializeCredential,\n tryRecoverChannel,\n} from './ChannelOps.js'\n\nexport const sessionContextSchema = z.object({\n account: z.optional(z.custom<Account.getResolver.Parameters['account']>()),\n action: z.optional(z.enum(['open', 'topUp', 'voucher', 'close'])),\n channelId: z.optional(z.string()),\n cumulativeAmount: z.optional(z.amount()),\n cumulativeAmountRaw: z.optional(z.string()),\n transaction: z.optional(z.string()),\n authorizedSigner: z.optional(z.string()),\n additionalDeposit: z.optional(z.amount()),\n additionalDepositRaw: z.optional(z.string()),\n depositRaw: z.optional(z.string()),\n})\n\nexport type SessionContext = z.infer<typeof sessionContextSchema>\n\n/**\n * Creates a session payment method for use with `Mppx.create()`.\n *\n * Supports both auto mode (set `deposit` to manage channels automatically)\n * and manual mode (pass `context.action` to control each step).\n *\n * @example\n * ```ts\n * // Auto mode\n * import { Mppx, tempo } from 'mppx/client'\n *\n * const mppx = Mppx.create({\n * methods: [tempo({\n * account: privateKeyToAccount('0x...'),\n * deposit: '10',\n * })],\n * })\n *\n * const res = await mppx.fetch('/api/chat?prompt=hello')\n * ```\n *\n * @example\n * ```ts\n * // Manual mode\n * const mppx = Mppx.create({\n * methods: [tempo({ account })],\n * })\n *\n * const credential = await mppx.createCredential(response, {\n * action: 'voucher',\n * channelId: '0x...',\n * cumulativeAmount: '1',\n * })\n * ```\n */\nexport function session(parameters: session.Parameters = {}) {\n const { decimals = defaults.decimals } = parameters\n\n const getClient = Client.getResolver({\n chain: tempo_chain,\n getClient: parameters.getClient,\n rpcUrl: defaults.rpcUrl,\n })\n const getAccount = Account.getResolver({ account: parameters.account })\n const getAuthorizedSigner = (account: viem_Account) =>\n parameters.authorizedSigner ??\n (account as unknown as { accessKeyAddress?: Address }).accessKeyAddress\n\n const maxDeposit =\n parameters.maxDeposit !== undefined ? parseUnits(parameters.maxDeposit, decimals) : undefined\n\n const escrowContractMap = new Map<string, Address>()\n const channels = new Map<string, ChannelEntry>()\n const channelIdToKey = new Map<string, string>()\n\n function notifyUpdate(entry: ChannelEntry) {\n parameters.onChannelUpdate?.(entry)\n }\n\n function channelKey(payee: Address, currency: Address, escrow: Address): string {\n return `${payee.toLowerCase()}:${currency.toLowerCase()}:${escrow.toLowerCase()}`\n }\n\n function resolveEscrowCached(\n challenge: { request: { methodDetails?: unknown } },\n chainId: number,\n channelId?: string,\n ): Address {\n if (channelId) {\n const cached = escrowContractMap.get(channelId)\n if (cached) return cached\n }\n return resolveEscrow(challenge, chainId, parameters.escrowContract)\n }\n\n async function autoManageCredential(\n challenge: Challenge.Challenge,\n account: viem_Account,\n context?: SessionContext,\n ): Promise<string> {\n const md = challenge.request.methodDetails as\n | { chainId?: number; escrowContract?: string; channelId?: string; feePayer?: boolean }\n | undefined\n const chainId = md?.chainId ?? 0\n const client = await getClient({ chainId })\n const escrowContract = resolveEscrowCached(challenge, chainId)\n const payee = challenge.request.recipient as Address\n const currency = challenge.request.currency as Address\n const amount = BigInt(challenge.request.amount as string)\n\n const suggestedDepositRaw = (challenge.request as { suggestedDeposit?: string })\n .suggestedDeposit\n const suggestedDeposit = suggestedDepositRaw ? BigInt(suggestedDepositRaw) : undefined\n\n const deposit = (() => {\n if (context?.depositRaw) return BigInt(context.depositRaw)\n if (suggestedDeposit !== undefined && maxDeposit !== undefined)\n return suggestedDeposit < maxDeposit ? suggestedDeposit : maxDeposit\n if (suggestedDeposit !== undefined) return suggestedDeposit\n if (maxDeposit !== undefined) return maxDeposit\n if (parameters.deposit !== undefined) return parseUnits(parameters.deposit, decimals)\n throw new Error(\n 'No deposit amount available. Set `deposit`, `maxDeposit`, or ensure the server challenge includes `suggestedDeposit`.',\n )\n })()\n\n const authorizedSigner = getAuthorizedSigner(account)\n\n const key = channelKey(payee, currency, escrowContract)\n let entry = channels.get(key)\n\n if (!entry) {\n const suggestedChannelId = (context?.channelId ?? md?.channelId) as Hex.Hex | undefined\n if (suggestedChannelId) {\n const recovered = await tryRecoverChannel(\n client,\n escrowContract,\n suggestedChannelId,\n chainId,\n )\n if (recovered) {\n const contextCumulative = context?.cumulativeAmountRaw\n ? BigInt(context.cumulativeAmountRaw)\n : context?.cumulativeAmount\n ? parseUnits(context.cumulativeAmount, decimals)\n : undefined\n if (contextCumulative !== undefined) recovered.cumulativeAmount = contextCumulative\n channels.set(key, recovered)\n channelIdToKey.set(recovered.channelId, key)\n escrowContractMap.set(recovered.channelId, escrowContract)\n entry = recovered\n notifyUpdate(entry)\n } else if (context?.channelId) {\n throw new Error(\n `Channel ${context.channelId} cannot be reused (closed or not found on-chain).`,\n )\n }\n }\n }\n\n let payload: SessionCredentialPayload\n\n if (entry?.opened) {\n entry.cumulativeAmount += amount\n payload = await createVoucherPayload(\n client,\n account,\n entry.channelId,\n entry.cumulativeAmount,\n escrowContract,\n chainId,\n authorizedSigner,\n )\n notifyUpdate(entry)\n } else {\n const result = await createOpenPayload(client, account, {\n authorizedSigner,\n escrowContract,\n payee,\n currency,\n deposit,\n initialAmount: amount,\n chainId,\n feePayer: md?.feePayer,\n })\n channels.set(key, result.entry)\n channelIdToKey.set(result.entry.channelId, key)\n escrowContractMap.set(result.entry.channelId, escrowContract)\n payload = result.payload\n notifyUpdate(result.entry)\n }\n\n return serializeCredential(challenge, payload, chainId, account)\n }\n\n async function manualCredential(\n challenge: Challenge.Challenge,\n account: viem_Account,\n context: SessionContext,\n ): Promise<string> {\n const md = challenge.request.methodDetails as\n | { chainId?: number; escrowContract?: string; channelId?: string }\n | undefined\n const chainId = md?.chainId ?? 0\n const client = await getClient({ chainId })\n\n const action = context.action!\n const {\n channelId: channelIdRaw,\n transaction,\n authorizedSigner: contextAuthorizedSigner,\n } = context\n const authorizedSigner = (contextAuthorizedSigner as Address) ?? getAuthorizedSigner(account)\n const channelId = channelIdRaw as Hex.Hex\n const cumulativeAmount = context.cumulativeAmountRaw\n ? BigInt(context.cumulativeAmountRaw)\n : context.cumulativeAmount\n ? parseUnits(context.cumulativeAmount, decimals)\n : undefined\n const resolvedAdditionalDeposit = context.additionalDepositRaw\n ? BigInt(context.additionalDepositRaw)\n : context.additionalDeposit\n ? parseUnits(context.additionalDeposit, decimals)\n : undefined\n\n const escrowContract = resolveEscrowCached(challenge, chainId, channelId)\n escrowContractMap.set(channelId, escrowContract)\n\n let payload: SessionCredentialPayload\n\n switch (action) {\n case 'open': {\n if (!transaction) throw new Error('transaction required for open action')\n if (cumulativeAmount === undefined)\n throw new Error('cumulativeAmount required for open action')\n const signature = await signVoucher(\n client,\n account,\n { channelId, cumulativeAmount },\n escrowContract,\n chainId,\n authorizedSigner,\n )\n payload = {\n action: 'open',\n type: 'transaction',\n channelId,\n transaction: transaction as Hex.Hex,\n authorizedSigner: authorizedSigner ?? account.address,\n cumulativeAmount: cumulativeAmount.toString(),\n signature,\n }\n break\n }\n\n case 'topUp':\n if (!transaction) throw new Error('transaction required for topUp action')\n if (resolvedAdditionalDeposit === undefined)\n throw new Error('additionalDeposit required for topUp action')\n payload = {\n action: 'topUp',\n type: 'transaction',\n channelId,\n transaction: transaction as Hex.Hex,\n additionalDeposit: resolvedAdditionalDeposit.toString(),\n }\n break\n\n case 'voucher': {\n if (cumulativeAmount === undefined)\n throw new Error('cumulativeAmount required for voucher action')\n payload = await createVoucherPayload(\n client,\n account,\n channelId,\n cumulativeAmount,\n escrowContract,\n chainId,\n authorizedSigner,\n )\n const key = channelIdToKey.get(channelId)\n if (key) {\n const entry = channels.get(key)\n if (entry) {\n entry.cumulativeAmount =\n entry.cumulativeAmount > cumulativeAmount ? entry.cumulativeAmount : cumulativeAmount\n notifyUpdate(entry)\n }\n }\n break\n }\n\n case 'close': {\n if (cumulativeAmount === undefined)\n throw new Error('cumulativeAmount required for close action')\n const signature = await signVoucher(\n client,\n account,\n { channelId, cumulativeAmount },\n escrowContract,\n chainId,\n authorizedSigner,\n )\n payload = {\n action: 'close',\n channelId,\n cumulativeAmount: cumulativeAmount.toString(),\n signature,\n }\n const closeKey = channelIdToKey.get(channelId)\n if (closeKey) {\n const entry = channels.get(closeKey)\n if (entry) {\n entry.opened = false\n entry.cumulativeAmount =\n entry.cumulativeAmount > cumulativeAmount ? entry.cumulativeAmount : cumulativeAmount\n notifyUpdate(entry)\n }\n }\n break\n }\n }\n\n return serializeCredential(challenge, payload, chainId, account)\n }\n\n return Method.toClient(Methods.session, {\n context: sessionContextSchema,\n\n async createCredential({ challenge, context }) {\n const chainId = challenge.request.methodDetails?.chainId ?? 0\n const client = await getClient({ chainId })\n const account = getAccount(client, context)\n\n if (!context?.action && (parameters.deposit !== undefined || maxDeposit !== undefined))\n return autoManageCredential(challenge, account, context)\n\n if (context?.action) return manualCredential(challenge, account, context)\n\n throw new Error(\n 'No `action` in context and no `deposit` or `maxDeposit` configured. Either provide context with action/channelId/cumulativeAmount, or configure `deposit`/`maxDeposit` for auto-management.',\n )\n },\n })\n}\n\nexport declare namespace session {\n type Parameters = Account.getResolver.Parameters &\n Client.getResolver.Parameters & {\n /** Address authorized to sign vouchers. Defaults to the account address. Use when a separate access key (e.g. secp256k1) signs vouchers while the root account funds the channel. */\n authorizedSigner?: Address | undefined\n /** Token decimals for parsing human-readable amounts (default: 6). */\n decimals?: number | undefined\n /** Initial deposit amount in human-readable units (e.g. \"10\" for 10 tokens). When set, the method handles the full channel lifecycle (open, voucher, cumulative tracking) automatically. */\n deposit?: string | undefined\n /** Escrow contract address override. Derived from challenge or defaults if not provided. */\n escrowContract?: Address | undefined\n /** Maximum deposit in human-readable units (e.g. \"10\"). Caps the server's `suggestedDeposit`. Enables auto-management like `deposit`. */\n maxDeposit?: string | undefined\n /** Called whenever channel state changes (open, voucher, close, recovery). */\n onChannelUpdate?: ((entry: ChannelEntry) => void) | undefined\n }\n}\n","import * as Challenge from '../../Challenge.js'\nimport type * as Method from '../../Method.js'\nimport type * as z from '../../zod.js'\n\n// We tag wrappers with a global symbol so we can recognize wrappers created by mppx,\n// even across multiple module instances/bundles. This lets restore() avoid clobbering\n// an unrelated fetch installed by user code or another library.\nconst MPPX_FETCH_WRAPPER = Symbol.for('mppx.fetch.wrapper')\n\ntype WrappedFetch = typeof globalThis.fetch & {\n [MPPX_FETCH_WRAPPER]?: typeof globalThis.fetch\n}\n\nlet originalFetch: typeof globalThis.fetch | undefined\n\n/**\n * Creates a fetch wrapper that automatically handles 402 Payment Required responses.\n *\n * @example\n * ```ts\n * import { Fetch, tempo } from 'mppx/client'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * const fetch = Fetch.from({\n * methods: [\n * tempo({\n * account: privateKeyToAccount('0x...'),\n * }),\n * ],\n * })\n *\n * // Use the wrapped fetch — handles 402 automatically\n * const res = await fetch('https://api.example.com/resource')\n * ```\n *\n */\nexport function from<const methods extends readonly Method.AnyClient[]>(\n config: from.Config<methods>,\n): from.Fetch<methods> {\n const { fetch = globalThis.fetch, methods, onChallenge } = config\n // Always operate on the true underlying fetch to avoid wrapper-on-wrapper stacking,\n // which can duplicate retries and make restore semantics fragile.\n const baseFetch = unwrapFetch(fetch)\n\n const wrappedFetch = async (input: RequestInfo | URL, init?: from.RequestInit<methods>) => {\n // Pass init through untouched to preserve object identity for non-402 responses.\n const response = await baseFetch(input, init)\n\n if (response.status !== 402) return response\n\n // Only extract context for payment handling after confirming 402.\n const context = (init as Record<string, unknown> | undefined)?.context\n const { context: _, ...fetchInit } = (init ?? {}) as Record<string, unknown>\n\n // Parse all challenges from the response (supports merged WWW-Authenticate headers).\n // Match in client preference order: iterate the client's methods array and pick the\n // first method that has a matching challenge, so the client controls priority.\n const challenges = Challenge.fromResponseList(response)\n\n let challenge: Challenge.Challenge | undefined\n let mi: (typeof methods)[number] | undefined\n for (const m of methods) {\n const match = challenges.find((c) => c.method === m.name && c.intent === m.intent)\n if (match) {\n challenge = match\n mi = m\n break\n }\n }\n if (!challenge || !mi)\n throw new Error(\n `No method found for challenges: ${challenges.map((c) => `${c.method}.${c.intent}`).join(', ')}. Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}`,\n )\n\n const onChallengeCredential = onChallenge\n ? await onChallenge(challenge, {\n createCredential: async (overrideContext?: AnyContextFor<methods>) =>\n resolveCredential(challenge, mi!, overrideContext ?? context),\n })\n : undefined\n const credential = onChallengeCredential ?? (await resolveCredential(challenge, mi, context))\n validateCredentialHeaderValue(credential)\n\n return baseFetch(input, {\n ...fetchInit,\n headers: withAuthorizationHeader(fetchInit.headers, credential),\n })\n }\n\n // Record the wrapped target so future polyfill() / restore() calls can detect origin\n // and safely unwrap only mppx-installed wrappers.\n ;(wrappedFetch as WrappedFetch)[MPPX_FETCH_WRAPPER] = baseFetch\n return wrappedFetch as from.Fetch<methods>\n}\n\n/** Union of all context types from all methods that have context schemas. */\ntype AnyContextFor<methods extends readonly Method.AnyClient[]> = {\n [K in keyof methods]: NonNullable<methods[K]['context']> extends infer ctx\n ? ctx extends z.ZodMiniType\n ? z.input<ctx>\n : undefined\n : undefined\n}[number]\n\nexport declare namespace from {\n type Config<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[]> = {\n /** Custom fetch function to wrap. Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch\n /** Array of methods to use. */\n methods: methods\n /** Called when a 402 challenge is received, before credential creation. */\n onChallenge?:\n | ((\n challenge: Challenge.Challenge,\n helpers: {\n createCredential: (context?: AnyContextFor<methods>) => Promise<string>\n },\n ) => Promise<string | undefined>)\n | undefined\n }\n\n type Fetch<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[]> = (\n input: RequestInfo | URL,\n init?: RequestInit<methods>,\n ) => Promise<Response>\n\n type RequestInit<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[]> =\n globalThis.RequestInit & {\n /** Context to pass to the method intent's createCredential. */\n context?: AnyContextFor<methods>\n }\n}\n\n/**\n * Replaces the global `fetch` with a payment-aware wrapper.\n *\n * @example\n * ```ts\n * import { Fetch, tempo } from 'mppx/client'\n * import { privateKeyToAccount } from 'viem/accounts'\n *\n * Fetch.polyfill({\n * methods: [\n * tempo({\n * account: privateKeyToAccount('0x...'),\n * }),\n * ],\n * })\n *\n * // Global fetch now handles 402 automatically\n * const res = await fetch('https://api.example.com/resource')\n * ```\n */\nexport function polyfill<const methods extends readonly Method.AnyClient[]>(\n config: polyfill.Config<methods>,\n): void {\n // Defensive guard for runtimes/tests where fetch might be non-configurable.\n const descriptor = Object.getOwnPropertyDescriptor(globalThis, 'fetch')\n if (!descriptor || (!descriptor.writable && !descriptor.set)) {\n throw new Error('globalThis.fetch is not writable')\n }\n\n if (!originalFetch) originalFetch = globalThis.fetch\n globalThis.fetch = from({ ...config, fetch: globalThis.fetch }) as typeof globalThis.fetch\n}\n\nexport declare namespace polyfill {\n type Config<methods extends readonly Method.AnyClient[] = readonly Method.AnyClient[]> =\n from.Config<methods>\n}\n\n/**\n * Restores the original `fetch` after calling `polyfill`.\n *\n * @example\n * ```ts\n * import { Fetch } from 'mppx/client'\n *\n * Fetch.polyfill({ methods: [...] })\n *\n * // ... use payment-aware fetch ...\n *\n * Fetch.restore()\n * ```\n */\nexport function restore(): void {\n // Only restore if the current fetch is still an mppx wrapper.\n // If app code replaced fetch after polyfill(), we must not overwrite it.\n if (originalFetch && isWrappedFetch(globalThis.fetch)) {\n globalThis.fetch = originalFetch\n originalFetch = undefined\n }\n}\n\n/** @internal Normalizes headers to a plain object for spreading. */\nexport function normalizeHeaders(headers: unknown): Record<string, string> {\n if (!headers) return {}\n if (headers instanceof Headers) {\n const result: Record<string, string> = {}\n headers.forEach((value, key) => {\n result[key] = value\n })\n return result\n }\n if (Array.isArray(headers)) return Object.fromEntries(headers)\n return headers as Record<string, string>\n}\n\n/** @internal */\nfunction withAuthorizationHeader(headers: unknown, credential: string): Record<string, string> {\n const normalized = normalizeHeaders(headers)\n // Remove any existing Authorization header regardless of casing to avoid\n // duplicate/conflicting credentials on retry.\n for (const key of Object.keys(normalized)) {\n if (key.toLowerCase() === 'authorization') delete normalized[key]\n }\n normalized.Authorization = credential\n return normalized\n}\n\n/** @internal */\nfunction unwrapFetch(fetch: typeof globalThis.fetch): typeof globalThis.fetch {\n let current = fetch as WrappedFetch\n while (current[MPPX_FETCH_WRAPPER]) {\n current = current[MPPX_FETCH_WRAPPER] as WrappedFetch\n }\n return current as typeof globalThis.fetch\n}\n\n/** @internal */\nfunction isWrappedFetch(fetch: typeof globalThis.fetch): fetch is WrappedFetch {\n return Boolean((fetch as WrappedFetch)[MPPX_FETCH_WRAPPER])\n}\n\n/** @internal */\nfunction validateCredentialHeaderValue(credential: string): void {\n if (!credential.trim()) throw new Error('Credential header value must be non-empty')\n if (credential.includes('\\r') || credential.includes('\\n')) {\n throw new Error('Credential header value contains illegal newline characters')\n }\n}\n\n/** @internal */\nasync function resolveCredential(\n challenge: Challenge.Challenge,\n mi: Method.AnyClient,\n context: unknown,\n): Promise<string> {\n const parsedContext = mi.context && context !== undefined ? mi.context.parse(context) : undefined\n return mi.createCredential(\n parsedContext !== undefined ? { challenge, context: parsedContext } : ({ challenge } as never),\n )\n}\n","import { Base64 } from 'ox'\nimport type { Hex } from 'viem'\n\nimport type { SessionReceipt } from './Types.js'\n\n/**\n * Create a session receipt.\n */\nexport function createSessionReceipt(params: {\n challengeId: string\n channelId: Hex\n acceptedCumulative: bigint\n spent: bigint\n units?: number | undefined\n txHash?: Hex | undefined\n}): SessionReceipt {\n return {\n method: 'tempo',\n intent: 'session',\n status: 'success',\n timestamp: new Date().toISOString(),\n reference: params.channelId,\n challengeId: params.challengeId,\n channelId: params.channelId,\n acceptedCumulative: params.acceptedCumulative.toString(),\n spent: params.spent.toString(),\n ...(params.units !== undefined && { units: params.units }),\n ...(params.txHash !== undefined && { txHash: params.txHash }),\n }\n}\n\n/**\n * Serialize a session receipt to the Payment-Receipt header format.\n */\nexport function serializeSessionReceipt(receipt: SessionReceipt): string {\n const json = JSON.stringify(receipt)\n return Base64.fromString(json, { pad: false, url: true })\n}\n\n/**\n * Deserialize a Payment-Receipt header value to a session receipt.\n */\nexport function deserializeSessionReceipt(encoded: string): SessionReceipt {\n const json = Base64.toString(encoded)\n return JSON.parse(json) as SessionReceipt\n}\n","/**\n * SSE (Server-Sent Events) utilities for metered streaming payments.\n *\n * Provides event formatting/parsing, balance polling, the core\n * `serve()` loop that meters an async iterable into a ReadableStream\n * of SSE events, and helpers (`toResponse`, `fromRequest`) for\n * building HTTP responses from the stream.\n */\nimport type { Hex } from 'viem'\n\nimport * as Credential from '../../Credential.js'\nimport * as ChannelStore from './ChannelStore.js'\nimport { createSessionReceipt } from './Receipt.js'\nimport type { NeedVoucherEvent, SessionCredentialPayload, SessionReceipt } from './Types.js'\n\n/**\n * Format a session receipt as a Server-Sent Event.\n *\n * Produces a valid SSE event string with `event: payment-receipt`\n * and the receipt JSON as the `data` field.\n */\nexport function formatReceiptEvent(receipt: SessionReceipt): string {\n return `event: payment-receipt\\ndata: ${JSON.stringify(receipt)}\\n\\n`\n}\n\n/**\n * Format a need-voucher event as a Server-Sent Event.\n *\n * Emitted when the channel balance is exhausted mid-stream.\n * The client responds by sending a new voucher credential to\n * any mppx-protected endpoint.\n */\nexport function formatNeedVoucherEvent(params: NeedVoucherEvent): string {\n return `event: payment-need-voucher\\ndata: ${JSON.stringify(params)}\\n\\n`\n}\n\n/**\n * Parsed SSE event (discriminated union by `type`).\n */\nexport type SseEvent =\n | { type: 'message'; data: string }\n | { type: 'payment-need-voucher'; data: NeedVoucherEvent }\n | { type: 'payment-receipt'; data: SessionReceipt }\n\n/**\n * Parse a raw SSE event string into a typed event.\n *\n * Handles the three event types used by mppx streaming:\n * - `message` (default / no event field) — application data\n * - `payment-need-voucher` — balance exhausted, client should send voucher\n * - `payment-receipt` — final receipt\n */\nexport function parseEvent(raw: string): SseEvent | null {\n let eventType = 'message'\n const dataLines: string[] = []\n\n for (const line of raw.split('\\n')) {\n if (line.startsWith('event: ')) {\n eventType = line.slice(7).trim()\n } else if (line.startsWith('data: ')) {\n dataLines.push(line.slice(6))\n } else if (line === 'data:') {\n dataLines.push('')\n }\n }\n\n if (dataLines.length === 0) return null\n const data = dataLines.join('\\n')\n\n switch (eventType) {\n case 'message':\n return { type: 'message', data }\n case 'payment-need-voucher':\n return { type: 'payment-need-voucher', data: JSON.parse(data) as NeedVoucherEvent }\n case 'payment-receipt':\n return { type: 'payment-receipt', data: JSON.parse(data) as SessionReceipt }\n default:\n return { type: 'message', data }\n }\n}\n\nexport type SessionController = {\n charge(): Promise<void>\n}\n\n/**\n * Wrap an async iterable with payment metering, producing an SSE stream.\n *\n * `generate` may be either:\n * - An `AsyncIterable<string>` — each yielded value is automatically charged\n * (one `tickCost` per value).\n * - A callback `(stream: SessionController) => AsyncIterable<string>` — the\n * generator controls when charges happen by calling `stream.charge()`.\n *\n * For each emitted value the stream:\n * 1. Deducts `tickCost` from the channel balance atomically (auto or manual).\n * 2. If balance is sufficient, emits `event: message` with the value.\n * 3. If balance is exhausted, emits `event: payment-need-voucher`\n * and polls store until the client tops up the channel.\n * 4. On generator completion, emits a final `event: payment-receipt`.\n *\n * Returns a `ReadableStream<Uint8Array>` suitable for use as an HTTP response body.\n */\nexport function serve(options: serve.Options): ReadableStream<Uint8Array> {\n const {\n store,\n channelId,\n challengeId,\n tickCost,\n generate,\n pollIntervalMs = 100,\n signal,\n } = options\n\n const encoder = new TextEncoder()\n\n return new ReadableStream<Uint8Array>({\n async start(controller) {\n const aborted = () => signal?.aborted ?? false\n const emit = (event: string) => controller.enqueue(encoder.encode(event))\n\n const charge = () =>\n chargeOrWait({\n store,\n channelId,\n amount: tickCost,\n emit,\n pollIntervalMs,\n signal,\n })\n\n const iterable: AsyncIterable<string> =\n typeof generate === 'function' ? generate({ charge }) : generate\n\n try {\n for await (const value of iterable) {\n if (aborted()) break\n\n if (typeof generate !== 'function') await charge()\n\n controller.enqueue(encoder.encode(`event: message\\ndata: ${value}\\n\\n`))\n }\n\n if (!aborted()) {\n const channel = await store.getChannel(channelId)\n if (channel) {\n const receipt = createSessionReceipt({\n challengeId,\n channelId,\n acceptedCumulative: channel.highestVoucherAmount,\n spent: channel.spent,\n units: channel.units,\n })\n controller.enqueue(encoder.encode(formatReceiptEvent(receipt)))\n }\n }\n } catch (e) {\n if (!aborted()) controller.error(e)\n } finally {\n controller.close()\n }\n },\n })\n}\n\nexport declare namespace serve {\n type Options = {\n store: ChannelStore.ChannelStore\n channelId: Hex\n challengeId: string\n tickCost: bigint\n generate: AsyncIterable<string> | ((stream: SessionController) => AsyncIterable<string>)\n pollIntervalMs?: number | undefined\n signal?: AbortSignal | undefined\n }\n}\n\n/**\n * Wrap a `ReadableStream<Uint8Array>` (from {@link serve}) in an HTTP\n * `Response` with the correct SSE headers.\n */\nexport function toResponse(body: ReadableStream<Uint8Array>): Response {\n return new Response(body, {\n headers: {\n 'Cache-Control': 'no-cache, no-transform',\n Connection: 'keep-alive',\n 'Content-Type': 'text/event-stream; charset=utf-8',\n },\n })\n}\n\n/**\n * Extract `channelId`, `challengeId`, and `tickCost` from a `Request`'s\n * `Authorization: Payment …` header.\n *\n * This is a convenience for callers that receive a raw `Request` and need\n * the parameters required by {@link serve}.\n */\nexport function fromRequest(request: Request): fromRequest.Context {\n const header = request.headers.get('Authorization')\n if (!header) throw new Error('Missing Authorization header.')\n\n const payment = Credential.extractPaymentScheme(header)\n if (!payment) throw new Error('Missing Payment credential in Authorization header.')\n\n const credential = Credential.deserialize(payment)\n const payload = credential.payload as SessionCredentialPayload\n return {\n challengeId: credential.challenge.id,\n channelId: payload.channelId,\n tickCost: BigInt(credential.challenge.request.amount as string),\n }\n}\n\nexport declare namespace fromRequest {\n type Context = {\n challengeId: string\n channelId: Hex\n tickCost: bigint\n }\n}\n\n/**\n * Atomically deduct `amount` from a channel, retrying when balance is\n * insufficient. Uses `store.waitForUpdate()` when available for\n * event-driven wakeups, falling back to polling otherwise. Emits\n * `payment-need-voucher` events via `emit` while waiting.\n */\nasync function chargeOrWait(options: {\n store: ChannelStore.ChannelStore\n channelId: Hex\n amount: bigint\n emit: (event: string) => void\n pollIntervalMs: number\n signal?: AbortSignal | undefined\n}): Promise<void> {\n const { store, channelId, amount, emit, pollIntervalMs, signal } = options\n\n let result = await ChannelStore.deductFromChannel(store, channelId, amount)\n\n if (!result.ok) {\n // Emit a single need-voucher event, then poll/wait until the client\n // sends an updated voucher. The requiredCumulative is constant here:\n // `spent` only changes on successful deduction (which exits the loop),\n // so re-emitting on every poll cycle would just cause redundant\n // voucher POSTs from the client.\n emit(\n formatNeedVoucherEvent({\n channelId,\n requiredCumulative: (result.channel.spent + amount).toString(),\n acceptedCumulative: result.channel.highestVoucherAmount.toString(),\n deposit: result.channel.deposit.toString(),\n }),\n )\n\n while (!result.ok) {\n await waitForUpdate(store, channelId, pollIntervalMs, signal)\n result = await ChannelStore.deductFromChannel(store, channelId, amount)\n }\n }\n}\n\nasync function waitForUpdate(\n store: ChannelStore.ChannelStore,\n channelId: Hex,\n pollIntervalMs: number,\n signal?: AbortSignal,\n): Promise<void> {\n if (signal?.aborted) throw new Error('Aborted while waiting for voucher')\n if (store.waitForUpdate) {\n await Promise.race([store.waitForUpdate(channelId), ...(signal ? [abortPromise(signal)] : [])])\n } else {\n await sleep(pollIntervalMs)\n }\n if (signal?.aborted) throw new Error('Aborted while waiting for voucher')\n}\n\nfunction abortPromise(signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) return resolve()\n signal.addEventListener('abort', () => resolve(), { once: true })\n })\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Check whether a `Response` carries an SSE event stream.\n *\n * Returns `true` when the `Content-Type` header starts with\n * `text/event-stream` (case-insensitive, ignoring charset params).\n */\nexport function isEventStream(response: Response): boolean {\n const ct = response.headers.get('content-type')\n return ct?.toLowerCase().startsWith('text/event-stream') ?? false\n}\n\n/**\n * Parse an SSE `Response` body into an async iterable of `data:` payloads.\n *\n * Yields the raw `data:` field content for each SSE event in the stream.\n * Events whose data matches the `skip` predicate are silently dropped\n * (e.g. `[DONE]` sentinels used by OpenAI-compatible APIs).\n *\n * Each yielded value typically becomes one charge tick when fed to\n * {@link serve} via the SSE transport's auto-charge mode.\n *\n * @example\n * ```ts\n * const upstream = await fetch('https://api.example.com/stream')\n * for await (const data of Sse.iterateData(upstream)) {\n * console.log(data)\n * }\n * ```\n */\nexport async function* iterateData(\n response: Response,\n options?: iterateData.Options,\n): AsyncGenerator<string> {\n const skip = options?.skip\n const body = response.body\n if (!body) return\n\n const reader = body.getReader()\n const decoder = new TextDecoder()\n let buffer = ''\n\n try {\n while (true) {\n const { value, done } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n\n // Split on double-newline SSE event boundaries.\n const events = buffer.split('\\n\\n')\n // Last element may be incomplete — keep in buffer.\n buffer = events.pop() ?? ''\n\n for (const event of events) {\n if (!event.trim()) continue\n const data = extractData(event)\n if (data === null) continue\n if (skip?.(data)) continue\n yield data\n }\n }\n\n // Flush remaining buffer.\n if (buffer.trim()) {\n const data = extractData(buffer)\n if (data !== null && !skip?.(data)) yield data\n }\n } finally {\n reader.releaseLock()\n }\n}\n\nexport declare namespace iterateData {\n type Options = {\n /** Predicate to skip specific data payloads (e.g. `d => d === '[DONE]'`). */\n skip?: ((data: string) => boolean) | undefined\n }\n}\n\n/** Extract the `data:` field value from a single SSE event block. */\nfunction extractData(event: string): string | null {\n const dataLines: string[] = []\n for (const line of event.split('\\n')) {\n if (line.startsWith('data: ')) dataLines.push(line.slice(6))\n else if (line === 'data:') dataLines.push('')\n }\n return dataLines.length > 0 ? dataLines.join('\\n') : null\n}\n","import type { Hex } from 'ox'\nimport type { Address } from 'viem'\n\nimport type * as Challenge from '../../Challenge.js'\nimport * as Fetch from '../../client/internal/Fetch.js'\nimport type * as Account from '../../viem/Account.js'\nimport type * as Client from '../../viem/Client.js'\nimport { deserializeSessionReceipt } from '../session/Receipt.js'\nimport { parseEvent } from '../session/Sse.js'\nimport type { SessionReceipt } from '../session/Types.js'\nimport type { ChannelEntry } from './ChannelOps.js'\nimport { session as sessionPlugin } from './Session.js'\n\nexport type SessionManager = {\n readonly channelId: Hex.Hex | undefined\n readonly cumulative: bigint\n readonly opened: boolean\n\n open(options?: { deposit?: bigint }): Promise<void>\n fetch(input: RequestInfo | URL, init?: RequestInit): Promise<PaymentResponse>\n sse(\n input: RequestInfo | URL,\n init?: RequestInit & {\n onReceipt?: ((receipt: SessionReceipt) => void) | undefined\n signal?: AbortSignal | undefined\n },\n ): Promise<AsyncIterable<string>>\n close(): Promise<SessionReceipt | undefined>\n}\n\nexport type PaymentResponse = Response & {\n receipt: SessionReceipt | null\n challenge: Challenge.Challenge | null\n channelId: Hex.Hex | null\n cumulative: bigint\n}\n\n/**\n * Creates a session manager that handles the full client payment lifecycle:\n * channel open, incremental vouchers, SSE streaming, and channel close.\n *\n * Internally delegates to the `session()` method for all\n * channel state management and credential creation, and to `Fetch.from`\n * for the 402 challenge/retry flow.\n *\n * ## Session resumption\n *\n * All channel state is held **in memory**. If the client process restarts,\n * the session is lost and a new on-chain channel will be opened on the next\n * request — the previous channel's deposit is orphaned until manually closed.\n *\n * When the server includes a `channelId` in the 402 challenge `methodDetails`,\n * the client will attempt to recover the channel by reading its on-chain state\n * via `getOnChainChannel()`. If the channel has a positive deposit and is not\n * finalized, it resumes from the on-chain settled amount.\n */\nexport function sessionManager(parameters: sessionManager.Parameters): SessionManager {\n const fetchFn = parameters.fetch ?? globalThis.fetch\n\n let channel: ChannelEntry | null = null\n let lastChallenge: Challenge.Challenge | null = null\n let lastUrl: RequestInfo | URL | null = null\n let spent = 0n\n\n const method = sessionPlugin({\n account: parameters.account,\n authorizedSigner: parameters.authorizedSigner,\n getClient: parameters.client ? () => parameters.client! : parameters.getClient,\n escrowContract: parameters.escrowContract,\n decimals: parameters.decimals,\n maxDeposit: parameters.maxDeposit,\n onChannelUpdate(entry) {\n if (entry.channelId !== channel?.channelId) spent = 0n\n channel = entry\n },\n })\n\n const wrappedFetch = Fetch.from({\n fetch: fetchFn,\n methods: [method],\n onChallenge: async (challenge, _helpers) => {\n lastChallenge = challenge\n return undefined\n },\n })\n\n function updateSpentFromReceipt(receipt: SessionReceipt | null | undefined) {\n if (!receipt || receipt.channelId !== channel?.channelId) return\n const next = BigInt(receipt.spent)\n spent = spent > next ? spent : next\n }\n\n function toPaymentResponse(response: Response): PaymentResponse {\n const receiptHeader = response.headers.get('Payment-Receipt')\n const receipt = receiptHeader ? deserializeSessionReceipt(receiptHeader) : null\n updateSpentFromReceipt(receipt)\n return Object.assign(response, {\n receipt,\n challenge: lastChallenge,\n channelId: channel?.channelId ?? null,\n cumulative: channel?.cumulativeAmount ?? 0n,\n })\n }\n\n async function doFetch(input: RequestInfo | URL, init?: RequestInit): Promise<PaymentResponse> {\n lastUrl = input\n const response = await wrappedFetch(input, init)\n return toPaymentResponse(response)\n }\n\n const self: SessionManager = {\n get channelId() {\n return channel?.channelId\n },\n get cumulative() {\n return channel?.cumulativeAmount ?? 0n\n },\n get opened() {\n return channel?.opened ?? false\n },\n\n async open(options) {\n if (channel?.opened) return\n\n if (!lastChallenge) {\n throw new Error(\n 'No challenge available. Make a request first to receive a 402 challenge, or pass a challenge via .fetch()/.sse().',\n )\n }\n\n const deposit = options?.deposit\n const credential = await method.createCredential({\n challenge: lastChallenge as never,\n context: {\n ...(deposit !== undefined && { depositRaw: deposit.toString() }),\n },\n })\n\n if (!lastUrl) throw new Error('No URL available — call fetch() or sse() before open().')\n const response = await fetchFn(lastUrl, {\n method: 'POST',\n headers: { Authorization: credential },\n })\n if (!response.ok) {\n const body = await response.text().catch(() => '')\n const wwwAuth = response.headers.get('WWW-Authenticate') ?? ''\n throw new Error(\n `Open request failed with status ${response.status}${body ? `: ${body}` : ''}${wwwAuth ? ` [WWW-Authenticate: ${wwwAuth}]` : ''}`,\n )\n }\n },\n\n fetch: doFetch,\n\n async sse(input, init) {\n const { onReceipt, signal, ...fetchInit } = init ?? {}\n\n const sseInit = {\n ...fetchInit,\n headers: {\n ...Fetch.normalizeHeaders(fetchInit.headers),\n Accept: 'text/event-stream',\n },\n ...(signal ? { signal } : {}),\n }\n\n const response = await doFetch(input, sseInit)\n\n // Snapshot the challenge at SSE open time so concurrent\n // calls don't overwrite it.\n const sseChallenge = lastChallenge\n\n if (!response.body) throw new Error('Response has no body.')\n\n const reader = response.body.getReader()\n const decoder = new TextDecoder()\n\n async function* iterate(): AsyncGenerator<string> {\n let buffer = ''\n\n try {\n while (true) {\n if (signal?.aborted) break\n\n const { done, value } = await reader.read()\n if (done) break\n\n buffer += decoder.decode(value, { stream: true })\n\n const parts = buffer.split('\\n\\n')\n buffer = parts.pop()!\n\n for (const part of parts) {\n if (!part.trim()) continue\n\n const event = parseEvent(part)\n if (!event) continue\n\n switch (event.type) {\n case 'message':\n yield event.data\n break\n\n case 'payment-need-voucher': {\n if (!channel || !sseChallenge) break\n const required = BigInt(event.data.requiredCumulative)\n channel.cumulativeAmount =\n channel.cumulativeAmount > required ? channel.cumulativeAmount : required\n\n const credential = await method.createCredential({\n challenge: sseChallenge as never,\n context: {\n action: 'voucher',\n channelId: channel.channelId,\n cumulativeAmountRaw: channel.cumulativeAmount.toString(),\n },\n })\n const voucherResponse = await fetchFn(input, {\n method: 'POST',\n headers: { Authorization: credential },\n })\n if (!voucherResponse.ok) {\n throw new Error(`Voucher POST failed with status ${voucherResponse.status}`)\n }\n break\n }\n\n case 'payment-receipt':\n updateSpentFromReceipt(event.data)\n onReceipt?.(event.data)\n break\n }\n }\n }\n } finally {\n reader.releaseLock()\n }\n }\n\n return iterate()\n },\n\n async close() {\n if (!channel?.opened || !lastChallenge) return undefined\n\n const credential = await method.createCredential({\n challenge: lastChallenge as never,\n context: {\n action: 'close',\n channelId: channel.channelId,\n cumulativeAmountRaw: spent.toString(),\n },\n })\n\n let receipt: SessionReceipt | undefined\n if (lastUrl) {\n const response = await fetchFn(lastUrl, {\n method: 'POST',\n headers: { Authorization: credential },\n })\n const receiptHeader = response.headers.get('Payment-Receipt')\n if (receiptHeader) receipt = deserializeSessionReceipt(receiptHeader)\n }\n\n return receipt\n },\n }\n\n return self\n}\n\nexport declare namespace sessionManager {\n type Parameters = Account.getResolver.Parameters &\n Client.getResolver.Parameters & {\n /** Address authorized to sign vouchers. Defaults to the account address. */\n authorizedSigner?: Address | undefined\n /** Viem client instance. Shorthand for `getClient: () => client`. */\n client?: import('viem').Client | undefined\n /** Token decimals used to convert `maxDeposit` to raw units. Defaults to `6`. */\n decimals?: number | undefined\n /** Escrow contract address. */\n escrowContract?: Address | undefined\n fetch?: typeof globalThis.fetch | undefined\n /** Maximum deposit in human-readable units (e.g. `'10'` for 10 tokens). Converted to raw units via `decimals`. */\n maxDeposit?: string | undefined\n }\n}\n","import { charge as charge_ } from './Charge.js'\nimport { session as sessionIntent_ } from './Session.js'\nimport { sessionManager as session_ } from './SessionManager.js'\n\n/**\n * Creates both Tempo `charge` and `session` client methods from shared parameters.\n *\n * @example\n * ```ts\n * import { Mppx, tempo } from 'mppx/client'\n *\n * const mppx = Mppx.create({\n * methods: [tempo({ account })],\n * })\n * ```\n */\nexport function tempo(parameters: tempo.Parameters = {}) {\n return [charge_(parameters), sessionIntent_(parameters)] as const\n}\n\nexport namespace tempo {\n export type Parameters = charge_.Parameters & sessionIntent_.Parameters\n\n /** Creates a Tempo `charge` client method for one-time TIP-20 token transfers. */\n export const charge = charge_\n /** Creates a client-side streaming session for managing payment channels. */\n export const session = session_\n}\n","import type * as Challenge from '../Challenge.js'\nimport type * as Method from '../Method.js'\nimport type * as z from '../zod.js'\nimport * as Fetch from './internal/Fetch.js'\nimport * as Transport from './Transport.js'\n\nexport type Methods = readonly (Method.AnyClient | readonly Method.AnyClient[])[]\n\n/**\n * Client-side payment handler.\n */\nexport type Mppx<\n methods extends Methods = Methods,\n transport extends Transport.Transport = Transport.Transport,\n> = {\n /** Payment-aware fetch function that automatically handles 402 responses. */\n fetch: Fetch.from.Fetch<FlattenMethods<methods>>\n /** The original, unwrapped fetch function (pre-polyfill). Useful when you need to make requests that should not be intercepted (e.g. 402 probes for websocket auth). */\n rawFetch: typeof globalThis.fetch\n /** Methods to configure. */\n methods: FlattenMethods<methods>\n /** The transport used. */\n transport: transport\n /** Creates a credential from a payment-required response by routing to the correct method. */\n createCredential: (\n response: Transport.ResponseOf<transport>,\n context?: AnyContextFor<FlattenMethods<methods>> | undefined,\n ) => Promise<string>\n}\n\n/**\n * Creates a client-side payment handler from an array of methods.\n *\n * Returns a payment handler with a `fetch` function that automatically handles\n * 402 Payment Required responses. By default, also polyfills `globalThis.fetch`.\n *\n * @example\n * ```ts\n * import { Mppx, tempo } from 'mppx/client'\n *\n * const mppx = Mppx.create({\n * methods: [tempo({ account })],\n * })\n *\n * // Use the returned fetch — handles 402 automatically\n * const res = await mppx.fetch('/resource')\n *\n * // Or use globalThis.fetch (polyfilled by default)\n * const res2 = await fetch('/resource')\n * ```\n */\nexport function create<\n const methods extends Methods,\n const transport extends Transport.Transport<any, any> = Transport.Transport<\n RequestInit,\n Response\n >,\n>(config: create.Config<methods, transport>): Mppx<methods, transport> {\n const { onChallenge, polyfill = true, transport = Transport.http() as transport } = config\n\n const rawFetch = config.fetch ?? globalThis.fetch\n\n const methods = config.methods.flat() as unknown as FlattenMethods<methods>\n\n const resolvedOnChallenge = onChallenge as Fetch.from.Config<\n FlattenMethods<methods>\n >['onChallenge']\n const config_fetch = {\n ...(config.fetch && { fetch: config.fetch }),\n ...(resolvedOnChallenge && { onChallenge: resolvedOnChallenge }),\n methods,\n } satisfies Fetch.from.Config<FlattenMethods<methods>>\n const fetch = Fetch.from<FlattenMethods<methods>>(config_fetch)\n\n if (polyfill) Fetch.polyfill(config_fetch)\n return {\n fetch,\n rawFetch,\n methods,\n transport,\n async createCredential(response: Transport.ResponseOf<transport>, context?: unknown) {\n const challenge = transport.getChallenge(response as never) as Challenge.Challenge\n\n const mi = methods.find((m) => m.name === challenge.method && m.intent === challenge.intent)\n if (!mi)\n throw new Error(\n `No method found for \"${challenge.method}.${challenge.intent}\". Available: ${methods.map((m) => `${m.name}.${m.intent}`).join(', ')}`,\n )\n\n const parsedContext =\n mi.context && context !== undefined ? mi.context.parse(context) : undefined\n\n return mi.createCredential(\n parsedContext !== undefined\n ? { challenge, context: parsedContext }\n : ({ challenge } as never),\n )\n },\n }\n}\n\n/**\n * Restores the original `fetch` after `create()` polyfilled it.\n *\n * @example\n * ```ts\n * import { Mppx, tempo } from 'mppx/client'\n *\n * Mppx.create({ methods: [tempo({ account })] })\n *\n * // ... use payment-aware fetch ...\n *\n * Mppx.restore()\n * ```\n */\nexport function restore(): void {\n Fetch.restore()\n}\n\nexport declare namespace create {\n type Config<\n methods extends Methods = Methods,\n transport extends Transport.Transport = Transport.Transport,\n > = {\n /** Custom fetch function to wrap. Defaults to `globalThis.fetch`. */\n fetch?: typeof globalThis.fetch\n /** Called when a 402 challenge is received, before credential creation. */\n onChallenge?:\n | ((\n challenge: Challenge.Challenge,\n helpers: {\n createCredential: (context?: AnyContextFor<FlattenMethods<methods>>) => Promise<string>\n },\n ) => Promise<string | undefined>)\n | undefined\n /** Array of methods to use. Accepts individual clients or tuples (e.g. from `tempo()`). */\n methods: methods\n /** Whether to polyfill `globalThis.fetch` with the payment-aware wrapper. @default true */\n polyfill?: boolean | undefined\n /** Transport to use (defaults to HTTP). */\n transport?: transport | undefined\n }\n}\n\n/**\n * Union of all context types from all methods that have context schemas.\n * @internal\n */\ntype AnyContextFor<methods extends readonly Method.AnyClient[]> = {\n [method in keyof methods]: NonNullable<methods[method]['context']> extends infer ctx\n ? ctx extends z.ZodMiniType\n ? z.input<ctx>\n : undefined\n : undefined\n}[number]\n\n/**\n * Flattens a methods config tuple, preserving positional types.\n * @internal\n */\ntype FlattenMethods<methods extends Methods> = methods extends readonly [\n infer head,\n ...infer tail extends Methods,\n]\n ? head extends readonly Method.AnyClient[]\n ? readonly [...head, ...FlattenMethods<tail>]\n : head extends Method.AnyClient\n ? readonly [head, ...FlattenMethods<tail>]\n : never\n : readonly []\n","import * as Challenge from '../Challenge.js'\nimport * as Credential from '../Credential.js'\nimport * as Mcp from '../Mcp.js'\n\n/**\n * Client-side transport adapter.\n *\n * Abstracts how challenges are received and credentials are sent\n * across different transport protocols (HTTP, MCP, etc.).\n */\nexport type Transport<in out request = unknown, in out response = unknown> = {\n /** Transport name for identification. */\n name: string\n /** Checks if a response indicates payment is required. */\n isPaymentRequired: (response: response) => boolean\n /** Extracts the challenge from a payment-required response. */\n getChallenge: (response: response) => Challenge.Challenge\n /** Attaches a credential to a request. */\n setCredential: (request: request, credential: string) => request\n}\nexport type AnyTransport = Transport<any, any>\n\n/** Extracts the response type from a transport. */\nexport type ResponseOf<transport extends Transport> =\n transport extends Transport<any, infer response> ? response : never\n\n/** Extracts the request type from a transport. */\nexport type RequestOf<transport extends Transport> =\n transport extends Transport<infer request, any> ? request : never\n\n/**\n * Creates a custom client-side transport.\n *\n * @example\n * ```ts\n * import { Transport } from 'mppx/client'\n *\n * const custom = Transport.from({\n * name: 'custom',\n * isPaymentRequired(response) { ... },\n * getChallenge(response) { ... },\n * setCredential(request, credential) { ... },\n * })\n * ```\n */\nexport function from<request, response>(\n transport: Transport<request, response>,\n): Transport<request, response> {\n return transport\n}\n\n/**\n * HTTP transport for client-side payment handling.\n *\n * - Detects payment required via 402 status\n * - Extracts challenges from `WWW-Authenticate` header\n * - Sends credentials via `Authorization` header\n */\nexport function http() {\n return from<RequestInit, Response>({\n name: 'http',\n\n isPaymentRequired(response) {\n return response.status === 402\n },\n\n getChallenge(response) {\n return Challenge.fromResponse(response)\n },\n\n setCredential(request, credential) {\n const headers = new Headers(request.headers)\n headers.set('Authorization', credential)\n return { ...request, headers }\n },\n })\n}\n\n/**\n * MCP transport for client-side payment handling.\n *\n * - Detects payment required via error code -32042\n * - Extracts challenges from `error.data.challenges[0]`\n * - Sends credentials via `_meta[\"org.paymentauth/credential\"]`\n */\nexport function mcp() {\n return from<Mcp.Request, Mcp.Response>({\n name: 'mcp',\n\n isPaymentRequired(response) {\n return 'error' in response && response.error?.code === Mcp.paymentRequiredCode\n },\n\n getChallenge(response) {\n if (!('error' in response) || !response.error) throw new Error('Response is not an error.')\n const challenge = response.error.data?.challenges[0]\n if (!challenge) throw new Error('No challenge in error response.')\n return challenge\n },\n\n setCredential(request, credential) {\n const parsed = Credential.deserialize(credential)\n return {\n ...request,\n params: {\n ...request.params,\n _meta: {\n ...request.params?._meta,\n [Mcp.credentialMetaKey]: parsed,\n },\n },\n }\n },\n })\n}\n"],"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AAU;AAChD,aAAO;QACL,GAAG;QACH,QAAQ;UACN,GAAG,QAAQ;UACX,OAAO;YACL,GAAG,QAAQ,QAAQ;YACnB,CAAK,iBAAiB,GAAG;;;;IAIjC;GACD;AACH;;;AD/DM,SAAUE,QAMd,QAAyC;AACzC,QAAM,EAAE,aAAa,UAAAC,YAAW,MAAM,YAAsBC,MAAI,EAAe,IAAK;AAEpF,QAAM,WAAW,OAAO,SAAS,WAAW;AAE5C,QAAM,UAAU,OAAO,QAAQ,KAAI;AAEnC,QAAM,sBAAsB;AAG5B,QAAM,eAAe;IACnB,GAAI,OAAO,SAAS,EAAE,OAAO,OAAO,MAAK;IACzC,GAAI,uBAAuB,EAAE,aAAa,oBAAmB;IAC7D;;AAEF,QAAMC,SAAcC,OAA8B,YAAY;AAE9D,MAAIH;AAAU,IAAM,SAAS,YAAY;AACzC,SAAO;IACL,OAAAE;IACA;IACA;IACA;IACA,MAAM,iBAAiB,UAA2C,SAAiB;AACjF,YAAM,YAAY,UAAU,aAAa,QAAiB;AAE1D,YAAM,KAAK,QAAQ,KAAK,CAAC,MAAM,EAAE,SAAS,UAAU,UAAU,EAAE,WAAW,UAAU,MAAM;AAC3F,UAAI,CAAC;AACH,cAAM,IAAI,MACR,wBAAwB,UAAU,MAAM,IAAI,UAAU,MAAM,iBAAiB,QAAQ,IAAI,CAAC,MAAM,GAAG,EAAE,IAAI,IAAI,EAAE,MAAM,EAAE,EAAE,KAAK,IAAI,CAAC,EAAE;AAGzI,YAAM,gBACJ,GAAG,WAAW,YAAY,SAAY,GAAG,QAAQ,MAAM,OAAO,IAAI;AAEpE,aAAO,GAAG,iBACR,kBAAkB,SACd,EAAE,WAAW,SAAS,cAAa,IAClC,EAAE,UAAS,CAAY;IAEhC;;AAEJ;AAgBM,SAAUE,WAAO;AACrB,EAAM,QAAO;AACf;","names":["BaseError","type","signature","docsPath","BaseError","err","recoverPublicKey","hash","signature","toHex","secp256k1","yParityOrV","recoveryBit","size","hash","signature","recoverPublicKey","to","list","encode","BaseError","chainId","nonce","to","hash","signature","BaseError","docsPath","nonce","to","docsPath","cause","BaseError","BaseError","format","type","decimals","to","to","sha256","to","toHex","version","to","sha256","version","to","BaseError","size","hash","version","to","size","to","docsPath","cause","nonceManager","to","type","nonce","chainId","format","decimals","nonceManager","prepareTransactionRequest","chainId","getChainId","nonce","from","gas","type","e","error","getBlock","block","to","BaseError","nonce","format","docsPath","signature","size","isEqual","index","value","input","event","listeners","cleanup","poll","cacheKey","stringify","transport","eventName","args","BaseError","docsPath","type","nonce","type","to","BaseError","chainId","format","concat","hash","e","writeContract","BaseError","shouldRetry","resolve","version","call","concat","BaseError","resolve","chainId","receipts","hash","status","version","statusCode","stringify","resolve","result","BaseError","size","type","key","chainId","hash","size","version","slice","to","BaseError","signature","type","chainId","nonce","to","blobs","commitments","proofs","v","chainId","nonce","signature","toHex","signature","promiseCache","uid","stringify","BaseError","to","length","BaseError","hash","size","resolve","stringify","body","response","BaseError","stringify","types","type","types","type","stringify","size","struct","type","assert","from","validate","LruMap","size","LruMap","keccak256","from","sha256","from","validate","size","assert","from","validate","fromHex","fromBytes","assert","x","slice","prefix","toBytes","toHex","concat","fromNumber","BaseError","stringify","size","from","assert","InvalidAddressError","checksum","hash","keccak256","fromString","from","fromPublicKey","toHex","isEqual","validate","BaseError","bytesRegex","integerRegex","maxUint256","checksumAddress","type","checksum","wrap","slice","toNumber","length","consumed","value","size","toBigInt","toString","integerRegex","fromNumber","concat","assert","BytesSizeMismatchError","BaseError","fromString","index","PositionOutOfBoundsError","size","BaseError","checksumAddress","fromHex","size","data","encode","types","type","concat","encodePacked","assert","fromString","integerRegex","fromNumber","bytesRegex","BytesSizeMismatchError","from","BaseError","size","type","BytesSizeMismatchError","toHex","to","fromHex","length","readLength","readList","BaseError","from","getEncodable","fromHex","from","getEncodable","getEncodableList","getEncodableBytes","list","getSizeOfLength","encode","BaseError","assert","signature","maxUint256","fromBytes","fromHex","InvalidSerializedSizeError","slice","yParity","extract","from","fromRpc","signature","fromRpc","yParity","from","toHex","signature","assert","concat","fromNumber","toRpc","signature","fromNumber","trimLeft","InvalidSerializedSizeError","BaseError","signature","size","from","stringify","from","fromRpc","chainId","nonce","signature","extract","hash","keccak256","concat","fromHex","toTuple","toRpc","chainId","nonce","signature","fromNumber","extract","recoverAddress","fromPublicKey","recoverPublicKey","signature","from","verify","hash","signature","isEqual","recoverAddress","from","toBytes","from","assert","slice","toNumber","signature","to","recoverAddress","encode","fromNumber","size","concat","validate","BaseError","serializedType","type","chainId","nonce","to","signature","BaseError","decimals","hash","index","nonce","format","hash","format","result","BaseError","InvalidWrappedSignatureError","assert","from","magicBytes","unwrap","validate","wrap","magicBytes","assert","slice","InvalidWrappedSignatureError","from","unwrap","to","signature","wrap","concat","encode","validate","BaseError","to","signature","hash","signature","to","stringify","transport","hash","stringify","resolve","from","nonce","format","supportsWalletNamespace","nonce","type","to","BaseError","chainId","format","concat","hash","e","chainId","format","types","type","uid","BaseError","wait","body","from","amount","decimals","charge","amount","currency","charge","stripe","MissingPropertiesError","VerificationError","assert","deserialize","from","fromRpc","magicBytes","serialize","toRpc","validate","verify","verify","hash","signature","fromHex","toHex","toBytes","size","verify","signature","fromHex","sha256","fromString","isEqual","toBytes","concat","verify","magicBytes","assert","type","secp256k1","MissingPropertiesError","signature","fromPublicKey","recoverPublicKey","deserialize","slice","size","fromHex","toBigInt","toNumber","toString","from","fromRpc","serialize","concat","toHex","fromNumber","fromString","toRpc","validate","verify","isEqual","VerificationError","BaseError","stringify","InvalidPrefixError","assert","checksum","InvalidPrefixError","BaseError","from","fromRpc","chainId","nonce","signature","fromRpcList","fromTuple","deserialize","list","toRpc","chainId","nonce","signature","fromNumber","toRpcList","toTuple","serialize","list","deserialize","from","fromRpc","fromTuple","getSignPayload","hash","serialize","toRpc","toTuple","from","fromRpc","chainId","signature","toBigInt","fromTuple","hexToNumber","deserialize","getSignPayload","hash","toHex","toTuple","fromHex","keccak256","serialize","toRpc","type","fromNumber","numberToHex","toNumber","from","from","from","toBigInt","slice","assert","fromNumber","concat","hash","keccak256","encode","from","keccak256","concat","serialize","serialize","keccak256","fromString","fromRpc","fromRpcType","toRpc","toRpcType","fromRpc","signature","extract","toRpc","fromNumber","toRpcType","fromRpcType","fromRpc","fromRpcList","call","toRpc","toRpcList","fromNumber","toRpc","toRpc","fromNumber","toRpc","toRpcList","call","fromNumber","toRpcType","assert","deserialize","from","getSignPayload","hash","serialize","validate","fromTupleList","list","assert","validate","trimLeft","toTupleList","size","InvalidStorageKeySizeError","BaseError","decimals","formatGwei","FeeCapTooHighError","BaseError","formatGwei","InvalidChainIdError","BaseError","chainId","InvalidSerializedError","type","TipAboveFeeCapError","formatGwei","assert","chainId","call","InvalidChainIdError","FeeCapTooHighError","TipAboveFeeCapError","deserialize","toHex","slice","nonce","signature","InvalidSerializedError","validate","to","fromTupleList","fromTuple","getSignPayload","from","serialize","toTupleList","fromNumber","fromPublicKey","recoverAddress","toTuple","concat","fromHex","hash","keccak256","BaseError","getType","type","deserialize","slice","serialize","signature","fromNumber","nonce","chainId","recoverAddress","hash","feePayerSignature","from","formatTransaction","nonce","fromNumber","formatTransactionReceipt","formatTransactionRequest","type","formatTransaction","formatTransactionReceipt","formatTransactionRequest","signature","serialize","hash","chainId","type","signature","accountKeychain","feeManager","stablecoinDex","tip20Factory","tip403Registry","validator","call","authorize","chainId","revoke","call","accountKeychain","updateLimit","getMetadata","getRemainingLimit","getPool","feeManager","getLiquidityBalance","call","rebalanceSwap","to","mint","burn","buy","call","stablecoinDex","cancel","cancelStale","createPair","getBalance","getBuyQuote","getOrder","getOrderbook","getTickLevel","getSellQuote","place","amount","type","placeFlip","sell","withdraw","keccak256","concat","hash","getUserToken","call","feeManager","setUserToken","validator","getValidatorToken","setValidatorToken","getNonce","call","create","create","type","call","tip403Registry","setAdmin","modifyWhitelist","modifyBlacklist","getData","isAuthorized","claim","call","distribute","amount","getGlobalRewardPerToken","getPendingRewards","getUserRewardInfo","setRecipient","burn","burnSync","create","createSync","getBalance","getMetadata","mint","mintSync","watchBurn","watchCreate","watchMint","approve","call","amount","burnBlocked","from","burn","burnSync","changeTransferPolicy","create","currency","tip20Factory","createSync","getAllowance","getBalance","getMetadata","decimals","getRoleAdmin","hasRole","grantRoles","to","mint","mintSync","pause","renounceRoles","revokeRoles","setSupplyCap","setRoleAdmin","transfer","unpause","prepareUpdateQuoteToken","updateQuoteToken","watchBurn","watchCreate","watchMint","type","add","call","validator","changeOwner","changeStatus","getNextFullDkgCeremony","getOwner","get","index","getByIndex","getCount","list","setNextFullDkgCeremony","update","deserialize","getResolver","rpcUrl","chainId","hash","encode","nonce","isEqual","isEqual","tokenIn","resolve","defaultCurrencies","currency","charge","from","amount","chainId","decimals","escrowContract","charge","getResolver","chainId","amount","currency","encode","resolve","hash","signature","SignatureEnvelope_exports","CoercionError","InvalidSerializedError","MissingPropertiesError","VerificationError","assert","deserialize","extractAddress","extractPublicKey","from","fromRpc","getType","magicBytes","serialize","toRpc","types","validate","verify","serializedP256Type","serializedWebAuthnType","serializedKeychainType","serializedKeychainV2Type","magicBytes","types","assert","type","getType","secp256k1","MissingPropertiesError","extractAddress","signature","extractPublicKey","deserialize","size","InvalidSerializedError","from","fromRpc","CoercionError","serialize","toRpc","validate","verify","VerificationError","escrowContract","chainId","signature","SignatureEnvelope_exports","escrowContract","chainId","escrowContract","signature","escrowContract","currency","chainId","signature","session","decimals","getResolver","currency","chainId","escrowContract","amount","signature","from","fetch","session","from","buffer","tempo","charge","session","create","restore","Transport_exports","from","http","from","http","create","polyfill","http","fetch","from","restore"]}
|