@zama-fhe/sdk 3.7.0-alpha.2 → 3.7.0-beta.2

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.
Files changed (102) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/chains.cjs +1 -1
  4. package/dist/cjs/chains.cjs.map +1 -1
  5. package/dist/cjs/erc165.cjs +2 -0
  6. package/dist/cjs/erc165.cjs.map +1 -0
  7. package/dist/cjs/ethers/index.cjs +1 -1
  8. package/dist/cjs/ethers/index.cjs.map +1 -1
  9. package/dist/cjs/fhevm-relayer.cjs +2 -2
  10. package/dist/cjs/fhevm-relayer.cjs.map +1 -1
  11. package/dist/cjs/index.cjs +1 -1
  12. package/dist/cjs/index.cjs.map +1 -1
  13. package/dist/cjs/invalidation.cjs +2 -0
  14. package/dist/cjs/invalidation.cjs.map +1 -0
  15. package/dist/cjs/primitives.cjs +2 -0
  16. package/dist/cjs/primitives.cjs.map +1 -0
  17. package/dist/cjs/query/index.cjs +1 -1
  18. package/dist/cjs/query/index.cjs.map +1 -1
  19. package/dist/cjs/relayer.cjs +1 -1
  20. package/dist/cjs/relayer.cjs.map +1 -1
  21. package/dist/cjs/token.cjs +1 -1
  22. package/dist/cjs/token.cjs.map +1 -1
  23. package/dist/cjs/vaults/index.cjs +2 -0
  24. package/dist/cjs/vaults/index.cjs.map +1 -0
  25. package/dist/cjs/viem/index.cjs +1 -1
  26. package/dist/cjs/viem/index.cjs.map +1 -1
  27. package/dist/cjs/wrapped-token.cjs +2 -0
  28. package/dist/cjs/wrapped-token.cjs.map +1 -0
  29. package/dist/cjs/wrappers-registry.cjs +1 -1
  30. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  31. package/dist/esm/base-signer-D5Cwv7yb.js +2 -0
  32. package/dist/esm/base-signer-D5Cwv7yb.js.map +1 -0
  33. package/dist/esm/{base-signer-S2Ogf6L4.d.ts → base-signer-DIYZwDnc.d.ts} +2 -2
  34. package/dist/esm/chains/index.d.ts +1 -1
  35. package/dist/esm/chains/index.js +1 -1
  36. package/dist/esm/chains-ByyCdrrd.js +2 -0
  37. package/dist/esm/chains-ByyCdrrd.js.map +1 -0
  38. package/dist/esm/cleartext/index.d.ts +2 -2
  39. package/dist/esm/cleartext/index.js +1 -1
  40. package/dist/esm/{cleartext-pv2blbFU.d.ts → cleartext-3HOk1BAg.d.ts} +2 -2
  41. package/dist/esm/{cleartext-DcbDCDXj.js → cleartext-PCpNqRGV.js} +2 -2
  42. package/dist/esm/{cleartext-DcbDCDXj.js.map → cleartext-PCpNqRGV.js.map} +1 -1
  43. package/dist/esm/encrypt.worker.js +51 -51
  44. package/dist/esm/{encryption-DJljZ2oV.js → encryption-BKoalB4o.js} +2 -2
  45. package/dist/esm/{encryption-DJljZ2oV.js.map → encryption-BKoalB4o.js.map} +1 -1
  46. package/dist/esm/erc165-DbMOt-s6.js +2 -0
  47. package/dist/esm/erc165-DbMOt-s6.js.map +1 -0
  48. package/dist/esm/ethers/index.d.ts +5 -5
  49. package/dist/esm/ethers/index.js +1 -1
  50. package/dist/esm/ethers/index.js.map +1 -1
  51. package/dist/esm/fhevm-relayer-CtrnKjJf.js +8 -0
  52. package/dist/esm/fhevm-relayer-CtrnKjJf.js.map +1 -0
  53. package/dist/esm/{index-tfvbrVa2.d.ts → index-BHrjck_q.d.ts} +4 -4
  54. package/dist/esm/{index-DRrrBtMX.d.ts → index-DJYq1rAB.d.ts} +989 -1874
  55. package/dist/esm/{index-Gk1S0gjO.d.ts → index-ijgDL4IC.d.ts} +1 -14
  56. package/dist/esm/index.d.ts +8 -108
  57. package/dist/esm/index.js +1 -1
  58. package/dist/esm/index.js.map +1 -1
  59. package/dist/esm/invalidation-BgFjmXeQ.js +2 -0
  60. package/dist/esm/invalidation-BgFjmXeQ.js.map +1 -0
  61. package/dist/esm/invalidation-CJ-pzOUG.d.ts +46 -0
  62. package/dist/esm/node/index.d.ts +4 -4
  63. package/dist/esm/node/index.js +1 -1
  64. package/dist/esm/primitives-Cym-3HKa.js +2 -0
  65. package/dist/esm/primitives-Cym-3HKa.js.map +1 -0
  66. package/dist/esm/query/index.d.ts +495 -4
  67. package/dist/esm/query/index.js +1 -1
  68. package/dist/esm/query/index.js.map +1 -1
  69. package/dist/esm/relayer-CVKO9GmQ.js +2 -0
  70. package/dist/esm/relayer-CVKO9GmQ.js.map +1 -0
  71. package/dist/esm/token-CRJ8eCr7.js +2 -0
  72. package/dist/esm/token-CRJ8eCr7.js.map +1 -0
  73. package/dist/esm/{types-BOyFfG7D.d.ts → types-Bz5-wHPv.d.ts} +23 -43
  74. package/dist/esm/{types-BRIpBy9n.d.ts → types-CI6BtpB7.d.ts} +3 -3
  75. package/dist/esm/{types-OXQqX_kH.d.ts → types-v0_sfkli.d.ts} +3 -3
  76. package/dist/esm/{validation-DWe2k89s.js → validation-BRu06AM_.js} +2 -2
  77. package/dist/esm/{validation-DWe2k89s.js.map → validation-BRu06AM_.js.map} +1 -1
  78. package/dist/esm/vaults/index.d.ts +13833 -0
  79. package/dist/esm/vaults/index.js +2 -0
  80. package/dist/esm/vaults/index.js.map +1 -0
  81. package/dist/esm/viem/index.d.ts +5 -5
  82. package/dist/esm/viem/index.js +1 -1
  83. package/dist/esm/viem/index.js.map +1 -1
  84. package/dist/esm/web/index.d.ts +1 -1
  85. package/dist/esm/web/index.js +1 -1
  86. package/dist/esm/wrapped-token-BOtzaSAY.js +2 -0
  87. package/dist/esm/wrapped-token-BOtzaSAY.js.map +1 -0
  88. package/dist/esm/wrappers-registry-Cm3JJeqx.js +2 -0
  89. package/dist/esm/wrappers-registry-Cm3JJeqx.js.map +1 -0
  90. package/package.json +19 -5
  91. package/dist/esm/base-signer--sBO2qJp.js +0 -2
  92. package/dist/esm/base-signer--sBO2qJp.js.map +0 -1
  93. package/dist/esm/chains-DEpKup1n.js +0 -2
  94. package/dist/esm/chains-DEpKup1n.js.map +0 -1
  95. package/dist/esm/fhevm-relayer-CPmCytDX.js +0 -8
  96. package/dist/esm/fhevm-relayer-CPmCytDX.js.map +0 -1
  97. package/dist/esm/relayer-B6Zo6EkX.js +0 -2
  98. package/dist/esm/relayer-B6Zo6EkX.js.map +0 -1
  99. package/dist/esm/token-BMQ6xlrk.js +0 -2
  100. package/dist/esm/token-BMQ6xlrk.js.map +0 -1
  101. package/dist/esm/wrappers-registry-BfQr2QHn.js +0 -2
  102. package/dist/esm/wrappers-registry-BfQr2QHn.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../../src/query/utils.ts","../../../src/query/query-keys.ts","../../../src/query/invalidation.ts","../../../src/query/token-metadata.ts","../../../src/query/is-confidential.ts","../../../src/query/total-supply.ts","../../../src/query/wrapper-discovery.ts","../../../src/query/underlying-allowance.ts","../../../src/query/pending-unshield.ts","../../../src/query/confidential-is-operator.ts","../../../src/query/confidential-balance.ts","../../../src/query/confidential-balances.ts","../../../src/query/wrappers-registry.ts","../../../src/query/shield.ts","../../../src/query/transfer.ts","../../../src/query/transfer-and-call.ts","../../../src/query/transfer-from.ts","../../../src/query/transfer-from-and-call.ts","../../../src/query/set-operator.ts","../../../src/query/approve-underlying.ts","../../../src/query/unshield.ts","../../../src/query/unshield-all.ts","../../../src/query/resume-unshield.ts","../../../src/query/unwrap.ts","../../../src/query/wrap.ts","../../../src/query/unwrap-all.ts","../../../src/query/finalize-unwrap.ts","../../../src/query/encrypt.ts","../../../src/query/delegated-decrypt.ts","../../../src/query/public-decrypt.ts","../../../src/query/grant-permit.ts","../../../src/query/prepare-permit.ts","../../../src/query/register-permit.ts","../../../src/query/has-permit.ts","../../../src/query/revoke-permits.ts","../../../src/query/clear-credentials.ts","../../../src/query/delegate-decryption.ts","../../../src/query/user-decrypt.ts","../../../src/query/decrypt-balance-as.ts","../../../src/query/batch-decrypt-balances-as.ts","../../../src/query/revoke-delegation.ts","../../../src/query/invalidate-decryption-signatures.ts","../../../src/query/delegation-status.ts"],"sourcesContent":["// Adapted from the wagmi codebase\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-wrapper-object-types\nfunction isPlainObject(value: any): value is Object {\n if (!hasObjectPrototype(value)) {\n return false;\n }\n\n // If has modified constructor\n const ctor = value.constructor;\n if (ctor === undefined) {\n return true;\n }\n\n // If has modified prototype\n const prot = ctor.prototype;\n if (!hasObjectPrototype(prot)) {\n return false;\n }\n\n // If constructor does not have an Object-specific method\n // eslint-disable-next-line no-prototype-builtins\n if (!prot.hasOwnProperty(\"isPrototypeOf\")) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === \"[object Object]\";\n}\n\n/** Union of TanStack Query option keys stripped by {@link filterQueryOptions}, leaving only domain parameters. */\nexport type StrippedQueryOptionKeys =\n // Keep this union aligned with @tanstack/query-core behavioral options\n // (for example QueryObserverOptions). Revisit on every upgrade to avoid\n // leaking query controls into lower-level query factories.\n | \"gcTime\"\n | \"staleTime\"\n | \"enabled\"\n | \"select\"\n | \"refetchInterval\"\n | \"refetchOnMount\"\n | \"refetchOnWindowFocus\"\n | \"refetchOnReconnect\"\n | \"retry\"\n | \"retryDelay\"\n | \"retryOnMount\"\n | \"queryFn\"\n | \"queryKey\"\n | \"queryKeyHashFn\"\n | \"initialData\"\n | \"initialDataUpdatedAt\"\n | \"placeholderData\"\n | \"structuralSharing\"\n | \"throwOnError\"\n | \"meta\"\n | \"query\"\n | \"pollingInterval\";\n\n/**\n * Remove TanStack behavioral options from a query config object so only domain\n * parameters remain for the lower-level factory.\n *\n * @example\n * ```ts\n * const params = filterQueryOptions({\n * query: { enabled: false },\n * gcTime: 60_000,\n * owner: \"0xabc\",\n * });\n * // => { owner: \"0xabc\" }\n * ```\n */\nexport function filterQueryOptions<TOptions extends Record<string, unknown>>(\n options: TOptions,\n): Omit<TOptions, StrippedQueryOptionKeys> {\n const {\n gcTime: _gcTime,\n staleTime: _staleTime,\n enabled: _enabled,\n select: _select,\n refetchInterval: _refetchInterval,\n refetchOnMount: _refetchOnMount,\n refetchOnWindowFocus: _refetchOnWindowFocus,\n refetchOnReconnect: _refetchOnReconnect,\n retry: _retry,\n retryDelay: _retryDelay,\n retryOnMount: _retryOnMount,\n queryFn: _queryFn,\n queryKey: _queryKey,\n queryKeyHashFn: _queryKeyHashFn,\n initialData: _initialData,\n initialDataUpdatedAt: _initialDataUpdatedAt,\n placeholderData: _placeholderData,\n structuralSharing: _structuralSharing,\n throwOnError: _throwOnError,\n meta: _meta,\n query: _query,\n pollingInterval: _pollingInterval,\n ...rest\n } = options;\n\n return rest;\n}\n\n/**\n * Stable hash function for query keys.\n * Sorts object keys recursively and converts bigint values to strings.\n *\n * @remarks\n * bigint values are serialized as decimal strings, so `42n` and `\"42\"` hash to\n * the same token when they occupy the same position. This collision is accepted\n * by design for the current query-key conventions in this package.\n */\nexport function hashFn(queryKey: readonly unknown[]): string {\n return JSON.stringify(queryKey, (_, value) => {\n if (isPlainObject(value)) {\n return Object.keys(value)\n .sort()\n .reduce(\n (result, key) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n }\n\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return value;\n });\n}\n","import { getAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\nimport type { WalletAccount } from \"../types\";\n\nconst normalizeAddresses = (addresses: Address[]): Address[] =>\n addresses.map((address) => getAddress(address));\nconst normalizeAddress = (address?: Address): Address | undefined =>\n address === undefined ? undefined : getAddress(address);\nconst walletAccountKey = (walletAccount?: WalletAccount) =>\n walletAccount\n ? { walletAddress: getAddress(walletAccount.address), walletChainId: walletAccount.chainId }\n : {};\n\n/**\n * Canonical query-key namespace for `@zama-fhe/sdk/query`.\n *\n * @example\n * ```ts\n * queryClient.invalidateQueries({\n * queryKey: zamaQueryKeys.confidentialBalance.token(\"0xToken\"),\n * });\n * ```\n */\nexport const zamaQueryKeys = {\n confidentialBalance: {\n all: [\"zama.confidentialBalance\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.confidentialBalance\", { tokenAddress: getAddress(tokenAddress) }] as const,\n owner: (tokenAddress: Address, owner?: Address, walletAccount?: WalletAccount) =>\n [\n \"zama.confidentialBalance\",\n {\n tokenAddress: getAddress(tokenAddress),\n ...walletAccountKey(walletAccount),\n ...(owner ? { owner: getAddress(owner) } : {}),\n },\n ] as const,\n },\n\n confidentialBalances: {\n all: [\"zama.confidentialBalances\"] as const,\n tokens: (tokenAddresses: Address[], owner?: Address, walletAccount?: WalletAccount) =>\n [\n \"zama.confidentialBalances\",\n {\n tokenAddresses: normalizeAddresses(tokenAddresses),\n ...walletAccountKey(walletAccount),\n ...(owner ? { owner: getAddress(owner) } : {}),\n },\n ] as const,\n },\n\n tokenMetadata: {\n all: [\"zama.tokenMetadata\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.tokenMetadata\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n isConfidential: {\n all: [\"zama.isConfidential\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.isConfidential\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n isWrapper: {\n all: [\"zama.isWrapper\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.isWrapper\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n wrapperDiscovery: {\n all: [\"zama.wrapperDiscovery\"] as const,\n token: (tokenAddress?: Address, erc20Address?: Address, registryAddress?: Address) => {\n const t = normalizeAddress(tokenAddress);\n const e = normalizeAddress(erc20Address);\n const r = normalizeAddress(registryAddress);\n return [\n \"zama.wrapperDiscovery\",\n {\n ...(t ? { tokenAddress: t } : {}),\n ...(e ? { erc20Address: e } : {}),\n ...(r ? { registryAddress: r } : {}),\n },\n ] as const;\n },\n },\n\n underlyingAllowance: {\n all: [\"zama.underlyingAllowance\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.underlyingAllowance\", { tokenAddress: getAddress(tokenAddress) }] as const,\n scope: (tokenAddress: Address, owner?: Address) =>\n [\n \"zama.underlyingAllowance\",\n { tokenAddress: getAddress(tokenAddress), ...(owner ? { owner: getAddress(owner) } : {}) },\n ] as const,\n },\n\n confidentialIsOperator: {\n all: [\"zama.confidentialIsOperator\"] as const,\n token: (tokenAddress?: Address) => {\n const t = normalizeAddress(tokenAddress);\n return [\"zama.confidentialIsOperator\", t ? { tokenAddress: t } : {}] as const;\n },\n scope: (tokenAddress?: Address, holder?: Address, spender?: Address) => {\n const t = normalizeAddress(tokenAddress);\n const h = normalizeAddress(holder);\n const s = normalizeAddress(spender);\n return [\n \"zama.confidentialIsOperator\",\n {\n ...(t ? { tokenAddress: t } : {}),\n ...(h ? { holder: h } : {}),\n ...(s ? { spender: s } : {}),\n },\n ] as const;\n },\n },\n\n totalSupply: {\n all: [\"zama.totalSupply\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.totalSupply\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n pendingUnshield: {\n all: [\"zama.pendingUnshield\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.pendingUnshield\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n hasPermit: {\n all: [\"zama.hasPermit\"] as const,\n scope: (contractAddresses: Address[], walletAccount?: WalletAccount) =>\n [\n \"zama.hasPermit\",\n {\n ...walletAccountKey(walletAccount),\n contractAddresses: normalizeAddresses(contractAddresses).sort(),\n },\n ] as const,\n },\n\n delegationStatus: {\n all: [\"zama.delegationStatus\"] as const,\n contract: (contractAddress?: Address) => {\n const t = normalizeAddress(contractAddress);\n return [\"zama.delegationStatus\", t ? { contractAddress: t } : {}] as const;\n },\n scope: (contractAddress?: Address, delegator?: Address, delegate?: Address) => {\n const t = normalizeAddress(contractAddress);\n const dr = normalizeAddress(delegator);\n const de = normalizeAddress(delegate);\n return [\n \"zama.delegationStatus\",\n {\n ...(t ? { contractAddress: t } : {}),\n ...(dr ? { delegatorAddress: dr } : {}),\n ...(de ? { delegateAddress: de } : {}),\n },\n ] as const;\n },\n },\n\n decryption: {\n all: [\"zama.decryption\"] as const,\n encryptedValue: (encryptedValue: string, contractAddress?: Address) =>\n [\n \"zama.decryption\",\n {\n encryptedValue,\n ...(contractAddress === undefined\n ? {}\n : { contractAddress: getAddress(contractAddress) }),\n },\n ] as const,\n encryptedInputs: (\n encryptedInputs: readonly { encryptedValue: string; contractAddress: Address }[],\n walletAccount?: WalletAccount,\n ) =>\n [\n \"zama.decryption\",\n {\n ...walletAccountKey(walletAccount),\n encryptedInputs: [...encryptedInputs]\n .sort((a, b) => a.encryptedValue.localeCompare(b.encryptedValue))\n .map((h) => ({\n encryptedValue: h.encryptedValue as Hex,\n contractAddress: getAddress(h.contractAddress),\n })),\n },\n ] as const,\n },\n\n wrappersRegistry: {\n all: [\"zama.wrappersRegistry\"] as const,\n chainId: () => [\"zama.wrappersRegistry\", { type: \"chainId\" }] as const,\n tokenPairs: (registryAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n { type: \"tokenPairs\", registryAddress: getAddress(registryAddress) },\n ] as const,\n confidentialTokenAddress: (registryAddress: Address, tokenAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"confidentialTokenAddress\",\n registryAddress: getAddress(registryAddress),\n tokenAddress: getAddress(tokenAddress),\n },\n ] as const,\n tokenAddress: (registryAddress: Address, confidentialTokenAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"tokenAddress\",\n registryAddress: getAddress(registryAddress),\n confidentialTokenAddress: getAddress(confidentialTokenAddress),\n },\n ] as const,\n tokenPairsLength: (registryAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n { type: \"tokenPairsLength\", registryAddress: getAddress(registryAddress) },\n ] as const,\n tokenPairsSlice: (registryAddress: Address, fromIndex: string, toIndex: string) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"tokenPairsSlice\",\n registryAddress: getAddress(registryAddress),\n fromIndex,\n toIndex,\n },\n ] as const,\n tokenPair: (registryAddress: Address, index: string) =>\n [\n \"zama.wrappersRegistry\",\n { type: \"tokenPair\", registryAddress: getAddress(registryAddress), index },\n ] as const,\n isConfidentialTokenValid: (registryAddress: Address, confidentialTokenAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"isConfidentialTokenValid\",\n registryAddress: getAddress(registryAddress),\n confidentialTokenAddress: getAddress(confidentialTokenAddress),\n },\n ] as const,\n listPairs: (registryAddress: Address, page: number, pageSize: number, metadata: boolean) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"listPairs\",\n registryAddress: getAddress(registryAddress),\n page,\n pageSize,\n metadata,\n },\n ] as const,\n },\n} as const;\n","import type { Address } from \"viem\";\nimport { z } from \"zod/mini\";\nimport { zamaQueryKeys } from \"./query-keys\";\n\n/** Minimal query shape read by the invalidation predicates. */\nexport interface QueryLike {\n /** The query's cache key. */\n queryKey: readonly unknown[];\n}\n\n/** Minimal filter shape accepted by the invalidation helpers, matching TanStack Query's `QueryFilters`. */\nexport interface QueryFilterLike {\n /** Match queries whose key starts with this prefix. */\n queryKey?: readonly unknown[];\n /** Match queries for which this returns `true`. */\n predicate?: (query: QueryLike) => boolean;\n}\n\n/** Minimal `QueryClient` surface used by the invalidation helpers. */\nexport interface QueryClientLike {\n /** Mark matching queries stale so they refetch. */\n invalidateQueries(filters: QueryFilterLike): void | Promise<void>;\n /** Remove matching queries from the cache entirely. */\n removeQueries(filters: QueryFilterLike): void;\n}\n\nfunction invalidateUnderlyingAllowanceQueries(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: zamaQueryKeys.underlyingAllowance.token(tokenAddress),\n });\n}\n\nfunction invalidatePendingUnshieldQueries(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: zamaQueryKeys.pendingUnshield.token(tokenAddress),\n });\n}\n\n/** Invalidates the caches affected by an unwrap: confidential balances, underlying allowance, and pending unshields. */\nexport function invalidateAfterUnwrap(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidatePendingUnshieldQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\n/** Invalidates the caches affected by a wrap: confidential balances and underlying allowance. */\nexport function invalidateAfterWrap(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\n/** Invalidates the confidential balance queries for a token (single-token and batched). */\nexport function invalidateBalanceQueries(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: zamaQueryKeys.confidentialBalance.token(tokenAddress),\n });\n void queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalances.all });\n}\n\n/** Invalidates the caches affected by a shield: confidential balances and underlying allowance. */\nexport function invalidateAfterShield(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\n/** Invalidates the caches affected by an unshield request: confidential balances, underlying allowance, and pending unshields. */\nexport function invalidateAfterUnshield(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidatePendingUnshieldQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\n/** Invalidates the pending-unshield cache once an unshield has settled on-chain. */\nexport function invalidateAfterUnshieldSettled(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n invalidatePendingUnshieldQueries(queryClient, tokenAddress);\n}\n\n/** Invalidates the confidential balance caches affected by a transfer. */\nexport function invalidateAfterTransfer(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n}\n\n/** Invalidates the underlying-allowance cache after approving the underlying ERC-20. */\nexport function invalidateAfterApproveUnderlying(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n}\n\n/** Invalidates the operator-status cache after changing a token operator. */\nexport function invalidateAfterSetOperator(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: zamaQueryKeys.confidentialIsOperator.token(tokenAddress),\n });\n}\n\nfunction isZamaQuery(query: QueryLike): boolean {\n return Array.isArray(query.queryKey) && typeof query.queryKey[0] === \"string\"\n ? query.queryKey[0].startsWith(\"zama.\")\n : false;\n}\n\nconst balanceFunctionName = z.enum([\"balanceOf\", \"confidentialBalanceOf\"]);\n\nconst balanceReadArgs = z.object({ functionName: balanceFunctionName });\n\nconst batchedReadArgs = z.object({ contracts: z.array(z.unknown()) });\n\nfunction isBalanceReadPart(part: unknown): boolean {\n if (balanceReadArgs.safeParse(part).success) {\n return true;\n }\n const batched = batchedReadArgs.safeParse(part);\n return (\n batched.success && batched.data.contracts.some((c) => balanceReadArgs.safeParse(c).success)\n );\n}\n\nfunction isWagmiBalanceQuery(query: QueryLike): boolean {\n return Array.isArray(query.queryKey) && query.queryKey.some(isBalanceReadPart);\n}\n\n/** Invalidates any wagmi `useBalance`/`readContract` balance queries so ERC-20 balances refresh. */\nexport function invalidateWagmiBalanceQueries(queryClient: QueryClientLike): void {\n void queryClient.invalidateQueries({ predicate: isWagmiBalanceQuery });\n}\n\n/** Clears wallet-local caches (decryption, permits) and invalidates all Zama queries — call on wallet connect/disconnect so a stale entitlement can't leak across accounts. */\nexport function invalidateWalletLifecycleQueries(queryClient: QueryClientLike): void {\n // Remove (not just invalidate) wallet-local caches so a stale allowed/true\n // cannot surface between wallet disconnect and the next refetch.\n queryClient.removeQueries({ queryKey: zamaQueryKeys.decryption.all });\n queryClient.removeQueries({ queryKey: zamaQueryKeys.hasPermit.all });\n void queryClient.invalidateQueries({ predicate: isZamaQuery });\n invalidateWagmiBalanceQueries(queryClient);\n}\n","import { decimalsContract, nameContract, symbolContract } from \"../contracts\";\n\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\nimport type { Address } from \"viem\";\n\n/** ERC-20 token metadata returned by {@link tokenMetadataQueryOptions}. */\nexport interface TokenMetadata {\n /** Human-readable token name. */\n name: string;\n /** Token ticker symbol. */\n symbol: string;\n /** Number of decimals the token uses. */\n decimals: number;\n}\n\n/** Configuration for {@link tokenMetadataQueryOptions}. */\nexport interface TokenMetadataQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading an ERC-20 token's name, symbol, and decimals. */\nexport function tokenMetadataQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: TokenMetadataQueryConfig,\n): QueryFactoryOptions<\n TokenMetadata,\n Error,\n TokenMetadata,\n ReturnType<typeof zamaQueryKeys.tokenMetadata.token>\n> {\n const queryKey = zamaQueryKeys.tokenMetadata.token(tokenAddress);\n\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n const [name, symbol, decimals] = await Promise.all([\n sdk.provider.readContract(nameContract(keyTokenAddress)),\n sdk.provider.readContract(symbolContract(keyTokenAddress)),\n sdk.provider.readContract(decimalsContract(keyTokenAddress)),\n ]);\n return { name, symbol, decimals };\n },\n staleTime: Infinity,\n enabled: config?.query?.enabled !== false,\n };\n}\n","import { isConfidentialTokenContract, isConfidentialWrapperContract } from \"../contracts\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport { isContractCallError } from \"../utils\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\nimport type { Address } from \"viem\";\n\n/** Configuration for {@link isConfidentialQueryOptions} and {@link isWrapperQueryOptions}. */\nexport interface IsConfidentialQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading whether a token address implements the confidential (ERC-7984) token interface. */\nexport function isConfidentialQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: IsConfidentialQueryConfig,\n): QueryFactoryOptions<\n boolean,\n Error,\n boolean,\n ReturnType<typeof zamaQueryKeys.isConfidential.token>\n> {\n const queryKey = zamaQueryKeys.isConfidential.token(tokenAddress);\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n try {\n return await sdk.provider.readContract(isConfidentialTokenContract(keyTokenAddress));\n } catch (err) {\n // Only suppress contract execution reverts (non-ERC-165 contracts).\n // Re-throw network/transport errors so TanStack Query's retry logic applies.\n if (isContractCallError(err)) {\n return false;\n }\n throw err;\n }\n },\n staleTime: Infinity,\n enabled: config?.query?.enabled !== false,\n };\n}\n\n/** Builds TanStack Query options for reading whether a token address is a confidential wrapper (ERC-7984 wrapper) contract. */\nexport function isWrapperQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: IsConfidentialQueryConfig,\n): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.isWrapper.token>> {\n const queryKey = zamaQueryKeys.isWrapper.token(tokenAddress);\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n try {\n return await sdk.provider.readContract(isConfidentialWrapperContract(keyTokenAddress));\n } catch (err) {\n // Only suppress contract execution reverts (non-ERC-165 contracts).\n // Re-throw network/transport errors so TanStack Query's retry logic applies.\n if (isContractCallError(err)) {\n return false;\n }\n throw err;\n }\n },\n staleTime: Infinity,\n enabled: config?.query?.enabled !== false,\n };\n}\n","import { inferredTotalSupplyContract } from \"../contracts\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\nimport type { Address } from \"viem\";\n\n/** Configuration for {@link totalSupplyQueryOptions}. */\nexport interface TotalSupplyQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading a token's total supply. */\nexport function totalSupplyQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: TotalSupplyQueryConfig,\n): QueryFactoryOptions<bigint, Error, bigint, ReturnType<typeof zamaQueryKeys.totalSupply.token>> {\n const queryKey = zamaQueryKeys.totalSupply.token(tokenAddress);\n\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n return sdk.provider.readContract(inferredTotalSupplyContract(keyTokenAddress));\n },\n staleTime: 30_000,\n enabled: config?.query?.enabled !== false,\n };\n}\n","import type { Address } from \"viem\";\nimport type { WrappersRegistry } from \"../wrappers-registry\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link wrapperDiscoveryQueryOptions}. */\nexport interface WrapperDiscoveryQueryConfig {\n /**\n * Address of any confidential token you control.\n * Used to scope the query cache key and to gate whether the query\n * is enabled — it does not affect which wrapper the registry returns.\n */\n tokenAddress?: Address;\n /**\n * The ERC-20 token address to discover the confidential wrapper for.\n * The registry is resolved automatically from chain config.\n */\n erc20Address?: Address;\n /**\n * The resolved registry contract address for the current chain.\n * Included in the query key so that switching chains invalidates\n * stale cached results. Pass `undefined` when the chain ID is not\n * yet known — the query will be disabled.\n */\n registryAddress?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for discovering the confidential wrapper address for a given ERC-20 token (resolves to `null` when none is registered). */\nexport function wrapperDiscoveryQueryOptions(\n registry: WrappersRegistry,\n config: WrapperDiscoveryQueryConfig,\n): QueryFactoryOptions<\n Address | null,\n Error,\n Address | null,\n ReturnType<typeof zamaQueryKeys.wrapperDiscovery.token>\n> {\n const queryKey = zamaQueryKeys.wrapperDiscovery.token(\n config.tokenAddress,\n config.erc20Address,\n config.registryAddress,\n );\n\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { erc20Address }] = context.queryKey;\n assertNonNullable(erc20Address, \"wrapperDiscoveryQueryOptions: erc20Address\");\n const result = await registry.getConfidentialToken(erc20Address);\n return result ? result.confidentialTokenAddress : null;\n },\n staleTime: Infinity,\n enabled:\n Boolean(config.tokenAddress && config.erc20Address && config.registryAddress) &&\n config.query?.enabled !== false,\n };\n}\n","import { allowanceContract, underlyingContract } from \"../contracts\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\nimport type { Address } from \"viem\";\n\n/** Configuration for {@link underlyingAllowanceQueryOptions}. */\nexport interface UnderlyingAllowanceQueryConfig {\n /** Owner whose underlying-token allowance to read; the query stays disabled until provided. */\n owner?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading the ERC-20 allowance the owner has granted a confidential wrapper on its underlying token. */\nexport function underlyingAllowanceQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config: UnderlyingAllowanceQueryConfig,\n): QueryFactoryOptions<\n bigint,\n Error,\n bigint,\n ReturnType<typeof zamaQueryKeys.underlyingAllowance.scope>\n> {\n const ownerKey = config.owner;\n const queryEnabled = config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.underlyingAllowance.scope(tokenAddress, ownerKey);\n\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress, owner: keyOwner }] = context.queryKey;\n assertNonNullable(keyOwner, \"underlyingAllowanceQueryOptions: owner\");\n const underlying = await sdk.provider.readContract(underlyingContract(keyTokenAddress));\n return sdk.provider.readContract(allowanceContract(underlying, keyOwner, keyTokenAddress));\n },\n staleTime: 30_000,\n enabled: Boolean(ownerKey) && queryEnabled,\n };\n}\n","import type { Address, Hex } from \"viem\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link pendingUnshieldQueryOptions}. */\nexport interface PendingUnshieldQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/**\n * Query options for reading the unwrap tx hash of an unshield that was\n * interrupted between its two phases (returns `null` if none is pending).\n *\n * Backed by {@link ZamaSDK} storage via `WrappedToken.getPendingUnshield()`.\n * `staleTime: 0` so the value reflects storage on mount; the unshield/unwrap\n * mutations also invalidate this key on success.\n */\nexport function pendingUnshieldQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: PendingUnshieldQueryConfig,\n): QueryFactoryOptions<\n Hex | null,\n Error,\n Hex | null,\n ReturnType<typeof zamaQueryKeys.pendingUnshield.token>\n> {\n const queryKey = zamaQueryKeys.pendingUnshield.token(tokenAddress);\n\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n return sdk.createWrappedToken(keyTokenAddress).getPendingUnshield();\n },\n staleTime: 0,\n enabled: config?.query?.enabled !== false,\n };\n}\n","import { isOperatorContract } from \"../contracts\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { filterQueryOptions } from \"./utils\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { Address } from \"viem\";\n\n/** Configuration for {@link confidentialIsOperatorQueryOptions}. */\nexport interface ConfidentialIsOperatorQueryConfig {\n /** Token holder whose operator authorization to check; the query stays disabled until provided. */\n holder?: Address;\n /** Spender address to check for operator authorization; the query stays disabled until provided. */\n spender?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading whether a spender is an authorized operator of a holder on a confidential token. */\nexport function confidentialIsOperatorQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address | undefined,\n config: ConfidentialIsOperatorQueryConfig,\n): QueryFactoryOptions<\n boolean,\n Error,\n boolean,\n ReturnType<typeof zamaQueryKeys.confidentialIsOperator.scope>\n> {\n const holderKey = config.holder;\n const spenderKey = config.spender;\n const queryEnabled = config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.confidentialIsOperator.scope(tokenAddress, holderKey, spenderKey);\n\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress, holder: keyHolder, spender: keySpender }] =\n context.queryKey;\n assertNonNullable(keyTokenAddress, \"confidentialIsOperatorQueryOptions: tokenAddress\");\n assertNonNullable(keyHolder, \"confidentialIsOperatorQueryOptions: holder\");\n assertNonNullable(keySpender, \"confidentialIsOperatorQueryOptions: spender\");\n return sdk.provider.readContract(isOperatorContract(keyTokenAddress, keyHolder, keySpender));\n },\n staleTime: 30_000,\n enabled: Boolean(tokenAddress && holderKey && spenderKey) && queryEnabled,\n };\n}\n","import type { Address } from \"viem\";\nimport type { Token } from \"../token\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { SignerQueryContext } from \"./signer-query-context\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link confidentialBalanceQueryOptions}. */\nexport interface ConfidentialBalanceQueryConfig {\n /** Address of the confidential token to read the balance of. */\n tokenAddress: Address;\n /** Account whose confidential balance to read; the query stays disabled until provided. */\n account?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Query options for a single confidential token balance. Auto-gated on `account`. */\nexport function confidentialBalanceQueryOptions(\n token: Token,\n config: ConfidentialBalanceQueryConfig,\n signerContext: SignerQueryContext = {},\n): QueryFactoryOptions<\n bigint,\n Error,\n bigint,\n ReturnType<typeof zamaQueryKeys.confidentialBalance.owner>\n> {\n const queryOpts = config.query ?? {};\n\n return {\n ...filterQueryOptions(queryOpts),\n queryKey: zamaQueryKeys.confidentialBalance.owner(\n config.tokenAddress,\n config.account,\n signerContext.walletAccount,\n ),\n queryFn: async (context) => {\n const [, { owner: keyOwner }] = context.queryKey;\n assertNonNullable(keyOwner, \"confidentialBalanceQueryOptions: owner\");\n return token.balanceOf(keyOwner);\n },\n enabled:\n Boolean(config.account) &&\n signerContext.walletAccount !== undefined &&\n queryOpts?.enabled !== false,\n };\n}\n","import type { Address } from \"viem\";\nimport { Token, type BatchBalancesResult } from \"../token/token\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { SignerQueryContext } from \"./signer-query-context\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link confidentialBalancesQueryOptions}. */\nexport interface ConfidentialBalancesQueryConfig {\n /** Account whose confidential balances to read; the query stays disabled until provided. */\n account?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading the confidential balances of several tokens for one account in a single batch. */\nexport function confidentialBalancesQueryOptions(\n tokens: Token[],\n config?: ConfidentialBalancesQueryConfig,\n signerContext: SignerQueryContext = {},\n): QueryFactoryOptions<\n BatchBalancesResult,\n Error,\n BatchBalancesResult,\n ReturnType<typeof zamaQueryKeys.confidentialBalances.tokens>\n> {\n const accountKey = config?.account;\n const walletAccount = signerContext.walletAccount;\n const queryOpts = config?.query ?? {};\n const tokenAddresses = tokens.map((token) => token.address);\n\n return {\n ...filterQueryOptions(queryOpts),\n queryKey: zamaQueryKeys.confidentialBalances.tokens(tokenAddresses, accountKey, walletAccount),\n queryFn: async (signerContextQuery) => {\n const [, { owner: keyOwner }] = signerContextQuery.queryKey;\n assertNonNullable(keyOwner, \"confidentialBalancesQueryOptions: owner\");\n return Token.batchBalancesOf(tokens, keyOwner);\n },\n enabled:\n Boolean(accountKey) &&\n tokens.length > 0 &&\n walletAccount !== undefined &&\n queryOpts?.enabled !== false,\n };\n}\n","import { type Address, zeroAddress } from \"viem\";\nimport {\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\nimport type {\n TokenWrapperPair,\n TokenWrapperPairWithMetadata,\n PaginatedResult,\n} from \"../contracts/wrappers-registry\";\nimport type { WrappersRegistry } from \"../wrappers-registry\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Base configuration shared by the wrappers-registry query option factories. */\nexport interface WrappersRegistryQueryConfig {\n /** Registry contract address for the current chain; used as a query key discriminator. */\n registryAddress: Address | undefined;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading all token wrapper pairs registered in the wrappers registry. */\nexport function tokenPairsQueryOptions(\n sdk: ZamaSDK,\n config: WrappersRegistryQueryConfig,\n): QueryFactoryOptions<\n readonly TokenWrapperPair[],\n Error,\n readonly TokenWrapperPair[],\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairs>\n> {\n const enabled = Boolean(config.registryAddress) && config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenPairs(config.registryAddress ?? zeroAddress);\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress }] = context.queryKey;\n return sdk.provider.readContract(getTokenPairsContract(registryAddress));\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link confidentialTokenAddressQueryOptions}. */\nexport interface ConfidentialTokenAddressQueryConfig extends WrappersRegistryQueryConfig {\n /** Underlying ERC-20 token address whose confidential counterpart to look up. */\n tokenAddress?: Address;\n}\n\n/** Builds TanStack Query options for reading the confidential token address registered for a given underlying ERC-20 token. */\nexport function confidentialTokenAddressQueryOptions(\n sdk: ZamaSDK,\n config: ConfidentialTokenAddressQueryConfig,\n): QueryFactoryOptions<\n readonly [boolean, Address],\n Error,\n readonly [boolean, Address],\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.confidentialTokenAddress>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n Boolean(config.tokenAddress) &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.confidentialTokenAddress(\n config.registryAddress ?? zeroAddress,\n config.tokenAddress ?? zeroAddress,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, tokenAddress }] = context.queryKey;\n return sdk.provider.readContract(\n getConfidentialTokenAddressContract(registryAddress, tokenAddress),\n );\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link tokenAddressQueryOptions}. */\nexport interface TokenAddressQueryConfig extends WrappersRegistryQueryConfig {\n /** Confidential token address whose underlying ERC-20 counterpart to look up. */\n confidentialTokenAddress?: Address;\n}\n\n/** Builds TanStack Query options for reading the underlying ERC-20 token address registered for a given confidential token. */\nexport function tokenAddressQueryOptions(\n sdk: ZamaSDK,\n config: TokenAddressQueryConfig,\n): QueryFactoryOptions<\n readonly [boolean, Address],\n Error,\n readonly [boolean, Address],\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenAddress>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n Boolean(config.confidentialTokenAddress) &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenAddress(\n config.registryAddress ?? zeroAddress,\n config.confidentialTokenAddress ?? zeroAddress,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, confidentialTokenAddress }] = context.queryKey;\n return sdk.provider.readContract(\n getTokenAddressContract(registryAddress, confidentialTokenAddress),\n );\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Builds TanStack Query options for reading the total number of token wrapper pairs in the registry. */\nexport function tokenPairsLengthQueryOptions(\n sdk: ZamaSDK,\n config: WrappersRegistryQueryConfig,\n): QueryFactoryOptions<\n bigint,\n Error,\n bigint,\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairsLength>\n> {\n const enabled = Boolean(config.registryAddress) && config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenPairsLength(\n config.registryAddress ?? zeroAddress,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress }] = context.queryKey;\n return sdk.provider.readContract(getTokenPairsLengthContract(registryAddress));\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link tokenPairsSliceQueryOptions}. */\nexport interface TokenPairsSliceQueryConfig extends WrappersRegistryQueryConfig {\n /** Zero-based index of the first pair in the slice (inclusive). */\n fromIndex?: bigint;\n /** Index bounding the end of the slice. */\n toIndex?: bigint;\n}\n\n/** Builds TanStack Query options for reading a contiguous slice of the registry's token wrapper pairs. */\nexport function tokenPairsSliceQueryOptions(\n sdk: ZamaSDK,\n config: TokenPairsSliceQueryConfig,\n): QueryFactoryOptions<\n readonly TokenWrapperPair[],\n Error,\n readonly TokenWrapperPair[],\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairsSlice>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n config.fromIndex !== undefined &&\n config.toIndex !== undefined &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenPairsSlice(\n config.registryAddress ?? zeroAddress,\n String(config.fromIndex ?? 0n),\n String(config.toIndex ?? 0n),\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, fromIndex, toIndex }] = context.queryKey;\n return sdk.provider.readContract(\n getTokenPairsSliceContract(registryAddress, BigInt(fromIndex), BigInt(toIndex)),\n );\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link tokenPairQueryOptions}. */\nexport interface TokenPairQueryConfig extends WrappersRegistryQueryConfig {\n /** Zero-based index of the token wrapper pair to read. */\n index?: bigint;\n}\n\n/** Builds TanStack Query options for reading a single token wrapper pair by its index in the registry. */\nexport function tokenPairQueryOptions(\n sdk: ZamaSDK,\n config: TokenPairQueryConfig,\n): QueryFactoryOptions<\n TokenWrapperPair,\n Error,\n TokenWrapperPair,\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPair>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n config.index !== undefined &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenPair(\n config.registryAddress ?? zeroAddress,\n String(config.index ?? 0n),\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, index }] = context.queryKey;\n return sdk.provider.readContract(getTokenPairContract(registryAddress, BigInt(index)));\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link isConfidentialTokenValidQueryOptions}. */\nexport interface IsConfidentialTokenValidQueryConfig extends WrappersRegistryQueryConfig {\n /** Confidential token address to validate against the registry. */\n confidentialTokenAddress?: Address;\n}\n\n/** Builds TanStack Query options for checking whether a confidential token is registered and valid in the registry. */\nexport function isConfidentialTokenValidQueryOptions(\n sdk: ZamaSDK,\n config: IsConfidentialTokenValidQueryConfig,\n): QueryFactoryOptions<\n boolean,\n Error,\n boolean,\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.isConfidentialTokenValid>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n Boolean(config.confidentialTokenAddress) &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.isConfidentialTokenValid(\n config.registryAddress ?? zeroAddress,\n config.confidentialTokenAddress ?? zeroAddress,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, confidentialTokenAddress }] = context.queryKey;\n return sdk.provider.readContract(\n isConfidentialTokenValidContract(registryAddress, confidentialTokenAddress),\n );\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link listPairsQueryOptions}. */\nexport interface ListPairsQueryConfig {\n /**\n * The registry address for this chain — used as a query key discriminator.\n * The registry instance already knows how to resolve the address for the\n * current chain; this field just keeps the TanStack Query cache isolated\n * per registry contract.\n */\n registryAddress: Address | undefined;\n /** 1-based page number to fetch; defaults to `1`. */\n page?: number;\n /** Number of pairs per page; defaults to `100`. */\n pageSize?: number;\n /** When `true`, resolve each pair's on-chain metadata; defaults to `false`. */\n metadata?: boolean;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/**\n * Query options for paginated listing of token wrapper pairs.\n *\n * Accepts a {@link WrappersRegistry} instance rather than a raw provider so that the\n * class-level TTL cache is shared across multiple `queryFn` executions. Pass\n * `sdk.registry` (the ZamaSDK lazy singleton) to ensure a single shared cache.\n */\nexport function listPairsQueryOptions(\n registry: WrappersRegistry,\n config: ListPairsQueryConfig,\n): QueryFactoryOptions<\n PaginatedResult<TokenWrapperPair | TokenWrapperPairWithMetadata>,\n Error,\n PaginatedResult<TokenWrapperPair | TokenWrapperPairWithMetadata>,\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.listPairs>\n> {\n const enabled = Boolean(config.registryAddress) && config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.listPairs(\n config.registryAddress ?? zeroAddress,\n config.page ?? 1,\n config.pageSize ?? 100,\n config.metadata ?? false,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { page, pageSize, metadata }] = context.queryKey;\n return registry.listPairs({ page, pageSize, metadata });\n },\n // Use the registry's own TTL so TanStack Query and the class-level cache\n // operate under the same freshness contract.\n staleTime: registry.ttlMs,\n enabled,\n };\n}\n","import type { Address } from \"viem\";\nimport type { WrappedToken } from \"../token/wrapped-token\";\nimport type { ShieldOptions, TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link shieldMutationOptions}. */\nexport interface ShieldParams extends ShieldOptions {\n /** Amount of the public ERC-20 to shield, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.shield | shielding} a public ERC-20 into its confidential form. @see {@link ShieldParams} */\nexport function shieldMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.shield\", Address], ShieldParams, TransactionResult> {\n return {\n mutationKey: [\"zama.shield\", token.address] as const,\n mutationFn: async ({ amount, ...rest }) => token.shield(amount, rest),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransactionResult, TransferOptions } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link confidentialTransferMutationOptions}. */\nexport interface ConfidentialTransferParams extends TransferOptions {\n /** Recipient address. */\n to: Address;\n /** Amount of tokens to transfer, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.confidentialTransfer | transferring} confidential tokens. @see {@link ConfidentialTransferParams} */\nexport function confidentialTransferMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialTransfer\", Address],\n ConfidentialTransferParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialTransfer\", token.address] as const,\n mutationFn: async ({ to, amount, ...options }) =>\n token.confidentialTransfer(to, amount, options),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransactionResult, TransferOptions } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address, Hex } from \"viem\";\n\n/** Variables for {@link confidentialTransferAndCallMutationOptions}. */\nexport interface ConfidentialTransferAndCallParams extends TransferOptions {\n /** Recipient address. */\n to: Address;\n /** Amount of tokens to transfer, in the token's base units. */\n amount: bigint;\n /** Opaque bytes forwarded to the recipient's ERC-7984 receiver hook. */\n data: Hex;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.confidentialTransferAndCall | transferring} confidential tokens and invoking the recipient's receiver hook. @see {@link ConfidentialTransferAndCallParams} */\nexport function confidentialTransferAndCallMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialTransferAndCall\", Address],\n ConfidentialTransferAndCallParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialTransferAndCall\", token.address] as const,\n mutationFn: async ({ to, amount, data, ...options }) =>\n token.confidentialTransferAndCall(to, amount, data, options),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransferCallbacks, TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link confidentialTransferFromMutationOptions}. */\nexport interface ConfidentialTransferFromParams {\n /** Address to transfer from. */\n from: Address;\n /** Recipient address. */\n to: Address;\n /** Amount of tokens to transfer, in the token's base units. */\n amount: bigint;\n /** Optional progress callbacks for the multi-step transfer flow. */\n callbacks?: TransferCallbacks;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.confidentialTransferFrom | transferring} confidential tokens from another account (operator flow). @see {@link ConfidentialTransferFromParams} */\nexport function confidentialTransferFromMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialTransferFrom\", Address],\n ConfidentialTransferFromParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialTransferFrom\", token.address] as const,\n mutationFn: async ({ from, to, amount, callbacks }) =>\n token.confidentialTransferFrom(from, to, amount, callbacks),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransferCallbacks, TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address, Hex } from \"viem\";\n\n/** Variables for {@link confidentialTransferFromAndCallMutationOptions}. */\nexport interface ConfidentialTransferFromAndCallParams {\n /** Address to transfer from. */\n from: Address;\n /** Recipient address. */\n to: Address;\n /** Amount of tokens to transfer, in the token's base units. */\n amount: bigint;\n /** Opaque bytes forwarded to the recipient's ERC-7984 receiver hook. */\n data: Hex;\n /** Optional progress callbacks for the multi-step transfer flow. */\n callbacks?: TransferCallbacks;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.confidentialTransferFromAndCall | transferring} confidential tokens from another account and invoking the recipient's receiver hook. @see {@link ConfidentialTransferFromAndCallParams} */\nexport function confidentialTransferFromAndCallMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialTransferFromAndCall\", Address],\n ConfidentialTransferFromAndCallParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialTransferFromAndCall\", token.address] as const,\n mutationFn: async ({ from, to, amount, data, callbacks }) =>\n token.confidentialTransferFromAndCall(from, to, amount, data, callbacks),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link confidentialSetOperatorMutationOptions}. */\nexport interface ConfidentialSetOperatorParams {\n /** Operator address to authorize. */\n operator: Address;\n /** Unix timestamp (seconds) when the operator authorization expires; defaults to one hour from now. */\n until?: number;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.setOperator | authorizing} an operator on a confidential token. @see {@link ConfidentialSetOperatorParams} */\nexport function confidentialSetOperatorMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialSetOperator\", Address],\n ConfidentialSetOperatorParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialSetOperator\", token.address] as const,\n mutationFn: async ({ operator, until }) => token.setOperator(operator, until),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link approveUnderlyingMutationOptions}. */\nexport interface ApproveUnderlyingParams {\n /** Amount of the underlying ERC-20 to approve, in its base units; omit for a max approval. */\n amount?: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.approveUnderlying | approving} the wrapper to spend the underlying ERC-20. @see {@link ApproveUnderlyingParams} */\nexport function approveUnderlyingMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<\n readonly [\"zama.approveUnderlying\", Address],\n ApproveUnderlyingParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.approveUnderlying\", token.address] as const,\n mutationFn: async ({ amount }) => token.approveUnderlying(amount),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult, UnshieldOptions } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link unshieldMutationOptions}. */\nexport interface UnshieldParams extends UnshieldOptions {\n /** Amount of tokens to unshield, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.unshield | unshielding} a confidential token back into its public ERC-20. @see {@link UnshieldParams} */\nexport function unshieldMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unshield\", Address], UnshieldParams, TransactionResult> {\n return {\n mutationKey: [\"zama.unshield\", token.address] as const,\n mutationFn: async ({ amount, ...options }) => token.unshield(amount, options),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult, UnshieldCallbacks } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link unshieldAllMutationOptions}. */\nexport interface UnshieldAllParams extends UnshieldCallbacks {}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.unshieldAll | unshielding} the entire confidential balance back into the public ERC-20. @see {@link UnshieldAllParams} */\nexport function unshieldAllMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<\n readonly [\"zama.unshieldAll\", Address],\n UnshieldAllParams | void,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.unshieldAll\", token.address] as const,\n mutationFn: async (params) => token.unshieldAll(params || undefined),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult, UnshieldCallbacks } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address, Hex } from \"viem\";\n\n/** Variables for {@link resumeUnshieldMutationOptions}. */\nexport interface ResumeUnshieldParams extends UnshieldCallbacks {\n /** Hash of the earlier unwrap request transaction to resume from. */\n unwrapTxHash: Hex;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.resumeUnshield | resuming} an interrupted unshield from its unwrap request transaction. @see {@link ResumeUnshieldParams} */\nexport function resumeUnshieldMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<\n readonly [\"zama.resumeUnshield\", Address],\n ResumeUnshieldParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.resumeUnshield\", token.address] as const,\n mutationFn: async ({ unwrapTxHash, ...callbacks }) =>\n token.resumeUnshield(unwrapTxHash, callbacks),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { UnwrapResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link unwrapMutationOptions}. */\nexport interface UnwrapParams {\n /** Amount of tokens to unwrap, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.unwrap | unwrapping} a confidential token (request phase of the two-phase unwrap). @see {@link UnwrapParams} */\nexport function unwrapMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unwrap\", Address], UnwrapParams, UnwrapResult> {\n return {\n mutationKey: [\"zama.unwrap\", token.address] as const,\n mutationFn: async ({ amount }) => token.unwrap(amount),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult, WrapOptions } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link wrapMutationOptions}. */\nexport interface WrapParams extends WrapOptions {\n /** Amount of the public ERC-20 to wrap, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.wrap | wrapping} a public ERC-20 into its confidential form. @see {@link WrapParams} */\nexport function wrapMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.wrap\", Address], WrapParams, TransactionResult> {\n return {\n mutationKey: [\"zama.wrap\", token.address] as const,\n mutationFn: async ({ amount, ...rest }) => token.wrap(amount, rest),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { UnwrapResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.unwrapAll | unwrapping} the entire confidential balance. */\nexport function unwrapAllMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unwrapAll\", Address], void, UnwrapResult> {\n return {\n mutationKey: [\"zama.unwrapAll\", token.address] as const,\n mutationFn: async () => token.unwrapAll(),\n };\n}\n","import type { EncryptedValue } from \"../relayer/types\";\nimport type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n/** Variables for {@link finalizeUnwrapMutationOptions}. */\nexport type FinalizeUnwrapParams = {\n /** Identifier from an `UnwrapRequested` event. */\n unwrapRequestId: EncryptedValue;\n};\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.finalizeUnwrap | finalizing} a previously requested unwrap. @see {@link FinalizeUnwrapParams} */\nexport function finalizeUnwrapMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<\n readonly [\"zama.finalizeUnwrap\", Address],\n FinalizeUnwrapParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.finalizeUnwrap\", token.address] as const,\n mutationFn: async ({ unwrapRequestId }) => token.finalizeUnwrap(unwrapRequestId),\n };\n}\n","import type { EncryptParams } from \"../node\";\nimport type { EncryptResult } from \"../relayer/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Builds TanStack Query mutation options for {@link ZamaSDK.encrypt | encrypting} plaintext inputs into an encrypted payload. */\nexport function encryptMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.encrypt\"], EncryptParams, EncryptResult> {\n return { mutationKey: [\"zama.encrypt\"], mutationFn: async (params) => sdk.encrypt(params) };\n}\n","import type { Address } from \"viem\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/types\";\nimport type { EncryptedInput } from \"./user-decrypt\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link delegatedDecryptValuesMutationOptions}. */\nexport interface DelegatedDecryptValuesMutationParams {\n /** Encrypted values (with their contract addresses) to decrypt. */\n encryptedInputs: EncryptedInput[];\n /** Address of the account that delegated decryption rights to the connected wallet. */\n delegatorAddress: Address;\n}\n\n/** Builds TanStack Query mutation options for {@link Decryption.delegatedDecryptValues | decrypting} encrypted values via delegated decryption credentials. @see {@link DelegatedDecryptValuesMutationParams} */\nexport function delegatedDecryptValuesMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<\n readonly [\"zama.delegatedDecryptValues\"],\n DelegatedDecryptValuesMutationParams,\n Readonly<Record<EncryptedValue, ClearValue>>\n> {\n return {\n mutationKey: [\"zama.delegatedDecryptValues\"],\n mutationFn: async (params) =>\n sdk.decryption.delegatedDecryptValues(params.encryptedInputs, params.delegatorAddress),\n };\n}\n","import type { ClearValue, EncryptedValue, DecryptPublicValuesResult } from \"../relayer/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\n\n/** Builds TanStack Query mutation options for {@link Decryption.decryptPublicValues | publicly decrypting} encrypted values, caching each clear result. */\nexport function decryptPublicValuesMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<\n readonly [\"zama.decryptPublicValues\"],\n EncryptedValue[],\n DecryptPublicValuesResult\n> {\n return {\n mutationKey: [\"zama.decryptPublicValues\"],\n mutationFn: async (handles) => sdk.decryption.decryptPublicValues(handles),\n onSuccess: (data, _variables, _onMutateResult, context) => {\n for (const [handle, value] of Object.entries(data.clearValues) as [\n EncryptedValue,\n ClearValue,\n ][]) {\n context.client.setQueryData(zamaQueryKeys.decryption.encryptedValue(handle), value);\n }\n },\n };\n}\n","import type { Address } from \"viem\";\nimport type { WildcardPermit } from \"../credentials/utils\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/**\n * Builds TanStack Query mutation options for {@link Permits.grantPermit | granting}\n * decryption permits for the given contract addresses, or {@link WILDCARD_PERMIT}\n * for a permissive V2 permit covering every contract.\n */\nexport function grantPermitMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.grantPermit\"], Address[] | WildcardPermit, void> {\n return {\n mutationKey: [\"zama.grantPermit\"],\n mutationFn: (contractAddresses) => sdk.permits.grantPermit(contractAddresses),\n };\n}\n","import type { PreparedPermit, PreparePermitRequest } from \"../credentials/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Builds TanStack Query mutation options for {@link Offline.preparePermit | preparing} an offline decryption permit. */\nexport function preparePermitMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.preparePermit\"], PreparePermitRequest, PreparedPermit> {\n return {\n mutationKey: [\"zama.preparePermit\"],\n mutationFn: (request) => sdk.offline.preparePermit(request),\n };\n}\n","import type { Hex } from \"viem\";\nimport type { PreparedPermit } from \"../credentials/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Parameters for {@link registerPermitMutationOptions}. */\nexport interface RegisterPermitParams {\n /** The payload `sdk.offline.preparePermit` returned. */\n prepared: PreparedPermit;\n /** The `eth_signTypedData_v4` signature over `prepared.eip712`. */\n signature: Hex;\n}\n\n/** Builds TanStack Query mutation options for {@link Permits.registerPermit | registering} a signed offline permit. */\nexport function registerPermitMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.registerPermit\"], RegisterPermitParams, void> {\n return {\n mutationKey: [\"zama.registerPermit\"],\n mutationFn: ({ prepared, signature }) => sdk.permits.registerPermit(prepared, signature),\n };\n}\n","import type { Address } from \"viem\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { SignerQueryContext } from \"./signer-query-context\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link hasPermitQueryOptions}. */\nexport interface HasPermitQueryConfig {\n /** Contract addresses to check credentials against. */\n contractAddresses: Address[];\n /**\n * Standard TanStack query options. `hasPermit` intentionally overrides cache\n * timing because permit state is wallet-local, not server state: every fetch\n * should read the SDK credential service directly.\n */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading whether the connected wallet holds a valid decryption permit for the given contracts. */\nexport function hasPermitQueryOptions(\n sdk: ZamaSDK,\n config: HasPermitQueryConfig,\n signerContext: SignerQueryContext = {},\n): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.hasPermit.scope>> {\n const callerEnabled = config.query?.enabled !== false;\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey: zamaQueryKeys.hasPermit.scope(config.contractAddresses, signerContext.walletAccount),\n queryFn: (context) => {\n const [, { contractAddresses }] = context.queryKey;\n return sdk.permits.hasPermit(contractAddresses as Address[]);\n },\n staleTime: 0,\n gcTime: 0,\n refetchOnMount: \"always\",\n refetchOnWindowFocus: false,\n enabled:\n callerEnabled &&\n signerContext.walletAccount !== undefined &&\n config.contractAddresses.length > 0,\n } as const;\n}\n","import type { Address } from \"viem\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** TanStack Query mutation factory for {@link Permits.revokePermits}. */\nexport function revokePermitsMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.revokePermits\"], Address[] | void, void> {\n return {\n mutationKey: [\"zama.revokePermits\"],\n mutationFn: (contracts: Address[] | void) =>\n contracts === undefined ? sdk.permits.revokePermits() : sdk.permits.revokePermits(contracts),\n };\n}\n","import type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** TanStack Query mutation factory for {@link Permits.clear}. */\nexport function clearCredentialsMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.clearCredentials\"], void, void> {\n return { mutationKey: [\"zama.clearCredentials\"], mutationFn: () => sdk.permits.clear() };\n}\n","import type { Address } from \"viem\";\nimport type { TransactionResult } from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link delegateDecryptionMutationOptions}. */\nexport interface DelegateDecryptionParams {\n /** Address to grant delegated decryption rights to. */\n delegateAddress: Address;\n /** When the delegation expires; omit for no expiry. */\n expirationDate?: Date;\n}\n\n/** Builds TanStack Query mutation options for {@link Delegations.delegateDecryption | granting} delegated decryption rights on a contract. @see {@link DelegateDecryptionParams} */\nexport function delegateDecryptionMutationOptions(\n sdk: ZamaSDK,\n contractAddress: Address,\n): MutationFactoryOptions<\n readonly [\"zama.delegateDecryption\", Address],\n DelegateDecryptionParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.delegateDecryption\", contractAddress] as const,\n mutationFn: async ({ delegateAddress, expirationDate }) =>\n sdk.delegations.delegateDecryption({ contractAddress, delegateAddress, expirationDate }),\n };\n}\n","import type { Address } from \"viem\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { SignerQueryContext } from \"./signer-query-context\";\n\n/** A single encrypted value to decrypt, paired with the contract that owns it. */\nexport interface EncryptedInput {\n /** Encrypted handle to decrypt. */\n encryptedValue: EncryptedValue;\n /** Address of the contract the encrypted value belongs to. */\n contractAddress: Address;\n}\n\n/** Decrypted clear values keyed by encrypted handle. */\nexport type DecryptResult = Readonly<Record<EncryptedValue, ClearValue>>;\n\n/** Builds TanStack Query options for decrypting a batch of encrypted handles into their clear values. */\nexport function decryptValuesQueryOptions(\n sdk: ZamaSDK,\n encryptedInputs: EncryptedInput[],\n signerContext: SignerQueryContext = {},\n): QueryFactoryOptions<\n DecryptResult,\n Error,\n DecryptResult,\n ReturnType<typeof zamaQueryKeys.decryption.encryptedInputs>\n> {\n return {\n queryKey: zamaQueryKeys.decryption.encryptedInputs(\n encryptedInputs,\n signerContext.walletAccount,\n ),\n queryFn: (context) => {\n const [, { encryptedInputs: keyedInputs }] = context.queryKey;\n return sdk.decryption.decryptValues(keyedInputs);\n },\n staleTime: Infinity,\n enabled: encryptedInputs.length > 0 && signerContext.walletAccount !== undefined,\n };\n}\n","import type { Address } from \"viem\";\nimport type { Token } from \"../token/token\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link decryptBalanceAsMutationOptions}. */\nexport interface DecryptBalanceAsParams {\n /** Address of the account that delegated decryption rights to the connected wallet. */\n delegatorAddress: Address;\n /** Account whose on-chain balance to read; defaults to the delegator address. */\n accountAddress?: Address;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.decryptBalanceAs | decrypting} a balance via delegated decryption credentials. @see {@link DecryptBalanceAsParams} */\nexport function decryptBalanceAsMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.decryptBalanceAs\", Address],\n DecryptBalanceAsParams,\n bigint\n> {\n return {\n mutationKey: [\"zama.decryptBalanceAs\", token.address] as const,\n mutationFn: async ({ delegatorAddress, accountAddress }) =>\n token.decryptBalanceAs({ delegatorAddress, accountAddress }),\n };\n}\n","import { Token, type BatchDecryptAsOptions } from \"../token/token\";\nimport type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link batchDecryptBalancesAsMutationOptions}. */\nexport type BatchDecryptBalancesAsParams = BatchDecryptAsOptions;\n\n/** Builds TanStack Query mutation options for {@link Token.batchDecryptBalancesAs | decrypting} multiple token balances via delegated decryption credentials. @see {@link BatchDecryptBalancesAsParams} */\nexport function batchDecryptBalancesAsMutationOptions(\n tokens: Token[],\n): MutationFactoryOptions<\n readonly [\"zama.batchDecryptBalancesAs\", ...Address[]],\n BatchDecryptBalancesAsParams,\n Map<Address, bigint>\n> {\n return {\n mutationKey: [\"zama.batchDecryptBalancesAs\", ...tokens.map((t) => t.address)] as const,\n mutationFn: async (params) => Token.batchDecryptBalancesAs(tokens, params),\n };\n}\n","import type { Address } from \"viem\";\nimport type { TransactionResult } from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link revokeDelegationMutationOptions}. */\nexport interface RevokeDelegationParams {\n /** Address whose delegated decryption rights to revoke. */\n delegateAddress: Address;\n}\n\n/** Builds TanStack Query mutation options for {@link Delegations.revokeDelegation | revoking} delegated decryption rights on a contract. @see {@link RevokeDelegationParams} */\nexport function revokeDelegationMutationOptions(\n sdk: ZamaSDK,\n contractAddress: Address,\n): MutationFactoryOptions<\n readonly [\"zama.revokeDelegation\", Address],\n RevokeDelegationParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.revokeDelegation\", contractAddress] as const,\n mutationFn: async ({ delegateAddress }) =>\n sdk.delegations.revokeDelegation({ contractAddress, delegateAddress }),\n };\n}\n","import type { TransactionResult } from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link invalidateDecryptionSignaturesMutationOptions}. */\nexport interface InvalidateDecryptionSignaturesParams {\n /** Oldest timestamp that remains valid. Omit to invalidate everything up to now. */\n timestamp?: Date;\n}\n\n/** Builds TanStack Query mutation options for {@link Permits.invalidateDecryptionSignatures | invalidating} every decryption signature signed before a timestamp. @see {@link InvalidateDecryptionSignaturesParams} */\nexport function invalidateDecryptionSignaturesMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<\n readonly [\"zama.invalidateDecryptionSignatures\"],\n InvalidateDecryptionSignaturesParams | void,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.invalidateDecryptionSignatures\"] as const,\n mutationFn: async (params: InvalidateDecryptionSignaturesParams | void) =>\n sdk.permits.invalidateDecryptionSignatures(params?.timestamp),\n };\n}\n","import type { Address } from \"viem\";\nimport type { DelegationStatus } from \"../services/delegation-service\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { filterQueryOptions } from \"./utils\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { assertNonNullable } from \"../utils\";\n\nexport type { DelegationStatus } from \"../services/delegation-service\";\n\n/** Configuration for {@link delegationStatusQueryOptions}. */\nexport interface DelegationStatusQueryConfig {\n /** Contract the delegation applies to; pass `undefined` to keep the query disabled. */\n contractAddress: Address | undefined;\n /** Address granting the delegated decryption rights; the query stays disabled until provided. */\n delegatorAddress?: Address;\n /** Address receiving the delegated decryption rights; the query stays disabled until provided. */\n delegateAddress?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading the decryption-delegation status between a delegator and a delegate on a contract. */\nexport function delegationStatusQueryOptions(\n sdk: ZamaSDK,\n config: DelegationStatusQueryConfig,\n): QueryFactoryOptions<\n DelegationStatus,\n Error,\n DelegationStatus,\n ReturnType<typeof zamaQueryKeys.delegationStatus.scope>\n> {\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey: zamaQueryKeys.delegationStatus.scope(\n config.contractAddress,\n config.delegatorAddress,\n config.delegateAddress,\n ),\n queryFn: async (context) => {\n const [, { contractAddress, delegatorAddress, delegateAddress }] = context.queryKey;\n assertNonNullable(contractAddress, \"delegationStatusQueryOptions: contractAddress\");\n assertNonNullable(delegatorAddress, \"delegationStatusQueryOptions: delegatorAddress\");\n assertNonNullable(delegateAddress, \"delegationStatusQueryOptions: delegateAddress\");\n return sdk.delegations.getStatus({ contractAddress, delegatorAddress, delegateAddress });\n },\n enabled:\n Boolean(config.contractAddress && config.delegatorAddress && config.delegateAddress) &&\n config.query?.enabled !== false,\n } as const;\n}\n"],"mappings":"+XAEA,SAAS,GAAc,EAA6B,CAClD,GAAI,CAAC,EAAmB,CAAK,EAC3B,MAAO,GAIT,IAAM,EAAO,EAAM,YACnB,GAAI,IAAS,IAAA,GACX,MAAO,GAIT,IAAM,EAAO,EAAK,UAYlB,MALA,EANI,CAAC,EAAmB,CAAI,GAMxB,CAAC,EAAK,eAAe,eAAe,EAM1C,CAGA,SAAS,EAAmB,EAAiB,CAC3C,OAAO,OAAO,UAAU,SAAS,KAAK,CAAC,IAAM,iBAC/C,CA4CA,SAAgB,EACd,EACyC,CACzC,GAAM,CACJ,OAAQ,EACR,UAAW,EACX,QAAS,EACT,OAAQ,EACR,gBAAiB,EACjB,eAAgB,EAChB,qBAAsB,EACtB,mBAAoB,EACpB,MAAO,EACP,WAAY,EACZ,aAAc,EACd,QAAS,EACT,SAAU,GACV,eAAgB,EAChB,YAAa,EACb,qBAAsB,EACtB,gBAAiB,EACjB,kBAAmB,EACnB,aAAc,EACd,KAAM,EACN,MAAO,EACP,gBAAiB,EACjB,GAAG,GACD,EAEJ,OAAO,CACT,CAWA,SAAgB,EAAO,EAAsC,CAC3D,OAAO,KAAK,UAAU,GAAW,EAAG,IAC9B,GAAc,CAAK,EACd,OAAO,KAAK,CAAK,CAAC,CACtB,KAAK,CAAC,CACN,QACE,EAAQ,KACP,EAAO,GAAO,EAAM,GACb,GAET,CAAC,CACH,EAGA,OAAO,GAAU,SACZ,EAAM,SAAS,EAGjB,CACR,CACH,CCrIA,MAAM,EAAsB,GAC1B,EAAU,IAAK,GAAY,EAAW,CAAO,CAAC,EAC1C,EAAoB,GACxB,IAAY,IAAA,GAAY,IAAA,GAAY,EAAW,CAAO,EAClD,EAAoB,GACxB,EACI,CAAE,cAAe,EAAW,EAAc,OAAO,EAAG,cAAe,EAAc,OAAQ,EACzF,CAAC,EAYM,EA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BAAiB,CAAE,kBAAiB,iBAAgB,CAAC,CACzE,CACF,CCdA,SAAgB,GACd,EAKA,CACA,MAAO,CACL,YAAa,CAAC,qCAAqC,EACnD,WAAY,KAAO,IACjB,EAAI,QAAQ,+BAA+B,GAAQ,SAAS,CAChE,CACF,CCAA,SAAgB,GACd,EACA,EAMA,CACA,MAAO,CACL,GAAG,EAAmB,EAAO,OAAS,CAAC,CAAC,EACxC,SAAU,EAAc,iBAAiB,MACvC,EAAO,gBACP,EAAO,iBACP,EAAO,eACT,EACA,QAAS,KAAO,IAAY,CAC1B,GAAM,EAAG,CAAE,kBAAiB,mBAAkB,oBAAqB,EAAQ,SAI3E,OAHA,EAAkB,EAAiB,+CAA+C,EAClF,EAAkB,EAAkB,gDAAgD,EACpF,EAAkB,EAAiB,+CAA+C,EAC3E,EAAI,YAAY,UAAU,CAAE,kBAAiB,mBAAkB,iBAAgB,CAAC,CACzF,EACA,QACE,GAAQ,EAAO,iBAAmB,EAAO,kBAAoB,EAAO,kBACpE,EAAO,OAAO,UAAY,EAC9B,CACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../../src/query/token-metadata.ts","../../../src/query/is-confidential.ts","../../../src/query/total-supply.ts","../../../src/query/wrapper-discovery.ts","../../../src/query/underlying-allowance.ts","../../../src/query/pending-unshield.ts","../../../src/query/confidential-is-operator.ts","../../../src/query/confidential-balance.ts","../../../src/query/confidential-balances.ts","../../../src/query/wrappers-registry.ts","../../../src/query/shield.ts","../../../src/query/transfer.ts","../../../src/query/transfer-and-call.ts","../../../src/query/transfer-from.ts","../../../src/query/transfer-from-and-call.ts","../../../src/query/set-operator.ts","../../../src/query/approve-underlying.ts","../../../src/query/unshield.ts","../../../src/query/unshield-all.ts","../../../src/query/resume-unshield.ts","../../../src/query/unwrap.ts","../../../src/query/wrap.ts","../../../src/query/unwrap-all.ts","../../../src/query/finalize-unwrap.ts","../../../src/query/encrypt.ts","../../../src/query/delegated-decrypt.ts","../../../src/query/public-decrypt.ts","../../../src/query/grant-permit.ts","../../../src/query/prepare-permit.ts","../../../src/query/register-permit.ts","../../../src/query/has-permit.ts","../../../src/query/revoke-permits.ts","../../../src/query/clear-credentials.ts","../../../src/query/delegate-decryption.ts","../../../src/query/user-decrypt.ts","../../../src/query/decrypt-balance-as.ts","../../../src/query/batch-decrypt-balances-as.ts","../../../src/query/revoke-delegation.ts","../../../src/query/delegation-status.ts"],"sourcesContent":["import { decimalsContract, nameContract, symbolContract } from \"../contracts\";\n\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\nimport type { Address } from \"viem\";\n\n/** ERC-20 token metadata returned by {@link tokenMetadataQueryOptions}. */\nexport interface TokenMetadata {\n /** Human-readable token name. */\n name: string;\n /** Token ticker symbol. */\n symbol: string;\n /** Number of decimals the token uses. */\n decimals: number;\n}\n\n/** Configuration for {@link tokenMetadataQueryOptions}. */\nexport interface TokenMetadataQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading an ERC-20 token's name, symbol, and decimals. */\nexport function tokenMetadataQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: TokenMetadataQueryConfig,\n): QueryFactoryOptions<\n TokenMetadata,\n Error,\n TokenMetadata,\n ReturnType<typeof zamaQueryKeys.tokenMetadata.token>\n> {\n const queryKey = zamaQueryKeys.tokenMetadata.token(tokenAddress);\n\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n const [name, symbol, decimals] = await Promise.all([\n sdk.provider.readContract(nameContract(keyTokenAddress)),\n sdk.provider.readContract(symbolContract(keyTokenAddress)),\n sdk.provider.readContract(decimalsContract(keyTokenAddress)),\n ]);\n return { name, symbol, decimals };\n },\n staleTime: Infinity,\n enabled: config?.query?.enabled !== false,\n };\n}\n","import { isConfidentialTokenContract, isConfidentialWrapperContract } from \"../contracts\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport { isContractCallError } from \"../utils\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\nimport type { Address } from \"viem\";\n\n/** Configuration for {@link isConfidentialQueryOptions} and {@link isWrapperQueryOptions}. */\nexport interface IsConfidentialQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading whether a token address implements the confidential (ERC-7984) token interface. */\nexport function isConfidentialQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: IsConfidentialQueryConfig,\n): QueryFactoryOptions<\n boolean,\n Error,\n boolean,\n ReturnType<typeof zamaQueryKeys.isConfidential.token>\n> {\n const queryKey = zamaQueryKeys.isConfidential.token(tokenAddress);\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n try {\n return await sdk.provider.readContract(isConfidentialTokenContract(keyTokenAddress));\n } catch (err) {\n // Only suppress contract execution reverts (non-ERC-165 contracts).\n // Re-throw network/transport errors so TanStack Query's retry logic applies.\n if (isContractCallError(err)) {\n return false;\n }\n throw err;\n }\n },\n staleTime: Infinity,\n enabled: config?.query?.enabled !== false,\n };\n}\n\n/** Builds TanStack Query options for reading whether a token address is a confidential wrapper (ERC-7984 wrapper) contract. */\nexport function isWrapperQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: IsConfidentialQueryConfig,\n): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.isWrapper.token>> {\n const queryKey = zamaQueryKeys.isWrapper.token(tokenAddress);\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n try {\n return await sdk.provider.readContract(isConfidentialWrapperContract(keyTokenAddress));\n } catch (err) {\n // Only suppress contract execution reverts (non-ERC-165 contracts).\n // Re-throw network/transport errors so TanStack Query's retry logic applies.\n if (isContractCallError(err)) {\n return false;\n }\n throw err;\n }\n },\n staleTime: Infinity,\n enabled: config?.query?.enabled !== false,\n };\n}\n","import { inferredTotalSupplyContract } from \"../contracts\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\nimport type { Address } from \"viem\";\n\n/** Configuration for {@link totalSupplyQueryOptions}. */\nexport interface TotalSupplyQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading a token's total supply. */\nexport function totalSupplyQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: TotalSupplyQueryConfig,\n): QueryFactoryOptions<bigint, Error, bigint, ReturnType<typeof zamaQueryKeys.totalSupply.token>> {\n const queryKey = zamaQueryKeys.totalSupply.token(tokenAddress);\n\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n return sdk.provider.readContract(inferredTotalSupplyContract(keyTokenAddress));\n },\n staleTime: 30_000,\n enabled: config?.query?.enabled !== false,\n };\n}\n","import type { Address } from \"viem\";\nimport type { WrappersRegistry } from \"../wrappers-registry\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link wrapperDiscoveryQueryOptions}. */\nexport interface WrapperDiscoveryQueryConfig {\n /**\n * Address of any confidential token you control.\n * Used to scope the query cache key and to gate whether the query\n * is enabled — it does not affect which wrapper the registry returns.\n */\n tokenAddress?: Address;\n /**\n * The ERC-20 token address to discover the confidential wrapper for.\n * The registry is resolved automatically from chain config.\n */\n erc20Address?: Address;\n /**\n * The resolved registry contract address for the current chain.\n * Included in the query key so that switching chains invalidates\n * stale cached results. Pass `undefined` when the chain ID is not\n * yet known — the query will be disabled.\n */\n registryAddress?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for discovering the confidential wrapper address for a given ERC-20 token (resolves to `null` when none is registered). */\nexport function wrapperDiscoveryQueryOptions(\n registry: WrappersRegistry,\n config: WrapperDiscoveryQueryConfig,\n): QueryFactoryOptions<\n Address | null,\n Error,\n Address | null,\n ReturnType<typeof zamaQueryKeys.wrapperDiscovery.token>\n> {\n const queryKey = zamaQueryKeys.wrapperDiscovery.token(\n config.tokenAddress,\n config.erc20Address,\n config.registryAddress,\n );\n\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { erc20Address }] = context.queryKey;\n assertNonNullable(erc20Address, \"wrapperDiscoveryQueryOptions: erc20Address\");\n const result = await registry.getConfidentialToken(erc20Address);\n return result ? result.confidentialTokenAddress : null;\n },\n staleTime: Infinity,\n enabled:\n Boolean(config.tokenAddress && config.erc20Address && config.registryAddress) &&\n config.query?.enabled !== false,\n };\n}\n","import { allowanceContract, underlyingContract } from \"../contracts\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\nimport type { Address } from \"viem\";\n\n/** Configuration for {@link underlyingAllowanceQueryOptions}. */\nexport interface UnderlyingAllowanceQueryConfig {\n /** Owner whose underlying-token allowance to read; the query stays disabled until provided. */\n owner?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading the ERC-20 allowance the owner has granted a confidential wrapper on its underlying token. */\nexport function underlyingAllowanceQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config: UnderlyingAllowanceQueryConfig,\n): QueryFactoryOptions<\n bigint,\n Error,\n bigint,\n ReturnType<typeof zamaQueryKeys.underlyingAllowance.scope>\n> {\n const ownerKey = config.owner;\n const queryEnabled = config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.underlyingAllowance.scope(tokenAddress, ownerKey);\n\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress, owner: keyOwner }] = context.queryKey;\n assertNonNullable(keyOwner, \"underlyingAllowanceQueryOptions: owner\");\n const underlying = await sdk.provider.readContract(underlyingContract(keyTokenAddress));\n return sdk.provider.readContract(allowanceContract(underlying, keyOwner, keyTokenAddress));\n },\n staleTime: 30_000,\n enabled: Boolean(ownerKey) && queryEnabled,\n };\n}\n","import type { Address, Hex } from \"viem\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link pendingUnshieldQueryOptions}. */\nexport interface PendingUnshieldQueryConfig {\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/**\n * Query options for reading the unwrap tx hash of an unshield that was\n * interrupted between its two phases (returns `null` if none is pending).\n *\n * Backed by {@link ZamaSDK} storage via `WrappedToken.getPendingUnshield()`.\n * `staleTime: 0` so the value reflects storage on mount; the unshield/unwrap\n * mutations also invalidate this key on success.\n */\nexport function pendingUnshieldQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address,\n config?: PendingUnshieldQueryConfig,\n): QueryFactoryOptions<\n Hex | null,\n Error,\n Hex | null,\n ReturnType<typeof zamaQueryKeys.pendingUnshield.token>\n> {\n const queryKey = zamaQueryKeys.pendingUnshield.token(tokenAddress);\n\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress }] = context.queryKey;\n return sdk.createWrappedToken(keyTokenAddress).getPendingUnshield();\n },\n staleTime: 0,\n enabled: config?.query?.enabled !== false,\n };\n}\n","import { isOperatorContract } from \"../contracts\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { filterQueryOptions } from \"./utils\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { Address } from \"viem\";\n\n/** Configuration for {@link confidentialIsOperatorQueryOptions}. */\nexport interface ConfidentialIsOperatorQueryConfig {\n /** Token holder whose operator authorization to check; the query stays disabled until provided. */\n holder?: Address;\n /** Spender address to check for operator authorization; the query stays disabled until provided. */\n spender?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading whether a spender is an authorized operator of a holder on a confidential token. */\nexport function confidentialIsOperatorQueryOptions(\n sdk: ZamaSDK,\n tokenAddress: Address | undefined,\n config: ConfidentialIsOperatorQueryConfig,\n): QueryFactoryOptions<\n boolean,\n Error,\n boolean,\n ReturnType<typeof zamaQueryKeys.confidentialIsOperator.scope>\n> {\n const holderKey = config.holder;\n const spenderKey = config.spender;\n const queryEnabled = config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.confidentialIsOperator.scope(tokenAddress, holderKey, spenderKey);\n\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { tokenAddress: keyTokenAddress, holder: keyHolder, spender: keySpender }] =\n context.queryKey;\n assertNonNullable(keyTokenAddress, \"confidentialIsOperatorQueryOptions: tokenAddress\");\n assertNonNullable(keyHolder, \"confidentialIsOperatorQueryOptions: holder\");\n assertNonNullable(keySpender, \"confidentialIsOperatorQueryOptions: spender\");\n return sdk.provider.readContract(isOperatorContract(keyTokenAddress, keyHolder, keySpender));\n },\n staleTime: 30_000,\n enabled: Boolean(tokenAddress && holderKey && spenderKey) && queryEnabled,\n };\n}\n","import type { Address } from \"viem\";\nimport type { Token } from \"../token\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { SignerQueryContext } from \"./signer-query-context\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link confidentialBalanceQueryOptions}. */\nexport interface ConfidentialBalanceQueryConfig {\n /** Address of the confidential token to read the balance of. */\n tokenAddress: Address;\n /** Account whose confidential balance to read; the query stays disabled until provided. */\n account?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Query options for a single confidential token balance. Auto-gated on `account`. */\nexport function confidentialBalanceQueryOptions(\n token: Token,\n config: ConfidentialBalanceQueryConfig,\n signerContext: SignerQueryContext = {},\n): QueryFactoryOptions<\n bigint,\n Error,\n bigint,\n ReturnType<typeof zamaQueryKeys.confidentialBalance.owner>\n> {\n const queryOpts = config.query ?? {};\n\n return {\n ...filterQueryOptions(queryOpts),\n queryKey: zamaQueryKeys.confidentialBalance.owner(\n config.tokenAddress,\n config.account,\n signerContext.walletAccount,\n ),\n queryFn: async (context) => {\n const [, { owner: keyOwner }] = context.queryKey;\n assertNonNullable(keyOwner, \"confidentialBalanceQueryOptions: owner\");\n return token.balanceOf(keyOwner);\n },\n enabled:\n Boolean(config.account) &&\n signerContext.walletAccount !== undefined &&\n queryOpts?.enabled !== false,\n };\n}\n","import type { Address } from \"viem\";\nimport { Token, type BatchBalancesResult } from \"../token/token\";\nimport { assertNonNullable } from \"../utils/assertions\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { SignerQueryContext } from \"./signer-query-context\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link confidentialBalancesQueryOptions}. */\nexport interface ConfidentialBalancesQueryConfig {\n /** Account whose confidential balances to read; the query stays disabled until provided. */\n account?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading the confidential balances of several tokens for one account in a single batch. */\nexport function confidentialBalancesQueryOptions(\n tokens: Token[],\n config?: ConfidentialBalancesQueryConfig,\n signerContext: SignerQueryContext = {},\n): QueryFactoryOptions<\n BatchBalancesResult,\n Error,\n BatchBalancesResult,\n ReturnType<typeof zamaQueryKeys.confidentialBalances.tokens>\n> {\n const accountKey = config?.account;\n const walletAccount = signerContext.walletAccount;\n const queryOpts = config?.query ?? {};\n const tokenAddresses = tokens.map((token) => token.address);\n\n return {\n ...filterQueryOptions(queryOpts),\n queryKey: zamaQueryKeys.confidentialBalances.tokens(tokenAddresses, accountKey, walletAccount),\n queryFn: async (signerContextQuery) => {\n const [, { owner: keyOwner }] = signerContextQuery.queryKey;\n assertNonNullable(keyOwner, \"confidentialBalancesQueryOptions: owner\");\n return Token.batchBalancesOf(tokens, keyOwner);\n },\n enabled:\n Boolean(accountKey) &&\n tokens.length > 0 &&\n walletAccount !== undefined &&\n queryOpts?.enabled !== false,\n };\n}\n","import { type Address, zeroAddress } from \"viem\";\nimport {\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\nimport type {\n TokenWrapperPair,\n TokenWrapperPairWithMetadata,\n PaginatedResult,\n} from \"../contracts/wrappers-registry\";\nimport type { WrappersRegistry } from \"../wrappers-registry\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Base configuration shared by the wrappers-registry query option factories. */\nexport interface WrappersRegistryQueryConfig {\n /** Registry contract address for the current chain; used as a query key discriminator. */\n registryAddress: Address | undefined;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading all token wrapper pairs registered in the wrappers registry. */\nexport function tokenPairsQueryOptions(\n sdk: ZamaSDK,\n config: WrappersRegistryQueryConfig,\n): QueryFactoryOptions<\n readonly TokenWrapperPair[],\n Error,\n readonly TokenWrapperPair[],\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairs>\n> {\n const enabled = Boolean(config.registryAddress) && config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenPairs(config.registryAddress ?? zeroAddress);\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress }] = context.queryKey;\n return sdk.provider.readContract(getTokenPairsContract(registryAddress));\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link confidentialTokenAddressQueryOptions}. */\nexport interface ConfidentialTokenAddressQueryConfig extends WrappersRegistryQueryConfig {\n /** Underlying ERC-20 token address whose confidential counterpart to look up. */\n tokenAddress?: Address;\n}\n\n/** Builds TanStack Query options for reading the confidential token address registered for a given underlying ERC-20 token. */\nexport function confidentialTokenAddressQueryOptions(\n sdk: ZamaSDK,\n config: ConfidentialTokenAddressQueryConfig,\n): QueryFactoryOptions<\n readonly [boolean, Address],\n Error,\n readonly [boolean, Address],\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.confidentialTokenAddress>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n Boolean(config.tokenAddress) &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.confidentialTokenAddress(\n config.registryAddress ?? zeroAddress,\n config.tokenAddress ?? zeroAddress,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, tokenAddress }] = context.queryKey;\n return sdk.provider.readContract(\n getConfidentialTokenAddressContract(registryAddress, tokenAddress),\n );\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link tokenAddressQueryOptions}. */\nexport interface TokenAddressQueryConfig extends WrappersRegistryQueryConfig {\n /** Confidential token address whose underlying ERC-20 counterpart to look up. */\n confidentialTokenAddress?: Address;\n}\n\n/** Builds TanStack Query options for reading the underlying ERC-20 token address registered for a given confidential token. */\nexport function tokenAddressQueryOptions(\n sdk: ZamaSDK,\n config: TokenAddressQueryConfig,\n): QueryFactoryOptions<\n readonly [boolean, Address],\n Error,\n readonly [boolean, Address],\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenAddress>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n Boolean(config.confidentialTokenAddress) &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenAddress(\n config.registryAddress ?? zeroAddress,\n config.confidentialTokenAddress ?? zeroAddress,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, confidentialTokenAddress }] = context.queryKey;\n return sdk.provider.readContract(\n getTokenAddressContract(registryAddress, confidentialTokenAddress),\n );\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Builds TanStack Query options for reading the total number of token wrapper pairs in the registry. */\nexport function tokenPairsLengthQueryOptions(\n sdk: ZamaSDK,\n config: WrappersRegistryQueryConfig,\n): QueryFactoryOptions<\n bigint,\n Error,\n bigint,\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairsLength>\n> {\n const enabled = Boolean(config.registryAddress) && config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenPairsLength(\n config.registryAddress ?? zeroAddress,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress }] = context.queryKey;\n return sdk.provider.readContract(getTokenPairsLengthContract(registryAddress));\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link tokenPairsSliceQueryOptions}. */\nexport interface TokenPairsSliceQueryConfig extends WrappersRegistryQueryConfig {\n /** Zero-based index of the first pair in the slice (inclusive). */\n fromIndex?: bigint;\n /** Index bounding the end of the slice. */\n toIndex?: bigint;\n}\n\n/** Builds TanStack Query options for reading a contiguous slice of the registry's token wrapper pairs. */\nexport function tokenPairsSliceQueryOptions(\n sdk: ZamaSDK,\n config: TokenPairsSliceQueryConfig,\n): QueryFactoryOptions<\n readonly TokenWrapperPair[],\n Error,\n readonly TokenWrapperPair[],\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairsSlice>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n config.fromIndex !== undefined &&\n config.toIndex !== undefined &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenPairsSlice(\n config.registryAddress ?? zeroAddress,\n String(config.fromIndex ?? 0n),\n String(config.toIndex ?? 0n),\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, fromIndex, toIndex }] = context.queryKey;\n return sdk.provider.readContract(\n getTokenPairsSliceContract(registryAddress, BigInt(fromIndex), BigInt(toIndex)),\n );\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link tokenPairQueryOptions}. */\nexport interface TokenPairQueryConfig extends WrappersRegistryQueryConfig {\n /** Zero-based index of the token wrapper pair to read. */\n index?: bigint;\n}\n\n/** Builds TanStack Query options for reading a single token wrapper pair by its index in the registry. */\nexport function tokenPairQueryOptions(\n sdk: ZamaSDK,\n config: TokenPairQueryConfig,\n): QueryFactoryOptions<\n TokenWrapperPair,\n Error,\n TokenWrapperPair,\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPair>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n config.index !== undefined &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.tokenPair(\n config.registryAddress ?? zeroAddress,\n String(config.index ?? 0n),\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, index }] = context.queryKey;\n return sdk.provider.readContract(getTokenPairContract(registryAddress, BigInt(index)));\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link isConfidentialTokenValidQueryOptions}. */\nexport interface IsConfidentialTokenValidQueryConfig extends WrappersRegistryQueryConfig {\n /** Confidential token address to validate against the registry. */\n confidentialTokenAddress?: Address;\n}\n\n/** Builds TanStack Query options for checking whether a confidential token is registered and valid in the registry. */\nexport function isConfidentialTokenValidQueryOptions(\n sdk: ZamaSDK,\n config: IsConfidentialTokenValidQueryConfig,\n): QueryFactoryOptions<\n boolean,\n Error,\n boolean,\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.isConfidentialTokenValid>\n> {\n const enabled =\n Boolean(config.registryAddress) &&\n Boolean(config.confidentialTokenAddress) &&\n config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.isConfidentialTokenValid(\n config.registryAddress ?? zeroAddress,\n config.confidentialTokenAddress ?? zeroAddress,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { registryAddress, confidentialTokenAddress }] = context.queryKey;\n return sdk.provider.readContract(\n isConfidentialTokenValidContract(registryAddress, confidentialTokenAddress),\n );\n },\n staleTime: sdk.registry.ttlMs,\n enabled,\n };\n}\n\n/** Configuration for {@link listPairsQueryOptions}. */\nexport interface ListPairsQueryConfig {\n /**\n * The registry address for this chain — used as a query key discriminator.\n * The registry instance already knows how to resolve the address for the\n * current chain; this field just keeps the TanStack Query cache isolated\n * per registry contract.\n */\n registryAddress: Address | undefined;\n /** 1-based page number to fetch; defaults to `1`. */\n page?: number;\n /** Number of pairs per page; defaults to `100`. */\n pageSize?: number;\n /** When `true`, resolve each pair's on-chain metadata; defaults to `false`. */\n metadata?: boolean;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/**\n * Query options for paginated listing of token wrapper pairs.\n *\n * Accepts a {@link WrappersRegistry} instance rather than a raw provider so that the\n * class-level TTL cache is shared across multiple `queryFn` executions. Pass\n * `sdk.registry` (the ZamaSDK lazy singleton) to ensure a single shared cache.\n */\nexport function listPairsQueryOptions(\n registry: WrappersRegistry,\n config: ListPairsQueryConfig,\n): QueryFactoryOptions<\n PaginatedResult<TokenWrapperPair | TokenWrapperPairWithMetadata>,\n Error,\n PaginatedResult<TokenWrapperPair | TokenWrapperPairWithMetadata>,\n ReturnType<typeof zamaQueryKeys.wrappersRegistry.listPairs>\n> {\n const enabled = Boolean(config.registryAddress) && config.query?.enabled !== false;\n const queryKey = zamaQueryKeys.wrappersRegistry.listPairs(\n config.registryAddress ?? zeroAddress,\n config.page ?? 1,\n config.pageSize ?? 100,\n config.metadata ?? false,\n );\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey,\n queryFn: async (context) => {\n const [, { page, pageSize, metadata }] = context.queryKey;\n return registry.listPairs({ page, pageSize, metadata });\n },\n // Use the registry's own TTL so TanStack Query and the class-level cache\n // operate under the same freshness contract.\n staleTime: registry.ttlMs,\n enabled,\n };\n}\n","import type { Address } from \"viem\";\nimport type { WrappedToken } from \"../token/wrapped-token\";\nimport type { ShieldOptions, TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link shieldMutationOptions}. */\nexport interface ShieldParams extends ShieldOptions {\n /** Amount of the public ERC-20 to shield, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.shield | shielding} a public ERC-20 into its confidential form. @see {@link ShieldParams} */\nexport function shieldMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.shield\", Address], ShieldParams, TransactionResult> {\n return {\n mutationKey: [\"zama.shield\", token.address] as const,\n mutationFn: async ({ amount, ...rest }) => token.shield(amount, rest),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransactionResult, TransferOptions } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link confidentialTransferMutationOptions}. */\nexport interface ConfidentialTransferParams extends TransferOptions {\n /** Recipient address. */\n to: Address;\n /** Amount of tokens to transfer, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.confidentialTransfer | transferring} confidential tokens. @see {@link ConfidentialTransferParams} */\nexport function confidentialTransferMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialTransfer\", Address],\n ConfidentialTransferParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialTransfer\", token.address] as const,\n mutationFn: async ({ to, amount, ...options }) =>\n token.confidentialTransfer(to, amount, options),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransactionResult, TransferOptions } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address, Hex } from \"viem\";\n\n/** Variables for {@link confidentialTransferAndCallMutationOptions}. */\nexport interface ConfidentialTransferAndCallParams extends TransferOptions {\n /** Recipient address. */\n to: Address;\n /** Amount of tokens to transfer, in the token's base units. */\n amount: bigint;\n /** Opaque bytes forwarded to the recipient's ERC-7984 receiver hook. */\n data: Hex;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.confidentialTransferAndCall | transferring} confidential tokens and invoking the recipient's receiver hook. @see {@link ConfidentialTransferAndCallParams} */\nexport function confidentialTransferAndCallMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialTransferAndCall\", Address],\n ConfidentialTransferAndCallParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialTransferAndCall\", token.address] as const,\n mutationFn: async ({ to, amount, data, ...options }) =>\n token.confidentialTransferAndCall(to, amount, data, options),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransferCallbacks, TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link confidentialTransferFromMutationOptions}. */\nexport interface ConfidentialTransferFromParams {\n /** Address to transfer from. */\n from: Address;\n /** Recipient address. */\n to: Address;\n /** Amount of tokens to transfer, in the token's base units. */\n amount: bigint;\n /** Optional progress callbacks for the multi-step transfer flow. */\n callbacks?: TransferCallbacks;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.confidentialTransferFrom | transferring} confidential tokens from another account (operator flow). @see {@link ConfidentialTransferFromParams} */\nexport function confidentialTransferFromMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialTransferFrom\", Address],\n ConfidentialTransferFromParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialTransferFrom\", token.address] as const,\n mutationFn: async ({ from, to, amount, callbacks }) =>\n token.confidentialTransferFrom(from, to, amount, callbacks),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransferCallbacks, TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address, Hex } from \"viem\";\n\n/** Variables for {@link confidentialTransferFromAndCallMutationOptions}. */\nexport interface ConfidentialTransferFromAndCallParams {\n /** Address to transfer from. */\n from: Address;\n /** Recipient address. */\n to: Address;\n /** Amount of tokens to transfer, in the token's base units. */\n amount: bigint;\n /** Opaque bytes forwarded to the recipient's ERC-7984 receiver hook. */\n data: Hex;\n /** Optional progress callbacks for the multi-step transfer flow. */\n callbacks?: TransferCallbacks;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.confidentialTransferFromAndCall | transferring} confidential tokens from another account and invoking the recipient's receiver hook. @see {@link ConfidentialTransferFromAndCallParams} */\nexport function confidentialTransferFromAndCallMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialTransferFromAndCall\", Address],\n ConfidentialTransferFromAndCallParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialTransferFromAndCall\", token.address] as const,\n mutationFn: async ({ from, to, amount, data, callbacks }) =>\n token.confidentialTransferFromAndCall(from, to, amount, data, callbacks),\n };\n}\n","import type { Token } from \"../token/token\";\nimport type { TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link confidentialSetOperatorMutationOptions}. */\nexport interface ConfidentialSetOperatorParams {\n /** Operator address to authorize. */\n operator: Address;\n /** Unix timestamp (seconds) when the operator authorization expires; defaults to one hour from now. */\n until?: number;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.setOperator | authorizing} an operator on a confidential token. @see {@link ConfidentialSetOperatorParams} */\nexport function confidentialSetOperatorMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.confidentialSetOperator\", Address],\n ConfidentialSetOperatorParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.confidentialSetOperator\", token.address] as const,\n mutationFn: async ({ operator, until }) => token.setOperator(operator, until),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link approveUnderlyingMutationOptions}. */\nexport interface ApproveUnderlyingParams {\n /** Amount of the underlying ERC-20 to approve, in its base units; omit for a max approval. */\n amount?: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.approveUnderlying | approving} the wrapper to spend the underlying ERC-20. @see {@link ApproveUnderlyingParams} */\nexport function approveUnderlyingMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<\n readonly [\"zama.approveUnderlying\", Address],\n ApproveUnderlyingParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.approveUnderlying\", token.address] as const,\n mutationFn: async ({ amount }) => token.approveUnderlying(amount),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult, UnshieldOptions } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link unshieldMutationOptions}. */\nexport interface UnshieldParams extends UnshieldOptions {\n /** Amount of tokens to unshield, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.unshield | unshielding} a confidential token back into its public ERC-20. @see {@link UnshieldParams} */\nexport function unshieldMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unshield\", Address], UnshieldParams, TransactionResult> {\n return {\n mutationKey: [\"zama.unshield\", token.address] as const,\n mutationFn: async ({ amount, ...options }) => token.unshield(amount, options),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult, UnshieldCallbacks } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link unshieldAllMutationOptions}. */\nexport interface UnshieldAllParams extends UnshieldCallbacks {}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.unshieldAll | unshielding} the entire confidential balance back into the public ERC-20. @see {@link UnshieldAllParams} */\nexport function unshieldAllMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<\n readonly [\"zama.unshieldAll\", Address],\n UnshieldAllParams | void,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.unshieldAll\", token.address] as const,\n mutationFn: async (params) => token.unshieldAll(params || undefined),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult, UnshieldCallbacks } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address, Hex } from \"viem\";\n\n/** Variables for {@link resumeUnshieldMutationOptions}. */\nexport interface ResumeUnshieldParams extends UnshieldCallbacks {\n /** Hash of the earlier unwrap request transaction to resume from. */\n unwrapTxHash: Hex;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.resumeUnshield | resuming} an interrupted unshield from its unwrap request transaction. @see {@link ResumeUnshieldParams} */\nexport function resumeUnshieldMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<\n readonly [\"zama.resumeUnshield\", Address],\n ResumeUnshieldParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.resumeUnshield\", token.address] as const,\n mutationFn: async ({ unwrapTxHash, ...callbacks }) =>\n token.resumeUnshield(unwrapTxHash, callbacks),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { UnwrapResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link unwrapMutationOptions}. */\nexport interface UnwrapParams {\n /** Amount of tokens to unwrap, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.unwrap | unwrapping} a confidential token (request phase of the two-phase unwrap). @see {@link UnwrapParams} */\nexport function unwrapMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unwrap\", Address], UnwrapParams, UnwrapResult> {\n return {\n mutationKey: [\"zama.unwrap\", token.address] as const,\n mutationFn: async ({ amount }) => token.unwrap(amount),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult, WrapOptions } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link wrapMutationOptions}. */\nexport interface WrapParams extends WrapOptions {\n /** Amount of the public ERC-20 to wrap, in the token's base units. */\n amount: bigint;\n}\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.wrap | wrapping} a public ERC-20 into its confidential form. @see {@link WrapParams} */\nexport function wrapMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.wrap\", Address], WrapParams, TransactionResult> {\n return {\n mutationKey: [\"zama.wrap\", token.address] as const,\n mutationFn: async ({ amount, ...rest }) => token.wrap(amount, rest),\n };\n}\n","import type { WrappedToken } from \"../token/wrapped-token\";\nimport type { UnwrapResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.unwrapAll | unwrapping} the entire confidential balance. */\nexport function unwrapAllMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unwrapAll\", Address], void, UnwrapResult> {\n return {\n mutationKey: [\"zama.unwrapAll\", token.address] as const,\n mutationFn: async () => token.unwrapAll(),\n };\n}\n","import type { EncryptedValue } from \"../relayer/types\";\nimport type { WrappedToken } from \"../token/wrapped-token\";\nimport type { TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n/** Variables for {@link finalizeUnwrapMutationOptions}. */\nexport type FinalizeUnwrapParams = {\n /** Identifier from an `UnwrapRequested` event. */\n unwrapRequestId: EncryptedValue;\n};\n\n/** Builds TanStack Query mutation options for {@link WrappedToken.finalizeUnwrap | finalizing} a previously requested unwrap. @see {@link FinalizeUnwrapParams} */\nexport function finalizeUnwrapMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<\n readonly [\"zama.finalizeUnwrap\", Address],\n FinalizeUnwrapParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.finalizeUnwrap\", token.address] as const,\n mutationFn: async ({ unwrapRequestId }) => token.finalizeUnwrap(unwrapRequestId),\n };\n}\n","import type { EncryptParams } from \"../node\";\nimport type { EncryptResult } from \"../relayer/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Builds TanStack Query mutation options for {@link ZamaSDK.encrypt | encrypting} plaintext inputs into an encrypted payload. */\nexport function encryptMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.encrypt\"], EncryptParams, EncryptResult> {\n return { mutationKey: [\"zama.encrypt\"], mutationFn: async (params) => sdk.encrypt(params) };\n}\n","import type { Address } from \"viem\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/types\";\nimport type { EncryptedInput } from \"./user-decrypt\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link delegatedDecryptValuesMutationOptions}. */\nexport interface DelegatedDecryptValuesMutationParams {\n /** Encrypted values (with their contract addresses) to decrypt. */\n encryptedInputs: EncryptedInput[];\n /** Address of the account that delegated decryption rights to the connected wallet. */\n delegatorAddress: Address;\n}\n\n/** Builds TanStack Query mutation options for {@link Decryption.delegatedDecryptValues | decrypting} encrypted values via delegated decryption credentials. @see {@link DelegatedDecryptValuesMutationParams} */\nexport function delegatedDecryptValuesMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<\n readonly [\"zama.delegatedDecryptValues\"],\n DelegatedDecryptValuesMutationParams,\n Readonly<Record<EncryptedValue, ClearValue>>\n> {\n return {\n mutationKey: [\"zama.delegatedDecryptValues\"],\n mutationFn: async (params) =>\n sdk.decryption.delegatedDecryptValues(params.encryptedInputs, params.delegatorAddress),\n };\n}\n","import type { ClearValue, EncryptedValue, DecryptPublicValuesResult } from \"../relayer/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\n\n/** Builds TanStack Query mutation options for {@link Decryption.decryptPublicValues | publicly decrypting} encrypted values, caching each clear result. */\nexport function decryptPublicValuesMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<\n readonly [\"zama.decryptPublicValues\"],\n EncryptedValue[],\n DecryptPublicValuesResult\n> {\n return {\n mutationKey: [\"zama.decryptPublicValues\"],\n mutationFn: async (handles) => sdk.decryption.decryptPublicValues(handles),\n onSuccess: (data, _variables, _onMutateResult, context) => {\n for (const [handle, value] of Object.entries(data.clearValues) as [\n EncryptedValue,\n ClearValue,\n ][]) {\n context.client.setQueryData(zamaQueryKeys.decryption.encryptedValue(handle), value);\n }\n },\n };\n}\n","import type { Address } from \"viem\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Builds TanStack Query mutation options for {@link Permits.grantPermit | granting} decryption permits for the given contract addresses. */\nexport function grantPermitMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.grantPermit\"], Address[], void> {\n return {\n mutationKey: [\"zama.grantPermit\"],\n mutationFn: (contractAddresses) => sdk.permits.grantPermit(contractAddresses),\n };\n}\n","import type { PreparedPermit, PreparePermitRequest } from \"../credentials/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Builds TanStack Query mutation options for {@link Offline.preparePermit | preparing} an offline decryption permit. */\nexport function preparePermitMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.preparePermit\"], PreparePermitRequest, PreparedPermit> {\n return {\n mutationKey: [\"zama.preparePermit\"],\n mutationFn: (request) => sdk.offline.preparePermit(request),\n };\n}\n","import type { Hex } from \"viem\";\nimport type { PreparedPermit } from \"../credentials/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Parameters for {@link registerPermitMutationOptions}. */\nexport interface RegisterPermitParams {\n /** The payload `sdk.offline.preparePermit` returned. */\n prepared: PreparedPermit;\n /** The `eth_signTypedData_v4` signature over `prepared.eip712`. */\n signature: Hex;\n}\n\n/** Builds TanStack Query mutation options for {@link Permits.registerPermit | registering} a signed offline permit. */\nexport function registerPermitMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.registerPermit\"], RegisterPermitParams, void> {\n return {\n mutationKey: [\"zama.registerPermit\"],\n mutationFn: ({ prepared, signature }) => sdk.permits.registerPermit(prepared, signature),\n };\n}\n","import type { Address } from \"viem\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { SignerQueryContext } from \"./signer-query-context\";\nimport { filterQueryOptions } from \"./utils\";\n\n/** Configuration for {@link hasPermitQueryOptions}. */\nexport interface HasPermitQueryConfig {\n /** Contract addresses to check credentials against. */\n contractAddresses: Address[];\n /**\n * Standard TanStack query options. `hasPermit` intentionally overrides cache\n * timing because permit state is wallet-local, not server state: every fetch\n * should read the SDK credential service directly.\n */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading whether the connected wallet holds a valid decryption permit for the given contracts. */\nexport function hasPermitQueryOptions(\n sdk: ZamaSDK,\n config: HasPermitQueryConfig,\n signerContext: SignerQueryContext = {},\n): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.hasPermit.scope>> {\n const callerEnabled = config.query?.enabled !== false;\n return {\n ...filterQueryOptions(config?.query ?? {}),\n queryKey: zamaQueryKeys.hasPermit.scope(config.contractAddresses, signerContext.walletAccount),\n queryFn: (context) => {\n const [, { contractAddresses }] = context.queryKey;\n return sdk.permits.hasPermit(contractAddresses as Address[]);\n },\n staleTime: 0,\n gcTime: 0,\n refetchOnMount: \"always\",\n refetchOnWindowFocus: false,\n enabled:\n callerEnabled &&\n signerContext.walletAccount !== undefined &&\n config.contractAddresses.length > 0,\n } as const;\n}\n","import type { Address } from \"viem\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** TanStack Query mutation factory for {@link Permits.revokePermits}. */\nexport function revokePermitsMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.revokePermits\"], Address[] | void, void> {\n return {\n mutationKey: [\"zama.revokePermits\"],\n mutationFn: (contracts: Address[] | void) =>\n contracts === undefined ? sdk.permits.revokePermits() : sdk.permits.revokePermits(contracts),\n };\n}\n","import type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** TanStack Query mutation factory for {@link Permits.clear}. */\nexport function clearCredentialsMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.clearCredentials\"], void, void> {\n return { mutationKey: [\"zama.clearCredentials\"], mutationFn: () => sdk.permits.clear() };\n}\n","import type { Address } from \"viem\";\nimport type { TransactionResult } from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link delegateDecryptionMutationOptions}. */\nexport interface DelegateDecryptionParams {\n /** Address to grant delegated decryption rights to. */\n delegateAddress: Address;\n /** When the delegation expires; omit for no expiry. */\n expirationDate?: Date;\n}\n\n/** Builds TanStack Query mutation options for {@link Delegations.delegateDecryption | granting} delegated decryption rights on a contract. @see {@link DelegateDecryptionParams} */\nexport function delegateDecryptionMutationOptions(\n sdk: ZamaSDK,\n contractAddress: Address,\n): MutationFactoryOptions<\n readonly [\"zama.delegateDecryption\", Address],\n DelegateDecryptionParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.delegateDecryption\", contractAddress] as const,\n mutationFn: async ({ delegateAddress, expirationDate }) =>\n sdk.delegations.delegateDecryption({ contractAddress, delegateAddress, expirationDate }),\n };\n}\n","import type { Address } from \"viem\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport type { SignerQueryContext } from \"./signer-query-context\";\n\n/** A single encrypted value to decrypt, paired with the contract that owns it. */\nexport interface EncryptedInput {\n /** Encrypted handle to decrypt. */\n encryptedValue: EncryptedValue;\n /** Address of the contract the encrypted value belongs to. */\n contractAddress: Address;\n}\n\n/** Decrypted clear values keyed by encrypted handle. */\nexport type DecryptResult = Readonly<Record<EncryptedValue, ClearValue>>;\n\n/** Builds TanStack Query options for decrypting a batch of encrypted handles into their clear values. */\nexport function decryptValuesQueryOptions(\n sdk: ZamaSDK,\n encryptedInputs: EncryptedInput[],\n signerContext: SignerQueryContext = {},\n): QueryFactoryOptions<\n DecryptResult,\n Error,\n DecryptResult,\n ReturnType<typeof zamaQueryKeys.decryption.encryptedInputs>\n> {\n return {\n queryKey: zamaQueryKeys.decryption.encryptedInputs(\n encryptedInputs,\n signerContext.walletAccount,\n ),\n queryFn: (context) => {\n const [, { encryptedInputs: keyedInputs }] = context.queryKey;\n return sdk.decryption.decryptValues(keyedInputs);\n },\n staleTime: Infinity,\n enabled: encryptedInputs.length > 0 && signerContext.walletAccount !== undefined,\n };\n}\n","import type { Address } from \"viem\";\nimport type { Token } from \"../token/token\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link decryptBalanceAsMutationOptions}. */\nexport interface DecryptBalanceAsParams {\n /** Address of the account that delegated decryption rights to the connected wallet. */\n delegatorAddress: Address;\n /** Account whose on-chain balance to read; defaults to the delegator address. */\n accountAddress?: Address;\n}\n\n/** Builds TanStack Query mutation options for {@link Token.decryptBalanceAs | decrypting} a balance via delegated decryption credentials. @see {@link DecryptBalanceAsParams} */\nexport function decryptBalanceAsMutationOptions(\n token: Token,\n): MutationFactoryOptions<\n readonly [\"zama.decryptBalanceAs\", Address],\n DecryptBalanceAsParams,\n bigint\n> {\n return {\n mutationKey: [\"zama.decryptBalanceAs\", token.address] as const,\n mutationFn: async ({ delegatorAddress, accountAddress }) =>\n token.decryptBalanceAs({ delegatorAddress, accountAddress }),\n };\n}\n","import { Token, type BatchDecryptAsOptions } from \"../token/token\";\nimport type { Address } from \"viem\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link batchDecryptBalancesAsMutationOptions}. */\nexport type BatchDecryptBalancesAsParams = BatchDecryptAsOptions;\n\n/** Builds TanStack Query mutation options for {@link Token.batchDecryptBalancesAs | decrypting} multiple token balances via delegated decryption credentials. @see {@link BatchDecryptBalancesAsParams} */\nexport function batchDecryptBalancesAsMutationOptions(\n tokens: Token[],\n): MutationFactoryOptions<\n readonly [\"zama.batchDecryptBalancesAs\", ...Address[]],\n BatchDecryptBalancesAsParams,\n Map<Address, bigint>\n> {\n return {\n mutationKey: [\"zama.batchDecryptBalancesAs\", ...tokens.map((t) => t.address)] as const,\n mutationFn: async (params) => Token.batchDecryptBalancesAs(tokens, params),\n };\n}\n","import type { Address } from \"viem\";\nimport type { TransactionResult } from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\n/** Variables for {@link revokeDelegationMutationOptions}. */\nexport interface RevokeDelegationParams {\n /** Address whose delegated decryption rights to revoke. */\n delegateAddress: Address;\n}\n\n/** Builds TanStack Query mutation options for {@link Delegations.revokeDelegation | revoking} delegated decryption rights on a contract. @see {@link RevokeDelegationParams} */\nexport function revokeDelegationMutationOptions(\n sdk: ZamaSDK,\n contractAddress: Address,\n): MutationFactoryOptions<\n readonly [\"zama.revokeDelegation\", Address],\n RevokeDelegationParams,\n TransactionResult\n> {\n return {\n mutationKey: [\"zama.revokeDelegation\", contractAddress] as const,\n mutationFn: async ({ delegateAddress }) =>\n sdk.delegations.revokeDelegation({ contractAddress, delegateAddress }),\n };\n}\n","import type { Address } from \"viem\";\nimport type { DelegationStatus } from \"../services/delegation-service\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { QueryFactoryOptions } from \"./factory-types\";\nimport { filterQueryOptions } from \"./utils\";\nimport { zamaQueryKeys } from \"./query-keys\";\nimport { assertNonNullable } from \"../utils\";\n\nexport type { DelegationStatus } from \"../services/delegation-service\";\n\n/** Configuration for {@link delegationStatusQueryOptions}. */\nexport interface DelegationStatusQueryConfig {\n /** Contract the delegation applies to; pass `undefined` to keep the query disabled. */\n contractAddress: Address | undefined;\n /** Address granting the delegated decryption rights; the query stays disabled until provided. */\n delegatorAddress?: Address;\n /** Address receiving the delegated decryption rights; the query stays disabled until provided. */\n delegateAddress?: Address;\n /** Additional TanStack Query options merged into the generated query (e.g. `staleTime`, `enabled`). */\n query?: Record<string, unknown>;\n}\n\n/** Builds TanStack Query options for reading the decryption-delegation status between a delegator and a delegate on a contract. */\nexport function delegationStatusQueryOptions(\n sdk: ZamaSDK,\n config: DelegationStatusQueryConfig,\n): QueryFactoryOptions<\n DelegationStatus,\n Error,\n DelegationStatus,\n ReturnType<typeof zamaQueryKeys.delegationStatus.scope>\n> {\n return {\n ...filterQueryOptions(config.query ?? {}),\n queryKey: zamaQueryKeys.delegationStatus.scope(\n config.contractAddress,\n config.delegatorAddress,\n config.delegateAddress,\n ),\n queryFn: async (context) => {\n const [, { contractAddress, delegatorAddress, delegateAddress }] = context.queryKey;\n assertNonNullable(contractAddress, \"delegationStatusQueryOptions: contractAddress\");\n assertNonNullable(delegatorAddress, \"delegationStatusQueryOptions: delegatorAddress\");\n assertNonNullable(delegateAddress, \"delegationStatusQueryOptions: delegateAddress\");\n return sdk.delegations.getStatus({ contractAddress, delegatorAddress, delegateAddress });\n },\n enabled:\n Boolean(config.contractAddress && config.delegatorAddress && config.delegateAddress) &&\n config.query?.enabled !== false,\n } as const;\n}\n"],"mappings":"ofAyBA,SAAgB,EACd,EACA,EACA,EAMA,CACA,IAAM,EAAW,EAAc,cAAc,MAAM,CAAY,EAE/D,MAAO,CACL,GAAG,EAAmB,GAAQ,OAAS,CAAC,CAAC,EACzC,WACA,QAAS,KAAO,IAAY,CAC1B,GAAM,EAAG,CAAE,aAAc,IAAqB,EAAQ,SAChD,CAAC,EAAM,EAAQ,GAAY,MAAM,QAAQ,IAAI,CACjD,EAAI,SAAS,aAAa,EAAa,CAAe,CAAC,EACvD,EAAI,SAAS,aAAa,EAAe,CAAe,CAAC,EACzD,EAAI,SAAS,aAAa,EAAiB,CAAe,CAAC,CAC7D,CAAC,EACD,MAAO,CAAE,OAAM,SAAQ,UAAS,CAClC,EACA,UAAW,IACX,QAAS,GAAQ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(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function t(e){if(!(e instanceof Error))return!1;if(e.name===`ContractFunctionExecutionError`||e.name===`ContractFunctionRevertedError`||`code`in e&&e.code===`CALL_EXCEPTION`)return!0;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}const n=[`cause`,`error`,`info`];function r(e,t,i=6){if(i<0||typeof e!=`object`||!e)return;let a=e;if(t(a))return a;for(let e of n){let n=a[e];if(typeof n==`object`&&n){let e=r(n,t,i-1);if(e)return e}}}function i(e){if(e.code===-32005||e.status===429||e.code===429)return!0;if(e.code===`SERVER_ERROR`&&typeof e.info==`object`&&e.info!==null){let t=e.info.responseStatus;if(typeof t==`string`&&/^\s*429\b/.test(t))return!0}return!1}function a(e){if(i(e))return!0;if(typeof e.message==`string`){let t=e.message.toLowerCase();return t.includes(`too many requests`)||t.includes(`rate limit`)||t.includes(`rate-limit`)}return!1}function o(e){return r(e,e=>typeof e.name==`string`&&e.name.startsWith(`Relayer`))!==void 0}function s(e){return r(e,e=>e.name===`RelayerTimeoutError`)!==void 0}function c(e){return!o(e)&&r(e,a)!==void 0}function l(e){return!o(e)&&r(e,i)!==void 0}function u(e){return e.toLowerCase().includes(`is not authorized to decrypt handle`)}function d(e){return e.toLowerCase().includes(`invalid transportkeypair`)}const f=[`data`,`raw`,`signature`];function p(e){for(let t of f){let n=e[t];if(typeof n==`string`&&n.toLowerCase().startsWith(`0x77ddbe81`))return!0}if(typeof e.message==`string`){let t=e.message.toLowerCase();return t.includes(`0x77ddbe81`)||t.includes(`invalidkmscontext`)}return!1}function m(e){return r(e,p)!==void 0}function h(e){return/handle (0x[0-9a-fA-F]{64})/.exec(e)?.[1]}function g(e){if(e==null)return;let t=e.trim();if(t!==``){if(/^\d+$/.test(t))return Number(t);if(/[a-zA-Z]/.test(t)){let e=Date.parse(t);if(!Number.isNaN(e))return Math.max(0,Math.round((e-Date.now())/1e3))}}}function _(e){if(typeof e!=`object`||!e)return;let t=e.get;if(typeof t==`function`)return g(t.call(e,`Retry-After`))}function v(e){let t=e.response;if(typeof t==`object`&&t)return _(t.headers)}function y(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function b(e){return y(e.retryAfter)?e.retryAfter:v(e)}function x(e){let t=r(e,e=>b(e)!==void 0);return t?b(t):void 0}function S(e){let t=r(e,e=>typeof e.statusCode==`number`||typeof e.status==`number`);if(t)return typeof t.statusCode==`number`?t.statusCode:t.status}function C(e){let t=r(e,e=>typeof e.code==`number`&&e.code!==-1);return t?t.code:void 0}function w(e){return e instanceof Error&&e.name!==`Error`?e.name:void 0}const T={SigningRejected:`SIGNING_REJECTED`,SigningFailed:`SIGNING_FAILED`,EncryptionFailed:`ENCRYPTION_FAILED`,DecryptionFailed:`DECRYPTION_FAILED`,EncryptOffloadUnavailable:`ENCRYPT_OFFLOAD_UNAVAILABLE`,TransactionReverted:`TRANSACTION_REVERTED`,TransportKeyPairExpired:`KEYPAIR_EXPIRED`,InvalidTransportKeyPair:`INVALID_KEYPAIR`,RevokedKmsContext:`REVOKED_KMS_CONTEXT`,NoCiphertext:`NO_CIPHERTEXT`,RelayerRequestFailed:`RELAYER_REQUEST_FAILED`,NotEntitled:`NOT_ENTITLED`,RpcRateLimited:`RPC_RATE_LIMITED`,Configuration:`CONFIGURATION`,DelegationSelfNotAllowed:`DELEGATION_SELF_NOT_ALLOWED`,DelegationCooldown:`DELEGATION_COOLDOWN`,DelegationNotFound:`DELEGATION_NOT_FOUND`,DelegationExpired:`DELEGATION_EXPIRED`,InsufficientConfidentialBalance:`INSUFFICIENT_CONFIDENTIAL_BALANCE`,InsufficientERC20Balance:`INSUFFICIENT_ERC20_BALANCE`,InsufficientAllowance:`INSUFFICIENT_ALLOWANCE`,BalanceCheckUnavailable:`BALANCE_CHECK_UNAVAILABLE`,ERC20ReadFailed:`ERC20_READ_FAILED`,DelegationExpiryUnchanged:`DELEGATION_EXPIRY_UNCHANGED`,DelegationDelegateEqualsContract:`DELEGATION_DELEGATE_EQUALS_CONTRACT`,DelegationContractIsSelf:`DELEGATION_CONTRACT_IS_SELF`,AclPaused:`ACL_PAUSED`,DelegationExpirationTooSoon:`DELEGATION_EXPIRATION_TOO_SOON`,DelegationNotPropagated:`DELEGATION_NOT_PROPAGATED`,ChainMismatch:`CHAIN_MISMATCH`,SignerNotConfigured:`SIGNER_NOT_CONFIGURED`,WalletNotConnected:`WALLET_NOT_CONNECTED`,WalletAccountNotReady:`WALLET_ACCOUNT_NOT_READY`,KeyWrappingFailed:`KEY_WRAPPING_FAILED`,TransportKeyPairChanged:`TRANSPORT_KEY_PAIR_CHANGED`,PreparedPermitChainMismatch:`PREPARED_PERMIT_CHAIN_MISMATCH`,PreparedPermitExpired:`PREPARED_PERMIT_EXPIRED`,UnshieldAlreadyFinalized:`UNSHIELD_ALREADY_FINALIZED`},E={[T.SigningRejected]:!1,[T.SigningFailed]:!1,[T.EncryptionFailed]:!1,[T.DecryptionFailed]:!1,[T.EncryptOffloadUnavailable]:!1,[T.TransactionReverted]:!1,[T.TransportKeyPairExpired]:!1,[T.InvalidTransportKeyPair]:!1,[T.RevokedKmsContext]:!1,[T.NoCiphertext]:!1,[T.RelayerRequestFailed]:!1,[T.NotEntitled]:!1,[T.RpcRateLimited]:!0,[T.Configuration]:!1,[T.DelegationSelfNotAllowed]:!1,[T.DelegationCooldown]:!0,[T.DelegationNotFound]:!1,[T.DelegationExpired]:!1,[T.InsufficientConfidentialBalance]:!1,[T.InsufficientERC20Balance]:!1,[T.InsufficientAllowance]:!1,[T.BalanceCheckUnavailable]:!1,[T.ERC20ReadFailed]:!1,[T.DelegationExpiryUnchanged]:!1,[T.DelegationDelegateEqualsContract]:!1,[T.DelegationContractIsSelf]:!1,[T.AclPaused]:!1,[T.DelegationExpirationTooSoon]:!1,[T.DelegationNotPropagated]:!0,[T.ChainMismatch]:!1,[T.SignerNotConfigured]:!1,[T.WalletNotConnected]:!1,[T.WalletAccountNotReady]:!0,[T.KeyWrappingFailed]:!1,[T.TransportKeyPairChanged]:!1,[T.PreparedPermitChainMismatch]:!1,[T.PreparedPermitExpired]:!1,[T.UnshieldAlreadyFinalized]:!1};var D=class extends Error{code;retryable;constructor(e,t,n){super(t,n),Object.setPrototypeOf(this,new.target.prototype),this.name=`ZamaError`,this.code=e,this.retryable=n?.retryable??E[e]}};function O(e){return e instanceof D&&e.retryable}function k(e){if(!O(e)||!(`retryAfter`in e))return;let t=e.retryAfter;return y(t)?t:void 0}var A=class extends D{statusCode;retryAfter;constructor(e,t,n){let r=n?.retryable??t===429;super(T.RelayerRequestFailed,e,{...n,retryable:r}),this.name=`RelayerRequestFailedError`,this.statusCode=t,this.retryAfter=r?n?.retryAfter:void 0}},j=class extends D{constructor(e,t){super(T.Configuration,e,t),this.name=`ConfigurationError`}};export{e as S,m as _,O as a,h as b,x as c,l as d,t as f,s as g,o as h,T as i,C as l,u as m,A as n,k as o,d as p,D as r,S as s,j as t,w as u,c as v,_ as x,y};
2
+ //# sourceMappingURL=relayer-CVKO9GmQ.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relayer-CVKO9GmQ.js","names":[],"sources":["../../src/utils/error.ts","../../src/errors/base.ts","../../src/errors/relayer.ts"],"sourcesContent":["/** Coerce an unknown caught value to an Error instance. */\nexport function toError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n return new Error(String(error.message));\n }\n return new Error(String(error));\n}\n\n/**\n * Returns true if the error is a contract call revert (as opposed to a network/transport error).\n * Detects viem's ContractFunctionExecutionError / ContractFunctionRevertedError\n * and ethers' CALL_EXCEPTION.\n */\nexport function isContractCallError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n // viem: ContractFunctionExecutionError, ContractFunctionRevertedError\n if (\n error.name === \"ContractFunctionExecutionError\" ||\n error.name === \"ContractFunctionRevertedError\"\n ) {\n return true;\n }\n // ethers: error.code === \"CALL_EXCEPTION\"\n if (\"code\" in error && error.code === \"CALL_EXCEPTION\") {\n return true;\n }\n // Fallback: common revert message patterns from various providers\n const msg = error.message.toLowerCase();\n return msg.includes(\"execution reverted\") || msg.includes(\"call revert exception\");\n}\n\n/** JSON-RPC error code providers use for rate limiting (\"limit exceeded\"). */\nconst JSON_RPC_LIMIT_EXCEEDED = -32005;\n\n/** Properties that may nest a lower-level cause across viem / ethers / fetch. */\nconst NESTED_ERROR_KEYS = [\"cause\", \"error\", \"info\"] as const;\n\n/**\n * Walk an error and its nested causes (`cause` / `error` / `info`, as used by\n * viem, ethers, and fetch wrappers), applying `predicate` to each object node.\n * Returns the first node for which `predicate` returns true, or `undefined`.\n * Depth-bounded to avoid pathological / cyclic structures.\n */\nfunction findInErrorChain(\n error: unknown,\n predicate: (node: Record<string, unknown>) => boolean,\n depth = 6,\n): Record<string, unknown> | undefined {\n if (depth < 0 || error === null || error === undefined || typeof error !== \"object\") {\n return undefined;\n }\n const node = error as Record<string, unknown>;\n if (predicate(node)) {\n return node;\n }\n for (const key of NESTED_ERROR_KEYS) {\n const next = node[key];\n if (next !== undefined && next !== null && typeof next === \"object\") {\n const found = findInErrorChain(next, predicate, depth - 1);\n if (found) {\n return found;\n }\n }\n }\n return undefined;\n}\n\n// ============================================================================\n// Classification detectors\n// ============================================================================\n\n/**\n * Structured (unambiguous) consumer rate-limit signal across the RPC providers\n * the SDK reads through:\n * - JSON-RPC `-32005` (\"limit exceeded\");\n * - viem-style numeric `status: 429`, and viem's own `shouldRetry` shape where\n * the JSON-RPC error `code` is `429`;\n * - ethers' 429, which surfaces as `code: \"SERVER_ERROR\"` with the status only\n * in `info.responseStatus` (a string like `\"429 Too Many Requests\"`) and no\n * numeric top-level status — the leading code is parsed out of it.\n *\n * Deliberately NOT `statusCode: 429` — that is the relayer / node-fetch HTTP\n * shape, which stays {@link RelayerRequestFailedError} (SDK-236), so a relayer\n * 429 is never mistaken for a consumer-RPC throttle.\n */\nfunction nodeHasStructuredRateLimit(node: Record<string, unknown>): boolean {\n if (node.code === JSON_RPC_LIMIT_EXCEEDED || node.status === 429 || node.code === 429) {\n return true;\n }\n // ethers: `code: \"SERVER_ERROR\"`, status lives in `info.responseStatus`.\n if (node.code === \"SERVER_ERROR\" && typeof node.info === \"object\" && node.info !== null) {\n const responseStatus = (node.info as Record<string, unknown>).responseStatus;\n if (typeof responseStatus === \"string\" && /^\\s*429\\b/.test(responseStatus)) {\n return true;\n }\n }\n return false;\n}\n\nfunction nodeIsRpcRateLimit(node: Record<string, unknown>): boolean {\n if (nodeHasStructuredRateLimit(node)) {\n return true;\n }\n // Message fallback for providers without a structured code. Deliberately\n // narrow (specific throttling phrases, no bare \"429\") to avoid false positives\n // that would turn a terminal error into a retryable one.\n if (typeof node.message === \"string\") {\n const msg = node.message.toLowerCase();\n return (\n msg.includes(\"too many requests\") || msg.includes(\"rate limit\") || msg.includes(\"rate-limit\")\n );\n }\n return false;\n}\n\n/**\n * True when a failure originates from `@fhevm/sdk`'s relayer transport. Every\n * relayer error it throws — `RelayerResponseStatusError`, `RelayerResponseApiError`,\n * `RelayerMaxRetryError`, `RelayerTimeoutError`, … — carries the `Relayer` `name`\n * prefix. Such errors stay the relayer's domain ({@link RelayerRequestFailedError}\n * / SDK-236), never {@link RpcRateLimitError}, even on a 429 (which `@fhevm/sdk`\n * retries internally, honoring `Retry-After`, before surfacing).\n */\nexport function isRelayerError(error: unknown): boolean {\n return (\n findInErrorChain(\n error,\n (node) => typeof node.name === \"string\" && node.name.startsWith(\"Relayer\"),\n ) !== undefined\n );\n}\n\n/**\n * True when the failure is an `@fhevm/sdk` relayer *timeout* (`RelayerTimeoutError`,\n * thrown when a request exceeds the relayer's global deadline without a verdict).\n * Unlike a terminal 4xx/5xx, the operation itself is safe to retry, so callers map\n * it to a {@link RelayerRequestFailedError} with `retryable: true` — mirroring the\n * former `WorkerTimeoutError`, which was likewise documented retryable.\n */\nexport function isRelayerTimeoutError(error: unknown): boolean {\n return findInErrorChain(error, (node) => node.name === \"RelayerTimeoutError\") !== undefined;\n}\n\n/**\n * True if the error is the consumer's RPC provider throttling an on-chain read\n * (HTTP 429 / JSON-RPC -32005). Relayer-originated 429s are excluded.\n */\nexport function isRpcRateLimitError(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeIsRpcRateLimit) !== undefined;\n}\n\n/**\n * Like {@link isRpcRateLimitError} but only matches an unambiguous **structured**\n * signal (`-32005` or a viem `status: 429`), ignoring message text. The classifier\n * promotes this ahead of any HTTP status, while a message-only throttle is only\n * trusted when no status is present — so a relayer HTTP error whose body happens\n * to say \"rate limit\" still maps to {@link RelayerRequestFailedError}.\n */\nexport function hasStructuredRpcRateLimitSignal(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeHasStructuredRateLimit) !== undefined;\n}\n\n/**\n * Transport-error signatures of the consumer's own RPC client (viem / ethers).\n * The SDK's on-chain reads (the ACL `persistAllowed` pre-check) go through that\n * client, which already retries transport faults internally — so a failure\n * carrying one of these shapes must NOT be retried again by the SDK on top.\n */\nfunction nodeHasConsumerRpcSignature(node: Record<string, unknown>): boolean {\n // ethers transient transport codes.\n const code = node.code;\n if (code === \"NETWORK_ERROR\" || code === \"SERVER_ERROR\" || code === \"TIMEOUT\") {\n return true;\n }\n // viem transport error classes, matched by `name`.\n const name = node.name;\n return (\n name === \"HttpRequestError\" ||\n name === \"RpcRequestError\" ||\n name === \"TimeoutError\" ||\n name === \"WebSocketRequestError\"\n );\n}\n\n/**\n * True when a failure originates from the **consumer's RPC provider** (viem /\n * ethers) rather than the relayer. Keeps the SDK's relayer retry from\n * double-retrying transport faults the integrator's client already retried.\n * A relayer error (`Relayer*`) is never consumer-RPC.\n */\nexport function isConsumerRpcError(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n if (hasStructuredRpcRateLimitSignal(error)) {\n return true;\n }\n return findInErrorChain(error, nodeHasConsumerRpcSignature) !== undefined;\n}\n\n/**\n * `@fhevm/sdk`'s ACL gate (`checkPersistAllowed`) throws an `AclUserDecryptionError`\n * when the requesting actor isn't allowed: `User <a> is not authorized to decrypt\n * handle <h>!`. Matching that phrase is what lets {@link wrapDecryptError} surface\n * a typed NotEntitledError with the parsed handle.\n *\n * Deliberately excludes the sibling `Dapp contract <a> is not authorized to\n * **user** decrypt handle <h>!` — a dapp ACL misconfig, intentionally left to\n * DecryptionFailedError. The differentiator is the inserted \"user\": the actor\n * message reads \"…to decrypt handle\", the dapp message \"…to user decrypt handle\",\n * so keying on \"is not authorized to decrypt handle\" matches only the former.\n *\n * The `error.test.ts` drift guard reads the installed `@fhevm/sdk` source and\n * fails loudly if the message is reworded.\n */\nexport function isNotEntitledMessage(message: string): boolean {\n return message.toLowerCase().includes(\"is not authorized to decrypt handle\");\n}\n\n/**\n * `@fhevm/sdk`'s `verifyTkmsPublicKey` throws `invalid TransportKeyPairKeyPair`\n * when a stored transport key pair can't be re-derived under the current TKMS\n * version — the signal that the persisted key pair is stale (typically after a\n * KMS/TKMS rotation) and must be evicted and regenerated. Matching it lets the\n * signing and decrypt paths surface a typed {@link InvalidTransportKeyPairError}\n * and self-heal the vault entry.\n */\nexport function isInvalidTransportKeyPairMessage(message: string): boolean {\n return message.toLowerCase().includes(\"invalid transportkeypair\");\n}\n\n/**\n * 4-byte selector of `InvalidKmsContext(uint256)`, the revert ProtocolConfig\n * raises when the KMS signers read resolves an unknown or revoked context.\n * The `error.test.ts` drift guard recomputes it from the Solidity signature.\n */\nexport const INVALID_KMS_CONTEXT_SELECTOR = \"0x77ddbe81\";\n\n/** Revert-data fields across clients: viem's `raw`/`signature`, ethers' `data`. */\nconst REVERT_DATA_KEYS = [\"data\", \"raw\", \"signature\"] as const;\n\nfunction nodeHasInvalidKmsContextRevert(node: Record<string, unknown>): boolean {\n for (const key of REVERT_DATA_KEYS) {\n const value = node[key];\n if (typeof value === \"string\" && value.toLowerCase().startsWith(INVALID_KMS_CONTEXT_SELECTOR)) {\n return true;\n }\n }\n // Text-only fallback for wrappers that stringify the revert instead of\n // carrying the data fields above.\n if (typeof node.message === \"string\") {\n const msg = node.message.toLowerCase();\n return msg.includes(INVALID_KMS_CONTEXT_SELECTOR) || msg.includes(\"invalidkmscontext\");\n }\n return false;\n}\n\n/**\n * True when a failure is the on-chain KMS signers read reverting with\n * `InvalidKmsContext`: the permit's KMS context has been revoked (or never\n * existed), so every permit signed under it is permanently dead. The decrypt\n * path uses this to evict the permit and re-grant under the current context.\n *\n * The installed `@fhevm/sdk` performs that read without the error in its ABI,\n * so the revert arrives as raw data; the selector is matched anywhere in the\n * cause chain, with a message fallback for text-only providers.\n */\nexport function isRevokedKmsContextError(error: unknown): boolean {\n return findInErrorChain(error, nodeHasInvalidKmsContextRevert) !== undefined;\n}\n\n/** Parse the on-chain handle out of the not-entitled message. */\nexport function parseHandleFromMessage(message: string): string | undefined {\n return /handle (0x[0-9a-fA-F]{64})/.exec(message)?.[1];\n}\n\n/**\n * Parse an HTTP `Retry-After` header value into **seconds** (the SDK's duration\n * unit and the header's own unit), or `undefined` when absent/unparseable. Per\n * RFC 9110 the value is either a non-negative number of seconds (`\"120\"`) or an\n * HTTP-date; a past date floors to `0`.\n */\nexport function parseRetryAfterHeader(value: string | null | undefined): number | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n const trimmed = value.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n // delta-seconds: a non-negative integer (already the unit we want).\n if (/^\\d+$/.test(trimmed)) {\n return Number(trimmed);\n }\n // HTTP-date — an IMF-fixdate always carries alphabetic day/month names, so\n // require a letter before deferring to the lenient Date.parse.\n if (/[a-zA-Z]/.test(trimmed)) {\n const dateMs = Date.parse(trimmed);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, Math.round((dateMs - Date.now()) / 1000));\n }\n }\n return undefined;\n}\n\n/** Read a `Retry-After` header (→ seconds) off a `Headers`-like object, if present. */\nexport function readRetryAfterHeader(headers: unknown): number | undefined {\n if (headers === null || typeof headers !== \"object\") {\n return undefined;\n }\n const get = (headers as { get?: unknown }).get;\n if (typeof get !== \"function\") {\n return undefined;\n }\n return parseRetryAfterHeader(\n (get as (name: string) => string | null).call(headers, \"Retry-After\"),\n );\n}\n\n/**\n * A node's **relayer** `Retry-After` header (seconds), read from a wrapped fetch\n * `Response` (the relayer's `cause.response.headers`). The SDK owns the\n * relayer fetch, so parsing the header there is legitimate.\n *\n * The viem/chain side (`HttpRequestError.headers`) is deliberately **not** read:\n * for consumer RPC the integrator's viem/ethers transport already honors\n * `Retry-After` in its own retry loop (and retries) before the error ever\n * surfaces, so re-reading it here would re-implement a transport concern.\n * Chain-RPC backoff is configured on the consumer's transport (`chain.network`).\n */\nfunction retryAfterFromHeader(node: Record<string, unknown>): number | undefined {\n const response = node.response;\n if (response !== null && typeof response === \"object\") {\n return readRetryAfterHeader((response as Record<string, unknown>).headers);\n }\n return undefined;\n}\n\n/**\n * True for a well-formed server-driven retry delay, in seconds: a finite,\n * positive number. Shared by the chain-walking extractor below and the public\n * {@link retryAfterSeconds} accessor (`errors/base.ts`), so a malformed value\n * (`0`, negative, `NaN`) is rejected the same way everywhere instead of being\n * handed unchanged to a `setTimeout` backoff.\n */\nexport function isValidRetryAfterSeconds(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0;\n}\n\n/**\n * A single node's server-driven retry delay (seconds): a numeric `retryAfter`\n * (a non-positive synthetic value is ignored), else a `Retry-After` header.\n */\nfunction retryAfterFromNode(node: Record<string, unknown>): number | undefined {\n if (isValidRetryAfterSeconds(node.retryAfter)) {\n return node.retryAfter;\n }\n return retryAfterFromHeader(node);\n}\n\n/**\n * Best-effort extraction of a server-driven retry delay, in **seconds**, from\n * anywhere in an error's cause chain. Reads a numeric `retryAfter` property and\n * the **relayer's** `Retry-After` header (`cause.response.headers`). The\n * consumer-RPC/chain side is intentionally not read — viem/ethers own that\n * backoff (see {@link retryAfterFromHeader}). `undefined` when absent.\n */\nexport function extractRetryAfter(error: unknown): number | undefined {\n const node = findInErrorChain(error, (n) => retryAfterFromNode(n) !== undefined);\n return node ? retryAfterFromNode(node) : undefined;\n}\n\n/**\n * Extract an HTTP status code from an error or anywhere in its cause chain.\n * Relayer SDK errors may carry a `status` or `statusCode` property; walking the\n * full chain (rather than just depth-1) keeps this in step with the other\n * chain-walking detectors and avoids a depth asymmetry between them.\n */\nexport function extractHttpStatus(error: unknown): number | undefined {\n const node = findInErrorChain(\n error,\n (n) => typeof n.statusCode === \"number\" || typeof n.status === \"number\",\n );\n if (!node) {\n return undefined;\n }\n return (typeof node.statusCode === \"number\" ? node.statusCode : node.status) as number;\n}\n\n/**\n * A JSON-RPC / EIP-1193 numeric error code (e.g. `4001` for user rejection, or a\n * wallet/provider code like `-32603`) found anywhere in a signing failure's cause\n * chain. Gives a signing error a structured, groupable field instead of leaving\n * the code buried in free-text `message` or an opaque nested `cause`.\n *\n * Skips `-1`: viem's own `UnknownRpcError` fallback code for errors it can't\n * classify, not an RPC-provided code. Reporting it as `rpcCode` would read as\n * a real (if odd) wallet error code, so the chain walk continues past it in\n * case a real code is nested deeper (e.g. in `cause`).\n */\nexport function extractRpcErrorCode(error: unknown): number | undefined {\n const node = findInErrorChain(error, (n) => typeof n.code === \"number\" && n.code !== -1);\n return node ? (node.code as number) : undefined;\n}\n\n/**\n * The `name` of the error class a signing failure was thrown as (e.g. viem's\n * `InvalidParamsRpcError`, an EIP-1193 `ProviderRpcError`) — a stable,\n * library-level classification an observability integration can group and alert\n * on. Deliberately reads only the top-level error, not the full cause chain: a\n * wallet's own internal error class name is inconsistent across wallets and\n * buried at an arbitrary depth, so it is not guessed at here — the full chain\n * remains available via the wrapped error's `cause` for manual inspection.\n */\nexport function extractWalletErrorName(error: unknown): string | undefined {\n return error instanceof Error && error.name !== \"Error\" ? error.name : undefined;\n}\n","import { isValidRetryAfterSeconds } from \"../utils/error\";\n\n/**\n * Typed error codes thrown by the SDK.\n * Use `error.code` or `instanceof` to programmatically handle specific failure modes.\n *\n * @example\n * ```ts\n * try {\n * await token.confidentialTransfer(\"0xTo\", 100n);\n * } catch (e) {\n * if (e instanceof SigningRejectedError) {\n * // User rejected the wallet signature\n * }\n * }\n * ```\n */\nexport const ZamaErrorCode = {\n /** User rejected the wallet signature prompt. */\n SigningRejected: \"SIGNING_REJECTED\",\n /** Wallet signature failed for a reason other than rejection. */\n SigningFailed: \"SIGNING_FAILED\",\n /** FHE encryption failed. */\n EncryptionFailed: \"ENCRYPTION_FAILED\",\n /** FHE decryption failed. */\n DecryptionFailed: \"DECRYPTION_FAILED\",\n /** Encryption offload was required (`offloadEncrypt: true`) but the worker is unavailable. */\n EncryptOffloadUnavailable: \"ENCRYPT_OFFLOAD_UNAVAILABLE\",\n /** On-chain transaction reverted. */\n TransactionReverted: \"TRANSACTION_REVERTED\",\n /** Transport key pair has expired and needs regeneration. */\n TransportKeyPairExpired: \"KEYPAIR_EXPIRED\",\n /** Relayer rejected transport key pair (stale, expired, or malformed). */\n InvalidTransportKeyPair: \"INVALID_KEYPAIR\",\n /** The permit's KMS context was revoked on-chain; the SDK's evict-and-regrant retry also failed. */\n RevokedKmsContext: \"REVOKED_KMS_CONTEXT\",\n /** No FHE ciphertext exists for this account (never shielded). */\n NoCiphertext: \"NO_CIPHERTEXT\",\n /** Relayer HTTP request failed. */\n RelayerRequestFailed: \"RELAYER_REQUEST_FAILED\",\n /** The configured signer/account is not entitled (ACL) to decrypt this encrypted value. Don't retry — wait for a grant. */\n NotEntitled: \"NOT_ENTITLED\",\n /** The consumer's RPC provider rate-limited an on-chain read (e.g. HTTP 429 / JSON-RPC -32005). Retryable. */\n RpcRateLimited: \"RPC_RATE_LIMITED\",\n /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\n Configuration: \"CONFIGURATION\",\n /** Delegation cannot target self (delegate === msg.sender). */\n DelegationSelfNotAllowed: \"DELEGATION_SELF_NOT_ALLOWED\",\n /** Only one delegate/revoke per (delegator, delegate, contract) per block. */\n DelegationCooldown: \"DELEGATION_COOLDOWN\",\n /** No active delegation found for this (delegator, delegate, contract) tuple. */\n DelegationNotFound: \"DELEGATION_NOT_FOUND\",\n /** The delegation has expired. */\n DelegationExpired: \"DELEGATION_EXPIRED\",\n /** Confidential (cToken) balance is insufficient for the requested operation. */\n InsufficientConfidentialBalance: \"INSUFFICIENT_CONFIDENTIAL_BALANCE\",\n /** ERC-20 balance is insufficient for the requested shield amount. */\n InsufficientERC20Balance: \"INSUFFICIENT_ERC20_BALANCE\",\n /** ERC-20 allowance granted to the wrapper is insufficient for the requested wrap amount. */\n InsufficientAllowance: \"INSUFFICIENT_ALLOWANCE\",\n /** Balance validation could not be performed (no cached credentials and decryption not possible). */\n BalanceCheckUnavailable: \"BALANCE_CHECK_UNAVAILABLE\",\n /** Public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\n ERC20ReadFailed: \"ERC20_READ_FAILED\",\n /** The new expiration date equals the current one — no on-chain change needed. */\n DelegationExpiryUnchanged: \"DELEGATION_EXPIRY_UNCHANGED\",\n /** Delegate address cannot be the contract address. */\n DelegationDelegateEqualsContract: \"DELEGATION_DELEGATE_EQUALS_CONTRACT\",\n /** Contract address cannot be the sender address. */\n DelegationContractIsSelf: \"DELEGATION_CONTRACT_IS_SELF\",\n /** The ACL contract is paused. */\n AclPaused: \"ACL_PAUSED\",\n /** Expiration date is too soon (must be at least 1 hour in the future). */\n DelegationExpirationTooSoon: \"DELEGATION_EXPIRATION_TOO_SOON\",\n /** Delegation exists on-chain but hasn't propagated to the gateway yet. */\n DelegationNotPropagated: \"DELEGATION_NOT_PROPAGATED\",\n /** Signer and provider are connected to different chains. */\n ChainMismatch: \"CHAIN_MISMATCH\",\n /** Operation requires a signer but none is configured. */\n SignerNotConfigured: \"SIGNER_NOT_CONFIGURED\",\n /** Operation requires a connected wallet account. */\n WalletNotConnected: \"WALLET_NOT_CONNECTED\",\n /** Wallet account discovery is still resolving. */\n WalletAccountNotReady: \"WALLET_ACCOUNT_NOT_READY\",\n /** Wrapping or unwrapping the transport private key with `transportKeyPairDerivationSecret` failed. */\n KeyWrappingFailed: \"KEY_WRAPPING_FAILED\",\n /** The transport key pair changed between `preparePermit` and `registerPermit`. */\n TransportKeyPairChanged: \"TRANSPORT_KEY_PAIR_CHANGED\",\n /** A prepared permit's `chainId` does not match the chain `registerPermit` is running against. */\n PreparedPermitChainMismatch: \"PREPARED_PERMIT_CHAIN_MISMATCH\",\n /** A prepared permit's validity window elapsed before its signature was registered. */\n PreparedPermitExpired: \"PREPARED_PERMIT_EXPIRED\",\n /** The unwrap request was already finalized on-chain; there is nothing left to resume. */\n UnshieldAlreadyFinalized: \"UNSHIELD_ALREADY_FINALIZED\",\n} as const;\n\n/** Union of all {@link ZamaErrorCode} string values. */\nexport type ZamaErrorCode = (typeof ZamaErrorCode)[keyof typeof ZamaErrorCode];\n\n/** Identity type that fails to instantiate unless `T` maps every {@link ZamaErrorCode} to a `boolean`. */\ntype Complete<T extends Record<ZamaErrorCode, boolean>> = T;\n\n/**\n * Default retryability for each {@link ZamaErrorCode}. `Complete` fails the build\n * if a new code is added without an entry here — the same exhaustiveness guard\n * `matchZamaError`'s `ErrorForCode` map uses (see `match.ts`) — so a new\n * transient (or terminal) cause can't silently default to the wrong signal.\n *\n * {@link RelayerRequestFailedError} is the one exception: its retryability\n * depends on the HTTP status (only a 429 is retryable), not just the code, so\n * it overrides this default via the constructor's `retryable` option instead\n * of being read from here.\n */\nconst RETRYABLE_BY_CODE: Complete<Record<ZamaErrorCode, boolean>> = {\n [ZamaErrorCode.SigningRejected]: false,\n [ZamaErrorCode.SigningFailed]: false,\n [ZamaErrorCode.EncryptionFailed]: false,\n [ZamaErrorCode.DecryptionFailed]: false,\n [ZamaErrorCode.EncryptOffloadUnavailable]: false, // the worker realm is unusable for this page; a retry hits the same environment\n [ZamaErrorCode.TransactionReverted]: false,\n [ZamaErrorCode.TransportKeyPairExpired]: false,\n [ZamaErrorCode.InvalidTransportKeyPair]: false,\n [ZamaErrorCode.RevokedKmsContext]: false, // the retry already re-granted; a blind retry re-hits the stale validity cache\n [ZamaErrorCode.NoCiphertext]: false,\n [ZamaErrorCode.RelayerRequestFailed]: false, // conditional — see doc above\n [ZamaErrorCode.NotEntitled]: false,\n [ZamaErrorCode.RpcRateLimited]: true,\n [ZamaErrorCode.Configuration]: false,\n [ZamaErrorCode.DelegationSelfNotAllowed]: false,\n [ZamaErrorCode.DelegationCooldown]: true, // per-block timing gate, resolves on next-block retry\n [ZamaErrorCode.DelegationNotFound]: false,\n [ZamaErrorCode.DelegationExpired]: false,\n [ZamaErrorCode.InsufficientConfidentialBalance]: false,\n [ZamaErrorCode.InsufficientERC20Balance]: false,\n [ZamaErrorCode.InsufficientAllowance]: false, // terminal: caller must approve a larger allowance\n [ZamaErrorCode.BalanceCheckUnavailable]: false,\n [ZamaErrorCode.ERC20ReadFailed]: false, // conservative: conflates network (transient) and contract (terminal) faults, see class doc\n [ZamaErrorCode.DelegationExpiryUnchanged]: false,\n [ZamaErrorCode.DelegationDelegateEqualsContract]: false,\n [ZamaErrorCode.DelegationContractIsSelf]: false,\n [ZamaErrorCode.AclPaused]: false,\n [ZamaErrorCode.DelegationExpirationTooSoon]: false,\n [ZamaErrorCode.DelegationNotPropagated]: true,\n [ZamaErrorCode.ChainMismatch]: false,\n [ZamaErrorCode.SignerNotConfigured]: false,\n [ZamaErrorCode.WalletNotConnected]: false,\n [ZamaErrorCode.WalletAccountNotReady]: true, // async wallet-account discovery still resolving\n [ZamaErrorCode.KeyWrappingFailed]: false, // a transportKeyPairDerivationSecret mismatch or environment capability issue, not transient\n [ZamaErrorCode.TransportKeyPairChanged]: false, // caller must re-run preparePermit against the current key pair\n [ZamaErrorCode.PreparedPermitChainMismatch]: false, // caller must register against the chain the permit was prepared for\n [ZamaErrorCode.PreparedPermitExpired]: false, // caller must re-run preparePermit for a fresh validity window\n [ZamaErrorCode.UnshieldAlreadyFinalized]: false, // the funds already arrived; the stale pointer is cleared\n};\n\n/**\n * Base error thrown by all SDK operations.\n * Carries a {@link ZamaErrorCode} for programmatic error handling.\n * Prefer catching specific subclasses (e.g. {@link EncryptionFailedError}).\n */\nexport class ZamaError extends Error {\n /** Machine-readable error code. */\n readonly code: ZamaErrorCode;\n\n /**\n * Whether the operation that threw this error is safe to retry. Defaults to\n * {@link RETRYABLE_BY_CODE}'s entry for `code`; only {@link RelayerRequestFailedError}\n * overrides it per-instance (its retryability depends on the HTTP status).\n * Prefer {@link isRetryable} over reading this directly, so a new `unknown`\n * caught value doesn't need an `instanceof ZamaError` check first.\n */\n readonly retryable: boolean;\n\n constructor(\n code: ZamaErrorCode,\n message: string,\n options?: ErrorOptions & { retryable?: boolean },\n ) {\n super(message, options);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"ZamaError\";\n this.code = code;\n this.retryable = options?.retryable ?? RETRYABLE_BY_CODE[code];\n }\n}\n\n/**\n * True if `error` is a {@link ZamaError} whose failure is transient and safe to\n * retry (rate-limited, back-pressured, a delegation still propagating or in\n * its per-block cooldown, or a wallet account still resolving).\n * Compiler-guaranteed to stay in sync with the\n * taxonomy: every {@link ZamaError} subclass declares its own retryability via\n * {@link ZamaError.retryable}, so a consumer never has to hardcode a set of\n * retryable codes.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (isRetryable(e)) {\n * // back off and retry (see retryAfterSeconds for a server-suggested delay)\n * } else {\n * throw e; // terminal — surface it\n * }\n * }\n * ```\n */\nexport function isRetryable(error: unknown): error is ZamaError & { retryable: true } {\n return error instanceof ZamaError && error.retryable;\n}\n\n/**\n * The server-suggested retry delay, in **seconds**, for a retryable\n * {@link ZamaError} — unifying the `retryAfter` field that today lives on\n * {@link RelayerRequestFailedError} and {@link RpcRateLimitError} only.\n * `undefined` when the error isn't retryable, or is retryable but carries no\n * server-driven delay (e.g. {@link DelegationNotPropagatedError} — retry that\n * with your own backoff).\n */\nexport function retryAfterSeconds(error: unknown): number | undefined {\n if (!isRetryable(error) || !(\"retryAfter\" in error)) {\n return undefined;\n }\n const retryAfter = (error as ZamaError & { retryAfter?: unknown }).retryAfter;\n return isValidRetryAfterSeconds(retryAfter) ? retryAfter : undefined;\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Relayer HTTP request failed. */\nexport class RelayerRequestFailedError extends ZamaError {\n /** HTTP status code from the relayer, if available. */\n readonly statusCode: number | undefined;\n\n /**\n * Server-driven retry delay in **seconds** (the SDK's duration unit and the\n * header's own unit), from the relayer's `Retry-After` header. Set only on\n * back-pressure (HTTP 429) responses that carry the header; `undefined`\n * otherwise. Implies {@link ZamaError.retryable}.\n */\n readonly retryAfter: number | undefined;\n\n constructor(\n message: string,\n statusCode?: number,\n options?: ErrorOptions & { retryAfter?: number; retryable?: boolean },\n ) {\n // Retryable on relayer back-pressure (HTTP 429) by default, or when the\n // caller forces it (a relayer timeout has no status but is safe to retry).\n const retryable = options?.retryable ?? statusCode === 429;\n super(ZamaErrorCode.RelayerRequestFailed, message, { ...options, retryable });\n this.name = \"RelayerRequestFailedError\";\n this.statusCode = statusCode;\n // Keep the two fields consistent: a delay only makes sense when retryable,\n // and only a 429 actually carries a server-supplied `Retry-After`.\n this.retryAfter = retryable ? options?.retryAfter : undefined;\n }\n}\n\n/** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\nexport class ConfigurationError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.Configuration, message, options);\n this.name = \"ConfigurationError\";\n }\n}\n"],"mappings":"AACA,SAAgB,EAAQ,EAAuB,CAO7C,OANI,aAAiB,MACZ,EAEL,OAAO,GAAU,UAAY,GAAkB,YAAa,EACnD,MAAM,OAAO,EAAM,OAAO,CAAC,EAE7B,MAAM,OAAO,CAAK,CAAC,CAChC,CAOA,SAAgB,EAAoB,EAAyB,CAC3D,GAAI,EAAE,aAAiB,OACrB,MAAO,GAUT,GANE,EAAM,OAAS,kCACf,EAAM,OAAS,iCAKb,SAAU,GAAS,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IAClC,EAAc,yBAA0B,IACxC,EAAc,6BAA8B,IAC5C,EAAc,uBAAwB,IACtC,EAAc,0BAA2B,EAC5C,EAOA,IAAa,EAAb,cAA+B,KAAM,CAEnC,KASA,UAEA,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,CAAO,EACtB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,EAChD,KAAK,KAAO,YACZ,KAAK,KAAO,EACZ,KAAK,UAAY,GAAS,WAAa,EAAkB,EAC3D,CACF,EAwBA,SAAgB,EAAY,EAA0D,CACpF,OAAO,aAAiB,GAAa,EAAM,SAC7C,CAUA,SAAgB,EAAkB,EAAoC,CACpE,GAAI,CAAC,EAAY,CAAK,GAAK,EAAE,eAAgB,GAC3C,OAEF,IAAM,EAAc,EAA+C,WACnE,OAAO,EAAyB,CAAU,EAAI,EAAa,IAAA,EAC7D,CC9NA,IAAa,EAAb,cAA+C,CAAU,CAEvD,WAQA,WAEA,YACE,EACA,EACA,EACA,CAGA,IAAM,EAAY,GAAS,WAAa,IAAe,IACvD,MAAM,EAAc,qBAAsB,EAAS,CAAE,GAAG,EAAS,WAAU,CAAC,EAC5E,KAAK,KAAO,4BACZ,KAAK,WAAa,EAGlB,KAAK,WAAa,EAAY,GAAS,WAAa,IAAA,EACtD,CACF,EAGa,EAAb,cAAwC,CAAU,CAChD,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAc,cAAe,EAAS,CAAO,EACnD,KAAK,KAAO,oBACd,CACF"}
@@ -0,0 +1,2 @@
1
+ import{S as e,i as t,r as n,t as r}from"./relayer-CVKO9GmQ.js";import{B as i,C as a,I as o,J as s,M as c,N as l,P as u,R as d,T as f,V as p,W as m,_ as h,b as g,d as _,h as v,j as y,m as b,n as x,p as S,r as C,s as w,v as T,y as E,z as D}from"./erc165-DbMOt-s6.js";import{r as O,t as k}from"./encryption-BKoalB4o.js";import{t as A}from"./assertions-Ca1ePdRJ.js";import{getAddress as j}from"viem";var M=class extends n{retryAfter;constructor(e,n){let{retryAfter:r,...i}=n??{};super(t.RpcRateLimited,e,i),this.name=`RpcRateLimitError`,this.retryAfter=r}},N=class extends n{operation;signerChainId;providerChainId;constructor({operation:e,signerChainId:n,providerChainId:r},i){super(t.ChainMismatch,`Operation "${e}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=e,this.signerChainId=n,this.providerChainId=r}},P=class extends n{requested;available;token;constructor(e,n,r){super(t.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},F=class extends n{requested;available;token;constructor(e,n,r){super(t.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},I=class extends n{requested;available;token;constructor(e,n,r){super(t.InsufficientAllowance,e,r),this.name=`InsufficientAllowanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},L=class extends n{constructor(e,n){super(t.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},R=class extends n{constructor(e,n){super(t.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function z(e){return e instanceof p||e instanceof i||e instanceof r||e instanceof M||e instanceof m||e instanceof s}const B={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},V={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},H={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(B),Object.freeze(V),Object.freeze(H),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function U(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function W(e){if(!U(e))throw Error(`Invalid FheType id '${e}'`);let t=H[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const G=`0x0000000000000000000000000000000000000000000000000000000000000000`;function K(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}function q(e){let t;try{t=BigInt(e)}catch{return 256}let n=Number(t>>8n&255n);return U(n)?W(n):256}function J(e,t=2048){let n=[],r=[],i=0;for(let a of e){let e=q(a);r.length>0&&i+e>t&&(n.push(r),r=[],i=0),r.push(a),i+=e}return r.length>0&&n.push(r),n}async function Y(e,t,n){if(!t)throw new u(e);let r;try{r=t.requireWalletAccount(e)}catch(n){if(!(n instanceof o)||!t.refreshWalletAccount)throw n;await t.refreshWalletAccount(),r=t.requireWalletAccount(e)}let i=await n.getChainId();if(r.chainId!==i)throw new N({operation:e,signerChainId:r.chainId,providerChainId:i});return r}async function X(e,t,n){return(await Y(e,t,n)).chainId}async function Z(e){let{operation:t,tokenAddress:r,amount:i,signer:a,provider:o,readBalance:s}=e;if(i===0n)return;let c;try{c=await s(j((await Y(t,a,o)).address))}catch(e){throw e instanceof n?e:new L(`Balance validation failed (token: ${r})`,{cause:e})}if(c<i)throw new P(`Insufficient confidential balance: requested ${i}, available ${c} (token: ${r})`,{requested:i,available:c,token:r})}async function Q(e,t=1/0){if(Number.isFinite(t)&&t<=0)throw Error(`maxConcurrency must be a positive number`);if(!Number.isFinite(t)||t>=e.length)return Promise.all(e.map(e=>e()));let n=Array.from({length:e.length}),r=0;async function i(){for(;r<e.length;){let t=r++;e[t]&&(n[t]=await e[t]())}}return await Promise.all(Array.from({length:t},i)),n}async function $(e){let{operation:t,signer:r,provider:i,config:a,emit:o,onSubmitted:s,logger:u}=e,d=l[t];try{let e=await r.writeContract(a);return o(d.submittedEvent(e)),y(`${t}: onSubmitted`,()=>s?.(e),u),{txHash:e,receipt:await i.waitForTransactionReceipt(e)}}catch(e){let r=e instanceof n?e:new D(`Transaction failed during ${t}`,{cause:e});throw o({type:c.TransactionError,operation:t,error:r}),r}}var ee=class t{sdk;address;constructor(e,t){this.sdk=e,this.address=j(t)}#e(e){return d(this.sdk.signer,e)}async name(){return this.sdk.provider.readContract(S(this.address))}async symbol(){return this.sdk.provider.readContract(b(this.address))}async decimals(){return this.sdk.provider.readContract(_(this.address))}async isConfidential(){return this.sdk.provider.readContract(w(this.address,x))}async isWrapper(){return this.sdk.provider.readContract(w(this.address,C))}async balanceOf(e){let t=j(e),n=await this.readConfidentialBalanceOf(t),r=(await this.sdk.decryption.decryptValues([{encryptedValue:n,contractAddress:this.address}]))[n];if(r===void 0)throw new k(`Decryption returned no value for ${n}`);return A(r,`balanceOf: result[encryptedValue]`),r}async confidentialBalanceOf(e){return this.readConfidentialBalanceOf(j(e))}async decryptBalanceAs({delegatorAddress:e,accountAddress:t}){await X(`decryptBalanceAs`,this.sdk.signer,this.sdk.provider);let n=j(e),r=t?j(t):n,i=await this.readConfidentialBalanceOf(r);if(K(i))return 0n;let a=(await this.sdk.decryption.delegatedDecryptValues([{encryptedValue:i,contractAddress:this.address}],n,r))[i];if(a===void 0)throw new k(`Delegated decryption returned no value for ${i}`);return A(a,`decryptBalanceAs: result[encryptedValue]`),a}static async batchBalancesOf(r,i){let a=new Map,o=new Map;if(r.length===0)return{results:a,errors:o};let s=t.assertSameSdk(r);await X(`batchBalancesOf`,s.signer,s.provider),await s.permits.grantPermit(r.map(e=>e.address));let c=!1,l,u=await Q(r.map(e=>async()=>{if(c)return{status:`aborted`};try{return{status:`fulfilled`,value:await e.balanceOf(i)}}catch(e){return z(e)?(c=!0,l??=e,{status:`aborted`}):{status:`rejected`,reason:e}}}),5);if(l!==void 0)throw l;for(let t=0;t<r.length;t++){let i=r[t].address,s=u[t];if(s.status!==`aborted`)if(s.status===`fulfilled`)a.set(i,s.value);else{let t=s.reason,r=t instanceof n?t:new k(e(t).message,{cause:t});o.set(i,r)}}if(o.size===r.length)throw o.values().next().value??new k(`All token balance decryptions failed`);return{results:a,errors:o}}static async batchDecryptBalancesAs(n,r){if(n.length===0)return new Map;let i=t.assertSameSdk(n),a=new Map,o=new Map,s=r.accountAddress?j(r.accountAddress):j(r.delegatorAddress),c=r.maxConcurrency??10;if(r.encryptedValues&&n.length!==r.encryptedValues.length)throw new k(`tokens.length (${n.length}) must equal encryptedValues.length (${r.encryptedValues.length})`);let l=r.encryptedValues??await t.readBalanceHandlesBatch(n,s,o,c),u=[];for(let[e,t]of n.entries()){let n=l[e];!n||o.has(t.address)||(K(n)?a.set(t.address,0n):u.push({token:t,encryptedValue:n}))}if(u.length>0){let e=await i.decryption.delegatedBatchDecryptValues({encryptedInputs:u.map(({token:e,encryptedValue:t})=>({encryptedValue:t,contractAddress:e.address})),delegatorAddress:r.delegatorAddress,accountAddress:r.accountAddress,maxConcurrency:c});for(let[t,n]of e.items.entries()){let e=u[t];if(!e)continue;if(n.error){o.set(e.token.address,n.error);continue}let r=n.value;if(r===void 0){o.set(e.token.address,new k(`Batch delegated decryption returned no value for ${n.encryptedValue} on token ${e.token.address}`));continue}A(r,`batchDecryptBalancesAs: result[encryptedValue]`),a.set(e.token.address,r)}}if(o.size===0)return a;if(r.onError){let t=[];for(let[n,i]of o)try{a.set(n,r.onError(i,n))}catch(r){t.push({address:n,error:e(r)})}if(t.length>0){let e=t.map(({address:e,error:t})=>`${e}: ${t.message}`).join(`; `);throw new k(`Batch delegated decryption onError callback failed for ${t.length} token(s): ${e}`,{cause:t[0]?.error})}return a}let d=Array.from(o.entries()),f=d.map(([e,t])=>`${e}: ${t.message}`).join(`; `);throw new k(`Batch delegated decryption failed for ${o.size} token(s): ${f}`,{cause:d[0]?.[1]})}static async readBalanceHandlesBatch(t,r,i,a){let o=!1,s,c=await Q(t.map(e=>async()=>{if(o)return{status:`aborted`};try{return{status:`fulfilled`,value:await e.readConfidentialBalanceOf(r)}}catch(e){return z(e)?(o=!0,s??=e,{status:`aborted`}):{status:`rejected`,reason:e}}}),a);if(s!==void 0)throw s;let l=[];for(let[r,a]of t.entries()){let t=c[r];if(!(!t||t.status===`aborted`)){if(t.status===`fulfilled`){l[r]=t.value;continue}i.set(a.address,t.reason instanceof n?t.reason:new k(e(t.reason).message,{cause:t.reason}))}}return l}async confidentialTransfer(e,t,n){this.#e(`confidentialTransfer`);let r=await Y(`confidentialTransfer`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=j(e);i||await this.assertConfidentialBalance(t);let{encryptedValues:c,inputProof:l}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:j(r.address)});if(y(`transfer: onEncryptComplete`,()=>a?.(),this.sdk.logger),c.length===0)throw new O(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transfer`,config:T(this.address,s,c[0],l),onSubmitted:o})}async confidentialTransferFrom(e,t,n,r){this.#e(`confidentialTransferFrom`);let i=await Y(`confidentialTransferFrom`,this.sdk.signer,this.sdk.provider),a=j(e),o=j(t),{encryptedValues:s,inputProof:c}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:j(i.address)});if(y(`transferFrom: onEncryptComplete`,()=>r?.onEncryptComplete?.(),this.sdk.logger),s.length===0)throw new O(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFrom`,config:g(this.address,a,o,s[0],c),onSubmitted:r?.onTransferSubmitted})}async confidentialTransferAndCall(e,t,n,r){this.#e(`confidentialTransferAndCall`);let i=await Y(`confidentialTransferAndCall`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:a=!1,onEncryptComplete:o,onTransferSubmitted:s}=r??{},c=j(e);a||await this.assertConfidentialBalance(t);let{encryptedValues:l,inputProof:u}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:j(i.address)});if(y(`transferAndCall: onEncryptComplete`,()=>o?.(),this.sdk.logger),l.length===0)throw new O(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferAndCall`,config:h(this.address,c,l[0],u,n),onSubmitted:s})}async confidentialTransferFromAndCall(e,t,n,r,i){this.#e(`confidentialTransferFromAndCall`);let a=await Y(`confidentialTransferFromAndCall`,this.sdk.signer,this.sdk.provider),o=j(e),s=j(t),{encryptedValues:c,inputProof:l}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:j(a.address)});if(y(`transferFromAndCall: onEncryptComplete`,()=>i?.onEncryptComplete?.(),this.sdk.logger),c.length===0)throw new O(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFromAndCall`,config:E(this.address,o,s,c[0],l,r),onSubmitted:i?.onTransferSubmitted})}async setOperator(e,t){this.#e(`setOperator`),await X(`setOperator`,this.sdk.signer,this.sdk.provider);let n=j(e);return this.submitTransaction({operation:`setOperator`,config:f(this.address,n,t)})}async isOperator(e,t){return this.sdk.provider.readContract(a(this.address,j(e),j(t)))}async readConfidentialBalanceOf(e){return await this.sdk.provider.readContract(v(this.address,e))}async assertConfidentialBalance(e){return Z({operation:`assertConfidentialBalance`,tokenAddress:this.address,amount:e,signer:this.sdk.signer,provider:this.sdk.provider,readBalance:e=>this.balanceOf(e)})}emit(e){this.sdk.emitEvent(e,this.address)}async submitTransaction(e){let{operation:t,config:n,onSubmitted:r}=e;return $({operation:t,signer:this.#e(t),provider:this.sdk.provider,config:n,emit:e=>this.emit(e),onSubmitted:r,logger:this.sdk.logger})}static assertSameSdk(e){let t=e[0].sdk;for(let n=1;n<e.length;n++)if(e[n].sdk!==t)throw new r(`All tokens in a batch operation must share the same ZamaSDK instance`);return t}};export{M as _,Y as a,J as c,L as d,R as f,N as g,F as h,Z as i,K as l,P as m,$ as n,X as o,I as p,Q as r,G as s,ee as t,z as u};
2
+ //# sourceMappingURL=token-CRJ8eCr7.js.map