@seedprotocol/publish 0.4.8
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 +75 -0
- package/dist/config.d.ts +40 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/helpers/blockchain.d.ts +3 -0
- package/dist/helpers/blockchain.d.ts.map +1 -0
- package/dist/helpers/constants.d.ts +16 -0
- package/dist/helpers/constants.d.ts.map +1 -0
- package/dist/helpers/debugLog.d.ts +7 -0
- package/dist/helpers/debugLog.d.ts.map +1 -0
- package/dist/helpers/easDirect.d.ts +91 -0
- package/dist/helpers/easDirect.d.ts.map +1 -0
- package/dist/helpers/thirdweb/11155420/0x043462304114da543add6b693c686b7d98865f3e.d.ts +565 -0
- package/dist/helpers/thirdweb/11155420/0x043462304114da543add6b693c686b7d98865f3e.d.ts.map +1 -0
- package/dist/helpers/thirdweb/11155420/0x67a4881391ad8b1f197c6bf7a556d70f87c3a786.d.ts +1586 -0
- package/dist/helpers/thirdweb/11155420/0x67a4881391ad8b1f197c6bf7a556d70f87c3a786.d.ts.map +1 -0
- package/dist/helpers/thirdweb/11155420/0x76f47d88bfaf670f5208911181fcdc0e160cb16d.d.ts +2878 -0
- package/dist/helpers/thirdweb/11155420/0x76f47d88bfaf670f5208911181fcdc0e160cb16d.d.ts.map +1 -0
- package/dist/helpers/thirdweb/11155420/0xa2b8315fd0f31c334be1b137d9e0ffbb3f200e57.d.ts +2 -0
- package/dist/helpers/thirdweb/11155420/0xa2b8315fd0f31c334be1b137d9e0ffbb3f200e57.d.ts.map +1 -0
- package/dist/helpers/thirdweb/11155420/0xcd8c945872df8e664e55cf8885c85ea3ea8f2148.d.ts +1617 -0
- package/dist/helpers/thirdweb/11155420/0xcd8c945872df8e664e55cf8885c85ea3ea8f2148.d.ts.map +1 -0
- package/dist/helpers/thirdweb/11155420/nameSchemaAttestation.d.ts +45 -0
- package/dist/helpers/thirdweb/11155420/nameSchemaAttestation.d.ts.map +1 -0
- package/dist/helpers/thirdweb/11155420/schemaRegistry.d.ts +145 -0
- package/dist/helpers/thirdweb/11155420/schemaRegistry.d.ts.map +1 -0
- package/dist/helpers/thirdweb.d.ts +40 -0
- package/dist/helpers/thirdweb.d.ts.map +1 -0
- package/dist/helpers/transformPayloadToIntegerIds.d.ts +34 -0
- package/dist/helpers/transformPayloadToIntegerIds.d.ts.map +1 -0
- package/dist/helpers/uploadApi.d.ts +30 -0
- package/dist/helpers/uploadApi.d.ts.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +11733 -0
- package/dist/index.js.map +1 -0
- package/dist/react/ConnectButton.d.ts +4 -0
- package/dist/react/ConnectButton.d.ts.map +1 -0
- package/dist/react/PublishProvider.d.ts +19 -0
- package/dist/react/PublishProvider.d.ts.map +1 -0
- package/dist/services/PublishManager/actions/addSubscription.d.ts +2 -0
- package/dist/services/PublishManager/actions/addSubscription.d.ts.map +1 -0
- package/dist/services/PublishManager/actions/createPublish.d.ts +2 -0
- package/dist/services/PublishManager/actions/createPublish.d.ts.map +1 -0
- package/dist/services/PublishManager/actions/publishDone.d.ts +2 -0
- package/dist/services/PublishManager/actions/publishDone.d.ts.map +1 -0
- package/dist/services/PublishManager/actions/query.d.ts +2 -0
- package/dist/services/PublishManager/actions/query.d.ts.map +1 -0
- package/dist/services/PublishManager/actions/removeSubscription.d.ts +2 -0
- package/dist/services/PublishManager/actions/removeSubscription.d.ts.map +1 -0
- package/dist/services/PublishManager/actions/requestSavePublish.d.ts +2 -0
- package/dist/services/PublishManager/actions/requestSavePublish.d.ts.map +1 -0
- package/dist/services/PublishManager/actions/stopAll.d.ts +2 -0
- package/dist/services/PublishManager/actions/stopAll.d.ts.map +1 -0
- package/dist/services/PublishManager/actions/stopPublish.d.ts +2 -0
- package/dist/services/PublishManager/actions/stopPublish.d.ts.map +1 -0
- package/dist/services/PublishManager/actors/activeRouter.d.ts +3 -0
- package/dist/services/PublishManager/actors/activeRouter.d.ts.map +1 -0
- package/dist/services/PublishManager/actors/restoreFromDb.d.ts +3 -0
- package/dist/services/PublishManager/actors/restoreFromDb.d.ts.map +1 -0
- package/dist/services/PublishManager/actors/savePublish.d.ts +6 -0
- package/dist/services/PublishManager/actors/savePublish.d.ts.map +1 -0
- package/dist/services/PublishManager/actors/subscribe.d.ts +3 -0
- package/dist/services/PublishManager/actors/subscribe.d.ts.map +1 -0
- package/dist/services/PublishManager/index.d.ts +82 -0
- package/dist/services/PublishManager/index.d.ts.map +1 -0
- package/dist/services/configService.d.ts +15 -0
- package/dist/services/configService.d.ts.map +1 -0
- package/dist/services/publish/actors/checking.d.ts +9 -0
- package/dist/services/publish/actors/checking.d.ts.map +1 -0
- package/dist/services/publish/actors/createAttestationsDirectToEas.d.ts +6 -0
- package/dist/services/publish/actors/createAttestationsDirectToEas.d.ts.map +1 -0
- package/dist/services/publish/actors/persistSeedUid.d.ts +11 -0
- package/dist/services/publish/actors/persistSeedUid.d.ts.map +1 -0
- package/dist/services/publish/actors.d.ts +31 -0
- package/dist/services/publish/actors.d.ts.map +1 -0
- package/dist/services/publish/helpers/ensureEasSchemas.d.ts +14 -0
- package/dist/services/publish/helpers/ensureEasSchemas.d.ts.map +1 -0
- package/dist/services/publish/helpers/getSchemasNeedingNameAttestation.d.ts +17 -0
- package/dist/services/publish/helpers/getSchemasNeedingNameAttestation.d.ts.map +1 -0
- package/dist/services/publish/helpers/itemNeedsArweave.d.ts +16 -0
- package/dist/services/publish/helpers/itemNeedsArweave.d.ts.map +1 -0
- package/dist/services/publish/index.d.ts +116 -0
- package/dist/services/publish/index.d.ts.map +1 -0
- package/dist/services/publish/seeds.d.ts +2 -0
- package/dist/services/publish/seeds.d.ts.map +1 -0
- package/dist/services/publish/utils.d.ts +18 -0
- package/dist/services/publish/utils.d.ts.map +1 -0
- package/dist/services/publish/versions.d.ts +3 -0
- package/dist/services/publish/versions.d.ts.map +1 -0
- package/dist/services/shared.d.ts +7 -0
- package/dist/services/shared.d.ts.map +1 -0
- package/dist/services/upload/actors.d.ts +8 -0
- package/dist/services/upload/actors.d.ts.map +1 -0
- package/dist/services/upload/index.d.ts +2 -0
- package/dist/services/upload/index.d.ts.map +1 -0
- package/dist/services/upload/utils.d.ts +19 -0
- package/dist/services/upload/utils.d.ts.map +1 -0
- package/dist/types.d.ts +49 -0
- package/dist/types.d.ts.map +1 -0
- package/package.json +54 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/helpers/constants.ts","../src/config.ts","../../../node_modules/.bun/react@19.2.4/node_modules/react/cjs/react-jsx-runtime.production.js","../../../node_modules/.bun/react@19.2.4/node_modules/react/cjs/react-jsx-runtime.development.js","../../../node_modules/.bun/react@19.2.4/node_modules/react/jsx-runtime.js","../src/helpers/thirdweb/11155420/0x76f47d88bfaf670f5208911181fcdc0e160cb16d.ts","../../../node_modules/.bun/ms@2.1.3/node_modules/ms/index.js","../../../node_modules/.bun/debug@4.4.3/node_modules/debug/src/common.js","../../../node_modules/.bun/debug@4.4.3/node_modules/debug/src/browser.js","../src/helpers/thirdweb.ts","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/version.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/errors.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/regex.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/runtime/signatures.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/errors/abiItem.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/errors/signature.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/errors/struct.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/runtime/cache.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/runtime/utils.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/runtime/structs.js","../../../node_modules/.bun/abitype@1.0.8+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/parseAbiItem.js","../../../node_modules/.bun/abitype@1.1.0+6690c94970067bc4/node_modules/abitype/dist/esm/regex.js","../../../node_modules/.bun/abitype@1.1.0+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js","../../../node_modules/.bun/abitype@1.1.0+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js","../../../node_modules/.bun/abitype@1.1.0+6690c94970067bc4/node_modules/abitype/dist/esm/human-readable/formatAbiItem.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/abi/formatAbiItem.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/isHex.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/size.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/errors/version.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/errors/base.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/errors/abi.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/errors/data.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/pad.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/errors/encoding.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/trim.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/encoding/fromHex.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/encoding/toHex.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/encoding/toBytes.js","../../../node_modules/.bun/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js","../../../node_modules/.bun/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/utils.js","../../../node_modules/.bun/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/hash/keccak256.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/hash/hashSignature.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/hash/normalizeSignature.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/hash/toSignature.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/hash/toSignatureHash.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/lru.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/address/getAddress.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/slice.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/abi/encodeAbiParameters.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/hash/toFunctionSelector.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/errors/cursor.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/cursor.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/encoding/fromBytes.js","../../../node_modules/.bun/viem@2.39.0+41d9f8f613c4b93e/node_modules/viem/_esm/utils/abi/decodeAbiParameters.js","../../../node_modules/.bun/ox@0.7.0+6690c94970067bc4/node_modules/ox/_esm/core/version.js","../../../node_modules/.bun/ox@0.7.0+6690c94970067bc4/node_modules/ox/_esm/core/internal/errors.js","../../../node_modules/.bun/ox@0.7.0+6690c94970067bc4/node_modules/ox/_esm/core/Errors.js","../../../node_modules/.bun/ox@0.7.0+6690c94970067bc4/node_modules/ox/_esm/core/Json.js","../../../node_modules/.bun/ox@0.7.0+6690c94970067bc4/node_modules/ox/_esm/core/internal/bytes.js","../../../node_modules/.bun/ox@0.7.0+6690c94970067bc4/node_modules/ox/_esm/core/internal/hex.js","../../../node_modules/.bun/ox@0.7.0+6690c94970067bc4/node_modules/ox/_esm/core/Bytes.js","../../../node_modules/.bun/ox@0.7.0+6690c94970067bc4/node_modules/ox/_esm/core/Hex.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/encoding/helpers/is-hex.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/encoding/hex.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/rpc/actions/eth_call.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/domains.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/version.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/caching/lru.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/detect-platform.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/jwt/is-jwt.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/process.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/fetch.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/chains/utils.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/json.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/rpc/fetch-rpc.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/rpc/rpc.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/encoding/to-bytes.js","../../../node_modules/.bun/@noble+hashes@1.7.2/node_modules/@noble/hashes/esm/_assert.js","../../../node_modules/.bun/@noble+hashes@1.7.2/node_modules/@noble/hashes/esm/_u64.js","../../../node_modules/.bun/@noble+hashes@1.7.2/node_modules/@noble/hashes/esm/utils.js","../../../node_modules/.bun/@noble+hashes@1.7.2/node_modules/@noble/hashes/esm/sha3.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/hashing/keccak256.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/address.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/encoding/helpers/byte-size.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/abi/encodeAbiParameters.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/abi/prepare-method.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/promise/resolve-promised-value.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/transaction/utils.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/transaction/read-contract.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/extensions/modules/__generated__/IModularCore/read/getInstalledModules.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/transaction/prepare-transaction.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/transaction/prepare-contract-call.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/utils/promise/once.js","../../../node_modules/.bun/thirdweb@5.118.1+2750b37c5d83a1ba/node_modules/thirdweb/dist/esm/extensions/modules/__generated__/IModularCore/write/installModule.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/abi/formatAbiItem.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/isHex.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/size.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/errors/version.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/errors/base.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/errors/abi.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/errors/data.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/pad.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/errors/encoding.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/trim.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/encoding/fromHex.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/encoding/toHex.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/encoding/toBytes.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/hash/keccak256.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/errors/address.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/lru.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/address/getAddress.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/address/isAddress.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/concat.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/data/slice.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/regex.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/abi/encodeAbiParameters.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/errors/cursor.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/cursor.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/encoding/fromBytes.js","../../../node_modules/.bun/viem@2.46.2+41d9f8f613c4b93e/node_modules/viem/_esm/utils/abi/decodeAbiParameters.js","../src/react/ConnectButton.tsx","../src/react/PublishProvider.tsx","../src/helpers/thirdweb/11155420/schemaRegistry.ts","../src/helpers/thirdweb/11155420/nameSchemaAttestation.ts","../src/services/publish/helpers/ensureEasSchemas.ts","../src/helpers/thirdweb/11155420/0xcd8c945872df8e664e55cf8885c85ea3ea8f2148.ts","../../../node_modules/.bun/xstate@5.28.0/node_modules/xstate/dev/dist/xstate-dev.esm.js","../../../node_modules/.bun/xstate@5.28.0/node_modules/xstate/dist/raise-34c45204.esm.js","../../../node_modules/.bun/xstate@5.28.0/node_modules/xstate/actors/dist/xstate-actors.esm.js","../../../node_modules/.bun/xstate@5.28.0/node_modules/xstate/dist/assign-5f7ff891.esm.js","../../../node_modules/.bun/xstate@5.28.0/node_modules/xstate/dist/StateMachine-9ef88566.esm.js","../../../node_modules/.bun/xstate@5.28.0/node_modules/xstate/dist/log-1324d455.esm.js","../../../node_modules/.bun/xstate@5.28.0/node_modules/xstate/dist/xstate.esm.js","../src/helpers/thirdweb/11155420/0x043462304114da543add6b693c686b7d98865f3e.ts","../src/services/publish/actors/persistSeedUid.ts","../../../node_modules/.bun/bignumber.js@9.3.1/node_modules/bignumber.js/bignumber.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/ar.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/lib/api.js","../../../node_modules/.bun/base64-js@1.5.1/node_modules/base64-js/index.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/lib/utils.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/lib/crypto/webcrypto-driver.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/network.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/lib/error.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/lib/deepHash.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/lib/merkle.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/lib/transaction.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/lib/transaction-uploader.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/transactions.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/wallets.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/silo.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/chunks.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/blocks.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/common.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/net-config.js","../../../node_modules/.bun/arweave@1.15.7/node_modules/arweave/web/index.js","../src/helpers/blockchain.ts","../src/helpers/transformPayloadToIntegerIds.ts","../src/helpers/uploadApi.ts","../src/services/publish/actors.ts","../src/helpers/easDirect.ts","../src/services/publish/actors/createAttestationsDirectToEas.ts","../src/services/publish/helpers/itemNeedsArweave.ts","../src/services/publish/actors/checking.ts","../src/services/publish/index.ts"],"sourcesContent":["/**\n * Constants for the publish package.\n */\n/** EAS Schema Registry on Optimism Sepolia (chain 11155420) */\nexport const SCHEMA_REGISTRY_ADDRESS =\n '0x4200000000000000000000000000000000000020' as const\n\n/** Schema #1 (Name a Schema) - universal UID for naming attestations */\nexport const EAS_SCHEMA_NAME_ATTESTATION_UID =\n '0x44d562ac1d7cd77e232978687fea027ace48f719cf1d58c7888e509663bb87fc' as const\n\n/** Thirdweb ManagedAccount factory on Optimism Sepolia (chain 11155420) */\nexport const THIRDWEB_ACCOUNT_FACTORY_ADDRESS =\n '0x76f47d88bfaf670f5208911181fcdc0e160cb16d' as const\n\n/** EAS contract address on Optimism Sepolia (chain 11155420) */\nexport const EAS_CONTRACT_ADDRESS =\n '0x4200000000000000000000000000000000000021' as const\n\nexport const PublishMachineStates = {\n SUCCESS: 'success',\n FAILURE: 'failure',\n} as const\n","import {\n THIRDWEB_ACCOUNT_FACTORY_ADDRESS,\n EAS_CONTRACT_ADDRESS,\n} from './helpers/constants'\n\nexport interface PublishConfig {\n thirdwebClientId: string\n /** Upload API base URL (e.g. from VITE_UPLOAD_API_BASE_URL or NEXT_PUBLIC_UPLOAD_API_BASE_URL) */\n uploadApiBaseUrl: string\n /**\n * Use integer indices instead of string localId/publishLocalId for multiPublish (gas-efficient).\n * Set to true when using the new contract that expects uint256 localIdIndex/publishLocalIdIndex.\n * Default: false (uses string-based payload for backward compatibility).\n */\n useIntegerLocalIds?: boolean\n /**\n * Bypass the SeedProtocol contract and call EAS attest/multiAttest directly from the user's wallet.\n * Default: false (uses contract multiPublish).\n */\n useDirectEas?: boolean\n /**\n * Optional IModularCore module to ensure is installed on the connected account contract.\n * When set, onConnect will check getInstalledModules and install if missing.\n */\n modularAccountModuleContract?: string\n /** Optional module install data (default \"0x\"). Used with modularAccountModuleContract. */\n modularAccountModuleData?: string\n /**\n * Use the modular executor for multiPublish.\n * Default: false (uses the smart wallet executor).\n */\n useModularExecutor?: boolean\n}\n\n/** Use window (renderer) or globalThis so config survives across module instances (e.g. Vite chunks). */\nfunction getConfig(): PublishConfig | null {\n if (typeof window !== 'undefined' && window.__SEED_PUBLISH_CONFIG__ != null) {\n return window.__SEED_PUBLISH_CONFIG__\n }\n if (typeof globalThis !== 'undefined') {\n const g = globalThis as Record<string, unknown>\n const v = g['__SEED_PUBLISH_CONFIG__']\n if (v != null) return v as PublishConfig\n }\n return null\n}\n\nfunction setConfig(c: PublishConfig | null): void {\n if (typeof window !== 'undefined') {\n window.__SEED_PUBLISH_CONFIG__ = c\n }\n if (typeof globalThis !== 'undefined') {\n (globalThis as Record<string, unknown>)['__SEED_PUBLISH_CONFIG__'] = c\n }\n}\n\nexport function initPublish(c: PublishConfig): void {\n setConfig(c)\n}\n\nexport interface ResolvedPublishConfig extends PublishConfig {\n thirdwebAccountFactoryAddress: string\n uploadApiBaseUrl: string\n easContractAddress: string\n useIntegerLocalIds: boolean\n useDirectEas: boolean\n modularAccountModuleData: string\n useModularExecutor: boolean\n}\n\nexport function getPublishConfig(): ResolvedPublishConfig {\n const config = getConfig()\n if (!config) {\n throw new Error(\n '@seedprotocol/publish: Call initPublish({ thirdwebClientId, uploadApiBaseUrl }) before using the package'\n )\n }\n return {\n ...config,\n thirdwebAccountFactoryAddress: THIRDWEB_ACCOUNT_FACTORY_ADDRESS,\n easContractAddress: EAS_CONTRACT_ADDRESS,\n useIntegerLocalIds: config.useIntegerLocalIds ?? false,\n useDirectEas: config.useDirectEas ?? false,\n modularAccountModuleData: config.modularAccountModuleData ?? '0x',\n useModularExecutor: config.useModularExecutor ?? false,\n }\n}\n","/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (\n (\"number\" === typeof type.tag &&\n console.error(\n \"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.\"\n ),\n type.$$typeof)\n ) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return type.displayName || \"Context\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n }\n function testStringCoercion(value) {\n return \"\" + value;\n }\n function checkKeyStringCoercion(value) {\n try {\n testStringCoercion(value);\n var JSCompiler_inline_result = !1;\n } catch (e) {\n JSCompiler_inline_result = !0;\n }\n if (JSCompiler_inline_result) {\n JSCompiler_inline_result = console;\n var JSCompiler_temp_const = JSCompiler_inline_result.error;\n var JSCompiler_inline_result$jscomp$0 =\n (\"function\" === typeof Symbol &&\n Symbol.toStringTag &&\n value[Symbol.toStringTag]) ||\n value.constructor.name ||\n \"Object\";\n JSCompiler_temp_const.call(\n JSCompiler_inline_result,\n \"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.\",\n JSCompiler_inline_result$jscomp$0\n );\n return testStringCoercion(value);\n }\n }\n function getTaskName(type) {\n if (type === REACT_FRAGMENT_TYPE) return \"<>\";\n if (\n \"object\" === typeof type &&\n null !== type &&\n type.$$typeof === REACT_LAZY_TYPE\n )\n return \"<...>\";\n try {\n var name = getComponentNameFromType(type);\n return name ? \"<\" + name + \">\" : \"<...>\";\n } catch (x) {\n return \"<...>\";\n }\n }\n function getOwner() {\n var dispatcher = ReactSharedInternals.A;\n return null === dispatcher ? null : dispatcher.getOwner();\n }\n function UnknownOwner() {\n return Error(\"react-stack-top-frame\");\n }\n function hasValidKey(config) {\n if (hasOwnProperty.call(config, \"key\")) {\n var getter = Object.getOwnPropertyDescriptor(config, \"key\").get;\n if (getter && getter.isReactWarning) return !1;\n }\n return void 0 !== config.key;\n }\n function defineKeyPropWarningGetter(props, displayName) {\n function warnAboutAccessingKey() {\n specialPropKeyWarningShown ||\n ((specialPropKeyWarningShown = !0),\n console.error(\n \"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)\",\n displayName\n ));\n }\n warnAboutAccessingKey.isReactWarning = !0;\n Object.defineProperty(props, \"key\", {\n get: warnAboutAccessingKey,\n configurable: !0\n });\n }\n function elementRefGetterWithDeprecationWarning() {\n var componentName = getComponentNameFromType(this.type);\n didWarnAboutElementRef[componentName] ||\n ((didWarnAboutElementRef[componentName] = !0),\n console.error(\n \"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.\"\n ));\n componentName = this.props.ref;\n return void 0 !== componentName ? componentName : null;\n }\n function ReactElement(type, key, props, owner, debugStack, debugTask) {\n var refProp = props.ref;\n type = {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n props: props,\n _owner: owner\n };\n null !== (void 0 !== refProp ? refProp : null)\n ? Object.defineProperty(type, \"ref\", {\n enumerable: !1,\n get: elementRefGetterWithDeprecationWarning\n })\n : Object.defineProperty(type, \"ref\", { enumerable: !1, value: null });\n type._store = {};\n Object.defineProperty(type._store, \"validated\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: 0\n });\n Object.defineProperty(type, \"_debugInfo\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: null\n });\n Object.defineProperty(type, \"_debugStack\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugStack\n });\n Object.defineProperty(type, \"_debugTask\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugTask\n });\n Object.freeze && (Object.freeze(type.props), Object.freeze(type));\n return type;\n }\n function jsxDEVImpl(\n type,\n config,\n maybeKey,\n isStaticChildren,\n debugStack,\n debugTask\n ) {\n var children = config.children;\n if (void 0 !== children)\n if (isStaticChildren)\n if (isArrayImpl(children)) {\n for (\n isStaticChildren = 0;\n isStaticChildren < children.length;\n isStaticChildren++\n )\n validateChildKeys(children[isStaticChildren]);\n Object.freeze && Object.freeze(children);\n } else\n console.error(\n \"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.\"\n );\n else validateChildKeys(children);\n if (hasOwnProperty.call(config, \"key\")) {\n children = getComponentNameFromType(type);\n var keys = Object.keys(config).filter(function (k) {\n return \"key\" !== k;\n });\n isStaticChildren =\n 0 < keys.length\n ? \"{key: someKey, \" + keys.join(\": ..., \") + \": ...}\"\n : \"{key: someKey}\";\n didWarnAboutKeySpread[children + isStaticChildren] ||\n ((keys =\n 0 < keys.length ? \"{\" + keys.join(\": ..., \") + \": ...}\" : \"{}\"),\n console.error(\n 'A props object containing a \"key\" prop is being spread into JSX:\\n let props = %s;\\n <%s {...props} />\\nReact keys must be passed directly to JSX without using spread:\\n let props = %s;\\n <%s key={someKey} {...props} />',\n isStaticChildren,\n children,\n keys,\n children\n ),\n (didWarnAboutKeySpread[children + isStaticChildren] = !0));\n }\n children = null;\n void 0 !== maybeKey &&\n (checkKeyStringCoercion(maybeKey), (children = \"\" + maybeKey));\n hasValidKey(config) &&\n (checkKeyStringCoercion(config.key), (children = \"\" + config.key));\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n children &&\n defineKeyPropWarningGetter(\n maybeKey,\n \"function\" === typeof type\n ? type.displayName || type.name || \"Unknown\"\n : type\n );\n return ReactElement(\n type,\n children,\n maybeKey,\n getOwner(),\n debugStack,\n debugTask\n );\n }\n function validateChildKeys(node) {\n isValidElement(node)\n ? node._store && (node._store.validated = 1)\n : \"object\" === typeof node &&\n null !== node &&\n node.$$typeof === REACT_LAZY_TYPE &&\n (\"fulfilled\" === node._payload.status\n ? isValidElement(node._payload.value) &&\n node._payload.value._store &&\n (node._payload.value._store.validated = 1)\n : node._store && (node._store.validated = 1));\n }\n function isValidElement(object) {\n return (\n \"object\" === typeof object &&\n null !== object &&\n object.$$typeof === REACT_ELEMENT_TYPE\n );\n }\n var React = require(\"react\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\"),\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n hasOwnProperty = Object.prototype.hasOwnProperty,\n isArrayImpl = Array.isArray,\n createTask = console.createTask\n ? console.createTask\n : function () {\n return null;\n };\n React = {\n react_stack_bottom_frame: function (callStackForError) {\n return callStackForError();\n }\n };\n var specialPropKeyWarningShown;\n var didWarnAboutElementRef = {};\n var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(\n React,\n UnknownOwner\n )();\n var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));\n var didWarnAboutKeySpread = {};\n exports.Fragment = REACT_FRAGMENT_TYPE;\n exports.jsx = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !1,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n exports.jsxs = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !0,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import {\n prepareEvent,\n prepareContractCall,\n readContract,\n type BaseTransactionOptions,\n type AbiParameterToPrimitiveType,\n} from \"thirdweb\";\n\n/**\n* Contract events\n*/\n\n/**\n * Represents the filters for the \"AccountCreated\" event.\n */\nexport type AccountCreatedEventFilters = Partial<{\n account: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\",\"indexed\":true}>\naccountAdmin: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"accountAdmin\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the AccountCreated event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { accountCreatedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * accountCreatedEvent({\n * account: ...,\n * accountAdmin: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function accountCreatedEvent(filters: AccountCreatedEventFilters = {}) {\n return prepareEvent({\n signature: \"event AccountCreated(address indexed account, address indexed accountAdmin)\",\n filters,\n });\n};\n \n\n\n\n/**\n * Creates an event object for the ContractURIUpdated event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { contractURIUpdatedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * contractURIUpdatedEvent()\n * ],\n * });\n * ```\n */ \nexport function contractURIUpdatedEvent() {\n return prepareEvent({\n signature: \"event ContractURIUpdated(string prevURI, string newURI)\",\n });\n};\n \n\n/**\n * Represents the filters for the \"ExtensionAdded\" event.\n */\nexport type ExtensionAddedEventFilters = Partial<{\n name: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"name\",\"indexed\":true}>\nimplementation: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"implementation\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the ExtensionAdded event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { extensionAddedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * extensionAddedEvent({\n * name: ...,\n * implementation: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function extensionAddedEvent(filters: ExtensionAddedEventFilters = {}) {\n return prepareEvent({\n signature: \"event ExtensionAdded(string indexed name, address indexed implementation, ((string name, string metadataURI, address implementation) metadata, (bytes4 functionSelector, string functionSignature)[] functions) extension)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"ExtensionRemoved\" event.\n */\nexport type ExtensionRemovedEventFilters = Partial<{\n name: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"name\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the ExtensionRemoved event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { extensionRemovedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * extensionRemovedEvent({\n * name: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function extensionRemovedEvent(filters: ExtensionRemovedEventFilters = {}) {\n return prepareEvent({\n signature: \"event ExtensionRemoved(string indexed name, ((string name, string metadataURI, address implementation) metadata, (bytes4 functionSelector, string functionSignature)[] functions) extension)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"ExtensionReplaced\" event.\n */\nexport type ExtensionReplacedEventFilters = Partial<{\n name: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"name\",\"indexed\":true}>\nimplementation: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"implementation\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the ExtensionReplaced event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { extensionReplacedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * extensionReplacedEvent({\n * name: ...,\n * implementation: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function extensionReplacedEvent(filters: ExtensionReplacedEventFilters = {}) {\n return prepareEvent({\n signature: \"event ExtensionReplaced(string indexed name, address indexed implementation, ((string name, string metadataURI, address implementation) metadata, (bytes4 functionSelector, string functionSignature)[] functions) extension)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"FunctionDisabled\" event.\n */\nexport type FunctionDisabledEventFilters = Partial<{\n name: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"name\",\"indexed\":true}>\nfunctionSelector: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"functionSelector\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the FunctionDisabled event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { functionDisabledEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * functionDisabledEvent({\n * name: ...,\n * functionSelector: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function functionDisabledEvent(filters: FunctionDisabledEventFilters = {}) {\n return prepareEvent({\n signature: \"event FunctionDisabled(string indexed name, bytes4 indexed functionSelector, (string name, string metadataURI, address implementation) extMetadata)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"FunctionEnabled\" event.\n */\nexport type FunctionEnabledEventFilters = Partial<{\n name: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"name\",\"indexed\":true}>\nfunctionSelector: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"functionSelector\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the FunctionEnabled event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { functionEnabledEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * functionEnabledEvent({\n * name: ...,\n * functionSelector: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function functionEnabledEvent(filters: FunctionEnabledEventFilters = {}) {\n return prepareEvent({\n signature: \"event FunctionEnabled(string indexed name, bytes4 indexed functionSelector, (bytes4 functionSelector, string functionSignature) extFunction, (string name, string metadataURI, address implementation) extMetadata)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"RoleAdminChanged\" event.\n */\nexport type RoleAdminChangedEventFilters = Partial<{\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\",\"indexed\":true}>\npreviousAdminRole: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"previousAdminRole\",\"indexed\":true}>\nnewAdminRole: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"newAdminRole\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the RoleAdminChanged event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { roleAdminChangedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * roleAdminChangedEvent({\n * role: ...,\n * previousAdminRole: ...,\n * newAdminRole: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function roleAdminChangedEvent(filters: RoleAdminChangedEventFilters = {}) {\n return prepareEvent({\n signature: \"event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"RoleGranted\" event.\n */\nexport type RoleGrantedEventFilters = Partial<{\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\",\"indexed\":true}>\naccount: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\",\"indexed\":true}>\nsender: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"sender\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the RoleGranted event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { roleGrantedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * roleGrantedEvent({\n * role: ...,\n * account: ...,\n * sender: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function roleGrantedEvent(filters: RoleGrantedEventFilters = {}) {\n return prepareEvent({\n signature: \"event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"RoleRevoked\" event.\n */\nexport type RoleRevokedEventFilters = Partial<{\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\",\"indexed\":true}>\naccount: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\",\"indexed\":true}>\nsender: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"sender\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the RoleRevoked event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { roleRevokedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * roleRevokedEvent({\n * role: ...,\n * account: ...,\n * sender: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function roleRevokedEvent(filters: RoleRevokedEventFilters = {}) {\n return prepareEvent({\n signature: \"event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"SignerAdded\" event.\n */\nexport type SignerAddedEventFilters = Partial<{\n account: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\",\"indexed\":true}>\nsigner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the SignerAdded event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { signerAddedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * signerAddedEvent({\n * account: ...,\n * signer: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function signerAddedEvent(filters: SignerAddedEventFilters = {}) {\n return prepareEvent({\n signature: \"event SignerAdded(address indexed account, address indexed signer)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"SignerRemoved\" event.\n */\nexport type SignerRemovedEventFilters = Partial<{\n account: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\",\"indexed\":true}>\nsigner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the SignerRemoved event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { signerRemovedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * signerRemovedEvent({\n * account: ...,\n * signer: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function signerRemovedEvent(filters: SignerRemovedEventFilters = {}) {\n return prepareEvent({\n signature: \"event SignerRemoved(address indexed account, address indexed signer)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"AdminUpdated\" event.\n */\nexport type AdminUpdatedEventFilters = Partial<{\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the AdminUpdated event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { adminUpdatedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * adminUpdatedEvent({\n * signer: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function adminUpdatedEvent(filters: AdminUpdatedEventFilters = {}) {\n return prepareEvent({\n signature: \"event AdminUpdated(address indexed signer, bool isAdmin)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"SignerPermissionsUpdated\" event.\n */\nexport type SignerPermissionsUpdatedEventFilters = Partial<{\n authorizingSigner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"authorizingSigner\",\"indexed\":true}>\ntargetSigner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"targetSigner\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the SignerPermissionsUpdated event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { signerPermissionsUpdatedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * signerPermissionsUpdatedEvent({\n * authorizingSigner: ...,\n * targetSigner: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function signerPermissionsUpdatedEvent(filters: SignerPermissionsUpdatedEventFilters = {}) {\n return prepareEvent({\n signature: \"event SignerPermissionsUpdated(address indexed authorizingSigner, address indexed targetSigner, (address signer, uint8 isAdmin, address[] approvedTargets, uint256 nativeTokenLimitPerTransaction, uint128 permissionStartTimestamp, uint128 permissionEndTimestamp, uint128 reqValidityStartTimestamp, uint128 reqValidityEndTimestamp, bytes32 uid) permissions)\",\n filters,\n });\n};\n \n\n\n\n/**\n * Creates an event object for the CreatedAttestation event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { createdAttestationEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * createdAttestationEvent()\n * ],\n * });\n * ```\n */ \nexport function createdAttestationEvent() {\n return prepareEvent({\n signature: \"event CreatedAttestation((bytes32 schemaUid, bytes32 attestationUid) result)\",\n });\n};\n \n\n\n\n/**\n * Creates an event object for the EIP712DomainChanged event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { eIP712DomainChangedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * eIP712DomainChangedEvent()\n * ],\n * });\n * ```\n */ \nexport function eIP712DomainChangedEvent() {\n return prepareEvent({\n signature: \"event EIP712DomainChanged()\",\n });\n};\n \n\n\n\n/**\n * Creates an event object for the Initialized event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { initializedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * initializedEvent()\n * ],\n * });\n * ```\n */ \nexport function initializedEvent() {\n return prepareEvent({\n signature: \"event Initialized(uint8 version)\",\n });\n};\n \n\n\n\n/**\n * Creates an event object for the Log event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { logEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * logEvent()\n * ],\n * });\n * ```\n */ \nexport function logEvent() {\n return prepareEvent({\n signature: \"event Log(string message)\",\n });\n};\n \n\n/**\n * Represents the filters for the \"OwnershipTransferred\" event.\n */\nexport type OwnershipTransferredEventFilters = Partial<{\n previousOwner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"previousOwner\",\"indexed\":true}>\nnewOwner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"newOwner\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the OwnershipTransferred event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { ownershipTransferredEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * ownershipTransferredEvent({\n * previousOwner: ...,\n * newOwner: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function ownershipTransferredEvent(filters: OwnershipTransferredEventFilters = {}) {\n return prepareEvent({\n signature: \"event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)\",\n filters,\n });\n};\n \n\n\n\n/**\n * Creates an event object for the SeedPublished event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { seedPublishedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * seedPublishedEvent()\n * ],\n * });\n * ```\n */ \nexport function seedPublishedEvent() {\n return prepareEvent({\n signature: \"event SeedPublished(bytes returnedDataFromEAS)\",\n });\n};\n \n\n/**\n* Contract read functions\n*/\n\n\n\n/**\n * Calls the \"DEFAULT_ADMIN_ROLE\" function on the contract.\n * @param options - The options for the DEFAULT_ADMIN_ROLE function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { DEFAULT_ADMIN_ROLE } from \"TODO\";\n * \n * const result = await DEFAULT_ADMIN_ROLE();\n * \n * ```\n */\nexport async function DEFAULT_ADMIN_ROLE(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xa217fddf\",\n [],\n [\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"accountImplementation\" function on the contract.\n * @param options - The options for the accountImplementation function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { accountImplementation } from \"TODO\";\n * \n * const result = await accountImplementation();\n * \n * ```\n */\nexport async function accountImplementation(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x11464fbe\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"contractURI\" function on the contract.\n * @param options - The options for the contractURI function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { contractURI } from \"TODO\";\n * \n * const result = await contractURI();\n * \n * ```\n */\nexport async function contractURI(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xe8a3d485\",\n [],\n [\n {\n \"type\": \"string\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"defaultExtensions\" function on the contract.\n * @param options - The options for the defaultExtensions function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { defaultExtensions } from \"TODO\";\n * \n * const result = await defaultExtensions();\n * \n * ```\n */\nexport async function defaultExtensions(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x463c4864\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"entrypoint\" function on the contract.\n * @param options - The options for the entrypoint function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { entrypoint } from \"TODO\";\n * \n * const result = await entrypoint();\n * \n * ```\n */\nexport async function entrypoint(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xa65d69d4\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"getAccounts\" function.\n */\nexport type GetAccountsParams = {\n start: AbiParameterToPrimitiveType<{\"type\":\"uint256\",\"name\":\"_start\"}>\nend: AbiParameterToPrimitiveType<{\"type\":\"uint256\",\"name\":\"_end\"}>\n};\n\n/**\n * Calls the \"getAccounts\" function on the contract.\n * @param options - The options for the getAccounts function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAccounts } from \"TODO\";\n * \n * const result = await getAccounts({\n * start: ...,\n * end: ...,\n * });\n * \n * ```\n */\nexport async function getAccounts(\n options: BaseTransactionOptions<GetAccountsParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xe68a7c3b\",\n [\n {\n \"type\": \"uint256\",\n \"name\": \"_start\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"_end\"\n }\n ],\n [\n {\n \"type\": \"address[]\",\n \"name\": \"accounts\"\n }\n ]\n],\n params: [options.start, options.end]\n });\n};\n\n\n/**\n * Represents the parameters for the \"getAccountsOfSigner\" function.\n */\nexport type GetAccountsOfSignerParams = {\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\"}>\n};\n\n/**\n * Calls the \"getAccountsOfSigner\" function on the contract.\n * @param options - The options for the getAccountsOfSigner function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAccountsOfSigner } from \"TODO\";\n * \n * const result = await getAccountsOfSigner({\n * signer: ...,\n * });\n * \n * ```\n */\nexport async function getAccountsOfSigner(\n options: BaseTransactionOptions<GetAccountsOfSignerParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x0e6254fd\",\n [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n }\n ],\n [\n {\n \"type\": \"address[]\",\n \"name\": \"accounts\"\n }\n ]\n],\n params: [options.signer]\n });\n};\n\n\n/**\n * Represents the parameters for the \"getAddress\" function.\n */\nexport type GetAddressParams = {\n adminSigner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_adminSigner\"}>\ndata: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_data\"}>\n};\n\n/**\n * Calls the \"getAddress\" function on the contract.\n * @param options - The options for the getAddress function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAddress } from \"TODO\";\n * \n * const result = await getAddress({\n * adminSigner: ...,\n * data: ...,\n * });\n * \n * ```\n */\nexport async function getAddress(\n options: BaseTransactionOptions<GetAddressParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x8878ed33\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_adminSigner\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_data\"\n }\n ],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: [options.adminSigner, options.data]\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllAccounts\" function on the contract.\n * @param options - The options for the getAllAccounts function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllAccounts } from \"TODO\";\n * \n * const result = await getAllAccounts();\n * \n * ```\n */\nexport async function getAllAccounts(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x08e93d0a\",\n [],\n [\n {\n \"type\": \"address[]\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllExtensions\" function on the contract.\n * @param options - The options for the getAllExtensions function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllExtensions } from \"TODO\";\n * \n * const result = await getAllExtensions();\n * \n * ```\n */\nexport async function getAllExtensions(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x4a00cc48\",\n [],\n [\n {\n \"type\": \"tuple[]\",\n \"name\": \"allExtensions\",\n \"components\": [\n {\n \"type\": \"tuple\",\n \"name\": \"metadata\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"name\"\n },\n {\n \"type\": \"string\",\n \"name\": \"metadataURI\"\n },\n {\n \"type\": \"address\",\n \"name\": \"implementation\"\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"functions\",\n \"components\": [\n {\n \"type\": \"bytes4\",\n \"name\": \"functionSelector\"\n },\n {\n \"type\": \"string\",\n \"name\": \"functionSignature\"\n }\n ]\n }\n ]\n }\n ]\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"getExtension\" function.\n */\nexport type GetExtensionParams = {\n extensionName: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"extensionName\"}>\n};\n\n/**\n * Calls the \"getExtension\" function on the contract.\n * @param options - The options for the getExtension function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getExtension } from \"TODO\";\n * \n * const result = await getExtension({\n * extensionName: ...,\n * });\n * \n * ```\n */\nexport async function getExtension(\n options: BaseTransactionOptions<GetExtensionParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xc22707ee\",\n [\n {\n \"type\": \"string\",\n \"name\": \"extensionName\"\n }\n ],\n [\n {\n \"type\": \"tuple\",\n \"components\": [\n {\n \"type\": \"tuple\",\n \"name\": \"metadata\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"name\"\n },\n {\n \"type\": \"string\",\n \"name\": \"metadataURI\"\n },\n {\n \"type\": \"address\",\n \"name\": \"implementation\"\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"functions\",\n \"components\": [\n {\n \"type\": \"bytes4\",\n \"name\": \"functionSelector\"\n },\n {\n \"type\": \"string\",\n \"name\": \"functionSignature\"\n }\n ]\n }\n ]\n }\n ]\n],\n params: [options.extensionName]\n });\n};\n\n\n/**\n * Represents the parameters for the \"getImplementationForFunction\" function.\n */\nexport type GetImplementationForFunctionParams = {\n functionSelector: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"_functionSelector\"}>\n};\n\n/**\n * Calls the \"getImplementationForFunction\" function on the contract.\n * @param options - The options for the getImplementationForFunction function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getImplementationForFunction } from \"TODO\";\n * \n * const result = await getImplementationForFunction({\n * functionSelector: ...,\n * });\n * \n * ```\n */\nexport async function getImplementationForFunction(\n options: BaseTransactionOptions<GetImplementationForFunctionParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xce0b6013\",\n [\n {\n \"type\": \"bytes4\",\n \"name\": \"_functionSelector\"\n }\n ],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: [options.functionSelector]\n });\n};\n\n\n/**\n * Represents the parameters for the \"getMetadataForFunction\" function.\n */\nexport type GetMetadataForFunctionParams = {\n functionSelector: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"functionSelector\"}>\n};\n\n/**\n * Calls the \"getMetadataForFunction\" function on the contract.\n * @param options - The options for the getMetadataForFunction function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getMetadataForFunction } from \"TODO\";\n * \n * const result = await getMetadataForFunction({\n * functionSelector: ...,\n * });\n * \n * ```\n */\nexport async function getMetadataForFunction(\n options: BaseTransactionOptions<GetMetadataForFunctionParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xa0dbaefd\",\n [\n {\n \"type\": \"bytes4\",\n \"name\": \"functionSelector\"\n }\n ],\n [\n {\n \"type\": \"tuple\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"name\"\n },\n {\n \"type\": \"string\",\n \"name\": \"metadataURI\"\n },\n {\n \"type\": \"address\",\n \"name\": \"implementation\"\n }\n ]\n }\n ]\n],\n params: [options.functionSelector]\n });\n};\n\n\n/**\n * Represents the parameters for the \"getRoleAdmin\" function.\n */\nexport type GetRoleAdminParams = {\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\"}>\n};\n\n/**\n * Calls the \"getRoleAdmin\" function on the contract.\n * @param options - The options for the getRoleAdmin function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getRoleAdmin } from \"TODO\";\n * \n * const result = await getRoleAdmin({\n * role: ...,\n * });\n * \n * ```\n */\nexport async function getRoleAdmin(\n options: BaseTransactionOptions<GetRoleAdminParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x248a9ca3\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"role\"\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.role]\n });\n};\n\n\n/**\n * Represents the parameters for the \"getRoleMember\" function.\n */\nexport type GetRoleMemberParams = {\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\"}>\nindex: AbiParameterToPrimitiveType<{\"type\":\"uint256\",\"name\":\"index\"}>\n};\n\n/**\n * Calls the \"getRoleMember\" function on the contract.\n * @param options - The options for the getRoleMember function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getRoleMember } from \"TODO\";\n * \n * const result = await getRoleMember({\n * role: ...,\n * index: ...,\n * });\n * \n * ```\n */\nexport async function getRoleMember(\n options: BaseTransactionOptions<GetRoleMemberParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x9010d07c\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"role\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"index\"\n }\n ],\n [\n {\n \"type\": \"address\",\n \"name\": \"member\"\n }\n ]\n],\n params: [options.role, options.index]\n });\n};\n\n\n/**\n * Represents the parameters for the \"getRoleMemberCount\" function.\n */\nexport type GetRoleMemberCountParams = {\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\"}>\n};\n\n/**\n * Calls the \"getRoleMemberCount\" function on the contract.\n * @param options - The options for the getRoleMemberCount function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getRoleMemberCount } from \"TODO\";\n * \n * const result = await getRoleMemberCount({\n * role: ...,\n * });\n * \n * ```\n */\nexport async function getRoleMemberCount(\n options: BaseTransactionOptions<GetRoleMemberCountParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xca15c873\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"role\"\n }\n ],\n [\n {\n \"type\": \"uint256\",\n \"name\": \"count\"\n }\n ]\n],\n params: [options.role]\n });\n};\n\n\n/**\n * Represents the parameters for the \"hasRole\" function.\n */\nexport type HasRoleParams = {\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\"}>\naccount: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\"}>\n};\n\n/**\n * Calls the \"hasRole\" function on the contract.\n * @param options - The options for the hasRole function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { hasRole } from \"TODO\";\n * \n * const result = await hasRole({\n * role: ...,\n * account: ...,\n * });\n * \n * ```\n */\nexport async function hasRole(\n options: BaseTransactionOptions<HasRoleParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x91d14854\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"role\"\n },\n {\n \"type\": \"address\",\n \"name\": \"account\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.role, options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"hasRoleWithSwitch\" function.\n */\nexport type HasRoleWithSwitchParams = {\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\"}>\naccount: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\"}>\n};\n\n/**\n * Calls the \"hasRoleWithSwitch\" function on the contract.\n * @param options - The options for the hasRoleWithSwitch function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { hasRoleWithSwitch } from \"TODO\";\n * \n * const result = await hasRoleWithSwitch({\n * role: ...,\n * account: ...,\n * });\n * \n * ```\n */\nexport async function hasRoleWithSwitch(\n options: BaseTransactionOptions<HasRoleWithSwitchParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xa32fa5b3\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"role\"\n },\n {\n \"type\": \"address\",\n \"name\": \"account\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.role, options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isRegistered\" function.\n */\nexport type IsRegisteredParams = {\n account: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_account\"}>\n};\n\n/**\n * Calls the \"isRegistered\" function on the contract.\n * @param options - The options for the isRegistered function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isRegistered } from \"TODO\";\n * \n * const result = await isRegistered({\n * account: ...,\n * });\n * \n * ```\n */\nexport async function isRegistered(\n options: BaseTransactionOptions<IsRegisteredParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xc3c5a547\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_account\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.account]\n });\n};\n\n\n\n\n/**\n * Calls the \"totalAccounts\" function on the contract.\n * @param options - The options for the totalAccounts function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { totalAccounts } from \"TODO\";\n * \n * const result = await totalAccounts();\n * \n * ```\n */\nexport async function totalAccounts(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x58451f97\",\n [],\n [\n {\n \"type\": \"uint256\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllActiveSigners\" function on the contract.\n * @param options - The options for the getAllActiveSigners function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllActiveSigners } from \"TODO\";\n * \n * const result = await getAllActiveSigners();\n * \n * ```\n */\nexport async function getAllActiveSigners(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x8b52d723\",\n [],\n [\n {\n \"type\": \"tuple[]\",\n \"name\": \"signers\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"startTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"endTimestamp\"\n }\n ]\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllAdmins\" function on the contract.\n * @param options - The options for the getAllAdmins function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllAdmins } from \"TODO\";\n * \n * const result = await getAllAdmins();\n * \n * ```\n */\nexport async function getAllAdmins(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xe9523c97\",\n [],\n [\n {\n \"type\": \"address[]\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllSigners\" function on the contract.\n * @param options - The options for the getAllSigners function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllSigners } from \"TODO\";\n * \n * const result = await getAllSigners();\n * \n * ```\n */\nexport async function getAllSigners(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xd42f2f35\",\n [],\n [\n {\n \"type\": \"tuple[]\",\n \"name\": \"signers\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"startTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"endTimestamp\"\n }\n ]\n }\n ]\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"getMessageHash\" function.\n */\nexport type GetMessageHashParams = {\n hash: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"_hash\"}>\n};\n\n/**\n * Calls the \"getMessageHash\" function on the contract.\n * @param options - The options for the getMessageHash function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getMessageHash } from \"TODO\";\n * \n * const result = await getMessageHash({\n * hash: ...,\n * });\n * \n * ```\n */\nexport async function getMessageHash(\n options: BaseTransactionOptions<GetMessageHashParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x399b77da\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"_hash\"\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.hash]\n });\n};\n\n\n/**\n * Represents the parameters for the \"getPermissionsForSigner\" function.\n */\nexport type GetPermissionsForSignerParams = {\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\"}>\n};\n\n/**\n * Calls the \"getPermissionsForSigner\" function on the contract.\n * @param options - The options for the getPermissionsForSigner function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getPermissionsForSigner } from \"TODO\";\n * \n * const result = await getPermissionsForSigner({\n * signer: ...,\n * });\n * \n * ```\n */\nexport async function getPermissionsForSigner(\n options: BaseTransactionOptions<GetPermissionsForSignerParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xf15d424e\",\n [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n }\n ],\n [\n {\n \"type\": \"tuple\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"startTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"endTimestamp\"\n }\n ]\n }\n ]\n],\n params: [options.signer]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isActiveSigner\" function.\n */\nexport type IsActiveSignerParams = {\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\"}>\n};\n\n/**\n * Calls the \"isActiveSigner\" function on the contract.\n * @param options - The options for the isActiveSigner function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isActiveSigner } from \"TODO\";\n * \n * const result = await isActiveSigner({\n * signer: ...,\n * });\n * \n * ```\n */\nexport async function isActiveSigner(\n options: BaseTransactionOptions<IsActiveSignerParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x7dff5a79\",\n [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.signer]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isAdmin\" function.\n */\nexport type IsAdminParams = {\n account: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_account\"}>\n};\n\n/**\n * Calls the \"isAdmin\" function on the contract.\n * @param options - The options for the isAdmin function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isAdmin } from \"TODO\";\n * \n * const result = await isAdmin({\n * account: ...,\n * });\n * \n * ```\n */\nexport async function isAdmin(\n options: BaseTransactionOptions<IsAdminParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x24d7806c\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_account\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isValidSignature\" function.\n */\nexport type IsValidSignatureParams = {\n hash: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"_hash\"}>\nsignature: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_signature\"}>\n};\n\n/**\n * Calls the \"isValidSignature\" function on the contract.\n * @param options - The options for the isValidSignature function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isValidSignature } from \"TODO\";\n * \n * const result = await isValidSignature({\n * hash: ...,\n * signature: ...,\n * });\n * \n * ```\n */\nexport async function isValidSignature(\n options: BaseTransactionOptions<IsValidSignatureParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x1626ba7e\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"_hash\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_signature\"\n }\n ],\n [\n {\n \"type\": \"bytes4\",\n \"name\": \"magicValue\"\n }\n ]\n],\n params: [options.hash, options.signature]\n });\n};\n\n\n/**\n * Represents the parameters for the \"supportsInterface\" function.\n */\nexport type SupportsInterfaceParams = {\n interfaceId: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"interfaceId\"}>\n};\n\n/**\n * Calls the \"supportsInterface\" function on the contract.\n * @param options - The options for the supportsInterface function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { supportsInterface } from \"TODO\";\n * \n * const result = await supportsInterface({\n * interfaceId: ...,\n * });\n * \n * ```\n */\nexport async function supportsInterface(\n options: BaseTransactionOptions<SupportsInterfaceParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x01ffc9a7\",\n [\n {\n \"type\": \"bytes4\",\n \"name\": \"interfaceId\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.interfaceId]\n });\n};\n\n\n/**\n * Represents the parameters for the \"verifySignerPermissionRequest\" function.\n */\nexport type VerifySignerPermissionRequestParams = {\n req: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"req\",\"components\":[{\"type\":\"address\",\"name\":\"signer\"},{\"type\":\"uint8\",\"name\":\"isAdmin\"},{\"type\":\"address[]\",\"name\":\"approvedTargets\"},{\"type\":\"uint256\",\"name\":\"nativeTokenLimitPerTransaction\"},{\"type\":\"uint128\",\"name\":\"permissionStartTimestamp\"},{\"type\":\"uint128\",\"name\":\"permissionEndTimestamp\"},{\"type\":\"uint128\",\"name\":\"reqValidityStartTimestamp\"},{\"type\":\"uint128\",\"name\":\"reqValidityEndTimestamp\"},{\"type\":\"bytes32\",\"name\":\"uid\"}]}>\nsignature: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"signature\"}>\n};\n\n/**\n * Calls the \"verifySignerPermissionRequest\" function on the contract.\n * @param options - The options for the verifySignerPermissionRequest function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { verifySignerPermissionRequest } from \"TODO\";\n * \n * const result = await verifySignerPermissionRequest({\n * req: ...,\n * signature: ...,\n * });\n * \n * ```\n */\nexport async function verifySignerPermissionRequest(\n options: BaseTransactionOptions<VerifySignerPermissionRequestParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xa9082d84\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"req\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"uint8\",\n \"name\": \"isAdmin\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"permissionStartTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"permissionEndTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"reqValidityStartTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"reqValidityEndTimestamp\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"uid\"\n }\n ]\n },\n {\n \"type\": \"bytes\",\n \"name\": \"signature\"\n }\n ],\n [\n {\n \"type\": \"bool\",\n \"name\": \"success\"\n },\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n }\n ]\n],\n params: [options.req, options.signature]\n });\n};\n\n\n\n\n/**\n * Calls the \"eip712Domain\" function on the contract.\n * @param options - The options for the eip712Domain function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { eip712Domain } from \"TODO\";\n * \n * const result = await eip712Domain();\n * \n * ```\n */\nexport async function eip712Domain(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x84b0196e\",\n [],\n [\n {\n \"type\": \"bytes1\",\n \"name\": \"fields\"\n },\n {\n \"type\": \"string\",\n \"name\": \"name\"\n },\n {\n \"type\": \"string\",\n \"name\": \"version\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"chainId\"\n },\n {\n \"type\": \"address\",\n \"name\": \"verifyingContract\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"salt\"\n },\n {\n \"type\": \"uint256[]\",\n \"name\": \"extensions\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getEas\" function on the contract.\n * @param options - The options for the getEas function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getEas } from \"TODO\";\n * \n * const result = await getEas();\n * \n * ```\n */\nexport async function getEas(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xd5f5127d\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"owner\" function on the contract.\n * @param options - The options for the owner function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { owner } from \"TODO\";\n * \n * const result = await owner();\n * \n * ```\n */\nexport async function owner(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x8da5cb5b\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n/**\n* Contract write functions\n*/\n\n/**\n * Represents the parameters for the \"_disableFunctionInExtension\" function.\n */\nexport type _disableFunctionInExtensionParams = {\n extensionName: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"_extensionName\"}>\nfunctionSelector: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"_functionSelector\"}>\n};\n\n/**\n * Calls the \"_disableFunctionInExtension\" function on the contract.\n * @param options - The options for the \"_disableFunctionInExtension\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { _disableFunctionInExtension } from \"TODO\";\n * \n * const transaction = _disableFunctionInExtension({\n * extensionName: ...,\n * functionSelector: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function _disableFunctionInExtension(\n options: BaseTransactionOptions<_disableFunctionInExtensionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x429eed80\",\n [\n {\n \"type\": \"string\",\n \"name\": \"_extensionName\"\n },\n {\n \"type\": \"bytes4\",\n \"name\": \"_functionSelector\"\n }\n ],\n []\n],\n params: [options.extensionName, options.functionSelector]\n });\n};\n\n\n/**\n * Represents the parameters for the \"addExtension\" function.\n */\nexport type AddExtensionParams = {\n extension: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"_extension\",\"components\":[{\"type\":\"tuple\",\"name\":\"metadata\",\"components\":[{\"type\":\"string\",\"name\":\"name\"},{\"type\":\"string\",\"name\":\"metadataURI\"},{\"type\":\"address\",\"name\":\"implementation\"}]},{\"type\":\"tuple[]\",\"name\":\"functions\",\"components\":[{\"type\":\"bytes4\",\"name\":\"functionSelector\"},{\"type\":\"string\",\"name\":\"functionSignature\"}]}]}>\n};\n\n/**\n * Calls the \"addExtension\" function on the contract.\n * @param options - The options for the \"addExtension\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { addExtension } from \"TODO\";\n * \n * const transaction = addExtension({\n * extension: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function addExtension(\n options: BaseTransactionOptions<AddExtensionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xe05688fe\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"_extension\",\n \"components\": [\n {\n \"type\": \"tuple\",\n \"name\": \"metadata\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"name\"\n },\n {\n \"type\": \"string\",\n \"name\": \"metadataURI\"\n },\n {\n \"type\": \"address\",\n \"name\": \"implementation\"\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"functions\",\n \"components\": [\n {\n \"type\": \"bytes4\",\n \"name\": \"functionSelector\"\n },\n {\n \"type\": \"string\",\n \"name\": \"functionSignature\"\n }\n ]\n }\n ]\n }\n ],\n []\n],\n params: [options.extension]\n });\n};\n\n\n/**\n * Represents the parameters for the \"createAccount\" function.\n */\nexport type CreateAccountParams = {\n admin: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_admin\"}>\ndata: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_data\"}>\n};\n\n/**\n * Calls the \"createAccount\" function on the contract.\n * @param options - The options for the \"createAccount\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { createAccount } from \"TODO\";\n * \n * const transaction = createAccount({\n * admin: ...,\n * data: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function createAccount(\n options: BaseTransactionOptions<CreateAccountParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xd8fd8f44\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_admin\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_data\"\n }\n ],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: [options.admin, options.data]\n });\n};\n\n\n/**\n * Represents the parameters for the \"disableFunctionInExtension\" function.\n */\nexport type DisableFunctionInExtensionParams = {\n extensionName: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"_extensionName\"}>\nfunctionSelector: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"_functionSelector\"}>\n};\n\n/**\n * Calls the \"disableFunctionInExtension\" function on the contract.\n * @param options - The options for the \"disableFunctionInExtension\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { disableFunctionInExtension } from \"TODO\";\n * \n * const transaction = disableFunctionInExtension({\n * extensionName: ...,\n * functionSelector: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function disableFunctionInExtension(\n options: BaseTransactionOptions<DisableFunctionInExtensionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x512cf914\",\n [\n {\n \"type\": \"string\",\n \"name\": \"_extensionName\"\n },\n {\n \"type\": \"bytes4\",\n \"name\": \"_functionSelector\"\n }\n ],\n []\n],\n params: [options.extensionName, options.functionSelector]\n });\n};\n\n\n/**\n * Represents the parameters for the \"enableFunctionInExtension\" function.\n */\nexport type EnableFunctionInExtensionParams = {\n extensionName: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"_extensionName\"}>\nfunction: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"_function\",\"components\":[{\"type\":\"bytes4\",\"name\":\"functionSelector\"},{\"type\":\"string\",\"name\":\"functionSignature\"}]}>\n};\n\n/**\n * Calls the \"enableFunctionInExtension\" function on the contract.\n * @param options - The options for the \"enableFunctionInExtension\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { enableFunctionInExtension } from \"TODO\";\n * \n * const transaction = enableFunctionInExtension({\n * extensionName: ...,\n * function: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function enableFunctionInExtension(\n options: BaseTransactionOptions<EnableFunctionInExtensionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x8856a113\",\n [\n {\n \"type\": \"string\",\n \"name\": \"_extensionName\"\n },\n {\n \"type\": \"tuple\",\n \"name\": \"_function\",\n \"components\": [\n {\n \"type\": \"bytes4\",\n \"name\": \"functionSelector\"\n },\n {\n \"type\": \"string\",\n \"name\": \"functionSignature\"\n }\n ]\n }\n ],\n []\n],\n params: [options.extensionName, options.function]\n });\n};\n\n\n/**\n * Represents the parameters for the \"grantRole\" function.\n */\nexport type GrantRoleParams = {\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\"}>\naccount: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\"}>\n};\n\n/**\n * Calls the \"grantRole\" function on the contract.\n * @param options - The options for the \"grantRole\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { grantRole } from \"TODO\";\n * \n * const transaction = grantRole({\n * role: ...,\n * account: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function grantRole(\n options: BaseTransactionOptions<GrantRoleParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x2f2ff15d\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"role\"\n },\n {\n \"type\": \"address\",\n \"name\": \"account\"\n }\n ],\n []\n],\n params: [options.role, options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"multicall\" function.\n */\nexport type MulticallParams = {\n data: AbiParameterToPrimitiveType<{\"type\":\"bytes[]\",\"name\":\"data\"}>\n};\n\n/**\n * Calls the \"multicall\" function on the contract.\n * @param options - The options for the \"multicall\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { multicall } from \"TODO\";\n * \n * const transaction = multicall({\n * data: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function multicall(\n options: BaseTransactionOptions<MulticallParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xac9650d8\",\n [\n {\n \"type\": \"bytes[]\",\n \"name\": \"data\"\n }\n ],\n [\n {\n \"type\": \"bytes[]\",\n \"name\": \"results\"\n }\n ]\n],\n params: [options.data]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onRegister\" function.\n */\nexport type OnRegisterParams = {\n salt: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"_salt\"}>\n};\n\n/**\n * Calls the \"onRegister\" function on the contract.\n * @param options - The options for the \"onRegister\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onRegister } from \"TODO\";\n * \n * const transaction = onRegister({\n * salt: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onRegister(\n options: BaseTransactionOptions<OnRegisterParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x83a03f8c\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"_salt\"\n }\n ],\n []\n],\n params: [options.salt]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onSignerAdded\" function.\n */\nexport type OnSignerAddedParams = {\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_signer\"}>\nsalt: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"_salt\"}>\n};\n\n/**\n * Calls the \"onSignerAdded\" function on the contract.\n * @param options - The options for the \"onSignerAdded\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onSignerAdded } from \"TODO\";\n * \n * const transaction = onSignerAdded({\n * signer: ...,\n * salt: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onSignerAdded(\n options: BaseTransactionOptions<OnSignerAddedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x0b61e12b\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_signer\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"_salt\"\n }\n ],\n []\n],\n params: [options.signer, options.salt]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onSignerRemoved\" function.\n */\nexport type OnSignerRemovedParams = {\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_signer\"}>\nsalt: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"_salt\"}>\n};\n\n/**\n * Calls the \"onSignerRemoved\" function on the contract.\n * @param options - The options for the \"onSignerRemoved\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onSignerRemoved } from \"TODO\";\n * \n * const transaction = onSignerRemoved({\n * signer: ...,\n * salt: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onSignerRemoved(\n options: BaseTransactionOptions<OnSignerRemovedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x9387a380\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_signer\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"_salt\"\n }\n ],\n []\n],\n params: [options.signer, options.salt]\n });\n};\n\n\n/**\n * Represents the parameters for the \"removeExtension\" function.\n */\nexport type RemoveExtensionParams = {\n extensionName: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"_extensionName\"}>\n};\n\n/**\n * Calls the \"removeExtension\" function on the contract.\n * @param options - The options for the \"removeExtension\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { removeExtension } from \"TODO\";\n * \n * const transaction = removeExtension({\n * extensionName: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function removeExtension(\n options: BaseTransactionOptions<RemoveExtensionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xee7d2adf\",\n [\n {\n \"type\": \"string\",\n \"name\": \"_extensionName\"\n }\n ],\n []\n],\n params: [options.extensionName]\n });\n};\n\n\n/**\n * Represents the parameters for the \"renounceRole\" function.\n */\nexport type RenounceRoleParams = {\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\"}>\naccount: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\"}>\n};\n\n/**\n * Calls the \"renounceRole\" function on the contract.\n * @param options - The options for the \"renounceRole\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { renounceRole } from \"TODO\";\n * \n * const transaction = renounceRole({\n * role: ...,\n * account: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function renounceRole(\n options: BaseTransactionOptions<RenounceRoleParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x36568abe\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"role\"\n },\n {\n \"type\": \"address\",\n \"name\": \"account\"\n }\n ],\n []\n],\n params: [options.role, options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"replaceExtension\" function.\n */\nexport type ReplaceExtensionParams = {\n extension: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"_extension\",\"components\":[{\"type\":\"tuple\",\"name\":\"metadata\",\"components\":[{\"type\":\"string\",\"name\":\"name\"},{\"type\":\"string\",\"name\":\"metadataURI\"},{\"type\":\"address\",\"name\":\"implementation\"}]},{\"type\":\"tuple[]\",\"name\":\"functions\",\"components\":[{\"type\":\"bytes4\",\"name\":\"functionSelector\"},{\"type\":\"string\",\"name\":\"functionSignature\"}]}]}>\n};\n\n/**\n * Calls the \"replaceExtension\" function on the contract.\n * @param options - The options for the \"replaceExtension\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { replaceExtension } from \"TODO\";\n * \n * const transaction = replaceExtension({\n * extension: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function replaceExtension(\n options: BaseTransactionOptions<ReplaceExtensionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xc0562f6d\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"_extension\",\n \"components\": [\n {\n \"type\": \"tuple\",\n \"name\": \"metadata\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"name\"\n },\n {\n \"type\": \"string\",\n \"name\": \"metadataURI\"\n },\n {\n \"type\": \"address\",\n \"name\": \"implementation\"\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"functions\",\n \"components\": [\n {\n \"type\": \"bytes4\",\n \"name\": \"functionSelector\"\n },\n {\n \"type\": \"string\",\n \"name\": \"functionSignature\"\n }\n ]\n }\n ]\n }\n ],\n []\n],\n params: [options.extension]\n });\n};\n\n\n/**\n * Represents the parameters for the \"revokeRole\" function.\n */\nexport type RevokeRoleParams = {\n role: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"role\"}>\naccount: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"account\"}>\n};\n\n/**\n * Calls the \"revokeRole\" function on the contract.\n * @param options - The options for the \"revokeRole\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { revokeRole } from \"TODO\";\n * \n * const transaction = revokeRole({\n * role: ...,\n * account: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function revokeRole(\n options: BaseTransactionOptions<RevokeRoleParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xd547741f\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"role\"\n },\n {\n \"type\": \"address\",\n \"name\": \"account\"\n }\n ],\n []\n],\n params: [options.role, options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"setContractURI\" function.\n */\nexport type SetContractURIParams = {\n uri: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"_uri\"}>\n};\n\n/**\n * Calls the \"setContractURI\" function on the contract.\n * @param options - The options for the \"setContractURI\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { setContractURI } from \"TODO\";\n * \n * const transaction = setContractURI({\n * uri: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function setContractURI(\n options: BaseTransactionOptions<SetContractURIParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x938e3d7b\",\n [\n {\n \"type\": \"string\",\n \"name\": \"_uri\"\n }\n ],\n []\n],\n params: [options.uri]\n });\n};\n\n\n\n\n/**\n * Calls the \"addDeposit\" function on the contract.\n * @param options - The options for the \"addDeposit\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { addDeposit } from \"TODO\";\n * \n * const transaction = addDeposit();\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function addDeposit(\n options: BaseTransactionOptions\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x4a58db19\",\n [],\n []\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"execute\" function.\n */\nexport type ExecuteParams = {\n target: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_target\"}>\nvalue: AbiParameterToPrimitiveType<{\"type\":\"uint256\",\"name\":\"_value\"}>\ncalldata: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_calldata\"}>\n};\n\n/**\n * Calls the \"execute\" function on the contract.\n * @param options - The options for the \"execute\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { execute } from \"TODO\";\n * \n * const transaction = execute({\n * target: ...,\n * value: ...,\n * calldata: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function execute(\n options: BaseTransactionOptions<ExecuteParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xb61d27f6\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_target\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"_value\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_calldata\"\n }\n ],\n []\n],\n params: [options.target, options.value, options.calldata]\n });\n};\n\n\n/**\n * Represents the parameters for the \"executeBatch\" function.\n */\nexport type ExecuteBatchParams = {\n target: AbiParameterToPrimitiveType<{\"type\":\"address[]\",\"name\":\"_target\"}>\nvalue: AbiParameterToPrimitiveType<{\"type\":\"uint256[]\",\"name\":\"_value\"}>\ncalldata: AbiParameterToPrimitiveType<{\"type\":\"bytes[]\",\"name\":\"_calldata\"}>\n};\n\n/**\n * Calls the \"executeBatch\" function on the contract.\n * @param options - The options for the \"executeBatch\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { executeBatch } from \"TODO\";\n * \n * const transaction = executeBatch({\n * target: ...,\n * value: ...,\n * calldata: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function executeBatch(\n options: BaseTransactionOptions<ExecuteBatchParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x47e1da2a\",\n [\n {\n \"type\": \"address[]\",\n \"name\": \"_target\"\n },\n {\n \"type\": \"uint256[]\",\n \"name\": \"_value\"\n },\n {\n \"type\": \"bytes[]\",\n \"name\": \"_calldata\"\n }\n ],\n []\n],\n params: [options.target, options.value, options.calldata]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onERC1155BatchReceived\" function.\n */\nexport type OnERC1155BatchReceivedParams = {\n arg_0: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_1: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_2: AbiParameterToPrimitiveType<{\"type\":\"uint256[]\"}>\narg_3: AbiParameterToPrimitiveType<{\"type\":\"uint256[]\"}>\narg_4: AbiParameterToPrimitiveType<{\"type\":\"bytes\"}>\n};\n\n/**\n * Calls the \"onERC1155BatchReceived\" function on the contract.\n * @param options - The options for the \"onERC1155BatchReceived\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onERC1155BatchReceived } from \"TODO\";\n * \n * const transaction = onERC1155BatchReceived({\n * arg_0: ...,\n * arg_1: ...,\n * arg_2: ...,\n * arg_3: ...,\n * arg_4: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onERC1155BatchReceived(\n options: BaseTransactionOptions<OnERC1155BatchReceivedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xbc197c81\",\n [\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"uint256[]\"\n },\n {\n \"type\": \"uint256[]\"\n },\n {\n \"type\": \"bytes\"\n }\n ],\n [\n {\n \"type\": \"bytes4\"\n }\n ]\n],\n params: [options.arg_0, options.arg_1, options.arg_2, options.arg_3, options.arg_4]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onERC1155Received\" function.\n */\nexport type OnERC1155ReceivedParams = {\n arg_0: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_1: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_2: AbiParameterToPrimitiveType<{\"type\":\"uint256\"}>\narg_3: AbiParameterToPrimitiveType<{\"type\":\"uint256\"}>\narg_4: AbiParameterToPrimitiveType<{\"type\":\"bytes\"}>\n};\n\n/**\n * Calls the \"onERC1155Received\" function on the contract.\n * @param options - The options for the \"onERC1155Received\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onERC1155Received } from \"TODO\";\n * \n * const transaction = onERC1155Received({\n * arg_0: ...,\n * arg_1: ...,\n * arg_2: ...,\n * arg_3: ...,\n * arg_4: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onERC1155Received(\n options: BaseTransactionOptions<OnERC1155ReceivedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xf23a6e61\",\n [\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"uint256\"\n },\n {\n \"type\": \"uint256\"\n },\n {\n \"type\": \"bytes\"\n }\n ],\n [\n {\n \"type\": \"bytes4\"\n }\n ]\n],\n params: [options.arg_0, options.arg_1, options.arg_2, options.arg_3, options.arg_4]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onERC721Received\" function.\n */\nexport type OnERC721ReceivedParams = {\n arg_0: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_1: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_2: AbiParameterToPrimitiveType<{\"type\":\"uint256\"}>\narg_3: AbiParameterToPrimitiveType<{\"type\":\"bytes\"}>\n};\n\n/**\n * Calls the \"onERC721Received\" function on the contract.\n * @param options - The options for the \"onERC721Received\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onERC721Received } from \"TODO\";\n * \n * const transaction = onERC721Received({\n * arg_0: ...,\n * arg_1: ...,\n * arg_2: ...,\n * arg_3: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onERC721Received(\n options: BaseTransactionOptions<OnERC721ReceivedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x150b7a02\",\n [\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"uint256\"\n },\n {\n \"type\": \"bytes\"\n }\n ],\n [\n {\n \"type\": \"bytes4\"\n }\n ]\n],\n params: [options.arg_0, options.arg_1, options.arg_2, options.arg_3]\n });\n};\n\n\n/**\n * Represents the parameters for the \"setPermissionsForSigner\" function.\n */\nexport type SetPermissionsForSignerParams = {\n req: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"_req\",\"components\":[{\"type\":\"address\",\"name\":\"signer\"},{\"type\":\"uint8\",\"name\":\"isAdmin\"},{\"type\":\"address[]\",\"name\":\"approvedTargets\"},{\"type\":\"uint256\",\"name\":\"nativeTokenLimitPerTransaction\"},{\"type\":\"uint128\",\"name\":\"permissionStartTimestamp\"},{\"type\":\"uint128\",\"name\":\"permissionEndTimestamp\"},{\"type\":\"uint128\",\"name\":\"reqValidityStartTimestamp\"},{\"type\":\"uint128\",\"name\":\"reqValidityEndTimestamp\"},{\"type\":\"bytes32\",\"name\":\"uid\"}]}>\nsignature: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_signature\"}>\n};\n\n/**\n * Calls the \"setPermissionsForSigner\" function on the contract.\n * @param options - The options for the \"setPermissionsForSigner\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { setPermissionsForSigner } from \"TODO\";\n * \n * const transaction = setPermissionsForSigner({\n * req: ...,\n * signature: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function setPermissionsForSigner(\n options: BaseTransactionOptions<SetPermissionsForSignerParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x5892e236\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"_req\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"uint8\",\n \"name\": \"isAdmin\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"permissionStartTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"permissionEndTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"reqValidityStartTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"reqValidityEndTimestamp\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"uid\"\n }\n ]\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_signature\"\n }\n ],\n []\n],\n params: [options.req, options.signature]\n });\n};\n\n\n/**\n * Represents the parameters for the \"withdrawDepositTo\" function.\n */\nexport type WithdrawDepositToParams = {\n withdrawAddress: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"withdrawAddress\"}>\namount: AbiParameterToPrimitiveType<{\"type\":\"uint256\",\"name\":\"amount\"}>\n};\n\n/**\n * Calls the \"withdrawDepositTo\" function on the contract.\n * @param options - The options for the \"withdrawDepositTo\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { withdrawDepositTo } from \"TODO\";\n * \n * const transaction = withdrawDepositTo({\n * withdrawAddress: ...,\n * amount: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function withdrawDepositTo(\n options: BaseTransactionOptions<WithdrawDepositToParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x4d44560d\",\n [\n {\n \"type\": \"address\",\n \"name\": \"withdrawAddress\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"amount\"\n }\n ],\n []\n],\n params: [options.withdrawAddress, options.amount]\n });\n};\n\n\n/**\n * Represents the parameters for the \"createSeed\" function.\n */\nexport type CreateSeedParams = {\n schemaUid: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"schemaUid\"}>\nrevocable: AbiParameterToPrimitiveType<{\"type\":\"bool\",\"name\":\"revocable\"}>\n};\n\n/**\n * Calls the \"createSeed\" function on the contract.\n * @param options - The options for the \"createSeed\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { createSeed } from \"TODO\";\n * \n * const transaction = createSeed({\n * schemaUid: ...,\n * revocable: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function createSeed(\n options: BaseTransactionOptions<CreateSeedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x6240d6d9\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"schemaUid\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"revocable\"\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.schemaUid, options.revocable]\n });\n};\n\n\n/**\n * Represents the parameters for the \"createVersion\" function.\n */\nexport type CreateVersionParams = {\n seedUid: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"seedUid\"}>\nversionSchemaUid: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"versionSchemaUid\"}>\n};\n\n/**\n * Calls the \"createVersion\" function on the contract.\n * @param options - The options for the \"createVersion\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { createVersion } from \"TODO\";\n * \n * const transaction = createVersion({\n * seedUid: ...,\n * versionSchemaUid: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function createVersion(\n options: BaseTransactionOptions<CreateVersionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x13e0c263\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"seedUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionSchemaUid\"\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.seedUid, options.versionSchemaUid]\n });\n};\n\n\n/**\n * Represents the parameters for the \"initialize\" function.\n */\nexport type InitializeParams = {\n eas: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_eas\"}>\n};\n\n/**\n * Calls the \"initialize\" function on the contract.\n * @param options - The options for the \"initialize\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { initialize } from \"TODO\";\n * \n * const transaction = initialize({\n * eas: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function initialize(\n options: BaseTransactionOptions<InitializeParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xc4d66de8\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_eas\"\n }\n ],\n []\n],\n params: [options.eas]\n });\n};\n\n\n/**\n * Represents the parameters for the \"multiPublish\" function.\n */\nexport type MultiPublishParams = {\n requests: AbiParameterToPrimitiveType<{\"type\":\"tuple[]\",\"name\":\"requests\",\"components\":[{\"type\":\"string\",\"name\":\"localId\"},{\"type\":\"bytes32\",\"name\":\"seedUid\"},{\"type\":\"bytes32\",\"name\":\"seedSchemaUid\"},{\"type\":\"bytes32\",\"name\":\"versionUid\"},{\"type\":\"bytes32\",\"name\":\"versionSchemaUid\"},{\"type\":\"bool\",\"name\":\"seedIsRevocable\"},{\"type\":\"tuple[]\",\"name\":\"listOfAttestations\",\"components\":[{\"type\":\"bytes32\",\"name\":\"schema\"},{\"type\":\"tuple[]\",\"name\":\"data\",\"components\":[{\"type\":\"address\",\"name\":\"recipient\"},{\"type\":\"uint64\",\"name\":\"expirationTime\"},{\"type\":\"bool\",\"name\":\"revocable\"},{\"type\":\"bytes32\",\"name\":\"refUID\"},{\"type\":\"bytes\",\"name\":\"data\"},{\"type\":\"uint256\",\"name\":\"value\"}]}]},{\"type\":\"tuple[]\",\"name\":\"propertiesToUpdate\",\"components\":[{\"type\":\"string\",\"name\":\"publishLocalId\"},{\"type\":\"bytes32\",\"name\":\"propertySchemaUid\"}]}]}>\n};\n\n/**\n * Calls the \"multiPublish\" function on the contract.\n * @param options - The options for the \"multiPublish\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { multiPublish } from \"TODO\";\n * \n * const transaction = multiPublish({\n * requests: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function multiPublish(\n options: BaseTransactionOptions<MultiPublishParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x31e19cb8\",\n [\n {\n \"type\": \"tuple[]\",\n \"name\": \"requests\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"localId\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"seedUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"seedSchemaUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionSchemaUid\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"seedIsRevocable\"\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"listOfAttestations\",\n \"components\": [\n {\n \"type\": \"bytes32\",\n \"name\": \"schema\"\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"data\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"recipient\"\n },\n {\n \"type\": \"uint64\",\n \"name\": \"expirationTime\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"revocable\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"refUID\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"data\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"value\"\n }\n ]\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"propertiesToUpdate\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"publishLocalId\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"propertySchemaUid\"\n }\n ]\n }\n ]\n }\n ],\n [\n {\n \"type\": \"bytes32[]\"\n }\n ]\n],\n params: [options.requests]\n });\n};\n\n\n/**\n * Represents the parameters for the \"publish\" function.\n */\nexport type PublishParams = {\n request: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"request\",\"components\":[{\"type\":\"string\",\"name\":\"localId\"},{\"type\":\"bytes32\",\"name\":\"seedUid\"},{\"type\":\"bytes32\",\"name\":\"seedSchemaUid\"},{\"type\":\"bytes32\",\"name\":\"versionUid\"},{\"type\":\"bytes32\",\"name\":\"versionSchemaUid\"},{\"type\":\"bool\",\"name\":\"seedIsRevocable\"},{\"type\":\"tuple[]\",\"name\":\"listOfAttestations\",\"components\":[{\"type\":\"bytes32\",\"name\":\"schema\"},{\"type\":\"tuple[]\",\"name\":\"data\",\"components\":[{\"type\":\"address\",\"name\":\"recipient\"},{\"type\":\"uint64\",\"name\":\"expirationTime\"},{\"type\":\"bool\",\"name\":\"revocable\"},{\"type\":\"bytes32\",\"name\":\"refUID\"},{\"type\":\"bytes\",\"name\":\"data\"},{\"type\":\"uint256\",\"name\":\"value\"}]}]},{\"type\":\"tuple[]\",\"name\":\"propertiesToUpdate\",\"components\":[{\"type\":\"string\",\"name\":\"publishLocalId\"},{\"type\":\"bytes32\",\"name\":\"propertySchemaUid\"}]}]}>\n};\n\n/**\n * Calls the \"publish\" function on the contract.\n * @param options - The options for the \"publish\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { publish } from \"TODO\";\n * \n * const transaction = publish({\n * request: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function publish(\n options: BaseTransactionOptions<PublishParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xb71308c5\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"request\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"localId\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"seedUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"seedSchemaUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionSchemaUid\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"seedIsRevocable\"\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"listOfAttestations\",\n \"components\": [\n {\n \"type\": \"bytes32\",\n \"name\": \"schema\"\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"data\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"recipient\"\n },\n {\n \"type\": \"uint64\",\n \"name\": \"expirationTime\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"revocable\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"refUID\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"data\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"value\"\n }\n ]\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"propertiesToUpdate\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"publishLocalId\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"propertySchemaUid\"\n }\n ]\n }\n ]\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n },\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.request]\n });\n};\n\n\n\n\n/**\n * Calls the \"renounceOwnership\" function on the contract.\n * @param options - The options for the \"renounceOwnership\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { renounceOwnership } from \"TODO\";\n * \n * const transaction = renounceOwnership();\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function renounceOwnership(\n options: BaseTransactionOptions\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x715018a6\",\n [],\n []\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"setEas\" function.\n */\nexport type SetEasParams = {\n eas: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_eas\"}>\n};\n\n/**\n * Calls the \"setEas\" function on the contract.\n * @param options - The options for the \"setEas\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { setEas } from \"TODO\";\n * \n * const transaction = setEas({\n * eas: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function setEas(\n options: BaseTransactionOptions<SetEasParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xb90b6e0d\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_eas\"\n }\n ],\n [\n {\n \"type\": \"string\"\n }\n ]\n],\n params: [options.eas]\n });\n};\n\n\n/**\n * Represents the parameters for the \"transferOwnership\" function.\n */\nexport type TransferOwnershipParams = {\n newOwner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"newOwner\"}>\n};\n\n/**\n * Calls the \"transferOwnership\" function on the contract.\n * @param options - The options for the \"transferOwnership\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { transferOwnership } from \"TODO\";\n * \n * const transaction = transferOwnership({\n * newOwner: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function transferOwnership(\n options: BaseTransactionOptions<TransferOwnershipParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xf2fde38b\",\n [\n {\n \"type\": \"address\",\n \"name\": \"newOwner\"\n }\n ],\n []\n],\n params: [options.newOwner]\n });\n};\n\n\n","/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n","\n/**\n * This is the common logic for both the Node.js and web browser\n * implementations of `debug()`.\n */\n\nfunction setup(env) {\n\tcreateDebug.debug = createDebug;\n\tcreateDebug.default = createDebug;\n\tcreateDebug.coerce = coerce;\n\tcreateDebug.disable = disable;\n\tcreateDebug.enable = enable;\n\tcreateDebug.enabled = enabled;\n\tcreateDebug.humanize = require('ms');\n\tcreateDebug.destroy = destroy;\n\n\tObject.keys(env).forEach(key => {\n\t\tcreateDebug[key] = env[key];\n\t});\n\n\t/**\n\t* The currently active debug mode names, and names to skip.\n\t*/\n\n\tcreateDebug.names = [];\n\tcreateDebug.skips = [];\n\n\t/**\n\t* Map of special \"%n\" handling functions, for the debug \"format\" argument.\n\t*\n\t* Valid key names are a single, lower or upper-case letter, i.e. \"n\" and \"N\".\n\t*/\n\tcreateDebug.formatters = {};\n\n\t/**\n\t* Selects a color for a debug namespace\n\t* @param {String} namespace The namespace string for the debug instance to be colored\n\t* @return {Number|String} An ANSI color code for the given namespace\n\t* @api private\n\t*/\n\tfunction selectColor(namespace) {\n\t\tlet hash = 0;\n\n\t\tfor (let i = 0; i < namespace.length; i++) {\n\t\t\thash = ((hash << 5) - hash) + namespace.charCodeAt(i);\n\t\t\thash |= 0; // Convert to 32bit integer\n\t\t}\n\n\t\treturn createDebug.colors[Math.abs(hash) % createDebug.colors.length];\n\t}\n\tcreateDebug.selectColor = selectColor;\n\n\t/**\n\t* Create a debugger with the given `namespace`.\n\t*\n\t* @param {String} namespace\n\t* @return {Function}\n\t* @api public\n\t*/\n\tfunction createDebug(namespace) {\n\t\tlet prevTime;\n\t\tlet enableOverride = null;\n\t\tlet namespacesCache;\n\t\tlet enabledCache;\n\n\t\tfunction debug(...args) {\n\t\t\t// Disabled?\n\t\t\tif (!debug.enabled) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tconst self = debug;\n\n\t\t\t// Set `diff` timestamp\n\t\t\tconst curr = Number(new Date());\n\t\t\tconst ms = curr - (prevTime || curr);\n\t\t\tself.diff = ms;\n\t\t\tself.prev = prevTime;\n\t\t\tself.curr = curr;\n\t\t\tprevTime = curr;\n\n\t\t\targs[0] = createDebug.coerce(args[0]);\n\n\t\t\tif (typeof args[0] !== 'string') {\n\t\t\t\t// Anything else let's inspect with %O\n\t\t\t\targs.unshift('%O');\n\t\t\t}\n\n\t\t\t// Apply any `formatters` transformations\n\t\t\tlet index = 0;\n\t\t\targs[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => {\n\t\t\t\t// If we encounter an escaped % then don't increase the array index\n\t\t\t\tif (match === '%%') {\n\t\t\t\t\treturn '%';\n\t\t\t\t}\n\t\t\t\tindex++;\n\t\t\t\tconst formatter = createDebug.formatters[format];\n\t\t\t\tif (typeof formatter === 'function') {\n\t\t\t\t\tconst val = args[index];\n\t\t\t\t\tmatch = formatter.call(self, val);\n\n\t\t\t\t\t// Now we need to remove `args[index]` since it's inlined in the `format`\n\t\t\t\t\targs.splice(index, 1);\n\t\t\t\t\tindex--;\n\t\t\t\t}\n\t\t\t\treturn match;\n\t\t\t});\n\n\t\t\t// Apply env-specific formatting (colors, etc.)\n\t\t\tcreateDebug.formatArgs.call(self, args);\n\n\t\t\tconst logFn = self.log || createDebug.log;\n\t\t\tlogFn.apply(self, args);\n\t\t}\n\n\t\tdebug.namespace = namespace;\n\t\tdebug.useColors = createDebug.useColors();\n\t\tdebug.color = createDebug.selectColor(namespace);\n\t\tdebug.extend = extend;\n\t\tdebug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release.\n\n\t\tObject.defineProperty(debug, 'enabled', {\n\t\t\tenumerable: true,\n\t\t\tconfigurable: false,\n\t\t\tget: () => {\n\t\t\t\tif (enableOverride !== null) {\n\t\t\t\t\treturn enableOverride;\n\t\t\t\t}\n\t\t\t\tif (namespacesCache !== createDebug.namespaces) {\n\t\t\t\t\tnamespacesCache = createDebug.namespaces;\n\t\t\t\t\tenabledCache = createDebug.enabled(namespace);\n\t\t\t\t}\n\n\t\t\t\treturn enabledCache;\n\t\t\t},\n\t\t\tset: v => {\n\t\t\t\tenableOverride = v;\n\t\t\t}\n\t\t});\n\n\t\t// Env-specific initialization logic for debug instances\n\t\tif (typeof createDebug.init === 'function') {\n\t\t\tcreateDebug.init(debug);\n\t\t}\n\n\t\treturn debug;\n\t}\n\n\tfunction extend(namespace, delimiter) {\n\t\tconst newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace);\n\t\tnewDebug.log = this.log;\n\t\treturn newDebug;\n\t}\n\n\t/**\n\t* Enables a debug mode by namespaces. This can include modes\n\t* separated by a colon and wildcards.\n\t*\n\t* @param {String} namespaces\n\t* @api public\n\t*/\n\tfunction enable(namespaces) {\n\t\tcreateDebug.save(namespaces);\n\t\tcreateDebug.namespaces = namespaces;\n\n\t\tcreateDebug.names = [];\n\t\tcreateDebug.skips = [];\n\n\t\tconst split = (typeof namespaces === 'string' ? namespaces : '')\n\t\t\t.trim()\n\t\t\t.replace(/\\s+/g, ',')\n\t\t\t.split(',')\n\t\t\t.filter(Boolean);\n\n\t\tfor (const ns of split) {\n\t\t\tif (ns[0] === '-') {\n\t\t\t\tcreateDebug.skips.push(ns.slice(1));\n\t\t\t} else {\n\t\t\t\tcreateDebug.names.push(ns);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Checks if the given string matches a namespace template, honoring\n\t * asterisks as wildcards.\n\t *\n\t * @param {String} search\n\t * @param {String} template\n\t * @return {Boolean}\n\t */\n\tfunction matchesTemplate(search, template) {\n\t\tlet searchIndex = 0;\n\t\tlet templateIndex = 0;\n\t\tlet starIndex = -1;\n\t\tlet matchIndex = 0;\n\n\t\twhile (searchIndex < search.length) {\n\t\t\tif (templateIndex < template.length && (template[templateIndex] === search[searchIndex] || template[templateIndex] === '*')) {\n\t\t\t\t// Match character or proceed with wildcard\n\t\t\t\tif (template[templateIndex] === '*') {\n\t\t\t\t\tstarIndex = templateIndex;\n\t\t\t\t\tmatchIndex = searchIndex;\n\t\t\t\t\ttemplateIndex++; // Skip the '*'\n\t\t\t\t} else {\n\t\t\t\t\tsearchIndex++;\n\t\t\t\t\ttemplateIndex++;\n\t\t\t\t}\n\t\t\t} else if (starIndex !== -1) { // eslint-disable-line no-negated-condition\n\t\t\t\t// Backtrack to the last '*' and try to match more characters\n\t\t\t\ttemplateIndex = starIndex + 1;\n\t\t\t\tmatchIndex++;\n\t\t\t\tsearchIndex = matchIndex;\n\t\t\t} else {\n\t\t\t\treturn false; // No match\n\t\t\t}\n\t\t}\n\n\t\t// Handle trailing '*' in template\n\t\twhile (templateIndex < template.length && template[templateIndex] === '*') {\n\t\t\ttemplateIndex++;\n\t\t}\n\n\t\treturn templateIndex === template.length;\n\t}\n\n\t/**\n\t* Disable debug output.\n\t*\n\t* @return {String} namespaces\n\t* @api public\n\t*/\n\tfunction disable() {\n\t\tconst namespaces = [\n\t\t\t...createDebug.names,\n\t\t\t...createDebug.skips.map(namespace => '-' + namespace)\n\t\t].join(',');\n\t\tcreateDebug.enable('');\n\t\treturn namespaces;\n\t}\n\n\t/**\n\t* Returns true if the given mode name is enabled, false otherwise.\n\t*\n\t* @param {String} name\n\t* @return {Boolean}\n\t* @api public\n\t*/\n\tfunction enabled(name) {\n\t\tfor (const skip of createDebug.skips) {\n\t\t\tif (matchesTemplate(name, skip)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tfor (const ns of createDebug.names) {\n\t\t\tif (matchesTemplate(name, ns)) {\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t* Coerce `val`.\n\t*\n\t* @param {Mixed} val\n\t* @return {Mixed}\n\t* @api private\n\t*/\n\tfunction coerce(val) {\n\t\tif (val instanceof Error) {\n\t\t\treturn val.stack || val.message;\n\t\t}\n\t\treturn val;\n\t}\n\n\t/**\n\t* XXX DO NOT USE. This is a temporary stub function.\n\t* XXX It WILL be removed in the next major release.\n\t*/\n\tfunction destroy() {\n\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t}\n\n\tcreateDebug.enable(createDebug.load());\n\n\treturn createDebug;\n}\n\nmodule.exports = setup;\n","/* eslint-env browser */\n\n/**\n * This is the web browser implementation of `debug()`.\n */\n\nexports.formatArgs = formatArgs;\nexports.save = save;\nexports.load = load;\nexports.useColors = useColors;\nexports.storage = localstorage();\nexports.destroy = (() => {\n\tlet warned = false;\n\n\treturn () => {\n\t\tif (!warned) {\n\t\t\twarned = true;\n\t\t\tconsole.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.');\n\t\t}\n\t};\n})();\n\n/**\n * Colors.\n */\n\nexports.colors = [\n\t'#0000CC',\n\t'#0000FF',\n\t'#0033CC',\n\t'#0033FF',\n\t'#0066CC',\n\t'#0066FF',\n\t'#0099CC',\n\t'#0099FF',\n\t'#00CC00',\n\t'#00CC33',\n\t'#00CC66',\n\t'#00CC99',\n\t'#00CCCC',\n\t'#00CCFF',\n\t'#3300CC',\n\t'#3300FF',\n\t'#3333CC',\n\t'#3333FF',\n\t'#3366CC',\n\t'#3366FF',\n\t'#3399CC',\n\t'#3399FF',\n\t'#33CC00',\n\t'#33CC33',\n\t'#33CC66',\n\t'#33CC99',\n\t'#33CCCC',\n\t'#33CCFF',\n\t'#6600CC',\n\t'#6600FF',\n\t'#6633CC',\n\t'#6633FF',\n\t'#66CC00',\n\t'#66CC33',\n\t'#9900CC',\n\t'#9900FF',\n\t'#9933CC',\n\t'#9933FF',\n\t'#99CC00',\n\t'#99CC33',\n\t'#CC0000',\n\t'#CC0033',\n\t'#CC0066',\n\t'#CC0099',\n\t'#CC00CC',\n\t'#CC00FF',\n\t'#CC3300',\n\t'#CC3333',\n\t'#CC3366',\n\t'#CC3399',\n\t'#CC33CC',\n\t'#CC33FF',\n\t'#CC6600',\n\t'#CC6633',\n\t'#CC9900',\n\t'#CC9933',\n\t'#CCCC00',\n\t'#CCCC33',\n\t'#FF0000',\n\t'#FF0033',\n\t'#FF0066',\n\t'#FF0099',\n\t'#FF00CC',\n\t'#FF00FF',\n\t'#FF3300',\n\t'#FF3333',\n\t'#FF3366',\n\t'#FF3399',\n\t'#FF33CC',\n\t'#FF33FF',\n\t'#FF6600',\n\t'#FF6633',\n\t'#FF9900',\n\t'#FF9933',\n\t'#FFCC00',\n\t'#FFCC33'\n];\n\n/**\n * Currently only WebKit-based Web Inspectors, Firefox >= v31,\n * and the Firebug extension (any Firefox version) are known\n * to support \"%c\" CSS customizations.\n *\n * TODO: add a `localStorage` variable to explicitly enable/disable colors\n */\n\n// eslint-disable-next-line complexity\nfunction useColors() {\n\t// NB: In an Electron preload script, document will be defined but not fully\n\t// initialized. Since we know we're in Chrome, we'll just detect this case\n\t// explicitly\n\tif (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) {\n\t\treturn true;\n\t}\n\n\t// Internet Explorer and Edge do not support colors.\n\tif (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\\/(\\d+)/)) {\n\t\treturn false;\n\t}\n\n\tlet m;\n\n\t// Is webkit? http://stackoverflow.com/a/16459606/376773\n\t// document is undefined in react-native: https://github.com/facebook/react-native/pull/1632\n\t// eslint-disable-next-line no-return-assign\n\treturn (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) ||\n\t\t// Is firebug? http://stackoverflow.com/a/398120/376773\n\t\t(typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) ||\n\t\t// Is firefox >= v31?\n\t\t// https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\\/(\\d+)/)) && parseInt(m[1], 10) >= 31) ||\n\t\t// Double check webkit in userAgent just in case we are in a worker\n\t\t(typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\\/(\\d+)/));\n}\n\n/**\n * Colorize log arguments if enabled.\n *\n * @api public\n */\n\nfunction formatArgs(args) {\n\targs[0] = (this.useColors ? '%c' : '') +\n\t\tthis.namespace +\n\t\t(this.useColors ? ' %c' : ' ') +\n\t\targs[0] +\n\t\t(this.useColors ? '%c ' : ' ') +\n\t\t'+' + module.exports.humanize(this.diff);\n\n\tif (!this.useColors) {\n\t\treturn;\n\t}\n\n\tconst c = 'color: ' + this.color;\n\targs.splice(1, 0, c, 'color: inherit');\n\n\t// The final \"%c\" is somewhat tricky, because there could be other\n\t// arguments passed either before or after the %c, so we need to\n\t// figure out the correct index to insert the CSS into\n\tlet index = 0;\n\tlet lastC = 0;\n\targs[0].replace(/%[a-zA-Z%]/g, match => {\n\t\tif (match === '%%') {\n\t\t\treturn;\n\t\t}\n\t\tindex++;\n\t\tif (match === '%c') {\n\t\t\t// We only are interested in the *last* %c\n\t\t\t// (the user may have provided their own)\n\t\t\tlastC = index;\n\t\t}\n\t});\n\n\targs.splice(lastC, 0, c);\n}\n\n/**\n * Invokes `console.debug()` when available.\n * No-op when `console.debug` is not a \"function\".\n * If `console.debug` is not available, falls back\n * to `console.log`.\n *\n * @api public\n */\nexports.log = console.debug || console.log || (() => {});\n\n/**\n * Save `namespaces`.\n *\n * @param {String} namespaces\n * @api private\n */\nfunction save(namespaces) {\n\ttry {\n\t\tif (namespaces) {\n\t\t\texports.storage.setItem('debug', namespaces);\n\t\t} else {\n\t\t\texports.storage.removeItem('debug');\n\t\t}\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\n/**\n * Load `namespaces`.\n *\n * @return {String} returns the previously persisted debug modes\n * @api private\n */\nfunction load() {\n\tlet r;\n\ttry {\n\t\tr = exports.storage.getItem('debug') || exports.storage.getItem('DEBUG') ;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n\n\t// If debug isn't set in LS, and we're in Electron, try to load $DEBUG\n\tif (!r && typeof process !== 'undefined' && 'env' in process) {\n\t\tr = process.env.DEBUG;\n\t}\n\n\treturn r;\n}\n\n/**\n * Localstorage attempts to return the localstorage.\n *\n * This is necessary because safari throws\n * when a user disables cookies/localstorage\n * and you attempt to access it.\n *\n * @return {LocalStorage}\n * @api private\n */\n\nfunction localstorage() {\n\ttry {\n\t\t// TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context\n\t\t// The Browser also has localStorage in the global context.\n\t\treturn localStorage;\n\t} catch (error) {\n\t\t// Swallow\n\t\t// XXX (@Qix-) should we be logging these?\n\t}\n}\n\nmodule.exports = require('./common')(exports);\n\nconst {formatters} = module.exports;\n\n/**\n * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.\n */\n\nformatters.j = function (v) {\n\ttry {\n\t\treturn JSON.stringify(v);\n\t} catch (error) {\n\t\treturn '[UnexpectedJSONParseError]: ' + error.message;\n\t}\n};\n","import { createThirdwebClient, getContract, sendTransaction, waitForReceipt, } from 'thirdweb'\nimport { createWallet, Account, inAppWallet, } from 'thirdweb/wallets'\nimport { useActiveAccount } from 'thirdweb/react'\nimport { ThirdwebContract, } from 'thirdweb/contract'\nimport { isContractDeployed } from 'thirdweb/utils'\nimport { useEffect, useRef, useState, } from 'react'\nimport { optimismSepolia, } from 'thirdweb/chains'\nimport {\n createAccount,\n getAddress as getFactoryAddress,\n} from './thirdweb/11155420/0x76f47d88bfaf670f5208911181fcdc0e160cb16d'\nimport debug from 'debug'\nimport { getPublishConfig } from '../config'\nimport { THIRDWEB_ACCOUNT_FACTORY_ADDRESS } from './constants'\n\nconst logger = debug('permaPress:helpers:thirdweb')\n\nlet _client: ReturnType<typeof createThirdwebClient> | null = null\n\nexport function getClient() {\n if (!_client) {\n const { thirdwebClientId } = getPublishConfig()\n _client = createThirdwebClient({ clientId: thirdwebClientId })\n }\n return _client\n}\n\nexport const wallets = [\n // embeddedWallet(),\n createWallet('io.metamask',),\n // createWallet(\"com.coinbase.wallet\"),\n // createWallet(\"me.rainbow\"),\n]\n\nexport const useLocalWalletAccount = () => {\n\n const [ localWalletAccount, setLocalWalletAccount, ] = useState<Account | null>(null,)\n const personalWallet = createWallet('io.metamask',)\n\n const isConnecting = useRef(false)\n\n useEffect(() => {\n const _getAccount = async (): Promise<void> => {\n // if ( isConnecting.current ) {\n // return\n // }\n // isConnecting.current = true\n\n // const personalAccount = await personalWallet.connect({ client, },)\n // if ( !personalAccount ) {\n // throw new Error('Failed to connect to personal account',)\n // }\n\n // setLocalWalletAccount(personalAccount,)\n // isConnecting.current = false\n }\n\n _getAccount()\n\n }, [],)\n\n return localWalletAccount\n\n}\n\nexport const useActiveSmartWalletContract = () => {\n const account = useActiveAccount()\n\n const [ contract, setContract, ] = useState<ThirdwebContract | null>(null,)\n\n useEffect(() => {\n if ( !account || !account.address ) {\n return\n }\n\n setContract(getContract({\n client: getClient(),\n chain : optimismSepolia,\n address : account.address,\n },),)\n\n }, [ account, ],)\n\n return contract\n}\n\nexport const getManagedAccountFactoryContract = () => {\n const { thirdwebAccountFactoryAddress } = getPublishConfig()\n const contract = getContract({\n client: getClient(),\n chain : optimismSepolia,\n address : thirdwebAccountFactoryAddress,\n },)\n\n return contract\n}\n\n/**\n * Returns the deterministic smart wallet address for an admin signer and optional data.\n */\nexport async function getSmartWalletAddressForAdmin (\n adminAddress: string,\n data: string = '0x',\n): Promise<string> {\n const factory = getManagedAccountFactoryContract()\n return getFactoryAddress({\n contract : factory,\n adminSigner : adminAddress,\n data : data as `0x${string}`,\n },) as Promise<string>\n}\n\n/**\n * Returns true if the given address has contract bytecode deployed (e.g. a ManagedAccount).\n */\nexport async function isSmartWalletDeployed ( smartWalletAddress: string, ): Promise<boolean> {\n const contract = getContract({\n client: getClient(),\n chain : optimismSepolia,\n address : smartWalletAddress,\n },)\n return isContractDeployed(contract,)\n}\n\n/**\n * Resolves the smart wallet address and account to use for publish.\n * If the user has no connected account or no deployed ManagedAccount, returns needsDeploy.\n *\n * When using EIP4337 (in-app wallet with account abstraction), account.address is already\n * the smart wallet address. We detect that case and use it directly instead of deriving\n * via getSmartWalletAddressForAdmin (which assumes account.address is the EOA admin).\n */\nexport async function resolveSmartWalletForPublish (\n account: Account | null,\n): Promise<{ address: string; account: Account } | { needsDeploy: true }> {\n if ( !account ) {\n return { needsDeploy: true }\n }\n // If account.address is already a deployed smart wallet (e.g. from EIP4337), use it directly\n const accountIsDeployedSmartWallet = await isSmartWalletDeployed(account.address,)\n if ( accountIsDeployedSmartWallet ) {\n return { address: account.address, account }\n }\n // Otherwise derive smart wallet from EOA admin (e.g. MetaMask)\n const smartWalletAddress = await getSmartWalletAddressForAdmin(account.address,)\n const deployed = await isSmartWalletDeployed(smartWalletAddress,)\n if ( deployed ) {\n return { address: smartWalletAddress, account }\n }\n return { needsDeploy: true }\n}\n\n/** External wallets (MetaMask, Rainbow) for the deploy flow only; no account abstraction. */\nexport const ExternalWalletsForDeploy = [\n createWallet('io.metamask',),\n createWallet('me.rainbow',),\n]\n\nexport const deploySmartWalletContract = async ( localAccount: Account, ) => {\n const managedAccountFactoryContract = getManagedAccountFactoryContract()\n const createAccountTx = createAccount({\n contract : managedAccountFactoryContract,\n admin : localAccount.address,\n data : '0x',\n },)\n\n const result = await sendTransaction({\n account : localAccount,\n transaction : createAccountTx,\n },)\n\n logger('createAccountTx result:', result,)\n\n const receipt = await waitForReceipt({\n client: getClient(),\n transactionHash : result.transactionHash,\n chain : optimismSepolia,\n },)\n\n if ( !receipt ) {\n throw new Error('Failed to deploy smart wallet',)\n }\n\n return receipt\n}\n\nexport const appMetadata = {\n name: \"Seed Protocol\",\n description: \"Seed Protocol\",\n url: \"https://seedprotocol.io\",\n}\n\nexport const getManagedAccountWallet = () => {\n return inAppWallet({\n auth: {\n options: [\n \"farcaster\",\n \"email\",\n \"passkey\",\n \"phone\",\n ],\n },\n executionMode: {\n mode: 'EIP4337',\n smartAccount: {\n chain: optimismSepolia,\n factoryAddress: THIRDWEB_ACCOUNT_FACTORY_ADDRESS,\n gasless: true,\n },\n },\n // executionMode: {\n // mode: 'EIP4337',\n // smartAccount: {\n // chain: optimismSepolia,\n // factoryAddress: thirdwebAccountFactoryAddress,\n // gasless: true,\n // overrides: {\n // // Custom paymaster that passes through but lets you modify the UserOp\n // paymaster: async (userOp) => {\n\n // const hexifyBigInts: any = (obj: any) => {\n // if (typeof obj === \"bigint\") return `0x${obj.toString(16)}`;\n // if (Array.isArray(obj)) return obj.map(hexifyBigInts);\n // if (obj && typeof obj === \"object\") {\n // return Object.fromEntries(\n // Object.entries(obj).map(([k, v]) => [k, hexifyBigInts(v)])\n // );\n // }\n // return obj;\n // };\n\n // const chainIdHex = `0x${optimismSepolia.id.toString(16)}`;\n\n // // Increase callGasLimit before sending to paymaster\n // const modifiedUserOp = hexifyBigInts({\n // ...userOp,\n // callGasLimit: BigInt(8000000), // Double it, or set a fixed value\n // });\n\n // console.log(\"[SmartWallet Paymaster]\", getPublishConfig().thirdwebClientId);\n \n // // Call thirdweb's default paymaster endpoint\n // const response = await fetch(\n // `https://${optimismSepolia.id}.bundler.thirdweb.com/v2`,\n // {\n // method: \"POST\",\n // headers: { \n // \"Content-Type\": \"application/json\",\n // \"X-Client-Id\": getPublishConfig().thirdwebClientId,\n // },\n // body: JSON.stringify({\n // id: 1,\n // jsonrpc: \"2.0\",\n // method: \"pm_sponsorUserOperation\",\n // params: [modifiedUserOp, '0x5ff137d4b0fdcd49dca30c7cf57e578a026d2789', chainIdHex],\n // }),\n // }\n // );\n \n // const data = await response.json();\n // console.log(\"[SmartWallet Paymaster Response]\", data);\n // return {\n // paymasterAndData: data.result.paymasterAndData,\n // preVerificationGas: data.result.preVerificationGas,\n // verificationGasLimit: data.result.verificationGasLimit,\n // callGasLimit: data.result.callGasLimit,\n // };\n // },\n // execute: (accountContract, transaction) => {\n // // Log the gas that was set on the transaction\n // console.log(\"[SmartWallet Execute]\", {\n // gas: transaction.gas,\n // to: transaction.to,\n // dataLength: transaction.data?.length,\n // });\n \n // // Return the default execute call — don't change behavior,\n // // just observe what's being passed through\n // return prepareContractCall({\n // contract: accountContract,\n // method: \"function execute(address, uint256, bytes)\",\n // params: [\n // transaction.to ?? \"\",\n // transaction.value ?? 0n,\n // transaction.data ?? \"0x\",\n // ],\n // gas: transaction.gas, // Pass through whatever was set\n // });\n // },\n // },\n // }\n // }\n })\n}\n\nexport const getModularAccountWallet = () => {\n return inAppWallet({\n auth: {\n options: [\n \"farcaster\",\n \"email\",\n \"passkey\",\n \"phone\",\n ],\n },\n executionMode: {\n mode: 'EIP7702',\n sponsorGas: true,\n \n },\n })\n}\n\nexport const getWalletsForConnectButton = () => {\n return [\n getModularAccountWallet(),\n ]\n};","export const version = '1.0.8';\n//# sourceMappingURL=version.js.map","import { version } from './version.js';\nexport class BaseError extends Error {\n constructor(shortMessage, args = {}) {\n const details = args.cause instanceof BaseError\n ? args.cause.details\n : args.cause?.message\n ? args.cause.message\n : args.details;\n const docsPath = args.cause instanceof BaseError\n ? args.cause.docsPath || args.docsPath\n : args.docsPath;\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsPath ? [`Docs: https://abitype.dev${docsPath}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n `Version: abitype@${version}`,\n ].join('\\n');\n super(message);\n Object.defineProperty(this, \"details\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docsPath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"metaMessages\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"shortMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'AbiTypeError'\n });\n if (args.cause)\n this.cause = args.cause;\n this.details = details;\n this.docsPath = docsPath;\n this.metaMessages = args.metaMessages;\n this.shortMessage = shortMessage;\n }\n}\n//# sourceMappingURL=errors.js.map","// TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.\n// https://twitter.com/GabrielVergnaud/status/1622906834343366657\nexport function execTyped(regex, string) {\n const match = regex.exec(string);\n return match?.groups;\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// `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n// https://regexr.com/6v8hp\nexport const integerRegex = /^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)?$/;\nexport const isTupleRegex = /^\\(.+?\\).*?$/;\n//# sourceMappingURL=regex.js.map","import { execTyped } from '../../regex.js';\n// https://regexr.com/7gmok\nconst errorSignatureRegex = /^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)$/;\nexport function isErrorSignature(signature) {\n return errorSignatureRegex.test(signature);\n}\nexport function execErrorSignature(signature) {\n return execTyped(errorSignatureRegex, signature);\n}\n// https://regexr.com/7gmoq\nconst eventSignatureRegex = /^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)$/;\nexport function isEventSignature(signature) {\n return eventSignatureRegex.test(signature);\n}\nexport function execEventSignature(signature) {\n return execTyped(eventSignatureRegex, signature);\n}\n// https://regexr.com/7gmot\nconst functionSignatureRegex = /^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\\((?<parameters>.*?)\\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\\s?\\((?<returns>.*?)\\))?$/;\nexport function isFunctionSignature(signature) {\n return functionSignatureRegex.test(signature);\n}\nexport function execFunctionSignature(signature) {\n return execTyped(functionSignatureRegex, signature);\n}\n// https://regexr.com/7gmp3\nconst structSignatureRegex = /^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \\{(?<properties>.*?)\\}$/;\nexport function isStructSignature(signature) {\n return structSignatureRegex.test(signature);\n}\nexport function execStructSignature(signature) {\n return execTyped(structSignatureRegex, signature);\n}\n// https://regexr.com/78u01\nconst constructorSignatureRegex = /^constructor\\((?<parameters>.*?)\\)(?:\\s(?<stateMutability>payable{1}))?$/;\nexport function isConstructorSignature(signature) {\n return constructorSignatureRegex.test(signature);\n}\nexport function execConstructorSignature(signature) {\n return execTyped(constructorSignatureRegex, signature);\n}\n// https://regexr.com/7srtn\nconst fallbackSignatureRegex = /^fallback\\(\\) external(?:\\s(?<stateMutability>payable{1}))?$/;\nexport function isFallbackSignature(signature) {\n return fallbackSignatureRegex.test(signature);\n}\nexport function execFallbackSignature(signature) {\n return execTyped(fallbackSignatureRegex, signature);\n}\n// https://regexr.com/78u1k\nconst receiveSignatureRegex = /^receive\\(\\) external payable$/;\nexport function isReceiveSignature(signature) {\n return receiveSignatureRegex.test(signature);\n}\nexport const modifiers = new Set([\n 'memory',\n 'indexed',\n 'storage',\n 'calldata',\n]);\nexport const eventModifiers = new Set(['indexed']);\nexport const functionModifiers = new Set([\n 'calldata',\n 'memory',\n 'storage',\n]);\n//# sourceMappingURL=signatures.js.map","import { BaseError } from '../../errors.js';\nexport class InvalidAbiItemError extends BaseError {\n constructor({ signature }) {\n super('Failed to parse ABI item.', {\n details: `parseAbiItem(${JSON.stringify(signature, null, 2)})`,\n docsPath: '/api/human#parseabiitem-1',\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidAbiItemError'\n });\n }\n}\nexport class UnknownTypeError extends BaseError {\n constructor({ type }) {\n super('Unknown type.', {\n metaMessages: [\n `Type \"${type}\" is not a valid ABI type. Perhaps you forgot to include a struct signature?`,\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'UnknownTypeError'\n });\n }\n}\nexport class UnknownSolidityTypeError extends BaseError {\n constructor({ type }) {\n super('Unknown type.', {\n metaMessages: [`Type \"${type}\" is not a valid ABI type.`],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'UnknownSolidityTypeError'\n });\n }\n}\n//# sourceMappingURL=abiItem.js.map","import { BaseError } from '../../errors.js';\nexport class InvalidAbiParameterError extends BaseError {\n constructor({ param }) {\n super('Failed to parse ABI parameter.', {\n details: `parseAbiParameter(${JSON.stringify(param, null, 2)})`,\n docsPath: '/api/human#parseabiparameter-1',\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidAbiParameterError'\n });\n }\n}\nexport class InvalidAbiParametersError extends BaseError {\n constructor({ params }) {\n super('Failed to parse ABI parameters.', {\n details: `parseAbiParameters(${JSON.stringify(params, null, 2)})`,\n docsPath: '/api/human#parseabiparameters-1',\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidAbiParametersError'\n });\n }\n}\nexport class InvalidParameterError extends BaseError {\n constructor({ param }) {\n super('Invalid ABI parameter.', {\n details: param,\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidParameterError'\n });\n }\n}\nexport class SolidityProtectedKeywordError extends BaseError {\n constructor({ param, name }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `\"${name}\" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`,\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'SolidityProtectedKeywordError'\n });\n }\n}\nexport class InvalidModifierError extends BaseError {\n constructor({ param, type, modifier, }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${type ? ` in \"${type}\" type` : ''}.`,\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidModifierError'\n });\n }\n}\nexport class InvalidFunctionModifierError extends BaseError {\n constructor({ param, type, modifier, }) {\n super('Invalid ABI parameter.', {\n details: param,\n metaMessages: [\n `Modifier \"${modifier}\" not allowed${type ? ` in \"${type}\" type` : ''}.`,\n `Data location can only be specified for array, struct, or mapping types, but \"${modifier}\" was given.`,\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidFunctionModifierError'\n });\n }\n}\nexport class InvalidAbiTypeParameterError extends BaseError {\n constructor({ abiParameter, }) {\n super('Invalid ABI parameter.', {\n details: JSON.stringify(abiParameter, null, 2),\n metaMessages: ['ABI parameter type is invalid.'],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidAbiTypeParameterError'\n });\n }\n}\n//# sourceMappingURL=abiParameter.js.map","import { BaseError } from '../../errors.js';\nexport class InvalidSignatureError extends BaseError {\n constructor({ signature, type, }) {\n super(`Invalid ${type} signature.`, {\n details: signature,\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidSignatureError'\n });\n }\n}\nexport class UnknownSignatureError extends BaseError {\n constructor({ signature }) {\n super('Unknown signature.', {\n details: signature,\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'UnknownSignatureError'\n });\n }\n}\nexport class InvalidStructSignatureError extends BaseError {\n constructor({ signature }) {\n super('Invalid struct signature.', {\n details: signature,\n metaMessages: ['No properties exist.'],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidStructSignatureError'\n });\n }\n}\n//# sourceMappingURL=signature.js.map","import { BaseError } from '../../errors.js';\nexport class CircularReferenceError extends BaseError {\n constructor({ type }) {\n super('Circular reference detected.', {\n metaMessages: [`Struct \"${type}\" is a circular reference.`],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'CircularReferenceError'\n });\n }\n}\n//# sourceMappingURL=struct.js.map","import { BaseError } from '../../errors.js';\nexport class InvalidParenthesisError extends BaseError {\n constructor({ current, depth }) {\n super('Unbalanced parentheses.', {\n metaMessages: [\n `\"${current.trim()}\" has too many ${depth > 0 ? 'opening' : 'closing'} parentheses.`,\n ],\n details: `Depth \"${depth}\"`,\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'InvalidParenthesisError'\n });\n }\n}\n//# sourceMappingURL=splitParameters.js.map","/**\n * Gets {@link parameterCache} cache key namespaced by {@link type}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`).\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @returns Cache key for {@link parameterCache}\n */\nexport function getParameterCacheKey(param, type, structs) {\n let structKey = '';\n if (structs)\n for (const struct of Object.entries(structs)) {\n if (!struct)\n continue;\n let propertyKey = '';\n for (const property of struct[1]) {\n propertyKey += `[${property.type}${property.name ? `:${property.name}` : ''}]`;\n }\n structKey += `(${struct[0]}{${propertyKey}})`;\n }\n if (type)\n return `${type}:${param}${structKey}`;\n return param;\n}\n/**\n * Basic cache seeded with common ABI parameter strings.\n *\n * **Note: When seeding more parameters, make sure you benchmark performance. The current number is the ideal balance between performance and having an already existing cache.**\n */\nexport const parameterCache = new Map([\n // Unnamed\n ['address', { type: 'address' }],\n ['bool', { type: 'bool' }],\n ['bytes', { type: 'bytes' }],\n ['bytes32', { type: 'bytes32' }],\n ['int', { type: 'int256' }],\n ['int256', { type: 'int256' }],\n ['string', { type: 'string' }],\n ['uint', { type: 'uint256' }],\n ['uint8', { type: 'uint8' }],\n ['uint16', { type: 'uint16' }],\n ['uint24', { type: 'uint24' }],\n ['uint32', { type: 'uint32' }],\n ['uint64', { type: 'uint64' }],\n ['uint96', { type: 'uint96' }],\n ['uint112', { type: 'uint112' }],\n ['uint160', { type: 'uint160' }],\n ['uint192', { type: 'uint192' }],\n ['uint256', { type: 'uint256' }],\n // Named\n ['address owner', { type: 'address', name: 'owner' }],\n ['address to', { type: 'address', name: 'to' }],\n ['bool approved', { type: 'bool', name: 'approved' }],\n ['bytes _data', { type: 'bytes', name: '_data' }],\n ['bytes data', { type: 'bytes', name: 'data' }],\n ['bytes signature', { type: 'bytes', name: 'signature' }],\n ['bytes32 hash', { type: 'bytes32', name: 'hash' }],\n ['bytes32 r', { type: 'bytes32', name: 'r' }],\n ['bytes32 root', { type: 'bytes32', name: 'root' }],\n ['bytes32 s', { type: 'bytes32', name: 's' }],\n ['string name', { type: 'string', name: 'name' }],\n ['string symbol', { type: 'string', name: 'symbol' }],\n ['string tokenURI', { type: 'string', name: 'tokenURI' }],\n ['uint tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint8 v', { type: 'uint8', name: 'v' }],\n ['uint256 balance', { type: 'uint256', name: 'balance' }],\n ['uint256 tokenId', { type: 'uint256', name: 'tokenId' }],\n ['uint256 value', { type: 'uint256', name: 'value' }],\n // Indexed\n [\n 'event:address indexed from',\n { type: 'address', name: 'from', indexed: true },\n ],\n ['event:address indexed to', { type: 'address', name: 'to', indexed: true }],\n [\n 'event:uint indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n [\n 'event:uint256 indexed tokenId',\n { type: 'uint256', name: 'tokenId', indexed: true },\n ],\n]);\n//# sourceMappingURL=cache.js.map","import { bytesRegex, execTyped, integerRegex, isTupleRegex, } from '../../regex.js';\nimport { UnknownSolidityTypeError } from '../errors/abiItem.js';\nimport { InvalidFunctionModifierError, InvalidModifierError, InvalidParameterError, SolidityProtectedKeywordError, } from '../errors/abiParameter.js';\nimport { InvalidSignatureError, UnknownSignatureError, } from '../errors/signature.js';\nimport { InvalidParenthesisError } from '../errors/splitParameters.js';\nimport { getParameterCacheKey, parameterCache } from './cache.js';\nimport { eventModifiers, execConstructorSignature, execErrorSignature, execEventSignature, execFallbackSignature, execFunctionSignature, functionModifiers, isConstructorSignature, isErrorSignature, isEventSignature, isFallbackSignature, isFunctionSignature, isReceiveSignature, } from './signatures.js';\nexport function parseSignature(signature, structs = {}) {\n if (isFunctionSignature(signature))\n return parseFunctionSignature(signature, structs);\n if (isEventSignature(signature))\n return parseEventSignature(signature, structs);\n if (isErrorSignature(signature))\n return parseErrorSignature(signature, structs);\n if (isConstructorSignature(signature))\n return parseConstructorSignature(signature, structs);\n if (isFallbackSignature(signature))\n return parseFallbackSignature(signature);\n if (isReceiveSignature(signature))\n return {\n type: 'receive',\n stateMutability: 'payable',\n };\n throw new UnknownSignatureError({ signature });\n}\nexport function parseFunctionSignature(signature, structs = {}) {\n const match = execFunctionSignature(signature);\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'function' });\n const inputParams = splitParameters(match.parameters);\n const inputs = [];\n const inputLength = inputParams.length;\n for (let i = 0; i < inputLength; i++) {\n inputs.push(parseAbiParameter(inputParams[i], {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }));\n }\n const outputs = [];\n if (match.returns) {\n const outputParams = splitParameters(match.returns);\n const outputLength = outputParams.length;\n for (let i = 0; i < outputLength; i++) {\n outputs.push(parseAbiParameter(outputParams[i], {\n modifiers: functionModifiers,\n structs,\n type: 'function',\n }));\n }\n }\n return {\n name: match.name,\n type: 'function',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs,\n outputs,\n };\n}\nexport function parseEventSignature(signature, structs = {}) {\n const match = execEventSignature(signature);\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'event' });\n const params = splitParameters(match.parameters);\n const abiParameters = [];\n const length = params.length;\n for (let i = 0; i < length; i++)\n abiParameters.push(parseAbiParameter(params[i], {\n modifiers: eventModifiers,\n structs,\n type: 'event',\n }));\n return { name: match.name, type: 'event', inputs: abiParameters };\n}\nexport function parseErrorSignature(signature, structs = {}) {\n const match = execErrorSignature(signature);\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'error' });\n const params = splitParameters(match.parameters);\n const abiParameters = [];\n const length = params.length;\n for (let i = 0; i < length; i++)\n abiParameters.push(parseAbiParameter(params[i], { structs, type: 'error' }));\n return { name: match.name, type: 'error', inputs: abiParameters };\n}\nexport function parseConstructorSignature(signature, structs = {}) {\n const match = execConstructorSignature(signature);\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'constructor' });\n const params = splitParameters(match.parameters);\n const abiParameters = [];\n const length = params.length;\n for (let i = 0; i < length; i++)\n abiParameters.push(parseAbiParameter(params[i], { structs, type: 'constructor' }));\n return {\n type: 'constructor',\n stateMutability: match.stateMutability ?? 'nonpayable',\n inputs: abiParameters,\n };\n}\nexport function parseFallbackSignature(signature) {\n const match = execFallbackSignature(signature);\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'fallback' });\n return {\n type: 'fallback',\n stateMutability: match.stateMutability ?? 'nonpayable',\n };\n}\nconst abiParameterWithoutTupleRegex = /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\\[\\d*?\\])+?)?(?:\\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/;\nconst abiParameterWithTupleRegex = /^\\((?<type>.+?)\\)(?<array>(?:\\[\\d*?\\])+?)?(?:\\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/;\nconst dynamicIntegerRegex = /^u?int$/;\nexport function parseAbiParameter(param, options) {\n // optional namespace cache by `type`\n const parameterCacheKey = getParameterCacheKey(param, options?.type, options?.structs);\n if (parameterCache.has(parameterCacheKey))\n return parameterCache.get(parameterCacheKey);\n const isTuple = isTupleRegex.test(param);\n const match = execTyped(isTuple ? abiParameterWithTupleRegex : abiParameterWithoutTupleRegex, param);\n if (!match)\n throw new InvalidParameterError({ param });\n if (match.name && isSolidityKeyword(match.name))\n throw new SolidityProtectedKeywordError({ param, name: match.name });\n const name = match.name ? { name: match.name } : {};\n const indexed = match.modifier === 'indexed' ? { indexed: true } : {};\n const structs = options?.structs ?? {};\n let type;\n let components = {};\n if (isTuple) {\n type = 'tuple';\n const params = splitParameters(match.type);\n const components_ = [];\n const length = params.length;\n for (let i = 0; i < length; i++) {\n // remove `modifiers` from `options` to prevent from being added to tuple components\n components_.push(parseAbiParameter(params[i], { structs }));\n }\n components = { components: components_ };\n }\n else if (match.type in structs) {\n type = 'tuple';\n components = { components: structs[match.type] };\n }\n else if (dynamicIntegerRegex.test(match.type)) {\n type = `${match.type}256`;\n }\n else {\n type = match.type;\n if (!(options?.type === 'struct') && !isSolidityType(type))\n throw new UnknownSolidityTypeError({ type });\n }\n if (match.modifier) {\n // Check if modifier exists, but is not allowed (e.g. `indexed` in `functionModifiers`)\n if (!options?.modifiers?.has?.(match.modifier))\n throw new InvalidModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n });\n // Check if resolved `type` is valid if there is a function modifier\n if (functionModifiers.has(match.modifier) &&\n !isValidDataLocation(type, !!match.array))\n throw new InvalidFunctionModifierError({\n param,\n type: options?.type,\n modifier: match.modifier,\n });\n }\n const abiParameter = {\n type: `${type}${match.array ?? ''}`,\n ...name,\n ...indexed,\n ...components,\n };\n parameterCache.set(parameterCacheKey, abiParameter);\n return abiParameter;\n}\n// s/o latika for this\nexport function splitParameters(params, result = [], current = '', depth = 0) {\n const length = params.trim().length;\n // biome-ignore lint/correctness/noUnreachable: recursive\n for (let i = 0; i < length; i++) {\n const char = params[i];\n const tail = params.slice(i + 1);\n switch (char) {\n case ',':\n return depth === 0\n ? splitParameters(tail, [...result, current.trim()])\n : splitParameters(tail, result, `${current}${char}`, depth);\n case '(':\n return splitParameters(tail, result, `${current}${char}`, depth + 1);\n case ')':\n return splitParameters(tail, result, `${current}${char}`, depth - 1);\n default:\n return splitParameters(tail, result, `${current}${char}`, depth);\n }\n }\n if (current === '')\n return result;\n if (depth !== 0)\n throw new InvalidParenthesisError({ current, depth });\n result.push(current.trim());\n return result;\n}\nexport function isSolidityType(type) {\n return (type === 'address' ||\n type === 'bool' ||\n type === 'function' ||\n type === 'string' ||\n bytesRegex.test(type) ||\n integerRegex.test(type));\n}\nconst protectedKeywordsRegex = /^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;\n/** @internal */\nexport function isSolidityKeyword(name) {\n return (name === 'address' ||\n name === 'bool' ||\n name === 'function' ||\n name === 'string' ||\n name === 'tuple' ||\n bytesRegex.test(name) ||\n integerRegex.test(name) ||\n protectedKeywordsRegex.test(name));\n}\n/** @internal */\nexport function isValidDataLocation(type, isArray) {\n return isArray || type === 'bytes' || type === 'string' || type === 'tuple';\n}\n//# sourceMappingURL=utils.js.map","import { execTyped, isTupleRegex } from '../../regex.js';\nimport { UnknownTypeError } from '../errors/abiItem.js';\nimport { InvalidAbiTypeParameterError } from '../errors/abiParameter.js';\nimport { InvalidSignatureError, InvalidStructSignatureError, } from '../errors/signature.js';\nimport { CircularReferenceError } from '../errors/struct.js';\nimport { execStructSignature, isStructSignature } from './signatures.js';\nimport { isSolidityType, parseAbiParameter } from './utils.js';\nexport function parseStructs(signatures) {\n // Create \"shallow\" version of each struct (and filter out non-structs or invalid structs)\n const shallowStructs = {};\n const signaturesLength = signatures.length;\n for (let i = 0; i < signaturesLength; i++) {\n const signature = signatures[i];\n if (!isStructSignature(signature))\n continue;\n const match = execStructSignature(signature);\n if (!match)\n throw new InvalidSignatureError({ signature, type: 'struct' });\n const properties = match.properties.split(';');\n const components = [];\n const propertiesLength = properties.length;\n for (let k = 0; k < propertiesLength; k++) {\n const property = properties[k];\n const trimmed = property.trim();\n if (!trimmed)\n continue;\n const abiParameter = parseAbiParameter(trimmed, {\n type: 'struct',\n });\n components.push(abiParameter);\n }\n if (!components.length)\n throw new InvalidStructSignatureError({ signature });\n shallowStructs[match.name] = components;\n }\n // Resolve nested structs inside each parameter\n const resolvedStructs = {};\n const entries = Object.entries(shallowStructs);\n const entriesLength = entries.length;\n for (let i = 0; i < entriesLength; i++) {\n const [name, parameters] = entries[i];\n resolvedStructs[name] = resolveStructs(parameters, shallowStructs);\n }\n return resolvedStructs;\n}\nconst typeWithoutTupleRegex = /^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\\[\\d*?\\])+?)?$/;\nfunction resolveStructs(abiParameters, structs, ancestors = new Set()) {\n const components = [];\n const length = abiParameters.length;\n for (let i = 0; i < length; i++) {\n const abiParameter = abiParameters[i];\n const isTuple = isTupleRegex.test(abiParameter.type);\n if (isTuple)\n components.push(abiParameter);\n else {\n const match = execTyped(typeWithoutTupleRegex, abiParameter.type);\n if (!match?.type)\n throw new InvalidAbiTypeParameterError({ abiParameter });\n const { array, type } = match;\n if (type in structs) {\n if (ancestors.has(type))\n throw new CircularReferenceError({ type });\n components.push({\n ...abiParameter,\n type: `tuple${array ?? ''}`,\n components: resolveStructs(structs[type] ?? [], structs, new Set([...ancestors, type])),\n });\n }\n else {\n if (isSolidityType(type))\n components.push(abiParameter);\n else\n throw new UnknownTypeError({ type });\n }\n }\n }\n return components;\n}\n//# sourceMappingURL=structs.js.map","import { InvalidAbiItemError } from './errors/abiItem.js';\nimport { isStructSignature } from './runtime/signatures.js';\nimport { parseStructs } from './runtime/structs.js';\nimport { parseSignature } from './runtime/utils.js';\n/**\n * Parses human-readable ABI item (e.g. error, event, function) into {@link Abi} item\n *\n * @param signature - Human-readable ABI item\n * @returns Parsed {@link Abi} item\n *\n * @example\n * const abiItem = parseAbiItem('function balanceOf(address owner) view returns (uint256)')\n * // ^? const abiItem: { name: \"balanceOf\"; type: \"function\"; stateMutability: \"view\";...\n *\n * @example\n * const abiItem = parseAbiItem([\n * // ^? const abiItem: { name: \"foo\"; type: \"function\"; stateMutability: \"view\"; inputs:...\n * 'function foo(Baz bar) view returns (string)',\n * 'struct Baz { string name; }',\n * ])\n */\nexport function parseAbiItem(signature) {\n let abiItem;\n if (typeof signature === 'string')\n abiItem = parseSignature(signature);\n else {\n const structs = parseStructs(signature);\n const length = signature.length;\n for (let i = 0; i < length; i++) {\n const signature_ = signature[i];\n if (isStructSignature(signature_))\n continue;\n abiItem = parseSignature(signature_, structs);\n break;\n }\n }\n if (!abiItem)\n throw new InvalidAbiItemError({ signature });\n return abiItem;\n}\n//# sourceMappingURL=parseAbiItem.js.map","// TODO: This looks cool. Need to check the performance of `new RegExp` versus defined inline though.\n// https://twitter.com/GabrielVergnaud/status/1622906834343366657\nexport function execTyped(regex, string) {\n const match = regex.exec(string);\n return match?.groups;\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// `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n// https://regexr.com/6v8hp\nexport const integerRegex = /^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)?$/;\nexport const isTupleRegex = /^\\(.+?\\).*?$/;\n//# sourceMappingURL=regex.js.map","import { execTyped } from '../regex.js';\n// https://regexr.com/7f7rv\nconst tupleRegex = /^tuple(?<array>(\\[(\\d*)\\])*)$/;\n/**\n * Formats {@link AbiParameter} to human-readable ABI parameter.\n *\n * @param abiParameter - ABI parameter\n * @returns Human-readable ABI parameter\n *\n * @example\n * const result = formatAbiParameter({ type: 'address', name: 'from' })\n * // ^? const result: 'address from'\n */\nexport function formatAbiParameter(abiParameter) {\n let type = abiParameter.type;\n if (tupleRegex.test(abiParameter.type) && 'components' in abiParameter) {\n type = '(';\n const length = abiParameter.components.length;\n for (let i = 0; i < length; i++) {\n const component = abiParameter.components[i];\n type += formatAbiParameter(component);\n if (i < length - 1)\n type += ', ';\n }\n const result = execTyped(tupleRegex, abiParameter.type);\n type += `)${result?.array ?? ''}`;\n return formatAbiParameter({\n ...abiParameter,\n type,\n });\n }\n // Add `indexed` to type if in `abiParameter`\n if ('indexed' in abiParameter && abiParameter.indexed)\n type = `${type} indexed`;\n // Return human-readable ABI parameter\n if (abiParameter.name)\n return `${type} ${abiParameter.name}`;\n return type;\n}\n//# sourceMappingURL=formatAbiParameter.js.map","import { formatAbiParameter, } from './formatAbiParameter.js';\n/**\n * Formats {@link AbiParameter}s to human-readable ABI parameters.\n *\n * @param abiParameters - ABI parameters\n * @returns Human-readable ABI parameters\n *\n * @example\n * const result = formatAbiParameters([\n * // ^? const result: 'address from, uint256 tokenId'\n * { type: 'address', name: 'from' },\n * { type: 'uint256', name: 'tokenId' },\n * ])\n */\nexport function formatAbiParameters(abiParameters) {\n let params = '';\n const length = abiParameters.length;\n for (let i = 0; i < length; i++) {\n const abiParameter = abiParameters[i];\n params += formatAbiParameter(abiParameter);\n if (i !== length - 1)\n params += ', ';\n }\n return params;\n}\n//# sourceMappingURL=formatAbiParameters.js.map","import { formatAbiParameters, } from './formatAbiParameters.js';\n/**\n * Formats ABI item (e.g. error, event, function) into human-readable ABI item\n *\n * @param abiItem - ABI item\n * @returns Human-readable ABI item\n */\nexport function formatAbiItem(abiItem) {\n if (abiItem.type === 'function')\n return `function ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability && abiItem.stateMutability !== 'nonpayable'\n ? ` ${abiItem.stateMutability}`\n : ''}${abiItem.outputs?.length\n ? ` returns (${formatAbiParameters(abiItem.outputs)})`\n : ''}`;\n if (abiItem.type === 'event')\n return `event ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;\n if (abiItem.type === 'error')\n return `error ${abiItem.name}(${formatAbiParameters(abiItem.inputs)})`;\n if (abiItem.type === 'constructor')\n return `constructor(${formatAbiParameters(abiItem.inputs)})${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;\n if (abiItem.type === 'fallback')\n return `fallback() external${abiItem.stateMutability === 'payable' ? ' payable' : ''}`;\n return 'receive() external payable';\n}\n//# sourceMappingURL=formatAbiItem.js.map","import { InvalidDefinitionTypeError, } from '../../errors/abi.js';\nexport function formatAbiItem(abiItem, { includeName = false } = {}) {\n if (abiItem.type !== 'function' &&\n abiItem.type !== 'event' &&\n abiItem.type !== 'error')\n throw new InvalidDefinitionTypeError(abiItem.type);\n return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`;\n}\nexport function formatAbiParams(params, { includeName = false } = {}) {\n if (!params)\n return '';\n return params\n .map((param) => formatAbiParam(param, { includeName }))\n .join(includeName ? ', ' : ',');\n}\nfunction formatAbiParam(param, { includeName }) {\n if (param.type.startsWith('tuple')) {\n return `(${formatAbiParams(param.components, { includeName })})${param.type.slice('tuple'.length)}`;\n }\n return param.type + (includeName && param.name ? ` ${param.name}` : '');\n}\n//# sourceMappingURL=formatAbiItem.js.map","export function isHex(value, { strict = true } = {}) {\n if (!value)\n return false;\n if (typeof value !== 'string')\n return false;\n return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');\n}\n//# sourceMappingURL=isHex.js.map","import { isHex } from './isHex.js';\n/**\n * @description Retrieves the size of the value (in bytes).\n *\n * @param value The value (hex or byte array) to retrieve the size of.\n * @returns The size of the value (in bytes).\n */\nexport function size(value) {\n if (isHex(value, { strict: false }))\n return Math.ceil((value.length - 2) / 2);\n return value.length;\n}\n//# sourceMappingURL=size.js.map","export const version = '2.39.0';\n//# sourceMappingURL=version.js.map","import { version } from './version.js';\nlet errorConfig = {\n getDocsUrl: ({ docsBaseUrl, docsPath = '', docsSlug, }) => docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${docsSlug ? `#${docsSlug}` : ''}`\n : undefined,\n version: `viem@${version}`,\n};\nexport function setErrorConfig(config) {\n errorConfig = config;\n}\nexport class BaseError extends Error {\n constructor(shortMessage, args = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.details;\n if (args.cause?.message)\n return args.cause.message;\n return args.details;\n })();\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath;\n return args.docsPath;\n })();\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n');\n super(message, args.cause ? { cause: args.cause } : undefined);\n Object.defineProperty(this, \"details\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docsPath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"metaMessages\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"shortMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'BaseError'\n });\n this.details = details;\n this.docsPath = docsPath;\n this.metaMessages = args.metaMessages;\n this.name = args.name ?? this.name;\n this.shortMessage = shortMessage;\n this.version = version;\n }\n walk(fn) {\n return walk(this, fn);\n }\n}\nfunction walk(err, fn) {\n if (fn?.(err))\n return err;\n if (err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined)\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n//# sourceMappingURL=base.js.map","import { formatAbiItem, formatAbiParams } from '../utils/abi/formatAbiItem.js';\nimport { size } from '../utils/data/size.js';\nimport { BaseError } from './base.js';\nexport class AbiConstructorNotFoundError extends BaseError {\n constructor({ docsPath }) {\n super([\n 'A constructor was not found on the ABI.',\n 'Make sure you are using the correct ABI and that the constructor exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiConstructorNotFoundError',\n });\n }\n}\nexport class AbiConstructorParamsNotFoundError extends BaseError {\n constructor({ docsPath }) {\n super([\n 'Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.',\n 'Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiConstructorParamsNotFoundError',\n });\n }\n}\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\n constructor({ data, size }) {\n super([\n `Data size of ${size} bytes is invalid.`,\n 'Size must be in increments of 32 bytes (size % 32 === 0).',\n ].join('\\n'), {\n metaMessages: [`Data: ${data} (${size} bytes)`],\n name: 'AbiDecodingDataSizeInvalidError',\n });\n }\n}\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\n constructor({ data, params, size, }) {\n super([`Data size of ${size} bytes is too small for given parameters.`].join('\\n'), {\n metaMessages: [\n `Params: (${formatAbiParams(params, { includeName: true })})`,\n `Data: ${data} (${size} bytes)`,\n ],\n name: 'AbiDecodingDataSizeTooSmallError',\n });\n Object.defineProperty(this, \"data\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"params\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"size\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.data = data;\n this.params = params;\n this.size = size;\n }\n}\nexport class AbiDecodingZeroDataError extends BaseError {\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n name: 'AbiDecodingZeroDataError',\n });\n }\n}\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\n constructor({ expectedLength, givenLength, type, }) {\n super([\n `ABI encoding array length mismatch for type ${type}.`,\n `Expected length: ${expectedLength}`,\n `Given length: ${givenLength}`,\n ].join('\\n'), { name: 'AbiEncodingArrayLengthMismatchError' });\n }\n}\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\n constructor({ expectedSize, value }) {\n super(`Size of bytes \"${value}\" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: 'AbiEncodingBytesSizeMismatchError' });\n }\n}\nexport class AbiEncodingLengthMismatchError extends BaseError {\n constructor({ expectedLength, givenLength, }) {\n super([\n 'ABI encoding params/values length mismatch.',\n `Expected length (params): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'), { name: 'AbiEncodingLengthMismatchError' });\n }\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\n constructor(errorName, { docsPath }) {\n super([\n `Arguments (\\`args\\`) were provided to \"${errorName}\", but \"${errorName}\" on the ABI does not contain any parameters (\\`inputs\\`).`,\n 'Cannot encode error result without knowing what the parameter types are.',\n 'Make sure you are using the correct ABI and that the inputs exist on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiErrorInputsNotFoundError',\n });\n }\n}\nexport class AbiErrorNotFoundError extends BaseError {\n constructor(errorName, { docsPath } = {}) {\n super([\n `Error ${errorName ? `\"${errorName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the error exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiErrorNotFoundError',\n });\n }\n}\nexport class AbiErrorSignatureNotFoundError extends BaseError {\n constructor(signature, { docsPath }) {\n super([\n `Encoded error signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the error exists on it.',\n `You can look up the decoded signature here: https://openchain.xyz/signatures?query=${signature}.`,\n ].join('\\n'), {\n docsPath,\n name: 'AbiErrorSignatureNotFoundError',\n });\n Object.defineProperty(this, \"signature\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.signature = signature;\n }\n}\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n constructor({ docsPath }) {\n super('Cannot extract event signature from empty topics.', {\n docsPath,\n name: 'AbiEventSignatureEmptyTopicsError',\n });\n }\n}\nexport class AbiEventSignatureNotFoundError extends BaseError {\n constructor(signature, { docsPath }) {\n super([\n `Encoded event signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the event exists on it.',\n `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`,\n ].join('\\n'), {\n docsPath,\n name: 'AbiEventSignatureNotFoundError',\n });\n }\n}\nexport class AbiEventNotFoundError extends BaseError {\n constructor(eventName, { docsPath } = {}) {\n super([\n `Event ${eventName ? `\"${eventName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the event exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiEventNotFoundError',\n });\n }\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n constructor(functionName, { docsPath } = {}) {\n super([\n `Function ${functionName ? `\"${functionName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the function exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiFunctionNotFoundError',\n });\n }\n}\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\n constructor(functionName, { docsPath }) {\n super([\n `Function \"${functionName}\" does not contain any \\`outputs\\` on ABI.`,\n 'Cannot decode function result without knowing what the parameter types are.',\n 'Make sure you are using the correct ABI and that the function exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiFunctionOutputsNotFoundError',\n });\n }\n}\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\n constructor(signature, { docsPath }) {\n super([\n `Encoded function signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the function exists on it.',\n `You can look up the signature here: https://openchain.xyz/signatures?query=${signature}.`,\n ].join('\\n'), {\n docsPath,\n name: 'AbiFunctionSignatureNotFoundError',\n });\n }\n}\nexport class AbiItemAmbiguityError extends BaseError {\n constructor(x, y) {\n super('Found ambiguous types in overloaded ABI items.', {\n metaMessages: [\n `\\`${x.type}\\` in \\`${formatAbiItem(x.abiItem)}\\`, and`,\n `\\`${y.type}\\` in \\`${formatAbiItem(y.abiItem)}\\``,\n '',\n 'These types encode differently and cannot be distinguished at runtime.',\n 'Remove one of the ambiguous items in the ABI.',\n ],\n name: 'AbiItemAmbiguityError',\n });\n }\n}\nexport class BytesSizeMismatchError extends BaseError {\n constructor({ expectedSize, givenSize, }) {\n super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {\n name: 'BytesSizeMismatchError',\n });\n }\n}\nexport class DecodeLogDataMismatch extends BaseError {\n constructor({ abiItem, data, params, size, }) {\n super([\n `Data size of ${size} bytes is too small for non-indexed event parameters.`,\n ].join('\\n'), {\n metaMessages: [\n `Params: (${formatAbiParams(params, { includeName: true })})`,\n `Data: ${data} (${size} bytes)`,\n ],\n name: 'DecodeLogDataMismatch',\n });\n Object.defineProperty(this, \"abiItem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"data\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"params\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"size\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.abiItem = abiItem;\n this.data = data;\n this.params = params;\n this.size = size;\n }\n}\nexport class DecodeLogTopicsMismatch extends BaseError {\n constructor({ abiItem, param, }) {\n super([\n `Expected a topic for indexed event parameter${param.name ? ` \"${param.name}\"` : ''} on event \"${formatAbiItem(abiItem, { includeName: true })}\".`,\n ].join('\\n'), { name: 'DecodeLogTopicsMismatch' });\n Object.defineProperty(this, \"abiItem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.abiItem = abiItem;\n }\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\n constructor(type, { docsPath }) {\n super([\n `Type \"${type}\" is not a valid encoding type.`,\n 'Please provide a valid ABI type.',\n ].join('\\n'), { docsPath, name: 'InvalidAbiEncodingType' });\n }\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\n constructor(type, { docsPath }) {\n super([\n `Type \"${type}\" is not a valid decoding type.`,\n 'Please provide a valid ABI type.',\n ].join('\\n'), { docsPath, name: 'InvalidAbiDecodingType' });\n }\n}\nexport class InvalidArrayError extends BaseError {\n constructor(value) {\n super([`Value \"${value}\" is not a valid array.`].join('\\n'), {\n name: 'InvalidArrayError',\n });\n }\n}\nexport class InvalidDefinitionTypeError extends BaseError {\n constructor(type) {\n super([\n `\"${type}\" is not a valid definition type.`,\n 'Valid types: \"function\", \"event\", \"error\"',\n ].join('\\n'), { name: 'InvalidDefinitionTypeError' });\n }\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n constructor(type) {\n super(`Type \"${type}\" is not supported for packed encoding.`, {\n name: 'UnsupportedPackedAbiType',\n });\n }\n}\n//# sourceMappingURL=abi.js.map","import { BaseError } from './base.js';\nexport class SliceOffsetOutOfBoundsError extends BaseError {\n constructor({ offset, position, size, }) {\n super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset \"${offset}\" is out-of-bounds (size: ${size}).`, { name: 'SliceOffsetOutOfBoundsError' });\n }\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: 'SizeExceedsPaddingSizeError' });\n }\n}\nexport class InvalidBytesLengthError extends BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`, { name: 'InvalidBytesLengthError' });\n }\n}\n//# sourceMappingURL=data.js.map","import { SizeExceedsPaddingSizeError, } from '../../errors/data.js';\nexport function pad(hexOrBytes, { dir, size = 32 } = {}) {\n if (typeof hexOrBytes === 'string')\n return padHex(hexOrBytes, { dir, size });\n return padBytes(hexOrBytes, { dir, size });\n}\nexport function padHex(hex_, { dir, size = 32 } = {}) {\n if (size === null)\n return hex_;\n const hex = hex_.replace('0x', '');\n if (hex.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'hex',\n });\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;\n}\nexport function padBytes(bytes, { dir, size = 32 } = {}) {\n if (size === null)\n return bytes;\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n });\n const paddedBytes = new Uint8Array(size);\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right';\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1];\n }\n return paddedBytes;\n}\n//# sourceMappingURL=pad.js.map","import { BaseError } from './base.js';\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({ max, min, signed, size, value, }) {\n super(`Number \"${value}\" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: 'IntegerOutOfRangeError' });\n }\n}\nexport class InvalidBytesBooleanError extends BaseError {\n constructor(bytes) {\n super(`Bytes value \"${bytes}\" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, {\n name: 'InvalidBytesBooleanError',\n });\n }\n}\nexport class InvalidHexBooleanError extends BaseError {\n constructor(hex) {\n super(`Hex value \"${hex}\" is not a valid boolean. The hex value must be \"0x0\" (false) or \"0x1\" (true).`, { name: 'InvalidHexBooleanError' });\n }\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value) {\n super(`Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`, { name: 'InvalidHexValueError' });\n }\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }) {\n super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: 'SizeOverflowError' });\n }\n}\n//# sourceMappingURL=encoding.js.map","export function trim(hexOrBytes, { dir = 'left' } = {}) {\n let data = typeof hexOrBytes === 'string' ? hexOrBytes.replace('0x', '') : hexOrBytes;\n let sliceLength = 0;\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++;\n else\n break;\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength);\n if (typeof hexOrBytes === 'string') {\n if (data.length === 1 && dir === 'right')\n data = `${data}0`;\n return `0x${data.length % 2 === 1 ? `0${data}` : data}`;\n }\n return data;\n}\n//# sourceMappingURL=trim.js.map","import { InvalidHexBooleanError, SizeOverflowError, } from '../../errors/encoding.js';\nimport { size as size_ } from '../data/size.js';\nimport { trim } from '../data/trim.js';\nimport { hexToBytes } from './toBytes.js';\nexport function assertSize(hexOrBytes, { size }) {\n if (size_(hexOrBytes) > size)\n throw new SizeOverflowError({\n givenSize: size_(hexOrBytes),\n maxSize: size,\n });\n}\n/**\n * Decodes a hex string into a string, number, bigint, boolean, or byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex\n * - Example: https://viem.sh/docs/utilities/fromHex#usage\n *\n * @param hex Hex string to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x1a4', 'number')\n * // 420\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c6421', 'string')\n * // 'Hello world'\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * to: 'string'\n * })\n * // 'Hello world'\n */\nexport function fromHex(hex, toOrOpts) {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts;\n const to = opts.to;\n if (to === 'number')\n return hexToNumber(hex, opts);\n if (to === 'bigint')\n return hexToBigInt(hex, opts);\n if (to === 'string')\n return hexToString(hex, opts);\n if (to === 'boolean')\n return hexToBool(hex, opts);\n return hexToBytes(hex, opts);\n}\n/**\n * Decodes a hex value into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x1a4', { signed: true })\n * // 420n\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420n\n */\nexport function hexToBigInt(hex, opts = {}) {\n const { signed } = opts;\n if (opts.size)\n assertSize(hex, { size: opts.size });\n const value = BigInt(hex);\n if (!signed)\n return value;\n const size = (hex.length - 2) / 2;\n const max = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n if (value <= max)\n return value;\n return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n;\n}\n/**\n * Decodes a hex value into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobool\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x01')\n * // true\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // true\n */\nexport function hexToBool(hex_, opts = {}) {\n let hex = hex_;\n if (opts.size) {\n assertSize(hex, { size: opts.size });\n hex = trim(hex);\n }\n if (trim(hex) === '0x00')\n return false;\n if (trim(hex) === '0x01')\n return true;\n throw new InvalidHexBooleanError(hex);\n}\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x1a4')\n * // 420\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420\n */\nexport function hexToNumber(hex, opts = {}) {\n return Number(hexToBigInt(hex, opts));\n}\n/**\n * Decodes a hex value into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextostring\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c6421')\n * // 'Hello world!'\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // 'Hello world'\n */\nexport function hexToString(hex, opts = {}) {\n let bytes = hexToBytes(hex);\n if (opts.size) {\n assertSize(bytes, { size: opts.size });\n bytes = trim(bytes, { dir: 'right' });\n }\n return new TextDecoder().decode(bytes);\n}\n//# sourceMappingURL=fromHex.js.map","import { IntegerOutOfRangeError, } from '../../errors/encoding.js';\nimport { pad } from '../data/pad.js';\nimport { assertSize } from './fromHex.js';\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));\n/**\n * Encodes a string, number, bigint, or ByteArray into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex\n * - Example: https://viem.sh/docs/utilities/toHex#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world')\n * // '0x48656c6c6f20776f726c6421'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex(420)\n * // '0x1a4'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world', { size: 32 })\n * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'\n */\nexport function toHex(value, opts = {}) {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToHex(value, opts);\n if (typeof value === 'string') {\n return stringToHex(value, opts);\n }\n if (typeof value === 'boolean')\n return boolToHex(value, opts);\n return bytesToHex(value, opts);\n}\n/**\n * Encodes a boolean into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#booltohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true)\n * // '0x1'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(false)\n * // '0x0'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true, { size: 32 })\n * // '0x0000000000000000000000000000000000000000000000000000000000000001'\n */\nexport function boolToHex(value, opts = {}) {\n const hex = `0x${Number(value)}`;\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size });\n return pad(hex, { size: opts.size });\n }\n return hex;\n}\n/**\n * Encodes a bytes array into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function bytesToHex(value, opts = {}) {\n let string = '';\n for (let i = 0; i < value.length; i++) {\n string += hexes[value[i]];\n }\n const hex = `0x${string}`;\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size });\n return pad(hex, { dir: 'right', size: opts.size });\n }\n return hex;\n}\n/**\n * Encodes a number or bigint into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420)\n * // '0x1a4'\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420, { size: 32 })\n * // '0x00000000000000000000000000000000000000000000000000000000000001a4'\n */\nexport function numberToHex(value_, opts = {}) {\n const { signed, size } = opts;\n const value = BigInt(value_);\n let maxValue;\n if (size) {\n if (signed)\n maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n else\n maxValue = 2n ** (BigInt(size) * 8n) - 1n;\n }\n else if (typeof value_ === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER);\n }\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;\n if ((maxValue && value > maxValue) || value < minValue) {\n const suffix = typeof value_ === 'bigint' ? 'n' : '';\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value_}${suffix}`,\n });\n }\n const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;\n if (size)\n return pad(hex, { size });\n return hex;\n}\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Encodes a UTF-8 string into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function stringToHex(value_, opts = {}) {\n const value = encoder.encode(value_);\n return bytesToHex(value, opts);\n}\n//# sourceMappingURL=toHex.js.map","import { BaseError } from '../../errors/base.js';\nimport { isHex } from '../data/isHex.js';\nimport { pad } from '../data/pad.js';\nimport { assertSize } from './fromHex.js';\nimport { numberToHex, } from './toHex.js';\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes\n * - Example: https://viem.sh/docs/utilities/toBytes#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes('Hello world')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function toBytes(value, opts = {}) {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToBytes(value, opts);\n if (typeof value === 'boolean')\n return boolToBytes(value, opts);\n if (isHex(value))\n return hexToBytes(value, opts);\n return stringToBytes(value, opts);\n}\n/**\n * Encodes a boolean into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes\n *\n * @param value Boolean value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true)\n * // Uint8Array([1])\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true, { size: 32 })\n * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n */\nexport function boolToBytes(value, opts = {}) {\n const bytes = new Uint8Array(1);\n bytes[0] = Number(value);\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size });\n return pad(bytes, { size: opts.size });\n }\n return bytes;\n}\n// We use very optimized technique to convert hex string to byte array\nconst charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n};\nfunction charCodeToBase16(char) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero;\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10);\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10);\n return undefined;\n}\n/**\n * Encodes a hex string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes\n *\n * @param hex Hex string to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function hexToBytes(hex_, opts = {}) {\n let hex = hex_;\n if (opts.size) {\n assertSize(hex, { size: opts.size });\n hex = pad(hex, { dir: 'right', size: opts.size });\n }\n let hexString = hex.slice(2);\n if (hexString.length % 2)\n hexString = `0${hexString}`;\n const length = hexString.length / 2;\n const bytes = new Uint8Array(length);\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));\n const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new BaseError(`Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`);\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight;\n }\n return bytes;\n}\n/**\n * Encodes a number into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes\n *\n * @param value Number to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function numberToBytes(value, opts) {\n const hex = numberToHex(value, opts);\n return hexToBytes(hex);\n}\n/**\n * Encodes a UTF-8 string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes\n *\n * @param value String to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function stringToBytes(value, opts = {}) {\n const bytes = encoder.encode(value);\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size });\n return pad(bytes, { dir: 'right', size: opts.size });\n }\n return bytes;\n}\n//# sourceMappingURL=toBytes.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n const len = lst.length;\n let Ah = new Uint32Array(len);\n let Al = new Uint32Array(len);\n for (let i = 0; i < len; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { add, add3H, add3L, add4H, add4L, add5H, add5L, fromBig, rotlBH, rotlBL, rotlSH, rotlSL, rotr32H, rotr32L, rotrBH, rotrBL, rotrSH, rotrSL, shrSH, shrSL, split, toBig };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is positive integer. */\nexport function anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Asserts something is Uint8Array. */\nexport function abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nexport function ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.createHasher');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nexport function aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nexport function aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\n/** Cast u8 / u16 / u32 to u8. */\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** Cast u8 / u16 / u32 to u32. */\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n/** Zeroize a byte array. Warning: JS provides no guarantees. */\nexport function clean(...arrays) {\n for (let i = 0; i < arrays.length; i++) {\n arrays[i].fill(0);\n }\n}\n/** Create DataView of an array for easy byte-level manipulation. */\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n/** The byte swap operation for uint32 */\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const swap8IfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** @deprecated */\nexport const byteSwapIfBE = swap8IfBE;\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n return arr;\n}\nexport const swap32IfBE = isLE\n ? (u) => u\n : byteSwap32;\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = /* @__PURE__ */ (() => \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function')();\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Converts string to bytes using UTF8 encoding.\n * @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('string expected');\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Converts bytes to string using UTF8 encoding.\n * @example bytesToUtf8(Uint8Array.from([97, 98, 99])) // 'abc'\n */\nexport function bytesToUtf8(bytes) {\n return new TextDecoder().decode(bytes);\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Helper for KDFs: consumes uint8array or string.\n * When string is passed, does utf8 decoding, using TextDecoder.\n */\nexport function kdfInputToBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/** Copies several Uint8Arrays into one. */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function createHasher(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function createOptHasher(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function createXOFer(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport const wrapConstructor = createHasher;\nexport const wrapConstructorWithOpts = createOptHasher;\nexport const wrapXOFConstructorWithOpts = createXOFer;\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\n// prettier-ignore\nimport { abytes, aexists, anumber, aoutput, clean, createHasher, createXOFer, Hash, swap32IfBE, toBytes, u32 } from \"./utils.js\";\n// No __PURE__ annotations in sha3 header:\n// EVERYTHING is in fact used on every export.\n// Various per round constants calculations\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst _7n = BigInt(7);\nconst _256n = BigInt(256);\nconst _0x71n = BigInt(0x71);\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst IOTAS = split(_SHA3_IOTA, true);\nconst SHA3_IOTA_H = IOTAS[0];\nconst SHA3_IOTA_L = IOTAS[1];\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n clean(B);\n}\n/** Keccak sponge function. */\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n this.enableXOF = false;\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (!(0 < blockLen && blockLen < 200))\n throw new Error('only keccak-f1600 function is supported');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n clone() {\n return this._cloneInto();\n }\n keccak() {\n swap32IfBE(this.state32);\n keccakP(this.state32, this.rounds);\n swap32IfBE(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n data = toBytes(data);\n abytes(data);\n const { blockLen, state } = this;\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n clean(this.state);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => createHasher(() => new Keccak(blockLen, suffix, outputLen));\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ (() => gen(0x06, 144, 224 / 8))();\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ (() => gen(0x06, 136, 256 / 8))();\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ (() => gen(0x06, 104, 384 / 8))();\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ (() => gen(0x06, 72, 512 / 8))();\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ (() => gen(0x01, 144, 224 / 8))();\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ (() => gen(0x01, 136, 256 / 8))();\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ (() => gen(0x01, 104, 384 / 8))();\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ (() => gen(0x01, 72, 512 / 8))();\nconst genShake = (suffix, blockLen, outputLen) => createXOFer((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = /* @__PURE__ */ (() => genShake(0x1f, 168, 128 / 8))();\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = /* @__PURE__ */ (() => genShake(0x1f, 136, 256 / 8))();\n//# sourceMappingURL=sha3.js.map","import { keccak_256 } from '@noble/hashes/sha3';\nimport { isHex } from '../data/isHex.js';\nimport { toBytes } from '../encoding/toBytes.js';\nimport { toHex } from '../encoding/toHex.js';\nexport function keccak256(value, to_) {\n const to = to_ || 'hex';\n const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value);\n if (to === 'bytes')\n return bytes;\n return toHex(bytes);\n}\n//# sourceMappingURL=keccak256.js.map","import { toBytes } from '../encoding/toBytes.js';\nimport { keccak256 } from './keccak256.js';\nconst hash = (value) => keccak256(toBytes(value));\nexport function hashSignature(sig) {\n return hash(sig);\n}\n//# sourceMappingURL=hashSignature.js.map","import { BaseError } from '../../errors/base.js';\nexport function normalizeSignature(signature) {\n let active = true;\n let current = '';\n let level = 0;\n let result = '';\n let valid = false;\n for (let i = 0; i < signature.length; i++) {\n const char = signature[i];\n // If the character is a separator, we want to reactivate.\n if (['(', ')', ','].includes(char))\n active = true;\n // If the character is a \"level\" token, we want to increment/decrement.\n if (char === '(')\n level++;\n if (char === ')')\n level--;\n // If we aren't active, we don't want to mutate the result.\n if (!active)\n continue;\n // If level === 0, we are at the definition level.\n if (level === 0) {\n if (char === ' ' && ['event', 'function', ''].includes(result))\n result = '';\n else {\n result += char;\n // If we are at the end of the definition, we must be finished.\n if (char === ')') {\n valid = true;\n break;\n }\n }\n continue;\n }\n // Ignore spaces\n if (char === ' ') {\n // If the previous character is a separator, and the current section isn't empty, we want to deactivate.\n if (signature[i - 1] !== ',' && current !== ',' && current !== ',(') {\n current = '';\n active = false;\n }\n continue;\n }\n result += char;\n current += char;\n }\n if (!valid)\n throw new BaseError('Unable to normalize signature.');\n return result;\n}\n//# sourceMappingURL=normalizeSignature.js.map","import { formatAbiItem } from 'abitype';\nimport { normalizeSignature, } from './normalizeSignature.js';\n/**\n * Returns the signature for a given function or event definition.\n *\n * @example\n * const signature = toSignature('function ownerOf(uint256 tokenId)')\n * // 'ownerOf(uint256)'\n *\n * @example\n * const signature_3 = toSignature({\n * name: 'ownerOf',\n * type: 'function',\n * inputs: [{ name: 'tokenId', type: 'uint256' }],\n * outputs: [],\n * stateMutability: 'view',\n * })\n * // 'ownerOf(uint256)'\n */\nexport const toSignature = (def) => {\n const def_ = (() => {\n if (typeof def === 'string')\n return def;\n return formatAbiItem(def);\n })();\n return normalizeSignature(def_);\n};\n//# sourceMappingURL=toSignature.js.map","import { hashSignature } from './hashSignature.js';\nimport { toSignature } from './toSignature.js';\n/**\n * Returns the hash (of the function/event signature) for a given event or function definition.\n */\nexport function toSignatureHash(fn) {\n return hashSignature(toSignature(fn));\n}\n//# sourceMappingURL=toSignatureHash.js.map","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n constructor(size) {\n super();\n Object.defineProperty(this, \"maxSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxSize = size;\n }\n get(key) {\n const value = super.get(key);\n if (super.has(key) && value !== undefined) {\n this.delete(key);\n super.set(key, value);\n }\n return value;\n }\n set(key, value) {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value;\n if (firstKey)\n this.delete(firstKey);\n }\n return this;\n }\n}\n//# sourceMappingURL=lru.js.map","import { InvalidAddressError } from '../../errors/address.js';\nimport { stringToBytes, } from '../encoding/toBytes.js';\nimport { keccak256 } from '../hash/keccak256.js';\nimport { LruMap } from '../lru.js';\nimport { isAddress } from './isAddress.js';\nconst checksumAddressCache = /*#__PURE__*/ new LruMap(8192);\nexport function checksumAddress(address_, \n/**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\nchainId) {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`);\n const hexAddress = chainId\n ? `${chainId}${address_.toLowerCase()}`\n : address_.substring(2).toLowerCase();\n const hash = keccak256(stringToBytes(hexAddress), 'bytes');\n const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split('');\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n address[i] = address[i].toUpperCase();\n }\n if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n address[i + 1] = address[i + 1].toUpperCase();\n }\n }\n const result = `0x${address.join('')}`;\n checksumAddressCache.set(`${address_}.${chainId}`, result);\n return result;\n}\nexport function getAddress(address, \n/**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\nchainId) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address });\n return checksumAddress(address, chainId);\n}\n//# sourceMappingURL=getAddress.js.map","import { SliceOffsetOutOfBoundsError, } from '../../errors/data.js';\nimport { isHex } from './isHex.js';\nimport { size } from './size.js';\n/**\n * @description Returns a section of the hex or byte array given a start/end bytes offset.\n *\n * @param value The hex or byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function slice(value, start, end, { strict } = {}) {\n if (isHex(value, { strict: false }))\n return sliceHex(value, start, end, {\n strict,\n });\n return sliceBytes(value, start, end, {\n strict,\n });\n}\nfunction assertStartOffset(value, start) {\n if (typeof start === 'number' && start > 0 && start > size(value) - 1)\n throw new SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: size(value),\n });\n}\nfunction assertEndOffset(value, start, end) {\n if (typeof start === 'number' &&\n typeof end === 'number' &&\n size(value) !== end - start) {\n throw new SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: size(value),\n });\n }\n}\n/**\n * @description Returns a section of the byte array given a start/end bytes offset.\n *\n * @param value The byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceBytes(value_, start, end, { strict } = {}) {\n assertStartOffset(value_, start);\n const value = value_.slice(start, end);\n if (strict)\n assertEndOffset(value, start, end);\n return value;\n}\n/**\n * @description Returns a section of the hex value given a start/end bytes offset.\n *\n * @param value The hex value to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceHex(value_, start, end, { strict } = {}) {\n assertStartOffset(value_, start);\n const value = `0x${value_\n .replace('0x', '')\n .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;\n if (strict)\n assertEndOffset(value, start, end);\n return value;\n}\n//# sourceMappingURL=slice.js.map","import { AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, InvalidAbiEncodingTypeError, InvalidArrayError, } from '../../errors/abi.js';\nimport { InvalidAddressError, } from '../../errors/address.js';\nimport { BaseError } from '../../errors/base.js';\nimport { IntegerOutOfRangeError } from '../../errors/encoding.js';\nimport { isAddress } from '../address/isAddress.js';\nimport { concat } from '../data/concat.js';\nimport { padHex } from '../data/pad.js';\nimport { size } from '../data/size.js';\nimport { slice } from '../data/slice.js';\nimport { boolToHex, numberToHex, stringToHex, } from '../encoding/toHex.js';\nimport { integerRegex } from '../regex.js';\n/**\n * @description Encodes a list of primitive values into an ABI-encoded hex value.\n *\n * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters\n *\n * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.\n *\n * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.\n * @param values - a set of values (values) that correspond to the given params.\n * @example\n * ```typescript\n * import { encodeAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' }\n * ],\n * ['wagmi', 420n, true]\n * )\n * ```\n *\n * You can also pass in Human Readable parameters with the parseAbiParameters utility.\n *\n * @example\n * ```typescript\n * import { encodeAbiParameters, parseAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * parseAbiParameters('string x, uint y, bool z'),\n * ['wagmi', 420n, true]\n * )\n * ```\n */\nexport function encodeAbiParameters(params, values) {\n if (params.length !== values.length)\n throw new AbiEncodingLengthMismatchError({\n expectedLength: params.length,\n givenLength: values.length,\n });\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params,\n values: values,\n });\n const data = encodeParams(preparedParams);\n if (data.length === 0)\n return '0x';\n return data;\n}\nfunction prepareParams({ params, values, }) {\n const preparedParams = [];\n for (let i = 0; i < params.length; i++) {\n preparedParams.push(prepareParam({ param: params[i], value: values[i] }));\n }\n return preparedParams;\n}\nfunction prepareParam({ param, value, }) {\n const arrayComponents = getArrayComponents(param.type);\n if (arrayComponents) {\n const [length, type] = arrayComponents;\n return encodeArray(value, { length, param: { ...param, type } });\n }\n if (param.type === 'tuple') {\n return encodeTuple(value, {\n param: param,\n });\n }\n if (param.type === 'address') {\n return encodeAddress(value);\n }\n if (param.type === 'bool') {\n return encodeBool(value);\n }\n if (param.type.startsWith('uint') || param.type.startsWith('int')) {\n const signed = param.type.startsWith('int');\n const [, , size = '256'] = integerRegex.exec(param.type) ?? [];\n return encodeNumber(value, {\n signed,\n size: Number(size),\n });\n }\n if (param.type.startsWith('bytes')) {\n return encodeBytes(value, { param });\n }\n if (param.type === 'string') {\n return encodeString(value);\n }\n throw new InvalidAbiEncodingTypeError(param.type, {\n docsPath: '/docs/contract/encodeAbiParameters',\n });\n}\nfunction encodeParams(preparedParams) {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0;\n for (let i = 0; i < preparedParams.length; i++) {\n const { dynamic, encoded } = preparedParams[i];\n if (dynamic)\n staticSize += 32;\n else\n staticSize += size(encoded);\n }\n // 2. Split the parameters into static and dynamic parts.\n const staticParams = [];\n const dynamicParams = [];\n let dynamicSize = 0;\n for (let i = 0; i < preparedParams.length; i++) {\n const { dynamic, encoded } = preparedParams[i];\n if (dynamic) {\n staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));\n dynamicParams.push(encoded);\n dynamicSize += size(encoded);\n }\n else {\n staticParams.push(encoded);\n }\n }\n // 3. Concatenate static and dynamic parts.\n return concat([...staticParams, ...dynamicParams]);\n}\nfunction encodeAddress(value) {\n if (!isAddress(value))\n throw new InvalidAddressError({ address: value });\n return { dynamic: false, encoded: padHex(value.toLowerCase()) };\n}\nfunction encodeArray(value, { length, param, }) {\n const dynamic = length === null;\n if (!Array.isArray(value))\n throw new InvalidArrayError(value);\n if (!dynamic && value.length !== length)\n throw new AbiEncodingArrayLengthMismatchError({\n expectedLength: length,\n givenLength: value.length,\n type: `${param.type}[${length}]`,\n });\n let dynamicChild = false;\n const preparedParams = [];\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParam({ param, value: value[i] });\n if (preparedParam.dynamic)\n dynamicChild = true;\n preparedParams.push(preparedParam);\n }\n if (dynamic || dynamicChild) {\n const data = encodeParams(preparedParams);\n if (dynamic) {\n const length = numberToHex(preparedParams.length, { size: 32 });\n return {\n dynamic: true,\n encoded: preparedParams.length > 0 ? concat([length, data]) : length,\n };\n }\n if (dynamicChild)\n return { dynamic: true, encoded: data };\n }\n return {\n dynamic: false,\n encoded: concat(preparedParams.map(({ encoded }) => encoded)),\n };\n}\nfunction encodeBytes(value, { param }) {\n const [, paramSize] = param.type.split('bytes');\n const bytesSize = size(value);\n if (!paramSize) {\n let value_ = value;\n // If the size is not divisible by 32 bytes, pad the end\n // with empty bytes to the ceiling 32 bytes.\n if (bytesSize % 32 !== 0)\n value_ = padHex(value_, {\n dir: 'right',\n size: Math.ceil((value.length - 2) / 2 / 32) * 32,\n });\n return {\n dynamic: true,\n encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]),\n };\n }\n if (bytesSize !== Number.parseInt(paramSize, 10))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize, 10),\n value,\n });\n return { dynamic: false, encoded: padHex(value, { dir: 'right' }) };\n}\nfunction encodeBool(value) {\n if (typeof value !== 'boolean')\n throw new BaseError(`Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`);\n return { dynamic: false, encoded: padHex(boolToHex(value)) };\n}\nfunction encodeNumber(value, { signed, size = 256 }) {\n if (typeof size === 'number') {\n const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n;\n const min = signed ? -max - 1n : 0n;\n if (value > max || value < min)\n throw new IntegerOutOfRangeError({\n max: max.toString(),\n min: min.toString(),\n signed,\n size: size / 8,\n value: value.toString(),\n });\n }\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n size: 32,\n signed,\n }),\n };\n}\nfunction encodeString(value) {\n const hexValue = stringToHex(value);\n const partsLength = Math.ceil(size(hexValue) / 32);\n const parts = [];\n for (let i = 0; i < partsLength; i++) {\n parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), {\n dir: 'right',\n }));\n }\n return {\n dynamic: true,\n encoded: concat([\n padHex(numberToHex(size(hexValue), { size: 32 })),\n ...parts,\n ]),\n };\n}\nfunction encodeTuple(value, { param }) {\n let dynamic = false;\n const preparedParams = [];\n for (let i = 0; i < param.components.length; i++) {\n const param_ = param.components[i];\n const index = Array.isArray(value) ? i : param_.name;\n const preparedParam = prepareParam({\n param: param_,\n value: value[index],\n });\n preparedParams.push(preparedParam);\n if (preparedParam.dynamic)\n dynamic = true;\n }\n return {\n dynamic,\n encoded: dynamic\n ? encodeParams(preparedParams)\n : concat(preparedParams.map(({ encoded }) => encoded)),\n };\n}\nexport function getArrayComponents(type) {\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//# sourceMappingURL=encodeAbiParameters.js.map","import { slice } from '../data/slice.js';\nimport { toSignatureHash, } from './toSignatureHash.js';\n/**\n * Returns the function selector for a given function definition.\n *\n * @example\n * const selector = toFunctionSelector('function ownerOf(uint256 tokenId)')\n * // 0x6352211e\n */\nexport const toFunctionSelector = (fn) => slice(toSignatureHash(fn), 0, 4);\n//# sourceMappingURL=toFunctionSelector.js.map","import { BaseError } from './base.js';\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n });\n }\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }) {\n super(`Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`, { name: 'PositionOutOfBoundsError' });\n }\n}\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }) {\n super(`Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`, { name: 'RecursiveReadLimitExceededError' });\n }\n}\n//# sourceMappingURL=cursor.js.map","import { NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError, } from '../errors/cursor.js';\nconst staticCursor = {\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)\n 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)\n 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 ((this.dataView.getUint16(position) << 8) +\n this.dataView.getUint8(position + 2));\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) {\n this.assertPosition(this.position);\n this.bytes[this.position] = byte;\n this.position++;\n },\n pushBytes(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) {\n this.assertPosition(this.position);\n this.bytes[this.position] = value;\n this.position++;\n },\n pushUint16(value) {\n this.assertPosition(this.position + 1);\n this.dataView.setUint16(this.position, value);\n this.position += 2;\n },\n pushUint24(value) {\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) {\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)\n return;\n const count = this.getReadCount();\n this.positionReadCount.set(this.position, count + 1);\n if (count > 0)\n this.recursiveReadCount++;\n },\n};\nexport function createCursor(bytes, { recursiveReadLimit = 8_192 } = {}) {\n const cursor = Object.create(staticCursor);\n cursor.bytes = bytes;\n cursor.dataView = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);\n cursor.positionReadCount = new Map();\n cursor.recursiveReadLimit = recursiveReadLimit;\n return cursor;\n}\n//# sourceMappingURL=cursor.js.map","import { InvalidBytesBooleanError } from '../../errors/encoding.js';\nimport { trim } from '../data/trim.js';\nimport { assertSize, hexToBigInt, hexToNumber, } from './fromHex.js';\nimport { bytesToHex } from './toHex.js';\n/**\n * Decodes a byte array into a UTF-8 string, hex value, number, bigint or boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes\n * - Example: https://viem.sh/docs/utilities/fromBytes#usage\n *\n * @param bytes Byte array to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(new Uint8Array([1, 164]), 'number')\n * // 420\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(\n * new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]),\n * 'string'\n * )\n * // 'Hello world'\n */\nexport function fromBytes(bytes, toOrOpts) {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts;\n const to = opts.to;\n if (to === 'number')\n return bytesToNumber(bytes, opts);\n if (to === 'bigint')\n return bytesToBigInt(bytes, opts);\n if (to === 'boolean')\n return bytesToBool(bytes, opts);\n if (to === 'string')\n return bytesToString(bytes, opts);\n return bytesToHex(bytes, opts);\n}\n/**\n * Decodes a byte array into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobigint\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { bytesToBigInt } from 'viem'\n * const data = bytesToBigInt(new Uint8Array([1, 164]))\n * // 420n\n */\nexport function bytesToBigInt(bytes, opts = {}) {\n if (typeof opts.size !== 'undefined')\n assertSize(bytes, { size: opts.size });\n const hex = bytesToHex(bytes, opts);\n return hexToBigInt(hex, opts);\n}\n/**\n * Decodes a byte array into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobool\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { bytesToBool } from 'viem'\n * const data = bytesToBool(new Uint8Array([1]))\n * // true\n */\nexport function bytesToBool(bytes_, opts = {}) {\n let bytes = bytes_;\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size });\n bytes = trim(bytes);\n }\n if (bytes.length > 1 || bytes[0] > 1)\n throw new InvalidBytesBooleanError(bytes);\n return Boolean(bytes[0]);\n}\n/**\n * Decodes a byte array into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestonumber\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { bytesToNumber } from 'viem'\n * const data = bytesToNumber(new Uint8Array([1, 164]))\n * // 420\n */\nexport function bytesToNumber(bytes, opts = {}) {\n if (typeof opts.size !== 'undefined')\n assertSize(bytes, { size: opts.size });\n const hex = bytesToHex(bytes, opts);\n return hexToNumber(hex, opts);\n}\n/**\n * Decodes a byte array into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestostring\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { bytesToString } from 'viem'\n * const data = bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // 'Hello world'\n */\nexport function bytesToString(bytes_, opts = {}) {\n let bytes = bytes_;\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size });\n bytes = trim(bytes, { dir: 'right' });\n }\n return new TextDecoder().decode(bytes);\n}\n//# sourceMappingURL=fromBytes.js.map","import { AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, InvalidAbiDecodingTypeError, } from '../../errors/abi.js';\nimport { checksumAddress, } from '../address/getAddress.js';\nimport { createCursor, } from '../cursor.js';\nimport { size } from '../data/size.js';\nimport { sliceBytes } from '../data/slice.js';\nimport { trim } from '../data/trim.js';\nimport { bytesToBigInt, bytesToBool, bytesToNumber, bytesToString, } from '../encoding/fromBytes.js';\nimport { hexToBytes } from '../encoding/toBytes.js';\nimport { bytesToHex } from '../encoding/toHex.js';\nimport { getArrayComponents } from './encodeAbiParameters.js';\nexport function decodeAbiParameters(params, data) {\n const bytes = typeof data === 'string' ? hexToBytes(data) : data;\n const cursor = createCursor(bytes);\n if (size(bytes) === 0 && params.length > 0)\n throw new AbiDecodingZeroDataError();\n if (size(data) && size(data) < 32)\n throw new AbiDecodingDataSizeTooSmallError({\n data: typeof data === 'string' ? data : bytesToHex(data),\n params: params,\n size: size(data),\n });\n let consumed = 0;\n const values = [];\n for (let i = 0; i < params.length; ++i) {\n const param = params[i];\n cursor.setPosition(consumed);\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: 0,\n });\n consumed += consumed_;\n values.push(data);\n }\n return values;\n}\nfunction decodeParameter(cursor, param, { staticPosition }) {\n const arrayComponents = getArrayComponents(param.type);\n if (arrayComponents) {\n const [length, type] = arrayComponents;\n return decodeArray(cursor, { ...param, type }, { length, staticPosition });\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param, { staticPosition });\n if (param.type === 'address')\n return decodeAddress(cursor);\n if (param.type === 'bool')\n 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')\n return decodeString(cursor, { staticPosition });\n throw new InvalidAbiDecodingTypeError(param.type, {\n docsPath: '/docs/contract/decodeAbiParameters',\n });\n}\n////////////////////////////////////////////////////////////////////\n// Type Decoders\nconst sizeOfLength = 32;\nconst sizeOfOffset = 32;\nfunction decodeAddress(cursor) {\n const value = cursor.readBytes(32);\n return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32];\n}\nfunction decodeArray(cursor, param, { length, staticPosition }) {\n // If the length of the array is not known in advance (dynamic array),\n // this means we will need to wonder off to the pointer and decode.\n if (!length) {\n // Dealing with a dynamic type, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset;\n const startOfData = start + sizeOfLength;\n // Get the length of the array from the offset.\n cursor.setPosition(start);\n const length = bytesToNumber(cursor.readBytes(sizeOfLength));\n // Check if the array has any dynamic children.\n const dynamicChild = hasDynamicChild(param);\n let consumed = 0;\n const value = [];\n for (let i = 0; i < length; ++i) {\n // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n // Otherwise, elements will be the size of their encoding (consumed bytes).\n cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed));\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: startOfData,\n });\n consumed += consumed_;\n value.push(data);\n }\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\n }\n // If the length of the array is known in advance,\n // and the length of an element deeply nested in the array is not known,\n // we need to decode the offset of the array data.\n if (hasDynamicChild(param)) {\n // Dealing with dynamic types, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset;\n const value = [];\n for (let i = 0; i < length; ++i) {\n // Move cursor along to the next slot (next offset pointer).\n cursor.setPosition(start + i * 32);\n const [data] = decodeParameter(cursor, param, {\n staticPosition: start,\n });\n value.push(data);\n }\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\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 = [];\n for (let i = 0; i < length; ++i) {\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: staticPosition + consumed,\n });\n consumed += consumed_;\n value.push(data);\n }\n return [value, consumed];\n}\nfunction decodeBool(cursor) {\n return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32];\n}\nfunction decodeBytes(cursor, param, { staticPosition }) {\n const [_, size] = param.type.split('bytes');\n if (!size) {\n // Dealing with dynamic types, so get the offset of the bytes data.\n const offset = bytesToNumber(cursor.readBytes(32));\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset);\n const length = bytesToNumber(cursor.readBytes(32));\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 const data = cursor.readBytes(length);\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [bytesToHex(data), 32];\n }\n const value = bytesToHex(cursor.readBytes(Number.parseInt(size, 10), 32));\n return [value, 32];\n}\nfunction decodeNumber(cursor, param) {\n const signed = param.type.startsWith('int');\n const size = Number.parseInt(param.type.split('int')[1] || '256', 10);\n const value = cursor.readBytes(32);\n return [\n size > 48\n ? bytesToBigInt(value, { signed })\n : bytesToNumber(value, { signed }),\n 32,\n ];\n}\nfunction decodeTuple(cursor, param, { staticPosition }) {\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 = param.components.length === 0 || param.components.some(({ name }) => !name);\n // Initialize the value to an object or an array, depending on whether the\n // tuple is named or unnamed.\n const value = hasUnnamedChild ? [] : {};\n let consumed = 0;\n // If the tuple has a dynamic child, we must first decode the offset to the\n // tuple data.\n if (hasDynamicChild(param)) {\n // Dealing with dynamic types, so get the offset of the tuple data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));\n // Start is the static position of referencing slot + offset.\n const start = staticPosition + offset;\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i];\n cursor.setPosition(start + consumed);\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition: start,\n });\n consumed += consumed_;\n value[hasUnnamedChild ? i : component?.name] = data;\n }\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\n }\n // If the tuple has static children, we can just decode each component\n // in sequence.\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i];\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition,\n });\n value[hasUnnamedChild ? i : component?.name] = data;\n consumed += consumed_;\n }\n return [value, consumed];\n}\nfunction decodeString(cursor, { staticPosition }) {\n // Get offset to start of string data.\n const offset = bytesToNumber(cursor.readBytes(32));\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset;\n cursor.setPosition(start);\n const length = bytesToNumber(cursor.readBytes(32));\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 const data = cursor.readBytes(length, 32);\n const value = bytesToString(trim(data));\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\n}\nfunction hasDynamicChild(param) {\n const { type } = param;\n if (type === 'string')\n return true;\n if (type === 'bytes')\n return true;\n if (type.endsWith('[]'))\n return true;\n if (type === 'tuple')\n return param.components?.some(hasDynamicChild);\n const arrayComponents = getArrayComponents(param.type);\n if (arrayComponents &&\n hasDynamicChild({ ...param, type: arrayComponents[1] }))\n return true;\n return false;\n}\n//# sourceMappingURL=decodeAbiParameters.js.map","/** @internal */\nexport const version = '0.1.1';\n//# sourceMappingURL=version.js.map","import { version } from '../version.js';\n/** @internal */\nexport function getUrl(url) {\n return url;\n}\n/** @internal */\nexport function getVersion() {\n return version;\n}\n/** @internal */\nexport function prettyPrint(args) {\n if (!args)\n return '';\n const entries = Object.entries(args)\n .map(([key, value]) => {\n if (value === undefined || value === false)\n return null;\n return [key, value];\n })\n .filter(Boolean);\n const maxLength = entries.reduce((acc, [key]) => Math.max(acc, key.length), 0);\n return entries\n .map(([key, value]) => ` ${`${key}:`.padEnd(maxLength + 1)} ${value}`)\n .join('\\n');\n}\n//# sourceMappingURL=errors.js.map","import { getVersion } from './internal/errors.js';\n/**\n * Base error class inherited by all errors thrown by ox.\n *\n * @example\n * ```ts\n * import { Errors } from 'ox'\n * throw new Errors.BaseError('An error occurred')\n * ```\n */\nexport class BaseError extends Error {\n constructor(shortMessage, options = {}) {\n const details = (() => {\n if (options.cause instanceof BaseError) {\n if (options.cause.details)\n return options.cause.details;\n if (options.cause.shortMessage)\n return options.cause.shortMessage;\n }\n if (options.cause &&\n 'details' in options.cause &&\n typeof options.cause.details === 'string')\n return options.cause.details;\n if (options.cause?.message)\n return options.cause.message;\n return options.details;\n })();\n const docsPath = (() => {\n if (options.cause instanceof BaseError)\n return options.cause.docsPath || options.docsPath;\n return options.docsPath;\n })();\n const docsBaseUrl = 'https://oxlib.sh';\n const docs = `${docsBaseUrl}${docsPath ?? ''}`;\n const message = [\n shortMessage || 'An error occurred.',\n ...(options.metaMessages ? ['', ...options.metaMessages] : []),\n ...(details || docsPath\n ? [\n '',\n details ? `Details: ${details}` : undefined,\n docsPath ? `See: ${docs}` : undefined,\n ]\n : []),\n ]\n .filter((x) => typeof x === 'string')\n .join('\\n');\n super(message, options.cause ? { cause: options.cause } : undefined);\n Object.defineProperty(this, \"details\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docsPath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"shortMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"cause\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'BaseError'\n });\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: `ox@${getVersion()}`\n });\n this.cause = options.cause;\n this.details = details;\n this.docs = docs;\n this.docsPath = docsPath;\n this.shortMessage = shortMessage;\n }\n walk(fn) {\n return walk(this, fn);\n }\n}\n/** @internal */\nfunction walk(err, fn) {\n if (fn?.(err))\n return err;\n if (err && typeof err === 'object' && 'cause' in err && err.cause)\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n//# sourceMappingURL=Errors.js.map","const bigIntSuffix = '#__bigint';\n/**\n * Parses a JSON string, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.parse('{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}')\n * // @log: {\n * // @log: foo: 'bar',\n * // @log: baz: 69420694206942069420694206942069420694206942069420n\n * // @log: }\n * ```\n *\n * @param string - The value to parse.\n * @param reviver - A function that transforms the results.\n * @returns The parsed value.\n */\nexport function parse(string, reviver) {\n return JSON.parse(string, (key, value_) => {\n const value = value_;\n if (typeof value === 'string' && value.endsWith(bigIntSuffix))\n return BigInt(value.slice(0, -bigIntSuffix.length));\n return typeof reviver === 'function' ? reviver(key, value) : value;\n });\n}\n/**\n * Stringifies a value to its JSON representation, with support for `bigint`.\n *\n * @example\n * ```ts twoslash\n * import { Json } from 'ox'\n *\n * const json = Json.stringify({\n * foo: 'bar',\n * baz: 69420694206942069420694206942069420694206942069420n,\n * })\n * // @log: '{\"foo\":\"bar\",\"baz\":\"69420694206942069420694206942069420694206942069420#__bigint\"}'\n * ```\n *\n * @param value - The value to stringify.\n * @param replacer - A function that transforms the results. It is passed the key and value of the property, and must return the value to be used in the JSON string. If this function returns `undefined`, the property is not included in the resulting JSON string.\n * @param space - A string or number that determines the indentation of the JSON string. If it is a number, it indicates the number of spaces to use as indentation; if it is a string (e.g. `'\\t'`), it uses the string as the indentation character.\n * @returns The JSON string.\n */\nexport function stringify(value, replacer, space) {\n return JSON.stringify(value, (key, value) => {\n if (typeof replacer === 'function')\n return replacer(key, value);\n if (typeof value === 'bigint')\n return value.toString() + bigIntSuffix;\n return value;\n }, space);\n}\n//# sourceMappingURL=Json.js.map","import * as Bytes from '../Bytes.js';\n/** @internal */\nexport function assertSize(bytes, size_) {\n if (Bytes.size(bytes) > size_)\n throw new Bytes.SizeOverflowError({\n givenSize: Bytes.size(bytes),\n maxSize: size_,\n });\n}\n/** @internal */\nexport function assertStartOffset(value, start) {\n if (typeof start === 'number' && start > 0 && start > Bytes.size(value) - 1)\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Bytes.size(value),\n });\n}\n/** @internal */\nexport function assertEndOffset(value, start, end) {\n if (typeof start === 'number' &&\n typeof end === 'number' &&\n Bytes.size(value) !== end - start) {\n throw new Bytes.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Bytes.size(value),\n });\n }\n}\n/** @internal */\nexport const charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n};\n/** @internal */\nexport function charCodeToBase16(char) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero;\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10);\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10);\n return undefined;\n}\n/** @internal */\nexport function pad(bytes, options = {}) {\n const { dir, size = 32 } = options;\n if (size === 0)\n return bytes;\n if (bytes.length > size)\n throw new Bytes.SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'Bytes',\n });\n const paddedBytes = new Uint8Array(size);\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right';\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1];\n }\n return paddedBytes;\n}\n/** @internal */\nexport function trim(value, options = {}) {\n const { dir = 'left' } = options;\n let data = value;\n let sliceLength = 0;\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++;\n else\n break;\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength);\n return data;\n}\n//# sourceMappingURL=bytes.js.map","import * as Hex from '../Hex.js';\n/** @internal */\nexport function assertSize(hex, size_) {\n if (Hex.size(hex) > size_)\n throw new Hex.SizeOverflowError({\n givenSize: Hex.size(hex),\n maxSize: size_,\n });\n}\n/** @internal */\nexport function assertStartOffset(value, start) {\n if (typeof start === 'number' && start > 0 && start > Hex.size(value) - 1)\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: Hex.size(value),\n });\n}\n/** @internal */\nexport function assertEndOffset(value, start, end) {\n if (typeof start === 'number' &&\n typeof end === 'number' &&\n Hex.size(value) !== end - start) {\n throw new Hex.SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: Hex.size(value),\n });\n }\n}\n/** @internal */\nexport function pad(hex_, options = {}) {\n const { dir, size = 32 } = options;\n if (size === 0)\n return hex_;\n const hex = hex_.replace('0x', '');\n if (hex.length > size * 2)\n throw new Hex.SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'Hex',\n });\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;\n}\n/** @internal */\nexport function trim(value, options = {}) {\n const { dir = 'left' } = options;\n let data = value.replace('0x', '');\n let sliceLength = 0;\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++;\n else\n break;\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength);\n if (data === '0')\n return '0x';\n if (dir === 'right' && data.length % 2 === 1)\n return `0x${data}0`;\n return `0x${data}`;\n}\n//# sourceMappingURL=hex.js.map","import { equalBytes } from '@noble/curves/abstract/utils';\nimport * as Errors from './Errors.js';\nimport * as Hex from './Hex.js';\nimport * as Json from './Json.js';\nimport * as internal from './internal/bytes.js';\nimport * as internal_hex from './internal/hex.js';\nconst decoder = /*#__PURE__*/ new TextDecoder();\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Asserts if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.assert('abc')\n * // @error: Bytes.InvalidBytesTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid Bytes value.\n * // @error: Bytes values must be of type `Uint8Array`.\n * ```\n *\n * @param value - Value to assert.\n */\nexport function assert(value) {\n if (value instanceof Uint8Array)\n return;\n if (!value)\n throw new InvalidBytesTypeError(value);\n if (typeof value !== 'object')\n throw new InvalidBytesTypeError(value);\n if (!('BYTES_PER_ELEMENT' in value))\n throw new InvalidBytesTypeError(value);\n if (value.BYTES_PER_ELEMENT !== 1 || value.constructor.name !== 'Uint8Array')\n throw new InvalidBytesTypeError(value);\n}\n/**\n * Concatenates two or more {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.concat(\n * Bytes.from([1]),\n * Bytes.from([69]),\n * Bytes.from([420, 69]),\n * )\n * // @log: Uint8Array [ 1, 69, 420, 69 ]\n * ```\n *\n * @param values - Values to concatenate.\n * @returns Concatenated {@link ox#Bytes.Bytes}.\n */\nexport function concat(...values) {\n let length = 0;\n for (const arr of values) {\n length += arr.length;\n }\n const result = new Uint8Array(length);\n for (let i = 0, index = 0; i < values.length; i++) {\n const arr = values[i];\n result.set(arr, index);\n index += arr.length;\n }\n return result;\n}\n/**\n * Instantiates a {@link ox#Bytes.Bytes} value from a `Uint8Array`, a hex string, or an array of unsigned 8-bit integers.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Bytes.fromBoolean`\n *\n * - `Bytes.fromString`\n *\n * - `Bytes.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.from([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n *\n * const data = Bytes.from('0xdeadbeef')\n * // @log: Uint8Array([222, 173, 190, 239])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function from(value) {\n if (value instanceof Uint8Array)\n return value;\n if (typeof value === 'string')\n return fromHex(value);\n return fromArray(value);\n}\n/**\n * Converts an array of unsigned 8-bit integers into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromArray([255, 124, 5, 4])\n * // @log: Uint8Array([255, 124, 5, 4])\n * ```\n *\n * @param value - Value to convert.\n * @returns A {@link ox#Bytes.Bytes} instance.\n */\nexport function fromArray(value) {\n return value instanceof Uint8Array ? value : new Uint8Array(value);\n}\n/**\n * Encodes a boolean value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true)\n * // @log: Uint8Array([1])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromBoolean(true, { size: 32 })\n * // @log: Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n * ```\n *\n * @param value - Boolean value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromBoolean(value, options = {}) {\n const { size } = options;\n const bytes = new Uint8Array(1);\n bytes[0] = Number(value);\n if (typeof size === 'number') {\n internal.assertSize(bytes, size);\n return padLeft(bytes, size);\n }\n return bytes;\n}\n/**\n * Encodes a {@link ox#Hex.Hex} value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromHex('0x48656c6c6f20776f726c6421', { size: 32 })\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Hex.Hex} value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromHex(value, options = {}) {\n const { size } = options;\n let hex = value;\n if (size) {\n internal_hex.assertSize(value, size);\n hex = Hex.padRight(value, size);\n }\n let hexString = hex.slice(2);\n if (hexString.length % 2)\n hexString = `0${hexString}`;\n const length = hexString.length / 2;\n const bytes = new Uint8Array(length);\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = internal.charCodeToBase16(hexString.charCodeAt(j++));\n const nibbleRight = internal.charCodeToBase16(hexString.charCodeAt(j++));\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new Errors.BaseError(`Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`);\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight;\n }\n return bytes;\n}\n/**\n * Encodes a number value into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420)\n * // @log: Uint8Array([1, 164])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromNumber(420, { size: 4 })\n * // @log: Uint8Array([0, 0, 1, 164])\n * ```\n *\n * @param value - Number value to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromNumber(value, options) {\n const hex = Hex.fromNumber(value, options);\n return fromHex(hex);\n}\n/**\n * Encodes a string into {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n * ```\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.fromString('Hello world!', { size: 32 })\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n * ```\n *\n * @param value - String to encode.\n * @param options - Encoding options.\n * @returns Encoded {@link ox#Bytes.Bytes}.\n */\nexport function fromString(value, options = {}) {\n const { size } = options;\n const bytes = encoder.encode(value);\n if (typeof size === 'number') {\n internal.assertSize(bytes, size);\n return padRight(bytes, size);\n }\n return bytes;\n}\n/**\n * Checks if two {@link ox#Bytes.Bytes} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([1]))\n * // @log: true\n *\n * Bytes.isEqual(Bytes.from([1]), Bytes.from([2]))\n * // @log: false\n * ```\n *\n * @param bytesA - First {@link ox#Bytes.Bytes} value.\n * @param bytesB - Second {@link ox#Bytes.Bytes} value.\n * @returns `true` if the two values are equal, otherwise `false`.\n */\nexport function isEqual(bytesA, bytesB) {\n return equalBytes(bytesA, bytesB);\n}\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.from([1]), 4)\n * // @log: Uint8Array([0, 0, 0, 1])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padLeft(value, size) {\n return internal.pad(value, { dir: 'left', size });\n}\n/**\n * Pads a {@link ox#Bytes.Bytes} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padRight(Bytes.from([1]), 4)\n * // @log: Uint8Array([1, 0, 0, 0])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value to pad.\n * @param size - Size to pad the {@link ox#Bytes.Bytes} value to.\n * @returns Padded {@link ox#Bytes.Bytes} value.\n */\nexport function padRight(value, size) {\n return internal.pad(value, { dir: 'right', size });\n}\n/**\n * Generates random {@link ox#Bytes.Bytes} of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const bytes = Bytes.random(32)\n * // @log: Uint8Array([... x32])\n * ```\n *\n * @param length - Length of the random {@link ox#Bytes.Bytes} to generate.\n * @returns Random {@link ox#Bytes.Bytes} of the specified length.\n */\nexport function random(length) {\n return crypto.getRandomValues(new Uint8Array(length));\n}\n/**\n * Retrieves the size of a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.size(Bytes.from([1, 2, 3, 4]))\n * // @log: 4\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Size of the {@link ox#Bytes.Bytes} value.\n */\nexport function size(value) {\n return value.length;\n}\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(\n * Bytes.from([1, 2, 3, 4, 5, 6, 7, 8, 9]),\n * 1,\n * 4,\n * )\n * // @log: Uint8Array([2, 3, 4])\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value.\n * @param start - Start offset.\n * @param end - End offset.\n * @param options - Slice options.\n * @returns Sliced {@link ox#Bytes.Bytes} value.\n */\nexport function slice(value, start, end, options = {}) {\n const { strict } = options;\n internal.assertStartOffset(value, start);\n const value_ = value.slice(start, end);\n if (strict)\n internal.assertEndOffset(value_, start, end);\n return value_;\n}\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a bigint.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBigInt(Bytes.from([1, 164]))\n * // @log: 420n\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded bigint.\n */\nexport function toBigInt(bytes, options = {}) {\n const { size } = options;\n if (typeof size !== 'undefined')\n internal.assertSize(bytes, size);\n const hex = Hex.fromBytes(bytes, options);\n return Hex.toBigInt(hex, options);\n}\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a boolean.\n *\n * @example\n * ```ts\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([1]))\n * // @log: true\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Decoding options.\n * @returns Decoded boolean.\n */\nexport function toBoolean(bytes, options = {}) {\n const { size } = options;\n let bytes_ = bytes;\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size);\n bytes_ = trimLeft(bytes_);\n }\n if (bytes_.length > 1 || bytes_[0] > 1)\n throw new InvalidBytesBooleanError(bytes_);\n return Boolean(bytes_[0]);\n}\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toHex(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded {@link ox#Hex.Hex} value.\n */\nexport function toHex(value, options = {}) {\n return Hex.fromBytes(value, options);\n}\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a number.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toNumber(Bytes.from([1, 164]))\n * // @log: 420\n * ```\n */\nexport function toNumber(bytes, options = {}) {\n const { size } = options;\n if (typeof size !== 'undefined')\n internal.assertSize(bytes, size);\n const hex = Hex.fromBytes(bytes, options);\n return Hex.toNumber(hex, options);\n}\n/**\n * Decodes a {@link ox#Bytes.Bytes} into a string.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * const data = Bytes.toString(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: 'Hello world'\n * ```\n *\n * @param bytes - The {@link ox#Bytes.Bytes} to decode.\n * @param options - Options.\n * @returns Decoded string.\n */\nexport function toString(bytes, options = {}) {\n const { size } = options;\n let bytes_ = bytes;\n if (typeof size !== 'undefined') {\n internal.assertSize(bytes_, size);\n bytes_ = trimRight(bytes_);\n }\n return decoder.decode(bytes_);\n}\n/**\n * Trims leading zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimLeft(Bytes.from([0, 0, 0, 0, 1, 2, 3]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimLeft(value) {\n return internal.trim(value, { dir: 'left' });\n}\n/**\n * Trims trailing zeros from a {@link ox#Bytes.Bytes} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.trimRight(Bytes.from([1, 2, 3, 0, 0, 0, 0]))\n * // @log: Uint8Array([1, 2, 3])\n * ```\n *\n * @param value - {@link ox#Bytes.Bytes} value.\n * @returns Trimmed {@link ox#Bytes.Bytes} value.\n */\nexport function trimRight(value) {\n return internal.trim(value, { dir: 'right' });\n}\n/**\n * Checks if the given value is {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.validate('0x')\n * // @log: false\n *\n * Bytes.validate(Bytes.from([1, 2, 3]))\n * // @log: true\n * ```\n *\n * @param value - Value to check.\n * @returns `true` if the value is {@link ox#Bytes.Bytes}, otherwise `false`.\n */\nexport function validate(value) {\n try {\n assert(value);\n return true;\n }\n catch {\n return false;\n }\n}\n/**\n * Thrown when the bytes value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.toBoolean(Bytes.from([5]))\n * // @error: Bytes.InvalidBytesBooleanError: Bytes value `[5]` is not a valid boolean.\n * // @error: The bytes array must contain a single byte of either a `0` or `1` value.\n * ```\n */\nexport class InvalidBytesBooleanError extends Errors.BaseError {\n constructor(bytes) {\n super(`Bytes value \\`${bytes}\\` is not a valid boolean.`, {\n metaMessages: [\n 'The bytes array must contain a single byte of either a `0` or `1` value.',\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.InvalidBytesBooleanError'\n });\n }\n}\n/**\n * Thrown when a value cannot be converted to bytes.\n *\n * @example\n * ```ts twoslash\n * // @noErrors\n * import { Bytes } from 'ox'\n *\n * Bytes.from('foo')\n * // @error: Bytes.InvalidBytesTypeError: Value `foo` of type `string` is an invalid Bytes value.\n * ```\n */\nexport class InvalidBytesTypeError extends Errors.BaseError {\n constructor(value) {\n super(`Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid Bytes value.`, {\n metaMessages: ['Bytes values must be of type `Bytes`.'],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.InvalidBytesTypeError'\n });\n }\n}\n/**\n * Thrown when a size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromString('Hello World!', { size: 8 })\n * // @error: Bytes.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n constructor({ givenSize, maxSize }) {\n super(`Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.SizeOverflowError'\n });\n }\n}\n/**\n * Thrown when a slice offset is out-of-bounds.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.slice(Bytes.from([1, 2, 3]), 4)\n * // @error: Bytes.SliceOffsetOutOfBoundsError: Slice starting at offset `4` is out-of-bounds (size: `3`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n constructor({ offset, position, size, }) {\n super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.SliceOffsetOutOfBoundsError'\n });\n }\n}\n/**\n * Thrown when a the padding size exceeds the maximum allowed size.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.padLeft(Bytes.fromString('Hello World!'), 8)\n * // @error: [Bytes.SizeExceedsPaddingSizeError: Bytes size (`12`) exceeds padding size (`8`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Bytes.SizeExceedsPaddingSizeError'\n });\n }\n}\n//# sourceMappingURL=Bytes.js.map","import { equalBytes } from '@noble/curves/abstract/utils';\nimport * as Bytes from './Bytes.js';\nimport * as Errors from './Errors.js';\nimport * as Json from './Json.js';\nimport * as internal_bytes from './internal/bytes.js';\nimport * as internal from './internal/hex.js';\nconst encoder = /*#__PURE__*/ new TextEncoder();\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));\n/**\n * Asserts if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('abc')\n * // @error: InvalidHexValueTypeError:\n * // @error: Value `\"abc\"` of type `string` is an invalid hex type.\n * // @error: Hex types must be represented as `\"0x\\${string}\"`.\n * ```\n *\n * @param value - The value to assert.\n * @param options - Options.\n */\nexport function assert(value, options = {}) {\n const { strict = false } = options;\n if (!value)\n throw new InvalidHexTypeError(value);\n if (typeof value !== 'string')\n throw new InvalidHexTypeError(value);\n if (strict) {\n if (!/^0x[0-9a-fA-F]*$/.test(value))\n throw new InvalidHexValueError(value);\n }\n if (!value.startsWith('0x'))\n throw new InvalidHexValueError(value);\n}\n/**\n * Concatenates two or more {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.concat('0x123', '0x456')\n * // @log: '0x123456'\n * ```\n *\n * @param values - The {@link ox#Hex.Hex} values to concatenate.\n * @returns The concatenated {@link ox#Hex.Hex} value.\n */\nexport function concat(...values) {\n return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;\n}\n/**\n * Instantiates a {@link ox#Hex.Hex} value from a hex string or {@link ox#Bytes.Bytes} value.\n *\n * :::tip\n *\n * To instantiate from a **Boolean**, **String**, or **Number**, use one of the following:\n *\n * - `Hex.fromBoolean`\n *\n * - `Hex.fromString`\n *\n * - `Hex.fromNumber`\n *\n * :::\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.from('0x48656c6c6f20576f726c6421')\n * // @log: '0x48656c6c6f20576f726c6421'\n *\n * Hex.from(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function from(value) {\n if (value instanceof Uint8Array)\n return fromBytes(value);\n if (Array.isArray(value))\n return fromBytes(new Uint8Array(value));\n return value;\n}\n/**\n * Encodes a boolean into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromBoolean(true)\n * // @log: '0x1'\n *\n * Hex.fromBoolean(false)\n * // @log: '0x0'\n *\n * Hex.fromBoolean(true, { size: 32 })\n * // @log: '0x0000000000000000000000000000000000000000000000000000000000000001'\n * ```\n *\n * @param value - The boolean value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBoolean(value, options = {}) {\n const hex = `0x${Number(value)}`;\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size);\n return padLeft(hex, options.size);\n }\n return hex;\n}\n/**\n * Encodes a {@link ox#Bytes.Bytes} value into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.fromBytes(Bytes.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // @log: '0x48656c6c6f20576f726c6421'\n * ```\n *\n * @param value - The {@link ox#Bytes.Bytes} value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromBytes(value, options = {}) {\n let string = '';\n for (let i = 0; i < value.length; i++)\n string += hexes[value[i]];\n const hex = `0x${string}`;\n if (typeof options.size === 'number') {\n internal.assertSize(hex, options.size);\n return padRight(hex, options.size);\n }\n return hex;\n}\n/**\n * Encodes a number or bigint into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420)\n * // @log: '0x1a4'\n *\n * Hex.fromNumber(420, { size: 32 })\n * // @log: '0x00000000000000000000000000000000000000000000000000000000000001a4'\n * ```\n *\n * @param value - The number or bigint value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromNumber(value, options = {}) {\n const { signed, size } = options;\n const value_ = BigInt(value);\n let maxValue;\n if (size) {\n if (signed)\n maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n else\n maxValue = 2n ** (BigInt(size) * 8n) - 1n;\n }\n else if (typeof value === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER);\n }\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;\n if ((maxValue && value_ > maxValue) || value_ < minValue) {\n const suffix = typeof value === 'bigint' ? 'n' : '';\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value}${suffix}`,\n });\n }\n const stringValue = (signed && value_ < 0 ? (1n << BigInt(size * 8)) + BigInt(value_) : value_).toString(16);\n const hex = `0x${stringValue}`;\n if (size)\n return padLeft(hex, size);\n return hex;\n}\n/**\n * Encodes a string into a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n * Hex.fromString('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * Hex.fromString('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n * ```\n *\n * @param value - The string value to encode.\n * @param options - Options.\n * @returns The encoded {@link ox#Hex.Hex} value.\n */\nexport function fromString(value, options = {}) {\n return fromBytes(encoder.encode(value), options);\n}\n/**\n * Checks if two {@link ox#Hex.Hex} values are equal.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.isEqual('0xdeadbeef', '0xdeadbeef')\n * // @log: true\n *\n * Hex.isEqual('0xda', '0xba')\n * // @log: false\n * ```\n *\n * @param hexA - The first {@link ox#Hex.Hex} value.\n * @param hexB - The second {@link ox#Hex.Hex} value.\n * @returns `true` if the two {@link ox#Hex.Hex} values are equal, `false` otherwise.\n */\nexport function isEqual(hexA, hexB) {\n return equalBytes(Bytes.fromHex(hexA), Bytes.fromHex(hexB));\n}\n/**\n * Pads a {@link ox#Hex.Hex} value to the left with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1234', 4)\n * // @log: '0x00001234'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padLeft(value, size) {\n return internal.pad(value, { dir: 'left', size });\n}\n/**\n * Pads a {@link ox#Hex.Hex} value to the right with zero bytes until it reaches the given `size` (default: 32 bytes).\n *\n * @example\n * ```ts\n * import { Hex } from 'ox'\n *\n * Hex.padRight('0x1234', 4)\n * // @log: '0x12340000'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to pad.\n * @param size - The size (in bytes) of the output hex value.\n * @returns The padded {@link ox#Hex.Hex} value.\n */\nexport function padRight(value, size) {\n return internal.pad(value, { dir: 'right', size });\n}\n/**\n * Generates a random {@link ox#Hex.Hex} value of the specified length.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const hex = Hex.random(32)\n * // @log: '0x...'\n * ```\n *\n * @returns Random {@link ox#Hex.Hex} value.\n */\nexport function random(length) {\n return fromBytes(Bytes.random(length));\n}\n/**\n * Returns a section of a {@link ox#Bytes.Bytes} value given a start/end bytes offset.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 1, 4)\n * // @log: '0x234567'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to slice.\n * @param start - The start offset (in bytes).\n * @param end - The end offset (in bytes).\n * @param options - Options.\n * @returns The sliced {@link ox#Hex.Hex} value.\n */\nexport function slice(value, start, end, options = {}) {\n const { strict } = options;\n internal.assertStartOffset(value, start);\n const value_ = `0x${value\n .replace('0x', '')\n .slice((start ?? 0) * 2, (end ?? value.length) * 2)}`;\n if (strict)\n internal.assertEndOffset(value_, start, end);\n return value_;\n}\n/**\n * Retrieves the size of a {@link ox#Hex.Hex} value (in bytes).\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.size('0xdeadbeef')\n * // @log: 4\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to get the size of.\n * @returns The size of the {@link ox#Hex.Hex} value (in bytes).\n */\nexport function size(value) {\n return Math.ceil((value.length - 2) / 2);\n}\n/**\n * Trims leading zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimLeft('0x00000000deadbeef')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimLeft(value) {\n return internal.trim(value, { dir: 'left' });\n}\n/**\n * Trims trailing zeros from a {@link ox#Hex.Hex} value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.trimRight('0xdeadbeef00000000')\n * // @log: '0xdeadbeef'\n * ```\n *\n * @param value - The {@link ox#Hex.Hex} value to trim.\n * @returns The trimmed {@link ox#Hex.Hex} value.\n */\nexport function trimRight(value) {\n return internal.trim(value, { dir: 'right' });\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a BigInt.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBigInt('0x1a4')\n * // @log: 420n\n *\n * Hex.toBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420n\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded BigInt.\n */\nexport function toBigInt(hex, options = {}) {\n const { signed } = options;\n if (options.size)\n internal.assertSize(hex, options.size);\n const value = BigInt(hex);\n if (!signed)\n return value;\n const size = (hex.length - 2) / 2;\n const max_unsigned = (1n << (BigInt(size) * 8n)) - 1n;\n const max_signed = max_unsigned >> 1n;\n if (value <= max_signed)\n return value;\n return value - max_unsigned - 1n;\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0x01')\n * // @log: true\n *\n * Hex.toBoolean('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // @log: true\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded boolean.\n */\nexport function toBoolean(hex, options = {}) {\n if (options.size)\n internal.assertSize(hex, options.size);\n const hex_ = trimLeft(hex);\n if (hex_ === '0x')\n return false;\n if (hex_ === '0x1')\n return true;\n throw new InvalidHexBooleanError(hex);\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a {@link ox#Bytes.Bytes}.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * const data = Hex.toBytes('0x48656c6c6f20776f726c6421')\n * // @log: Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded {@link ox#Bytes.Bytes}.\n */\nexport function toBytes(hex, options = {}) {\n return Bytes.fromHex(hex, options);\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a number.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toNumber('0x1a4')\n * // @log: 420\n *\n * Hex.toNumber('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // @log: 420\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded number.\n */\nexport function toNumber(hex, options = {}) {\n const { signed, size } = options;\n if (!signed && !size)\n return Number(hex);\n return Number(toBigInt(hex, options));\n}\n/**\n * Decodes a {@link ox#Hex.Hex} value into a string.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toString('0x48656c6c6f20576f726c6421')\n * // @log: 'Hello world!'\n *\n * Hex.toString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // @log: 'Hello world'\n * ```\n *\n * @param hex - The {@link ox#Hex.Hex} value to decode.\n * @param options - Options.\n * @returns The decoded string.\n */\nexport function toString(hex, options = {}) {\n const { size } = options;\n let bytes = Bytes.fromHex(hex);\n if (size) {\n internal_bytes.assertSize(bytes, size);\n bytes = Bytes.trimRight(bytes);\n }\n return new TextDecoder().decode(bytes);\n}\n/**\n * Checks if the given value is {@link ox#Hex.Hex}.\n *\n * @example\n * ```ts twoslash\n * import { Bytes, Hex } from 'ox'\n *\n * Hex.validate('0xdeadbeef')\n * // @log: true\n *\n * Hex.validate(Bytes.from([1, 2, 3]))\n * // @log: false\n * ```\n *\n * @param value - The value to check.\n * @param options - Options.\n * @returns `true` if the value is a {@link ox#Hex.Hex}, `false` otherwise.\n */\nexport function validate(value, options = {}) {\n const { strict = false } = options;\n try {\n assert(value, { strict });\n return true;\n }\n catch {\n return false;\n }\n}\n/**\n * Thrown when the provided integer is out of range, and cannot be represented as a hex value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromNumber(420182738912731283712937129)\n * // @error: Hex.IntegerOutOfRangeError: Number \\`4.2018273891273126e+26\\` is not in safe unsigned integer range (`0` to `9007199254740991`)\n * ```\n */\nexport class IntegerOutOfRangeError extends Errors.BaseError {\n constructor({ max, min, signed, size, value, }) {\n super(`Number \\`${value}\\` is not in safe${size ? ` ${size * 8}-bit` : ''}${signed ? ' signed' : ' unsigned'} integer range ${max ? `(\\`${min}\\` to \\`${max}\\`)` : `(above \\`${min}\\`)`}`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.IntegerOutOfRangeError'\n });\n }\n}\n/**\n * Thrown when the provided hex value cannot be represented as a boolean.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.toBoolean('0xa')\n * // @error: Hex.InvalidHexBooleanError: Hex value `\"0xa\"` is not a valid boolean.\n * // @error: The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).\n * ```\n */\nexport class InvalidHexBooleanError extends Errors.BaseError {\n constructor(hex) {\n super(`Hex value \\`\"${hex}\"\\` is not a valid boolean.`, {\n metaMessages: [\n 'The hex value must be `\"0x0\"` (false) or `\"0x1\"` (true).',\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.InvalidHexBooleanError'\n });\n }\n}\n/**\n * Thrown when the provided value is not a valid hex type.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert(1)\n * // @error: Hex.InvalidHexTypeError: Value `1` of type `number` is an invalid hex type.\n * ```\n */\nexport class InvalidHexTypeError extends Errors.BaseError {\n constructor(value) {\n super(`Value \\`${typeof value === 'object' ? Json.stringify(value) : value}\\` of type \\`${typeof value}\\` is an invalid hex type.`, {\n metaMessages: ['Hex types must be represented as `\"0x${string}\"`.'],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.InvalidHexTypeError'\n });\n }\n}\n/**\n * Thrown when the provided hex value is invalid.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.assert('0x0123456789abcdefg')\n * // @error: Hex.InvalidHexValueError: Value `0x0123456789abcdefg` is an invalid hex value.\n * // @error: Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).\n * ```\n */\nexport class InvalidHexValueError extends Errors.BaseError {\n constructor(value) {\n super(`Value \\`${value}\\` is an invalid hex value.`, {\n metaMessages: [\n 'Hex values must start with `\"0x\"` and contain only hexadecimal characters (0-9, a-f, A-F).',\n ],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.InvalidHexValueError'\n });\n }\n}\n/**\n * Thrown when the provided hex value is an odd length.\n *\n * @example\n * ```ts twoslash\n * import { Bytes } from 'ox'\n *\n * Bytes.fromHex('0xabcde')\n * // @error: Hex.InvalidLengthError: Hex value `\"0xabcde\"` is an odd length (5 nibbles).\n * ```\n */\nexport class InvalidLengthError extends Errors.BaseError {\n constructor(value) {\n super(`Hex value \\`\"${value}\"\\` is an odd length (${value.length - 2} nibbles).`, {\n metaMessages: ['It must be an even length.'],\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.InvalidLengthError'\n });\n }\n}\n/**\n * Thrown when the size of the value exceeds the expected max size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.fromString('Hello World!', { size: 8 })\n * // @error: Hex.SizeOverflowError: Size cannot exceed `8` bytes. Given size: `12` bytes.\n * ```\n */\nexport class SizeOverflowError extends Errors.BaseError {\n constructor({ givenSize, maxSize }) {\n super(`Size cannot exceed \\`${maxSize}\\` bytes. Given size: \\`${givenSize}\\` bytes.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.SizeOverflowError'\n });\n }\n}\n/**\n * Thrown when the slice offset exceeds the bounds of the value.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.slice('0x0123456789', 6)\n * // @error: Hex.SliceOffsetOutOfBoundsError: Slice starting at offset `6` is out-of-bounds (size: `5`).\n * ```\n */\nexport class SliceOffsetOutOfBoundsError extends Errors.BaseError {\n constructor({ offset, position, size, }) {\n super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset \\`${offset}\\` is out-of-bounds (size: \\`${size}\\`).`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.SliceOffsetOutOfBoundsError'\n });\n }\n}\n/**\n * Thrown when the size of the value exceeds the pad size.\n *\n * @example\n * ```ts twoslash\n * import { Hex } from 'ox'\n *\n * Hex.padLeft('0x1a4e12a45a21323123aaa87a897a897a898a6567a578a867a98778a667a85a875a87a6a787a65a675a6a9', 32)\n * // @error: Hex.SizeExceedsPaddingSizeError: Hex size (`43`) exceeds padding size (`32`).\n * ```\n */\nexport class SizeExceedsPaddingSizeError extends Errors.BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (\\`${size}\\`) exceeds padding size (\\`${targetSize}\\`).`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Hex.SizeExceedsPaddingSizeError'\n });\n }\n}\n//# sourceMappingURL=Hex.js.map","import * as ox__Hex from \"ox/Hex\";\n/**\n * Checks if a value is a valid hexadecimal string.\n * @param value - The value to be checked.\n * @param options - Optional configuration for the validation.\n * @returns True if the value is a valid hexadecimal string, false otherwise.\n * @example\n * ```ts\n * import { isHex } from \"thirdweb/utils\";\n * const result = isHex(\"0x1a4\");\n * console.log(result); // true\n * ```\n * @utils\n */\nexport function isHex(value, options = {}) {\n return ox__Hex.validate(value, options);\n}\n//# sourceMappingURL=is-hex.js.map","import * as ox__Hex from \"ox/Hex\";\nexport { isHex } from \"./helpers/is-hex.js\";\n/**\n * Pads a hexadecimal string with zeros to a specified size.\n * @param hex_ The hexadecimal string to pad.\n * @param options The padding options.\n * @returns The padded hexadecimal string.\n * @throws Error if the resulting padded string exceeds the specified size.\n * @example\n * ```ts\n * import { padHex } from \"thirdweb/utils\";\n * const paddedHex = padHex(\"0x1a4\", { size: 32 });\n * console.log(paddedHex); // \"0x000000000000000000000000000001a4\"\n * ```\n * @utils\n */\nexport function padHex(hex_, options = {}) {\n const { dir, size = 32 } = options;\n if (size === null) {\n return hex_;\n }\n if (dir === \"right\") {\n return ox__Hex.padRight(hex_, size);\n }\n return ox__Hex.padLeft(hex_, size);\n}\n/**\n * Converts a hexadecimal string to a UTF-8 string.\n * @param hex The hexadecimal string to convert.\n * @param opts The options for the conversion.\n * @returns The UTF-8 string representation of the hexadecimal string.\n * @example\n * ```ts\n * import { hexToString } from \"thirdweb/utils\";\n * const string = hexToString(\"0x48656c6c6f2c20776f726c6421\");\n * console.log(string); // \"Hello, world!\"\n * ```\n * @utils\n */\nexport function hexToString(hex, opts = {}) {\n return ox__Hex.toString(hex, opts);\n}\n/**\n * Converts a hexadecimal string to a BigInt.\n * @param hex - The hexadecimal string to convert.\n * @param opts - Optional parameters for the conversion.\n * @returns The BigInt representation of the hexadecimal string.\n * @example\n * ```ts\n * import { hexToBigInt } from \"thirdweb/utils\";\n * const bigInt = hexToBigInt(\"0x1a4\");\n * console.log(bigInt); // 420n\n * ```\n * @utils\n */\nexport function hexToBigInt(hex, opts = {}) {\n return ox__Hex.toBigInt(hex, opts);\n}\n/**\n * Converts a hexadecimal string to a number.\n * @param hex The hexadecimal string to convert.\n * @param opts Optional options for the conversion.\n * @returns The converted number.\n * @example\n * ```ts\n * import { hexToNumber } from \"thirdweb/utils\";\n * const number = hexToNumber(\"0x1a4\");\n * console.log(number); // 420\n * ```\n * @utils\n */\nexport function hexToNumber(hex, opts = {}) {\n return ox__Hex.toNumber(hex, opts);\n}\n/**\n * Converts a hexadecimal string to a boolean value.\n * @param hex The hexadecimal string to convert.\n * @param opts Optional options for the conversion.\n * @returns The boolean value corresponding to the hexadecimal string.\n * @throws Error if the hexadecimal string is invalid.\n * @example\n * ```ts\n * import { hexToBool } from \"thirdweb/utils\";\n * const bool = hexToBool(\"0x01\");\n * console.log(bool); // true\n * ```\n * @utils\n */\nexport function hexToBool(hex, opts = {}) {\n return ox__Hex.toBoolean(hex, opts);\n}\n/**\n * Converts a hexadecimal string to a Uint8Array.\n * @param hex The hexadecimal string to convert.\n * @param opts Options for the conversion.\n * @returns The Uint8Array representation of the hexadecimal string.\n * @example\n * ```ts\n * import { hexToUint8Array } from \"thirdweb/utils\";\n * const bytes = hexToUint8Array(\"0x48656c6c6f2c20776f726c6421\");\n * console.log(bytes); // Uint8Array([72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33])\n * ```\n * @utils\n */\nexport function hexToUint8Array(hex, opts = {}) {\n return ox__Hex.toBytes(hex, opts);\n}\n/**\n * Converts a hexadecimal string to the specified type.\n * @param hex - The hexadecimal string to convert.\n * @param toOrOpts - The target type or conversion options.\n * @returns The converted value of the specified type.\n * @example\n * ```ts\n * import { fromHex } from \"thirdweb/utils\";\n * const string = fromHex(\"0x48656c6c6f2c20776f726c6421\", \"string\");\n * console.log(string); // \"Hello, world!\"\n * ```\n * @utils\n */\nexport function fromHex(hex, toOrOpts) {\n const opts = typeof toOrOpts === \"string\" ? { to: toOrOpts } : toOrOpts;\n switch (opts.to) {\n case \"number\":\n return hexToNumber(hex, opts);\n case \"bigint\":\n return hexToBigInt(hex, opts);\n case \"string\":\n return hexToString(hex, opts);\n case \"boolean\":\n return hexToBool(hex, opts);\n default:\n return hexToUint8Array(hex, opts);\n }\n}\n/**\n * Converts a boolean value to a hexadecimal string representation.\n * @param value - The boolean value to convert.\n * @param opts - Optional options for the conversion.\n * @returns The hexadecimal string representation of the boolean value.\n * @example\n * ```ts\n * import { boolToHex } from \"thirdweb/utils\";\n * const hex = boolToHex(true);\n * console.log(hex); // \"0x01\"\n * ```\n * @utils\n */\nexport function boolToHex(value, opts = {}) {\n return ox__Hex.fromBoolean(value, opts);\n}\n/**\n * Converts an array of bytes to a hexadecimal string.\n * @param value - The array of bytes to convert.\n * @param opts - Optional parameters for the conversion.\n * @returns The hexadecimal string representation of the bytes.\n * @example\n * ```ts\n * import { uint8arrayToHex } from \"thirdweb/utils\";\n * const hex = uint8arrayToHex(new Uint8Array([72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]));\n * console.log(hex); // \"0x48656c6c6f2c20776f726c64\"\n * ```\n * @utils\n */\nexport function uint8ArrayToHex(value, opts = {}) {\n return ox__Hex.fromBytes(value, opts);\n}\n/**\n * Converts a number or bigint to a hexadecimal string.\n * @param value_ - The number or bigint value to convert.\n * @param opts - Optional configuration options.\n * @returns The hexadecimal representation of the input value.\n * @throws An error if the input value is not within the safe integer range.\n * @example\n * ```ts\n * import { numberToHex } from \"thirdweb/utils\";\n * const hex = numberToHex(420);\n * console.log(hex); // \"0x1a4\"\n * ```\n * @utils\n */\nexport function numberToHex(value_, opts = {}) {\n return ox__Hex.fromNumber(value_, opts);\n}\n/**\n * Converts a string to its hexadecimal representation.\n * @param value_ The string to convert to hexadecimal.\n * @param opts Options for the conversion.\n * @returns The hexadecimal representation of the input string.\n * @example\n * ```ts\n * import { stringToHex } from \"thirdweb/utils\";\n * const hex = stringToHex(\"Hello, world!\");\n * console.log(hex); // \"0x48656c6c6f2c20776f726c6421\"\n * ```\n * @utils\n */\nexport function stringToHex(value_, opts = {}) {\n return ox__Hex.fromString(value_, opts);\n}\n/**\n * Converts a value to its hexadecimal representation.\n * @param value - The value to convert to hexadecimal.\n * @param opts - Optional parameters for the conversion.\n * @returns The hexadecimal representation of the value.\n * @example\n * ```ts\n * import { toHex } from \"thirdweb/utils\";\n * const hex = toHex(420);\n * console.log(hex); // \"0x1a4\"\n * ```\n * @utils\n */\nexport function toHex(value, opts = {}) {\n switch (typeof value) {\n case \"number\":\n case \"bigint\":\n return numberToHex(value, opts);\n case \"string\":\n return stringToHex(value, opts);\n case \"boolean\":\n return boolToHex(value, opts);\n default:\n return uint8ArrayToHex(value, opts);\n }\n}\n//# sourceMappingURL=hex.js.map","import { numberToHex } from \"../../utils/encoding/hex.js\";\nfunction encodeStateOverrides(overrides) {\n return Object.fromEntries(Object.entries(overrides).map(([address, override]) => {\n return [\n address,\n {\n balance: override.balance ? numberToHex(override.balance) : undefined,\n code: override.code,\n nonce: override.nonce ? numberToHex(override.nonce) : undefined,\n state: override.state,\n stateDiff: override.stateDiff,\n },\n ];\n }));\n}\n/**\n * Executes a call or a transaction on the Ethereum network.\n * @param request - The EIP1193 request function.\n * @param params - The parameters for the call or transaction.\n * @returns A promise that resolves to the result of the call or transaction.\n * @rpc\n * @example\n * ```ts\n * import { getRpcClient, eth_call } from \"thirdweb/rpc\";\n * const rpcRequest = getRpcClient({ client, chain });\n * const result = await eth_call(rpcRequest, {\n * to: \"0x...\",\n * ...\n * });\n * ```\n */\nexport async function eth_call(request, params) {\n const { blockNumber, blockTag, ...txRequest } = params;\n const blockNumberHex = blockNumber ? numberToHex(blockNumber) : undefined;\n // default to \"latest\" if no block is provided\n const block = blockNumberHex || blockTag || \"latest\";\n return await request({\n method: \"eth_call\",\n params: params.stateOverrides\n ? [\n txRequest,\n block,\n encodeStateOverrides(params.stateOverrides),\n ]\n : [txRequest, block],\n });\n}\n//# sourceMappingURL=eth_call.js.map","export const DEFAULT_RPC_URL = \"rpc.thirdweb.com\";\nconst DEFAULT_SOCIAL_URL = \"social.thirdweb.com\";\nconst DEFAULT_IN_APP_WALLET_URL = \"embedded-wallet.thirdweb.com\";\nconst DEFAULT_PAY_URL = \"pay.thirdweb.com\";\nconst DEFAULT_STORAGE_URL = \"storage.thirdweb.com\";\nconst DEFAULT_BUNDLER_URL = \"bundler.thirdweb.com\";\nconst DEFAULT_ANALYTICS_URL = \"c.thirdweb.com\";\nconst DEFAULT_INSIGHT_URL = \"insight.thirdweb.com\";\nconst DEFAULT_ENGINE_CLOUD_URL = \"engine.thirdweb.com\";\nconst DEFAULT_BRIDGE_URL = \"bridge.thirdweb.com\";\nlet domains = {\n analytics: DEFAULT_ANALYTICS_URL,\n bridge: DEFAULT_BRIDGE_URL,\n bundler: DEFAULT_BUNDLER_URL,\n engineCloud: DEFAULT_ENGINE_CLOUD_URL,\n inAppWallet: DEFAULT_IN_APP_WALLET_URL,\n insight: DEFAULT_INSIGHT_URL,\n pay: DEFAULT_PAY_URL,\n rpc: DEFAULT_RPC_URL,\n social: DEFAULT_SOCIAL_URL,\n storage: DEFAULT_STORAGE_URL,\n};\nexport const setThirdwebDomains = (DomainOverrides) => {\n domains = {\n analytics: DomainOverrides.analytics ?? DEFAULT_ANALYTICS_URL,\n bridge: DomainOverrides.bridge ?? DEFAULT_BRIDGE_URL,\n bundler: DomainOverrides.bundler ?? DEFAULT_BUNDLER_URL,\n engineCloud: DomainOverrides.engineCloud ?? DEFAULT_ENGINE_CLOUD_URL,\n inAppWallet: DomainOverrides.inAppWallet ?? DEFAULT_IN_APP_WALLET_URL,\n insight: DomainOverrides.insight ?? DEFAULT_INSIGHT_URL,\n pay: DomainOverrides.pay ?? DEFAULT_PAY_URL,\n rpc: DomainOverrides.rpc ?? DEFAULT_RPC_URL,\n social: DomainOverrides.social ?? DEFAULT_SOCIAL_URL,\n storage: DomainOverrides.storage ?? DEFAULT_STORAGE_URL,\n };\n};\n/**\n * @internal\n */\nexport const getThirdwebDomains = () => {\n return domains;\n};\n/**\n * @internal\n */\nexport const getThirdwebBaseUrl = (service) => {\n const origin = domains[service];\n if (origin.startsWith(\"localhost\")) {\n return `http://${origin}`;\n }\n return `https://${origin}`;\n};\nlet serviceKey = null;\nexport const setServiceKey = (key) => {\n serviceKey = key;\n};\nexport const getServiceKey = () => {\n return serviceKey;\n};\n//# sourceMappingURL=domains.js.map","export const version = \"5.118.1\";\n//# sourceMappingURL=version.js.map","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n constructor(size) {\n super();\n Object.defineProperty(this, \"maxSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxSize = size;\n }\n get(key) {\n const value = super.get(key);\n if (super.has(key) && value !== undefined) {\n this.delete(key);\n super.set(key, value);\n }\n return value;\n }\n set(key, value) {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value;\n if (firstKey) {\n this.delete(firstKey);\n }\n }\n return this;\n }\n}\n//# sourceMappingURL=lru.js.map","const operatingSystemRules = [\n [\"iOS\", /iP(hone|od|ad)/],\n [\"Android OS\", /Android/],\n [\"BlackBerry OS\", /BlackBerry|BB10/],\n [\"Windows Mobile\", /IEMobile/],\n [\"Amazon OS\", /Kindle/],\n [\"Windows 3.11\", /Win16/],\n [\"Windows 95\", /(Windows 95)|(Win95)|(Windows_95)/],\n [\"Windows 98\", /(Windows 98)|(Win98)/],\n [\"Windows 2000\", /(Windows NT 5.0)|(Windows 2000)/],\n [\"Windows XP\", /(Windows NT 5.1)|(Windows XP)/],\n [\"Windows Server 2003\", /(Windows NT 5.2)/],\n [\"Windows Vista\", /(Windows NT 6.0)/],\n [\"Windows 7\", /(Windows NT 6.1)/],\n [\"Windows 8\", /(Windows NT 6.2)/],\n [\"Windows 8.1\", /(Windows NT 6.3)/],\n [\"Windows 10\", /(Windows NT 10.0)/],\n [\"Windows ME\", /Windows ME/],\n [\"Windows CE\", /Windows CE|WinCE|Microsoft Pocket Internet Explorer/],\n [\"Open BSD\", /OpenBSD/],\n [\"Sun OS\", /SunOS/],\n [\"Chrome OS\", /CrOS/],\n [\"Linux\", /(Linux)|(X11)/],\n [\"Mac OS\", /(Mac_PowerPC)|(Macintosh)/],\n [\"QNX\", /QNX/],\n [\"BeOS\", /BeOS/],\n [\"OS/2\", /OS\\/2/],\n];\nexport function detectPlatform() {\n if (typeof document === \"undefined\" &&\n typeof navigator !== \"undefined\" &&\n navigator.product === \"ReactNative\") {\n // react-native\n return \"mobile\";\n }\n if (typeof navigator !== \"undefined\") {\n return \"browser\";\n }\n return \"node\";\n}\nexport function detectOS(ua) {\n for (let ii = 0, count = operatingSystemRules.length; ii < count; ii++) {\n const [os, regex] = operatingSystemRules[ii];\n const match = regex.exec(ua);\n if (match) {\n return os;\n }\n }\n return null;\n}\n//# sourceMappingURL=detect-platform.js.map","export function isJWT(str) {\n return str.split(\".\").length === 3;\n}\n//# sourceMappingURL=is-jwt.js.map","// You must use typeof process !== \"undefined\" instead of just \"process\"\nexport const IS_DEV = typeof process !== \"undefined\" &&\n process.env &&\n (process.env.NODE_ENV === \"development\" || process.env.NODE_ENV === \"test\");\nexport const IS_TEST = typeof process !== \"undefined\" &&\n process.env &&\n process.env.NODE_ENV === \"test\";\n//# sourceMappingURL=process.js.map","import { version } from \"../version.js\";\nimport { LruMap } from \"./caching/lru.js\";\nimport { detectOS, detectPlatform, } from \"./detect-platform.js\";\nimport { getServiceKey } from \"./domains.js\";\nimport { isJWT } from \"./jwt/is-jwt.js\";\nimport { IS_DEV } from \"./process.js\";\nconst DEFAULT_REQUEST_TIMEOUT = 60000;\n/**\n * @internal\n */\nexport function getClientFetch(client, ecosystem) {\n /**\n * @internal\n */\n async function fetchWithHeaders(url, init) {\n const { requestTimeoutMs = DEFAULT_REQUEST_TIMEOUT, useAuthToken, ...restInit } = init || {};\n let headers = restInit.headers\n ? new Headers(restInit.headers)\n : typeof url === \"object\"\n ? url.headers\n : undefined;\n const urlString = typeof url === \"string\" ? url : url.url;\n // check if we are making a request to a thirdweb service (we don't want to send any headers to non-thirdweb services)\n if (isThirdwebUrl(urlString)) {\n if (!headers) {\n headers = new Headers();\n }\n // auth token if secret key === jwt\n const authToken = useAuthToken && client.secretKey && isJWT(client.secretKey)\n ? client.secretKey\n : undefined;\n // secret key if secret key !== jwt\n const secretKey = client.secretKey && !isJWT(client.secretKey)\n ? client.secretKey\n : undefined;\n const clientId = client.clientId;\n if (authToken && isBundlerUrl(urlString)) {\n headers.set(\"authorization\", `Bearer ${authToken}`);\n if (client.teamId) {\n headers.set(\"x-team-id\", client.teamId);\n }\n if (clientId) {\n headers.set(\"x-client-id\", clientId);\n }\n }\n // if we have an auth token set, use that (thirdweb dashboard sets this for the user)\n // pay urls should never send the auth token, because we always want the \"developer\" to be the one making the request, not the \"end user\"\n else if (authToken &&\n !isPayUrl(urlString) &&\n !isInAppWalletUrl(urlString)) {\n headers.set(\"authorization\", `Bearer ${authToken}`);\n // if we have a specific teamId set, add it to the request headers\n if (client.teamId) {\n headers.set(\"x-team-id\", client.teamId);\n }\n }\n else {\n // only set secret key or client id if we are NOT using the auth token!\n if (secretKey) {\n headers.set(\"x-secret-key\", secretKey);\n }\n if (clientId) {\n headers.set(\"x-client-id\", clientId);\n }\n }\n if (ecosystem) {\n headers.set(\"x-ecosystem-id\", ecosystem.id);\n if (ecosystem.partnerId) {\n headers.set(\"x-ecosystem-partner-id\", ecosystem.partnerId);\n }\n }\n // this already internally caches\n for (const [key, value] of getPlatformHeaders()) {\n headers.set(key, value);\n }\n const serviceKey = getServiceKey();\n if (serviceKey) {\n headers.set(\"x-service-api-key\", serviceKey);\n }\n }\n let controller;\n let abortTimeout;\n if (requestTimeoutMs) {\n controller = new AbortController();\n abortTimeout = setTimeout(() => {\n controller?.abort(\"timeout\");\n }, requestTimeoutMs);\n }\n return fetch(url, {\n ...restInit,\n headers,\n signal: controller?.signal,\n }).finally(() => {\n if (abortTimeout) {\n clearTimeout(abortTimeout);\n }\n });\n }\n return fetchWithHeaders;\n}\n// NOTE: these all start with \".\" because we want to make sure we don't match (for example) \"otherthirdweb.com\"\nconst THIRDWEB_DOMAINS = [\n \".thirdweb.com\",\n \".ipfscdn.io\",\n // dev domains\n \".thirdweb.dev\",\n \".thirdweb-dev.com\",\n \".thirdwebstorage-dev.com\",\n];\nexport const IS_THIRDWEB_URL_CACHE = new LruMap(4096);\n/**\n * @internal\n */\nexport function isThirdwebUrl(url) {\n if (IS_THIRDWEB_URL_CACHE.has(url)) {\n // biome-ignore lint/style/noNonNullAssertion: the `has` above ensures that this will always be set\n return IS_THIRDWEB_URL_CACHE.get(url);\n }\n try {\n const { hostname } = new URL(url);\n try {\n // special case for localhost in development only\n if (IS_DEV) {\n if (hostname === \"localhost\") {\n IS_THIRDWEB_URL_CACHE.set(url, true);\n return true;\n }\n }\n }\n catch { }\n const is = THIRDWEB_DOMAINS.some((domain) => hostname.endsWith(domain));\n IS_THIRDWEB_URL_CACHE.set(url, is);\n return is;\n }\n catch {\n IS_THIRDWEB_URL_CACHE.set(url, false);\n return false;\n }\n}\nfunction isPayUrl(url) {\n try {\n const { hostname } = new URL(url);\n // pay service hostname always starts with \"pay.\"\n return hostname.startsWith(\"pay.\");\n }\n catch {\n return false;\n }\n}\nfunction isInAppWalletUrl(url) {\n try {\n const { hostname } = new URL(url);\n // in app wallet service hostname always starts with \"in-app-wallet.\" or \"embedded-wallet.\"\n return (hostname.startsWith(\"in-app-wallet.\") ||\n hostname.startsWith(\"embedded-wallet.\"));\n }\n catch {\n return false;\n }\n}\nfunction isBundlerUrl(url) {\n try {\n const { hostname } = new URL(url);\n return (hostname.endsWith(\".bundler.thirdweb.com\") ||\n hostname.endsWith(\".bundler.thirdweb-dev.com\"));\n }\n catch {\n return false;\n }\n}\nconst SDK_NAME = \"unified-sdk\";\nlet previousPlatform;\n/**\n * @internal\n */\nexport function getPlatformHeaders() {\n if (previousPlatform) {\n return previousPlatform;\n }\n let os = null;\n if (typeof navigator !== \"undefined\") {\n os = detectOS(navigator.userAgent);\n }\n let bundleId;\n if (typeof globalThis !== \"undefined\" && \"Application\" in globalThis) {\n // shims use wallet connect RN module which injects Application info in globalThis\n // biome-ignore lint/suspicious/noExplicitAny: get around globalThis typing\n bundleId = globalThis.Application.applicationId;\n }\n previousPlatform = Object.entries({\n \"x-sdk-name\": SDK_NAME,\n \"x-sdk-os\": os ? parseOs(os) : \"unknown\",\n \"x-sdk-platform\": detectPlatform(),\n \"x-sdk-version\": version,\n ...(bundleId ? { \"x-bundle-id\": bundleId } : {}),\n });\n return previousPlatform;\n}\n/**\n * @internal\n */\nfunction parseOs(os) {\n const osLowerCased = os.toLowerCase();\n if (osLowerCased.startsWith(\"win\")) {\n return \"win\";\n }\n // we do NOT use the lowercase here\n switch (os) {\n case \"Mac OS\":\n return \"mac\";\n case \"iOS\":\n return \"ios\";\n case \"Android OS\":\n return \"android\";\n default:\n // if we somehow fall through here, just replace all spaces with underscores and send it\n return osLowerCased.replace(/\\s/gi, \"_\");\n }\n}\n//# sourceMappingURL=fetch.js.map","import { DEFAULT_RPC_URL, getThirdwebDomains } from \"../utils/domains.js\";\nimport { isThirdwebUrl } from \"../utils/fetch.js\";\nimport { withCache } from \"../utils/promise/withCache.js\";\n/**\n * @internal Exported for tests\n */\nexport const CUSTOM_CHAIN_MAP = new Map();\n/**\n * Defines a chain with the given options.\n * @param options The options for the chain.\n * @returns The defined chain.\n * @example\n * Just pass the chain ID to connect to:\n * ```ts\n * const chain = defineChain(1);\n * ```\n * Or pass your own RPC or custom values:\n * ```ts\n * const chain = defineChain({\n * id: 1,\n * rpc: \"https://my-rpc.com\",\n * nativeCurrency: {\n * name: \"Ether\",\n * symbol: \"ETH\",\n * decimals: 18,\n * },\n * });\n * ```\n * @chain\n */\nexport function defineChain(options) {\n const RPC_URL = getThirdwebDomains().rpc;\n if (typeof options === \"number\") {\n return {\n id: options,\n rpc: `https://${options}.${RPC_URL}`,\n };\n }\n if (isViemChain(options)) {\n return convertViemChain(options);\n }\n if (isLegacyChain(options)) {\n return convertLegacyChain(options);\n }\n // otherwise if it's not a viem chain, continue\n let rpc = options.rpc;\n if (!rpc) {\n rpc = `https://${options.id}.${RPC_URL}`;\n }\n const chain = { ...options, rpc };\n CUSTOM_CHAIN_MAP.set(options.id, chain);\n return chain;\n}\n/**\n * @internal\n */\nexport function cacheChains(chains) {\n for (const chain of chains) {\n CUSTOM_CHAIN_MAP.set(chain.id, chain);\n }\n}\n/**\n * @internal\n */\nexport function getCachedChain(id) {\n if (CUSTOM_CHAIN_MAP.has(id)) {\n return CUSTOM_CHAIN_MAP.get(id);\n }\n const RPC_URL = getThirdwebDomains().rpc;\n const chain = {\n id: id,\n rpc: `https://${id}.${RPC_URL}`,\n };\n return chain;\n}\n/**\n * @internal\n */\nexport function getCachedChainIfExists(id) {\n return CUSTOM_CHAIN_MAP.get(id);\n}\nfunction isLegacyChain(chain) {\n return \"rpc\" in chain && Array.isArray(chain.rpc) && \"slug\" in chain;\n}\n/**\n * @internal\n */\nexport function convertLegacyChain(legacyChain) {\n const RPC_URL = getThirdwebDomains().rpc;\n return {\n blockExplorers: legacyChain?.explorers?.map((explorer) => ({\n apiUrl: explorer.url,\n name: explorer.name,\n url: explorer.url,\n })),\n faucets: legacyChain.faucets ? [...legacyChain.faucets] : undefined,\n icon: legacyChain.icon,\n id: legacyChain.chainId,\n name: legacyChain.name,\n nativeCurrency: {\n decimals: legacyChain.nativeCurrency.decimals,\n name: legacyChain.nativeCurrency.name,\n symbol: legacyChain.nativeCurrency.symbol,\n },\n rpc: legacyChain.rpc[0] ?? `https://${legacyChain.chainId}.${RPC_URL}`,\n testnet: legacyChain.testnet ? true : undefined,\n };\n}\nfunction isViemChain(chain) {\n return \"rpcUrls\" in chain && !(\"rpc\" in chain);\n}\n/**\n * @internal\n */\nexport function convertViemChain(viemChain) {\n const RPC_URL = getThirdwebDomains().rpc;\n return {\n blockExplorers: viemChain?.blockExplorers\n ? Object.values(viemChain?.blockExplorers).map((explorer) => {\n return {\n apiUrl: explorer.apiUrl,\n name: explorer.name,\n url: explorer.url,\n };\n })\n : [],\n id: viemChain.id,\n name: viemChain.name,\n nativeCurrency: {\n decimals: viemChain.nativeCurrency.decimals,\n name: viemChain.nativeCurrency.name,\n symbol: viemChain.nativeCurrency.symbol,\n },\n rpc: viemChain.rpcUrls.default.http[0] ?? `https://${viemChain.id}.${RPC_URL}`,\n testnet: viemChain.testnet ? true : undefined,\n };\n}\n/**\n * Retrieves the RPC URL for the specified chain.\n * If a custom RPC URL is defined in the options, it will be used.\n * Otherwise, a thirdweb RPC URL will be constructed using the chain ID and client ID.\n * @param options - The options object containing the chain and client information.\n * @returns The RPC URL for the specified chain.\n * @example\n * ```ts\n * import { getRpcUrlForChain } from \"thirdweb/chains\";\n * const rpcUrl = getRpcUrlForChain({ chain: 1, client });\n * console.log(rpcUrl); // \"https://1.rpc.thirdweb.com/...\n * ```\n * @chain\n */\nexport function getRpcUrlForChain(options) {\n const baseRpcUrl = getThirdwebDomains().rpc;\n // if the chain is just a number, construct the RPC URL using the chain ID and client ID\n if (typeof options.chain === \"number\") {\n return `https://${options.chain}.${baseRpcUrl}/${options.client.clientId}`;\n }\n const { rpc } = options.chain;\n // add on the client ID to the RPC URL if it's a thirdweb URL\n if (isThirdwebUrl(rpc)) {\n const rpcUrl = new URL(options.chain.rpc.replace(DEFAULT_RPC_URL, baseRpcUrl));\n if (rpcUrl.pathname === \"/\" || rpcUrl.pathname.startsWith(\"/$\")) {\n rpcUrl.pathname = `/${options.client.clientId}`;\n }\n return rpcUrl.toString();\n }\n return rpc;\n}\n/**\n * Retrieves the chain symbol from the provided chain.\n * @param chain - The chain.\n * @returns The chain symbol.\n * @internal\n */\nexport async function getChainSymbol(chain) {\n if (!chain.nativeCurrency?.symbol) {\n return getChainMetadata(chain)\n .then((data) => data.nativeCurrency.symbol)\n .catch(() => {\n // if we fail to fetch the chain data, return \"ETH\" as a fallback\n return \"ETH\";\n });\n }\n // if we have a symbol, return it\n return chain.nativeCurrency.symbol;\n}\n/**\n * Retrieves the number of decimals for the native currency of a given chain.\n * If the chain is not recognized or the data cannot be fetched, it returns a fallback value of 18.\n * @param chain - The chain for which to retrieve the decimals.\n * @returns A promise that resolves to the number of decimals for the native currency of the chain.\n * @internal\n */\nexport async function getChainDecimals(chain) {\n if (!chain.nativeCurrency?.decimals) {\n return getChainMetadata(chain)\n .then((data) => data.nativeCurrency.decimals)\n .catch(() => {\n // if we fail to fetch the chain data, return 18 as a fallback (most likely it's 18)\n return 18;\n });\n }\n // if we have decimals, return it\n return chain.nativeCurrency.decimals;\n}\n/**\n * Retrieves the name of the native currency for a given chain.\n * If the chain object does not have a native currency name, it attempts to fetch the chain data and retrieve the native currency name from there.\n * If fetching the chain data fails, it falls back to returning \"ETH\".\n * @param chain The chain object for which to retrieve the native currency name.\n * @returns A promise that resolves to the native currency name.\n * @internal\n */\nexport async function getChainNativeCurrencyName(chain) {\n if (!chain.nativeCurrency?.name) {\n return getChainMetadata(chain)\n .then((data) => data.nativeCurrency.name)\n .catch(() => {\n // if we fail to fetch the chain data, return 18 as a fallback (most likely it's 18)\n return \"ETH\";\n });\n }\n // if we have a name, return it\n return chain.nativeCurrency.name;\n}\n/**\n * Retrieves chain data for a given chain.\n * @param chain - The chain object containing the chain ID.\n * @returns A Promise that resolves to the chain data.\n * @throws If there is an error fetching the chain data.\n * @example\n * ```ts\n * const chain = defineChain({ id: 1 });\n * const chainData = await getChainMetadata(chain);\n * console.log(chainData);\n * ```\n * @chain\n */\nexport function getChainMetadata(chain) {\n const chainId = chain.id;\n return withCache(async () => {\n try {\n const res = await fetch(`https://api.thirdweb.com/v1/chains/${chainId}`);\n if (!res.ok) {\n throw new Error(`Failed to fetch chain data for chainId ${chainId}. ${res.status} ${res.statusText}`);\n }\n const response = (await res.json());\n if (response.error) {\n throw new Error(`Failed to fetch chain data for chainId ${chainId}`);\n }\n if (!response.data) {\n throw new Error(`Failed to fetch chain data for chainId ${chainId}`);\n }\n const data = response.data;\n return createChainMetadata(chain, data);\n }\n catch {\n return createChainMetadata(chain);\n }\n }, {\n cacheKey: `chain:${chainId}`,\n cacheTime: 5 * 60 * 1000, // 5 minutes\n });\n}\nexport async function getInsightEnabledChainIds() {\n return withCache(async () => {\n const res = await fetch(`https://api.thirdweb.com/v1/chains/services?service=insight`);\n if (!res.ok) {\n throw new Error(`Failed to fetch services. ${res.status} ${res.statusText}`);\n }\n const response = (await res.json());\n return Object.keys(response.data).map((chainId) => Number(chainId));\n }, {\n cacheKey: `chain:insight-enabled`,\n cacheTime: 24 * 60 * 60 * 1000, // 1 day\n });\n}\n/**\n * Convert `ApiChain` to `Chain` object\n * @internal\n */\nexport function convertApiChainToChain(apiChain) {\n return {\n blockExplorers: apiChain.explorers?.map((explorer) => {\n return {\n apiUrl: explorer.url,\n name: explorer.name,\n url: explorer.url,\n };\n }),\n faucets: apiChain.faucets ? [...apiChain.faucets] : undefined,\n icon: apiChain.icon,\n id: apiChain.chainId,\n name: apiChain.name,\n nativeCurrency: apiChain.nativeCurrency,\n rpc: apiChain.rpc[0] || \"\",\n testnet: apiChain.testnet === true ? true : undefined,\n };\n}\nfunction createChainMetadata(chain, data) {\n const nativeCurrency = chain.nativeCurrency\n ? {\n ...data?.nativeCurrency,\n ...chain.nativeCurrency,\n }\n : data?.nativeCurrency;\n return {\n ...data,\n chain: data?.chain || chain.name || \"\",\n chainId: chain.id || data?.chainId || -1,\n explorers: chain.blockExplorers?.map((e) => ({\n name: e.name,\n standard: \"EIP3091\",\n url: e.url,\n })) || data?.explorers,\n icon: chain.icon || data?.icon,\n name: chain.name || data?.name || \"\",\n nativeCurrency: {\n decimals: nativeCurrency?.decimals || 18,\n name: nativeCurrency?.name || \"\",\n symbol: nativeCurrency?.symbol || \"\",\n },\n rpc: chain.rpc ? [chain.rpc] : data?.rpc || [\"\"],\n shortName: data?.shortName || chain.name || \"\",\n slug: data?.slug || chain.name || \"\",\n stackType: data?.stackType || \"\",\n testnet: chain.testnet || data?.testnet || false,\n };\n}\n//# sourceMappingURL=utils.js.map","/**\n * Stringify a JSON object and convert all bigint values to string\n *\n * If you are getting this error: \"Exception: Do not know how to serialize a BigInt\",\n * you probably can use this function to parse the data.\n * Because bigint is not an accepted value of the JSON format.\n *\n * @returns An object with all bigint values converted to string\n * @example\n * ```ts\n * import { stringify } from \"thirdweb/utils\";\n * const obj = { tokenId: 0n };\n * const str = stringify(obj); // \"{\"tokenId\":\"0\"}\"\n * ```\n * @utils\n */\nexport function stringify(\n// biome-ignore lint/suspicious/noExplicitAny: JSON.stringify signature\nvalue, \n// biome-ignore lint/suspicious/noExplicitAny: JSON.stringify signature\nreplacer, space) {\n const res = JSON.stringify(value, (key, value_) => {\n const value__ = typeof value_ === \"bigint\" ? value_.toString() : value_;\n return typeof replacer === \"function\" ? replacer(key, value__) : value__;\n }, space);\n return res;\n}\n//# sourceMappingURL=json.js.map","import { getClientFetch } from \"../utils/fetch.js\";\nimport { stringify } from \"../utils/json.js\";\n/**\n * @internal\n */\nexport async function fetchRpc(rpcUrl, client, options) {\n const response = await getClientFetch(client)(rpcUrl, {\n body: stringify(options.requests),\n headers: {\n ...client.config?.rpc?.fetch?.headers,\n \"Content-Type\": \"application/json\",\n },\n keepalive: client.config?.rpc?.fetch?.keepalive,\n method: \"POST\",\n requestTimeoutMs: options.requestTimeoutMs ?? client.config?.rpc?.fetch?.requestTimeoutMs,\n });\n if (!response.ok) {\n const error = await response.text().catch(() => null);\n throw new Error(`RPC request failed with status ${response.status} - ${response.statusText}: ${error || \"unknown error\"}`);\n }\n return await response.json();\n}\n/**\n * @internal\n */\nexport async function fetchSingleRpc(rpcUrl, client, options) {\n const response = await getClientFetch(client)(rpcUrl, {\n body: stringify(options.request),\n headers: {\n ...(client.config?.rpc?.fetch?.headers || {}),\n \"Content-Type\": \"application/json\",\n },\n keepalive: client.config?.rpc?.fetch?.keepalive,\n method: \"POST\",\n requestTimeoutMs: options.requestTimeoutMs ?? client.config?.rpc?.fetch?.requestTimeoutMs,\n });\n if (!response.ok) {\n const error = await response.text().catch(() => null);\n throw new Error(`RPC request failed with status ${response.status} - ${response.statusText}: ${error || \"unknown error\"}`);\n }\n return await response.json();\n}\n//# sourceMappingURL=fetch-rpc.js.map","import { getRpcUrlForChain } from \"../chains/utils.js\";\nimport { stringify } from \"../utils/json.js\";\nimport { fetchRpc, fetchSingleRpc } from \"./fetch-rpc.js\";\nconst RPC_CLIENT_MAP = new WeakMap();\n/**\n * @internal\n */\nfunction getRpcClientMap(client) {\n if (RPC_CLIENT_MAP.has(client)) {\n return RPC_CLIENT_MAP.get(client);\n }\n const rpcClientMap = new Map();\n RPC_CLIENT_MAP.set(client, rpcClientMap);\n return rpcClientMap;\n}\n/**\n * @internal\n */\nfunction rpcRequestKey(request) {\n return `${request.method}:${stringify(request.params)}`;\n}\nconst DEFAULT_MAX_BATCH_SIZE = 100;\n// default to no timeout (next tick)\nconst DEFAULT_BATCH_TIMEOUT_MS = 0;\n/**\n * Returns an RPC request that can be used to make JSON-RPC requests.\n * @param options - The RPC options.\n * @returns The RPC request function.\n * @rpc\n * @example\n * ```ts\n * import { createThirdwebClient } from \"thirdweb\";\n * import { getRpcClient } from \"thirdweb/rpc\";\n * import { ethereum } from \"thirdweb/chains\";\n * const client = createThirdwebClient({ clientId: \"...\" });\n * const rpcRequest = getRpcClient({ client, chain: ethereum, });\n * const blockNumber = await rpcRequest({\n * method: \"eth_blockNumber\",\n * });\n * ```\n */\nexport function getRpcClient(options) {\n const rpcClientMap = getRpcClientMap(options.client);\n const rpcUrl = options.chain.rpc;\n if (rpcClientMap.has(rpcUrl)) {\n return rpcClientMap.get(rpcUrl);\n }\n const rpcClient = (() => {\n // we can do this upfront because it cannot change later\n const rpcUrl = getRpcUrlForChain({\n chain: options.chain,\n client: options.client,\n });\n const batchSize = \n // look at the direct options passed\n options.config?.maxBatchSize ??\n // look at the client options\n options.client.config?.rpc?.maxBatchSize ??\n // use defaults\n DEFAULT_MAX_BATCH_SIZE;\n const batchTimeoutMs = \n // look at the direct options passed\n options.config?.batchTimeoutMs ??\n // look at the client options\n options.client.config?.rpc?.batchTimeoutMs ??\n DEFAULT_BATCH_TIMEOUT_MS;\n // inflight requests\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix any\n const inflightRequests = new Map();\n let pendingBatch = [];\n let pendingBatchTimeout = null;\n /**\n * Sends the pending batch of requests.\n * @internal\n */\n function sendPendingBatch() {\n // clear the timeout if any\n if (pendingBatchTimeout) {\n clearTimeout(pendingBatchTimeout);\n pendingBatchTimeout = null;\n }\n // prepare the requests array (we know the size)\n const requests = new Array(pendingBatch.length);\n const activeBatch = pendingBatch.slice().map((inflight, index) => {\n // assign the id to the request\n inflight.request.id = index;\n // also assign the jsonrpc version\n inflight.request.jsonrpc = \"2.0\";\n // assign the request to the requests array (so we don't have to map it again later)\n requests[index] = inflight.request;\n return inflight;\n });\n // reset pendingBatch to empty\n pendingBatch = [];\n fetchRpc(rpcUrl, options.client, {\n requests,\n requestTimeoutMs: options.config?.requestTimeoutMs,\n })\n .then((responses) => {\n activeBatch.forEach((inflight, index) => {\n // Handle the inflight request promise for each response.\n const response = responses[index];\n // No response.\n if (!response) {\n inflight.reject(new Error(`RPC Error from ${rpcUrl}:\\nrequests: ${stringify(requests)}\\nresponses: ${stringify(responses)}`));\n }\n // Response is an error or error string.\n else if (response instanceof Error) {\n inflight.reject(response);\n }\n else if (\"error\" in response) {\n inflight.reject(response.error);\n }\n else if (typeof response === \"string\") {\n inflight.reject(new Error(response));\n }\n // eth_subscription is not supported yet.\n else if (response.method === \"eth_subscription\") {\n inflight.reject(\"Subscriptions not supported yet\");\n }\n // Else return the successful response for the inflight request.\n else {\n inflight.resolve(response.result);\n }\n });\n })\n .catch((err) => {\n // http call failed, reject all inflight requests\n for (const inflight of activeBatch) {\n inflight.reject(err);\n }\n })\n .finally(() => {\n // Clear the inflight requests map so any new requests are re-fetched.\n inflightRequests.clear();\n });\n }\n // shortcut everything if we do not need to batch\n if (batchSize === 1) {\n return async (request) => {\n // we can hard-code the id and jsonrpc version\n // we also mutate the request object here to avoid copying it\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix any\n request.id = 1;\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix any\n request.jsonrpc = \"2.0\";\n const rpcResponse = await fetchSingleRpc(rpcUrl, options.client, {\n request: request,\n requestTimeoutMs: options.config?.requestTimeoutMs,\n });\n if (!rpcResponse) {\n throw new Error(\"No response\");\n }\n if (\"error\" in rpcResponse) {\n throw rpcResponse.error;\n }\n return rpcResponse.result;\n };\n }\n return async (request) => {\n const requestKey = rpcRequestKey(request);\n // if the request for this key is already inflight, return the promise directly\n if (inflightRequests.has(requestKey)) {\n // biome-ignore lint/style/noNonNullAssertion: the `has` check ensures this is defined\n return inflightRequests.get(requestKey);\n }\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix any\n let resolve;\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix any\n let reject;\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix any\n const promise = new Promise((resolve_, reject_) => {\n resolve = resolve_;\n reject = reject_;\n });\n inflightRequests.set(requestKey, promise);\n // @ts-expect-error - they *are* definitely assigned within the promise constructor\n pendingBatch.push({ reject, request, requestKey, resolve });\n if (batchSize > 1) {\n // if there is no timeout, set one\n if (!pendingBatchTimeout) {\n pendingBatchTimeout = setTimeout(sendPendingBatch, batchTimeoutMs);\n }\n // if the batch is full, send it\n if (pendingBatch.length >= batchSize) {\n sendPendingBatch();\n }\n }\n else {\n sendPendingBatch();\n }\n return promise;\n };\n })();\n rpcClientMap.set(rpcUrl, rpcClient);\n return rpcClient;\n}\n//# sourceMappingURL=rpc.js.map","import * as ox__Bytes from \"ox/Bytes\";\nimport { isHex } from \"./helpers/is-hex.js\";\n/**\n * Converts a value to an array of bytes.\n * @param value - The value to convert.\n * @param opts - Optional parameters for the conversion.\n * @returns The array of bytes representing the value.\n * @example\n * ```ts\n * import { toBytes } from \"thirdweb/utils\";\n * const bytes = toBytes(\"0x1a4\");\n * console.log(bytes); // Uint8Array(2) [ 1, 164 ]\n * ```\n * @utils\n */\nexport function toBytes(value, opts = {}) {\n switch (typeof value) {\n case \"number\":\n case \"bigint\":\n return numberToBytes(value, opts);\n case \"boolean\":\n return boolToBytes(value, opts);\n default:\n if (isHex(value)) {\n return hexToBytes(value, opts);\n }\n return stringToBytes(value, opts);\n }\n}\n/**\n * Converts a boolean value to a Uint8Array of bytes.\n * @param value - The boolean value to convert.\n * @param opts - Optional parameters for the conversion.\n * @returns The Uint8Array of bytes representing the boolean value.\n * @example\n * ```ts\n * import { boolToBytes } from \"thirdweb/utils\";\n * const bytes = boolToBytes(true);\n * console.log(bytes); // Uint8Array(1) [ 1 ]\n * ```\n * @utils\n */\nexport function boolToBytes(value, opts = {}) {\n return ox__Bytes.fromBoolean(value, opts);\n}\n/**\n * Converts a hexadecimal string to a Uint8Array of bytes.\n * @param hex_ The hexadecimal string to convert.\n * @param opts Options for converting the hexadecimal string.\n * @returns The Uint8Array of bytes.\n * @throws Error if the byte sequence is invalid.\n * @example\n * ```ts\n * import { hexToBytes } from \"thirdweb/utils\";\n * const bytes = hexToBytes(\"0x1a4\");\n * console.log(bytes); // Uint8Array(2) [ 1, 164 ]\n * ```\n * @utils\n */\nexport function hexToBytes(hex_, opts = {}) {\n return ox__Bytes.fromHex(hex_, opts);\n}\n/**\n * Converts a number to bytes.\n * @param value - The number to convert.\n * @param opts - Options for converting the number to hex.\n * @returns The bytes representation of the number.\n * @example\n * ```ts\n * import { numberToBytes } from \"thirdweb/utils\";\n * const bytes = numberToBytes(420);\n * console.log(bytes); // Uint8Array(2) [ 1, 164 ]\n * ```\n * @utils\n */\nexport function numberToBytes(value, opts) {\n return ox__Bytes.fromNumber(value, opts);\n}\n/**\n * Converts a string to an array of bytes.\n * @param value - The string to convert.\n * @param opts - Optional parameters for the conversion.\n * @returns The array of bytes representing the string.\n * @example\n * ```ts\n * import { stringToBytes } from \"thirdweb/utils\";\n * const bytes = stringToBytes(\"Hello, world!\");\n * console.log(bytes); // Uint8Array(13) [ 72, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100, 33 ]\n * ```\n * @utils\n */\nexport function stringToBytes(value, opts = {}) {\n return ox__Bytes.fromString(value, opts);\n}\n//# sourceMappingURL=to-bytes.js.map","/**\n * Internal assertion helpers.\n * @module\n */\n/** Asserts something is positive integer. */\nfunction anumber(n) {\n if (!Number.isSafeInteger(n) || n < 0)\n throw new Error('positive integer expected, got ' + n);\n}\n/** Is number an Uint8Array? Copied from utils for perf. */\nfunction isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n/** Asserts something is Uint8Array. */\nfunction abytes(b, ...lengths) {\n if (!isBytes(b))\n throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error('Uint8Array expected of length ' + lengths + ', got length=' + b.length);\n}\n/** Asserts something is hash */\nfunction ahash(h) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n anumber(h.outputLen);\n anumber(h.blockLen);\n}\n/** Asserts a hash instance has not been destroyed / finished */\nfunction aexists(instance, checkFinished = true) {\n if (instance.destroyed)\n throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished)\n throw new Error('Hash#digest() has already been called');\n}\n/** Asserts output is properly-sized byte array */\nfunction aoutput(out, instance) {\n abytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error('digestInto() expects output buffer of length at least ' + min);\n }\n}\nexport { anumber, abytes, ahash, aexists, aoutput };\n//# sourceMappingURL=_assert.js.map","/**\n * Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.\n * @todo re-check https://issues.chromium.org/issues/42212588\n * @module\n */\nconst U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\nfunction fromBig(n, le = false) {\n if (le)\n return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\nfunction split(lst, le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\nconst toBig = (h, l) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h, _l, s) => h >>> s;\nconst shrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h, l, s) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h, l, s) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h, l, s) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h, l, s) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h, l) => l;\nconst rotr32L = (h, _l) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h, l, s) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h, l, s) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h, l, s) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h, l, s) => (h << (s - 32)) | (l >>> (64 - s));\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah, Al, Bh, Bl) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al, Bl, Cl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low, Ah, Bh, Ch) => (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al, Bl, Cl, Dl) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low, Ah, Bh, Ch, Dh) => (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al, Bl, Cl, Dl, El) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low, Ah, Bh, Ch, Dh, Eh) => (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n// prettier-ignore\nexport { fromBig, split, toBig, shrSH, shrSL, rotrSH, rotrSL, rotrBH, rotrBL, rotr32H, rotr32L, rotlSH, rotlSL, rotlBH, rotlBL, add, add3L, add3H, add4L, add4H, add5H, add5L, };\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n//# sourceMappingURL=_u64.js.map","/**\n * Utilities for hex, bytes, CSPRNG.\n * @module\n */\n/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { abytes } from \"./_assert.js\";\n// export { isBytes } from './_assert.ts';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a) {\n return a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n}\n// Cast array to different type\nexport function u8(arr) {\n return new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\n}\nexport function u32(arr) {\n return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n}\n// Cast array to view\nexport function createView(arr) {\n return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n}\n/** The rotate right (circular right shift) operation for uint32 */\nexport function rotr(word, shift) {\n return (word << (32 - shift)) | (word >>> shift);\n}\n/** The rotate left (circular left shift) operation for uint32 */\nexport function rotl(word, shift) {\n return (word << shift) | ((word >>> (32 - shift)) >>> 0);\n}\n/** Is current platform little-endian? Most are. Big-Endian platform: IBM */\nexport const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44)();\n// The byte swap operation for uint32\nexport function byteSwap(word) {\n return (((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff));\n}\n/** Conditionally byte swap if on a big-endian platform */\nexport const byteSwapIfBE = isLE\n ? (n) => n\n : (n) => byteSwap(n);\n/** In place byte swap for Uint32Array */\nexport function byteSwap32(arr) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n// Built-in hex conversion https://caniuse.com/mdn-javascript_builtins_uint8array_fromhex\nconst hasHexBuiltin = \n// @ts-ignore\ntypeof Uint8Array.from([]).toHex === 'function' && typeof Uint8Array.fromHex === 'function';\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, '0'));\n/**\n * Convert byte array to hex string. Uses built-in function, when available.\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes) {\n abytes(bytes);\n // @ts-ignore\n if (hasHexBuiltin)\n return bytes.toHex();\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 };\nfunction asciiToBase16(ch) {\n if (ch >= asciis._0 && ch <= asciis._9)\n return ch - asciis._0; // '2' => 50-48\n if (ch >= asciis.A && ch <= asciis.F)\n return ch - (asciis.A - 10); // 'B' => 66-(65-10)\n if (ch >= asciis.a && ch <= asciis.f)\n return ch - (asciis.a - 10); // 'b' => 98-(97-10)\n return;\n}\n/**\n * Convert hex string to byte array. Uses built-in function, when available.\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex) {\n if (typeof hex !== 'string')\n throw new Error('hex string expected, got ' + typeof hex);\n // @ts-ignore\n if (hasHexBuiltin)\n return Uint8Array.fromHex(hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n throw new Error('hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2; // multiply first octet, e.g. 'a3' => 10*16+3 => 160 + 3 => 163\n }\n return array;\n}\n/**\n * There is no setImmediate in browser and setTimeout is slow.\n * Call of async fn will return Promise, which will be fullfiled only on\n * next scheduler queue processing step and this is exactly what we need.\n */\nexport const nextTick = async () => { };\n/** Returns control to thread each 'tick' ms to avoid blocking. */\nexport async function asyncLoop(iters, tick, cb) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick)\n continue;\n await nextTick();\n ts += diff;\n }\n}\n/**\n * Convert JS string to byte array.\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str) {\n if (typeof str !== 'string')\n throw new Error('utf8ToBytes expected string, got ' + typeof str);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data) {\n if (typeof data === 'string')\n data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays) {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n/** For runtime check if class implements interface */\nexport class Hash {\n // Safe version that clones internal state\n clone() {\n return this._cloneInto();\n }\n}\nexport function checkOpts(defaults, opts) {\n if (opts !== undefined && {}.toString.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged;\n}\n/** Wraps hash function, creating an interface on top of it */\nexport function wrapConstructor(hashCons) {\n const hashC = (msg) => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\nexport function wrapConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\nexport function wrapXOFConstructorWithOpts(hashCons) {\n const hashC = (msg, opts) => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({});\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts) => hashCons(opts);\n return hashC;\n}\n/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */\nexport function randomBytes(bytesLength = 32) {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n // Legacy Node.js compatibility\n if (crypto && typeof crypto.randomBytes === 'function') {\n return Uint8Array.from(crypto.randomBytes(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n//# sourceMappingURL=utils.js.map","/**\n * SHA3 (keccak) hash function, based on a new \"Sponge function\" design.\n * Different from older hashes, the internal state is bigger than output size.\n *\n * Check out [FIPS-202](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf),\n * [Website](https://keccak.team/keccak.html),\n * [the differences between SHA-3 and Keccak](https://crypto.stackexchange.com/questions/15727/what-are-the-key-differences-between-the-draft-sha-3-standard-and-the-keccak-sub).\n *\n * Check out `sha3-addons` module for cSHAKE, k12, and others.\n * @module\n */\nimport { abytes, aexists, anumber, aoutput } from \"./_assert.js\";\nimport { rotlBH, rotlBL, rotlSH, rotlSL, split } from \"./_u64.js\";\nimport { byteSwap32, Hash, isLE, toBytes, u32, wrapConstructor, wrapXOFConstructorWithOpts, } from \"./utils.js\";\n// Various per round constants calculations\nconst SHA3_PI = [];\nconst SHA3_ROTL = [];\nconst _SHA3_IOTA = [];\nconst _0n = /* @__PURE__ */ BigInt(0);\nconst _1n = /* @__PURE__ */ BigInt(1);\nconst _2n = /* @__PURE__ */ BigInt(2);\nconst _7n = /* @__PURE__ */ BigInt(7);\nconst _256n = /* @__PURE__ */ BigInt(256);\nconst _0x71n = /* @__PURE__ */ BigInt(0x71);\nfor (let round = 0, R = _1n, x = 1, y = 0; round < 24; round++) {\n // Pi\n [x, y] = [y, (2 * x + 3 * y) % 5];\n SHA3_PI.push(2 * (5 * y + x));\n // Rotational\n SHA3_ROTL.push((((round + 1) * (round + 2)) / 2) % 64);\n // Iota\n let t = _0n;\n for (let j = 0; j < 7; j++) {\n R = ((R << _1n) ^ ((R >> _7n) * _0x71n)) % _256n;\n if (R & _2n)\n t ^= _1n << ((_1n << /* @__PURE__ */ BigInt(j)) - _1n);\n }\n _SHA3_IOTA.push(t);\n}\nconst [SHA3_IOTA_H, SHA3_IOTA_L] = /* @__PURE__ */ split(_SHA3_IOTA, true);\n// Left rotation (without 0, 32, 64)\nconst rotlH = (h, l, s) => (s > 32 ? rotlBH(h, l, s) : rotlSH(h, l, s));\nconst rotlL = (h, l, s) => (s > 32 ? rotlBL(h, l, s) : rotlSL(h, l, s));\n/** `keccakf1600` internal function, additionally allows to adjust round count. */\nexport function keccakP(s, rounds = 24) {\n const B = new Uint32Array(5 * 2);\n // NOTE: all indices are x2 since we store state as u32 instead of u64 (bigints to slow in js)\n for (let round = 24 - rounds; round < 24; round++) {\n // Theta θ\n for (let x = 0; x < 10; x++)\n B[x] = s[x] ^ s[x + 10] ^ s[x + 20] ^ s[x + 30] ^ s[x + 40];\n for (let x = 0; x < 10; x += 2) {\n const idx1 = (x + 8) % 10;\n const idx0 = (x + 2) % 10;\n const B0 = B[idx0];\n const B1 = B[idx0 + 1];\n const Th = rotlH(B0, B1, 1) ^ B[idx1];\n const Tl = rotlL(B0, B1, 1) ^ B[idx1 + 1];\n for (let y = 0; y < 50; y += 10) {\n s[x + y] ^= Th;\n s[x + y + 1] ^= Tl;\n }\n }\n // Rho (ρ) and Pi (π)\n let curH = s[2];\n let curL = s[3];\n for (let t = 0; t < 24; t++) {\n const shift = SHA3_ROTL[t];\n const Th = rotlH(curH, curL, shift);\n const Tl = rotlL(curH, curL, shift);\n const PI = SHA3_PI[t];\n curH = s[PI];\n curL = s[PI + 1];\n s[PI] = Th;\n s[PI + 1] = Tl;\n }\n // Chi (χ)\n for (let y = 0; y < 50; y += 10) {\n for (let x = 0; x < 10; x++)\n B[x] = s[y + x];\n for (let x = 0; x < 10; x++)\n s[y + x] ^= ~B[(x + 2) % 10] & B[(x + 4) % 10];\n }\n // Iota (ι)\n s[0] ^= SHA3_IOTA_H[round];\n s[1] ^= SHA3_IOTA_L[round];\n }\n B.fill(0);\n}\n/** Keccak sponge function. */\nexport class Keccak extends Hash {\n // NOTE: we accept arguments in bytes instead of bits here.\n constructor(blockLen, suffix, outputLen, enableXOF = false, rounds = 24) {\n super();\n this.pos = 0;\n this.posOut = 0;\n this.finished = false;\n this.destroyed = false;\n this.enableXOF = false;\n this.blockLen = blockLen;\n this.suffix = suffix;\n this.outputLen = outputLen;\n this.enableXOF = enableXOF;\n this.rounds = rounds;\n // Can be passed from user as dkLen\n anumber(outputLen);\n // 1600 = 5x5 matrix of 64bit. 1600 bits === 200 bytes\n // 0 < blockLen < 200\n if (0 >= this.blockLen || this.blockLen >= 200)\n throw new Error('Sha3 supports only keccak-f1600 function');\n this.state = new Uint8Array(200);\n this.state32 = u32(this.state);\n }\n keccak() {\n if (!isLE)\n byteSwap32(this.state32);\n keccakP(this.state32, this.rounds);\n if (!isLE)\n byteSwap32(this.state32);\n this.posOut = 0;\n this.pos = 0;\n }\n update(data) {\n aexists(this);\n const { blockLen, state } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len;) {\n const take = Math.min(blockLen - this.pos, len - pos);\n for (let i = 0; i < take; i++)\n state[this.pos++] ^= data[pos++];\n if (this.pos === blockLen)\n this.keccak();\n }\n return this;\n }\n finish() {\n if (this.finished)\n return;\n this.finished = true;\n const { state, suffix, pos, blockLen } = this;\n // Do the padding\n state[pos] ^= suffix;\n if ((suffix & 0x80) !== 0 && pos === blockLen - 1)\n this.keccak();\n state[blockLen - 1] ^= 0x80;\n this.keccak();\n }\n writeInto(out) {\n aexists(this, false);\n abytes(out);\n this.finish();\n const bufferOut = this.state;\n const { blockLen } = this;\n for (let pos = 0, len = out.length; pos < len;) {\n if (this.posOut >= blockLen)\n this.keccak();\n const take = Math.min(blockLen - this.posOut, len - pos);\n out.set(bufferOut.subarray(this.posOut, this.posOut + take), pos);\n this.posOut += take;\n pos += take;\n }\n return out;\n }\n xofInto(out) {\n // Sha3/Keccak usage with XOF is probably mistake, only SHAKE instances can do XOF\n if (!this.enableXOF)\n throw new Error('XOF is not possible for this instance');\n return this.writeInto(out);\n }\n xof(bytes) {\n anumber(bytes);\n return this.xofInto(new Uint8Array(bytes));\n }\n digestInto(out) {\n aoutput(out, this);\n if (this.finished)\n throw new Error('digest() was already called');\n this.writeInto(out);\n this.destroy();\n return out;\n }\n digest() {\n return this.digestInto(new Uint8Array(this.outputLen));\n }\n destroy() {\n this.destroyed = true;\n this.state.fill(0);\n }\n _cloneInto(to) {\n const { blockLen, suffix, outputLen, rounds, enableXOF } = this;\n to || (to = new Keccak(blockLen, suffix, outputLen, enableXOF, rounds));\n to.state32.set(this.state32);\n to.pos = this.pos;\n to.posOut = this.posOut;\n to.finished = this.finished;\n to.rounds = rounds;\n // Suffix can change in cSHAKE\n to.suffix = suffix;\n to.outputLen = outputLen;\n to.enableXOF = enableXOF;\n to.destroyed = this.destroyed;\n return to;\n }\n}\nconst gen = (suffix, blockLen, outputLen) => wrapConstructor(() => new Keccak(blockLen, suffix, outputLen));\n/** SHA3-224 hash function. */\nexport const sha3_224 = /* @__PURE__ */ gen(0x06, 144, 224 / 8);\n/** SHA3-256 hash function. Different from keccak-256. */\nexport const sha3_256 = /* @__PURE__ */ gen(0x06, 136, 256 / 8);\n/** SHA3-384 hash function. */\nexport const sha3_384 = /* @__PURE__ */ gen(0x06, 104, 384 / 8);\n/** SHA3-512 hash function. */\nexport const sha3_512 = /* @__PURE__ */ gen(0x06, 72, 512 / 8);\n/** keccak-224 hash function. */\nexport const keccak_224 = /* @__PURE__ */ gen(0x01, 144, 224 / 8);\n/** keccak-256 hash function. Different from SHA3-256. */\nexport const keccak_256 = /* @__PURE__ */ gen(0x01, 136, 256 / 8);\n/** keccak-384 hash function. */\nexport const keccak_384 = /* @__PURE__ */ gen(0x01, 104, 384 / 8);\n/** keccak-512 hash function. */\nexport const keccak_512 = /* @__PURE__ */ gen(0x01, 72, 512 / 8);\nconst genShake = (suffix, blockLen, outputLen) => wrapXOFConstructorWithOpts((opts = {}) => new Keccak(blockLen, suffix, opts.dkLen === undefined ? outputLen : opts.dkLen, true));\n/** SHAKE128 XOF with 128-bit security. */\nexport const shake128 = /* @__PURE__ */ genShake(0x1f, 168, 128 / 8);\n/** SHAKE256 XOF with 256-bit security. */\nexport const shake256 = /* @__PURE__ */ genShake(0x1f, 136, 256 / 8);\n//# sourceMappingURL=sha3.js.map","import { keccak_256 } from \"@noble/hashes/sha3\";\nimport { hexToUint8Array, isHex, uint8ArrayToHex, } from \"../encoding/hex.js\";\n/**\n * Calculates the Keccak-256 hash of the given value.\n * @param value - The value to hash, either as a hexadecimal string or a Uint8Array.\n * @param to - The desired output format of the hash (optional). Defaults to 'hex'.\n * @returns The Keccak-256 hash of the value in the specified format.\n * @example\n * ```ts\n * import { keccak256 } from \"thirdweb/utils\";\n * const hash = keccak256(\"0x1234\");\n * ```\n * @utils\n */\nexport function keccak256(value, to) {\n const bytes = keccak_256(isHex(value, { strict: false }) ? hexToUint8Array(value) : value);\n if (to === \"bytes\") {\n return bytes;\n }\n // default fall through to hex\n return uint8ArrayToHex(bytes);\n}\n//# sourceMappingURL=keccak256.js.map","import { LruMap } from \"./caching/lru.js\";\nimport { stringToBytes } from \"./encoding/to-bytes.js\";\nimport { keccak256 } from \"./hashing/keccak256.js\";\nconst ADDRESS_REGEX = /^0x[a-fA-F0-9]{40}$/;\nconst IS_ADDRESS_CACHE = new LruMap(4096);\n/**\n * Checks if a given string is a valid address.\n * @param address The address to check.\n * @returns True if the address is valid, false otherwise.\n * @example\n * ```ts\n * import { isAddress } from 'thirdweb/utils';\n *\n * isAddress('0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed');\n * //=> true\n * ```\n * @utils\n */\nexport function isAddress(address) {\n if (IS_ADDRESS_CACHE.has(address)) {\n // biome-ignore lint/style/noNonNullAssertion: the `has` above ensures that this will always be set\n return IS_ADDRESS_CACHE.get(address);\n }\n const result = ADDRESS_REGEX.test(address) &&\n (address.toLowerCase() === address || checksumAddress(address) === address);\n IS_ADDRESS_CACHE.set(address, result);\n return result;\n}\n/**\n * Calculates the checksum address for the given address.\n * @param address - The address to calculate the checksum for.\n * @returns The checksum address.\n * @example\n * ```ts\n * import { checksumAddress } from 'thirdweb/utils';\n *\n * checksumAddress('0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed');\n * //=> '0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed'\n * ```\n * @utils\n */\nexport function checksumAddress(address) {\n const hexAddress = address.substring(2).toLowerCase();\n const hash = keccak256(stringToBytes(hexAddress), \"bytes\");\n const address_ = hexAddress.split(\"\");\n for (let i = 0; i < 40; i += 2) {\n // biome-ignore lint/style/noNonNullAssertion: TODO\n if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n // biome-ignore lint/style/noNonNullAssertion: TODO\n address_[i] = address_[i].toUpperCase();\n }\n // biome-ignore lint/style/noNonNullAssertion: TODO\n if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n // biome-ignore lint/style/noNonNullAssertion: TODO\n address_[i + 1] = address_[i + 1].toUpperCase();\n }\n }\n return `0x${address_.join(\"\")}`;\n}\n/**\n * Retrieves the address after performing validation and checksumming.\n * @param address - The address to be validated and checksummed.\n * @returns The validated and checksummed address.\n * @throws Error if the address is invalid.\n * @example\n * ```ts\n * import { getAddress } from 'thirdweb/utils';\n *\n * getAddress('0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed');\n * //=> '0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed'\n * ```\n * @utils\n */\nexport function getAddress(address) {\n if (!isAddress(address)) {\n throw new Error(`Invalid address: ${address}`);\n }\n return checksumAddress(address);\n}\n/**\n * Checksums and formats an address if valid. Note this function does not check if the provided address is an ENS.\n * @param address - The address to shorten.\n * @param length - The number of characters to keep from the start and end of the address.\n * @returns The shortened address.\n * @example\n * ```ts\n * import { shortenAddress } from 'thirdweb/utils';\n *\n * shortenAddress('0xa0cf798816d4b9b9866b5330eea46a18382f251e');\n * //=> '0xA0Cf...251e'\n * ```\n * @utils\n */\nexport function shortenAddress(address, length = 4) {\n const _address = getAddress(address);\n return shortenHex(_address, length);\n}\n/**\n * Shortens a hexadecimal string without performing any validation or checksumming.\n * @param hex - The hexadecimal string to shorten.\n * @param length - The number of characters to keep from the start and end of the string.\n * @returns The shortened hexadecimal string.\n * @example\n * ```ts\n * import { shortenHex } from 'thirdweb/utils';\n *\n * shortenHex('0xa0cf798816d4b9b9866b5330eea46a18382f251e');\n * //=> '0xa0cf...251e'\n * ```\n * @utils\n */\nexport function shortenHex(hex, length = 4) {\n return `${hex.slice(0, length + 2)}...${hex.slice(-length)}`;\n}\n//# sourceMappingURL=address.js.map","import { isHex } from \"../hex.js\";\n/**\n * Calculates the byte size of a Hex string or Uint8Array.\n * If the value is a Hex string, it accounts for the leading \"0x\" prefix.\n * @param value The Hex string or Uint8Array.\n * @returns The byte size of the value.\n * @example\n * ```ts\n * import { byteSize } from \"thirdweb/utils\";\n * const size = byteSize(\"0x1a4\");\n * console.log(size); // 2\n * ```\n */\nexport function byteSize(value) {\n if (isHex(value, { strict: false })) {\n return Math.ceil((value.length - 2) / 2);\n }\n return value.length;\n}\n//# sourceMappingURL=byte-size.js.map","import * as ox__Hex from \"ox/Hex\";\nimport { isAddress } from \"../address.js\";\nimport { byteSize } from \"../encoding/helpers/byte-size.js\";\nimport { boolToHex, numberToHex, padHex, stringToHex, } from \"../encoding/hex.js\";\n/**\n * Encodes the given ABI parameters and values into a hexadecimal string.\n * @template TParams - The type of the ABI parameters.\n * @param params - The ABI parameters.\n * @param values - The corresponding values for the ABI parameters.\n * @returns - The encoded ABI parameters as a hexadecimal string.\n * @throws {Error} - If the number of parameters and values do not match.\n * @example\n * ```ts\n * import { encodeAbiParameters } from \"thirdweb/utils\";\n *\n * const params = [\n * { name: \"param1\", type: \"uint256\" },\n * { name: \"param2\", type: \"string\" },\n * ];\n * const values = [123, \"hello\"];\n *\n * const data = encodeAbiParameters(params, values);\n * console.log(data);\n * ```\n * @utils\n */\nexport function encodeAbiParameters(params, values) {\n if (params.length !== values.length) {\n throw new Error(\"The number of parameters and values must match.\");\n }\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params,\n values,\n });\n const data = encodeParams(preparedParams);\n if (data.length === 0) {\n return \"0x\";\n }\n return data;\n}\nfunction prepareParams({ params, values, }) {\n const preparedParams = [];\n for (let i = 0; i < params.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: we know the value is not `undefined`.\n preparedParams.push(prepareParam({ param: params[i], value: values[i] }));\n }\n return preparedParams;\n}\n/**\n * @internal Export for unit test\n */\nexport function prepareParam({ param, value, }) {\n const arrayComponents = getArrayComponents(param.type);\n if (arrayComponents) {\n const [length, type] = arrayComponents;\n return encodeArray(value, { length, param: { ...param, type } });\n }\n if (param.type === \"tuple\") {\n return encodeTuple(value, {\n param: param,\n });\n }\n if (param.type === \"address\") {\n return encodeAddress(value);\n }\n if (param.type === \"bool\") {\n return encodeBool(value);\n }\n if (param.type.startsWith(\"uint\") || param.type.startsWith(\"int\")) {\n const signed = param.type.startsWith(\"int\");\n return encodeNumber(value, { signed });\n }\n if (param.type.startsWith(\"bytes\")) {\n return encodeBytes(value, { param });\n }\n if (param.type === \"string\") {\n return encodeString(value);\n }\n throw new Error(`Unsupported parameter type: ${param.type}`);\n}\nfunction encodeParams(preparedParams) {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0;\n for (let i = 0; i < preparedParams.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: we know the value is not `undefined`.\n const { dynamic, encoded } = preparedParams[i];\n if (dynamic) {\n staticSize += 32;\n }\n else {\n staticSize += byteSize(encoded);\n }\n }\n // 2. Split the parameters into static and dynamic parts.\n const staticParams = [];\n const dynamicParams = [];\n let dynamicSize = 0;\n for (let i = 0; i < preparedParams.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: we know the value is not `undefined`.\n const { dynamic, encoded } = preparedParams[i];\n if (dynamic) {\n staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));\n dynamicParams.push(encoded);\n dynamicSize += byteSize(encoded);\n }\n else {\n staticParams.push(encoded);\n }\n }\n // 3. Concatenate static and dynamic parts.\n return ox__Hex.concat(...[...staticParams, ...dynamicParams]);\n}\n/////////////////////////////////////////////////////////////////\n/**\n * @internal Export for unit test\n */\nexport function encodeAddress(value) {\n // We allow empty strings for deployment transactions where there is no to address\n if (value !== \"\" && value !== undefined && !isAddress(value)) {\n throw new Error(`Invalid address: ${value}`);\n }\n return { dynamic: false, encoded: padHex(value.toLowerCase()) };\n}\nfunction encodeArray(value, { length, param, }) {\n const dynamic = length === null;\n if (!Array.isArray(value)) {\n throw new Error(\"Invalid array value.\");\n }\n if (!dynamic && value.length !== length) {\n throw new Error(\"Invalid array length.\");\n }\n let dynamicChild = false;\n const preparedParams = [];\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParam({ param, value: value[i] });\n if (preparedParam.dynamic) {\n dynamicChild = true;\n }\n preparedParams.push(preparedParam);\n }\n if (dynamic || dynamicChild) {\n const data = encodeParams(preparedParams);\n if (dynamic) {\n const length_ = numberToHex(preparedParams.length, { size: 32 });\n return {\n dynamic: true,\n encoded: preparedParams.length > 0\n ? ox__Hex.concat(...[length_, data])\n : length_,\n };\n }\n if (dynamicChild) {\n return { dynamic: true, encoded: data };\n }\n }\n return {\n dynamic: false,\n encoded: ox__Hex.concat(...preparedParams.map(({ encoded }) => encoded)),\n };\n}\nfunction encodeBytes(value, { param }) {\n const [, paramSize] = param.type.split(\"bytes\");\n const bytesSize = byteSize(value);\n if (!paramSize) {\n let value_ = value;\n // If the size is not divisible by 32 bytes, pad the end\n // with empty bytes to the ceiling 32 bytes.\n if (bytesSize % 32 !== 0) {\n value_ = padHex(value_, {\n dir: \"right\",\n size: Math.ceil((value.length - 2) / 2 / 32) * 32,\n });\n }\n return {\n dynamic: true,\n encoded: ox__Hex.concat(...[padHex(numberToHex(bytesSize, { size: 32 })), value_]),\n };\n }\n if (bytesSize !== Number.parseInt(paramSize)) {\n throw new Error(`Invalid bytes${paramSize} size: ${bytesSize}`);\n }\n return { dynamic: false, encoded: padHex(value, { dir: \"right\" }) };\n}\nfunction encodeBool(value) {\n return { dynamic: false, encoded: padHex(boolToHex(value)) };\n}\nfunction encodeNumber(value, { signed }) {\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n signed,\n size: 32,\n }),\n };\n}\nfunction encodeString(value) {\n const hexValue = stringToHex(value);\n const partsLength = Math.ceil(byteSize(hexValue) / 32);\n const parts = [];\n for (let i = 0; i < partsLength; i++) {\n parts.push(padHex(ox__Hex.slice(hexValue, i * 32, (i + 1) * 32), {\n dir: \"right\",\n }));\n }\n return {\n dynamic: true,\n encoded: ox__Hex.concat(...[padHex(numberToHex(byteSize(hexValue), { size: 32 })), ...parts]),\n };\n}\nfunction encodeTuple(value, { param }) {\n let dynamic = false;\n const preparedParams = [];\n for (let i = 0; i < param.components.length; i++) {\n // biome-ignore lint/style/noNonNullAssertion: we know the value is not `undefined`.\n const param_ = param.components[i];\n const index = Array.isArray(value) ? i : param_.name;\n const preparedParam = prepareParam({\n param: param_,\n // biome-ignore lint/style/noNonNullAssertion: we know the value is not `undefined`.\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix any\n value: value[index],\n });\n preparedParams.push(preparedParam);\n if (preparedParam.dynamic) {\n dynamic = true;\n }\n }\n return {\n dynamic,\n encoded: dynamic\n ? encodeParams(preparedParams)\n : ox__Hex.concat(...preparedParams.map(({ encoded }) => encoded)),\n };\n}\nfunction getArrayComponents(type) {\n const matches = type.match(/^(.*)\\[(\\d+)?\\]$/);\n return matches\n ? // Return `null` if the array is dynamic.\n // biome-ignore lint/style/noNonNullAssertion: we know the value is not `undefined`.\n [matches[2] ? Number(matches[2]) : null, matches[1]]\n : undefined;\n}\n//# sourceMappingURL=encodeAbiParameters.js.map","import { parseAbiItem } from \"abitype\";\nimport { toFunctionSelector } from \"viem\";\nimport { LruMap } from \"../caching/lru.js\";\nimport { stringify } from \"../json.js\";\nconst prepareMethodCache = new LruMap(4096);\n/**\n * Prepares a method for usage by converting it into a prepared method object.\n * @param method The method to prepare.\n * @returns The prepared method object.\n * @example\n * ```ts\n * import { prepareMethod } from \"thirdweb/utils\";\n * const method = \"function transfer(address to, uint256 value)\";\n * const preparedMethod = prepareMethod(method);\n * ```\n * @contract\n */\nexport function prepareMethod(method) {\n const key = typeof method === \"string\" ? method : stringify(method);\n if (prepareMethodCache.has(key)) {\n return prepareMethodCache.get(key);\n }\n const abiFn = typeof method === \"string\"\n ? // @ts-expect-error - we're sure it's a string...\n parseAbiItem(method)\n : method;\n // encode the method signature\n const sig = toFunctionSelector(abiFn);\n const ret = [sig, abiFn.inputs, abiFn.outputs];\n prepareMethodCache.set(key, ret);\n return ret;\n}\n//# sourceMappingURL=prepare-method.js.map","/**\n * Resolves a possibly asynchronous value.\n * If the value is a function that returns a promise, it will be awaited and the resolved value will be returned.\n * Otherwise, the value itself will be returned.\n *\n * @param value - The value to resolve.\n * @returns A promise that resolves to the resolved value.\n * @internal\n */\nexport async function resolvePromisedValue(value) {\n // @ts-expect-error - this works fine, but TS doesn't like it since 5.8\n return typeof value === \"function\" ? await value() : value;\n}\n//# sourceMappingURL=resolve-promised-value.js.map","import { getGasPrice } from \"../gas/get-gas-price.js\";\nimport { estimateGasCost } from \"./actions/estimate-gas-cost.js\";\n/**\n * @internal\n */\nexport function isAbiFunction(item) {\n return !!(item &&\n typeof item === \"object\" &&\n \"type\" in item &&\n item.type === \"function\");\n}\nexport async function getTransactionGasCost(tx, from) {\n try {\n const gasCost = await estimateGasCost({\n from,\n transaction: tx,\n });\n const bufferCost = gasCost.wei / 10n;\n // Note: get tx.value AFTER estimateGasCost\n // add 10% extra gas cost to the estimate to ensure user buys enough to cover the tx cost\n return gasCost.wei + bufferCost;\n }\n catch {\n if (from) {\n // try again without passing from\n return await getTransactionGasCost(tx);\n }\n // fallback if both fail, use the tx value + 1M * gas price\n const gasPrice = await getGasPrice({\n chain: tx.chain,\n client: tx.client,\n });\n return 1000000n * gasPrice;\n }\n}\n//# sourceMappingURL=utils.js.map","import { parseAbiItem, } from \"abitype\";\nimport { decodeAbiParameters } from \"viem\";\nimport { eth_call } from \"../rpc/actions/eth_call.js\";\nimport { getRpcClient } from \"../rpc/rpc.js\";\nimport { encodeAbiParameters } from \"../utils/abi/encodeAbiParameters.js\";\nimport { prepareMethod, } from \"../utils/abi/prepare-method.js\";\nimport { getAddress } from \"../utils/address.js\";\nimport { isAbiFunction } from \"./utils.js\";\n/**\n * ### Reads state from a deployed smart contract.\n *\n * Use this for raw read calls from a contract, but you can also use read [extensions](https://portal.thirdweb.com/typescript/v5/extensions/use) for predefined methods for common standards.\n *\n * @param options - The transaction options.\n * @returns A promise that resolves with the result of the read call.\n * @transaction\n * @example\n *\n * ### Raw contract call (recommended)\n *\n * You can read from any contract by using the solidity signature of the function you want to call.\n *\n * ```ts\n * import { getContract } from \"thirdweb\";\n * import { sepolia } from \"thirdweb/chains\";\n * import { useReadContract } from \"thirdweb/react\";\n *\n * const contract = getContract({\n * client,\n * address: \"0x...\",\n * chain: sepolia,\n * });\n *\n * const { data, isLoading } = useReadContract({\n * contract,\n * method: \"function tokenURI(uint256 tokenId) returns (string)\",\n * params: [1n],\n * });\n * ```\n *\n * Note that this is type safe, the params types will be enforced based on the signature.\n *\n * ### Raw contract call with `resolveMethod`\n *\n * If you don't have the solidity signature of the function you want to call, you can use the `resolveMethod` helper to resolve the method from any deployed contract.\n *\n * Note that this is not type safe, and will also have a 1 time overhead of resolving the contract ABI.\n *\n * ```ts\n * import { getContract, resolveMethod } from \"thirdweb\";\n * import { sepolia } from \"thirdweb/chains\";\n * import { useReadContract } from \"thirdweb/react\";\n *\n * const contract = getContract({\n * client,\n * address: \"0x...\",\n * chain: sepolia,\n * });\n *\n * const { data, isLoading } = useReadContract({\n * contract,\n * method: resolveMethod(\"tokenURI\"),\n * params: [1n],\n * });\n * ```\n */\nexport async function readContract(options) {\n const { contract, method, params } = options;\n const resolvePreparedMethod = async () => {\n if (Array.isArray(method)) {\n return method;\n }\n if (isAbiFunction(method)) {\n return prepareMethod(method);\n }\n if (typeof method === \"function\") {\n return prepareMethod(\n // @ts-expect-error - we're sure it's a function\n (await method(contract)));\n }\n // if the method starts with the string `function ` we always will want to try to parse it\n if (typeof method === \"string\" && method.startsWith(\"function \")) {\n // @ts-expect-error - method *is* string in this case\n const abiItem = parseAbiItem(method);\n if (abiItem.type === \"function\") {\n return prepareMethod(abiItem);\n }\n throw new Error(`\"method\" passed is not of type \"function\"`);\n }\n // check if we have a \"abi\" on the contract\n if (contract.abi && contract.abi?.length > 0) {\n // extract the abiFunction from it\n const abiFunction = contract.abi?.find((item) => item.type === \"function\" && item.name === method);\n // if we were able to find it -> return it\n if (abiFunction) {\n return prepareMethod(abiFunction);\n }\n }\n throw new Error(`Could not resolve method \"${method}\".`);\n };\n // resolve in parallel\n const [resolvedPreparedMethod, resolvedParams] = await Promise.all([\n resolvePreparedMethod(),\n typeof params === \"function\" ? params() : params,\n ]);\n let encodedData;\n // if we have no inputs, we know it's just the signature\n if (resolvedPreparedMethod[1].length === 0) {\n encodedData = resolvedPreparedMethod[0];\n }\n else {\n // we do a \"manual\" concat here to avoid the overhead of the \"concatHex\" function\n // we can do this because we know the specific formats of the values\n encodedData = (resolvedPreparedMethod[0] +\n encodeAbiParameters(resolvedPreparedMethod[1], \n // @ts-expect-error - TODO: fix this type issue\n resolvedParams).slice(2));\n }\n const rpcRequest = getRpcClient({\n chain: contract.chain,\n client: contract.client,\n });\n const result = await eth_call(rpcRequest, {\n data: encodedData,\n from: options.from ? getAddress(options.from) : undefined,\n to: contract.address,\n });\n // use the prepared method to decode the result\n const decoded = decodeAbiParameters(resolvedPreparedMethod[2], result);\n if (Array.isArray(decoded) && decoded.length === 1) {\n return decoded[0];\n }\n return decoded;\n}\n//# sourceMappingURL=read-contract.js.map","import { decodeAbiParameters } from \"viem\";\nimport { readContract } from \"../../../../../transaction/read-contract.js\";\nimport { detectMethod } from \"../../../../../utils/bytecode/detectExtension.js\";\nexport const FN_SELECTOR = \"0x3e429396\";\nconst FN_INPUTS = [];\nconst FN_OUTPUTS = [\n {\n components: [\n {\n name: \"implementation\",\n type: \"address\",\n },\n {\n components: [\n {\n name: \"registerInstallationCallback\",\n type: \"bool\",\n },\n {\n name: \"requiredInterfaces\",\n type: \"bytes4[]\",\n },\n {\n name: \"supportedInterfaces\",\n type: \"bytes4[]\",\n },\n {\n components: [\n {\n name: \"selector\",\n type: \"bytes4\",\n },\n ],\n name: \"callbackFunctions\",\n type: \"tuple[]\",\n },\n {\n components: [\n {\n name: \"selector\",\n type: \"bytes4\",\n },\n {\n name: \"permissionBits\",\n type: \"uint256\",\n },\n ],\n name: \"fallbackFunctions\",\n type: \"tuple[]\",\n },\n ],\n name: \"config\",\n type: \"tuple\",\n },\n ],\n type: \"tuple[]\",\n },\n];\n/**\n * Checks if the `getInstalledModules` method is supported by the given contract.\n * @param availableSelectors An array of 4byte function selectors of the contract. You can get this in various ways, such as using \"whatsabi\" or if you have the ABI of the contract available you can use it to generate the selectors.\n * @returns A boolean indicating if the `getInstalledModules` method is supported.\n * @extension MODULES\n * @example\n * ```ts\n * import { isGetInstalledModulesSupported } from \"thirdweb/extensions/modules\";\n * const supported = isGetInstalledModulesSupported([\"0x...\"]);\n * ```\n */\nexport function isGetInstalledModulesSupported(availableSelectors) {\n return detectMethod({\n availableSelectors,\n method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS],\n });\n}\n/**\n * Decodes the result of the getInstalledModules function call.\n * @param result - The hexadecimal result to decode.\n * @returns The decoded result as per the FN_OUTPUTS definition.\n * @extension MODULES\n * @example\n * ```ts\n * import { decodeGetInstalledModulesResult } from \"thirdweb/extensions/modules\";\n * const result = decodeGetInstalledModulesResultResult(\"...\");\n * ```\n */\nexport function decodeGetInstalledModulesResult(result) {\n return decodeAbiParameters(FN_OUTPUTS, result)[0];\n}\n/**\n * Calls the \"getInstalledModules\" function on the contract.\n * @param options - The options for the getInstalledModules function.\n * @returns The parsed result of the function call.\n * @extension MODULES\n * @example\n * ```ts\n * import { getInstalledModules } from \"thirdweb/extensions/modules\";\n *\n * const result = await getInstalledModules({\n * contract,\n * });\n *\n * ```\n */\nexport async function getInstalledModules(options) {\n return readContract({\n contract: options.contract,\n method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS],\n params: [],\n });\n}\n//# sourceMappingURL=getInstalledModules.js.map","export const TransactionTypeMap = {\n eip1559: 1,\n eip2930: 2,\n eip4844: 3,\n eip7702: 4,\n legacy: 0,\n};\n/**\n * Prepares a transaction with the given options.\n * @param options - The options for preparing the transaction.\n * @param info - Additional information about the ABI function.\n * @returns The prepared transaction.\n * @transaction\n * @example\n * ```ts\n * import { prepareTransaction, toWei } from \"thirdweb\";\n * import { ethereum } from \"thirdweb/chains\";\n * const transaction = prepareTransaction({\n * to: \"0x1234567890123456789012345678901234567890\",\n * chain: ethereum,\n * client: thirdwebClient,\n * value: toWei(\"1.0\"),\n * gasPrice: 30n\n * });\n * ```\n */\nexport function prepareTransaction(options, info) {\n if (info) {\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix later\n options.__preparedMethod = info.preparedMethod;\n // biome-ignore lint/suspicious/noExplicitAny: TODO: fix later\n options.__contract = info.contract;\n }\n return options;\n}\n//# sourceMappingURL=prepare-transaction.js.map","import { parseAbiItem, } from \"abitype\";\nimport { encodeAbiParameters } from \"../utils/abi/encodeAbiParameters.js\";\nimport { prepareMethod, } from \"../utils/abi/prepare-method.js\";\nimport { resolvePromisedValue } from \"../utils/promise/resolve-promised-value.js\";\nimport { prepareTransaction, } from \"./prepare-transaction.js\";\nimport { isAbiFunction } from \"./utils.js\";\n/**\n * Prepares a contract call by resolving the ABI function, parameters and encoded data. Optionally specify other properties such as value or gas price.\n * @param options - The options for preparing the contract call.\n * @returns A promise that resolves to the prepared transaction.\n * @transaction\n * @example\n *\n * ### Usage with a human-readable method signature:\n *\n * ```ts\n * import { prepareContractCall } from \"thirdweb\";\n *\n * const transaction = prepareContractCall({\n * contract,\n * method: \"function transfer(address to, uint256 value)\",\n * params: [to, value],\n * });\n * ```\n *\n * ### Usage with explicit gas price and/or value:\n *\n * ```ts\n * import { prepareContractCall } from \"thirdweb\";\n * import { toWei } from \"thirdweb/utils\";\n *\n * const transaction = prepareContractCall({\n * contract,\n * method: \"function transfer(address to, uint256 value)\",\n * params: [to, value],\n * maxFeePerGas: 30n,\n * maxPriorityFeePerGas: 1n,\n * value: toWei(\"0.01\"),\n * });\n * ```\n *\n * ### Usage with ERC20 value:\n *\n * For transactions that transfer ERC20 tokens, you can specify the value as the amount of tokens to transfer.\n *\n * You can use this in conjuction with the [`getApprovalForTransaction`](https://portal.thirdweb.com/references/typescript/v5/getApprovalForTransaction) function to easily create approval transactions for ERC20 tokens.\n *\n * This value will also be read by the react hooks and UI components to present to total cost to the user.\n *\n * ```ts\n * import { prepareContractCall } from \"thirdweb\";\n * import { toWei } from \"thirdweb/utils\";\n *\n * const transaction = prepareContractCall({\n * contract,\n * method: \"function payWithCoin()\",\n * params: [],\n * erc20Value: {\n * tokenAddress: \"0x...\", // the address of the ERC20 token\n * amountWei: toWei(\"0.1\"), // the amount of tokens to transfer in wei\n * },\n * });\n * ```\n *\n * ### Usage with a JSON ABI function object:\n *\n * ```ts\n * import { prepareContractCall } from \"thirdweb\";\n *\n * const transaction = prepareContractCall({\n * contract,\n * method: {\n * name: \"transfer\",\n * type: \"function\",\n * inputs: [\n * { name: \"to\", type: \"address\" },\n * { name: \"value\", type: \"uint256\" },\n * ],\n * outputs: [],\n * stateMutability: \"payable\"\n * },\n * params: [to, value],\n * });\n * ```\n *\n * ### Usage with the ABI defined on the contract:\n *\n * ```ts\n * import { getContract, prepareContractCall } from \"thirdweb\";\n * const contract = getContract({\n * ..., // chain, address, client\n * abi: [...] // ABI with a \"transfer\" method\n * });\n * const transaction = prepareContractCall({\n * contract,\n * method: \"transfer\", // <- this gets inferred from the contract\n * params: [to, value],\n * });\n * ```\n *\n * ### Passing extra call data to the transaction\n * ```ts\n * import { getContract, prepareContractCall } from \"thirdweb\";\n * const contract = getContract({\n * ..., // chain, address, client\n * });\n *\n * const transaction = prepareContractCall({\n * contract,\n * method: \"function transfer(address to, uint256 value)\",\n * params: [...],\n * // The extra call data MUST be encoded to hex before passing\n * extraCallData: \"0x.......\"\n * });\n * ```\n */\nexport function prepareContractCall(options) {\n const { contract, method, params, ...rest } = options;\n const preparedMethodPromise = () => (async () => {\n if (Array.isArray(method)) {\n return method;\n }\n if (isAbiFunction(method)) {\n return prepareMethod(method);\n }\n if (typeof method === \"function\") {\n return prepareMethod(\n // @ts-expect-error - method *is* function in this case\n (await method(contract)));\n }\n // if the method starts with the string `function ` we always will want to try to parse it\n if (typeof method === \"string\" && method.startsWith(\"function \")) {\n // @ts-expect-error - method *is* string in this case\n const abiItem = parseAbiItem(method);\n if (abiItem.type === \"function\") {\n return prepareMethod(abiItem);\n }\n throw new Error(`\"method\" passed is not of type \"function\"`);\n }\n // check if we have a \"abi\" on the contract\n if (contract.abi && contract.abi?.length > 0) {\n // extract the abiFunction from it\n const abiFunction = contract.abi?.find((item) => item.type === \"function\" && item.name === method);\n // if we were able to find it -> return it\n if (abiFunction) {\n return prepareMethod(abiFunction);\n }\n }\n throw new Error(`Could not resolve method \"${method}\".`);\n })();\n return prepareTransaction({\n ...rest,\n chain: contract.chain,\n client: contract.client,\n data: async () => {\n let preparedM;\n if (Array.isArray(method)) {\n preparedM = method;\n }\n else {\n preparedM = await preparedMethodPromise();\n }\n if (preparedM[1].length === 0) {\n // just return the fn sig directly -> no params\n return preparedM[0];\n }\n // we do a \"manual\" concat here to avoid the overhead of the \"concatHex\" function\n // we can do this because we know the specific formats of the values\n return (preparedM[0] +\n encodeAbiParameters(preparedM[1], \n // @ts-expect-error - TODO: fix this type issue\n await resolvePromisedValue(params ?? [])).slice(2));\n },\n // these always inferred from the contract\n to: contract.address,\n }, {\n contract: contract,\n preparedMethod: preparedMethodPromise,\n });\n}\n//# sourceMappingURL=prepare-contract-call.js.map","export function once(fn) {\n let result;\n return () => {\n if (!result) {\n result = fn();\n }\n return result;\n };\n}\n//# sourceMappingURL=once.js.map","import { prepareContractCall } from \"../../../../../transaction/prepare-contract-call.js\";\nimport { encodeAbiParameters } from \"../../../../../utils/abi/encodeAbiParameters.js\";\nimport { detectMethod } from \"../../../../../utils/bytecode/detectExtension.js\";\nimport { once } from \"../../../../../utils/promise/once.js\";\nexport const FN_SELECTOR = \"0x8da798da\";\nconst FN_INPUTS = [\n {\n name: \"moduleContract\",\n type: \"address\",\n },\n {\n name: \"data\",\n type: \"bytes\",\n },\n];\nconst FN_OUTPUTS = [];\n/**\n * Checks if the `installModule` method is supported by the given contract.\n * @param availableSelectors An array of 4byte function selectors of the contract. You can get this in various ways, such as using \"whatsabi\" or if you have the ABI of the contract available you can use it to generate the selectors.\n * @returns A boolean indicating if the `installModule` method is supported.\n * @extension MODULES\n * @example\n * ```ts\n * import { isInstallModuleSupported } from \"thirdweb/extensions/modules\";\n *\n * const supported = isInstallModuleSupported([\"0x...\"]);\n * ```\n */\nexport function isInstallModuleSupported(availableSelectors) {\n return detectMethod({\n availableSelectors,\n method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS],\n });\n}\n/**\n * Encodes the parameters for the \"installModule\" function.\n * @param options - The options for the installModule function.\n * @returns The encoded ABI parameters.\n * @extension MODULES\n * @example\n * ```ts\n * import { encodeInstallModuleParams } from \"thirdweb/extensions/modules\";\n * const result = encodeInstallModuleParams({\n * moduleContract: ...,\n * data: ...,\n * });\n * ```\n */\nexport function encodeInstallModuleParams(options) {\n return encodeAbiParameters(FN_INPUTS, [options.moduleContract, options.data]);\n}\n/**\n * Encodes the \"installModule\" function into a Hex string with its parameters.\n * @param options - The options for the installModule function.\n * @returns The encoded hexadecimal string.\n * @extension MODULES\n * @example\n * ```ts\n * import { encodeInstallModule } from \"thirdweb/extensions/modules\";\n * const result = encodeInstallModule({\n * moduleContract: ...,\n * data: ...,\n * });\n * ```\n */\nexport function encodeInstallModule(options) {\n // we do a \"manual\" concat here to avoid the overhead of the \"concatHex\" function\n // we can do this because we know the specific formats of the values\n return (FN_SELECTOR +\n encodeInstallModuleParams(options).slice(2));\n}\n/**\n * Prepares a transaction to call the \"installModule\" function on the contract.\n * @param options - The options for the \"installModule\" function.\n * @returns A prepared transaction object.\n * @extension MODULES\n * @example\n * ```ts\n * import { sendTransaction } from \"thirdweb\";\n * import { installModule } from \"thirdweb/extensions/modules\";\n *\n * const transaction = installModule({\n * contract,\n * moduleContract: ...,\n * data: ...,\n * overrides: {\n * ...\n * }\n * });\n *\n * // Send the transaction\n * await sendTransaction({ transaction, account });\n * ```\n */\nexport function installModule(options) {\n const asyncOptions = once(async () => {\n return \"asyncParams\" in options ? await options.asyncParams() : options;\n });\n return prepareContractCall({\n accessList: async () => (await asyncOptions()).overrides?.accessList,\n authorizationList: async () => (await asyncOptions()).overrides?.authorizationList,\n contract: options.contract,\n erc20Value: async () => (await asyncOptions()).overrides?.erc20Value,\n extraGas: async () => (await asyncOptions()).overrides?.extraGas,\n gas: async () => (await asyncOptions()).overrides?.gas,\n gasPrice: async () => (await asyncOptions()).overrides?.gasPrice,\n maxFeePerGas: async () => (await asyncOptions()).overrides?.maxFeePerGas,\n maxPriorityFeePerGas: async () => (await asyncOptions()).overrides?.maxPriorityFeePerGas,\n method: [FN_SELECTOR, FN_INPUTS, FN_OUTPUTS],\n nonce: async () => (await asyncOptions()).overrides?.nonce,\n params: async () => {\n const resolvedOptions = await asyncOptions();\n return [resolvedOptions.moduleContract, resolvedOptions.data];\n },\n value: async () => (await asyncOptions()).overrides?.value,\n });\n}\n//# sourceMappingURL=installModule.js.map","import { InvalidDefinitionTypeError, } from '../../errors/abi.js';\nexport function formatAbiItem(abiItem, { includeName = false } = {}) {\n if (abiItem.type !== 'function' &&\n abiItem.type !== 'event' &&\n abiItem.type !== 'error')\n throw new InvalidDefinitionTypeError(abiItem.type);\n return `${abiItem.name}(${formatAbiParams(abiItem.inputs, { includeName })})`;\n}\nexport function formatAbiParams(params, { includeName = false } = {}) {\n if (!params)\n return '';\n return params\n .map((param) => formatAbiParam(param, { includeName }))\n .join(includeName ? ', ' : ',');\n}\nfunction formatAbiParam(param, { includeName }) {\n if (param.type.startsWith('tuple')) {\n return `(${formatAbiParams(param.components, { includeName })})${param.type.slice('tuple'.length)}`;\n }\n return param.type + (includeName && param.name ? ` ${param.name}` : '');\n}\n//# sourceMappingURL=formatAbiItem.js.map","export function isHex(value, { strict = true } = {}) {\n if (!value)\n return false;\n if (typeof value !== 'string')\n return false;\n return strict ? /^0x[0-9a-fA-F]*$/.test(value) : value.startsWith('0x');\n}\n//# sourceMappingURL=isHex.js.map","import { isHex } from './isHex.js';\n/**\n * @description Retrieves the size of the value (in bytes).\n *\n * @param value The value (hex or byte array) to retrieve the size of.\n * @returns The size of the value (in bytes).\n */\nexport function size(value) {\n if (isHex(value, { strict: false }))\n return Math.ceil((value.length - 2) / 2);\n return value.length;\n}\n//# sourceMappingURL=size.js.map","export const version = '2.46.2';\n//# sourceMappingURL=version.js.map","import { version } from './version.js';\nlet errorConfig = {\n getDocsUrl: ({ docsBaseUrl, docsPath = '', docsSlug, }) => docsPath\n ? `${docsBaseUrl ?? 'https://viem.sh'}${docsPath}${docsSlug ? `#${docsSlug}` : ''}`\n : undefined,\n version: `viem@${version}`,\n};\nexport function setErrorConfig(config) {\n errorConfig = config;\n}\nexport class BaseError extends Error {\n constructor(shortMessage, args = {}) {\n const details = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.details;\n if (args.cause?.message)\n return args.cause.message;\n return args.details;\n })();\n const docsPath = (() => {\n if (args.cause instanceof BaseError)\n return args.cause.docsPath || args.docsPath;\n return args.docsPath;\n })();\n const docsUrl = errorConfig.getDocsUrl?.({ ...args, docsPath });\n const message = [\n shortMessage || 'An error occurred.',\n '',\n ...(args.metaMessages ? [...args.metaMessages, ''] : []),\n ...(docsUrl ? [`Docs: ${docsUrl}`] : []),\n ...(details ? [`Details: ${details}`] : []),\n ...(errorConfig.version ? [`Version: ${errorConfig.version}`] : []),\n ].join('\\n');\n super(message, args.cause ? { cause: args.cause } : undefined);\n Object.defineProperty(this, \"details\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"docsPath\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"metaMessages\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"shortMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"version\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'BaseError'\n });\n this.details = details;\n this.docsPath = docsPath;\n this.metaMessages = args.metaMessages;\n this.name = args.name ?? this.name;\n this.shortMessage = shortMessage;\n this.version = version;\n }\n walk(fn) {\n return walk(this, fn);\n }\n}\nfunction walk(err, fn) {\n if (fn?.(err))\n return err;\n if (err &&\n typeof err === 'object' &&\n 'cause' in err &&\n err.cause !== undefined)\n return walk(err.cause, fn);\n return fn ? null : err;\n}\n//# sourceMappingURL=base.js.map","import { formatAbiItem, formatAbiParams } from '../utils/abi/formatAbiItem.js';\nimport { size } from '../utils/data/size.js';\nimport { BaseError } from './base.js';\nexport class AbiConstructorNotFoundError extends BaseError {\n constructor({ docsPath }) {\n super([\n 'A constructor was not found on the ABI.',\n 'Make sure you are using the correct ABI and that the constructor exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiConstructorNotFoundError',\n });\n }\n}\nexport class AbiConstructorParamsNotFoundError extends BaseError {\n constructor({ docsPath }) {\n super([\n 'Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.',\n 'Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiConstructorParamsNotFoundError',\n });\n }\n}\nexport class AbiDecodingDataSizeInvalidError extends BaseError {\n constructor({ data, size }) {\n super([\n `Data size of ${size} bytes is invalid.`,\n 'Size must be in increments of 32 bytes (size % 32 === 0).',\n ].join('\\n'), {\n metaMessages: [`Data: ${data} (${size} bytes)`],\n name: 'AbiDecodingDataSizeInvalidError',\n });\n }\n}\nexport class AbiDecodingDataSizeTooSmallError extends BaseError {\n constructor({ data, params, size, }) {\n super([`Data size of ${size} bytes is too small for given parameters.`].join('\\n'), {\n metaMessages: [\n `Params: (${formatAbiParams(params, { includeName: true })})`,\n `Data: ${data} (${size} bytes)`,\n ],\n name: 'AbiDecodingDataSizeTooSmallError',\n });\n Object.defineProperty(this, \"data\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"params\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"size\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.data = data;\n this.params = params;\n this.size = size;\n }\n}\nexport class AbiDecodingZeroDataError extends BaseError {\n constructor() {\n super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n name: 'AbiDecodingZeroDataError',\n });\n }\n}\nexport class AbiEncodingArrayLengthMismatchError extends BaseError {\n constructor({ expectedLength, givenLength, type, }) {\n super([\n `ABI encoding array length mismatch for type ${type}.`,\n `Expected length: ${expectedLength}`,\n `Given length: ${givenLength}`,\n ].join('\\n'), { name: 'AbiEncodingArrayLengthMismatchError' });\n }\n}\nexport class AbiEncodingBytesSizeMismatchError extends BaseError {\n constructor({ expectedSize, value }) {\n super(`Size of bytes \"${value}\" (bytes${size(value)}) does not match expected size (bytes${expectedSize}).`, { name: 'AbiEncodingBytesSizeMismatchError' });\n }\n}\nexport class AbiEncodingLengthMismatchError extends BaseError {\n constructor({ expectedLength, givenLength, }) {\n super([\n 'ABI encoding params/values length mismatch.',\n `Expected length (params): ${expectedLength}`,\n `Given length (values): ${givenLength}`,\n ].join('\\n'), { name: 'AbiEncodingLengthMismatchError' });\n }\n}\nexport class AbiErrorInputsNotFoundError extends BaseError {\n constructor(errorName, { docsPath }) {\n super([\n `Arguments (\\`args\\`) were provided to \"${errorName}\", but \"${errorName}\" on the ABI does not contain any parameters (\\`inputs\\`).`,\n 'Cannot encode error result without knowing what the parameter types are.',\n 'Make sure you are using the correct ABI and that the inputs exist on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiErrorInputsNotFoundError',\n });\n }\n}\nexport class AbiErrorNotFoundError extends BaseError {\n constructor(errorName, { docsPath } = {}) {\n super([\n `Error ${errorName ? `\"${errorName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the error exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiErrorNotFoundError',\n });\n }\n}\nexport class AbiErrorSignatureNotFoundError extends BaseError {\n constructor(signature, { docsPath }) {\n super([\n `Encoded error signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the error exists on it.',\n `You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${signature}.`,\n ].join('\\n'), {\n docsPath,\n name: 'AbiErrorSignatureNotFoundError',\n });\n Object.defineProperty(this, \"signature\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.signature = signature;\n }\n}\nexport class AbiEventSignatureEmptyTopicsError extends BaseError {\n constructor({ docsPath }) {\n super('Cannot extract event signature from empty topics.', {\n docsPath,\n name: 'AbiEventSignatureEmptyTopicsError',\n });\n }\n}\nexport class AbiEventSignatureNotFoundError extends BaseError {\n constructor(signature, { docsPath }) {\n super([\n `Encoded event signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the event exists on it.',\n `You can look up the signature here: https://4byte.sourcify.dev/?q=${signature}.`,\n ].join('\\n'), {\n docsPath,\n name: 'AbiEventSignatureNotFoundError',\n });\n }\n}\nexport class AbiEventNotFoundError extends BaseError {\n constructor(eventName, { docsPath } = {}) {\n super([\n `Event ${eventName ? `\"${eventName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the event exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiEventNotFoundError',\n });\n }\n}\nexport class AbiFunctionNotFoundError extends BaseError {\n constructor(functionName, { docsPath } = {}) {\n super([\n `Function ${functionName ? `\"${functionName}\" ` : ''}not found on ABI.`,\n 'Make sure you are using the correct ABI and that the function exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiFunctionNotFoundError',\n });\n }\n}\nexport class AbiFunctionOutputsNotFoundError extends BaseError {\n constructor(functionName, { docsPath }) {\n super([\n `Function \"${functionName}\" does not contain any \\`outputs\\` on ABI.`,\n 'Cannot decode function result without knowing what the parameter types are.',\n 'Make sure you are using the correct ABI and that the function exists on it.',\n ].join('\\n'), {\n docsPath,\n name: 'AbiFunctionOutputsNotFoundError',\n });\n }\n}\nexport class AbiFunctionSignatureNotFoundError extends BaseError {\n constructor(signature, { docsPath }) {\n super([\n `Encoded function signature \"${signature}\" not found on ABI.`,\n 'Make sure you are using the correct ABI and that the function exists on it.',\n `You can look up the signature here: https://4byte.sourcify.dev/?q=${signature}.`,\n ].join('\\n'), {\n docsPath,\n name: 'AbiFunctionSignatureNotFoundError',\n });\n }\n}\nexport class AbiItemAmbiguityError extends BaseError {\n constructor(x, y) {\n super('Found ambiguous types in overloaded ABI items.', {\n metaMessages: [\n `\\`${x.type}\\` in \\`${formatAbiItem(x.abiItem)}\\`, and`,\n `\\`${y.type}\\` in \\`${formatAbiItem(y.abiItem)}\\``,\n '',\n 'These types encode differently and cannot be distinguished at runtime.',\n 'Remove one of the ambiguous items in the ABI.',\n ],\n name: 'AbiItemAmbiguityError',\n });\n }\n}\nexport class BytesSizeMismatchError extends BaseError {\n constructor({ expectedSize, givenSize, }) {\n super(`Expected bytes${expectedSize}, got bytes${givenSize}.`, {\n name: 'BytesSizeMismatchError',\n });\n }\n}\nexport class DecodeLogDataMismatch extends BaseError {\n constructor({ abiItem, data, params, size, }) {\n super([\n `Data size of ${size} bytes is too small for non-indexed event parameters.`,\n ].join('\\n'), {\n metaMessages: [\n `Params: (${formatAbiParams(params, { includeName: true })})`,\n `Data: ${data} (${size} bytes)`,\n ],\n name: 'DecodeLogDataMismatch',\n });\n Object.defineProperty(this, \"abiItem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"data\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"params\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"size\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.abiItem = abiItem;\n this.data = data;\n this.params = params;\n this.size = size;\n }\n}\nexport class DecodeLogTopicsMismatch extends BaseError {\n constructor({ abiItem, param, }) {\n super([\n `Expected a topic for indexed event parameter${param.name ? ` \"${param.name}\"` : ''} on event \"${formatAbiItem(abiItem, { includeName: true })}\".`,\n ].join('\\n'), { name: 'DecodeLogTopicsMismatch' });\n Object.defineProperty(this, \"abiItem\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.abiItem = abiItem;\n }\n}\nexport class InvalidAbiEncodingTypeError extends BaseError {\n constructor(type, { docsPath }) {\n super([\n `Type \"${type}\" is not a valid encoding type.`,\n 'Please provide a valid ABI type.',\n ].join('\\n'), { docsPath, name: 'InvalidAbiEncodingType' });\n }\n}\nexport class InvalidAbiDecodingTypeError extends BaseError {\n constructor(type, { docsPath }) {\n super([\n `Type \"${type}\" is not a valid decoding type.`,\n 'Please provide a valid ABI type.',\n ].join('\\n'), { docsPath, name: 'InvalidAbiDecodingType' });\n }\n}\nexport class InvalidArrayError extends BaseError {\n constructor(value) {\n super([`Value \"${value}\" is not a valid array.`].join('\\n'), {\n name: 'InvalidArrayError',\n });\n }\n}\nexport class InvalidDefinitionTypeError extends BaseError {\n constructor(type) {\n super([\n `\"${type}\" is not a valid definition type.`,\n 'Valid types: \"function\", \"event\", \"error\"',\n ].join('\\n'), { name: 'InvalidDefinitionTypeError' });\n }\n}\nexport class UnsupportedPackedAbiType extends BaseError {\n constructor(type) {\n super(`Type \"${type}\" is not supported for packed encoding.`, {\n name: 'UnsupportedPackedAbiType',\n });\n }\n}\n//# sourceMappingURL=abi.js.map","import { BaseError } from './base.js';\nexport class SliceOffsetOutOfBoundsError extends BaseError {\n constructor({ offset, position, size, }) {\n super(`Slice ${position === 'start' ? 'starting' : 'ending'} at offset \"${offset}\" is out-of-bounds (size: ${size}).`, { name: 'SliceOffsetOutOfBoundsError' });\n }\n}\nexport class SizeExceedsPaddingSizeError extends BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} size (${size}) exceeds padding size (${targetSize}).`, { name: 'SizeExceedsPaddingSizeError' });\n }\n}\nexport class InvalidBytesLengthError extends BaseError {\n constructor({ size, targetSize, type, }) {\n super(`${type.charAt(0).toUpperCase()}${type\n .slice(1)\n .toLowerCase()} is expected to be ${targetSize} ${type} long, but is ${size} ${type} long.`, { name: 'InvalidBytesLengthError' });\n }\n}\n//# sourceMappingURL=data.js.map","import { SizeExceedsPaddingSizeError, } from '../../errors/data.js';\nexport function pad(hexOrBytes, { dir, size = 32 } = {}) {\n if (typeof hexOrBytes === 'string')\n return padHex(hexOrBytes, { dir, size });\n return padBytes(hexOrBytes, { dir, size });\n}\nexport function padHex(hex_, { dir, size = 32 } = {}) {\n if (size === null)\n return hex_;\n const hex = hex_.replace('0x', '');\n if (hex.length > size * 2)\n throw new SizeExceedsPaddingSizeError({\n size: Math.ceil(hex.length / 2),\n targetSize: size,\n type: 'hex',\n });\n return `0x${hex[dir === 'right' ? 'padEnd' : 'padStart'](size * 2, '0')}`;\n}\nexport function padBytes(bytes, { dir, size = 32 } = {}) {\n if (size === null)\n return bytes;\n if (bytes.length > size)\n throw new SizeExceedsPaddingSizeError({\n size: bytes.length,\n targetSize: size,\n type: 'bytes',\n });\n const paddedBytes = new Uint8Array(size);\n for (let i = 0; i < size; i++) {\n const padEnd = dir === 'right';\n paddedBytes[padEnd ? i : size - i - 1] =\n bytes[padEnd ? i : bytes.length - i - 1];\n }\n return paddedBytes;\n}\n//# sourceMappingURL=pad.js.map","import { BaseError } from './base.js';\nexport class IntegerOutOfRangeError extends BaseError {\n constructor({ max, min, signed, size, value, }) {\n super(`Number \"${value}\" is not in safe ${size ? `${size * 8}-bit ${signed ? 'signed' : 'unsigned'} ` : ''}integer range ${max ? `(${min} to ${max})` : `(above ${min})`}`, { name: 'IntegerOutOfRangeError' });\n }\n}\nexport class InvalidBytesBooleanError extends BaseError {\n constructor(bytes) {\n super(`Bytes value \"${bytes}\" is not a valid boolean. The bytes array must contain a single byte of either a 0 or 1 value.`, {\n name: 'InvalidBytesBooleanError',\n });\n }\n}\nexport class InvalidHexBooleanError extends BaseError {\n constructor(hex) {\n super(`Hex value \"${hex}\" is not a valid boolean. The hex value must be \"0x0\" (false) or \"0x1\" (true).`, { name: 'InvalidHexBooleanError' });\n }\n}\nexport class InvalidHexValueError extends BaseError {\n constructor(value) {\n super(`Hex value \"${value}\" is an odd length (${value.length}). It must be an even length.`, { name: 'InvalidHexValueError' });\n }\n}\nexport class SizeOverflowError extends BaseError {\n constructor({ givenSize, maxSize }) {\n super(`Size cannot exceed ${maxSize} bytes. Given size: ${givenSize} bytes.`, { name: 'SizeOverflowError' });\n }\n}\n//# sourceMappingURL=encoding.js.map","export function trim(hexOrBytes, { dir = 'left' } = {}) {\n let data = typeof hexOrBytes === 'string' ? hexOrBytes.replace('0x', '') : hexOrBytes;\n let sliceLength = 0;\n for (let i = 0; i < data.length - 1; i++) {\n if (data[dir === 'left' ? i : data.length - i - 1].toString() === '0')\n sliceLength++;\n else\n break;\n }\n data =\n dir === 'left'\n ? data.slice(sliceLength)\n : data.slice(0, data.length - sliceLength);\n if (typeof hexOrBytes === 'string') {\n if (data.length === 1 && dir === 'right')\n data = `${data}0`;\n return `0x${data.length % 2 === 1 ? `0${data}` : data}`;\n }\n return data;\n}\n//# sourceMappingURL=trim.js.map","import { IntegerOutOfRangeError, InvalidHexBooleanError, SizeOverflowError, } from '../../errors/encoding.js';\nimport { size as size_ } from '../data/size.js';\nimport { trim } from '../data/trim.js';\nimport { hexToBytes } from './toBytes.js';\nexport function assertSize(hexOrBytes, { size }) {\n if (size_(hexOrBytes) > size)\n throw new SizeOverflowError({\n givenSize: size_(hexOrBytes),\n maxSize: size,\n });\n}\n/**\n * Decodes a hex string into a string, number, bigint, boolean, or byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex\n * - Example: https://viem.sh/docs/utilities/fromHex#usage\n *\n * @param hex Hex string to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x1a4', 'number')\n * // 420\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c6421', 'string')\n * // 'Hello world'\n *\n * @example\n * import { fromHex } from 'viem'\n * const data = fromHex('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * to: 'string'\n * })\n * // 'Hello world'\n */\nexport function fromHex(hex, toOrOpts) {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts;\n const to = opts.to;\n if (to === 'number')\n return hexToNumber(hex, opts);\n if (to === 'bigint')\n return hexToBigInt(hex, opts);\n if (to === 'string')\n return hexToString(hex, opts);\n if (to === 'boolean')\n return hexToBool(hex, opts);\n return hexToBytes(hex, opts);\n}\n/**\n * Decodes a hex value into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobigint\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x1a4', { signed: true })\n * // 420n\n *\n * @example\n * import { hexToBigInt } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420n\n */\nexport function hexToBigInt(hex, opts = {}) {\n const { signed } = opts;\n if (opts.size)\n assertSize(hex, { size: opts.size });\n const value = BigInt(hex);\n if (!signed)\n return value;\n const size = (hex.length - 2) / 2;\n const max = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n if (value <= max)\n return value;\n return value - BigInt(`0x${'f'.padStart(size * 2, 'f')}`) - 1n;\n}\n/**\n * Decodes a hex value into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextobool\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x01')\n * // true\n *\n * @example\n * import { hexToBool } from 'viem'\n * const data = hexToBool('0x0000000000000000000000000000000000000000000000000000000000000001', { size: 32 })\n * // true\n */\nexport function hexToBool(hex_, opts = {}) {\n let hex = hex_;\n if (opts.size) {\n assertSize(hex, { size: opts.size });\n hex = trim(hex);\n }\n if (trim(hex) === '0x00')\n return false;\n if (trim(hex) === '0x01')\n return true;\n throw new InvalidHexBooleanError(hex);\n}\n/**\n * Decodes a hex string into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextonumber\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToNumber('0x1a4')\n * // 420\n *\n * @example\n * import { hexToNumber } from 'viem'\n * const data = hexToBigInt('0x00000000000000000000000000000000000000000000000000000000000001a4', { size: 32 })\n * // 420\n */\nexport function hexToNumber(hex, opts = {}) {\n const value = hexToBigInt(hex, opts);\n const number = Number(value);\n if (!Number.isSafeInteger(number))\n throw new IntegerOutOfRangeError({\n max: `${Number.MAX_SAFE_INTEGER}`,\n min: `${Number.MIN_SAFE_INTEGER}`,\n signed: opts.signed,\n size: opts.size,\n value: `${value}n`,\n });\n return number;\n}\n/**\n * Decodes a hex value into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromHex#hextostring\n *\n * @param hex Hex value to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c6421')\n * // 'Hello world!'\n *\n * @example\n * import { hexToString } from 'viem'\n * const data = hexToString('0x48656c6c6f20576f726c64210000000000000000000000000000000000000000', {\n * size: 32,\n * })\n * // 'Hello world'\n */\nexport function hexToString(hex, opts = {}) {\n let bytes = hexToBytes(hex);\n if (opts.size) {\n assertSize(bytes, { size: opts.size });\n bytes = trim(bytes, { dir: 'right' });\n }\n return new TextDecoder().decode(bytes);\n}\n//# sourceMappingURL=fromHex.js.map","import { IntegerOutOfRangeError, } from '../../errors/encoding.js';\nimport { pad } from '../data/pad.js';\nimport { assertSize } from './fromHex.js';\nconst hexes = /*#__PURE__*/ Array.from({ length: 256 }, (_v, i) => i.toString(16).padStart(2, '0'));\n/**\n * Encodes a string, number, bigint, or ByteArray into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex\n * - Example: https://viem.sh/docs/utilities/toHex#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world')\n * // '0x48656c6c6f20776f726c6421'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex(420)\n * // '0x1a4'\n *\n * @example\n * import { toHex } from 'viem'\n * const data = toHex('Hello world', { size: 32 })\n * // '0x48656c6c6f20776f726c64210000000000000000000000000000000000000000'\n */\nexport function toHex(value, opts = {}) {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToHex(value, opts);\n if (typeof value === 'string') {\n return stringToHex(value, opts);\n }\n if (typeof value === 'boolean')\n return boolToHex(value, opts);\n return bytesToHex(value, opts);\n}\n/**\n * Encodes a boolean into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#booltohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true)\n * // '0x1'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(false)\n * // '0x0'\n *\n * @example\n * import { boolToHex } from 'viem'\n * const data = boolToHex(true, { size: 32 })\n * // '0x0000000000000000000000000000000000000000000000000000000000000001'\n */\nexport function boolToHex(value, opts = {}) {\n const hex = `0x${Number(value)}`;\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size });\n return pad(hex, { size: opts.size });\n }\n return hex;\n}\n/**\n * Encodes a bytes array into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#bytestohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { bytesToHex } from 'viem'\n * const data = bytesToHex(Uint8Array.from([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]), { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function bytesToHex(value, opts = {}) {\n let string = '';\n for (let i = 0; i < value.length; i++) {\n string += hexes[value[i]];\n }\n const hex = `0x${string}`;\n if (typeof opts.size === 'number') {\n assertSize(hex, { size: opts.size });\n return pad(hex, { dir: 'right', size: opts.size });\n }\n return hex;\n}\n/**\n * Encodes a number or bigint into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#numbertohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420)\n * // '0x1a4'\n *\n * @example\n * import { numberToHex } from 'viem'\n * const data = numberToHex(420, { size: 32 })\n * // '0x00000000000000000000000000000000000000000000000000000000000001a4'\n */\nexport function numberToHex(value_, opts = {}) {\n const { signed, size } = opts;\n const value = BigInt(value_);\n let maxValue;\n if (size) {\n if (signed)\n maxValue = (1n << (BigInt(size) * 8n - 1n)) - 1n;\n else\n maxValue = 2n ** (BigInt(size) * 8n) - 1n;\n }\n else if (typeof value_ === 'number') {\n maxValue = BigInt(Number.MAX_SAFE_INTEGER);\n }\n const minValue = typeof maxValue === 'bigint' && signed ? -maxValue - 1n : 0;\n if ((maxValue && value > maxValue) || value < minValue) {\n const suffix = typeof value_ === 'bigint' ? 'n' : '';\n throw new IntegerOutOfRangeError({\n max: maxValue ? `${maxValue}${suffix}` : undefined,\n min: `${minValue}${suffix}`,\n signed,\n size,\n value: `${value_}${suffix}`,\n });\n }\n const hex = `0x${(signed && value < 0 ? (1n << BigInt(size * 8)) + BigInt(value) : value).toString(16)}`;\n if (size)\n return pad(hex, { size });\n return hex;\n}\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Encodes a UTF-8 string into a hex string\n *\n * - Docs: https://viem.sh/docs/utilities/toHex#stringtohex\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Hex value.\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!')\n * // '0x48656c6c6f20576f726c6421'\n *\n * @example\n * import { stringToHex } from 'viem'\n * const data = stringToHex('Hello World!', { size: 32 })\n * // '0x48656c6c6f20576f726c64210000000000000000000000000000000000000000'\n */\nexport function stringToHex(value_, opts = {}) {\n const value = encoder.encode(value_);\n return bytesToHex(value, opts);\n}\n//# sourceMappingURL=toHex.js.map","import { BaseError } from '../../errors/base.js';\nimport { isHex } from '../data/isHex.js';\nimport { pad } from '../data/pad.js';\nimport { assertSize } from './fromHex.js';\nimport { numberToHex, } from './toHex.js';\nconst encoder = /*#__PURE__*/ new TextEncoder();\n/**\n * Encodes a UTF-8 string, hex value, bigint, number or boolean to a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes\n * - Example: https://viem.sh/docs/utilities/toBytes#usage\n *\n * @param value Value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes('Hello world')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { toBytes } from 'viem'\n * const data = toBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function toBytes(value, opts = {}) {\n if (typeof value === 'number' || typeof value === 'bigint')\n return numberToBytes(value, opts);\n if (typeof value === 'boolean')\n return boolToBytes(value, opts);\n if (isHex(value))\n return hexToBytes(value, opts);\n return stringToBytes(value, opts);\n}\n/**\n * Encodes a boolean into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#booltobytes\n *\n * @param value Boolean value to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true)\n * // Uint8Array([1])\n *\n * @example\n * import { boolToBytes } from 'viem'\n * const data = boolToBytes(true, { size: 32 })\n * // Uint8Array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])\n */\nexport function boolToBytes(value, opts = {}) {\n const bytes = new Uint8Array(1);\n bytes[0] = Number(value);\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size });\n return pad(bytes, { size: opts.size });\n }\n return bytes;\n}\n// We use very optimized technique to convert hex string to byte array\nconst charCodeMap = {\n zero: 48,\n nine: 57,\n A: 65,\n F: 70,\n a: 97,\n f: 102,\n};\nfunction charCodeToBase16(char) {\n if (char >= charCodeMap.zero && char <= charCodeMap.nine)\n return char - charCodeMap.zero;\n if (char >= charCodeMap.A && char <= charCodeMap.F)\n return char - (charCodeMap.A - 10);\n if (char >= charCodeMap.a && char <= charCodeMap.f)\n return char - (charCodeMap.a - 10);\n return undefined;\n}\n/**\n * Encodes a hex string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#hextobytes\n *\n * @param hex Hex string to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33])\n *\n * @example\n * import { hexToBytes } from 'viem'\n * const data = hexToBytes('0x48656c6c6f20776f726c6421', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function hexToBytes(hex_, opts = {}) {\n let hex = hex_;\n if (opts.size) {\n assertSize(hex, { size: opts.size });\n hex = pad(hex, { dir: 'right', size: opts.size });\n }\n let hexString = hex.slice(2);\n if (hexString.length % 2)\n hexString = `0${hexString}`;\n const length = hexString.length / 2;\n const bytes = new Uint8Array(length);\n for (let index = 0, j = 0; index < length; index++) {\n const nibbleLeft = charCodeToBase16(hexString.charCodeAt(j++));\n const nibbleRight = charCodeToBase16(hexString.charCodeAt(j++));\n if (nibbleLeft === undefined || nibbleRight === undefined) {\n throw new BaseError(`Invalid byte sequence (\"${hexString[j - 2]}${hexString[j - 1]}\" in \"${hexString}\").`);\n }\n bytes[index] = nibbleLeft * 16 + nibbleRight;\n }\n return bytes;\n}\n/**\n * Encodes a number into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#numbertobytes\n *\n * @param value Number to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420)\n * // Uint8Array([1, 164])\n *\n * @example\n * import { numberToBytes } from 'viem'\n * const data = numberToBytes(420, { size: 4 })\n * // Uint8Array([0, 0, 1, 164])\n */\nexport function numberToBytes(value, opts) {\n const hex = numberToHex(value, opts);\n return hexToBytes(hex);\n}\n/**\n * Encodes a UTF-8 string into a byte array.\n *\n * - Docs: https://viem.sh/docs/utilities/toBytes#stringtobytes\n *\n * @param value String to encode.\n * @param opts Options.\n * @returns Byte array value.\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!')\n * // Uint8Array([72, 101, 108, 108, 111, 32, 119, 111, 114, 108, 100, 33])\n *\n * @example\n * import { stringToBytes } from 'viem'\n * const data = stringToBytes('Hello world!', { size: 32 })\n * // Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])\n */\nexport function stringToBytes(value, opts = {}) {\n const bytes = encoder.encode(value);\n if (typeof opts.size === 'number') {\n assertSize(bytes, { size: opts.size });\n return pad(bytes, { dir: 'right', size: opts.size });\n }\n return bytes;\n}\n//# sourceMappingURL=toBytes.js.map","import { keccak_256 } from '@noble/hashes/sha3';\nimport { isHex } from '../data/isHex.js';\nimport { toBytes } from '../encoding/toBytes.js';\nimport { toHex } from '../encoding/toHex.js';\nexport function keccak256(value, to_) {\n const to = to_ || 'hex';\n const bytes = keccak_256(isHex(value, { strict: false }) ? toBytes(value) : value);\n if (to === 'bytes')\n return bytes;\n return toHex(bytes);\n}\n//# sourceMappingURL=keccak256.js.map","import { BaseError } from './base.js';\nexport class InvalidAddressError extends BaseError {\n constructor({ address }) {\n super(`Address \"${address}\" is invalid.`, {\n metaMessages: [\n '- Address must be a hex value of 20 bytes (40 hex characters).',\n '- Address must match its checksum counterpart.',\n ],\n name: 'InvalidAddressError',\n });\n }\n}\n//# sourceMappingURL=address.js.map","/**\n * Map with a LRU (Least recently used) policy.\n *\n * @link https://en.wikipedia.org/wiki/Cache_replacement_policies#LRU\n */\nexport class LruMap extends Map {\n constructor(size) {\n super();\n Object.defineProperty(this, \"maxSize\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.maxSize = size;\n }\n get(key) {\n const value = super.get(key);\n if (super.has(key) && value !== undefined) {\n this.delete(key);\n super.set(key, value);\n }\n return value;\n }\n set(key, value) {\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = this.keys().next().value;\n if (firstKey)\n this.delete(firstKey);\n }\n return this;\n }\n}\n//# sourceMappingURL=lru.js.map","import { InvalidAddressError } from '../../errors/address.js';\nimport { stringToBytes, } from '../encoding/toBytes.js';\nimport { keccak256 } from '../hash/keccak256.js';\nimport { LruMap } from '../lru.js';\nimport { isAddress } from './isAddress.js';\nconst checksumAddressCache = /*#__PURE__*/ new LruMap(8192);\nexport function checksumAddress(address_, \n/**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\nchainId) {\n if (checksumAddressCache.has(`${address_}.${chainId}`))\n return checksumAddressCache.get(`${address_}.${chainId}`);\n const hexAddress = chainId\n ? `${chainId}${address_.toLowerCase()}`\n : address_.substring(2).toLowerCase();\n const hash = keccak256(stringToBytes(hexAddress), 'bytes');\n const address = (chainId ? hexAddress.substring(`${chainId}0x`.length) : hexAddress).split('');\n for (let i = 0; i < 40; i += 2) {\n if (hash[i >> 1] >> 4 >= 8 && address[i]) {\n address[i] = address[i].toUpperCase();\n }\n if ((hash[i >> 1] & 0x0f) >= 8 && address[i + 1]) {\n address[i + 1] = address[i + 1].toUpperCase();\n }\n }\n const result = `0x${address.join('')}`;\n checksumAddressCache.set(`${address_}.${chainId}`, result);\n return result;\n}\nexport function getAddress(address, \n/**\n * Warning: EIP-1191 checksum addresses are generally not backwards compatible with the\n * wider Ethereum ecosystem, meaning it will break when validated against an application/tool\n * that relies on EIP-55 checksum encoding (checksum without chainId).\n *\n * It is highly recommended to not use this feature unless you\n * know what you are doing.\n *\n * See more: https://github.com/ethereum/EIPs/issues/1121\n */\nchainId) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address });\n return checksumAddress(address, chainId);\n}\n//# sourceMappingURL=getAddress.js.map","import { LruMap } from '../lru.js';\nimport { checksumAddress } from './getAddress.js';\nconst addressRegex = /^0x[a-fA-F0-9]{40}$/;\n/** @internal */\nexport const isAddressCache = /*#__PURE__*/ new LruMap(8192);\nexport function isAddress(address, options) {\n const { strict = true } = options ?? {};\n const cacheKey = `${address}.${strict}`;\n if (isAddressCache.has(cacheKey))\n return isAddressCache.get(cacheKey);\n const result = (() => {\n if (!addressRegex.test(address))\n return false;\n if (address.toLowerCase() === address)\n return true;\n if (strict)\n return checksumAddress(address) === address;\n return true;\n })();\n isAddressCache.set(cacheKey, result);\n return result;\n}\n//# sourceMappingURL=isAddress.js.map","export function concat(values) {\n if (typeof values[0] === 'string')\n return concatHex(values);\n return concatBytes(values);\n}\nexport function concatBytes(values) {\n let length = 0;\n for (const arr of values) {\n length += arr.length;\n }\n const result = new Uint8Array(length);\n let offset = 0;\n for (const arr of values) {\n result.set(arr, offset);\n offset += arr.length;\n }\n return result;\n}\nexport function concatHex(values) {\n return `0x${values.reduce((acc, x) => acc + x.replace('0x', ''), '')}`;\n}\n//# sourceMappingURL=concat.js.map","import { SliceOffsetOutOfBoundsError, } from '../../errors/data.js';\nimport { isHex } from './isHex.js';\nimport { size } from './size.js';\n/**\n * @description Returns a section of the hex or byte array given a start/end bytes offset.\n *\n * @param value The hex or byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function slice(value, start, end, { strict } = {}) {\n if (isHex(value, { strict: false }))\n return sliceHex(value, start, end, {\n strict,\n });\n return sliceBytes(value, start, end, {\n strict,\n });\n}\nfunction assertStartOffset(value, start) {\n if (typeof start === 'number' && start > 0 && start > size(value) - 1)\n throw new SliceOffsetOutOfBoundsError({\n offset: start,\n position: 'start',\n size: size(value),\n });\n}\nfunction assertEndOffset(value, start, end) {\n if (typeof start === 'number' &&\n typeof end === 'number' &&\n size(value) !== end - start) {\n throw new SliceOffsetOutOfBoundsError({\n offset: end,\n position: 'end',\n size: size(value),\n });\n }\n}\n/**\n * @description Returns a section of the byte array given a start/end bytes offset.\n *\n * @param value The byte array to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceBytes(value_, start, end, { strict } = {}) {\n assertStartOffset(value_, start);\n const value = value_.slice(start, end);\n if (strict)\n assertEndOffset(value, start, end);\n return value;\n}\n/**\n * @description Returns a section of the hex value given a start/end bytes offset.\n *\n * @param value The hex value to slice.\n * @param start The start offset (in bytes).\n * @param end The end offset (in bytes).\n */\nexport function sliceHex(value_, start, end, { strict } = {}) {\n assertStartOffset(value_, start);\n const value = `0x${value_\n .replace('0x', '')\n .slice((start ?? 0) * 2, (end ?? value_.length) * 2)}`;\n if (strict)\n assertEndOffset(value, start, end);\n return value;\n}\n//# sourceMappingURL=slice.js.map","export const arrayRegex = /^(.*)\\[([0-9]*)\\]$/;\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// `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n// https://regexr.com/6v8hp\nexport const integerRegex = /^(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//# sourceMappingURL=regex.js.map","import { AbiEncodingArrayLengthMismatchError, AbiEncodingBytesSizeMismatchError, AbiEncodingLengthMismatchError, InvalidAbiEncodingTypeError, InvalidArrayError, } from '../../errors/abi.js';\nimport { InvalidAddressError, } from '../../errors/address.js';\nimport { BaseError } from '../../errors/base.js';\nimport { IntegerOutOfRangeError } from '../../errors/encoding.js';\nimport { isAddress } from '../address/isAddress.js';\nimport { concat } from '../data/concat.js';\nimport { padHex } from '../data/pad.js';\nimport { size } from '../data/size.js';\nimport { slice } from '../data/slice.js';\nimport { boolToHex, numberToHex, stringToHex, } from '../encoding/toHex.js';\nimport { integerRegex } from '../regex.js';\n/**\n * @description Encodes a list of primitive values into an ABI-encoded hex value.\n *\n * - Docs: https://viem.sh/docs/abi/encodeAbiParameters#encodeabiparameters\n *\n * Generates ABI encoded data using the [ABI specification](https://docs.soliditylang.org/en/latest/abi-spec), given a set of ABI parameters (inputs/outputs) and their corresponding values.\n *\n * @param params - a set of ABI Parameters (params), that can be in the shape of the inputs or outputs attribute of an ABI Item.\n * @param values - a set of values (values) that correspond to the given params.\n * @example\n * ```typescript\n * import { encodeAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * [\n * { name: 'x', type: 'string' },\n * { name: 'y', type: 'uint' },\n * { name: 'z', type: 'bool' }\n * ],\n * ['wagmi', 420n, true]\n * )\n * ```\n *\n * You can also pass in Human Readable parameters with the parseAbiParameters utility.\n *\n * @example\n * ```typescript\n * import { encodeAbiParameters, parseAbiParameters } from 'viem'\n *\n * const encodedData = encodeAbiParameters(\n * parseAbiParameters('string x, uint y, bool z'),\n * ['wagmi', 420n, true]\n * )\n * ```\n */\nexport function encodeAbiParameters(params, values) {\n if (params.length !== values.length)\n throw new AbiEncodingLengthMismatchError({\n expectedLength: params.length,\n givenLength: values.length,\n });\n // Prepare the parameters to determine dynamic types to encode.\n const preparedParams = prepareParams({\n params: params,\n values: values,\n });\n const data = encodeParams(preparedParams);\n if (data.length === 0)\n return '0x';\n return data;\n}\nfunction prepareParams({ params, values, }) {\n const preparedParams = [];\n for (let i = 0; i < params.length; i++) {\n preparedParams.push(prepareParam({ param: params[i], value: values[i] }));\n }\n return preparedParams;\n}\nfunction prepareParam({ param, value, }) {\n const arrayComponents = getArrayComponents(param.type);\n if (arrayComponents) {\n const [length, type] = arrayComponents;\n return encodeArray(value, { length, param: { ...param, type } });\n }\n if (param.type === 'tuple') {\n return encodeTuple(value, {\n param: param,\n });\n }\n if (param.type === 'address') {\n return encodeAddress(value);\n }\n if (param.type === 'bool') {\n return encodeBool(value);\n }\n if (param.type.startsWith('uint') || param.type.startsWith('int')) {\n const signed = param.type.startsWith('int');\n const [, , size = '256'] = integerRegex.exec(param.type) ?? [];\n return encodeNumber(value, {\n signed,\n size: Number(size),\n });\n }\n if (param.type.startsWith('bytes')) {\n return encodeBytes(value, { param });\n }\n if (param.type === 'string') {\n return encodeString(value);\n }\n throw new InvalidAbiEncodingTypeError(param.type, {\n docsPath: '/docs/contract/encodeAbiParameters',\n });\n}\nfunction encodeParams(preparedParams) {\n // 1. Compute the size of the static part of the parameters.\n let staticSize = 0;\n for (let i = 0; i < preparedParams.length; i++) {\n const { dynamic, encoded } = preparedParams[i];\n if (dynamic)\n staticSize += 32;\n else\n staticSize += size(encoded);\n }\n // 2. Split the parameters into static and dynamic parts.\n const staticParams = [];\n const dynamicParams = [];\n let dynamicSize = 0;\n for (let i = 0; i < preparedParams.length; i++) {\n const { dynamic, encoded } = preparedParams[i];\n if (dynamic) {\n staticParams.push(numberToHex(staticSize + dynamicSize, { size: 32 }));\n dynamicParams.push(encoded);\n dynamicSize += size(encoded);\n }\n else {\n staticParams.push(encoded);\n }\n }\n // 3. Concatenate static and dynamic parts.\n return concat([...staticParams, ...dynamicParams]);\n}\nfunction encodeAddress(value) {\n if (!isAddress(value))\n throw new InvalidAddressError({ address: value });\n return { dynamic: false, encoded: padHex(value.toLowerCase()) };\n}\nfunction encodeArray(value, { length, param, }) {\n const dynamic = length === null;\n if (!Array.isArray(value))\n throw new InvalidArrayError(value);\n if (!dynamic && value.length !== length)\n throw new AbiEncodingArrayLengthMismatchError({\n expectedLength: length,\n givenLength: value.length,\n type: `${param.type}[${length}]`,\n });\n let dynamicChild = false;\n const preparedParams = [];\n for (let i = 0; i < value.length; i++) {\n const preparedParam = prepareParam({ param, value: value[i] });\n if (preparedParam.dynamic)\n dynamicChild = true;\n preparedParams.push(preparedParam);\n }\n if (dynamic || dynamicChild) {\n const data = encodeParams(preparedParams);\n if (dynamic) {\n const length = numberToHex(preparedParams.length, { size: 32 });\n return {\n dynamic: true,\n encoded: preparedParams.length > 0 ? concat([length, data]) : length,\n };\n }\n if (dynamicChild)\n return { dynamic: true, encoded: data };\n }\n return {\n dynamic: false,\n encoded: concat(preparedParams.map(({ encoded }) => encoded)),\n };\n}\nfunction encodeBytes(value, { param }) {\n const [, paramSize] = param.type.split('bytes');\n const bytesSize = size(value);\n if (!paramSize) {\n let value_ = value;\n // If the size is not divisible by 32 bytes, pad the end\n // with empty bytes to the ceiling 32 bytes.\n if (bytesSize % 32 !== 0)\n value_ = padHex(value_, {\n dir: 'right',\n size: Math.ceil((value.length - 2) / 2 / 32) * 32,\n });\n return {\n dynamic: true,\n encoded: concat([padHex(numberToHex(bytesSize, { size: 32 })), value_]),\n };\n }\n if (bytesSize !== Number.parseInt(paramSize, 10))\n throw new AbiEncodingBytesSizeMismatchError({\n expectedSize: Number.parseInt(paramSize, 10),\n value,\n });\n return { dynamic: false, encoded: padHex(value, { dir: 'right' }) };\n}\nfunction encodeBool(value) {\n if (typeof value !== 'boolean')\n throw new BaseError(`Invalid boolean value: \"${value}\" (type: ${typeof value}). Expected: \\`true\\` or \\`false\\`.`);\n return { dynamic: false, encoded: padHex(boolToHex(value)) };\n}\nfunction encodeNumber(value, { signed, size = 256 }) {\n if (typeof size === 'number') {\n const max = 2n ** (BigInt(size) - (signed ? 1n : 0n)) - 1n;\n const min = signed ? -max - 1n : 0n;\n if (value > max || value < min)\n throw new IntegerOutOfRangeError({\n max: max.toString(),\n min: min.toString(),\n signed,\n size: size / 8,\n value: value.toString(),\n });\n }\n return {\n dynamic: false,\n encoded: numberToHex(value, {\n size: 32,\n signed,\n }),\n };\n}\nfunction encodeString(value) {\n const hexValue = stringToHex(value);\n const partsLength = Math.ceil(size(hexValue) / 32);\n const parts = [];\n for (let i = 0; i < partsLength; i++) {\n parts.push(padHex(slice(hexValue, i * 32, (i + 1) * 32), {\n dir: 'right',\n }));\n }\n return {\n dynamic: true,\n encoded: concat([\n padHex(numberToHex(size(hexValue), { size: 32 })),\n ...parts,\n ]),\n };\n}\nfunction encodeTuple(value, { param }) {\n let dynamic = false;\n const preparedParams = [];\n for (let i = 0; i < param.components.length; i++) {\n const param_ = param.components[i];\n const index = Array.isArray(value) ? i : param_.name;\n const preparedParam = prepareParam({\n param: param_,\n value: value[index],\n });\n preparedParams.push(preparedParam);\n if (preparedParam.dynamic)\n dynamic = true;\n }\n return {\n dynamic,\n encoded: dynamic\n ? encodeParams(preparedParams)\n : concat(preparedParams.map(({ encoded }) => encoded)),\n };\n}\nexport function getArrayComponents(type) {\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//# sourceMappingURL=encodeAbiParameters.js.map","import { BaseError } from './base.js';\nexport class NegativeOffsetError extends BaseError {\n constructor({ offset }) {\n super(`Offset \\`${offset}\\` cannot be negative.`, {\n name: 'NegativeOffsetError',\n });\n }\n}\nexport class PositionOutOfBoundsError extends BaseError {\n constructor({ length, position }) {\n super(`Position \\`${position}\\` is out of bounds (\\`0 < position < ${length}\\`).`, { name: 'PositionOutOfBoundsError' });\n }\n}\nexport class RecursiveReadLimitExceededError extends BaseError {\n constructor({ count, limit }) {\n super(`Recursive read limit of \\`${limit}\\` exceeded (recursive read count: \\`${count}\\`).`, { name: 'RecursiveReadLimitExceededError' });\n }\n}\n//# sourceMappingURL=cursor.js.map","import { NegativeOffsetError, PositionOutOfBoundsError, RecursiveReadLimitExceededError, } from '../errors/cursor.js';\nconst staticCursor = {\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)\n 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)\n 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 ((this.dataView.getUint16(position) << 8) +\n this.dataView.getUint8(position + 2));\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) {\n this.assertPosition(this.position);\n this.bytes[this.position] = byte;\n this.position++;\n },\n pushBytes(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) {\n this.assertPosition(this.position);\n this.bytes[this.position] = value;\n this.position++;\n },\n pushUint16(value) {\n this.assertPosition(this.position + 1);\n this.dataView.setUint16(this.position, value);\n this.position += 2;\n },\n pushUint24(value) {\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) {\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)\n return;\n const count = this.getReadCount();\n this.positionReadCount.set(this.position, count + 1);\n if (count > 0)\n this.recursiveReadCount++;\n },\n};\nexport function createCursor(bytes, { recursiveReadLimit = 8_192 } = {}) {\n const cursor = Object.create(staticCursor);\n cursor.bytes = bytes;\n cursor.dataView = new DataView(bytes.buffer ?? bytes, bytes.byteOffset, bytes.byteLength);\n cursor.positionReadCount = new Map();\n cursor.recursiveReadLimit = recursiveReadLimit;\n return cursor;\n}\n//# sourceMappingURL=cursor.js.map","import { InvalidBytesBooleanError } from '../../errors/encoding.js';\nimport { trim } from '../data/trim.js';\nimport { assertSize, hexToBigInt, hexToNumber, } from './fromHex.js';\nimport { bytesToHex } from './toHex.js';\n/**\n * Decodes a byte array into a UTF-8 string, hex value, number, bigint or boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes\n * - Example: https://viem.sh/docs/utilities/fromBytes#usage\n *\n * @param bytes Byte array to decode.\n * @param toOrOpts Type to convert to or options.\n * @returns Decoded value.\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(new Uint8Array([1, 164]), 'number')\n * // 420\n *\n * @example\n * import { fromBytes } from 'viem'\n * const data = fromBytes(\n * new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]),\n * 'string'\n * )\n * // 'Hello world'\n */\nexport function fromBytes(bytes, toOrOpts) {\n const opts = typeof toOrOpts === 'string' ? { to: toOrOpts } : toOrOpts;\n const to = opts.to;\n if (to === 'number')\n return bytesToNumber(bytes, opts);\n if (to === 'bigint')\n return bytesToBigInt(bytes, opts);\n if (to === 'boolean')\n return bytesToBool(bytes, opts);\n if (to === 'string')\n return bytesToString(bytes, opts);\n return bytesToHex(bytes, opts);\n}\n/**\n * Decodes a byte array into a bigint.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobigint\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns BigInt value.\n *\n * @example\n * import { bytesToBigInt } from 'viem'\n * const data = bytesToBigInt(new Uint8Array([1, 164]))\n * // 420n\n */\nexport function bytesToBigInt(bytes, opts = {}) {\n if (typeof opts.size !== 'undefined')\n assertSize(bytes, { size: opts.size });\n const hex = bytesToHex(bytes, opts);\n return hexToBigInt(hex, opts);\n}\n/**\n * Decodes a byte array into a boolean.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestobool\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Boolean value.\n *\n * @example\n * import { bytesToBool } from 'viem'\n * const data = bytesToBool(new Uint8Array([1]))\n * // true\n */\nexport function bytesToBool(bytes_, opts = {}) {\n let bytes = bytes_;\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size });\n bytes = trim(bytes);\n }\n if (bytes.length > 1 || bytes[0] > 1)\n throw new InvalidBytesBooleanError(bytes);\n return Boolean(bytes[0]);\n}\n/**\n * Decodes a byte array into a number.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestonumber\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns Number value.\n *\n * @example\n * import { bytesToNumber } from 'viem'\n * const data = bytesToNumber(new Uint8Array([1, 164]))\n * // 420\n */\nexport function bytesToNumber(bytes, opts = {}) {\n if (typeof opts.size !== 'undefined')\n assertSize(bytes, { size: opts.size });\n const hex = bytesToHex(bytes, opts);\n return hexToNumber(hex, opts);\n}\n/**\n * Decodes a byte array into a UTF-8 string.\n *\n * - Docs: https://viem.sh/docs/utilities/fromBytes#bytestostring\n *\n * @param bytes Byte array to decode.\n * @param opts Options.\n * @returns String value.\n *\n * @example\n * import { bytesToString } from 'viem'\n * const data = bytesToString(new Uint8Array([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]))\n * // 'Hello world'\n */\nexport function bytesToString(bytes_, opts = {}) {\n let bytes = bytes_;\n if (typeof opts.size !== 'undefined') {\n assertSize(bytes, { size: opts.size });\n bytes = trim(bytes, { dir: 'right' });\n }\n return new TextDecoder().decode(bytes);\n}\n//# sourceMappingURL=fromBytes.js.map","import { AbiDecodingDataSizeTooSmallError, AbiDecodingZeroDataError, InvalidAbiDecodingTypeError, } from '../../errors/abi.js';\nimport { checksumAddress, } from '../address/getAddress.js';\nimport { createCursor, } from '../cursor.js';\nimport { size } from '../data/size.js';\nimport { sliceBytes } from '../data/slice.js';\nimport { trim } from '../data/trim.js';\nimport { bytesToBigInt, bytesToBool, bytesToNumber, bytesToString, } from '../encoding/fromBytes.js';\nimport { hexToBytes } from '../encoding/toBytes.js';\nimport { bytesToHex } from '../encoding/toHex.js';\nimport { getArrayComponents } from './encodeAbiParameters.js';\nexport function decodeAbiParameters(params, data) {\n const bytes = typeof data === 'string' ? hexToBytes(data) : data;\n const cursor = createCursor(bytes);\n if (size(bytes) === 0 && params.length > 0)\n throw new AbiDecodingZeroDataError();\n if (size(data) && size(data) < 32)\n throw new AbiDecodingDataSizeTooSmallError({\n data: typeof data === 'string' ? data : bytesToHex(data),\n params: params,\n size: size(data),\n });\n let consumed = 0;\n const values = [];\n for (let i = 0; i < params.length; ++i) {\n const param = params[i];\n cursor.setPosition(consumed);\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: 0,\n });\n consumed += consumed_;\n values.push(data);\n }\n return values;\n}\nfunction decodeParameter(cursor, param, { staticPosition }) {\n const arrayComponents = getArrayComponents(param.type);\n if (arrayComponents) {\n const [length, type] = arrayComponents;\n return decodeArray(cursor, { ...param, type }, { length, staticPosition });\n }\n if (param.type === 'tuple')\n return decodeTuple(cursor, param, { staticPosition });\n if (param.type === 'address')\n return decodeAddress(cursor);\n if (param.type === 'bool')\n 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')\n return decodeString(cursor, { staticPosition });\n throw new InvalidAbiDecodingTypeError(param.type, {\n docsPath: '/docs/contract/decodeAbiParameters',\n });\n}\n////////////////////////////////////////////////////////////////////\n// Type Decoders\nconst sizeOfLength = 32;\nconst sizeOfOffset = 32;\nfunction decodeAddress(cursor) {\n const value = cursor.readBytes(32);\n return [checksumAddress(bytesToHex(sliceBytes(value, -20))), 32];\n}\nfunction decodeArray(cursor, param, { length, staticPosition }) {\n // If the length of the array is not known in advance (dynamic array),\n // this means we will need to wonder off to the pointer and decode.\n if (!length) {\n // Dealing with a dynamic type, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset;\n const startOfData = start + sizeOfLength;\n // Get the length of the array from the offset.\n cursor.setPosition(start);\n const length = bytesToNumber(cursor.readBytes(sizeOfLength));\n // Check if the array has any dynamic children.\n const dynamicChild = hasDynamicChild(param);\n let consumed = 0;\n const value = [];\n for (let i = 0; i < length; ++i) {\n // If any of the children is dynamic, then all elements will be offset pointer, thus size of one slot (32 bytes).\n // Otherwise, elements will be the size of their encoding (consumed bytes).\n cursor.setPosition(startOfData + (dynamicChild ? i * 32 : consumed));\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: startOfData,\n });\n consumed += consumed_;\n value.push(data);\n }\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\n }\n // If the length of the array is known in advance,\n // and the length of an element deeply nested in the array is not known,\n // we need to decode the offset of the array data.\n if (hasDynamicChild(param)) {\n // Dealing with dynamic types, so get the offset of the array data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset;\n const value = [];\n for (let i = 0; i < length; ++i) {\n // Move cursor along to the next slot (next offset pointer).\n cursor.setPosition(start + i * 32);\n const [data] = decodeParameter(cursor, param, {\n staticPosition: start,\n });\n value.push(data);\n }\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\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 = [];\n for (let i = 0; i < length; ++i) {\n const [data, consumed_] = decodeParameter(cursor, param, {\n staticPosition: staticPosition + consumed,\n });\n consumed += consumed_;\n value.push(data);\n }\n return [value, consumed];\n}\nfunction decodeBool(cursor) {\n return [bytesToBool(cursor.readBytes(32), { size: 32 }), 32];\n}\nfunction decodeBytes(cursor, param, { staticPosition }) {\n const [_, size] = param.type.split('bytes');\n if (!size) {\n // Dealing with dynamic types, so get the offset of the bytes data.\n const offset = bytesToNumber(cursor.readBytes(32));\n // Set position of the cursor to start of bytes data.\n cursor.setPosition(staticPosition + offset);\n const length = bytesToNumber(cursor.readBytes(32));\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 const data = cursor.readBytes(length);\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [bytesToHex(data), 32];\n }\n const value = bytesToHex(cursor.readBytes(Number.parseInt(size, 10), 32));\n return [value, 32];\n}\nfunction decodeNumber(cursor, param) {\n const signed = param.type.startsWith('int');\n const size = Number.parseInt(param.type.split('int')[1] || '256', 10);\n const value = cursor.readBytes(32);\n return [\n size > 48\n ? bytesToBigInt(value, { signed })\n : bytesToNumber(value, { signed }),\n 32,\n ];\n}\nfunction decodeTuple(cursor, param, { staticPosition }) {\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 = param.components.length === 0 || param.components.some(({ name }) => !name);\n // Initialize the value to an object or an array, depending on whether the\n // tuple is named or unnamed.\n const value = hasUnnamedChild ? [] : {};\n let consumed = 0;\n // If the tuple has a dynamic child, we must first decode the offset to the\n // tuple data.\n if (hasDynamicChild(param)) {\n // Dealing with dynamic types, so get the offset of the tuple data.\n const offset = bytesToNumber(cursor.readBytes(sizeOfOffset));\n // Start is the static position of referencing slot + offset.\n const start = staticPosition + offset;\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i];\n cursor.setPosition(start + consumed);\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition: start,\n });\n consumed += consumed_;\n value[hasUnnamedChild ? i : component?.name] = data;\n }\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\n }\n // If the tuple has static children, we can just decode each component\n // in sequence.\n for (let i = 0; i < param.components.length; ++i) {\n const component = param.components[i];\n const [data, consumed_] = decodeParameter(cursor, component, {\n staticPosition,\n });\n value[hasUnnamedChild ? i : component?.name] = data;\n consumed += consumed_;\n }\n return [value, consumed];\n}\nfunction decodeString(cursor, { staticPosition }) {\n // Get offset to start of string data.\n const offset = bytesToNumber(cursor.readBytes(32));\n // Start is the static position of current slot + offset.\n const start = staticPosition + offset;\n cursor.setPosition(start);\n const length = bytesToNumber(cursor.readBytes(32));\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 const data = cursor.readBytes(length, 32);\n const value = bytesToString(trim(data));\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\n}\nfunction hasDynamicChild(param) {\n const { type } = param;\n if (type === 'string')\n return true;\n if (type === 'bytes')\n return true;\n if (type.endsWith('[]'))\n return true;\n if (type === 'tuple')\n return param.components?.some(hasDynamicChild);\n const arrayComponents = getArrayComponents(param.type);\n if (arrayComponents &&\n hasDynamicChild({ ...param, type: arrayComponents[1] }))\n return true;\n return false;\n}\n//# sourceMappingURL=decodeAbiParameters.js.map","import React, { FC } from \"react\"\nimport { ConnectButton as ConnectButtonThirdweb, darkTheme } from \"thirdweb/react\"\nimport { client as seedClient } from \"@seedprotocol/sdk\"\nimport { getClient, getWalletsForConnectButton } from \"../helpers/thirdweb\"\nimport { getPublishConfig } from \"../config\"\nimport { optimismSepolia } from \"thirdweb/chains\"\nimport { getContract, sendTransaction, waitForReceipt } from \"thirdweb\"\nimport { getInstalledModules, installModule } from \"thirdweb/modules\"\nimport type { Account, Wallet } from \"thirdweb/wallets\"\nimport { encodeAbiParameters } from \"viem\"\nimport { EAS_CONTRACT_ADDRESS } from \"../helpers/constants\"\n\nasync function ensureModularAccountModule(account: Account): Promise<void> {\n const config = getPublishConfig()\n const { modularAccountModuleContract, modularAccountModuleData } = config\n if (!modularAccountModuleContract) return\n\n const accountContract = getContract({\n client: getClient(),\n chain: optimismSepolia,\n address: account.address,\n })\n\n const installed = await getInstalledModules({ contract: accountContract })\n const moduleAddr = modularAccountModuleContract.toLowerCase()\n const isInstalled = installed.some(\n (m: { implementation: string }) => m.implementation?.toLowerCase() === moduleAddr\n )\n if (isInstalled) return\n\n const tx = installModule({\n contract: accountContract,\n moduleContract: modularAccountModuleContract,\n data: encodeAbiParameters(\n [{ type: \"address\" }],\n [EAS_CONTRACT_ADDRESS]\n ),\n })\n const result = await sendTransaction({ transaction: tx, account })\n await waitForReceipt({\n client: getClient(),\n transactionHash: result.transactionHash,\n chain: optimismSepolia,\n })\n}\n\nconst ConnectButton: FC = () => {\n const handleDisconnect = async () => {\n console.log('[ConnectButton] Disconnected')\n try {\n await seedClient.setAddresses([])\n } catch (err) {\n console.warn('[ConnectButton] Failed to clear seed client addresses:', err)\n }\n }\n\n const handleConnect = async (activeWallet: Wallet, _allConnectedWallets: Wallet[]) => {\n const account = activeWallet.getAccount()\n if (!account) return\n console.log('[ConnectButton] Connected', account.address)\n try {\n await ensureModularAccountModule(account)\n } catch (err) {\n console.warn('[ConnectButton] Module check/install failed:', err)\n }\n }\n\n return (\n <ConnectButtonThirdweb\n client={getClient()}\n wallets={getWalletsForConnectButton()}\n autoConnect={true}\n chain={optimismSepolia}\n chains={[ optimismSepolia, ]}\n onConnect={handleConnect}\n // accountAbstraction={{\n // chain : optimismSepolia,\n // factoryAddress : thirdwebAccountFactoryAddress,\n // gasless : true,\n // overrides: {\n // execute: (accountContract, transaction) => {\n // // Log the gas that was set on the transaction\n // console.log(\"[SmartWallet Execute]\", {\n // gas: transaction.gas,\n // to: transaction.to,\n // dataLength: transaction.data?.length,\n // });\n \n // // Return the default execute call — don't change behavior,\n // // just observe what's being passed through\n // return prepareContractCall({\n // contract: accountContract,\n // method: \"function execute(address, uint256, bytes)\",\n // params: [\n // transaction.to ?? \"\",\n // transaction.value ?? 0n,\n // transaction.data ?? \"0x\",\n // ],\n // gas: transaction.gas, // Pass through whatever was set\n // });\n // },\n // },\n // }}\n onDisconnect={handleDisconnect}\n theme={darkTheme({\n colors: {\n primaryButtonBg: '#1D2939',\n primaryButtonText: '#FFFFFF',\n secondaryButtonHoverBg: '#1D2939',\n connectedButtonBg: '#101828',\n connectedButtonBgHover: '#1D2939',\n borderColor: '#344054',\n },\n })}\n />\n )\n}\n\nexport default ConnectButton","import React, { FC } from \"react\"\nimport type { MutableRefObject } from \"react\"\nimport type { QueryClient } from \"@tanstack/react-query\"\nimport { ThirdwebProvider } from \"thirdweb/react\"\nimport { SeedProvider } from \"@seedprotocol/sdk\"\nimport { initPublish, type PublishConfig } from \"../config\"\n\nexport interface PublishProviderProps {\n children: React.ReactNode\n /**\n * If provided, calls initPublish with this config.\n * Otherwise, assumes initPublish was already called elsewhere.\n */\n config?: PublishConfig\n /** Optional: use your own QueryClient for Seed hooks. If not provided, SeedProvider creates one. */\n queryClient?: QueryClient\n /** Optional: ref to receive the QueryClient instance (e.g. for tests). */\n queryClientRef?: MutableRefObject<QueryClient | null>\n}\n\nconst PublishProvider: FC<PublishProviderProps> = ({\n children,\n config,\n queryClient,\n queryClientRef,\n}) => {\n if (config) {\n initPublish(config)\n }\n\n return (\n <ThirdwebProvider>\n <SeedProvider queryClient={queryClient} queryClientRef={queryClientRef}>\n {children}\n </SeedProvider>\n </ThirdwebProvider>\n )\n}\n\nexport default PublishProvider\n","import { getContract, prepareContractCall, readContract } from 'thirdweb'\nimport type { ThirdwebClient } from 'thirdweb'\nimport type { Chain } from 'thirdweb/chains'\nimport { SCHEMA_REGISTRY_ADDRESS } from '~/helpers/constants'\n\nconst SCHEMA_REGISTRY_ABI = [\n {\n inputs: [{ internalType: 'bytes32', name: 'uid', type: 'bytes32' }],\n name: 'getSchema',\n outputs: [\n {\n components: [\n { internalType: 'bytes32', name: 'uid', type: 'bytes32' },\n { internalType: 'contract ISchemaResolver', name: 'resolver', type: 'address' },\n { internalType: 'bool', name: 'revocable', type: 'bool' },\n { internalType: 'string', name: 'schema', type: 'string' },\n ],\n internalType: 'struct SchemaRecord',\n name: '',\n type: 'tuple',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n { internalType: 'string', name: 'schema', type: 'string' },\n { internalType: 'contract ISchemaResolver', name: 'resolver', type: 'address' },\n { internalType: 'bool', name: 'revocable', type: 'bool' },\n ],\n name: 'register',\n outputs: [{ internalType: 'bytes32', name: '', type: 'bytes32' }],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n] as const\n\nexport type SchemaRecord = {\n uid: string\n resolver: string\n revocable: boolean\n schema: string\n}\n\nconst ZERO_BYTES32 = '0x' + '0'.repeat(64)\n\nexport function getSchemaRegistryContract(client: ThirdwebClient, chain: Chain) {\n return getContract({\n client,\n chain,\n address: SCHEMA_REGISTRY_ADDRESS,\n abi: SCHEMA_REGISTRY_ABI,\n })\n}\n\n/** Use string signature for getSchema - the EAS SchemaRegistry expects this exact selector.\n * The ABI-based method resolution can produce a different selector (e.g. from internalType\n * or tuple encoding) causing \"Router: function does not exist\" on proxy/router contracts. */\nconst GET_SCHEMA_SIGNATURE =\n 'function getSchema(bytes32 uid) view returns ((bytes32 uid, address resolver, bool revocable, string schema))' as const\n\nexport async function getSchemaRecord(\n client: ThirdwebClient,\n chain: Chain,\n uid: string,\n): Promise<SchemaRecord | null> {\n const contract = getContract({\n client,\n chain,\n address: SCHEMA_REGISTRY_ADDRESS,\n // No ABI - use string method so thirdweb parses the exact signature and produces correct selector\n })\n const result = await readContract({\n contract,\n method: GET_SCHEMA_SIGNATURE,\n params: [uid as `0x${string}`],\n })\n if (!result || (result as SchemaRecord).uid === ZERO_BYTES32) {\n return null\n }\n return result as SchemaRecord\n}\n\nexport type RegisterSchemaParams = {\n schema: string\n resolverAddress: string\n revocable: boolean\n}\n\nexport function registerSchema(\n client: ThirdwebClient,\n chain: Chain,\n params: RegisterSchemaParams,\n) {\n const contract = getSchemaRegistryContract(client, chain)\n return prepareContractCall({\n contract,\n method: 'register',\n params: [params.schema, params.resolverAddress as `0x${string}`, params.revocable],\n })\n}\n","import { getContract, prepareContractCall } from 'thirdweb'\nimport type { ThirdwebClient } from 'thirdweb'\nimport type { Chain } from 'thirdweb/chains'\nimport { SchemaEncoder, NO_EXPIRATION, ZERO_BYTES32 } from '@ethereum-attestation-service/eas-sdk'\nimport { getPublishConfig } from '~/config'\nimport { EAS_SCHEMA_NAME_ATTESTATION_UID } from '~/helpers/constants'\n\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000'\n\nexport type NameSchemaAttestationParams = {\n schemaUid: string\n schemaName: string\n}\n\nexport function prepareNameSchemaAttestation(\n client: ThirdwebClient,\n chain: Chain,\n params: NameSchemaAttestationParams,\n) {\n const schemaEncoder = new SchemaEncoder('bytes32 schemaId,string name')\n const encodedData = schemaEncoder.encodeData([\n { name: 'schemaId', value: params.schemaUid as `0x${string}`, type: 'bytes32' },\n { name: 'name', value: params.schemaName, type: 'string' },\n ])\n\n const { easContractAddress } = getPublishConfig()\n const contract = getContract({\n client,\n chain,\n address: easContractAddress as `0x${string}`,\n // No ABI - use string method so thirdweb parses the exact signature\n })\n\n return prepareContractCall({\n contract,\n method:\n 'function attest((bytes32 schema,(address recipient,uint64 expirationTime,bool revocable,bytes32 refUID,bytes data,uint256 value) data) request) payable returns (bytes32)' as const,\n params: [\n {\n schema: EAS_SCHEMA_NAME_ATTESTATION_UID as `0x${string}`,\n data: {\n recipient: ZERO_ADDRESS as `0x${string}`,\n expirationTime: BigInt(NO_EXPIRATION),\n revocable: true,\n refUID: ZERO_BYTES32 as `0x${string}`,\n data: encodedData as `0x${string}`,\n value: 0n,\n },\n },\n ],\n })\n}\n","import {\n getSegmentedItemProperties,\n getRelatedItemsForPublish,\n INTERNAL_DATA_TYPES,\n getEasSchemaForItemProperty,\n setSchemaUidForSchemaDefinition,\n setSchemaUidForModel,\n} from '@seedprotocol/sdk'\nimport type { Item } from '@seedprotocol/sdk'\n\ntype ItemInstance = InstanceType<typeof Item>\nimport { SchemaRegistry } from '@ethereum-attestation-service/eas-sdk'\nimport type { ThirdwebClient } from 'thirdweb'\nimport type { Chain } from 'thirdweb/chains'\nimport { sendTransaction, waitForReceipt } from 'thirdweb'\nimport type { Account } from 'thirdweb/wallets'\nimport { getSchemaRecord, registerSchema } from '~/helpers/thirdweb/11155420/schemaRegistry'\nimport { prepareNameSchemaAttestation } from '~/helpers/thirdweb/11155420/nameSchemaAttestation'\n\nconst RESOLVER_ADDRESS = '0x0000000000000000000000000000000000000000'\nconst REVOCABLE = true\n\nfunction toSnakeCase(str: string): string {\n return str.replace(/([a-z])([A-Z])/g, '$1_$2').toLowerCase()\n}\n\n/**\n * Collects all model names used by the item (item's model + relation refs + list refs + Image).\n */\nfunction getModelNamesForItem(item: ItemInstance): Set<string> {\n const { itemRelationProperties, itemImageProperties, itemListProperties } =\n getSegmentedItemProperties(item)\n const modelNames = new Set<string>()\n\n if (item.modelName) {\n modelNames.add(item.modelName)\n }\n\n for (const prop of itemRelationProperties) {\n const ref = prop.propertyDef?.ref as string | undefined\n if (ref) modelNames.add(ref)\n }\n\n for (const _prop of itemImageProperties) {\n modelNames.add('Image')\n }\n\n for (const prop of itemListProperties) {\n const ref = prop.propertyDef?.ref as string | undefined\n if (ref) modelNames.add(ref)\n }\n\n return modelNames\n}\n\n/**\n * Ensures EAS schemas exist for each item property and each model used by the item.\n * If a schema is not found on-chain or in the indexer, registers it via SchemaRegistry\n * and creates a name attestation (Schema #1) so EASSCAN displays it.\n * Populates the SDK's schema map so getPublishPayload can resolve schema UIDs.\n */\nexport async function ensureEasSchemasForItem(\n item: ItemInstance,\n account: Account,\n client: ThirdwebClient,\n chain: Chain,\n): Promise<void> {\n const { itemBasicProperties, itemRelationProperties, itemImageProperties, itemListProperties } =\n getSegmentedItemProperties(item)\n\n const allProperties = [\n ...itemBasicProperties,\n ...itemRelationProperties,\n ...itemImageProperties,\n ...itemListProperties,\n ]\n\n const registeredSchemaUids = new Set<string>()\n\n // Ensure model schemas (bytes32 <model_name>) so getPublishPayload can resolve seedSchemaUid\n const modelNames = getModelNamesForItem(item)\n const registeredModelSchemaUids = new Set<string>()\n\n for (const modelName of modelNames) {\n const schemaDef = `bytes32 ${toSnakeCase(modelName)}`\n const schemaUid = SchemaRegistry.getSchemaUID(\n schemaDef,\n RESOLVER_ADDRESS as `0x${string}`,\n REVOCABLE,\n )\n\n const onChainRecord = await getSchemaRecord(client, chain, schemaUid)\n if (onChainRecord) {\n setSchemaUidForModel({ modelName, schemaUid })\n continue\n }\n\n if (registeredModelSchemaUids.has(schemaUid)) {\n setSchemaUidForModel({ modelName, schemaUid })\n continue\n }\n\n try {\n const registerTx = registerSchema(client, chain, {\n schema: schemaDef,\n resolverAddress: RESOLVER_ADDRESS,\n revocable: REVOCABLE,\n })\n\n const registerResult = await sendTransaction({\n account,\n transaction: registerTx,\n })\n\n await waitForReceipt({\n client,\n chain,\n transactionHash: registerResult.transactionHash,\n })\n } catch (err) {\n throw new Error(\n `Failed to register EAS schema for model ${modelName}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n try {\n const attestTx = prepareNameSchemaAttestation(client, chain, {\n schemaUid,\n schemaName: toSnakeCase(modelName),\n })\n\n const attestResult = await sendTransaction({\n account,\n transaction: attestTx,\n })\n\n await waitForReceipt({\n client,\n chain,\n transactionHash: attestResult.transactionHash,\n })\n } catch (err) {\n throw new Error(\n `Failed to name EAS schema for model ${modelName}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n registeredModelSchemaUids.add(schemaUid)\n setSchemaUidForModel({ modelName, schemaUid })\n }\n\n // Ensure storage seed property schemas (Image/File/Html models have storageTransactionId).\n // The top-level item doesn't have these properties, but nested storage seeds do.\n const storageSchemaDef = 'string storage_transaction_id'\n const storageSchemaUid = SchemaRegistry.getSchemaUID(\n storageSchemaDef,\n RESOLVER_ADDRESS as `0x${string}`,\n REVOCABLE,\n )\n const storageOnChain = await getSchemaRecord(client, chain, storageSchemaUid)\n if (storageOnChain) {\n setSchemaUidForSchemaDefinition({ text: storageSchemaDef, schemaUid: storageSchemaUid })\n } else if (!registeredSchemaUids.has(storageSchemaUid) && (modelNames.has('Image') || modelNames.has('File') || modelNames.has('Html'))) {\n try {\n const registerTx = registerSchema(client, chain, {\n schema: storageSchemaDef,\n resolverAddress: RESOLVER_ADDRESS,\n revocable: REVOCABLE,\n })\n const registerResult = await sendTransaction({ account, transaction: registerTx })\n await waitForReceipt({ client, chain, transactionHash: registerResult.transactionHash })\n const attestTx = prepareNameSchemaAttestation(client, chain, {\n schemaUid: storageSchemaUid,\n schemaName: 'storage_transaction_id',\n })\n const attestResult = await sendTransaction({ account, transaction: attestTx })\n await waitForReceipt({ client, chain, transactionHash: attestResult.transactionHash })\n } catch (err) {\n throw new Error(\n `Failed to register EAS schema for storageTransactionId: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n registeredSchemaUids.add(storageSchemaUid)\n setSchemaUidForSchemaDefinition({ text: storageSchemaDef, schemaUid: storageSchemaUid })\n }\n\n for (const property of allProperties) {\n if (!property.propertyDef) continue\n\n const easDataType =\n (INTERNAL_DATA_TYPES as Record<string, { eas?: string }>)[property.propertyDef.dataType]?.eas ?? 'string'\n const propertyNameSnakeCase = toSnakeCase(property.propertyName)\n const schemaDef = `${easDataType} ${propertyNameSnakeCase}`\n\n let schema = await getEasSchemaForItemProperty({\n schemaUid: property.schemaUid,\n propertyName: property.propertyName,\n easDataType,\n })\n\n if (schema) {\n // Verify SDK schema matches our schemaDef on-chain before trusting it.\n // The SDK may return a cached schema from a different chain/definition.\n const onChainRecord = await getSchemaRecord(client, chain, schema.id)\n const matches = onChainRecord && onChainRecord.schema === schemaDef\n if (matches) {\n setSchemaUidForSchemaDefinition({ text: schemaDef, schemaUid: schema.id })\n continue\n }\n // Schema mismatch or not found: fall through to register/use our schemaDef\n }\n\n const schemaUid = SchemaRegistry.getSchemaUID(schemaDef, RESOLVER_ADDRESS as `0x${string}`, REVOCABLE)\n const onChainRecord = await getSchemaRecord(client, chain, schemaUid)\n\n if (onChainRecord) {\n setSchemaUidForSchemaDefinition({ text: schemaDef, schemaUid })\n continue\n }\n\n if (registeredSchemaUids.has(schemaUid)) {\n setSchemaUidForSchemaDefinition({ text: schemaDef, schemaUid })\n continue\n }\n\n try {\n const registerTx = registerSchema(client, chain, {\n schema: schemaDef,\n resolverAddress: RESOLVER_ADDRESS,\n revocable: REVOCABLE,\n })\n\n const registerResult = await sendTransaction({\n account,\n transaction: registerTx,\n })\n\n await waitForReceipt({\n client,\n chain,\n transactionHash: registerResult.transactionHash,\n })\n } catch (err) {\n throw new Error(\n `Failed to register EAS schema for property ${property.propertyName}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n try {\n const attestTx = prepareNameSchemaAttestation(client, chain, {\n schemaUid,\n schemaName: propertyNameSnakeCase,\n })\n\n const attestResult = await sendTransaction({\n account,\n transaction: attestTx,\n })\n\n await waitForReceipt({\n client,\n chain,\n transactionHash: attestResult.transactionHash,\n })\n } catch (err) {\n throw new Error(\n `Failed to name EAS schema for property ${property.propertyName}: ${err instanceof Error ? err.message : String(err)}`,\n )\n }\n\n registeredSchemaUids.add(schemaUid)\n setSchemaUidForSchemaDefinition({ text: schemaDef, schemaUid })\n }\n\n // Ensure schemas for related/list items that will be in the multiPublish payload.\n // Without this, schemas for nested items (e.g. Image's properties) are never registered,\n // causing EAS multiAttest to revert with InvalidSchema.\n const relatedItems = await getRelatedItemsForPublish(item)\n for (const relatedItem of relatedItems) {\n await ensureEasSchemasForItem(relatedItem as ItemInstance, account, client, chain)\n }\n}\n","import {\n prepareEvent,\n prepareContractCall,\n readContract,\n type BaseTransactionOptions,\n type AbiParameterToPrimitiveType,\n} from \"thirdweb\";\n\n/**\n* Contract events\n*/\n\n/**\n * Represents the filters for the \"AdminUpdated\" event.\n */\nexport type AdminUpdatedEventFilters = Partial<{\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the AdminUpdated event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { adminUpdatedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * adminUpdatedEvent({\n * signer: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function adminUpdatedEvent(filters: AdminUpdatedEventFilters = {}) {\n return prepareEvent({\n signature: \"event AdminUpdated(address indexed signer, bool isAdmin)\",\n filters,\n });\n};\n \n\n\n\n/**\n * Creates an event object for the Initialized event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { initializedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * initializedEvent()\n * ],\n * });\n * ```\n */ \nexport function initializedEvent() {\n return prepareEvent({\n signature: \"event Initialized(uint8 version)\",\n });\n};\n \n\n/**\n * Represents the filters for the \"SignerPermissionsUpdated\" event.\n */\nexport type SignerPermissionsUpdatedEventFilters = Partial<{\n authorizingSigner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"authorizingSigner\",\"indexed\":true}>\ntargetSigner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"targetSigner\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the SignerPermissionsUpdated event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { signerPermissionsUpdatedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * signerPermissionsUpdatedEvent({\n * authorizingSigner: ...,\n * targetSigner: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function signerPermissionsUpdatedEvent(filters: SignerPermissionsUpdatedEventFilters = {}) {\n return prepareEvent({\n signature: \"event SignerPermissionsUpdated(address indexed authorizingSigner, address indexed targetSigner, (address signer, uint8 isAdmin, address[] approvedTargets, uint256 nativeTokenLimitPerTransaction, uint128 permissionStartTimestamp, uint128 permissionEndTimestamp, uint128 reqValidityStartTimestamp, uint128 reqValidityEndTimestamp, bytes32 uid) permissions)\",\n filters,\n });\n};\n \n\n\n\n/**\n * Creates an event object for the ContractURIUpdated event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { contractURIUpdatedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * contractURIUpdatedEvent()\n * ],\n * });\n * ```\n */ \nexport function contractURIUpdatedEvent() {\n return prepareEvent({\n signature: \"event ContractURIUpdated(string prevURI, string newURI)\",\n });\n};\n \n\n\n\n/**\n * Creates an event object for the CreatedAttestation event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { createdAttestationEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * createdAttestationEvent()\n * ],\n * });\n * ```\n */ \nexport function createdAttestationEvent() {\n return prepareEvent({\n signature: \"event CreatedAttestation((bytes32 schemaUid, bytes32 attestationUid) result)\",\n });\n};\n \n\n\n\n/**\n * Creates an event object for the EIP712DomainChanged event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { eIP712DomainChangedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * eIP712DomainChangedEvent()\n * ],\n * });\n * ```\n */ \nexport function eIP712DomainChangedEvent() {\n return prepareEvent({\n signature: \"event EIP712DomainChanged()\",\n });\n};\n \n\n\n\n/**\n * Creates an event object for the Log event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { logEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * logEvent()\n * ],\n * });\n * ```\n */ \nexport function logEvent() {\n return prepareEvent({\n signature: \"event Log(string message)\",\n });\n};\n \n\n/**\n * Represents the filters for the \"OwnershipTransferred\" event.\n */\nexport type OwnershipTransferredEventFilters = Partial<{\n previousOwner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"previousOwner\",\"indexed\":true}>\nnewOwner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"newOwner\",\"indexed\":true}>\n}>;\n\n/**\n * Creates an event object for the OwnershipTransferred event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { ownershipTransferredEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * ownershipTransferredEvent({\n * previousOwner: ...,\n * newOwner: ...,\n * })\n * ],\n * });\n * ```\n */ \nexport function ownershipTransferredEvent(filters: OwnershipTransferredEventFilters = {}) {\n return prepareEvent({\n signature: \"event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)\",\n filters,\n });\n};\n \n\n\n\n/**\n * Creates an event object for the SeedPublished event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { seedPublishedEvent } from \"TODO\";\n * \n * const events = await getContractEvents({\n * contract,\n * events: [\n * seedPublishedEvent()\n * ],\n * });\n * ```\n */ \nexport function seedPublishedEvent() {\n return prepareEvent({\n signature: \"event SeedPublished(bytes returnedDataFromEAS)\",\n });\n};\n \n\n/**\n* Contract read functions\n*/\n\n\n\n/**\n * Calls the \"entryPoint\" function on the contract.\n * @param options - The options for the entryPoint function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { entryPoint } from \"TODO\";\n * \n * const result = await entryPoint();\n * \n * ```\n */\nexport async function entryPoint(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xb0d691fe\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"factory\" function on the contract.\n * @param options - The options for the factory function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { factory } from \"TODO\";\n * \n * const result = await factory();\n * \n * ```\n */\nexport async function factory(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xc45a0155\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllActiveSigners\" function on the contract.\n * @param options - The options for the getAllActiveSigners function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllActiveSigners } from \"TODO\";\n * \n * const result = await getAllActiveSigners();\n * \n * ```\n */\nexport async function getAllActiveSigners(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x8b52d723\",\n [],\n [\n {\n \"type\": \"tuple[]\",\n \"name\": \"signers\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"startTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"endTimestamp\"\n }\n ]\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllAdmins\" function on the contract.\n * @param options - The options for the getAllAdmins function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllAdmins } from \"TODO\";\n * \n * const result = await getAllAdmins();\n * \n * ```\n */\nexport async function getAllAdmins(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xe9523c97\",\n [],\n [\n {\n \"type\": \"address[]\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllExtensions\" function on the contract.\n * @param options - The options for the getAllExtensions function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllExtensions } from \"TODO\";\n * \n * const result = await getAllExtensions();\n * \n * ```\n */\nexport async function getAllExtensions(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x4a00cc48\",\n [],\n [\n {\n \"type\": \"tuple[]\",\n \"components\": [\n {\n \"type\": \"tuple\",\n \"name\": \"metadata\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"name\"\n },\n {\n \"type\": \"string\",\n \"name\": \"metadataURI\"\n },\n {\n \"type\": \"address\",\n \"name\": \"implementation\"\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"functions\",\n \"components\": [\n {\n \"type\": \"bytes4\",\n \"name\": \"functionSelector\"\n },\n {\n \"type\": \"string\",\n \"name\": \"functionSignature\"\n }\n ]\n }\n ]\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getAllSigners\" function on the contract.\n * @param options - The options for the getAllSigners function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getAllSigners } from \"TODO\";\n * \n * const result = await getAllSigners();\n * \n * ```\n */\nexport async function getAllSigners(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xd42f2f35\",\n [],\n [\n {\n \"type\": \"tuple[]\",\n \"name\": \"signers\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"startTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"endTimestamp\"\n }\n ]\n }\n ]\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"getImplementationForFunction\" function.\n */\nexport type GetImplementationForFunctionParams = {\n functionSelector: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"_functionSelector\"}>\n};\n\n/**\n * Calls the \"getImplementationForFunction\" function on the contract.\n * @param options - The options for the getImplementationForFunction function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getImplementationForFunction } from \"TODO\";\n * \n * const result = await getImplementationForFunction({\n * functionSelector: ...,\n * });\n * \n * ```\n */\nexport async function getImplementationForFunction(\n options: BaseTransactionOptions<GetImplementationForFunctionParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xce0b6013\",\n [\n {\n \"type\": \"bytes4\",\n \"name\": \"_functionSelector\"\n }\n ],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: [options.functionSelector]\n });\n};\n\n\n\n\n/**\n * Calls the \"getNonce\" function on the contract.\n * @param options - The options for the getNonce function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getNonce } from \"TODO\";\n * \n * const result = await getNonce();\n * \n * ```\n */\nexport async function getNonce(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xd087d288\",\n [],\n [\n {\n \"type\": \"uint256\"\n }\n ]\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"getPermissionsForSigner\" function.\n */\nexport type GetPermissionsForSignerParams = {\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\"}>\n};\n\n/**\n * Calls the \"getPermissionsForSigner\" function on the contract.\n * @param options - The options for the getPermissionsForSigner function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getPermissionsForSigner } from \"TODO\";\n * \n * const result = await getPermissionsForSigner({\n * signer: ...,\n * });\n * \n * ```\n */\nexport async function getPermissionsForSigner(\n options: BaseTransactionOptions<GetPermissionsForSignerParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xf15d424e\",\n [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n }\n ],\n [\n {\n \"type\": \"tuple\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"startTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"endTimestamp\"\n }\n ]\n }\n ]\n],\n params: [options.signer]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isActiveSigner\" function.\n */\nexport type IsActiveSignerParams = {\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"signer\"}>\n};\n\n/**\n * Calls the \"isActiveSigner\" function on the contract.\n * @param options - The options for the isActiveSigner function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isActiveSigner } from \"TODO\";\n * \n * const result = await isActiveSigner({\n * signer: ...,\n * });\n * \n * ```\n */\nexport async function isActiveSigner(\n options: BaseTransactionOptions<IsActiveSignerParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x7dff5a79\",\n [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.signer]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isAdmin\" function.\n */\nexport type IsAdminParams = {\n account: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_account\"}>\n};\n\n/**\n * Calls the \"isAdmin\" function on the contract.\n * @param options - The options for the isAdmin function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isAdmin } from \"TODO\";\n * \n * const result = await isAdmin({\n * account: ...,\n * });\n * \n * ```\n */\nexport async function isAdmin(\n options: BaseTransactionOptions<IsAdminParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x24d7806c\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_account\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isValidSigner\" function.\n */\nexport type IsValidSignerParams = {\n signer: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_signer\"}>\nuserOp: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"_userOp\",\"components\":[{\"type\":\"address\",\"name\":\"sender\"},{\"type\":\"uint256\",\"name\":\"nonce\"},{\"type\":\"bytes\",\"name\":\"initCode\"},{\"type\":\"bytes\",\"name\":\"callData\"},{\"type\":\"uint256\",\"name\":\"callGasLimit\"},{\"type\":\"uint256\",\"name\":\"verificationGasLimit\"},{\"type\":\"uint256\",\"name\":\"preVerificationGas\"},{\"type\":\"uint256\",\"name\":\"maxFeePerGas\"},{\"type\":\"uint256\",\"name\":\"maxPriorityFeePerGas\"},{\"type\":\"bytes\",\"name\":\"paymasterAndData\"},{\"type\":\"bytes\",\"name\":\"signature\"}]}>\n};\n\n/**\n * Calls the \"isValidSigner\" function on the contract.\n * @param options - The options for the isValidSigner function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isValidSigner } from \"TODO\";\n * \n * const result = await isValidSigner({\n * signer: ...,\n * userOp: ...,\n * });\n * \n * ```\n */\nexport async function isValidSigner(\n options: BaseTransactionOptions<IsValidSignerParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x1dd756c5\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_signer\"\n },\n {\n \"type\": \"tuple\",\n \"name\": \"_userOp\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"sender\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nonce\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"initCode\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"callData\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"callGasLimit\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"verificationGasLimit\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"preVerificationGas\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"maxFeePerGas\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"maxPriorityFeePerGas\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"paymasterAndData\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"signature\"\n }\n ]\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.signer, options.userOp]\n });\n};\n\n\n/**\n * Represents the parameters for the \"verifySignerPermissionRequest\" function.\n */\nexport type VerifySignerPermissionRequestParams = {\n req: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"req\",\"components\":[{\"type\":\"address\",\"name\":\"signer\"},{\"type\":\"uint8\",\"name\":\"isAdmin\"},{\"type\":\"address[]\",\"name\":\"approvedTargets\"},{\"type\":\"uint256\",\"name\":\"nativeTokenLimitPerTransaction\"},{\"type\":\"uint128\",\"name\":\"permissionStartTimestamp\"},{\"type\":\"uint128\",\"name\":\"permissionEndTimestamp\"},{\"type\":\"uint128\",\"name\":\"reqValidityStartTimestamp\"},{\"type\":\"uint128\",\"name\":\"reqValidityEndTimestamp\"},{\"type\":\"bytes32\",\"name\":\"uid\"}]}>\nsignature: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"signature\"}>\n};\n\n/**\n * Calls the \"verifySignerPermissionRequest\" function on the contract.\n * @param options - The options for the verifySignerPermissionRequest function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { verifySignerPermissionRequest } from \"TODO\";\n * \n * const result = await verifySignerPermissionRequest({\n * req: ...,\n * signature: ...,\n * });\n * \n * ```\n */\nexport async function verifySignerPermissionRequest(\n options: BaseTransactionOptions<VerifySignerPermissionRequestParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xa9082d84\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"req\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"uint8\",\n \"name\": \"isAdmin\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"permissionStartTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"permissionEndTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"reqValidityStartTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"reqValidityEndTimestamp\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"uid\"\n }\n ]\n },\n {\n \"type\": \"bytes\",\n \"name\": \"signature\"\n }\n ],\n [\n {\n \"type\": \"bool\",\n \"name\": \"success\"\n },\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n }\n ]\n],\n params: [options.req, options.signature]\n });\n};\n\n\n\n\n/**\n * Calls the \"contractURI\" function on the contract.\n * @param options - The options for the contractURI function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { contractURI } from \"TODO\";\n * \n * const result = await contractURI();\n * \n * ```\n */\nexport async function contractURI(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xe8a3d485\",\n [],\n [\n {\n \"type\": \"string\"\n }\n ]\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"getMessageHash\" function.\n */\nexport type GetMessageHashParams = {\n hash: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"_hash\"}>\n};\n\n/**\n * Calls the \"getMessageHash\" function on the contract.\n * @param options - The options for the getMessageHash function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getMessageHash } from \"TODO\";\n * \n * const result = await getMessageHash({\n * hash: ...,\n * });\n * \n * ```\n */\nexport async function getMessageHash(\n options: BaseTransactionOptions<GetMessageHashParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x399b77da\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"_hash\"\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.hash]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isValidSignature\" function.\n */\nexport type IsValidSignatureParams = {\n hash: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"_hash\"}>\nsignature: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_signature\"}>\n};\n\n/**\n * Calls the \"isValidSignature\" function on the contract.\n * @param options - The options for the isValidSignature function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isValidSignature } from \"TODO\";\n * \n * const result = await isValidSignature({\n * hash: ...,\n * signature: ...,\n * });\n * \n * ```\n */\nexport async function isValidSignature(\n options: BaseTransactionOptions<IsValidSignatureParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x1626ba7e\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"_hash\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_signature\"\n }\n ],\n [\n {\n \"type\": \"bytes4\",\n \"name\": \"magicValue\"\n }\n ]\n],\n params: [options.hash, options.signature]\n });\n};\n\n\n/**\n * Represents the parameters for the \"supportsInterface\" function.\n */\nexport type SupportsInterfaceParams = {\n interfaceId: AbiParameterToPrimitiveType<{\"type\":\"bytes4\",\"name\":\"interfaceId\"}>\n};\n\n/**\n * Calls the \"supportsInterface\" function on the contract.\n * @param options - The options for the supportsInterface function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { supportsInterface } from \"TODO\";\n * \n * const result = await supportsInterface({\n * interfaceId: ...,\n * });\n * \n * ```\n */\nexport async function supportsInterface(\n options: BaseTransactionOptions<SupportsInterfaceParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x01ffc9a7\",\n [\n {\n \"type\": \"bytes4\",\n \"name\": \"interfaceId\"\n }\n ],\n [\n {\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.interfaceId]\n });\n};\n\n\n\n\n/**\n * Calls the \"eip712Domain\" function on the contract.\n * @param options - The options for the eip712Domain function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { eip712Domain } from \"TODO\";\n * \n * const result = await eip712Domain();\n * \n * ```\n */\nexport async function eip712Domain(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x84b0196e\",\n [],\n [\n {\n \"type\": \"bytes1\",\n \"name\": \"fields\"\n },\n {\n \"type\": \"string\",\n \"name\": \"name\"\n },\n {\n \"type\": \"string\",\n \"name\": \"version\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"chainId\"\n },\n {\n \"type\": \"address\",\n \"name\": \"verifyingContract\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"salt\"\n },\n {\n \"type\": \"uint256[]\",\n \"name\": \"extensions\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"getEas\" function on the contract.\n * @param options - The options for the getEas function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getEas } from \"TODO\";\n * \n * const result = await getEas();\n * \n * ```\n */\nexport async function getEas(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xd5f5127d\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n\n\n/**\n * Calls the \"owner\" function on the contract.\n * @param options - The options for the owner function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { owner } from \"TODO\";\n * \n * const result = await owner();\n * \n * ```\n */\nexport async function owner(\n options: BaseTransactionOptions\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x8da5cb5b\",\n [],\n [\n {\n \"type\": \"address\"\n }\n ]\n],\n params: []\n });\n};\n\n\n/**\n* Contract write functions\n*/\n\n/**\n * Represents the parameters for the \"initialize\" function.\n */\nexport type InitializeParams = {\n defaultAdmin: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_defaultAdmin\"}>\ndata: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_data\"}>\n};\n\n/**\n * Calls the \"initialize\" function on the contract.\n * @param options - The options for the \"initialize\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { initialize } from \"TODO\";\n * \n * const transaction = initialize({\n * defaultAdmin: ...,\n * data: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function initialize(\n options: BaseTransactionOptions<InitializeParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xd1f57894\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_defaultAdmin\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_data\"\n }\n ],\n []\n],\n params: [options.defaultAdmin, options.data]\n });\n};\n\n\n/**\n * Represents the parameters for the \"multicall\" function.\n */\nexport type MulticallParams = {\n data: AbiParameterToPrimitiveType<{\"type\":\"bytes[]\",\"name\":\"data\"}>\n};\n\n/**\n * Calls the \"multicall\" function on the contract.\n * @param options - The options for the \"multicall\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { multicall } from \"TODO\";\n * \n * const transaction = multicall({\n * data: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function multicall(\n options: BaseTransactionOptions<MulticallParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xac9650d8\",\n [\n {\n \"type\": \"bytes[]\",\n \"name\": \"data\"\n }\n ],\n [\n {\n \"type\": \"bytes[]\",\n \"name\": \"results\"\n }\n ]\n],\n params: [options.data]\n });\n};\n\n\n/**\n * Represents the parameters for the \"setEntrypointOverride\" function.\n */\nexport type SetEntrypointOverrideParams = {\n entrypointOverride: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_entrypointOverride\"}>\n};\n\n/**\n * Calls the \"setEntrypointOverride\" function on the contract.\n * @param options - The options for the \"setEntrypointOverride\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { setEntrypointOverride } from \"TODO\";\n * \n * const transaction = setEntrypointOverride({\n * entrypointOverride: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function setEntrypointOverride(\n options: BaseTransactionOptions<SetEntrypointOverrideParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xb76464d5\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_entrypointOverride\"\n }\n ],\n []\n],\n params: [options.entrypointOverride]\n });\n};\n\n\n/**\n * Represents the parameters for the \"setPermissionsForSigner\" function.\n */\nexport type SetPermissionsForSignerParams = {\n req: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"_req\",\"components\":[{\"type\":\"address\",\"name\":\"signer\"},{\"type\":\"uint8\",\"name\":\"isAdmin\"},{\"type\":\"address[]\",\"name\":\"approvedTargets\"},{\"type\":\"uint256\",\"name\":\"nativeTokenLimitPerTransaction\"},{\"type\":\"uint128\",\"name\":\"permissionStartTimestamp\"},{\"type\":\"uint128\",\"name\":\"permissionEndTimestamp\"},{\"type\":\"uint128\",\"name\":\"reqValidityStartTimestamp\"},{\"type\":\"uint128\",\"name\":\"reqValidityEndTimestamp\"},{\"type\":\"bytes32\",\"name\":\"uid\"}]}>\nsignature: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_signature\"}>\n};\n\n/**\n * Calls the \"setPermissionsForSigner\" function on the contract.\n * @param options - The options for the \"setPermissionsForSigner\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { setPermissionsForSigner } from \"TODO\";\n * \n * const transaction = setPermissionsForSigner({\n * req: ...,\n * signature: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function setPermissionsForSigner(\n options: BaseTransactionOptions<SetPermissionsForSignerParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x5892e236\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"_req\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"signer\"\n },\n {\n \"type\": \"uint8\",\n \"name\": \"isAdmin\"\n },\n {\n \"type\": \"address[]\",\n \"name\": \"approvedTargets\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nativeTokenLimitPerTransaction\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"permissionStartTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"permissionEndTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"reqValidityStartTimestamp\"\n },\n {\n \"type\": \"uint128\",\n \"name\": \"reqValidityEndTimestamp\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"uid\"\n }\n ]\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_signature\"\n }\n ],\n []\n],\n params: [options.req, options.signature]\n });\n};\n\n\n/**\n * Represents the parameters for the \"validateUserOp\" function.\n */\nexport type ValidateUserOpParams = {\n userOp: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"userOp\",\"components\":[{\"type\":\"address\",\"name\":\"sender\"},{\"type\":\"uint256\",\"name\":\"nonce\"},{\"type\":\"bytes\",\"name\":\"initCode\"},{\"type\":\"bytes\",\"name\":\"callData\"},{\"type\":\"uint256\",\"name\":\"callGasLimit\"},{\"type\":\"uint256\",\"name\":\"verificationGasLimit\"},{\"type\":\"uint256\",\"name\":\"preVerificationGas\"},{\"type\":\"uint256\",\"name\":\"maxFeePerGas\"},{\"type\":\"uint256\",\"name\":\"maxPriorityFeePerGas\"},{\"type\":\"bytes\",\"name\":\"paymasterAndData\"},{\"type\":\"bytes\",\"name\":\"signature\"}]}>\nuserOpHash: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"userOpHash\"}>\nmissingAccountFunds: AbiParameterToPrimitiveType<{\"type\":\"uint256\",\"name\":\"missingAccountFunds\"}>\n};\n\n/**\n * Calls the \"validateUserOp\" function on the contract.\n * @param options - The options for the \"validateUserOp\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { validateUserOp } from \"TODO\";\n * \n * const transaction = validateUserOp({\n * userOp: ...,\n * userOpHash: ...,\n * missingAccountFunds: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function validateUserOp(\n options: BaseTransactionOptions<ValidateUserOpParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x3a871cdd\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"userOp\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"sender\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"nonce\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"initCode\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"callData\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"callGasLimit\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"verificationGasLimit\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"preVerificationGas\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"maxFeePerGas\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"maxPriorityFeePerGas\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"paymasterAndData\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"signature\"\n }\n ]\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"userOpHash\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"missingAccountFunds\"\n }\n ],\n [\n {\n \"type\": \"uint256\",\n \"name\": \"validationData\"\n }\n ]\n],\n params: [options.userOp, options.userOpHash, options.missingAccountFunds]\n });\n};\n\n\n\n\n/**\n * Calls the \"addDeposit\" function on the contract.\n * @param options - The options for the \"addDeposit\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { addDeposit } from \"TODO\";\n * \n * const transaction = addDeposit();\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function addDeposit(\n options: BaseTransactionOptions\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x4a58db19\",\n [],\n []\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"execute\" function.\n */\nexport type ExecuteParams = {\n target: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_target\"}>\nvalue: AbiParameterToPrimitiveType<{\"type\":\"uint256\",\"name\":\"_value\"}>\ncalldata: AbiParameterToPrimitiveType<{\"type\":\"bytes\",\"name\":\"_calldata\"}>\n};\n\n/**\n * Calls the \"execute\" function on the contract.\n * @param options - The options for the \"execute\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { execute } from \"TODO\";\n * \n * const transaction = execute({\n * target: ...,\n * value: ...,\n * calldata: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function execute(\n options: BaseTransactionOptions<ExecuteParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xb61d27f6\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_target\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"_value\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"_calldata\"\n }\n ],\n []\n],\n params: [options.target, options.value, options.calldata]\n });\n};\n\n\n/**\n * Represents the parameters for the \"executeBatch\" function.\n */\nexport type ExecuteBatchParams = {\n target: AbiParameterToPrimitiveType<{\"type\":\"address[]\",\"name\":\"_target\"}>\nvalue: AbiParameterToPrimitiveType<{\"type\":\"uint256[]\",\"name\":\"_value\"}>\ncalldata: AbiParameterToPrimitiveType<{\"type\":\"bytes[]\",\"name\":\"_calldata\"}>\n};\n\n/**\n * Calls the \"executeBatch\" function on the contract.\n * @param options - The options for the \"executeBatch\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { executeBatch } from \"TODO\";\n * \n * const transaction = executeBatch({\n * target: ...,\n * value: ...,\n * calldata: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function executeBatch(\n options: BaseTransactionOptions<ExecuteBatchParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x47e1da2a\",\n [\n {\n \"type\": \"address[]\",\n \"name\": \"_target\"\n },\n {\n \"type\": \"uint256[]\",\n \"name\": \"_value\"\n },\n {\n \"type\": \"bytes[]\",\n \"name\": \"_calldata\"\n }\n ],\n []\n],\n params: [options.target, options.value, options.calldata]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onERC1155BatchReceived\" function.\n */\nexport type OnERC1155BatchReceivedParams = {\n arg_0: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_1: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_2: AbiParameterToPrimitiveType<{\"type\":\"uint256[]\"}>\narg_3: AbiParameterToPrimitiveType<{\"type\":\"uint256[]\"}>\narg_4: AbiParameterToPrimitiveType<{\"type\":\"bytes\"}>\n};\n\n/**\n * Calls the \"onERC1155BatchReceived\" function on the contract.\n * @param options - The options for the \"onERC1155BatchReceived\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onERC1155BatchReceived } from \"TODO\";\n * \n * const transaction = onERC1155BatchReceived({\n * arg_0: ...,\n * arg_1: ...,\n * arg_2: ...,\n * arg_3: ...,\n * arg_4: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onERC1155BatchReceived(\n options: BaseTransactionOptions<OnERC1155BatchReceivedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xbc197c81\",\n [\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"uint256[]\"\n },\n {\n \"type\": \"uint256[]\"\n },\n {\n \"type\": \"bytes\"\n }\n ],\n [\n {\n \"type\": \"bytes4\"\n }\n ]\n],\n params: [options.arg_0, options.arg_1, options.arg_2, options.arg_3, options.arg_4]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onERC1155Received\" function.\n */\nexport type OnERC1155ReceivedParams = {\n arg_0: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_1: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_2: AbiParameterToPrimitiveType<{\"type\":\"uint256\"}>\narg_3: AbiParameterToPrimitiveType<{\"type\":\"uint256\"}>\narg_4: AbiParameterToPrimitiveType<{\"type\":\"bytes\"}>\n};\n\n/**\n * Calls the \"onERC1155Received\" function on the contract.\n * @param options - The options for the \"onERC1155Received\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onERC1155Received } from \"TODO\";\n * \n * const transaction = onERC1155Received({\n * arg_0: ...,\n * arg_1: ...,\n * arg_2: ...,\n * arg_3: ...,\n * arg_4: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onERC1155Received(\n options: BaseTransactionOptions<OnERC1155ReceivedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xf23a6e61\",\n [\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"uint256\"\n },\n {\n \"type\": \"uint256\"\n },\n {\n \"type\": \"bytes\"\n }\n ],\n [\n {\n \"type\": \"bytes4\"\n }\n ]\n],\n params: [options.arg_0, options.arg_1, options.arg_2, options.arg_3, options.arg_4]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onERC721Received\" function.\n */\nexport type OnERC721ReceivedParams = {\n arg_0: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_1: AbiParameterToPrimitiveType<{\"type\":\"address\"}>\narg_2: AbiParameterToPrimitiveType<{\"type\":\"uint256\"}>\narg_3: AbiParameterToPrimitiveType<{\"type\":\"bytes\"}>\n};\n\n/**\n * Calls the \"onERC721Received\" function on the contract.\n * @param options - The options for the \"onERC721Received\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onERC721Received } from \"TODO\";\n * \n * const transaction = onERC721Received({\n * arg_0: ...,\n * arg_1: ...,\n * arg_2: ...,\n * arg_3: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function onERC721Received(\n options: BaseTransactionOptions<OnERC721ReceivedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x150b7a02\",\n [\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"address\"\n },\n {\n \"type\": \"uint256\"\n },\n {\n \"type\": \"bytes\"\n }\n ],\n [\n {\n \"type\": \"bytes4\"\n }\n ]\n],\n params: [options.arg_0, options.arg_1, options.arg_2, options.arg_3]\n });\n};\n\n\n/**\n * Represents the parameters for the \"setContractURI\" function.\n */\nexport type SetContractURIParams = {\n uri: AbiParameterToPrimitiveType<{\"type\":\"string\",\"name\":\"_uri\"}>\n};\n\n/**\n * Calls the \"setContractURI\" function on the contract.\n * @param options - The options for the \"setContractURI\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { setContractURI } from \"TODO\";\n * \n * const transaction = setContractURI({\n * uri: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function setContractURI(\n options: BaseTransactionOptions<SetContractURIParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x938e3d7b\",\n [\n {\n \"type\": \"string\",\n \"name\": \"_uri\"\n }\n ],\n []\n],\n params: [options.uri]\n });\n};\n\n\n/**\n * Represents the parameters for the \"withdrawDepositTo\" function.\n */\nexport type WithdrawDepositToParams = {\n withdrawAddress: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"withdrawAddress\"}>\namount: AbiParameterToPrimitiveType<{\"type\":\"uint256\",\"name\":\"amount\"}>\n};\n\n/**\n * Calls the \"withdrawDepositTo\" function on the contract.\n * @param options - The options for the \"withdrawDepositTo\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { withdrawDepositTo } from \"TODO\";\n * \n * const transaction = withdrawDepositTo({\n * withdrawAddress: ...,\n * amount: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function withdrawDepositTo(\n options: BaseTransactionOptions<WithdrawDepositToParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x4d44560d\",\n [\n {\n \"type\": \"address\",\n \"name\": \"withdrawAddress\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"amount\"\n }\n ],\n []\n],\n params: [options.withdrawAddress, options.amount]\n });\n};\n\n\n/**\n * Represents the parameters for the \"createSeed\" function.\n */\nexport type CreateSeedParams = {\n schemaUid: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"schemaUid\"}>\nrevocable: AbiParameterToPrimitiveType<{\"type\":\"bool\",\"name\":\"revocable\"}>\n};\n\n/**\n * Calls the \"createSeed\" function on the contract.\n * @param options - The options for the \"createSeed\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { createSeed } from \"TODO\";\n * \n * const transaction = createSeed({\n * schemaUid: ...,\n * revocable: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function createSeed(\n options: BaseTransactionOptions<CreateSeedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x6240d6d9\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"schemaUid\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"revocable\"\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.schemaUid, options.revocable]\n });\n};\n\n\n/**\n * Represents the parameters for the \"createVersion\" function.\n */\nexport type CreateVersionParams = {\n seedUid: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"seedUid\"}>\nversionSchemaUid: AbiParameterToPrimitiveType<{\"type\":\"bytes32\",\"name\":\"versionSchemaUid\"}>\n};\n\n/**\n * Calls the \"createVersion\" function on the contract.\n * @param options - The options for the \"createVersion\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { createVersion } from \"TODO\";\n * \n * const transaction = createVersion({\n * seedUid: ...,\n * versionSchemaUid: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function createVersion(\n options: BaseTransactionOptions<CreateVersionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x13e0c263\",\n [\n {\n \"type\": \"bytes32\",\n \"name\": \"seedUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionSchemaUid\"\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.seedUid, options.versionSchemaUid]\n });\n};\n\n\n/**\n * Represents the parameters for the \"multiPublish\" function.\n */\nexport type MultiPublishParams = {\n requests: AbiParameterToPrimitiveType<{\"type\":\"tuple[]\",\"name\":\"requests\",\"components\":[{\"type\":\"string\",\"name\":\"localId\"},{\"type\":\"bytes32\",\"name\":\"seedUid\"},{\"type\":\"bytes32\",\"name\":\"seedSchemaUid\"},{\"type\":\"bytes32\",\"name\":\"versionUid\"},{\"type\":\"bytes32\",\"name\":\"versionSchemaUid\"},{\"type\":\"bool\",\"name\":\"seedIsRevocable\"},{\"type\":\"tuple[]\",\"name\":\"listOfAttestations\",\"components\":[{\"type\":\"bytes32\",\"name\":\"schema\"},{\"type\":\"tuple[]\",\"name\":\"data\",\"components\":[{\"type\":\"address\",\"name\":\"recipient\"},{\"type\":\"uint64\",\"name\":\"expirationTime\"},{\"type\":\"bool\",\"name\":\"revocable\"},{\"type\":\"bytes32\",\"name\":\"refUID\"},{\"type\":\"bytes\",\"name\":\"data\"},{\"type\":\"uint256\",\"name\":\"value\"}]}]},{\"type\":\"tuple[]\",\"name\":\"propertiesToUpdate\",\"components\":[{\"type\":\"string\",\"name\":\"publishLocalId\"},{\"type\":\"bytes32\",\"name\":\"propertySchemaUid\"}]}]}>\n};\n\n/**\n * Calls the \"multiPublish\" function on the contract.\n * @param options - The options for the \"multiPublish\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { multiPublish } from \"TODO\";\n * \n * const transaction = multiPublish({\n * requests: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function multiPublish(\n options: BaseTransactionOptions<MultiPublishParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x31e19cb8\",\n [\n {\n \"type\": \"tuple[]\",\n \"name\": \"requests\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"localId\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"seedUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"seedSchemaUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionSchemaUid\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"seedIsRevocable\"\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"listOfAttestations\",\n \"components\": [\n {\n \"type\": \"bytes32\",\n \"name\": \"schema\"\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"data\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"recipient\"\n },\n {\n \"type\": \"uint64\",\n \"name\": \"expirationTime\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"revocable\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"refUID\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"data\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"value\"\n }\n ]\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"propertiesToUpdate\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"publishLocalId\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"propertySchemaUid\"\n }\n ]\n }\n ]\n }\n ],\n [\n {\n \"type\": \"bytes32[]\"\n }\n ]\n],\n params: [options.requests],\n });\n};\n\n/**\n * multiPublish variant that uses uint256 localIdIndex and publishLocalIdIndex instead of strings.\n * Use when the contract expects integer-based IDs (gas-efficient).\n * Selector: keccak256(\"multiPublish((uint256,bytes32,...)[])[]\") -> 0xd688e801\n */\nexport type MultiPublishWithIntegerIdsParams = {\n requests: Array<{\n localIdIndex: bigint\n seedUid: `0x${string}`\n seedSchemaUid: `0x${string}`\n versionUid: `0x${string}`\n versionSchemaUid: `0x${string}`\n seedIsRevocable: boolean\n listOfAttestations: Array<{\n schema: `0x${string}`\n data: Array<{\n recipient: `0x${string}`\n expirationTime: bigint\n revocable: boolean\n refUID: `0x${string}`\n data: `0x${string}`\n value: bigint\n }>\n }>\n propertiesToUpdate: Array<{\n publishLocalIdIndex: bigint\n propertySchemaUid: `0x${string}`\n }>\n }>\n}\n\nexport function multiPublishWithIntegerIds(\n options: BaseTransactionOptions<MultiPublishWithIntegerIdsParams>,\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xd688e801\",\n [\n {\n \"type\": \"tuple[]\",\n \"name\": \"requests\",\n \"components\": [\n { \"type\": \"uint256\", \"name\": \"localIdIndex\" },\n { \"type\": \"bytes32\", \"name\": \"seedUid\" },\n { \"type\": \"bytes32\", \"name\": \"seedSchemaUid\" },\n { \"type\": \"bytes32\", \"name\": \"versionUid\" },\n { \"type\": \"bytes32\", \"name\": \"versionSchemaUid\" },\n { \"type\": \"bool\", \"name\": \"seedIsRevocable\" },\n {\n \"type\": \"tuple[]\",\n \"name\": \"listOfAttestations\",\n \"components\": [\n { \"type\": \"bytes32\", \"name\": \"schema\" },\n {\n \"type\": \"tuple[]\",\n \"name\": \"data\",\n \"components\": [\n { \"type\": \"address\", \"name\": \"recipient\" },\n { \"type\": \"uint64\", \"name\": \"expirationTime\" },\n { \"type\": \"bool\", \"name\": \"revocable\" },\n { \"type\": \"bytes32\", \"name\": \"refUID\" },\n { \"type\": \"bytes\", \"name\": \"data\" },\n { \"type\": \"uint256\", \"name\": \"value\" },\n ],\n },\n ],\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"propertiesToUpdate\",\n \"components\": [\n { \"type\": \"uint256\", \"name\": \"publishLocalIdIndex\" },\n { \"type\": \"bytes32\", \"name\": \"propertySchemaUid\" },\n ],\n },\n ],\n },\n ],\n [{ \"type\": \"bytes32[]\" }],\n ],\n params: [options.requests],\n });\n}\n\n/**\n * Represents the parameters for the \"publish\" function.\n */\nexport type PublishParams = {\n request: AbiParameterToPrimitiveType<{\"type\":\"tuple\",\"name\":\"request\",\"components\":[{\"type\":\"string\",\"name\":\"localId\"},{\"type\":\"bytes32\",\"name\":\"seedUid\"},{\"type\":\"bytes32\",\"name\":\"seedSchemaUid\"},{\"type\":\"bytes32\",\"name\":\"versionUid\"},{\"type\":\"bytes32\",\"name\":\"versionSchemaUid\"},{\"type\":\"bool\",\"name\":\"seedIsRevocable\"},{\"type\":\"tuple[]\",\"name\":\"listOfAttestations\",\"components\":[{\"type\":\"bytes32\",\"name\":\"schema\"},{\"type\":\"tuple[]\",\"name\":\"data\",\"components\":[{\"type\":\"address\",\"name\":\"recipient\"},{\"type\":\"uint64\",\"name\":\"expirationTime\"},{\"type\":\"bool\",\"name\":\"revocable\"},{\"type\":\"bytes32\",\"name\":\"refUID\"},{\"type\":\"bytes\",\"name\":\"data\"},{\"type\":\"uint256\",\"name\":\"value\"}]}]},{\"type\":\"tuple[]\",\"name\":\"propertiesToUpdate\",\"components\":[{\"type\":\"string\",\"name\":\"publishLocalId\"},{\"type\":\"bytes32\",\"name\":\"propertySchemaUid\"}]}]}>\n};\n\n/**\n * Calls the \"publish\" function on the contract.\n * @param options - The options for the \"publish\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { publish } from \"TODO\";\n * \n * const transaction = publish({\n * request: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function publish(\n options: BaseTransactionOptions<PublishParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xb71308c5\",\n [\n {\n \"type\": \"tuple\",\n \"name\": \"request\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"localId\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"seedUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"seedSchemaUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionUid\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"versionSchemaUid\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"seedIsRevocable\"\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"listOfAttestations\",\n \"components\": [\n {\n \"type\": \"bytes32\",\n \"name\": \"schema\"\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"data\",\n \"components\": [\n {\n \"type\": \"address\",\n \"name\": \"recipient\"\n },\n {\n \"type\": \"uint64\",\n \"name\": \"expirationTime\"\n },\n {\n \"type\": \"bool\",\n \"name\": \"revocable\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"refUID\"\n },\n {\n \"type\": \"bytes\",\n \"name\": \"data\"\n },\n {\n \"type\": \"uint256\",\n \"name\": \"value\"\n }\n ]\n }\n ]\n },\n {\n \"type\": \"tuple[]\",\n \"name\": \"propertiesToUpdate\",\n \"components\": [\n {\n \"type\": \"string\",\n \"name\": \"publishLocalId\"\n },\n {\n \"type\": \"bytes32\",\n \"name\": \"propertySchemaUid\"\n }\n ]\n }\n ]\n }\n ],\n [\n {\n \"type\": \"bytes32\"\n },\n {\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.request]\n });\n};\n\n\n\n\n/**\n * Calls the \"renounceOwnership\" function on the contract.\n * @param options - The options for the \"renounceOwnership\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { renounceOwnership } from \"TODO\";\n * \n * const transaction = renounceOwnership();\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function renounceOwnership(\n options: BaseTransactionOptions\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x715018a6\",\n [],\n []\n],\n params: []\n });\n};\n\n\n/**\n * Represents the parameters for the \"setEas\" function.\n */\nexport type SetEasParams = {\n eas: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"_eas\"}>\n};\n\n/**\n * Calls the \"setEas\" function on the contract.\n * @param options - The options for the \"setEas\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { setEas } from \"TODO\";\n * \n * const transaction = setEas({\n * eas: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function setEas(\n options: BaseTransactionOptions<SetEasParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xb90b6e0d\",\n [\n {\n \"type\": \"address\",\n \"name\": \"_eas\"\n }\n ],\n [\n {\n \"type\": \"string\"\n }\n ]\n],\n params: [options.eas]\n });\n};\n\n\n/**\n * Represents the parameters for the \"transferOwnership\" function.\n */\nexport type TransferOwnershipParams = {\n newOwner: AbiParameterToPrimitiveType<{\"type\":\"address\",\"name\":\"newOwner\"}>\n};\n\n/**\n * Calls the \"transferOwnership\" function on the contract.\n * @param options - The options for the \"transferOwnership\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { transferOwnership } from \"TODO\";\n * \n * const transaction = transferOwnership({\n * newOwner: ...,\n * });\n * \n * // Send the transaction\n * ...\n * \n * ```\n */\nexport function transferOwnership(\n options: BaseTransactionOptions<TransferOwnershipParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0xf2fde38b\",\n [\n {\n \"type\": \"address\",\n \"name\": \"newOwner\"\n }\n ],\n []\n],\n params: [options.newOwner]\n });\n};\n\n\n","// From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/globalThis\nfunction getGlobal() {\n if (typeof globalThis !== 'undefined') {\n return globalThis;\n }\n if (typeof self !== 'undefined') {\n return self;\n }\n if (typeof window !== 'undefined') {\n return window;\n }\n if (typeof global !== 'undefined') {\n return global;\n }\n}\nfunction getDevTools() {\n const w = getGlobal();\n if (w.__xstate__) {\n return w.__xstate__;\n }\n return undefined;\n}\nfunction registerService(service) {\n if (typeof window === 'undefined') {\n return;\n }\n const devTools = getDevTools();\n if (devTools) {\n devTools.register(service);\n }\n}\nconst devToolsAdapter = service => {\n if (typeof window === 'undefined') {\n return;\n }\n const devTools = getDevTools();\n if (devTools) {\n devTools.register(service);\n }\n};\n\nexport { devToolsAdapter, getGlobal, registerService };\n","import { devToolsAdapter } from '../dev/dist/xstate-dev.esm.js';\n\nclass Mailbox {\n constructor(_process) {\n this._process = _process;\n this._active = false;\n this._current = null;\n this._last = null;\n }\n start() {\n this._active = true;\n this.flush();\n }\n clear() {\n // we can't set _current to null because we might be currently processing\n // and enqueue following clear shouldn't start processing the enqueued item immediately\n if (this._current) {\n this._current.next = null;\n this._last = this._current;\n }\n }\n enqueue(event) {\n const enqueued = {\n value: event,\n next: null\n };\n if (this._current) {\n this._last.next = enqueued;\n this._last = enqueued;\n return;\n }\n this._current = enqueued;\n this._last = enqueued;\n if (this._active) {\n this.flush();\n }\n }\n flush() {\n while (this._current) {\n // atm the given _process is responsible for implementing proper try/catch handling\n // we assume here that this won't throw in a way that can affect this mailbox\n const consumed = this._current;\n this._process(consumed.value);\n this._current = consumed.next;\n }\n this._last = null;\n }\n}\n\nconst STATE_DELIMITER = '.';\nconst TARGETLESS_KEY = '';\nconst NULL_EVENT = '';\nconst STATE_IDENTIFIER = '#';\nconst WILDCARD = '*';\nconst XSTATE_INIT = 'xstate.init';\nconst XSTATE_ERROR = 'xstate.error';\nconst XSTATE_STOP = 'xstate.stop';\n\n/**\n * Returns an event that represents an implicit event that is sent after the\n * specified `delay`.\n *\n * @param delayRef The delay in milliseconds\n * @param id The state node ID where this event is handled\n */\nfunction createAfterEvent(delayRef, id) {\n return {\n type: `xstate.after.${delayRef}.${id}`\n };\n}\n\n/**\n * Returns an event that represents that a final state node has been reached in\n * the parent state node.\n *\n * @param id The final state node's parent state node `id`\n * @param output The data to pass into the event\n */\nfunction createDoneStateEvent(id, output) {\n return {\n type: `xstate.done.state.${id}`,\n output\n };\n}\n\n/**\n * Returns an event that represents that an invoked service has terminated.\n *\n * An invoked service is terminated when it has reached a top-level final state\n * node, but not when it is canceled.\n *\n * @param invokeId The invoked service ID\n * @param output The data to pass into the event\n */\nfunction createDoneActorEvent(invokeId, output) {\n return {\n type: `xstate.done.actor.${invokeId}`,\n output,\n actorId: invokeId\n };\n}\nfunction createErrorActorEvent(id, error) {\n return {\n type: `xstate.error.actor.${id}`,\n error,\n actorId: id\n };\n}\nfunction createInitEvent(input) {\n return {\n type: XSTATE_INIT,\n input\n };\n}\n\n/**\n * This function makes sure that unhandled errors are thrown in a separate\n * macrotask. It allows those errors to be detected by global error handlers and\n * reported to bug tracking services without interrupting our own stack of\n * execution.\n *\n * @param err Error to be thrown\n */\nfunction reportUnhandledError(err) {\n setTimeout(() => {\n throw err;\n });\n}\n\nconst symbolObservable = (() => typeof Symbol === 'function' && Symbol.observable || '@@observable')();\n\nfunction matchesState(parentStateId, childStateId) {\n const parentStateValue = toStateValue(parentStateId);\n const childStateValue = toStateValue(childStateId);\n if (typeof childStateValue === 'string') {\n if (typeof parentStateValue === 'string') {\n return childStateValue === parentStateValue;\n }\n\n // Parent more specific than child\n return false;\n }\n if (typeof parentStateValue === 'string') {\n return parentStateValue in childStateValue;\n }\n return Object.keys(parentStateValue).every(key => {\n if (!(key in childStateValue)) {\n return false;\n }\n return matchesState(parentStateValue[key], childStateValue[key]);\n });\n}\nfunction toStatePath(stateId) {\n if (isArray(stateId)) {\n return stateId;\n }\n const result = [];\n let segment = '';\n for (let i = 0; i < stateId.length; i++) {\n const char = stateId.charCodeAt(i);\n switch (char) {\n // \\\n case 92:\n // consume the next character\n segment += stateId[i + 1];\n // and skip over it\n i++;\n continue;\n // .\n case 46:\n result.push(segment);\n segment = '';\n continue;\n }\n segment += stateId[i];\n }\n result.push(segment);\n return result;\n}\nfunction toStateValue(stateValue) {\n if (isMachineSnapshot(stateValue)) {\n return stateValue.value;\n }\n if (typeof stateValue !== 'string') {\n return stateValue;\n }\n const statePath = toStatePath(stateValue);\n return pathToStateValue(statePath);\n}\nfunction pathToStateValue(statePath) {\n if (statePath.length === 1) {\n return statePath[0];\n }\n const value = {};\n let marker = value;\n for (let i = 0; i < statePath.length - 1; i++) {\n if (i === statePath.length - 2) {\n marker[statePath[i]] = statePath[i + 1];\n } else {\n const previous = marker;\n marker = {};\n previous[statePath[i]] = marker;\n }\n }\n return value;\n}\nfunction mapValues(collection, iteratee) {\n const result = {};\n const collectionKeys = Object.keys(collection);\n for (let i = 0; i < collectionKeys.length; i++) {\n const key = collectionKeys[i];\n result[key] = iteratee(collection[key], key, collection, i);\n }\n return result;\n}\nfunction toArrayStrict(value) {\n if (isArray(value)) {\n return value;\n }\n return [value];\n}\nfunction toArray(value) {\n if (value === undefined) {\n return [];\n }\n return toArrayStrict(value);\n}\nfunction resolveOutput(mapper, context, event, self) {\n if (typeof mapper === 'function') {\n return mapper({\n context,\n event,\n self\n });\n }\n return mapper;\n}\nfunction isArray(value) {\n return Array.isArray(value);\n}\nfunction isErrorActorEvent(event) {\n return event.type.startsWith('xstate.error.actor');\n}\nfunction toTransitionConfigArray(configLike) {\n return toArrayStrict(configLike).map(transitionLike => {\n if (typeof transitionLike === 'undefined' || typeof transitionLike === 'string') {\n return {\n target: transitionLike\n };\n }\n return transitionLike;\n });\n}\nfunction normalizeTarget(target) {\n if (target === undefined || target === TARGETLESS_KEY) {\n return undefined;\n }\n return toArray(target);\n}\nfunction toObserver(nextHandler, errorHandler, completionHandler) {\n const isObserver = typeof nextHandler === 'object';\n const self = isObserver ? nextHandler : undefined;\n return {\n next: (isObserver ? nextHandler.next : nextHandler)?.bind(self),\n error: (isObserver ? nextHandler.error : errorHandler)?.bind(self),\n complete: (isObserver ? nextHandler.complete : completionHandler)?.bind(self)\n };\n}\nfunction createInvokeId(stateNodeId, index) {\n return `${index}.${stateNodeId}`;\n}\nfunction resolveReferencedActor(machine, src) {\n const match = src.match(/^xstate\\.invoke\\.(\\d+)\\.(.*)/);\n if (!match) {\n return machine.implementations.actors[src];\n }\n const [, indexStr, nodeId] = match;\n const node = machine.getStateNodeById(nodeId);\n const invokeConfig = node.config.invoke;\n return (Array.isArray(invokeConfig) ? invokeConfig[indexStr] : invokeConfig).src;\n}\nfunction getAllOwnEventDescriptors(snapshot) {\n return [...new Set([...snapshot._nodes.flatMap(sn => sn.ownEvents)])];\n}\n\n/**\n * Checks if an event type matches an event descriptor, supporting wildcards.\n * Event descriptors can be:\n *\n * - Exact matches: \"event.type\"\n * - Wildcard: \"*\"\n * - Partial matches: \"event.*\"\n *\n * @param eventType - The actual event type string\n * @param descriptor - The event descriptor to match against\n * @returns True if the event type matches the descriptor\n */\nfunction matchesEventDescriptor(eventType, descriptor) {\n if (descriptor === eventType) {\n return true;\n }\n if (descriptor === WILDCARD) {\n return true;\n }\n if (!descriptor.endsWith('.*')) {\n return false;\n }\n const partialEventTokens = descriptor.split('.');\n const eventTokens = eventType.split('.');\n for (let tokenIndex = 0; tokenIndex < partialEventTokens.length; tokenIndex++) {\n const partialEventToken = partialEventTokens[tokenIndex];\n const eventToken = eventTokens[tokenIndex];\n if (partialEventToken === '*') {\n const isLastToken = tokenIndex === partialEventTokens.length - 1;\n return isLastToken;\n }\n if (partialEventToken !== eventToken) {\n return false;\n }\n }\n return true;\n}\n\nfunction createScheduledEventId(actorRef, id) {\n return `${actorRef.sessionId}.${id}`;\n}\nlet idCounter = 0;\nfunction createSystem(rootActor, options) {\n const children = new Map();\n const keyedActors = new Map();\n const reverseKeyedActors = new WeakMap();\n const inspectionObservers = new Set();\n const timerMap = {};\n const {\n clock,\n logger\n } = options;\n const scheduler = {\n schedule: (source, target, event, delay, id = Math.random().toString(36).slice(2)) => {\n const scheduledEvent = {\n source,\n target,\n event,\n delay,\n id,\n startedAt: Date.now()\n };\n const scheduledEventId = createScheduledEventId(source, id);\n system._snapshot._scheduledEvents[scheduledEventId] = scheduledEvent;\n const timeout = clock.setTimeout(() => {\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n system._relay(source, target, event);\n }, delay);\n timerMap[scheduledEventId] = timeout;\n },\n cancel: (source, id) => {\n const scheduledEventId = createScheduledEventId(source, id);\n const timeout = timerMap[scheduledEventId];\n delete timerMap[scheduledEventId];\n delete system._snapshot._scheduledEvents[scheduledEventId];\n if (timeout !== undefined) {\n clock.clearTimeout(timeout);\n }\n },\n cancelAll: actorRef => {\n for (const scheduledEventId in system._snapshot._scheduledEvents) {\n const scheduledEvent = system._snapshot._scheduledEvents[scheduledEventId];\n if (scheduledEvent.source === actorRef) {\n scheduler.cancel(actorRef, scheduledEvent.id);\n }\n }\n }\n };\n const sendInspectionEvent = event => {\n if (!inspectionObservers.size) {\n return;\n }\n const resolvedInspectionEvent = {\n ...event,\n rootId: rootActor.sessionId\n };\n inspectionObservers.forEach(observer => observer.next?.(resolvedInspectionEvent));\n };\n const system = {\n _snapshot: {\n _scheduledEvents: (options?.snapshot && options.snapshot.scheduler) ?? {}\n },\n _bookId: () => `x:${idCounter++}`,\n _register: (sessionId, actorRef) => {\n children.set(sessionId, actorRef);\n return sessionId;\n },\n _unregister: actorRef => {\n children.delete(actorRef.sessionId);\n const systemId = reverseKeyedActors.get(actorRef);\n if (systemId !== undefined) {\n keyedActors.delete(systemId);\n reverseKeyedActors.delete(actorRef);\n }\n },\n get: systemId => {\n return keyedActors.get(systemId);\n },\n getAll: () => {\n return Object.fromEntries(keyedActors.entries());\n },\n _set: (systemId, actorRef) => {\n const existing = keyedActors.get(systemId);\n if (existing && existing !== actorRef) {\n throw new Error(`Actor with system ID '${systemId}' already exists.`);\n }\n keyedActors.set(systemId, actorRef);\n reverseKeyedActors.set(actorRef, systemId);\n },\n inspect: observerOrFn => {\n const observer = toObserver(observerOrFn);\n inspectionObservers.add(observer);\n return {\n unsubscribe() {\n inspectionObservers.delete(observer);\n }\n };\n },\n _sendInspectionEvent: sendInspectionEvent,\n _relay: (source, target, event) => {\n system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: source,\n actorRef: target,\n event\n });\n target._send(event);\n },\n scheduler,\n getSnapshot: () => {\n return {\n _scheduledEvents: {\n ...system._snapshot._scheduledEvents\n }\n };\n },\n start: () => {\n const scheduledEvents = system._snapshot._scheduledEvents;\n system._snapshot._scheduledEvents = {};\n for (const scheduledId in scheduledEvents) {\n const {\n source,\n target,\n event,\n delay,\n id\n } = scheduledEvents[scheduledId];\n scheduler.schedule(source, target, event, delay, id);\n }\n },\n _clock: clock,\n _logger: logger\n };\n return system;\n}\n\n// those are needed to make JSDoc `@link` work properly\n\nlet executingCustomAction = false;\nconst $$ACTOR_TYPE = 1;\n\n// those values are currently used by @xstate/react directly so it's important to keep the assigned values in sync\nlet ProcessingStatus = /*#__PURE__*/function (ProcessingStatus) {\n ProcessingStatus[ProcessingStatus[\"NotStarted\"] = 0] = \"NotStarted\";\n ProcessingStatus[ProcessingStatus[\"Running\"] = 1] = \"Running\";\n ProcessingStatus[ProcessingStatus[\"Stopped\"] = 2] = \"Stopped\";\n return ProcessingStatus;\n}({});\nconst defaultOptions = {\n clock: {\n setTimeout: (fn, ms) => {\n return setTimeout(fn, ms);\n },\n clearTimeout: id => {\n return clearTimeout(id);\n }\n },\n logger: console.log.bind(console),\n devTools: false\n};\n\n/**\n * An Actor is a running process that can receive events, send events and change\n * its behavior based on the events it receives, which can cause effects outside\n * of the actor. When you run a state machine, it becomes an actor.\n */\nclass Actor {\n /**\n * Creates a new actor instance for the given logic with the provided options,\n * if any.\n *\n * @param logic The logic to create an actor from\n * @param options Actor options\n */\n constructor(logic, options) {\n this.logic = logic;\n /** The current internal state of the actor. */\n this._snapshot = void 0;\n /**\n * The clock that is responsible for setting and clearing timeouts, such as\n * delayed events and transitions.\n */\n this.clock = void 0;\n this.options = void 0;\n /** The unique identifier for this actor relative to its parent. */\n this.id = void 0;\n this.mailbox = new Mailbox(this._process.bind(this));\n this.observers = new Set();\n this.eventListeners = new Map();\n this.logger = void 0;\n /** @internal */\n this._processingStatus = ProcessingStatus.NotStarted;\n // Actor Ref\n this._parent = void 0;\n /** @internal */\n this._syncSnapshot = void 0;\n this.ref = void 0;\n // TODO: add typings for system\n this._actorScope = void 0;\n this.systemId = void 0;\n /** The globally unique process ID for this invocation. */\n this.sessionId = void 0;\n /** The system to which this actor belongs. */\n this.system = void 0;\n this._doneEvent = void 0;\n this.src = void 0;\n // array of functions to defer\n this._deferred = [];\n const resolvedOptions = {\n ...defaultOptions,\n ...options\n };\n const {\n clock,\n logger,\n parent,\n syncSnapshot,\n id,\n systemId,\n inspect\n } = resolvedOptions;\n this.system = parent ? parent.system : createSystem(this, {\n clock,\n logger\n });\n if (inspect && !parent) {\n // Always inspect at the system-level\n this.system.inspect(toObserver(inspect));\n }\n this.sessionId = this.system._bookId();\n this.id = id ?? this.sessionId;\n this.logger = options?.logger ?? this.system._logger;\n this.clock = options?.clock ?? this.system._clock;\n this._parent = parent;\n this._syncSnapshot = syncSnapshot;\n this.options = resolvedOptions;\n this.src = resolvedOptions.src ?? logic;\n this.ref = this;\n this._actorScope = {\n self: this,\n id: this.id,\n sessionId: this.sessionId,\n logger: this.logger,\n defer: fn => {\n this._deferred.push(fn);\n },\n system: this.system,\n stopChild: child => {\n if (child._parent !== this) {\n throw new Error(`Cannot stop child actor ${child.id} of ${this.id} because it is not a child`);\n }\n child._stop();\n },\n emit: emittedEvent => {\n const listeners = this.eventListeners.get(emittedEvent.type);\n const wildcardListener = this.eventListeners.get('*');\n if (!listeners && !wildcardListener) {\n return;\n }\n const allListeners = [...(listeners ? listeners.values() : []), ...(wildcardListener ? wildcardListener.values() : [])];\n for (const handler of allListeners) {\n try {\n handler(emittedEvent);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n },\n actionExecutor: action => {\n const exec = () => {\n this._actorScope.system._sendInspectionEvent({\n type: '@xstate.action',\n actorRef: this,\n action: {\n type: action.type,\n params: action.params\n }\n });\n if (!action.exec) {\n return;\n }\n const saveExecutingCustomAction = executingCustomAction;\n try {\n executingCustomAction = true;\n action.exec(action.info, action.params);\n } finally {\n executingCustomAction = saveExecutingCustomAction;\n }\n };\n if (this._processingStatus === ProcessingStatus.Running) {\n exec();\n } else {\n this._deferred.push(exec);\n }\n }\n };\n\n // Ensure that the send method is bound to this Actor instance\n // if destructured\n this.send = this.send.bind(this);\n this.system._sendInspectionEvent({\n type: '@xstate.actor',\n actorRef: this\n });\n if (systemId) {\n this.systemId = systemId;\n this.system._set(systemId, this);\n }\n this._initState(options?.snapshot ?? options?.state);\n if (systemId && this._snapshot.status !== 'active') {\n this.system._unregister(this);\n }\n }\n _initState(persistedState) {\n try {\n this._snapshot = persistedState ? this.logic.restoreSnapshot ? this.logic.restoreSnapshot(persistedState, this._actorScope) : persistedState : this.logic.getInitialSnapshot(this._actorScope, this.options?.input);\n } catch (err) {\n // if we get here then it means that we assign a value to this._snapshot that is not of the correct type\n // we can't get the true `TSnapshot & { status: 'error'; }`, it's impossible\n // so right now this is a lie of sorts\n this._snapshot = {\n status: 'error',\n output: undefined,\n error: err\n };\n }\n }\n update(snapshot, event) {\n // Update state\n this._snapshot = snapshot;\n\n // Execute deferred effects\n let deferredFn;\n while (deferredFn = this._deferred.shift()) {\n try {\n deferredFn();\n } catch (err) {\n // this error can only be caught when executing *initial* actions\n // it's the only time when we call actions provided by the user through those deferreds\n // when the actor is already running we always execute them synchronously while transitioning\n // no \"builtin deferred\" should actually throw an error since they are either safe\n // or the control flow is passed through the mailbox and errors should be caught by the `_process` used by the mailbox\n this._deferred.length = 0;\n this._snapshot = {\n ...snapshot,\n status: 'error',\n error: err\n };\n }\n }\n switch (this._snapshot.status) {\n case 'active':\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n case 'done':\n // next observers are meant to be notified about done snapshots\n // this can be seen as something that is different from how observable work\n // but with observables `complete` callback is called without any arguments\n // it's more ergonomic for XState to treat a done snapshot as a \"next\" value\n // and the completion event as something that is separate,\n // something that merely follows emitting that done snapshot\n for (const observer of this.observers) {\n try {\n observer.next?.(snapshot);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this._stopProcedure();\n this._complete();\n this._doneEvent = createDoneActorEvent(this.id, this._snapshot.output);\n if (this._parent) {\n this.system._relay(this, this._parent, this._doneEvent);\n }\n break;\n case 'error':\n this._error(this._snapshot.error);\n break;\n }\n this.system._sendInspectionEvent({\n type: '@xstate.snapshot',\n actorRef: this,\n event,\n snapshot\n });\n }\n\n /**\n * Subscribe an observer to an actor’s snapshot values.\n *\n * @remarks\n * The observer will receive the actor’s snapshot value when it is emitted.\n * The observer can be:\n *\n * - A plain function that receives the latest snapshot, or\n * - An observer object whose `.next(snapshot)` method receives the latest\n * snapshot\n *\n * @example\n *\n * ```ts\n * // Observer as a plain function\n * const subscription = actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * ```\n *\n * @example\n *\n * ```ts\n * // Observer as an object\n * const subscription = actor.subscribe({\n * next(snapshot) {\n * console.log(snapshot);\n * },\n * error(err) {\n * // ...\n * },\n * complete() {\n * // ...\n * }\n * });\n * ```\n *\n * The return value of `actor.subscribe(observer)` is a subscription object\n * that has an `.unsubscribe()` method. You can call\n * `subscription.unsubscribe()` to unsubscribe the observer:\n *\n * @example\n *\n * ```ts\n * const subscription = actor.subscribe((snapshot) => {\n * // ...\n * });\n *\n * // Unsubscribe the observer\n * subscription.unsubscribe();\n * ```\n *\n * When the actor is stopped, all of its observers will automatically be\n * unsubscribed.\n *\n * @param observer - Either a plain function that receives the latest\n * snapshot, or an observer object whose `.next(snapshot)` method receives\n * the latest snapshot\n */\n\n subscribe(nextListenerOrObserver, errorListener, completeListener) {\n const observer = toObserver(nextListenerOrObserver, errorListener, completeListener);\n if (this._processingStatus !== ProcessingStatus.Stopped) {\n this.observers.add(observer);\n } else {\n switch (this._snapshot.status) {\n case 'done':\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n break;\n case 'error':\n {\n const err = this._snapshot.error;\n if (!observer.error) {\n reportUnhandledError(err);\n } else {\n try {\n observer.error(err);\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n break;\n }\n }\n }\n return {\n unsubscribe: () => {\n this.observers.delete(observer);\n }\n };\n }\n on(type, handler) {\n let listeners = this.eventListeners.get(type);\n if (!listeners) {\n listeners = new Set();\n this.eventListeners.set(type, listeners);\n }\n const wrappedHandler = handler.bind(undefined);\n listeners.add(wrappedHandler);\n return {\n unsubscribe: () => {\n listeners.delete(wrappedHandler);\n }\n };\n }\n\n /** Starts the Actor from the initial state */\n start() {\n if (this._processingStatus === ProcessingStatus.Running) {\n // Do not restart the service if it is already started\n return this;\n }\n if (this._syncSnapshot) {\n this.subscribe({\n next: snapshot => {\n if (snapshot.status === 'active') {\n this.system._relay(this, this._parent, {\n type: `xstate.snapshot.${this.id}`,\n snapshot\n });\n }\n },\n error: () => {}\n });\n }\n this.system._register(this.sessionId, this);\n if (this.systemId) {\n this.system._set(this.systemId, this);\n }\n this._processingStatus = ProcessingStatus.Running;\n\n // TODO: this isn't correct when rehydrating\n const initEvent = createInitEvent(this.options.input);\n this.system._sendInspectionEvent({\n type: '@xstate.event',\n sourceRef: this._parent,\n actorRef: this,\n event: initEvent\n });\n const status = this._snapshot.status;\n switch (status) {\n case 'done':\n // a state machine can be \"done\" upon initialization (it could reach a final state using initial microsteps)\n // we still need to complete observers, flush deferreds etc\n this.update(this._snapshot, initEvent);\n // TODO: rethink cleanup of observers, mailbox, etc\n return this;\n case 'error':\n this._error(this._snapshot.error);\n return this;\n }\n if (!this._parent) {\n this.system.start();\n }\n if (this.logic.start) {\n try {\n this.logic.start(this._snapshot, this._actorScope);\n } catch (err) {\n this._snapshot = {\n ...this._snapshot,\n status: 'error',\n error: err\n };\n this._error(err);\n return this;\n }\n }\n\n // TODO: this notifies all subscribers but usually this is redundant\n // there is no real change happening here\n // we need to rethink if this needs to be refactored\n this.update(this._snapshot, initEvent);\n if (this.options.devTools) {\n this.attachDevTools();\n }\n this.mailbox.start();\n return this;\n }\n _process(event) {\n let nextState;\n let caughtError;\n try {\n nextState = this.logic.transition(this._snapshot, event, this._actorScope);\n } catch (err) {\n // we wrap it in a box so we can rethrow it later even if falsy value gets caught here\n caughtError = {\n err\n };\n }\n if (caughtError) {\n const {\n err\n } = caughtError;\n this._snapshot = {\n ...this._snapshot,\n status: 'error',\n error: err\n };\n this._error(err);\n return;\n }\n this.update(nextState, event);\n if (event.type === XSTATE_STOP) {\n this._stopProcedure();\n this._complete();\n }\n }\n _stop() {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return this;\n }\n this.mailbox.clear();\n if (this._processingStatus === ProcessingStatus.NotStarted) {\n this._processingStatus = ProcessingStatus.Stopped;\n return this;\n }\n this.mailbox.enqueue({\n type: XSTATE_STOP\n });\n return this;\n }\n\n /** Stops the Actor and unsubscribe all listeners. */\n stop() {\n if (this._parent) {\n throw new Error('A non-root actor cannot be stopped directly.');\n }\n return this._stop();\n }\n _complete() {\n for (const observer of this.observers) {\n try {\n observer.complete?.();\n } catch (err) {\n reportUnhandledError(err);\n }\n }\n this.observers.clear();\n this.eventListeners.clear();\n }\n _reportError(err) {\n if (!this.observers.size) {\n if (!this._parent) {\n reportUnhandledError(err);\n }\n this.eventListeners.clear();\n return;\n }\n let reportError = false;\n for (const observer of this.observers) {\n const errorListener = observer.error;\n reportError ||= !errorListener;\n try {\n errorListener?.(err);\n } catch (err2) {\n reportUnhandledError(err2);\n }\n }\n this.observers.clear();\n this.eventListeners.clear();\n if (reportError) {\n reportUnhandledError(err);\n }\n }\n _error(err) {\n this._stopProcedure();\n this._reportError(err);\n if (this._parent) {\n this.system._relay(this, this._parent, createErrorActorEvent(this.id, err));\n }\n }\n // TODO: atm children don't belong entirely to the actor so\n // in a way - it's not even super aware of them\n // so we can't stop them from here but we really should!\n // right now, they are being stopped within the machine's transition\n // but that could throw and leave us with \"orphaned\" active actors\n _stopProcedure() {\n if (this._processingStatus !== ProcessingStatus.Running) {\n // Actor already stopped; do nothing\n return this;\n }\n\n // Cancel all delayed events\n this.system.scheduler.cancelAll(this);\n\n // TODO: mailbox.reset\n this.mailbox.clear();\n // TODO: after `stop` we must prepare ourselves for receiving events again\n // events sent *after* stop signal must be queued\n // it seems like this should be the common behavior for all of our consumers\n // so perhaps this should be unified somehow for all of them\n this.mailbox = new Mailbox(this._process.bind(this));\n this._processingStatus = ProcessingStatus.Stopped;\n this.system._unregister(this);\n return this;\n }\n\n /** @internal */\n _send(event) {\n if (this._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n this.mailbox.enqueue(event);\n }\n\n /**\n * Sends an event to the running Actor to trigger a transition.\n *\n * @param event The event to send\n */\n send(event) {\n this.system._relay(undefined, this, event);\n }\n attachDevTools() {\n const {\n devTools\n } = this.options;\n if (devTools) {\n const resolvedDevToolsAdapter = typeof devTools === 'function' ? devTools : devToolsAdapter;\n resolvedDevToolsAdapter(this);\n }\n }\n toJSON() {\n return {\n xstate$$type: $$ACTOR_TYPE,\n id: this.id\n };\n }\n\n /**\n * Obtain the internal state of the actor, which can be persisted.\n *\n * @remarks\n * The internal state can be persisted from any actor, not only machines.\n *\n * Note that the persisted state is not the same as the snapshot from\n * {@link Actor.getSnapshot}. Persisted state represents the internal state of\n * the actor, while snapshots represent the actor's last emitted value.\n *\n * Can be restored with {@link ActorOptions.state}\n * @see https://stately.ai/docs/persistence\n */\n\n getPersistedSnapshot(options) {\n return this.logic.getPersistedSnapshot(this._snapshot, options);\n }\n [symbolObservable]() {\n return this;\n }\n\n /**\n * Read an actor’s snapshot synchronously.\n *\n * @remarks\n * The snapshot represent an actor's last emitted value.\n *\n * When an actor receives an event, its internal state may change. An actor\n * may emit a snapshot when a state transition occurs.\n *\n * Note that some actors, such as callback actors generated with\n * `fromCallback`, will not emit snapshots.\n * @see {@link Actor.subscribe} to subscribe to an actor’s snapshot values.\n * @see {@link Actor.getPersistedSnapshot} to persist the internal state of an actor (which is more than just a snapshot).\n */\n getSnapshot() {\n return this._snapshot;\n }\n}\n/**\n * Creates a new actor instance for the given actor logic with the provided\n * options, if any.\n *\n * @remarks\n * When you create an actor from actor logic via `createActor(logic)`, you\n * implicitly create an actor system where the created actor is the root actor.\n * Any actors spawned from this root actor and its descendants are part of that\n * actor system.\n * @example\n *\n * ```ts\n * import { createActor } from 'xstate';\n * import { someActorLogic } from './someActorLogic.ts';\n *\n * // Creating the actor, which implicitly creates an actor system with itself as the root actor\n * const actor = createActor(someActorLogic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n *\n * // Actors must be started by calling `actor.start()`, which will also start the actor system.\n * actor.start();\n *\n * // Actors can receive events\n * actor.send({ type: 'someEvent' });\n *\n * // You can stop root actors by calling `actor.stop()`, which will also stop the actor system and all actors in that system.\n * actor.stop();\n * ```\n *\n * @param logic - The actor logic to create an actor from. For a state machine\n * actor logic creator, see {@link createMachine}. Other actor logic creators\n * include {@link fromCallback}, {@link fromEventObservable},\n * {@link fromObservable}, {@link fromPromise}, and {@link fromTransition}.\n * @param options - Actor options\n */\nfunction createActor(logic, ...[options]) {\n return new Actor(logic, options);\n}\n\n/**\n * Creates a new Interpreter instance for the given machine with the provided\n * options, if any.\n *\n * @deprecated Use `createActor` instead\n * @alias\n */\nconst interpret = createActor;\n\n/**\n * @deprecated Use `Actor` instead.\n * @alias\n */\n\nfunction resolveCancel(_, snapshot, actionArgs, actionParams, {\n sendId\n}) {\n const resolvedSendId = typeof sendId === 'function' ? sendId(actionArgs, actionParams) : sendId;\n return [snapshot, {\n sendId: resolvedSendId\n }, undefined];\n}\nfunction executeCancel(actorScope, params) {\n actorScope.defer(() => {\n actorScope.system.scheduler.cancel(actorScope.self, params.sendId);\n });\n}\n/**\n * Cancels a delayed `sendTo(...)` action that is waiting to be executed. The\n * canceled `sendTo(...)` action will not send its event or execute, unless the\n * `delay` has already elapsed before `cancel(...)` is called.\n *\n * @example\n *\n * ```ts\n * import { createMachine, sendTo, cancel } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * sendEvent: {\n * actions: sendTo(\n * 'some-actor',\n * { type: 'someEvent' },\n * {\n * id: 'some-id',\n * delay: 1000\n * }\n * )\n * },\n * cancelEvent: {\n * actions: cancel('some-id')\n * }\n * }\n * });\n * ```\n *\n * @param sendId The `id` of the `sendTo(...)` action to cancel.\n */\nfunction cancel(sendId) {\n function cancel(_args, _params) {\n }\n cancel.type = 'xstate.cancel';\n cancel.sendId = sendId;\n cancel.resolve = resolveCancel;\n cancel.execute = executeCancel;\n return cancel;\n}\n\nfunction resolveSpawn(actorScope, snapshot, actionArgs, _actionParams, {\n id,\n systemId,\n src,\n input,\n syncSnapshot\n}) {\n const logic = typeof src === 'string' ? resolveReferencedActor(snapshot.machine, src) : src;\n const resolvedId = typeof id === 'function' ? id(actionArgs) : id;\n let actorRef;\n let resolvedInput = undefined;\n if (logic) {\n resolvedInput = typeof input === 'function' ? input({\n context: snapshot.context,\n event: actionArgs.event,\n self: actorScope.self\n }) : input;\n actorRef = createActor(logic, {\n id: resolvedId,\n src,\n parent: actorScope.self,\n syncSnapshot,\n systemId,\n input: resolvedInput\n });\n }\n return [cloneMachineSnapshot(snapshot, {\n children: {\n ...snapshot.children,\n [resolvedId]: actorRef\n }\n }), {\n id,\n systemId,\n actorRef,\n src,\n input: resolvedInput\n }, undefined];\n}\nfunction executeSpawn(actorScope, {\n actorRef\n}) {\n if (!actorRef) {\n return;\n }\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n}\nfunction spawnChild(...[src, {\n id,\n systemId,\n input,\n syncSnapshot = false\n} = {}]) {\n function spawnChild(_args, _params) {\n }\n spawnChild.type = 'xstate.spawnChild';\n spawnChild.id = id;\n spawnChild.systemId = systemId;\n spawnChild.src = src;\n spawnChild.input = input;\n spawnChild.syncSnapshot = syncSnapshot;\n spawnChild.resolve = resolveSpawn;\n spawnChild.execute = executeSpawn;\n return spawnChild;\n}\n\nfunction resolveStop(_, snapshot, args, actionParams, {\n actorRef\n}) {\n const actorRefOrString = typeof actorRef === 'function' ? actorRef(args, actionParams) : actorRef;\n const resolvedActorRef = typeof actorRefOrString === 'string' ? snapshot.children[actorRefOrString] : actorRefOrString;\n let children = snapshot.children;\n if (resolvedActorRef) {\n children = {\n ...children\n };\n delete children[resolvedActorRef.id];\n }\n return [cloneMachineSnapshot(snapshot, {\n children\n }), resolvedActorRef, undefined];\n}\nfunction unregisterRecursively(actorScope, actorRef) {\n // unregister children first (depth-first)\n const snapshot = actorRef.getSnapshot();\n if (snapshot && 'children' in snapshot) {\n for (const child of Object.values(snapshot.children)) {\n unregisterRecursively(actorScope, child);\n }\n }\n actorScope.system._unregister(actorRef);\n}\nfunction executeStop(actorScope, actorRef) {\n if (!actorRef) {\n return;\n }\n\n // we need to eagerly unregister it here so a new actor with the same systemId can be registered immediately\n // since we defer actual stopping of the actor but we don't defer actor creations (and we can't do that)\n // this could throw on `systemId` collision, for example, when dealing with reentering transitions\n // we also need to recursively unregister all nested children's systemIds\n unregisterRecursively(actorScope, actorRef);\n\n // this allows us to prevent an actor from being started if it gets stopped within the same macrostep\n // this can happen, for example, when the invoking state is being exited immediately by an always transition\n if (actorRef._processingStatus !== ProcessingStatus.Running) {\n actorScope.stopChild(actorRef);\n return;\n }\n // stopping a child enqueues a stop event in the child actor's mailbox\n // we need for all of the already enqueued events to be processed before we stop the child\n // the parent itself might want to send some events to a child (for example from exit actions on the invoking state)\n // and we don't want to ignore those events\n actorScope.defer(() => {\n actorScope.stopChild(actorRef);\n });\n}\n/**\n * Stops a child actor.\n *\n * @param actorRef The actor to stop.\n */\nfunction stopChild(actorRef) {\n function stop(_args, _params) {\n }\n stop.type = 'xstate.stopChild';\n stop.actorRef = actorRef;\n stop.resolve = resolveStop;\n stop.execute = executeStop;\n return stop;\n}\n\n/**\n * Stops a child actor.\n *\n * @deprecated Use `stopChild(...)` instead\n * @alias\n */\nconst stop = stopChild;\n\nfunction checkStateIn(snapshot, _, {\n stateValue\n}) {\n if (typeof stateValue === 'string' && isStateId(stateValue)) {\n const target = snapshot.machine.getStateNodeById(stateValue);\n return snapshot._nodes.some(sn => sn === target);\n }\n return snapshot.matches(stateValue);\n}\nfunction stateIn(stateValue) {\n function stateIn() {\n return false;\n }\n stateIn.check = checkStateIn;\n stateIn.stateValue = stateValue;\n return stateIn;\n}\nfunction checkNot(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return !evaluateGuard(guards[0], context, event, snapshot);\n}\n\n/**\n * Higher-order guard that evaluates to `true` if the `guard` passed to it\n * evaluates to `false`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, not } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => false\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: not('someNamedGuard'),\n * actions: () => {\n * // will be executed if guard in `not(...)`\n * // evaluates to `false`\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard\n */\nfunction not(guard) {\n function not(_args, _params) {\n return false;\n }\n not.check = checkNot;\n not.guards = [guard];\n return not;\n}\nfunction checkAnd(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return guards.every(guard => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if all `guards` passed to it\n * evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, and } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: and([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if all guards in `and(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nfunction and(guards) {\n function and(_args, _params) {\n return false;\n }\n and.check = checkAnd;\n and.guards = guards;\n return and;\n}\nfunction checkOr(snapshot, {\n context,\n event\n}, {\n guards\n}) {\n return guards.some(guard => evaluateGuard(guard, context, event, snapshot));\n}\n\n/**\n * Higher-order guard that evaluates to `true` if any of the `guards` passed to\n * it evaluate to `true`.\n *\n * @category Guards\n * @example\n *\n * ```ts\n * import { setup, or } from 'xstate';\n *\n * const machine = setup({\n * guards: {\n * someNamedGuard: () => true\n * }\n * }).createMachine({\n * on: {\n * someEvent: {\n * guard: or([({ context }) => context.value > 0, 'someNamedGuard']),\n * actions: () => {\n * // will be executed if any of the guards in `or(...)`\n * // evaluate to true\n * }\n * }\n * }\n * });\n * ```\n *\n * @returns A guard action object\n */\nfunction or(guards) {\n function or(_args, _params) {\n return false;\n }\n or.check = checkOr;\n or.guards = guards;\n return or;\n}\n\n// TODO: throw on cycles (depth check should be enough)\nfunction evaluateGuard(guard, context, event, snapshot) {\n const {\n machine\n } = snapshot;\n const isInline = typeof guard === 'function';\n const resolved = isInline ? guard : machine.implementations.guards[typeof guard === 'string' ? guard : guard.type];\n if (!isInline && !resolved) {\n throw new Error(`Guard '${typeof guard === 'string' ? guard : guard.type}' is not implemented.'.`);\n }\n if (typeof resolved !== 'function') {\n return evaluateGuard(resolved, context, event, snapshot);\n }\n const guardArgs = {\n context,\n event\n };\n const guardParams = isInline || typeof guard === 'string' ? undefined : 'params' in guard ? typeof guard.params === 'function' ? guard.params({\n context,\n event\n }) : guard.params : undefined;\n if (!('check' in resolved)) {\n // the existing type of `.guards` assumes non-nullable `TExpressionGuard`\n // inline guards expect `TExpressionGuard` to be set to `undefined`\n // it's fine to cast this here, our logic makes sure that we call those 2 \"variants\" correctly\n return resolved(guardArgs, guardParams);\n }\n const builtinGuard = resolved;\n return builtinGuard.check(snapshot, guardArgs, resolved // this holds all params\n );\n}\n\nfunction isAtomicStateNode(stateNode) {\n return stateNode.type === 'atomic' || stateNode.type === 'final';\n}\nfunction getChildren(stateNode) {\n return Object.values(stateNode.states).filter(sn => sn.type !== 'history');\n}\nfunction getProperAncestors(stateNode, toStateNode) {\n const ancestors = [];\n if (toStateNode === stateNode) {\n return ancestors;\n }\n\n // add all ancestors\n let m = stateNode.parent;\n while (m && m !== toStateNode) {\n ancestors.push(m);\n m = m.parent;\n }\n return ancestors;\n}\nfunction getAllStateNodes(stateNodes) {\n const nodeSet = new Set(stateNodes);\n const adjList = getAdjList(nodeSet);\n\n // add descendants\n for (const s of nodeSet) {\n // if previously active, add existing child nodes\n if (s.type === 'compound' && (!adjList.get(s) || !adjList.get(s).length)) {\n getInitialStateNodesWithTheirAncestors(s).forEach(sn => nodeSet.add(sn));\n } else {\n if (s.type === 'parallel') {\n for (const child of getChildren(s)) {\n if (child.type === 'history') {\n continue;\n }\n if (!nodeSet.has(child)) {\n const initialStates = getInitialStateNodesWithTheirAncestors(child);\n for (const initialStateNode of initialStates) {\n nodeSet.add(initialStateNode);\n }\n }\n }\n }\n }\n }\n\n // add all ancestors\n for (const s of nodeSet) {\n let m = s.parent;\n while (m) {\n nodeSet.add(m);\n m = m.parent;\n }\n }\n return nodeSet;\n}\nfunction getValueFromAdj(baseNode, adjList) {\n const childStateNodes = adjList.get(baseNode);\n if (!childStateNodes) {\n return {}; // todo: fix?\n }\n if (baseNode.type === 'compound') {\n const childStateNode = childStateNodes[0];\n if (childStateNode) {\n if (isAtomicStateNode(childStateNode)) {\n return childStateNode.key;\n }\n } else {\n return {};\n }\n }\n const stateValue = {};\n for (const childStateNode of childStateNodes) {\n stateValue[childStateNode.key] = getValueFromAdj(childStateNode, adjList);\n }\n return stateValue;\n}\nfunction getAdjList(stateNodes) {\n const adjList = new Map();\n for (const s of stateNodes) {\n if (!adjList.has(s)) {\n adjList.set(s, []);\n }\n if (s.parent) {\n if (!adjList.has(s.parent)) {\n adjList.set(s.parent, []);\n }\n adjList.get(s.parent).push(s);\n }\n }\n return adjList;\n}\nfunction getStateValue(rootNode, stateNodes) {\n const config = getAllStateNodes(stateNodes);\n return getValueFromAdj(rootNode, getAdjList(config));\n}\nfunction isInFinalState(stateNodeSet, stateNode) {\n if (stateNode.type === 'compound') {\n return getChildren(stateNode).some(s => s.type === 'final' && stateNodeSet.has(s));\n }\n if (stateNode.type === 'parallel') {\n return getChildren(stateNode).every(sn => isInFinalState(stateNodeSet, sn));\n }\n return stateNode.type === 'final';\n}\nconst isStateId = str => str[0] === STATE_IDENTIFIER;\nfunction getCandidates(stateNode, receivedEventType) {\n const candidates = stateNode.transitions.get(receivedEventType) || [...stateNode.transitions.keys()].filter(eventDescriptor => matchesEventDescriptor(receivedEventType, eventDescriptor)).sort((a, b) => b.length - a.length).flatMap(key => stateNode.transitions.get(key));\n return candidates;\n}\n\n/** All delayed transitions from the config. */\nfunction getDelayedTransitions(stateNode) {\n const afterConfig = stateNode.config.after;\n if (!afterConfig) {\n return [];\n }\n const mutateEntryExit = delay => {\n const afterEvent = createAfterEvent(delay, stateNode.id);\n const eventType = afterEvent.type;\n stateNode.entry.push(raise(afterEvent, {\n id: eventType,\n delay\n }));\n stateNode.exit.push(cancel(eventType));\n return eventType;\n };\n const delayedTransitions = Object.keys(afterConfig).flatMap(delay => {\n const configTransition = afterConfig[delay];\n const resolvedTransition = typeof configTransition === 'string' ? {\n target: configTransition\n } : configTransition;\n const resolvedDelay = Number.isNaN(+delay) ? delay : +delay;\n const eventType = mutateEntryExit(resolvedDelay);\n return toArray(resolvedTransition).map(transition => ({\n ...transition,\n event: eventType,\n delay: resolvedDelay\n }));\n });\n return delayedTransitions.map(delayedTransition => {\n const {\n delay\n } = delayedTransition;\n return {\n ...formatTransition(stateNode, delayedTransition.event, delayedTransition),\n delay\n };\n });\n}\nfunction formatTransition(stateNode, descriptor, transitionConfig) {\n const normalizedTarget = normalizeTarget(transitionConfig.target);\n const reenter = transitionConfig.reenter ?? false;\n const target = resolveTarget(stateNode, normalizedTarget);\n const transition = {\n ...transitionConfig,\n actions: toArray(transitionConfig.actions),\n guard: transitionConfig.guard,\n target,\n source: stateNode,\n reenter,\n eventType: descriptor,\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: target ? target.map(t => `#${t.id}`) : undefined\n })\n };\n return transition;\n}\nfunction formatTransitions(stateNode) {\n const transitions = new Map();\n if (stateNode.config.on) {\n for (const descriptor of Object.keys(stateNode.config.on)) {\n if (descriptor === NULL_EVENT) {\n throw new Error('Null events (\"\") cannot be specified as a transition key. Use `always: { ... }` instead.');\n }\n const transitionsConfig = stateNode.config.on[descriptor];\n transitions.set(descriptor, toTransitionConfigArray(transitionsConfig).map(t => formatTransition(stateNode, descriptor, t)));\n }\n }\n if (stateNode.config.onDone) {\n const descriptor = `xstate.done.state.${stateNode.id}`;\n transitions.set(descriptor, toTransitionConfigArray(stateNode.config.onDone).map(t => formatTransition(stateNode, descriptor, t)));\n }\n for (const invokeDef of stateNode.invoke) {\n if (invokeDef.onDone) {\n const descriptor = `xstate.done.actor.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onDone).map(t => formatTransition(stateNode, descriptor, t)));\n }\n if (invokeDef.onError) {\n const descriptor = `xstate.error.actor.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onError).map(t => formatTransition(stateNode, descriptor, t)));\n }\n if (invokeDef.onSnapshot) {\n const descriptor = `xstate.snapshot.${invokeDef.id}`;\n transitions.set(descriptor, toTransitionConfigArray(invokeDef.onSnapshot).map(t => formatTransition(stateNode, descriptor, t)));\n }\n }\n for (const delayedTransition of stateNode.after) {\n let existing = transitions.get(delayedTransition.eventType);\n if (!existing) {\n existing = [];\n transitions.set(delayedTransition.eventType, existing);\n }\n existing.push(delayedTransition);\n }\n return transitions;\n}\n\n/**\n * Collects route transitions from all descendants with explicit IDs. Called\n * once on the root node to avoid O(N²) repeated traversals.\n */\nfunction formatRouteTransitions(rootStateNode) {\n const routeTransitions = [];\n const collectRoutes = states => {\n Object.values(states).forEach(sn => {\n if (sn.config.route && sn.config.id) {\n const routeId = sn.config.id;\n const userGuard = sn.config.route.guard;\n const routeGuard = (args, params) => {\n if (args.event.to !== `#${routeId}`) {\n return false;\n }\n if (!userGuard) {\n return true;\n }\n if (typeof userGuard === 'function') {\n return userGuard(args, params);\n }\n return true;\n };\n const transition = {\n ...sn.config.route,\n guard: routeGuard,\n target: `#${routeId}`\n };\n routeTransitions.push(formatTransition(rootStateNode, 'xstate.route', transition));\n }\n if (sn.states) {\n collectRoutes(sn.states);\n }\n });\n };\n collectRoutes(rootStateNode.states);\n if (routeTransitions.length > 0) {\n rootStateNode.transitions.set('xstate.route', routeTransitions);\n }\n}\nfunction formatInitialTransition(stateNode, _target) {\n const resolvedTarget = typeof _target === 'string' ? stateNode.states[_target] : _target ? stateNode.states[_target.target] : undefined;\n if (!resolvedTarget && _target) {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions, @typescript-eslint/no-base-to-string\n `Initial state node \"${_target}\" not found on parent state node #${stateNode.id}`);\n }\n const transition = {\n source: stateNode,\n actions: !_target || typeof _target === 'string' ? [] : toArray(_target.actions),\n eventType: null,\n reenter: false,\n target: resolvedTarget ? [resolvedTarget] : [],\n toJSON: () => ({\n ...transition,\n source: `#${stateNode.id}`,\n target: resolvedTarget ? [`#${resolvedTarget.id}`] : []\n })\n };\n return transition;\n}\nfunction resolveTarget(stateNode, targets) {\n if (targets === undefined) {\n // an undefined target signals that the state node should not transition from that state when receiving that event\n return undefined;\n }\n return targets.map(target => {\n if (typeof target !== 'string') {\n return target;\n }\n if (isStateId(target)) {\n return stateNode.machine.getStateNodeById(target);\n }\n const isInternalTarget = target[0] === STATE_DELIMITER;\n // If internal target is defined on machine,\n // do not include machine key on target\n if (isInternalTarget && !stateNode.parent) {\n return getStateNodeByPath(stateNode, target.slice(1));\n }\n const resolvedTarget = isInternalTarget ? stateNode.key + target : target;\n if (stateNode.parent) {\n try {\n const targetStateNode = getStateNodeByPath(stateNode.parent, resolvedTarget);\n return targetStateNode;\n } catch (err) {\n throw new Error(`Invalid transition definition for state node '${stateNode.id}':\\n${err.message}`);\n }\n } else {\n throw new Error(`Invalid target: \"${target}\" is not a valid target from the root node. Did you mean \".${target}\"?`);\n }\n });\n}\nfunction resolveHistoryDefaultTransition(stateNode) {\n const normalizedTarget = normalizeTarget(stateNode.config.target);\n if (!normalizedTarget) {\n return stateNode.parent.initial;\n }\n return {\n target: normalizedTarget.map(t => typeof t === 'string' ? getStateNodeByPath(stateNode.parent, t) : t)\n };\n}\nfunction isHistoryNode(stateNode) {\n return stateNode.type === 'history';\n}\nfunction getInitialStateNodesWithTheirAncestors(stateNode) {\n const states = getInitialStateNodes(stateNode);\n for (const initialState of states) {\n for (const ancestor of getProperAncestors(initialState, stateNode)) {\n states.add(ancestor);\n }\n }\n return states;\n}\nfunction getInitialStateNodes(stateNode) {\n const set = new Set();\n function iter(descStateNode) {\n if (set.has(descStateNode)) {\n return;\n }\n set.add(descStateNode);\n if (descStateNode.type === 'compound') {\n iter(descStateNode.initial.target[0]);\n } else if (descStateNode.type === 'parallel') {\n for (const child of getChildren(descStateNode)) {\n iter(child);\n }\n }\n }\n iter(stateNode);\n return set;\n}\n/** Returns the child state node from its relative `stateKey`, or throws. */\nfunction getStateNode(stateNode, stateKey) {\n if (isStateId(stateKey)) {\n return stateNode.machine.getStateNodeById(stateKey);\n }\n if (!stateNode.states) {\n throw new Error(`Unable to retrieve child state '${stateKey}' from '${stateNode.id}'; no child states exist.`);\n }\n const result = stateNode.states[stateKey];\n if (!result) {\n throw new Error(`Child state '${stateKey}' does not exist on '${stateNode.id}'`);\n }\n return result;\n}\n\n/**\n * Returns the relative state node from the given `statePath`, or throws.\n *\n * @param statePath The string or string array relative path to the state node.\n */\nfunction getStateNodeByPath(stateNode, statePath) {\n if (typeof statePath === 'string' && isStateId(statePath)) {\n try {\n return stateNode.machine.getStateNodeById(statePath);\n } catch {\n // try individual paths\n // throw e;\n }\n }\n const arrayStatePath = toStatePath(statePath).slice();\n let currentStateNode = stateNode;\n while (arrayStatePath.length) {\n const key = arrayStatePath.shift();\n if (!key.length) {\n break;\n }\n currentStateNode = getStateNode(currentStateNode, key);\n }\n return currentStateNode;\n}\n\n/**\n * Returns the state nodes represented by the current state value.\n *\n * @param stateValue The state value or State instance\n */\nfunction getStateNodes(stateNode, stateValue) {\n if (typeof stateValue === 'string') {\n const childStateNode = stateNode.states[stateValue];\n if (!childStateNode) {\n throw new Error(`State '${stateValue}' does not exist on '${stateNode.id}'`);\n }\n return [stateNode, childStateNode];\n }\n const childStateKeys = Object.keys(stateValue);\n const childStateNodes = childStateKeys.map(subStateKey => getStateNode(stateNode, subStateKey)).filter(Boolean);\n return [stateNode.machine.root, stateNode].concat(childStateNodes, childStateKeys.reduce((allSubStateNodes, subStateKey) => {\n const subStateNode = getStateNode(stateNode, subStateKey);\n if (!subStateNode) {\n return allSubStateNodes;\n }\n const subStateNodes = getStateNodes(subStateNode, stateValue[subStateKey]);\n return allSubStateNodes.concat(subStateNodes);\n }, []));\n}\nfunction transitionAtomicNode(stateNode, stateValue, snapshot, event) {\n const childStateNode = getStateNode(stateNode, stateValue);\n const next = childStateNode.next(snapshot, event);\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n return next;\n}\nfunction transitionCompoundNode(stateNode, stateValue, snapshot, event) {\n const subStateKeys = Object.keys(stateValue);\n const childStateNode = getStateNode(stateNode, subStateKeys[0]);\n const next = transitionNode(childStateNode, stateValue[subStateKeys[0]], snapshot, event);\n if (!next || !next.length) {\n return stateNode.next(snapshot, event);\n }\n return next;\n}\nfunction transitionParallelNode(stateNode, stateValue, snapshot, event) {\n const allInnerTransitions = [];\n for (const subStateKey of Object.keys(stateValue)) {\n const subStateValue = stateValue[subStateKey];\n if (!subStateValue) {\n continue;\n }\n const subStateNode = getStateNode(stateNode, subStateKey);\n const innerTransitions = transitionNode(subStateNode, subStateValue, snapshot, event);\n if (innerTransitions) {\n allInnerTransitions.push(...innerTransitions);\n }\n }\n if (!allInnerTransitions.length) {\n return stateNode.next(snapshot, event);\n }\n return allInnerTransitions;\n}\nfunction transitionNode(stateNode, stateValue, snapshot, event) {\n // leaf node\n if (typeof stateValue === 'string') {\n return transitionAtomicNode(stateNode, stateValue, snapshot, event);\n }\n\n // compound node\n if (Object.keys(stateValue).length === 1) {\n return transitionCompoundNode(stateNode, stateValue, snapshot, event);\n }\n\n // parallel node\n return transitionParallelNode(stateNode, stateValue, snapshot, event);\n}\nfunction getHistoryNodes(stateNode) {\n return Object.keys(stateNode.states).map(key => stateNode.states[key]).filter(sn => sn.type === 'history');\n}\nfunction isDescendant(childStateNode, parentStateNode) {\n let marker = childStateNode;\n while (marker.parent && marker.parent !== parentStateNode) {\n marker = marker.parent;\n }\n return marker.parent === parentStateNode;\n}\nfunction hasIntersection(s1, s2) {\n const set1 = new Set(s1);\n const set2 = new Set(s2);\n for (const item of set1) {\n if (set2.has(item)) {\n return true;\n }\n }\n for (const item of set2) {\n if (set1.has(item)) {\n return true;\n }\n }\n return false;\n}\nfunction removeConflictingTransitions(enabledTransitions, stateNodeSet, historyValue) {\n const filteredTransitions = new Set();\n for (const t1 of enabledTransitions) {\n let t1Preempted = false;\n const transitionsToRemove = new Set();\n for (const t2 of filteredTransitions) {\n if (hasIntersection(computeExitSet([t1], stateNodeSet, historyValue), computeExitSet([t2], stateNodeSet, historyValue))) {\n if (isDescendant(t1.source, t2.source)) {\n transitionsToRemove.add(t2);\n } else {\n t1Preempted = true;\n break;\n }\n }\n }\n if (!t1Preempted) {\n for (const t3 of transitionsToRemove) {\n filteredTransitions.delete(t3);\n }\n filteredTransitions.add(t1);\n }\n }\n return Array.from(filteredTransitions);\n}\nfunction findLeastCommonAncestor(stateNodes) {\n const [head, ...tail] = stateNodes;\n for (const ancestor of getProperAncestors(head, undefined)) {\n if (tail.every(sn => isDescendant(sn, ancestor))) {\n return ancestor;\n }\n }\n}\nfunction getEffectiveTargetStates(transition, historyValue) {\n if (!transition.target) {\n return [];\n }\n const targets = new Set();\n for (const targetNode of transition.target) {\n if (isHistoryNode(targetNode)) {\n if (historyValue[targetNode.id]) {\n for (const node of historyValue[targetNode.id]) {\n targets.add(node);\n }\n } else {\n for (const node of getEffectiveTargetStates(resolveHistoryDefaultTransition(targetNode), historyValue)) {\n targets.add(node);\n }\n }\n } else {\n targets.add(targetNode);\n }\n }\n return [...targets];\n}\nfunction getTransitionDomain(transition, historyValue) {\n const targetStates = getEffectiveTargetStates(transition, historyValue);\n if (!targetStates) {\n return;\n }\n if (!transition.reenter && targetStates.every(target => target === transition.source || isDescendant(target, transition.source))) {\n return transition.source;\n }\n const lca = findLeastCommonAncestor(targetStates.concat(transition.source));\n if (lca) {\n return lca;\n }\n\n // at this point we know that it's a root transition since LCA couldn't be found\n if (transition.reenter) {\n return;\n }\n return transition.source.machine.root;\n}\nfunction computeExitSet(transitions, stateNodeSet, historyValue) {\n const statesToExit = new Set();\n for (const t of transitions) {\n if (t.target?.length) {\n const domain = getTransitionDomain(t, historyValue);\n if (t.reenter && t.source === domain) {\n statesToExit.add(domain);\n }\n for (const stateNode of stateNodeSet) {\n if (isDescendant(stateNode, domain)) {\n statesToExit.add(stateNode);\n }\n }\n }\n }\n return [...statesToExit];\n}\nfunction areStateNodeCollectionsEqual(prevStateNodes, nextStateNodeSet) {\n if (prevStateNodes.length !== nextStateNodeSet.size) {\n return false;\n }\n for (const node of prevStateNodes) {\n if (!nextStateNodeSet.has(node)) {\n return false;\n }\n }\n return true;\n}\nfunction initialMicrostep(root, preInitialState, actorScope, initEvent, internalQueue) {\n return microstep([{\n target: [...getInitialStateNodes(root)],\n source: root,\n reenter: true,\n actions: [],\n eventType: null,\n toJSON: null\n }], preInitialState, actorScope, initEvent, true, internalQueue);\n}\n\n/** https://www.w3.org/TR/scxml/#microstepProcedure */\nfunction microstep(transitions, currentSnapshot, actorScope, event, isInitial, internalQueue) {\n const actions = [];\n if (!transitions.length) {\n return [currentSnapshot, actions];\n }\n const originalExecutor = actorScope.actionExecutor;\n actorScope.actionExecutor = action => {\n actions.push(action);\n originalExecutor(action);\n };\n try {\n const mutStateNodeSet = new Set(currentSnapshot._nodes);\n let historyValue = currentSnapshot.historyValue;\n const filteredTransitions = removeConflictingTransitions(transitions, mutStateNodeSet, historyValue);\n let nextState = currentSnapshot;\n\n // Exit states\n if (!isInitial) {\n [nextState, historyValue] = exitStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, historyValue, internalQueue, actorScope.actionExecutor);\n }\n\n // Execute transition content\n nextState = resolveActionsAndContext(nextState, event, actorScope, filteredTransitions.flatMap(t => t.actions), internalQueue, undefined);\n\n // Enter states\n nextState = enterStates(nextState, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial);\n const nextStateNodes = [...mutStateNodeSet];\n if (nextState.status === 'done') {\n nextState = resolveActionsAndContext(nextState, event, actorScope, nextStateNodes.sort((a, b) => b.order - a.order).flatMap(state => state.exit), internalQueue, undefined);\n }\n\n // eslint-disable-next-line no-useless-catch\n try {\n if (historyValue === currentSnapshot.historyValue && areStateNodeCollectionsEqual(currentSnapshot._nodes, mutStateNodeSet)) {\n return [nextState, actions];\n }\n return [cloneMachineSnapshot(nextState, {\n _nodes: nextStateNodes,\n historyValue\n }), actions];\n } catch (e) {\n // TODO: Refactor this once proper error handling is implemented.\n // See https://github.com/statelyai/rfcs/pull/4\n throw e;\n }\n } finally {\n actorScope.actionExecutor = originalExecutor;\n }\n}\nfunction getMachineOutput(snapshot, event, actorScope, rootNode, rootCompletionNode) {\n if (rootNode.output === undefined) {\n return;\n }\n const doneStateEvent = createDoneStateEvent(rootCompletionNode.id, rootCompletionNode.output !== undefined && rootCompletionNode.parent ? resolveOutput(rootCompletionNode.output, snapshot.context, event, actorScope.self) : undefined);\n return resolveOutput(rootNode.output, snapshot.context, doneStateEvent, actorScope.self);\n}\nfunction enterStates(currentSnapshot, event, actorScope, filteredTransitions, mutStateNodeSet, internalQueue, historyValue, isInitial) {\n let nextSnapshot = currentSnapshot;\n const statesToEnter = new Set();\n // those are states that were directly targeted or indirectly targeted by the explicit target\n // in other words, those are states for which initial actions should be executed\n // when we target `#deep_child` initial actions of its ancestors shouldn't be executed\n const statesForDefaultEntry = new Set();\n computeEntrySet(filteredTransitions, historyValue, statesForDefaultEntry, statesToEnter);\n\n // In the initial state, the root state node is \"entered\".\n if (isInitial) {\n statesForDefaultEntry.add(currentSnapshot.machine.root);\n }\n const completedNodes = new Set();\n for (const stateNodeToEnter of [...statesToEnter].sort((a, b) => a.order - b.order)) {\n mutStateNodeSet.add(stateNodeToEnter);\n const actions = [];\n\n // Add entry actions\n actions.push(...stateNodeToEnter.entry);\n for (const invokeDef of stateNodeToEnter.invoke) {\n actions.push(spawnChild(invokeDef.src, {\n ...invokeDef,\n syncSnapshot: !!invokeDef.onSnapshot\n }));\n }\n if (statesForDefaultEntry.has(stateNodeToEnter)) {\n const initialActions = stateNodeToEnter.initial.actions;\n actions.push(...initialActions);\n }\n nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, actions, internalQueue, stateNodeToEnter.invoke.map(invokeDef => invokeDef.id));\n if (stateNodeToEnter.type === 'final') {\n const parent = stateNodeToEnter.parent;\n let ancestorMarker = parent?.type === 'parallel' ? parent : parent?.parent;\n let rootCompletionNode = ancestorMarker || stateNodeToEnter;\n if (parent?.type === 'compound') {\n internalQueue.push(createDoneStateEvent(parent.id, stateNodeToEnter.output !== undefined ? resolveOutput(stateNodeToEnter.output, nextSnapshot.context, event, actorScope.self) : undefined));\n }\n while (ancestorMarker?.type === 'parallel' && !completedNodes.has(ancestorMarker) && isInFinalState(mutStateNodeSet, ancestorMarker)) {\n completedNodes.add(ancestorMarker);\n internalQueue.push(createDoneStateEvent(ancestorMarker.id));\n rootCompletionNode = ancestorMarker;\n ancestorMarker = ancestorMarker.parent;\n }\n if (ancestorMarker) {\n continue;\n }\n nextSnapshot = cloneMachineSnapshot(nextSnapshot, {\n status: 'done',\n output: getMachineOutput(nextSnapshot, event, actorScope, nextSnapshot.machine.root, rootCompletionNode)\n });\n }\n }\n return nextSnapshot;\n}\nfunction computeEntrySet(transitions, historyValue, statesForDefaultEntry, statesToEnter) {\n for (const t of transitions) {\n const domain = getTransitionDomain(t, historyValue);\n for (const s of t.target || []) {\n if (!isHistoryNode(s) && (\n // if the target is different than the source then it will *definitely* be entered\n t.source !== s ||\n // we know that the domain can't lie within the source\n // if it's different than the source then it's outside of it and it means that the target has to be entered as well\n t.source !== domain ||\n // reentering transitions always enter the target, even if it's the source itself\n t.reenter)) {\n statesToEnter.add(s);\n statesForDefaultEntry.add(s);\n }\n addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n }\n const targetStates = getEffectiveTargetStates(t, historyValue);\n for (const s of targetStates) {\n const ancestors = getProperAncestors(s, domain);\n if (domain?.type === 'parallel') {\n ancestors.push(domain);\n }\n addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, !t.source.parent && t.reenter ? undefined : domain);\n }\n }\n}\nfunction addDescendantStatesToEnter(stateNode, historyValue, statesForDefaultEntry, statesToEnter) {\n if (isHistoryNode(stateNode)) {\n if (historyValue[stateNode.id]) {\n const historyStateNodes = historyValue[stateNode.id];\n for (const s of historyStateNodes) {\n statesToEnter.add(s);\n addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n }\n for (const s of historyStateNodes) {\n addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);\n }\n } else {\n const historyDefaultTransition = resolveHistoryDefaultTransition(stateNode);\n for (const s of historyDefaultTransition.target) {\n statesToEnter.add(s);\n if (historyDefaultTransition === stateNode.parent?.initial) {\n statesForDefaultEntry.add(stateNode.parent);\n }\n addDescendantStatesToEnter(s, historyValue, statesForDefaultEntry, statesToEnter);\n }\n for (const s of historyDefaultTransition.target) {\n addProperAncestorStatesToEnter(s, stateNode.parent, statesToEnter, historyValue, statesForDefaultEntry);\n }\n }\n } else {\n if (stateNode.type === 'compound') {\n const [initialState] = stateNode.initial.target;\n if (!isHistoryNode(initialState)) {\n statesToEnter.add(initialState);\n statesForDefaultEntry.add(initialState);\n }\n addDescendantStatesToEnter(initialState, historyValue, statesForDefaultEntry, statesToEnter);\n addProperAncestorStatesToEnter(initialState, stateNode, statesToEnter, historyValue, statesForDefaultEntry);\n } else {\n if (stateNode.type === 'parallel') {\n for (const child of getChildren(stateNode).filter(sn => !isHistoryNode(sn))) {\n if (![...statesToEnter].some(s => isDescendant(s, child))) {\n if (!isHistoryNode(child)) {\n statesToEnter.add(child);\n statesForDefaultEntry.add(child);\n }\n addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);\n }\n }\n }\n }\n }\n}\nfunction addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, ancestors, reentrancyDomain) {\n for (const anc of ancestors) {\n if (!reentrancyDomain || isDescendant(anc, reentrancyDomain)) {\n statesToEnter.add(anc);\n }\n if (anc.type === 'parallel') {\n for (const child of getChildren(anc).filter(sn => !isHistoryNode(sn))) {\n if (![...statesToEnter].some(s => isDescendant(s, child))) {\n statesToEnter.add(child);\n addDescendantStatesToEnter(child, historyValue, statesForDefaultEntry, statesToEnter);\n }\n }\n }\n }\n}\nfunction addProperAncestorStatesToEnter(stateNode, toStateNode, statesToEnter, historyValue, statesForDefaultEntry) {\n addAncestorStatesToEnter(statesToEnter, historyValue, statesForDefaultEntry, getProperAncestors(stateNode, toStateNode));\n}\nfunction exitStates(currentSnapshot, event, actorScope, transitions, mutStateNodeSet, historyValue, internalQueue, _actionExecutor) {\n let nextSnapshot = currentSnapshot;\n const statesToExit = computeExitSet(transitions, mutStateNodeSet, historyValue);\n statesToExit.sort((a, b) => b.order - a.order);\n let changedHistory;\n\n // From SCXML algorithm: https://www.w3.org/TR/scxml/#exitStates\n for (const exitStateNode of statesToExit) {\n for (const historyNode of getHistoryNodes(exitStateNode)) {\n let predicate;\n if (historyNode.history === 'deep') {\n predicate = sn => isAtomicStateNode(sn) && isDescendant(sn, exitStateNode);\n } else {\n predicate = sn => {\n return sn.parent === exitStateNode;\n };\n }\n changedHistory ??= {\n ...historyValue\n };\n changedHistory[historyNode.id] = Array.from(mutStateNodeSet).filter(predicate);\n }\n }\n for (const s of statesToExit) {\n nextSnapshot = resolveActionsAndContext(nextSnapshot, event, actorScope, [...s.exit, ...s.invoke.map(def => stopChild(def.id))], internalQueue, undefined);\n mutStateNodeSet.delete(s);\n }\n return [nextSnapshot, changedHistory || historyValue];\n}\nfunction getAction(machine, actionType) {\n return machine.implementations.actions[actionType];\n}\nfunction resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, extra, retries) {\n const {\n machine\n } = currentSnapshot;\n let intermediateSnapshot = currentSnapshot;\n for (const action of actions) {\n const isInline = typeof action === 'function';\n const resolvedAction = isInline ? action :\n // the existing type of `.actions` assumes non-nullable `TExpressionAction`\n // it's fine to cast this here to get a common type and lack of errors in the rest of the code\n // our logic below makes sure that we call those 2 \"variants\" correctly\n\n getAction(machine, typeof action === 'string' ? action : action.type);\n const actionArgs = {\n context: intermediateSnapshot.context,\n event,\n self: actorScope.self,\n system: actorScope.system\n };\n const actionParams = isInline || typeof action === 'string' ? undefined : 'params' in action ? typeof action.params === 'function' ? action.params({\n context: intermediateSnapshot.context,\n event\n }) : action.params : undefined;\n if (!resolvedAction || !('resolve' in resolvedAction)) {\n actorScope.actionExecutor({\n type: typeof action === 'string' ? action : typeof action === 'object' ? action.type : action.name || '(anonymous)',\n info: actionArgs,\n params: actionParams,\n exec: resolvedAction\n });\n continue;\n }\n const builtinAction = resolvedAction;\n const [nextState, params, actions] = builtinAction.resolve(actorScope, intermediateSnapshot, actionArgs, actionParams, resolvedAction,\n // this holds all params\n extra);\n intermediateSnapshot = nextState;\n if ('retryResolve' in builtinAction) {\n retries?.push([builtinAction, params]);\n }\n if ('execute' in builtinAction) {\n actorScope.actionExecutor({\n type: builtinAction.type,\n info: actionArgs,\n params,\n exec: builtinAction.execute.bind(null, actorScope, params)\n });\n }\n if (actions) {\n intermediateSnapshot = resolveAndExecuteActionsWithContext(intermediateSnapshot, event, actorScope, actions, extra, retries);\n }\n }\n return intermediateSnapshot;\n}\nfunction resolveActionsAndContext(currentSnapshot, event, actorScope, actions, internalQueue, deferredActorIds) {\n const retries = deferredActorIds ? [] : undefined;\n const nextState = resolveAndExecuteActionsWithContext(currentSnapshot, event, actorScope, actions, {\n internalQueue,\n deferredActorIds\n }, retries);\n retries?.forEach(([builtinAction, params]) => {\n builtinAction.retryResolve(actorScope, nextState, params);\n });\n return nextState;\n}\nfunction macrostep(snapshot, event, actorScope, internalQueue) {\n let nextSnapshot = snapshot;\n const microsteps = [];\n function addMicrostep(step, event, transitions) {\n actorScope.system._sendInspectionEvent({\n type: '@xstate.microstep',\n actorRef: actorScope.self,\n event,\n snapshot: step[0],\n _transitions: transitions\n });\n microsteps.push(step);\n }\n\n // Handle stop event\n if (event.type === XSTATE_STOP) {\n nextSnapshot = cloneMachineSnapshot(stopChildren(nextSnapshot, event, actorScope), {\n status: 'stopped'\n });\n addMicrostep([nextSnapshot, []], event, []);\n return {\n snapshot: nextSnapshot,\n microsteps\n };\n }\n let nextEvent = event;\n\n // Assume the state is at rest (no raised events)\n // Determine the next state based on the next microstep\n if (nextEvent.type !== XSTATE_INIT) {\n const currentEvent = nextEvent;\n const isErr = isErrorActorEvent(currentEvent);\n const transitions = selectTransitions(currentEvent, nextSnapshot);\n if (isErr && !transitions.length) {\n // TODO: we should likely only allow transitions selected by very explicit descriptors\n // `*` shouldn't be matched, likely `xstate.error.*` shouldn't be either\n // similarly `xstate.error.actor.*` and `xstate.error.actor.todo.*` have to be considered too\n nextSnapshot = cloneMachineSnapshot(snapshot, {\n status: 'error',\n error: currentEvent.error\n });\n addMicrostep([nextSnapshot, []], currentEvent, []);\n return {\n snapshot: nextSnapshot,\n microsteps\n };\n }\n const step = microstep(transitions, snapshot, actorScope, nextEvent, false,\n // isInitial\n internalQueue);\n nextSnapshot = step[0];\n addMicrostep(step, currentEvent, transitions);\n }\n let shouldSelectEventlessTransitions = true;\n while (nextSnapshot.status === 'active') {\n let enabledTransitions = shouldSelectEventlessTransitions ? selectEventlessTransitions(nextSnapshot, nextEvent) : [];\n\n // eventless transitions should always be selected after selecting *regular* transitions\n // by assigning `undefined` to `previousState` we ensure that `shouldSelectEventlessTransitions` gets always computed to true in such a case\n const previousState = enabledTransitions.length ? nextSnapshot : undefined;\n if (!enabledTransitions.length) {\n if (!internalQueue.length) {\n break;\n }\n nextEvent = internalQueue.shift();\n enabledTransitions = selectTransitions(nextEvent, nextSnapshot);\n }\n const step = microstep(enabledTransitions, nextSnapshot, actorScope, nextEvent, false, internalQueue);\n nextSnapshot = step[0];\n shouldSelectEventlessTransitions = nextSnapshot !== previousState;\n addMicrostep(step, nextEvent, enabledTransitions);\n }\n if (nextSnapshot.status !== 'active') {\n stopChildren(nextSnapshot, nextEvent, actorScope);\n }\n return {\n snapshot: nextSnapshot,\n microsteps\n };\n}\nfunction stopChildren(nextState, event, actorScope) {\n return resolveActionsAndContext(nextState, event, actorScope, Object.values(nextState.children).map(child => stopChild(child)), [], undefined);\n}\nfunction selectTransitions(event, nextState) {\n return nextState.machine.getTransitionData(nextState, event);\n}\nfunction selectEventlessTransitions(nextState, event) {\n const enabledTransitionSet = new Set();\n const atomicStates = nextState._nodes.filter(isAtomicStateNode);\n for (const stateNode of atomicStates) {\n loop: for (const s of [stateNode].concat(getProperAncestors(stateNode, undefined))) {\n if (!s.always) {\n continue;\n }\n for (const transition of s.always) {\n if (transition.guard === undefined || evaluateGuard(transition.guard, nextState.context, event, nextState)) {\n enabledTransitionSet.add(transition);\n break loop;\n }\n }\n }\n }\n return removeConflictingTransitions(Array.from(enabledTransitionSet), new Set(nextState._nodes), nextState.historyValue);\n}\n\n/**\n * Resolves a partial state value with its full representation in the state\n * node's machine.\n *\n * @param stateValue The partial state value to resolve.\n */\nfunction resolveStateValue(rootNode, stateValue) {\n const allStateNodes = getAllStateNodes(getStateNodes(rootNode, stateValue));\n return getStateValue(rootNode, [...allStateNodes]);\n}\n\nfunction isMachineSnapshot(value) {\n return !!value && typeof value === 'object' && 'machine' in value && 'value' in value;\n}\nconst machineSnapshotMatches = function matches(testValue) {\n return matchesState(testValue, this.value);\n};\nconst machineSnapshotHasTag = function hasTag(tag) {\n return this.tags.has(tag);\n};\nconst machineSnapshotCan = function can(event) {\n const transitionData = this.machine.getTransitionData(this, event);\n return !!transitionData?.length &&\n // Check that at least one transition is not forbidden\n transitionData.some(t => t.target !== undefined || t.actions.length);\n};\nconst machineSnapshotToJSON = function toJSON() {\n const {\n _nodes: nodes,\n tags,\n machine,\n getMeta,\n toJSON,\n can,\n hasTag,\n matches,\n ...jsonValues\n } = this;\n return {\n ...jsonValues,\n tags: Array.from(tags)\n };\n};\nconst machineSnapshotGetMeta = function getMeta() {\n return this._nodes.reduce((acc, stateNode) => {\n if (stateNode.meta !== undefined) {\n acc[stateNode.id] = stateNode.meta;\n }\n return acc;\n }, {});\n};\nfunction createMachineSnapshot(config, machine) {\n return {\n status: config.status,\n output: config.output,\n error: config.error,\n machine,\n context: config.context,\n _nodes: config._nodes,\n value: getStateValue(machine.root, config._nodes),\n tags: new Set(config._nodes.flatMap(sn => sn.tags)),\n children: config.children,\n historyValue: config.historyValue || {},\n matches: machineSnapshotMatches,\n hasTag: machineSnapshotHasTag,\n can: machineSnapshotCan,\n getMeta: machineSnapshotGetMeta,\n toJSON: machineSnapshotToJSON\n };\n}\nfunction cloneMachineSnapshot(snapshot, config = {}) {\n return createMachineSnapshot({\n ...snapshot,\n ...config\n }, snapshot.machine);\n}\nfunction serializeHistoryValue(historyValue) {\n if (typeof historyValue !== 'object' || historyValue === null) {\n return {};\n }\n const result = {};\n for (const key in historyValue) {\n const value = historyValue[key];\n if (Array.isArray(value)) {\n result[key] = value.map(item => ({\n id: item.id\n }));\n }\n }\n return result;\n}\nfunction getPersistedSnapshot(snapshot, options) {\n const {\n _nodes: nodes,\n tags,\n machine,\n children,\n context,\n can,\n hasTag,\n matches,\n getMeta,\n toJSON,\n ...jsonValues\n } = snapshot;\n const childrenJson = {};\n for (const id in children) {\n const child = children[id];\n childrenJson[id] = {\n snapshot: child.getPersistedSnapshot(options),\n src: child.src,\n systemId: child.systemId,\n syncSnapshot: child._syncSnapshot\n };\n }\n const persisted = {\n ...jsonValues,\n context: persistContext(context),\n children: childrenJson,\n historyValue: serializeHistoryValue(jsonValues.historyValue)\n };\n return persisted;\n}\nfunction persistContext(contextPart) {\n let copy;\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('sessionId' in value && 'send' in value && 'ref' in value) {\n copy ??= Array.isArray(contextPart) ? contextPart.slice() : {\n ...contextPart\n };\n copy[key] = {\n xstate$$type: $$ACTOR_TYPE,\n id: value.id\n };\n } else {\n const result = persistContext(value);\n if (result !== value) {\n copy ??= Array.isArray(contextPart) ? contextPart.slice() : {\n ...contextPart\n };\n copy[key] = result;\n }\n }\n }\n }\n return copy ?? contextPart;\n}\n\nfunction resolveRaise(_, snapshot, args, actionParams, {\n event: eventOrExpr,\n id,\n delay\n}, {\n internalQueue\n}) {\n const delaysMap = snapshot.machine.implementations.delays;\n if (typeof eventOrExpr === 'string') {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with raise; use raise({ type: \"${eventOrExpr}\" }) instead`);\n }\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n let resolvedDelay;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;\n } else {\n resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n if (typeof resolvedDelay !== 'number') {\n internalQueue.push(resolvedEvent);\n }\n return [snapshot, {\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n }, undefined];\n}\nfunction executeRaise(actorScope, params) {\n const {\n event,\n delay,\n id\n } = params;\n if (typeof delay === 'number') {\n actorScope.defer(() => {\n const self = actorScope.self;\n actorScope.system.scheduler.schedule(self, self, event, delay, id);\n });\n return;\n }\n}\n/**\n * Raises an event. This places the event in the internal event queue, so that\n * the event is immediately consumed by the machine in the current step.\n *\n * @param eventType The event to raise.\n */\nfunction raise(eventOrExpr, options) {\n function raise(_args, _params) {\n }\n raise.type = 'xstate.raise';\n raise.event = eventOrExpr;\n raise.id = options?.id;\n raise.delay = options?.delay;\n raise.resolve = resolveRaise;\n raise.execute = executeRaise;\n return raise;\n}\n\nexport { $$ACTOR_TYPE as $, Actor as A, toTransitionConfigArray as B, formatTransition as C, evaluateGuard as D, createInvokeId as E, getDelayedTransitions as F, formatInitialTransition as G, getCandidates as H, formatRouteTransitions as I, resolveStateValue as J, getAllStateNodes as K, createMachineSnapshot as L, isInFinalState as M, NULL_EVENT as N, transitionNode as O, resolveActionsAndContext as P, toStatePath as Q, isStateId as R, STATE_DELIMITER as S, getStateNodeByPath as T, getPersistedSnapshot as U, resolveReferencedActor as V, XSTATE_ERROR as W, XSTATE_STOP as X, createErrorActorEvent as Y, ProcessingStatus as Z, cloneMachineSnapshot as _, cancel as a, spawnChild as b, createActor as c, macrostep as d, createInitEvent as e, isAtomicStateNode as f, getProperAncestors as g, interpret as h, initialMicrostep as i, and as j, stateIn as k, isMachineSnapshot as l, matchesEventDescriptor as m, not as n, or as o, getStateNodes as p, getAllOwnEventDescriptors as q, raise as r, stopChild as s, toArray as t, matchesState as u, pathToStateValue as v, toObserver as w, stop as x, mapValues as y, formatTransitions as z };\n","import { X as XSTATE_STOP, c as createActor } from '../../dist/raise-34c45204.esm.js';\nimport '../../dev/dist/xstate-dev.esm.js';\n\n/**\n * Represents an actor created by `fromTransition`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import {\n * fromTransition,\n * createActor,\n * type AnyActorSystem\n * } from 'xstate';\n *\n * //* The actor's stored context.\n * type Context = {\n * // The current count.\n * count: number;\n * // The amount to increase `count` by.\n * step: number;\n * };\n * // The events the actor receives.\n * type Event = { type: 'increment' };\n * // The actor's input.\n * type Input = { step?: number };\n *\n * // Actor logic that increments `count` by `step` when it receives an event of\n * // type `increment`.\n * const logic = fromTransition<Context, Event, AnyActorSystem, Input>(\n * (state, event, actorScope) => {\n * actorScope.self;\n * // ^? TransitionActorRef<Context, Event>\n *\n * if (event.type === 'increment') {\n * return {\n * ...state,\n * count: state.count + state.step\n * };\n * }\n * return state;\n * },\n * ({ input, self }) => {\n * self;\n * // ^? TransitionActorRef<Context, Event>\n *\n * return {\n * count: 0,\n * step: input.step ?? 1\n * };\n * }\n * );\n *\n * const actor = createActor(logic, { input: { step: 10 } });\n * // ^? TransitionActorRef<Context, Event>\n * ```\n *\n * @see {@link fromTransition}\n */\n\n/**\n * Returns actor logic given a transition function and its initial state.\n *\n * A “transition function” is a function that takes the current `state` and\n * received `event` object as arguments, and returns the next state, similar to\n * a reducer.\n *\n * Actors created from transition logic (“transition actors”) can:\n *\n * - Receive events\n * - Emit snapshots of its state\n *\n * The transition function’s `state` is used as its transition actor’s\n * `context`.\n *\n * Note that the \"state\" for a transition function is provided by the initial\n * state argument, and is not the same as the State object of an actor or a\n * state within a machine configuration.\n *\n * @example\n *\n * ```ts\n * const transitionLogic = fromTransition(\n * (state, event) => {\n * if (event.type === 'increment') {\n * return {\n * ...state,\n * count: state.count + 1\n * };\n * }\n * return state;\n * },\n * { count: 0 }\n * );\n *\n * const transitionActor = createActor(transitionLogic);\n * transitionActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * transitionActor.start();\n * // => {\n * // status: 'active',\n * // context: { count: 0 },\n * // ...\n * // }\n *\n * transitionActor.send({ type: 'increment' });\n * // => {\n * // status: 'active',\n * // context: { count: 1 },\n * // ...\n * // }\n * ```\n *\n * @param transition The transition function used to describe the transition\n * logic. It should return the next state given the current state and event.\n * It receives the following arguments:\n *\n * - `state` - the current state.\n * - `event` - the received event.\n * - `actorScope` - the actor scope object, with properties like `self` and\n * `system`.\n *\n * @param initialContext The initial state of the transition function, either an\n * object representing the state, or a function which returns a state object.\n * If a function, it will receive as its only argument an object with the\n * following properties:\n *\n * - `input` - the `input` provided to its parent transition actor.\n * - `self` - a reference to its parent transition actor.\n *\n * @returns Actor logic\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromTransition(transition, initialContext) {\n return {\n config: transition,\n transition: (snapshot, event, actorScope) => {\n return {\n ...snapshot,\n context: transition(snapshot.context, event, actorScope)\n };\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: typeof initialContext === 'function' ? initialContext({\n input\n }) : initialContext\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n}\n\nconst instanceStates = /* #__PURE__ */new WeakMap();\n\n/**\n * Represents an actor created by `fromCallback`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromCallback, createActor } from 'xstate';\n *\n * // The events the actor receives.\n * type Event = { type: 'someEvent' };\n * // The actor's input.\n * type Input = { name: string };\n *\n * // Actor logic that logs whenever it receives an event of type `someEvent`.\n * const logic = fromCallback<Event, Input>(({ self, input, receive }) => {\n * self;\n * // ^? CallbackActorRef<Event, Input>\n *\n * receive((event) => {\n * if (event.type === 'someEvent') {\n * console.log(`${input.name}: received \"someEvent\" event`);\n * // logs 'myActor: received \"someEvent\" event'\n * }\n * });\n * });\n *\n * const actor = createActor(logic, { input: { name: 'myActor' } });\n * // ^? CallbackActorRef<Event, Input>\n * ```\n *\n * @see {@link fromCallback}\n */\n\n/**\n * An actor logic creator which returns callback logic as defined by a callback\n * function.\n *\n * @remarks\n * Useful for subscription-based or other free-form logic that can send events\n * back to the parent actor.\n *\n * Actors created from callback logic (“callback actors”) can:\n *\n * - Receive events via the `receive` function\n * - Send events to the parent actor via the `sendBack` function\n *\n * Callback actors are a bit different from other actors in that they:\n *\n * - Do not work with `onDone`\n * - Do not produce a snapshot using `.getSnapshot()`\n * - Do not emit values when used with `.subscribe()`\n * - Can not be stopped with `.stop()`\n *\n * @example\n *\n * ```typescript\n * const callbackLogic = fromCallback(({ sendBack, receive }) => {\n * let lockStatus = 'unlocked';\n *\n * const handler = (event) => {\n * if (lockStatus === 'locked') {\n * return;\n * }\n * sendBack(event);\n * };\n *\n * receive((event) => {\n * if (event.type === 'lock') {\n * lockStatus = 'locked';\n * } else if (event.type === 'unlock') {\n * lockStatus = 'unlocked';\n * }\n * });\n *\n * document.body.addEventListener('click', handler);\n *\n * return () => {\n * document.body.removeEventListener('click', handler);\n * };\n * });\n * ```\n *\n * @param callback - The callback function used to describe the callback logic\n * The callback function is passed an object with the following properties:\n *\n * - `receive` - A function that can send events back to the parent actor; the\n * listener is then called whenever events are received by the callback\n * actor\n * - `sendBack` - A function that can send events back to the parent actor\n * - `input` - Data that was provided to the callback actor\n * - `self` - The parent actor of the callback actor\n * - `system` - The actor system to which the callback actor belongs The callback\n * function can (optionally) return a cleanup function, which is called\n * when the actor is stopped.\n *\n * @returns Callback logic\n * @see {@link CallbackLogicFunction} for more information about the callback function and its object argument\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromCallback(callback) {\n const logic = {\n config: callback,\n start: (state, actorScope) => {\n const {\n self,\n system,\n emit\n } = actorScope;\n const callbackState = {\n receivers: undefined,\n dispose: undefined\n };\n instanceStates.set(self, callbackState);\n callbackState.dispose = callback({\n input: state.input,\n system,\n self,\n sendBack: event => {\n if (self.getSnapshot().status === 'stopped') {\n return;\n }\n if (self._parent) {\n system._relay(self, self._parent, event);\n }\n },\n receive: listener => {\n callbackState.receivers ??= new Set();\n callbackState.receivers.add(listener);\n },\n emit\n });\n },\n transition: (state, event, actorScope) => {\n const callbackState = instanceStates.get(actorScope.self);\n if (event.type === XSTATE_STOP) {\n state = {\n ...state,\n status: 'stopped',\n error: undefined\n };\n instanceStates.delete(actorScope.self);\n callbackState.receivers?.clear();\n callbackState.dispose?.();\n return state;\n }\n callbackState.receivers?.forEach(receiver => receiver(event));\n return state;\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n return logic;\n}\n\nconst XSTATE_OBSERVABLE_NEXT = 'xstate.observable.next';\nconst XSTATE_OBSERVABLE_ERROR = 'xstate.observable.error';\nconst XSTATE_OBSERVABLE_COMPLETE = 'xstate.observable.complete';\n\n/**\n * Represents an actor created by `fromObservable` or `fromEventObservable`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromObservable, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * // The type of the value observed by the actor's logic.\n * type Context = number;\n * // The actor's input.\n * type Input = { period?: number };\n *\n * // Actor logic that observes a number incremented every `input.period`\n * // milliseconds (default: 1_000).\n * const logic = fromObservable<Context, Input>(({ input, self }) => {\n * self;\n * // ^? ObservableActorRef<Event, Input>\n *\n * return interval(input.period ?? 1_000);\n * });\n *\n * const actor = createActor(logic, { input: { period: 2_000 } });\n * // ^? ObservableActorRef<Event, Input>\n * ```\n *\n * @see {@link fromObservable}\n * @see {@link fromEventObservable}\n */\n\n/**\n * Observable actor logic is described by an observable stream of values. Actors\n * created from observable logic (“observable actors”) can:\n *\n * - Emit snapshots of the observable’s emitted value\n *\n * The observable’s emitted value is used as its observable actor’s `context`.\n *\n * Sending events to observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import { fromObservable, createActor } from 'xstate';\n * import { interval } from 'rxjs';\n *\n * const logic = fromObservable((obj) => interval(1000));\n *\n * const actor = createActor(logic);\n *\n * actor.subscribe((snapshot) => {\n * console.log(snapshot.context);\n * });\n *\n * actor.start();\n * // At every second:\n * // Logs 0\n * // Logs 1\n * // Logs 2\n * // ...\n * ```\n *\n * @param observableCreator A function that creates an observable. It receives\n * one argument, an object with the following properties:\n *\n * - `input` - Data that was provided to the observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the observable actor belongs\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n * @see {@link https://rxjs.dev} for documentation on RxJS Observable and observable creators.\n * @see {@link Subscribable} interface in XState, which is based on and compatible with RxJS Observable.\n */\nfunction fromObservable(observableCreator) {\n // TODO: add event types\n const logic = {\n config: observableCreator,\n transition: (snapshot, event) => {\n if (snapshot.status !== 'active') {\n return snapshot;\n }\n switch (event.type) {\n case XSTATE_OBSERVABLE_NEXT:\n {\n const newSnapshot = {\n ...snapshot,\n context: event.data\n };\n return newSnapshot;\n }\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...snapshot,\n status: 'error',\n error: event.data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...snapshot,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n snapshot._subscription.unsubscribe();\n return {\n ...snapshot,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return snapshot;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = observableCreator({\n input: state.input,\n system,\n self,\n emit\n }).subscribe({\n next: value => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_NEXT,\n data: value\n });\n },\n error: err => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n },\n getPersistedSnapshot: ({\n _subscription,\n ...state\n }) => state,\n restoreSnapshot: state => ({\n ...state,\n _subscription: undefined\n })\n };\n return logic;\n}\n\n/**\n * Creates event observable logic that listens to an observable that delivers\n * event objects.\n *\n * Event observable actor logic is described by an observable stream of\n * {@link https://stately.ai/docs/transitions#event-objects | event objects}.\n * Actors created from event observable logic (“event observable actors”) can:\n *\n * - Implicitly send events to its parent actor\n * - Emit snapshots of its emitted event objects\n *\n * Sending events to event observable actors will have no effect.\n *\n * @example\n *\n * ```ts\n * import {\n * fromEventObservable,\n * Subscribable,\n * EventObject,\n * createMachine,\n * createActor\n * } from 'xstate';\n * import { fromEvent } from 'rxjs';\n *\n * const mouseClickLogic = fromEventObservable(\n * () => fromEvent(document.body, 'click') as Subscribable<EventObject>\n * );\n *\n * const canvasMachine = createMachine({\n * invoke: {\n * // Will send mouse `click` events to the canvas actor\n * src: mouseClickLogic\n * }\n * });\n *\n * const canvasActor = createActor(canvasMachine);\n * canvasActor.start();\n * ```\n *\n * @param lazyObservable A function that creates an observable that delivers\n * event objects. It receives one argument, an object with the following\n * properties:\n *\n * - `input` - Data that was provided to the event observable actor\n * - `self` - The parent actor\n * - `system` - The actor system to which the event observable actor belongs.\n *\n * It should return a {@link Subscribable}, which is compatible with an RxJS\n * Observable, although RxJS is not required to create them.\n */\nfunction fromEventObservable(lazyObservable) {\n // TODO: event types\n const logic = {\n config: lazyObservable,\n transition: (state, event) => {\n if (state.status !== 'active') {\n return state;\n }\n switch (event.type) {\n case XSTATE_OBSERVABLE_ERROR:\n return {\n ...state,\n status: 'error',\n error: event.data,\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_OBSERVABLE_COMPLETE:\n return {\n ...state,\n status: 'done',\n input: undefined,\n _subscription: undefined\n };\n case XSTATE_STOP:\n state._subscription.unsubscribe();\n return {\n ...state,\n status: 'stopped',\n input: undefined,\n _subscription: undefined\n };\n default:\n return state;\n }\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n context: undefined,\n input,\n _subscription: undefined\n };\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n if (state.status === 'done') {\n // Do not restart a completed observable\n return;\n }\n state._subscription = lazyObservable({\n input: state.input,\n system,\n self,\n emit\n }).subscribe({\n next: value => {\n if (self._parent) {\n system._relay(self, self._parent, value);\n }\n },\n error: err => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_ERROR,\n data: err\n });\n },\n complete: () => {\n system._relay(self, self, {\n type: XSTATE_OBSERVABLE_COMPLETE\n });\n }\n });\n },\n getPersistedSnapshot: ({\n _subscription,\n ...snapshot\n }) => snapshot,\n restoreSnapshot: snapshot => ({\n ...snapshot,\n _subscription: undefined\n })\n };\n return logic;\n}\n\nconst XSTATE_PROMISE_RESOLVE = 'xstate.promise.resolve';\nconst XSTATE_PROMISE_REJECT = 'xstate.promise.reject';\n\n/**\n * Represents an actor created by `fromPromise`.\n *\n * The type of `self` within the actor's logic.\n *\n * @example\n *\n * ```ts\n * import { fromPromise, createActor } from 'xstate';\n *\n * // The actor's resolved output\n * type Output = string;\n * // The actor's input.\n * type Input = { message: string };\n *\n * // Actor logic that fetches the url of an image of a cat saying `input.message`.\n * const logic = fromPromise<Output, Input>(async ({ input, self }) => {\n * self;\n * // ^? PromiseActorRef<Output, Input>\n *\n * const data = await fetch(\n * `https://cataas.com/cat/says/${input.message}`\n * );\n * const url = await data.json();\n * return url;\n * });\n *\n * const actor = createActor(logic, { input: { message: 'hello world' } });\n * // ^? PromiseActorRef<Output, Input>\n * ```\n *\n * @see {@link fromPromise}\n */\n\nconst controllerMap = new WeakMap();\n\n/**\n * An actor logic creator which returns promise logic as defined by an async\n * process that resolves or rejects after some time.\n *\n * Actors created from promise actor logic (“promise actors”) can:\n *\n * - Emit the resolved value of the promise\n * - Output the resolved value of the promise\n *\n * Sending events to promise actors will have no effect.\n *\n * @example\n *\n * ```ts\n * const promiseLogic = fromPromise(async () => {\n * const result = await fetch('https://example.com/...').then((data) =>\n * data.json()\n * );\n *\n * return result;\n * });\n *\n * const promiseActor = createActor(promiseLogic);\n * promiseActor.subscribe((snapshot) => {\n * console.log(snapshot);\n * });\n * promiseActor.start();\n * // => {\n * // output: undefined,\n * // status: 'active'\n * // ...\n * // }\n *\n * // After promise resolves\n * // => {\n * // output: { ... },\n * // status: 'done',\n * // ...\n * // }\n * ```\n *\n * @param promiseCreator A function which returns a Promise, and accepts an\n * object with the following properties:\n *\n * - `input` - Data that was provided to the promise actor\n * - `self` - The parent actor of the promise actor\n * - `system` - The actor system to which the promise actor belongs\n *\n * @see {@link https://stately.ai/docs/input | Input docs} for more information about how input is passed\n */\nfunction fromPromise(promiseCreator) {\n const logic = {\n config: promiseCreator,\n transition: (state, event, scope) => {\n if (state.status !== 'active') {\n return state;\n }\n switch (event.type) {\n case XSTATE_PROMISE_RESOLVE:\n {\n const resolvedValue = event.data;\n return {\n ...state,\n status: 'done',\n output: resolvedValue,\n input: undefined\n };\n }\n case XSTATE_PROMISE_REJECT:\n return {\n ...state,\n status: 'error',\n error: event.data,\n input: undefined\n };\n case XSTATE_STOP:\n {\n controllerMap.get(scope.self)?.abort();\n controllerMap.delete(scope.self);\n return {\n ...state,\n status: 'stopped',\n input: undefined\n };\n }\n default:\n return state;\n }\n },\n start: (state, {\n self,\n system,\n emit\n }) => {\n // TODO: determine how to allow customizing this so that promises\n // can be restarted if necessary\n if (state.status !== 'active') {\n return;\n }\n const controller = new AbortController();\n controllerMap.set(self, controller);\n const resolvedPromise = Promise.resolve(promiseCreator({\n input: state.input,\n system,\n self,\n signal: controller.signal,\n emit\n }));\n resolvedPromise.then(response => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controllerMap.delete(self);\n system._relay(self, self, {\n type: XSTATE_PROMISE_RESOLVE,\n data: response\n });\n }, errorData => {\n if (self.getSnapshot().status !== 'active') {\n return;\n }\n controllerMap.delete(self);\n system._relay(self, self, {\n type: XSTATE_PROMISE_REJECT,\n data: errorData\n });\n });\n },\n getInitialSnapshot: (_, input) => {\n return {\n status: 'active',\n output: undefined,\n error: undefined,\n input\n };\n },\n getPersistedSnapshot: snapshot => snapshot,\n restoreSnapshot: snapshot => snapshot\n };\n return logic;\n}\n\nconst emptyLogic = fromTransition(_ => undefined, undefined);\nfunction createEmptyActor() {\n return createActor(emptyLogic);\n}\n\nexport { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition };\n","import { Z as ProcessingStatus, V as resolveReferencedActor, c as createActor, _ as cloneMachineSnapshot } from './raise-34c45204.esm.js';\n\nfunction createSpawner(actorScope, {\n machine,\n context\n}, event, spawnedChildren) {\n const spawn = (src, options) => {\n if (typeof src === 'string') {\n const logic = resolveReferencedActor(machine, src);\n if (!logic) {\n throw new Error(`Actor logic '${src}' not implemented in machine '${machine.id}'`);\n }\n const actorRef = createActor(logic, {\n id: options?.id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: typeof options?.input === 'function' ? options.input({\n context,\n event,\n self: actorScope.self\n }) : options?.input,\n src,\n systemId: options?.systemId\n });\n spawnedChildren[actorRef.id] = actorRef;\n return actorRef;\n } else {\n const actorRef = createActor(src, {\n id: options?.id,\n parent: actorScope.self,\n syncSnapshot: options?.syncSnapshot,\n input: options?.input,\n src,\n systemId: options?.systemId\n });\n return actorRef;\n }\n };\n return (src, options) => {\n const actorRef = spawn(src, options); // TODO: fix types\n spawnedChildren[actorRef.id] = actorRef;\n actorScope.defer(() => {\n if (actorRef._processingStatus === ProcessingStatus.Stopped) {\n return;\n }\n actorRef.start();\n });\n return actorRef;\n };\n}\n\nfunction resolveAssign(actorScope, snapshot, actionArgs, actionParams, {\n assignment\n}) {\n if (!snapshot.context) {\n throw new Error('Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.');\n }\n const spawnedChildren = {};\n const assignArgs = {\n context: snapshot.context,\n event: actionArgs.event,\n spawn: createSpawner(actorScope, snapshot, actionArgs.event, spawnedChildren),\n self: actorScope.self,\n system: actorScope.system\n };\n let partialUpdate = {};\n if (typeof assignment === 'function') {\n partialUpdate = assignment(assignArgs, actionParams);\n } else {\n for (const key of Object.keys(assignment)) {\n const propAssignment = assignment[key];\n partialUpdate[key] = typeof propAssignment === 'function' ? propAssignment(assignArgs, actionParams) : propAssignment;\n }\n }\n const updatedContext = Object.assign({}, snapshot.context, partialUpdate);\n return [cloneMachineSnapshot(snapshot, {\n context: updatedContext,\n children: Object.keys(spawnedChildren).length ? {\n ...snapshot.children,\n ...spawnedChildren\n } : snapshot.children\n }), undefined, undefined];\n}\n/**\n * Updates the current context of the machine.\n *\n * @example\n *\n * ```ts\n * import { createMachine, assign } from 'xstate';\n *\n * const countMachine = createMachine({\n * context: {\n * count: 0,\n * message: ''\n * },\n * on: {\n * inc: {\n * actions: assign({\n * count: ({ context }) => context.count + 1\n * })\n * },\n * updateMessage: {\n * actions: assign(({ context, event }) => {\n * return {\n * message: event.message.trim()\n * };\n * })\n * }\n * }\n * });\n * ```\n *\n * @param assignment An object that represents the partial context to update, or\n * a function that returns an object that represents the partial context to\n * update.\n */\nfunction assign(assignment) {\n function assign(_args, _params) {\n }\n assign.type = 'xstate.assign';\n assign.assignment = assignment;\n assign.resolve = resolveAssign;\n return assign;\n}\n\nexport { assign as a };\n","import { S as STATE_DELIMITER, y as mapValues, t as toArray, z as formatTransitions, B as toTransitionConfigArray, C as formatTransition, N as NULL_EVENT, D as evaluateGuard, E as createInvokeId, F as getDelayedTransitions, G as formatInitialTransition, H as getCandidates, I as formatRouteTransitions, J as resolveStateValue, K as getAllStateNodes, p as getStateNodes, L as createMachineSnapshot, M as isInFinalState, d as macrostep, O as transitionNode, P as resolveActionsAndContext, e as createInitEvent, i as initialMicrostep, Q as toStatePath, R as isStateId, T as getStateNodeByPath, U as getPersistedSnapshot, V as resolveReferencedActor, c as createActor, $ as $$ACTOR_TYPE } from './raise-34c45204.esm.js';\nimport { a as assign } from './assign-5f7ff891.esm.js';\n\nconst cache = new WeakMap();\nfunction memo(object, key, fn) {\n let memoizedData = cache.get(object);\n if (!memoizedData) {\n memoizedData = {\n [key]: fn()\n };\n cache.set(object, memoizedData);\n } else if (!(key in memoizedData)) {\n memoizedData[key] = fn();\n }\n return memoizedData[key];\n}\n\nconst EMPTY_OBJECT = {};\nconst toSerializableAction = action => {\n if (typeof action === 'string') {\n return {\n type: action\n };\n }\n if (typeof action === 'function') {\n if ('resolve' in action) {\n return {\n type: action.type\n };\n }\n return {\n type: action.name\n };\n }\n return action;\n};\nclass StateNode {\n constructor(/** The raw config used to create the machine. */\n config, options) {\n this.config = config;\n /**\n * The relative key of the state node, which represents its location in the\n * overall state value.\n */\n this.key = void 0;\n /** The unique ID of the state node. */\n this.id = void 0;\n /**\n * The type of this state node:\n *\n * - `'atomic'` - no child state nodes\n * - `'compound'` - nested child state nodes (XOR)\n * - `'parallel'` - orthogonal nested child state nodes (AND)\n * - `'history'` - history state node\n * - `'final'` - final state node\n */\n this.type = void 0;\n /** The string path from the root machine node to this node. */\n this.path = void 0;\n /** The child state nodes. */\n this.states = void 0;\n /**\n * The type of history on this state node. Can be:\n *\n * - `'shallow'` - recalls only top-level historical state value\n * - `'deep'` - recalls historical state value at all levels\n */\n this.history = void 0;\n /** The action(s) to be executed upon entering the state node. */\n this.entry = void 0;\n /** The action(s) to be executed upon exiting the state node. */\n this.exit = void 0;\n /** The parent state node. */\n this.parent = void 0;\n /** The root machine node. */\n this.machine = void 0;\n /**\n * The meta data associated with this state node, which will be returned in\n * State instances.\n */\n this.meta = void 0;\n /**\n * The output data sent with the \"xstate.done.state._id_\" event if this is a\n * final state node.\n */\n this.output = void 0;\n /**\n * The order this state node appears. Corresponds to the implicit document\n * order.\n */\n this.order = -1;\n this.description = void 0;\n this.tags = [];\n this.transitions = void 0;\n this.always = void 0;\n this.parent = options._parent;\n this.key = options._key;\n this.machine = options._machine;\n this.path = this.parent ? this.parent.path.concat(this.key) : [];\n this.id = this.config.id || [this.machine.id, ...this.path].join(STATE_DELIMITER);\n this.type = this.config.type || (this.config.states && Object.keys(this.config.states).length ? 'compound' : this.config.history ? 'history' : 'atomic');\n this.description = this.config.description;\n this.order = this.machine.idMap.size;\n this.machine.idMap.set(this.id, this);\n this.states = this.config.states ? mapValues(this.config.states, (stateConfig, key) => {\n const stateNode = new StateNode(stateConfig, {\n _parent: this,\n _key: key,\n _machine: this.machine\n });\n return stateNode;\n }) : EMPTY_OBJECT;\n if (this.type === 'compound' && !this.config.initial) {\n throw new Error(`No initial state specified for compound state node \"#${this.id}\". Try adding { initial: \"${Object.keys(this.states)[0]}\" } to the state config.`);\n }\n\n // History config\n this.history = this.config.history === true ? 'shallow' : this.config.history || false;\n this.entry = toArray(this.config.entry).slice();\n this.exit = toArray(this.config.exit).slice();\n this.meta = this.config.meta;\n this.output = this.type === 'final' || !this.parent ? this.config.output : undefined;\n this.tags = toArray(config.tags).slice();\n }\n\n /** @internal */\n _initialize() {\n this.transitions = formatTransitions(this);\n if (this.config.always) {\n this.always = toTransitionConfigArray(this.config.always).map(t => formatTransition(this, NULL_EVENT, t));\n }\n Object.keys(this.states).forEach(key => {\n this.states[key]._initialize();\n });\n }\n\n /** The well-structured state node definition. */\n get definition() {\n return {\n id: this.id,\n key: this.key,\n version: this.machine.version,\n type: this.type,\n initial: this.initial ? {\n target: this.initial.target,\n source: this,\n actions: this.initial.actions.map(toSerializableAction),\n eventType: null,\n reenter: false,\n toJSON: () => ({\n target: this.initial.target.map(t => `#${t.id}`),\n source: `#${this.id}`,\n actions: this.initial.actions.map(toSerializableAction),\n eventType: null\n })\n } : undefined,\n history: this.history,\n states: mapValues(this.states, state => {\n return state.definition;\n }),\n on: this.on,\n transitions: [...this.transitions.values()].flat().map(t => ({\n ...t,\n actions: t.actions.map(toSerializableAction)\n })),\n entry: this.entry.map(toSerializableAction),\n exit: this.exit.map(toSerializableAction),\n meta: this.meta,\n order: this.order || -1,\n output: this.output,\n invoke: this.invoke,\n description: this.description,\n tags: this.tags\n };\n }\n\n /** @internal */\n toJSON() {\n return this.definition;\n }\n\n /** The logic invoked as actors by this state node. */\n get invoke() {\n return memo(this, 'invoke', () => toArray(this.config.invoke).map((invokeConfig, i) => {\n const {\n src,\n systemId\n } = invokeConfig;\n const resolvedId = invokeConfig.id ?? createInvokeId(this.id, i);\n const sourceName = typeof src === 'string' ? src : `xstate.invoke.${createInvokeId(this.id, i)}`;\n return {\n ...invokeConfig,\n src: sourceName,\n id: resolvedId,\n systemId: systemId,\n toJSON() {\n const {\n onDone,\n onError,\n ...invokeDefValues\n } = invokeConfig;\n return {\n ...invokeDefValues,\n type: 'xstate.invoke',\n src: sourceName,\n id: resolvedId\n };\n }\n };\n }));\n }\n\n /** The mapping of events to transitions. */\n get on() {\n return memo(this, 'on', () => {\n const transitions = this.transitions;\n return [...transitions].flatMap(([descriptor, t]) => t.map(t => [descriptor, t])).reduce((map, [descriptor, transition]) => {\n map[descriptor] = map[descriptor] || [];\n map[descriptor].push(transition);\n return map;\n }, {});\n });\n }\n get after() {\n return memo(this, 'delayedTransitions', () => getDelayedTransitions(this));\n }\n get initial() {\n return memo(this, 'initial', () => formatInitialTransition(this, this.config.initial));\n }\n\n /** @internal */\n next(snapshot, event) {\n const eventType = event.type;\n const actions = [];\n let selectedTransition;\n const candidates = memo(this, `candidates-${eventType}`, () => getCandidates(this, eventType));\n for (const candidate of candidates) {\n const {\n guard\n } = candidate;\n const resolvedContext = snapshot.context;\n let guardPassed = false;\n try {\n guardPassed = !guard || evaluateGuard(guard, resolvedContext, event, snapshot);\n } catch (err) {\n const guardType = typeof guard === 'string' ? guard : typeof guard === 'object' ? guard.type : undefined;\n throw new Error(`Unable to evaluate guard ${guardType ? `'${guardType}' ` : ''}in transition for event '${eventType}' in state node '${this.id}':\\n${err.message}`);\n }\n if (guardPassed) {\n actions.push(...candidate.actions);\n selectedTransition = candidate;\n break;\n }\n }\n return selectedTransition ? [selectedTransition] : undefined;\n }\n\n /** All the event types accepted by this state node and its descendants. */\n get events() {\n return memo(this, 'events', () => {\n const {\n states\n } = this;\n const events = new Set(this.ownEvents);\n if (states) {\n for (const stateId of Object.keys(states)) {\n const state = states[stateId];\n if (state.states) {\n for (const event of state.events) {\n events.add(`${event}`);\n }\n }\n }\n }\n return Array.from(events);\n });\n }\n\n /**\n * All the events that have transitions directly from this state node.\n *\n * Excludes any inert events.\n */\n get ownEvents() {\n const keys = Object.keys(Object.fromEntries(this.transitions));\n const events = new Set(keys.filter(descriptor => {\n return this.transitions.get(descriptor).some(transition => !(!transition.target && !transition.actions.length && !transition.reenter));\n }));\n return Array.from(events);\n }\n}\n\nconst STATE_IDENTIFIER = '#';\nclass StateMachine {\n constructor(/** The raw config used to create the machine. */\n config, implementations) {\n this.config = config;\n /** The machine's own version. */\n this.version = void 0;\n this.schemas = void 0;\n this.implementations = void 0;\n /** @internal */\n this.__xstatenode = true;\n /** @internal */\n this.idMap = new Map();\n this.root = void 0;\n this.id = void 0;\n this.states = void 0;\n this.events = void 0;\n this.id = config.id || '(machine)';\n this.implementations = {\n actors: implementations?.actors ?? {},\n actions: implementations?.actions ?? {},\n delays: implementations?.delays ?? {},\n guards: implementations?.guards ?? {}\n };\n this.version = this.config.version;\n this.schemas = this.config.schemas;\n this.transition = this.transition.bind(this);\n this.getInitialSnapshot = this.getInitialSnapshot.bind(this);\n this.getPersistedSnapshot = this.getPersistedSnapshot.bind(this);\n this.restoreSnapshot = this.restoreSnapshot.bind(this);\n this.start = this.start.bind(this);\n this.root = new StateNode(config, {\n _key: this.id,\n _machine: this\n });\n this.root._initialize();\n formatRouteTransitions(this.root);\n this.states = this.root.states; // TODO: remove!\n this.events = this.root.events;\n }\n\n /**\n * Clones this state machine with the provided implementations.\n *\n * @param implementations Options (`actions`, `guards`, `actors`, `delays`) to\n * recursively merge with the existing options.\n * @returns A new `StateMachine` instance with the provided implementations.\n */\n provide(implementations) {\n const {\n actions,\n guards,\n actors,\n delays\n } = this.implementations;\n return new StateMachine(this.config, {\n actions: {\n ...actions,\n ...implementations.actions\n },\n guards: {\n ...guards,\n ...implementations.guards\n },\n actors: {\n ...actors,\n ...implementations.actors\n },\n delays: {\n ...delays,\n ...implementations.delays\n }\n });\n }\n resolveState(config) {\n const resolvedStateValue = resolveStateValue(this.root, config.value);\n const nodeSet = getAllStateNodes(getStateNodes(this.root, resolvedStateValue));\n return createMachineSnapshot({\n _nodes: [...nodeSet],\n context: config.context || {},\n children: {},\n status: isInFinalState(nodeSet, this.root) ? 'done' : config.status || 'active',\n output: config.output,\n error: config.error,\n historyValue: config.historyValue\n }, this);\n }\n\n /**\n * Determines the next snapshot given the current `snapshot` and received\n * `event`. Calculates a full macrostep from all microsteps.\n *\n * @param snapshot The current snapshot\n * @param event The received event\n */\n transition(snapshot, event, actorScope) {\n return macrostep(snapshot, event, actorScope, []).snapshot;\n }\n\n /**\n * Determines the next state given the current `state` and `event`. Calculates\n * a microstep.\n *\n * @param state The current state\n * @param event The received event\n */\n microstep(snapshot, event, actorScope) {\n return macrostep(snapshot, event, actorScope, []).microsteps.map(([s]) => s);\n }\n getTransitionData(snapshot, event) {\n return transitionNode(this.root, snapshot.value, snapshot, event) || [];\n }\n\n /**\n * The initial state _before_ evaluating any microsteps. This \"pre-initial\"\n * state is provided to initial actions executed in the initial state.\n *\n * @internal\n */\n _getPreInitialState(actorScope, initEvent, internalQueue) {\n const {\n context\n } = this.config;\n const preInitial = createMachineSnapshot({\n context: typeof context !== 'function' && context ? context : {},\n _nodes: [this.root],\n children: {},\n status: 'active'\n }, this);\n if (typeof context === 'function') {\n const assignment = ({\n spawn,\n event,\n self\n }) => context({\n spawn,\n input: event.input,\n self\n });\n return resolveActionsAndContext(preInitial, initEvent, actorScope, [assign(assignment)], internalQueue, undefined);\n }\n return preInitial;\n }\n\n /**\n * Returns the initial `State` instance, with reference to `self` as an\n * `ActorRef`.\n */\n getInitialSnapshot(actorScope, input) {\n const initEvent = createInitEvent(input); // TODO: fix;\n const internalQueue = [];\n const preInitialState = this._getPreInitialState(actorScope, initEvent, internalQueue);\n const [nextState] = initialMicrostep(this.root, preInitialState, actorScope, initEvent, internalQueue);\n const {\n snapshot: macroState\n } = macrostep(nextState, initEvent, actorScope, internalQueue);\n return macroState;\n }\n start(snapshot) {\n Object.values(snapshot.children).forEach(child => {\n if (child.getSnapshot().status === 'active') {\n child.start();\n }\n });\n }\n getStateNodeById(stateId) {\n const fullPath = toStatePath(stateId);\n const relativePath = fullPath.slice(1);\n const resolvedStateId = isStateId(fullPath[0]) ? fullPath[0].slice(STATE_IDENTIFIER.length) : fullPath[0];\n const stateNode = this.idMap.get(resolvedStateId);\n if (!stateNode) {\n throw new Error(`Child state node '#${resolvedStateId}' does not exist on machine '${this.id}'`);\n }\n return getStateNodeByPath(stateNode, relativePath);\n }\n get definition() {\n return this.root.definition;\n }\n toJSON() {\n return this.definition;\n }\n getPersistedSnapshot(snapshot, options) {\n return getPersistedSnapshot(snapshot, options);\n }\n restoreSnapshot(snapshot, _actorScope) {\n const children = {};\n const snapshotChildren = snapshot.children;\n Object.keys(snapshotChildren).forEach(actorId => {\n const actorData = snapshotChildren[actorId];\n const childState = actorData.snapshot;\n const src = actorData.src;\n const logic = typeof src === 'string' ? resolveReferencedActor(this, src) : src;\n if (!logic) {\n return;\n }\n const actorRef = createActor(logic, {\n id: actorId,\n parent: _actorScope.self,\n syncSnapshot: actorData.syncSnapshot,\n snapshot: childState,\n src,\n systemId: actorData.systemId\n });\n children[actorId] = actorRef;\n });\n function resolveHistoryReferencedState(root, referenced) {\n if (referenced instanceof StateNode) {\n return referenced;\n }\n try {\n return root.machine.getStateNodeById(referenced.id);\n } catch {\n }\n }\n function reviveHistoryValue(root, historyValue) {\n if (!historyValue || typeof historyValue !== 'object') {\n return {};\n }\n const revived = {};\n for (const key in historyValue) {\n const arr = historyValue[key];\n for (const item of arr) {\n const resolved = resolveHistoryReferencedState(root, item);\n if (!resolved) {\n continue;\n }\n revived[key] ??= [];\n revived[key].push(resolved);\n }\n }\n return revived;\n }\n const revivedHistoryValue = reviveHistoryValue(this.root, snapshot.historyValue);\n const restoredSnapshot = createMachineSnapshot({\n ...snapshot,\n children,\n _nodes: Array.from(getAllStateNodes(getStateNodes(this.root, snapshot.value))),\n historyValue: revivedHistoryValue\n }, this);\n const seen = new Set();\n function reviveContext(contextPart, children) {\n if (seen.has(contextPart)) {\n return;\n }\n seen.add(contextPart);\n for (const key in contextPart) {\n const value = contextPart[key];\n if (value && typeof value === 'object') {\n if ('xstate$$type' in value && value.xstate$$type === $$ACTOR_TYPE) {\n contextPart[key] = children[value.id];\n continue;\n }\n reviveContext(value, children);\n }\n }\n }\n reviveContext(restoredSnapshot.context, children);\n return restoredSnapshot;\n }\n}\n\nexport { StateMachine as S, StateNode as a };\n","import { W as XSTATE_ERROR, Y as createErrorActorEvent, D as evaluateGuard, a as cancel, r as raise, b as spawnChild, s as stopChild } from './raise-34c45204.esm.js';\nimport { a as assign } from './assign-5f7ff891.esm.js';\n\nfunction resolveEmit(_, snapshot, args, actionParams, {\n event: eventOrExpr\n}) {\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n return [snapshot, {\n event: resolvedEvent\n }, undefined];\n}\nfunction executeEmit(actorScope, {\n event\n}) {\n actorScope.defer(() => actorScope.emit(event));\n}\n/**\n * Emits an event to event handlers registered on the actor via `actor.on(event,\n * handler)`.\n *\n * @example\n *\n * ```ts\n * import { emit } from 'xstate';\n *\n * const machine = createMachine({\n * // ...\n * on: {\n * something: {\n * actions: emit({\n * type: 'emitted',\n * some: 'data'\n * })\n * }\n * }\n * // ...\n * });\n *\n * const actor = createActor(machine).start();\n *\n * actor.on('emitted', (event) => {\n * console.log(event);\n * });\n *\n * actor.send({ type: 'something' });\n * // logs:\n * // {\n * // type: 'emitted',\n * // some: 'data'\n * // }\n * ```\n */\nfunction emit(/** The event to emit, or an expression that returns an event to emit. */\neventOrExpr) {\n function emit(_args, _params) {\n }\n emit.type = 'xstate.emit';\n emit.event = eventOrExpr;\n emit.resolve = resolveEmit;\n emit.execute = executeEmit;\n return emit;\n}\n\n// this is needed to make JSDoc `@link` work properly\n\n/**\n * @remarks\n * `T | unknown` reduces to `unknown` and that can be problematic when it comes\n * to contextual typing. It especially is a problem when the union has a\n * function member, like here:\n *\n * ```ts\n * declare function test(\n * cbOrVal: ((arg: number) => unknown) | unknown\n * ): void;\n * test((arg) => {}); // oops, implicit any\n * ```\n *\n * This type can be used to avoid this problem. This union represents the same\n * value space as `unknown`.\n */\n\n// https://github.com/microsoft/TypeScript/issues/23182#issuecomment-379091887\n\n// @TODO: we can't use native `NoInfer` as we need those:\n// https://github.com/microsoft/TypeScript/pull/61092\n// https://github.com/microsoft/TypeScript/pull/61077\n// but even with those fixes native NoInfer still doesn't work - further issues have to be reproduced and fixed\n\n/** @deprecated Use the built-in `NoInfer` type instead */\n\n/** The full definition of an event, with a string `type`. */\n\n/**\n * The string or object representing the state value relative to the parent\n * state node.\n *\n * @remarks\n * - For a child atomic state node, this is a string, e.g., `\"pending\"`.\n * - For complex state nodes, this is an object, e.g., `{ success:\n * \"someChildState\" }`.\n */\n\n/** @deprecated Use `AnyMachineSnapshot` instead */\n\n// TODO: possibly refactor this somehow, use even a simpler type, and maybe even make `machine.options` private or something\n/** @ignore */\n\nlet SpecialTargets = /*#__PURE__*/function (SpecialTargets) {\n SpecialTargets[\"Parent\"] = \"#_parent\";\n SpecialTargets[\"Internal\"] = \"#_internal\";\n return SpecialTargets;\n}({});\n\n/** @deprecated Use `AnyActor` instead. */\n\n// Based on RxJS types\n\n// TODO: in v6, this should only accept AnyActorLogic, like ActorRefFromLogic\n\n/** @deprecated Use `Actor<T>` instead. */\n\n/**\n * Represents logic which can be used by an actor.\n *\n * @template TSnapshot - The type of the snapshot.\n * @template TEvent - The type of the event object.\n * @template TInput - The type of the input.\n * @template TSystem - The type of the actor system.\n */\n\n/** @deprecated */\n\n// TODO: cover all that can be actually returned\n\nfunction resolveSendTo(actorScope, snapshot, args, actionParams, {\n to,\n event: eventOrExpr,\n id,\n delay\n}, extra) {\n const delaysMap = snapshot.machine.implementations.delays;\n if (typeof eventOrExpr === 'string') {\n throw new Error(\n // eslint-disable-next-line @typescript-eslint/restrict-template-expressions\n `Only event objects may be used with sendTo; use sendTo({ type: \"${eventOrExpr}\" }) instead`);\n }\n const resolvedEvent = typeof eventOrExpr === 'function' ? eventOrExpr(args, actionParams) : eventOrExpr;\n let resolvedDelay;\n if (typeof delay === 'string') {\n const configDelay = delaysMap && delaysMap[delay];\n resolvedDelay = typeof configDelay === 'function' ? configDelay(args, actionParams) : configDelay;\n } else {\n resolvedDelay = typeof delay === 'function' ? delay(args, actionParams) : delay;\n }\n const resolvedTarget = typeof to === 'function' ? to(args, actionParams) : to;\n let targetActorRef;\n if (typeof resolvedTarget === 'string') {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n if (resolvedTarget === SpecialTargets.Parent) {\n targetActorRef = actorScope.self._parent;\n }\n // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison\n else if (resolvedTarget === SpecialTargets.Internal) {\n targetActorRef = actorScope.self;\n } else if (resolvedTarget.startsWith('#_')) {\n // SCXML compatibility: https://www.w3.org/TR/scxml/#SCXMLEventProcessor\n // #_invokeid. If the target is the special term '#_invokeid', where invokeid is the invokeid of an SCXML session that the sending session has created by <invoke>, the Processor must add the event to the external queue of that session.\n targetActorRef = snapshot.children[resolvedTarget.slice(2)];\n } else {\n targetActorRef = extra.deferredActorIds?.includes(resolvedTarget) ? resolvedTarget : snapshot.children[resolvedTarget];\n }\n if (!targetActorRef) {\n throw new Error(`Unable to send event to actor '${resolvedTarget}' from machine '${snapshot.machine.id}'.`);\n }\n } else {\n targetActorRef = resolvedTarget || actorScope.self;\n }\n return [snapshot, {\n to: targetActorRef,\n targetId: typeof resolvedTarget === 'string' ? resolvedTarget : undefined,\n event: resolvedEvent,\n id,\n delay: resolvedDelay\n }, undefined];\n}\nfunction retryResolveSendTo(_, snapshot, params) {\n if (typeof params.to === 'string') {\n params.to = snapshot.children[params.to];\n }\n}\nfunction executeSendTo(actorScope, params) {\n // this forms an outgoing events queue\n // thanks to that the recipient actors are able to read the *updated* snapshot value of the sender\n actorScope.defer(() => {\n const {\n to,\n event,\n delay,\n id\n } = params;\n if (typeof delay === 'number') {\n actorScope.system.scheduler.schedule(actorScope.self, to, event, delay, id);\n return;\n }\n actorScope.system._relay(actorScope.self,\n // at this point, in a deferred task, it should already be mutated by retryResolveSendTo\n // if it initially started as a string\n to, event.type === XSTATE_ERROR ? createErrorActorEvent(actorScope.self.id, event.data) : event);\n });\n}\n/**\n * Sends an event to an actor.\n *\n * @param actor The `ActorRef` to send the event to.\n * @param event The event to send, or an expression that evaluates to the event\n * to send\n * @param options Send action options\n *\n * - `id` - The unique send event identifier (used with `cancel()`).\n * - `delay` - The number of milliseconds to delay the sending of the event.\n */\nfunction sendTo(to, eventOrExpr, options) {\n function sendTo(_args, _params) {\n }\n sendTo.type = 'xstate.sendTo';\n sendTo.to = to;\n sendTo.event = eventOrExpr;\n sendTo.id = options?.id;\n sendTo.delay = options?.delay;\n sendTo.resolve = resolveSendTo;\n sendTo.retryResolve = retryResolveSendTo;\n sendTo.execute = executeSendTo;\n return sendTo;\n}\n\n/**\n * Sends an event to this machine's parent.\n *\n * @param event The event to send to the parent machine.\n * @param options Options to pass into the send event.\n */\nfunction sendParent(event, options) {\n return sendTo(SpecialTargets.Parent, event, options);\n}\n/**\n * Forwards (sends) an event to the `target` actor.\n *\n * @param target The target actor to forward the event to.\n * @param options Options to pass into the send action creator.\n */\nfunction forwardTo(target, options) {\n return sendTo(target, ({\n event\n }) => event, options);\n}\n\nfunction resolveEnqueueActions(actorScope, snapshot, args, actionParams, {\n collect\n}) {\n const actions = [];\n const enqueue = function enqueue(action) {\n actions.push(action);\n };\n enqueue.assign = (...args) => {\n actions.push(assign(...args));\n };\n enqueue.cancel = (...args) => {\n actions.push(cancel(...args));\n };\n enqueue.raise = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay`\n actions.push(raise(...args));\n };\n enqueue.sendTo = (...args) => {\n // for some reason it fails to infer `TDelay` from `...args` here and picks its default (`never`)\n // then it fails to typecheck that because `...args` use `string` in place of `TDelay\n actions.push(sendTo(...args));\n };\n enqueue.sendParent = (...args) => {\n actions.push(sendParent(...args));\n };\n enqueue.spawnChild = (...args) => {\n actions.push(spawnChild(...args));\n };\n enqueue.stopChild = (...args) => {\n actions.push(stopChild(...args));\n };\n enqueue.emit = (...args) => {\n actions.push(emit(...args));\n };\n collect({\n context: args.context,\n event: args.event,\n enqueue,\n check: guard => evaluateGuard(guard, snapshot.context, args.event, snapshot),\n self: actorScope.self,\n system: actorScope.system\n }, actionParams);\n return [snapshot, undefined, actions];\n}\n/**\n * Creates an action object that will execute actions that are queued by the\n * `enqueue(action)` function.\n *\n * @example\n *\n * ```ts\n * import { createMachine, enqueueActions } from 'xstate';\n *\n * const machine = createMachine({\n * entry: enqueueActions(({ enqueue, check }) => {\n * enqueue.assign({ count: 0 });\n *\n * if (check('someGuard')) {\n * enqueue.assign({ count: 1 });\n * }\n *\n * enqueue('someAction');\n * })\n * });\n * ```\n */\nfunction enqueueActions(collect) {\n function enqueueActions(_args, _params) {\n }\n enqueueActions.type = 'xstate.enqueueActions';\n enqueueActions.collect = collect;\n enqueueActions.resolve = resolveEnqueueActions;\n return enqueueActions;\n}\n\nfunction resolveLog(_, snapshot, actionArgs, actionParams, {\n value,\n label\n}) {\n return [snapshot, {\n value: typeof value === 'function' ? value(actionArgs, actionParams) : value,\n label\n }, undefined];\n}\nfunction executeLog({\n logger\n}, {\n value,\n label\n}) {\n if (label) {\n logger(label, value);\n } else {\n logger(value);\n }\n}\n/**\n * @param expr The expression function to evaluate which will be logged. Takes\n * in 2 arguments:\n *\n * - `ctx` - the current state context\n * - `event` - the event that caused this action to be executed.\n *\n * @param label The label to give to the logged expression.\n */\nfunction log(value = ({\n context,\n event\n}) => ({\n context,\n event\n}), label) {\n function log(_args, _params) {\n }\n log.type = 'xstate.log';\n log.value = value;\n log.label = label;\n log.resolve = resolveLog;\n log.execute = executeLog;\n return log;\n}\n\nexport { SpecialTargets as S, emit as a, sendParent as b, enqueueActions as e, forwardTo as f, log as l, sendTo as s };\n","export { createEmptyActor, fromCallback, fromEventObservable, fromObservable, fromPromise, fromTransition } from '../actors/dist/xstate-actors.esm.js';\nimport { m as matchesEventDescriptor, t as toArray, c as createActor, r as raise, a as cancel, s as stopChild, b as spawnChild, d as macrostep, e as createInitEvent, i as initialMicrostep, f as isAtomicStateNode, g as getProperAncestors } from './raise-34c45204.esm.js';\nexport { A as Actor, q as __unsafe_getAllOwnEventDescriptors, j as and, a as cancel, c as createActor, p as getStateNodes, h as interpret, l as isMachineSnapshot, u as matchesState, n as not, o as or, v as pathToStateValue, r as raise, b as spawnChild, k as stateIn, x as stop, s as stopChild, w as toObserver } from './raise-34c45204.esm.js';\nimport { S as StateMachine } from './StateMachine-9ef88566.esm.js';\nexport { S as StateMachine, a as StateNode } from './StateMachine-9ef88566.esm.js';\nimport { a as assign } from './assign-5f7ff891.esm.js';\nexport { a as assign } from './assign-5f7ff891.esm.js';\nimport { s as sendTo, l as log, e as enqueueActions, a as emit } from './log-1324d455.esm.js';\nexport { S as SpecialTargets, a as emit, e as enqueueActions, f as forwardTo, l as log, b as sendParent, s as sendTo } from './log-1324d455.esm.js';\nimport '../dev/dist/xstate-dev.esm.js';\n\n/**\n * Asserts that the given event object is of the specified type or types. Throws\n * an error if the event object is not of the specified types.\n *\n * @example\n *\n * ```ts\n * // ...\n * entry: ({ event }) => {\n * assertEvent(event, 'doNothing');\n * // event is { type: 'doNothing' }\n * },\n * // ...\n * exit: ({ event }) => {\n * assertEvent(event, 'greet');\n * // event is { type: 'greet'; message: string }\n *\n * assertEvent(event, ['greet', 'notify']);\n * // event is { type: 'greet'; message: string }\n * // or { type: 'notify'; message: string; level: 'info' | 'error' }\n * },\n * ```\n */\nfunction assertEvent(event, type) {\n const types = toArray(type);\n const matches = types.some(descriptor => matchesEventDescriptor(event.type, descriptor));\n if (!matches) {\n const typesText = types.length === 1 ? `type matching \"${types[0]}\"` : `one of types matching \"${types.join('\", \"')}\"`;\n throw new Error(`Expected event ${JSON.stringify(event)} to have ${typesText}`);\n }\n}\n\n/**\n * Creates a state machine (statechart) with the given configuration.\n *\n * The state machine represents the pure logic of a state machine actor.\n *\n * @example\n *\n * ```ts\n * import { createMachine } from 'xstate';\n *\n * const lightMachine = createMachine({\n * id: 'light',\n * initial: 'green',\n * states: {\n * green: {\n * on: {\n * TIMER: { target: 'yellow' }\n * }\n * },\n * yellow: {\n * on: {\n * TIMER: { target: 'red' }\n * }\n * },\n * red: {\n * on: {\n * TIMER: { target: 'green' }\n * }\n * }\n * }\n * });\n *\n * const lightActor = createActor(lightMachine);\n * lightActor.start();\n *\n * lightActor.send({ type: 'TIMER' });\n * ```\n *\n * @param config The state machine configuration.\n * @param options DEPRECATED: use `setup({ ... })` or `machine.provide({ ... })`\n * to provide machine implementations instead.\n */\nfunction createMachine(config, implementations) {\n return new StateMachine(config, implementations);\n}\n\n/** @internal */\nfunction createInertActorScope(actorLogic) {\n const self = createActor(actorLogic);\n const inertActorScope = {\n self,\n defer: () => {},\n id: '',\n logger: () => {},\n sessionId: '',\n stopChild: () => {},\n system: self.system,\n emit: () => {},\n actionExecutor: () => {}\n };\n return inertActorScope;\n}\n\n/** @deprecated Use `initialTransition(…)` instead. */\nfunction getInitialSnapshot(actorLogic, ...[input]) {\n const actorScope = createInertActorScope(actorLogic);\n return actorLogic.getInitialSnapshot(actorScope, input);\n}\n\n/**\n * Determines the next snapshot for the given `actorLogic` based on the given\n * `snapshot` and `event`.\n *\n * If the `snapshot` is `undefined`, the initial snapshot of the `actorLogic` is\n * used.\n *\n * @deprecated Use `transition(…)` instead.\n * @example\n *\n * ```ts\n * import { getNextSnapshot } from 'xstate';\n * import { trafficLightMachine } from './trafficLightMachine.ts';\n *\n * const nextSnapshot = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * undefined, // snapshot (or initial state if undefined)\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot.value);\n * // => 'yellow'\n *\n * const nextSnapshot2 = getNextSnapshot(\n * trafficLightMachine, // actor logic\n * nextSnapshot, // snapshot\n * { type: 'TIMER' }\n * ); // event object\n *\n * console.log(nextSnapshot2.value);\n * // =>'red'\n * ```\n */\nfunction getNextSnapshot(actorLogic, snapshot, event) {\n const inertActorScope = createInertActorScope(actorLogic);\n inertActorScope.self._snapshot = snapshot;\n return actorLogic.transition(snapshot, event, inertActorScope);\n}\n\n// at the moment we allow extra actors - ones that are not specified by `children`\n// this could be reconsidered in the future\n\n// used to keep only StateSchema relevant keys\n// this helps with type serialization as it makes the inferred type much shorter when dealing with huge configs\n\nfunction setup({\n schemas,\n actors,\n actions,\n guards,\n delays\n}) {\n return {\n assign,\n sendTo,\n raise,\n log,\n cancel,\n stopChild,\n enqueueActions,\n emit,\n spawnChild,\n createStateConfig: config => config,\n createAction: fn => fn,\n createMachine: config => createMachine({\n ...config,\n schemas\n }, {\n actors,\n actions,\n guards,\n delays\n }),\n extend: extended => setup({\n schemas,\n actors,\n actions: {\n ...actions,\n ...extended.actions\n },\n guards: {\n ...guards,\n ...extended.guards\n },\n delays: {\n ...delays,\n ...extended.delays\n }\n })\n };\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\n\n// eslint-disable-next-line @typescript-eslint/no-unsafe-declaration-merging\nclass SimulatedClock {\n constructor() {\n this.timeouts = new Map();\n this._now = 0;\n this._id = 0;\n this._flushing = false;\n this._flushingInvalidated = false;\n }\n now() {\n return this._now;\n }\n getId() {\n return this._id++;\n }\n setTimeout(fn, timeout) {\n this._flushingInvalidated = this._flushing;\n const id = this.getId();\n this.timeouts.set(id, {\n start: this.now(),\n timeout,\n fn\n });\n return id;\n }\n clearTimeout(id) {\n this._flushingInvalidated = this._flushing;\n this.timeouts.delete(id);\n }\n set(time) {\n if (this._now > time) {\n throw new Error('Unable to travel back in time');\n }\n this._now = time;\n this.flushTimeouts();\n }\n flushTimeouts() {\n if (this._flushing) {\n this._flushingInvalidated = true;\n return;\n }\n this._flushing = true;\n const sorted = [...this.timeouts].sort(([_idA, timeoutA], [_idB, timeoutB]) => {\n const endA = timeoutA.start + timeoutA.timeout;\n const endB = timeoutB.start + timeoutB.timeout;\n return endB > endA ? -1 : 1;\n });\n for (const [id, timeout] of sorted) {\n if (this._flushingInvalidated) {\n this._flushingInvalidated = false;\n this._flushing = false;\n this.flushTimeouts();\n return;\n }\n if (this.now() - timeout.start >= timeout.timeout) {\n this.timeouts.delete(id);\n timeout.fn.call(null);\n }\n }\n this._flushing = false;\n }\n increment(ms) {\n this._now += ms;\n this.flushTimeouts();\n }\n}\n\n/**\n * Returns a promise that resolves to the `output` of the actor when it is done.\n *\n * @example\n *\n * ```ts\n * const machine = createMachine({\n * // ...\n * output: {\n * count: 42\n * }\n * });\n *\n * const actor = createActor(machine);\n *\n * actor.start();\n *\n * const output = await toPromise(actor);\n *\n * console.log(output);\n * // logs { count: 42 }\n * ```\n */\nfunction toPromise(actor) {\n return new Promise((resolve, reject) => {\n actor.subscribe({\n complete: () => {\n resolve(actor.getSnapshot().output);\n },\n error: reject\n });\n });\n}\n\n/**\n * Given actor `logic`, a `snapshot`, and an `event`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute.\n *\n * This is a pure function that does not execute `actions`.\n */\nfunction transition(logic, snapshot, event) {\n const executableActions = [];\n const actorScope = createInertActorScope(logic);\n actorScope.actionExecutor = action => {\n executableActions.push(action);\n };\n const nextSnapshot = logic.transition(snapshot, event, actorScope);\n return [nextSnapshot, executableActions];\n}\n\n/**\n * Given actor `logic` and optional `input`, returns a tuple of the\n * `nextSnapshot` and `actions` to execute from the initial transition (no\n * previous state).\n *\n * This is a pure function that does not execute `actions`.\n */\nfunction initialTransition(logic, ...[input]) {\n const executableActions = [];\n const actorScope = createInertActorScope(logic);\n actorScope.actionExecutor = action => {\n executableActions.push(action);\n };\n const nextSnapshot = logic.getInitialSnapshot(actorScope, input);\n return [nextSnapshot, executableActions];\n}\n\n/**\n * Given a state `machine`, a `snapshot`, and an `event`, returns an array of\n * microsteps, where each microstep is a tuple of `[snapshot, actions]`.\n *\n * This is a pure function that does not execute `actions`.\n */\nfunction getMicrosteps(machine, snapshot, event) {\n const actorScope = createInertActorScope(machine);\n const {\n microsteps\n } = macrostep(snapshot, event, actorScope, []);\n return microsteps;\n}\n\n/**\n * Given a state `machine` and optional `input`, returns an array of microsteps\n * from the initial transition, where each microstep is a tuple of `[snapshot,\n * actions]`.\n *\n * This is a pure function that does not execute `actions`.\n */\nfunction getInitialMicrosteps(machine, ...[input]) {\n const actorScope = createInertActorScope(machine);\n const initEvent = createInitEvent(input);\n const internalQueue = [];\n const preInitialSnapshot = machine._getPreInitialState(actorScope, initEvent, internalQueue);\n const first = initialMicrostep(machine.root, preInitialSnapshot, actorScope, initEvent, internalQueue);\n const {\n microsteps\n } = macrostep(first[0], initEvent, actorScope, internalQueue);\n return [first, ...microsteps];\n}\n\n/**\n * Gets all potential next transitions from the current state.\n *\n * Returns all transitions that are available from the current state, including:\n *\n * - All transitions from atomic states (leaf states in the current state\n * configuration)\n * - All transitions from ancestor states (parent states that may handle events)\n * - All guarded transitions (regardless of whether their guards would pass)\n * - Always (eventless) transitions\n * - After (delayed) transitions\n *\n * The order of transitions is deterministic:\n *\n * 1. Atomic states are processed in document order\n * 2. For each atomic state, transitions are collected from the state itself first,\n * then its ancestors\n * 3. Within each state node, transitions are in the order they appear in the state\n * definition\n *\n * @param state - The current machine snapshot\n * @returns Array of transition definitions from the current state, in\n * deterministic order\n */\nfunction getNextTransitions(state) {\n const potentialTransitions = [];\n const atomicStates = state._nodes.filter(isAtomicStateNode);\n const visited = new Set();\n\n // Collect all transitions from atomic states and their ancestors\n // Process atomic states in document order (as they appear in state._nodes)\n for (const stateNode of atomicStates) {\n // For each atomic state, process the state itself first, then its ancestors\n // This ensures child state transitions come before parent state transitions\n for (const s of [stateNode].concat(getProperAncestors(stateNode, undefined))) {\n if (visited.has(s.id)) {\n continue;\n }\n visited.add(s.id);\n\n // Get all transitions for each event type\n // Include ALL transitions, even if the same event type appears in multiple state nodes\n // This is important for guarded transitions - all are \"potential\" regardless of guard evaluation\n for (const [, transitions] of s.transitions) {\n potentialTransitions.push(...transitions);\n }\n\n // Also include always (eventless) transitions\n if (s.always) {\n potentialTransitions.push(...s.always);\n }\n }\n }\n return potentialTransitions;\n}\n\nconst defaultWaitForOptions = {\n timeout: Infinity // much more than 10 seconds\n};\n\n/**\n * Subscribes to an actor ref and waits for its emitted value to satisfy a\n * predicate, and then resolves with that value. Will throw if the desired state\n * is not reached after an optional timeout. (defaults to Infinity).\n *\n * @example\n *\n * ```js\n * const state = await waitFor(someService, (state) => {\n * return state.hasTag('loaded');\n * });\n *\n * state.hasTag('loaded'); // true\n * ```\n *\n * @param actorRef The actor ref to subscribe to\n * @param predicate Determines if a value matches the condition to wait for\n * @param options\n * @returns A promise that eventually resolves to the emitted value that matches\n * the condition\n */\nfunction waitFor(actorRef, predicate, options) {\n const resolvedOptions = {\n ...defaultWaitForOptions,\n ...options\n };\n return new Promise((res, rej) => {\n const {\n signal\n } = resolvedOptions;\n if (signal?.aborted) {\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n rej(signal.reason);\n return;\n }\n let done = false;\n const handle = resolvedOptions.timeout === Infinity ? undefined : setTimeout(() => {\n dispose();\n rej(new Error(`Timeout of ${resolvedOptions.timeout} ms exceeded`));\n }, resolvedOptions.timeout);\n const dispose = () => {\n clearTimeout(handle);\n done = true;\n sub?.unsubscribe();\n if (abortListener) {\n signal.removeEventListener('abort', abortListener);\n }\n };\n function checkEmitted(emitted) {\n if (predicate(emitted)) {\n dispose();\n res(emitted);\n }\n }\n\n /**\n * If the `signal` option is provided, this will be the listener for its\n * `abort` event\n */\n let abortListener;\n // eslint-disable-next-line prefer-const\n let sub; // avoid TDZ when disposing synchronously\n\n // See if the current snapshot already matches the predicate\n checkEmitted(actorRef.getSnapshot());\n if (done) {\n return;\n }\n\n // only define the `abortListener` if the `signal` option is provided\n if (signal) {\n abortListener = () => {\n dispose();\n // XState does not \"own\" the signal, so we should reject with its reason (if any)\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n rej(signal.reason);\n };\n signal.addEventListener('abort', abortListener);\n }\n sub = actorRef.subscribe({\n next: checkEmitted,\n error: err => {\n dispose();\n // eslint-disable-next-line @typescript-eslint/prefer-promise-reject-errors\n rej(err);\n },\n complete: () => {\n dispose();\n rej(new Error(`Actor terminated without satisfying predicate`));\n }\n });\n if (done) {\n sub.unsubscribe();\n }\n });\n}\n\nexport { SimulatedClock, assertEvent, createMachine, getInitialMicrosteps, getInitialSnapshot, getMicrosteps, getNextSnapshot, getNextTransitions, initialTransition, setup, toPromise, transition, waitFor };\n","import {\n prepareEvent,\n prepareContractCall,\n readContract,\n type BaseTransactionOptions,\n type AbiParameterToPrimitiveType,\n} from \"thirdweb\";\n\n/**\n* Contract events\n*/\n\n\n\n/**\n * Creates an event object for the CreatedAttestation event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { createdAttestationEvent } from \"TODO\";\n *\n * const events = await getContractEvents({\n * contract,\n * events: [\n * createdAttestationEvent()\n * ],\n * });\n * ```\n */\nexport function createdAttestationEvent() {\n return prepareEvent({\n signature: \"event CreatedAttestation((bytes32 schemaUid, bytes32 attestationUid) result)\",\n });\n};\n \n\n/**\n * Represents the filters for the \"ModuleInitialized\" event.\n */\nexport type ModuleInitializedEventFilters = Partial<{\n account: AbiParameterToPrimitiveType<{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}>\neas: AbiParameterToPrimitiveType<{\"indexed\":true,\"internalType\":\"address\",\"name\":\"eas\",\"type\":\"address\"}>\n}>;\n\n/**\n * Creates an event object for the ModuleInitialized event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { moduleInitializedEvent } from \"TODO\";\n *\n * const events = await getContractEvents({\n * contract,\n * events: [\n * moduleInitializedEvent({\n * account: ...,\n * eas: ...,\n * })\n * ],\n * });\n * ```\n */\nexport function moduleInitializedEvent(filters: ModuleInitializedEventFilters = {}) {\n return prepareEvent({\n signature: \"event ModuleInitialized(address indexed account, address indexed eas)\",\n filters,\n });\n};\n \n\n/**\n * Represents the filters for the \"ModuleUninitialized\" event.\n */\nexport type ModuleUninitializedEventFilters = Partial<{\n account: AbiParameterToPrimitiveType<{\"indexed\":true,\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}>\n}>;\n\n/**\n * Creates an event object for the ModuleUninitialized event.\n * @param filters - Optional filters to apply to the event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { moduleUninitializedEvent } from \"TODO\";\n *\n * const events = await getContractEvents({\n * contract,\n * events: [\n * moduleUninitializedEvent({\n * account: ...,\n * })\n * ],\n * });\n * ```\n */\nexport function moduleUninitializedEvent(filters: ModuleUninitializedEventFilters = {}) {\n return prepareEvent({\n signature: \"event ModuleUninitialized(address indexed account)\",\n filters,\n });\n};\n \n\n\n\n/**\n * Creates an event object for the SeedPublished event.\n * @returns The prepared event object.\n * @example\n * ```\n * import { getContractEvents } from \"thirdweb\";\n * import { seedPublishedEvent } from \"TODO\";\n *\n * const events = await getContractEvents({\n * contract,\n * events: [\n * seedPublishedEvent()\n * ],\n * });\n * ```\n */\nexport function seedPublishedEvent() {\n return prepareEvent({\n signature: \"event SeedPublished(bytes32 seedUid, bytes32 versionUid)\",\n });\n};\n \n\n/**\n* Contract read functions\n*/\n\n/**\n * Represents the parameters for the \"getEAS\" function.\n */\nexport type GetEASParams = {\n account: AbiParameterToPrimitiveType<{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}>\n};\n\n/**\n * Calls the \"getEAS\" function on the contract.\n * @param options - The options for the getEAS function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { getEAS } from \"TODO\";\n *\n * const result = await getEAS({\n * account: ...,\n * });\n *\n * ```\n */\nexport async function getEAS(\n options: BaseTransactionOptions<GetEASParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0x7dda06c4\",\n [\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n }\n ],\n [\n {\n \"internalType\": \"address\",\n \"name\": \"\",\n \"type\": \"address\"\n }\n ]\n],\n params: [options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isInitialized\" function.\n */\nexport type IsInitializedParams = {\n account: AbiParameterToPrimitiveType<{\"internalType\":\"address\",\"name\":\"account\",\"type\":\"address\"}>\n};\n\n/**\n * Calls the \"isInitialized\" function on the contract.\n * @param options - The options for the isInitialized function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isInitialized } from \"TODO\";\n *\n * const result = await isInitialized({\n * account: ...,\n * });\n *\n * ```\n */\nexport async function isInitialized(\n options: BaseTransactionOptions<IsInitializedParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xd60b347f\",\n [\n {\n \"internalType\": \"address\",\n \"name\": \"account\",\n \"type\": \"address\"\n }\n ],\n [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.account]\n });\n};\n\n\n/**\n * Represents the parameters for the \"isModuleType\" function.\n */\nexport type IsModuleTypeParams = {\n moduleTypeId: AbiParameterToPrimitiveType<{\"internalType\":\"uint256\",\"name\":\"moduleTypeId\",\"type\":\"uint256\"}>\n};\n\n/**\n * Calls the \"isModuleType\" function on the contract.\n * @param options - The options for the isModuleType function.\n * @returns The parsed result of the function call.\n * @example\n * ```\n * import { isModuleType } from \"TODO\";\n *\n * const result = await isModuleType({\n * moduleTypeId: ...,\n * });\n *\n * ```\n */\nexport async function isModuleType(\n options: BaseTransactionOptions<IsModuleTypeParams>\n) {\n return readContract({\n contract: options.contract,\n method: [\n \"0xecd05961\",\n [\n {\n \"internalType\": \"uint256\",\n \"name\": \"moduleTypeId\",\n \"type\": \"uint256\"\n }\n ],\n [\n {\n \"internalType\": \"bool\",\n \"name\": \"\",\n \"type\": \"bool\"\n }\n ]\n],\n params: [options.moduleTypeId]\n });\n};\n\n\n/**\n* Contract write functions\n*/\n\n/**\n * Represents the parameters for the \"createSeed\" function.\n */\nexport type CreateSeedParams = {\n schemaUid: AbiParameterToPrimitiveType<{\"internalType\":\"bytes32\",\"name\":\"schemaUid\",\"type\":\"bytes32\"}>\nrevocable: AbiParameterToPrimitiveType<{\"internalType\":\"bool\",\"name\":\"revocable\",\"type\":\"bool\"}>\n};\n\n/**\n * Calls the \"createSeed\" function on the contract.\n * @param options - The options for the \"createSeed\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { createSeed } from \"TODO\";\n *\n * const transaction = createSeed({\n * schemaUid: ...,\n * revocable: ...,\n * });\n *\n * // Send the transaction\n * ...\n *\n * ```\n */\nexport function createSeed(\n options: BaseTransactionOptions<CreateSeedParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x6240d6d9\",\n [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"schemaUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"revocable\",\n \"type\": \"bool\"\n }\n ],\n [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.schemaUid, options.revocable]\n });\n};\n\n\n/**\n * Represents the parameters for the \"createVersion\" function.\n */\nexport type CreateVersionParams = {\n seedUid: AbiParameterToPrimitiveType<{\"internalType\":\"bytes32\",\"name\":\"seedUid\",\"type\":\"bytes32\"}>\nversionSchemaUid: AbiParameterToPrimitiveType<{\"internalType\":\"bytes32\",\"name\":\"versionSchemaUid\",\"type\":\"bytes32\"}>\n};\n\n/**\n * Calls the \"createVersion\" function on the contract.\n * @param options - The options for the \"createVersion\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { createVersion } from \"TODO\";\n *\n * const transaction = createVersion({\n * seedUid: ...,\n * versionSchemaUid: ...,\n * });\n *\n * // Send the transaction\n * ...\n *\n * ```\n */\nexport function createVersion(\n options: BaseTransactionOptions<CreateVersionParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x13e0c263\",\n [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"seedUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"versionSchemaUid\",\n \"type\": \"bytes32\"\n }\n ],\n [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.seedUid, options.versionSchemaUid]\n });\n};\n\n\n/**\n * Represents the parameters for the \"multiPublish\" function.\n */\nexport type MultiPublishParams = {\n requests: AbiParameterToPrimitiveType<{\"components\":[{\"internalType\":\"string\",\"name\":\"localId\",\"type\":\"string\"},{\"internalType\":\"bytes32\",\"name\":\"seedUid\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"versionUid\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"seedSchemaUid\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"versionSchemaUid\",\"type\":\"bytes32\"},{\"internalType\":\"bool\",\"name\":\"seedIsRevocable\",\"type\":\"bool\"},{\"components\":[{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"components\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint64\",\"name\":\"expirationTime\",\"type\":\"uint64\"},{\"internalType\":\"bool\",\"name\":\"revocable\",\"type\":\"bool\"},{\"internalType\":\"bytes32\",\"name\":\"refUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"internalType\":\"struct AttestationRequestData[]\",\"name\":\"data\",\"type\":\"tuple[]\"}],\"internalType\":\"struct MultiAttestationRequest[]\",\"name\":\"listOfAttestations\",\"type\":\"tuple[]\"},{\"components\":[{\"internalType\":\"uint256\",\"name\":\"publishIndex\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"propertySchemaUid\",\"type\":\"bytes32\"}],\"internalType\":\"struct PropertyToUpdateWithSeed[]\",\"name\":\"propertiesToUpdate\",\"type\":\"tuple[]\"}],\"internalType\":\"struct PublishRequestData[]\",\"name\":\"requests\",\"type\":\"tuple[]\"}>\n};\n\n/**\n * Calls the \"multiPublish\" function on the contract.\n * @param options - The options for the \"multiPublish\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { multiPublish } from \"TODO\";\n *\n * const transaction = multiPublish({\n * requests: ...,\n * });\n *\n * // Send the transaction\n * ...\n *\n * ```\n */\nexport function multiPublish(\n options: BaseTransactionOptions<MultiPublishParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x2a29fadc\",\n [\n {\n \"components\": [\n {\n \"internalType\": \"string\",\n \"name\": \"localId\",\n \"type\": \"string\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"seedUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"versionUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"seedSchemaUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"versionSchemaUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"seedIsRevocable\",\n \"type\": \"bool\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"schema\",\n \"type\": \"bytes32\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"address\",\n \"name\": \"recipient\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint64\",\n \"name\": \"expirationTime\",\n \"type\": \"uint64\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"revocable\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"refUID\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"internalType\": \"struct AttestationRequestData[]\",\n \"name\": \"data\",\n \"type\": \"tuple[]\"\n }\n ],\n \"internalType\": \"struct MultiAttestationRequest[]\",\n \"name\": \"listOfAttestations\",\n \"type\": \"tuple[]\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"publishIndex\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"propertySchemaUid\",\n \"type\": \"bytes32\"\n }\n ],\n \"internalType\": \"struct PropertyToUpdateWithSeed[]\",\n \"name\": \"propertiesToUpdate\",\n \"type\": \"tuple[]\"\n }\n ],\n \"internalType\": \"struct PublishRequestData[]\",\n \"name\": \"requests\",\n \"type\": \"tuple[]\"\n }\n ],\n [\n {\n \"internalType\": \"bytes32[]\",\n \"name\": \"\",\n \"type\": \"bytes32[]\"\n }\n ]\n],\n params: [options.requests]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onInstall\" function.\n */\nexport type OnInstallParams = {\n data: AbiParameterToPrimitiveType<{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"}>\n};\n\n/**\n * Calls the \"onInstall\" function on the contract.\n * @param options - The options for the \"onInstall\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onInstall } from \"TODO\";\n *\n * const transaction = onInstall({\n * data: ...,\n * });\n *\n * // Send the transaction\n * ...\n *\n * ```\n */\nexport function onInstall(\n options: BaseTransactionOptions<OnInstallParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x6d61fe70\",\n [\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n }\n ],\n []\n],\n params: [options.data]\n });\n};\n\n\n/**\n * Represents the parameters for the \"onUninstall\" function.\n */\nexport type OnUninstallParams = {\n arg_0: AbiParameterToPrimitiveType<{\"internalType\":\"bytes\",\"name\":\"\",\"type\":\"bytes\"}>\n};\n\n/**\n * Calls the \"onUninstall\" function on the contract.\n * @param options - The options for the \"onUninstall\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { onUninstall } from \"TODO\";\n *\n * const transaction = onUninstall({\n * arg_0: ...,\n * });\n *\n * // Send the transaction\n * ...\n *\n * ```\n */\nexport function onUninstall(\n options: BaseTransactionOptions<OnUninstallParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x8a91b0e3\",\n [\n {\n \"internalType\": \"bytes\",\n \"name\": \"\",\n \"type\": \"bytes\"\n }\n ],\n []\n],\n params: [options.arg_0]\n });\n};\n\n\n/**\n * Represents the parameters for the \"publish\" function.\n */\nexport type PublishParams = {\n request: AbiParameterToPrimitiveType<{\"components\":[{\"internalType\":\"string\",\"name\":\"localId\",\"type\":\"string\"},{\"internalType\":\"bytes32\",\"name\":\"seedUid\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"versionUid\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"seedSchemaUid\",\"type\":\"bytes32\"},{\"internalType\":\"bytes32\",\"name\":\"versionSchemaUid\",\"type\":\"bytes32\"},{\"internalType\":\"bool\",\"name\":\"seedIsRevocable\",\"type\":\"bool\"},{\"components\":[{\"internalType\":\"bytes32\",\"name\":\"schema\",\"type\":\"bytes32\"},{\"components\":[{\"internalType\":\"address\",\"name\":\"recipient\",\"type\":\"address\"},{\"internalType\":\"uint64\",\"name\":\"expirationTime\",\"type\":\"uint64\"},{\"internalType\":\"bool\",\"name\":\"revocable\",\"type\":\"bool\"},{\"internalType\":\"bytes32\",\"name\":\"refUID\",\"type\":\"bytes32\"},{\"internalType\":\"bytes\",\"name\":\"data\",\"type\":\"bytes\"},{\"internalType\":\"uint256\",\"name\":\"value\",\"type\":\"uint256\"}],\"internalType\":\"struct AttestationRequestData[]\",\"name\":\"data\",\"type\":\"tuple[]\"}],\"internalType\":\"struct MultiAttestationRequest[]\",\"name\":\"listOfAttestations\",\"type\":\"tuple[]\"},{\"components\":[{\"internalType\":\"uint256\",\"name\":\"publishIndex\",\"type\":\"uint256\"},{\"internalType\":\"bytes32\",\"name\":\"propertySchemaUid\",\"type\":\"bytes32\"}],\"internalType\":\"struct PropertyToUpdateWithSeed[]\",\"name\":\"propertiesToUpdate\",\"type\":\"tuple[]\"}],\"internalType\":\"struct PublishRequestData\",\"name\":\"request\",\"type\":\"tuple\"}>\n};\n\n/**\n * Calls the \"publish\" function on the contract.\n * @param options - The options for the \"publish\" function.\n * @returns A prepared transaction object.\n * @example\n * ```\n * import { publish } from \"TODO\";\n *\n * const transaction = publish({\n * request: ...,\n * });\n *\n * // Send the transaction\n * ...\n *\n * ```\n */\nexport function publish(\n options: BaseTransactionOptions<PublishParams>\n) {\n return prepareContractCall({\n contract: options.contract,\n method: [\n \"0x801d5ac9\",\n [\n {\n \"components\": [\n {\n \"internalType\": \"string\",\n \"name\": \"localId\",\n \"type\": \"string\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"seedUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"versionUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"seedSchemaUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"versionSchemaUid\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"seedIsRevocable\",\n \"type\": \"bool\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"schema\",\n \"type\": \"bytes32\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"address\",\n \"name\": \"recipient\",\n \"type\": \"address\"\n },\n {\n \"internalType\": \"uint64\",\n \"name\": \"expirationTime\",\n \"type\": \"uint64\"\n },\n {\n \"internalType\": \"bool\",\n \"name\": \"revocable\",\n \"type\": \"bool\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"refUID\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes\",\n \"name\": \"data\",\n \"type\": \"bytes\"\n },\n {\n \"internalType\": \"uint256\",\n \"name\": \"value\",\n \"type\": \"uint256\"\n }\n ],\n \"internalType\": \"struct AttestationRequestData[]\",\n \"name\": \"data\",\n \"type\": \"tuple[]\"\n }\n ],\n \"internalType\": \"struct MultiAttestationRequest[]\",\n \"name\": \"listOfAttestations\",\n \"type\": \"tuple[]\"\n },\n {\n \"components\": [\n {\n \"internalType\": \"uint256\",\n \"name\": \"publishIndex\",\n \"type\": \"uint256\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"propertySchemaUid\",\n \"type\": \"bytes32\"\n }\n ],\n \"internalType\": \"struct PropertyToUpdateWithSeed[]\",\n \"name\": \"propertiesToUpdate\",\n \"type\": \"tuple[]\"\n }\n ],\n \"internalType\": \"struct PublishRequestData\",\n \"name\": \"request\",\n \"type\": \"tuple\"\n }\n ],\n [\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n },\n {\n \"internalType\": \"bytes32\",\n \"name\": \"\",\n \"type\": \"bytes32\"\n }\n ]\n],\n params: [options.request]\n });\n};\n\n\n","const ZERO_BYTES32 = '0x' + '0'.repeat(64)\n\nexport type RequestWithSeedUid = { seedUid?: string }\n\n/**\n * Assigns the first request's non-zero seedUid to the item so the SDK's\n * in-memory context is updated after a successful publish.\n */\nexport function persistSeedUidFromPublishResult(\n item: { seedUid?: string },\n normalizedRequests: RequestWithSeedUid[],\n): void {\n const firstRequestSeedUid = normalizedRequests[0]?.seedUid\n if (firstRequestSeedUid && firstRequestSeedUid !== ZERO_BYTES32) {\n ;(item as { seedUid?: string }).seedUid = firstRequestSeedUid\n }\n}\n",";(function (globalObject) {\r\n 'use strict';\r\n\r\n/*\r\n * bignumber.js v9.3.1\r\n * A JavaScript library for arbitrary-precision arithmetic.\r\n * https://github.com/MikeMcl/bignumber.js\r\n * Copyright (c) 2025 Michael Mclaughlin <M8ch88l@gmail.com>\r\n * MIT Licensed.\r\n *\r\n * BigNumber.prototype methods | BigNumber methods\r\n * |\r\n * absoluteValue abs | clone\r\n * comparedTo | config set\r\n * decimalPlaces dp | DECIMAL_PLACES\r\n * dividedBy div | ROUNDING_MODE\r\n * dividedToIntegerBy idiv | EXPONENTIAL_AT\r\n * exponentiatedBy pow | RANGE\r\n * integerValue | CRYPTO\r\n * isEqualTo eq | MODULO_MODE\r\n * isFinite | POW_PRECISION\r\n * isGreaterThan gt | FORMAT\r\n * isGreaterThanOrEqualTo gte | ALPHABET\r\n * isInteger | isBigNumber\r\n * isLessThan lt | maximum max\r\n * isLessThanOrEqualTo lte | minimum min\r\n * isNaN | random\r\n * isNegative | sum\r\n * isPositive |\r\n * isZero |\r\n * minus |\r\n * modulo mod |\r\n * multipliedBy times |\r\n * negated |\r\n * plus |\r\n * precision sd |\r\n * shiftedBy |\r\n * squareRoot sqrt |\r\n * toExponential |\r\n * toFixed |\r\n * toFormat |\r\n * toFraction |\r\n * toJSON |\r\n * toNumber |\r\n * toPrecision |\r\n * toString |\r\n * valueOf |\r\n *\r\n */\r\n\r\n\r\n var BigNumber,\r\n isNumeric = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?$/i,\r\n mathceil = Math.ceil,\r\n mathfloor = Math.floor,\r\n\r\n bignumberError = '[BigNumber Error] ',\r\n tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ',\r\n\r\n BASE = 1e14,\r\n LOG_BASE = 14,\r\n MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r\n // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r\n POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r\n SQRT_BASE = 1e7,\r\n\r\n // EDITABLE\r\n // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r\n // the arguments to toExponential, toFixed, toFormat, and toPrecision.\r\n MAX = 1E9; // 0 to MAX_INT32\r\n\r\n\r\n /*\r\n * Create and return a BigNumber constructor.\r\n */\r\n function clone(configObject) {\r\n var div, convertBase, parseNumeric,\r\n P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null },\r\n ONE = new BigNumber(1),\r\n\r\n\r\n //----------------------------- EDITABLE CONFIG DEFAULTS -------------------------------\r\n\r\n\r\n // The default values below must be integers within the inclusive ranges stated.\r\n // The values can also be changed at run-time using BigNumber.set.\r\n\r\n // The maximum number of decimal places for operations involving division.\r\n DECIMAL_PLACES = 20, // 0 to MAX\r\n\r\n // The rounding mode used when rounding to the above decimal places, and when using\r\n // toExponential, toFixed, toFormat and toPrecision, and round (default value).\r\n // UP 0 Away from zero.\r\n // DOWN 1 Towards zero.\r\n // CEIL 2 Towards +Infinity.\r\n // FLOOR 3 Towards -Infinity.\r\n // HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r\n // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r\n // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r\n // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r\n // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r\n ROUNDING_MODE = 4, // 0 to 8\r\n\r\n // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r\n\r\n // The exponent value at and beneath which toString returns exponential notation.\r\n // Number type: -7\r\n TO_EXP_NEG = -7, // 0 to -MAX\r\n\r\n // The exponent value at and above which toString returns exponential notation.\r\n // Number type: 21\r\n TO_EXP_POS = 21, // 0 to MAX\r\n\r\n // RANGE : [MIN_EXP, MAX_EXP]\r\n\r\n // The minimum exponent value, beneath which underflow to zero occurs.\r\n // Number type: -324 (5e-324)\r\n MIN_EXP = -1e7, // -1 to -MAX\r\n\r\n // The maximum exponent value, above which overflow to Infinity occurs.\r\n // Number type: 308 (1.7976931348623157e+308)\r\n // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r\n MAX_EXP = 1e7, // 1 to MAX\r\n\r\n // Whether to use cryptographically-secure random number generation, if available.\r\n CRYPTO = false, // true or false\r\n\r\n // The modulo mode used when calculating the modulus: a mod n.\r\n // The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r\n // The remainder (r) is calculated as: r = a - n * q.\r\n //\r\n // UP 0 The remainder is positive if the dividend is negative, else is negative.\r\n // DOWN 1 The remainder has the same sign as the dividend.\r\n // This modulo mode is commonly known as 'truncated division' and is\r\n // equivalent to (a % n) in JavaScript.\r\n // FLOOR 3 The remainder has the same sign as the divisor (Python %).\r\n // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r\n // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r\n // The remainder is always positive.\r\n //\r\n // The truncated division, floored division, Euclidian division and IEEE 754 remainder\r\n // modes are commonly used for the modulus operation.\r\n // Although the other rounding modes can also be used, they may not give useful results.\r\n MODULO_MODE = 1, // 0 to 9\r\n\r\n // The maximum number of significant digits of the result of the exponentiatedBy operation.\r\n // If POW_PRECISION is 0, there will be unlimited significant digits.\r\n POW_PRECISION = 0, // 0 to MAX\r\n\r\n // The format specification used by the BigNumber.prototype.toFormat method.\r\n FORMAT = {\r\n prefix: '',\r\n groupSize: 3,\r\n secondaryGroupSize: 0,\r\n groupSeparator: ',',\r\n decimalSeparator: '.',\r\n fractionGroupSize: 0,\r\n fractionGroupSeparator: '\\xA0', // non-breaking space\r\n suffix: ''\r\n },\r\n\r\n // The alphabet used for base conversion. It must be at least 2 characters long, with no '+',\r\n // '-', '.', whitespace, or repeated character.\r\n // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'\r\n ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz',\r\n alphabetHasNormalDecimalDigits = true;\r\n\r\n\r\n //------------------------------------------------------------------------------------------\r\n\r\n\r\n // CONSTRUCTOR\r\n\r\n\r\n /*\r\n * The BigNumber constructor and exported function.\r\n * Create and return a new instance of a BigNumber object.\r\n *\r\n * v {number|string|BigNumber} A numeric value.\r\n * [b] {number} The base of v. Integer, 2 to ALPHABET.length inclusive.\r\n */\r\n function BigNumber(v, b) {\r\n var alphabet, c, caseChanged, e, i, isNum, len, str,\r\n x = this;\r\n\r\n // Enable constructor call without `new`.\r\n if (!(x instanceof BigNumber)) return new BigNumber(v, b);\r\n\r\n if (b == null) {\r\n\r\n if (v && v._isBigNumber === true) {\r\n x.s = v.s;\r\n\r\n if (!v.c || v.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else if (v.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = v.e;\r\n x.c = v.c.slice();\r\n }\r\n\r\n return;\r\n }\r\n\r\n if ((isNum = typeof v == 'number') && v * 0 == 0) {\r\n\r\n // Use `1 / n` to handle minus zero also.\r\n x.s = 1 / v < 0 ? (v = -v, -1) : 1;\r\n\r\n // Fast path for integers, where n < 2147483648 (2**31).\r\n if (v === ~~v) {\r\n for (e = 0, i = v; i >= 10; i /= 10, e++);\r\n\r\n if (e > MAX_EXP) {\r\n x.c = x.e = null;\r\n } else {\r\n x.e = e;\r\n x.c = [v];\r\n }\r\n\r\n return;\r\n }\r\n\r\n str = String(v);\r\n } else {\r\n\r\n if (!isNumeric.test(str = String(v))) return parseNumeric(x, str, isNum);\r\n\r\n x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n\r\n // Exponential form?\r\n if ((i = str.search(/e/i)) > 0) {\r\n\r\n // Determine exponent.\r\n if (e < 0) e = i;\r\n e += +str.slice(i + 1);\r\n str = str.substring(0, i);\r\n } else if (e < 0) {\r\n\r\n // Integer.\r\n e = str.length;\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n\r\n // Allow exponential notation to be used with base 10 argument, while\r\n // also rounding to DECIMAL_PLACES as with other bases.\r\n if (b == 10 && alphabetHasNormalDecimalDigits) {\r\n x = new BigNumber(v);\r\n return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE);\r\n }\r\n\r\n str = String(v);\r\n\r\n if (isNum = typeof v == 'number') {\r\n\r\n // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r\n if (v * 0 != 0) return parseNumeric(x, str, isNum, b);\r\n\r\n x.s = 1 / v < 0 ? (str = str.slice(1), -1) : 1;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (BigNumber.DEBUG && str.replace(/^0\\.0*|\\./, '').length > 15) {\r\n throw Error\r\n (tooManyDigits + v);\r\n }\r\n } else {\r\n x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1;\r\n }\r\n\r\n alphabet = ALPHABET.slice(0, b);\r\n e = i = 0;\r\n\r\n // Check that str is a valid base b number.\r\n // Don't use RegExp, so alphabet can contain special characters.\r\n for (len = str.length; i < len; i++) {\r\n if (alphabet.indexOf(c = str.charAt(i)) < 0) {\r\n if (c == '.') {\r\n\r\n // If '.' is not the first character and it has not be found before.\r\n if (i > e) {\r\n e = len;\r\n continue;\r\n }\r\n } else if (!caseChanged) {\r\n\r\n // Allow e.g. hexadecimal 'FF' as well as 'ff'.\r\n if (str == str.toUpperCase() && (str = str.toLowerCase()) ||\r\n str == str.toLowerCase() && (str = str.toUpperCase())) {\r\n caseChanged = true;\r\n i = -1;\r\n e = 0;\r\n continue;\r\n }\r\n }\r\n\r\n return parseNumeric(x, String(v), isNum, b);\r\n }\r\n }\r\n\r\n // Prevent later check for length on converted number.\r\n isNum = false;\r\n str = convertBase(str, b, 10, x.s);\r\n\r\n // Decimal point?\r\n if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');\r\n else e = str.length;\r\n }\r\n\r\n // Determine leading zeros.\r\n for (i = 0; str.charCodeAt(i) === 48; i++);\r\n\r\n // Determine trailing zeros.\r\n for (len = str.length; str.charCodeAt(--len) === 48;);\r\n\r\n if (str = str.slice(i, ++len)) {\r\n len -= i;\r\n\r\n // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}'\r\n if (isNum && BigNumber.DEBUG &&\r\n len > 15 && (v > MAX_SAFE_INTEGER || v !== mathfloor(v))) {\r\n throw Error\r\n (tooManyDigits + (x.s * v));\r\n }\r\n\r\n // Overflow?\r\n if ((e = e - i - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n x.c = x.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n } else {\r\n x.e = e;\r\n x.c = [];\r\n\r\n // Transform base\r\n\r\n // e is the base 10 exponent.\r\n // i is where to slice str to get the first element of the coefficient array.\r\n i = (e + 1) % LOG_BASE;\r\n if (e < 0) i += LOG_BASE; // i < 1\r\n\r\n if (i < len) {\r\n if (i) x.c.push(+str.slice(0, i));\r\n\r\n for (len -= LOG_BASE; i < len;) {\r\n x.c.push(+str.slice(i, i += LOG_BASE));\r\n }\r\n\r\n i = LOG_BASE - (str = str.slice(i)).length;\r\n } else {\r\n i -= len;\r\n }\r\n\r\n for (; i--; str += '0');\r\n x.c.push(+str);\r\n }\r\n } else {\r\n\r\n // Zero.\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n\r\n // CONSTRUCTOR PROPERTIES\r\n\r\n\r\n BigNumber.clone = clone;\r\n\r\n BigNumber.ROUND_UP = 0;\r\n BigNumber.ROUND_DOWN = 1;\r\n BigNumber.ROUND_CEIL = 2;\r\n BigNumber.ROUND_FLOOR = 3;\r\n BigNumber.ROUND_HALF_UP = 4;\r\n BigNumber.ROUND_HALF_DOWN = 5;\r\n BigNumber.ROUND_HALF_EVEN = 6;\r\n BigNumber.ROUND_HALF_CEIL = 7;\r\n BigNumber.ROUND_HALF_FLOOR = 8;\r\n BigNumber.EUCLID = 9;\r\n\r\n\r\n /*\r\n * Configure infrequently-changing library-wide settings.\r\n *\r\n * Accept an object with the following optional properties (if the value of a property is\r\n * a number, it must be an integer within the inclusive range stated):\r\n *\r\n * DECIMAL_PLACES {number} 0 to MAX\r\n * ROUNDING_MODE {number} 0 to 8\r\n * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX]\r\n * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX]\r\n * CRYPTO {boolean} true or false\r\n * MODULO_MODE {number} 0 to 9\r\n * POW_PRECISION {number} 0 to MAX\r\n * ALPHABET {string} A string of two or more unique characters which does\r\n * not contain '.'.\r\n * FORMAT {object} An object with some of the following properties:\r\n * prefix {string}\r\n * groupSize {number}\r\n * secondaryGroupSize {number}\r\n * groupSeparator {string}\r\n * decimalSeparator {string}\r\n * fractionGroupSize {number}\r\n * fractionGroupSeparator {string}\r\n * suffix {string}\r\n *\r\n * (The values assigned to the above FORMAT object properties are not checked for validity.)\r\n *\r\n * E.g.\r\n * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r\n *\r\n * Ignore properties/parameters set to null or undefined, except for ALPHABET.\r\n *\r\n * Return an object with the properties current values.\r\n */\r\n BigNumber.config = BigNumber.set = function (obj) {\r\n var p, v;\r\n\r\n if (obj != null) {\r\n\r\n if (typeof obj == 'object') {\r\n\r\n // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n DECIMAL_PLACES = v;\r\n }\r\n\r\n // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r\n // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 8, p);\r\n ROUNDING_MODE = v;\r\n }\r\n\r\n // EXPONENTIAL_AT {number|number[]}\r\n // Integer, -MAX to MAX inclusive or\r\n // [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r\n // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, 0, p);\r\n intCheck(v[1], 0, MAX, p);\r\n TO_EXP_NEG = v[0];\r\n TO_EXP_POS = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v);\r\n }\r\n }\r\n\r\n // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r\n // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r\n // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}'\r\n if (obj.hasOwnProperty(p = 'RANGE')) {\r\n v = obj[p];\r\n if (v && v.pop) {\r\n intCheck(v[0], -MAX, -1, p);\r\n intCheck(v[1], 1, MAX, p);\r\n MIN_EXP = v[0];\r\n MAX_EXP = v[1];\r\n } else {\r\n intCheck(v, -MAX, MAX, p);\r\n if (v) {\r\n MIN_EXP = -(MAX_EXP = v < 0 ? -v : v);\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' cannot be zero: ' + v);\r\n }\r\n }\r\n }\r\n\r\n // CRYPTO {boolean} true or false.\r\n // '[BigNumber Error] CRYPTO not true or false: {v}'\r\n // '[BigNumber Error] crypto unavailable'\r\n if (obj.hasOwnProperty(p = 'CRYPTO')) {\r\n v = obj[p];\r\n if (v === !!v) {\r\n if (v) {\r\n if (typeof crypto != 'undefined' && crypto &&\r\n (crypto.getRandomValues || crypto.randomBytes)) {\r\n CRYPTO = v;\r\n } else {\r\n CRYPTO = !v;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n } else {\r\n CRYPTO = v;\r\n }\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' not true or false: ' + v);\r\n }\r\n }\r\n\r\n // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r\n // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'MODULO_MODE')) {\r\n v = obj[p];\r\n intCheck(v, 0, 9, p);\r\n MODULO_MODE = v;\r\n }\r\n\r\n // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r\n // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}'\r\n if (obj.hasOwnProperty(p = 'POW_PRECISION')) {\r\n v = obj[p];\r\n intCheck(v, 0, MAX, p);\r\n POW_PRECISION = v;\r\n }\r\n\r\n // FORMAT {object}\r\n // '[BigNumber Error] FORMAT not an object: {v}'\r\n if (obj.hasOwnProperty(p = 'FORMAT')) {\r\n v = obj[p];\r\n if (typeof v == 'object') FORMAT = v;\r\n else throw Error\r\n (bignumberError + p + ' not an object: ' + v);\r\n }\r\n\r\n // ALPHABET {string}\r\n // '[BigNumber Error] ALPHABET invalid: {v}'\r\n if (obj.hasOwnProperty(p = 'ALPHABET')) {\r\n v = obj[p];\r\n\r\n // Disallow if less than two characters,\r\n // or if it contains '+', '-', '.', whitespace, or a repeated character.\r\n if (typeof v == 'string' && !/^.?$|[+\\-.\\s]|(.).*\\1/.test(v)) {\r\n alphabetHasNormalDecimalDigits = v.slice(0, 10) == '0123456789';\r\n ALPHABET = v;\r\n } else {\r\n throw Error\r\n (bignumberError + p + ' invalid: ' + v);\r\n }\r\n }\r\n\r\n } else {\r\n\r\n // '[BigNumber Error] Object expected: {v}'\r\n throw Error\r\n (bignumberError + 'Object expected: ' + obj);\r\n }\r\n }\r\n\r\n return {\r\n DECIMAL_PLACES: DECIMAL_PLACES,\r\n ROUNDING_MODE: ROUNDING_MODE,\r\n EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS],\r\n RANGE: [MIN_EXP, MAX_EXP],\r\n CRYPTO: CRYPTO,\r\n MODULO_MODE: MODULO_MODE,\r\n POW_PRECISION: POW_PRECISION,\r\n FORMAT: FORMAT,\r\n ALPHABET: ALPHABET\r\n };\r\n };\r\n\r\n\r\n /*\r\n * Return true if v is a BigNumber instance, otherwise return false.\r\n *\r\n * If BigNumber.DEBUG is true, throw if a BigNumber instance is not well-formed.\r\n *\r\n * v {any}\r\n *\r\n * '[BigNumber Error] Invalid BigNumber: {v}'\r\n */\r\n BigNumber.isBigNumber = function (v) {\r\n if (!v || v._isBigNumber !== true) return false;\r\n if (!BigNumber.DEBUG) return true;\r\n\r\n var i, n,\r\n c = v.c,\r\n e = v.e,\r\n s = v.s;\r\n\r\n out: if ({}.toString.call(c) == '[object Array]') {\r\n\r\n if ((s === 1 || s === -1) && e >= -MAX && e <= MAX && e === mathfloor(e)) {\r\n\r\n // If the first element is zero, the BigNumber value must be zero.\r\n if (c[0] === 0) {\r\n if (e === 0 && c.length === 1) return true;\r\n break out;\r\n }\r\n\r\n // Calculate number of digits that c[0] should have, based on the exponent.\r\n i = (e + 1) % LOG_BASE;\r\n if (i < 1) i += LOG_BASE;\r\n\r\n // Calculate number of digits of c[0].\r\n //if (Math.ceil(Math.log(c[0] + 1) / Math.LN10) == i) {\r\n if (String(c[0]).length == i) {\r\n\r\n for (i = 0; i < c.length; i++) {\r\n n = c[i];\r\n if (n < 0 || n >= BASE || n !== mathfloor(n)) break out;\r\n }\r\n\r\n // Last element cannot be zero, unless it is the only element.\r\n if (n !== 0) return true;\r\n }\r\n }\r\n\r\n // Infinity/NaN\r\n } else if (c === null && e === null && (s === null || s === 1 || s === -1)) {\r\n return true;\r\n }\r\n\r\n throw Error\r\n (bignumberError + 'Invalid BigNumber: ' + v);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the maximum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.maximum = BigNumber.max = function () {\r\n return maxOrMin(arguments, -1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the minimum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.minimum = BigNumber.min = function () {\r\n return maxOrMin(arguments, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r\n * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r\n * zeros are produced).\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}'\r\n * '[BigNumber Error] crypto unavailable'\r\n */\r\n BigNumber.random = (function () {\r\n var pow2_53 = 0x20000000000000;\r\n\r\n // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r\n // Check if Math.random() produces more than 32 bits of randomness.\r\n // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r\n // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r\n var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r\n ? function () { return mathfloor(Math.random() * pow2_53); }\r\n : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r\n (Math.random() * 0x800000 | 0); };\r\n\r\n return function (dp) {\r\n var a, b, e, k, v,\r\n i = 0,\r\n c = [],\r\n rand = new BigNumber(ONE);\r\n\r\n if (dp == null) dp = DECIMAL_PLACES;\r\n else intCheck(dp, 0, MAX);\r\n\r\n k = mathceil(dp / LOG_BASE);\r\n\r\n if (CRYPTO) {\r\n\r\n // Browsers supporting crypto.getRandomValues.\r\n if (crypto.getRandomValues) {\r\n\r\n a = crypto.getRandomValues(new Uint32Array(k *= 2));\r\n\r\n for (; i < k;) {\r\n\r\n // 53 bits:\r\n // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r\n // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r\n // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r\n // 11111 11111111 11111111\r\n // 0x20000 is 2^21.\r\n v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r\n\r\n // Rejection sampling:\r\n // 0 <= v < 9007199254740992\r\n // Probability that v >= 9e15, is\r\n // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r\n if (v >= 9e15) {\r\n b = crypto.getRandomValues(new Uint32Array(2));\r\n a[i] = b[0];\r\n a[i + 1] = b[1];\r\n } else {\r\n\r\n // 0 <= v <= 8999999999999999\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 2;\r\n }\r\n }\r\n i = k / 2;\r\n\r\n // Node.js supporting crypto.randomBytes.\r\n } else if (crypto.randomBytes) {\r\n\r\n // buffer\r\n a = crypto.randomBytes(k *= 7);\r\n\r\n for (; i < k;) {\r\n\r\n // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r\n // 0x100000000 is 2^32, 0x1000000 is 2^24\r\n // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r\n // 0 <= v < 9007199254740992\r\n v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) +\r\n (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) +\r\n (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6];\r\n\r\n if (v >= 9e15) {\r\n crypto.randomBytes(7).copy(a, i);\r\n } else {\r\n\r\n // 0 <= (v % 1e14) <= 99999999999999\r\n c.push(v % 1e14);\r\n i += 7;\r\n }\r\n }\r\n i = k / 7;\r\n } else {\r\n CRYPTO = false;\r\n throw Error\r\n (bignumberError + 'crypto unavailable');\r\n }\r\n }\r\n\r\n // Use Math.random.\r\n if (!CRYPTO) {\r\n\r\n for (; i < k;) {\r\n v = random53bitInt();\r\n if (v < 9e15) c[i++] = v % 1e14;\r\n }\r\n }\r\n\r\n k = c[--i];\r\n dp %= LOG_BASE;\r\n\r\n // Convert trailing digits to zeros according to dp.\r\n if (k && dp) {\r\n v = POWS_TEN[LOG_BASE - dp];\r\n c[i] = mathfloor(k / v) * v;\r\n }\r\n\r\n // Remove trailing elements which are zero.\r\n for (; c[i] === 0; c.pop(), i--);\r\n\r\n // Zero?\r\n if (i < 0) {\r\n c = [e = 0];\r\n } else {\r\n\r\n // Remove leading elements which are zero and adjust exponent accordingly.\r\n for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r\n\r\n // Count the digits of the first element of c to determine leading zeros, and...\r\n for (i = 1, v = c[0]; v >= 10; v /= 10, i++);\r\n\r\n // adjust the exponent accordingly.\r\n if (i < LOG_BASE) e -= LOG_BASE - i;\r\n }\r\n\r\n rand.e = e;\r\n rand.c = c;\r\n return rand;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the sum of the arguments.\r\n *\r\n * arguments {number|string|BigNumber}\r\n */\r\n BigNumber.sum = function () {\r\n var i = 1,\r\n args = arguments,\r\n sum = new BigNumber(args[0]);\r\n for (; i < args.length;) sum = sum.plus(args[i++]);\r\n return sum;\r\n };\r\n\r\n\r\n // PRIVATE FUNCTIONS\r\n\r\n\r\n // Called by BigNumber and BigNumber.prototype.toString.\r\n convertBase = (function () {\r\n var decimal = '0123456789';\r\n\r\n /*\r\n * Convert string of baseIn to an array of numbers of baseOut.\r\n * Eg. toBaseOut('255', 10, 16) returns [15, 15].\r\n * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5].\r\n */\r\n function toBaseOut(str, baseIn, baseOut, alphabet) {\r\n var j,\r\n arr = [0],\r\n arrL,\r\n i = 0,\r\n len = str.length;\r\n\r\n for (; i < len;) {\r\n for (arrL = arr.length; arrL--; arr[arrL] *= baseIn);\r\n\r\n arr[0] += alphabet.indexOf(str.charAt(i++));\r\n\r\n for (j = 0; j < arr.length; j++) {\r\n\r\n if (arr[j] > baseOut - 1) {\r\n if (arr[j + 1] == null) arr[j + 1] = 0;\r\n arr[j + 1] += arr[j] / baseOut | 0;\r\n arr[j] %= baseOut;\r\n }\r\n }\r\n }\r\n\r\n return arr.reverse();\r\n }\r\n\r\n // Convert a numeric string of baseIn to a numeric string of baseOut.\r\n // If the caller is toString, we are converting from base 10 to baseOut.\r\n // If the caller is BigNumber, we are converting from baseIn to base 10.\r\n return function (str, baseIn, baseOut, sign, callerIsToString) {\r\n var alphabet, d, e, k, r, x, xc, y,\r\n i = str.indexOf('.'),\r\n dp = DECIMAL_PLACES,\r\n rm = ROUNDING_MODE;\r\n\r\n // Non-integer.\r\n if (i >= 0) {\r\n k = POW_PRECISION;\r\n\r\n // Unlimited precision.\r\n POW_PRECISION = 0;\r\n str = str.replace('.', '');\r\n y = new BigNumber(baseIn);\r\n x = y.pow(str.length - i);\r\n POW_PRECISION = k;\r\n\r\n // Convert str as if an integer, then restore the fraction part by dividing the\r\n // result by its base raised to a power.\r\n\r\n y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'),\r\n 10, baseOut, decimal);\r\n y.e = y.c.length;\r\n }\r\n\r\n // Convert the number as integer.\r\n\r\n xc = toBaseOut(str, baseIn, baseOut, callerIsToString\r\n ? (alphabet = ALPHABET, decimal)\r\n : (alphabet = decimal, ALPHABET));\r\n\r\n // xc now represents str as an integer and converted to baseOut. e is the exponent.\r\n e = k = xc.length;\r\n\r\n // Remove trailing zeros.\r\n for (; xc[--k] == 0; xc.pop());\r\n\r\n // Zero?\r\n if (!xc[0]) return alphabet.charAt(0);\r\n\r\n // Does str represent an integer? If so, no need for the division.\r\n if (i < 0) {\r\n --e;\r\n } else {\r\n x.c = xc;\r\n x.e = e;\r\n\r\n // The sign is needed for correct rounding.\r\n x.s = sign;\r\n x = div(x, y, dp, rm, baseOut);\r\n xc = x.c;\r\n r = x.r;\r\n e = x.e;\r\n }\r\n\r\n // xc now represents str converted to baseOut.\r\n\r\n // The index of the rounding digit.\r\n d = e + dp + 1;\r\n\r\n // The rounding digit: the digit to the right of the digit that may be rounded up.\r\n i = xc[d];\r\n\r\n // Look at the rounding digits and mode to determine whether to round up.\r\n\r\n k = baseOut / 2;\r\n r = r || d < 0 || xc[d + 1] != null;\r\n\r\n r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n // If the index of the rounding digit is not greater than zero, or xc represents\r\n // zero, then the result of the base conversion is zero or, if rounding up, a value\r\n // such as 0.00001.\r\n if (d < 1 || !xc[0]) {\r\n\r\n // 1^-dp or 0\r\n str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) : alphabet.charAt(0);\r\n } else {\r\n\r\n // Truncate xc to the required number of decimal places.\r\n xc.length = d;\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n // Rounding up may mean the previous digit has to be rounded up and so on.\r\n for (--baseOut; ++xc[--d] > baseOut;) {\r\n xc[d] = 0;\r\n\r\n if (!d) {\r\n ++e;\r\n xc = [1].concat(xc);\r\n }\r\n }\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (k = xc.length; !xc[--k];);\r\n\r\n // E.g. [4, 11, 15] becomes 4bf.\r\n for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++]));\r\n\r\n // Add leading zeros, decimal point and trailing zeros as required.\r\n str = toFixedPoint(str, e, alphabet.charAt(0));\r\n }\r\n\r\n // The caller will add the sign.\r\n return str;\r\n };\r\n })();\r\n\r\n\r\n // Perform division in the specified base. Called by div and convertBase.\r\n div = (function () {\r\n\r\n // Assume non-zero x and k.\r\n function multiply(x, k, base) {\r\n var m, temp, xlo, xhi,\r\n carry = 0,\r\n i = x.length,\r\n klo = k % SQRT_BASE,\r\n khi = k / SQRT_BASE | 0;\r\n\r\n for (x = x.slice(); i--;) {\r\n xlo = x[i] % SQRT_BASE;\r\n xhi = x[i] / SQRT_BASE | 0;\r\n m = khi * xlo + xhi * klo;\r\n temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry;\r\n carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi;\r\n x[i] = temp % base;\r\n }\r\n\r\n if (carry) x = [carry].concat(x);\r\n\r\n return x;\r\n }\r\n\r\n function compare(a, b, aL, bL) {\r\n var i, cmp;\r\n\r\n if (aL != bL) {\r\n cmp = aL > bL ? 1 : -1;\r\n } else {\r\n\r\n for (i = cmp = 0; i < aL; i++) {\r\n\r\n if (a[i] != b[i]) {\r\n cmp = a[i] > b[i] ? 1 : -1;\r\n break;\r\n }\r\n }\r\n }\r\n\r\n return cmp;\r\n }\r\n\r\n function subtract(a, b, aL, base) {\r\n var i = 0;\r\n\r\n // Subtract b from a.\r\n for (; aL--;) {\r\n a[aL] -= i;\r\n i = a[aL] < b[aL] ? 1 : 0;\r\n a[aL] = i * base + a[aL] - b[aL];\r\n }\r\n\r\n // Remove leading zeros.\r\n for (; !a[0] && a.length > 1; a.splice(0, 1));\r\n }\r\n\r\n // x: dividend, y: divisor.\r\n return function (x, y, dp, rm, base) {\r\n var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r\n yL, yz,\r\n s = x.s == y.s ? 1 : -1,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n // Either NaN, Infinity or 0?\r\n if (!xc || !xc[0] || !yc || !yc[0]) {\r\n\r\n return new BigNumber(\r\n\r\n // Return NaN if either NaN, or both Infinity or 0.\r\n !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN :\r\n\r\n // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.\r\n xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r\n );\r\n }\r\n\r\n q = new BigNumber(s);\r\n qc = q.c = [];\r\n e = x.e - y.e;\r\n s = dp + e + 1;\r\n\r\n if (!base) {\r\n base = BASE;\r\n e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE);\r\n s = s / LOG_BASE | 0;\r\n }\r\n\r\n // Result exponent may be one less then the current value of e.\r\n // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r\n for (i = 0; yc[i] == (xc[i] || 0); i++);\r\n\r\n if (yc[i] > (xc[i] || 0)) e--;\r\n\r\n if (s < 0) {\r\n qc.push(1);\r\n more = true;\r\n } else {\r\n xL = xc.length;\r\n yL = yc.length;\r\n i = 0;\r\n s += 2;\r\n\r\n // Normalise xc and yc so highest order digit of yc is >= base / 2.\r\n\r\n n = mathfloor(base / (yc[0] + 1));\r\n\r\n // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1.\r\n // if (n > 1 || n++ == 1 && yc[0] < base / 2) {\r\n if (n > 1) {\r\n yc = multiply(yc, n, base);\r\n xc = multiply(xc, n, base);\r\n yL = yc.length;\r\n xL = xc.length;\r\n }\r\n\r\n xi = yL;\r\n rem = xc.slice(0, yL);\r\n remL = rem.length;\r\n\r\n // Add zeros to make remainder as long as divisor.\r\n for (; remL < yL; rem[remL++] = 0);\r\n yz = yc.slice();\r\n yz = [0].concat(yz);\r\n yc0 = yc[0];\r\n if (yc[1] >= base / 2) yc0++;\r\n // Not necessary, but to prevent trial digit n > base, when using base 3.\r\n // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15;\r\n\r\n do {\r\n n = 0;\r\n\r\n // Compare divisor and remainder.\r\n cmp = compare(yc, rem, yL, remL);\r\n\r\n // If divisor < remainder.\r\n if (cmp < 0) {\r\n\r\n // Calculate trial digit, n.\r\n\r\n rem0 = rem[0];\r\n if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);\r\n\r\n // n is how many times the divisor goes into the current remainder.\r\n n = mathfloor(rem0 / yc0);\r\n\r\n // Algorithm:\r\n // product = divisor multiplied by trial digit (n).\r\n // Compare product and remainder.\r\n // If product is greater than remainder:\r\n // Subtract divisor from product, decrement trial digit.\r\n // Subtract product from remainder.\r\n // If product was less than remainder at the last compare:\r\n // Compare new remainder and divisor.\r\n // If remainder is greater than divisor:\r\n // Subtract divisor from remainder, increment trial digit.\r\n\r\n if (n > 1) {\r\n\r\n // n may be > base only when base is 3.\r\n if (n >= base) n = base - 1;\r\n\r\n // product = divisor * trial digit.\r\n prod = multiply(yc, n, base);\r\n prodL = prod.length;\r\n remL = rem.length;\r\n\r\n // Compare product and remainder.\r\n // If product > remainder then trial digit n too high.\r\n // n is 1 too high about 5% of the time, and is not known to have\r\n // ever been more than 1 too high.\r\n while (compare(prod, rem, prodL, remL) == 1) {\r\n n--;\r\n\r\n // Subtract divisor from product.\r\n subtract(prod, yL < prodL ? yz : yc, prodL, base);\r\n prodL = prod.length;\r\n cmp = 1;\r\n }\r\n } else {\r\n\r\n // n is 0 or 1, cmp is -1.\r\n // If n is 0, there is no need to compare yc and rem again below,\r\n // so change cmp to 1 to avoid it.\r\n // If n is 1, leave cmp as -1, so yc and rem are compared again.\r\n if (n == 0) {\r\n\r\n // divisor < remainder, so n must be at least 1.\r\n cmp = n = 1;\r\n }\r\n\r\n // product = divisor\r\n prod = yc.slice();\r\n prodL = prod.length;\r\n }\r\n\r\n if (prodL < remL) prod = [0].concat(prod);\r\n\r\n // Subtract product from remainder.\r\n subtract(rem, prod, remL, base);\r\n remL = rem.length;\r\n\r\n // If product was < remainder.\r\n if (cmp == -1) {\r\n\r\n // Compare divisor and new remainder.\r\n // If divisor < new remainder, subtract divisor from remainder.\r\n // Trial digit n too low.\r\n // n is 1 too low about 5% of the time, and very rarely 2 too low.\r\n while (compare(yc, rem, yL, remL) < 1) {\r\n n++;\r\n\r\n // Subtract divisor from remainder.\r\n subtract(rem, yL < remL ? yz : yc, remL, base);\r\n remL = rem.length;\r\n }\r\n }\r\n } else if (cmp === 0) {\r\n n++;\r\n rem = [0];\r\n } // else cmp === 1 and n will be 0\r\n\r\n // Add the next digit, n, to the result array.\r\n qc[i++] = n;\r\n\r\n // Update the remainder.\r\n if (rem[0]) {\r\n rem[remL++] = xc[xi] || 0;\r\n } else {\r\n rem = [xc[xi]];\r\n remL = 1;\r\n }\r\n } while ((xi++ < xL || rem[0] != null) && s--);\r\n\r\n more = rem[0] != null;\r\n\r\n // Leading zero?\r\n if (!qc[0]) qc.splice(0, 1);\r\n }\r\n\r\n if (base == BASE) {\r\n\r\n // To calculate q.e, first get the number of digits of qc[0].\r\n for (i = 1, s = qc[0]; s >= 10; s /= 10, i++);\r\n\r\n round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more);\r\n\r\n // Caller is convertBase.\r\n } else {\r\n q.e = e;\r\n q.r = +more;\r\n }\r\n\r\n return q;\r\n };\r\n })();\r\n\r\n\r\n /*\r\n * Return a string representing the value of BigNumber n in fixed-point or exponential\r\n * notation rounded to the specified decimal places or significant digits.\r\n *\r\n * n: a BigNumber.\r\n * i: the index of the last digit required (i.e. the digit that may be rounded up).\r\n * rm: the rounding mode.\r\n * id: 1 (toExponential) or 2 (toPrecision).\r\n */\r\n function format(n, i, rm, id) {\r\n var c0, e, ne, len, str;\r\n\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n if (!n.c) return n.toString();\r\n\r\n c0 = n.c[0];\r\n ne = n.e;\r\n\r\n if (i == null) {\r\n str = coeffToString(n.c);\r\n str = id == 1 || id == 2 && (ne <= TO_EXP_NEG || ne >= TO_EXP_POS)\r\n ? toExponential(str, ne)\r\n : toFixedPoint(str, ne, '0');\r\n } else {\r\n n = round(new BigNumber(n), i, rm);\r\n\r\n // n.e may have changed if the value was rounded up.\r\n e = n.e;\r\n\r\n str = coeffToString(n.c);\r\n len = str.length;\r\n\r\n // toPrecision returns exponential notation if the number of significant digits\r\n // specified is less than the number of digits necessary to represent the integer\r\n // part of the value in fixed-point notation.\r\n\r\n // Exponential notation.\r\n if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) {\r\n\r\n // Append zeros?\r\n for (; len < i; str += '0', len++);\r\n str = toExponential(str, e);\r\n\r\n // Fixed-point notation.\r\n } else {\r\n i -= ne + (id === 2 && e > ne);\r\n str = toFixedPoint(str, e, '0');\r\n\r\n // Append zeros?\r\n if (e + 1 > len) {\r\n if (--i > 0) for (str += '.'; i--; str += '0');\r\n } else {\r\n i += e - len;\r\n if (i > 0) {\r\n if (e + 1 == len) str += '.';\r\n for (; i--; str += '0');\r\n }\r\n }\r\n }\r\n }\r\n\r\n return n.s < 0 && c0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // Handle BigNumber.max and BigNumber.min.\r\n // If any number is NaN, return NaN.\r\n function maxOrMin(args, n) {\r\n var k, y,\r\n i = 1,\r\n x = new BigNumber(args[0]);\r\n\r\n for (; i < args.length; i++) {\r\n y = new BigNumber(args[i]);\r\n if (!y.s || (k = compare(x, y)) === n || k === 0 && x.s === n) {\r\n x = y;\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n /*\r\n * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r\n * Called by minus, plus and times.\r\n */\r\n function normalise(n, c, e) {\r\n var i = 1,\r\n j = c.length;\r\n\r\n // Remove trailing zeros.\r\n for (; !c[--j]; c.pop());\r\n\r\n // Calculate the base 10 exponent. First get the number of digits of c[0].\r\n for (j = c[0]; j >= 10; j /= 10, i++);\r\n\r\n // Overflow?\r\n if ((e = i + e * LOG_BASE - 1) > MAX_EXP) {\r\n\r\n // Infinity.\r\n n.c = n.e = null;\r\n\r\n // Underflow?\r\n } else if (e < MIN_EXP) {\r\n\r\n // Zero.\r\n n.c = [n.e = 0];\r\n } else {\r\n n.e = e;\r\n n.c = c;\r\n }\r\n\r\n return n;\r\n }\r\n\r\n\r\n // Handle values that fail the validity test in BigNumber.\r\n parseNumeric = (function () {\r\n var basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i,\r\n dotAfter = /^([^.]+)\\.$/,\r\n dotBefore = /^\\.([^.]+)$/,\r\n isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r\n whitespaceOrPlus = /^\\s*\\+(?=[\\w.])|^\\s+|\\s+$/g;\r\n\r\n return function (x, str, isNum, b) {\r\n var base,\r\n s = isNum ? str : str.replace(whitespaceOrPlus, '');\r\n\r\n // No exception on ±Infinity or NaN.\r\n if (isInfinityOrNaN.test(s)) {\r\n x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r\n } else {\r\n if (!isNum) {\r\n\r\n // basePrefix = /^(-?)0([xbo])(?=\\w[\\w.]*$)/i\r\n s = s.replace(basePrefix, function (m, p1, p2) {\r\n base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r\n return !b || b == base ? p1 : m;\r\n });\r\n\r\n if (b) {\r\n base = b;\r\n\r\n // E.g. '1.' to '1', '.1' to '0.1'\r\n s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1');\r\n }\r\n\r\n if (str != s) return new BigNumber(s, base);\r\n }\r\n\r\n // '[BigNumber Error] Not a number: {n}'\r\n // '[BigNumber Error] Not a base {b} number: {n}'\r\n if (BigNumber.DEBUG) {\r\n throw Error\r\n (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str);\r\n }\r\n\r\n // NaN\r\n x.s = null;\r\n }\r\n\r\n x.c = x.e = null;\r\n }\r\n })();\r\n\r\n\r\n /*\r\n * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r\n * If r is truthy, it is known that there are more digits after the rounding digit.\r\n */\r\n function round(x, sd, rm, r) {\r\n var d, i, j, k, n, ni, rd,\r\n xc = x.c,\r\n pows10 = POWS_TEN;\r\n\r\n // if x is not Infinity or NaN...\r\n if (xc) {\r\n\r\n // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r\n // n is a base 1e14 number, the value of the element of array x.c containing rd.\r\n // ni is the index of n within x.c.\r\n // d is the number of digits of n.\r\n // i is the index of rd within n including leading zeros.\r\n // j is the actual index of rd within n (if < 0, rd is a leading zero).\r\n out: {\r\n\r\n // Get the number of digits of the first element of xc.\r\n for (d = 1, k = xc[0]; k >= 10; k /= 10, d++);\r\n i = sd - d;\r\n\r\n // If the rounding digit is in the first element of xc...\r\n if (i < 0) {\r\n i += LOG_BASE;\r\n j = sd;\r\n n = xc[ni = 0];\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = mathfloor(n / pows10[d - j - 1] % 10);\r\n } else {\r\n ni = mathceil((i + 1) / LOG_BASE);\r\n\r\n if (ni >= xc.length) {\r\n\r\n if (r) {\r\n\r\n // Needed by sqrt.\r\n for (; xc.length <= ni; xc.push(0));\r\n n = rd = 0;\r\n d = 1;\r\n i %= LOG_BASE;\r\n j = i - LOG_BASE + 1;\r\n } else {\r\n break out;\r\n }\r\n } else {\r\n n = k = xc[ni];\r\n\r\n // Get the number of digits of n.\r\n for (d = 1; k >= 10; k /= 10, d++);\r\n\r\n // Get the index of rd within n.\r\n i %= LOG_BASE;\r\n\r\n // Get the index of rd within n, adjusted for leading zeros.\r\n // The number of leading zeros of n is given by LOG_BASE - d.\r\n j = i - LOG_BASE + d;\r\n\r\n // Get the rounding digit at index j of n.\r\n rd = j < 0 ? 0 : mathfloor(n / pows10[d - j - 1] % 10);\r\n }\r\n }\r\n\r\n r = r || sd < 0 ||\r\n\r\n // Are there any non-zero digits after the rounding digit?\r\n // The expression n % pows10[d - j - 1] returns all digits of n to the right\r\n // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r\n xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]);\r\n\r\n r = rm < 4\r\n ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))\r\n : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 &&\r\n\r\n // Check whether the digit to the left of the rounding digit is odd.\r\n ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 ||\r\n rm == (x.s < 0 ? 8 : 7));\r\n\r\n if (sd < 1 || !xc[0]) {\r\n xc.length = 0;\r\n\r\n if (r) {\r\n\r\n // Convert sd to decimal places.\r\n sd -= x.e + 1;\r\n\r\n // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r\n xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE];\r\n x.e = -sd || 0;\r\n } else {\r\n\r\n // Zero.\r\n xc[0] = x.e = 0;\r\n }\r\n\r\n return x;\r\n }\r\n\r\n // Remove excess digits.\r\n if (i == 0) {\r\n xc.length = ni;\r\n k = 1;\r\n ni--;\r\n } else {\r\n xc.length = ni + 1;\r\n k = pows10[LOG_BASE - i];\r\n\r\n // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r\n // j > 0 means i > number of leading zeros of n.\r\n xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0;\r\n }\r\n\r\n // Round up?\r\n if (r) {\r\n\r\n for (; ;) {\r\n\r\n // If the digit to be rounded up is in the first element of xc...\r\n if (ni == 0) {\r\n\r\n // i will be the length of xc[0] before k is added.\r\n for (i = 1, j = xc[0]; j >= 10; j /= 10, i++);\r\n j = xc[0] += k;\r\n for (k = 1; j >= 10; j /= 10, k++);\r\n\r\n // if i != k the length has increased.\r\n if (i != k) {\r\n x.e++;\r\n if (xc[0] == BASE) xc[0] = 1;\r\n }\r\n\r\n break;\r\n } else {\r\n xc[ni] += k;\r\n if (xc[ni] != BASE) break;\r\n xc[ni--] = 0;\r\n k = 1;\r\n }\r\n }\r\n }\r\n\r\n // Remove trailing zeros.\r\n for (i = xc.length; xc[--i] === 0; xc.pop());\r\n }\r\n\r\n // Overflow? Infinity.\r\n if (x.e > MAX_EXP) {\r\n x.c = x.e = null;\r\n\r\n // Underflow? Zero.\r\n } else if (x.e < MIN_EXP) {\r\n x.c = [x.e = 0];\r\n }\r\n }\r\n\r\n return x;\r\n }\r\n\r\n\r\n function valueOf(n) {\r\n var str,\r\n e = n.e;\r\n\r\n if (e === null) return n.toString();\r\n\r\n str = coeffToString(n.c);\r\n\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(str, e)\r\n : toFixedPoint(str, e, '0');\r\n\r\n return n.s < 0 ? '-' + str : str;\r\n }\r\n\r\n\r\n // PROTOTYPE/INSTANCE METHODS\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the absolute value of this BigNumber.\r\n */\r\n P.absoluteValue = P.abs = function () {\r\n var x = new BigNumber(this);\r\n if (x.s < 0) x.s = 1;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * Return\r\n * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * 0 if they have the same value,\r\n * or null if the value of either is NaN.\r\n */\r\n P.comparedTo = function (y, b) {\r\n return compare(this, new BigNumber(y, b));\r\n };\r\n\r\n\r\n /*\r\n * If dp is undefined or null or true or false, return the number of decimal places of the\r\n * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n *\r\n * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * [dp] {number} Decimal places: integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.decimalPlaces = P.dp = function (dp, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), dp + x.e + 1, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE;\r\n\r\n // Subtract the number of trailing zeros of the last number.\r\n if (v = c[v]) for (; v % 10 == 0; v /= 10, n--);\r\n if (n < 0) n = 0;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * n / 0 = I\r\n * n / N = N\r\n * n / I = 0\r\n * 0 / n = 0\r\n * 0 / 0 = N\r\n * 0 / N = N\r\n * 0 / I = 0\r\n * N / n = N\r\n * N / 0 = N\r\n * N / N = N\r\n * N / I = N\r\n * I / n = I\r\n * I / 0 = I\r\n * I / N = N\r\n * I / I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r\n * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.dividedBy = P.div = function (y, b) {\r\n return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the integer part of dividing the value of this\r\n * BigNumber by the value of BigNumber(y, b).\r\n */\r\n P.dividedToIntegerBy = P.idiv = function (y, b) {\r\n return div(this, new BigNumber(y, b), 0, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a BigNumber whose value is the value of this BigNumber exponentiated by n.\r\n *\r\n * If m is present, return the result modulo m.\r\n * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r\n * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE.\r\n *\r\n * The modular power operation works efficiently when x, n, and m are integers, otherwise it\r\n * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0.\r\n *\r\n * n {number|string|BigNumber} The exponent. An integer.\r\n * [m] {number|string|BigNumber} The modulus.\r\n *\r\n * '[BigNumber Error] Exponent not an integer: {n}'\r\n */\r\n P.exponentiatedBy = P.pow = function (n, m) {\r\n var half, isModExp, i, k, more, nIsBig, nIsNeg, nIsOdd, y,\r\n x = this;\r\n\r\n n = new BigNumber(n);\r\n\r\n // Allow NaN and ±Infinity, but not other non-integers.\r\n if (n.c && !n.isInteger()) {\r\n throw Error\r\n (bignumberError + 'Exponent not an integer: ' + valueOf(n));\r\n }\r\n\r\n if (m != null) m = new BigNumber(m);\r\n\r\n // Exponent of MAX_SAFE_INTEGER is 15.\r\n nIsBig = n.e > 14;\r\n\r\n // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0.\r\n if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) {\r\n\r\n // The sign of the result of pow when x is negative depends on the evenness of n.\r\n // If +n overflows to ±Infinity, the evenness of n would be not be known.\r\n y = new BigNumber(Math.pow(+valueOf(x), nIsBig ? n.s * (2 - isOdd(n)) : +valueOf(n)));\r\n return m ? y.mod(m) : y;\r\n }\r\n\r\n nIsNeg = n.s < 0;\r\n\r\n if (m) {\r\n\r\n // x % m returns NaN if abs(m) is zero, or m is NaN.\r\n if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN);\r\n\r\n isModExp = !nIsNeg && x.isInteger() && m.isInteger();\r\n\r\n if (isModExp) x = x.mod(m);\r\n\r\n // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15.\r\n // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15.\r\n } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0\r\n // [1, 240000000]\r\n ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7\r\n // [80000000000000] [99999750000000]\r\n : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) {\r\n\r\n // If x is negative and n is odd, k = -0, else k = 0.\r\n k = x.s < 0 && isOdd(n) ? -0 : 0;\r\n\r\n // If x >= 1, k = ±Infinity.\r\n if (x.e > -1) k = 1 / k;\r\n\r\n // If n is negative return ±0, else return ±Infinity.\r\n return new BigNumber(nIsNeg ? 1 / k : k);\r\n\r\n } else if (POW_PRECISION) {\r\n\r\n // Truncating each coefficient array to a length of k after each multiplication\r\n // equates to truncating significant digits to POW_PRECISION + [28, 41],\r\n // i.e. there will be a minimum of 28 guard digits retained.\r\n k = mathceil(POW_PRECISION / LOG_BASE + 2);\r\n }\r\n\r\n if (nIsBig) {\r\n half = new BigNumber(0.5);\r\n if (nIsNeg) n.s = 1;\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = Math.abs(+valueOf(n));\r\n nIsOdd = i % 2;\r\n }\r\n\r\n y = new BigNumber(ONE);\r\n\r\n // Performs 54 loop iterations for n of 9007199254740991.\r\n for (; ;) {\r\n\r\n if (nIsOdd) {\r\n y = y.times(x);\r\n if (!y.c) break;\r\n\r\n if (k) {\r\n if (y.c.length > k) y.c.length = k;\r\n } else if (isModExp) {\r\n y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (i) {\r\n i = mathfloor(i / 2);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n } else {\r\n n = n.times(half);\r\n round(n, n.e + 1, 1);\r\n\r\n if (n.e > 14) {\r\n nIsOdd = isOdd(n);\r\n } else {\r\n i = +valueOf(n);\r\n if (i === 0) break;\r\n nIsOdd = i % 2;\r\n }\r\n }\r\n\r\n x = x.times(x);\r\n\r\n if (k) {\r\n if (x.c && x.c.length > k) x.c.length = k;\r\n } else if (isModExp) {\r\n x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m));\r\n }\r\n }\r\n\r\n if (isModExp) return y;\r\n if (nIsNeg) y = ONE.div(y);\r\n\r\n return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer\r\n * using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}'\r\n */\r\n P.integerValue = function (rm) {\r\n var n = new BigNumber(this);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n return round(n, n.e + 1, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isEqualTo = P.eq = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is a finite number, otherwise return false.\r\n */\r\n P.isFinite = function () {\r\n return !!this.c;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isGreaterThan = P.gt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is greater than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isGreaterThanOrEqualTo = P.gte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0;\r\n\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is an integer, otherwise return false.\r\n */\r\n P.isInteger = function () {\r\n return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r\n * otherwise return false.\r\n */\r\n P.isLessThan = P.lt = function (y, b) {\r\n return compare(this, new BigNumber(y, b)) < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is less than or equal to the value of\r\n * BigNumber(y, b), otherwise return false.\r\n */\r\n P.isLessThanOrEqualTo = P.lte = function (y, b) {\r\n return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is NaN, otherwise return false.\r\n */\r\n P.isNaN = function () {\r\n return !this.s;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is negative, otherwise return false.\r\n */\r\n P.isNegative = function () {\r\n return this.s < 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is positive, otherwise return false.\r\n */\r\n P.isPositive = function () {\r\n return this.s > 0;\r\n };\r\n\r\n\r\n /*\r\n * Return true if the value of this BigNumber is 0 or -0, otherwise return false.\r\n */\r\n P.isZero = function () {\r\n return !!this.c && this.c[0] == 0;\r\n };\r\n\r\n\r\n /*\r\n * n - 0 = n\r\n * n - N = N\r\n * n - I = -I\r\n * 0 - n = -n\r\n * 0 - 0 = 0\r\n * 0 - N = N\r\n * 0 - I = -I\r\n * N - n = N\r\n * N - 0 = N\r\n * N - N = N\r\n * N - I = N\r\n * I - n = I\r\n * I - 0 = I\r\n * I - N = N\r\n * I - I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.minus = function (y, b) {\r\n var i, j, t, xLTy,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.plus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN);\r\n\r\n // Either zero?\r\n if (!xc[0] || !yc[0]) {\r\n\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x :\r\n\r\n // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r\n ROUNDING_MODE == 3 ? -0 : 0);\r\n }\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Determine which is the bigger number.\r\n if (a = xe - ye) {\r\n\r\n if (xLTy = a < 0) {\r\n a = -a;\r\n t = xc;\r\n } else {\r\n ye = xe;\r\n t = yc;\r\n }\r\n\r\n t.reverse();\r\n\r\n // Prepend zeros to equalise exponents.\r\n for (b = a; b--; t.push(0));\r\n t.reverse();\r\n } else {\r\n\r\n // Exponents equal. Check digit by digit.\r\n j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b;\r\n\r\n for (a = b = 0; b < j; b++) {\r\n\r\n if (xc[b] != yc[b]) {\r\n xLTy = xc[b] < yc[b];\r\n break;\r\n }\r\n }\r\n }\r\n\r\n // x < y? Point xc to the array of the bigger number.\r\n if (xLTy) {\r\n t = xc;\r\n xc = yc;\r\n yc = t;\r\n y.s = -y.s;\r\n }\r\n\r\n b = (j = yc.length) - (i = xc.length);\r\n\r\n // Append zeros to xc if shorter.\r\n // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r\n if (b > 0) for (; b--; xc[i++] = 0);\r\n b = BASE - 1;\r\n\r\n // Subtract yc from xc.\r\n for (; j > a;) {\r\n\r\n if (xc[--j] < yc[j]) {\r\n for (i = j; i && !xc[--i]; xc[i] = b);\r\n --xc[i];\r\n xc[j] += BASE;\r\n }\r\n\r\n xc[j] -= yc[j];\r\n }\r\n\r\n // Remove leading zeros and adjust exponent accordingly.\r\n for (; xc[0] == 0; xc.splice(0, 1), --ye);\r\n\r\n // Zero?\r\n if (!xc[0]) {\r\n\r\n // Following IEEE 754 (2008) 6.3,\r\n // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r\n y.s = ROUNDING_MODE == 3 ? -1 : 1;\r\n y.c = [y.e = 0];\r\n return y;\r\n }\r\n\r\n // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r\n // for finite x and y.\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * n % 0 = N\r\n * n % N = N\r\n * n % I = n\r\n * 0 % n = 0\r\n * -0 % n = -0\r\n * 0 % 0 = N\r\n * 0 % N = N\r\n * 0 % I = 0\r\n * N % n = N\r\n * N % 0 = N\r\n * N % N = N\r\n * N % I = N\r\n * I % n = N\r\n * I % 0 = N\r\n * I % N = N\r\n * I % I = N\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r\n * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r\n */\r\n P.modulo = P.mod = function (y, b) {\r\n var q, s,\r\n x = this;\r\n\r\n y = new BigNumber(y, b);\r\n\r\n // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r\n if (!x.c || !y.s || y.c && !y.c[0]) {\r\n return new BigNumber(NaN);\r\n\r\n // Return x if y is Infinity or x is zero.\r\n } else if (!y.c || x.c && !x.c[0]) {\r\n return new BigNumber(x);\r\n }\r\n\r\n if (MODULO_MODE == 9) {\r\n\r\n // Euclidian division: q = sign(y) * floor(x / abs(y))\r\n // r = x - qy where 0 <= r < abs(y)\r\n s = y.s;\r\n y.s = 1;\r\n q = div(x, y, 0, 3);\r\n y.s = s;\r\n q.s *= s;\r\n } else {\r\n q = div(x, y, 0, MODULO_MODE);\r\n }\r\n\r\n y = x.minus(q.times(y));\r\n\r\n // To match JavaScript %, ensure sign of zero is sign of dividend.\r\n if (!y.c[0] && MODULO_MODE == 1) y.s = x.s;\r\n\r\n return y;\r\n };\r\n\r\n\r\n /*\r\n * n * 0 = 0\r\n * n * N = N\r\n * n * I = I\r\n * 0 * n = 0\r\n * 0 * 0 = 0\r\n * 0 * N = N\r\n * 0 * I = N\r\n * N * n = N\r\n * N * 0 = N\r\n * N * N = N\r\n * N * I = N\r\n * I * n = I\r\n * I * 0 = N\r\n * I * N = N\r\n * I * I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value\r\n * of BigNumber(y, b).\r\n */\r\n P.multipliedBy = P.times = function (y, b) {\r\n var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r\n base, sqrtBase,\r\n x = this,\r\n xc = x.c,\r\n yc = (y = new BigNumber(y, b)).c;\r\n\r\n // Either NaN, ±Infinity or ±0?\r\n if (!xc || !yc || !xc[0] || !yc[0]) {\r\n\r\n // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r\n if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) {\r\n y.c = y.e = y.s = null;\r\n } else {\r\n y.s *= x.s;\r\n\r\n // Return ±Infinity if either is ±Infinity.\r\n if (!xc || !yc) {\r\n y.c = y.e = null;\r\n\r\n // Return ±0 if either is ±0.\r\n } else {\r\n y.c = [0];\r\n y.e = 0;\r\n }\r\n }\r\n\r\n return y;\r\n }\r\n\r\n e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE);\r\n y.s *= x.s;\r\n xcL = xc.length;\r\n ycL = yc.length;\r\n\r\n // Ensure xc points to longer array and xcL to its length.\r\n if (xcL < ycL) {\r\n zc = xc;\r\n xc = yc;\r\n yc = zc;\r\n i = xcL;\r\n xcL = ycL;\r\n ycL = i;\r\n }\r\n\r\n // Initialise the result array with zeros.\r\n for (i = xcL + ycL, zc = []; i--; zc.push(0));\r\n\r\n base = BASE;\r\n sqrtBase = SQRT_BASE;\r\n\r\n for (i = ycL; --i >= 0;) {\r\n c = 0;\r\n ylo = yc[i] % sqrtBase;\r\n yhi = yc[i] / sqrtBase | 0;\r\n\r\n for (k = xcL, j = i + k; j > i;) {\r\n xlo = xc[--k] % sqrtBase;\r\n xhi = xc[k] / sqrtBase | 0;\r\n m = yhi * xlo + xhi * ylo;\r\n xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c;\r\n c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi;\r\n zc[j--] = xlo % base;\r\n }\r\n\r\n zc[j] = c;\r\n }\r\n\r\n if (c) {\r\n ++e;\r\n } else {\r\n zc.splice(0, 1);\r\n }\r\n\r\n return normalise(y, zc, e);\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber negated,\r\n * i.e. multiplied by -1.\r\n */\r\n P.negated = function () {\r\n var x = new BigNumber(this);\r\n x.s = -x.s || null;\r\n return x;\r\n };\r\n\r\n\r\n /*\r\n * n + 0 = n\r\n * n + N = N\r\n * n + I = I\r\n * 0 + n = n\r\n * 0 + 0 = 0\r\n * 0 + N = N\r\n * 0 + I = I\r\n * N + n = N\r\n * N + 0 = N\r\n * N + N = N\r\n * N + I = N\r\n * I + n = I\r\n * I + 0 = I\r\n * I + N = N\r\n * I + I = I\r\n *\r\n * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r\n * BigNumber(y, b).\r\n */\r\n P.plus = function (y, b) {\r\n var t,\r\n x = this,\r\n a = x.s;\r\n\r\n y = new BigNumber(y, b);\r\n b = y.s;\r\n\r\n // Either NaN?\r\n if (!a || !b) return new BigNumber(NaN);\r\n\r\n // Signs differ?\r\n if (a != b) {\r\n y.s = -b;\r\n return x.minus(y);\r\n }\r\n\r\n var xe = x.e / LOG_BASE,\r\n ye = y.e / LOG_BASE,\r\n xc = x.c,\r\n yc = y.c;\r\n\r\n if (!xe || !ye) {\r\n\r\n // Return ±Infinity if either ±Infinity.\r\n if (!xc || !yc) return new BigNumber(a / 0);\r\n\r\n // Either zero?\r\n // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r\n if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0);\r\n }\r\n\r\n xe = bitFloor(xe);\r\n ye = bitFloor(ye);\r\n xc = xc.slice();\r\n\r\n // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r\n if (a = xe - ye) {\r\n if (a > 0) {\r\n ye = xe;\r\n t = yc;\r\n } else {\r\n a = -a;\r\n t = xc;\r\n }\r\n\r\n t.reverse();\r\n for (; a--; t.push(0));\r\n t.reverse();\r\n }\r\n\r\n a = xc.length;\r\n b = yc.length;\r\n\r\n // Point xc to the longer array, and b to the shorter length.\r\n if (a - b < 0) {\r\n t = yc;\r\n yc = xc;\r\n xc = t;\r\n b = a;\r\n }\r\n\r\n // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r\n for (a = 0; b;) {\r\n a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0;\r\n xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r\n }\r\n\r\n if (a) {\r\n xc = [a].concat(xc);\r\n ++ye;\r\n }\r\n\r\n // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r\n // ye = MAX_EXP + 1 possible\r\n return normalise(y, xc, ye);\r\n };\r\n\r\n\r\n /*\r\n * If sd is undefined or null or true or false, return the number of significant digits of\r\n * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN.\r\n * If sd is true include integer-part trailing zeros in the count.\r\n *\r\n * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this\r\n * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or\r\n * ROUNDING_MODE if rm is omitted.\r\n *\r\n * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive.\r\n * boolean: whether to count integer-part trailing zeros: true or false.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.precision = P.sd = function (sd, rm) {\r\n var c, n, v,\r\n x = this;\r\n\r\n if (sd != null && sd !== !!sd) {\r\n intCheck(sd, 1, MAX);\r\n if (rm == null) rm = ROUNDING_MODE;\r\n else intCheck(rm, 0, 8);\r\n\r\n return round(new BigNumber(x), sd, rm);\r\n }\r\n\r\n if (!(c = x.c)) return null;\r\n v = c.length - 1;\r\n n = v * LOG_BASE + 1;\r\n\r\n if (v = c[v]) {\r\n\r\n // Subtract the number of trailing zeros of the last element.\r\n for (; v % 10 == 0; v /= 10, n--);\r\n\r\n // Add the number of digits of the first element.\r\n for (v = c[0]; v >= 10; v /= 10, n++);\r\n }\r\n\r\n if (sd && x.e + 1 > n) n = x.e + 1;\r\n\r\n return n;\r\n };\r\n\r\n\r\n /*\r\n * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r\n * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r\n *\r\n * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}'\r\n */\r\n P.shiftedBy = function (k) {\r\n intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER);\r\n return this.times('1e' + k);\r\n };\r\n\r\n\r\n /*\r\n * sqrt(-n) = N\r\n * sqrt(N) = N\r\n * sqrt(-I) = N\r\n * sqrt(I) = I\r\n * sqrt(0) = 0\r\n * sqrt(-0) = -0\r\n *\r\n * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r\n * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r\n */\r\n P.squareRoot = P.sqrt = function () {\r\n var m, n, r, rep, t,\r\n x = this,\r\n c = x.c,\r\n s = x.s,\r\n e = x.e,\r\n dp = DECIMAL_PLACES + 4,\r\n half = new BigNumber('0.5');\r\n\r\n // Negative/NaN/Infinity/zero?\r\n if (s !== 1 || !c || !c[0]) {\r\n return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0);\r\n }\r\n\r\n // Initial estimate.\r\n s = Math.sqrt(+valueOf(x));\r\n\r\n // Math.sqrt underflow/overflow?\r\n // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r\n if (s == 0 || s == 1 / 0) {\r\n n = coeffToString(c);\r\n if ((n.length + e) % 2 == 0) n += '0';\r\n s = Math.sqrt(+n);\r\n e = bitFloor((e + 1) / 2) - (e < 0 || e % 2);\r\n\r\n if (s == 1 / 0) {\r\n n = '5e' + e;\r\n } else {\r\n n = s.toExponential();\r\n n = n.slice(0, n.indexOf('e') + 1) + e;\r\n }\r\n\r\n r = new BigNumber(n);\r\n } else {\r\n r = new BigNumber(s + '');\r\n }\r\n\r\n // Check for zero.\r\n // r could be zero if MIN_EXP is changed after the this value was created.\r\n // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r\n // coeffToString to throw.\r\n if (r.c[0]) {\r\n e = r.e;\r\n s = e + dp;\r\n if (s < 3) s = 0;\r\n\r\n // Newton-Raphson iteration.\r\n for (; ;) {\r\n t = r;\r\n r = half.times(t.plus(div(x, t, dp, 1)));\r\n\r\n if (coeffToString(t.c).slice(0, s) === (n = coeffToString(r.c)).slice(0, s)) {\r\n\r\n // The exponent of r may here be one less than the final result exponent,\r\n // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r\n // are indexed correctly.\r\n if (r.e < e) --s;\r\n n = n.slice(s - 3, s + 1);\r\n\r\n // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r\n // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r\n // iteration.\r\n if (n == '9999' || !rep && n == '4999') {\r\n\r\n // On the first iteration only, check to see if rounding up gives the\r\n // exact result as the nines may infinitely repeat.\r\n if (!rep) {\r\n round(t, t.e + DECIMAL_PLACES + 2, 0);\r\n\r\n if (t.times(t).eq(x)) {\r\n r = t;\r\n break;\r\n }\r\n }\r\n\r\n dp += 4;\r\n s += 4;\r\n rep = 1;\r\n } else {\r\n\r\n // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r\n // result. If not, then there are further digits and m will be truthy.\r\n if (!+n || !+n.slice(1) && n.charAt(0) == '5') {\r\n\r\n // Truncate to the first rounding digit.\r\n round(r, r.e + DECIMAL_PLACES + 2, 1);\r\n m = !r.times(r).eq(x);\r\n }\r\n\r\n break;\r\n }\r\n }\r\n }\r\n }\r\n\r\n return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in exponential notation and\r\n * rounded using ROUNDING_MODE to dp fixed decimal places.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toExponential = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp++;\r\n }\r\n return format(this, dp, rm, 1);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounding\r\n * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r\n *\r\n * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r\n * but e.g. (-0.00001).toFixed(0) is '-0'.\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n */\r\n P.toFixed = function (dp, rm) {\r\n if (dp != null) {\r\n intCheck(dp, 0, MAX);\r\n dp = dp + this.e + 1;\r\n }\r\n return format(this, dp, rm);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in fixed-point notation rounded\r\n * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r\n * of the format or FORMAT object (see BigNumber.set).\r\n *\r\n * The formatting object may contain some or all of the properties shown below.\r\n *\r\n * FORMAT = {\r\n * prefix: '',\r\n * groupSize: 3,\r\n * secondaryGroupSize: 0,\r\n * groupSeparator: ',',\r\n * decimalSeparator: '.',\r\n * fractionGroupSize: 0,\r\n * fractionGroupSeparator: '\\xA0', // non-breaking space\r\n * suffix: ''\r\n * };\r\n *\r\n * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n * [format] {object} Formatting options. See FORMAT pbject above.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}'\r\n * '[BigNumber Error] Argument not an object: {format}'\r\n */\r\n P.toFormat = function (dp, rm, format) {\r\n var str,\r\n x = this;\r\n\r\n if (format == null) {\r\n if (dp != null && rm && typeof rm == 'object') {\r\n format = rm;\r\n rm = null;\r\n } else if (dp && typeof dp == 'object') {\r\n format = dp;\r\n dp = rm = null;\r\n } else {\r\n format = FORMAT;\r\n }\r\n } else if (typeof format != 'object') {\r\n throw Error\r\n (bignumberError + 'Argument not an object: ' + format);\r\n }\r\n\r\n str = x.toFixed(dp, rm);\r\n\r\n if (x.c) {\r\n var i,\r\n arr = str.split('.'),\r\n g1 = +format.groupSize,\r\n g2 = +format.secondaryGroupSize,\r\n groupSeparator = format.groupSeparator || '',\r\n intPart = arr[0],\r\n fractionPart = arr[1],\r\n isNeg = x.s < 0,\r\n intDigits = isNeg ? intPart.slice(1) : intPart,\r\n len = intDigits.length;\r\n\r\n if (g2) {\r\n i = g1;\r\n g1 = g2;\r\n g2 = i;\r\n len -= i;\r\n }\r\n\r\n if (g1 > 0 && len > 0) {\r\n i = len % g1 || g1;\r\n intPart = intDigits.substr(0, i);\r\n for (; i < len; i += g1) intPart += groupSeparator + intDigits.substr(i, g1);\r\n if (g2 > 0) intPart += groupSeparator + intDigits.slice(i);\r\n if (isNeg) intPart = '-' + intPart;\r\n }\r\n\r\n str = fractionPart\r\n ? intPart + (format.decimalSeparator || '') + ((g2 = +format.fractionGroupSize)\r\n ? fractionPart.replace(new RegExp('\\\\d{' + g2 + '}\\\\B', 'g'),\r\n '$&' + (format.fractionGroupSeparator || ''))\r\n : fractionPart)\r\n : intPart;\r\n }\r\n\r\n return (format.prefix || '') + str + (format.suffix || '');\r\n };\r\n\r\n\r\n /*\r\n * Return an array of two BigNumbers representing the value of this BigNumber as a simple\r\n * fraction with an integer numerator and an integer denominator.\r\n * The denominator will be a positive non-zero value less than or equal to the specified\r\n * maximum denominator. If a maximum denominator is not specified, the denominator will be\r\n * the lowest value necessary to represent the number exactly.\r\n *\r\n * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator.\r\n *\r\n * '[BigNumber Error] Argument {not an integer|out of range} : {md}'\r\n */\r\n P.toFraction = function (md) {\r\n var d, d0, d1, d2, e, exp, n, n0, n1, q, r, s,\r\n x = this,\r\n xc = x.c;\r\n\r\n if (md != null) {\r\n n = new BigNumber(md);\r\n\r\n // Throw if md is less than one or is not an integer, unless it is Infinity.\r\n if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) {\r\n throw Error\r\n (bignumberError + 'Argument ' +\r\n (n.isInteger() ? 'out of range: ' : 'not an integer: ') + valueOf(n));\r\n }\r\n }\r\n\r\n if (!xc) return new BigNumber(x);\r\n\r\n d = new BigNumber(ONE);\r\n n1 = d0 = new BigNumber(ONE);\r\n d1 = n0 = new BigNumber(ONE);\r\n s = coeffToString(xc);\r\n\r\n // Determine initial denominator.\r\n // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r\n e = d.e = s.length - x.e - 1;\r\n d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp];\r\n md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n;\r\n\r\n exp = MAX_EXP;\r\n MAX_EXP = 1 / 0;\r\n n = new BigNumber(s);\r\n\r\n // n0 = d1 = 0\r\n n0.c[0] = 0;\r\n\r\n for (; ;) {\r\n q = div(n, d, 0, 1);\r\n d2 = d0.plus(q.times(d1));\r\n if (d2.comparedTo(md) == 1) break;\r\n d0 = d1;\r\n d1 = d2;\r\n n1 = n0.plus(q.times(d2 = n1));\r\n n0 = d2;\r\n d = n.minus(q.times(d2 = d));\r\n n = d2;\r\n }\r\n\r\n d2 = div(md.minus(d0), d1, 0, 1);\r\n n0 = n0.plus(d2.times(n1));\r\n d0 = d0.plus(d2.times(d1));\r\n n0.s = n1.s = x.s;\r\n e = e * 2;\r\n\r\n // Determine which fraction is closer to x, n0/d0 or n1/d1\r\n r = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo(\r\n div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 ? [n1, d1] : [n0, d0];\r\n\r\n MAX_EXP = exp;\r\n\r\n return r;\r\n };\r\n\r\n\r\n /*\r\n * Return the value of this BigNumber converted to a number primitive.\r\n */\r\n P.toNumber = function () {\r\n return +valueOf(this);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber rounded to sd significant digits\r\n * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r\n * necessary to represent the integer part of the value in fixed-point notation, then use\r\n * exponential notation.\r\n *\r\n * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r\n * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r\n *\r\n * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}'\r\n */\r\n P.toPrecision = function (sd, rm) {\r\n if (sd != null) intCheck(sd, 1, MAX);\r\n return format(this, sd, rm, 2);\r\n };\r\n\r\n\r\n /*\r\n * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r\n * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r\n * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r\n * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r\n * TO_EXP_NEG, return exponential notation.\r\n *\r\n * [b] {number} Integer, 2 to ALPHABET.length inclusive.\r\n *\r\n * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}'\r\n */\r\n P.toString = function (b) {\r\n var str,\r\n n = this,\r\n s = n.s,\r\n e = n.e;\r\n\r\n // Infinity or NaN?\r\n if (e === null) {\r\n if (s) {\r\n str = 'Infinity';\r\n if (s < 0) str = '-' + str;\r\n } else {\r\n str = 'NaN';\r\n }\r\n } else {\r\n if (b == null) {\r\n str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r\n ? toExponential(coeffToString(n.c), e)\r\n : toFixedPoint(coeffToString(n.c), e, '0');\r\n } else if (b === 10 && alphabetHasNormalDecimalDigits) {\r\n n = round(new BigNumber(n), DECIMAL_PLACES + e + 1, ROUNDING_MODE);\r\n str = toFixedPoint(coeffToString(n.c), n.e, '0');\r\n } else {\r\n intCheck(b, 2, ALPHABET.length, 'Base');\r\n str = convertBase(toFixedPoint(coeffToString(n.c), e, '0'), 10, b, s, true);\r\n }\r\n\r\n if (s < 0 && n.c[0]) str = '-' + str;\r\n }\r\n\r\n return str;\r\n };\r\n\r\n\r\n /*\r\n * Return as toString, but do not accept a base argument, and include the minus sign for\r\n * negative zero.\r\n */\r\n P.valueOf = P.toJSON = function () {\r\n return valueOf(this);\r\n };\r\n\r\n\r\n P._isBigNumber = true;\r\n\r\n if (configObject != null) BigNumber.set(configObject);\r\n\r\n return BigNumber;\r\n }\r\n\r\n\r\n // PRIVATE HELPER FUNCTIONS\r\n\r\n // These functions don't need access to variables,\r\n // e.g. DECIMAL_PLACES, in the scope of the `clone` function above.\r\n\r\n\r\n function bitFloor(n) {\r\n var i = n | 0;\r\n return n > 0 || n === i ? i : i - 1;\r\n }\r\n\r\n\r\n // Return a coefficient array as a string of base 10 digits.\r\n function coeffToString(a) {\r\n var s, z,\r\n i = 1,\r\n j = a.length,\r\n r = a[0] + '';\r\n\r\n for (; i < j;) {\r\n s = a[i++] + '';\r\n z = LOG_BASE - s.length;\r\n for (; z--; s = '0' + s);\r\n r += s;\r\n }\r\n\r\n // Determine trailing zeros.\r\n for (j = r.length; r.charCodeAt(--j) === 48;);\r\n\r\n return r.slice(0, j + 1 || 1);\r\n }\r\n\r\n\r\n // Compare the value of BigNumbers x and y.\r\n function compare(x, y) {\r\n var a, b,\r\n xc = x.c,\r\n yc = y.c,\r\n i = x.s,\r\n j = y.s,\r\n k = x.e,\r\n l = y.e;\r\n\r\n // Either NaN?\r\n if (!i || !j) return null;\r\n\r\n a = xc && !xc[0];\r\n b = yc && !yc[0];\r\n\r\n // Either zero?\r\n if (a || b) return a ? b ? 0 : -j : i;\r\n\r\n // Signs differ?\r\n if (i != j) return i;\r\n\r\n a = i < 0;\r\n b = k == l;\r\n\r\n // Either Infinity?\r\n if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1;\r\n\r\n // Compare exponents.\r\n if (!b) return k > l ^ a ? 1 : -1;\r\n\r\n j = (k = xc.length) < (l = yc.length) ? k : l;\r\n\r\n // Compare digit by digit.\r\n for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1;\r\n\r\n // Compare lengths.\r\n return k == l ? 0 : k > l ^ a ? 1 : -1;\r\n }\r\n\r\n\r\n /*\r\n * Check that n is a primitive number, an integer, and in range, otherwise throw.\r\n */\r\n function intCheck(n, min, max, name) {\r\n if (n < min || n > max || n !== mathfloor(n)) {\r\n throw Error\r\n (bignumberError + (name || 'Argument') + (typeof n == 'number'\r\n ? n < min || n > max ? ' out of range: ' : ' not an integer: '\r\n : ' not a primitive number: ') + String(n));\r\n }\r\n }\r\n\r\n\r\n // Assumes finite n.\r\n function isOdd(n) {\r\n var k = n.c.length - 1;\r\n return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0;\r\n }\r\n\r\n\r\n function toExponential(str, e) {\r\n return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) +\r\n (e < 0 ? 'e' : 'e+') + e;\r\n }\r\n\r\n\r\n function toFixedPoint(str, e, z) {\r\n var len, zs;\r\n\r\n // Negative exponent?\r\n if (e < 0) {\r\n\r\n // Prepend zeros.\r\n for (zs = z + '.'; ++e; zs += z);\r\n str = zs + str;\r\n\r\n // Positive exponent\r\n } else {\r\n len = str.length;\r\n\r\n // Append zeros.\r\n if (++e > len) {\r\n for (zs = z, e -= len; --e; zs += z);\r\n str += zs;\r\n } else if (e < len) {\r\n str = str.slice(0, e) + '.' + str.slice(e);\r\n }\r\n }\r\n\r\n return str;\r\n }\r\n\r\n\r\n // EXPORT\r\n\r\n\r\n BigNumber = clone();\r\n BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r\n\r\n // AMD.\r\n if (typeof define == 'function' && define.amd) {\r\n define(function () { return BigNumber; });\r\n\r\n // Node.js and other environments that support module.exports.\r\n } else if (typeof module != 'undefined' && module.exports) {\r\n module.exports = BigNumber;\r\n\r\n // Browser.\r\n } else {\r\n if (!globalObject) {\r\n globalObject = typeof self != 'undefined' && self ? self : window;\r\n }\r\n\r\n globalObject.BigNumber = BigNumber;\r\n }\r\n})(this);\r\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst bignumber_js_1 = require(\"bignumber.js\");\nclass Ar {\n /**\n * Method to take a string value and return a bignumber object.\n *\n * @protected\n * @type {Function}\n * @memberof Arweave\n */\n BigNum;\n constructor() {\n // Configure and assign the constructor function for the bignumber library.\n this.BigNum = (value, decimals) => {\n let instance = bignumber_js_1.BigNumber.clone({ DECIMAL_PLACES: decimals });\n return new instance(value);\n };\n }\n winstonToAr(winstonString, { formatted = false, decimals = 12, trim = true } = {}) {\n let number = this.stringToBigNum(winstonString, decimals).shiftedBy(-12);\n return formatted ? number.toFormat(decimals) : number.toFixed(decimals);\n }\n arToWinston(arString, { formatted = false } = {}) {\n let number = this.stringToBigNum(arString).shiftedBy(12);\n return formatted ? number.toFormat() : number.toFixed(0);\n }\n compare(winstonStringA, winstonStringB) {\n let a = this.stringToBigNum(winstonStringA);\n let b = this.stringToBigNum(winstonStringB);\n return a.comparedTo(b);\n }\n isEqual(winstonStringA, winstonStringB) {\n return this.compare(winstonStringA, winstonStringB) === 0;\n }\n isLessThan(winstonStringA, winstonStringB) {\n let a = this.stringToBigNum(winstonStringA);\n let b = this.stringToBigNum(winstonStringB);\n return a.isLessThan(b);\n }\n isGreaterThan(winstonStringA, winstonStringB) {\n let a = this.stringToBigNum(winstonStringA);\n let b = this.stringToBigNum(winstonStringB);\n return a.isGreaterThan(b);\n }\n add(winstonStringA, winstonStringB) {\n let a = this.stringToBigNum(winstonStringA);\n let b = this.stringToBigNum(winstonStringB);\n return a.plus(winstonStringB).toFixed(0);\n }\n sub(winstonStringA, winstonStringB) {\n let a = this.stringToBigNum(winstonStringA);\n let b = this.stringToBigNum(winstonStringB);\n return a.minus(winstonStringB).toFixed(0);\n }\n stringToBigNum(stringValue, decimalPlaces = 12) {\n return this.BigNum(stringValue, decimalPlaces);\n }\n}\nexports.default = Ar;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass Api {\n METHOD_GET = \"GET\";\n METHOD_POST = \"POST\";\n config;\n constructor(config) {\n this.applyConfig(config);\n }\n applyConfig(config) {\n this.config = this.mergeDefaults(config);\n }\n getConfig() {\n return this.config;\n }\n mergeDefaults(config) {\n const protocol = config.protocol || \"http\";\n const port = config.port || (protocol === \"https\" ? 443 : 80);\n return {\n host: config.host || \"127.0.0.1\",\n protocol,\n port,\n timeout: config.timeout || 20000,\n logging: config.logging || false,\n logger: config.logger || console.log,\n network: config.network,\n };\n }\n async get(endpoint, config) {\n return await this.request(endpoint, { ...config, method: this.METHOD_GET });\n }\n async post(endpoint, body, config) {\n const headers = new Headers(config?.headers || {});\n if (!headers.get(\"content-type\")?.includes(\"application/json\")) {\n headers.append(\"content-type\", \"application/json\");\n }\n headers.append(\"accept\", \"application/json, text/plain, */*\");\n return await this.request(endpoint, {\n ...config,\n method: this.METHOD_POST,\n body: typeof body !== \"string\" ? JSON.stringify(body) : body,\n headers,\n });\n }\n async request(endpoint, init) {\n const headers = new Headers(init?.headers || {});\n const baseURL = `${this.config.protocol}://${this.config.host}:${this.config.port}`;\n /* responseType is purely for backwards compatibility with external apps */\n const responseType = init?.responseType;\n delete init?.responseType;\n if (endpoint.startsWith(\"/\")) {\n endpoint = endpoint.slice(1);\n }\n if (this.config.network) {\n headers.append(\"x-network\", this.config.network);\n }\n if (this.config.logging) {\n this.config.logger(`Requesting: ${baseURL}/${endpoint}`);\n }\n let res = await fetch(`${baseURL}/${endpoint}`, {\n ...(init || {}),\n headers,\n });\n if (this.config.logging) {\n this.config.logger(`Response: ${res.url} - ${res.status}`);\n }\n const contentType = res.headers.get(\"content-type\");\n const charset = contentType?.match(/charset=([^()<>@,;:\\\"/[\\]?.=\\s]*)/i)?.[1];\n const response = res;\n const decodeText = async () => {\n if (charset) {\n try {\n response.data = new TextDecoder(charset).decode(await res.arrayBuffer());\n }\n catch (e) {\n response.data = (await res.text());\n }\n }\n else {\n response.data = (await res.text());\n }\n };\n if (responseType === \"arraybuffer\") {\n response.data = (await res.arrayBuffer());\n }\n else if (responseType === \"text\") {\n await decodeText();\n }\n else if (responseType === \"webstream\") {\n response.data = addAsyncIterator(res.body);\n }\n else {\n /** axios defaults to JSON, and then text, we mimic the behaviour */\n try {\n let test = await res.clone().json();\n if (typeof test !== \"object\") {\n await decodeText();\n }\n else {\n response.data = (await res.json());\n }\n test = null;\n }\n catch {\n await decodeText();\n }\n }\n return response;\n }\n}\nexports.default = Api;\n// | ReadableStream<Uint8Array>\nconst addAsyncIterator = (body) => {\n const bodyWithIter = body;\n if (typeof bodyWithIter[Symbol.asyncIterator] === \"undefined\") {\n bodyWithIter[Symbol.asyncIterator] = webIiterator(body);\n }\n return bodyWithIter;\n};\nconst webIiterator = function (stream) {\n return async function* iteratorGenerator() {\n const reader = stream.getReader(); //lock\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n return;\n yield value;\n }\n }\n finally {\n reader.releaseLock(); //unlock\n }\n };\n};\n","'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.concatBuffers = concatBuffers;\nexports.b64UrlToString = b64UrlToString;\nexports.bufferToString = bufferToString;\nexports.stringToBuffer = stringToBuffer;\nexports.stringToB64Url = stringToB64Url;\nexports.b64UrlToBuffer = b64UrlToBuffer;\nexports.bufferTob64 = bufferTob64;\nexports.bufferTob64Url = bufferTob64Url;\nexports.b64UrlEncode = b64UrlEncode;\nexports.b64UrlDecode = b64UrlDecode;\nconst B64js = require(\"base64-js\");\nfunction concatBuffers(buffers) {\n let total_length = 0;\n for (let i = 0; i < buffers.length; i++) {\n total_length += buffers[i].byteLength;\n }\n let temp = new Uint8Array(total_length);\n let offset = 0;\n temp.set(new Uint8Array(buffers[0]), offset);\n offset += buffers[0].byteLength;\n for (let i = 1; i < buffers.length; i++) {\n temp.set(new Uint8Array(buffers[i]), offset);\n offset += buffers[i].byteLength;\n }\n return temp;\n}\nfunction b64UrlToString(b64UrlString) {\n let buffer = b64UrlToBuffer(b64UrlString);\n return bufferToString(buffer);\n}\nfunction bufferToString(buffer) {\n return new TextDecoder(\"utf-8\", { fatal: true }).decode(buffer);\n}\nfunction stringToBuffer(string) {\n return new TextEncoder().encode(string);\n}\nfunction stringToB64Url(string) {\n return bufferTob64Url(stringToBuffer(string));\n}\nfunction b64UrlToBuffer(b64UrlString) {\n return new Uint8Array(B64js.toByteArray(b64UrlDecode(b64UrlString)));\n}\nfunction bufferTob64(buffer) {\n return B64js.fromByteArray(new Uint8Array(buffer));\n}\nfunction bufferTob64Url(buffer) {\n return b64UrlEncode(bufferTob64(buffer));\n}\nfunction b64UrlEncode(b64UrlString) {\n try {\n return b64UrlString\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/\\=/g, \"\");\n }\n catch (error) {\n throw new Error(\"Failed to encode string\", { cause: error });\n }\n}\nfunction b64UrlDecode(b64UrlString) {\n try {\n b64UrlString = b64UrlString.replace(/\\-/g, \"+\").replace(/\\_/g, \"/\");\n let padding;\n b64UrlString.length % 4 == 0\n ? (padding = 0)\n : (padding = 4 - (b64UrlString.length % 4));\n return b64UrlString.concat(\"=\".repeat(padding));\n }\n catch (error) {\n throw new Error(\"Failed to decode string\", { cause: error });\n }\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ArweaveUtils = require(\"../utils\");\nclass WebCryptoDriver {\n keyLength = 4096;\n publicExponent = 0x10001;\n hashAlgorithm = \"sha256\";\n driver;\n constructor() {\n if (!this.detectWebCrypto()) {\n throw new Error(\"SubtleCrypto not available!\");\n }\n this.driver = crypto.subtle;\n }\n async generateJWK() {\n let cryptoKey = await this.driver.generateKey({\n name: \"RSA-PSS\",\n modulusLength: 4096,\n publicExponent: new Uint8Array([0x01, 0x00, 0x01]),\n hash: {\n name: \"SHA-256\",\n },\n }, true, [\"sign\"]);\n let jwk = await this.driver.exportKey(\"jwk\", cryptoKey.privateKey);\n return {\n kty: jwk.kty,\n e: jwk.e,\n n: jwk.n,\n d: jwk.d,\n p: jwk.p,\n q: jwk.q,\n dp: jwk.dp,\n dq: jwk.dq,\n qi: jwk.qi,\n };\n }\n async sign(jwk, data, { saltLength } = {}) {\n let signature = await this.driver.sign({\n name: \"RSA-PSS\",\n saltLength: saltLength ?? 32,\n }, await this.jwkToCryptoKey(jwk), data);\n return new Uint8Array(signature);\n }\n async hash(data, algorithm = \"SHA-256\") {\n let digest = await this.driver.digest(algorithm, data);\n return new Uint8Array(digest);\n }\n async verify(publicModulus, data, signature) {\n const publicKey = {\n kty: \"RSA\",\n e: \"AQAB\",\n n: publicModulus,\n };\n const key = await this.jwkToPublicCryptoKey(publicKey);\n const digest = await this.driver.digest(\"SHA-256\", data);\n const salt0 = await this.driver.verify({\n name: \"RSA-PSS\",\n saltLength: 0,\n }, key, signature, data);\n const salt32 = await this.driver.verify({\n name: \"RSA-PSS\",\n saltLength: 32,\n }, key, signature, data);\n // saltN's salt-length is derived from a formula described here\n // https://developer.mozilla.org/en-US/docs/Web/API/RsaPssParams\n const saltLengthN = Math.ceil((key.algorithm.modulusLength - 1) / 8) -\n digest.byteLength -\n 2;\n const saltN = await this.driver.verify({\n name: \"RSA-PSS\",\n saltLength: saltLengthN,\n }, key, signature, data);\n const result = salt0 || salt32 || saltN;\n if (!result) {\n const details = {\n algorithm: key.algorithm.name,\n modulusLength: key.algorithm.modulusLength,\n keyUsages: key.usages,\n saltLengthsAttempted: `0, 32, ${saltLengthN}`,\n };\n console.warn(\"Transaction Verification Failed! \\n\", `Details: ${JSON.stringify(details, null, 2)} \\n`, \"N.B. ArweaveJS is only guaranteed to verify txs created using ArweaveJS.\");\n }\n return result;\n }\n async jwkToCryptoKey(jwk) {\n return this.driver.importKey(\"jwk\", jwk, {\n name: \"RSA-PSS\",\n hash: {\n name: \"SHA-256\",\n },\n }, false, [\"sign\"]);\n }\n async jwkToPublicCryptoKey(publicJwk) {\n return this.driver.importKey(\"jwk\", publicJwk, {\n name: \"RSA-PSS\",\n hash: {\n name: \"SHA-256\",\n },\n }, false, [\"verify\"]);\n }\n detectWebCrypto() {\n if (typeof crypto === \"undefined\") {\n return false;\n }\n const subtle = crypto?.subtle;\n if (subtle === undefined) {\n return false;\n }\n const names = [\n \"generateKey\",\n \"importKey\",\n \"exportKey\",\n \"digest\",\n \"sign\",\n ];\n return names.every((name) => typeof subtle[name] === \"function\");\n }\n async encrypt(data, key, salt) {\n const initialKey = await this.driver.importKey(\"raw\", typeof key == \"string\" ? ArweaveUtils.stringToBuffer(key) : key, {\n name: \"PBKDF2\",\n length: 32,\n }, false, [\"deriveKey\"]);\n // const salt = ArweaveUtils.stringToBuffer(\"salt\");\n // create a random string for deriving the key\n // const salt = this.driver.randomBytes(16).toString('hex');\n const derivedkey = await this.driver.deriveKey({\n name: \"PBKDF2\",\n salt: salt\n ? ArweaveUtils.stringToBuffer(salt)\n : ArweaveUtils.stringToBuffer(\"salt\"),\n iterations: 100000,\n hash: \"SHA-256\",\n }, initialKey, {\n name: \"AES-CBC\",\n length: 256,\n }, false, [\"encrypt\", \"decrypt\"]);\n const iv = new Uint8Array(16);\n crypto.getRandomValues(iv);\n const encryptedData = await this.driver.encrypt({\n name: \"AES-CBC\",\n iv: iv,\n }, derivedkey, data);\n return ArweaveUtils.concatBuffers([iv, encryptedData]);\n }\n async decrypt(encrypted, key, salt) {\n const initialKey = await this.driver.importKey(\"raw\", typeof key == \"string\" ? ArweaveUtils.stringToBuffer(key) : key, {\n name: \"PBKDF2\",\n length: 32,\n }, false, [\"deriveKey\"]);\n // const salt = ArweaveUtils.stringToBuffer(\"pepper\");\n const derivedkey = await this.driver.deriveKey({\n name: \"PBKDF2\",\n salt: salt\n ? ArweaveUtils.stringToBuffer(salt)\n : ArweaveUtils.stringToBuffer(\"salt\"),\n iterations: 100000,\n hash: \"SHA-256\",\n }, initialKey, {\n name: \"AES-CBC\",\n length: 256,\n }, false, [\"encrypt\", \"decrypt\"]);\n const iv = encrypted.slice(0, 16);\n const data = await this.driver.decrypt({\n name: \"AES-CBC\",\n iv: iv,\n }, derivedkey, encrypted.slice(16));\n // We're just using concat to convert from an array buffer to uint8array\n return ArweaveUtils.concatBuffers([data]);\n }\n}\nexports.default = WebCryptoDriver;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nclass Network {\n api;\n constructor(api) {\n this.api = api;\n }\n getInfo() {\n return this.api.get(`info`).then((response) => {\n return response.data;\n });\n }\n getPeers() {\n return this.api.get(`peers`).then((response) => {\n return response.data;\n });\n }\n}\nexports.default = Network;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getError = getError;\nclass ArweaveError extends Error {\n type;\n response;\n constructor(type, optional = {}) {\n if (optional.message) {\n super(optional.message);\n }\n else {\n super();\n }\n this.type = type;\n this.response = optional.response;\n }\n getType() {\n return this.type;\n }\n}\nexports.default = ArweaveError;\n// Safely get error string\n// from a response, falling back to\n// resp.data, statusText or 'unknown'.\n// Note: a wrongly set content-type can\n// cause what is a json response to be interepted\n// as a string or Buffer, so we handle that too.\nfunction getError(resp) {\n let data = resp.data;\n if (typeof resp.data === \"string\") {\n try {\n data = JSON.parse(resp.data);\n }\n catch (e) { }\n }\n if (resp.data instanceof ArrayBuffer || resp.data instanceof Uint8Array) {\n try {\n data = JSON.parse(data.toString());\n }\n catch (e) { }\n }\n return data ? data.error || data : resp.statusText || \"unknown\";\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.default = deepHash;\nconst common_1 = require(\"../common\");\nasync function deepHash(data) {\n if (Array.isArray(data)) {\n const tag = common_1.default.utils.concatBuffers([\n common_1.default.utils.stringToBuffer(\"list\"),\n common_1.default.utils.stringToBuffer(data.length.toString()),\n ]);\n return await deepHashChunks(data, await common_1.default.crypto.hash(tag, \"SHA-384\"));\n }\n const tag = common_1.default.utils.concatBuffers([\n common_1.default.utils.stringToBuffer(\"blob\"),\n common_1.default.utils.stringToBuffer(data.byteLength.toString()),\n ]);\n const taggedHash = common_1.default.utils.concatBuffers([\n await common_1.default.crypto.hash(tag, \"SHA-384\"),\n await common_1.default.crypto.hash(data, \"SHA-384\"),\n ]);\n return await common_1.default.crypto.hash(taggedHash, \"SHA-384\");\n}\nasync function deepHashChunks(chunks, acc) {\n if (chunks.length < 1) {\n return acc;\n }\n const hashPair = common_1.default.utils.concatBuffers([\n acc,\n await deepHash(chunks[0]),\n ]);\n const newAcc = await common_1.default.crypto.hash(hashPair, \"SHA-384\");\n return await deepHashChunks(chunks.slice(1), newAcc);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.arrayCompare = exports.MIN_CHUNK_SIZE = exports.MAX_CHUNK_SIZE = void 0;\nexports.chunkData = chunkData;\nexports.generateLeaves = generateLeaves;\nexports.computeRootHash = computeRootHash;\nexports.generateTree = generateTree;\nexports.generateTransactionChunks = generateTransactionChunks;\nexports.buildLayers = buildLayers;\nexports.generateProofs = generateProofs;\nexports.arrayFlatten = arrayFlatten;\nexports.intToBuffer = intToBuffer;\nexports.bufferToInt = bufferToInt;\nexports.validatePath = validatePath;\nexports.debug = debug;\n/**\n * @see {@link https://github.com/ArweaveTeam/arweave/blob/fbc381e0e36efffa45d13f2faa6199d3766edaa2/apps/arweave/src/ar_merkle.erl}\n */\nconst common_1 = require(\"../common\");\nconst utils_1 = require(\"./utils\");\nexports.MAX_CHUNK_SIZE = 256 * 1024;\nexports.MIN_CHUNK_SIZE = 32 * 1024;\nconst NOTE_SIZE = 32;\nconst HASH_SIZE = 32;\n/**\n * Takes the input data and chunks it into (mostly) equal sized chunks.\n * The last chunk will be a bit smaller as it contains the remainder\n * from the chunking process.\n */\nasync function chunkData(data) {\n let chunks = [];\n let rest = data;\n let cursor = 0;\n while (rest.byteLength >= exports.MAX_CHUNK_SIZE) {\n let chunkSize = exports.MAX_CHUNK_SIZE;\n // If the total bytes left will produce a chunk < MIN_CHUNK_SIZE,\n // then adjust the amount we put in this 2nd last chunk.\n let nextChunkSize = rest.byteLength - exports.MAX_CHUNK_SIZE;\n if (nextChunkSize > 0 && nextChunkSize < exports.MIN_CHUNK_SIZE) {\n chunkSize = Math.ceil(rest.byteLength / 2);\n // console.log(`Last chunk will be: ${nextChunkSize} which is below ${MIN_CHUNK_SIZE}, adjusting current to ${chunkSize} with ${rest.byteLength} left.`)\n }\n const chunk = rest.slice(0, chunkSize);\n const dataHash = await common_1.default.crypto.hash(chunk);\n cursor += chunk.byteLength;\n chunks.push({\n dataHash,\n minByteRange: cursor - chunk.byteLength,\n maxByteRange: cursor,\n });\n rest = rest.slice(chunkSize);\n }\n chunks.push({\n dataHash: await common_1.default.crypto.hash(rest),\n minByteRange: cursor,\n maxByteRange: cursor + rest.byteLength,\n });\n return chunks;\n}\nasync function generateLeaves(chunks) {\n return Promise.all(chunks.map(async ({ dataHash, minByteRange, maxByteRange }) => {\n return {\n type: \"leaf\",\n id: await hash(await Promise.all([hash(dataHash), hash(intToBuffer(maxByteRange))])),\n dataHash: dataHash,\n minByteRange,\n maxByteRange,\n };\n }));\n}\n/**\n * Builds an arweave merkle tree and gets the root hash for the given input.\n */\nasync function computeRootHash(data) {\n const rootNode = await generateTree(data);\n return rootNode.id;\n}\nasync function generateTree(data) {\n const rootNode = await buildLayers(await generateLeaves(await chunkData(data)));\n return rootNode;\n}\n/**\n * Generates the data_root, chunks & proofs\n * needed for a transaction.\n *\n * This also checks if the last chunk is a zero-length\n * chunk and discards that chunk and proof if so.\n * (we do not need to upload this zero length chunk)\n *\n * @param data\n */\nasync function generateTransactionChunks(data) {\n const chunks = await chunkData(data);\n const leaves = await generateLeaves(chunks);\n const root = await buildLayers(leaves);\n const proofs = await generateProofs(root);\n // Discard the last chunk & proof if it's zero length.\n const lastChunk = chunks.slice(-1)[0];\n if (lastChunk.maxByteRange - lastChunk.minByteRange === 0) {\n chunks.splice(chunks.length - 1, 1);\n proofs.splice(proofs.length - 1, 1);\n }\n return {\n data_root: root.id,\n chunks,\n proofs,\n };\n}\n/**\n * Starting with the bottom layer of leaf nodes, hash every second pair\n * into a new branch node, push those branch nodes onto a new layer,\n * and then recurse, building up the tree to it's root, where the\n * layer only consists of two items.\n */\nasync function buildLayers(nodes, level = 0) {\n // If there is only 1 node left, this is going to be the root node\n if (nodes.length < 2) {\n const root = nodes[0];\n // console.log(\"Root layer\", root);\n return root;\n }\n const nextLayer = [];\n for (let i = 0; i < nodes.length; i += 2) {\n nextLayer.push(await hashBranch(nodes[i], nodes[i + 1]));\n }\n // console.log(\"Layer\", nextLayer);\n return buildLayers(nextLayer, level + 1);\n}\n/**\n * Recursively search through all branches of the tree,\n * and generate a proof for each leaf node.\n */\nfunction generateProofs(root) {\n const proofs = resolveBranchProofs(root);\n if (!Array.isArray(proofs)) {\n return [proofs];\n }\n return arrayFlatten(proofs);\n}\nfunction resolveBranchProofs(node, proof = new Uint8Array(), depth = 0) {\n if (node.type == \"leaf\") {\n return {\n offset: node.maxByteRange - 1,\n proof: (0, utils_1.concatBuffers)([\n proof,\n node.dataHash,\n intToBuffer(node.maxByteRange),\n ]),\n };\n }\n if (node.type == \"branch\") {\n const partialProof = (0, utils_1.concatBuffers)([\n proof,\n node.leftChild.id,\n node.rightChild.id,\n intToBuffer(node.byteRange),\n ]);\n return [\n resolveBranchProofs(node.leftChild, partialProof, depth + 1),\n resolveBranchProofs(node.rightChild, partialProof, depth + 1),\n ];\n }\n throw new Error(`Unexpected node type`);\n}\nfunction arrayFlatten(input) {\n const flat = [];\n input.forEach((item) => {\n if (Array.isArray(item)) {\n flat.push(...arrayFlatten(item));\n }\n else {\n flat.push(item);\n }\n });\n return flat;\n}\nasync function hashBranch(left, right) {\n if (!right) {\n return left;\n }\n let branch = {\n type: \"branch\",\n id: await hash([\n await hash(left.id),\n await hash(right.id),\n await hash(intToBuffer(left.maxByteRange)),\n ]),\n byteRange: left.maxByteRange,\n maxByteRange: right.maxByteRange,\n leftChild: left,\n rightChild: right,\n };\n return branch;\n}\nasync function hash(data) {\n if (Array.isArray(data)) {\n data = common_1.default.utils.concatBuffers(data);\n }\n return new Uint8Array(await common_1.default.crypto.hash(data));\n}\nfunction intToBuffer(note) {\n const buffer = new Uint8Array(NOTE_SIZE);\n for (var i = buffer.length - 1; i >= 0; i--) {\n var byte = note % 256;\n buffer[i] = byte;\n note = (note - byte) / 256;\n }\n return buffer;\n}\nfunction bufferToInt(buffer) {\n let value = 0;\n for (var i = 0; i < buffer.length; i++) {\n value *= 256;\n value += buffer[i];\n }\n return value;\n}\nconst arrayCompare = (a, b) => a.every((value, index) => b[index] === value);\nexports.arrayCompare = arrayCompare;\nasync function validatePath(id, dest, leftBound, rightBound, path) {\n if (rightBound <= 0) {\n return false;\n }\n if (dest >= rightBound) {\n return validatePath(id, 0, rightBound - 1, rightBound, path);\n }\n if (dest < 0) {\n return validatePath(id, 0, 0, rightBound, path);\n }\n if (path.length == HASH_SIZE + NOTE_SIZE) {\n const pathData = path.slice(0, HASH_SIZE);\n const endOffsetBuffer = path.slice(pathData.length, pathData.length + NOTE_SIZE);\n const pathDataHash = await hash([\n await hash(pathData),\n await hash(endOffsetBuffer),\n ]);\n let result = (0, exports.arrayCompare)(id, pathDataHash);\n if (result) {\n return {\n offset: rightBound - 1,\n leftBound: leftBound,\n rightBound: rightBound,\n chunkSize: rightBound - leftBound,\n };\n }\n return false;\n }\n const left = path.slice(0, HASH_SIZE);\n const right = path.slice(left.length, left.length + HASH_SIZE);\n const offsetBuffer = path.slice(left.length + right.length, left.length + right.length + NOTE_SIZE);\n const offset = bufferToInt(offsetBuffer);\n const remainder = path.slice(left.length + right.length + offsetBuffer.length);\n const pathHash = await hash([\n await hash(left),\n await hash(right),\n await hash(offsetBuffer),\n ]);\n if ((0, exports.arrayCompare)(id, pathHash)) {\n if (dest < offset) {\n return await validatePath(left, dest, leftBound, Math.min(rightBound, offset), remainder);\n }\n return await validatePath(right, dest, Math.max(leftBound, offset), rightBound, remainder);\n }\n return false;\n}\n/**\n * Inspect an arweave chunk proof.\n * Takes proof, parses, reads and displays the values for console logging.\n * One proof section per line\n * Format: left,right,offset => hash\n */\nasync function debug(proof, output = \"\") {\n if (proof.byteLength < 1) {\n return output;\n }\n const left = proof.slice(0, HASH_SIZE);\n const right = proof.slice(left.length, left.length + HASH_SIZE);\n const offsetBuffer = proof.slice(left.length + right.length, left.length + right.length + NOTE_SIZE);\n const offset = bufferToInt(offsetBuffer);\n const remainder = proof.slice(left.length + right.length + offsetBuffer.length);\n const pathHash = await hash([\n await hash(left),\n await hash(right),\n await hash(offsetBuffer),\n ]);\n const updatedOutput = `${output}\\n${JSON.stringify(Buffer.from(left))},${JSON.stringify(Buffer.from(right))},${offset} => ${JSON.stringify(pathHash)}`;\n return debug(remainder, updatedOutput);\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Tag = void 0;\nconst ArweaveUtils = require(\"./utils\");\nconst deepHash_1 = require(\"./deepHash\");\nconst merkle_1 = require(\"./merkle\");\nclass BaseObject {\n get(field, options) {\n if (!Object.getOwnPropertyNames(this).includes(field)) {\n throw new Error(`Field \"${field}\" is not a property of the Arweave Transaction class.`);\n }\n // Handle fields that are Uint8Arrays.\n // To maintain compat we encode them to b64url\n // if decode option is not specificed.\n if (this[field] instanceof Uint8Array) {\n if (options && options.decode && options.string) {\n return ArweaveUtils.bufferToString(this[field]);\n }\n if (options && options.decode && !options.string) {\n return this[field];\n }\n return ArweaveUtils.bufferTob64Url(this[field]);\n }\n if (this[field] instanceof Array) {\n if (options?.decode !== undefined || options?.string !== undefined) {\n if (field === \"tags\") {\n console.warn(`Did you mean to use 'transaction[\"tags\"]' ?`);\n }\n throw new Error(`Cannot decode or stringify an array.`);\n }\n return this[field];\n }\n if (options && options.decode == true) {\n if (options && options.string) {\n return ArweaveUtils.b64UrlToString(this[field]);\n }\n return ArweaveUtils.b64UrlToBuffer(this[field]);\n }\n return this[field];\n }\n}\nclass Tag extends BaseObject {\n name;\n value;\n constructor(name, value, decode = false) {\n super();\n this.name = name;\n this.value = value;\n }\n}\nexports.Tag = Tag;\nclass Transaction extends BaseObject {\n format = 2;\n id = \"\";\n last_tx = \"\";\n owner = \"\";\n tags = [];\n target = \"\";\n quantity = \"0\";\n data_size = \"0\";\n data = new Uint8Array();\n data_root = \"\";\n reward = \"0\";\n signature = \"\";\n // Computed when needed.\n chunks;\n constructor(attributes = {}) {\n super();\n Object.assign(this, attributes);\n // If something passes in a Tx that has been toJSON'ed and back,\n // or where the data was filled in from /tx/data endpoint.\n // data will be b64url encoded, so decode it.\n if (typeof this.data === \"string\") {\n this.data = ArweaveUtils.b64UrlToBuffer(this.data);\n }\n if (attributes.tags) {\n this.tags = attributes.tags.map((tag) => {\n return new Tag(tag.name, tag.value);\n });\n }\n }\n addTag(name, value) {\n this.tags.push(new Tag(ArweaveUtils.stringToB64Url(name), ArweaveUtils.stringToB64Url(value)));\n }\n toJSON() {\n return {\n format: this.format,\n id: this.id,\n last_tx: this.last_tx,\n owner: this.owner,\n tags: this.tags,\n target: this.target,\n quantity: this.quantity,\n data: ArweaveUtils.bufferTob64Url(this.data),\n data_size: this.data_size,\n data_root: this.data_root,\n data_tree: this.data_tree,\n reward: this.reward,\n signature: this.signature,\n };\n }\n setOwner(owner) {\n this.owner = owner;\n }\n setSignature({ id, owner, reward, tags, signature, }) {\n this.id = id;\n this.owner = owner;\n if (reward)\n this.reward = reward;\n if (tags)\n this.tags = tags;\n this.signature = signature;\n }\n async prepareChunks(data) {\n // Note: we *do not* use `this.data`, the caller may be\n // operating on a transaction with an zero length data field.\n // This function computes the chunks for the data passed in and\n // assigns the result to this transaction. It should not read the\n // data *from* this transaction.\n if (!this.chunks && data.byteLength > 0) {\n this.chunks = await (0, merkle_1.generateTransactionChunks)(data);\n this.data_root = ArweaveUtils.bufferTob64Url(this.chunks.data_root);\n }\n if (!this.chunks && data.byteLength === 0) {\n this.chunks = {\n chunks: [],\n data_root: new Uint8Array(),\n proofs: [],\n };\n this.data_root = \"\";\n }\n }\n // Returns a chunk in a format suitable for posting to /chunk.\n // Similar to `prepareChunks()` this does not operate `this.data`,\n // instead using the data passed in.\n getChunk(idx, data) {\n if (!this.chunks) {\n throw new Error(`Chunks have not been prepared`);\n }\n const proof = this.chunks.proofs[idx];\n const chunk = this.chunks.chunks[idx];\n return {\n data_root: this.data_root,\n data_size: this.data_size,\n data_path: ArweaveUtils.bufferTob64Url(proof.proof),\n offset: proof.offset.toString(),\n chunk: ArweaveUtils.bufferTob64Url(data.slice(chunk.minByteRange, chunk.maxByteRange)),\n };\n }\n async getSignatureData() {\n switch (this.format) {\n case 1:\n let tags = this.tags.reduce((accumulator, tag) => {\n return ArweaveUtils.concatBuffers([\n accumulator,\n tag.get(\"name\", { decode: true, string: false }),\n tag.get(\"value\", { decode: true, string: false }),\n ]);\n }, new Uint8Array());\n return ArweaveUtils.concatBuffers([\n this.get(\"owner\", { decode: true, string: false }),\n this.get(\"target\", { decode: true, string: false }),\n this.get(\"data\", { decode: true, string: false }),\n ArweaveUtils.stringToBuffer(this.quantity),\n ArweaveUtils.stringToBuffer(this.reward),\n this.get(\"last_tx\", { decode: true, string: false }),\n tags,\n ]);\n case 2:\n if (!this.data_root) {\n await this.prepareChunks(this.data);\n }\n const tagList = this.tags.map((tag) => [\n tag.get(\"name\", { decode: true, string: false }),\n tag.get(\"value\", { decode: true, string: false }),\n ]);\n return await (0, deepHash_1.default)([\n ArweaveUtils.stringToBuffer(this.format.toString()),\n this.get(\"owner\", { decode: true, string: false }),\n this.get(\"target\", { decode: true, string: false }),\n ArweaveUtils.stringToBuffer(this.quantity),\n ArweaveUtils.stringToBuffer(this.reward),\n this.get(\"last_tx\", { decode: true, string: false }),\n tagList,\n ArweaveUtils.stringToBuffer(this.data_size),\n this.get(\"data_root\", { decode: true, string: false }),\n ]);\n default:\n throw new Error(`Unexpected transaction format: ${this.format}`);\n }\n }\n}\nexports.default = Transaction;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.TransactionUploader = void 0;\nconst transaction_1 = require(\"./transaction\");\nconst ArweaveUtils = require(\"./utils\");\nconst error_1 = require(\"./error\");\nconst merkle_1 = require(\"./merkle\");\n// Maximum amount of chunks we will upload in the body.\nconst MAX_CHUNKS_IN_BODY = 1;\n// We assume these errors are intermitment and we can try again after a delay:\n// - not_joined\n// - timeout\n// - data_root_not_found (we may have hit a node that just hasn't seen it yet)\n// - exceeds_disk_pool_size_limit\n// We also try again after any kind of unexpected network errors\n// Errors from /chunk we should never try and continue on.\nconst FATAL_CHUNK_UPLOAD_ERRORS = [\n \"invalid_json\",\n \"chunk_too_big\",\n \"data_path_too_big\",\n \"offset_too_big\",\n \"data_size_too_big\",\n \"chunk_proof_ratio_not_attractive\",\n \"invalid_proof\",\n];\n// Amount we will delay on receiving an error response but do want to continue.\nconst ERROR_DELAY = 1000 * 40;\nclass TransactionUploader {\n api;\n chunkIndex = 0;\n txPosted = false;\n transaction;\n lastRequestTimeEnd = 0;\n totalErrors = 0; // Not serialized.\n data;\n lastResponseStatus = 0;\n lastResponseError = \"\";\n get isComplete() {\n return (this.txPosted &&\n this.chunkIndex === this.transaction.chunks.chunks.length);\n }\n get totalChunks() {\n return this.transaction.chunks.chunks.length;\n }\n get uploadedChunks() {\n return this.chunkIndex;\n }\n get pctComplete() {\n return Math.trunc((this.uploadedChunks / this.totalChunks) * 100);\n }\n constructor(api, transaction) {\n this.api = api;\n if (!transaction.id) {\n throw new Error(`Transaction is not signed`);\n }\n if (!transaction.chunks) {\n throw new Error(`Transaction chunks not prepared`);\n }\n // Make a copy of transaction, zeroing the data so we can serialize.\n this.data = transaction.data;\n this.transaction = new transaction_1.default(Object.assign({}, transaction, { data: new Uint8Array(0) }));\n }\n /**\n * Uploads the next part of the transaction.\n * On the first call this posts the transaction\n * itself and on any subsequent calls uploads the\n * next chunk until it completes.\n */\n async uploadChunk(chunkIndex_) {\n if (this.isComplete) {\n throw new Error(`Upload is already complete`);\n }\n if (this.lastResponseError !== \"\") {\n this.totalErrors++;\n }\n else {\n this.totalErrors = 0;\n }\n // We have been trying for about an hour receiving an\n // error every time, so eventually bail.\n if (this.totalErrors === 100) {\n throw new Error(`Unable to complete upload: ${this.lastResponseStatus}: ${this.lastResponseError}`);\n }\n let delay = this.lastResponseError === \"\"\n ? 0\n : Math.max(this.lastRequestTimeEnd + ERROR_DELAY - Date.now(), ERROR_DELAY);\n if (delay > 0) {\n // Jitter delay bcoz networks, subtract up to 30% from 40 seconds\n delay = delay - delay * Math.random() * 0.3;\n await new Promise((res) => setTimeout(res, delay));\n }\n this.lastResponseError = \"\";\n if (!this.txPosted) {\n await this.postTransaction();\n return;\n }\n if (chunkIndex_) {\n this.chunkIndex = chunkIndex_;\n }\n const chunk = this.transaction.getChunk(chunkIndex_ || this.chunkIndex, this.data);\n const chunkOk = await (0, merkle_1.validatePath)(this.transaction.chunks.data_root, parseInt(chunk.offset), 0, parseInt(chunk.data_size), ArweaveUtils.b64UrlToBuffer(chunk.data_path));\n if (!chunkOk) {\n throw new Error(`Unable to validate chunk ${this.chunkIndex}`);\n }\n // Catch network errors and turn them into objects with status -1 and an error message.\n const resp = await this.api\n .post(`chunk`, this.transaction.getChunk(this.chunkIndex, this.data))\n .catch((e) => {\n console.error(e.message);\n return { status: -1, data: { error: e.message } };\n });\n this.lastRequestTimeEnd = Date.now();\n this.lastResponseStatus = resp.status;\n if (this.lastResponseStatus == 200) {\n this.chunkIndex++;\n }\n else {\n this.lastResponseError = (0, error_1.getError)(resp);\n if (FATAL_CHUNK_UPLOAD_ERRORS.includes(this.lastResponseError)) {\n throw new Error(`Fatal error uploading chunk ${this.chunkIndex}: ${this.lastResponseError}`);\n }\n }\n }\n /**\n * Reconstructs an upload from its serialized state and data.\n * Checks if data matches the expected data_root.\n *\n * @param serialized\n * @param data\n */\n static async fromSerialized(api, serialized, data) {\n if (!serialized ||\n typeof serialized.chunkIndex !== \"number\" ||\n typeof serialized.transaction !== \"object\") {\n throw new Error(`Serialized object does not match expected format.`);\n }\n // Everything looks ok, reconstruct the TransactionUpload,\n // prepare the chunks again and verify the data_root matches\n var transaction = new transaction_1.default(serialized.transaction);\n if (!transaction.chunks) {\n await transaction.prepareChunks(data);\n }\n const upload = new TransactionUploader(api, transaction);\n // Copy the serialized upload information, and data passed in.\n upload.chunkIndex = serialized.chunkIndex;\n upload.lastRequestTimeEnd = serialized.lastRequestTimeEnd;\n upload.lastResponseError = serialized.lastResponseError;\n upload.lastResponseStatus = serialized.lastResponseStatus;\n upload.txPosted = serialized.txPosted;\n upload.data = data;\n if (upload.transaction.data_root !== serialized.transaction.data_root) {\n throw new Error(`Data mismatch: Uploader doesn't match provided data.`);\n }\n return upload;\n }\n /**\n * Reconstruct an upload from the tx metadata, ie /tx/<id>.\n *\n * @param api\n * @param id\n * @param data\n */\n static async fromTransactionId(api, id) {\n const resp = await api.get(`tx/${id}`);\n if (resp.status !== 200) {\n throw new Error(`Tx ${id} not found: ${resp.status}`);\n }\n const transaction = resp.data;\n transaction.data = new Uint8Array(0);\n const serialized = {\n txPosted: true,\n chunkIndex: 0,\n lastResponseError: \"\",\n lastRequestTimeEnd: 0,\n lastResponseStatus: 0,\n transaction,\n };\n return serialized;\n }\n toJSON() {\n return {\n chunkIndex: this.chunkIndex,\n transaction: this.transaction,\n lastRequestTimeEnd: this.lastRequestTimeEnd,\n lastResponseStatus: this.lastResponseStatus,\n lastResponseError: this.lastResponseError,\n txPosted: this.txPosted,\n };\n }\n // POST to /tx\n async postTransaction() {\n const uploadInBody = this.totalChunks <= MAX_CHUNKS_IN_BODY;\n if (uploadInBody) {\n // Post the transaction with data.\n this.transaction.data = this.data;\n const resp = await this.api.post(`tx`, this.transaction).catch((e) => {\n console.error(e);\n return { status: -1, data: { error: e.message } };\n });\n this.lastRequestTimeEnd = Date.now();\n this.lastResponseStatus = resp.status;\n this.transaction.data = new Uint8Array(0);\n if (resp.status >= 200 && resp.status < 300) {\n // We are complete.\n this.txPosted = true;\n this.chunkIndex = MAX_CHUNKS_IN_BODY;\n return;\n }\n this.lastResponseError = (0, error_1.getError)(resp);\n throw new Error(`Unable to upload transaction: ${resp.status}, ${this.lastResponseError}`);\n }\n // Post the transaction with no data.\n const resp = await this.api.post(`tx`, this.transaction);\n this.lastRequestTimeEnd = Date.now();\n this.lastResponseStatus = resp.status;\n if (!(resp.status >= 200 && resp.status < 300)) {\n this.lastResponseError = (0, error_1.getError)(resp);\n throw new Error(`Unable to upload transaction: ${resp.status}, ${this.lastResponseError}`);\n }\n this.txPosted = true;\n }\n}\nexports.TransactionUploader = TransactionUploader;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst error_1 = require(\"./lib/error\");\nconst transaction_1 = require(\"./lib/transaction\");\nconst ArweaveUtils = require(\"./lib/utils\");\nconst transaction_uploader_1 = require(\"./lib/transaction-uploader\");\nrequire(\"arconnect\");\nclass Transactions {\n api;\n crypto;\n chunks;\n constructor(api, crypto, chunks) {\n this.api = api;\n this.crypto = crypto;\n this.chunks = chunks;\n }\n async getTransactionAnchor() {\n const res = await this.api.get(`tx_anchor`);\n if (!res.data.match(/^[a-z0-9_-]{43,}/i) || !res.ok) {\n throw new Error(`Could not getTransactionAnchor. Received: ${res.data}. Status: ${res.status}, ${res.statusText}`);\n }\n return res.data;\n }\n async getPrice(byteSize, targetAddress) {\n let endpoint = targetAddress\n ? `price/${byteSize}/${targetAddress}`\n : `price/${byteSize}`;\n const res = await this.api.get(endpoint);\n if (!/^\\d+$/.test(res.data) || !res.ok) {\n throw new Error(`Could not getPrice. Received: ${res.data}. Status: ${res.status}, ${res.statusText}`);\n }\n return res.data;\n }\n async get(id) {\n const response = await this.api.get(`tx/${id}`);\n if (response.status == 200) {\n const data_size = parseInt(response.data.data_size);\n if (response.data.format >= 2 &&\n data_size > 0 &&\n data_size <= 1024 * 1024 * 12) {\n const data = await this.getData(id);\n return new transaction_1.default({\n ...response.data,\n data,\n });\n }\n return new transaction_1.default({\n ...response.data,\n format: response.data.format || 1,\n });\n }\n if (response.status == 404) {\n throw new error_1.default(\"TX_NOT_FOUND\" /* ArweaveErrorType.TX_NOT_FOUND */);\n }\n if (response.status == 410) {\n throw new error_1.default(\"TX_FAILED\" /* ArweaveErrorType.TX_FAILED */);\n }\n throw new error_1.default(\"TX_INVALID\" /* ArweaveErrorType.TX_INVALID */);\n }\n fromRaw(attributes) {\n return new transaction_1.default(attributes);\n }\n /** @deprecated use GQL https://gql-guide.arweave.net */\n async search(tagName, tagValue) {\n return this.api\n .post(`arql`, {\n op: \"equals\",\n expr1: tagName,\n expr2: tagValue,\n })\n .then((response) => {\n if (!response.data) {\n return [];\n }\n return response.data;\n });\n }\n getStatus(id) {\n return this.api.get(`tx/${id}/status`).then((response) => {\n if (response.status == 200) {\n return {\n status: 200,\n confirmed: response.data,\n };\n }\n return {\n status: response.status,\n confirmed: null,\n };\n });\n }\n async getData(id, options) {\n let data = undefined;\n try {\n data = await this.chunks.downloadChunkedData(id);\n }\n catch (error) {\n console.error(`Error while trying to download chunked data for ${id}`);\n console.error(error);\n }\n if (!data) {\n console.warn(`Falling back to gateway cache for ${id}`);\n try {\n const { data: resData, ok, status, statusText, } = await this.api.get(`/${id}`, { responseType: \"arraybuffer\" });\n if (!ok) {\n throw new Error(`Bad http status code`, {\n cause: { status, statusText },\n });\n }\n data = resData;\n }\n catch (error) {\n console.error(`Error while trying to download contiguous data from gateway cache for ${id}`);\n console.error(error);\n }\n }\n if (!data) {\n throw new Error(`${id} data was not found!`);\n }\n if (options && options.decode && !options.string) {\n return data;\n }\n if (options && options.decode && options.string) {\n return ArweaveUtils.bufferToString(data);\n }\n // Since decode wasn't requested, caller expects b64url encoded data.\n return ArweaveUtils.bufferTob64Url(data);\n }\n async sign(transaction, jwk, //\"use_wallet\" for backwards compatibility only\n options) {\n /** Non-exhaustive (only checks key names), but previously no jwk checking was done */\n const isJwk = (obj) => {\n let valid = true;\n [\"n\", \"e\", \"d\", \"p\", \"q\", \"dp\", \"dq\", \"qi\"].map((key) => !(key in obj) && (valid = false));\n return valid;\n };\n const validJwk = typeof jwk === \"object\" && isJwk(jwk);\n const externalWallet = typeof arweaveWallet === \"object\";\n if (!validJwk && !externalWallet) {\n throw new Error(`No valid JWK or external wallet found to sign transaction.`);\n }\n else if (validJwk) {\n transaction.setOwner(jwk.n);\n let dataToSign = await transaction.getSignatureData();\n let rawSignature = await this.crypto.sign(jwk, dataToSign, options);\n let id = await this.crypto.hash(rawSignature);\n transaction.setSignature({\n id: ArweaveUtils.bufferTob64Url(id),\n owner: jwk.n,\n signature: ArweaveUtils.bufferTob64Url(rawSignature),\n });\n }\n else if (externalWallet) {\n try {\n const existingPermissions = await arweaveWallet.getPermissions();\n if (!existingPermissions.includes(\"SIGN_TRANSACTION\"))\n await arweaveWallet.connect([\"SIGN_TRANSACTION\"]);\n }\n catch {\n // Permission is already granted\n }\n const signedTransaction = await arweaveWallet.sign(transaction, options);\n transaction.setSignature({\n id: signedTransaction.id,\n owner: signedTransaction.owner,\n reward: signedTransaction.reward,\n tags: signedTransaction.tags,\n signature: signedTransaction.signature,\n });\n }\n else {\n //can't get here, but for sanity we'll throw an error.\n throw new Error(`An error occurred while signing. Check wallet is valid`);\n }\n }\n async verify(transaction) {\n const signaturePayload = await transaction.getSignatureData();\n /**\n * The transaction ID should be a SHA-256 hash of the raw signature bytes, so this needs\n * to be recalculated from the signature and checked against the transaction ID.\n */\n const rawSignature = transaction.get(\"signature\", {\n decode: true,\n string: false,\n });\n const expectedId = ArweaveUtils.bufferTob64Url(await this.crypto.hash(rawSignature));\n if (transaction.id !== expectedId) {\n throw new Error(`Invalid transaction signature or ID! The transaction ID doesn't match the expected SHA-256 hash of the signature.`);\n }\n /**\n * Now verify the signature is valid and signed by the owner wallet (owner field = originating wallet public key).\n */\n return this.crypto.verify(transaction.owner, signaturePayload, rawSignature);\n }\n async post(transaction) {\n if (typeof transaction === \"string\") {\n transaction = new transaction_1.default(JSON.parse(transaction));\n }\n else if (typeof transaction.readInt32BE === \"function\") {\n transaction = new transaction_1.default(JSON.parse(transaction.toString()));\n }\n else if (typeof transaction === \"object\" &&\n !(transaction instanceof transaction_1.default)) {\n transaction = new transaction_1.default(transaction);\n }\n if (!(transaction instanceof transaction_1.default)) {\n throw new Error(`Must be Transaction object`);\n }\n if (!transaction.chunks) {\n await transaction.prepareChunks(transaction.data);\n }\n const uploader = await this.getUploader(transaction, transaction.data);\n // Emulate existing error & return value behavior.\n try {\n while (!uploader.isComplete) {\n await uploader.uploadChunk();\n }\n }\n catch (e) {\n if (uploader.lastResponseStatus > 0) {\n return {\n status: uploader.lastResponseStatus,\n statusText: uploader.lastResponseError,\n data: {\n error: uploader.lastResponseError,\n },\n };\n }\n throw e;\n }\n return {\n status: 200,\n statusText: \"OK\",\n data: {},\n };\n }\n /**\n * Gets an uploader than can be used to upload a transaction chunk by chunk, giving progress\n * and the ability to resume.\n *\n * Usage example:\n *\n * ```\n * const uploader = arweave.transactions.getUploader(transaction);\n * while (!uploader.isComplete) {\n * await uploader.uploadChunk();\n * console.log(`${uploader.pctComplete}%`);\n * }\n * ```\n *\n * @param upload a Transaction object, a previously save progress object, or a transaction id.\n * @param data the data of the transaction. Required when resuming an upload.\n */\n async getUploader(upload, data) {\n let uploader;\n if (data instanceof ArrayBuffer) {\n data = new Uint8Array(data);\n }\n if (upload instanceof transaction_1.default) {\n if (!data) {\n data = upload.data;\n }\n if (!(data instanceof Uint8Array)) {\n throw new Error(\"Data format is invalid\");\n }\n if (!upload.chunks) {\n await upload.prepareChunks(data);\n }\n uploader = new transaction_uploader_1.TransactionUploader(this.api, upload);\n if (!uploader.data || uploader.data.length === 0) {\n uploader.data = data;\n }\n }\n else {\n if (typeof upload === \"string\") {\n upload = await transaction_uploader_1.TransactionUploader.fromTransactionId(this.api, upload);\n }\n if (!data || !(data instanceof Uint8Array)) {\n throw new Error(`Must provide data when resuming upload`);\n }\n // upload should be a serialized upload.\n uploader = await transaction_uploader_1.TransactionUploader.fromSerialized(this.api, upload, data);\n }\n return uploader;\n }\n /**\n * Async generator version of uploader\n *\n * Usage example:\n *\n * ```\n * for await (const uploader of arweave.transactions.upload(tx)) {\n * console.log(`${uploader.pctComplete}%`);\n * }\n * ```\n *\n * @param upload a Transaction object, a previously save uploader, or a transaction id.\n * @param data the data of the transaction. Required when resuming an upload.\n */\n async *upload(upload, data) {\n const uploader = await this.getUploader(upload, data);\n while (!uploader.isComplete) {\n await uploader.uploadChunk();\n yield uploader;\n }\n return uploader;\n }\n}\nexports.default = Transactions;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ArweaveUtils = require(\"./lib/utils\");\nrequire(\"arconnect\");\nclass Wallets {\n api;\n crypto;\n constructor(api, crypto) {\n this.api = api;\n this.crypto = crypto;\n }\n /**\n * Get the wallet balance for the given address.\n *\n * @param {string} address - The arweave address to get the balance for.\n *\n * @returns {Promise<string>} - Promise which resolves with a winston string balance.\n */\n getBalance(address) {\n return this.api.get(`wallet/${address}/balance`).then((response) => {\n return response.data;\n });\n }\n /**\n * Get the last transaction ID for the given wallet address.\n *\n * @param {string} address - The arweave address to get the transaction for.\n *\n * @returns {Promise<string>} - Promise which resolves with a transaction ID.\n */\n getLastTransactionID(address) {\n return this.api.get(`wallet/${address}/last_tx`).then((response) => {\n return response.data;\n });\n }\n generate() {\n return this.crypto.generateJWK();\n }\n async jwkToAddress(jwk) {\n if (!jwk || jwk === \"use_wallet\") {\n return this.getAddress();\n }\n else {\n return this.getAddress(jwk);\n }\n }\n async getAddress(jwk) {\n if (!jwk || jwk === \"use_wallet\") {\n try {\n // @ts-ignore\n await arweaveWallet.connect([\"ACCESS_ADDRESS\"]);\n }\n catch {\n // Permission is already granted\n }\n // @ts-ignore\n return arweaveWallet.getActiveAddress();\n }\n else {\n return this.ownerToAddress(jwk.n);\n }\n }\n async ownerToAddress(owner) {\n return ArweaveUtils.bufferTob64Url(await this.crypto.hash(ArweaveUtils.b64UrlToBuffer(owner)));\n }\n}\nexports.default = Wallets;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.SiloResource = void 0;\nconst ArweaveUtils = require(\"./lib/utils\");\nclass Silo {\n api;\n crypto;\n transactions;\n constructor(api, crypto, transactions) {\n this.api = api;\n this.crypto = crypto;\n this.transactions = transactions;\n }\n async get(siloURI) {\n if (!siloURI) {\n throw new Error(`No Silo URI specified`);\n }\n const resource = await this.parseUri(siloURI);\n const ids = await this.transactions.search(\"Silo-Name\", resource.getAccessKey());\n if (ids.length == 0) {\n throw new Error(`No data could be found for the Silo URI: ${siloURI}`);\n }\n const transaction = await this.transactions.get(ids[0]);\n if (!transaction) {\n throw new Error(`No data could be found for the Silo URI: ${siloURI}`);\n }\n const encrypted = transaction.get(\"data\", { decode: true, string: false });\n return this.crypto.decrypt(encrypted, resource.getEncryptionKey());\n }\n async readTransactionData(transaction, siloURI) {\n if (!siloURI) {\n throw new Error(`No Silo URI specified`);\n }\n const resource = await this.parseUri(siloURI);\n const encrypted = transaction.get(\"data\", { decode: true, string: false });\n return this.crypto.decrypt(encrypted, resource.getEncryptionKey());\n }\n async parseUri(siloURI) {\n const parsed = siloURI.match(/^([a-z0-9-_]+)\\.([0-9]+)/i);\n if (!parsed) {\n throw new Error(`Invalid Silo name, must be a name in the format of [a-z0-9]+.[0-9]+, e.g. 'bubble.7'`);\n }\n const siloName = parsed[1];\n const hashIterations = Math.pow(2, parseInt(parsed[2]));\n const digest = await this.hash(ArweaveUtils.stringToBuffer(siloName), hashIterations);\n const accessKey = ArweaveUtils.bufferTob64(digest.slice(0, 15));\n const encryptionkey = await this.hash(digest.slice(16, 31), 1);\n return new SiloResource(siloURI, accessKey, encryptionkey);\n }\n async hash(input, iterations) {\n let digest = await this.crypto.hash(input);\n for (let count = 0; count < iterations - 1; count++) {\n digest = await this.crypto.hash(digest);\n }\n return digest;\n }\n}\nexports.default = Silo;\nclass SiloResource {\n uri;\n accessKey;\n encryptionKey;\n constructor(uri, accessKey, encryptionKey) {\n this.uri = uri;\n this.accessKey = accessKey;\n this.encryptionKey = encryptionKey;\n }\n getUri() {\n return this.uri;\n }\n getAccessKey() {\n return this.accessKey;\n }\n getEncryptionKey() {\n return this.encryptionKey;\n }\n}\nexports.SiloResource = SiloResource;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst error_1 = require(\"./lib/error\");\nconst ArweaveUtils = require(\"./lib/utils\");\nclass Chunks {\n api;\n constructor(api) {\n this.api = api;\n }\n async getTransactionOffset(id) {\n const resp = await this.api.get(`tx/${id}/offset`);\n if (resp.status === 200) {\n return resp.data;\n }\n throw new Error(`Unable to get transaction offset: ${(0, error_1.getError)(resp)}`);\n }\n async getChunk(offset) {\n const resp = await this.api.get(`chunk/${offset}`);\n if (resp.status === 200) {\n return resp.data;\n }\n throw new Error(`Unable to get chunk: ${(0, error_1.getError)(resp)}`);\n }\n async getChunkData(offset) {\n const chunk = await this.getChunk(offset);\n const buf = ArweaveUtils.b64UrlToBuffer(chunk.chunk);\n return buf;\n }\n firstChunkOffset(offsetResponse) {\n return parseInt(offsetResponse.offset) - parseInt(offsetResponse.size) + 1;\n }\n async downloadChunkedData(id) {\n const offsetResponse = await this.getTransactionOffset(id);\n const size = parseInt(offsetResponse.size);\n const endOffset = parseInt(offsetResponse.offset);\n const startOffset = endOffset - size + 1;\n const data = new Uint8Array(size);\n let byte = 0;\n while (byte < size) {\n if (this.api.config.logging) {\n console.log(`[chunk] ${byte}/${size}`);\n }\n let chunkData;\n try {\n chunkData = await this.getChunkData(startOffset + byte);\n }\n catch (error) {\n console.error(`[chunk] Failed to fetch chunk at offset ${startOffset + byte}`);\n console.error(`[chunk] This could indicate that the chunk wasn't uploaded or hasn't yet seeded properly to a particular gateway/node`);\n }\n if (chunkData) {\n data.set(chunkData, byte);\n byte += chunkData.length;\n }\n else {\n throw new Error(`Couldn't complete data download at ${byte}/${size}`);\n }\n }\n return data;\n }\n}\nexports.default = Chunks;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst error_1 = require(\"./lib/error\");\nrequire(\"arconnect\");\nclass Blocks {\n api;\n network;\n static HASH_ENDPOINT = \"block/hash/\";\n static HEIGHT_ENDPOINT = \"block/height/\";\n constructor(api, network) {\n this.api = api;\n this.network = network;\n }\n /**\n * Gets a block by its \"indep_hash\"\n */\n async get(indepHash) {\n const response = await this.api.get(`${Blocks.HASH_ENDPOINT}${indepHash}`);\n if (response.status === 200) {\n return response.data;\n }\n else {\n if (response.status === 404) {\n throw new error_1.default(\"BLOCK_NOT_FOUND\" /* ArweaveErrorType.BLOCK_NOT_FOUND */);\n }\n else {\n throw new Error(`Error while loading block data: ${response}`);\n }\n }\n }\n /**\n * Gets a block by its \"height\"\n */\n async getByHeight(height) {\n const response = await this.api.get(`${Blocks.HEIGHT_ENDPOINT}${height}`);\n if (response.status === 200) {\n return response.data;\n }\n else {\n if (response.status === 404) {\n throw new error_1.default(\"BLOCK_NOT_FOUND\" /* ArweaveErrorType.BLOCK_NOT_FOUND */);\n }\n else {\n throw new Error(`Error while loading block data: ${response}`);\n }\n }\n }\n /**\n * Gets current block data (ie. block with indep_hash = Network.getInfo().current)\n */\n async getCurrent() {\n const { current } = await this.network.getInfo();\n return await this.get(current);\n }\n}\nexports.default = Blocks;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst ar_1 = require(\"./ar\");\nconst api_1 = require(\"./lib/api\");\nconst node_driver_1 = require(\"./lib/crypto/webcrypto-driver\");\nconst network_1 = require(\"./network\");\nconst transactions_1 = require(\"./transactions\");\nconst wallets_1 = require(\"./wallets\");\nconst transaction_1 = require(\"./lib/transaction\");\nconst ArweaveUtils = require(\"./lib/utils\");\nconst silo_1 = require(\"./silo\");\nconst chunks_1 = require(\"./chunks\");\nconst blocks_1 = require(\"./blocks\");\nclass Arweave {\n api;\n wallets;\n transactions;\n network;\n blocks;\n ar;\n silo;\n chunks;\n static init;\n static crypto = new node_driver_1.default();\n static utils = ArweaveUtils;\n constructor(apiConfig) {\n this.api = new api_1.default(apiConfig);\n this.wallets = new wallets_1.default(this.api, Arweave.crypto);\n this.chunks = new chunks_1.default(this.api);\n this.transactions = new transactions_1.default(this.api, Arweave.crypto, this.chunks);\n this.silo = new silo_1.default(this.api, this.crypto, this.transactions);\n this.network = new network_1.default(this.api);\n this.blocks = new blocks_1.default(this.api, this.network);\n this.ar = new ar_1.default();\n }\n /** @deprecated */\n get crypto() {\n return Arweave.crypto;\n }\n /** @deprecated */\n get utils() {\n return Arweave.utils;\n }\n getConfig() {\n return {\n api: this.api.getConfig(),\n crypto: null,\n };\n }\n async createTransaction(attributes, jwk) {\n const transaction = {};\n Object.assign(transaction, attributes);\n if (!attributes.data && !(attributes.target && attributes.quantity)) {\n throw new Error(`A new Arweave transaction must have a 'data' value, or 'target' and 'quantity' values.`);\n }\n if (attributes.owner == undefined) {\n if (jwk && jwk !== \"use_wallet\") {\n transaction.owner = jwk.n;\n }\n }\n if (attributes.last_tx == undefined) {\n transaction.last_tx = await this.transactions.getTransactionAnchor();\n }\n if (typeof attributes.data === \"string\") {\n attributes.data = ArweaveUtils.stringToBuffer(attributes.data);\n }\n if (attributes.data instanceof ArrayBuffer) {\n attributes.data = new Uint8Array(attributes.data);\n }\n if (attributes.data && !(attributes.data instanceof Uint8Array)) {\n throw new Error(\"Expected data to be a string, Uint8Array or ArrayBuffer\");\n }\n if (attributes.reward == undefined) {\n const length = attributes.data ? attributes.data.byteLength : 0;\n transaction.reward = await this.transactions.getPrice(length, transaction.target);\n }\n // here we should call prepare chunk\n transaction.data_root = \"\";\n transaction.data_size = attributes.data\n ? attributes.data.byteLength.toString()\n : \"0\";\n transaction.data = attributes.data || new Uint8Array(0);\n const createdTransaction = new transaction_1.default(transaction);\n await createdTransaction.getSignatureData();\n return createdTransaction;\n }\n async createSiloTransaction(attributes, jwk, siloUri) {\n const transaction = {};\n Object.assign(transaction, attributes);\n if (!attributes.data) {\n throw new Error(`Silo transactions must have a 'data' value`);\n }\n if (!siloUri) {\n throw new Error(`No Silo URI specified.`);\n }\n if (attributes.target || attributes.quantity) {\n throw new Error(`Silo transactions can only be used for storing data, sending AR to other wallets isn't supported.`);\n }\n if (attributes.owner == undefined) {\n if (!jwk || !jwk.n) {\n throw new Error(`A new Arweave transaction must either have an 'owner' attribute, or you must provide the jwk parameter.`);\n }\n transaction.owner = jwk.n;\n }\n if (attributes.last_tx == undefined) {\n transaction.last_tx = await this.transactions.getTransactionAnchor();\n }\n const siloResource = await this.silo.parseUri(siloUri);\n if (typeof attributes.data == \"string\") {\n const encrypted = await this.crypto.encrypt(ArweaveUtils.stringToBuffer(attributes.data), siloResource.getEncryptionKey());\n transaction.reward = await this.transactions.getPrice(encrypted.byteLength);\n transaction.data = ArweaveUtils.bufferTob64Url(encrypted);\n }\n if (attributes.data instanceof Uint8Array) {\n const encrypted = await this.crypto.encrypt(attributes.data, siloResource.getEncryptionKey());\n transaction.reward = await this.transactions.getPrice(encrypted.byteLength);\n transaction.data = ArweaveUtils.bufferTob64Url(encrypted);\n }\n const siloTransaction = new transaction_1.default(transaction);\n siloTransaction.addTag(\"Silo-Name\", siloResource.getAccessKey());\n siloTransaction.addTag(\"Silo-Version\", `0.1.0`);\n return siloTransaction;\n }\n arql(query) {\n return this.api\n .post(\"/arql\", query)\n .then((response) => response.data || []);\n }\n}\nexports.default = Arweave;\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.getDefaultConfig = void 0;\n/** exhaustive localhost testing */\nconst isLocal = (protocol, hostname) => {\n const regexLocalIp = /^127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/;\n const split = hostname.split(\".\");\n const tld = split[split.length - 1]; // check if subdomain on the localhost\n const localStrings = [\"localhost\", \"[::1]\"];\n return (localStrings.includes(hostname) ||\n protocol == \"file\" ||\n localStrings.includes(tld) ||\n !!hostname.match(regexLocalIp) ||\n !!tld.match(regexLocalIp));\n};\n/** simplified tests for ip addresses */\nconst isIpAdress = (host) => {\n // an IPv6 location.hostname (and only IPv6 hostnames) must be surrounded by square brackets\n const isIpv6 = host.charAt(0) === \"[\";\n // Potential speed-up for IPv4 detection:\n // the tld of a domain name cannot be a number (IDN location.hostnames appear to be converted, needs further clarification)\n const regexMatchIpv4 = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$/;\n return !!host.match(regexMatchIpv4) || isIpv6;\n};\nconst getDefaultConfig = (protocol, host) => {\n // If we're running in what looks like a local dev environment\n // then default to using arweave.net\n if (isLocal(protocol, host)) {\n return {\n protocol: \"https\",\n host: \"arweave.net\",\n port: 443,\n };\n }\n //check if hostname is an IP address before removing first subdomain\n if (!isIpAdress(host)) {\n let split = host.split(\".\");\n if (split.length >= 3) {\n split.shift();\n const parentDomain = split.join(\".\");\n return {\n protocol,\n host: parentDomain,\n };\n }\n }\n // there are 2 potential garbage returns here:\n // a non-GW ip address & a non-GW hostname without ArNS. garbage in, garbage out.\n // they should be overridden with user inputs in apiConfig.\n // otherwise we have a valid ip based GW address.\n return {\n protocol,\n host,\n };\n};\nexports.getDefaultConfig = getDefaultConfig;\n","\"use strict\";\nvar __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n var desc = Object.getOwnPropertyDescriptor(m, k);\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\n desc = { enumerable: true, get: function() { return m[k]; } };\n }\n Object.defineProperty(o, k2, desc);\n}) : (function(o, m, k, k2) {\n if (k2 === undefined) k2 = k;\n o[k2] = m[k];\n}));\nvar __exportStar = (this && this.__exportStar) || function(m, exports) {\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n};\nObject.defineProperty(exports, \"__esModule\", { value: true });\nconst common_1 = require(\"./common\");\nconst net_config_1 = require(\"./net-config\");\ncommon_1.default.init = function (apiConfig = {}) {\n const defaults = {\n host: \"arweave.net\",\n port: 443,\n protocol: \"https\",\n };\n if (typeof location !== \"object\" ||\n !location.protocol ||\n !location.hostname) {\n return new common_1.default({\n ...apiConfig,\n ...defaults,\n });\n }\n // window.location.protocol has a trailing colon (http:, https:, file: etc)\n const locationProtocol = location.protocol.replace(\":\", \"\");\n const locationHost = location.hostname;\n const locationPort = location.port\n ? parseInt(location.port)\n : locationProtocol == \"https\"\n ? 443\n : 80;\n const defaultConfig = (0, net_config_1.getDefaultConfig)(locationProtocol, locationHost);\n const protocol = apiConfig.protocol || defaultConfig.protocol;\n const host = apiConfig.host || defaultConfig.host;\n const port = apiConfig.port || defaultConfig.port || locationPort;\n return new common_1.default({\n ...apiConfig,\n host,\n protocol,\n port,\n });\n};\nif (typeof globalThis === \"object\") {\n globalThis.Arweave = common_1.default;\n}\nelse if (typeof self === \"object\") {\n self.Arweave = common_1.default;\n}\n__exportStar(require(\"./common\"), exports);\nexports.default = common_1.default;\n","import Arweave from 'arweave'\nimport { BaseArweaveClient } from '@seedprotocol/sdk'\n\nexport const getArweave = (): Arweave => {\n const host = BaseArweaveClient.getHost()\n\n const ArweaveModule = Arweave as typeof Arweave & { default?: typeof Arweave }\n if (Object.keys(ArweaveModule).includes('default') && ArweaveModule.default) {\n return ArweaveModule.default.init({\n host,\n protocol: 'https',\n })\n }\n\n return ArweaveModule.init({\n host,\n protocol: 'https',\n })\n}\n\n","/**\n * Transforms multiPublish payload from string-based localId/publishLocalId to integer indices\n * for gas-efficient contract comparison. Use when the contract expects uint256 localIdIndex\n * and publishLocalIdIndex instead of strings.\n */\n\nexport type RequestWithStringIds = {\n localId: string\n propertiesToUpdate?: Array<{ publishLocalId?: string; propertySchemaUid?: string; [k: string]: unknown }>\n [k: string]: unknown\n}\n\nexport type RequestWithIntegerIds = Omit<RequestWithStringIds, 'localId' | 'propertiesToUpdate'> & {\n localIdIndex: bigint\n propertiesToUpdate?: Array<{\n publishLocalIdIndex: bigint\n propertySchemaUid?: string\n [k: string]: unknown\n }>\n}\n\n/**\n * Converts localId/publishLocalId strings to uint256 indices.\n * Each request's index is its position in the array (0-based).\n * Throws if any publishLocalId does not exist in the payload.\n */\nexport function transformPayloadToIntegerIds(\n requests: RequestWithStringIds[],\n): RequestWithIntegerIds[] {\n const localIdToIndex = new Map<string, bigint>()\n for (let i = 0; i < requests.length; i++) {\n const localId = requests[i]?.localId\n if (localId != null) {\n localIdToIndex.set(localId, BigInt(i))\n }\n }\n\n return requests.map((req, i) => {\n const propertiesToUpdate = (req.propertiesToUpdate ?? []).map((pu) => {\n const publishLocalId = pu.publishLocalId\n const index = publishLocalId != null ? localIdToIndex.get(publishLocalId) : undefined\n if (publishLocalId != null && publishLocalId !== '' && index === undefined) {\n throw new Error(\n `publishLocalId \"${publishLocalId}\" not found in payload (valid localIds: ${Array.from(localIdToIndex.keys()).join(', ')})`,\n )\n }\n const { publishLocalId: _omit, ...rest } = pu\n return {\n ...rest,\n publishLocalIdIndex: index ?? BigInt(0),\n }\n })\n\n const { localId: _omitLocalId, ...rest } = req\n return {\n ...rest,\n localIdIndex: BigInt(i),\n propertiesToUpdate,\n } as RequestWithIntegerIds\n })\n}\n\n/**\n * Transforms propertiesToUpdate from publishLocalId (string) to publishIndex (uint256)\n * for the Executor contract, which expects publishIndex. Keeps localId as string.\n */\nexport function transformPayloadForExecutor<T extends RequestWithStringIds>(\n requests: T[],\n): T[] {\n const localIdToIndex = new Map<string, bigint>()\n for (let i = 0; i < requests.length; i++) {\n const localId = requests[i]?.localId\n if (localId != null) {\n localIdToIndex.set(localId, BigInt(i))\n }\n }\n\n return requests.map((req) => {\n const propertiesToUpdate = (req.propertiesToUpdate ?? []).map((pu) => {\n const publishLocalId = pu.publishLocalId\n const index = publishLocalId != null ? localIdToIndex.get(publishLocalId) : undefined\n if (publishLocalId != null && publishLocalId !== '' && index === undefined) {\n throw new Error(\n `publishLocalId \"${publishLocalId}\" not found in payload (valid localIds: ${Array.from(localIdToIndex.keys()).join(', ')})`,\n )\n }\n const { publishLocalId: _omit, ...rest } = pu\n return {\n ...rest,\n publishIndex: index ?? BigInt(0),\n }\n })\n return { ...req, propertiesToUpdate } as T\n })\n}\n","/**\n * Serialized form part for IPC to main process (avoids CORS by proxying uploads).\n */\nexport type UploadFormPart = {\n name: string\n value: string\n encoding?: 'base64'\n filename?: string\n}\n\n/** Chunk size for base64 encoding; spreading large arrays blows the call stack. */\nconst BASE64_CHUNK_SIZE = 8192\n\nfunction arrayBufferToBase64(buffer: ArrayBuffer): string {\n const bytes = new Uint8Array(buffer)\n let binary = ''\n for (let i = 0; i < bytes.length; i += BASE64_CHUNK_SIZE) {\n const chunk = bytes.subarray(i, Math.min(i + BASE64_CHUNK_SIZE, bytes.length))\n binary += String.fromCharCode.apply(null, chunk as unknown as number[])\n }\n return btoa(binary)\n}\n\n/**\n * Convert FormData to a serializable array for IPC. Blobs are base64-encoded.\n */\nexport async function formDataToSerializableParts(\n formData: FormData\n): Promise<UploadFormPart[]> {\n const parts: UploadFormPart[] = []\n for (const [name, value] of formData.entries()) {\n const entry = value as string | Blob\n if (typeof entry === 'object' && entry !== null && 'arrayBuffer' in entry) {\n const buf = await entry.arrayBuffer()\n const base64 = arrayBufferToBase64(buf)\n const file = entry as File\n parts.push({\n name,\n value: base64,\n encoding: 'base64',\n filename: file.name || undefined,\n })\n } else {\n parts.push({ name, value: String(value) })\n }\n }\n return parts\n}\n\n/** Result from upload POST (status 0 = network/proxy error). */\nexport type PostUploadResult = {\n status: number\n body: unknown\n error?: string\n message?: string\n}\n\n/** Build a user-facing message when the upload API returns a non-2xx status. */\nexport function uploadServerErrorMessage(\n status: number,\n body: unknown,\n transactionKeys?: string | null\n): string {\n const parts: string[] = ['Upload server returned ', String(status)]\n const msg =\n body && typeof body === 'object' && 'message' in body\n ? String((body as { message: unknown }).message)\n : body && typeof body === 'object' && 'error' in body\n ? String((body as { error: unknown }).error)\n : null\n if (msg) parts.push(`: ${msg}`)\n else if (transactionKeys) parts.push(` (${transactionKeys})`)\n return parts.join('')\n}\n\n/** Map technical network error messages to a short, user-facing message. */\nexport function uploadNetworkErrorMessage(technicalMessage?: string | null): string {\n if (!technicalMessage) {\n return 'Upload server unavailable. Please try again or check your connection.'\n }\n const t = technicalMessage.toLowerCase()\n if (/other side closed|econnreset|socket hang up|connection closed/i.test(t)) {\n return 'Upload server closed the connection. It may be busy or the request may be too large—try again.'\n }\n if (/etimedout|timeout/i.test(t)) {\n return 'Upload request timed out. Please try again.'\n }\n if (/enotfound|getaddrinfo|dns/i.test(t)) {\n return 'Upload server could not be reached. Check the upload URL and your network.'\n }\n return 'Upload failed. Please try again or check the upload server.'\n}\n\n/**\n * POST to the upload API. Uses main-process proxy in Electron to avoid CORS;\n * falls back to fetch when not in Electron (e.g. browser tests).\n */\nexport async function postUploadArweaveStart(\n url: string,\n formData: FormData,\n uploadApiBaseUrl: string\n): Promise<PostUploadResult> {\n const api = typeof window !== 'undefined' ? (window as Window & { Main?: { uploadArweaveStart?: (url: string, parts: UploadFormPart[]) => Promise<PostUploadResult> } }).Main : undefined\n if (api?.uploadArweaveStart) {\n const parts = await formDataToSerializableParts(formData)\n return api.uploadArweaveStart(url, parts)\n }\n const res = await fetch(url, {\n method: 'POST',\n body: formData,\n })\n const body = await res.json().catch(() => ({}))\n return { status: res.status, body }\n}\n","import { ActorRefFrom, EventObject, fromCallback, fromPromise, } from 'xstate'\nimport type { ArweaveTransactionInfo, PublishMachineContext } from '../../types'\nimport {\n ZERO_ADDRESS,\n} from '@ethereum-attestation-service/eas-sdk'\nimport { encode, getContract, parseEventLogs, readContract, sendTransaction, waitForReceipt, } from 'thirdweb'\nimport {\n optimismSepolia,\n} from 'thirdweb/chains'\nimport { getClient, getManagedAccountWallet, getModularAccountWallet } from '~/helpers/thirdweb'\nimport {\n createdAttestationEvent,\n execute,\n factory,\n getEas,\n multiPublish,\n multiPublishWithIntegerIds,\n type MultiPublishWithIntegerIdsParams,\n seedPublishedEvent,\n setEas,\n} from '~/helpers/thirdweb/11155420/0xcd8c945872df8e664e55cf8885c85ea3ea8f2148'\nimport {\n multiPublish as executorMultiPublish,\n createdAttestationEvent as executorCreatedAttestationEvent,\n seedPublishedEvent as executorSeedPublishedEvent,\n} from '~/helpers/thirdweb/11155420/0x043462304114da543add6b693c686b7d98865f3e'\nimport { decodeAbiParameters, encodeAbiParameters, } from 'viem'\nimport { publishMachine, } from './index'\n// import { getModelInstance, getPublishAttempt, } from '~/helpers'\nimport Transaction from 'arweave/web/lib/transaction'\nimport type { ReimbursementResponse } from '../upload'\nimport { Item } from '@seedprotocol/sdk'\nimport type { PublishUpload } from '../../types'\nimport { persistSeedUidFromPublishResult } from './actors/persistSeedUid'\nimport { ensureEasSchemasForItem } from './helpers/ensureEasSchemas'\nimport { getArweave } from '~/helpers/blockchain'\nimport { getPublishConfig } from '~/config'\nimport { transformPayloadForExecutor, transformPayloadToIntegerIds } from '~/helpers/transformPayloadToIntegerIds'\nimport { postUploadArweaveStart, uploadNetworkErrorMessage, uploadServerErrorMessage } from '~/helpers/uploadApi'\nimport debug from 'debug'\nimport { getInstalledModules, installModule } from 'thirdweb/modules'\nimport { EAS_CONTRACT_ADDRESS, THIRDWEB_ACCOUNT_FACTORY_ADDRESS } from '~/helpers/constants'\nimport { inAppWallet } from 'thirdweb/wallets'\n\n\nconst logger = debug('seedProtocol:services:publish:actors')\n\nconst ZERO_BYTES32 = '0x' + '0'.repeat(64)\n\nconst BYTES32_LEN = 64\nfunction toHex32Normalized(v: string | undefined): string {\n if (v == null || v === '') return ZERO_BYTES32\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0').padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n return ('0x' + hex).toLowerCase()\n}\n\n/**\n * Extract the seed attestation UID by matching the request's seedSchemaUid to a CreatedAttestation\n * event. The payload links each request to a schema (seedSchemaUid); the contract emits\n * CreatedAttestation(schemaUid, attestationUid) for each attestation, so we find the event whose\n * schemaUid matches and use its attestationUid. No index guessing.\n */\nfunction seedUidFromCreatedAttestationEvents(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n seedSchemaUid: string | undefined,\n useModularExecutor: boolean,\n): string | undefined {\n if (!seedSchemaUid || !receipt.logs?.length) return undefined\n const wantSchema = toHex32Normalized(seedSchemaUid)\n if (wantSchema === ZERO_BYTES32) return undefined\n const createdAttestationEvt = useModularExecutor ? executorCreatedAttestationEvent : createdAttestationEvent\n try {\n const parsed = parseEventLogs({\n logs: receipt.logs as import('viem').Log[],\n events: [createdAttestationEvt()],\n strict: false,\n })\n for (const ev of parsed) {\n const result = ev?.args?.result as { schemaUid?: string; attestationUid?: string } | undefined\n if (!result?.attestationUid) continue\n if (toHex32Normalized(result.schemaUid) === wantSchema) {\n const uid = result.attestationUid\n if (uid && toHex32Normalized(uid) !== ZERO_BYTES32) return uid\n return undefined\n }\n }\n } catch {\n // ignore\n }\n return undefined\n}\n\n/**\n * Fallback: extract seed UID from SeedPublished when CreatedAttestation events are not\n * available or don't match.\n * Extension: SeedPublished(bytes returnedDataFromEAS) - decode bytes as bytes32[], use index.\n * Executor: SeedPublished(bytes32 seedUid, bytes32 versionUid) - read args.seedUid directly.\n */\nfunction seedUidFromSeedPublished(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n contractAddress: string,\n listOfAttestationsCount: number,\n useModularExecutor: boolean,\n): string | undefined {\n const want = contractAddress.toLowerCase()\n const logs = receipt.logs?.filter(\n (l) => l.address && l.address.toLowerCase() === want,\n )\n if (!logs?.length) return undefined\n try {\n const seedPublishedEvt = useModularExecutor ? executorSeedPublishedEvent : seedPublishedEvent\n const parsed = parseEventLogs({\n logs: logs as import('viem').Log[],\n events: [seedPublishedEvt()],\n strict: false,\n })\n const first = parsed[0]\n if (!first) return undefined\n if (useModularExecutor) {\n const args = first.args as { seedUid?: string }\n const seedUid = args?.seedUid\n return seedUid && toHex32Normalized(seedUid) !== ZERO_BYTES32 ? seedUid : undefined\n }\n const args = first.args as { returnedDataFromEAS?: `0x${string}` }\n const data = args?.returnedDataFromEAS\n if (!data || data === '0x') return undefined\n const decoded = decodeAbiParameters([{ type: 'bytes32[]' }], data)\n const uids = decoded[0] as readonly `0x${string}`[]\n if (!uids?.length) return undefined\n const seedIndex = listOfAttestationsCount\n const atIndex = uids[seedIndex]\n if (atIndex && atIndex !== ZERO_BYTES32) return atIndex as string\n if (uids.length === 1 && uids[0] && uids[0] !== ZERO_BYTES32) return uids[0] as string\n return undefined\n } catch {\n return undefined\n }\n}\n\n\nconst waitForItem = async (seedLocalId: string): Promise<InstanceType<typeof Item>> => {\n let item: InstanceType<typeof Item> | undefined\n\n try {\n item = await Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n } catch {\n // No-op: Error is intentionally ignored\n }\n\n if (item) {\n return item\n }\n\n return new Promise<InstanceType<typeof Item>>((resolve) => {\n const interval = setInterval(() => {\n try {\n Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n .then((found: InstanceType<typeof Item> | undefined) => {\n if (found) {\n clearInterval(interval)\n resolve(found)\n }\n })\n } catch {\n // No-op: Error is intentionally ignored\n }\n }, 200)\n })\n}\n\nconst activePublishProcesses = new Set<string>()\n\ntype CreateArweaveTransactionsResult = {\n arweaveTransactions: ArweaveTransactionInfo[]\n publishUploads: /* `PublishUpload` seems to be a type or interface used in the codebase to represent\n data related to uploading content for publishing. It likely contains information\n such as the transaction to sign, version local ID, item property name, and\n possibly other relevant details needed for the publishing process. It is used in\n functions like `createArweaveTransactions` and `createAttestations` to handle the\n upload data and transactions associated with publishing content. */\n PublishUpload[]\n}\n\nexport type PublishActor = ActorRefFrom<typeof publishMachine>\n\nfunction deserializeChunks(serialized: unknown): { data_root: Uint8Array; chunks: Array<{ dataHash: Uint8Array; minByteRange: number; maxByteRange: number }>; proofs: Array<{ offset: number; proof: Uint8Array }> } | undefined {\n if (!serialized || typeof serialized !== 'object') return undefined\n const s = serialized as { data_root?: number[]; chunks?: Array<{ dataHash: number[]; minByteRange: number; maxByteRange: number }>; proofs?: Array<{ offset: number; proof: number[] }> }\n if (!Array.isArray(s.data_root)) return undefined\n return {\n data_root: new Uint8Array(s.data_root),\n chunks: (s.chunks ?? []).map((c) => ({ ...c, dataHash: new Uint8Array(c.dataHash ?? []) })),\n proofs: (s.proofs ?? []).map((p) => ({ ...p, proof: new Uint8Array(p.proof ?? []) })),\n }\n}\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\nexport const createArweaveTransactions = fromPromise(async ({\n input: { context, event },\n}: PublishInput): Promise<CreateArweaveTransactionsResult> => {\n let { item } = context\n\n if (!item.getPublishUploads) {\n item = await waitForItem(item.seedLocalId)\n }\n\n const publishUploads = await item.getPublishUploads()\n\n const win = typeof window !== 'undefined' ? (window as Window & { Main?: { createAndSignArweaveTransactions?: (uploads: unknown[]) => Promise<unknown[]> } }) : null\n if (!win?.Main?.createAndSignArweaveTransactions) {\n throw new Error('Arweave signing not available')\n }\n\n const uploads = publishUploads.map((u: PublishUpload) => ({\n versionLocalId: u.versionLocalId,\n itemPropertyName: u.itemPropertyName,\n transactionJson: (u.transactionToSign as Transaction).toJSON(),\n }))\n\n const results = await win.Main.createAndSignArweaveTransactions(uploads)\n\n const arweave = getArweave()\n const arweaveTransactions: ArweaveTransactionInfo[] = (results as Array<{ transaction: Record<string, unknown>; versionId?: string; modelName?: string }>).map((r) => {\n const { chunks: serializedChunks, ...rest } = r.transaction as Record<string, unknown>\n const attrs = { ...rest }\n const chunks = deserializeChunks(serializedChunks)\n if (chunks) (attrs as Record<string, unknown>).chunks = chunks\n const tx = arweave.transactions.fromRaw(attrs)\n return {\n transaction: tx,\n versionId: r.versionId,\n modelName: r.modelName,\n }\n })\n\n return {\n arweaveTransactions,\n publishUploads,\n }\n},)\n\nexport const sendReimbursementRequest = fromPromise(async ({\n input: { context, event },\n}: PublishInput): Promise<ReimbursementResponse> => {\n\n\n const { arweaveTransactions = [], transactionKeys, reimbursementTransactionId } = context\n\n if (reimbursementTransactionId) {\n return {\n transactionId: reimbursementTransactionId,\n }\n }\n\n const transactions = arweaveTransactions.map(({ transaction }: ArweaveTransactionInfo) => transaction)\n\n const formData = new FormData()\n\n\n type ArweaveTx = { id: string; data?: unknown; chunks?: unknown; [key: string]: unknown }\n for (const transaction of transactions as ArweaveTx[]) {\n let { data, chunks, ...json } = transaction\n const dataBlob = data instanceof Blob ? data : new Blob([data as BlobPart])\n formData.append(`${transaction.id}-data`, dataBlob, `${transaction.id}-data`)\n const chunksBlob = new Blob([ JSON.stringify(chunks,), ], {type: 'application/json',},)\n formData.append(`${transaction.id}-chunks`, chunksBlob, `${transaction.id}-chunks`,)\n const jsonBlob = new Blob([ JSON.stringify(json,), ], {type: 'application/json',},)\n formData.append(`${transaction.id}-json`, jsonBlob, `${transaction.id}-json`,)\n }\n\n // TODO: What if this fails but a successful one has already gone through? We don't want to crash the app\n\n const { uploadApiBaseUrl } = getPublishConfig()\n const url = `${uploadApiBaseUrl}/api/upload/arweave/start`\n const { status, body, message: serverMessage } = await postUploadArweaveStart(url, formData, uploadApiBaseUrl)\n\n if ( status >= 300 || status < 200 ) {\n const technicalMsg = status === 0 ? serverMessage : null\n if (technicalMsg) console.error('[upload]', technicalMsg)\n const errMsg = status === 0\n ? uploadNetworkErrorMessage(technicalMsg as string | undefined)\n : uploadServerErrorMessage(status, body, transactionKeys)\n throw new Error(errMsg)\n }\n\n return body as ReimbursementResponse\n},)\n\nexport const pollForConfirmation = fromPromise(async ({ input: { context, event } }: PublishInput): Promise<void> => {\n\n const {requestResponse, reimbursementTransactionId} = context\n\n if ( !requestResponse ) {\n throw new Error('No request response',)\n }\n\n if ( !reimbursementTransactionId ) {\n throw new Error('No reimbursement transaction id',)\n }\n\n const arweave = getArweave()\n\n const _pollForConfirmation = new Promise<void>(( resolve, reject, ) => {\n const interval = setInterval(async () => {\n let response\n try {\n response = await arweave.transactions.getStatus(reimbursementTransactionId,)\n } catch ( error ) {\n return\n }\n if (response && response.confirmed ) {\n clearInterval(interval,)\n resolve()\n }\n }, 5000)\n\n })\n\n await _pollForConfirmation\n\n})\n\nexport const uploadData = fromCallback<EventObject, { context: PublishMachineContext }>(({\n sendBack,\n input,\n}) => {\n const arweaveTransactions = input.context.arweaveTransactions ?? []\n const transactions = arweaveTransactions.map(({ transaction }: ArweaveTransactionInfo) => transaction)\n const arweave = getArweave()\n\n const processTransactions = async (): Promise<string> => {\n\n for ( const rawTransaction of transactions ) {\n\n const transaction = arweave.transactions.fromRaw(rawTransaction,)\n\n const verified = await arweave.transactions.verify(transaction,)\n\n if ( !verified ) {\n throw new Error('Transaction verification failed',)\n }\n\n const uploader = await arweave.transactions.getUploader(transaction, transaction.data,)\n while ( !uploader.isComplete ) {\n logger('uploading chunk',)\n logger(`uploader.pctComplete: ${uploader.pctComplete}`,)\n logger(`uploader.uploadedChunks: ${uploader.uploadedChunks}`,)\n logger(`uploader.totalChunks: ${uploader.totalChunks}`,)\n logger(uploader.lastResponseError,)\n logger(uploader.lastResponseStatus,)\n try {\n await uploader.uploadChunk()\n sendBack({type: 'updatePercentage', completionPercentage: uploader.pctComplete,},)\n logger(`${uploader.pctComplete}% complete, ${uploader.uploadedChunks}/${uploader.totalChunks}`,)\n\n } catch ( error ) {\n logger(error,)\n }\n }\n }\n\n return 'done'\n }\n\n processTransactions().then(( result, ) => {\n sendBack({type: 'uploadComplete', result,},)\n },).catch(( error, ) => {\n sendBack({type: 'uploadError', error,},)\n },)\n},)\n\nexport const createAttestations = fromPromise(async ({ input: { context, event } }: PublishInput): Promise<void> => {\n const { address, account } = context\n const arweaveTransactions = context.arweaveTransactions ?? []\n const publishUploads = context.publishUploads ?? []\n let { item } = context\n\n const { modularAccountModuleContract, useIntegerLocalIds, useModularExecutor } = getPublishConfig()\n\n if (!address || typeof address !== 'string' || !address.trim()) {\n throw new Error('No wallet address for publish. Connect a wallet and try again.')\n }\n\n if (!account) {\n throw new Error('Wallet session is missing. Reconnect your wallet and retry the publish.')\n }\n\n if (!item?.seedLocalId) {\n throw new Error('Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.')\n }\n if (typeof item.getPublishUploads !== 'function') {\n item = await waitForItem(item.seedLocalId)\n }\n\n const txCount = arweaveTransactions.length\n const uploadCount = publishUploads.length\n if (txCount !== uploadCount) {\n throw new Error(\n 'Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.'\n )\n }\n\n const smartWalletContract = getContract({\n client: getClient(),\n chain: optimismSepolia,\n address,\n },)\n\n let targetContract = useModularExecutor && modularAccountModuleContract\n ? getContract({\n client: getClient(),\n chain: optimismSepolia,\n address: modularAccountModuleContract,\n })\n : smartWalletContract\n\n // if (!useModularExecutor) {\n // let easAddress: string\n // try {\n // easAddress = await getEas({\n // contract: smartWalletContract,\n // },) as string\n // // #region agent log\n // fetch('http://127.0.0.1:7242/ingest/0978b378-ebae-46bf-8fd3-134ef2e16cdd',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'4756f9'},body:JSON.stringify({sessionId:'4756f9',location:'actors.ts:getEas-success',message:'getEas succeeded (EAS already set)',data:{easAddress,address},timestamp:Date.now()})}).catch(()=>{});\n // // #endregion\n // } catch (getEasErr: unknown) {\n // const err = getEasErr instanceof Error ? getEasErr : new Error(String(getEasErr))\n // const msg = err.message\n // // #region agent log\n // fetch('http://127.0.0.1:7242/ingest/0978b378-ebae-46bf-8fd3-134ef2e16cdd',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'4756f9'},body:JSON.stringify({sessionId:'4756f9',location:'actors.ts:getEas-error',message:'getEas failed (will attempt setEas if zero data)',data:{errorMessage:msg,errorName:err.name,address},timestamp:Date.now()})}).catch(()=>{});\n // // #endregion\n // // Contract returned \"0x\" (e.g. EOA or not deployed). Treat as EAS not set so we attempt setEas; if address has no code, sendTransaction will fail with a clear error.\n // if (err.name === 'AbiDecodingZeroDataError' || /Cannot decode zero data/i.test(msg)) {\n // easAddress = ZERO_ADDRESS\n // } else {\n // throw getEasErr\n // }\n // }\n\n // // We send setEas and multiPublish using the smart wallet (in-app) account.\n // // This assumes the contract allows the smart account as tx sender for these calls.\n // // If the contract only allows an EOA owner, revisit: fall back to EOA connection or update the contract.\n // if ( easAddress === ZERO_ADDRESS ) {\n // // #region agent log\n // try {\n // fetch('http://127.0.0.1:7242/ingest/0978b378-ebae-46bf-8fd3-134ef2e16cdd',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'4756f9'},body:JSON.stringify({sessionId:'4756f9',location:'actors.ts:setEas-entry',message:'Attempting setEas',data:{easContractAddress:getPublishConfig().easContractAddress,address},timestamp:Date.now()})}).catch(()=>{});\n // } catch { /* noop */ }\n // // #endregion\n // const { easContractAddress } = getPublishConfig()\n // const tx = setEas({\n // contract: smartWalletContract,\n // eas: easContractAddress,\n // },)\n\n // try {\n // const result = await sendTransaction({\n // account,\n // transaction: tx,\n // },)\n\n // const receipt = await waitForReceipt({\n // client: getClient(),\n // chain: optimismSepolia,\n // transactionHash: result.transactionHash,\n // },)\n\n // if ( !receipt ) {\n // // #region agent log\n // fetch('http://127.0.0.1:7242/ingest/0978b378-ebae-46bf-8fd3-134ef2e16cdd',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'4756f9'},body:JSON.stringify({sessionId:'4756f9',location:'actors.ts:setEas-receipt-null',message:'setEas failed: receipt is null',data:{transactionHash:result.transactionHash},timestamp:Date.now()})}).catch(()=>{});\n // // #endregion\n // throw new Error('Failed to set EAS address',)\n // }\n\n // // #region agent log\n // fetch('http://127.0.0.1:7242/ingest/0978b378-ebae-46bf-8fd3-134ef2e16cdd',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'4756f9'},body:JSON.stringify({sessionId:'4756f9',location:'actors.ts:setEas-success',message:'setEas succeeded',data:{transactionHash:result.transactionHash,receiptStatus:receipt.status},timestamp:Date.now()})}).catch(()=>{});\n // // Verify getEas returns expected value after setEas\n // try {\n // const easAfterSet = await getEas({ contract: smartWalletContract }) as string\n // fetch('http://127.0.0.1:7242/ingest/0978b378-ebae-46bf-8fd3-134ef2e16cdd',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'4756f9'},body:JSON.stringify({sessionId:'4756f9',location:'actors.ts:getEas-after-setEas',message:'getEas after setEas',data:{easAddress:easAfterSet,expected:easContractAddress,match:easAfterSet?.toLowerCase()===easContractAddress?.toLowerCase()},timestamp:Date.now()})}).catch(()=>{});\n // } catch (getEasAfterErr: unknown) {\n // const e = getEasAfterErr instanceof Error ? getEasAfterErr : new Error(String(getEasAfterErr))\n // fetch('http://127.0.0.1:7242/ingest/0978b378-ebae-46bf-8fd3-134ef2e16cdd',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'4756f9'},body:JSON.stringify({sessionId:'4756f9',location:'actors.ts:getEas-after-setEas-error',message:'getEas after setEas failed',data:{errorMessage:e.message,errorName:e.name},timestamp:Date.now()})}).catch(()=>{});\n // }\n // // #endregion\n // } catch (setEasErr: unknown) {\n // // #region agent log\n // const err = setEasErr instanceof Error ? setEasErr : new Error(String(setEasErr))\n // fetch('http://127.0.0.1:7242/ingest/0978b378-ebae-46bf-8fd3-134ef2e16cdd',{method:'POST',headers:{'Content-Type':'application/json','X-Debug-Session-Id':'4756f9'},body:JSON.stringify({sessionId:'4756f9',location:'actors.ts:setEas-error',message:'setEas failed',data:{errorMessage:err.message,errorName:err.name,stack:err.stack},timestamp:Date.now()})}).catch(()=>{});\n // // #endregion\n // throw setEasErr\n // }\n // }\n // }\n\n await ensureEasSchemasForItem(item, account, getClient(), optimismSepolia)\n\n // Match by index: createAndSignArweaveTransactions returns results in the same order as publishUploads.\n // Index matching is more reliable than versionLocalId+itemPropertyName, which can fail for storage seeds\n // (e.g. when versionLocalId comes from the parent's property and doesn't uniquely identify the upload).\n // After JSON round-trip (restore), transaction may be a plain object; ensure we read id safely.\n const uploadDataWithTxIds: Array<PublishUpload & { txId: string }> = arweaveTransactions.map((arweaveTransaction: ArweaveTransactionInfo, i: number) => {\n const tx = arweaveTransaction.transaction as { id?: string }\n const txId = tx?.id\n if (!txId || typeof txId !== 'string') {\n throw new Error(\n 'Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.'\n )\n }\n const upload = publishUploads[i] as PublishUpload | undefined\n if (!upload) throw new Error('Publish upload index mismatch')\n return { ...upload, txId }\n })\n\n const requestData = await item.getPublishPayload(uploadDataWithTxIds)\n\n const rawReqs = Array.isArray(requestData) ? requestData : [requestData]\n\n // Normalize bytes32 fields to 0x-prefixed 32-byte (64 hex char) strings so ABI encoding accepts them.\n const BYTES32_LEN = 64\n const toHex32 = (v: unknown): string => {\n if (v == null) return '0x' + '0'.repeat(BYTES32_LEN)\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0').padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n return '0x' + hex\n }\n if (v instanceof Uint8Array || (typeof ArrayBuffer !== 'undefined' && v instanceof ArrayBuffer)) {\n const arr = v instanceof Uint8Array ? v : new Uint8Array(v)\n const hex = Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('')\n return '0x' + hex.padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n }\n return '0x' + '0'.repeat(BYTES32_LEN)\n }\n const toBytesHex = (v: unknown): string => {\n if (v == null || (typeof v === 'string' && (v === '' || v === '0x'))) return '0x'\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0')\n return '0x' + (hex.length % 2 === 1 ? '0' + hex : hex)\n }\n if (v instanceof Uint8Array || (typeof ArrayBuffer !== 'undefined' && v instanceof ArrayBuffer)) {\n const arr = v instanceof Uint8Array ? v : new Uint8Array(v)\n return '0x' + Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('')\n }\n return '0x'\n }\n const reqs = Array.isArray(requestData) ? requestData : [requestData]\n const normalizedRequests = reqs.map((req: any) => {\n const listOfAttestations = (req?.listOfAttestations ?? []).map((att: any) => {\n const dataArr = Array.isArray(att?.data) ? att.data : []\n return {\n schema: toHex32(att?.schema),\n data: dataArr.map((d: any) => ({\n ...d,\n refUID: toHex32(d?.refUID),\n data: toBytesHex(d?.data),\n expirationTime: d?.expirationTime != null ? BigInt(d.expirationTime) : BigInt(0),\n value: d?.value != null ? BigInt(d.value) : BigInt(0),\n })),\n }\n })\n const propertiesToUpdate = (req?.propertiesToUpdate ?? []).map((p: any) => ({\n ...p,\n propertySchemaUid: toHex32(p?.propertySchemaUid),\n }))\n return {\n ...req,\n seedUid: toHex32(req?.seedUid),\n seedSchemaUid: toHex32(req?.seedSchemaUid),\n versionUid: toHex32(req?.versionUid),\n versionSchemaUid: toHex32(req?.versionSchemaUid),\n listOfAttestations,\n propertiesToUpdate,\n }\n })\n\n // Defensive: ensure attestations referenced in propertiesToUpdate have at least one data element.\n // The contract writes the seed UID into data[0].data; empty data causes Panic 50.\n const byLocalId = new Map(normalizedRequests.map((r: any) => [r?.localId, r]))\n const placeholderData = {\n recipient: ZERO_ADDRESS,\n expirationTime: BigInt(0),\n revocable: true,\n refUID: ZERO_BYTES32,\n data: ZERO_BYTES32 as `0x${string}`,\n value: BigInt(0),\n }\n for (const req of normalizedRequests) {\n for (const pu of req?.propertiesToUpdate ?? []) {\n const targetId = pu?.publishLocalId\n const schemaUid = toHex32(pu?.propertySchemaUid)\n if (!targetId || !schemaUid) continue\n const targetReq = byLocalId.get(targetId)\n if (!targetReq?.listOfAttestations) continue\n const att = targetReq.listOfAttestations.find(\n (a: any) => toHex32(a?.schema)?.toLowerCase() === schemaUid?.toLowerCase(),\n )\n if (!att) continue\n if (!Array.isArray(att.data) || att.data.length === 0) {\n att.data = [{ ...placeholderData, refUID: ZERO_BYTES32 }]\n }\n }\n }\n\n const payloadForContract = Array.isArray(requestData) ? normalizedRequests : [normalizedRequests[0]]\n\n const executorPayload = useModularExecutor\n ? transformPayloadForExecutor(payloadForContract)\n : payloadForContract\n\n let managedAccountAddress: string | undefined\n let activeAccount = account\n\n if (useModularExecutor) {\n const managedAccountWallet = getManagedAccountWallet()\n await managedAccountWallet.autoConnect({client: getClient(), chain: optimismSepolia})\n const managedAccount = managedAccountWallet.getAccount()\n if (!managedAccount) {\n throw new Error('Failed to get managed account')\n }\n managedAccountAddress = managedAccount.address\n targetContract = getContract({\n client: getClient(),\n chain: optimismSepolia,\n address: managedAccountAddress,\n })\n const modularAccountWallet = getModularAccountWallet()\n await modularAccountWallet.autoConnect({client: getClient(), chain: optimismSepolia})\n const modularAccount = modularAccountWallet.getAccount()\n if (!modularAccount) {\n throw new Error('Failed to get modular account')\n }\n activeAccount = modularAccount\n }\n\n const tx = {\n ...multiPublish({\n contract: targetContract,\n requests: payloadForContract,\n }),\n gas: 5_000_000n,\n }\n\n // const tx = useModularExecutor\n // ? (async () => {\n // const multiPublishTx = executorMultiPublish({\n // contract: targetContract,\n // requests: executorPayload,\n // })\n // const calldata = await encode(multiPublishTx)\n // return {\n // ...execute({\n // contract: smartWalletContract,\n // target: modularAccountModuleContract!,\n // value: 0n,\n // calldata,\n // }),\n // gas: 5_000_000n,\n // }\n // })()\n // : useIntegerLocalIds\n // ? {\n // ...multiPublishWithIntegerIds({\n // contract: targetContract,\n // requests: transformPayloadToIntegerIds(payloadForContract) as MultiPublishWithIntegerIdsParams['requests'],\n // }),\n // gas: 5_000_000n,\n // }\n // : {\n // ...multiPublish({\n // contract: targetContract,\n // requests: payloadForContract,\n // }),\n // gas: 5_000_000n,\n // }\n\n // TODO: Save this tx in appState so we can recover it later if necessary\n\n const txToSend = await Promise.resolve(tx)\n\n let result: { transactionHash: `0x${string}` }\n try {\n result = await sendTransaction({\n account: activeAccount,\n transaction: txToSend,\n },)\n } catch (sendErr: unknown) {\n throw sendErr\n }\n\n const receipt = await waitForReceipt({\n client: getClient(),\n chain: optimismSepolia,\n transactionHash: result.transactionHash,\n },)\n if ( !receipt ) {\n throw new Error('Failed to send transaction',)\n }\n\n const firstRequest = normalizedRequests[0]\n const firstRequestSeedUid = firstRequest?.seedUid\n const hadZeroSeedUid = firstRequestSeedUid === ZERO_BYTES32 || !firstRequestSeedUid\n const listOfAttestationsCount = firstRequest?.listOfAttestations?.length ?? 0\n const seedSchemaUid = firstRequest?.seedSchemaUid\n const contractAddressForEvents = useModularExecutor && modularAccountModuleContract\n ? modularAccountModuleContract\n : address\n const seedUidFromTx = hadZeroSeedUid\n ? (seedUidFromCreatedAttestationEvents(receipt, seedSchemaUid, useModularExecutor) ??\n seedUidFromSeedPublished(receipt, contractAddressForEvents, listOfAttestationsCount, useModularExecutor))\n : undefined\n const effectiveRequests =\n seedUidFromTx && normalizedRequests.length > 0\n ? [{ ...normalizedRequests[0], seedUid: seedUidFromTx }, ...normalizedRequests.slice(1) ]\n : normalizedRequests\n persistSeedUidFromPublishResult(item as { seedUid?: string }, effectiveRequests)\n // Persist seedUid to the SDK's DB (seeds table) so useItems/useItem show it in the UI\n const itemWithPersist = item as { persistSeedUid?: () => Promise<void> }\n if (effectiveRequests[0]?.seedUid && typeof itemWithPersist.persistSeedUid === 'function') {\n await itemWithPersist.persistSeedUid()\n }\n\n // TODO: Get rid of the publishProcess and clean up any remaining state\n // TODO: Write tests that can ensure that the publish process is working properly\n // TODO: Perhaps as part of the tests, figure out how/why versions are getting their own versions\n // TODO: Implement protected pages based on whether Metamask is connected\n\n logger('result', result,)\n\n logger('requestData', requestData,)\n\n return\n\n},)\n","import { getContract, prepareContractCall, prepareEvent, parseEventLogs } from 'thirdweb'\nimport type { ThirdwebClient } from 'thirdweb'\nimport type { Chain } from 'thirdweb/chains'\nimport { encodeAbiParameters } from 'viem'\nimport { getPublishConfig } from '~/config'\n\nconst attestedEvent = () =>\n prepareEvent({\n signature:\n 'event Attested(address indexed recipient, address indexed attester, bytes32 uid, bytes32 indexed schemaUID)',\n })\n\nconst ZERO_ADDRESS = '0x0000000000000000000000000000000000000000' as const\nconst ZERO_BYTES32 = ('0x' + '0'.repeat(64)) as `0x${string}`\n\nexport type EasAttestParams = {\n schema: `0x${string}`\n data: {\n recipient?: `0x${string}`\n expirationTime?: bigint\n revocable?: boolean\n refUID: `0x${string}`\n data: `0x${string}`\n value?: bigint\n }\n}\n\n/**\n * Prepares a single EAS attest call.\n * Used for Seed and Version attestations in the direct-to-EAS publish path.\n */\nexport function prepareEasAttest(\n client: ThirdwebClient,\n chain: Chain,\n params: EasAttestParams,\n) {\n const { easContractAddress } = getPublishConfig()\n const contract = getContract({\n client,\n chain,\n address: easContractAddress as `0x${string}`,\n })\n\n return prepareContractCall({\n contract,\n method:\n 'function attest((bytes32 schema,(address recipient,uint64 expirationTime,bool revocable,bytes32 refUID,bytes data,uint256 value) data) request) payable returns (bytes32)' as const,\n params: [\n {\n schema: params.schema,\n data: {\n recipient: (params.data.recipient ?? ZERO_ADDRESS) as `0x${string}`,\n expirationTime: params.data.expirationTime ?? 0n,\n revocable: params.data.revocable ?? true,\n refUID: params.data.refUID,\n data: params.data.data,\n value: params.data.value ?? 0n,\n },\n },\n ],\n })\n}\n\nexport type MultiAttestationRequest = {\n schema: `0x${string}`\n data: Array<{\n recipient: `0x${string}`\n expirationTime: bigint\n revocable: boolean\n refUID: `0x${string}`\n data: `0x${string}`\n value: bigint\n }>\n}\n\n/**\n * Prepares an EAS multiAttest call for batch attestations.\n * Used for property attestations in the direct-to-EAS publish path.\n */\nexport function prepareEasMultiAttest(\n client: ThirdwebClient,\n chain: Chain,\n requests: MultiAttestationRequest[],\n) {\n const { easContractAddress } = getPublishConfig()\n const contract = getContract({\n client,\n chain,\n address: easContractAddress as `0x${string}`,\n })\n\n return prepareContractCall({\n contract,\n method:\n 'function multiAttest((bytes32 schema,(address recipient,uint64 expirationTime,bool revocable,bytes32 refUID,bytes data,uint256 value)[] data)[] requests) payable returns (bytes32[])' as const,\n params: [requests],\n } as Parameters<typeof prepareContractCall>[0])\n}\n\n/**\n * Encodes a bytes32 value for Seed/Version attestation data.\n * Equivalent to Solidity abi.encode(bytes32).\n */\nexport function encodeBytes32(value: `0x${string}`): `0x${string}` {\n return encodeAbiParameters([{ type: 'bytes32' }], [value]) as `0x${string}`\n}\n\n/**\n * Extracts the attestation UID from an EAS attest transaction receipt.\n * Parses the Attested event from the receipt logs.\n */\nexport function getAttestationUidFromReceipt(\n receipt: { logs?: Array<{ address?: string; data?: string; topics?: unknown[] }> },\n easContractAddress: string,\n): string | undefined {\n if (!receipt.logs?.length) return undefined\n const want = easContractAddress.toLowerCase()\n const logs = receipt.logs.filter((l) => l.address && l.address.toLowerCase() === want)\n if (!logs.length) return undefined\n try {\n const parsed = parseEventLogs({\n logs: logs as import('viem').Log[],\n events: [attestedEvent()],\n strict: false,\n })\n const first = parsed[0]\n const uid = first?.args?.uid as string | undefined\n if (uid && uid !== ZERO_BYTES32) return uid\n } catch {\n // ignore\n }\n return undefined\n}\n\nexport { ZERO_ADDRESS, ZERO_BYTES32 }\n","import { fromPromise } from 'xstate'\nimport type { PublishMachineContext } from '../../../types'\nimport { ZERO_ADDRESS } from '@ethereum-attestation-service/eas-sdk'\nimport { sendTransaction, waitForReceipt } from 'thirdweb'\nimport { optimismSepolia } from 'thirdweb/chains'\nimport { getClient } from '~/helpers/thirdweb'\nimport { Item } from '@seedprotocol/sdk'\nimport type { PublishUpload } from '../../../types'\nimport { persistSeedUidFromPublishResult } from './persistSeedUid'\nimport { ensureEasSchemasForItem } from '../helpers/ensureEasSchemas'\nimport { getPublishConfig } from '~/config'\nimport {\n prepareEasAttest,\n prepareEasMultiAttest,\n encodeBytes32,\n ZERO_BYTES32,\n getAttestationUidFromReceipt,\n type MultiAttestationRequest,\n} from '~/helpers/easDirect'\nimport type { ArweaveTransactionInfo } from '../../../types'\nimport debug from 'debug'\n\nconst logger = debug('seedProtocol:services:publish:createAttestationsDirectToEas')\n\nconst BYTES32_LEN = 64\nconst toHex32 = (v: unknown): string => {\n if (v == null) return '0x' + '0'.repeat(BYTES32_LEN)\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0').padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n return '0x' + hex\n }\n if (v instanceof Uint8Array || (typeof ArrayBuffer !== 'undefined' && v instanceof ArrayBuffer)) {\n const arr = v instanceof Uint8Array ? v : new Uint8Array(v)\n const hex = Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('')\n return '0x' + hex.padStart(BYTES32_LEN, '0').slice(-BYTES32_LEN)\n }\n return '0x' + '0'.repeat(BYTES32_LEN)\n}\nconst toBytesHex = (v: unknown): string => {\n if (v == null || (typeof v === 'string' && (v === '' || v === '0x'))) return '0x'\n if (typeof v === 'string') {\n const raw = v.startsWith('0x') ? v.slice(2) : v\n const hex = raw.replace(/[^0-9a-fA-F]/g, '0')\n return '0x' + (hex.length % 2 === 1 ? '0' + hex : hex)\n }\n if (v instanceof Uint8Array || (typeof ArrayBuffer !== 'undefined' && v instanceof ArrayBuffer)) {\n const arr = v instanceof Uint8Array ? v : new Uint8Array(v)\n return '0x' + Array.from(arr).map((b) => b.toString(16).padStart(2, '0')).join('')\n }\n return '0x'\n}\n\nconst waitForItem = async (seedLocalId: string): Promise<InstanceType<typeof Item>> => {\n let item: InstanceType<typeof Item> | undefined\n try {\n item = await Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n } catch {\n // No-op\n }\n if (item) return item\n return new Promise<InstanceType<typeof Item>>((resolve) => {\n const interval = setInterval(() => {\n try {\n Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n .then((found: InstanceType<typeof Item> | undefined) => {\n if (found) {\n clearInterval(interval)\n resolve(found)\n }\n })\n } catch {\n // No-op\n }\n }, 200)\n })\n}\n\ntype PublishInput = { input: { context: PublishMachineContext; event: unknown } }\n\ntype NormalizedRequest = {\n localId: string\n seedUid: string\n seedSchemaUid: string\n versionUid: string\n versionSchemaUid: string\n seedIsRevocable: boolean\n listOfAttestations: Array<{\n schema: string\n data: Array<{\n recipient: string\n expirationTime: bigint\n revocable: boolean\n refUID: string\n data: string\n value: bigint\n }>\n }>\n propertiesToUpdate: Array<{ publishLocalId: string; propertySchemaUid: string }>\n}\n\nexport const createAttestationsDirectToEas = fromPromise(\n async ({ input: { context, event } }: PublishInput): Promise<void> => {\n const { address, account } = context\n const arweaveTransactions = context.arweaveTransactions ?? []\n const publishUploads = context.publishUploads ?? []\n let { item } = context\n\n if (!address || typeof address !== 'string' || !address.trim()) {\n throw new Error('No wallet address for publish. Connect a wallet and try again.')\n }\n\n if (!account) {\n throw new Error('Wallet session is missing. Reconnect your wallet and retry the publish.')\n }\n\n if (!item?.seedLocalId) {\n throw new Error(\n 'Attestation recovery failed: Item data is missing. Delete this publish record and try a full publish from the beginning.',\n )\n }\n if (typeof item.getPublishUploads !== 'function') {\n item = await waitForItem(item.seedLocalId)\n }\n\n const txCount = arweaveTransactions.length\n const uploadCount = publishUploads.length\n if (txCount !== uploadCount) {\n throw new Error(\n 'Attestation recovery failed: Arweave transaction data is missing or incomplete. Delete this publish record and try a full publish from the beginning.',\n )\n }\n\n await ensureEasSchemasForItem(item, account, getClient(), optimismSepolia)\n\n const uploadDataWithTxIds: Array<PublishUpload & { txId: string }> = arweaveTransactions.map(\n (arweaveTransaction: ArweaveTransactionInfo, i: number) => {\n const tx = arweaveTransaction.transaction as { id?: string }\n const txId = tx?.id\n if (!txId || typeof txId !== 'string') {\n throw new Error(\n 'Attestation recovery failed: Arweave transaction data did not survive restore. Delete this publish record and try a full publish from the beginning.',\n )\n }\n const upload = publishUploads[i] as PublishUpload | undefined\n if (!upload) throw new Error('Publish upload index mismatch')\n return { ...upload, txId }\n },\n )\n\n const requestData = await item.getPublishPayload(uploadDataWithTxIds)\n const reqs = Array.isArray(requestData) ? requestData : [requestData]\n\n const normalizedRequests: NormalizedRequest[] = reqs.map((req: any) => {\n const listOfAttestations = (req?.listOfAttestations ?? []).map((att: any) => {\n const dataArr = Array.isArray(att?.data) ? att.data : []\n return {\n schema: toHex32(att?.schema),\n data: dataArr.map((d: any) => ({\n ...d,\n refUID: toHex32(d?.refUID),\n data: toBytesHex(d?.data),\n })),\n }\n })\n const propertiesToUpdate = (req?.propertiesToUpdate ?? []).map((p: any) => ({\n ...p,\n propertySchemaUid: toHex32(p?.propertySchemaUid),\n }))\n return {\n ...req,\n seedUid: toHex32(req?.seedUid),\n seedSchemaUid: toHex32(req?.seedSchemaUid),\n versionUid: toHex32(req?.versionUid),\n versionSchemaUid: toHex32(req?.versionSchemaUid),\n listOfAttestations,\n propertiesToUpdate,\n }\n })\n\n const byLocalId = new Map(normalizedRequests.map((r) => [r.localId, r]))\n const placeholderData = {\n recipient: ZERO_ADDRESS,\n expirationTime: BigInt(0),\n revocable: true,\n refUID: ZERO_BYTES32,\n data: ZERO_BYTES32 as `0x${string}`,\n value: BigInt(0),\n }\n for (const req of normalizedRequests) {\n for (const pu of req.propertiesToUpdate ?? []) {\n const targetId = pu.publishLocalId\n const schemaUid = toHex32(pu.propertySchemaUid)\n if (!targetId || !schemaUid) continue\n const targetReq = byLocalId.get(targetId)\n if (!targetReq?.listOfAttestations) continue\n const att = targetReq.listOfAttestations.find(\n (a) => toHex32(a?.schema)?.toLowerCase() === schemaUid?.toLowerCase(),\n )\n if (!att) continue\n if (!Array.isArray(att.data) || att.data.length === 0) {\n att.data = [{ ...placeholderData, refUID: ZERO_BYTES32 }]\n }\n }\n }\n\n const client = getClient()\n\n for (let i = 0; i < normalizedRequests.length; i++) {\n const request = normalizedRequests[i] as NormalizedRequest\n let newSeedUid = request.seedUid\n let newVersionUid = request.versionUid\n\n if (newSeedUid === ZERO_BYTES32) {\n const attestTx = prepareEasAttest(client, optimismSepolia, {\n schema: request.seedSchemaUid as `0x${string}`,\n data: {\n refUID: ZERO_BYTES32,\n data: encodeBytes32(request.seedSchemaUid as `0x${string}`),\n revocable: request.seedIsRevocable,\n },\n })\n const result = await sendTransaction({ account, transaction: attestTx })\n const receipt = await waitForReceipt({\n client,\n chain: optimismSepolia,\n transactionHash: result.transactionHash,\n })\n if (!receipt) throw new Error('Failed to create Seed attestation')\n const { easContractAddress } = getPublishConfig()\n const seedUidFromReceipt = getAttestationUidFromReceipt(receipt, easContractAddress)\n if (!seedUidFromReceipt || seedUidFromReceipt === ZERO_BYTES32) {\n throw new Error('Failed to get Seed UID from attestation receipt')\n }\n newSeedUid = seedUidFromReceipt\n request.seedUid = seedUidFromReceipt\n logger('created Seed attestation', newSeedUid)\n }\n\n if (newSeedUid !== ZERO_BYTES32 && newVersionUid === ZERO_BYTES32) {\n const attestTx = prepareEasAttest(client, optimismSepolia, {\n schema: request.versionSchemaUid as `0x${string}`,\n data: {\n refUID: newSeedUid as `0x${string}`,\n data: encodeBytes32(request.versionSchemaUid as `0x${string}`),\n revocable: true,\n },\n })\n const result = await sendTransaction({ account, transaction: attestTx })\n const receipt = await waitForReceipt({\n client,\n chain: optimismSepolia,\n transactionHash: result.transactionHash,\n })\n if (!receipt) throw new Error('Failed to create Version attestation')\n const { easContractAddress } = getPublishConfig()\n const versionUidFromReceipt = getAttestationUidFromReceipt(receipt, easContractAddress)\n if (!versionUidFromReceipt || versionUidFromReceipt === ZERO_BYTES32) {\n throw new Error('Failed to get Version UID from attestation receipt')\n }\n newVersionUid = versionUidFromReceipt\n request.versionUid = versionUidFromReceipt\n logger('created Version attestation', newVersionUid)\n }\n\n for (const att of request.listOfAttestations) {\n for (const d of att.data) {\n d.refUID = newVersionUid\n }\n }\n\n for (const pu of request.propertiesToUpdate ?? []) {\n const targetReq = byLocalId.get(pu.publishLocalId)\n if (!targetReq?.listOfAttestations) continue\n const schemaUid = toHex32(pu.propertySchemaUid)\n const att = targetReq.listOfAttestations.find(\n (a) => toHex32(a?.schema)?.toLowerCase() === schemaUid?.toLowerCase(),\n )\n if (!att?.data?.[0]) continue\n att.data[0].data = encodeBytes32(newSeedUid as `0x${string}`)\n }\n\n const multiRequests: MultiAttestationRequest[] = request.listOfAttestations.map((att) => ({\n schema: att.schema as `0x${string}`,\n data: att.data.map((d) => ({\n recipient: (d.recipient ?? ZERO_ADDRESS) as `0x${string}`,\n expirationTime: d.expirationTime ?? 0n,\n revocable: d.revocable ?? true,\n refUID: (d.refUID ?? ZERO_BYTES32) as `0x${string}`,\n data: (d.data ?? '0x') as `0x${string}`,\n value: d.value ?? 0n,\n })),\n }))\n\n if (multiRequests.length > 0) {\n const multiTx = prepareEasMultiAttest(client, optimismSepolia, multiRequests)\n const result = await sendTransaction({ account, transaction: multiTx })\n const receipt = await waitForReceipt({\n client,\n chain: optimismSepolia,\n transactionHash: result.transactionHash,\n })\n if (!receipt) throw new Error('Failed to create property attestations')\n logger('created property attestations for request', i)\n }\n }\n\n persistSeedUidFromPublishResult(item as { seedUid?: string }, normalizedRequests)\n const itemWithPersist = item as { persistSeedUid?: () => Promise<void> }\n if (\n normalizedRequests[0]?.seedUid &&\n normalizedRequests[0].seedUid !== ZERO_BYTES32 &&\n typeof itemWithPersist.persistSeedUid === 'function'\n ) {\n await itemWithPersist.persistSeedUid()\n }\n\n logger('direct EAS publish complete')\n },\n)\n","import { Item } from '@seedprotocol/sdk'\n\ntype ItemInstance = InstanceType<typeof Item>\n\n/**\n * Resolve a full Item (with getPublishUploads) by seedLocalId, polling until found.\n * Used when the input item might not have the data needed for the \"needs Arweave\" check.\n */\nconst resolveItem = async (seedLocalId: string): Promise<ItemInstance> => {\n let item: ItemInstance | undefined\n try {\n item = await Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n } catch {\n // No-op: Error is intentionally ignored\n }\n if (item) return item\n\n return new Promise<ItemInstance>((resolve) => {\n const interval = setInterval(() => {\n Item.find({ seedLocalId } as Parameters<typeof Item.find>[0])\n .then((found: ItemInstance | undefined) => {\n if (found) {\n clearInterval(interval)\n resolve(found)\n }\n })\n .catch(() => {})\n }, 200)\n })\n}\n\n/**\n * Returns true if the item needs the Arweave upload path (reimbursement, poll, upload)\n * before creating attestations. Returns false when the item has no storage or no values\n * to upload, in which case the publish flow can skip straight to EAS.\n *\n * Uses item.getPublishUploads(): empty array means \"no storage or no values to upload\",\n * non-empty means at least one property has storageType and a value (needs Arweave).\n * If the SDK later exposes ItemProperties with propertyDef and value in a non-React\n * context, this could be replaced by an explicit check using propertyDef.storageType\n * and itemProperty.value.\n */\nexport async function itemNeedsArweaveUpload(item: ItemInstance): Promise<boolean> {\n const resolved = typeof item.getPublishUploads === 'function'\n ? item\n : await resolveItem(item.seedLocalId)\n const publishUploads = await resolved.getPublishUploads()\n return publishUploads.length > 0\n}\n","import type { PublishMachineContext } from '../../../types'\n\ntype FromCallbackInput<T> = { context: T; event?: unknown }\nimport { EventObject, fromCallback } from \"xstate\";\nimport { itemNeedsArweaveUpload } from \"../helpers/itemNeedsArweave\";\n\nconst activePublishProcesses = new Set<string>()\n\nexport const checking = fromCallback<\n EventObject, \n FromCallbackInput<PublishMachineContext>\n>(( {sendBack, input: {context, }, }, ) => {\n const { item, } = context\n\n const _check = async () => {\n if (activePublishProcesses.has(item.seedLocalId)) {\n sendBack({\n type : 'redundantPublishProcess',\n },)\n return\n }\n\n activePublishProcesses.add(item.seedLocalId)\n\n try {\n const needsArweave = await itemNeedsArweaveUpload(item)\n if (needsArweave) {\n sendBack({ type: 'validPublishProcess' })\n } else {\n sendBack({ type: 'skipArweave' })\n }\n } catch (err) {\n activePublishProcesses.delete(item.seedLocalId)\n console.error('[checking] itemNeedsArweaveUpload failed', err)\n sendBack({ type: 'skipArweave' })\n }\n }\n\n _check().catch(() => {\n activePublishProcesses.delete(item.seedLocalId)\n sendBack({ type: 'validPublishProcess' })\n })\n\n return () => {\n activePublishProcesses.delete(item.seedLocalId)\n }\n})\n","import type { Account } from 'thirdweb/wallets'\nimport { setup, assign, } from 'xstate'\nimport {\n ArweaveTransactionInfo,\n PublishMachineContext,\n ReimbursementResponse,\n PublishUpload,\n} from '../../types'\nimport {\n createArweaveTransactions,\n createAttestations,\n sendReimbursementRequest,\n pollForConfirmation,\n uploadData,\n} from './actors'\nimport { createAttestationsDirectToEas } from './actors/createAttestationsDirectToEas'\nimport { checking, } from './actors/checking'\nimport {\n PublishMachineStates,\n} from '~/helpers/constants'\nimport { getPublishConfig } from '~/config'\n\n\nconst {\n SUCCESS,\n FAILURE,\n} = PublishMachineStates\n\nexport const publishMachine = setup({\n types : {\n context : {} as Partial<PublishMachineContext>,\n input : {} as Partial<PublishMachineContext> | undefined,\n },\n actors : {\n createArweaveTransactions,\n sendReimbursementRequest,\n pollForConfirmation,\n uploadData,\n createAttestations,\n createAttestationsDirectToEas,\n checking,\n },\n actions : {\n /** Log error; error/errorStep are assigned per transition. */\n handleError : ( { event, }, ) => {\n console.error(event.error,)\n },\n assignErrorCreatingArweaveTransactions : assign({\n error : ( { event, }, ) => event.error,\n errorStep : () => 'creatingArweaveTransactions',\n },),\n assignErrorSendingReimbursementRequest : assign({\n error : ( { event, }, ) => event.error,\n errorStep : () => 'sendingReimbursementRequest',\n },),\n assignErrorPollingForConfirmation : assign({\n error : ( { event, }, ) => event.error,\n errorStep : () => 'pollingForConfirmation',\n },),\n assignErrorUploadingData : assign({\n error : ( { event, }, ) => event.error,\n errorStep : () => 'uploadingData',\n },),\n assignErrorCreatingAttestations : assign({\n error : ( { event, }, ) => event.error,\n errorStep : () => 'creatingAttestations',\n },),\n assignErrorCreatingAttestationsDirectToEas : assign({\n error : ( { event, }, ) => event.error,\n errorStep : () => 'creatingAttestationsDirectToEas',\n },),\n assignAccountFromRetry : assign({\n account : ( { event, }, ) => (event as { account?: Account }).account,\n },),\n },\n\n},).createMachine({\n id : 'publish',\n initial : 'checking',\n context : ( { input, }, ) => input as PublishMachineContext,\n states : {\n checking : {\n on: {\n redundantPublishProcess: {\n target: 'stopping',\n },\n validPublishProcess: {\n target: 'creatingArweaveTransactions',\n },\n skipArweave: [\n {\n guard: () => getPublishConfig().useDirectEas,\n target: 'creatingAttestationsDirectToEas',\n actions: assign({\n arweaveTransactions: () => [],\n publishUploads: () => [],\n }),\n },\n {\n guard: () => !getPublishConfig().useDirectEas,\n target: 'creatingAttestations',\n actions: assign({\n arweaveTransactions: () => [],\n publishUploads: () => [],\n }),\n },\n ],\n },\n invoke : {\n src : 'checking',\n input : ( { context } ) => ({ context } as { context: PublishMachineContext }),\n },\n },\n creatingArweaveTransactions : {\n invoke : {\n src : 'createArweaveTransactions',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : 'sendingReimbursementRequest',\n actions : assign({\n arweaveTransactions : ( { event, }, ) => event.output.arweaveTransactions as ArweaveTransactionInfo[],\n publishUploads : ( { event, }, ) => event.output.publishUploads as PublishUpload[],\n },),\n },\n onError : {\n target : 'failure',\n actions : [ 'assignErrorCreatingArweaveTransactions', 'handleError', ],\n },\n },\n },\n sendingReimbursementRequest : {\n invoke : {\n src : 'sendReimbursementRequest',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : 'pollingForConfirmation',\n actions : assign({\n requestResponse : ( { event, }, ) => event.output as ReimbursementResponse,\n reimbursementTransactionId : ( { event, }, ) => (event.output as ReimbursementResponse).transactionId as string,\n },),\n },\n onError : {\n target : 'failure',\n actions : [ 'assignErrorSendingReimbursementRequest', 'handleError', ],\n },\n },\n },\n pollingForConfirmation : {\n invoke : {\n src : 'pollForConfirmation',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : 'uploadingData',\n actions : assign({\n reimbursementConfirmed : true,\n },),\n },\n onError : {\n target : 'failure',\n actions : [ 'assignErrorPollingForConfirmation', 'handleError', ],\n },\n }\n },\n uploadingData : {\n on : {\n updatePercentage : {\n actions : assign({\n completionPercentage : ( { event, }, ) => {\n console.log('updatePercentage', event,)\n return event.percentage as number\n\n },\n },),\n },\n uploadComplete : [\n {\n guard: () => getPublishConfig().useDirectEas,\n target: 'creatingAttestationsDirectToEas',\n actions: assign({\n completionPercentage: 100,\n }),\n },\n {\n guard: () => !getPublishConfig().useDirectEas,\n target: 'creatingAttestations',\n actions: assign({\n completionPercentage: 100,\n }),\n },\n ],\n uploadError : {\n target : 'failure',\n actions : [ 'assignErrorUploadingData', 'handleError', ],\n },\n },\n invoke : {\n src : 'uploadData',\n input : ( { context } ) => ({ context }) as { context: PublishMachineContext },\n },\n },\n creatingAttestations : {\n invoke : {\n src : 'createAttestations',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : SUCCESS,\n },\n onError : {\n target : 'attestationFailureRecoverable',\n actions : [ 'assignErrorCreatingAttestations', 'handleError', ],\n },\n },\n },\n attestationFailureRecoverable : {\n on : {\n retry : {\n target : 'creatingAttestations',\n actions : [ 'assignAccountFromRetry', ],\n },\n },\n },\n creatingAttestationsDirectToEas : {\n invoke : {\n src : 'createAttestationsDirectToEas',\n input : ( { context, event } ) => ({ context, event } as { context: PublishMachineContext; event: unknown }),\n onDone : {\n target : SUCCESS,\n },\n onError : {\n target : 'attestationFailureRecoverableDirectToEas',\n actions : [ 'assignErrorCreatingAttestationsDirectToEas', 'handleError', ],\n },\n },\n },\n attestationFailureRecoverableDirectToEas : {\n on : {\n retry : {\n target : 'creatingAttestationsDirectToEas',\n actions : [ 'assignAccountFromRetry', ],\n },\n },\n },\n stopping: {\n entry: ( { context }: { context: Partial<PublishMachineContext> } ) => {\n console.log(`Actor for ${context.item?.seedLocalId} stopped`,)\n },\n type: 'final',\n },\n [SUCCESS] : {\n type : 'final',\n },\n [FAILURE] : {\n type : 'final',\n },\n },\n},)\n\n\n"],"names":["SCHEMA_REGISTRY_ADDRESS","EAS_SCHEMA_NAME_ATTESTATION_UID","THIRDWEB_ACCOUNT_FACTORY_ADDRESS","EAS_CONTRACT_ADDRESS","PublishMachineStates","getConfig","v","setConfig","c","initPublish","getPublishConfig","config","REACT_ELEMENT_TYPE","REACT_FRAGMENT_TYPE","jsxProd","type","maybeKey","key","propName","reactJsxRuntime_production","getComponentNameFromType","REACT_CLIENT_REFERENCE","REACT_PROFILER_TYPE","REACT_STRICT_MODE_TYPE","REACT_SUSPENSE_TYPE","REACT_SUSPENSE_LIST_TYPE","REACT_ACTIVITY_TYPE","REACT_PORTAL_TYPE","REACT_CONTEXT_TYPE","REACT_CONSUMER_TYPE","REACT_FORWARD_REF_TYPE","innerType","REACT_MEMO_TYPE","REACT_LAZY_TYPE","testStringCoercion","value","checkKeyStringCoercion","JSCompiler_inline_result","JSCompiler_temp_const","JSCompiler_inline_result$jscomp$0","getTaskName","name","getOwner","dispatcher","ReactSharedInternals","UnknownOwner","hasValidKey","hasOwnProperty","getter","defineKeyPropWarningGetter","props","displayName","warnAboutAccessingKey","specialPropKeyWarningShown","elementRefGetterWithDeprecationWarning","componentName","didWarnAboutElementRef","ReactElement","owner","debugStack","debugTask","refProp","jsxDEVImpl","isStaticChildren","children","isArrayImpl","validateChildKeys","keys","k","didWarnAboutKeySpread","node","isValidElement","object","React","require$$0","createTask","callStackForError","unknownOwnerDebugStack","unknownOwnerDebugTask","reactJsxRuntime_development","trackActualOwner","jsxRuntimeModule","require$$1","getAddress","options","readContract","createAccount","prepareContractCall","s","m","h","d","w","y","ms","val","parse","fmtLong","fmtShort","str","match","n","msAbs","plural","isPlural","setup","env","createDebug","coerce","disable","enable","enabled","destroy","selectColor","namespace","hash","i","prevTime","enableOverride","namespacesCache","enabledCache","debug","args","self","curr","index","format","formatter","extend","delimiter","newDebug","namespaces","split","ns","matchesTemplate","search","template","searchIndex","templateIndex","starIndex","matchIndex","skip","common","exports","formatArgs","save","load","useColors","localstorage","warned","module","lastC","r","formatters","error","logger","_client","getClient","thirdwebClientId","createThirdwebClient","wallets","createWallet","useLocalWalletAccount","localWalletAccount","setLocalWalletAccount","useState","useRef","useEffect","useActiveSmartWalletContract","account","useActiveAccount","contract","setContract","getContract","optimismSepolia","getManagedAccountFactoryContract","thirdwebAccountFactoryAddress","getSmartWalletAddressForAdmin","adminAddress","data","factory","getFactoryAddress","isSmartWalletDeployed","smartWalletAddress","isContractDeployed","resolveSmartWalletForPublish","ExternalWalletsForDeploy","deploySmartWalletContract","localAccount","managedAccountFactoryContract","createAccountTx","result","sendTransaction","receipt","waitForReceipt","appMetadata","getManagedAccountWallet","inAppWallet","getModularAccountWallet","getWalletsForConnectButton","version","BaseError","shortMessage","details","docsPath","message","execTyped","regex","string","bytesRegex","integerRegex","isTupleRegex","errorSignatureRegex","isErrorSignature","signature","execErrorSignature","eventSignatureRegex","isEventSignature","execEventSignature","functionSignatureRegex","isFunctionSignature","execFunctionSignature","structSignatureRegex","isStructSignature","execStructSignature","constructorSignatureRegex","isConstructorSignature","execConstructorSignature","fallbackSignatureRegex","isFallbackSignature","execFallbackSignature","receiveSignatureRegex","isReceiveSignature","eventModifiers","functionModifiers","InvalidAbiItemError","UnknownTypeError","UnknownSolidityTypeError","InvalidParameterError","param","SolidityProtectedKeywordError","InvalidModifierError","modifier","InvalidFunctionModifierError","InvalidAbiTypeParameterError","abiParameter","InvalidSignatureError","UnknownSignatureError","InvalidStructSignatureError","CircularReferenceError","InvalidParenthesisError","current","depth","getParameterCacheKey","structs","structKey","struct","propertyKey","property","parameterCache","parseSignature","parseFunctionSignature","parseEventSignature","parseErrorSignature","parseConstructorSignature","parseFallbackSignature","inputParams","splitParameters","inputs","inputLength","parseAbiParameter","outputs","outputParams","outputLength","params","abiParameters","length","abiParameterWithoutTupleRegex","abiParameterWithTupleRegex","dynamicIntegerRegex","parameterCacheKey","isTuple","isSolidityKeyword","indexed","components","components_","isSolidityType","isValidDataLocation","char","tail","protectedKeywordsRegex","isArray","parseStructs","signatures","shallowStructs","signaturesLength","properties","propertiesLength","trimmed","resolvedStructs","entries","entriesLength","parameters","resolveStructs","typeWithoutTupleRegex","ancestors","array","parseAbiItem","abiItem","signature_","tupleRegex","formatAbiParameter","component","formatAbiParameters","formatAbiItem","formatAbiParams","includeName","formatAbiParam","isHex","strict","size","errorConfig","docsBaseUrl","docsSlug","docsUrl","fn","walk","err","offset","position","targetSize","pad","hexOrBytes","dir","padHex","padBytes","hex_","hex","SizeExceedsPaddingSizeError","bytes","paddedBytes","padEnd","max","min","signed","givenSize","maxSize","trim","sliceLength","assertSize","size_","SizeOverflowError","hexToBigInt","opts","hexToNumber","hexes","_v","toHex","numberToHex","stringToHex","boolToHex","bytesToHex","value_","maxValue","minValue","suffix","IntegerOutOfRangeError","encoder","toBytes","numberToBytes","boolToBytes","hexToBytes","stringToBytes","charCodeMap","charCodeToBase16","hexString","j","nibbleLeft","nibbleRight","U32_MASK64","_32n","fromBig","le","lst","len","Ah","Al","l","rotlSH","rotlSL","rotlBH","rotlBL","isBytes","a","anumber","abytes","b","lengths","aexists","instance","checkFinished","aoutput","out","u32","arr","clean","arrays","isLE","byteSwap","word","byteSwap32","swap32IfBE","u","utf8ToBytes","Hash$1","createHasher","hashCons","hashC","msg","tmp","_0n","_1n","_2n","_7n","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","R","x","t","IOTAS","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","rotlL","keccakP","rounds","B","idx1","idx0","B0","B1","Th","Tl","curH","curL","shift","PI","Keccak","Hash","blockLen","outputLen","enableXOF","state","pos","take","bufferOut","to","gen","keccak_256","keccak256","to_","hashSignature","sig","normalizeSignature","active","level","valid","toSignature","def","def_","toSignatureHash","firstKey","checksumAddressCache","LruMap","checksumAddress","address_","chainId","hexAddress","address","slice","start","end","sliceHex","sliceBytes","assertStartOffset","SliceOffsetOutOfBoundsError","assertEndOffset","getArrayComponents","matches","toFunctionSelector","count","limit","staticCursor","RecursiveReadLimitExceededError","PositionOutOfBoundsError","NegativeOffsetError","position_","byte","oldPosition","createCursor","recursiveReadLimit","cursor","bytesToBigInt","bytesToBool","bytes_","InvalidBytesBooleanError","bytesToNumber","bytesToString","decodeAbiParameters","AbiDecodingZeroDataError","AbiDecodingDataSizeTooSmallError","consumed","values","consumed_","decodeParameter","staticPosition","arrayComponents","decodeArray","decodeTuple","decodeAddress","decodeBool","decodeBytes","decodeNumber","decodeString","InvalidAbiDecodingTypeError","sizeOfLength","sizeOfOffset","startOfData","dynamicChild","hasDynamicChild","_","hasUnnamedChild","getVersion","docs","bigIntSuffix","stringify","replacer","space","Bytes.size","Bytes.SizeOverflowError","Bytes.SizeExceedsPaddingSizeError","Hex.size","Hex.SizeOverflowError","Hex.SliceOffsetOutOfBoundsError","Hex.SizeExceedsPaddingSizeError","fromHex","internal_hex.assertSize","Hex.padRight","internal.charCodeToBase16","Errors.BaseError","fromString","internal.assertSize","padRight","internal.pad","assert","InvalidHexTypeError","InvalidHexValueError","concat","acc","fromBoolean","padLeft","fromBytes","fromNumber","internal.assertStartOffset","internal.assertEndOffset","Bytes.fromHex","validate","Json.stringify","ox__Hex.validate","ox__Hex.padRight","ox__Hex.padLeft","hexToUint8Array","ox__Hex.toBytes","ox__Hex.fromBoolean","ox__Hex.fromNumber","ox__Hex.fromString","encodeStateOverrides","overrides","override","eth_call","request","blockNumber","blockTag","txRequest","block","DEFAULT_RPC_URL","DEFAULT_SOCIAL_URL","DEFAULT_IN_APP_WALLET_URL","DEFAULT_PAY_URL","DEFAULT_STORAGE_URL","DEFAULT_BUNDLER_URL","DEFAULT_ANALYTICS_URL","DEFAULT_INSIGHT_URL","DEFAULT_ENGINE_CLOUD_URL","DEFAULT_BRIDGE_URL","domains","getThirdwebDomains","operatingSystemRules","detectPlatform","detectOS","ua","ii","os","isJWT","IS_DEV","DEFAULT_REQUEST_TIMEOUT","getClientFetch","client","ecosystem","fetchWithHeaders","url","init","requestTimeoutMs","useAuthToken","restInit","headers","urlString","isThirdwebUrl","authToken","secretKey","clientId","isBundlerUrl","isPayUrl","isInAppWalletUrl","getPlatformHeaders","controller","abortTimeout","THIRDWEB_DOMAINS","IS_THIRDWEB_URL_CACHE","hostname","is","domain","SDK_NAME","previousPlatform","bundleId","parseOs","osLowerCased","getRpcUrlForChain","baseRpcUrl","rpc","rpcUrl","fetchRpc","response","fetchSingleRpc","RPC_CLIENT_MAP","getRpcClientMap","rpcClientMap","rpcRequestKey","DEFAULT_MAX_BATCH_SIZE","DEFAULT_BATCH_TIMEOUT_MS","getRpcClient","rpcClient","batchSize","batchTimeoutMs","inflightRequests","pendingBatch","pendingBatchTimeout","sendPendingBatch","requests","activeBatch","inflight","responses","rpcResponse","requestKey","resolve","reject","promise","resolve_","reject_","ox__Bytes.fromString","wrapConstructor","ADDRESS_REGEX","IS_ADDRESS_CACHE","isAddress","byteSize","encodeAbiParameters","preparedParams","prepareParams","encodeParams","prepareParam","encodeArray","encodeTuple","encodeAddress","encodeBool","encodeNumber","encodeBytes","encodeString","staticSize","dynamic","encoded","staticParams","dynamicParams","dynamicSize","ox__Hex.concat","preparedParam","length_","paramSize","bytesSize","hexValue","partsLength","parts","ox__Hex.slice","param_","prepareMethodCache","prepareMethod","method","abiFn","ret","resolvePromisedValue","isAbiFunction","item","resolvePreparedMethod","abiFunction","resolvedPreparedMethod","resolvedParams","encodedData","rpcRequest","decoded","FN_SELECTOR","FN_INPUTS","FN_OUTPUTS","getInstalledModules","prepareTransaction","info","rest","preparedMethodPromise","preparedM","once","installModule","asyncOptions","resolvedOptions","AbiEncodingArrayLengthMismatchError","expectedLength","givenLength","AbiEncodingBytesSizeMismatchError","expectedSize","AbiEncodingLengthMismatchError","InvalidAbiEncodingTypeError","InvalidArrayError","number","InvalidAddressError","addressRegex","isAddressCache","cacheKey","concatHex","concatBytes","ensureModularAccountModule","modularAccountModuleContract","modularAccountModuleData","accountContract","installed","moduleAddr","tx","ConnectButton","handleDisconnect","seedClient","handleConnect","activeWallet","_allConnectedWallets","jsx","ConnectButtonThirdweb","darkTheme","PublishProvider","queryClient","queryClientRef","ThirdwebProvider","SeedProvider","SCHEMA_REGISTRY_ABI","ZERO_BYTES32","getSchemaRegistryContract","chain","GET_SCHEMA_SIGNATURE","getSchemaRecord","uid","registerSchema","ZERO_ADDRESS","prepareNameSchemaAttestation","SchemaEncoder","easContractAddress","NO_EXPIRATION","RESOLVER_ADDRESS","REVOCABLE","toSnakeCase","getModelNamesForItem","itemRelationProperties","itemImageProperties","itemListProperties","getSegmentedItemProperties","modelNames","prop","ref","_prop","ensureEasSchemasForItem","itemBasicProperties","allProperties","registeredSchemaUids","registeredModelSchemaUids","modelName","schemaDef","schemaUid","SchemaRegistry","setSchemaUidForModel","registerTx","registerResult","attestTx","attestResult","storageSchemaDef","storageSchemaUid","setSchemaUidForSchemaDefinition","easDataType","INTERNAL_DATA_TYPES","propertyNameSnakeCase","schema","getEasSchemaForItemProperty","onChainRecord","relatedItems","getRelatedItemsForPublish","relatedItem","adminUpdatedEvent","filters","prepareEvent","initializedEvent","signerPermissionsUpdatedEvent","contractURIUpdatedEvent","createdAttestationEvent","eIP712DomainChangedEvent","logEvent","ownershipTransferredEvent","seedPublishedEvent","entryPoint","getAllActiveSigners","getAllAdmins","getAllExtensions","getAllSigners","getImplementationForFunction","getNonce","getPermissionsForSigner","isActiveSigner","isAdmin","isValidSigner","verifySignerPermissionRequest","contractURI","getMessageHash","isValidSignature","supportsInterface","eip712Domain","getEas","initialize","multicall","setEntrypointOverride","setPermissionsForSigner","validateUserOp","addDeposit","execute","executeBatch","onERC1155BatchReceived","onERC1155Received","onERC721Received","setContractURI","withdrawDepositTo","createSeed","createVersion","multiPublish","multiPublishWithIntegerIds","publish","renounceOwnership","setEas","transferOwnership","getGlobal","getDevTools","devToolsAdapter","service","devTools","Mailbox","_process","event","enqueued","STATE_DELIMITER","TARGETLESS_KEY","NULL_EVENT","STATE_IDENTIFIER","WILDCARD","XSTATE_INIT","XSTATE_ERROR","XSTATE_STOP","createAfterEvent","delayRef","id","createDoneStateEvent","output","createDoneActorEvent","invokeId","createErrorActorEvent","createInitEvent","input","reportUnhandledError","symbolObservable","matchesState","parentStateId","childStateId","parentStateValue","toStateValue","childStateValue","toStatePath","stateId","segment","stateValue","isMachineSnapshot","statePath","pathToStateValue","marker","previous","mapValues","collection","iteratee","collectionKeys","toArrayStrict","toArray","resolveOutput","mapper","context","isErrorActorEvent","toTransitionConfigArray","configLike","transitionLike","normalizeTarget","target","toObserver","nextHandler","errorHandler","completionHandler","isObserver","createInvokeId","stateNodeId","resolveReferencedActor","machine","src","indexStr","nodeId","invokeConfig","matchesEventDescriptor","eventType","descriptor","partialEventTokens","eventTokens","tokenIndex","partialEventToken","eventToken","createScheduledEventId","actorRef","idCounter","createSystem","rootActor","keyedActors","reverseKeyedActors","inspectionObservers","timerMap","clock","scheduler","source","delay","scheduledEvent","scheduledEventId","system","timeout","sendInspectionEvent","resolvedInspectionEvent","observer","sessionId","systemId","existing","observerOrFn","scheduledEvents","scheduledId","executingCustomAction","$$ACTOR_TYPE","ProcessingStatus","defaultOptions","Actor","logic","parent","syncSnapshot","inspect","child","emittedEvent","listeners","wildcardListener","allListeners","handler","action","exec","saveExecutingCustomAction","persistedState","snapshot","deferredFn","nextListenerOrObserver","errorListener","completeListener","wrappedHandler","initEvent","nextState","caughtError","reportError","err2","createActor","resolveCancel","actionArgs","actionParams","sendId","resolvedSendId","executeCancel","actorScope","cancel","_args","_params","resolveSpawn","_actionParams","resolvedId","resolvedInput","cloneMachineSnapshot","executeSpawn","spawnChild","resolveStop","actorRefOrString","resolvedActorRef","unregisterRecursively","executeStop","stopChild","stop","evaluateGuard","guard","isInline","resolved","guardArgs","guardParams","isAtomicStateNode","stateNode","getChildren","sn","getProperAncestors","toStateNode","getAllStateNodes","stateNodes","nodeSet","adjList","getAdjList","getInitialStateNodesWithTheirAncestors","initialStates","initialStateNode","getValueFromAdj","baseNode","childStateNodes","childStateNode","getStateValue","rootNode","isInFinalState","stateNodeSet","isStateId","getCandidates","receivedEventType","eventDescriptor","getDelayedTransitions","afterConfig","mutateEntryExit","afterEvent","raise","configTransition","resolvedTransition","resolvedDelay","transition","delayedTransition","formatTransition","transitionConfig","normalizedTarget","reenter","resolveTarget","formatTransitions","transitions","transitionsConfig","invokeDef","formatRouteTransitions","rootStateNode","routeTransitions","collectRoutes","states","routeId","userGuard","routeGuard","formatInitialTransition","_target","resolvedTarget","targets","isInternalTarget","getStateNodeByPath","resolveHistoryDefaultTransition","isHistoryNode","getInitialStateNodes","initialState","ancestor","set","iter","descStateNode","getStateNode","stateKey","arrayStatePath","currentStateNode","getStateNodes","childStateKeys","subStateKey","allSubStateNodes","subStateNode","subStateNodes","transitionAtomicNode","next","transitionCompoundNode","subStateKeys","transitionNode","transitionParallelNode","allInnerTransitions","subStateValue","innerTransitions","getHistoryNodes","isDescendant","parentStateNode","hasIntersection","s1","s2","set1","set2","removeConflictingTransitions","enabledTransitions","historyValue","filteredTransitions","t1","t1Preempted","transitionsToRemove","t2","computeExitSet","t3","findLeastCommonAncestor","head","getEffectiveTargetStates","targetNode","getTransitionDomain","targetStates","lca","statesToExit","areStateNodeCollectionsEqual","prevStateNodes","nextStateNodeSet","initialMicrostep","root","preInitialState","internalQueue","microstep","currentSnapshot","isInitial","actions","originalExecutor","mutStateNodeSet","exitStates","resolveActionsAndContext","enterStates","nextStateNodes","e","getMachineOutput","rootCompletionNode","doneStateEvent","nextSnapshot","statesToEnter","statesForDefaultEntry","computeEntrySet","completedNodes","stateNodeToEnter","initialActions","ancestorMarker","addDescendantStatesToEnter","addAncestorStatesToEnter","historyStateNodes","addProperAncestorStatesToEnter","historyDefaultTransition","reentrancyDomain","anc","_actionExecutor","changedHistory","exitStateNode","historyNode","predicate","getAction","actionType","resolveAndExecuteActionsWithContext","extra","retries","intermediateSnapshot","resolvedAction","builtinAction","deferredActorIds","macrostep","microsteps","addMicrostep","step","stopChildren","nextEvent","currentEvent","isErr","selectTransitions","shouldSelectEventlessTransitions","selectEventlessTransitions","previousState","enabledTransitionSet","atomicStates","loop","resolveStateValue","allStateNodes","machineSnapshotMatches","testValue","machineSnapshotHasTag","tag","machineSnapshotCan","transitionData","machineSnapshotToJSON","nodes","tags","getMeta","toJSON","can","hasTag","jsonValues","machineSnapshotGetMeta","createMachineSnapshot","serializeHistoryValue","getPersistedSnapshot","childrenJson","persistContext","contextPart","copy","resolveRaise","eventOrExpr","delaysMap","resolvedEvent","configDelay","executeRaise","instanceStates","fromCallback","callback","emit","callbackState","listener","receiver","XSTATE_PROMISE_RESOLVE","XSTATE_PROMISE_REJECT","controllerMap","fromPromise","promiseCreator","scope","resolvedValue","errorData","createSpawner","spawnedChildren","spawn","resolveAssign","assignment","assignArgs","partialUpdate","propAssignment","updatedContext","assign","cache","memo","memoizedData","EMPTY_OBJECT","toSerializableAction","StateNode","stateConfig","sourceName","onDone","onError","invokeDefValues","map","selectedTransition","candidates","candidate","resolvedContext","guardPassed","guardType","events","StateMachine","implementations","guards","actors","delays","resolvedStateValue","preInitial","macroState","fullPath","relativePath","resolvedStateId","_actorScope","snapshotChildren","actorId","actorData","childState","resolveHistoryReferencedState","referenced","reviveHistoryValue","revived","revivedHistoryValue","restoredSnapshot","seen","reviveContext","resolveEmit","executeEmit","SpecialTargets","resolveSendTo","targetActorRef","retryResolveSendTo","executeSendTo","sendTo","sendParent","resolveEnqueueActions","collect","enqueue","enqueueActions","resolveLog","label","executeLog","log","createMachine","schemas","extended","persistSeedUidFromPublishResult","normalizedRequests","firstRequestSeedUid","globalObject","BigNumber","isNumeric","mathceil","mathfloor","bignumberError","tooManyDigits","BASE","LOG_BASE","MAX_SAFE_INTEGER","POWS_TEN","SQRT_BASE","MAX","clone","configObject","div","convertBase","parseNumeric","P","ONE","DECIMAL_PLACES","ROUNDING_MODE","TO_EXP_NEG","TO_EXP_POS","MIN_EXP","MAX_EXP","CRYPTO","MODULO_MODE","POW_PRECISION","FORMAT","ALPHABET","alphabetHasNormalDecimalDigits","alphabet","caseChanged","isNum","intCheck","obj","p","maxOrMin","pow2_53","random53bitInt","dp","rand","sum","decimal","toBaseOut","baseIn","baseOut","arrL","sign","callerIsToString","xc","rm","toFixedPoint","coeffToString","multiply","base","temp","xlo","xhi","carry","klo","khi","compare","aL","bL","cmp","subtract","more","prod","prodL","q","qc","rem","remL","rem0","xi","xL","yc0","yL","yz","yc","bitFloor","c0","ne","toExponential","normalise","basePrefix","dotAfter","dotBefore","isInfinityOrNaN","whitespaceOrPlus","p1","p2","sd","ni","rd","pows10","valueOf","half","isModExp","nIsBig","nIsNeg","nIsOdd","isOdd","xLTy","xe","ye","xcL","ycL","ylo","yhi","zc","sqrtBase","rep","g1","g2","groupSeparator","intPart","fractionPart","isNeg","intDigits","md","d0","d1","d2","exp","n0","n1","z","zs","this","ar","bignumber_js_1","Ar","decimals","winstonString","formatted","arString","winstonStringA","winstonStringB","stringValue","decimalPlaces","api","Api","protocol","port","endpoint","body","baseURL","responseType","res","charset","decodeText","addAsyncIterator","test","bodyWithIter","webIiterator","stream","reader","done","base64Js","byteLength","toByteArray","fromByteArray","lookup","revLookup","Arr","code","getLens","b64","validLen","placeHoldersLen","lens","_byteLength","curByte","tripletToBase64","num","encodeChunk","uint8","extraBytes","maxChunkLength","len2","utils","concatBuffers","b64UrlToString","bufferToString","stringToBuffer","stringToB64Url","b64UrlToBuffer","bufferTob64","bufferTob64Url","b64UrlEncode","b64UrlDecode","B64js","buffers","total_length","b64UrlString","buffer","padding","webcryptoDriver","ArweaveUtils","WebCryptoDriver","cryptoKey","jwk","saltLength","algorithm","digest","publicModulus","publicKey","salt0","salt32","saltLengthN","saltN","publicJwk","subtle","salt","initialKey","derivedkey","iv","encryptedData","encrypted","network","Network","getError","ArweaveError","optional","resp","deepHash_1","deepHash","common_1","deepHashChunks","taggedHash","chunks","hashPair","newAcc","chunkData","generateLeaves","computeRootHash","generateTree","generateTransactionChunks","buildLayers","generateProofs","arrayFlatten","intToBuffer","bufferToInt","validatePath","utils_1","NOTE_SIZE","HASH_SIZE","chunkSize","nextChunkSize","chunk","dataHash","minByteRange","maxByteRange","leaves","proofs","lastChunk","nextLayer","hashBranch","resolveBranchProofs","proof","partialProof","flat","left","right","note","arrayCompare","dest","leftBound","rightBound","path","pathData","endOffsetBuffer","pathDataHash","offsetBuffer","remainder","pathHash","updatedOutput","transaction","merkle_1","require$$2","BaseObject","field","Tag","decode","Transaction","attributes","reward","idx","accumulator","tagList","transactionUploader","transaction_1","error_1","require$$3","MAX_CHUNKS_IN_BODY","FATAL_CHUNK_UPLOAD_ERRORS","ERROR_DELAY","TransactionUploader","chunkIndex_","serialized","upload","transactions","transaction_uploader_1","Transactions","crypto","targetAddress","data_size","tagName","tagValue","resData","ok","status","statusText","validJwk","externalWallet","dataToSign","rawSignature","signedTransaction","signaturePayload","expectedId","uploader","Wallets","silo","Silo","siloURI","resource","ids","parsed","siloName","hashIterations","accessKey","encryptionkey","SiloResource","iterations","uri","encryptionKey","Chunks","offsetResponse","startOffset","blocks","Blocks","indepHash","height","ar_1","api_1","node_driver_1","network_1","transactions_1","require$$4","wallets_1","require$$5","require$$6","require$$7","silo_1","require$$8","chunks_1","require$$9","blocks_1","require$$10","Arweave","apiConfig","createdTransaction","siloUri","siloResource","siloTransaction","query","netConfig","isLocal","regexLocalIp","tld","localStrings","isIpAdress","host","isIpv6","regexMatchIpv4","getDefaultConfig","parentDomain","__createBinding","k2","desc","__exportStar","net_config_1","defaults","locationProtocol","locationHost","locationPort","defaultConfig","getArweave","BaseArweaveClient","ArweaveModule","transformPayloadToIntegerIds","localIdToIndex","localId","req","propertiesToUpdate","pu","publishLocalId","_omit","_omitLocalId","transformPayloadForExecutor","BASE64_CHUNK_SIZE","arrayBufferToBase64","binary","formDataToSerializableParts","formData","entry","buf","base64","file","uploadServerErrorMessage","transactionKeys","uploadNetworkErrorMessage","technicalMessage","postUploadArweaveStart","uploadApiBaseUrl","BYTES32_LEN","toHex32Normalized","seedUidFromCreatedAttestationEvents","seedSchemaUid","useModularExecutor","wantSchema","createdAttestationEvt","executorCreatedAttestationEvent","parseEventLogs","ev","seedUidFromSeedPublished","contractAddress","listOfAttestationsCount","want","logs","first","executorSeedPublishedEvent","seedUid","uids","atIndex","waitForItem","seedLocalId","Item","interval","found","deserializeChunks","createArweaveTransactions","publishUploads","win","uploads","results","arweave","serializedChunks","attrs","sendReimbursementRequest","arweaveTransactions","reimbursementTransactionId","json","dataBlob","chunksBlob","jsonBlob","serverMessage","technicalMsg","errMsg","pollForConfirmation","requestResponse","uploadData","sendBack","rawTransaction","createAttestations","useIntegerLocalIds","txCount","uploadCount","smartWalletContract","targetContract","uploadDataWithTxIds","arweaveTransaction","txId","requestData","toHex32","toBytesHex","listOfAttestations","att","dataArr","byLocalId","placeholderData","targetId","targetReq","payloadForContract","managedAccountAddress","activeAccount","managedAccountWallet","managedAccount","modularAccountWallet","modularAccount","txToSend","sendErr","firstRequest","hadZeroSeedUid","contractAddressForEvents","seedUidFromTx","effectiveRequests","itemWithPersist","attestedEvent","prepareEasAttest","prepareEasMultiAttest","encodeBytes32","getAttestationUidFromReceipt","createAttestationsDirectToEas","newSeedUid","newVersionUid","seedUidFromReceipt","versionUidFromReceipt","multiRequests","multiTx","resolveItem","itemNeedsArweaveUpload","activePublishProcesses","checking","needsArweave","SUCCESS","FAILURE","publishMachine"],"mappings":";;;;;;;;;AAIO,MAAMA,KACX,8CAGWC,KACX,sEAGWC,KACX,8CAGWC,KACX,8CAEWC,KAAuB;AAAA,EAClC,SAAS;AAAA,EACT,SAAS;AACX;ACaA,SAASC,KAAkC;AACzC,MAAI,OAAO,SAAW,OAAe,OAAO,2BAA2B;AACrE,WAAO,OAAO;AAEhB,MAAI,OAAO,aAAe,KAAa;AAErC,UAAMC,IADI,WACE;AACZ,QAAIA,KAAK,KAAM,QAAOA;AAAA,EACxB;AACA,SAAO;AACT;AAEA,SAASC,GAAUC,GAA+B;AAChD,EAAI,OAAO,SAAW,QACpB,OAAO,0BAA0BA,IAE/B,OAAO,aAAe,QACvB,WAAuC,0BAA6BA;AAEzE;AAEO,SAASC,GAAYD,GAAwB;AAClD,EAAAD,GAAUC,CAAC;AACb;AAYO,SAASE,KAA0C;AACxD,QAAMC,IAASN,GAAA;AACf,MAAI,CAACM;AACH,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAGJ,SAAO;AAAA,IACL,GAAGA;AAAA,IACH,+BAA+BT;AAAA,IAC/B,oBAAoBC;AAAA,IACpB,oBAAoBQ,EAAO,sBAAsB;AAAA,IACjD,cAAcA,EAAO,gBAAgB;AAAA,IACrC,0BAA0BA,EAAO,4BAA4B;AAAA,IAC7D,oBAAoBA,EAAO,sBAAsB;AAAA,EAAA;AAErD;;;;;;;;;AC3EA,MAAIC,IAAqB,OAAO,IAAI,4BAA4B,GAC9DC,IAAsB,OAAO,IAA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,CAAE;","x_google_ignoreList":[2,3,4,6,7,8,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,129,130,131,132,133,134,135,138,139,140,141,142,143,144,145,146,147,148,149,150,151,152,153,154,155,156,157]}
|