@solarpunkltd/swarm-id 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index-BbRV2bja.js","sources":["../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/_u64.js","../../src/utils/collection.ts","../../src/swarm-id-client.ts","../../src/proxy/manifest-builder.ts","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/errors.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/regex.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/formatAbiParameter.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/formatAbiParameters.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/runtime/signatures.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/errors/abiItem.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/errors/abiParameter.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/errors/signature.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/errors/struct.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/errors/splitParameters.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/runtime/cache.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/runtime/utils.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/runtime/structs.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/parseAbi.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/getAction.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/formatAbiItem.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/data/isHex.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/data/size.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/version.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/base.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/abi.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/data.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/data/pad.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/encoding.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/data/trim.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/encoding/fromHex.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/encoding/toHex.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/encoding/toBytes.js","../../../node_modules/.pnpm/@noble+hashes@1.8.0/node_modules/@noble/hashes/esm/sha3.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/hash/keccak256.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/hash/hashSignature.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/hash/toSignature.js","../../../node_modules/.pnpm/abitype@1.2.3_typescript@5.8.3_zod@4.1.13/node_modules/abitype/dist/esm/human-readable/formatAbiItem.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/hash/normalizeSignature.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/hash/toSignatureHash.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/hash/toEventSelector.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/address.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/lru.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/address/getAddress.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/address/isAddress.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/data/concat.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/data/slice.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/regex.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/encodeAbiParameters.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/hash/toFunctionSelector.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/getAbiItem.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/accounts/utils/parseAccount.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/prepareEncodeFunctionData.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/encodeFunctionData.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/constants/solidity.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/cursor.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/cursor.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/encoding/fromBytes.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/decodeAbiParameters.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/decodeErrorResult.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/stringify.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/formatAbiItemWithArgs.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/unit/Value.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/unit/formatEther.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/unit/formatGwei.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/stateOverride.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/transaction.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/utils.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/contract.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/request.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/rpc.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/errors/getContractError.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/node.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/formatters/extract.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/formatters/transactionRequest.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/stateOverride.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/constants/number.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/block/formatBlockParameter.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/address/isAddressEqual.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/decodeFunctionResult.js","../../../node_modules/.pnpm/ox@0.14.33_typescript@5.8.3_zod@4.1.13/node_modules/ox/_esm/core/Errors.js","../../../node_modules/.pnpm/ox@0.14.33_typescript@5.8.3_zod@4.1.13/node_modules/ox/_esm/core/Hex.js","../../../node_modules/.pnpm/ox@0.14.33_typescript@5.8.3_zod@4.1.13/node_modules/ox/_esm/core/internal/hex.js","../../../node_modules/.pnpm/ox@0.14.33_typescript@5.8.3_zod@4.1.13/node_modules/ox/_esm/core/Withdrawal.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/constants/abis.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/constants/contract.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/constants/contracts.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/chain.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/encodeDeployData.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/chain/getChainContractAddress.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/errors/getCallError.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/errors/getNodeError.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/promise/createBatchScheduler.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/promise/withResolvers.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/actions/public/call.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/transaction/assertRequest.js","../../../node_modules/.pnpm/ox@0.14.33_typescript@5.8.3_zod@4.1.13/node_modules/ox/_esm/core/BlockOverrides.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/actions/public/readContract.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/promise/withRetry.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/wait.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/uid.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/clients/createClient.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/encodeErrorResult.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/encodeFunctionResult.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/ens/localBatchGatewayRequest.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/abi/decodeFunctionData.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/promise/withDedupe.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/buildRequest.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/chain/defineChain.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/rpc/id.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/rpc/http.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/promise/withTimeout.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/errors/transport.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/clients/transports/http.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/clients/transports/createTransport.js","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/chains/definitions/mainnet.js","../../../node_modules/.pnpm/@adraffy+ens-normalize@1.11.1/node_modules/@adraffy/ens-normalize/dist/index.mjs","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/utils/ens/normalize.js","../../../node_modules/.pnpm/ox@0.14.33_typescript@5.8.3_zod@4.1.13/node_modules/ox/_esm/core/Ens.js","../../src/utils/ens-name.ts","../../../node_modules/.pnpm/viem@2.55.13_typescript@5.8.3_zod@4.1.13/node_modules/viem/_esm/actions/ens/getEnsName.js"],"sourcesContent":["/**\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","// Copyright 2026 The Swarm Authors. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * A file's path inside the folder it was picked with. `webkitdirectory` and a\n * dropped directory prefix every path with the folder's own name; that segment\n * goes, so `index.html` sits at the manifest root — the rule bee-js applies.\n */\nexport function collectionPath(\n file: Pick<File, \"name\" | \"webkitRelativePath\">,\n): string {\n const relative = file.webkitRelativePath\n return relative ? relative.replace(/^[^/]*\\//, \"\") : file.name\n}\n","// Copyright 2026 The Swarm Authors. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { SwarmIdError } from \"./errors\"\nimport type {\n ClientOptions,\n ConnectOptions,\n AuthStatus,\n Avatar,\n ConnectionInfo,\n UploadResult,\n FileData,\n UploadOptions,\n UploadFilesOptions,\n CollectionFileInput,\n CollectionEntry,\n UploadProgress,\n ActUploadOptions,\n DownloadOptions,\n RequestOptions,\n Reference,\n SOCReader,\n SOCWriter,\n SingleOwnerChunk,\n SocRawUploadResult,\n SocRawUploadResponseMessage,\n SocRawUploadMessage,\n SocGetOwnerMessage,\n SocGetOwnerResponseMessage,\n FeedReaderOptions,\n FeedWriterOptions,\n FeedReader,\n FeedWriter,\n EpochFeedDownloadReferenceMessage,\n EpochFeedDownloadReferenceResponseMessage,\n EpochFeedUploadReferenceMessage,\n EpochFeedUploadReferenceResponseMessage,\n FeedGetOwnerMessage,\n FeedGetOwnerResponseMessage,\n EpochFeedDownloadOptions,\n EpochFeedDownloadPayloadResult,\n EpochFeedDownloadReferenceResult,\n EpochFeedUploadOptions,\n EpochFeedUploadResult,\n SequentialFeedReaderOptions,\n SequentialFeedWriterOptions,\n SequentialFeedUpdateOptions,\n SequentialFeedUploadOptions,\n SequentialFeedDownloadRawOptions,\n SequentialFeedUploadRawOptions,\n SequentialFeedPayloadResult,\n SequentialFeedReferenceResult,\n SequentialFeedUploadResult,\n SequentialFeedReader,\n SequentialFeedWriter,\n SequentialFeedGetOwnerMessage,\n SequentialFeedGetOwnerResponseMessage,\n SequentialFeedDownloadPayloadMessage,\n SequentialFeedDownloadPayloadResponseMessage,\n SequentialFeedDownloadRawPayloadMessage,\n SequentialFeedDownloadRawPayloadResponseMessage,\n SequentialFeedDownloadReferenceMessage,\n SequentialFeedDownloadReferenceResponseMessage,\n SequentialFeedUploadPayloadMessage,\n SequentialFeedUploadPayloadResponseMessage,\n SequentialFeedUploadRawPayloadMessage,\n SequentialFeedUploadRawPayloadResponseMessage,\n SequentialFeedUploadReferenceMessage,\n SequentialFeedUploadReferenceResponseMessage,\n CreateFeedManifestMessage,\n CreateFeedManifestResponseMessage,\n SocDownloadMessage,\n SocDownloadResponseMessage,\n SocRawDownloadMessage,\n SocRawDownloadResponseMessage,\n SocUploadResult,\n SocUploadResponseMessage,\n StampChunkInput,\n StampChunkRequest,\n StampChunkResponseMessage,\n StampedChunk,\n SocUploadMessage,\n ParentToIframeMessage,\n IframeToParentMessage,\n AppMetadata,\n ButtonAction,\n ButtonConfig,\n MountButtonOptions,\n MountedButton,\n ParentToButtonMessage,\n PostageBatch,\n} from \"./types\"\nimport {\n BUTTON_FRAME_LOADED,\n ButtonActionSchema,\n ButtonConfigSchema,\n ButtonToParentMessageSchema,\n IframeToParentMessageSchema,\n ParentToIframeMessageSchema,\n AppMetadataSchema,\n} from \"./types\"\nimport { EthAddress, Identifier, PrivateKey, Topic } from \"@ethersphere/bee-js\"\nimport { generatedAvatar } from \"./utils/avatar\"\nimport { uint8ArrayToHex } from \"./utils/hex\"\nimport { collectionPath } from \"./utils/collection\"\nimport { buildAuthUrl, isBeeApiUrl } from \"./utils/url\"\nimport { TimeoutError, withTimeout } from \"./utils/promise\"\n\nconst DEFAULT_TIMEOUT_MS = 30000\n/** The largest delay `setTimeout` honours; past it, it fires almost at once. */\nconst MAX_TIMER_DELAY_MS = 2 ** 31 - 1\nconst DEFAULT_INITIALIZATION_TIMEOUT_MS = 30000\n\n/**\n * {@link withTimeout} for one of `initialize()`'s waits: a missed deadline\n * rejects as `init-failed`, the `TimeoutError` kept as its cause, so every\n * way `initialize()` fails to come up carries the same code.\n */\nfunction initDeadline(\n work: Promise<void>,\n ms: number,\n message: string,\n): Promise<void> {\n return withTimeout(work, ms, message).catch((error: unknown) => {\n throw error instanceof TimeoutError\n ? new SwarmIdError(\"init-failed\", error.message, { cause: error })\n : error\n })\n}\n\n/**\n * A button's look, refused here rather than by the frame, which drops a\n * message it cannot parse, so a bad value would leave the button unshown or\n * an update unapplied with nothing said on the site's side.\n */\nfunction checkedButtonConfig(\n config: ButtonConfig | undefined,\n): ButtonConfig | undefined {\n if (config === undefined) return undefined\n const parsed = ButtonConfigSchema.safeParse(config)\n if (parsed.success) return parsed.data\n const issue = parsed.error.issues[0]\n throw new SwarmIdError(\n \"invalid-request\",\n `Invalid button config at ${[\"config\", ...issue.path].join(\".\")}: ${issue.message}`,\n { cause: parsed.error },\n )\n}\n\nfunction checkedButtonAction(action: ButtonAction): ButtonAction {\n if (ButtonActionSchema.safeParse(action).success) return action\n throw new SwarmIdError(\n \"invalid-request\",\n `Invalid button action: ${JSON.stringify(action)}`,\n )\n}\n\n/**\n * The site's Bee address, refused here rather than by the outgoing message\n * check, so a bad one never reaches the frame and the error says what is\n * wrong. The value is left out of the message, since a refused one may carry\n * credentials.\n */\nfunction parseBeeApiUrl(url: string): string {\n if (!isBeeApiUrl(url)) {\n throw new SwarmIdError(\n \"invalid-request\",\n \"Invalid beeApiUrl: must be an http(s) URL, optionally with a path, and no credentials, query or fragment\",\n )\n }\n return url\n}\n\n/**\n * Main client library for integrating Swarm ID authentication and storage capabilities\n * into web applications.\n *\n * SwarmIdClient enables parent windows to interact with a Swarm ID iframe proxy,\n * providing secure authentication, identity management, and data upload/download\n * functionality to the Swarm decentralized storage network.\n *\n * @example\n * ```typescript\n * const client = new SwarmIdClient({\n * iframeOrigin: 'https://swarm-id.example.com',\n * metadata: {\n * name: 'My App',\n * description: 'A decentralized application'\n * },\n * onConnectionChange: (info) => {\n * console.log('Connection changed:', info.identity?.name, info.canUpload)\n * }\n * })\n *\n * await client.initialize()\n *\n * // Check canUpload — an authenticated user can still lack upload capability\n * // when they have no postage stamp and no subsidised gateway is configured.\n * if (client.connectionInfo.identity && client.connectionInfo.canUpload) {\n * const result = await client.uploadData(new Uint8Array([1, 2, 3]))\n * console.log('Uploaded with reference:', result.reference)\n * }\n * ```\n */\nexport class SwarmIdClient {\n private iframe: HTMLIFrameElement | undefined\n private iframeOrigin: string\n private iframePath: string\n private timeout: number\n private initializationTimeout: number\n private onConnectionChange?: (info: ConnectionInfo) => void\n private lastConnectionInfo: ConnectionInfo | undefined\n private firstConnectionInfoPromise: Promise<void> | undefined\n private firstConnectionInfoResolve?: () => void\n private firstConnectionInfoReject?: (error: SwarmIdError) => void\n private iframeLoadReject?: (error: SwarmIdError) => void\n private popupMode: \"popup\" | \"window\"\n private metadata: AppMetadata\n /** Each mounted button, with what removes its frame at once */\n private mountedButtons = new Map<MountedButton, () => void>()\n private subsidisedGatewayUrl?: string\n private beeApiUrl?: string\n private ready: boolean = false\n /**\n * Whether the proxy iframe can read the trusted domain's first-party store,\n * as reported on `proxyReady`. Decides which transport `connect()` uses\n * (#613); undefined against a proxy that predates the field, which reads as\n * \"not proven shared\".\n */\n private storageShared: boolean | undefined\n private readyPromise: Promise<void> | undefined\n private readyResolve?: () => void\n private readyReject?: (error: SwarmIdError) => void\n private pendingRequests: Map<\n string,\n {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n resolve: (value: any) => void\n reject: (error: Error) => void\n timeoutId: NodeJS.Timeout\n }\n > = new Map()\n /**\n * Progress callbacks of in-flight uploads, by request id. Dispatched from\n * the one window listener, so progress passes the same source and origin\n * checks as every other message from the iframe.\n */\n private progressListeners: Map<string, (progress: UploadProgress) => void> =\n new Map()\n private requestIdCounter = 0\n private messageListener: ((event: MessageEvent) => void) | undefined\n private proxyInitializedPromise: Promise<void> | undefined\n private proxyInitializedResolve?: () => void\n private proxyInitializedReject?: (error: SwarmIdError) => void\n\n /**\n * Creates a new SwarmIdClient instance.\n *\n * @param options - Configuration options for the client\n * @param options.iframeOrigin - The origin URL where the Swarm ID proxy iframe is hosted\n * @param options.iframePath - The path to the proxy iframe (defaults to \"/proxy\")\n * @param options.timeout - Request timeout in milliseconds (defaults to 30000). Bounds each call's whole round trip through the iframe; a call's own `requestOptions.timeout` replaces it for that call\n * @param options.onConnectionChange - Callback invoked when the dApp-visible ConnectionInfo changes (identity, stamp, account type, auth)\n * @param options.popupMode - How the connect window opens, from {@link connect} or a mounted button: \"popup\" or \"window\" (defaults to \"window\")\n * @param options.metadata - Application metadata shown to users during authentication\n * @param options.metadata.name - Application name (1-100 characters)\n * @param options.metadata.description - Optional application description (max 500 characters)\n * @param options.metadata.icon - Optional application icon as a data URL (SVG or PNG, max 4KB)\n * @param options.subsidisedGatewayUrl - A gateway that stamps uploads for a person with no drive of their own (optional)\n * @param options.beeApiUrl - The Bee node this site's content reads and stamped uploads go through, in place of the person's own setting. Their account and device coordination stay on their own node. Change it later with {@link setBeeApiUrl} (optional)\n * @throws {Error} If constructed where there is no `window` (a server render)\n * @throws {SwarmIdError} `invalid-request` if the provided app metadata is invalid, or `beeApiUrl` is not an http(s) URL without credentials, query or fragment\n */\n constructor(options: ClientOptions) {\n // Before anything touches `window`: a server render reached\n // `setupMessageListener` and threw a bare `ReferenceError` from what, in\n // the published build, is minified code (#778). Name the package and the\n // fix instead.\n if (typeof window === \"undefined\") {\n throw new Error(\n \"@solarpunkltd/swarm-id runs in the browser only: construct SwarmIdClient in code that runs there (an effect, onMount, or behind `typeof window !== 'undefined'`), not in a server render\",\n )\n }\n this.iframeOrigin = options.iframeOrigin\n this.iframePath = options.iframePath || \"/proxy\"\n this.timeout = options.timeout ?? DEFAULT_TIMEOUT_MS\n this.initializationTimeout =\n options.initializationTimeout ?? DEFAULT_INITIALIZATION_TIMEOUT_MS\n this.onConnectionChange = options.onConnectionChange\n this.popupMode = options.popupMode || \"window\"\n this.metadata = options.metadata\n this.subsidisedGatewayUrl = options.subsidisedGatewayUrl\n if (options.beeApiUrl !== undefined) {\n this.beeApiUrl = parseBeeApiUrl(options.beeApiUrl)\n }\n\n // Validate metadata\n try {\n AppMetadataSchema.parse(this.metadata)\n } catch (error) {\n throw new SwarmIdError(\n \"invalid-request\",\n `Invalid app metadata: ${error}`,\n { cause: error },\n )\n }\n\n // Note: `readyPromise`, `proxyInitializedPromise`, and\n // `firstConnectionInfoPromise` (with their timeouts) are all created in\n // `initialize()`, not here — starting the timers at construction would\n // make them expire on consumers that instantiate the client and call\n // `initialize()` later (or never, in tests), and leak an armed timer plus\n // an unguarded rejection in the meantime.\n\n this.setupMessageListener()\n }\n\n /**\n * Initializes the client by creating and embedding the proxy iframe.\n *\n * This method must be called before using any other client methods.\n * It creates a hidden iframe, waits for the proxy to initialize,\n * identifies the parent application to the proxy, and waits for\n * the proxy to signal readiness.\n *\n * @returns A promise that resolves when the client is fully initialized\n * @throws {SwarmIdError} `invalid-state` if the client is already initialized, or `destroy()` runs before it resolves\n * @throws {SwarmIdError} `init-failed` if the iframe fails to load, origin validation fails on the proxy side, or the proxy does not respond within `initializationTimeout` (30 seconds by default)\n *\n * @example\n * ```typescript\n * const client = new SwarmIdClient({ ... })\n * try {\n * await client.initialize()\n * console.log('Client ready')\n * } catch (error) {\n * console.error('Failed to initialize:', error)\n * }\n * ```\n */\n async initialize(): Promise<void> {\n if (this.iframe) {\n throw new SwarmIdError(\n \"invalid-state\",\n \"SwarmIdClient already initialized\",\n )\n }\n\n // Set up the first-snapshot wait now (not in the constructor) so the\n // timeout starts when initialization actually begins, not when the\n // client object is created. The proxy emits `connectionInfoChanged`\n // unconditionally right after `proxyReady`; we race that against the\n // initializationTimeout so a buggy or version-mismatched proxy can't\n // wedge initialization indefinitely.\n //\n // The `resolve` callback is stashed in an instance field\n // (deferred-style) because it has to be called later, from\n // `handleIframeMessage` when the `connectionInfoChanged` arrives — not\n // from this executor. ES2024's `Promise.withResolvers()` would express\n // the same shape more directly. The `reject` is stashed for `destroy()`.\n this.firstConnectionInfoPromise = initDeadline(\n new Promise<void>((resolve, reject) => {\n this.firstConnectionInfoResolve = resolve\n this.firstConnectionInfoReject = reject\n }),\n this.initializationTimeout,\n `Proxy initialization timeout - proxy did not send initial connectionInfoChanged within ${this.initializationTimeout}ms`,\n )\n // Attach a no-op handler so the rejection isn't surfaced as\n // \"unhandled\" if the timeout fires before we reach the awaiting line\n // below (e.g. because an earlier `await` in this method hung first).\n // The original promise is still rejected; the `await` at the end of this\n // method re-throws it normally.\n this.firstConnectionInfoPromise.catch(() => {})\n\n // Same deferred+timeout pattern for the proxyReady handshake and the\n // iframe-ready signal: created here (not the constructor) so the timers\n // start when init begins and `withTimeout` clears them on settle. The\n // stashed resolve/reject are invoked later from `handleIframeMessage`.\n this.proxyInitializedPromise = initDeadline(\n new Promise<void>((resolve, reject) => {\n this.proxyInitializedResolve = resolve\n this.proxyInitializedReject = reject\n }),\n this.initializationTimeout,\n `Proxy initialization timeout - proxy did not signal readiness within ${this.initializationTimeout}ms`,\n )\n this.proxyInitializedPromise.catch(() => {})\n\n this.readyPromise = initDeadline(\n new Promise<void>((resolve, reject) => {\n this.readyResolve = resolve\n this.readyReject = reject\n }),\n this.initializationTimeout,\n `Proxy initialization timeout - proxy did not respond within ${this.initializationTimeout}ms`,\n )\n this.readyPromise.catch(() => {})\n\n // Create iframe for proxy\n this.iframe = document.createElement(\"iframe\")\n this.iframe.src = `${this.iframeOrigin}${this.iframePath}`\n\n // The session frame shows nothing. A button the person clicks is a\n // frame of its own (`mountButton`), so a site can remove it and keep the\n // session.\n this.iframe.style.display = \"none\"\n\n // Wait for iframe to load. The `reject` is stashed for `destroy()` while\n // the load is pending: a removed iframe never fires `load`, and nothing\n // else would settle this.\n await new Promise<void>((resolve, reject) => {\n this.iframeLoadReject = reject\n this.iframe!.onload = () => resolve()\n this.iframe!.onerror = () =>\n reject(\n new SwarmIdError(\"init-failed\", \"Failed to load Swarm ID iframe\"),\n )\n\n document.body.appendChild(this.iframe!)\n })\n this.iframeLoadReject = undefined\n\n // Wait for proxy to signal it's ready\n await this.proxyInitializedPromise\n\n // Identify ourselves to the iframe\n this.sendMessage({\n type: \"parentIdentify\",\n requestId: this.generateRequestId(),\n metadata: this.metadata,\n subsidisedGatewayUrl: this.subsidisedGatewayUrl,\n beeApiUrl: this.beeApiUrl,\n })\n\n // Wait for iframe to be ready\n await this.readyPromise\n\n // Wait for the initial ConnectionInfo snapshot (sent right after proxyReady)\n // so `client.connectionInfo` is populated by the time `initialize()` resolves.\n await this.firstConnectionInfoPromise\n }\n\n /**\n * Setup message listener for iframe responses\n */\n private setupMessageListener(): void {\n this.messageListener = (event: MessageEvent) => {\n // Source first, and silently: `window` carries every message the page\n // sends itself — devtools, HMR, wallet extensions — and none of it was\n // addressed to this client, so dropping it is routine rather than a\n // security event and must not reach the console. Before the iframe\n // exists there is no window a message of ours could have come from.\n // This is also what keeps a sibling or parent frame on the identity\n // origin from spoofing a push event like `connectionInfoChanged` or\n // `authSuccess`.\n if (!this.iframe || event.source !== this.iframe.contentWindow) {\n return\n }\n\n // `proxyInitialized` is sent the moment the iframe loads, with a\n // wildcard target origin, so it is answered before the origin check.\n if (event.data?.type === \"proxyInitialized\") {\n if (this.proxyInitializedResolve) {\n this.proxyInitializedResolve()\n this.proxyInitializedResolve = undefined // Prevent double resolution\n }\n return\n }\n\n // Our own iframe with an origin other than the configured identity one\n // is worth reporting: the frame is serving something unexpected.\n // (Extract just the origin part, ignoring any path in iframeOrigin.)\n const expectedOrigin = new URL(this.iframeOrigin).origin\n if (event.origin !== expectedOrigin) {\n console.warn(\n \"[SwarmIdClient] Rejected message from unauthorized origin:\",\n event.origin,\n )\n return\n }\n\n // Parse and validate message\n let message: IframeToParentMessage\n try {\n message = IframeToParentMessageSchema.parse(event.data)\n } catch (error) {\n console.warn(\n \"[SwarmIdClient] Invalid message format:\",\n event.data,\n error,\n )\n return\n }\n\n this.handleIframeMessage(message)\n }\n\n window.addEventListener(\"message\", this.messageListener)\n }\n\n /**\n * Handle messages from iframe\n */\n private handleIframeMessage(message: IframeToParentMessage): void {\n switch (message.type) {\n case \"proxyReady\":\n this.ready = true\n // Which transport `connect()` can use, known before the first click\n // (#613). Undefined against a proxy older than that field.\n this.storageShared = message.storageShared\n if (this.readyResolve) {\n this.readyResolve()\n }\n break\n\n case \"connectionInfoChanged\": {\n const info: ConnectionInfo = {\n canUpload: message.canUpload,\n storagePartitioned: message.storagePartitioned,\n uploadMode: message.uploadMode,\n uploadUnavailableReason: message.uploadUnavailableReason,\n identity: message.identity,\n appKey: message.appKey,\n partition: message.partition,\n chatBinding: message.chatBinding,\n beeApiUrl: message.beeApiUrl,\n postageBatchId: message.postageBatchId,\n }\n this.lastConnectionInfo = info\n if (this.firstConnectionInfoResolve) {\n this.firstConnectionInfoResolve()\n this.firstConnectionInfoResolve = undefined\n }\n if (this.onConnectionChange) {\n this.onConnectionChange(info)\n }\n break\n }\n\n case \"initError\":\n // Initialization error from proxy (e.g., origin validation failed)\n console.error(\n \"[SwarmIdClient] Proxy initialization error:\",\n message.error,\n )\n if (this.readyReject) {\n this.readyReject(new SwarmIdError(\"init-failed\", message.error))\n }\n break\n\n case \"disconnectResponse\":\n // Handle as response if there's a matching request\n if (\"requestId\" in message) {\n const pending = this.pendingRequests.get(message.requestId)\n if (pending) {\n clearTimeout(pending.timeoutId)\n this.pendingRequests.delete(message.requestId)\n pending.resolve(message)\n }\n }\n break\n\n case \"error\": {\n const pending = this.pendingRequests.get(message.requestId)\n if (pending) {\n clearTimeout(pending.timeoutId)\n this.pendingRequests.delete(message.requestId)\n pending.reject(SwarmIdError.fromWire(message))\n }\n break\n }\n\n case \"uploadProgress\":\n // Report to the upload's callback, if it registered one. Don't resolve\n // the pending request - the response does that\n this.progressListeners.get(message.requestId)?.({\n total: message.total,\n processed: message.processed,\n })\n break\n\n default:\n // Handle response messages with requestId\n if (\"requestId\" in message) {\n const pending = this.pendingRequests.get(message.requestId)\n if (pending) {\n clearTimeout(pending.timeoutId)\n this.pendingRequests.delete(message.requestId)\n pending.resolve(message)\n }\n }\n }\n }\n\n /**\n * Send message to iframe\n */\n private sendMessage(message: ParentToIframeMessage): void {\n if (!this.iframe || !this.iframe.contentWindow) {\n throw new SwarmIdError(\"invalid-state\", \"Iframe not initialized\")\n }\n\n // Validate message before sending\n try {\n ParentToIframeMessageSchema.parse(message)\n } catch (error) {\n throw new SwarmIdError(\n \"invalid-request\",\n `Invalid message format: ${error}`,\n { cause: error },\n )\n }\n\n this.iframe.contentWindow.postMessage(message, this.iframeOrigin)\n }\n\n /**\n * Send request and wait for response\n */\n private async sendRequest<\n TResponse,\n TRequest extends ParentToIframeMessage & { requestId: string } =\n ParentToIframeMessage & {\n requestId: string\n },\n >(message: TRequest): Promise<TResponse> {\n // A per-call `requestOptions.timeout` bounds this whole round trip, not\n // only the Bee request the proxy makes with it: a caller raising it for a\n // large upload must not be cut off at the constructor default (#775).\n const timeout = this.roundTripTimeout(\n (message as { requestOptions?: RequestOptions }).requestOptions?.timeout,\n )\n return new Promise((resolve, reject) => {\n const timeoutId = setTimeout(() => {\n this.pendingRequests.delete(message.requestId)\n reject(\n new SwarmIdError(\"timeout\", `Request timeout after ${timeout}ms`),\n )\n }, timeout)\n\n this.pendingRequests.set(message.requestId, {\n resolve,\n reject,\n timeoutId,\n })\n\n this.sendMessage(message)\n })\n }\n\n /**\n * The round-trip bound for one call, from its own `requestOptions.timeout`.\n *\n * Only a value `setTimeout` can honour is taken. Zero and negatives mean\n * \"no timeout\" to Bee, which is where this option went before it also bound\n * the round trip — taken literally here they would reject on the next tick,\n * the opposite of what the caller asked, so they fall back to the client\n * default and still reach Bee unchanged. A value past the 32-bit timer\n * ceiling means \"as long as it takes\", and `setTimeout` would wrap it into\n * firing almost at once, so it clamps to the ceiling instead. `Infinity` and\n * `NaN` never get this far: `z.number()` rejects them on the way out.\n */\n private roundTripTimeout(perCall: number | undefined): number {\n if (perCall === undefined || perCall <= 0) {\n return this.timeout\n }\n return Math.min(perCall, MAX_TIMER_DELAY_MS)\n }\n\n /**\n * Generate unique request ID\n */\n private generateRequestId(): string {\n return `req-${++this.requestIdCounter}-${Date.now()}`\n }\n\n private normalizeSocIdentifier(\n identifier: Identifier | Uint8Array | string,\n ): string {\n if (identifier instanceof Identifier) {\n return identifier.toHex()\n }\n if (identifier instanceof Uint8Array) {\n return uint8ArrayToHex(identifier)\n }\n return identifier\n }\n\n private normalizeSocKey(key: Uint8Array | string): string {\n if (key instanceof Uint8Array) {\n return uint8ArrayToHex(key)\n }\n return key\n }\n\n private normalizeFeedTopic(\n topic: Topic | Identifier | Uint8Array | string,\n ): string {\n if (topic instanceof Topic) {\n return uint8ArrayToHex(topic.toUint8Array())\n }\n if (topic instanceof Identifier) {\n return topic.toHex()\n }\n if (topic instanceof Uint8Array) {\n return uint8ArrayToHex(topic)\n }\n return topic\n }\n\n private normalizeReference(reference: Uint8Array | string): string {\n if (reference instanceof Uint8Array) {\n return uint8ArrayToHex(reference)\n }\n return reference\n }\n\n private normalizeFeedTimestamp(value: bigint | number | string): string {\n if (typeof value === \"bigint\") {\n return value.toString()\n }\n if (typeof value === \"number\") {\n return BigInt(Math.floor(value)).toString()\n }\n return value\n }\n\n private normalizeFeedIndex(value: bigint | number | string): string {\n if (typeof value === \"bigint\") {\n return value.toString()\n }\n if (typeof value === \"number\") {\n return BigInt(Math.floor(value)).toString()\n }\n return value\n }\n\n private normalizePayload(data: Uint8Array | string): Uint8Array {\n if (data instanceof Uint8Array) {\n return data\n }\n return new TextEncoder().encode(data)\n }\n\n private socChunkFromResponse(response: {\n data: Uint8Array\n identifier: string\n signature: string\n span: number\n payload: Uint8Array\n address: Reference\n owner: string\n }): SingleOwnerChunk {\n return {\n data: response.data,\n identifier: response.identifier,\n signature: response.signature,\n span: response.span,\n payload: response.payload,\n address: response.address,\n owner: response.owner,\n }\n }\n\n /**\n * Ensure client is initialized\n */\n private ensureReady(): void {\n if (!this.ready) {\n throw new SwarmIdError(\n \"invalid-state\",\n \"SwarmIdClient not initialized. Call initialize() first.\",\n )\n }\n }\n\n // ============================================================================\n // Authentication Methods\n // ============================================================================\n\n /**\n * Checks the current authentication status with the Swarm ID proxy.\n *\n * @returns A promise resolving to the authentication status object\n * @returns return.authenticated - Whether the user is currently authenticated\n * @returns return.origin - The origin that authenticated (if authenticated)\n * @returns return.beeApiUrl - The Bee node this site gave, if it gave one. The person's own node is never reported\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const status = await client.checkAuthStatus()\n * if (status.authenticated) {\n * console.log('Authenticated from:', status.origin)\n * }\n * ```\n */\n async checkAuthStatus(): Promise<AuthStatus> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"authStatusResponse\"\n requestId: string\n authenticated: boolean\n origin?: string\n beeApiUrl?: string\n }>({\n type: \"checkAuth\",\n requestId,\n })\n\n return {\n authenticated: response.authenticated,\n origin: response.origin,\n beeApiUrl: response.beeApiUrl,\n }\n }\n\n /**\n * Changes the Bee node this site's content reads and stamped uploads go\n * through, without a reload, for example when the viewer picks another source. It\n * replaces the `beeApiUrl` given at construction, and takes over from the\n * person's own Bee setting on this site if none was given. Every other site,\n * and Swarm ID itself, keep the person's setting. The checks and writes\n * that coordinate the person's account and devices always use their own\n * node. Nothing is stored: the next page load starts from the\n * constructor's `beeApiUrl` again.\n *\n * Works signed in or not. A subsidised gateway the person's own custom node\n * had switched off comes back once the site names its node.\n *\n * @param url - An http(s) URL, optionally with a path, without credentials, query or fragment\n * @throws {SwarmIdError} `invalid-request` if `url` is not such a URL, and nothing is sent\n * @throws {SwarmIdError} `invalid-state` if the client is not initialized\n * @throws {SwarmIdError} `timeout` if the request times out\n *\n * @example\n * ```typescript\n * await client.setBeeApiUrl('https://bee.example.com/')\n * console.log(client.connectionInfo.beeApiUrl)\n * ```\n */\n async setBeeApiUrl(url: string): Promise<void> {\n const beeApiUrl = parseBeeApiUrl(url)\n this.ensureReady()\n await this.sendRequest<{\n type: \"setBeeApiUrlResponse\"\n requestId: string\n beeApiUrl: string\n }>({\n type: \"setBeeApiUrl\",\n requestId: this.generateRequestId(),\n beeApiUrl,\n })\n this.beeApiUrl = beeApiUrl\n }\n\n /**\n * Gets the current postage batch for the authenticated identity.\n *\n * Returns information about the postage stamp associated with the\n * connected identity, including batch ID, utilization, depth, and TTL.\n *\n * @returns A promise resolving to the PostageBatch or undefined if none is configured\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const batch = await client.getPostageBatch()\n * if (batch) {\n * console.log('Batch ID:', batch.batchID)\n * console.log('Utilization:', batch.utilization)\n * console.log('Depth:', batch.depth)\n * console.log('TTL:', batch.batchTTL)\n * } else {\n * console.log('No postage batch configured')\n * }\n * ```\n */\n async getPostageBatch(): Promise<PostageBatch | undefined> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"getPostageBatchResponse\"\n requestId: string\n postageBatch?: PostageBatch\n }>({\n type: \"getPostageBatch\",\n requestId,\n })\n\n return response.postageBatch\n }\n\n /**\n * Disconnects the current session and clears authentication data.\n *\n * After disconnection, the user will need to re-authenticate to perform\n * uploads or access identity-related features. The\n * {@link ClientOptions.onConnectionChange} callback will fire with an\n * un-authenticated snapshot.\n *\n * @returns A promise that resolves when disconnection is complete\n * @throws {SwarmIdError} `invalid-state` if the client is not initialized\n * @throws {SwarmIdError} `internal` if the proxy reports the disconnect failed\n * @throws {SwarmIdError} `timeout` if the request times out\n *\n * @example\n * ```typescript\n * await client.disconnect()\n * console.log('User logged out')\n * ```\n */\n async disconnect(): Promise<void> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"disconnectResponse\"\n requestId: string\n success: boolean\n }>({\n type: \"disconnect\",\n requestId,\n })\n\n if (!response.success) {\n throw new SwarmIdError(\"internal\", \"Failed to disconnect\")\n }\n }\n\n /**\n * Opens the Swarm ID connect window from the site's own control, where the\n * session frame shares Swarm ID's storage: a site on the same site as Swarm\n * ID, such as a self-hosted copy on the site's own domain. The window\n * writes the connection to that storage and the session frame picks it up.\n *\n * Anywhere else the browser partitions the session frame's storage, and the\n * session can reach it only through a window a Swarm ID frame opened from a\n * click inside it. A window opened from here would end on \"Connected\" with\n * the site still signed out, so this refuses instead and the site shows\n * {@link mountButton}'s button. `connectionInfo.storagePartitioned` and the\n * error's code tell the two apart. The button works in both cases, so a\n * site that always mounts it never needs this.\n *\n * @param options - Configuration options for the connect flow\n * @throws {SwarmIdError} `invalid-state` if the client is not initialized\n * @throws {SwarmIdError} `button-required` if the session frame's storage is partitioned, or not proven shared\n * @throws {SwarmIdError} `popup-blocked` if the browser blocks the window\n *\n * @example\n * ```typescript\n * try {\n * await client.connect()\n * } catch (error) {\n * if (error instanceof SwarmIdError && error.code === 'button-required') {\n * client.mountButton(container, { action: 'sign-in' })\n * }\n * }\n * ```\n */\n async connect(options: ConnectOptions = {}): Promise<void> {\n this.ensureReady()\n if (this.storageShared !== true) {\n throw new SwarmIdError(\n \"button-required\",\n \"Swarm ID's frame cannot read Swarm ID's storage here, so a window opened from this page cannot sign it in. Sign in through the button from client.mountButton().\",\n )\n }\n // Checked, not discarded: a blocked popup opens nothing, and a\n // `connect()` that resolved anyway would report a connect in progress\n // that no window is running.\n if (!this.openAuthWindow(options)) {\n throw new SwarmIdError(\n \"popup-blocked\",\n \"Failed to open authentication popup\",\n )\n }\n }\n\n /**\n * Shows a Swarm ID button in `container`: a small frame of Swarm ID's own,\n * apart from the hidden session frame, that fills the container. Its click\n * opens the connect window, which hands the session to the site's Swarm ID\n * frames, and the site hears of it on {@link ClientOptions.onConnectionChange} as from\n * any sign-in. This is how a person signs in, or changes the stamp the\n * site uses, wherever the site and Swarm ID are on different sites.\n *\n * Unmounting removes only the button, at any time. The session stays, and\n * signing out stays {@link disconnect}. A button unmounted while its window\n * is open stays hidden until the window closes, because the window reads\n * from it, as it opens, where to hand the session. Unmounting it, or\n * removing its container, in the moment between the click and the window\n * opening loses that sign-in, and the person signs in again.\n *\n * @param container - The element the button fills. Give it the size the button should have\n * @param options.action - `sign-in`, or `change-stamp` for a person signed in\n * @param options.config - The label, its busy and disabled states, colours and typography\n * @param options.onWindowChange - Called with `open`, `closed` or `blocked` for the button's connect window\n * @returns The button: `ready`, `update()` and `unmount()`, where `update()` refuses a bad value the same way\n * @throws {SwarmIdError} `invalid-state` if the client is not initialized\n * @throws {SwarmIdError} `invalid-request` if `action` or a `config` value is not one the button takes, naming the field\n *\n * @example\n * ```typescript\n * const button = client.mountButton(document.getElementById('sign-in')!, {\n * action: 'sign-in',\n * config: { text: 'Sign in', backgroundColor: '#000', borderRadius: '6px' },\n * })\n * await button.ready\n * // later, closing the panel it sits in\n * button.unmount()\n * ```\n */\n mountButton(\n container: HTMLElement,\n options: MountButtonOptions,\n ): MountedButton {\n this.ensureReady()\n const iframeOrigin = this.iframeOrigin\n const expectedOrigin = new URL(iframeOrigin).origin\n let action: ButtonAction = checkedButtonAction(options.action)\n let config: ButtonConfig | undefined = checkedButtonConfig(options.config)\n let loaded = false\n let settled = false\n let windowOpen = false\n let unmounted = false\n\n const frame = document.createElement(\"iframe\")\n frame.src = `${iframeOrigin}${this.iframePath.replace(/\\/proxy$/, \"\")}/button`\n frame.title = \"Swarm ID\"\n Object.assign(frame.style, {\n border: \"none\",\n backgroundColor: \"transparent\",\n width: \"100%\",\n height: \"100%\",\n display: \"block\",\n borderRadius: config?.borderRadius ?? \"0\",\n })\n\n let resolveReady!: () => void\n let rejectReady!: (error: SwarmIdError) => void\n const ready = initDeadline(\n new Promise<void>((resolve, reject) => {\n resolveReady = resolve\n rejectReady = reject\n }),\n this.initializationTimeout,\n `Swarm ID button did not show within ${this.initializationTimeout}ms`,\n )\n ready.then(\n () => (settled = true),\n () => (settled = true),\n )\n\n const post = (message: ParentToButtonMessage) =>\n frame.contentWindow?.postMessage(message, iframeOrigin)\n\n const listener = (event: MessageEvent) => {\n if (event.source !== frame.contentWindow) return\n if (event.data?.type === BUTTON_FRAME_LOADED) {\n loaded = true\n post({\n type: \"buttonIdentify\",\n action,\n config,\n metadata: this.metadata,\n popupMode: this.popupMode,\n })\n return\n }\n if (event.origin !== expectedOrigin) return\n const parsed = ButtonToParentMessageSchema.safeParse(event.data)\n if (!parsed.success) return\n const message = parsed.data\n if (message.type === \"buttonReady\") resolveReady()\n else if (message.type === \"buttonInitError\")\n rejectReady(new SwarmIdError(\"init-failed\", message.error))\n else {\n windowOpen = message.state === \"open\"\n if (unmounted) {\n if (!windowOpen) remove()\n } else {\n options.onWindowChange?.(message.state)\n }\n }\n }\n const remove = () => {\n this.mountedButtons.delete(mounted)\n window.removeEventListener(\"message\", listener)\n frame.remove()\n if (!settled) {\n rejectReady(\n new SwarmIdError(\"invalid-state\", \"Swarm ID button unmounted\"),\n )\n }\n }\n window.addEventListener(\"message\", listener)\n container.appendChild(frame)\n\n const mounted: MountedButton = {\n ready,\n update: (next) => {\n if (unmounted) return\n action =\n next.action === undefined ? action : checkedButtonAction(next.action)\n config =\n next.config === undefined ? config : checkedButtonConfig(next.config)\n frame.style.borderRadius = config?.borderRadius ?? \"0\"\n if (loaded) post({ type: \"buttonUpdate\", action, config })\n },\n // The connect window reads which frames to hand the session to from\n // this frame, its opener, as it opens, so while it is open the frame\n // stays, hidden, and goes once the window closes.\n unmount: () => {\n if (unmounted || !this.mountedButtons.has(mounted)) return\n unmounted = true\n if (windowOpen) frame.style.display = \"none\"\n else remove()\n },\n }\n this.mountedButtons.set(mounted, remove)\n return mounted\n }\n\n /**\n * Open the connect window from the site's page, for a session frame that\n * shares Swarm ID's storage.\n *\n * Carries no challenge: a window opened here has the site's page as its\n * `window.opener`, so there is nothing for a handover to attach to, and the\n * window writes the connection to the storage the session frame reads.\n *\n * @returns whether the popup opened — a blocked one returns null, which the\n * caller must not report as a connect in progress.\n */\n private openAuthWindow(options: ConnectOptions): boolean {\n const basePath = this.iframePath.replace(/\\/proxy$/, \"\")\n const authUrl = buildAuthUrl(\n this.iframeOrigin + basePath,\n window.location.origin,\n this.metadata,\n )\n\n const effectivePopupMode = options.popupMode ?? this.popupMode\n const popup =\n effectivePopupMode === \"popup\"\n ? window.open(authUrl, \"_blank\", \"width=500,height=600\")\n : window.open(authUrl, \"_blank\")\n return Boolean(popup)\n }\n\n /**\n * Current dApp-visible {@link ConnectionInfo} snapshot — identity, app key,\n * upload capability, and upload mode. Populated by the proxy as soon as it\n * is ready and refreshed whenever any of those derived fields change.\n * Subscribe to {@link ClientOptions.onConnectionChange} to react to updates.\n *\n * @throws {SwarmIdError} `invalid-state` if {@link initialize} has not resolved yet\n *\n * @example\n * ```typescript\n * await client.initialize()\n * const info = client.connectionInfo\n * if (info.canUpload) {\n * console.log('Ready to upload as:', info.identity?.name)\n * }\n * ```\n */\n get connectionInfo(): ConnectionInfo {\n this.ensureReady()\n if (!this.lastConnectionInfo) {\n // `ready` flips true on `proxyReady`, which the proxy sends before its\n // first `connectionInfoChanged`, so a read before `initialize()`\n // resolves can land here.\n throw new SwarmIdError(\n \"invalid-state\",\n \"SwarmIdClient connectionInfo not yet available.\",\n )\n }\n return this.lastConnectionInfo\n }\n\n /**\n * Avatar of the connected identity at a specific size.\n *\n * Most callers want `connectionInfo.identity.avatar` instead — it is already\n * resolved on every snapshot and needs no call. Reach for this only to\n * render at a size the default does not suit. Async so that honouring a size\n * may involve fetching, which anything but the generated avatar would.\n *\n * @param options.size - Width and height in pixels\n * @returns The avatar, or `undefined` when no identity is connected\n */\n async getAvatar(\n options: { size?: number } = {},\n ): Promise<Avatar | undefined> {\n const { identity } = this.connectionInfo\n if (!identity) {\n return undefined\n }\n // Only a generated avatar can be re-rendered from the id; any other kind\n // is served as-is.\n return options.size !== undefined && identity.avatar.source === \"generated\"\n ? generatedAvatar(identity.id, options.size)\n : identity.avatar\n }\n\n // ============================================================================\n // Bee Connectivity Methods\n // ============================================================================\n\n /**\n * Checks whether the Bee node is reachable.\n *\n * This method never throws an exception. If the client is not initialized,\n * the request times out, or any other error occurs, it returns `false`.\n *\n * @returns A promise resolving to `true` if the Bee node is reachable, `false` otherwise\n *\n * @example\n * ```typescript\n * const connected = await client.isBeeConnected()\n * if (connected) {\n * console.log('Bee node is online')\n * } else {\n * console.log('Bee node is offline')\n * }\n * ```\n */\n async isBeeConnected(): Promise<boolean> {\n try {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"isConnectedResponse\"\n requestId: string\n connected: boolean\n }>({\n type: \"isConnected\",\n requestId,\n })\n\n return response.connected\n } catch {\n return false\n }\n }\n\n /**\n * Gets information about the Bee node configuration.\n *\n * Needs a real Bee node: the public gateway has no `/node` endpoint, so this\n * rejects there. Do not gate uploads on it — it exists to detect a dev-mode\n * node, where deferred uploads are required.\n *\n * This method retrieves the current Bee node's operating mode and feature flags.\n * Use this to determine if deferred uploads are required (dev mode) or if direct\n * uploads are available (production modes).\n *\n * @returns A promise resolving to the node info object\n * @returns return.beeMode - The Bee node operating mode (\"dev\", \"light\", \"full\", \"ultra-light\")\n * @returns return.chequebookEnabled - Whether the chequebook is enabled\n * @returns return.swapEnabled - Whether SWAP is enabled\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the Bee node is not reachable\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const nodeInfo = await client.getNodeInfo()\n * if (nodeInfo.beeMode === 'dev') {\n * // Dev mode requires deferred uploads\n * await client.uploadData(data, { deferred: true })\n * } else {\n * // Production modes can use direct uploads\n * await client.uploadData(data, { deferred: false })\n * }\n * ```\n */\n async getNodeInfo(): Promise<{\n beeMode: string\n chequebookEnabled: boolean\n swapEnabled: boolean\n }> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"getNodeInfoResponse\"\n requestId: string\n beeMode: string\n chequebookEnabled: boolean\n swapEnabled: boolean\n }>({\n type: \"getNodeInfo\",\n requestId,\n })\n\n return {\n beeMode: response.beeMode,\n chequebookEnabled: response.chequebookEnabled,\n swapEnabled: response.swapEnabled,\n }\n }\n\n // ============================================================================\n // Data Upload/Download Methods\n // ============================================================================\n\n /**\n * Uploads raw binary data to the Swarm network.\n *\n * Read the returned reference back with {@link downloadData}, or from a\n * gateway at `/bytes/<reference>`. It carries no manifest, so\n * {@link downloadFile} and `/bzz/` cannot resolve it.\n *\n * The data is uploaded using the authenticated user's postage stamp.\n * Progress can be tracked via the optional callback.\n *\n * @param data - The binary data to upload as a Uint8Array\n * @param options - Optional upload configuration\n * @param options.pin - Whether to pin the data locally (defaults to false; ignored on a subsidised gateway)\n * @param options.encrypt - Whether to encrypt the data (defaults to false)\n * @param options.tag - Tag ID for tracking upload progress\n * @param options.deferred - Whether to use deferred upload (defaults to false)\n * @param options.onProgress - Optional callback for tracking upload progress\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the upload result\n * @returns return.reference - The Swarm reference (hash) of the uploaded data\n * @returns return.tagUid - The tag UID if a tag was created\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not authenticated or cannot upload\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const data = new TextEncoder().encode('Hello, Swarm!')\n * const result = await client.uploadData(data, {\n * encrypt: true,\n * onProgress: (progress) => {\n * console.log(`Progress: ${progress.processed}/${progress.total}`)\n * },\n * })\n * console.log('Reference:', result.reference)\n * ```\n */\n async uploadData(\n data: Uint8Array,\n options?: UploadOptions,\n requestOptions?: RequestOptions,\n ): Promise<UploadResult> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n const {\n onProgress,\n useWebSocket,\n useWorkers,\n workerCount,\n concurrency,\n ...serializableOptions\n } = options ?? {}\n\n const stopProgress = this.listenForProgress(requestId, onProgress)\n try {\n const response = await this.sendRequest<{\n type: \"uploadDataResponse\"\n requestId: string\n reference: Reference\n tagUid?: number\n }>({\n type: \"uploadData\",\n requestId,\n data: new Uint8Array(data),\n options: serializableOptions,\n requestOptions,\n enableProgress: !!onProgress,\n useWebSocket,\n useWorkers,\n workerCount,\n concurrency,\n })\n\n return {\n reference: response.reference,\n tagUid: response.tagUid,\n }\n } finally {\n stopProgress()\n }\n }\n\n /**\n * Downloads raw binary data from the Swarm network: the counterpart of\n * {@link uploadData}. Pass an encrypted (128-hex) reference here rather\n * than putting it in a gateway URL — it contains the decryption key.\n *\n * @param reference - The Swarm reference (hash) of the data to download.\n * Can be 64 hex chars (32 bytes) or 128 hex chars (64 bytes for encrypted)\n * @param options - Optional download configuration\n * @param options.redundancyStrategy - Strategy for handling redundancy (0-3)\n * @param options.fallback - Whether to use fallback retrieval\n * @param options.timeoutMs - Download timeout in milliseconds\n * @param options.actPublisher - ACT publisher for encrypted content\n * @param options.actHistoryAddress - ACT history address for encrypted content\n * @param options.actTimestamp - ACT timestamp for encrypted content\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the downloaded data as a Uint8Array\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the reference is not found\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const data = await client.downloadData('a1b2c3...') // 64 char hex reference\n * const text = new TextDecoder().decode(data)\n * console.log('Downloaded:', text)\n * ```\n */\n async downloadData(\n reference: Reference,\n options?: DownloadOptions,\n requestOptions?: RequestOptions,\n ): Promise<Uint8Array> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"downloadDataResponse\"\n requestId: string\n data: Uint8Array\n }>({\n type: \"downloadData\",\n requestId,\n reference,\n options,\n requestOptions,\n })\n\n return response.data\n }\n\n /**\n * Derive a stable, app-scoped secret for this identity + app origin.\n *\n * Computes `HMAC(appSecret, label)` inside the iframe, where `appSecret` is the\n * app-specific secret that never leaves the trusted context. The result is\n * deterministic — the same identity, app origin, and label always yield the\n * same bytes across sessions and devices — yet unguessable to anyone without\n * the identity. Use it to seed feed topics or other app material without\n * exposing the recoverable app public key (#520).\n *\n * @param label - Application-chosen domain separator (e.g. `\"state-feed\"`)\n * @returns A promise resolving to the 32-byte derived secret\n * @throws {Error} If the client is not initialized or not authenticated\n *\n * @example\n * ```typescript\n * const seed = await client.deriveAppSecret('state-feed')\n * const topic = keccak256(seed) // an unguessable, stable feed topic\n * ```\n */\n async deriveAppSecret(label: string): Promise<Uint8Array> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"deriveAppSecretResponse\"\n requestId: string\n secret: Uint8Array\n }>({\n type: \"deriveAppSecret\",\n requestId,\n label,\n })\n\n return response.secret\n }\n\n /**\n * The site's chat key: the private key this site's chat signs messages\n * with, whose address `connectionInfo.chatBinding` names as the account's\n * chat address on this site (docs/Chat-Binding.md).\n *\n * It is derived inside the iframe from the app secret, which never leaves\n * it, and is the same for this account and this site on every device. The\n * library keeps it in memory only and never writes it to storage. Hold it no\n * longer than the chat needs it, and never publish it.\n *\n * @returns A promise resolving to the 32-byte secp256k1 private key\n * @throws {SwarmIdError} If the client is not initialized, or with code\n * `not-authenticated` when no account is connected\n *\n * @example\n * ```typescript\n * const chatKey = await client.getChatKey()\n * const signer = new PrivateKey(chatKey) // its address is the binding's chat address\n * ```\n */\n async getChatKey(): Promise<Uint8Array> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"getChatKeyResponse\"\n requestId: string\n chatKey: Uint8Array\n }>({\n type: \"getChatKey\",\n requestId,\n })\n\n return response.chatKey\n }\n\n /**\n * Stamp a chunk with the account's own postage stamp and get the stamp back,\n * to send the chunk through whatever Swarm access the app chose: a gateway,\n * its own Bee node or a browser node.\n *\n * The frame computes the chunk's address itself, so the whole chunk goes in,\n * never an address. A content chunk is stamped as it is. A single-owner chunk\n * is signed by the frame in this same call, with the app's own secret\n * (`signer: \"app\"`) or a private key the app supplies, such as a chat's\n * shared GSOC inbox key. A pre-signed chunk is refused, and so is one owned\n * by any of the account's own keys.\n *\n * The stamp is returned only once the bucket counter it spent is saved and,\n * for an account shared between devices, published, as an upload is\n * acknowledged. Two calls never return the same bucket slot.\n *\n * @param chunk - The chunk: `data` is the 8-byte little-endian span followed\n * by the payload, 8 to 4104 bytes\n * @returns The chunk address, the stamp as the `swarm-postage-stamp` header\n * value, and for a single-owner chunk its owner and signature\n * @throws {SwarmIdError} `upload-unavailable` with reason `subsidised` when\n * the account is in subsidised mode, where the gateway stamps and there is\n * no stamp of the account's to return, and `invalid-request` for a chunk of the\n * wrong shape or an owner that is one of the account's keys\n *\n * @example\n * ```typescript\n * const { address, stamp } = await client.stampChunk({ kind: 'content', data })\n * await fetch(`${gateway}/chunks`, {\n * method: 'POST',\n * headers: { 'swarm-postage-stamp': stamp },\n * body: data,\n * })\n * ```\n */\n async stampChunk(chunk: StampChunkInput): Promise<StampedChunk> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n // Spread rather than rebuilt, so a field the frame refuses (an address, a\n // signature) still reaches the schema check and is refused here.\n const wireChunk =\n chunk.kind === \"soc\"\n ? {\n ...chunk,\n identifier: this.normalizeSocIdentifier(chunk.identifier),\n signer:\n chunk.signer === \"app\"\n ? chunk.signer\n : {\n ...chunk.signer,\n privateKey: this.normalizeSocKey(chunk.signer.privateKey),\n },\n }\n : chunk\n\n const response = await this.sendRequest<StampChunkResponseMessage>({\n type: \"stampChunk\",\n requestId,\n chunk: wireChunk as StampChunkRequest,\n })\n\n return {\n address: response.address,\n stamp: response.stamp,\n ...(response.owner !== undefined && { owner: response.owner }),\n ...(response.signature !== undefined && {\n signature: response.signature,\n }),\n }\n }\n\n // ============================================================================\n // File Upload/Download Methods\n // ============================================================================\n\n /**\n * Uploads a file to the Swarm network, wrapped in a manifest that carries\n * its name and content type. Read the reference back with\n * {@link downloadFile}. A gateway's `/bzz/<reference>/` is only for a plain\n * reference, uploaded with `encrypt: false`.\n *\n * Accepts either a File object (from file input) or raw Uint8Array data.\n * When using a File object, the filename is automatically extracted unless\n * explicitly overridden.\n *\n * Content is encrypted unless `options.encrypt` is `false`, and the\n * manifest too — a 64-byte reference that carries the key — unless\n * `options.encrypt` or `options.encryptManifest` is `false`. The same rule\n * as {@link uploadFiles}.\n *\n * @param file - The file to upload (File object or Uint8Array)\n * @param name - Optional filename (extracted from File object if not provided)\n * @param options - Optional upload configuration\n * @param options.pin - Whether to pin the file locally (defaults to false; ignored on a subsidised gateway)\n * @param options.encrypt - Whether to encrypt the file content (defaults to true); `false` also leaves the manifest plain\n * @param options.encryptManifest - Whether to encrypt the manifest too (defaults to true); `false` gives a 32-byte reference over encrypted content\n * @param options.tag - Tag ID for tracking upload progress\n * @param options.deferred - Whether to use deferred upload (defaults to false)\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the upload result\n * @returns return.reference - The Swarm reference (hash) of the uploaded file\n * @returns return.tagUid - The tag UID if a tag was created\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not authenticated or cannot upload\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * // From file input\n * const fileInput = document.querySelector('input[type=\"file\"]')\n * const file = fileInput.files[0]\n * const result = await client.uploadFile(file)\n *\n * // From Uint8Array with custom name\n * const data = new Uint8Array([...])\n * const result = await client.uploadFile(data, 'document.pdf')\n * ```\n */\n async uploadFile(\n file: File | Uint8Array,\n name?: string,\n options?: UploadOptions,\n requestOptions?: RequestOptions,\n ): Promise<UploadResult> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n const {\n onProgress,\n useWebSocket,\n useWorkers,\n workerCount,\n concurrency,\n ...serializableOptions\n } = options ?? {}\n\n let data: Uint8Array\n let fileName: string | undefined = name\n\n if (file instanceof File) {\n const buffer = await file.arrayBuffer()\n data = new Uint8Array(buffer)\n fileName = fileName || file.name\n } else {\n data = new Uint8Array(\n file.buffer.slice(0),\n file.byteOffset,\n file.byteLength,\n )\n }\n\n const stopProgress = this.listenForProgress(requestId, onProgress)\n try {\n const response = await this.sendRequest<{\n type: \"uploadFileResponse\"\n requestId: string\n reference: Reference\n tagUid?: number\n }>({\n type: \"uploadFile\",\n requestId,\n data,\n name: fileName,\n options: serializableOptions,\n requestOptions,\n enableProgress: !!onProgress,\n useWebSocket,\n useWorkers,\n workerCount,\n concurrency,\n })\n\n return {\n reference: response.reference,\n tagUid: response.tagUid,\n }\n } finally {\n stopProgress()\n }\n }\n\n /**\n * Downloads a file from the Swarm network: the counterpart of\n * {@link uploadFile}. It resolves a manifest, so a reference produced by\n * {@link uploadData} fails here inside the manifest parser; use\n * {@link downloadData} for those.\n *\n * Returns both the file data and its original filename (if available).\n * For manifest references, an optional path can be specified to retrieve\n * a specific file from the manifest.\n *\n * @param reference - The Swarm reference (hash) of the file to download\n * @param path - Optional path within a manifest to retrieve a specific file\n * @param options - Optional download configuration\n * @param options.redundancyStrategy - Strategy for handling redundancy (0-3)\n * @param options.fallback - Whether to use fallback retrieval\n * @param options.timeoutMs - Download timeout in milliseconds\n * @param options.actPublisher - ACT publisher for encrypted content\n * @param options.actHistoryAddress - ACT history address for encrypted content\n * @param options.actTimestamp - ACT timestamp for encrypted content\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the file data object\n * @returns return.name - The filename\n * @returns return.data - The file contents as a Uint8Array\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the reference is not found\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const file = await client.downloadFile('a1b2c3...')\n * console.log('Filename:', file.name)\n *\n * // Create download link\n * const blob = new Blob([file.data])\n * const url = URL.createObjectURL(blob)\n * ```\n */\n async downloadFile(\n reference: Reference,\n path?: string,\n options?: DownloadOptions,\n requestOptions?: RequestOptions,\n ): Promise<FileData> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"downloadFileResponse\"\n requestId: string\n name: string\n data: number[]\n }>({\n type: \"downloadFile\",\n requestId,\n reference,\n path,\n options,\n requestOptions,\n })\n\n return {\n name: response.name,\n data: new Uint8Array(response.data),\n }\n }\n\n /**\n * Uploads a folder as one manifest (#750): a fork per file with its path and\n * content type, which a gateway serves at `/bzz/<reference>/<path>` when the\n * folder is plain (`encrypt: false`). Takes what bee-js takes — the\n * `FileList` of a `webkitdirectory` input or a dropped directory, a `File[]`,\n * or `{ path, file }` pairs for a folder the app assembled itself. A `File`'s\n * path is its `webkitRelativePath` minus the picked folder's own name, or its\n * name.\n *\n * Content is encrypted unless `options.encrypt` is `false`, and the\n * manifest too — a 64-byte root reference — unless `options.encrypt` or\n * `options.encryptManifest` is `false`. Name `options.indexDocument` for\n * the bare `/bzz/<reference>/` to serve a file. Read a folder back with\n * {@link listFiles} and {@link downloadData} per entry, or one file with\n * {@link downloadFile} and its path.\n *\n * Every file is read into memory before the upload starts; for folders\n * larger than that, upload the files with {@link uploadData} and build the\n * manifest with `@ethersphere/core-sdk`.\n *\n * @param files - The folder's files\n * @param options - Optional upload configuration; `onProgress` counts files, `useWorkers` / `workerCount` stamp in a pool as with {@link uploadData}\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the upload result\n * @returns return.reference - The Swarm reference of the manifest\n * @returns return.tagUid - The tag UID if a tag was created\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not authenticated or cannot upload\n * @throws {Error} If two files share a path\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * // <input type=\"file\" webkitdirectory>\n * const { reference } = await client.uploadFiles(input.files, {\n * indexDocument: 'index.html',\n * })\n * // or assembled by the app\n * await client.uploadFiles([{ path: 'a/b.txt', file: new Blob(['hi']) }])\n * ```\n */\n async uploadFiles(\n files: FileList | Iterable<File | CollectionFileInput>,\n options?: UploadFilesOptions,\n requestOptions?: RequestOptions,\n ): Promise<UploadResult> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n const { onProgress, useWorkers, workerCount, ...serializableOptions } =\n options ?? {}\n\n const entries = await Promise.all(\n Array.from(files, async (item) => {\n const { path, file } =\n item instanceof File\n ? { path: collectionPath(item), file: item }\n : item\n return {\n path,\n data: new Uint8Array(await file.arrayBuffer()),\n contentType: file.type || undefined,\n }\n }),\n )\n\n const stopProgress = this.listenForProgress(requestId, onProgress)\n try {\n const response = await this.sendRequest<{\n type: \"uploadFilesResponse\"\n requestId: string\n reference: Reference\n tagUid?: number\n }>({\n type: \"uploadFiles\",\n requestId,\n files: entries,\n options: serializableOptions,\n requestOptions,\n enableProgress: !!onProgress,\n useWorkers,\n workerCount,\n })\n return { reference: response.reference, tagUid: response.tagUid }\n } finally {\n stopProgress()\n }\n }\n\n /**\n * Lists the files of a manifest uploaded with {@link uploadFiles} (or any\n * manifest): each entry's path, content type, and the reference of its\n * content, which {@link downloadData} reads.\n *\n * @param reference - The Swarm reference of the manifest\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry)\n * @returns A promise resolving to the entries, the index-document fork excluded\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the reference is not a manifest or is not found\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * for (const { path, reference } of await client.listFiles(root)) {\n * const data = await client.downloadData(reference)\n * }\n * ```\n */\n async listFiles(\n reference: Reference,\n requestOptions?: RequestOptions,\n ): Promise<CollectionEntry[]> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<{\n type: \"listFilesResponse\"\n requestId: string\n entries: CollectionEntry[]\n }>({ type: \"listFiles\", requestId, reference, requestOptions })\n return response.entries\n }\n\n /**\n * Forward the proxy's `uploadProgress` messages for one request to a\n * callback, through the window listener's checks. Returns the function that\n * stops forwarding; a no-op without a callback.\n */\n private listenForProgress(\n requestId: string,\n onProgress: ((progress: UploadProgress) => void) | undefined,\n ): () => void {\n if (!onProgress) return () => {}\n this.progressListeners.set(requestId, onProgress)\n return () => {\n this.progressListeners.delete(requestId)\n }\n }\n\n // ============================================================================\n // Chunk Upload/Download Methods\n // ============================================================================\n\n /**\n * Uploads a single chunk to the Swarm network.\n *\n * Chunks are the fundamental unit of storage in Swarm (4KB each).\n * This method is useful for low-level operations or when implementing\n * custom chunking strategies.\n *\n * `data` is the chunk's payload, not a finished chunk: the proxy builds the\n * content-addressed chunk around it (span header, BMT address) and returns\n * that address. A chunk that already carries its span header is wrapped a\n * second time and stored under an address nothing else computes (#774). To\n * store a folder as a manifest, use {@link uploadFiles}; to save a Mantaray\n * tree of your own, use `saveMantarayTreeRecursively` with {@link uploadData}.\n *\n * @param data - The chunk payload, 1 to 4096 bytes\n * @param options - Optional upload configuration\n * @param options.pin - Whether to pin the chunk locally (defaults to false; ignored on a subsidised gateway)\n * @param options.encrypt - Whether to encrypt the chunk (defaults to false)\n * @param options.tag - Tag ID for tracking upload progress\n * @param options.deferred - Whether to use deferred upload (defaults to false)\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the upload result\n * @returns return.reference - The Swarm reference (hash) of the uploaded chunk\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not authenticated or cannot upload\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const chunk = new Uint8Array(4096) // 4KB chunk\n * chunk.fill(0x42) // Fill with data\n * const result = await client.uploadChunk(chunk)\n * console.log('Chunk reference:', result.reference)\n * ```\n */\n async uploadChunk(\n data: Uint8Array,\n options?: UploadOptions,\n requestOptions?: RequestOptions,\n ): Promise<UploadResult> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n const { onProgress: _onProgress, ...serializableOptions } = options ?? {}\n\n const response = await this.sendRequest<{\n type: \"uploadChunkResponse\"\n requestId: string\n reference: Reference\n }>({\n type: \"uploadChunk\",\n requestId,\n data: data as Uint8Array,\n options: serializableOptions,\n requestOptions,\n })\n\n return {\n reference: response.reference,\n }\n }\n\n /**\n * Downloads a single chunk from the Swarm network.\n *\n * Retrieves a chunk by its reference hash. This method is useful for\n * low-level operations or when implementing custom retrieval strategies.\n *\n * @param reference - The Swarm reference (hash) of the chunk to download\n * @param options - Optional download configuration\n * @param options.redundancyStrategy - Strategy for handling redundancy (0-3)\n * @param options.fallback - Whether to use fallback retrieval\n * @param options.timeoutMs - Download timeout in milliseconds\n * @param options.actPublisher - ACT publisher for encrypted content\n * @param options.actHistoryAddress - ACT history address for encrypted content\n * @param options.actTimestamp - ACT timestamp for encrypted content\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the chunk data as a Uint8Array\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the reference is not found\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const chunk = await client.downloadChunk('a1b2c3...')\n * console.log('Chunk size:', chunk.length)\n * ```\n */\n async downloadChunk(\n reference: Reference,\n options?: DownloadOptions,\n requestOptions?: RequestOptions,\n ): Promise<Uint8Array> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"downloadChunkResponse\"\n requestId: string\n data: number[]\n }>({\n type: \"downloadChunk\",\n requestId,\n reference,\n options,\n requestOptions,\n })\n\n return new Uint8Array(response.data)\n }\n\n // ============================================================================\n // SOC (Single Owner Chunk) Methods\n // ============================================================================\n\n /**\n * Returns an object for reading single owner chunks (SOC).\n *\n * @param ownerAddress - Ethereum address of the SOC owner\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns SOCReader with `download` (encrypted) and `rawDownload` (unencrypted)\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const reader = client.makeSOCReader(owner)\n * const soc = await reader.download(identifier, encryptionKey)\n * console.log('Payload:', new TextDecoder().decode(soc.payload))\n * ```\n */\n makeSOCReader(\n ownerAddress: EthAddress | Uint8Array | string,\n requestOptions?: RequestOptions,\n ): SOCReader {\n this.ensureReady()\n const owner = new EthAddress(ownerAddress).toHex()\n\n const sendSocDownload = async (\n identifier: Identifier | Uint8Array | string,\n encryptionKey: Uint8Array | string,\n ): Promise<SingleOwnerChunk> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SocDownloadResponseMessage,\n SocDownloadMessage\n >({\n type: \"socDownload\",\n requestId,\n owner,\n identifier: this.normalizeSocIdentifier(identifier),\n encryptionKey: this.normalizeSocKey(encryptionKey),\n requestOptions,\n })\n\n return this.socChunkFromResponse(response)\n }\n\n const sendRawSocDownload = async (\n identifier: Identifier | Uint8Array | string,\n encryptionKey?: Uint8Array | string,\n ): Promise<SingleOwnerChunk> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SocRawDownloadResponseMessage,\n SocRawDownloadMessage\n >({\n type: \"socRawDownload\",\n requestId,\n owner,\n identifier: this.normalizeSocIdentifier(identifier),\n encryptionKey: encryptionKey\n ? this.normalizeSocKey(encryptionKey)\n : undefined,\n requestOptions,\n })\n\n return this.socChunkFromResponse(response)\n }\n\n return {\n getOwner: async () => owner,\n rawDownload: (identifier, encryptionKey) =>\n sendRawSocDownload(identifier, encryptionKey),\n download: (identifier, encryptionKey) =>\n sendSocDownload(identifier, encryptionKey),\n }\n }\n\n /**\n * Returns an object for reading and writing single owner chunks (SOC).\n *\n * Uploads are encrypted by default. Use `rawUpload` for unencrypted SOCs.\n *\n * @param signer - Optional SOC signer private key. If omitted, the proxy uses the app signer.\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns SOCWriter with `upload`, `rawUpload`, `download`, and `rawDownload`\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const writer = client.makeSOCWriter()\n * const upload = await writer.upload(identifier, payload)\n * const soc = await writer.download(identifier, upload.encryptionKey)\n * ```\n */\n makeSOCWriter(\n signer?: PrivateKey | Uint8Array | string,\n requestOptions?: RequestOptions,\n ): SOCWriter {\n this.ensureReady()\n const signerObj = signer ? new PrivateKey(signer) : undefined\n const signerKey = signerObj ? signerObj.toHex() : undefined\n let owner: string | undefined = signerObj\n ? signerObj.publicKey().address().toHex()\n : undefined\n\n const resolveOwner = async (): Promise<string> => {\n if (owner) {\n return owner\n }\n\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SocGetOwnerResponseMessage,\n SocGetOwnerMessage\n >({\n type: \"socGetOwner\",\n requestId,\n })\n\n owner = response.owner\n return owner\n }\n\n const sendSocDownload = async (\n identifier: Identifier | Uint8Array | string,\n encryptionKey: Uint8Array | string,\n ): Promise<SingleOwnerChunk> => {\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<\n SocDownloadResponseMessage,\n SocDownloadMessage\n >({\n type: \"socDownload\",\n requestId,\n owner,\n identifier: this.normalizeSocIdentifier(identifier),\n encryptionKey: this.normalizeSocKey(encryptionKey),\n requestOptions,\n })\n\n return this.socChunkFromResponse(response)\n }\n\n const sendRawSocDownload = async (\n identifier: Identifier | Uint8Array | string,\n encryptionKey?: Uint8Array | string,\n ): Promise<SingleOwnerChunk> => {\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<\n SocRawDownloadResponseMessage,\n SocRawDownloadMessage\n >({\n type: \"socRawDownload\",\n requestId,\n owner,\n identifier: this.normalizeSocIdentifier(identifier),\n encryptionKey: encryptionKey\n ? this.normalizeSocKey(encryptionKey)\n : undefined,\n requestOptions,\n })\n\n return this.socChunkFromResponse(response)\n }\n\n const sendSocUpload = async (\n identifier: Identifier | Uint8Array | string,\n data: Uint8Array,\n options?: UploadOptions,\n ): Promise<SocUploadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SocUploadResponseMessage,\n SocUploadMessage\n >({\n type: \"socUpload\",\n requestId,\n identifier: this.normalizeSocIdentifier(identifier),\n data: new Uint8Array(data),\n signer: signerKey,\n options,\n requestOptions,\n })\n\n owner = response.owner\n\n return {\n reference: response.reference,\n tagUid: response.tagUid,\n encryptionKey: response.encryptionKey,\n owner: response.owner,\n }\n }\n\n const sendRawSocUpload = async (\n identifier: Identifier | Uint8Array | string,\n data: Uint8Array,\n options?: UploadOptions,\n ): Promise<SocRawUploadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SocRawUploadResponseMessage,\n SocRawUploadMessage\n >({\n type: \"socRawUpload\",\n requestId,\n identifier: this.normalizeSocIdentifier(identifier),\n data: new Uint8Array(data),\n signer: signerKey,\n options,\n requestOptions,\n })\n\n owner = response.owner\n\n return {\n reference: response.reference,\n tagUid: response.tagUid,\n encryptionKey: response.encryptionKey,\n owner: response.owner,\n }\n }\n\n return {\n getOwner: resolveOwner,\n rawDownload: (identifier, encryptionKey) =>\n sendRawSocDownload(identifier, encryptionKey),\n download: (identifier, encryptionKey) =>\n sendSocDownload(identifier, encryptionKey),\n upload: (identifier, data, options) =>\n sendSocUpload(identifier, data, options),\n rawUpload: (identifier, data, options) =>\n sendRawSocUpload(identifier, data, options),\n }\n }\n\n /**\n * Returns an object for reading epoch-based feeds.\n *\n * @param options - Feed reader options\n * @param options.topic - Feed topic (32 bytes)\n * @param options.owner - Optional feed owner address\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns FeedReader with `getOwner`, `downloadReference`, and `downloadPayload`\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the request times out\n */\n makeEpochFeedReader(\n options: FeedReaderOptions,\n requestOptions?: RequestOptions,\n ): FeedReader {\n this.ensureReady()\n const topic = this.normalizeFeedTopic(options.topic)\n let owner: string | undefined = options.owner\n ? new EthAddress(options.owner).toHex()\n : undefined\n\n const resolveOwner = async (): Promise<string> => {\n if (owner) {\n return owner\n }\n\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n FeedGetOwnerResponseMessage,\n FeedGetOwnerMessage\n >({\n type: \"feedGetOwner\",\n requestId,\n })\n\n owner = response.owner\n return owner\n }\n\n const downloadReference = async (\n options?: EpochFeedDownloadOptions,\n ): Promise<EpochFeedDownloadReferenceResult> => {\n const atValue =\n options?.at !== undefined\n ? options.at\n : BigInt(Math.floor(Date.now() / 1000))\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n EpochFeedDownloadReferenceResponseMessage,\n EpochFeedDownloadReferenceMessage\n >({\n type: \"epochFeedDownloadReference\",\n requestId,\n topic,\n owner,\n at: this.normalizeFeedTimestamp(atValue),\n after:\n options?.after !== undefined\n ? this.normalizeFeedTimestamp(options.after)\n : undefined,\n encryptionKey:\n options?.encryptionKey !== undefined\n ? this.normalizeSocKey(options.encryptionKey)\n : undefined,\n requestOptions,\n })\n const reference = response.reference\n const cleanRef =\n reference && reference.startsWith(\"0x\") ? reference.slice(2) : reference\n const encryptionKey =\n cleanRef && cleanRef.length === 128 ? cleanRef.slice(64) : undefined\n return { reference, encryptionKey }\n }\n\n const downloadPayload = async (\n options?: EpochFeedDownloadOptions,\n ): Promise<EpochFeedDownloadPayloadResult> => {\n const result = await downloadReference(options)\n if (!result.reference) {\n return {\n reference: undefined,\n payload: undefined,\n encryptionKey: undefined,\n }\n }\n const payload = await this.downloadData(\n result.reference,\n undefined,\n requestOptions,\n )\n return {\n reference: result.reference,\n payload,\n encryptionKey: result.encryptionKey,\n }\n }\n\n const downloadRawReference = async (\n options?: Omit<EpochFeedDownloadOptions, \"encryptionKey\">,\n ): Promise<EpochFeedDownloadReferenceResult> => {\n const atValue =\n options?.at !== undefined\n ? options.at\n : BigInt(Math.floor(Date.now() / 1000))\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n EpochFeedDownloadReferenceResponseMessage,\n EpochFeedDownloadReferenceMessage\n >({\n type: \"epochFeedDownloadReference\",\n requestId,\n topic,\n owner,\n at: this.normalizeFeedTimestamp(atValue),\n after:\n options?.after !== undefined\n ? this.normalizeFeedTimestamp(options.after)\n : undefined,\n encryptionKey: undefined, // No encryption for raw download\n requestOptions,\n })\n const reference = response.reference\n return { reference, encryptionKey: undefined }\n }\n\n const downloadRawPayload = async (\n options?: Omit<EpochFeedDownloadOptions, \"encryptionKey\">,\n ): Promise<EpochFeedDownloadPayloadResult> => {\n const result = await downloadRawReference(options)\n if (!result.reference) {\n return {\n reference: undefined,\n payload: undefined,\n encryptionKey: undefined,\n }\n }\n const payload = await this.downloadData(\n result.reference,\n undefined,\n requestOptions,\n )\n return {\n reference: result.reference,\n payload,\n encryptionKey: undefined,\n }\n }\n\n return {\n getOwner: resolveOwner,\n downloadReference,\n downloadPayload,\n downloadRawReference,\n downloadRawPayload,\n }\n }\n\n /**\n * Returns an object for reading and writing epoch-based feeds.\n *\n * @param options - Feed writer options\n * @param options.topic - Feed topic (32 bytes)\n * @param options.signer - Optional feed signer private key. If omitted, the proxy uses the app signer.\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns FeedWriter with `getOwner`, `downloadReference`, `downloadPayload`, `uploadPayload`, and `uploadReference`\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the request times out\n */\n makeEpochFeedWriter(\n options: FeedWriterOptions,\n requestOptions?: RequestOptions,\n ): FeedWriter {\n this.ensureReady()\n const topic = this.normalizeFeedTopic(options.topic)\n const signerObj = options.signer\n ? new PrivateKey(options.signer)\n : undefined\n const signerKey = signerObj ? signerObj.toHex() : undefined\n let owner: string | undefined = signerObj\n ? signerObj.publicKey().address().toHex()\n : undefined\n\n const resolveOwner = async (): Promise<string> => {\n if (owner) {\n return owner\n }\n\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n FeedGetOwnerResponseMessage,\n FeedGetOwnerMessage\n >({\n type: \"feedGetOwner\",\n requestId,\n })\n\n owner = response.owner\n return owner\n }\n\n const downloadReference = async (\n options?: EpochFeedDownloadOptions,\n ): Promise<EpochFeedDownloadReferenceResult> => {\n const atValue =\n options?.at !== undefined\n ? options.at\n : BigInt(Math.floor(Date.now() / 1000))\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n EpochFeedDownloadReferenceResponseMessage,\n EpochFeedDownloadReferenceMessage\n >({\n type: \"epochFeedDownloadReference\",\n requestId,\n topic,\n owner,\n at: this.normalizeFeedTimestamp(atValue),\n after:\n options?.after !== undefined\n ? this.normalizeFeedTimestamp(options.after)\n : undefined,\n encryptionKey:\n options?.encryptionKey !== undefined\n ? this.normalizeSocKey(options.encryptionKey)\n : undefined,\n requestOptions,\n })\n const reference = response.reference\n const cleanRef =\n reference && reference.startsWith(\"0x\") ? reference.slice(2) : reference\n const encryptionKey =\n cleanRef && cleanRef.length === 128 ? cleanRef.slice(64) : undefined\n return { reference, encryptionKey }\n }\n\n const downloadPayload = async (\n options?: EpochFeedDownloadOptions,\n ): Promise<EpochFeedDownloadPayloadResult> => {\n const result = await downloadReference(options)\n if (!result.reference) {\n return {\n reference: undefined,\n payload: undefined,\n encryptionKey: undefined,\n }\n }\n const payload = await this.downloadData(\n result.reference,\n undefined,\n requestOptions,\n )\n return {\n reference: result.reference,\n payload,\n encryptionKey: result.encryptionKey,\n }\n }\n\n const uploadReference = async (\n reference: Uint8Array | string,\n options?: EpochFeedUploadOptions,\n ): Promise<EpochFeedUploadResult> => {\n const atValue =\n options?.at !== undefined\n ? options.at\n : BigInt(Math.floor(Date.now() / 1000))\n const normalizedRef = this.normalizeReference(reference)\n const cleanRef = normalizedRef.startsWith(\"0x\")\n ? normalizedRef.slice(2)\n : normalizedRef\n const derivedKey =\n cleanRef.length === 128 ? cleanRef.slice(64) : undefined\n const feedKey = options?.encryptionKey ?? derivedKey\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n EpochFeedUploadReferenceResponseMessage,\n EpochFeedUploadReferenceMessage\n >({\n type: \"epochFeedUploadReference\",\n requestId,\n topic,\n signer: signerKey,\n at: this.normalizeFeedTimestamp(atValue),\n reference: normalizedRef,\n encryptionKey:\n feedKey !== undefined ? this.normalizeSocKey(feedKey) : undefined,\n hints: options?.hints,\n requestOptions,\n })\n const socAddress = response.socAddress\n const encryptionKey = derivedKey\n return {\n socAddress,\n reference: normalizedRef,\n encryptionKey,\n epoch: response.epoch,\n timestamp: response.timestamp,\n }\n }\n\n const uploadPayload = async (\n data: Uint8Array | string,\n options?: EpochFeedUploadOptions,\n ): Promise<EpochFeedUploadResult> => {\n const atValue =\n options?.at !== undefined\n ? options.at\n : BigInt(Math.floor(Date.now() / 1000))\n const encrypt = options?.encrypt !== false\n const uploadResult = await this.uploadData(\n this.normalizePayload(data),\n { ...options?.uploadOptions, encrypt },\n requestOptions,\n )\n const cleanRef = uploadResult.reference.startsWith(\"0x\")\n ? uploadResult.reference.slice(2)\n : uploadResult.reference\n const derivedKey =\n cleanRef.length === 128 ? cleanRef.slice(64) : undefined\n const feedKey = options?.encryptionKey ?? derivedKey\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n EpochFeedUploadReferenceResponseMessage,\n EpochFeedUploadReferenceMessage\n >({\n type: \"epochFeedUploadReference\",\n requestId,\n topic,\n signer: signerKey,\n at: this.normalizeFeedTimestamp(atValue),\n reference: uploadResult.reference,\n encryptionKey:\n feedKey !== undefined ? this.normalizeSocKey(feedKey) : undefined,\n hints: options?.hints,\n requestOptions,\n })\n const socAddress = response.socAddress\n const encryptionKey = derivedKey\n return {\n socAddress,\n reference: uploadResult.reference,\n encryptionKey,\n epoch: response.epoch,\n timestamp: response.timestamp,\n }\n }\n\n const downloadRawReference = async (\n options?: Omit<EpochFeedDownloadOptions, \"encryptionKey\">,\n ): Promise<EpochFeedDownloadReferenceResult> => {\n const atValue =\n options?.at !== undefined\n ? options.at\n : BigInt(Math.floor(Date.now() / 1000))\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n EpochFeedDownloadReferenceResponseMessage,\n EpochFeedDownloadReferenceMessage\n >({\n type: \"epochFeedDownloadReference\",\n requestId,\n topic,\n owner,\n at: this.normalizeFeedTimestamp(atValue),\n after:\n options?.after !== undefined\n ? this.normalizeFeedTimestamp(options.after)\n : undefined,\n encryptionKey: undefined, // No encryption for raw download\n requestOptions,\n })\n const reference = response.reference\n return { reference, encryptionKey: undefined }\n }\n\n const downloadRawPayload = async (\n options?: Omit<EpochFeedDownloadOptions, \"encryptionKey\">,\n ): Promise<EpochFeedDownloadPayloadResult> => {\n const result = await downloadRawReference(options)\n if (!result.reference) {\n return {\n reference: undefined,\n payload: undefined,\n encryptionKey: undefined,\n }\n }\n const payload = await this.downloadData(\n result.reference,\n undefined,\n requestOptions,\n )\n return {\n reference: result.reference,\n payload,\n encryptionKey: undefined,\n }\n }\n\n const uploadRawReference = async (\n reference: Uint8Array | string,\n options?: Omit<EpochFeedUploadOptions, \"encryptionKey\">,\n ): Promise<EpochFeedUploadResult> => {\n const atValue =\n options?.at !== undefined\n ? options.at\n : BigInt(Math.floor(Date.now() / 1000))\n const normalizedRef = this.normalizeReference(reference)\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n EpochFeedUploadReferenceResponseMessage,\n EpochFeedUploadReferenceMessage\n >({\n type: \"epochFeedUploadReference\",\n requestId,\n topic,\n signer: signerKey,\n at: this.normalizeFeedTimestamp(atValue),\n reference: normalizedRef,\n encryptionKey: undefined, // No encryption for raw upload\n hints: options?.hints,\n requestOptions,\n })\n const socAddress = response.socAddress\n return {\n socAddress,\n reference: normalizedRef,\n encryptionKey: undefined,\n epoch: response.epoch,\n timestamp: response.timestamp,\n }\n }\n\n const uploadRawPayload = async (\n data: Uint8Array | string,\n options?: Omit<EpochFeedUploadOptions, \"encryptionKey\" | \"encrypt\">,\n ): Promise<EpochFeedUploadResult> => {\n const atValue =\n options?.at !== undefined\n ? options.at\n : BigInt(Math.floor(Date.now() / 1000))\n // Upload with encrypt: false for raw payload\n const uploadResult = await this.uploadData(\n this.normalizePayload(data),\n { ...options?.uploadOptions, encrypt: false },\n requestOptions,\n )\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n EpochFeedUploadReferenceResponseMessage,\n EpochFeedUploadReferenceMessage\n >({\n type: \"epochFeedUploadReference\",\n requestId,\n topic,\n signer: signerKey,\n at: this.normalizeFeedTimestamp(atValue),\n reference: uploadResult.reference,\n encryptionKey: undefined, // No encryption for raw upload\n hints: options?.hints,\n requestOptions,\n })\n const socAddress = response.socAddress\n return {\n socAddress,\n reference: uploadResult.reference,\n encryptionKey: undefined,\n epoch: response.epoch,\n timestamp: response.timestamp,\n }\n }\n\n return {\n getOwner: resolveOwner,\n downloadReference,\n downloadPayload,\n downloadRawReference,\n downloadRawPayload,\n uploadReference,\n uploadPayload,\n uploadRawReference,\n uploadRawPayload,\n }\n }\n\n /**\n * Returns a sequential feed reader (chunk API only).\n *\n * @param options - Sequential feed reader options\n * @param options.topic - Feed topic (32 bytes)\n * @param options.owner - Optional feed owner address\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns SequentialFeedReader with payload/reference download helpers\n */\n makeSequentialFeedReader(\n options: SequentialFeedReaderOptions,\n requestOptions?: RequestOptions,\n ): SequentialFeedReader {\n this.ensureReady()\n const topic = this.normalizeFeedTopic(options.topic)\n let owner: string | undefined = options.owner\n ? new EthAddress(options.owner).toHex()\n : undefined\n\n const resolveOwner = async (): Promise<string> => {\n if (owner) {\n return owner\n }\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedGetOwnerResponseMessage,\n SequentialFeedGetOwnerMessage\n >({\n type: \"seqFeedGetOwner\",\n requestId,\n })\n owner = response.owner\n return owner\n }\n\n const downloadPayload = async (\n encryptionKey: Uint8Array | string,\n options?: SequentialFeedUpdateOptions,\n ): Promise<SequentialFeedPayloadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedDownloadPayloadResponseMessage,\n SequentialFeedDownloadPayloadMessage\n >({\n type: \"seqFeedDownloadPayload\",\n requestId,\n topic,\n owner,\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n lookupTimeoutMs: options?.lookupTimeoutMs,\n encryptionKey: this.normalizeSocKey(encryptionKey),\n requestOptions,\n })\n\n return {\n payload: response.payload,\n timestamp: response.timestamp,\n feedIndex: response.feedIndex,\n feedIndexNext: response.feedIndexNext,\n }\n }\n\n const downloadRawPayload = async (\n options?: SequentialFeedDownloadRawOptions,\n ): Promise<SequentialFeedPayloadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedDownloadRawPayloadResponseMessage,\n SequentialFeedDownloadRawPayloadMessage\n >({\n type: \"seqFeedDownloadRawPayload\",\n requestId,\n topic,\n owner,\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n lookupTimeoutMs: options?.lookupTimeoutMs,\n encryptionKey: options?.encryptionKey\n ? this.normalizeSocKey(options.encryptionKey)\n : undefined,\n requestOptions,\n })\n\n return {\n payload: response.payload,\n timestamp: response.timestamp,\n feedIndex: response.feedIndex,\n feedIndexNext: response.feedIndexNext,\n }\n }\n\n const downloadReference = async (\n encryptionKey: Uint8Array | string,\n options?: SequentialFeedUpdateOptions,\n ): Promise<SequentialFeedReferenceResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedDownloadReferenceResponseMessage,\n SequentialFeedDownloadReferenceMessage\n >({\n type: \"seqFeedDownloadReference\",\n requestId,\n topic,\n owner,\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n lookupTimeoutMs: options?.lookupTimeoutMs,\n encryptionKey: this.normalizeSocKey(encryptionKey),\n requestOptions,\n })\n\n return {\n reference: response.reference,\n feedIndex: response.feedIndex,\n feedIndexNext: response.feedIndexNext,\n }\n }\n\n return {\n getOwner: resolveOwner,\n downloadPayload,\n downloadRawPayload,\n downloadReference,\n }\n }\n\n /**\n * Returns a sequential feed writer (chunk API only).\n *\n * @param options - Sequential feed writer options\n * @param options.topic - Feed topic (32 bytes)\n * @param options.signer - Optional signer private key. If omitted, proxy uses app signer.\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns SequentialFeedWriter with payload/reference upload helpers\n */\n makeSequentialFeedWriter(\n options: SequentialFeedWriterOptions,\n requestOptions?: RequestOptions,\n ): SequentialFeedWriter {\n this.ensureReady()\n const topic = this.normalizeFeedTopic(options.topic)\n const signerObj = options.signer\n ? new PrivateKey(options.signer)\n : undefined\n const signerKey = signerObj ? signerObj.toHex() : undefined\n let owner: string | undefined = signerObj\n ? signerObj.publicKey().address().toHex()\n : undefined\n\n const resolveOwner = async (): Promise<string> => {\n if (owner) {\n return owner\n }\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedGetOwnerResponseMessage,\n SequentialFeedGetOwnerMessage\n >({\n type: \"seqFeedGetOwner\",\n requestId,\n })\n owner = response.owner\n return owner\n }\n\n const downloadPayload = async (\n encryptionKey: Uint8Array | string,\n options?: SequentialFeedUpdateOptions,\n ): Promise<SequentialFeedPayloadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedDownloadPayloadResponseMessage,\n SequentialFeedDownloadPayloadMessage\n >({\n type: \"seqFeedDownloadPayload\",\n requestId,\n topic,\n owner,\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n encryptionKey: this.normalizeSocKey(encryptionKey),\n requestOptions,\n })\n\n return {\n payload: response.payload,\n timestamp: response.timestamp,\n feedIndex: response.feedIndex,\n feedIndexNext: response.feedIndexNext,\n }\n }\n\n const downloadRawPayload = async (\n options?: SequentialFeedDownloadRawOptions,\n ): Promise<SequentialFeedPayloadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedDownloadRawPayloadResponseMessage,\n SequentialFeedDownloadRawPayloadMessage\n >({\n type: \"seqFeedDownloadRawPayload\",\n requestId,\n topic,\n owner,\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n encryptionKey: options?.encryptionKey\n ? this.normalizeSocKey(options.encryptionKey)\n : undefined,\n requestOptions,\n })\n\n return {\n payload: response.payload,\n timestamp: response.timestamp,\n feedIndex: response.feedIndex,\n feedIndexNext: response.feedIndexNext,\n }\n }\n\n const downloadReference = async (\n encryptionKey: Uint8Array | string,\n options?: SequentialFeedUpdateOptions,\n ): Promise<SequentialFeedReferenceResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedDownloadReferenceResponseMessage,\n SequentialFeedDownloadReferenceMessage\n >({\n type: \"seqFeedDownloadReference\",\n requestId,\n topic,\n owner,\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n encryptionKey: this.normalizeSocKey(encryptionKey),\n requestOptions,\n })\n\n return {\n reference: response.reference,\n feedIndex: response.feedIndex,\n feedIndexNext: response.feedIndexNext,\n }\n }\n\n const uploadPayload = async (\n data: Uint8Array | string,\n options?: SequentialFeedUploadOptions,\n ): Promise<SequentialFeedUploadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedUploadPayloadResponseMessage,\n SequentialFeedUploadPayloadMessage\n >({\n type: \"seqFeedUploadPayload\",\n requestId,\n topic,\n signer: signerKey,\n data: this.normalizePayload(data),\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n lookupTimeoutMs: options?.lookupTimeoutMs,\n options,\n requestOptions,\n })\n\n owner = response.owner\n\n return {\n reference: response.reference,\n feedIndex: response.feedIndex,\n owner: response.owner,\n encryptionKey: response.encryptionKey,\n tagUid: response.tagUid,\n }\n }\n\n const uploadRawPayload = async (\n data: Uint8Array | string,\n options?: SequentialFeedUploadRawOptions,\n ): Promise<SequentialFeedUploadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedUploadRawPayloadResponseMessage,\n SequentialFeedUploadRawPayloadMessage\n >({\n type: \"seqFeedUploadRawPayload\",\n requestId,\n topic,\n signer: signerKey,\n data: this.normalizePayload(data),\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n lookupTimeoutMs: options?.lookupTimeoutMs,\n encryptionKey: options?.encryptionKey\n ? this.normalizeSocKey(options.encryptionKey)\n : undefined,\n options,\n requestOptions,\n })\n\n owner = response.owner\n\n return {\n reference: response.reference,\n feedIndex: response.feedIndex,\n owner: response.owner,\n encryptionKey: response.encryptionKey,\n tagUid: response.tagUid,\n }\n }\n\n const uploadReference = async (\n reference: Uint8Array | string,\n options?: SequentialFeedUploadOptions,\n ): Promise<SequentialFeedUploadResult> => {\n const requestId = this.generateRequestId()\n const response = await this.sendRequest<\n SequentialFeedUploadReferenceResponseMessage,\n SequentialFeedUploadReferenceMessage\n >({\n type: \"seqFeedUploadReference\",\n requestId,\n topic,\n signer: signerKey,\n reference: this.normalizeReference(reference),\n index:\n options?.index !== undefined\n ? this.normalizeFeedIndex(options.index as bigint | number | string)\n : undefined,\n at:\n options?.at !== undefined\n ? this.normalizeFeedTimestamp(\n options.at as bigint | number | string,\n )\n : undefined,\n hasTimestamp: options?.hasTimestamp,\n lookupTimeoutMs: options?.lookupTimeoutMs,\n options,\n requestOptions,\n })\n\n owner = response.owner\n\n return {\n reference: response.reference,\n feedIndex: response.feedIndex,\n owner: response.owner,\n encryptionKey: response.encryptionKey,\n tagUid: response.tagUid,\n }\n }\n\n return {\n getOwner: resolveOwner,\n downloadPayload,\n downloadRawPayload,\n downloadReference,\n uploadPayload,\n uploadRawPayload,\n uploadReference,\n }\n }\n\n // ============================================================================\n // Feed Manifest Methods\n // ============================================================================\n\n /**\n * Creates a feed manifest for accessing feed content via URL.\n *\n * A feed manifest enables accessing the latest feed content via a URL path\n * (e.g., `/bzz/{manifest-reference}/`). The manifest stores metadata about\n * the feed including owner, topic, and type.\n *\n * @param topic - Feed topic (32-byte hex string)\n * @param options - Optional configuration\n * @param options.owner - Feed owner address; if omitted, uses app signer\n * @param options.uploadOptions - Upload configuration (pin, deferred, etc.)\n * @param requestOptions - Request configuration (timeout, headers). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns Promise resolving to the manifest reference\n * @throws {Error} If the client is not initialized\n * @throws {Error} If no owner is provided and no app signer is available\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * // Create manifest for a feed (uses app signer as owner)\n * const manifestRef = await client.createFeedManifest(topic)\n * console.log('Feed accessible at /bzz/' + manifestRef)\n *\n * // Create manifest with explicit owner\n * const manifestRef = await client.createFeedManifest(topic, {\n * owner: '0x1234...',\n * })\n * ```\n */\n async createFeedManifest(\n topic: string,\n options?: {\n owner?: string\n /** Feed type: \"Sequence\" for sequential feeds, \"Epoch\" for epoch feeds. Default: \"Sequence\" */\n feedType?: \"Sequence\" | \"Epoch\"\n uploadOptions?: UploadOptions\n },\n requestOptions?: RequestOptions,\n ): Promise<string> {\n this.ensureReady()\n const normalizedTopic = this.normalizeFeedTopic(topic)\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<\n CreateFeedManifestResponseMessage,\n CreateFeedManifestMessage\n >({\n type: \"createFeedManifest\",\n requestId,\n topic: normalizedTopic,\n owner: options?.owner,\n feedType: options?.feedType,\n uploadOptions: options?.uploadOptions,\n requestOptions,\n })\n\n return response.reference\n }\n\n // ============================================================================\n // GSOC Methods\n // ============================================================================\n\n /**\n * Mines a private key whose SOC address is proximate to a target overlay.\n *\n * This is a synchronous, pure computation that does not require authentication.\n * The mined signer can be used with {@link gsocSend} to send GSOC messages\n * that route to the target overlay node.\n *\n * @param targetOverlay - The target overlay address to mine proximity for\n * @param identifier - The GSOC identifier\n * @param proximity - Optional proximity depth (defaults to 12 in bee-js)\n * @returns A promise resolving to the mined signer as a hex string (private key)\n * @throws {Error} If the client is not initialized\n * @throws {Error} If no valid signer can be mined\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const signer = await client.gsocMine(targetOverlay, identifier)\n * // Use signer with gsocSend\n * await client.gsocSend(signer, identifier, data)\n * ```\n */\n async gsocMine(\n targetOverlay: string,\n identifier: string,\n proximity?: number,\n ): Promise<string> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"gsocMineResponse\"\n requestId: string\n signer: string\n }>({\n type: \"gsocMine\",\n requestId,\n targetOverlay,\n identifier,\n proximity,\n })\n\n return response.signer\n }\n\n /**\n * Sends a GSOC (Global Single Owner Chunk) message using a mined signer.\n *\n * The signer should be obtained from {@link gsocMine}. The message is sent\n * using the proxy's stored postage batch ID.\n *\n * @param signer - The mined signer as a hex string (from gsocMine)\n * @param identifier - The GSOC identifier\n * @param data - The message data to send\n * @param options - Optional upload configuration\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the upload result with reference and optional tagUid\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not authenticated\n * @throws {Error} If no postage batch ID is available\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const signer = await client.gsocMine(targetOverlay, identifier)\n * const result = await client.gsocSend(signer, identifier, new TextEncoder().encode('Hello!'))\n * console.log('GSOC reference:', result.reference)\n * ```\n */\n async gsocSend(\n signer: string,\n identifier: string,\n data: Uint8Array,\n options?: UploadOptions,\n requestOptions?: RequestOptions,\n ): Promise<UploadResult> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"gsocSendResponse\"\n requestId: string\n reference: Reference\n tagUid?: number\n }>({\n type: \"gsocSend\",\n requestId,\n signer,\n identifier,\n data: new Uint8Array(data),\n options,\n requestOptions,\n })\n\n return {\n reference: response.reference,\n tagUid: response.tagUid,\n }\n }\n\n // ============================================================================\n // ACT (Access Control Tries) Methods\n // ============================================================================\n\n /**\n * Uploads data with ACT (Access Control Tries) protection.\n *\n * This method encrypts the data and creates an ACT that controls who can decrypt it.\n * Only the specified grantees (and the publisher) can decrypt and access the data.\n *\n * @param data - The binary data to upload as a Uint8Array\n * @param grantees - Array of grantee public keys as compressed hex strings (33 bytes = 66 hex chars).\n * A grantee is either another user's `appKey.publicKey` (that user in this app origin only) or\n * their `identity.sharingPublicKey` (that user in every app they connect, #519)\n * @param options - Optional upload configuration\n * @param options.publisher - `\"app\"` (default) publishes with this origin's app key; `\"identity\"`\n * publishes with the account-wide sharing key, so any of the user's apps can manage the grantees later\n * @param options.pin - Whether to pin the data locally (defaults to false; ignored on a subsidised gateway)\n * @param options.tag - Tag ID for tracking upload progress\n * @param options.deferred - Whether to use deferred upload (defaults to false)\n * @param options.onProgress - Optional callback for tracking upload progress\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the ACT upload result\n * @returns return.encryptedReference - The encrypted reference that must be stored with the ACT\n * @returns return.actReference - The Swarm reference (hash) of the ACT manifest\n * @returns return.historyReference - The Swarm reference of the history manifest (use for future operations)\n * @returns return.granteeListReference - The Swarm reference of the encrypted grantee list\n * @returns return.publisherPubKey - The publisher's compressed public key (share with grantees)\n * @returns return.tagUid - The tag UID if a tag was created\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not authenticated or cannot upload\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const data = new TextEncoder().encode('Secret message')\n * const grantees = ['03a1b2c3...'] // Compressed public keys of allowed readers\n * const result = await client.actUploadData(data, grantees, {\n * onProgress: (progress) => {\n * console.log(`Progress: ${progress.processed}/${progress.total}`)\n * },\n * })\n * console.log('History Reference:', result.historyReference)\n * console.log('Encrypted Reference:', result.encryptedReference)\n * console.log('Publisher Public Key:', result.publisherPubKey)\n * ```\n */\n async actUploadData(\n data: Uint8Array,\n grantees: string[],\n options?: ActUploadOptions,\n requestOptions?: RequestOptions,\n ): Promise<{\n encryptedReference: string\n historyReference: string\n granteeListReference: string\n publisherPubKey: string\n actReference: string\n tagUid?: number\n }> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n const { onProgress, ...serializableOptions } = options ?? {}\n\n const stopProgress = this.listenForProgress(requestId, onProgress)\n try {\n const response = await this.sendRequest<{\n type: \"actUploadDataResponse\"\n requestId: string\n encryptedReference: string\n historyReference: string\n granteeListReference: string\n publisherPubKey: string\n actReference: string\n tagUid?: number\n }>({\n type: \"actUploadData\",\n requestId,\n data: new Uint8Array(data),\n grantees,\n options: serializableOptions,\n requestOptions,\n enableProgress: !!onProgress,\n })\n\n return {\n encryptedReference: response.encryptedReference,\n historyReference: response.historyReference,\n granteeListReference: response.granteeListReference,\n publisherPubKey: response.publisherPubKey,\n actReference: response.actReference,\n tagUid: response.tagUid,\n }\n } finally {\n stopProgress()\n }\n }\n\n /**\n * Downloads ACT-protected data from the Swarm network.\n *\n * This method decrypts the ACT to recover the content reference,\n * then downloads and returns the decrypted data. Only authorized\n * grantees (including the publisher) can successfully decrypt.\n *\n * @param encryptedReference - The encrypted reference from actUploadData\n * @param historyReference - The history reference from actUploadData\n * @param publisherPubKey - The publisher's compressed public key from actUploadData\n * @param timestamp - Optional timestamp to look up a specific ACT version\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the decrypted data as a Uint8Array\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not authorized to decrypt the ACT\n * @throws {Error} If the references are not found\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * // Using the references from actUploadData\n * const data = await client.actDownloadData(\n * encryptedReference,\n * historyReference,\n * publisherPubKey\n * )\n * const text = new TextDecoder().decode(data)\n * console.log('Decrypted:', text)\n * ```\n */\n async actDownloadData(\n encryptedReference: string,\n historyReference: string,\n publisherPubKey: string,\n timestamp?: number,\n requestOptions?: RequestOptions,\n ): Promise<Uint8Array> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"actDownloadDataResponse\"\n requestId: string\n data: Uint8Array\n }>({\n type: \"actDownloadData\",\n requestId,\n encryptedReference,\n historyReference,\n publisherPubKey,\n timestamp,\n requestOptions,\n })\n\n return response.data\n }\n\n /**\n * Adds new grantees to an existing ACT.\n *\n * This method adds new public keys to the ACT's access list.\n * Only the publisher (original uploader) can add grantees.\n * Returns new references since Swarm content is immutable.\n *\n * @param historyReference - The current history reference\n * @param grantees - Array of new grantee public keys as compressed hex strings\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the new references\n * @returns return.historyReference - The new history reference after adding grantees\n * @returns return.granteeListReference - The new grantee list reference\n * @returns return.actReference - The new ACT reference\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not the publisher\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const newGrantees = ['03d4e5f6...'] // New public keys to grant access\n * const result = await client.actAddGrantees(historyReference, newGrantees)\n * console.log('New History Reference:', result.historyReference)\n * // The encrypted reference remains the same\n * ```\n */\n async actAddGrantees(\n historyReference: string,\n grantees: string[],\n requestOptions?: RequestOptions,\n ): Promise<{\n historyReference: string\n granteeListReference: string\n actReference: string\n }> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"actAddGranteesResponse\"\n requestId: string\n historyReference: string\n granteeListReference: string\n actReference: string\n }>({\n type: \"actAddGrantees\",\n requestId,\n historyReference,\n grantees,\n requestOptions,\n })\n\n return {\n historyReference: response.historyReference,\n granteeListReference: response.granteeListReference,\n actReference: response.actReference,\n }\n }\n\n /**\n * Revokes grantees from an existing ACT.\n *\n * This method removes public keys from the ACT's access list, producing a new\n * ACT/history without the revoked entries.\n *\n * IMPORTANT: Revocation cannot un-share already-published content. A former\n * grantee kept the access key while granted and the reference lives in\n * immutable history, so they can still decrypt content published before\n * revocation. Revocation only stops access to content published afterwards.\n * The returned `encryptedReference` is unchanged — it is NOT re-encrypted, as\n * that would leak the keystream to former grantees (#496).\n *\n * @param historyReference - The current history reference\n * @param encryptedReference - The current encrypted reference\n * @param revokeGrantees - Array of grantee public keys to revoke as compressed hex strings\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to the new references after revocation\n * @returns return.encryptedReference - The content reference, unchanged\n * @returns return.historyReference - The new history reference after revocation\n * @returns return.granteeListReference - The new grantee list reference\n * @returns return.actReference - The new ACT reference after revocation\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not the publisher\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const revokeKeys = ['03a1b2c3...'] // Public keys to revoke\n * const result = await client.actRevokeGrantees(historyReference, encryptedReference, revokeKeys)\n * console.log('New History Reference:', result.historyReference)\n * // encryptedReference is unchanged; historyReference/actReference are new\n * ```\n */\n async actRevokeGrantees(\n historyReference: string,\n encryptedReference: string,\n revokeGrantees: string[],\n requestOptions?: RequestOptions,\n ): Promise<{\n encryptedReference: string\n historyReference: string\n granteeListReference: string\n actReference: string\n }> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"actRevokeGranteesResponse\"\n requestId: string\n encryptedReference: string\n historyReference: string\n granteeListReference: string\n actReference: string\n }>({\n type: \"actRevokeGrantees\",\n requestId,\n historyReference,\n encryptedReference,\n revokeGrantees,\n requestOptions,\n })\n\n return {\n encryptedReference: response.encryptedReference,\n historyReference: response.historyReference,\n granteeListReference: response.granteeListReference,\n actReference: response.actReference,\n }\n }\n\n /**\n * Retrieves the list of grantees from an ACT.\n *\n * Only the publisher (original uploader) can view the grantee list,\n * as it is encrypted with the publisher's key.\n *\n * @param historyReference - The history reference\n * @param requestOptions - Optional request configuration (timeout, headers, endlesslyRetry). `timeout` replaces the client default for this call's whole round trip, not only the Bee request\n * @returns A promise resolving to an array of grantee public keys as compressed hex strings\n * @throws {Error} If the client is not initialized\n * @throws {Error} If the user is not the publisher\n * @throws {Error} If the request times out\n *\n * @example\n * ```typescript\n * const grantees = await client.actGetGrantees(historyReference)\n * console.log('Current grantees:', grantees.length)\n * grantees.forEach(pubKey => console.log(' -', pubKey))\n * ```\n */\n async actGetGrantees(\n historyReference: string,\n requestOptions?: RequestOptions,\n ): Promise<string[]> {\n this.ensureReady()\n const requestId = this.generateRequestId()\n\n const response = await this.sendRequest<{\n type: \"actGetGranteesResponse\"\n requestId: string\n grantees: string[]\n }>({\n type: \"actGetGrantees\",\n requestId,\n historyReference,\n requestOptions,\n })\n\n return response.grantees\n }\n\n // ============================================================================\n // Cleanup\n // ============================================================================\n\n /**\n * Destroys the client and releases all resources.\n *\n * This method should be called when the client is no longer needed.\n * It performs the following cleanup:\n * - Rejects every pending request, and a pending `initialize()`, with a\n * `SwarmIdError` of code `invalid-state`\n * - Removes the message event listener\n * - Removes the iframe from the DOM\n * - Resets the client to an uninitialized state\n *\n * After calling destroy(), the client instance cannot be reused.\n * Create a new instance if you need to reconnect.\n *\n * @example\n * ```typescript\n * // Clean up when component unmounts\n * useEffect(() => {\n * const client = new SwarmIdClient({ ... })\n * client.initialize()\n *\n * return () => {\n * client.destroy()\n * }\n * }, [])\n * ```\n */\n destroy(): void {\n const destroyed = () =>\n new SwarmIdError(\"invalid-state\", \"Client destroyed\")\n\n for (const remove of [...this.mountedButtons.values()]) remove()\n\n // Clear pending requests\n this.pendingRequests.forEach((pending) => {\n clearTimeout(pending.timeoutId)\n pending.reject(destroyed())\n })\n this.pendingRequests.clear()\n this.progressListeners.clear()\n\n // Remove message listener\n if (this.messageListener) {\n window.removeEventListener(\"message\", this.messageListener)\n this.messageListener = undefined\n }\n\n // Remove iframe\n if (this.iframe && this.iframe.parentNode) {\n this.iframe.parentNode.removeChild(this.iframe)\n this.iframe = undefined\n }\n\n // Reject every still-pending init wait. Whichever one `initialize()` is\n // awaiting rejects it, so a destroy mid-initialize settles it instead of\n // leaving it on an iframe that will never load or a proxy that is gone;\n // and the deadline-bound ones clear their `withTimeout` timers now\n // instead of lingering the full initializationTimeout. The\n // `.catch(() => {})` guards attached in initialize() keep these from\n // surfacing as unhandled when nothing is awaiting.\n this.iframeLoadReject?.(destroyed())\n this.proxyInitializedReject?.(destroyed())\n this.readyReject?.(destroyed())\n this.firstConnectionInfoReject?.(destroyed())\n this.iframeLoadReject = undefined\n this.readyResolve = undefined\n this.readyReject = undefined\n this.proxyInitializedResolve = undefined\n this.proxyInitializedReject = undefined\n this.firstConnectionInfoResolve = undefined\n this.firstConnectionInfoReject = undefined\n this.readyPromise = undefined\n this.proxyInitializedPromise = undefined\n this.firstConnectionInfoPromise = undefined\n\n this.ready = false\n }\n}\n","// Copyright 2026 The Swarm Authors. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\nimport { Reference, NULL_ADDRESS } from \"@ethersphere/bee-js\"\nimport { MantarayNode } from \"@ethersphere/core-sdk\"\nimport { makeContentAddressedChunk } from \"../chunk\"\nimport { hexToUint8Array } from \"../utils/hex\"\n\n/**\n * Mantaray v0.2 version hash (31 bytes).\n * From bee-js: the first 31 bytes of keccak256(\"mantaray:0.2\")\n */\nconst MANTARAY_VERSION_HASH = new Uint8Array([\n 0x57, 0x68, 0xb3, 0xb6, 0xa7, 0xdb, 0x56, 0xd2, 0x1d, 0x1a, 0xbf, 0xf4, 0x0d,\n 0x41, 0xce, 0xbf, 0xc8, 0x34, 0x48, 0xfe, 0xd8, 0xd7, 0xe9, 0xb0, 0x6e, 0xc0,\n 0xd3, 0xb0, 0x73, 0xf2, 0x8f,\n])\n\n/**\n * Fork flags for Mantaray format.\n */\nconst FORK_FLAG_VALUE_TYPE = 0x02 // TYPE_VALUE: has targetAddress (matches bee-js)\nconst FORK_FLAG_HAS_METADATA = 0x10 // TYPE_WITH_METADATA: has metadata bytes (matches bee-js)\n\n/**\n * Result of building a /bzz/-compatible manifest.\n *\n * This is a FLAT manifest with no child nodes - just the root manifest.\n * Bee's /bzz/ endpoint can directly resolve paths from this structure.\n *\n * IMPORTANT: The `data` field contains RAW manifest bytes (without span prefix).\n * When uploaded via `uploadData()`, span will be added and the resulting address\n * will match the pre-computed `address` field.\n */\nexport interface BzzCompatibleManifestResult {\n /** The manifest chunk to upload. Raw bytes, no span. */\n manifestChunk: {\n data: Uint8Array\n address: string\n }\n}\n\n/**\n * Build a /bzz/-compatible flat manifest with VALUE forks.\n *\n * Creates a flat manifest with two VALUE forks at root level:\n * - \"/\" → VALUE fork with website-index-document metadata pointing to NULL\n * - \"index.bin\" → VALUE fork pointing directly to content reference\n *\n * This is built manually because bee-js MantarayNode always creates EDGE forks\n * with child nodes, which causes Bee to fail to resolve the content.\n *\n * When Bee accesses /bzz/manifest/:\n * 1. Finds \"/\" fork, reads website-index-document metadata\n * 2. Looks up \"index.bin\" fork at root level\n * 3. \"index.bin\" is VALUE type → serves content directly\n *\n * Binary format (Mantaray v0.2):\n * - obfuscationKey (32 bytes): All zeros for no obfuscation\n * - versionHash (31 bytes): MANTARAY_VERSION_HASH\n * - refBytesCount (1 byte): 32\n * - entry (32 bytes): All zeros (root has no entry)\n * - indexBitmap (32 bytes): Bits set for '/' (47) and 'i' (105)\n * - fork1 (64+ bytes): \"/\" fork with metadata\n * - fork2 (64+ bytes): \"index.bin\" fork with metadata\n *\n * @param contentReference - Reference to the actual content (32 bytes / 64 hex chars)\n * @returns Single manifest chunk to upload\n */\nexport async function buildBzzCompatibleManifest(\n contentReference: string | Uint8Array,\n): Promise<BzzCompatibleManifestResult> {\n const refBytes =\n contentReference instanceof Uint8Array\n ? contentReference\n : new Reference(contentReference).toUint8Array()\n\n if (refBytes.length !== 32) {\n throw new Error(\n `Invalid content reference length: ${refBytes.length} (expected 32 bytes)`,\n )\n }\n\n // Prepare metadata JSON for both forks\n const slashMetadata =\n JSON.stringify({ \"website-index-document\": \"index.bin\" }) + \"\\n\"\n const indexMetadata =\n JSON.stringify({\n \"Content-Type\": \"application/octet-stream\",\n Filename: \"index.bin\",\n }) + \"\\n\"\n\n const slashMetadataBytes = new TextEncoder().encode(slashMetadata)\n const indexMetadataBytes = new TextEncoder().encode(indexMetadata)\n\n // Calculate sizes\n // Header: 32 + 31 + 1 + 32 + 32 = 128 bytes\n // Fork \"/\" : flags(1) + prefixLen(1) + prefix(30) + reference(32) + metaLen(2) + meta\n // Fork \"index.bin\": flags(1) + prefixLen(1) + prefix(30) + reference(32) + metaLen(2) + meta\n const HEADER_SIZE = 128\n const FORK_BASE_SIZE = 66 // 1 + 1 + 30 + 32 + 2\n const TOTAL_SIZE =\n HEADER_SIZE +\n FORK_BASE_SIZE +\n slashMetadataBytes.length +\n FORK_BASE_SIZE +\n indexMetadataBytes.length\n\n const manifest = new Uint8Array(TOTAL_SIZE)\n let offset = 0\n\n // 1. Obfuscation key (32 bytes) - all zeros for no obfuscation\n offset += 32\n\n // 2. Version hash (31 bytes)\n manifest.set(MANTARAY_VERSION_HASH, offset)\n offset += 31\n\n // 3. refBytesCount (1 byte) - 32 for standard reference size\n manifest[offset] = 32\n offset += 1\n\n // 4. Entry (32 bytes) - all zeros for root node\n offset += 32\n\n // 5. Index bitmap (32 bytes)\n // Bit 47 set for '/' and bit 105 set for 'i' (start of \"index.bin\")\n // Byte 47/8 = 5, bit 47%8 = 7 → byte 5 = 0x80\n // Byte 105/8 = 13, bit 105%8 = 1 → byte 13 = 0x02\n manifest[offset + 5] = 0x80 // '/' at position 47\n manifest[offset + 13] = 0x02 // 'i' at position 105\n offset += 32\n\n // Forks are ordered by their first byte value\n // '/' = 47 comes before 'i' = 105\n\n // 6. Fork entry for '/' (first because 47 < 105)\n // Flags: TYPE_WITH_METADATA only (0x10) - NO VALUE since reference is NULL\n // The \"/\" fork is just a metadata carrier for website-index-document\n manifest[offset] = FORK_FLAG_HAS_METADATA\n offset += 1\n\n // Prefix length\n manifest[offset] = 1\n offset += 1\n\n // Prefix (30 bytes padded)\n manifest[offset] = 0x2f // '/'\n offset += 30\n\n // Reference (32 bytes) - NULL_ADDRESS (all zeros) because \"/\" just has metadata\n // Already zeros, just advance\n offset += 32\n\n // Metadata length (2 bytes big-endian)\n manifest[offset] = (slashMetadataBytes.length >> 8) & 0xff\n manifest[offset + 1] = slashMetadataBytes.length & 0xff\n offset += 2\n\n // Metadata content\n manifest.set(slashMetadataBytes, offset)\n offset += slashMetadataBytes.length\n\n // 7. Fork entry for 'index.bin'\n // Flags: TYPE_VALUE (0x02) + TYPE_WITH_METADATA (0x10) = 0x12\n manifest[offset] = FORK_FLAG_VALUE_TYPE | FORK_FLAG_HAS_METADATA\n offset += 1\n\n // Prefix length - \"index.bin\" = 9 characters\n manifest[offset] = 9\n offset += 1\n\n // Prefix (30 bytes padded)\n const indexBinBytes = new TextEncoder().encode(\"index.bin\")\n manifest.set(indexBinBytes, offset)\n offset += 30\n\n // Reference (32 bytes) - the actual content reference\n manifest.set(refBytes, offset)\n offset += 32\n\n // Metadata length (2 bytes big-endian)\n manifest[offset] = (indexMetadataBytes.length >> 8) & 0xff\n manifest[offset + 1] = indexMetadataBytes.length & 0xff\n offset += 2\n\n // Metadata content\n manifest.set(indexMetadataBytes, offset)\n offset += indexMetadataBytes.length\n\n // Calculate manifest address\n const rootChunk = makeContentAddressedChunk(manifest)\n\n return {\n manifestChunk: {\n data: manifest,\n address: rootChunk.address.toHex(),\n },\n }\n}\n\n/**\n * Result of building a /bzz/-compatible MantarayNode manifest.\n */\nexport interface BzzManifestNodeResult {\n /** The MantarayNode to be uploaded with saveMantarayTreeRecursively */\n manifestNode: MantarayNode\n}\n\n/**\n * Build a /bzz/-compatible manifest as a MantarayNode.\n *\n * This function creates a MantarayNode with the proper structure for /bzz/ access:\n * - \"/\" fork with website-index-document metadata pointing to \"index.bin\"\n * - \"index.bin\" fork pointing to the actual content reference\n *\n * IMPORTANT: After calling this function, use saveMantarayTreeRecursively() to\n * upload the manifest. This ensures all child nodes are uploaded bottom-up and\n * their addresses are correctly set from Bee's responses.\n *\n * Usage:\n * ```typescript\n * const { manifestNode } = buildBzzManifestNode(contentReference)\n * const result = await saveMantarayTreeRecursively(manifestNode, async (data, isRoot) => {\n * const uploadResult = await uploadData(bee, stamper, data, uploadOptions)\n * return { reference: uploadResult.reference }\n * })\n * // result.rootReference is the /bzz/ compatible manifest address\n * ```\n *\n * @param contentReference - Reference to the actual content (32 bytes / 64 hex chars)\n * @returns MantarayNode ready for upload with saveMantarayTreeRecursively\n */\nexport function buildBzzManifestNode(\n contentReference: string | Uint8Array,\n): BzzManifestNodeResult {\n const refBytes =\n contentReference instanceof Uint8Array\n ? contentReference\n : hexToUint8Array(contentReference)\n\n if (refBytes.length !== 32) {\n throw new Error(\n `Invalid content reference length: ${refBytes.length} (expected 32 bytes)`,\n )\n }\n\n const manifest = new MantarayNode()\n\n // Add \"/\" fork with website-index-document metadata\n // This tells Bee to look for \"index.bin\" when accessing the root path\n manifest.addFork(\"/\", NULL_ADDRESS, {\n \"website-index-document\": \"index.bin\",\n })\n\n // Add \"index.bin\" fork pointing to the actual content\n manifest.addFork(\"index.bin\", refBytes, {\n \"Content-Type\": \"application/octet-stream\",\n Filename: \"index.bin\",\n })\n\n return { manifestNode: manifest }\n}\n\n/**\n * @deprecated Use buildBzzManifestNode() with saveMantarayTreeRecursively() instead.\n * This function manually builds binary format but doesn't upload child nodes,\n * which causes Bee to fail to resolve content via /bzz/.\n */\n\n/**\n * @deprecated Use buildBzzCompatibleManifest() for /bzz/ compatibility.\n * This function creates a manifest that won't work with Bee's /bzz/ endpoint\n * because it embeds the content reference directly in the manifest instead\n * of using the proper two-level structure (root → child → content).\n *\n * Build a minimal mantaray manifest for /bzz/ feed compatibility.\n *\n * This creates a manifest with a single \"/\" fork pointing to a content reference.\n * The manifest is built manually (not using bee-js MantarayNode.marshal()) because\n * bee-js doesn't embed the targetAddress correctly for value-type nodes.\n *\n * Binary format (Mantaray v0.2):\n * - obfuscationKey (32 bytes): All zeros for no obfuscation\n * - versionHash (31 bytes): MANTARAY_VERSION_HASH\n * - refBytesCount (1 byte): 32 (size of entry reference)\n * - entry (32 bytes): All zeros (root has no entry)\n * - indexBitmap (32 bytes): Bitmap with bit 47 set (for '/')\n * - fork (64+ bytes): flags + prefixLen + prefix(30) + reference(32) + metadata\n *\n * @param contentReference - Reference to the actual content (32 bytes / 64 hex chars)\n * @returns Marshaled manifest bytes\n */\nexport function buildMinimalManifest(\n contentReference: string | Uint8Array,\n): Uint8Array {\n // Normalize reference to Uint8Array\n const refBytes =\n contentReference instanceof Uint8Array\n ? contentReference\n : new Reference(contentReference).toUint8Array()\n\n if (refBytes.length !== 32) {\n throw new Error(\n `Invalid content reference length: ${refBytes.length} (expected 32 bytes)`,\n )\n }\n\n // Calculate total size\n // Header: 32 + 31 + 1 + 32 + 32 = 128 bytes\n // Fork: 1 + 1 + 30 + 32 = 64 bytes (no metadata for simplicity)\n // Total: 192 bytes\n const HEADER_SIZE = 128\n const FORK_SIZE = 64\n const TOTAL_SIZE = HEADER_SIZE + FORK_SIZE\n\n const manifest = new Uint8Array(TOTAL_SIZE)\n let offset = 0\n\n // 1. Obfuscation key (32 bytes) - all zeros for no obfuscation\n offset += 32\n\n // 2. Version hash (31 bytes)\n manifest.set(MANTARAY_VERSION_HASH, offset)\n offset += 31\n\n // 3. refBytesCount (1 byte) - 32 for standard reference size\n manifest[offset] = 32\n offset += 1\n\n // 4. Entry (32 bytes) - all zeros for root node\n offset += 32\n\n // 5. Index bitmap (32 bytes) - bit 47 set for '/'\n // Byte index = 47 / 8 = 5, bit position = 47 % 8 = 7 (MSB)\n // So we set byte 5 to 0x80 (bit 7 set)\n manifest[offset + 5] = 0x80\n offset += 32\n\n // 6. Fork entry for '/'\n // Flags: VALUE_TYPE (reference is the target)\n manifest[offset] = FORK_FLAG_VALUE_TYPE\n offset += 1\n\n // Prefix length\n manifest[offset] = 1\n offset += 1\n\n // Prefix (30 bytes padded)\n manifest[offset] = 0x2f // '/'\n offset += 30\n\n // Reference (32 bytes) - the actual content reference\n manifest.set(refBytes, offset)\n offset += 32\n\n return manifest\n}\n\n/**\n * Extract content reference from a minimal mantaray manifest.\n *\n * This is the reverse of buildMinimalManifest() - it parses the manifest\n * binary format and extracts the \"/\" fork's targetAddress.\n *\n * Binary format (Mantaray v0.2):\n * - Offset 0-31: obfuscationKey\n * - Offset 32-62: versionHash (31 bytes)\n * - Offset 63: refBytesCount\n * - Offset 64-95: entry (refBytesCount bytes, assuming 32)\n * - Offset 96-127: indexBitmap\n * - Offset 128+: forks (flags + prefixLen + prefix + reference + metadata)\n *\n * For a minimal manifest with just \"/\" fork:\n * - Fork flags at offset 128\n * - Prefix length at offset 129\n * - Prefix (30 bytes) at offset 130\n * - Reference (32 bytes) at offset 160\n *\n * @param manifestData - Raw manifest bytes (from feed payload)\n * @returns Content reference as 64 hex characters\n */\nexport function extractReferenceFromManifest(manifestData: Uint8Array): string {\n // Minimum size check: header (128) + minimal fork (64)\n if (manifestData.length < 192) {\n throw new Error(\n `Manifest too small: ${manifestData.length} bytes (expected at least 192)`,\n )\n }\n\n // Header offsets (for reference)\n // Offset 0-31: obfuscationKey\n // Offset 32-62: versionHash (31 bytes)\n // Offset 63: refBytesCount\n // Offset 64-95: entry (refBytesCount bytes, assuming 32)\n // Offset 96-127: indexBitmap\n // Offset 128+: forks\n const REF_BYTES_COUNT_OFFSET = 63\n const INDEX_BITMAP_OFFSET = 96\n const FORKS_OFFSET = 128\n\n // Read refBytesCount to determine entry size\n const refBytesCount = manifestData[REF_BYTES_COUNT_OFFSET]\n if (refBytesCount !== 32) {\n console.warn(\n `[ManifestBuilder] Unexpected refBytesCount: ${refBytesCount} (expected 32)`,\n )\n }\n\n // Verify \"/\" fork exists in index bitmap\n // Byte 5, bit 7 should be set for '/' (byte value 47)\n // Bit ordering: value N is at byte N/8, bit N%8\n // So value 47 is at byte 5, bit 7 (mask 0x80)\n const indexBitmap = manifestData.slice(\n INDEX_BITMAP_OFFSET,\n INDEX_BITMAP_OFFSET + 32,\n )\n const slashByteIndex = Math.floor(47 / 8) // = 5\n const slashBitMask = 1 << (47 % 8) // = 0x80\n\n if ((indexBitmap[slashByteIndex] & slashBitMask) === 0) {\n throw new Error('Manifest does not contain \"/\" fork')\n }\n\n // Count forks before \"/\" to find its offset\n // We need to count all set bits for byte values less than 47\n let forkIndex = 0\n // Count all bits in bytes 0-4\n for (let byte = 0; byte < slashByteIndex; byte++) {\n forkIndex += popcount8(indexBitmap[byte])\n }\n // Count bits in byte 5 for values 40-46 (bits 0-6)\n for (let bit = 0; bit < 47 % 8; bit++) {\n if (indexBitmap[slashByteIndex] & (1 << bit)) {\n forkIndex++\n }\n }\n\n // Calculate fork offset\n // Each fork is: flags(1) + prefixLen(1) + prefix(30) + reference(32) + metadata(variable)\n // For simplicity, assume all forks before \"/\" have the same minimal structure\n // In a minimal manifest, \"/\" should be the first (and only) fork\n\n let forkOffset = FORKS_OFFSET\n\n // Skip previous forks if any\n for (let i = 0; i < forkIndex; i++) {\n // Read flags to check if metadata exists\n const flags = manifestData[forkOffset]\n const hasMetadata = (flags & FORK_FLAG_HAS_METADATA) !== 0\n\n forkOffset += 1 + 1 + 30 + 32 // flags + prefixLen + prefix + reference\n\n if (hasMetadata) {\n // Read metadata length (2 bytes big-endian)\n const metadataLen =\n (manifestData[forkOffset] << 8) | manifestData[forkOffset + 1]\n forkOffset += 2 + metadataLen\n }\n }\n\n // Now at the \"/\" fork\n const prefixLen = manifestData[forkOffset + 1]\n\n // Verify it's actually \"/\"\n if (prefixLen !== 1 || manifestData[forkOffset + 2] !== 0x2f) {\n throw new Error(\n `Expected \"/\" prefix, got length ${prefixLen} and byte 0x${manifestData[forkOffset + 2].toString(16)}`,\n )\n }\n\n // Reference is at offset: forkOffset + 1 (flags) + 1 (prefixLen) + 30 (prefix) = forkOffset + 32\n const referenceOffset = forkOffset + 32\n const reference = manifestData.slice(referenceOffset, referenceOffset + 32)\n\n if (isAllZeros(reference)) {\n throw new Error('Manifest \"/\" fork has zero reference')\n }\n\n const hexRef = new Reference(reference).toHex()\n\n return hexRef\n}\n\n/**\n * Count number of set bits in a byte (population count).\n */\nfunction popcount8(n: number): number {\n let count = 0\n while (n) {\n count += n & 1\n n >>>= 1\n }\n return count\n}\n\n/**\n * Check if a Uint8Array is all zeros.\n */\nfunction isAllZeros(arr: Uint8Array): boolean {\n for (let i = 0; i < arr.length; i++) {\n if (arr[i] !== 0) return false\n }\n return true\n}\n\n/**\n * Extract entry (targetAddress) from a leaf manifest node.\n *\n * In Mantaray v0.2, leaf nodes store their targetAddress in the entry field\n * (bytes 64-95), not in a fork. This is used for the second level of parsing\n * when using buildBzzCompatibleManifest().\n *\n * Binary format (Mantaray v0.2):\n * - Offset 0-31: obfuscationKey\n * - Offset 32-62: versionHash (31 bytes)\n * - Offset 63: refBytesCount\n * - Offset 64-95: entry (32 bytes) ← targetAddress for leaf nodes\n * - Offset 96-127: indexBitmap\n * - Offset 128+: forks\n *\n * @param manifestData - Raw manifest bytes (child chunk data from two-level structure)\n * @returns Content reference as 64 hex characters\n */\nexport function extractEntryFromManifest(manifestData: Uint8Array): string {\n if (manifestData.length < 96) {\n throw new Error(\n `Manifest too small: ${manifestData.length} bytes (expected at least 96)`,\n )\n }\n\n const ENTRY_OFFSET = 64\n const entry = manifestData.slice(ENTRY_OFFSET, ENTRY_OFFSET + 32)\n\n if (isAllZeros(entry)) {\n throw new Error(\"Manifest entry is zero\")\n }\n\n const hexRef = new Reference(entry).toHex()\n\n return hexRef\n}\n\n/**\n * Extract content reference from a flat /bzz/-compatible manifest.\n *\n * In the flat structure, the manifest has:\n * - \"/\" fork with NULL_ADDRESS and website-index-document metadata\n * - \"index.bin\" fork with VALUE type pointing to content reference\n *\n * This function looks for the \"index.bin\" fork ('i' = ASCII 105) and\n * extracts its reference.\n *\n * @param manifestData - Raw manifest bytes (flat manifest)\n * @returns Content reference as 64 hex characters\n */\nexport function extractContentFromFlatManifest(\n manifestData: Uint8Array,\n): string {\n if (manifestData.length < 192) {\n throw new Error(\n `Manifest too small: ${manifestData.length} bytes (expected at least 192)`,\n )\n }\n\n const INDEX_BITMAP_OFFSET = 96\n const FORKS_OFFSET = 128\n\n // Look for 'i' (105) in the index bitmap\n // Byte index = 105 / 8 = 13, bit position = 105 % 8 = 1\n const indexBitmap = manifestData.slice(\n INDEX_BITMAP_OFFSET,\n INDEX_BITMAP_OFFSET + 32,\n )\n const iByteIndex = Math.floor(105 / 8) // = 13\n const iBitMask = 1 << (105 % 8) // = 0x02\n\n if ((indexBitmap[iByteIndex] & iBitMask) === 0) {\n throw new Error('Manifest does not contain \"index.bin\" fork')\n }\n\n // Count forks before 'i' to find its offset\n let forkIndex = 0\n for (let byte = 0; byte < iByteIndex; byte++) {\n forkIndex += popcount8(indexBitmap[byte])\n }\n // Count bits in byte 13 for values less than 105\n for (let bit = 0; bit < 105 % 8; bit++) {\n if (indexBitmap[iByteIndex] & (1 << bit)) {\n forkIndex++\n }\n }\n\n // Navigate to the correct fork by skipping previous forks\n let forkOffset = FORKS_OFFSET\n for (let i = 0; i < forkIndex; i++) {\n const flags = manifestData[forkOffset]\n const hasMetadata = (flags & FORK_FLAG_HAS_METADATA) !== 0\n forkOffset += 1 + 1 + 30 + 32 // flags + prefixLen + prefix + reference\n\n if (hasMetadata) {\n const metadataLen =\n (manifestData[forkOffset] << 8) | manifestData[forkOffset + 1]\n forkOffset += 2 + metadataLen\n }\n }\n\n // Now at the \"index.bin\" fork\n const forkFlags = manifestData[forkOffset]\n const prefixLen = manifestData[forkOffset + 1]\n\n // Verify it starts with 'i' (index.bin)\n if (manifestData[forkOffset + 2] !== 0x69) {\n // 'i'\n throw new Error(\n `Expected \"index.bin\" prefix, got byte 0x${manifestData[forkOffset + 2].toString(16)}`,\n )\n }\n\n // Optionally verify full prefix \"index.bin\" (9 bytes)\n if (prefixLen >= 9) {\n const prefixBytes = manifestData.slice(forkOffset + 2, forkOffset + 2 + 9)\n const expectedPrefix = new TextEncoder().encode(\"index.bin\")\n const prefixMatches = prefixBytes.every((b, i) => b === expectedPrefix[i])\n if (!prefixMatches) {\n console.warn('[ManifestBuilder] Prefix does not fully match \"index.bin\"')\n }\n }\n\n // Check if this is a value type (reference is the target)\n const isValueType = (forkFlags & FORK_FLAG_VALUE_TYPE) !== 0\n if (!isValueType) {\n throw new Error('\"index.bin\" fork is not a VALUE type')\n }\n\n // Reference is at offset: forkOffset + 1 (flags) + 1 (prefixLen) + 30 (prefix) = forkOffset + 32\n const referenceOffset = forkOffset + 32\n const reference = manifestData.slice(referenceOffset, referenceOffset + 32)\n\n if (isAllZeros(reference)) {\n throw new Error('Manifest \"index.bin\" fork has zero reference')\n }\n\n const hexRef = new Reference(reference).toHex()\n\n return hexRef\n}\n","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/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 { 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} and {@link structs}. This prevents parameters from being accessible to types that don't allow them (e.g. `string indexed foo` not allowed outside of `type: 'event'`) and ensures different struct definitions with the same name are cached separately.\n * @param param ABI parameter string\n * @param type ABI parameter type\n * @param structs Struct definitions to include in cache key\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}${structKey}`;\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$_]*(?:\\spayable)?)(?<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 if (match.type === 'address payable') {\n type = 'address';\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 { isStructSignature } from './runtime/signatures.js';\nimport { parseStructs } from './runtime/structs.js';\nimport { parseSignature } from './runtime/utils.js';\n/**\n * Parses human-readable ABI into JSON {@link Abi}\n *\n * @param signatures - Human-Readable ABI\n * @returns Parsed {@link Abi}\n *\n * @example\n * const abi = parseAbi([\n * // ^? const abi: readonly [{ name: \"balanceOf\"; type: \"function\"; stateMutability:...\n * 'function balanceOf(address owner) view returns (uint256)',\n * 'event Transfer(address indexed from, address indexed to, uint256 amount)',\n * ])\n */\nexport function parseAbi(signatures) {\n const structs = parseStructs(signatures);\n const abi = [];\n const length = signatures.length;\n for (let i = 0; i < length; i++) {\n const signature = signatures[i];\n if (isStructSignature(signature))\n continue;\n abi.push(parseSignature(signature, structs));\n }\n return abi;\n}\n//# sourceMappingURL=parseAbi.js.map","/**\n * Retrieves and returns an action from the client (if exists), and falls\n * back to the tree-shakable action.\n *\n * Useful for extracting overridden actions from a client (ie. if a consumer\n * wants to override the `sendTransaction` implementation).\n */\nexport function getAction(client, actionFn, \n// Some minifiers drop `Function.prototype.name`, or replace it with short letters,\n// meaning that `actionFn.name` will not always work. For that case, the consumer\n// needs to pass the name explicitly.\nname) {\n const action_implicit = client[actionFn.name];\n if (typeof action_implicit === 'function')\n return action_implicit;\n const action_explicit = client[name];\n if (typeof action_explicit === 'function')\n return action_explicit;\n return (params) => actionFn(client, params);\n}\n//# sourceMappingURL=getAction.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.55.13';\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({ cause } = {}) {\n super('Cannot decode zero data (\"0x\") with ABI parameters.', {\n name: 'AbiDecodingZeroDataError',\n cause,\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, cause, }) {\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 cause,\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 RlpDepthLimitExceededError extends BaseError {\n constructor({ limit }) {\n super(`RLP depth limit of \\`${limit}\\` exceeded.`, {\n name: 'RlpDepthLimitExceededError',\n });\n }\n}\nexport class RlpListBoundaryExceededError extends BaseError {\n constructor({ consumed, declared }) {\n super(`RLP list items consumed \\`${consumed}\\` bytes but the list declared a length of \\`${declared}\\`.`, { name: 'RlpListBoundaryExceededError' });\n }\n}\nexport class RlpTrailingBytesError extends BaseError {\n constructor({ count }) {\n super(`RLP payload encodes a single item, but \\`${count}\\` trailing ${count === 1 ? 'byte remains' : 'bytes remain'}.`, { name: 'RlpTrailingBytesError' });\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 = hexToNumber('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","/**\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 { 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 { 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 { 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 { 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","import { toSignatureHash, } from './toSignatureHash.js';\n/**\n * Returns the event selector for a given event definition.\n *\n * @example\n * const selector = toEventSelector('Transfer(address indexed from, address indexed to, uint256 amount)')\n * // 0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef\n */\nexport const toEventSelector = toSignatureHash;\n//# sourceMappingURL=toEventSelector.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)) {\n super.delete(key);\n super.set(key, value);\n }\n return value;\n }\n set(key, value) {\n if (super.has(key))\n super.delete(key);\n super.set(key, value);\n if (this.maxSize && this.size > this.maxSize) {\n const firstKey = super.keys().next().value;\n if (firstKey !== undefined)\n super.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 { concatHex } 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 return encodeParams(preparedParams);\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 // `concatHex` returns `'0x'` for empty input (zero-width parameters).\n return concatHex([...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 // Zero-length fixed arrays of dynamic types (e.g. `string[0]`) are dynamic\n // per the ABI spec, even though they have no elements to inspect.\n let dynamicChild = value.length === 0 && isDynamicType(param);\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: concatHex([length, data]),\n };\n }\n if (dynamicChild)\n return { dynamic: true, encoded: data };\n }\n return {\n dynamic: false,\n encoded: concatHex(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: concatHex([\n padHex(numberToHex(bytesSize, { size: 32 })),\n value_,\n ]),\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: concatHex([\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 : concatHex(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}\nfunction isDynamicType(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(isDynamicType);\n const arrayComponents = getArrayComponents(type);\n if (arrayComponents)\n return isDynamicType({ ...param, type: arrayComponents[1] });\n return false;\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 { AbiItemAmbiguityError, } from '../../errors/abi.js';\nimport { isHex } from '../../utils/data/isHex.js';\nimport { isAddress } from '../address/isAddress.js';\nimport { toEventSelector } from '../hash/toEventSelector.js';\nimport { toFunctionSelector, } from '../hash/toFunctionSelector.js';\nexport function getAbiItem(parameters) {\n const { abi, args = [], name } = parameters;\n const isSelector = isHex(name, { strict: false });\n const abiItems = abi.filter((abiItem) => {\n if (isSelector) {\n if (abiItem.type === 'function')\n return toFunctionSelector(abiItem) === name;\n if (abiItem.type === 'event')\n return toEventSelector(abiItem) === name;\n return false;\n }\n return 'name' in abiItem && abiItem.name === name;\n });\n if (abiItems.length === 0)\n return undefined;\n if (abiItems.length === 1)\n return abiItems[0];\n let matchedAbiItem;\n for (const abiItem of abiItems) {\n if (!('inputs' in abiItem))\n continue;\n if (!args || args.length === 0) {\n if (!abiItem.inputs || abiItem.inputs.length === 0)\n return abiItem;\n continue;\n }\n if (!abiItem.inputs)\n continue;\n if (abiItem.inputs.length === 0)\n continue;\n if (abiItem.inputs.length !== args.length)\n continue;\n const matched = args.every((arg, index) => {\n const abiParameter = 'inputs' in abiItem && abiItem.inputs[index];\n if (!abiParameter)\n return false;\n return isArgOfType(arg, abiParameter);\n });\n if (matched) {\n // Check for ambiguity against already matched parameters (e.g. `address` vs `bytes20`).\n if (matchedAbiItem &&\n 'inputs' in matchedAbiItem &&\n matchedAbiItem.inputs) {\n const ambiguousTypes = getAmbiguousTypes(abiItem.inputs, matchedAbiItem.inputs, args);\n if (ambiguousTypes)\n throw new AbiItemAmbiguityError({\n abiItem,\n type: ambiguousTypes[0],\n }, {\n abiItem: matchedAbiItem,\n type: ambiguousTypes[1],\n });\n }\n matchedAbiItem = abiItem;\n }\n }\n if (matchedAbiItem)\n return matchedAbiItem;\n return abiItems[0];\n}\n/** @internal */\nexport function isArgOfType(arg, abiParameter) {\n const argType = typeof arg;\n const abiParameterType = abiParameter.type;\n switch (abiParameterType) {\n case 'address':\n return isAddress(arg, { strict: false });\n case 'bool':\n return argType === 'boolean';\n case 'function':\n return argType === 'string';\n case 'string':\n return argType === 'string';\n default: {\n if (abiParameterType === 'tuple' && 'components' in abiParameter)\n return Object.values(abiParameter.components).every((component, index) => {\n return (argType === 'object' &&\n isArgOfType(Object.values(arg)[index], component));\n });\n // `(u)int<M>`: (un)signed integer type of `M` bits, `0 < M <= 256`, `M % 8 == 0`\n // https://regexr.com/6v8hp\n if (/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/.test(abiParameterType))\n return argType === 'number' || argType === 'bigint';\n // `bytes<M>`: binary type of `M` bytes, `0 < M <= 32`\n // https://regexr.com/6va55\n if (/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/.test(abiParameterType))\n return argType === 'string' || arg instanceof Uint8Array;\n // fixed-length (`<type>[M]`) and dynamic (`<type>[]`) arrays\n // https://regexr.com/6va6i\n if (/[a-z]+[1-9]{0,3}(\\[[0-9]{0,}\\])+$/.test(abiParameterType)) {\n return (Array.isArray(arg) &&\n arg.every((x) => isArgOfType(x, {\n ...abiParameter,\n // Pop off `[]` or `[M]` from end of type\n type: abiParameterType.replace(/(\\[[0-9]{0,}\\])$/, ''),\n })));\n }\n return false;\n }\n }\n}\n/** @internal */\nexport function getAmbiguousTypes(sourceParameters, targetParameters, args) {\n for (const parameterIndex in sourceParameters) {\n const sourceParameter = sourceParameters[parameterIndex];\n const targetParameter = targetParameters[parameterIndex];\n if (sourceParameter.type === 'tuple' &&\n targetParameter.type === 'tuple' &&\n 'components' in sourceParameter &&\n 'components' in targetParameter)\n return getAmbiguousTypes(sourceParameter.components, targetParameter.components, args[parameterIndex]);\n const types = [sourceParameter.type, targetParameter.type];\n const ambiguous = (() => {\n if (types.includes('address') && types.includes('bytes20'))\n return true;\n if (types.includes('address') && types.includes('string'))\n return isAddress(args[parameterIndex], { strict: false });\n if (types.includes('address') && types.includes('bytes'))\n return isAddress(args[parameterIndex], { strict: false });\n return false;\n })();\n if (ambiguous)\n return types;\n }\n return;\n}\n//# sourceMappingURL=getAbiItem.js.map","export function parseAccount(account) {\n if (typeof account === 'string')\n return { address: account, type: 'json-rpc' };\n return account;\n}\n//# sourceMappingURL=parseAccount.js.map","import { AbiFunctionNotFoundError, } from '../../errors/abi.js';\nimport { toFunctionSelector, } from '../hash/toFunctionSelector.js';\nimport { formatAbiItem } from './formatAbiItem.js';\nimport { getAbiItem } from './getAbiItem.js';\nconst docsPath = '/docs/contract/encodeFunctionData';\nexport function prepareEncodeFunctionData(parameters) {\n const { abi, args, functionName } = parameters;\n let abiItem = abi[0];\n if (functionName) {\n const item = getAbiItem({\n abi,\n args,\n name: functionName,\n });\n if (!item)\n throw new AbiFunctionNotFoundError(functionName, { docsPath });\n abiItem = item;\n }\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath });\n return {\n abi: [abiItem],\n functionName: toFunctionSelector(formatAbiItem(abiItem)),\n };\n}\n//# sourceMappingURL=prepareEncodeFunctionData.js.map","import { concatHex } from '../data/concat.js';\nimport { encodeAbiParameters, } from './encodeAbiParameters.js';\nimport { prepareEncodeFunctionData } from './prepareEncodeFunctionData.js';\nexport function encodeFunctionData(parameters) {\n const { args } = parameters;\n const { abi, functionName } = (() => {\n if (parameters.abi.length === 1 &&\n parameters.functionName?.startsWith('0x'))\n return parameters;\n return prepareEncodeFunctionData(parameters);\n })();\n const abiItem = abi[0];\n const signature = functionName;\n const data = 'inputs' in abiItem && abiItem.inputs\n ? encodeAbiParameters(abiItem.inputs, args ?? [])\n : undefined;\n return concatHex([signature, data ?? '0x']);\n}\n//# sourceMappingURL=encodeFunctionData.js.map","// https://docs.soliditylang.org/en/v0.8.16/control-structures.html#panic-via-assert-and-error-via-require\nexport const panicReasons = {\n 1: 'An `assert` condition failed.',\n 17: 'Arithmetic operation resulted in underflow or overflow.',\n 18: 'Division or modulo by zero (e.g. `5 / 0` or `23 % 0`).',\n 33: 'Attempted to convert to an invalid type.',\n 34: 'Attempted to access a storage byte array that is incorrectly encoded.',\n 49: 'Performed `.pop()` on an empty array',\n 50: 'Array index is out of bounds.',\n 65: 'Allocated too much memory or created an array which is too large.',\n 81: 'Attempted to call a zero-initialized variable of internal function type.',\n};\nexport const solidityError = {\n inputs: [\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'Error',\n type: 'error',\n};\nexport const solidityPanic = {\n inputs: [\n {\n name: 'reason',\n type: 'uint256',\n },\n ],\n name: 'Panic',\n type: 'error',\n};\n//# sourceMappingURL=solidity.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);\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);\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 { 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 // Zero-width types (e.g. `uint256[0]`, empty tuples) at the end of the\n // data consume no bytes, so the cursor may already be exhausted.\n if (consumed < bytes.length)\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 // Note: zero-length fixed arrays (`T[0]`) are not dynamic.\n if (length === null) {\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 // Charge zero-width elements against the read limit to bound work\n // on huge lengths of zero-width types (e.g. `uint256[0][]`).\n if (consumed_ === 0) {\n cursor.assertReadLimit();\n cursor._touch();\n }\n }\n // As we have gone wondering, restore to the original position + next slot.\n cursor.setPosition(staticPosition + 32);\n return [value, 32];\n }\n // 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 // Charge zero-width elements against the read limit to bound work\n // on huge lengths of zero-width types (e.g. `uint256[0][4294967295]`).\n if (consumed_ === 0) {\n cursor.assertReadLimit();\n cursor._touch();\n }\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(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 { solidityError, solidityPanic } from '../../constants/solidity.js';\nimport { AbiDecodingZeroDataError, AbiErrorSignatureNotFoundError, } from '../../errors/abi.js';\nimport { slice } from '../data/slice.js';\nimport { toFunctionSelector, } from '../hash/toFunctionSelector.js';\nimport { decodeAbiParameters, } from './decodeAbiParameters.js';\nimport { formatAbiItem } from './formatAbiItem.js';\nexport function decodeErrorResult(parameters) {\n const { abi, data, cause } = parameters;\n const signature = slice(data, 0, 4);\n if (signature === '0x')\n throw new AbiDecodingZeroDataError({ cause });\n const abi_ = [...(abi || []), solidityError, solidityPanic];\n const abiItem = abi_.find((x) => x.type === 'error' && signature === toFunctionSelector(formatAbiItem(x)));\n if (!abiItem)\n throw new AbiErrorSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeErrorResult',\n cause,\n });\n return {\n abiItem,\n args: 'inputs' in abiItem && abiItem.inputs && abiItem.inputs.length > 0\n ? decodeAbiParameters(abiItem.inputs, slice(data, 4))\n : undefined,\n errorName: abiItem.name,\n };\n}\n//# sourceMappingURL=decodeErrorResult.js.map","export const stringify = (value, replacer, space) => 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//# sourceMappingURL=stringify.js.map","import { stringify } from '../stringify.js';\nexport function formatAbiItemWithArgs({ abiItem, args, includeFunctionName = true, includeName = false, }) {\n if (!('name' in abiItem))\n return;\n if (!('inputs' in abiItem))\n return;\n if (!abiItem.inputs)\n return;\n return `${includeFunctionName ? abiItem.name : ''}(${abiItem.inputs\n .map((input, i) => `${includeName && input.name ? `${input.name}: ` : ''}${typeof args[i] === 'object' ? stringify(args[i]) : args[i]}`)\n .join(', ')})`;\n}\n//# sourceMappingURL=formatAbiItemWithArgs.js.map","// Adapted from the Ox v1 `Value` module.\n/** @see https://ethereum.github.io/yellowpaper/paper.pdf */\nconst exponents = {\n wei: 0,\n gwei: 9,\n szabo: 12,\n finney: 15,\n ether: 18,\n};\n/**\n * Formats a `bigint` Value to its string representation (divided by the given exponent).\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.format(420_000_000_000n, 9)\n * // @log: '420'\n * ```\n *\n * @param value - The `bigint` Value to format.\n * @param decimals - The exponent to divide the `bigint` Value by.\n * @returns The string representation of the Value.\n */\nexport function format(value, decimals = 0) {\n if (!Number.isInteger(decimals) || decimals < 0)\n throw new InvalidDecimalsError({ decimals });\n let display = value.toString();\n const negative = display.startsWith('-');\n if (negative)\n display = display.slice(1);\n display = display.padStart(decimals, '0');\n let [integer, fraction] = [\n display.slice(0, display.length - decimals),\n display.slice(display.length - decimals),\n ];\n fraction = fraction.replace(/(0+)$/, '');\n return `${negative ? '-' : ''}${integer || '0'}${fraction ? `.${fraction}` : ''}`;\n}\n/**\n * Formats a `bigint` Value (default: wei) to a string representation of Ether.\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.formatEther(1_000_000_000_000_000_000n)\n * // @log: '1'\n * ```\n *\n * @param wei - The Value to format.\n * @param unit - The unit to format the Value in. @default 'wei'.\n * @returns The Ether string representation of the Value.\n */\nexport function formatEther(wei, unit = 'wei') {\n return format(wei, exponents.ether - exponents[unit]);\n}\n/**\n * Formats a `bigint` Value (default: wei) to a string representation of Gwei.\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.formatGwei(1_000_000_000n)\n * // @log: '1'\n * ```\n *\n * @param wei - The Value to format.\n * @param unit - The unit to format the Value in. @default 'wei'.\n * @returns The Gwei string representation of the Value.\n */\nexport function formatGwei(wei, unit = 'wei') {\n return format(wei, exponents.gwei - exponents[unit]);\n}\n/**\n * Parses a `string` representation of a Value to `bigint` (multiplied by the given exponent).\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.from('420', 9)\n * // @log: 420000000000n\n * ```\n *\n * @param value - The string representation of the Value.\n * @param decimals - The exponent to multiply the Value by.\n * @returns The `bigint` representation of the Value.\n */\nexport function from(value, decimals = 0) {\n if (!Number.isInteger(decimals) || decimals < 0)\n throw new InvalidDecimalsError({ decimals });\n // Require at least one digit overall. Rejects '', '.', '-', '-.' which\n // the previous regex accepted (and which then either produced garbage or\n // threw a raw `SyntaxError` from `BigInt('')`).\n if (!/^-?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)$/.test(value))\n throw new InvalidDecimalNumberError({ value });\n let [integer = '', fraction = '0'] = value.split('.');\n const negative = integer.startsWith('-');\n if (negative)\n integer = integer.slice(1);\n if (integer === '')\n integer = '0';\n // trim trailing zeros.\n fraction = fraction.replace(/(0+)$/, '');\n // round off if the fraction is larger than the number of decimals.\n if (decimals === 0) {\n // Round half-away-from-zero by inspecting the first fractional digit.\n if (fraction.length > 0 && Number.parseInt(fraction[0], 10) >= 5)\n integer = `${BigInt(integer) + 1n}`;\n fraction = '';\n }\n else if (fraction.length > decimals) {\n const left = fraction.slice(0, decimals);\n const roundDigit = Number.parseInt(fraction.slice(decimals, decimals + 1), 10);\n if (roundDigit >= 5) {\n // Carry through the truncated fraction digits into the integer part\n // without converting to a JS Number (avoids float precision loss).\n const carried = carry(left);\n if (carried.length > decimals) {\n // Carry overflowed into the integer part.\n fraction = carried.slice(1);\n integer = `${BigInt(integer) + 1n}`;\n }\n else {\n fraction = carried;\n }\n }\n else {\n fraction = left;\n }\n }\n else {\n fraction = fraction.padEnd(decimals, '0');\n }\n return BigInt(`${negative ? '-' : ''}${integer}${fraction}`);\n}\n/**\n * Adds 1 to a digit string with carry, returning a string of the same length\n * unless the carry overflows past the most-significant digit (in which case\n * the returned string is one digit longer).\n *\n * @internal\n */\nfunction carry(digits) {\n const out = digits.split('');\n let i = out.length - 1;\n while (i >= 0) {\n const d = Number.parseInt(out[i], 10) + 1;\n if (d < 10) {\n out[i] = String(d);\n return out.join('');\n }\n out[i] = '0';\n i--;\n }\n return `1${out.join('')}`;\n}\n/**\n * Parses a string representation of Ether to a `bigint` Value (default: wei).\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.fromEther('420')\n * // @log: 420000000000000000000n\n * ```\n *\n * @param ether - String representation of Ether.\n * @param unit - The unit to parse to. @default 'wei'.\n * @returns A `bigint` Value.\n */\nexport function fromEther(ether, unit = 'wei') {\n return from(ether, exponents.ether - exponents[unit]);\n}\n/**\n * Parses a string representation of Gwei to a `bigint` Value (default: wei).\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.fromGwei('420')\n * // @log: 420000000000n\n * ```\n *\n * @param gwei - String representation of Gwei.\n * @param unit - The unit to parse to. @default 'wei'.\n * @returns A `bigint` Value.\n */\nexport function fromGwei(gwei, unit = 'wei') {\n return from(gwei, exponents.gwei - exponents[unit]);\n}\n/**\n * Thrown when a value is not a valid decimal number.\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.fromEther('123.456.789')\n * // @error: Value.InvalidDecimalNumberError: Value `123.456.789` is not a valid decimal number.\n * ```\n */\nclass InvalidDecimalNumberError extends Error {\n constructor({ value }) {\n super(`Value \\`${value}\\` is not a valid decimal number.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Value.InvalidDecimalNumberError'\n });\n }\n}\n/**\n * Thrown when the `decimals` argument is not a non-negative integer.\n *\n * @example\n * ```ts twoslash\n * import { Value } from 'ox'\n *\n * Value.from('1', -1)\n * // @error: Value.InvalidDecimalsError: `decimals` must be a non-negative integer. Got `-1`.\n * ```\n */\nclass InvalidDecimalsError extends Error {\n constructor({ decimals }) {\n super(`\\`decimals\\` must be a non-negative integer. Got \\`${decimals}\\`.`);\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'Value.InvalidDecimalsError'\n });\n }\n}\n//# sourceMappingURL=Value.js.map","import * as Value from './Value.js';\n/**\n * Converts numerical wei to a string representation of ether.\n *\n * - Docs: https://viem.sh/docs/utilities/formatEther\n *\n * @example\n * import { formatEther } from 'viem'\n *\n * formatEther(1000000000000000000n)\n * // '1'\n */\nexport function formatEther(wei, unit = 'wei') {\n return Value.formatEther(wei, unit);\n}\n//# sourceMappingURL=formatEther.js.map","import * as Value from './Value.js';\n/**\n * Converts numerical wei to a string representation of gwei.\n *\n * - Docs: https://viem.sh/docs/utilities/formatGwei\n *\n * @example\n * import { formatGwei } from 'viem'\n *\n * formatGwei(1000000000n)\n * // '1'\n */\nexport function formatGwei(wei, unit = 'wei') {\n return Value.formatGwei(wei, unit);\n}\n//# sourceMappingURL=formatGwei.js.map","import { BaseError } from './base.js';\nexport class AccountStateConflictError extends BaseError {\n constructor({ address }) {\n super(`State for account \"${address}\" is set multiple times.`, {\n name: 'AccountStateConflictError',\n });\n }\n}\nexport class StateAssignmentConflictError extends BaseError {\n constructor() {\n super('state and stateDiff are set on the same account.', {\n name: 'StateAssignmentConflictError',\n });\n }\n}\n/** @internal */\nexport function prettyStateMapping(stateMapping) {\n return stateMapping.reduce((pretty, { slot, value }) => {\n return `${pretty} ${slot}: ${value}\\n`;\n }, '');\n}\nexport function prettyStateOverride(stateOverride) {\n return stateOverride\n .reduce((pretty, { address, ...state }) => {\n let val = `${pretty} ${address}:\\n`;\n if (state.nonce)\n val += ` nonce: ${state.nonce}\\n`;\n if (state.balance)\n val += ` balance: ${state.balance}\\n`;\n if (state.code)\n val += ` code: ${state.code}\\n`;\n if (state.state) {\n val += ' state:\\n';\n val += prettyStateMapping(state.state);\n }\n if (state.stateDiff) {\n val += ' stateDiff:\\n';\n val += prettyStateMapping(state.stateDiff);\n }\n return val;\n }, ' State Override:\\n')\n .slice(0, -1);\n}\n//# sourceMappingURL=stateOverride.js.map","import { formatEther } from '../utils/unit/formatEther.js';\nimport { formatGwei } from '../utils/unit/formatGwei.js';\nimport { BaseError } from './base.js';\nexport function prettyPrint(args) {\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}\nexport class FeeConflictError extends BaseError {\n constructor() {\n super([\n 'Cannot specify both a `gasPrice` and a `maxFeePerGas`/`maxPriorityFeePerGas`.',\n 'Use `maxFeePerGas`/`maxPriorityFeePerGas` for EIP-1559 compatible networks, and `gasPrice` for others.',\n ].join('\\n'), { name: 'FeeConflictError' });\n }\n}\nexport class InvalidLegacyVError extends BaseError {\n constructor({ v }) {\n super(`Invalid \\`v\\` value \"${v}\". Expected 27 or 28.`, {\n name: 'InvalidLegacyVError',\n });\n }\n}\nexport class InvalidYParityError extends BaseError {\n constructor({ yParity }) {\n super(`Invalid \\`yParity\\` value \"${yParity}\". Expected 0 or 1.`, {\n name: 'InvalidYParityError',\n });\n }\n}\nexport class InvalidSerializableTransactionError extends BaseError {\n constructor({ transaction }) {\n super('Cannot infer a transaction type from provided transaction.', {\n metaMessages: [\n 'Provided Transaction:',\n '{',\n prettyPrint(transaction),\n '}',\n '',\n 'To infer the type, either provide:',\n '- a `type` to the Transaction, or',\n '- an EIP-1559 Transaction with `maxFeePerGas`, or',\n '- an EIP-2930 Transaction with `gasPrice` & `accessList`, or',\n '- an EIP-4844 Transaction with `blobs`, `blobVersionedHashes`, `sidecars`, or',\n '- an EIP-7702 Transaction with `authorizationList`, or',\n '- a Legacy Transaction with `gasPrice`',\n ],\n name: 'InvalidSerializableTransactionError',\n });\n }\n}\nexport class InvalidSerializedTransactionTypeError extends BaseError {\n constructor({ serializedType }) {\n super(`Serialized transaction type \"${serializedType}\" is invalid.`, {\n name: 'InvalidSerializedTransactionType',\n });\n Object.defineProperty(this, \"serializedType\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.serializedType = serializedType;\n }\n}\nexport class InvalidSerializedTransactionError extends BaseError {\n constructor({ attributes, serializedTransaction, type, }) {\n const missing = Object.entries(attributes)\n .map(([key, value]) => (typeof value === 'undefined' ? key : undefined))\n .filter(Boolean);\n super(`Invalid serialized transaction of type \"${type}\" was provided.`, {\n metaMessages: [\n `Serialized Transaction: \"${serializedTransaction}\"`,\n missing.length > 0 ? `Missing Attributes: ${missing.join(', ')}` : '',\n ].filter(Boolean),\n name: 'InvalidSerializedTransactionError',\n });\n Object.defineProperty(this, \"serializedTransaction\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"type\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.serializedTransaction = serializedTransaction;\n this.type = type;\n }\n}\nexport class InvalidStorageKeySizeError extends BaseError {\n constructor({ storageKey }) {\n super(`Size for storage key \"${storageKey}\" is invalid. Expected 32 bytes. Got ${Math.floor((storageKey.length - 2) / 2)} bytes.`, { name: 'InvalidStorageKeySizeError' });\n }\n}\nexport class TransactionExecutionError extends BaseError {\n constructor(cause, { account, docsPath, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, }) {\n const prettyArgs = prettyPrint({\n chain: chain && `${chain?.name} (id: ${chain?.id})`,\n from: account?.address,\n to,\n value: typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice: typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas: typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n });\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Request Arguments:',\n prettyArgs,\n ].filter(Boolean),\n name: 'TransactionExecutionError',\n });\n Object.defineProperty(this, \"cause\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.cause = cause;\n }\n}\nexport class TransactionNotFoundError extends BaseError {\n constructor({ blockHash, blockNumber, blockTag, hash, index, }) {\n let identifier = 'Transaction';\n if (blockTag && index !== undefined)\n identifier = `Transaction at block time \"${blockTag}\" at index \"${index}\"`;\n if (blockHash && index !== undefined)\n identifier = `Transaction at block hash \"${blockHash}\" at index \"${index}\"`;\n if (blockNumber && index !== undefined)\n identifier = `Transaction at block number \"${blockNumber}\" at index \"${index}\"`;\n if (hash)\n identifier = `Transaction with hash \"${hash}\"`;\n super(`${identifier} could not be found.`, {\n name: 'TransactionNotFoundError',\n });\n }\n}\nexport class TransactionReceiptNotFoundError extends BaseError {\n constructor({ hash }) {\n super(`Transaction receipt with hash \"${hash}\" could not be found. The Transaction may not be processed on a block yet.`, {\n name: 'TransactionReceiptNotFoundError',\n });\n }\n}\nexport class TransactionReceiptRevertedError extends BaseError {\n constructor({ receipt }) {\n super(`Transaction with hash \"${receipt.transactionHash}\" reverted.`, {\n metaMessages: [\n 'The receipt marked the transaction as \"reverted\". This could mean that the function on the contract you are trying to call threw an error.',\n ' ',\n 'You can attempt to extract the revert reason by:',\n '- calling the `simulateContract` or `simulateCalls` Action with the `abi` and `functionName` of the contract',\n '- using the `call` Action with raw `data`',\n ],\n name: 'TransactionReceiptRevertedError',\n });\n Object.defineProperty(this, \"receipt\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.receipt = receipt;\n }\n}\nexport class WaitForTransactionReceiptTimeoutError extends BaseError {\n constructor({ hash }) {\n super(`Timed out while waiting for transaction with hash \"${hash}\" to be confirmed.`, { name: 'WaitForTransactionReceiptTimeoutError' });\n }\n}\n//# sourceMappingURL=transaction.js.map","export const getContractAddress = (address) => address;\nexport function getAbortError(signal) {\n if (signal?.reason)\n return signal.reason;\n if (typeof DOMException === 'function')\n return new DOMException('This operation was aborted', 'AbortError');\n const error = new Error('This operation was aborted');\n error.name = 'AbortError';\n return error;\n}\nexport function isAbortError(error) {\n return (typeof error === 'object' &&\n error !== null &&\n 'name' in error &&\n error.name === 'AbortError');\n}\n/**\n * Returns the URL with any embedded basic-auth credentials stripped, so\n * error messages and logs don't leak secrets when an RPC URL like\n * `https://user:pass@host` is used.\n */\nexport const getUrl = (url) => {\n try {\n const parsed = new URL(url);\n if (!parsed.username && !parsed.password)\n return url;\n parsed.username = '';\n parsed.password = '';\n return parsed.toString();\n }\n catch {\n return url;\n }\n};\n//# sourceMappingURL=utils.js.map","import { parseAccount } from '../accounts/utils/parseAccount.js';\nimport { panicReasons } from '../constants/solidity.js';\nimport { decodeErrorResult, } from '../utils/abi/decodeErrorResult.js';\nimport { formatAbiItem } from '../utils/abi/formatAbiItem.js';\nimport { formatAbiItemWithArgs } from '../utils/abi/formatAbiItemWithArgs.js';\nimport { getAbiItem } from '../utils/abi/getAbiItem.js';\nimport { formatEther } from '../utils/unit/formatEther.js';\nimport { formatGwei } from '../utils/unit/formatGwei.js';\nimport { AbiErrorSignatureNotFoundError } from './abi.js';\nimport { BaseError } from './base.js';\nimport { prettyStateOverride } from './stateOverride.js';\nimport { prettyPrint } from './transaction.js';\nimport { getContractAddress } from './utils.js';\nexport class CallExecutionError extends BaseError {\n constructor(cause, { account: account_, docsPath, chain, data, gas, gasPrice, maxFeePerGas, maxPriorityFeePerGas, nonce, to, value, stateOverride, }) {\n const account = account_ ? parseAccount(account_) : undefined;\n let prettyArgs = prettyPrint({\n from: account?.address,\n to,\n value: typeof value !== 'undefined' &&\n `${formatEther(value)} ${chain?.nativeCurrency?.symbol || 'ETH'}`,\n data,\n gas,\n gasPrice: typeof gasPrice !== 'undefined' && `${formatGwei(gasPrice)} gwei`,\n maxFeePerGas: typeof maxFeePerGas !== 'undefined' &&\n `${formatGwei(maxFeePerGas)} gwei`,\n maxPriorityFeePerGas: typeof maxPriorityFeePerGas !== 'undefined' &&\n `${formatGwei(maxPriorityFeePerGas)} gwei`,\n nonce,\n });\n if (stateOverride) {\n prettyArgs += `\\n${prettyStateOverride(stateOverride)}`;\n }\n super(cause.shortMessage, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n 'Raw Call Arguments:',\n prettyArgs,\n ].filter(Boolean),\n name: 'CallExecutionError',\n });\n Object.defineProperty(this, \"cause\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.cause = cause;\n }\n}\nexport class ContractFunctionExecutionError extends BaseError {\n constructor(cause, { abi, args, contractAddress, docsPath, functionName, sender, }) {\n const abiItem = getAbiItem({ abi, args, name: functionName });\n const formattedArgs = abiItem\n ? formatAbiItemWithArgs({\n abiItem,\n args,\n includeFunctionName: false,\n includeName: false,\n })\n : undefined;\n const functionWithParams = abiItem\n ? formatAbiItem(abiItem, { includeName: true })\n : undefined;\n const prettyArgs = prettyPrint({\n address: contractAddress && getContractAddress(contractAddress),\n function: functionWithParams,\n args: formattedArgs &&\n formattedArgs !== '()' &&\n `${[...Array(functionName?.length ?? 0).keys()]\n .map(() => ' ')\n .join('')}${formattedArgs}`,\n sender,\n });\n super(cause.shortMessage ||\n `An unknown error occurred while executing the contract function \"${functionName}\".`, {\n cause,\n docsPath,\n metaMessages: [\n ...(cause.metaMessages ? [...cause.metaMessages, ' '] : []),\n prettyArgs && 'Contract Call:',\n prettyArgs,\n ].filter(Boolean),\n name: 'ContractFunctionExecutionError',\n });\n Object.defineProperty(this, \"abi\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"args\", {\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, \"contractAddress\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"formattedArgs\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"functionName\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"sender\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.abi = abi;\n this.args = args;\n this.cause = cause;\n this.contractAddress = contractAddress;\n this.functionName = functionName;\n this.sender = sender;\n }\n}\nexport class ContractFunctionRevertedError extends BaseError {\n constructor({ abi, data, functionName, message, cause: error, }) {\n let cause;\n let decodedData;\n let metaMessages;\n let reason;\n if (data && data !== '0x') {\n try {\n decodedData = decodeErrorResult({ abi, data, cause: error });\n const { abiItem, errorName, args: errorArgs } = decodedData;\n if (errorName === 'Error') {\n reason = errorArgs[0];\n }\n else if (errorName === 'Panic') {\n const [firstArg] = errorArgs;\n reason = panicReasons[firstArg];\n }\n else {\n const errorWithParams = abiItem\n ? formatAbiItem(abiItem, { includeName: true })\n : undefined;\n const formattedArgs = abiItem && errorArgs\n ? formatAbiItemWithArgs({\n abiItem,\n args: errorArgs,\n includeFunctionName: false,\n includeName: false,\n })\n : undefined;\n metaMessages = [\n errorWithParams ? `Error: ${errorWithParams}` : '',\n formattedArgs && formattedArgs !== '()'\n ? ` ${[...Array(errorName?.length ?? 0).keys()]\n .map(() => ' ')\n .join('')}${formattedArgs}`\n : '',\n ];\n }\n }\n catch (err) {\n cause = err;\n }\n }\n else if (message)\n reason = message;\n let signature;\n if (cause instanceof AbiErrorSignatureNotFoundError) {\n signature = cause.signature;\n metaMessages = [\n `Unable to decode signature \"${signature}\" as it was not found on the provided ABI.`,\n 'Make sure you are using the correct ABI and that the error exists on it.',\n `You can look up the decoded signature here: https://4byte.sourcify.dev/?q=${signature}.`,\n ];\n }\n super((reason && reason !== 'execution reverted') || signature\n ? [\n `The contract function \"${functionName}\" reverted with the following ${signature ? 'signature' : 'reason'}:`,\n reason || signature,\n ].join('\\n')\n : `The contract function \"${functionName}\" reverted.`, {\n cause: cause ?? error,\n metaMessages,\n name: 'ContractFunctionRevertedError',\n });\n Object.defineProperty(this, \"data\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"raw\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"reason\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"signature\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.data = decodedData;\n this.raw = data;\n this.reason = reason;\n this.signature = signature;\n }\n}\nexport class ContractFunctionZeroDataError extends BaseError {\n constructor({ functionName, cause, }) {\n super(`The contract function \"${functionName}\" returned no data (\"0x\").`, {\n metaMessages: [\n 'This could be due to any of the following:',\n ` - The contract does not have the function \"${functionName}\",`,\n ' - The parameters passed to the contract function may be invalid, or',\n ' - The address is not a contract.',\n ],\n name: 'ContractFunctionZeroDataError',\n cause,\n });\n }\n}\nexport class CounterfactualDeploymentFailedError extends BaseError {\n constructor({ factory }) {\n super(`Deployment for counterfactual contract call failed${factory ? ` for factory \"${factory}\".` : ''}`, {\n metaMessages: [\n 'Please ensure:',\n '- The `factory` is a valid contract deployment factory (ie. Create2 Factory, ERC-4337 Factory, etc).',\n '- The `factoryData` is a valid encoded function call for contract deployment function on the factory.',\n ],\n name: 'CounterfactualDeploymentFailedError',\n });\n }\n}\nexport class RawContractError extends BaseError {\n constructor({ data, message, }) {\n super(message || '', { name: 'RawContractError' });\n Object.defineProperty(this, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 3\n });\n Object.defineProperty(this, \"data\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.data = data;\n }\n}\n//# sourceMappingURL=contract.js.map","import { stringify } from '../utils/stringify.js';\nimport { BaseError } from './base.js';\nimport { getUrl } from './utils.js';\nexport class HttpRequestError extends BaseError {\n constructor({ body, cause, details, headers, status, url, }) {\n super('HTTP request failed.', {\n cause,\n details,\n metaMessages: [\n status && `Status: ${status}`,\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean),\n name: 'HttpRequestError',\n });\n Object.defineProperty(this, \"body\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"headers\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"status\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n Object.defineProperty(this, \"url\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.body = body;\n this.headers = headers;\n this.status = status;\n this.url = url;\n }\n}\nexport class ResponseBodyTooLargeError extends BaseError {\n constructor({ maxSize, size }) {\n super('HTTP response body exceeded the size limit.', {\n metaMessages: [`Max: ${maxSize} bytes`, `Received: ${size} bytes`],\n name: 'ResponseBodyTooLargeError',\n });\n Object.defineProperty(this, \"maxSize\", {\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.maxSize = maxSize;\n this.size = size;\n }\n}\nexport class WebSocketRequestError extends BaseError {\n constructor({ body, cause, details, url, }) {\n super('WebSocket request failed.', {\n cause,\n details,\n metaMessages: [\n `URL: ${getUrl(url)}`,\n body && `Request body: ${stringify(body)}`,\n ].filter(Boolean),\n name: 'WebSocketRequestError',\n });\n Object.defineProperty(this, \"url\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.url = url;\n }\n}\nexport class RpcRequestError extends BaseError {\n constructor({ body, error, url, }) {\n super('RPC Request failed.', {\n cause: error,\n details: error.message,\n metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n name: 'RpcRequestError',\n });\n Object.defineProperty(this, \"code\", {\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, \"url\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.code = error.code;\n this.data = error.data;\n this.url = url;\n }\n}\nexport class SocketClosedError extends BaseError {\n constructor({ url, } = {}) {\n super('The socket has been closed.', {\n metaMessages: [url && `URL: ${getUrl(url)}`].filter(Boolean),\n name: 'SocketClosedError',\n });\n Object.defineProperty(this, \"url\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.url = url;\n }\n}\nexport class TimeoutError extends BaseError {\n constructor({ body, url, }) {\n super('The request took too long to respond.', {\n details: 'The request timed out.',\n metaMessages: [`URL: ${getUrl(url)}`, `Request body: ${stringify(body)}`],\n name: 'TimeoutError',\n });\n Object.defineProperty(this, \"url\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.url = url;\n }\n}\n//# sourceMappingURL=request.js.map","import { BaseError } from './base.js';\nimport { RpcRequestError } from './request.js';\nconst unknownErrorCode = -1;\nexport class RpcError extends BaseError {\n constructor(cause, { code, docsPath, metaMessages, name, shortMessage, }) {\n super(shortMessage, {\n cause,\n docsPath,\n metaMessages: metaMessages || cause?.metaMessages,\n name: name || 'RpcError',\n });\n Object.defineProperty(this, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.name = name || cause.name;\n this.code = (cause instanceof RpcRequestError ? cause.code : (code ?? unknownErrorCode));\n }\n}\nexport class ProviderRpcError extends RpcError {\n constructor(cause, options) {\n super(cause, options);\n Object.defineProperty(this, \"data\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: void 0\n });\n this.data = options.data;\n }\n}\nexport class ParseRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: ParseRpcError.code,\n name: 'ParseRpcError',\n shortMessage: 'Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.',\n });\n }\n}\nObject.defineProperty(ParseRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32700\n});\nexport class InvalidRequestRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: InvalidRequestRpcError.code,\n name: 'InvalidRequestRpcError',\n shortMessage: 'JSON is not a valid request object.',\n });\n }\n}\nObject.defineProperty(InvalidRequestRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32600\n});\nexport class MethodNotFoundRpcError extends RpcError {\n constructor(cause, { method } = {}) {\n super(cause, {\n code: MethodNotFoundRpcError.code,\n name: 'MethodNotFoundRpcError',\n shortMessage: `The method${method ? ` \"${method}\"` : ''} does not exist / is not available.`,\n });\n }\n}\nObject.defineProperty(MethodNotFoundRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32601\n});\nexport class InvalidParamsRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: InvalidParamsRpcError.code,\n name: 'InvalidParamsRpcError',\n shortMessage: [\n 'Invalid parameters were provided to the RPC method.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n });\n }\n}\nObject.defineProperty(InvalidParamsRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32602\n});\nexport class InternalRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: InternalRpcError.code,\n name: 'InternalRpcError',\n shortMessage: 'An internal error was received.',\n });\n }\n}\nObject.defineProperty(InternalRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32603\n});\nexport class InvalidInputRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: InvalidInputRpcError.code,\n name: 'InvalidInputRpcError',\n shortMessage: [\n 'Missing or invalid parameters.',\n 'Double check you have provided the correct parameters.',\n ].join('\\n'),\n });\n }\n}\nObject.defineProperty(InvalidInputRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32000\n});\nexport class ResourceNotFoundRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: ResourceNotFoundRpcError.code,\n name: 'ResourceNotFoundRpcError',\n shortMessage: 'Requested resource not found.',\n });\n Object.defineProperty(this, \"name\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 'ResourceNotFoundRpcError'\n });\n }\n}\nObject.defineProperty(ResourceNotFoundRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32001\n});\nexport class ResourceUnavailableRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: ResourceUnavailableRpcError.code,\n name: 'ResourceUnavailableRpcError',\n shortMessage: 'Requested resource not available.',\n });\n }\n}\nObject.defineProperty(ResourceUnavailableRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32002\n});\nexport class TransactionRejectedRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: TransactionRejectedRpcError.code,\n name: 'TransactionRejectedRpcError',\n shortMessage: 'Transaction creation failed.',\n });\n }\n}\nObject.defineProperty(TransactionRejectedRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32003\n});\nexport class MethodNotSupportedRpcError extends RpcError {\n constructor(cause, { method } = {}) {\n super(cause, {\n code: MethodNotSupportedRpcError.code,\n name: 'MethodNotSupportedRpcError',\n shortMessage: `Method${method ? ` \"${method}\"` : ''} is not supported.`,\n });\n }\n}\nObject.defineProperty(MethodNotSupportedRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32004\n});\nexport class LimitExceededRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: LimitExceededRpcError.code,\n name: 'LimitExceededRpcError',\n shortMessage: 'Request exceeds defined limit.',\n });\n }\n}\nObject.defineProperty(LimitExceededRpcError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32005\n});\nexport class JsonRpcVersionUnsupportedError extends RpcError {\n constructor(cause) {\n super(cause, {\n code: JsonRpcVersionUnsupportedError.code,\n name: 'JsonRpcVersionUnsupportedError',\n shortMessage: 'Version of JSON-RPC protocol is not supported.',\n });\n }\n}\nObject.defineProperty(JsonRpcVersionUnsupportedError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: -32006\n});\nexport class UserRejectedRequestError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: UserRejectedRequestError.code,\n name: 'UserRejectedRequestError',\n shortMessage: 'User rejected the request.',\n });\n }\n}\nObject.defineProperty(UserRejectedRequestError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 4001\n});\nexport class UnauthorizedProviderError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: UnauthorizedProviderError.code,\n name: 'UnauthorizedProviderError',\n shortMessage: 'The requested method and/or account has not been authorized by the user.',\n });\n }\n}\nObject.defineProperty(UnauthorizedProviderError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 4100\n});\nexport class UnsupportedProviderMethodError extends ProviderRpcError {\n constructor(cause, { method } = {}) {\n super(cause, {\n code: UnsupportedProviderMethodError.code,\n name: 'UnsupportedProviderMethodError',\n shortMessage: `The Provider does not support the requested method${method ? ` \" ${method}\"` : ''}.`,\n });\n }\n}\nObject.defineProperty(UnsupportedProviderMethodError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 4200\n});\nexport class ProviderDisconnectedError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: ProviderDisconnectedError.code,\n name: 'ProviderDisconnectedError',\n shortMessage: 'The Provider is disconnected from all chains.',\n });\n }\n}\nObject.defineProperty(ProviderDisconnectedError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 4900\n});\nexport class ChainDisconnectedError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: ChainDisconnectedError.code,\n name: 'ChainDisconnectedError',\n shortMessage: 'The Provider is not connected to the requested chain.',\n });\n }\n}\nObject.defineProperty(ChainDisconnectedError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 4901\n});\nexport class SwitchChainError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: SwitchChainError.code,\n name: 'SwitchChainError',\n shortMessage: 'An error occurred when attempting to switch chain.',\n });\n }\n}\nObject.defineProperty(SwitchChainError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 4902\n});\nexport class UnsupportedNonOptionalCapabilityError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: UnsupportedNonOptionalCapabilityError.code,\n name: 'UnsupportedNonOptionalCapabilityError',\n shortMessage: 'This Wallet does not support a capability that was not marked as optional.',\n });\n }\n}\nObject.defineProperty(UnsupportedNonOptionalCapabilityError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5700\n});\nexport class UnsupportedChainIdError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: UnsupportedChainIdError.code,\n name: 'UnsupportedChainIdError',\n shortMessage: 'This Wallet does not support the requested chain ID.',\n });\n }\n}\nObject.defineProperty(UnsupportedChainIdError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5710\n});\nexport class DuplicateIdError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: DuplicateIdError.code,\n name: 'DuplicateIdError',\n shortMessage: 'There is already a bundle submitted with this ID.',\n });\n }\n}\nObject.defineProperty(DuplicateIdError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5720\n});\nexport class UnknownBundleIdError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: UnknownBundleIdError.code,\n name: 'UnknownBundleIdError',\n shortMessage: 'This bundle id is unknown / has not been submitted',\n });\n }\n}\nObject.defineProperty(UnknownBundleIdError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5730\n});\nexport class BundleTooLargeError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: BundleTooLargeError.code,\n name: 'BundleTooLargeError',\n shortMessage: 'The call bundle is too large for the Wallet to process.',\n });\n }\n}\nObject.defineProperty(BundleTooLargeError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5740\n});\nexport class AtomicReadyWalletRejectedUpgradeError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: AtomicReadyWalletRejectedUpgradeError.code,\n name: 'AtomicReadyWalletRejectedUpgradeError',\n shortMessage: 'The Wallet can support atomicity after an upgrade, but the user rejected the upgrade.',\n });\n }\n}\nObject.defineProperty(AtomicReadyWalletRejectedUpgradeError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5750\n});\nexport class AtomicityNotSupportedError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: AtomicityNotSupportedError.code,\n name: 'AtomicityNotSupportedError',\n shortMessage: 'The wallet does not support atomic execution but the request requires it.',\n });\n }\n}\nObject.defineProperty(AtomicityNotSupportedError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 5760\n});\nexport class WalletConnectSessionSettlementError extends ProviderRpcError {\n constructor(cause) {\n super(cause, {\n code: WalletConnectSessionSettlementError.code,\n name: 'WalletConnectSessionSettlementError',\n shortMessage: 'WalletConnect session settlement failed.',\n });\n }\n}\nObject.defineProperty(WalletConnectSessionSettlementError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 7000\n});\nexport class UnknownRpcError extends RpcError {\n constructor(cause) {\n super(cause, {\n name: 'UnknownRpcError',\n shortMessage: 'An unknown RPC error occurred.',\n });\n }\n}\n//# sourceMappingURL=rpc.js.map","import { AbiDecodingZeroDataError } from '../../errors/abi.js';\nimport { BaseError } from '../../errors/base.js';\nimport { ContractFunctionExecutionError, ContractFunctionRevertedError, ContractFunctionZeroDataError, RawContractError, } from '../../errors/contract.js';\nimport { RpcRequestError } from '../../errors/request.js';\nimport { InternalRpcError, InvalidInputRpcError } from '../../errors/rpc.js';\nconst EXECUTION_REVERTED_ERROR_CODE = 3;\nexport function getContractError(err, { abi, address, args, docsPath, functionName, sender, }) {\n const error = (err instanceof RawContractError\n ? err\n : err instanceof BaseError\n ? err.walk((err) => 'data' in err) || err.walk()\n : {});\n const { code, data, details, message, shortMessage } = error;\n const cause = (() => {\n if (err instanceof AbiDecodingZeroDataError)\n return new ContractFunctionZeroDataError({ functionName, cause: err });\n if (([EXECUTION_REVERTED_ERROR_CODE, InternalRpcError.code].includes(code) &&\n (data || details || message || shortMessage)) ||\n (code === InvalidInputRpcError.code &&\n details === 'execution reverted' &&\n data)) {\n return new ContractFunctionRevertedError({\n abi,\n data: typeof data === 'object' ? data.data : data,\n functionName,\n message: error instanceof RpcRequestError\n ? details\n : (shortMessage ?? message),\n cause: err,\n });\n }\n return err;\n })();\n return new ContractFunctionExecutionError(cause, {\n abi,\n args,\n contractAddress: address,\n docsPath,\n functionName,\n sender,\n });\n}\n//# sourceMappingURL=getContractError.js.map","import { formatGwei } from '../utils/unit/formatGwei.js';\nimport { BaseError } from './base.js';\nexport class ExecutionRevertedError extends BaseError {\n constructor({ cause, message, } = {}) {\n const reason = message\n ?.replace('execution reverted: ', '')\n ?.replace('execution reverted', '');\n super(`Execution reverted ${reason ? `with reason: ${reason}` : 'for an unknown reason'}.`, {\n cause,\n name: 'ExecutionRevertedError',\n });\n }\n}\nObject.defineProperty(ExecutionRevertedError, \"code\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: 3\n});\nObject.defineProperty(ExecutionRevertedError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /execution reverted|gas required exceeds allowance/\n});\nexport class FeeCapTooHighError extends BaseError {\n constructor({ cause, maxFeePerGas, } = {}) {\n super(`The fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''}) cannot be higher than the maximum allowed value (2^256-1).`, {\n cause,\n name: 'FeeCapTooHighError',\n });\n }\n}\nObject.defineProperty(FeeCapTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max fee per gas higher than 2\\^256-1|fee cap higher than 2\\^256-1/\n});\nexport class FeeCapTooLowError extends BaseError {\n constructor({ cause, maxFeePerGas, } = {}) {\n super(`The fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)}` : ''} gwei) cannot be lower than the block base fee.`, {\n cause,\n name: 'FeeCapTooLowError',\n });\n }\n}\nObject.defineProperty(FeeCapTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max fee per gas less than block base fee|fee cap less than block base fee|transaction is outdated/\n});\nexport class NonceTooHighError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}is higher than the next one expected.`, { cause, name: 'NonceTooHighError' });\n }\n}\nObject.defineProperty(NonceTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce too high/\n});\nexport class NonceTooLowError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super([\n `Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}is lower than the current nonce of the account.`,\n 'Try increasing the nonce or find the latest nonce with `getTransactionCount`.',\n ].join('\\n'), { cause, name: 'NonceTooLowError' });\n }\n}\nObject.defineProperty(NonceTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce too low|transaction already imported|already known/\n});\nexport class NonceMaxValueError extends BaseError {\n constructor({ cause, nonce, } = {}) {\n super(`Nonce provided for the transaction ${nonce ? `(${nonce}) ` : ''}exceeds the maximum allowed nonce.`, { cause, name: 'NonceMaxValueError' });\n }\n}\nObject.defineProperty(NonceMaxValueError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /nonce has max value/\n});\nexport class InsufficientFundsError extends BaseError {\n constructor({ cause } = {}) {\n super([\n 'The total cost (gas * gas fee + value) of executing this transaction exceeds the balance of the account.',\n ].join('\\n'), {\n cause,\n metaMessages: [\n 'This error could arise when the account does not have enough funds to:',\n ' - pay for the total gas fee,',\n ' - pay for the value to send.',\n ' ',\n 'The cost of the transaction is calculated as `gas * gas fee + value`, where:',\n ' - `gas` is the amount of gas needed for transaction to execute,',\n ' - `gas fee` is the gas fee,',\n ' - `value` is the amount of ether to send to the recipient.',\n ],\n name: 'InsufficientFundsError',\n });\n }\n}\nObject.defineProperty(InsufficientFundsError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /insufficient funds|exceeds transaction sender account balance/\n});\nexport class IntrinsicGasTooHighError extends BaseError {\n constructor({ cause, gas, } = {}) {\n super(`The amount of gas ${gas ? `(${gas}) ` : ''}provided for the transaction exceeds the limit allowed for the block.`, {\n cause,\n name: 'IntrinsicGasTooHighError',\n });\n }\n}\nObject.defineProperty(IntrinsicGasTooHighError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /intrinsic gas too high|gas limit reached/\n});\nexport class IntrinsicGasTooLowError extends BaseError {\n constructor({ cause, gas, } = {}) {\n super(`The amount of gas ${gas ? `(${gas}) ` : ''}provided for the transaction is too low.`, {\n cause,\n name: 'IntrinsicGasTooLowError',\n });\n }\n}\nObject.defineProperty(IntrinsicGasTooLowError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /intrinsic gas too low/\n});\nexport class TransactionTypeNotSupportedError extends BaseError {\n constructor({ cause }) {\n super('The transaction type is not supported for this chain.', {\n cause,\n name: 'TransactionTypeNotSupportedError',\n });\n }\n}\nObject.defineProperty(TransactionTypeNotSupportedError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /transaction type not valid/\n});\nexport class TipAboveFeeCapError extends BaseError {\n constructor({ cause, maxPriorityFeePerGas, maxFeePerGas, } = {}) {\n super([\n `The provided tip (\\`maxPriorityFeePerGas\\`${maxPriorityFeePerGas\n ? ` = ${formatGwei(maxPriorityFeePerGas)} gwei`\n : ''}) cannot be higher than the fee cap (\\`maxFeePerGas\\`${maxFeePerGas ? ` = ${formatGwei(maxFeePerGas)} gwei` : ''}).`,\n ].join('\\n'), {\n cause,\n name: 'TipAboveFeeCapError',\n });\n }\n}\nObject.defineProperty(TipAboveFeeCapError, \"nodeMessage\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: /max priority fee per gas higher than max fee per gas|tip higher than fee cap/\n});\nexport class UnknownNodeError extends BaseError {\n constructor({ cause }) {\n super(`An error occurred while executing: ${cause?.shortMessage}`, {\n cause,\n name: 'UnknownNodeError',\n });\n }\n}\n//# sourceMappingURL=node.js.map","/**\n * @description Picks out the keys from `value` that exist in the formatter..\n */\nexport function extract(value_, { format }) {\n if (!format)\n return {};\n const value = {};\n function extract_(formatted) {\n const keys = Object.keys(formatted);\n for (const key of keys) {\n if (key in value_)\n value[key] = value_[key];\n if (formatted[key] &&\n typeof formatted[key] === 'object' &&\n !Array.isArray(formatted[key]))\n extract_(formatted[key]);\n }\n }\n const formatted = format(value_ || {});\n extract_(formatted);\n return value;\n}\n//# sourceMappingURL=extract.js.map","import { bytesToHex, numberToHex } from '../encoding/toHex.js';\nimport { defineFormatter } from './formatter.js';\nexport const rpcTransactionType = {\n legacy: '0x0',\n eip2930: '0x1',\n eip1559: '0x2',\n eip4844: '0x3',\n eip7702: '0x4',\n};\nexport function formatTransactionRequest(request, _) {\n const rpcRequest = {};\n if (typeof request.authorizationList !== 'undefined')\n rpcRequest.authorizationList = formatAuthorizationList(request.authorizationList);\n if (typeof request.accessList !== 'undefined')\n rpcRequest.accessList = request.accessList;\n if (typeof request.blobVersionedHashes !== 'undefined')\n rpcRequest.blobVersionedHashes = request.blobVersionedHashes;\n if (typeof request.blobs !== 'undefined') {\n if (typeof request.blobs[0] !== 'string')\n rpcRequest.blobs = request.blobs.map((x) => bytesToHex(x));\n else\n rpcRequest.blobs = request.blobs;\n }\n if (typeof request.data !== 'undefined')\n rpcRequest.data = request.data;\n if (request.account)\n rpcRequest.from = request.account.address;\n if (typeof request.from !== 'undefined')\n rpcRequest.from = request.from;\n if (typeof request.gas !== 'undefined')\n rpcRequest.gas = numberToHex(request.gas);\n if (typeof request.gasPrice !== 'undefined')\n rpcRequest.gasPrice = numberToHex(request.gasPrice);\n if (typeof request.maxFeePerBlobGas !== 'undefined')\n rpcRequest.maxFeePerBlobGas = numberToHex(request.maxFeePerBlobGas);\n if (typeof request.maxFeePerGas !== 'undefined')\n rpcRequest.maxFeePerGas = numberToHex(request.maxFeePerGas);\n if (typeof request.maxPriorityFeePerGas !== 'undefined')\n rpcRequest.maxPriorityFeePerGas = numberToHex(request.maxPriorityFeePerGas);\n if (typeof request.nonce !== 'undefined')\n rpcRequest.nonce = numberToHex(request.nonce);\n if (typeof request.to !== 'undefined')\n rpcRequest.to = request.to;\n if (typeof request.type !== 'undefined')\n rpcRequest.type = rpcTransactionType[request.type];\n if (typeof request.value !== 'undefined')\n rpcRequest.value = numberToHex(request.value);\n return rpcRequest;\n}\nexport const defineTransactionRequest = /*#__PURE__*/ defineFormatter('transactionRequest', formatTransactionRequest);\n//////////////////////////////////////////////////////////////////////////////\nfunction formatAuthorizationList(authorizationList) {\n return authorizationList.map((authorization) => ({\n address: authorization.address,\n r: authorization.r\n ? numberToHex(BigInt(authorization.r))\n : authorization.r,\n s: authorization.s\n ? numberToHex(BigInt(authorization.s))\n : authorization.s,\n chainId: numberToHex(authorization.chainId),\n nonce: numberToHex(authorization.nonce),\n ...(typeof authorization.yParity !== 'undefined'\n ? { yParity: numberToHex(authorization.yParity) }\n : {}),\n ...(typeof authorization.v !== 'undefined' &&\n typeof authorization.yParity === 'undefined'\n ? { v: numberToHex(authorization.v) }\n : {}),\n }));\n}\n//# sourceMappingURL=transactionRequest.js.map","import { InvalidAddressError, } from '../errors/address.js';\nimport { InvalidBytesLengthError, } from '../errors/data.js';\nimport { AccountStateConflictError, StateAssignmentConflictError, } from '../errors/stateOverride.js';\nimport { isAddress } from './address/isAddress.js';\nimport { numberToHex } from './encoding/toHex.js';\n/** @internal */\nexport function serializeStateMapping(stateMapping) {\n if (!stateMapping || stateMapping.length === 0)\n return undefined;\n return stateMapping.reduce((acc, { slot, value }) => {\n if (slot.length !== 66)\n throw new InvalidBytesLengthError({\n size: slot.length,\n targetSize: 66,\n type: 'hex',\n });\n if (value.length !== 66)\n throw new InvalidBytesLengthError({\n size: value.length,\n targetSize: 66,\n type: 'hex',\n });\n acc[slot] = value;\n return acc;\n }, {});\n}\n/** @internal */\nexport function serializeAccountStateOverride(parameters) {\n const { balance, nonce, state, stateDiff, code } = parameters;\n const rpcAccountStateOverride = {};\n if (code !== undefined)\n rpcAccountStateOverride.code = code;\n if (balance !== undefined)\n rpcAccountStateOverride.balance = numberToHex(balance);\n if (nonce !== undefined)\n rpcAccountStateOverride.nonce = numberToHex(nonce);\n if (state !== undefined)\n rpcAccountStateOverride.state = serializeStateMapping(state);\n if (stateDiff !== undefined) {\n if (rpcAccountStateOverride.state)\n throw new StateAssignmentConflictError();\n rpcAccountStateOverride.stateDiff = serializeStateMapping(stateDiff);\n }\n return rpcAccountStateOverride;\n}\n/** @internal */\nexport function serializeStateOverride(parameters) {\n if (!parameters)\n return undefined;\n const rpcStateOverride = {};\n for (const { address, ...accountState } of parameters) {\n if (!isAddress(address, { strict: false }))\n throw new InvalidAddressError({ address });\n if (rpcStateOverride[address])\n throw new AccountStateConflictError({ address: address });\n rpcStateOverride[address] = serializeAccountStateOverride(accountState);\n }\n return rpcStateOverride;\n}\n//# sourceMappingURL=stateOverride.js.map","export const maxInt8 = 2n ** (8n - 1n) - 1n;\nexport const maxInt16 = 2n ** (16n - 1n) - 1n;\nexport const maxInt24 = 2n ** (24n - 1n) - 1n;\nexport const maxInt32 = 2n ** (32n - 1n) - 1n;\nexport const maxInt40 = 2n ** (40n - 1n) - 1n;\nexport const maxInt48 = 2n ** (48n - 1n) - 1n;\nexport const maxInt56 = 2n ** (56n - 1n) - 1n;\nexport const maxInt64 = 2n ** (64n - 1n) - 1n;\nexport const maxInt72 = 2n ** (72n - 1n) - 1n;\nexport const maxInt80 = 2n ** (80n - 1n) - 1n;\nexport const maxInt88 = 2n ** (88n - 1n) - 1n;\nexport const maxInt96 = 2n ** (96n - 1n) - 1n;\nexport const maxInt104 = 2n ** (104n - 1n) - 1n;\nexport const maxInt112 = 2n ** (112n - 1n) - 1n;\nexport const maxInt120 = 2n ** (120n - 1n) - 1n;\nexport const maxInt128 = 2n ** (128n - 1n) - 1n;\nexport const maxInt136 = 2n ** (136n - 1n) - 1n;\nexport const maxInt144 = 2n ** (144n - 1n) - 1n;\nexport const maxInt152 = 2n ** (152n - 1n) - 1n;\nexport const maxInt160 = 2n ** (160n - 1n) - 1n;\nexport const maxInt168 = 2n ** (168n - 1n) - 1n;\nexport const maxInt176 = 2n ** (176n - 1n) - 1n;\nexport const maxInt184 = 2n ** (184n - 1n) - 1n;\nexport const maxInt192 = 2n ** (192n - 1n) - 1n;\nexport const maxInt200 = 2n ** (200n - 1n) - 1n;\nexport const maxInt208 = 2n ** (208n - 1n) - 1n;\nexport const maxInt216 = 2n ** (216n - 1n) - 1n;\nexport const maxInt224 = 2n ** (224n - 1n) - 1n;\nexport const maxInt232 = 2n ** (232n - 1n) - 1n;\nexport const maxInt240 = 2n ** (240n - 1n) - 1n;\nexport const maxInt248 = 2n ** (248n - 1n) - 1n;\nexport const maxInt256 = 2n ** (256n - 1n) - 1n;\nexport const minInt8 = -(2n ** (8n - 1n));\nexport const minInt16 = -(2n ** (16n - 1n));\nexport const minInt24 = -(2n ** (24n - 1n));\nexport const minInt32 = -(2n ** (32n - 1n));\nexport const minInt40 = -(2n ** (40n - 1n));\nexport const minInt48 = -(2n ** (48n - 1n));\nexport const minInt56 = -(2n ** (56n - 1n));\nexport const minInt64 = -(2n ** (64n - 1n));\nexport const minInt72 = -(2n ** (72n - 1n));\nexport const minInt80 = -(2n ** (80n - 1n));\nexport const minInt88 = -(2n ** (88n - 1n));\nexport const minInt96 = -(2n ** (96n - 1n));\nexport const minInt104 = -(2n ** (104n - 1n));\nexport const minInt112 = -(2n ** (112n - 1n));\nexport const minInt120 = -(2n ** (120n - 1n));\nexport const minInt128 = -(2n ** (128n - 1n));\nexport const minInt136 = -(2n ** (136n - 1n));\nexport const minInt144 = -(2n ** (144n - 1n));\nexport const minInt152 = -(2n ** (152n - 1n));\nexport const minInt160 = -(2n ** (160n - 1n));\nexport const minInt168 = -(2n ** (168n - 1n));\nexport const minInt176 = -(2n ** (176n - 1n));\nexport const minInt184 = -(2n ** (184n - 1n));\nexport const minInt192 = -(2n ** (192n - 1n));\nexport const minInt200 = -(2n ** (200n - 1n));\nexport const minInt208 = -(2n ** (208n - 1n));\nexport const minInt216 = -(2n ** (216n - 1n));\nexport const minInt224 = -(2n ** (224n - 1n));\nexport const minInt232 = -(2n ** (232n - 1n));\nexport const minInt240 = -(2n ** (240n - 1n));\nexport const minInt248 = -(2n ** (248n - 1n));\nexport const minInt256 = -(2n ** (256n - 1n));\nexport const maxUint8 = 2n ** 8n - 1n;\nexport const maxUint16 = 2n ** 16n - 1n;\nexport const maxUint24 = 2n ** 24n - 1n;\nexport const maxUint32 = 2n ** 32n - 1n;\nexport const maxUint40 = 2n ** 40n - 1n;\nexport const maxUint48 = 2n ** 48n - 1n;\nexport const maxUint56 = 2n ** 56n - 1n;\nexport const maxUint64 = 2n ** 64n - 1n;\nexport const maxUint72 = 2n ** 72n - 1n;\nexport const maxUint80 = 2n ** 80n - 1n;\nexport const maxUint88 = 2n ** 88n - 1n;\nexport const maxUint96 = 2n ** 96n - 1n;\nexport const maxUint104 = 2n ** 104n - 1n;\nexport const maxUint112 = 2n ** 112n - 1n;\nexport const maxUint120 = 2n ** 120n - 1n;\nexport const maxUint128 = 2n ** 128n - 1n;\nexport const maxUint136 = 2n ** 136n - 1n;\nexport const maxUint144 = 2n ** 144n - 1n;\nexport const maxUint152 = 2n ** 152n - 1n;\nexport const maxUint160 = 2n ** 160n - 1n;\nexport const maxUint168 = 2n ** 168n - 1n;\nexport const maxUint176 = 2n ** 176n - 1n;\nexport const maxUint184 = 2n ** 184n - 1n;\nexport const maxUint192 = 2n ** 192n - 1n;\nexport const maxUint200 = 2n ** 200n - 1n;\nexport const maxUint208 = 2n ** 208n - 1n;\nexport const maxUint216 = 2n ** 216n - 1n;\nexport const maxUint224 = 2n ** 224n - 1n;\nexport const maxUint232 = 2n ** 232n - 1n;\nexport const maxUint240 = 2n ** 240n - 1n;\nexport const maxUint248 = 2n ** 248n - 1n;\nexport const maxUint256 = 2n ** 256n - 1n;\n//# sourceMappingURL=number.js.map","import { BaseError } from '../../errors/base.js';\nimport { numberToHex } from '../encoding/toHex.js';\n/**\n * Formats block parameters for RPC calls according to EIP-1898.\n *\n * @param parameters - Block parameters\n * @returns Formatted block parameter for RPC call\n *\n * @example\n * // Using block tag\n * formatBlockParameter({ blockTag: 'latest' })\n * // => 'latest'\n *\n * @example\n * // Using block number\n * formatBlockParameter({ blockNumber: 69420n })\n * // => '0x10f2c'\n *\n * @example\n * // Using block hash (EIP-1898)\n * formatBlockParameter({ blockHash: '0x...' })\n * // => { blockHash: '0x...' }\n *\n * @example\n * // Using block hash with requireCanonical (EIP-1898)\n * formatBlockParameter({ blockHash: '0x...', requireCanonical: true })\n * // => { blockHash: '0x...', requireCanonical: true }\n */\nexport function formatBlockParameter(parameters) {\n const { blockHash, blockNumber, blockTag, requireCanonical } = parameters;\n if (requireCanonical !== undefined && !blockHash)\n throw new BaseError('`requireCanonical` can only be provided when `blockHash` is set.');\n if (blockHash)\n return requireCanonical ? { blockHash, requireCanonical } : { blockHash };\n if (typeof blockNumber === 'bigint')\n return numberToHex(blockNumber);\n return blockTag ?? 'latest';\n}\n//# sourceMappingURL=formatBlockParameter.js.map","import { InvalidAddressError, } from '../../errors/address.js';\nimport { isAddress } from './isAddress.js';\nexport function isAddressEqual(a, b) {\n if (!isAddress(a, { strict: false }))\n throw new InvalidAddressError({ address: a });\n if (!isAddress(b, { strict: false }))\n throw new InvalidAddressError({ address: b });\n return a.toLowerCase() === b.toLowerCase();\n}\n//# sourceMappingURL=isAddressEqual.js.map","import { AbiFunctionNotFoundError, AbiFunctionOutputsNotFoundError, } from '../../errors/abi.js';\nimport { decodeAbiParameters, } from './decodeAbiParameters.js';\nimport { getAbiItem } from './getAbiItem.js';\nconst docsPath = '/docs/contract/decodeFunctionResult';\nexport function decodeFunctionResult(parameters) {\n const { abi, args, functionName, data } = parameters;\n let abiItem = abi[0];\n if (functionName) {\n const item = getAbiItem({ abi, args, name: functionName });\n if (!item)\n throw new AbiFunctionNotFoundError(functionName, { docsPath });\n abiItem = item;\n }\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath });\n if (!abiItem.outputs)\n throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath });\n const values = decodeAbiParameters(abiItem.outputs, data);\n if (values && values.length > 1)\n return values;\n if (values && values.length === 1)\n return values[0];\n return undefined;\n}\n//# sourceMappingURL=decodeFunctionResult.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 static setStaticOptions(options) {\n BaseError.prototype.docsOrigin = options.docsOrigin;\n BaseError.prototype.showVersion = options.showVersion;\n BaseError.prototype.version = options.version;\n }\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 = options.docsOrigin ?? BaseError.prototype.docsOrigin;\n const docs = `${docsBaseUrl}${docsPath ?? ''}`;\n const showVersion = Boolean(options.version ?? BaseError.prototype.showVersion);\n const version = options.version ?? BaseError.prototype.version;\n const message = [\n shortMessage || 'An error occurred.',\n ...(options.metaMessages ? ['', ...options.metaMessages] : []),\n ...(details || docsPath || showVersion\n ? [\n '',\n details ? `Details: ${details}` : undefined,\n docsPath ? `See: ${docs}` : undefined,\n showVersion ? `Version: ${version}` : 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, \"docsOrigin\", {\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, \"showVersion\", {\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, \"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 this.cause = options.cause;\n this.details = details;\n this.docs = docs;\n this.docsOrigin = docsBaseUrl;\n this.docsPath = docsPath;\n this.shortMessage = shortMessage;\n this.showVersion = showVersion;\n this.version = version;\n }\n walk(fn) {\n return walk(this, fn);\n }\n}\nObject.defineProperty(BaseError, \"defaultStaticOptions\", {\n enumerable: true,\n configurable: true,\n writable: true,\n value: {\n docsOrigin: 'https://oxlib.sh',\n showVersion: false,\n version: `ox@${getVersion()}`,\n }\n});\n(() => {\n BaseError.setStaticOptions(BaseError.defaultStaticOptions);\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","import { equalBytes } from '@noble/curves/abstract/utils';\nimport * as Bytes from './Bytes.js';\nimport * as Errors from './Errors.js';\nimport * as internal_bytes from './internal/bytes.js';\nimport * as internal from './internal/hex.js';\nimport * as Json from './Json.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 ? BigInt.asUintN(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 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 * as Hex from './Hex.js';\n/**\n * Converts a {@link ox#Withdrawal.Rpc} to an {@link ox#Withdrawal.Withdrawal}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.fromRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: '0x620323',\n * index: '0x0',\n * validatorIndex: '0x1',\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: 6423331n,\n * // @log: index: 0,\n * // @log: validatorIndex: 1\n * // @log: }\n * ```\n *\n * @param withdrawal - The RPC withdrawal to convert.\n * @returns An instantiated {@link ox#Withdrawal.Withdrawal}.\n */\nexport function fromRpc(withdrawal) {\n return {\n ...withdrawal,\n amount: BigInt(withdrawal.amount),\n index: Number(withdrawal.index),\n validatorIndex: Number(withdrawal.validatorIndex),\n };\n}\n/**\n * Converts a {@link ox#Withdrawal.Withdrawal} to an {@link ox#Withdrawal.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { Withdrawal } from 'ox'\n *\n * const withdrawal = Withdrawal.toRpc({\n * address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * amount: 6423331n,\n * index: 0,\n * validatorIndex: 1,\n * })\n * // @log: {\n * // @log: address: '0x00000000219ab540356cBB839Cbe05303d7705Fa',\n * // @log: amount: '0x620323',\n * // @log: index: '0x0',\n * // @log: validatorIndex: '0x1',\n * // @log: }\n * ```\n *\n * @param withdrawal - The Withdrawal to convert.\n * @returns An RPC Withdrawal.\n */\nexport function toRpc(withdrawal) {\n return {\n address: withdrawal.address,\n amount: Hex.fromNumber(withdrawal.amount),\n index: Hex.fromNumber(withdrawal.index),\n validatorIndex: Hex.fromNumber(withdrawal.validatorIndex),\n };\n}\n//# sourceMappingURL=Withdrawal.js.map","/* [Multicall3](https://github.com/mds1/multicall) */\nexport const multicall3Abi = [\n {\n inputs: [\n {\n components: [\n {\n name: 'target',\n type: 'address',\n },\n {\n name: 'allowFailure',\n type: 'bool',\n },\n {\n name: 'callData',\n type: 'bytes',\n },\n ],\n name: 'calls',\n type: 'tuple[]',\n },\n ],\n name: 'aggregate3',\n outputs: [\n {\n components: [\n {\n name: 'success',\n type: 'bool',\n },\n {\n name: 'returnData',\n type: 'bytes',\n },\n ],\n name: 'returnData',\n type: 'tuple[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'addr',\n type: 'address',\n },\n ],\n name: 'getEthBalance',\n outputs: [\n {\n name: 'balance',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'getCurrentBlockTimestamp',\n outputs: [\n {\n internalType: 'uint256',\n name: 'timestamp',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n];\nexport const batchGatewayAbi = [\n {\n name: 'query',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n {\n type: 'tuple[]',\n name: 'queries',\n components: [\n {\n type: 'address',\n name: 'sender',\n },\n {\n type: 'string[]',\n name: 'urls',\n },\n {\n type: 'bytes',\n name: 'data',\n },\n ],\n },\n ],\n outputs: [\n {\n type: 'bool[]',\n name: 'failures',\n },\n {\n type: 'bytes[]',\n name: 'responses',\n },\n ],\n },\n {\n name: 'HttpError',\n type: 'error',\n inputs: [\n {\n type: 'uint16',\n name: 'status',\n },\n {\n type: 'string',\n name: 'message',\n },\n ],\n },\n];\nconst universalResolverErrors = [\n {\n inputs: [\n {\n name: 'dns',\n type: 'bytes',\n },\n ],\n name: 'DNSDecodingFailed',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'ens',\n type: 'string',\n },\n ],\n name: 'DNSEncodingFailed',\n type: 'error',\n },\n {\n inputs: [],\n name: 'EmptyAddress',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'status',\n type: 'uint16',\n },\n {\n name: 'message',\n type: 'string',\n },\n ],\n name: 'HttpError',\n type: 'error',\n },\n {\n inputs: [],\n name: 'InvalidBatchGatewayResponse',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'errorData',\n type: 'bytes',\n },\n ],\n name: 'ResolverError',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n {\n name: 'resolver',\n type: 'address',\n },\n ],\n name: 'ResolverNotContract',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'name',\n type: 'bytes',\n },\n ],\n name: 'ResolverNotFound',\n type: 'error',\n },\n {\n inputs: [\n {\n name: 'primary',\n type: 'string',\n },\n {\n name: 'primaryAddress',\n type: 'bytes',\n },\n ],\n name: 'ReverseAddressMismatch',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'selector',\n type: 'bytes4',\n },\n ],\n name: 'UnsupportedResolverProfile',\n type: 'error',\n },\n];\nexport const universalResolverResolveAbi = [\n ...universalResolverErrors,\n {\n name: 'resolveWithGateways',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes' },\n { name: 'data', type: 'bytes' },\n { name: 'gateways', type: 'string[]' },\n ],\n outputs: [\n { name: '', type: 'bytes' },\n { name: 'address', type: 'address' },\n ],\n },\n];\nexport const universalResolverReverseAbi = [\n ...universalResolverErrors,\n {\n name: 'reverseWithGateways',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { type: 'bytes', name: 'reverseName' },\n { type: 'uint256', name: 'coinType' },\n { type: 'string[]', name: 'gateways' },\n ],\n outputs: [\n { type: 'string', name: 'resolvedName' },\n { type: 'address', name: 'resolver' },\n { type: 'address', name: 'reverseResolver' },\n ],\n },\n];\nexport const textResolverAbi = [\n {\n name: 'text',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes32' },\n { name: 'key', type: 'string' },\n ],\n outputs: [{ name: '', type: 'string' }],\n },\n];\nexport const addressResolverAbi = [\n {\n name: 'addr',\n type: 'function',\n stateMutability: 'view',\n inputs: [{ name: 'name', type: 'bytes32' }],\n outputs: [{ name: '', type: 'address' }],\n },\n {\n name: 'addr',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'name', type: 'bytes32' },\n { name: 'coinType', type: 'uint256' },\n ],\n outputs: [{ name: '', type: 'bytes' }],\n },\n];\n// ERC-1271\n// isValidSignature(bytes32 hash, bytes signature) → bytes4 magicValue\n/** @internal */\nexport const erc1271Abi = [\n {\n name: 'isValidSignature',\n type: 'function',\n stateMutability: 'view',\n inputs: [\n { name: 'hash', type: 'bytes32' },\n { name: 'signature', type: 'bytes' },\n ],\n outputs: [{ name: '', type: 'bytes4' }],\n },\n];\n// ERC-6492 - universal deployless signature validator contract\n// constructor(address _signer, bytes32 _hash, bytes _signature) → bytes4 returnValue\n// returnValue is either 0x1 (valid) or 0x0 (invalid)\nexport const erc6492SignatureValidatorAbi = [\n {\n inputs: [\n {\n name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'constructor',\n },\n {\n inputs: [\n {\n name: '_signer',\n type: 'address',\n },\n {\n name: '_hash',\n type: 'bytes32',\n },\n {\n name: '_signature',\n type: 'bytes',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n name: 'isValidSig',\n },\n];\n/** [ERC-20 Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20) */\nexport const erc20Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n];\n/**\n * [bytes32-flavored ERC-20](https://docs.makerdao.com/smart-contract-modules/mkr-module#4.-gotchas-potential-source-of-user-error)\n * for tokens (ie. Maker) that use bytes32 instead of string.\n */\nexport const erc20Abi_bytes32 = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'allowance',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'decimals',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint8',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'bytes32',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transfer',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n];\n/** [ERC-1155 Multi Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-1155) */\nexport const erc1155Abi = [\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'balance',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'needed',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InsufficientBalance',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'approver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidApprover',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: 'idsLength',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'valuesLength',\n type: 'uint256',\n },\n ],\n name: 'ERC1155InvalidArrayLength',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidOperator',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidReceiver',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'sender',\n type: 'address',\n },\n ],\n name: 'ERC1155InvalidSender',\n type: 'error',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'ERC1155MissingApprovalForAll',\n type: 'error',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'ApprovalForAll',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n indexed: false,\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n ],\n name: 'TransferBatch',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n indexed: false,\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'TransferSingle',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: false,\n internalType: 'string',\n name: 'value',\n type: 'string',\n },\n {\n indexed: true,\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'URI',\n type: 'event',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address[]',\n name: 'accounts',\n type: 'address[]',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n ],\n name: 'balanceOfBatch',\n outputs: [\n {\n internalType: 'uint256[]',\n name: '',\n type: 'uint256[]',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'account',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n ],\n name: 'isApprovedForAll',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256[]',\n name: 'ids',\n type: 'uint256[]',\n },\n {\n internalType: 'uint256[]',\n name: 'values',\n type: 'uint256[]',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeBatchTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'from',\n type: 'address',\n },\n {\n internalType: 'address',\n name: 'to',\n type: 'address',\n },\n {\n internalType: 'uint256',\n name: 'id',\n type: 'uint256',\n },\n {\n internalType: 'uint256',\n name: 'value',\n type: 'uint256',\n },\n {\n internalType: 'bytes',\n name: 'data',\n type: 'bytes',\n },\n ],\n name: 'safeTransferFrom',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'address',\n name: 'operator',\n type: 'address',\n },\n {\n internalType: 'bool',\n name: 'approved',\n type: 'bool',\n },\n ],\n name: 'setApprovalForAll',\n outputs: [],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'bytes4',\n name: 'interfaceId',\n type: 'bytes4',\n },\n ],\n name: 'supportsInterface',\n outputs: [\n {\n internalType: 'bool',\n name: '',\n type: 'bool',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n internalType: 'uint256',\n name: '',\n type: 'uint256',\n },\n ],\n name: 'uri',\n outputs: [\n {\n internalType: 'string',\n name: '',\n type: 'string',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n];\n/** [ERC-721 Non-Fungible Token Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-721) */\nexport const erc721Abi = [\n {\n type: 'event',\n name: 'Approval',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'event',\n name: 'ApprovalForAll',\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'operator',\n type: 'address',\n },\n {\n indexed: false,\n name: 'approved',\n type: 'bool',\n },\n ],\n },\n {\n type: 'event',\n name: 'Transfer',\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: true,\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'approve',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'balanceOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'getApproved',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'isApprovedForAll',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'operator',\n type: 'address',\n },\n ],\n outputs: [\n {\n type: 'bool',\n },\n ],\n },\n {\n type: 'function',\n name: 'name',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'ownerOf',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'safeTransferFrom',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'id',\n type: 'uint256',\n },\n {\n name: 'data',\n type: 'bytes',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'setApprovalForAll',\n stateMutability: 'nonpayable',\n inputs: [\n {\n name: 'operator',\n type: 'address',\n },\n {\n name: 'approved',\n type: 'bool',\n },\n ],\n outputs: [],\n },\n {\n type: 'function',\n name: 'symbol',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenByIndex',\n stateMutability: 'view',\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'index',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'tokenURI',\n stateMutability: 'view',\n inputs: [\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [\n {\n type: 'string',\n },\n ],\n },\n {\n type: 'function',\n name: 'totalSupply',\n stateMutability: 'view',\n inputs: [],\n outputs: [\n {\n type: 'uint256',\n },\n ],\n },\n {\n type: 'function',\n name: 'transferFrom',\n stateMutability: 'payable',\n inputs: [\n {\n name: 'sender',\n type: 'address',\n },\n {\n name: 'recipient',\n type: 'address',\n },\n {\n name: 'tokenId',\n type: 'uint256',\n },\n ],\n outputs: [],\n },\n];\n/** [ERC-4626 Tokenized Vaults Standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-4626) */\nexport const erc4626Abi = [\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: true,\n name: 'spender',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Approval',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Deposit',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'from',\n type: 'address',\n },\n {\n indexed: true,\n name: 'to',\n type: 'address',\n },\n {\n indexed: false,\n name: 'value',\n type: 'uint256',\n },\n ],\n name: 'Transfer',\n type: 'event',\n },\n {\n anonymous: false,\n inputs: [\n {\n indexed: true,\n name: 'sender',\n type: 'address',\n },\n {\n indexed: true,\n name: 'receiver',\n type: 'address',\n },\n {\n indexed: true,\n name: 'owner',\n type: 'address',\n },\n {\n indexed: false,\n name: 'assets',\n type: 'uint256',\n },\n {\n indexed: false,\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'Withdraw',\n type: 'event',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n {\n name: 'spender',\n type: 'address',\n },\n ],\n name: 'allowance',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'spender',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'approve',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'asset',\n outputs: [\n {\n name: 'assetTokenAddress',\n type: 'address',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'account',\n type: 'address',\n },\n ],\n name: 'balanceOf',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'convertToAssets',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'convertToShares',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'deposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxDeposit',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'caller',\n type: 'address',\n },\n ],\n name: 'maxMint',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxRedeem',\n outputs: [\n {\n name: 'maxShares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'maxWithdraw',\n outputs: [\n {\n name: 'maxAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n ],\n name: 'mint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewDeposit',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewMint',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n name: 'previewRedeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n name: 'previewWithdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'redeem',\n outputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalAssets',\n outputs: [\n {\n name: 'totalManagedAssets',\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [],\n name: 'totalSupply',\n outputs: [\n {\n type: 'uint256',\n },\n ],\n stateMutability: 'view',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transfer',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'from',\n type: 'address',\n },\n {\n name: 'to',\n type: 'address',\n },\n {\n name: 'amount',\n type: 'uint256',\n },\n ],\n name: 'transferFrom',\n outputs: [\n {\n type: 'bool',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n {\n inputs: [\n {\n name: 'assets',\n type: 'uint256',\n },\n {\n name: 'receiver',\n type: 'address',\n },\n {\n name: 'owner',\n type: 'address',\n },\n ],\n name: 'withdraw',\n outputs: [\n {\n name: 'shares',\n type: 'uint256',\n },\n ],\n stateMutability: 'nonpayable',\n type: 'function',\n },\n];\n//# sourceMappingURL=abis.js.map","export const aggregate3Signature = '0x82ad56cb';\n//# sourceMappingURL=contract.js.map","export const deploylessCallViaBytecodeBytecode = '0x608060405234801561001057600080fd5b5060405161018e38038061018e83398101604081905261002f91610124565b6000808351602085016000f59050803b61004857600080fd5b6000808351602085016000855af16040513d6000823e81610067573d81fd5b3d81f35b634e487b7160e01b600052604160045260246000fd5b600082601f83011261009257600080fd5b81516001600160401b038111156100ab576100ab61006b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156100d9576100d961006b565b6040528181528382016020018510156100f157600080fd5b60005b82811015610110576020818601810151838301820152016100f4565b506000918101602001919091529392505050565b6000806040838503121561013757600080fd5b82516001600160401b0381111561014d57600080fd5b61015985828601610081565b602085015190935090506001600160401b0381111561017757600080fd5b61018385828601610081565b915050925092905056fe';\nexport const deploylessCallViaFactoryBytecode = '0x608060405234801561001057600080fd5b506040516102c03803806102c083398101604081905261002f916101e6565b836001600160a01b03163b6000036100e457600080836001600160a01b03168360405161005c9190610270565b6000604051808303816000865af19150503d8060008114610099576040519150601f19603f3d011682016040523d82523d6000602084013e61009e565b606091505b50915091508115806100b857506001600160a01b0386163b155b156100e1578060405163101bb98d60e01b81526004016100d8919061028c565b60405180910390fd5b50505b6000808451602086016000885af16040513d6000823e81610103573d81fd5b3d81f35b80516001600160a01b038116811461011e57600080fd5b919050565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561015457818101518382015260200161013c565b50506000910152565b600082601f83011261016e57600080fd5b81516001600160401b0381111561018757610187610123565b604051601f8201601f19908116603f011681016001600160401b03811182821017156101b5576101b5610123565b6040528181528382016020018510156101cd57600080fd5b6101de826020830160208701610139565b949350505050565b600080600080608085870312156101fc57600080fd5b61020585610107565b60208601519094506001600160401b0381111561022157600080fd5b61022d8782880161015d565b93505061023c60408601610107565b60608601519092506001600160401b0381111561025857600080fd5b6102648782880161015d565b91505092959194509250565b60008251610282818460208701610139565b9190910192915050565b60208152600082518060208401526102ab816040850160208701610139565b601f01601f1916919091016040019291505056fe';\nexport const erc6492SignatureValidatorByteCode = '0x608060405234801561001057600080fd5b5060405161069438038061069483398101604081905261002f9161051e565b600061003c848484610048565b9050806000526001601ff35b60007f64926492649264926492649264926492649264926492649264926492649264926100748361040c565b036101e7576000606080848060200190518101906100929190610577565b60405192955090935091506000906001600160a01b038516906100b69085906105dd565b6000604051808303816000865af19150503d80600081146100f3576040519150601f19603f3d011682016040523d82523d6000602084013e6100f8565b606091505b50509050876001600160a01b03163b60000361016057806101605760405162461bcd60e51b815260206004820152601e60248201527f5369676e617475726556616c696461746f723a206465706c6f796d656e74000060448201526064015b60405180910390fd5b604051630b135d3f60e11b808252906001600160a01b038a1690631626ba7e90610190908b9087906004016105f9565b602060405180830381865afa1580156101ad573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906101d19190610633565b6001600160e01b03191614945050505050610405565b6001600160a01b0384163b1561027a57604051630b135d3f60e11b808252906001600160a01b03861690631626ba7e9061022790879087906004016105f9565b602060405180830381865afa158015610244573d6000803e3d6000fd5b505050506040513d601f19601f820116820180604052508101906102689190610633565b6001600160e01b031916149050610405565b81516041146102df5760405162461bcd60e51b815260206004820152603a602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e6174757265206c656e6774680000000000006064820152608401610157565b6102e7610425565b5060208201516040808401518451859392600091859190811061030c5761030c61065d565b016020015160f81c9050601b811480159061032b57508060ff16601c14155b1561038c5760405162461bcd60e51b815260206004820152603b602482015260008051602061067483398151915260448201527f3a20696e76616c6964207369676e617475726520762076616c756500000000006064820152608401610157565b60408051600081526020810180835289905260ff83169181019190915260608101849052608081018390526001600160a01b0389169060019060a0016020604051602081039080840390855afa1580156103ea573d6000803e3d6000fd5b505050602060405103516001600160a01b0316149450505050505b9392505050565b600060208251101561041d57600080fd5b508051015190565b60405180606001604052806003906020820280368337509192915050565b6001600160a01b038116811461045857600080fd5b50565b634e487b7160e01b600052604160045260246000fd5b60005b8381101561048c578181015183820152602001610474565b50506000910152565b600082601f8301126104a657600080fd5b81516001600160401b038111156104bf576104bf61045b565b604051601f8201601f19908116603f011681016001600160401b03811182821017156104ed576104ed61045b565b60405281815283820160200185101561050557600080fd5b610516826020830160208701610471565b949350505050565b60008060006060848603121561053357600080fd5b835161053e81610443565b6020850151604086015191945092506001600160401b0381111561056157600080fd5b61056d86828701610495565b9150509250925092565b60008060006060848603121561058c57600080fd5b835161059781610443565b60208501519093506001600160401b038111156105b357600080fd5b6105bf86828701610495565b604086015190935090506001600160401b0381111561056157600080fd5b600082516105ef818460208701610471565b9190910192915050565b828152604060208201526000825180604084015261061e816060850160208701610471565b601f01601f1916919091016060019392505050565b60006020828403121561064557600080fd5b81516001600160e01b03198116811461040557600080fd5b634e487b7160e01b600052603260045260246000fdfe5369676e617475726556616c696461746f72237265636f7665725369676e6572';\nexport const multicall3Bytecode = '0x608060405234801561001057600080fd5b506115b9806100206000396000f3fe6080604052600436106100f35760003560e01c80634d2301cc1161008a578063a8b0574e11610059578063a8b0574e14610325578063bce38bd714610350578063c3077fa914610380578063ee82ac5e146103b2576100f3565b80634d2301cc1461026257806372425d9d1461029f57806382ad56cb146102ca57806386d516e8146102fa576100f3565b80633408e470116100c65780633408e470146101af578063399542e9146101da5780633e64a6961461020c57806342cbb15c14610237576100f3565b80630f28c97d146100f8578063174dea7114610123578063252dba421461015357806327e86d6e14610184575b600080fd5b34801561010457600080fd5b5061010d6103ef565b60405161011a9190610c0a565b60405180910390f35b61013d60048036038101906101389190610c94565b6103f7565b60405161014a9190610e94565b60405180910390f35b61016d60048036038101906101689190610f0c565b610615565b60405161017b92919061101b565b60405180910390f35b34801561019057600080fd5b506101996107ab565b6040516101a69190611064565b60405180910390f35b3480156101bb57600080fd5b506101c46107b7565b6040516101d19190610c0a565b60405180910390f35b6101f460048036038101906101ef91906110ab565b6107bf565b6040516102039392919061110b565b60405180910390f35b34801561021857600080fd5b506102216107e1565b60405161022e9190610c0a565b60405180910390f35b34801561024357600080fd5b5061024c6107e9565b6040516102599190610c0a565b60405180910390f35b34801561026e57600080fd5b50610289600480360381019061028491906111a7565b6107f1565b6040516102969190610c0a565b60405180910390f35b3480156102ab57600080fd5b506102b4610812565b6040516102c19190610c0a565b60405180910390f35b6102e460048036038101906102df919061122a565b61081a565b6040516102f19190610e94565b60405180910390f35b34801561030657600080fd5b5061030f6109e4565b60405161031c9190610c0a565b60405180910390f35b34801561033157600080fd5b5061033a6109ec565b6040516103479190611286565b60405180910390f35b61036a600480360381019061036591906110ab565b6109f4565b6040516103779190610e94565b60405180910390f35b61039a60048036038101906103959190610f0c565b610ba6565b6040516103a99392919061110b565b60405180910390f35b3480156103be57600080fd5b506103d960048036038101906103d491906112cd565b610bca565b6040516103e69190611064565b60405180910390f35b600042905090565b60606000808484905090508067ffffffffffffffff81111561041c5761041b6112fa565b5b60405190808252806020026020018201604052801561045557816020015b610442610bd5565b81526020019060019003908161043a5790505b5092503660005b828110156105c957600085828151811061047957610478611329565b5b6020026020010151905087878381811061049657610495611329565b5b90506020028101906104a89190611367565b925060008360400135905080860195508360000160208101906104cb91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16818580606001906104f2919061138f565b604051610500929190611431565b60006040518083038185875af1925050503d806000811461053d576040519150601f19603f3d011682016040523d82523d6000602084013e610542565b606091505b5083600001846020018290528215151515815250505081516020850135176105bc577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260846000fd5b826001019250505061045c565b5082341461060c576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610603906114a7565b60405180910390fd5b50505092915050565b6000606043915060008484905090508067ffffffffffffffff81111561063e5761063d6112fa565b5b60405190808252806020026020018201604052801561067157816020015b606081526020019060019003908161065c5790505b5091503660005b828110156107a157600087878381811061069557610694611329565b5b90506020028101906106a791906114c7565b92508260000160208101906106bc91906111a7565b73ffffffffffffffffffffffffffffffffffffffff168380602001906106e2919061138f565b6040516106f0929190611431565b6000604051808303816000865af19150503d806000811461072d576040519150601f19603f3d011682016040523d82523d6000602084013e610732565b606091505b5086848151811061074657610745611329565b5b60200260200101819052819250505080610795576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161078c9061153b565b60405180910390fd5b81600101915050610678565b5050509250929050565b60006001430340905090565b600046905090565b6000806060439250434091506107d68686866109f4565b905093509350939050565b600048905090565b600043905090565b60008173ffffffffffffffffffffffffffffffffffffffff16319050919050565b600044905090565b606060008383905090508067ffffffffffffffff81111561083e5761083d6112fa565b5b60405190808252806020026020018201604052801561087757816020015b610864610bd5565b81526020019060019003908161085c5790505b5091503660005b828110156109db57600084828151811061089b5761089a611329565b5b602002602001015190508686838181106108b8576108b7611329565b5b90506020028101906108ca919061155b565b92508260000160208101906108df91906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060400190610905919061138f565b604051610913929190611431565b6000604051808303816000865af19150503d8060008114610950576040519150601f19603f3d011682016040523d82523d6000602084013e610955565b606091505b5082600001836020018290528215151515815250505080516020840135176109cf577f08c379a000000000000000000000000000000000000000000000000000000000600052602060045260176024527f4d756c746963616c6c333a2063616c6c206661696c656400000000000000000060445260646000fd5b8160010191505061087e565b50505092915050565b600045905090565b600041905090565b606060008383905090508067ffffffffffffffff811115610a1857610a176112fa565b5b604051908082528060200260200182016040528015610a5157816020015b610a3e610bd5565b815260200190600190039081610a365790505b5091503660005b82811015610b9c576000848281518110610a7557610a74611329565b5b60200260200101519050868683818110610a9257610a91611329565b5b9050602002810190610aa491906114c7565b9250826000016020810190610ab991906111a7565b73ffffffffffffffffffffffffffffffffffffffff16838060200190610adf919061138f565b604051610aed929190611431565b6000604051808303816000865af19150503d8060008114610b2a576040519150601f19603f3d011682016040523d82523d6000602084013e610b2f565b606091505b508260000183602001829052821515151581525050508715610b90578060000151610b8f576040517f08c379a0000000000000000000000000000000000000000000000000000000008152600401610b869061153b565b60405180910390fd5b5b81600101915050610a58565b5050509392505050565b6000806060610bb7600186866107bf565b8093508194508295505050509250925092565b600081409050919050565b6040518060400160405280600015158152602001606081525090565b6000819050919050565b610c0481610bf1565b82525050565b6000602082019050610c1f6000830184610bfb565b92915050565b600080fd5b600080fd5b600080fd5b600080fd5b600080fd5b60008083601f840112610c5457610c53610c2f565b5b8235905067ffffffffffffffff811115610c7157610c70610c34565b5b602083019150836020820283011115610c8d57610c8c610c39565b5b9250929050565b60008060208385031215610cab57610caa610c25565b5b600083013567ffffffffffffffff811115610cc957610cc8610c2a565b5b610cd585828601610c3e565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b60008115159050919050565b610d2281610d0d565b82525050565b600081519050919050565b600082825260208201905092915050565b60005b83811015610d62578082015181840152602081019050610d47565b83811115610d71576000848401525b50505050565b6000601f19601f8301169050919050565b6000610d9382610d28565b610d9d8185610d33565b9350610dad818560208601610d44565b610db681610d77565b840191505092915050565b6000604083016000830151610dd96000860182610d19565b5060208301518482036020860152610df18282610d88565b9150508091505092915050565b6000610e0a8383610dc1565b905092915050565b6000602082019050919050565b6000610e2a82610ce1565b610e348185610cec565b935083602082028501610e4685610cfd565b8060005b85811015610e825784840389528151610e638582610dfe565b9450610e6e83610e12565b925060208a01995050600181019050610e4a565b50829750879550505050505092915050565b60006020820190508181036000830152610eae8184610e1f565b905092915050565b60008083601f840112610ecc57610ecb610c2f565b5b8235905067ffffffffffffffff811115610ee957610ee8610c34565b5b602083019150836020820283011115610f0557610f04610c39565b5b9250929050565b60008060208385031215610f2357610f22610c25565b5b600083013567ffffffffffffffff811115610f4157610f40610c2a565b5b610f4d85828601610eb6565b92509250509250929050565b600081519050919050565b600082825260208201905092915050565b6000819050602082019050919050565b6000610f918383610d88565b905092915050565b6000602082019050919050565b6000610fb182610f59565b610fbb8185610f64565b935083602082028501610fcd85610f75565b8060005b858110156110095784840389528151610fea8582610f85565b9450610ff583610f99565b925060208a01995050600181019050610fd1565b50829750879550505050505092915050565b60006040820190506110306000830185610bfb565b81810360208301526110428184610fa6565b90509392505050565b6000819050919050565b61105e8161104b565b82525050565b60006020820190506110796000830184611055565b92915050565b61108881610d0d565b811461109357600080fd5b50565b6000813590506110a58161107f565b92915050565b6000806000604084860312156110c4576110c3610c25565b5b60006110d286828701611096565b935050602084013567ffffffffffffffff8111156110f3576110f2610c2a565b5b6110ff86828701610eb6565b92509250509250925092565b60006060820190506111206000830186610bfb565b61112d6020830185611055565b818103604083015261113f8184610e1f565b9050949350505050565b600073ffffffffffffffffffffffffffffffffffffffff82169050919050565b600061117482611149565b9050919050565b61118481611169565b811461118f57600080fd5b50565b6000813590506111a18161117b565b92915050565b6000602082840312156111bd576111bc610c25565b5b60006111cb84828501611192565b91505092915050565b60008083601f8401126111ea576111e9610c2f565b5b8235905067ffffffffffffffff81111561120757611206610c34565b5b60208301915083602082028301111561122357611222610c39565b5b9250929050565b6000806020838503121561124157611240610c25565b5b600083013567ffffffffffffffff81111561125f5761125e610c2a565b5b61126b858286016111d4565b92509250509250929050565b61128081611169565b82525050565b600060208201905061129b6000830184611277565b92915050565b6112aa81610bf1565b81146112b557600080fd5b50565b6000813590506112c7816112a1565b92915050565b6000602082840312156112e3576112e2610c25565b5b60006112f1848285016112b8565b91505092915050565b7f4e487b7100000000000000000000000000000000000000000000000000000000600052604160045260246000fd5b7f4e487b7100000000000000000000000000000000000000000000000000000000600052603260045260246000fd5b600080fd5b600080fd5b600080fd5b60008235600160800383360303811261138357611382611358565b5b80830191505092915050565b600080833560016020038436030381126113ac576113ab611358565b5b80840192508235915067ffffffffffffffff8211156113ce576113cd61135d565b5b6020830192506001820236038313156113ea576113e9611362565b5b509250929050565b600081905092915050565b82818337600083830152505050565b600061141883856113f2565b93506114258385846113fd565b82840190509392505050565b600061143e82848661140c565b91508190509392505050565b600082825260208201905092915050565b7f4d756c746963616c6c333a2076616c7565206d69736d61746368000000000000600082015250565b6000611491601a8361144a565b915061149c8261145b565b602082019050919050565b600060208201905081810360008301526114c081611484565b9050919050565b6000823560016040038336030381126114e3576114e2611358565b5b80830191505092915050565b7f4d756c746963616c6c333a2063616c6c206661696c6564000000000000000000600082015250565b600061152560178361144a565b9150611530826114ef565b602082019050919050565b6000602082019050818103600083015261155481611518565b9050919050565b60008235600160600383360303811261157757611576611358565b5b8083019150509291505056fea264697066735822122020c1bc9aacf8e4a6507193432a895a8e77094f45a1395583f07b24e860ef06cd64736f6c634300080c0033';\n//# sourceMappingURL=contracts.js.map","import { BaseError } from './base.js';\nexport class ChainDoesNotSupportContract extends BaseError {\n constructor({ blockNumber, chain, contract, }) {\n super(`Chain \"${chain.name}\" does not support contract \"${contract.name}\".`, {\n metaMessages: [\n 'This could be due to any of the following:',\n ...(blockNumber &&\n contract.blockCreated &&\n contract.blockCreated > blockNumber\n ? [\n `- The contract \"${contract.name}\" was not deployed until block ${contract.blockCreated} (current block ${blockNumber}).`,\n ]\n : [\n `- The chain does not have the contract \"${contract.name}\" configured.`,\n ]),\n ],\n name: 'ChainDoesNotSupportContract',\n });\n }\n}\nexport class ChainMismatchError extends BaseError {\n constructor({ chain, currentChainId, }) {\n super(`The current chain of the wallet (id: ${currentChainId}) does not match the target chain for the transaction (id: ${chain.id} – ${chain.name}).`, {\n metaMessages: [\n `Current Chain ID: ${currentChainId}`,\n `Expected Chain ID: ${chain.id} – ${chain.name}`,\n ],\n name: 'ChainMismatchError',\n });\n }\n}\nexport class ChainNotFoundError extends BaseError {\n constructor() {\n super([\n 'No chain was provided to the request.',\n 'Please provide a chain with the `chain` argument on the Action, or by supplying a `chain` to WalletClient.',\n ].join('\\n'), {\n name: 'ChainNotFoundError',\n });\n }\n}\nexport class ClientChainNotConfiguredError extends BaseError {\n constructor() {\n super('No chain was provided to the Client.', {\n name: 'ClientChainNotConfiguredError',\n });\n }\n}\nexport class InvalidChainIdError extends BaseError {\n constructor({ chainId }) {\n super(typeof chainId === 'number'\n ? `Chain ID \"${chainId}\" is invalid.`\n : 'Chain ID is invalid.', { name: 'InvalidChainIdError' });\n }\n}\n//# sourceMappingURL=chain.js.map","import { AbiConstructorNotFoundError, AbiConstructorParamsNotFoundError, } from '../../errors/abi.js';\nimport { concatHex } from '../data/concat.js';\nimport { encodeAbiParameters, } from './encodeAbiParameters.js';\nconst docsPath = '/docs/contract/encodeDeployData';\nexport function encodeDeployData(parameters) {\n const { abi, args, bytecode } = parameters;\n if (!args || args.length === 0)\n return bytecode;\n const description = abi.find((x) => 'type' in x && x.type === 'constructor');\n if (!description)\n throw new AbiConstructorNotFoundError({ docsPath });\n if (!('inputs' in description))\n throw new AbiConstructorParamsNotFoundError({ docsPath });\n if (!description.inputs || description.inputs.length === 0)\n throw new AbiConstructorParamsNotFoundError({ docsPath });\n const data = encodeAbiParameters(description.inputs, args);\n return concatHex([bytecode, data]);\n}\n//# sourceMappingURL=encodeDeployData.js.map","import { ChainDoesNotSupportContract, } from '../../errors/chain.js';\nexport function getChainContractAddress({ blockNumber, chain, contract: name, }) {\n const contract = chain?.contracts?.[name];\n if (!contract)\n throw new ChainDoesNotSupportContract({\n chain,\n contract: { name },\n });\n if (blockNumber &&\n contract.blockCreated &&\n contract.blockCreated > blockNumber)\n throw new ChainDoesNotSupportContract({\n blockNumber,\n chain,\n contract: {\n name,\n blockCreated: contract.blockCreated,\n },\n });\n return contract.address;\n}\n//# sourceMappingURL=getChainContractAddress.js.map","import { CallExecutionError, } from '../../errors/contract.js';\nimport { UnknownNodeError } from '../../errors/node.js';\nimport { getNodeError, } from './getNodeError.js';\nexport function getCallError(err, { docsPath, ...args }) {\n const cause = (() => {\n const cause = getNodeError(err, args);\n if (cause instanceof UnknownNodeError)\n return err;\n return cause;\n })();\n return new CallExecutionError(cause, {\n docsPath,\n ...args,\n });\n}\n//# sourceMappingURL=getCallError.js.map","import { BaseError } from '../../errors/base.js';\nimport { ExecutionRevertedError, FeeCapTooHighError, FeeCapTooLowError, InsufficientFundsError, IntrinsicGasTooHighError, IntrinsicGasTooLowError, NonceMaxValueError, NonceTooHighError, NonceTooLowError, TipAboveFeeCapError, TransactionTypeNotSupportedError, UnknownNodeError, } from '../../errors/node.js';\nimport { RpcRequestError } from '../../errors/request.js';\nimport { InvalidInputRpcError, TransactionRejectedRpcError, } from '../../errors/rpc.js';\nexport function containsNodeError(err) {\n return (err instanceof TransactionRejectedRpcError ||\n err instanceof InvalidInputRpcError ||\n (err instanceof RpcRequestError && err.code === ExecutionRevertedError.code));\n}\nexport function getNodeError(err, args) {\n const message = (err.details || '').toLowerCase();\n const executionRevertedError = err instanceof BaseError\n ? err.walk((e) => e?.code ===\n ExecutionRevertedError.code)\n : err;\n if (executionRevertedError instanceof BaseError)\n return new ExecutionRevertedError({\n cause: err,\n message: executionRevertedError.details,\n });\n if (ExecutionRevertedError.nodeMessage.test(message))\n return new ExecutionRevertedError({\n cause: err,\n message: err.details,\n });\n if (FeeCapTooHighError.nodeMessage.test(message))\n return new FeeCapTooHighError({\n cause: err,\n maxFeePerGas: args?.maxFeePerGas,\n });\n if (FeeCapTooLowError.nodeMessage.test(message))\n return new FeeCapTooLowError({\n cause: err,\n maxFeePerGas: args?.maxFeePerGas,\n });\n if (NonceTooHighError.nodeMessage.test(message))\n return new NonceTooHighError({ cause: err, nonce: args?.nonce });\n if (NonceTooLowError.nodeMessage.test(message))\n return new NonceTooLowError({ cause: err, nonce: args?.nonce });\n if (NonceMaxValueError.nodeMessage.test(message))\n return new NonceMaxValueError({ cause: err, nonce: args?.nonce });\n if (InsufficientFundsError.nodeMessage.test(message))\n return new InsufficientFundsError({ cause: err });\n if (IntrinsicGasTooHighError.nodeMessage.test(message))\n return new IntrinsicGasTooHighError({ cause: err, gas: args?.gas });\n if (IntrinsicGasTooLowError.nodeMessage.test(message))\n return new IntrinsicGasTooLowError({ cause: err, gas: args?.gas });\n if (TransactionTypeNotSupportedError.nodeMessage.test(message))\n return new TransactionTypeNotSupportedError({ cause: err });\n if (TipAboveFeeCapError.nodeMessage.test(message))\n return new TipAboveFeeCapError({\n cause: err,\n maxFeePerGas: args?.maxFeePerGas,\n maxPriorityFeePerGas: args?.maxPriorityFeePerGas,\n });\n return new UnknownNodeError({\n cause: err,\n });\n}\n//# sourceMappingURL=getNodeError.js.map","import { withResolvers } from './withResolvers.js';\nconst schedulerCache = /*#__PURE__*/ new Map();\n/** @internal */\nexport function createBatchScheduler({ fn, id, shouldSplitBatch, wait = 0, sort, }) {\n const exec = async () => {\n const scheduler = getScheduler();\n flush();\n const args = scheduler.map(({ args }) => args);\n if (args.length === 0)\n return;\n fn(args)\n .then((data) => {\n if (sort && Array.isArray(data))\n data.sort(sort);\n for (let i = 0; i < scheduler.length; i++) {\n const { resolve } = scheduler[i];\n resolve?.([data[i], data]);\n }\n })\n .catch((err) => {\n for (let i = 0; i < scheduler.length; i++) {\n const { reject } = scheduler[i];\n reject?.(err);\n }\n });\n };\n const flush = () => schedulerCache.delete(id);\n const getBatchedArgs = () => getScheduler().map(({ args }) => args);\n const getScheduler = () => schedulerCache.get(id) || [];\n const setScheduler = (item) => schedulerCache.set(id, [...getScheduler(), item]);\n return {\n flush,\n async schedule(args) {\n const { promise, resolve, reject } = withResolvers();\n const split = shouldSplitBatch?.([...getBatchedArgs(), args]);\n if (split)\n exec();\n const hasActiveScheduler = getScheduler().length > 0;\n if (hasActiveScheduler) {\n setScheduler({ args, resolve, reject });\n return promise;\n }\n setScheduler({ args, resolve, reject });\n setTimeout(exec, wait);\n return promise;\n },\n };\n}\n//# sourceMappingURL=createBatchScheduler.js.map","/** @internal */\nexport function withResolvers() {\n let resolve = () => undefined;\n let reject = () => undefined;\n const promise = new Promise((resolve_, reject_) => {\n resolve = resolve_;\n reject = reject_;\n });\n return { promise, resolve, reject };\n}\n//# sourceMappingURL=withResolvers.js.map","import { parseAbi } from 'abitype';\nimport * as BlockOverrides from 'ox/BlockOverrides';\nimport { parseAccount, } from '../../accounts/utils/parseAccount.js';\nimport { multicall3Abi } from '../../constants/abis.js';\nimport { aggregate3Signature } from '../../constants/contract.js';\nimport { deploylessCallViaBytecodeBytecode, deploylessCallViaFactoryBytecode, multicall3Bytecode, } from '../../constants/contracts.js';\nimport { BaseError } from '../../errors/base.js';\nimport { ChainDoesNotSupportContract, ClientChainNotConfiguredError, } from '../../errors/chain.js';\nimport { CounterfactualDeploymentFailedError, RawContractError, } from '../../errors/contract.js';\nimport { getAbortError, isAbortError, } from '../../errors/utils.js';\nimport { decodeFunctionResult, } from '../../utils/abi/decodeFunctionResult.js';\nimport { encodeDeployData, } from '../../utils/abi/encodeDeployData.js';\nimport { encodeFunctionData, } from '../../utils/abi/encodeFunctionData.js';\nimport { isAddressEqual } from '../../utils/address/isAddressEqual.js';\nimport { formatBlockParameter, } from '../../utils/block/formatBlockParameter.js';\nimport { getChainContractAddress, } from '../../utils/chain/getChainContractAddress.js';\nimport { getCallError, } from '../../utils/errors/getCallError.js';\nimport { extract } from '../../utils/formatters/extract.js';\nimport { formatTransactionRequest, } from '../../utils/formatters/transactionRequest.js';\nimport { createBatchScheduler, } from '../../utils/promise/createBatchScheduler.js';\nimport { serializeStateOverride, } from '../../utils/stateOverride.js';\nimport { assertRequest } from '../../utils/transaction/assertRequest.js';\n/**\n * Executes a new message call immediately without submitting a transaction to the network.\n *\n * - Docs: https://viem.sh/docs/actions/public/call\n * - JSON-RPC Methods: [`eth_call`](https://ethereum.org/en/developers/docs/apis/json-rpc/#eth_call)\n *\n * @param client - Client to use\n * @param parameters - {@link CallParameters}\n * @returns The call data. {@link CallReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { call } from 'viem/public'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const data = await call(client, {\n * account: '0xf39fd6e51aad88f6f4ce6ab8827279cfffb92266',\n * data: '0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2',\n * to: '0x70997970c51812dc3a010c7d01b50e0d17dc79c8',\n * })\n */\nexport async function call(client, args) {\n const { account: account_ = client.account, authorizationList, batch = Boolean(client.batch?.multicall), blockHash, blockNumber, blockTag = client.experimental_blockTag ?? 'latest', requireCanonical, accessList, blobs, blockOverrides, code, data: data_, factory, factoryData, gas, gasPrice, maxFeePerBlobGas, maxFeePerGas, maxPriorityFeePerGas, nonce, requestOptions, to, value, stateOverride, ...rest } = args;\n const account = account_ ? parseAccount(account_) : undefined;\n if (code && (factory || factoryData))\n throw new BaseError('Cannot provide both `code` & `factory`/`factoryData` as parameters.');\n if (code && to)\n throw new BaseError('Cannot provide both `code` & `to` as parameters.');\n // Check if the call is deployless via bytecode.\n const deploylessCallViaBytecode = code && data_;\n // Check if the call is deployless via a factory.\n const deploylessCallViaFactory = factory && factoryData && to && data_;\n const deploylessCall = deploylessCallViaBytecode || deploylessCallViaFactory;\n const data = (() => {\n if (deploylessCallViaBytecode)\n return toDeploylessCallViaBytecodeData({\n code,\n data: data_,\n });\n if (deploylessCallViaFactory)\n return toDeploylessCallViaFactoryData({\n data: data_,\n factory,\n factoryData,\n to,\n });\n return data_;\n })();\n try {\n assertRequest(args);\n const block = formatBlockParameter({\n blockHash,\n blockNumber,\n blockTag,\n requireCanonical,\n });\n const rpcBlockOverrides = blockOverrides\n ? BlockOverrides.toRpc(blockOverrides)\n : undefined;\n const rpcStateOverride = serializeStateOverride(stateOverride);\n const chainFormat = client.chain?.formatters?.transactionRequest?.format;\n const format = chainFormat || formatTransactionRequest;\n const request = format({\n // Pick out extra data that might exist on the chain's transaction request type.\n ...extract(rest, { format: chainFormat }),\n accessList,\n account,\n authorizationList,\n blobs,\n data,\n gas,\n gasPrice,\n maxFeePerBlobGas,\n maxFeePerGas,\n maxPriorityFeePerGas,\n nonce,\n to: deploylessCall ? undefined : to,\n value,\n }, 'call');\n if (batch &&\n shouldPerformMulticall({ request }) &&\n !rpcBlockOverrides &&\n blockHash === undefined) {\n try {\n const { deployless = false } = typeof client.batch?.multicall === 'object'\n ? client.batch.multicall\n : {};\n const multicallAddress = getMulticallAddress(client, {\n blockNumber,\n deployless,\n });\n if (!multicallAddress ||\n !hasStateOverrideForAddress(rpcStateOverride, multicallAddress))\n return await scheduleMulticall(client, {\n ...request,\n blockHash,\n blockNumber,\n blockTag,\n multicallAddress,\n requestOptions,\n requireCanonical,\n rpcStateOverride,\n });\n }\n catch (err) {\n if (!(err instanceof ClientChainNotConfiguredError) &&\n !(err instanceof ChainDoesNotSupportContract))\n throw err;\n }\n }\n const params = (() => {\n const base = [\n request,\n block,\n ];\n if (rpcStateOverride && rpcBlockOverrides)\n return [...base, rpcStateOverride, rpcBlockOverrides];\n if (rpcStateOverride)\n return [...base, rpcStateOverride];\n if (rpcBlockOverrides)\n return [...base, {}, rpcBlockOverrides];\n return base;\n })();\n const response = await client.request({\n method: 'eth_call',\n params,\n }, requestOptions);\n if (response === '0x')\n return { data: undefined };\n return { data: response };\n }\n catch (err) {\n if (requestOptions?.signal?.aborted)\n throw getAbortError(requestOptions.signal);\n if (isAbortError(err))\n throw err;\n const data = getRevertErrorData(err);\n // Check for CCIP-Read offchain lookup signature.\n const { offchainLookup, offchainLookupSignature } = await import('../../utils/ccip.js');\n if (client.ccipRead !== false &&\n data?.slice(0, 10) === offchainLookupSignature &&\n to)\n return {\n data: await offchainLookup(client, { data, requestOptions, to }),\n };\n // Check for counterfactual deployment error.\n if (deploylessCall && data?.slice(0, 10) === '0x101bb98d')\n throw new CounterfactualDeploymentFailedError({ factory });\n throw getCallError(err, {\n ...args,\n account,\n chain: client.chain,\n });\n }\n}\n// We only want to perform a scheduled multicall if:\n// - The request has calldata,\n// - The request has a target address,\n// - The target address is not already the aggregate3 signature,\n// - The request has no other properties (`nonce`, `gas`, etc cannot be sent with a multicall).\nfunction shouldPerformMulticall({ request }) {\n const { data, to, ...request_ } = request;\n if (!data)\n return false;\n if (data.startsWith(aggregate3Signature))\n return false;\n if (!to)\n return false;\n if (Object.values(request_).filter((x) => typeof x !== 'undefined').length > 0)\n return false;\n return true;\n}\nlet requestOptionsId = 0;\nconst requestOptionsIds = new WeakMap();\nfunction getRequestOptionsId(requestOptions) {\n if (!requestOptions)\n return 'default';\n const id = requestOptionsIds.get(requestOptions);\n if (id !== undefined)\n return id;\n const nextId = requestOptionsId++;\n requestOptionsIds.set(requestOptions, nextId);\n return nextId;\n}\nasync function scheduleMulticall(client, args) {\n const { batchSize = 1024, deployless = false, wait = 0, } = typeof client.batch?.multicall === 'object' ? client.batch.multicall : {};\n const { blockHash, blockNumber, blockTag = client.experimental_blockTag ?? 'latest', requireCanonical, data, multicallAddress: multicallAddress_, requestOptions, rpcStateOverride, to, } = args;\n const multicallAddress = multicallAddress_ !== undefined\n ? multicallAddress_\n : getMulticallAddress(client, {\n blockNumber,\n deployless,\n });\n const block = formatBlockParameter({\n blockHash,\n blockNumber,\n blockTag,\n requireCanonical,\n });\n const blockId = typeof block === 'string' ? block : JSON.stringify(block);\n const stateOverrideKey = rpcStateOverride\n ? `.${JSON.stringify(rpcStateOverride)}`\n : '';\n const { schedule } = createBatchScheduler({\n id: `${client.uid}.${blockId}.${getRequestOptionsId(requestOptions)}${stateOverrideKey}`,\n wait,\n shouldSplitBatch(args) {\n const size = args.reduce((size, { data }) => size + (data.length - 2), 0);\n return size > batchSize * 2;\n },\n fn: async (requests) => {\n const calls = requests.map((request) => ({\n allowFailure: true,\n callData: request.data,\n target: request.to,\n }));\n const calldata = encodeFunctionData({\n abi: multicall3Abi,\n args: [calls],\n functionName: 'aggregate3',\n });\n const multicallRequest = {\n ...(multicallAddress === null\n ? {\n data: toDeploylessCallViaBytecodeData({\n code: multicall3Bytecode,\n data: calldata,\n }),\n }\n : { to: multicallAddress, data: calldata }),\n };\n const data = await client.request({\n method: 'eth_call',\n params: rpcStateOverride\n ? [multicallRequest, block, rpcStateOverride]\n : [multicallRequest, block],\n }, requestOptions);\n return decodeFunctionResult({\n abi: multicall3Abi,\n args: [calls],\n functionName: 'aggregate3',\n data: data || '0x',\n });\n },\n });\n const [{ returnData, success }] = await schedule({ data, to });\n if (!success)\n throw new RawContractError({ data: returnData });\n if (returnData === '0x')\n return { data: undefined };\n return { data: returnData };\n}\nfunction getMulticallAddress(client, parameters) {\n const { blockNumber, deployless } = parameters;\n if (deployless)\n return null;\n if (client.chain)\n return getChainContractAddress({\n blockNumber,\n chain: client.chain,\n contract: 'multicall3',\n });\n throw new ClientChainNotConfiguredError();\n}\nfunction hasStateOverrideForAddress(rpcStateOverride, address) {\n if (!rpcStateOverride)\n return false;\n return Object.keys(rpcStateOverride).some((stateOverrideAddress) => isAddressEqual(stateOverrideAddress, address));\n}\nfunction toDeploylessCallViaBytecodeData(parameters) {\n const { code, data } = parameters;\n return encodeDeployData({\n abi: parseAbi(['constructor(bytes, bytes)']),\n bytecode: deploylessCallViaBytecodeBytecode,\n args: [code, data],\n });\n}\nfunction toDeploylessCallViaFactoryData(parameters) {\n const { data, factory, factoryData, to } = parameters;\n return encodeDeployData({\n abi: parseAbi(['constructor(address, bytes, address, bytes)']),\n bytecode: deploylessCallViaFactoryBytecode,\n args: [to, data, factory, factoryData],\n });\n}\n/** @internal */\nexport function getRevertErrorData(err) {\n if (!(err instanceof BaseError))\n return undefined;\n const error = err.walk();\n return typeof error?.data === 'object' ? error.data?.data : error.data;\n}\n//# sourceMappingURL=call.js.map","import { parseAccount, } from '../../accounts/utils/parseAccount.js';\nimport { maxUint256 } from '../../constants/number.js';\nimport { InvalidAddressError, } from '../../errors/address.js';\nimport { FeeCapTooHighError, TipAboveFeeCapError, } from '../../errors/node.js';\nimport { isAddress } from '../address/isAddress.js';\nexport function assertRequest(args) {\n const { account: account_, maxFeePerGas, maxPriorityFeePerGas, to } = args;\n const account = account_ ? parseAccount(account_) : undefined;\n if (account && !isAddress(account.address))\n throw new InvalidAddressError({ address: account.address });\n if (to && !isAddress(to))\n throw new InvalidAddressError({ address: to });\n if (maxFeePerGas && maxFeePerGas > maxUint256)\n throw new FeeCapTooHighError({ maxFeePerGas });\n if (maxPriorityFeePerGas &&\n maxFeePerGas &&\n maxPriorityFeePerGas > maxFeePerGas)\n throw new TipAboveFeeCapError({ maxFeePerGas, maxPriorityFeePerGas });\n}\n//# sourceMappingURL=assertRequest.js.map","import * as Hex from './Hex.js';\nimport * as Withdrawal from './Withdrawal.js';\n/**\n * Converts an {@link ox#BlockOverrides.Rpc} to an {@link ox#BlockOverrides.BlockOverrides}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.fromRpc({\n * baseFeePerGas: '0x1',\n * blobBaseFee: '0x2',\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: '0x4',\n * number: '0x5',\n * prevRandao: '0x6',\n * time: '0x1234567890',\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: '0x1',\n * index: '0x0',\n * validatorIndex: '0x1',\n * },\n * ],\n * })\n * ```\n *\n * @param rpcBlockOverrides - The RPC block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.BlockOverrides}.\n */\nexport function fromRpc(rpcBlockOverrides) {\n return {\n ...(rpcBlockOverrides.baseFeePerGas && {\n baseFeePerGas: BigInt(rpcBlockOverrides.baseFeePerGas),\n }),\n ...(rpcBlockOverrides.blobBaseFee && {\n blobBaseFee: BigInt(rpcBlockOverrides.blobBaseFee),\n }),\n ...(rpcBlockOverrides.feeRecipient && {\n feeRecipient: rpcBlockOverrides.feeRecipient,\n }),\n ...(rpcBlockOverrides.gasLimit && {\n gasLimit: BigInt(rpcBlockOverrides.gasLimit),\n }),\n ...(rpcBlockOverrides.number && {\n number: BigInt(rpcBlockOverrides.number),\n }),\n ...(rpcBlockOverrides.prevRandao && {\n prevRandao: BigInt(rpcBlockOverrides.prevRandao),\n }),\n ...(rpcBlockOverrides.time && {\n time: BigInt(rpcBlockOverrides.time),\n }),\n ...(rpcBlockOverrides.withdrawals && {\n withdrawals: rpcBlockOverrides.withdrawals.map(Withdrawal.fromRpc),\n }),\n };\n}\n/**\n * Converts an {@link ox#BlockOverrides.BlockOverrides} to an {@link ox#BlockOverrides.Rpc}.\n *\n * @example\n * ```ts twoslash\n * import { BlockOverrides } from 'ox'\n *\n * const blockOverrides = BlockOverrides.toRpc({\n * baseFeePerGas: 1n,\n * blobBaseFee: 2n,\n * feeRecipient: '0x0000000000000000000000000000000000000000',\n * gasLimit: 4n,\n * number: 5n,\n * prevRandao: 6n,\n * time: 78187493520n,\n * withdrawals: [\n * {\n * address: '0x0000000000000000000000000000000000000000',\n * amount: 1n,\n * index: 0,\n * validatorIndex: 1,\n * },\n * ],\n * })\n * ```\n *\n * @param blockOverrides - The block overrides to convert.\n * @returns An instantiated {@link ox#BlockOverrides.Rpc}.\n */\nexport function toRpc(blockOverrides) {\n return {\n ...(typeof blockOverrides.baseFeePerGas === 'bigint' && {\n baseFeePerGas: Hex.fromNumber(blockOverrides.baseFeePerGas),\n }),\n ...(typeof blockOverrides.blobBaseFee === 'bigint' && {\n blobBaseFee: Hex.fromNumber(blockOverrides.blobBaseFee),\n }),\n ...(typeof blockOverrides.feeRecipient === 'string' && {\n feeRecipient: blockOverrides.feeRecipient,\n }),\n ...(typeof blockOverrides.gasLimit === 'bigint' && {\n gasLimit: Hex.fromNumber(blockOverrides.gasLimit),\n }),\n ...(typeof blockOverrides.number === 'bigint' && {\n number: Hex.fromNumber(blockOverrides.number),\n }),\n ...(typeof blockOverrides.prevRandao === 'bigint' && {\n prevRandao: Hex.fromNumber(blockOverrides.prevRandao),\n }),\n ...(typeof blockOverrides.time === 'bigint' && {\n time: Hex.fromNumber(blockOverrides.time),\n }),\n ...(blockOverrides.withdrawals && {\n withdrawals: blockOverrides.withdrawals.map(Withdrawal.toRpc),\n }),\n };\n}\n//# sourceMappingURL=BlockOverrides.js.map","import { decodeFunctionResult, } from '../../utils/abi/decodeFunctionResult.js';\nimport { encodeFunctionData, } from '../../utils/abi/encodeFunctionData.js';\nimport { getContractError, } from '../../utils/errors/getContractError.js';\nimport { getAction } from '../../utils/getAction.js';\nimport { call } from './call.js';\n/**\n * Calls a read-only function on a contract, and returns the response.\n *\n * - Docs: https://viem.sh/docs/contract/readContract\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/contracts_reading-contracts\n *\n * A \"read-only\" function (constant function) on a Solidity contract is denoted by a `view` or `pure` keyword. They can only read the state of the contract, and cannot make any changes to it. Since read-only methods do not change the state of the contract, they do not require any gas to be executed, and can be called by any user without the need to pay for gas.\n *\n * Internally, uses a [Public Client](https://viem.sh/docs/clients/public) to call the [`call` action](https://viem.sh/docs/actions/public/call) with [ABI-encoded `data`](https://viem.sh/docs/contract/encodeFunctionData).\n *\n * @param client - Client to use\n * @param parameters - {@link ReadContractParameters}\n * @returns The response from the contract. Type is inferred. {@link ReadContractReturnType}\n *\n * @example\n * import { createPublicClient, http, parseAbi } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { readContract } from 'viem/contract'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const result = await readContract(client, {\n * address: '0xFBA3912Ca04dd458c843e2EE08967fC04f3579c2',\n * abi: parseAbi(['function balanceOf(address) view returns (uint256)']),\n * functionName: 'balanceOf',\n * args: ['0xA0Cf798816D4b9b9866b5330EEa46a18382f251e'],\n * })\n * // 424122n\n */\nexport async function readContract(client, parameters) {\n const { abi, address, args, functionName, ...rest } = parameters;\n const calldata = encodeFunctionData({\n abi,\n args,\n functionName,\n });\n try {\n const { data } = await getAction(client, call, 'call')({\n ...rest,\n data: calldata,\n to: address,\n });\n return decodeFunctionResult({\n abi,\n args,\n functionName,\n data: data || '0x',\n });\n }\n catch (error) {\n throw getContractError(error, {\n abi,\n address,\n args,\n docsPath: '/docs/contract/readContract',\n functionName,\n });\n }\n}\n//# sourceMappingURL=readContract.js.map","import { getAbortError, isAbortError, } from '../../errors/utils.js';\nimport { wait } from '../wait.js';\nexport function withRetry(fn, { delay: delay_ = 100, retryCount = 2, shouldRetry = () => true, signal, } = {}) {\n return new Promise((resolve, reject) => {\n const attemptRetry = async ({ count = 0 } = {}) => {\n if (signal?.aborted) {\n reject(getAbortError(signal));\n return;\n }\n const retry = async ({ error }) => {\n const delay = typeof delay_ === 'function' ? delay_({ count, error }) : delay_;\n if (delay) {\n try {\n await wait(delay, { signal });\n }\n catch (err) {\n reject(err);\n return;\n }\n }\n return attemptRetry({ count: count + 1 });\n };\n try {\n const data = await fn();\n resolve(data);\n }\n catch (err) {\n if (signal?.aborted) {\n reject(getAbortError(signal));\n return;\n }\n if (isAbortError(err)) {\n reject(err);\n return;\n }\n if (count < retryCount &&\n (await shouldRetry({ count, error: err })))\n return retry({ error: err });\n reject(err);\n }\n };\n void attemptRetry().catch(reject);\n });\n}\n//# sourceMappingURL=withRetry.js.map","import { getAbortError } from '../errors/utils.js';\nexport async function wait(time, { signal } = {}) {\n return new Promise((resolve, reject) => {\n if (signal?.aborted) {\n reject(getAbortError(signal));\n return;\n }\n const cleanup = () => signal?.removeEventListener('abort', onAbort);\n const timeout = setTimeout(() => {\n cleanup();\n resolve();\n }, time);\n const onAbort = () => {\n clearTimeout(timeout);\n cleanup();\n reject(getAbortError(signal));\n };\n signal?.addEventListener('abort', onAbort, { once: true });\n });\n}\n//# sourceMappingURL=wait.js.map","const size = 256;\nlet index = size;\nlet buffer;\nexport function uid(length = 11) {\n if (!buffer || index + length > size * 2) {\n buffer = '';\n index = 0;\n for (let i = 0; i < size; i++) {\n buffer += ((256 + Math.random() * 256) | 0).toString(16).substring(1);\n }\n }\n return buffer.substring(index, index++ + length);\n}\n//# sourceMappingURL=uid.js.map","import { parseAccount, } from '../accounts/utils/parseAccount.js';\nimport { uid } from '../utils/uid.js';\nexport function createClient(parameters) {\n const { batch, chain, ccipRead, dataSuffix, key = 'base', name = 'Base Client', tokens, type = 'base', } = parameters;\n const experimental_blockTag = parameters.experimental_blockTag ??\n (typeof chain?.experimental_preconfirmationTime === 'number'\n ? 'pending'\n : undefined);\n const blockTime = chain?.blockTime ?? 12_000;\n const defaultPollingInterval = Math.min(Math.max(Math.floor(blockTime / 2), 500), 4_000);\n const pollingInterval = parameters.pollingInterval ?? defaultPollingInterval;\n const cacheTime = parameters.cacheTime ?? pollingInterval;\n const account = parameters.account\n ? parseAccount(parameters.account)\n : undefined;\n const { config, request, value } = parameters.transport({\n account,\n chain,\n pollingInterval,\n });\n const transport = { ...config, ...value };\n const client = {\n account,\n batch,\n cacheTime,\n ccipRead,\n chain,\n dataSuffix,\n key,\n name,\n pollingInterval,\n request,\n tokens,\n transport,\n type,\n uid: uid(),\n ...(experimental_blockTag ? { experimental_blockTag } : {}),\n };\n function extend(base) {\n return (extendFn) => {\n const extended = extendFn(base);\n for (const key in client)\n delete extended[key];\n const combined = { ...base, ...extended };\n // For keys that exist on both the base client and the extension and\n // resolve to plain objects (e.g. namespaces like `token`), shallow-merge\n // their members instead of overwriting. This lets decorators contribute\n // to the same namespace (e.g. `publicActions` adds read actions and\n // `walletActions` adds write actions to `client.token`).\n for (const key in extended) {\n const a = base[key];\n const b = extended[key];\n if (isPlainObject(a) && isPlainObject(b))\n combined[key] = { ...a, ...b };\n }\n return Object.assign(combined, { extend: extend(combined) });\n };\n }\n return Object.assign(client, { extend: extend(client) });\n}\n/** Whether `value` is a plain object (`{}`), as opposed to a function, array,\n * or class instance. Used to decide which extension namespaces to merge. */\nfunction isPlainObject(value) {\n if (typeof value !== 'object' || value === null)\n return false;\n const prototype = Object.getPrototypeOf(value);\n return prototype === Object.prototype || prototype === null;\n}\n/**\n * Binds an action function to a `client`, returning a parameter-only version\n * along with any helpers the action exposes. Helpers that need a client\n * (`.call`, `.calls`, `.callWithPeriod`, `.estimateGas`, `.prepare`,\n * `.prepareRecipient`, `.predict`, `.simulate`) are bound to `client`;\n * pure helpers (`.extractEvent`, `.extractEvents`) are copied as-is. Used\n * by decorators that attach namespaced actions to a Client.\n * @internal\n */\nexport function bindActionDecorators(client, action) {\n const wrapped = (parameters = {}) => action(client, parameters);\n for (const key of [\n 'call',\n 'calls',\n 'callWithPeriod',\n 'estimateGas',\n 'prepare',\n 'prepareRecipient',\n 'predict',\n 'simulate',\n ])\n if (Object.hasOwn(action, key)) {\n const helper = action[key];\n wrapped[key] = (args = {}) => {\n // Single-parameter helpers are client-less (e.g. `dex.buy.call(args)`).\n // Everything else is called with `(client, args)`: two-parameter\n // helpers, rest-parameter helpers that accept `(client, args)` or\n // `(args)` (`length === 0`, e.g. `token.transfer.call`), and\n // zero-argument helpers, which ignore the extra arguments.\n if (helper.length === 1)\n return helper(args);\n return helper(client, args);\n };\n }\n for (const key of ['extractEvent', 'extractEvents'])\n if (Object.hasOwn(action, key))\n wrapped[key] = action[key];\n return wrapped;\n}\n/**\n * Defines a typed JSON-RPC schema for the client.\n * Note: This is a runtime noop function.\n */\nexport function rpcSchema() {\n return null;\n}\n//# sourceMappingURL=createClient.js.map","import { AbiErrorInputsNotFoundError, AbiErrorNotFoundError, } from '../../errors/abi.js';\nimport { concatHex } from '../data/concat.js';\nimport { toFunctionSelector, } from '../hash/toFunctionSelector.js';\nimport { encodeAbiParameters, } from './encodeAbiParameters.js';\nimport { formatAbiItem } from './formatAbiItem.js';\nimport { getAbiItem } from './getAbiItem.js';\nconst docsPath = '/docs/contract/encodeErrorResult';\nexport function encodeErrorResult(parameters) {\n const { abi, errorName, args } = parameters;\n let abiItem = abi[0];\n if (errorName) {\n const item = getAbiItem({ abi, args, name: errorName });\n if (!item)\n throw new AbiErrorNotFoundError(errorName, { docsPath });\n abiItem = item;\n }\n if (abiItem.type !== 'error')\n throw new AbiErrorNotFoundError(undefined, { docsPath });\n const definition = formatAbiItem(abiItem);\n const signature = toFunctionSelector(definition);\n let data = '0x';\n if (args && args.length > 0) {\n if (!abiItem.inputs)\n throw new AbiErrorInputsNotFoundError(abiItem.name, { docsPath });\n data = encodeAbiParameters(abiItem.inputs, args);\n }\n return concatHex([signature, data]);\n}\n//# sourceMappingURL=encodeErrorResult.js.map","import { AbiFunctionNotFoundError, AbiFunctionOutputsNotFoundError, InvalidArrayError, } from '../../errors/abi.js';\nimport { encodeAbiParameters, } from './encodeAbiParameters.js';\nimport { getAbiItem } from './getAbiItem.js';\nconst docsPath = '/docs/contract/encodeFunctionResult';\nexport function encodeFunctionResult(parameters) {\n const { abi, functionName, result } = parameters;\n let abiItem = abi[0];\n if (functionName) {\n const item = getAbiItem({ abi, name: functionName });\n if (!item)\n throw new AbiFunctionNotFoundError(functionName, { docsPath });\n abiItem = item;\n }\n if (abiItem.type !== 'function')\n throw new AbiFunctionNotFoundError(undefined, { docsPath });\n if (!abiItem.outputs)\n throw new AbiFunctionOutputsNotFoundError(abiItem.name, { docsPath });\n const values = (() => {\n if (abiItem.outputs.length === 0)\n return [];\n if (abiItem.outputs.length === 1)\n return [result];\n if (Array.isArray(result))\n return result;\n throw new InvalidArrayError(result);\n })();\n return encodeAbiParameters(abiItem.outputs, values);\n}\n//# sourceMappingURL=encodeFunctionResult.js.map","import { batchGatewayAbi } from '../../constants/abis.js';\nimport { solidityError } from '../../constants/solidity.js';\nimport { decodeFunctionData } from '../abi/decodeFunctionData.js';\nimport { encodeErrorResult } from '../abi/encodeErrorResult.js';\nimport { encodeFunctionResult } from '../abi/encodeFunctionResult.js';\nexport const localBatchGatewayUrl = 'x-batch-gateway:true';\nexport async function localBatchGatewayRequest(parameters) {\n const { data, ccipRequest } = parameters;\n const { args: [queries], } = decodeFunctionData({ abi: batchGatewayAbi, data });\n const failures = [];\n const responses = [];\n await Promise.all(queries.map(async (query, i) => {\n try {\n responses[i] = query.urls.includes(localBatchGatewayUrl)\n ? await localBatchGatewayRequest({ data: query.data, ccipRequest })\n : await ccipRequest(query);\n failures[i] = false;\n }\n catch (err) {\n failures[i] = true;\n responses[i] = encodeError(err);\n }\n }));\n return encodeFunctionResult({\n abi: batchGatewayAbi,\n functionName: 'query',\n result: [failures, responses],\n });\n}\nfunction encodeError(error) {\n if (error.name === 'HttpRequestError' && error.status)\n return encodeErrorResult({\n abi: batchGatewayAbi,\n errorName: 'HttpError',\n args: [error.status, error.shortMessage],\n });\n return encodeErrorResult({\n abi: [solidityError],\n errorName: 'Error',\n args: ['shortMessage' in error ? error.shortMessage : error.message],\n });\n}\n//# sourceMappingURL=localBatchGatewayRequest.js.map","import { AbiFunctionSignatureNotFoundError } from '../../errors/abi.js';\nimport { slice } from '../data/slice.js';\nimport { toFunctionSelector, } from '../hash/toFunctionSelector.js';\nimport { decodeAbiParameters, } from './decodeAbiParameters.js';\nimport { formatAbiItem } from './formatAbiItem.js';\nexport function decodeFunctionData(parameters) {\n const { abi, data } = parameters;\n const signature = slice(data, 0, 4);\n const description = abi.find((x) => x.type === 'function' &&\n signature === toFunctionSelector(formatAbiItem(x)));\n if (!description)\n throw new AbiFunctionSignatureNotFoundError(signature, {\n docsPath: '/docs/contract/decodeFunctionData',\n });\n return {\n functionName: description.name,\n args: ('inputs' in description &&\n description.inputs &&\n description.inputs.length > 0\n ? decodeAbiParameters(description.inputs, slice(data, 4))\n : undefined),\n };\n}\n//# sourceMappingURL=decodeFunctionData.js.map","import { LruMap } from '../lru.js';\n/** @internal */\nexport const promiseCache = /*#__PURE__*/ new LruMap(8192);\n/** Deduplicates in-flight promises. */\nexport function withDedupe(fn, { enabled = true, id }) {\n if (!enabled || !id)\n return fn();\n if (promiseCache.get(id))\n return promiseCache.get(id);\n const promise = fn().finally(() => promiseCache.delete(id));\n promiseCache.set(id, promise);\n return promise;\n}\n//# sourceMappingURL=withDedupe.js.map","import { BaseError } from '../errors/base.js';\nimport { HttpRequestError, } from '../errors/request.js';\nimport { AtomicityNotSupportedError, AtomicReadyWalletRejectedUpgradeError, BundleTooLargeError, ChainDisconnectedError, DuplicateIdError, InternalRpcError, InvalidInputRpcError, InvalidParamsRpcError, InvalidRequestRpcError, JsonRpcVersionUnsupportedError, LimitExceededRpcError, MethodNotFoundRpcError, MethodNotSupportedRpcError, ParseRpcError, ProviderDisconnectedError, ResourceNotFoundRpcError, ResourceUnavailableRpcError, SwitchChainError, TransactionRejectedRpcError, UnauthorizedProviderError, UnknownBundleIdError, UnknownRpcError, UnsupportedChainIdError, UnsupportedNonOptionalCapabilityError, UnsupportedProviderMethodError, UserRejectedRequestError, WalletConnectSessionSettlementError, } from '../errors/rpc.js';\nimport { getAbortError, isAbortError, } from '../errors/utils.js';\nimport { withDedupe } from './promise/withDedupe.js';\nimport { withRetry } from './promise/withRetry.js';\nimport { stringify } from './stringify.js';\nexport function buildRequest(request, options = {}) {\n return async (args, overrideOptions = {}) => {\n const { dedupe = false, methods, retryDelay = 150, retryCount = 3, signal, uid, } = {\n ...options,\n ...overrideOptions,\n };\n const { method } = args;\n if (methods?.exclude?.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n });\n if (methods?.include && !methods.include.includes(method))\n throw new MethodNotSupportedRpcError(new Error('method not supported'), {\n method,\n });\n if (signal?.aborted)\n throw getAbortError(signal);\n const requestId = dedupe\n ? hashString(`${uid}.${stringify(args)}`)\n : undefined;\n return withDedupe(() => withRetry(async () => {\n try {\n return await request(args, signal ? { signal } : undefined);\n }\n catch (err_) {\n if (signal?.aborted)\n throw getAbortError(signal);\n if (isAbortError(err_))\n throw err_;\n const err = err_;\n switch (err.code) {\n // -32700\n case ParseRpcError.code:\n throw new ParseRpcError(err);\n // -32600\n case InvalidRequestRpcError.code:\n throw new InvalidRequestRpcError(err);\n // -32601\n case MethodNotFoundRpcError.code:\n throw new MethodNotFoundRpcError(err, { method: args.method });\n // -32602\n case InvalidParamsRpcError.code:\n throw new InvalidParamsRpcError(err);\n // -32603\n case InternalRpcError.code:\n throw new InternalRpcError(err);\n // -32000\n case InvalidInputRpcError.code:\n throw new InvalidInputRpcError(err);\n // -32001\n case ResourceNotFoundRpcError.code:\n throw new ResourceNotFoundRpcError(err);\n // -32002\n case ResourceUnavailableRpcError.code:\n throw new ResourceUnavailableRpcError(err);\n // -32003\n case TransactionRejectedRpcError.code:\n throw new TransactionRejectedRpcError(err);\n // -32004\n case MethodNotSupportedRpcError.code:\n throw new MethodNotSupportedRpcError(err, {\n method: args.method,\n });\n // -32005\n case LimitExceededRpcError.code:\n throw new LimitExceededRpcError(err);\n // -32006\n case JsonRpcVersionUnsupportedError.code:\n throw new JsonRpcVersionUnsupportedError(err);\n // 4001\n case UserRejectedRequestError.code:\n throw new UserRejectedRequestError(err);\n // 4100\n case UnauthorizedProviderError.code:\n throw new UnauthorizedProviderError(err);\n // 4200\n case UnsupportedProviderMethodError.code:\n throw new UnsupportedProviderMethodError(err);\n // 4900\n case ProviderDisconnectedError.code:\n throw new ProviderDisconnectedError(err);\n // 4901\n case ChainDisconnectedError.code:\n throw new ChainDisconnectedError(err);\n // 4902\n case SwitchChainError.code:\n throw new SwitchChainError(err);\n // 5700\n case UnsupportedNonOptionalCapabilityError.code:\n throw new UnsupportedNonOptionalCapabilityError(err);\n // 5710\n case UnsupportedChainIdError.code:\n throw new UnsupportedChainIdError(err);\n // 5720\n case DuplicateIdError.code:\n throw new DuplicateIdError(err);\n // 5730\n case UnknownBundleIdError.code:\n throw new UnknownBundleIdError(err);\n // 5740\n case BundleTooLargeError.code:\n throw new BundleTooLargeError(err);\n // 5750\n case AtomicReadyWalletRejectedUpgradeError.code:\n throw new AtomicReadyWalletRejectedUpgradeError(err);\n // 5760\n case AtomicityNotSupportedError.code:\n throw new AtomicityNotSupportedError(err);\n // CAIP-25: User Rejected Error\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes#rejected-caip-25\n case 5000:\n throw new UserRejectedRequestError(err);\n // WalletConnect: Session Settlement Failed\n // https://docs.walletconnect.com/2.0/specs/clients/sign/error-codes\n case WalletConnectSessionSettlementError.code:\n throw new WalletConnectSessionSettlementError(err);\n default:\n if (err_ instanceof BaseError)\n throw err_;\n throw new UnknownRpcError(err);\n }\n }\n }, {\n delay: ({ count, error }) => {\n // If we find a Retry-After header, let's retry after the given time.\n if (error && error instanceof HttpRequestError) {\n const retryAfter = error?.headers?.get('Retry-After');\n if (retryAfter?.match(/\\d/))\n return Number.parseInt(retryAfter, 10) * 1000;\n }\n // Otherwise, let's retry with an exponential backoff.\n return ~~(1 << count) * retryDelay;\n },\n retryCount,\n signal,\n shouldRetry: ({ error }) => shouldRetry(error),\n }), { enabled: dedupe, id: requestId });\n };\n}\n/** @internal */\nexport function shouldRetry(error) {\n if (isAbortError(error))\n return false;\n if ('code' in error && typeof error.code === 'number') {\n if (error.code === -1)\n return true; // Unknown error\n if (error.code === LimitExceededRpcError.code)\n return true;\n if (error.code === InternalRpcError.code)\n return true;\n // Too Many Requests — some providers (e.g. Alchemy in batch mode) return\n // HTTP 200 with a JSON-RPC body of `{ code: 429 }` instead of an HTTP 429,\n // so we need to handle this code in addition to the HTTP status check below.\n if (error.code === 429)\n return true;\n return false;\n }\n if (error instanceof HttpRequestError && error.status) {\n // Forbidden\n if (error.status === 403)\n return true;\n // Request Timeout\n if (error.status === 408)\n return true;\n // Request Entity Too Large\n if (error.status === 413)\n return true;\n // Too Many Requests\n if (error.status === 429)\n return true;\n // Internal Server Error\n if (error.status === 500)\n return true;\n // Bad Gateway\n if (error.status === 502)\n return true;\n // Service Unavailable\n if (error.status === 503)\n return true;\n // Gateway Timeout\n if (error.status === 504)\n return true;\n return false;\n }\n return true;\n}\n/** @internal cyrb53 – fast, non-cryptographic 53-bit string hash */\nfunction hashString(str, seed = 0) {\n let h1 = 0xdeadbeef ^ seed;\n let h2 = 0x41c6ce57 ^ seed;\n for (let i = 0; i < str.length; i++) {\n const ch = str.charCodeAt(i);\n h1 = Math.imul(h1 ^ ch, 2654435761);\n h2 = Math.imul(h2 ^ ch, 1597334677);\n }\n h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507);\n h1 ^= Math.imul(h2 ^ (h2 >>> 16), 3266489909);\n h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507);\n h2 ^= Math.imul(h1 ^ (h1 >>> 16), 3266489909);\n return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);\n}\n//# sourceMappingURL=buildRequest.js.map","export function defineChain(chain) {\n const chainInstance = {\n formatters: undefined,\n fees: undefined,\n serializers: undefined,\n ...chain,\n };\n function extend(base) {\n return (fnOrExtended) => {\n const properties = (typeof fnOrExtended === 'function' ? fnOrExtended(base) : fnOrExtended);\n const combined = { ...base, ...properties };\n return Object.assign(combined, { extend: extend(combined) });\n };\n }\n return Object.assign(chainInstance, {\n extend: extend(chainInstance),\n });\n}\nexport function extendSchema() {\n return {};\n}\n//# sourceMappingURL=defineChain.js.map","function createIdStore() {\n return {\n current: 0,\n take() {\n return this.current++;\n },\n reset() {\n this.current = 0;\n },\n };\n}\nexport const idCache = /*#__PURE__*/ createIdStore();\n//# sourceMappingURL=id.js.map","import { HttpRequestError, ResponseBodyTooLargeError, TimeoutError, } from '../../errors/request.js';\nimport { getAbortError, isAbortError, } from '../../errors/utils.js';\nimport { withTimeout, } from '../promise/withTimeout.js';\nimport { stringify } from '../stringify.js';\nimport { idCache } from './id.js';\nconst defaultMaxResponseBodySize = 10_485_760;\nexport function getHttpRpcClient(url_, options = {}) {\n const { url, headers: headers_url } = parseUrl(url_);\n return {\n async request(params) {\n const { body, fetchFn = options.fetchFn ?? fetch, maxResponseBodySize = options.maxResponseBodySize ??\n defaultMaxResponseBodySize, onRequest = options.onRequest, onResponse = options.onResponse, timeout = options.timeout ?? 10_000, } = params;\n const fetchOptions = {\n ...(options.fetchOptions ?? {}),\n ...(params.fetchOptions ?? {}),\n };\n const { headers, method, signal: signal_ } = fetchOptions;\n try {\n const response = await withTimeout(async ({ signal }) => {\n const init = {\n ...fetchOptions,\n body: Array.isArray(body)\n ? stringify(body.map((body) => ({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n })))\n : stringify({\n jsonrpc: '2.0',\n id: body.id ?? idCache.take(),\n ...body,\n }),\n headers: {\n ...headers_url,\n 'Content-Type': 'application/json',\n ...headers,\n },\n method: method || 'POST',\n signal: signal_ || (timeout > 0 ? signal : null),\n };\n const request = new Request(url, init);\n const args = (await onRequest?.(request, init)) ?? { ...init, url };\n const response = await fetchFn(args.url ?? url, args);\n return response;\n }, {\n errorInstance: new TimeoutError({ body, url }),\n timeout,\n signal: true,\n });\n if (onResponse)\n await onResponse(response);\n let data;\n const responseBody = await readResponseBody(response, {\n maxResponseBodySize,\n });\n if (response.headers.get('Content-Type')?.startsWith('application/json'))\n data = JSON.parse(responseBody);\n else {\n data = responseBody;\n try {\n data = JSON.parse(data || '{}');\n }\n catch (err) {\n if (response.ok)\n throw err;\n data = { error: data };\n }\n }\n if (!response.ok) {\n // If the response body contains a valid JSON-RPC error, return it\n // so it flows through the normal RPC error handling pipeline.\n if (typeof data.error?.code === 'number' &&\n typeof data.error?.message === 'string')\n return data;\n throw new HttpRequestError({\n body,\n details: stringify(data.error) || response.statusText,\n headers: response.headers,\n status: response.status,\n url,\n });\n }\n return data;\n }\n catch (err) {\n if (signal_?.aborted)\n throw getAbortError(signal_);\n if (isAbortError(err))\n throw err;\n if (err instanceof HttpRequestError)\n throw err;\n if (err instanceof ResponseBodyTooLargeError)\n throw err;\n if (err instanceof TimeoutError)\n throw err;\n throw new HttpRequestError({\n body,\n cause: err,\n url,\n });\n }\n },\n };\n}\nasync function readResponseBody(response, { maxResponseBodySize }) {\n if (maxResponseBodySize === false)\n return response.text();\n const contentLength = response.headers.get('Content-Length');\n if (contentLength) {\n const size = Number(contentLength);\n if (size > maxResponseBodySize)\n throw new ResponseBodyTooLargeError({\n maxSize: maxResponseBodySize,\n size,\n });\n }\n if (!response.body) {\n const body = await response.text();\n const size = new TextEncoder().encode(body).length;\n if (size > maxResponseBodySize)\n throw new ResponseBodyTooLargeError({\n maxSize: maxResponseBodySize,\n size,\n });\n return body;\n }\n const reader = response.body.getReader();\n const decoder = new TextDecoder();\n let body = '';\n let size = 0;\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done)\n break;\n size += value.byteLength;\n if (size > maxResponseBodySize) {\n await reader.cancel();\n throw new ResponseBodyTooLargeError({\n maxSize: maxResponseBodySize,\n size,\n });\n }\n body += decoder.decode(value, { stream: true });\n }\n body += decoder.decode();\n return body;\n }\n finally {\n reader.releaseLock();\n }\n}\n/** @internal */\nexport function parseUrl(url_) {\n try {\n const url = new URL(url_);\n const result = (() => {\n // Handle Basic authentication credentials\n if (url.username) {\n const credentials = `${decodeURIComponent(url.username)}:${decodeURIComponent(url.password)}`;\n url.username = '';\n url.password = '';\n return {\n url: url.toString(),\n headers: { Authorization: `Basic ${btoa(credentials)}` },\n };\n }\n return;\n })();\n return { url: url.toString(), ...result };\n }\n catch {\n return { url: url_ };\n }\n}\n//# sourceMappingURL=http.js.map","import { isAbortError } from '../../errors/utils.js';\nexport function withTimeout(fn, { errorInstance = new Error('timed out'), timeout, signal, }) {\n return new Promise((resolve, reject) => {\n ;\n (async () => {\n let timeoutId;\n const controller = new AbortController();\n try {\n if (timeout > 0) {\n timeoutId = setTimeout(() => {\n if (signal) {\n controller.abort();\n }\n else {\n reject(errorInstance);\n }\n }, timeout); // need to cast because bun globals.d.ts overrides @types/node\n }\n resolve(await fn({ signal: controller?.signal || null }));\n }\n catch (err) {\n if (controller?.signal.aborted && isAbortError(err)) {\n reject(errorInstance);\n return;\n }\n reject(err);\n }\n finally {\n clearTimeout(timeoutId);\n }\n })();\n });\n}\n//# sourceMappingURL=withTimeout.js.map","import { BaseError } from './base.js';\nexport class UrlRequiredError extends BaseError {\n constructor() {\n super('No URL was provided to the Transport. Please provide a valid RPC URL to the Transport.', {\n docsPath: '/docs/clients/intro',\n name: 'UrlRequiredError',\n });\n }\n}\n//# sourceMappingURL=transport.js.map","import { RpcRequestError } from '../../errors/request.js';\nimport { UrlRequiredError, } from '../../errors/transport.js';\nimport { createBatchScheduler } from '../../utils/promise/createBatchScheduler.js';\nimport { getHttpRpcClient, } from '../../utils/rpc/http.js';\nimport { createTransport, } from './createTransport.js';\nlet signalId = 0;\nconst signalIds = new WeakMap();\nfunction getSignalId(signal) {\n if (!signal)\n return 'default';\n const id = signalIds.get(signal);\n if (id !== undefined)\n return id;\n const nextId = signalId++;\n signalIds.set(signal, nextId);\n return nextId;\n}\n/**\n * @description Creates a HTTP transport that connects to a JSON-RPC API.\n */\nexport function http(\n/** URL of the JSON-RPC API. Defaults to the chain's public RPC URL. */\nurl, config = {}) {\n const { batch, fetchFn, fetchOptions, key = 'http', maxResponseBodySize, methods, name = 'HTTP JSON-RPC', onFetchRequest, onFetchResponse, retryDelay, raw, } = config;\n return ({ chain, retryCount: retryCount_, timeout: timeout_ }) => {\n const { batchSize = 1000, wait = 0 } = typeof batch === 'object' ? batch : {};\n const retryCount = config.retryCount ?? retryCount_;\n const timeout = timeout_ ?? config.timeout ?? 10_000;\n const url_ = url || chain?.rpcUrls.default.http[0];\n if (!url_)\n throw new UrlRequiredError();\n const rpcClient = getHttpRpcClient(url_, {\n fetchFn,\n fetchOptions,\n maxResponseBodySize,\n onRequest: onFetchRequest,\n onResponse: onFetchResponse,\n timeout,\n });\n return createTransport({\n key,\n methods,\n name,\n async request({ method, params }, options) {\n const body = { method, params };\n const fetchOptions = options?.signal\n ? { signal: options.signal }\n : undefined;\n const { schedule } = createBatchScheduler({\n id: `${url_}.${getSignalId(options?.signal)}`,\n wait,\n shouldSplitBatch(requests) {\n return requests.length > batchSize;\n },\n fn: (body) => rpcClient.request({\n body,\n fetchOptions,\n }),\n sort: (a, b) => a.id - b.id,\n });\n const fn = async (body) => batch\n ? schedule(body)\n : [\n await rpcClient.request({\n body,\n fetchOptions,\n }),\n ];\n const [{ error, result }] = await fn(body);\n if (raw)\n return { error, result };\n if (error)\n throw new RpcRequestError({\n body,\n error,\n url: url_,\n });\n return result;\n },\n retryCount,\n retryDelay,\n timeout,\n type: 'http',\n }, {\n fetchOptions,\n url: url_,\n });\n };\n}\n//# sourceMappingURL=http.js.map","import { buildRequest } from '../../utils/buildRequest.js';\nimport { uid as uid_ } from '../../utils/uid.js';\n/**\n * @description Creates an transport intended to be used with a client.\n */\nexport function createTransport({ key, methods, name, request, retryCount = 3, retryDelay = 150, timeout, type, }, value) {\n const uid = uid_();\n return {\n config: {\n key,\n methods,\n name,\n request,\n retryCount,\n retryDelay,\n timeout,\n type,\n },\n request: buildRequest(request, { methods, retryCount, retryDelay, uid }),\n value,\n };\n}\n//# sourceMappingURL=createTransport.js.map","import { defineChain } from '../../utils/chain/defineChain.js';\nexport const mainnet = /*#__PURE__*/ defineChain({\n id: 1,\n name: 'Ethereum',\n nativeCurrency: { name: 'Ether', symbol: 'ETH', decimals: 18 },\n blockTime: 12_000,\n rpcUrls: {\n default: {\n http: ['https://ethereum.reth.rs/rpc'],\n },\n },\n blockExplorers: {\n default: {\n name: 'Etherscan',\n url: 'https://etherscan.io',\n apiUrl: 'https://api.etherscan.io/api',\n },\n },\n contracts: {\n ensUniversalResolver: {\n address: '0xeeeeeeee14d718c2b47d9923deab1335e144eeee',\n blockCreated: 23_085_558,\n },\n multicall3: {\n address: '0xca11bde05977b3631167028862be2a173976ca11',\n blockCreated: 14_353_601,\n },\n },\n});\n//# sourceMappingURL=mainnet.js.map","// created 2025-09-14T17:56:24.099Z\n// compressed base64-encoded blob for include-ens data\n// source: https://github.com/adraffy/ens-normalize.js/blob/main/src/make.js\n// see: https://github.com/adraffy/ens-normalize.js#security\n// SHA-256: 92cbf3a1af3c3c0a91aee0dc542072775f4ebbbc526a84189a12da2d56f5accd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81zpbJV9SuqZ6Pd1ge0Zz2RFHeCdV5CLPftH9V5o9+VzFu4R0QeumqDwUhXn3IyYotdJnxr1l3BqWnQVAeDBEOtPyJQx1q5+mODiClXtYeBLTWtsJ42AMBcf/IFIhpfhYO08hsg0Ik+DpQFNOKReK3o3cudkxWX0soPtI5eSFOA6yNylS+IQjrQtYQ/5s4UcixJfokumBUjpH9ofSjUTwPCapGFndfqqG5IHeMMvfg+88SXm7bNyjk6pGKzL+WxDAdqKtQ72WWVbOk3I+ueGuammmB2pvFZvqIcU/lvW3n9+r2lycnQLE4OX9R1jIgW4cDjJ3v8dAa66mVcfC7ptCr5io6mCaA9qI9T9FFWqo1ZAaMxgxAu8aXqmaOYryMND2sTUfoHvxcYK7hEiJhCLYFDx3PBhE97c2a0ub1/ePJcyJOqr7UaTAPTJ+xvZtjb/40sloY1ltRnTkWILmIP2b7S3AdXCR+YiArMUHwdncpjpyDGfzqGOUoAuaamWzAMacQtb34/M32FEgR5lUEf8fRzFrZUhzQj0fR7/6gdzdnVVvcSneLmtqJ930VCCDORY8CVdQWdo/S3PNkX3pQsPVKWIYGAMrFZoq8bQ/OJBDSXP7KSBdL3QN0Zqd393p6VFc7DnlnFiN00SY5Nux7yadeIM0Upl2rVsu8/VAI';\nconst FENCED = new Map([[8217,\"apostrophe\"],[8260,\"fraction slash\"],[12539,\"middle dot\"]]);\nconst NSM_MAX = 4;\n\nfunction decode_arithmetic(bytes) {\r\n\tlet pos = 0;\r\n\tfunction u16() { return (bytes[pos++] << 8) | bytes[pos++]; }\r\n\t\r\n\t// decode the frequency table\r\n\tlet symbol_count = u16();\r\n\tlet total = 1;\r\n\tlet acc = [0, 1]; // first symbol has frequency 1\r\n\tfor (let i = 1; i < symbol_count; i++) {\r\n\t\tacc.push(total += u16());\r\n\t}\r\n\r\n\t// skip the sized-payload that the last 3 symbols index into\r\n\tlet skip = u16();\r\n\tlet pos_payload = pos;\r\n\tpos += skip;\r\n\r\n\tlet read_width = 0;\r\n\tlet read_buffer = 0; \r\n\tfunction read_bit() {\r\n\t\tif (read_width == 0) {\r\n\t\t\t// this will read beyond end of buffer\r\n\t\t\t// but (undefined|0) => zero pad\r\n\t\t\tread_buffer = (read_buffer << 8) | bytes[pos++];\r\n\t\t\tread_width = 8;\r\n\t\t}\r\n\t\treturn (read_buffer >> --read_width) & 1;\r\n\t}\r\n\r\n\tconst N = 31;\r\n\tconst FULL = 2**N;\r\n\tconst HALF = FULL >>> 1;\r\n\tconst QRTR = HALF >> 1;\r\n\tconst MASK = FULL - 1;\r\n\r\n\t// fill register\r\n\tlet register = 0;\r\n\tfor (let i = 0; i < N; i++) register = (register << 1) | read_bit();\r\n\r\n\tlet symbols = [];\r\n\tlet low = 0;\r\n\tlet range = FULL; // treat like a float\r\n\twhile (true) {\r\n\t\tlet value = Math.floor((((register - low + 1) * total) - 1) / range);\r\n\t\tlet start = 0;\r\n\t\tlet end = symbol_count;\r\n\t\twhile (end - start > 1) { // binary search\r\n\t\t\tlet mid = (start + end) >>> 1;\r\n\t\t\tif (value < acc[mid]) {\r\n\t\t\t\tend = mid;\r\n\t\t\t} else {\r\n\t\t\t\tstart = mid;\r\n\t\t\t}\r\n\t\t}\r\n\t\tif (start == 0) break; // first symbol is end mark\r\n\t\tsymbols.push(start);\r\n\t\tlet a = low + Math.floor(range * acc[start] / total);\r\n\t\tlet b = low + Math.floor(range * acc[start+1] / total) - 1;\r\n\t\twhile (((a ^ b) & HALF) == 0) {\r\n\t\t\tregister = (register << 1) & MASK | read_bit();\r\n\t\t\ta = (a << 1) & MASK;\r\n\t\t\tb = (b << 1) & MASK | 1;\r\n\t\t}\r\n\t\twhile (a & ~b & QRTR) {\r\n\t\t\tregister = (register & HALF) | ((register << 1) & (MASK >>> 1)) | read_bit();\r\n\t\t\ta = (a << 1) ^ HALF;\r\n\t\t\tb = ((b ^ HALF) << 1) | HALF | 1;\r\n\t\t}\r\n\t\tlow = a;\r\n\t\trange = 1 + b - a;\r\n\t}\r\n\tlet offset = symbol_count - 4;\r\n\treturn symbols.map(x => { // index into payload\r\n\t\tswitch (x - offset) {\r\n\t\t\tcase 3: return offset + 0x10100 + ((bytes[pos_payload++] << 16) | (bytes[pos_payload++] << 8) | bytes[pos_payload++]);\r\n\t\t\tcase 2: return offset + 0x100 + ((bytes[pos_payload++] << 8) | bytes[pos_payload++]);\r\n\t\t\tcase 1: return offset + bytes[pos_payload++];\r\n\t\t\tdefault: return x - 1;\r\n\t\t}\r\n\t});\r\n}\t\r\n\r\n// returns an iterator which returns the next symbol\r\nfunction read_payload(v) {\r\n\tlet pos = 0;\r\n\treturn () => v[pos++];\r\n}\r\nfunction read_compressed_payload(s) {\r\n\treturn read_payload(decode_arithmetic(unsafe_atob(s)));\r\n}\r\n\r\n// unsafe in the sense:\r\n// expected well-formed Base64 w/o padding \r\n// 20220922: added for https://github.com/adraffy/ens-normalize.js/issues/4\r\nfunction unsafe_atob(s) {\r\n\tlet lookup = [];\r\n\t[...'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'].forEach((c, i) => lookup[c.charCodeAt(0)] = i);\r\n\tlet n = s.length;\r\n\tlet ret = new Uint8Array((6 * n) >> 3);\r\n\tfor (let i = 0, pos = 0, width = 0, carry = 0; i < n; i++) {\r\n\t\tcarry = (carry << 6) | lookup[s.charCodeAt(i)];\r\n\t\twidth += 6;\r\n\t\tif (width >= 8) {\r\n\t\t\tret[pos++] = (carry >> (width -= 8));\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n// eg. [0,1,2,3...] => [0,-1,1,-2,...]\r\nfunction signed(i) { \r\n\treturn (i & 1) ? (~i >> 1) : (i >> 1);\r\n}\r\n\r\nfunction read_deltas(n, next) {\r\n\tlet v = Array(n);\r\n\tfor (let i = 0, x = 0; i < n; i++) v[i] = x += signed(next());\r\n\treturn v;\r\n}\r\n\r\n// [123][5] => [0 3] [1 1] [0 0]\r\nfunction read_sorted(next, prev = 0) {\r\n\tlet ret = [];\r\n\twhile (true) {\r\n\t\tlet x = next();\r\n\t\tlet n = next();\r\n\t\tif (!n) break;\r\n\t\tprev += x;\r\n\t\tfor (let i = 0; i < n; i++) {\r\n\t\t\tret.push(prev + i);\r\n\t\t}\r\n\t\tprev += n + 1;\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nfunction read_sorted_arrays(next) {\r\n\treturn read_array_while(() => { \r\n\t\tlet v = read_sorted(next);\r\n\t\tif (v.length) return v;\r\n\t});\r\n}\r\n\r\n// returns map of x => ys\r\nfunction read_mapped(next) {\r\n\tlet ret = [];\r\n\twhile (true) {\r\n\t\tlet w = next();\r\n\t\tif (w == 0) break;\r\n\t\tret.push(read_linear_table(w, next));\r\n\t}\r\n\twhile (true) {\r\n\t\tlet w = next() - 1;\r\n\t\tif (w < 0) break;\r\n\t\tret.push(read_replacement_table(w, next));\r\n\t}\r\n\treturn ret.flat();\r\n}\r\n\r\n// read until next is falsy\r\n// return array of read values\r\nfunction read_array_while(next) {\r\n\tlet v = [];\r\n\twhile (true) {\r\n\t\tlet x = next(v.length);\r\n\t\tif (!x) break;\r\n\t\tv.push(x);\r\n\t}\r\n\treturn v;\r\n}\r\n\r\n// read w columns of length n\r\n// return as n rows of length w\r\nfunction read_transposed(n, w, next) {\r\n\tlet m = Array(n).fill().map(() => []);\r\n\tfor (let i = 0; i < w; i++) {\r\n\t\tread_deltas(n, next).forEach((x, j) => m[j].push(x));\r\n\t}\r\n\treturn m;\r\n}\r\n \r\n// returns [[x, ys], [x+dx, ys+dy], [x+2*dx, ys+2*dy], ...]\r\n// where dx/dy = steps, n = run size, w = length of y\r\nfunction read_linear_table(w, next) {\r\n\tlet dx = 1 + next();\r\n\tlet dy = next();\r\n\tlet vN = read_array_while(next);\r\n\tlet m = read_transposed(vN.length, 1+w, next);\r\n\treturn m.flatMap((v, i) => {\r\n\t\tlet [x, ...ys] = v;\r\n\t\treturn Array(vN[i]).fill().map((_, j) => {\r\n\t\t\tlet j_dy = j * dy;\r\n\t\t\treturn [x + j * dx, ys.map(y => y + j_dy)];\r\n\t\t});\r\n\t});\r\n}\r\n\r\n// return [[x, ys...], ...]\r\n// where w = length of y\r\nfunction read_replacement_table(w, next) { \r\n\tlet n = 1 + next();\r\n\tlet m = read_transposed(n, 1+w, next);\r\n\treturn m.map(v => [v[0], v.slice(1)]);\r\n}\r\n\r\n\r\nfunction read_trie(next) {\r\n\tlet ret = [];\r\n\tlet sorted = read_sorted(next); \r\n\texpand(decode([]), []);\r\n\treturn ret; // not sorted\r\n\tfunction decode(Q) { // characters that lead into this node\r\n\t\tlet S = next(); // state: valid, save, check\r\n\t\tlet B = read_array_while(() => { // buckets leading to new nodes\r\n\t\t\tlet cps = read_sorted(next).map(i => sorted[i]);\r\n\t\t\tif (cps.length) return decode(cps);\r\n\t\t});\r\n\t\treturn {S, B, Q};\r\n\t}\r\n\tfunction expand({S, B}, cps, saved) {\r\n\t\tif (S & 4 && saved === cps[cps.length-1]) return;\r\n\t\tif (S & 2) saved = cps[cps.length-1];\r\n\t\tif (S & 1) ret.push(cps); \r\n\t\tfor (let br of B) {\r\n\t\t\tfor (let cp of br.Q) {\r\n\t\t\t\texpand(br, [...cps, cp], saved);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\n\nfunction hex_cp(cp) {\r\n\treturn cp.toString(16).toUpperCase().padStart(2, '0');\r\n}\r\n\r\nfunction quote_cp(cp) {\r\n\treturn `{${hex_cp(cp)}}`; // raffy convention: like \"\\u{X}\" w/o the \"\\u\"\r\n}\r\n\r\n/*\r\nexport function explode_cp(s) {\r\n\treturn [...s].map(c => c.codePointAt(0));\r\n}\r\n*/\r\nfunction explode_cp(s) { // this is about 2x faster\r\n\tlet cps = [];\r\n\tfor (let pos = 0, len = s.length; pos < len; ) {\r\n\t\tlet cp = s.codePointAt(pos);\r\n\t\tpos += cp < 0x10000 ? 1 : 2;\r\n\t\tcps.push(cp);\r\n\t}\r\n\treturn cps;\r\n}\r\n\r\nfunction str_from_cps(cps) {\r\n\tconst chunk = 4096;\r\n\tlet len = cps.length;\r\n\tif (len < chunk) return String.fromCodePoint(...cps);\r\n\tlet buf = [];\r\n\tfor (let i = 0; i < len; ) {\r\n\t\tbuf.push(String.fromCodePoint(...cps.slice(i, i += chunk)));\r\n\t}\r\n\treturn buf.join('');\r\n}\r\n\r\nfunction compare_arrays(a, b) {\r\n\tlet n = a.length;\r\n\tlet c = n - b.length;\r\n\tfor (let i = 0; c == 0 && i < n; i++) c = a[i] - b[i];\r\n\treturn c;\r\n}\r\n\r\nfunction array_replace(v, a, b) {\r\n\tlet prev = 0;\r\n\twhile (true) {\r\n\t\tlet next = v.indexOf(a, prev);\r\n\t\tif (next < 0) break;\r\n\t\tv[next] = b; \r\n\t\tprev = next + 1;\r\n\t}\r\n}\n\n// created 2025-09-14T17:56:24.099Z\n// compressed base64-encoded blob for include-nf data\n// source: https://github.com/adraffy/ens-normalize.js/blob/main/src/make.js\n// see: https://github.com/adraffy/ens-normalize.js#security\n// SHA-256: 9ef43cc7215aa7a53e4ed9afa3b4f2f8ce00a2c708b9eb96aa409ae6fa3fb6af\nvar COMPRESSED = 'AEUDWAHSCGYATwDVADIAdgAiADQAFAAtABQAIQAPACcADQASAAsAGQAJABIACQARAAUACwAFAAwABQAQAAMABwAEAAoABQAJAAIACgABAAQAFAALAAIACwABAAIAAQAHAAMAAwAEAAsADAAMAAwACwANAA0AAwAKAAkABAAdAAYAZwDTAecDNACxCmIB8xhZAqfoC190UGcThgBurwf7PT09Pb09AjgJum8OjDllxHYUKXAPxzq6tABAxgK8ysUvWAgMPT09PT09PSs6LT2HcgWXWwFLoSMEEEl5RFVMKvO0XQ8ExDdJMnIgPi89uj00MsvBXxEPAGPCDwBnQKoEbwRwBHEEcgRzBHQEdQR2BHcEeAR6BHsEfAR+BIAEgfndBQoBYgULAWIFDAFiBNcE2ATZBRAFEQUvBdALFAsVDPcNBw13DYcOMA4xDjMB4BllHI0B2grbAMDpHLkQ7QHVAPRNQQFnGRUEg0yE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nbGfc8s+qcr3zyzyHp1aJg+jxTF4kD1ry5Wauv5V3xnOGwTFecNzXSLHBW20/pCQjk4uorD0plIhMSTc79+/r4RKPClRYTBYex1Ob5crtfvRQBBv6re/6FhtCqtduag67glqRA77/3ulblh9YRtMdDxkCyJDeNnAuCLPQFmdRRWJtH20Z8DstfJf+5oj5SSB64d0iF5/Ya4KfTWxfivj9Ap2/zbYaTo/1gO3tM6RYsCZharMBFr7Fm61mLSrQnEI4OF1gbVS4k/JE9UotOrnLJZuswoWodCSV8zbybkJSVIP7n8UaE9xCR39rJZmf27HOAPVOGc9pdkQUcRrI0qyVF9Z3j1RHDbxIfwbWzmPVjwIdPJvtmBYwEQIUsIW1S939hcVikK00ozPRI02cqhzVUNzpOxVdrwRPvlh1aIOf0xFEqD3YkGnCnFah/cFN3J2gB7N+bZSGawwkKFu1tpQMrp1W+27YNkyT0TpcFpTqgOqqLabrgcCUPxh97mREOGy4xItzQ9xSl6rq+8BZsHcrQFReS+QeMxJ3P6CnL9EP/eOLDjumLhvrcQrpPiknsofbzBv9gTP0lU+TIVwE6E7CcKfT36q+ZiEOHJ9ayf0dyUJLezAb2M8aNHwd0+OJmsVgTzRWA';\n\n// https://unicode.org/reports/tr15/\r\n// for reference implementation\r\n// see: /derive/nf.js\r\n\r\n\r\n// algorithmic hangul\r\n// https://www.unicode.org/versions/Unicode15.0.0/ch03.pdf (page 144)\r\nconst S0 = 0xAC00;\r\nconst L0 = 0x1100;\r\nconst V0 = 0x1161;\r\nconst T0 = 0x11A7;\r\nconst L_COUNT = 19;\r\nconst V_COUNT = 21;\r\nconst T_COUNT = 28;\r\nconst N_COUNT = V_COUNT * T_COUNT;\r\nconst S_COUNT = L_COUNT * N_COUNT;\r\nconst S1 = S0 + S_COUNT;\r\nconst L1 = L0 + L_COUNT;\r\nconst V1 = V0 + V_COUNT;\r\nconst T1 = T0 + T_COUNT;\r\n\r\nfunction unpack_cc(packed) {\r\n\treturn (packed >> 24) & 0xFF;\r\n}\r\nfunction unpack_cp(packed) {\r\n\treturn packed & 0xFFFFFF;\r\n}\r\n\r\nlet SHIFTED_RANK, EXCLUSIONS, DECOMP, RECOMP;\r\n\r\n// export function nf_deinit() {\r\n// \tif (!SHIFTED_RANK) return;\r\n// \tSHIFTED_RANK = EXCLUSIONS = DECOMP = RECOMP = undefined;\r\n// }\r\n\r\nfunction init$1() {\r\n\t//console.time('nf');\r\n\tlet r = read_compressed_payload(COMPRESSED);\r\n\tSHIFTED_RANK = new Map(read_sorted_arrays(r).flatMap((v, i) => v.map(x => [x, (i+1) << 24]))); // pre-shifted\r\n\tEXCLUSIONS = new Set(read_sorted(r));\r\n\tDECOMP = new Map();\r\n\tRECOMP = new Map();\r\n\tfor (let [cp, cps] of read_mapped(r)) {\r\n\t\tif (!EXCLUSIONS.has(cp) && cps.length == 2) {\r\n\t\t\tlet [a, b] = cps;\r\n\t\t\tlet bucket = RECOMP.get(a);\r\n\t\t\tif (!bucket) {\r\n\t\t\t\tbucket = new Map();\r\n\t\t\t\tRECOMP.set(a, bucket);\r\n\t\t\t}\r\n\t\t\tbucket.set(b, cp);\r\n\t\t}\r\n\t\tDECOMP.set(cp, cps.reverse()); // stored reversed\r\n\t}\r\n\t//console.timeEnd('nf');\r\n\t// 20230905: 11ms\r\n}\r\n\r\nfunction is_hangul(cp) {\r\n\treturn cp >= S0 && cp < S1;\r\n}\r\n\r\nfunction compose_pair(a, b) {\r\n\tif (a >= L0 && a < L1 && b >= V0 && b < V1) {\r\n\t\treturn S0 + (a - L0) * N_COUNT + (b - V0) * T_COUNT;\r\n\t} else if (is_hangul(a) && b > T0 && b < T1 && (a - S0) % T_COUNT == 0) {\r\n\t\treturn a + (b - T0);\r\n\t} else {\r\n\t\tlet recomp = RECOMP.get(a);\r\n\t\tif (recomp) {\r\n\t\t\trecomp = recomp.get(b);\r\n\t\t\tif (recomp) {\r\n\t\t\t\treturn recomp;\r\n\t\t\t}\r\n\t\t}\r\n\t\treturn -1;\r\n\t}\r\n}\r\n\r\nfunction decomposed(cps) {\r\n\tif (!SHIFTED_RANK) init$1();\r\n\tlet ret = [];\r\n\tlet buf = [];\r\n\tlet check_order = false;\r\n\tfunction add(cp) {\r\n\t\tlet cc = SHIFTED_RANK.get(cp);\r\n\t\tif (cc) {\r\n\t\t\tcheck_order = true;\r\n\t\t\tcp |= cc;\r\n\t\t}\r\n\t\tret.push(cp);\r\n\t}\r\n\tfor (let cp of cps) {\r\n\t\twhile (true) {\r\n\t\t\tif (cp < 0x80) {\r\n\t\t\t\tret.push(cp);\r\n\t\t\t} else if (is_hangul(cp)) {\r\n\t\t\t\tlet s_index = cp - S0;\r\n\t\t\t\tlet l_index = s_index / N_COUNT | 0;\r\n\t\t\t\tlet v_index = (s_index % N_COUNT) / T_COUNT | 0;\r\n\t\t\t\tlet t_index = s_index % T_COUNT;\r\n\t\t\t\tadd(L0 + l_index);\r\n\t\t\t\tadd(V0 + v_index);\r\n\t\t\t\tif (t_index > 0) add(T0 + t_index);\r\n\t\t\t} else {\r\n\t\t\t\tlet mapped = DECOMP.get(cp);\r\n\t\t\t\tif (mapped) {\r\n\t\t\t\t\tbuf.push(...mapped);\r\n\t\t\t\t} else {\r\n\t\t\t\t\tadd(cp);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif (!buf.length) break;\r\n\t\t\tcp = buf.pop();\r\n\t\t}\r\n\t}\r\n\tif (check_order && ret.length > 1) {\r\n\t\tlet prev_cc = unpack_cc(ret[0]);\r\n\t\tfor (let i = 1; i < ret.length; i++) {\r\n\t\t\tlet cc = unpack_cc(ret[i]);\r\n\t\t\tif (cc == 0 || prev_cc <= cc) {\r\n\t\t\t\tprev_cc = cc;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\t\t\tlet j = i-1;\r\n\t\t\twhile (true) {\r\n\t\t\t\tlet tmp = ret[j+1];\r\n\t\t\t\tret[j+1] = ret[j];\r\n\t\t\t\tret[j] = tmp;\r\n\t\t\t\tif (!j) break;\r\n\t\t\t\tprev_cc = unpack_cc(ret[--j]);\r\n\t\t\t\tif (prev_cc <= cc) break;\r\n\t\t\t}\r\n\t\t\tprev_cc = unpack_cc(ret[i]);\r\n\t\t}\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nfunction composed_from_decomposed(v) {\r\n\tlet ret = [];\r\n\tlet stack = [];\r\n\tlet prev_cp = -1;\r\n\tlet prev_cc = 0;\r\n\tfor (let packed of v) {\r\n\t\tlet cc = unpack_cc(packed);\r\n\t\tlet cp = unpack_cp(packed);\r\n\t\tif (prev_cp == -1) {\r\n\t\t\tif (cc == 0) {\r\n\t\t\t\tprev_cp = cp;\r\n\t\t\t} else {\r\n\t\t\t\tret.push(cp);\r\n\t\t\t}\r\n\t\t} else if (prev_cc > 0 && prev_cc >= cc) {\r\n\t\t\tif (cc == 0) {\r\n\t\t\t\tret.push(prev_cp, ...stack);\r\n\t\t\t\tstack.length = 0;\r\n\t\t\t\tprev_cp = cp;\r\n\t\t\t} else {\r\n\t\t\t\tstack.push(cp);\r\n\t\t\t}\r\n\t\t\tprev_cc = cc;\r\n\t\t} else {\r\n\t\t\tlet composed = compose_pair(prev_cp, cp);\r\n\t\t\tif (composed >= 0) {\r\n\t\t\t\tprev_cp = composed;\r\n\t\t\t} else if (prev_cc == 0 && cc == 0) {\r\n\t\t\t\tret.push(prev_cp);\r\n\t\t\t\tprev_cp = cp;\r\n\t\t\t} else {\r\n\t\t\t\tstack.push(cp);\r\n\t\t\t\tprev_cc = cc;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (prev_cp >= 0) {\r\n\t\tret.push(prev_cp, ...stack);\t\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\n// note: cps can be iterable\r\nfunction nfd(cps) {\r\n\treturn decomposed(cps).map(unpack_cp);\r\n}\r\nfunction nfc(cps) {\r\n\treturn composed_from_decomposed(decomposed(cps));\r\n}\n\nconst HYPHEN = 0x2D;\r\nconst STOP = 0x2E;\r\nconst STOP_CH = '.';\r\nconst FE0F = 0xFE0F;\r\nconst UNIQUE_PH = 1;\r\n\r\n// 20230913: replace [...v] with Array_from(v) to avoid large spreads\r\nconst Array_from = x => Array.from(x); // Array.from.bind(Array);\r\n\r\nfunction group_has_cp(g, cp) {\r\n\t// 20230913: keep primary and secondary distinct instead of creating valid union\r\n\treturn g.P.has(cp) || g.Q.has(cp);\r\n}\r\n\r\nclass Emoji extends Array {\r\n\tget is_emoji() { return true; } // free tagging system\r\n}\r\n\r\nlet MAPPED, IGNORED, CM, NSM, ESCAPE, NFC_CHECK, GROUPS, WHOLE_VALID, WHOLE_MAP, VALID, EMOJI_LIST, EMOJI_ROOT;\r\n\r\n// export function ens_deinit() {\r\n// \tnf_deinit();\r\n// \tif (!MAPPED) return;\r\n// \tMAPPED = IGNORED = CM = NSM = ESCAPE = NFC_CHECK = GROUPS = WHOLE_VALID = WHOLE_MAP = VALID = EMOJI_LIST = EMOJI_ROOT = undefined;\r\n// }\r\n\r\nfunction init() {\r\n\tif (MAPPED) return;\r\n\t\r\n\tlet r = read_compressed_payload(COMPRESSED$1);\r\n\tconst read_sorted_array = () => read_sorted(r);\r\n\tconst read_sorted_set = () => new Set(read_sorted_array());\r\n\tconst set_add_many = (set, v) => v.forEach(x => set.add(x));\r\n\r\n\tMAPPED = new Map(read_mapped(r)); \r\n\tIGNORED = read_sorted_set(); // ignored characters are not valid, so just read raw codepoints\r\n\r\n\t/*\r\n\t// direct include from payload is smaller than the decompression code\r\n\tconst FENCED = new Map(read_array_while(() => {\r\n\t\tlet cp = r();\r\n\t\tif (cp) return [cp, read_str(r())];\r\n\t}));\r\n\t*/\r\n\t// 20230217: we still need all CM for proper error formatting\r\n\t// but norm only needs NSM subset that are potentially-valid\r\n\tCM = read_sorted_array();\r\n\tNSM = new Set(read_sorted_array().map(i => CM[i]));\r\n\tCM = new Set(CM);\r\n\t\r\n\tESCAPE = read_sorted_set(); // characters that should not be printed\r\n\tNFC_CHECK = read_sorted_set(); // only needed to illustrate ens_tokenize() transformations\r\n\r\n\tlet chunks = read_sorted_arrays(r);\r\n\tlet unrestricted = r();\r\n\t//const read_chunked = () => new Set(read_sorted_array().flatMap(i => chunks[i]).concat(read_sorted_array()));\r\n\tconst read_chunked = () => {\r\n\t\t// 20230921: build set in parts, 2x faster\r\n\t\tlet set = new Set();\r\n\t\tread_sorted_array().forEach(i => set_add_many(set, chunks[i]));\r\n\t\tset_add_many(set, read_sorted_array());\r\n\t\treturn set; \r\n\t};\r\n\tGROUPS = read_array_while(i => {\r\n\t\t// minifier property mangling seems unsafe\r\n\t\t// so these are manually renamed to single chars\r\n\t\tlet N = read_array_while(r).map(x => x+0x60);\r\n\t\tif (N.length) {\r\n\t\t\tlet R = i >= unrestricted; // unrestricted then restricted\r\n\t\t\tN[0] -= 32; // capitalize\r\n\t\t\tN = str_from_cps(N);\r\n\t\t\tif (R) N=`Restricted[${N}]`;\r\n\t\t\tlet P = read_chunked(); // primary\r\n\t\t\tlet Q = read_chunked(); // secondary\r\n\t\t\tlet M = !r(); // not-whitelisted, check for NSM\r\n\t\t\t// *** this code currently isn't needed ***\r\n\t\t\t/*\r\n\t\t\tlet V = [...P, ...Q].sort((a, b) => a-b); // derive: sorted valid\r\n\t\t\tlet M = r()-1; // number of combining mark\r\n\t\t\tif (M < 0) { // whitelisted\r\n\t\t\t\tM = new Map(read_array_while(() => {\r\n\t\t\t\t\tlet i = r();\r\n\t\t\t\t\tif (i) return [V[i-1], read_array_while(() => {\r\n\t\t\t\t\t\tlet v = read_array_while(r);\r\n\t\t\t\t\t\tif (v.length) return v.map(x => x-1);\r\n\t\t\t\t\t})];\r\n\t\t\t\t}));\r\n\t\t\t}*/\r\n\t\t\treturn {N, P, Q, M, R};\r\n\t\t}\r\n\t});\r\n\r\n\t// decode compressed wholes\r\n\tWHOLE_VALID = read_sorted_set();\r\n\tWHOLE_MAP = new Map();\r\n\tlet wholes = read_sorted_array().concat(Array_from(WHOLE_VALID)).sort((a, b) => a-b); // must be sorted\r\n\twholes.forEach((cp, i) => {\r\n\t\tlet d = r(); \r\n\t\tlet w = wholes[i] = d ? wholes[i-d] : {V: [], M: new Map()};\r\n\t\tw.V.push(cp); // add to member set\r\n\t\tif (!WHOLE_VALID.has(cp)) {\r\n\t\t\tWHOLE_MAP.set(cp, w); // register with whole map\r\n\t\t}\r\n\t});\r\n\r\n\t// compute confusable-extent complements\r\n\t// usage: WHOLE_MAP.get(cp).M.get(cp) = complement set\r\n\tfor (let {V, M} of new Set(WHOLE_MAP.values())) {\r\n\t\t// connect all groups that have each whole character\r\n\t\tlet recs = [];\r\n\t\tfor (let cp of V) {\r\n\t\t\tlet gs = GROUPS.filter(g => group_has_cp(g, cp));\r\n\t\t\tlet rec = recs.find(({G}) => gs.some(g => G.has(g)));\r\n\t\t\tif (!rec) {\r\n\t\t\t\trec = {G: new Set(), V: []};\r\n\t\t\t\trecs.push(rec);\r\n\t\t\t}\r\n\t\t\trec.V.push(cp);\r\n\t\t\tset_add_many(rec.G, gs);\r\n\t\t}\r\n\t\t// per character cache groups which are not a member of the extent\r\n\t\tlet union = recs.flatMap(x => Array_from(x.G)); // all of the groups used by this whole\r\n\t\tfor (let {G, V} of recs) {\r\n\t\t\tlet complement = new Set(union.filter(g => !G.has(g))); // groups not covered by the extent\r\n\t\t\tfor (let cp of V) {\r\n\t\t\t\tM.set(cp, complement); // this is the same reference\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t// compute valid set\r\n\t// 20230924: VALID was union but can be re-used\r\n\tVALID = new Set(); // exists in 1+ groups\r\n\tlet multi = new Set(); // exists in 2+ groups\r\n\tconst add_to_union = cp => VALID.has(cp) ? multi.add(cp) : VALID.add(cp);\r\n\tfor (let g of GROUPS) {\r\n\t\tfor (let cp of g.P) add_to_union(cp);\r\n\t\tfor (let cp of g.Q) add_to_union(cp);\r\n\t}\r\n\t// dual purpose WHOLE_MAP: return placeholder if unique non-confusable\r\n\tfor (let cp of VALID) {\r\n\t\tif (!WHOLE_MAP.has(cp) && !multi.has(cp)) {\r\n\t\t\tWHOLE_MAP.set(cp, UNIQUE_PH);\r\n\t\t}\r\n\t}\r\n\t// add all decomposed parts\r\n\t// see derive: \"Valid is Closed (via Brute-force)\"\r\n\tset_add_many(VALID, nfd(VALID));\r\n\t\r\n\t// decode emoji\r\n\t// 20230719: emoji are now fully-expanded to avoid quirk logic \r\n\tEMOJI_LIST = read_trie(r).map(v => Emoji.from(v)).sort(compare_arrays);\r\n\tEMOJI_ROOT = new Map(); // this has approx 7K nodes (2+ per emoji)\r\n\tfor (let cps of EMOJI_LIST) {\r\n\t\t// 20230719: change to *slightly* stricter algorithm which disallows \r\n\t\t// insertion of misplaced FE0F in emoji sequences (matching ENSIP-15)\r\n\t\t// example: beautified [A B] (eg. flag emoji) \r\n\t\t// before: allow: [A FE0F B], error: [A FE0F FE0F B] \r\n\t\t// after: error: both\r\n\t\t// note: this code now matches ENSNormalize.{cs,java} logic\r\n\t\tlet prev = [EMOJI_ROOT];\r\n\t\tfor (let cp of cps) {\r\n\t\t\tlet next = prev.map(node => {\r\n\t\t\t\tlet child = node.get(cp);\r\n\t\t\t\tif (!child) {\r\n\t\t\t\t\t// should this be object? \r\n\t\t\t\t\t// (most have 1-2 items, few have many)\r\n\t\t\t\t\t// 20230719: no, v8 default map is 4?\r\n\t\t\t\t\tchild = new Map();\r\n\t\t\t\t\tnode.set(cp, child);\r\n\t\t\t\t}\r\n\t\t\t\treturn child;\r\n\t\t\t});\r\n\t\t\tif (cp === FE0F) {\r\n\t\t\t\tprev.push(...next); // less than 20 elements\r\n\t\t\t} else {\r\n\t\t\t\tprev = next;\r\n\t\t\t}\r\n\t\t}\r\n\t\tfor (let x of prev) {\r\n\t\t\tx.V = cps;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n// if escaped: {HEX}\r\n// else: \"x\" {HEX}\r\nfunction quoted_cp(cp) {\r\n\treturn (should_escape(cp) ? '' : `${bidi_qq(safe_str_from_cps([cp]))} `) + quote_cp(cp);\r\n}\r\n\r\n// 20230211: some messages can be mixed-directional and result in spillover\r\n// use 200E after a quoted string to force the remainder of a string from \r\n// acquring the direction of the quote\r\n// https://www.w3.org/International/questions/qa-bidi-unicode-controls#exceptions\r\nfunction bidi_qq(s) {\r\n\treturn `\"${s}\"\\u200E`; // strong LTR\r\n}\r\n\r\nfunction check_label_extension(cps) {\r\n\tif (cps.length >= 4 && cps[2] == HYPHEN && cps[3] == HYPHEN) {\r\n\t\tthrow new Error(`invalid label extension: \"${str_from_cps(cps.slice(0, 4))}\"`); // this can only be ascii so cant be bidi\r\n\t}\r\n}\r\nfunction check_leading_underscore(cps) {\r\n\tconst UNDERSCORE = 0x5F;\r\n\tfor (let i = cps.lastIndexOf(UNDERSCORE); i > 0; ) {\r\n\t\tif (cps[--i] !== UNDERSCORE) {\r\n\t\t\tthrow new Error('underscore allowed only at start');\r\n\t\t}\r\n\t}\r\n}\r\n// check that a fenced cp is not leading, trailing, or touching another fenced cp\r\nfunction check_fenced(cps) {\r\n\tlet cp = cps[0];\r\n\tlet prev = FENCED.get(cp);\r\n\tif (prev) throw error_placement(`leading ${prev}`);\r\n\tlet n = cps.length;\r\n\tlet last = -1; // prevents trailing from throwing\r\n\tfor (let i = 1; i < n; i++) {\r\n\t\tcp = cps[i];\r\n\t\tlet match = FENCED.get(cp);\r\n\t\tif (match) {\r\n\t\t\t// since cps[0] isn't fenced, cps[1] cannot throw\r\n\t\t\tif (last == i) throw error_placement(`${prev} + ${match}`);\r\n\t\t\tlast = i + 1;\r\n\t\t\tprev = match;\r\n\t\t}\r\n\t}\r\n\tif (last == n) throw error_placement(`trailing ${prev}`);\r\n}\r\n\r\n// create a safe to print string \r\n// invisibles are escaped\r\n// leading cm uses placeholder\r\n// if cps exceed max, middle truncate with ellipsis\r\n// quoter(cp) => string, eg. 3000 => \"{3000}\"\r\n// note: in html, you'd call this function then replace [<>&] with entities\r\nfunction safe_str_from_cps(cps, max = Infinity, quoter = quote_cp) {\r\n\t//if (Number.isInteger(cps)) cps = [cps];\r\n\t//if (!Array.isArray(cps)) throw new TypeError(`expected codepoints`);\r\n\tlet buf = [];\r\n\tif (is_combining_mark(cps[0])) buf.push('◌');\r\n\tif (cps.length > max) {\r\n\t\tmax >>= 1;\r\n\t\tcps = [...cps.slice(0, max), 0x2026, ...cps.slice(-max)];\r\n\t}\r\n\tlet prev = 0;\r\n\tlet n = cps.length;\r\n\tfor (let i = 0; i < n; i++) {\r\n\t\tlet cp = cps[i];\r\n\t\tif (should_escape(cp)) {\r\n\t\t\tbuf.push(str_from_cps(cps.slice(prev, i)));\r\n\t\t\tbuf.push(quoter(cp));\r\n\t\t\tprev = i + 1;\r\n\t\t}\r\n\t}\r\n\tbuf.push(str_from_cps(cps.slice(prev, n)));\r\n\treturn buf.join('');\r\n}\r\n\r\n// note: set(s) cannot be exposed because they can be modified\r\n// note: Object.freeze() doesn't work\r\nfunction is_combining_mark(cp, only_nsm) { // 20240127: add extra argument\r\n\tinit();\r\n\treturn only_nsm ? NSM.has(cp) : CM.has(cp);\r\n}\r\nfunction should_escape(cp) {\r\n\tinit();\r\n\treturn ESCAPE.has(cp);\r\n}\r\n\r\n// return all supported emoji as fully-qualified emoji \r\n// ordered by length then lexicographic \r\nfunction ens_emoji() {\r\n\tinit();\r\n\treturn EMOJI_LIST.map(x => x.slice()); // emoji are exposed so copy\r\n}\r\n\r\nfunction ens_normalize_fragment(frag, decompose) {\r\n\tinit();\r\n\tlet nf = decompose ? nfd : nfc;\r\n\treturn frag.split(STOP_CH).map(label => str_from_cps(tokens_from_str(explode_cp(label), nf, filter_fe0f).flat())).join(STOP_CH);\r\n}\r\n\r\nfunction ens_normalize(name) {\r\n\treturn flatten(split(name, nfc, filter_fe0f));\r\n}\r\n\r\nfunction ens_beautify(name) {\r\n\tlet labels = split(name, nfc, x => x); // emoji not exposed\r\n\tfor (let {type, output, error} of labels) {\r\n\t\tif (error) break; // flatten will throw\r\n\r\n\t\t// replace leading/trailing hyphen\r\n\t\t// 20230121: consider beautifing all or leading/trailing hyphen to unicode variant\r\n\t\t// not exactly the same in every font, but very similar: \"-\" vs \"‐\"\r\n\t\t/*\r\n\t\tconst UNICODE_HYPHEN = 0x2010;\r\n\t\t// maybe this should replace all for visual consistancy?\r\n\t\t// `node tools/reg-count.js regex ^-\\{2,\\}` => 592\r\n\t\t//for (let i = 0; i < output.length; i++) if (output[i] == 0x2D) output[i] = 0x2010;\r\n\t\tif (output[0] == HYPHEN) output[0] = UNICODE_HYPHEN;\r\n\t\tlet end = output.length-1;\r\n\t\tif (output[end] == HYPHEN) output[end] = UNICODE_HYPHEN;\r\n\t\t*/\r\n\t\t// 20230123: WHATWG URL uses \"CheckHyphens\" false\r\n\t\t// https://url.spec.whatwg.org/#idna\r\n\r\n\t\t// update ethereum symbol\r\n\t\t// ξ => Ξ if not greek\r\n\t\tif (type !== 'Greek') array_replace(output, 0x3BE, 0x39E);\r\n\r\n\t\t// 20221213: fixes bidi subdomain issue, but breaks invariant (200E is disallowed)\r\n\t\t// could be fixed with special case for: 2D (.) + 200E (LTR)\r\n\t\t// https://discuss.ens.domains/t/bidi-label-ordering-spoof/15824\r\n\t\t//output.splice(0, 0, 0x200E);\r\n\t}\r\n\treturn flatten(labels);\r\n}\r\n\r\nfunction ens_split(name, preserve_emoji) {\r\n\treturn split(name, nfc, preserve_emoji ? x => x.slice() : filter_fe0f); // emoji are exposed so copy\r\n}\r\n\r\nfunction split(name, nf, ef) {\r\n\tif (!name) return []; // 20230719: empty name allowance\r\n\tinit();\r\n\tlet offset = 0;\r\n\t// https://unicode.org/reports/tr46/#Validity_Criteria\r\n\t// 4.) \"The label must not contain a U+002E ( . ) FULL STOP.\"\r\n\treturn name.split(STOP_CH).map(label => {\r\n\t\tlet input = explode_cp(label);\r\n\t\tlet info = {\r\n\t\t\tinput,\r\n\t\t\toffset, // codepoint, not substring!\r\n\t\t};\r\n\t\toffset += input.length + 1; // + stop\r\n\t\ttry {\r\n\t\t\t// 1.) \"The label must be in Unicode Normalization Form NFC\"\r\n\t\t\tlet tokens = info.tokens = tokens_from_str(input, nf, ef);\r\n\t\t\tlet token_count = tokens.length;\r\n\t\t\tlet type;\r\n\t\t\tif (!token_count) { // the label was effectively empty (could of had ignored characters)\r\n\t\t\t\t//norm = [];\r\n\t\t\t\t//type = 'None'; // use this instead of next match, \"ASCII\"\r\n\t\t\t\t// 20230120: change to strict\r\n\t\t\t\t// https://discuss.ens.domains/t/ens-name-normalization-2nd/14564/59\r\n\t\t\t\tthrow new Error(`empty label`);\r\n\t\t\t} \r\n\t\t\tlet norm = info.output = tokens.flat();\r\n\t\t\tcheck_leading_underscore(norm);\r\n\t\t\tlet emoji = info.emoji = token_count > 1 || tokens[0].is_emoji; // same as: tokens.some(x => x.is_emoji);\r\n\t\t\tif (!emoji && norm.every(cp => cp < 0x80)) { // special case for ascii\r\n\t\t\t\t// 20230123: matches matches WHATWG, see note 3.3\r\n\t\t\t\tcheck_label_extension(norm); // only needed for ascii\r\n\t\t\t\t// cant have fenced\r\n\t\t\t\t// cant have cm\r\n\t\t\t\t// cant have wholes\r\n\t\t\t\t// see derive: \"Fastpath ASCII\"\r\n\t\t\t\ttype = 'ASCII';\r\n\t\t\t} else {\r\n\t\t\t\tlet chars = tokens.flatMap(x => x.is_emoji ? [] : x); // all of the nfc tokens concat together\r\n\t\t\t\tif (!chars.length) { // theres no text, just emoji\r\n\t\t\t\t\ttype = 'Emoji';\r\n\t\t\t\t} else {\r\n\t\t\t\t\t// 5.) \"The label must not begin with a combining mark, that is: General_Category=Mark.\"\r\n\t\t\t\t\tif (CM.has(norm[0])) throw error_placement('leading combining mark');\r\n\t\t\t\t\tfor (let i = 1; i < token_count; i++) { // we've already checked the first token\r\n\t\t\t\t\t\tlet cps = tokens[i];\r\n\t\t\t\t\t\tif (!cps.is_emoji && CM.has(cps[0])) { // every text token has emoji neighbors, eg. EtEEEtEt...\r\n\t\t\t\t\t\t\t// bidi_qq() not needed since emoji is LTR and cps is a CM\r\n\t\t\t\t\t\t\tthrow error_placement(`emoji + combining mark: \"${str_from_cps(tokens[i-1])} + ${safe_str_from_cps([cps[0]])}\"`); \r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tcheck_fenced(norm);\r\n\t\t\t\t\tlet unique = Array_from(new Set(chars));\r\n\t\t\t\t\tlet [g] = determine_group(unique); // take the first match\r\n\t\t\t\t\t// see derive: \"Matching Groups have Same CM Style\"\r\n\t\t\t\t\t// alternative: could form a hybrid type: Latin/Japanese/...\t\r\n\t\t\t\t\tcheck_group(g, chars); // need text in order\r\n\t\t\t\t\tcheck_whole(g, unique); // only need unique text (order would be required for multiple-char confusables)\r\n\t\t\t\t\ttype = g.N;\r\n\t\t\t\t\t// 20230121: consider exposing restricted flag\r\n\t\t\t\t\t// it's simpler to just check for 'Restricted'\r\n\t\t\t\t\t// or even better: type.endsWith(']')\r\n\t\t\t\t\t//if (g.R) info.restricted = true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tinfo.type = type;\r\n\t\t} catch (err) {\r\n\t\t\tinfo.error = err; // use full error object\r\n\t\t}\r\n\t\treturn info;\r\n\t});\r\n}\r\n\r\nfunction check_whole(group, unique) {\r\n\tlet maker;\r\n\tlet shared = [];\r\n\tfor (let cp of unique) {\r\n\t\tlet whole = WHOLE_MAP.get(cp);\r\n\t\tif (whole === UNIQUE_PH) return; // unique, non-confusable\r\n\t\tif (whole) {\r\n\t\t\tlet set = whole.M.get(cp); // groups which have a character that look-like this character\r\n\t\t\tmaker = maker ? maker.filter(g => set.has(g)) : Array_from(set);\r\n\t\t\tif (!maker.length) return; // confusable intersection is empty\r\n\t\t} else {\r\n\t\t\tshared.push(cp); \r\n\t\t}\r\n\t}\r\n\tif (maker) {\r\n\t\t// we have 1+ confusable\r\n\t\t// check if any of the remaining groups\r\n\t\t// contain the shared characters too\r\n\t\tfor (let g of maker) {\r\n\t\t\tif (shared.every(cp => group_has_cp(g, cp))) {\r\n\t\t\t\tthrow new Error(`whole-script confusable: ${group.N}/${g.N}`);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n}\r\n\r\n// assumption: unique.size > 0\r\n// returns list of matching groups\r\nfunction determine_group(unique) {\r\n\tlet groups = GROUPS;\r\n\tfor (let cp of unique) {\r\n\t\t// note: we need to dodge CM that are whitelisted\r\n\t\t// but that code isn't currently necessary\r\n\t\tlet gs = groups.filter(g => group_has_cp(g, cp));\r\n\t\tif (!gs.length) {\r\n\t\t\tif (!GROUPS.some(g => group_has_cp(g, cp))) { \r\n\t\t\t\t// the character was composed of valid parts\r\n\t\t\t\t// but it's NFC form is invalid\r\n\t\t\t\t// 20230716: change to more exact statement, see: ENSNormalize.{cs,java}\r\n\t\t\t\t// note: this doesn't have to be a composition\r\n\t\t\t\t// 20230720: change to full check\r\n\t\t\t\tthrow error_disallowed(cp); // this should be rare\r\n\t\t\t} else {\r\n\t\t\t\t// there is no group that contains all these characters\r\n\t\t\t\t// throw using the highest priority group that matched\r\n\t\t\t\t// https://www.unicode.org/reports/tr39/#mixed_script_confusables\r\n\t\t\t\tthrow error_group_member(groups[0], cp);\r\n\t\t\t}\r\n\t\t}\r\n\t\tgroups = gs;\r\n\t\tif (gs.length == 1) break; // there is only one group left\r\n\t}\r\n\t// there are at least 1 group(s) with all of these characters\r\n\treturn groups;\r\n}\r\n\r\n// throw on first error\r\nfunction flatten(split) {\r\n\treturn split.map(({input, error, output}) => {\r\n\t\tif (error) {\r\n\t\t\t// don't print label again if just a single label\r\n\t\t\tlet msg = error.message;\r\n\t\t\t// bidi_qq() only necessary if msg is digits\r\n\t\t\tthrow new Error(split.length == 1 ? msg : `Invalid label ${bidi_qq(safe_str_from_cps(input, 63))}: ${msg}`); \r\n\t\t}\r\n\t\treturn str_from_cps(output);\r\n\t}).join(STOP_CH);\r\n}\r\n\r\nfunction error_disallowed(cp) {\r\n\t// TODO: add cp to error?\r\n\treturn new Error(`disallowed character: ${quoted_cp(cp)}`); \r\n}\r\nfunction error_group_member(g, cp) {\r\n\tlet quoted = quoted_cp(cp);\r\n\tlet gg = GROUPS.find(g => g.P.has(cp)); // only check primary\r\n\tif (gg) {\r\n\t\tquoted = `${gg.N} ${quoted}`;\r\n\t}\r\n\treturn new Error(`illegal mixture: ${g.N} + ${quoted}`);\r\n}\r\nfunction error_placement(where) {\r\n\treturn new Error(`illegal placement: ${where}`);\r\n}\r\n\r\n// assumption: cps.length > 0\r\n// assumption: cps[0] isn't a CM\r\n// assumption: the previous character isn't an emoji\r\nfunction check_group(g, cps) {\r\n\tfor (let cp of cps) {\r\n\t\tif (!group_has_cp(g, cp)) {\r\n\t\t\t// for whitelisted scripts, this will throw illegal mixture on invalid cm, eg. \"e{300}{300}\"\r\n\t\t\t// at the moment, it's unnecessary to introduce an extra error type\r\n\t\t\t// until there exists a whitelisted multi-character\r\n\t\t\t// eg. if (M < 0 && is_combining_mark(cp)) { ... }\r\n\t\t\t// there are 3 cases:\r\n\t\t\t// 1. illegal cm for wrong group => mixture error\r\n\t\t\t// 2. illegal cm for same group => cm error\r\n\t\t\t// requires set of whitelist cm per group: \r\n\t\t\t// eg. new Set([...g.P, ...g.Q].flatMap(nfc).filter(cp => CM.has(cp)))\r\n\t\t\t// 3. wrong group => mixture error\r\n\t\t\tthrow error_group_member(g, cp);\r\n\t\t}\r\n\t}\r\n\t//if (M >= 0) { // we have a known fixed cm count\r\n\tif (g.M) { // we need to check for NSM\r\n\t\tlet decomposed = nfd(cps);\r\n\t\tfor (let i = 1, e = decomposed.length; i < e; i++) { // see: assumption\r\n\t\t\t// 20230210: bugfix: using cps instead of decomposed h/t Carbon225\r\n\t\t\t/*\r\n\t\t\tif (CM.has(decomposed[i])) {\r\n\t\t\t\tlet j = i + 1;\r\n\t\t\t\twhile (j < e && CM.has(decomposed[j])) j++;\r\n\t\t\t\tif (j - i > M) {\r\n\t\t\t\t\tthrow new Error(`too many combining marks: ${g.N} ${bidi_qq(str_from_cps(decomposed.slice(i-1, j)))} (${j-i}/${M})`);\r\n\t\t\t\t}\r\n\t\t\t\ti = j;\r\n\t\t\t}\r\n\t\t\t*/\r\n\t\t\t// 20230217: switch to NSM counting\r\n\t\t\t// https://www.unicode.org/reports/tr39/#Optional_Detection\r\n\t\t\tif (NSM.has(decomposed[i])) {\r\n\t\t\t\tlet j = i + 1;\r\n\t\t\t\tfor (let cp; j < e && NSM.has(cp = decomposed[j]); j++) {\r\n\t\t\t\t\t// a. Forbid sequences of the same nonspacing mark.\r\n\t\t\t\t\tfor (let k = i; k < j; k++) { // O(n^2) but n < 100\r\n\t\t\t\t\t\tif (decomposed[k] == cp) {\r\n\t\t\t\t\t\t\tthrow new Error(`duplicate non-spacing marks: ${quoted_cp(cp)}`);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\t// parse to end so we have full nsm count\r\n\t\t\t\t// b. Forbid sequences of more than 4 nonspacing marks (gc=Mn or gc=Me).\r\n\t\t\t\tif (j - i > NSM_MAX) {\r\n\t\t\t\t\t// note: this slice starts with a base char or spacing-mark cm\r\n\t\t\t\t\tthrow new Error(`excessive non-spacing marks: ${bidi_qq(safe_str_from_cps(decomposed.slice(i-1, j)))} (${j-i}/${NSM_MAX})`);\r\n\t\t\t\t}\r\n\t\t\t\ti = j;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t// *** this code currently isn't needed ***\r\n\t/*\r\n\tlet cm_whitelist = M instanceof Map;\r\n\tfor (let i = 0, e = cps.length; i < e; ) {\r\n\t\tlet cp = cps[i++];\r\n\t\tlet seqs = cm_whitelist && M.get(cp);\r\n\t\tif (seqs) { \r\n\t\t\t// list of codepoints that can follow\r\n\t\t\t// if this exists, this will always be 1+\r\n\t\t\tlet j = i;\r\n\t\t\twhile (j < e && CM.has(cps[j])) j++;\r\n\t\t\tlet cms = cps.slice(i, j);\r\n\t\t\tlet match = seqs.find(seq => !compare_arrays(seq, cms));\r\n\t\t\tif (!match) throw new Error(`disallowed combining mark sequence: \"${safe_str_from_cps([cp, ...cms])}\"`);\r\n\t\t\ti = j;\r\n\t\t} else if (!V.has(cp)) {\r\n\t\t\t// https://www.unicode.org/reports/tr39/#mixed_script_confusables\r\n\t\t\tlet quoted = quoted_cp(cp);\r\n\t\t\tfor (let cp of cps) {\r\n\t\t\t\tlet u = UNIQUE.get(cp);\r\n\t\t\t\tif (u && u !== g) {\r\n\t\t\t\t\t// if both scripts are restricted this error is confusing\r\n\t\t\t\t\t// because we don't differentiate RestrictedA from RestrictedB \r\n\t\t\t\t\tif (!u.R) quoted = `${quoted} is ${u.N}`;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tthrow new Error(`disallowed ${g.N} character: ${quoted}`);\r\n\t\t\t//throw new Error(`disallowed character: ${quoted} (expected ${g.N})`);\r\n\t\t\t//throw new Error(`${g.N} does not allow: ${quoted}`);\r\n\t\t}\r\n\t}\r\n\tif (!cm_whitelist) {\r\n\t\tlet decomposed = nfd(cps);\r\n\t\tfor (let i = 1, e = decomposed.length; i < e; i++) { // we know it can't be cm leading\r\n\t\t\tif (CM.has(decomposed[i])) {\r\n\t\t\t\tlet j = i + 1;\r\n\t\t\t\twhile (j < e && CM.has(decomposed[j])) j++;\r\n\t\t\t\tif (j - i > M) {\r\n\t\t\t\t\tthrow new Error(`too many combining marks: \"${str_from_cps(decomposed.slice(i-1, j))}\" (${j-i}/${M})`);\r\n\t\t\t\t}\r\n\t\t\t\ti = j;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\t*/\r\n}\r\n\r\n// given a list of codepoints\r\n// returns a list of lists, where emoji are a fully-qualified (as Array subclass)\r\n// eg. explode_cp(\"abc💩d\") => [[61, 62, 63], Emoji[1F4A9, FE0F], [64]]\r\n// 20230818: rename for 'process' name collision h/t Javarome\r\n// https://github.com/adraffy/ens-normalize.js/issues/23\r\nfunction tokens_from_str(input, nf, ef) {\r\n\tlet ret = [];\r\n\tlet chars = [];\r\n\tinput = input.slice().reverse(); // flip so we can pop\r\n\twhile (input.length) {\r\n\t\tlet emoji = consume_emoji_reversed(input);\r\n\t\tif (emoji) {\r\n\t\t\tif (chars.length) {\r\n\t\t\t\tret.push(nf(chars));\r\n\t\t\t\tchars = [];\r\n\t\t\t}\r\n\t\t\tret.push(ef(emoji));\r\n\t\t} else {\r\n\t\t\tlet cp = input.pop();\r\n\t\t\tif (VALID.has(cp)) {\r\n\t\t\t\tchars.push(cp);\r\n\t\t\t} else {\r\n\t\t\t\tlet cps = MAPPED.get(cp);\r\n\t\t\t\tif (cps) {\r\n\t\t\t\t\tchars.push(...cps); // less than 10 elements\r\n\t\t\t\t} else if (!IGNORED.has(cp)) {\r\n\t\t\t\t\t// 20230912: unicode 15.1 changed the order of processing such that\r\n\t\t\t\t\t// disallowed parts are only rejected after NFC\r\n\t\t\t\t\t// https://unicode.org/reports/tr46/#Validity_Criteria\r\n\t\t\t\t\t// this doesn't impact normalization as of today\r\n\t\t\t\t\t// technically, this error can be removed as the group logic will apply similar logic\r\n\t\t\t\t\t// however the error type might be less clear\r\n\t\t\t\t\tthrow error_disallowed(cp);\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (chars.length) {\r\n\t\tret.push(nf(chars));\r\n\t}\r\n\treturn ret;\r\n}\r\n\r\nfunction filter_fe0f(cps) {\r\n\treturn cps.filter(cp => cp != FE0F);\r\n}\r\n\r\n// given array of codepoints\r\n// returns the longest valid emoji sequence (or undefined if no match)\r\n// *MUTATES* the supplied array\r\n// disallows interleaved ignored characters\r\n// fills (optional) eaten array with matched codepoints\r\nfunction consume_emoji_reversed(cps, eaten) {\r\n\tlet node = EMOJI_ROOT;\r\n\tlet emoji;\r\n\tlet pos = cps.length;\r\n\twhile (pos) {\r\n\t\tnode = node.get(cps[--pos]);\r\n\t\tif (!node) break;\r\n\t\tlet {V} = node;\r\n\t\tif (V) { // this is a valid emoji (so far)\r\n\t\t\temoji = V;\r\n\t\t\tif (eaten) eaten.push(...cps.slice(pos).reverse()); // (optional) copy input, used for ens_tokenize()\r\n\t\t\tcps.length = pos; // truncate\r\n\t\t}\r\n\t}\r\n\treturn emoji;\r\n}\r\n\r\n// ************************************************************\r\n// tokenizer \r\n\r\nconst TY_VALID = 'valid';\r\nconst TY_MAPPED = 'mapped';\r\nconst TY_IGNORED = 'ignored';\r\nconst TY_DISALLOWED = 'disallowed';\r\nconst TY_EMOJI = 'emoji';\r\nconst TY_NFC = 'nfc';\r\nconst TY_STOP = 'stop';\r\n\r\nfunction ens_tokenize(name, {\r\n\tnf = true, // collapse unnormalized runs into a single token\r\n} = {}) {\r\n\tinit();\r\n\tlet input = explode_cp(name).reverse();\r\n\tlet eaten = [];\r\n\tlet tokens = [];\r\n\twhile (input.length) {\r\n\t\tlet emoji = consume_emoji_reversed(input, eaten);\r\n\t\tif (emoji) {\r\n\t\t\ttokens.push({\r\n\t\t\t\ttype: TY_EMOJI,\r\n\t\t\t\temoji: emoji.slice(), // copy emoji\r\n\t\t\t\tinput: eaten,\r\n\t\t\t\tcps: filter_fe0f(emoji)\r\n\t\t\t});\r\n\t\t\teaten = []; // reset buffer\r\n\t\t} else {\r\n\t\t\tlet cp = input.pop();\r\n\t\t\tif (cp == STOP) {\r\n\t\t\t\ttokens.push({type: TY_STOP, cp});\r\n\t\t\t} else if (VALID.has(cp)) {\r\n\t\t\t\ttokens.push({type: TY_VALID, cps: [cp]});\r\n\t\t\t} else if (IGNORED.has(cp)) {\r\n\t\t\t\ttokens.push({type: TY_IGNORED, cp});\r\n\t\t\t} else {\r\n\t\t\t\tlet cps = MAPPED.get(cp);\r\n\t\t\t\tif (cps) {\r\n\t\t\t\t\ttokens.push({type: TY_MAPPED, cp, cps: cps.slice()});\r\n\t\t\t\t} else {\r\n\t\t\t\t\ttokens.push({type: TY_DISALLOWED, cp});\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif (nf) {\r\n\t\tfor (let i = 0, start = -1; i < tokens.length; i++) {\r\n\t\t\tlet token = tokens[i];\r\n\t\t\tif (is_valid_or_mapped(token.type)) {\r\n\t\t\t\tif (requires_check(token.cps)) { // normalization might be needed\r\n\t\t\t\t\tlet end = i + 1;\r\n\t\t\t\t\tfor (let pos = end; pos < tokens.length; pos++) { // find adjacent text\r\n\t\t\t\t\t\tlet {type, cps} = tokens[pos];\r\n\t\t\t\t\t\tif (is_valid_or_mapped(type)) {\r\n\t\t\t\t\t\t\tif (!requires_check(cps)) break;\r\n\t\t\t\t\t\t\tend = pos + 1;\r\n\t\t\t\t\t\t} else if (type !== TY_IGNORED) { // || type !== TY_DISALLOWED) { \r\n\t\t\t\t\t\t\tbreak;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif (start < 0) start = i;\r\n\t\t\t\t\tlet slice = tokens.slice(start, end);\r\n\t\t\t\t\tlet cps0 = slice.flatMap(x => is_valid_or_mapped(x.type) ? x.cps : []); // strip junk tokens\r\n\t\t\t\t\tlet cps = nfc(cps0);\r\n\t\t\t\t\tif (compare_arrays(cps, cps0)) { // bundle into an nfc token\r\n\t\t\t\t\t\ttokens.splice(start, end - start, {\r\n\t\t\t\t\t\t\ttype: TY_NFC, \r\n\t\t\t\t\t\t\tinput: cps0, // there are 3 states: tokens0 ==(process)=> input ==(nfc)=> tokens/cps\r\n\t\t\t\t\t\t\tcps, \r\n\t\t\t\t\t\t\ttokens0: collapse_valid_tokens(slice),\r\n\t\t\t\t\t\t\ttokens: ens_tokenize(str_from_cps(cps), {nf: false})\r\n\t\t\t\t\t\t});\r\n\t\t\t\t\t\ti = start;\r\n\t\t\t\t\t} else { \r\n\t\t\t\t\t\ti = end - 1; // skip to end of slice\r\n\t\t\t\t\t}\r\n\t\t\t\t\tstart = -1; // reset\r\n\t\t\t\t} else {\r\n\t\t\t\t\tstart = i; // remember last\r\n\t\t\t\t}\r\n\t\t\t} else if (token.type !== TY_IGNORED) { // 20221024: is this correct?\r\n\t\t\t\tstart = -1; // reset\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\treturn collapse_valid_tokens(tokens);\r\n}\r\n\r\nfunction is_valid_or_mapped(type) {\r\n\treturn type == TY_VALID || type == TY_MAPPED;\r\n}\r\n\r\nfunction requires_check(cps) {\r\n\treturn cps.some(cp => NFC_CHECK.has(cp));\r\n}\r\n\r\nfunction collapse_valid_tokens(tokens) {\r\n\tfor (let i = 0; i < tokens.length; i++) {\r\n\t\tif (tokens[i].type == TY_VALID) {\r\n\t\t\tlet j = i + 1;\r\n\t\t\twhile (j < tokens.length && tokens[j].type == TY_VALID) j++;\r\n\t\t\ttokens.splice(i, j - i, {type: TY_VALID, cps: tokens.slice(i, j).flatMap(x => x.cps)});\r\n\t\t}\r\n\t}\r\n\treturn tokens;\r\n}\n\nexport { ens_beautify, ens_emoji, ens_normalize, ens_normalize_fragment, ens_split, ens_tokenize, is_combining_mark, nfc, nfd, safe_str_from_cps, should_escape };\n","import * as Ens from 'ox/Ens';\n/**\n * @description Normalizes ENS name according to ENSIP-15.\n *\n * @example\n * normalize('wevm.eth')\n * 'wevm.eth'\n *\n * @see https://docs.ens.domains/contract-api-reference/name-processing#normalising-names\n * @see https://github.com/ensdomains/docs/blob/9edf9443de4333a0ea7ec658a870672d5d180d53/ens-improvement-proposals/ensip-15-normalization-standard.md\n */\nexport function normalize(name) {\n return Ens.normalize(name);\n}\n//# sourceMappingURL=normalize.js.map","import { ens_normalize } from '@adraffy/ens-normalize';\nimport * as Bytes from './Bytes.js';\nimport * as Hash from './Hash.js';\nimport * as Hex from './Hex.js';\nimport * as internal from './internal/ens.js';\n/**\n * Hashes ENS label.\n *\n * Since ENS labels prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS labels](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `labelhash`. You can use the built-in {@link ox#Ens.(normalize:function)} function for this.\n *\n * @example\n * ```ts twoslash\n * import { Ens } from 'ox'\n * Ens.labelhash('eth')\n * '0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0'\n * ```\n *\n * @param label - ENS label.\n * @returns ENS labelhash.\n */\nexport function labelhash(label) {\n const result = new Uint8Array(32).fill(0);\n if (!label)\n return Hex.fromBytes(result);\n return (internal.unwrapLabelhash(label) || Hash.keccak256(Hex.fromString(label)));\n}\n/**\n * Hashes ENS name.\n *\n * Since ENS names prohibit certain forbidden characters (e.g. underscore) and have other validation rules, you likely want to [normalize ENS names](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) with [UTS-46 normalization](https://unicode.org/reports/tr46) before passing them to `namehash`. You can use the built-in {@link ox#Ens.(normalize:function)} function for this.\n *\n * @example\n * ```ts twoslash\n * import { Ens } from 'ox'\n * Ens.namehash('wevm.eth')\n * // @log: '0xf246651c1b9a6b141d19c2604e9a58f567973833990f830d882534a747801359'\n * ```\n *\n * @param name - ENS name.\n * @returns ENS namehash.\n */\nexport function namehash(name) {\n let result = new Uint8Array(32).fill(0);\n if (!name)\n return Hex.fromBytes(result);\n const labels = name.split('.');\n // Iterate in reverse order building up hash\n for (let i = labels.length - 1; i >= 0; i -= 1) {\n const hashFromEncodedLabel = internal.unwrapLabelhash(labels[i]);\n const hashed = hashFromEncodedLabel\n ? Bytes.fromHex(hashFromEncodedLabel)\n : Hash.keccak256(Bytes.fromString(labels[i]), { as: 'Bytes' });\n result = Hash.keccak256(Bytes.concat(result, hashed), { as: 'Bytes' });\n }\n return Hex.fromBytes(result);\n}\n/**\n * Normalizes ENS name according to [ENSIP-15](https://github.com/ensdomains/docs/blob/9edf9443de4333a0ea7ec658a870672d5d180d53/ens-improvement-proposals/ensip-15-normalization-standard.md).\n *\n * For more info see [ENS documentation](https://docs.ens.domains/contract-api-reference/name-processing#normalising-names) on name processing.\n *\n * @example\n * ```ts twoslash\n * import { Ens } from 'ox'\n * Ens.normalize('wevm.eth')\n * // @log: 'wevm.eth'\n * ```\n *\n * @param name - ENS name.\n * @returns Normalized ENS name.\n */\nexport function normalize(name) {\n return ens_normalize(name);\n}\n//# sourceMappingURL=Ens.js.map","// Copyright 2026 The Swarm Authors. All rights reserved.\n// SPDX-License-Identifier: Apache-2.0\n\n/**\n * A wallet's ENS name, for a reader that checked a wallet link\n * (docs/Wallet-Link.md) and wants to show the name instead of the address.\n *\n * Anyone can point the reverse record of their own wallet at any name, so the\n * reverse record alone proves nothing. ENS's Universal Resolver, read through\n * viem's `getEnsName`, answers a primary name only when the name's address\n * record names the wallet back, and it follows CCIP-read (EIP-3668), wildcard\n * (ENSIP-10) and chain-specific (ENSIP-19) resolvers on the way. The name\n * must also be in its ENSIP-15 normalised form already, because a name that\n * normalises to something else can look like a different name on screen.\n *\n * Read over an Ethereum mainnet JSON-RPC endpoint the caller names, never a\n * Swarm gateway (`ens.ts` says why).\n */\n\nimport {\n BaseError,\n ContractFunctionRevertedError,\n createClient,\n http,\n type Hex,\n} from \"viem\"\nimport { mainnet } from \"viem/chains\"\nimport { getEnsName, normalize } from \"viem/ens\"\nimport { CHAIN_READ_TIMEOUT_MS } from \"./json-rpc\"\nimport { withTimeout } from \"./promise\"\n\n/**\n * How long a wallet's answer is kept before the chain is asked again. A name\n * changed on chain shows at most this long after on a page that read it.\n */\nexport const ENS_NAME_CACHE_MS = 10 * 60 * 1000\n\n/**\n * How long a failed read is kept, so a page that shows many senders does not\n * ask a broken or slow endpoint again for every message it renders, while a\n * passing outage still clears soon.\n */\nexport const ENS_NAME_FAILURE_CACHE_MS = 30 * 1000\n\n/**\n * The Universal Resolver's reverts that are a definite answer of no name: no\n * reverse record, a name whose address record names another wallet, a\n * resolver that is not a contract or cannot answer a name. Every other revert,\n * such as an offchain gateway that failed (`HttpError`) or a resolver that\n * reverted (`ResolverError`), is a failed read.\n */\nconst NO_NAME_REVERTS = new Set([\n \"ResolverNotFound\",\n \"ReverseAddressMismatch\",\n \"ResolverNotContract\",\n \"UnsupportedResolverProfile\",\n])\n\nconst LOG_PREFIX = \"[EnsName]\"\nconst WALLET_PATTERN = /^(0x)?[0-9a-fA-F]{40}$/\n\nexport interface EnsNameOptions {\n /** An Ethereum mainnet JSON-RPC endpoint. Empty, no name is ever answered. */\n rpcUrl: string\n /** Deadline for the whole lookup. Defaults to `CHAIN_READ_TIMEOUT_MS`. */\n timeoutMs?: number\n}\n\ninterface CachedName {\n name: string | undefined\n fetchedAt: number\n /** How long this entry answers: `ENS_NAME_CACHE_MS` or, for a failed read, `ENS_NAME_FAILURE_CACHE_MS`. */\n keepMs: number\n}\n\nconst cache = new Map<string, CachedName>()\nconst inFlight = new Map<string, Promise<string | undefined>>()\n\n/** Whether ENSIP-15 leaves `name` exactly as it is. */\nfunction isNormalised(name: string): boolean {\n try {\n return normalize(name) === name\n } catch {\n return false\n }\n}\n\nfunction isNoNameRevert(error: unknown): boolean {\n if (!(error instanceof BaseError)) {\n return false\n }\n const revert = error.walk(\n (cause) => cause instanceof ContractFunctionRevertedError,\n )\n return (\n revert instanceof ContractFunctionRevertedError &&\n NO_NAME_REVERTS.has(revert.data?.errorName ?? \"\")\n )\n}\n\n/**\n * The verified name, or undefined when the chain says there is none.\n * @throws when the endpoint fails, an answer does not decode or a name's\n * resolver could not answer, which is not an answer and is therefore kept\n * only for `ENS_NAME_FAILURE_CACHE_MS`.\n */\nasync function readVerifiedName(\n rpcUrl: string,\n wallet: Hex,\n timeoutMs: number,\n): Promise<string | undefined> {\n // A retry would outlive the whole lookup's deadline and keep asking an\n // endpoint whose failure is already cached.\n const client = createClient({\n chain: mainnet,\n transport: http(rpcUrl, { timeout: timeoutMs, retryCount: 0 }),\n })\n try {\n // Strict, so a failed read throws instead of reading as no name, and only\n // the reverts above are taken as a definite no.\n const name = await getEnsName(client, { address: wallet, strict: true })\n return name && isNormalised(name) ? name : undefined\n } catch (error) {\n if (isNoNameRevert(error)) {\n return undefined\n }\n throw error\n }\n}\n\n/** viem's short message leaves out the endpoint, whose path can hold a key. */\nfunction describeFailure(error: unknown): string {\n if (error instanceof BaseError) {\n return error.shortMessage\n }\n return error instanceof Error ? error.message : String(error)\n}\n\n/**\n * The ENS name of `wallet`, when ENS's Universal Resolver answers a primary\n * name whose address record names the wallet back, and the name is already\n * ENSIP-15 normalised. Undefined for no such name and for everything that goes\n * wrong: no endpoint, an endpoint that does not answer in time, an answer that\n * does not decode, a name's offchain gateway that fails. Never throws.\n *\n * An answer, name or no name, is kept in memory for `ENS_NAME_CACHE_MS` per\n * endpoint and wallet, and lookups that arrive together share one read. A\n * failed read answers no name for `ENS_NAME_FAILURE_CACHE_MS`, and the first\n * lookup after that asks again.\n *\n * @param wallet - the wallet's address, in any case, with or without `0x`,\n * such as `verifyWalletLink(...).wallet`\n */\nexport async function resolveVerifiedEnsName(\n wallet: string,\n options: EnsNameOptions,\n): Promise<string | undefined> {\n if (!options.rpcUrl || !WALLET_PATTERN.test(wallet)) {\n return undefined\n }\n const bare = wallet.toLowerCase().replace(/^0x/, \"\")\n const key = `${options.rpcUrl}\\n${bare}`\n const cached = cache.get(key)\n if (cached) {\n const age = Date.now() - cached.fetchedAt\n if (age >= 0 && age < cached.keepMs) {\n return cached.name\n }\n cache.delete(key)\n }\n const pending = inFlight.get(key)\n if (pending) {\n return pending\n }\n const timeoutMs = options.timeoutMs ?? CHAIN_READ_TIMEOUT_MS\n const read = withTimeout(\n readVerifiedName(options.rpcUrl, `0x${bare}`, timeoutMs),\n timeoutMs,\n `The ENS name of 0x${bare} was not read within ${timeoutMs}ms.`,\n )\n .then((name) => {\n cache.set(key, {\n name,\n fetchedAt: Date.now(),\n keepMs: ENS_NAME_CACHE_MS,\n })\n return name\n })\n .catch((error: unknown) => {\n console.warn(\n `${LOG_PREFIX} Could not read the name of 0x${bare}:`,\n describeFailure(error),\n )\n cache.set(key, {\n name: undefined,\n fetchedAt: Date.now(),\n keepMs: ENS_NAME_FAILURE_CACHE_MS,\n })\n return undefined\n })\n .finally(() => {\n inFlight.delete(key)\n })\n inFlight.set(key, read)\n return read\n}\n","import { universalResolverReverseAbi } from '../../constants/abis.js';\nimport { getChainContractAddress, } from '../../utils/chain/getChainContractAddress.js';\nimport { isNullUniversalResolverError } from '../../utils/ens/errors.js';\nimport { localBatchGatewayUrl } from '../../utils/ens/localBatchGatewayRequest.js';\nimport { getAction } from '../../utils/getAction.js';\nimport { readContract, } from '../public/readContract.js';\n/**\n * Gets primary name for specified address.\n *\n * - Docs: https://viem.sh/docs/ens/actions/getEnsName\n * - Examples: https://stackblitz.com/github/wevm/viem/tree/main/examples/ens\n *\n * Calls `reverse(bytes)` on ENS Universal Resolver Contract to \"reverse resolve\" the address to the primary ENS name.\n *\n * @param client - Client to use\n * @param parameters - {@link GetEnsNameParameters}\n * @returns Name or `null` if not found. {@link GetEnsNameReturnType}\n *\n * @example\n * import { createPublicClient, http } from 'viem'\n * import { mainnet } from 'viem/chains'\n * import { getEnsName } from 'viem/ens'\n *\n * const client = createPublicClient({\n * chain: mainnet,\n * transport: http(),\n * })\n * const ensName = await getEnsName(client, {\n * address: '0xd2135CfB216b74109775236E36d4b433F1DF507B',\n * })\n * // 'wevm.eth'\n */\nexport async function getEnsName(client, parameters) {\n const { address, blockNumber, blockTag, coinType = 60n, gatewayUrls, strict, } = parameters;\n const { chain } = client;\n const universalResolverAddress = (() => {\n if (parameters.universalResolverAddress)\n return parameters.universalResolverAddress;\n if (!chain)\n throw new Error('client chain not configured. universalResolverAddress is required.');\n return getChainContractAddress({\n blockNumber,\n chain,\n contract: 'ensUniversalResolver',\n });\n })();\n try {\n const readContractParameters = {\n address: universalResolverAddress,\n abi: universalResolverReverseAbi,\n args: [address, coinType, gatewayUrls ?? [localBatchGatewayUrl]],\n functionName: 'reverseWithGateways',\n blockNumber,\n blockTag,\n };\n const readContractAction = getAction(client, readContract, 'readContract');\n const [name] = await readContractAction(readContractParameters);\n return name || null;\n }\n catch (err) {\n if (strict)\n throw err;\n if (isNullUniversalResolverError(err))\n return null;\n throw err;\n }\n}\n//# sourceMappingURL=getEnsName.js.map"],"names":["U32_MASK64","BigInt","_32n","fromBig","n","le","h","Number","l","collectionPath","file","relative","webkitRelativePath","replace","name","initDeadline","work","ms","message","withTimeout","catch","error","TimeoutError","SwarmIdError","cause","checkedButtonConfig","config","undefined","parsed","ButtonConfigSchema","safeParse","success","data","issue","issues","path","join","checkedButtonAction","action","ButtonActionSchema","JSON","stringify","parseBeeApiUrl","url","isBeeApiUrl","SwarmIdClient","constructor","options","this","mountedButtons","Map","ready","pendingRequests","progressListeners","requestIdCounter","window","Error","iframeOrigin","iframePath","timeout","initializationTimeout","onConnectionChange","popupMode","metadata","subsidisedGatewayUrl","beeApiUrl","AppMetadataSchema","parse","setupMessageListener","initialize","iframe","firstConnectionInfoPromise","Promise","resolve","reject","firstConnectionInfoResolve","firstConnectionInfoReject","proxyInitializedPromise","proxyInitializedResolve","proxyInitializedReject","readyPromise","readyResolve","readyReject","document","createElement","src","style","display","iframeLoadReject","onload","onerror","body","appendChild","sendMessage","type","requestId","generateRequestId","messageListener","event","source","contentWindow","expectedOrigin","URL","origin","console","warn","IframeToParentMessageSchema","handleIframeMessage","addEventListener","storageShared","info","canUpload","storagePartitioned","uploadMode","uploadUnavailableReason","identity","appKey","partition","chatBinding","postageBatchId","lastConnectionInfo","pending","get","clearTimeout","timeoutId","delete","fromWire","total","processed","ParentToIframeMessageSchema","postMessage","sendRequest","roundTripTimeout","requestOptions","setTimeout","set","perCall","Math","min","Date","now","normalizeSocIdentifier","identifier","Identifier","toHex","Uint8Array","uint8ArrayToHex","normalizeSocKey","key","normalizeFeedTopic","topic","Topic","toUint8Array","normalizeReference","reference","normalizeFeedTimestamp","value","toString","floor","normalizeFeedIndex","normalizePayload","TextEncoder","encode","socChunkFromResponse","response","signature","span","payload","address","owner","ensureReady","checkAuthStatus","authenticated","setBeeApiUrl","getPostageBatch","postageBatch","disconnect","connect","openAuthWindow","mountButton","container","loaded","settled","windowOpen","unmounted","frame","resolveReady","rejectReady","title","Object","assign","border","backgroundColor","width","height","borderRadius","then","post","listener","BUTTON_FRAME_LOADED","ButtonToParentMessageSchema","state","remove","onWindowChange","mounted","removeEventListener","update","next","unmount","has","basePath","authUrl","buildAuthUrl","location","popup","open","Boolean","connectionInfo","getAvatar","size","avatar","generatedAvatar","id","isBeeConnected","connected","getNodeInfo","beeMode","chequebookEnabled","swapEnabled","uploadData","onProgress","useWebSocket","useWorkers","workerCount","concurrency","serializableOptions","stopProgress","listenForProgress","enableProgress","tagUid","downloadData","deriveAppSecret","label","secret","getChatKey","chatKey","stampChunk","chunk","wireChunk","kind","signer","privateKey","stamp","uploadFile","fileName","File","buffer","arrayBuffer","slice","byteOffset","byteLength","downloadFile","uploadFiles","files","entries","all","Array","from","async","item","contentType","listFiles","uploadChunk","_onProgress","downloadChunk","makeSOCReader","ownerAddress","EthAddress","sendSocDownload","encryptionKey","sendRawSocDownload","getOwner","rawDownload","download","makeSOCWriter","signerObj","PrivateKey","signerKey","publicKey","sendSocUpload","sendRawSocUpload","upload","rawUpload","makeEpochFeedReader","downloadReference","atValue","at","after","cleanRef","startsWith","length","downloadRawReference","downloadPayload","result","downloadRawPayload","makeEpochFeedWriter","uploadReference","normalizedRef","derivedKey","feedKey","hints","socAddress","epoch","timestamp","uploadPayload","encrypt","uploadResult","uploadOptions","uploadRawReference","uploadRawPayload","makeSequentialFeedReader","index","hasTimestamp","lookupTimeoutMs","feedIndex","feedIndexNext","makeSequentialFeedWriter","createFeedManifest","normalizedTopic","feedType","gsocMine","targetOverlay","proximity","gsocSend","actUploadData","grantees","encryptedReference","historyReference","granteeListReference","publisherPubKey","actReference","actDownloadData","actAddGrantees","actRevokeGrantees","revokeGrantees","actGetGrantees","destroy","destroyed","values","forEach","clear","parentNode","removeChild","buildBzzManifestNode","contentReference","refBytes","hexToUint8Array","manifest","MantarayNode","addFork","NULL_ADDRESS","Filename","manifestNode","popcount8","count","isAllZeros","arr","i","extractEntryFromManifest","manifestData","entry","ENTRY_OFFSET","Reference","extractContentFromFlatManifest","indexBitmap","INDEX_BITMAP_OFFSET","iByteIndex","forkIndex","byte","bit","forkOffset","flags","forkFlags","prefixLen","prefixBytes","expectedPrefix","every","b","referenceOffset","BaseError","shortMessage","args","details","docsPath","super","metaMessages","defineProperty","enumerable","configurable","writable","execTyped","regex","string","match","exec","groups","bytesRegex","integerRegex","isTupleRegex","tupleRegex","formatAbiParameter","abiParameter","test","components","array","indexed","formatAbiParameters","abiParameters","params","errorSignatureRegex","eventSignatureRegex","functionSignatureRegex","structSignatureRegex","isStructSignature","execStructSignature","constructorSignatureRegex","fallbackSignatureRegex","receiveSignatureRegex","eventModifiers","Set","functionModifiers","UnknownTypeError","UnknownSolidityTypeError","InvalidParameterError","param","SolidityProtectedKeywordError","InvalidModifierError","modifier","InvalidFunctionModifierError","InvalidAbiTypeParameterError","InvalidSignatureError","UnknownSignatureError","InvalidStructSignatureError","CircularReferenceError","InvalidParenthesisError","current","depth","trim","parameterCache","parseSignature","structs","isFunctionSignature","execFunctionSignature","inputParams","splitParameters","parameters","inputs","inputLength","push","parseAbiParameter","modifiers","outputs","returns","outputParams","outputLength","stateMutability","parseFunctionSignature","isEventSignature","execEventSignature","parseEventSignature","isErrorSignature","execErrorSignature","parseErrorSignature","isConstructorSignature","execConstructorSignature","parseConstructorSignature","isFallbackSignature","execFallbackSignature","parseFallbackSignature","isReceiveSignature","abiParameterWithoutTupleRegex","abiParameterWithTupleRegex","dynamicIntegerRegex","parameterCacheKey","structKey","struct","propertyKey","property","getParameterCacheKey","isTuple","protectedKeywordsRegex","isSolidityKeyword","components_","isSolidityType","isArray","isValidDataLocation","char","tail","typeWithoutTupleRegex","resolveStructs","ancestors","parseAbi","signatures","shallowStructs","signaturesLength","properties","split","propertiesLength","k","trimmed","resolvedStructs","entriesLength","parseStructs","abi","getAction","client","actionFn","action_implicit","action_explicit","formatAbiItem","abiItem","includeName","InvalidDefinitionTypeError","formatAbiParams","map","formatAbiParam","isHex","strict","ceil","version","errorConfig","docsBaseUrl","docsSlug","docsUrl","walk","fn","err","AbiConstructorNotFoundError","AbiConstructorParamsNotFoundError","AbiDecodingDataSizeTooSmallError","AbiDecodingZeroDataError","AbiEncodingArrayLengthMismatchError","expectedLength","givenLength","AbiEncodingBytesSizeMismatchError","expectedSize","AbiEncodingLengthMismatchError","AbiErrorInputsNotFoundError","errorName","AbiErrorNotFoundError","AbiErrorSignatureNotFoundError","AbiFunctionNotFoundError","functionName","AbiFunctionOutputsNotFoundError","AbiFunctionSignatureNotFoundError","AbiItemAmbiguityError","x","y","InvalidAbiEncodingTypeError","InvalidAbiDecodingTypeError","InvalidArrayError","SliceOffsetOutOfBoundsError","offset","position","targetSize","charAt","toUpperCase","toLowerCase","InvalidBytesLengthError","pad","hexOrBytes","dir","padHex","bytes","SizeExceedsPaddingSizeError","paddedBytes","padEnd","padBytes","hex_","hex","max","signed","InvalidBytesBooleanError","SizeOverflowError","givenSize","maxSize","sliceLength","assertSize","size_","hexToBigInt","opts","padStart","hexes","_v","boolToHex","bytesToHex","numberToHex","value_","maxValue","MAX_SAFE_INTEGER","minValue","suffix","IntegerOutOfRangeError","encoder","stringToHex","toBytes","hexToBytes","numberToBytes","boolToBytes","stringToBytes","charCodeMap","zero","nine","A","F","a","f","charCodeToBase16","hexString","j","nibbleLeft","charCodeAt","nibbleRight","_0n","_1n","_2n","_7n","_256n","_0x71n","SHA3_PI","SHA3_ROTL","_SHA3_IOTA","round","R","t","IOTAS","lst","len","Ah","Uint32Array","Al","SHA3_IOTA_H","SHA3_IOTA_L","rotlH","s","rotlBH","rotlSH","rotlL","rotlBL","rotlSL","Keccak","Hash","blockLen","outputLen","enableXOF","rounds","pos","posOut","finished","anumber","state32","u32","clone","_cloneInto","keccak","swap32IfBE","B","idx1","idx0","B0","B1","Th","Tl","curH","curL","shift","PI","clean","keccakP","aexists","abytes","take","finish","writeInto","out","bufferOut","subarray","xofInto","xof","digestInto","aoutput","digest","to","keccak_256","gen","createHasher","keccak256","to_","hashSignature","sig","toSignature","def","active","level","valid","includes","normalizeSignature","toSignatureHash","toEventSelector","InvalidAddressError","LruMap","firstKey","keys","checksumAddressCache","checksumAddress","address_","chainId","hexAddress","substring","hash","addressRegex","isAddressCache","isAddress","cacheKey","concat","concatHex","concatBytes","reduce","acc","start","end","assertStartOffset","assertEndOffset","sliceHex","sliceBytes","encodeAbiParameters","preparedParams","prepareParam","prepareParams","encodeParams","arrayComponents","getArrayComponents","dynamic","dynamicChild","isDynamicType","preparedParam","encoded","encodeArray","param_","encodeTuple","encodeAddress","encodeBool","encodeNumber","paramSize","bytesSize","parseInt","encodeBytes","hexValue","partsLength","parts","encodeString","staticSize","staticParams","dynamicParams","dynamicSize","matches","endsWith","some","toFunctionSelector","getAbiItem","isSelector","abiItems","filter","matchedAbiItem","matched","arg","isArgOfType","ambiguousTypes","getAmbiguousTypes","argType","abiParameterType","component","sourceParameters","targetParameters","parameterIndex","sourceParameter","targetParameter","types","parseAccount","account","encodeFunctionData","prepareEncodeFunctionData","panicReasons","solidityError","solidityPanic","NegativeOffsetError","PositionOutOfBoundsError","RecursiveReadLimitExceededError","limit","staticCursor","dataView","DataView","ArrayBuffer","positionReadCount","recursiveReadCount","recursiveReadLimit","POSITIVE_INFINITY","assertReadLimit","assertPosition","decrementPosition","getReadCount","incrementPosition","inspectByte","position_","inspectBytes","inspectUint8","inspectUint16","getUint16","inspectUint24","getUint8","inspectUint32","getUint32","pushByte","pushBytes","pushUint8","pushUint16","setUint16","pushUint24","setUint8","pushUint32","setUint32","readByte","_touch","readBytes","readUint8","readUint16","readUint24","readUint32","remaining","setPosition","oldPosition","bytesToBigInt","bytesToBool","bytes_","bytesToNumber","number","isSafeInteger","MIN_SAFE_INTEGER","hexToNumber","decodeAbiParameters","cursor","create","createCursor","consumed","consumed_","decodeParameter","staticPosition","sizeOfOffset","startOfData","sizeOfLength","hasDynamicChild","decodeArray","hasUnnamedChild","decodeTuple","decodeAddress","decodeBool","_","decodeBytes","decodeNumber","TextDecoder","decode","bytesToString","decodeString","decodeErrorResult","find","replacer","space","formatAbiItemWithArgs","includeFunctionName","input","exponents","wei","gwei","szabo","finney","ether","format","decimals","isInteger","InvalidDecimalsError","negative","integer","fraction","formatEther","unit","Value.formatEther","formatGwei","Value.formatGwei","AccountStateConflictError","StateAssignmentConflictError","prettyStateMapping","stateMapping","pretty","slot","prettyPrint","maxLength","getAbortError","signal","reason","DOMException","isAbortError","getUrl","username","password","CallExecutionError","account_","chain","gas","gasPrice","maxFeePerGas","maxPriorityFeePerGas","nonce","stateOverride","prettyArgs","nativeCurrency","symbol","val","balance","code","stateDiff","prettyStateOverride","ContractFunctionExecutionError","contractAddress","sender","formattedArgs","function","ContractFunctionRevertedError","decodedData","errorArgs","firstArg","errorWithParams","raw","ContractFunctionZeroDataError","CounterfactualDeploymentFailedError","factory","RawContractError","HttpRequestError","headers","status","ResponseBodyTooLargeError","RpcRequestError","RpcError","ProviderRpcError","ParseRpcError","InvalidRequestRpcError","MethodNotFoundRpcError","method","InvalidParamsRpcError","InternalRpcError","InvalidInputRpcError","ResourceNotFoundRpcError","ResourceUnavailableRpcError","TransactionRejectedRpcError","MethodNotSupportedRpcError","LimitExceededRpcError","JsonRpcVersionUnsupportedError","UserRejectedRequestError","UnauthorizedProviderError","UnsupportedProviderMethodError","ProviderDisconnectedError","ChainDisconnectedError","SwitchChainError","UnsupportedNonOptionalCapabilityError","UnsupportedChainIdError","DuplicateIdError","UnknownBundleIdError","BundleTooLargeError","AtomicReadyWalletRejectedUpgradeError","AtomicityNotSupportedError","WalletConnectSessionSettlementError","UnknownRpcError","EXECUTION_REVERTED_ERROR_CODE","ExecutionRevertedError","FeeCapTooHighError","FeeCapTooLowError","NonceTooHighError","NonceTooLowError","NonceMaxValueError","InsufficientFundsError","IntrinsicGasTooHighError","IntrinsicGasTooLowError","TransactionTypeNotSupportedError","TipAboveFeeCapError","UnknownNodeError","extract","extract_","formatted","rpcTransactionType","legacy","eip2930","eip1559","eip4844","eip7702","formatTransactionRequest","request","rpcRequest","authorizationList","authorization","r","yParity","v","accessList","blobVersionedHashes","blobs","maxFeePerBlobGas","serializeStateMapping","serializeAccountStateOverride","rpcAccountStateOverride","maxUint256","formatBlockParameter","blockHash","blockNumber","blockTag","requireCanonical","isAddressEqual","decodeFunctionResult","setStaticOptions","prototype","docsOrigin","showVersion","docs","fromNumber","asUintN","Hex.SizeExceedsPaddingSizeError","internal.pad","padLeft","defaultStaticOptions","Errors.BaseError","toRpc","withdrawal","amount","Hex.fromNumber","validatorIndex","multicall3Abi","internalType","batchGatewayAbi","universalResolverReverseAbi","aggregate3Signature","deploylessCallViaFactoryBytecode","multicall3Bytecode","ChainDoesNotSupportContract","contract","blockCreated","ClientChainNotConfiguredError","encodeDeployData","bytecode","description","getChainContractAddress","contracts","getCallError","executionRevertedError","e","nodeMessage","getNodeError","schedulerCache","createBatchScheduler","shouldSplitBatch","wait","sort","scheduler","getScheduler","flush","setScheduler","schedule","promise","resolve_","reject_","withResolvers","call","batch","multicall","experimental_blockTag","blockOverrides","data_","factoryData","rest","deploylessCallViaBytecode","deploylessCallViaFactory","deploylessCall","toDeploylessCallViaBytecodeData","toDeploylessCallViaFactoryData","assertRequest","block","rpcBlockOverrides","baseFeePerGas","blobBaseFee","feeRecipient","gasLimit","prevRandao","time","withdrawals","Withdrawal.toRpc","BlockOverrides.toRpc","rpcStateOverride","accountState","serializeStateOverride","chainFormat","formatters","transactionRequest","request_","shouldPerformMulticall","deployless","multicallAddress","getMulticallAddress","stateOverrideAddress","hasStateOverrideForAddress","batchSize","multicallAddress_","blockId","stateOverrideKey","uid","getRequestOptionsId","requests","calls","allowFailure","callData","target","calldata","multicallRequest","returnData","scheduleMulticall","base","aborted","getRevertErrorData","offchainLookup","offchainLookupSignature","import","ccipRead","requestOptionsId","requestOptionsIds","WeakMap","nextId","readContract","getContractError","withRetry","delay","delay_","retryCount","shouldRetry","attemptRetry","retry","cleanup","onAbort","once","random","isPlainObject","getPrototypeOf","encodeErrorResult","definition","localBatchGatewayUrl","localBatchGatewayRequest","ccipRequest","queries","decodeFunctionData","failures","responses","query","urls","encodeFunctionResult","promiseCache","buildRequest","overrideOptions","dedupe","methods","retryDelay","exclude","include","enabled","finally","withDedupe","err_","retryAfter","str","seed","h1","h2","ch","imul","hashString","defineChain","chainInstance","fees","serializers","extend","fnOrExtended","combined","createIdStore","reset","idCache","defaultMaxResponseBodySize","getHttpRpcClient","url_","headers_url","credentials","decodeURIComponent","Authorization","btoa","parseUrl","fetchFn","fetch","maxResponseBodySize","onRequest","onResponse","fetchOptions","signal_","errorInstance","controller","AbortController","abort","init","jsonrpc","Request","responseBody","text","contentLength","reader","getReader","decoder","done","read","cancel","stream","releaseLock","readResponseBody","ok","statusText","UrlRequiredError","signalId","signalIds","getSignalId","http","onFetchRequest","onFetchResponse","retryCount_","timeout_","rpcUrls","default","rpcClient","uid_","createTransport","mainnet","blockTime","blockExplorers","apiUrl","ensUniversalResolver","multicall3","FENCED","read_compressed_payload","read_payload","u16","symbol_count","skip","pos_payload","read_width","read_buffer","read_bit","FULL","HALF","QRTR","MASK","register","symbols","low","range","mid","decode_arithmetic","lookup","c","ret","carry","unsafe_atob","read_deltas","read_sorted","prev","read_sorted_arrays","read_array_while","read_mapped","w","read_linear_table","read_replacement_table","flat","read_transposed","m","fill","dx","dy","vN","flatMap","ys","j_dy","quote_cp","cp","hex_cp","str_from_cps","cps","String","fromCodePoint","buf","compare_arrays","S0","L0","V0","T0","T_COUNT","N_COUNT","V_COUNT","unpack_cc","packed","unpack_cp","SHIFTED_RANK","EXCLUSIONS","DECOMP","RECOMP","is_hangul","compose_pair","recomp","decomposed","bucket","reverse","init$1","check_order","add","cc","s_index","v_index","t_index","mapped","pop","prev_cc","tmp","nfd","nfc","stack","prev_cp","composed","composed_from_decomposed","STOP_CH","Array_from","group_has_cp","g","P","Q","Emoji","is_emoji","MAPPED","IGNORED","CM","NSM","ESCAPE","GROUPS","WHOLE_VALID","WHOLE_MAP","VALID","EMOJI_LIST","EMOJI_ROOT","read_sorted_array","read_sorted_set","set_add_many","chunks","unrestricted","read_chunked","N","M","wholes","d","V","recs","gs","rec","G","union","complement","multi","add_to_union","sorted","expand","S","saved","br","read_trie","node","child","quoted_cp","should_escape","bidi_qq","safe_str_from_cps","Infinity","quoter","ens_normalize","output","msg","flatten","nf","ef","codePointAt","explode_cp","tokens","chars","emoji","consume_emoji_reversed","error_disallowed","tokens_from_str","token_count","norm","lastIndexOf","check_leading_underscore","check_label_extension","error_placement","last","check_fenced","unique","error_group_member","determine_group","check_group","group","maker","shared","whole","check_whole","filter_fe0f","quoted","gg","where","eaten","normalize","Ens.normalize","ENS_NAME_CACHE_MS","ENS_NAME_FAILURE_CACHE_MS","NO_NAME_REVERTS","WALLET_PATTERN","cache","inFlight","readVerifiedName","rpcUrl","wallet","timeoutMs","dataSuffix","experimental_preconfirmationTime","defaultPollingInterval","pollingInterval","cacheTime","transport","extendFn","extended","createClient","coinType","gatewayUrls","universalResolverAddress","readContractParameters","readContractAction","getEnsName","isNormalised","revert","isNoNameRevert","resolveVerifiedEnsName","bare","cached","age","fetchedAt","keepMs","CHAIN_READ_TIMEOUT_MS","describeFailure"],"mappings":"+QAKA,MAAMA,EAA6BC,OAAO,GAAK,GAAK,GAC9CC,EAAuBD,OAAO,IACpC,SAASE,EAAQC,EAAGC,GAAK,GACrB,OAAIA,EACO,CAAEC,EAAGC,OAAOH,EAAIJ,GAAaQ,EAAGD,OAAQH,GAAKF,EAAQF,IACzD,CAAEM,EAAsC,EAAnCC,OAAQH,GAAKF,EAAQF,GAAiBQ,EAA4B,EAAzBD,OAAOH,EAAIJ,GACpE,CCHM,SAAUS,EACdC,GAEA,MAAMC,EAAWD,EAAKE,mBACtB,OAAOD,EAAWA,EAASE,QAAQ,WAAY,IAAMH,EAAKI,IAC5D,CCyGA,SAASC,EACPC,EACAC,EACAC,GAEA,OAAOC,EAAYH,EAAMC,EAAIC,GAASE,MAAOC,IAC3C,MAAMA,aAAiBC,EACnB,IAAIC,EAAa,cAAeF,EAAMH,QAAS,CAAEM,MAAOH,IACxDA,GAER,CAOA,SAASI,EACPC,GAEA,QAAeC,IAAXD,EAAsB,OAC1B,MAAME,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SAAWJ,GAAengC,KAAKwgC,GAC1C,OAEF,MAAMqB,EAAOrB,EAAO72B,cAAc1iB,QAAQ,MAAO,IAC3CuI,EAAM,GAAGrG,EAAQo3C,WAAWsB,IAC5BC,EAAS1B,GAAMtyC,IAAI0B,GACzB,GAAIsyC,EAAQ,CACV,MAAMC,EAAMhzC,KAAKC,MAAQ8yC,EAAOE,UAChC,GAAID,GAAO,GAAKA,EAAMD,EAAOG,OAC3B,OAAOH,EAAO56C,KAEhBk5C,GAAMnyC,OAAOuB,EACf,CACA,MAAM3B,EAAUwyC,GAASvyC,IAAI0B,GAC7B,GAAI3B,EACF,OAAOA,EAET,MAAM4yC,EAAYt3C,EAAQs3C,WAAayB,EACjCjP,EAAO1rC,EACX+4C,GAAiBn3C,EAAQo3C,OAAQ,KAAKsB,IAAQpB,GAC9CA,EACA,qBAAqBoB,yBAA4BpB,QAEhDjuC,KAAMtL,IACLk5C,GAAMzxC,IAAIa,EAAK,CACbtI,OACA86C,UAAWjzC,KAAKC,MAChBizC,OAAQjC,KAEH94C,IAERM,MAAOC,IACNmF,QAAQC,KACN,0CAA8Cg1C,KA3DtD,SAAyBp6C,GACvB,OAAIA,aAAiBgX,GACZhX,EAAMiX,aAERjX,aAAiBmC,MAAQnC,EAAMH,QAAUuwC,OAAOpwC,EACzD,CAuDQ06C,CAAgB16C,IAElB24C,GAAMzxC,IAAIa,EAAK,CACbtI,UAAMa,EACNi6C,UAAWjzC,KAAKC,MAChBizC,OA1JiC,QA8JpCnS,QAAQ,KACPuQ,GAASpyC,OAAOuB,KAGpB,OADA6wC,GAAS1xC,IAAIa,EAAKyjC,GACXA,CACT","x_google_ignoreList":[0,4,5,6,7,8,9,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,119]}