@zama-fhe/sdk 3.2.0 → 3.3.0-alpha.10

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 (94) hide show
  1. package/dist/cjs/assertions.cjs +1 -1
  2. package/dist/cjs/assertions.cjs.map +1 -1
  3. package/dist/cjs/base-signer.cjs +1 -1
  4. package/dist/cjs/base-signer.cjs.map +1 -1
  5. package/dist/cjs/ethers/index.cjs +1 -1
  6. package/dist/cjs/index.cjs +1 -1
  7. package/dist/cjs/index.cjs.map +1 -1
  8. package/dist/cjs/query/index.cjs +1 -1
  9. package/dist/cjs/query/index.cjs.map +1 -1
  10. package/dist/cjs/relayer-cleartext.cjs +1 -1
  11. package/dist/cjs/relayer-cleartext.cjs.map +1 -1
  12. package/dist/cjs/relayer-sdk.worker.js +134 -34
  13. package/dist/cjs/relayer.cjs +1 -1
  14. package/dist/cjs/relayer.cjs.map +1 -1
  15. package/dist/cjs/timeout.cjs +2 -0
  16. package/dist/cjs/timeout.cjs.map +1 -0
  17. package/dist/cjs/token.cjs +1 -1
  18. package/dist/cjs/token.cjs.map +1 -1
  19. package/dist/cjs/viem/index.cjs +1 -1
  20. package/dist/cjs/viem/index.cjs.map +1 -1
  21. package/dist/cjs/web/index.cjs +136 -36
  22. package/dist/cjs/web/index.cjs.map +1 -1
  23. package/dist/cjs/wrappers-registry.cjs +1 -1
  24. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  25. package/dist/esm/assertions-zYseN5Xz.js +2 -0
  26. package/dist/esm/assertions-zYseN5Xz.js.map +1 -0
  27. package/dist/esm/{base-signer-ByGw5ReU.d.ts → base-signer-C3Wc5oi9.d.ts} +2 -2
  28. package/dist/esm/base-signer-DjytqPkd.js +2 -0
  29. package/dist/esm/base-signer-DjytqPkd.js.map +1 -0
  30. package/dist/esm/cleartext/index.d.ts +1 -1
  31. package/dist/esm/cleartext/index.js +1 -1
  32. package/dist/esm/{cleartext-DMW5nK1M.d.ts → cleartext-DAkOTlrE.d.ts} +2 -2
  33. package/dist/esm/{cleartext-CTla3A3O.js → cleartext-rTWFctyd.js} +2 -2
  34. package/dist/esm/{cleartext-CTla3A3O.js.map → cleartext-rTWFctyd.js.map} +1 -1
  35. package/dist/esm/{encryption-BGmINekJ.js → encryption-x4Z_Icqk.js} +2 -2
  36. package/dist/esm/{encryption-BGmINekJ.js.map → encryption-x4Z_Icqk.js.map} +1 -1
  37. package/dist/esm/ethers/index.d.ts +4 -4
  38. package/dist/esm/ethers/index.js +1 -1
  39. package/dist/esm/ethers/index.js.map +1 -1
  40. package/dist/esm/{hex-CxtyupeQ.js → hex-A72GrTf9.js} +2 -2
  41. package/dist/esm/{hex-CxtyupeQ.js.map → hex-A72GrTf9.js.map} +1 -1
  42. package/dist/esm/{index-DoVo9J1n.d.ts → index-C1Mtc8Rw.d.ts} +450 -163
  43. package/dist/esm/index.d.ts +17 -13
  44. package/dist/esm/index.js +1 -1
  45. package/dist/esm/index.js.map +1 -1
  46. package/dist/esm/node/index.d.ts +25 -7
  47. package/dist/esm/node/index.js +1 -1
  48. package/dist/esm/node/index.js.map +1 -1
  49. package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
  50. package/dist/esm/node/relayer-sdk.node-worker.js.map +1 -1
  51. package/dist/esm/query/index.d.ts +42 -4
  52. package/dist/esm/query/index.js +1 -1
  53. package/dist/esm/query/index.js.map +1 -1
  54. package/dist/esm/relayer-cleartext-Bp6jtxDd.js +2 -0
  55. package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +1 -0
  56. package/dist/esm/{relayer-cleartext-DkKKjfI6.d.ts → relayer-cleartext-CSeMlmGO.d.ts} +102 -13
  57. package/dist/esm/relayer-eavK5bfZ.js +2 -0
  58. package/dist/esm/relayer-eavK5bfZ.js.map +1 -0
  59. package/dist/esm/relayer-sdk.worker.js +134 -34
  60. package/dist/esm/timeout-CNVfiaJD.js +2 -0
  61. package/dist/esm/timeout-CNVfiaJD.js.map +1 -0
  62. package/dist/esm/token-Bt33g0zQ.js +2 -0
  63. package/dist/esm/token-Bt33g0zQ.js.map +1 -0
  64. package/dist/esm/{types-BjDu-RZg.d.ts → types-Gn5MeDsr.d.ts} +14 -2
  65. package/dist/esm/{types-Xg_On_yY.d.ts → types-OHIaPwCy.d.ts} +2 -2
  66. package/dist/esm/{types-DiZhtG8i.d.ts → types-piBsdTIP.d.ts} +2 -2
  67. package/dist/esm/{validation-DHZ3JPOn.js → validation-DLszOweh.js} +2 -2
  68. package/dist/esm/{validation-DHZ3JPOn.js.map → validation-DLszOweh.js.map} +1 -1
  69. package/dist/esm/viem/index.d.ts +4 -4
  70. package/dist/esm/viem/index.js +1 -1
  71. package/dist/esm/viem/index.js.map +1 -1
  72. package/dist/esm/web/index.d.ts +2 -2
  73. package/dist/esm/web/index.js +135 -35
  74. package/dist/esm/web/index.js.map +1 -1
  75. package/dist/esm/worker.base-client-BVnT4yJa.js +2 -0
  76. package/dist/esm/worker.base-client-BVnT4yJa.js.map +1 -0
  77. package/dist/esm/{wrappers-registry-BWWG0aze.js → wrappers-registry-C1oK8Bi6.js} +2 -2
  78. package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +1 -0
  79. package/package.json +51 -51
  80. package/dist/esm/assertions-CnPIS0VN.js +0 -2
  81. package/dist/esm/assertions-CnPIS0VN.js.map +0 -1
  82. package/dist/esm/base-signer-BVqcM5jt.js +0 -2
  83. package/dist/esm/base-signer-BVqcM5jt.js.map +0 -1
  84. package/dist/esm/error-W1N-FGwV.js +0 -2
  85. package/dist/esm/error-W1N-FGwV.js.map +0 -1
  86. package/dist/esm/relayer-D-nicEYJ.js +0 -2
  87. package/dist/esm/relayer-D-nicEYJ.js.map +0 -1
  88. package/dist/esm/relayer-cleartext-DGcb5qtE.js +0 -2
  89. package/dist/esm/relayer-cleartext-DGcb5qtE.js.map +0 -1
  90. package/dist/esm/token-TQ-VFHS4.js +0 -2
  91. package/dist/esm/token-TQ-VFHS4.js.map +0 -1
  92. package/dist/esm/worker.base-client-x522sMBy.js +0 -2
  93. package/dist/esm/worker.base-client-x522sMBy.js.map +0 -1
  94. package/dist/esm/wrappers-registry-BWWG0aze.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/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-from.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/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/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":["// 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\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 .toSorted()\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 ? {\n walletAddress: getAddress(walletAccount.address),\n walletChainId: walletAccount.chainId,\n }\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 {\n tokenAddress: getAddress(tokenAddress),\n ...(owner ? { owner: getAddress(owner) } : {}),\n },\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 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).toSorted(),\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 {\n encryptedValue: string;\n contractAddress: Address;\n }[],\n walletAccount?: WalletAccount,\n ) =>\n [\n \"zama.decryption\",\n {\n ...walletAccountKey(walletAccount),\n encryptedInputs: [...encryptedInputs]\n .toSorted((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 {\n type: \"tokenPairs\",\n registryAddress: getAddress(registryAddress),\n },\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 {\n type: \"tokenPairsLength\",\n registryAddress: getAddress(registryAddress),\n },\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 {\n type: \"tokenPair\",\n registryAddress: getAddress(registryAddress),\n index,\n },\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\nexport interface QueryLike {\n queryKey: readonly unknown[];\n}\n\nexport interface QueryFilterLike {\n queryKey?: readonly unknown[];\n predicate?: (query: QueryLike) => boolean;\n}\n\nexport interface QueryClientLike {\n invalidateQueries(filters: QueryFilterLike): void | Promise<void>;\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\nexport function invalidateAfterUnwrap(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\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\nexport function invalidateAfterShield(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\nexport function invalidateAfterUnshield(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\nexport function invalidateAfterTransfer(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n}\n\nexport function invalidateAfterApproveUnderlying(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n}\n\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\nexport function invalidateWagmiBalanceQueries(queryClient: QueryClientLike): void {\n void queryClient.invalidateQueries({ predicate: isWagmiBalanceQuery });\n}\n\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 name: string;\n symbol: string;\n decimals: number;\n}\n\nexport interface TokenMetadataQueryConfig {\n query?: Record<string, unknown>;\n}\n\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\nexport interface IsConfidentialQueryConfig {\n query?: Record<string, unknown>;\n}\n\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\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\nexport interface TotalSupplyQueryConfig {\n query?: Record<string, unknown>;\n}\n\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\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 query?: Record<string, unknown>;\n}\n\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\nexport interface UnderlyingAllowanceQueryConfig {\n owner?: Address;\n query?: Record<string, unknown>;\n}\n\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 { 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\nexport interface ConfidentialIsOperatorQueryConfig {\n holder?: Address;\n spender?: Address;\n query?: Record<string, unknown>;\n}\n\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\nexport interface ConfidentialBalanceQueryConfig {\n tokenAddress: Address;\n account?: Address;\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\nexport interface ConfidentialBalancesQueryConfig {\n account?: Address;\n query?: Record<string, unknown>;\n}\n\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/** Default registry TTL in milliseconds — matches {@link WrappersRegistry} default of 86400 s. */\nconst DEFAULT_STALE_TIME_MS = 86400 * 1000;\n\nexport interface WrappersRegistryQueryConfig {\n registryAddress: Address | undefined;\n query?: Record<string, unknown>;\n}\n\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: DEFAULT_STALE_TIME_MS,\n enabled,\n };\n}\n\nexport interface ConfidentialTokenAddressQueryConfig extends WrappersRegistryQueryConfig {\n tokenAddress?: Address;\n}\n\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: DEFAULT_STALE_TIME_MS,\n enabled,\n };\n}\n\nexport interface TokenAddressQueryConfig extends WrappersRegistryQueryConfig {\n confidentialTokenAddress?: Address;\n}\n\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: DEFAULT_STALE_TIME_MS,\n enabled,\n };\n}\n\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: DEFAULT_STALE_TIME_MS,\n enabled,\n };\n}\n\nexport interface TokenPairsSliceQueryConfig extends WrappersRegistryQueryConfig {\n fromIndex?: bigint;\n toIndex?: bigint;\n}\n\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: DEFAULT_STALE_TIME_MS,\n enabled,\n };\n}\n\nexport interface TokenPairQueryConfig extends WrappersRegistryQueryConfig {\n index?: bigint;\n}\n\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: DEFAULT_STALE_TIME_MS,\n enabled,\n };\n}\n\nexport interface IsConfidentialTokenValidQueryConfig extends WrappersRegistryQueryConfig {\n confidentialTokenAddress?: Address;\n}\n\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: DEFAULT_STALE_TIME_MS,\n enabled,\n };\n}\n\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 page?: number;\n pageSize?: number;\n metadata?: boolean;\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: bigint;\n}\n\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 to: Address;\n amount: bigint;\n}\n\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 { 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 from: Address;\n to: Address;\n amount: bigint;\n /** Optional progress callbacks for the multi-step transfer flow. */\n callbacks?: TransferCallbacks;\n}\n\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 { 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;\n until?: number;\n}\n\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?: bigint;\n}\n\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: bigint;\n}\n\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\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 unwrapTxHash: Hex;\n}\n\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 { TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link unwrapMutationOptions}. */\nexport interface UnwrapParams {\n amount: bigint;\n}\n\nexport function unwrapMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unwrap\", Address], UnwrapParams, TransactionResult> {\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 } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\nexport function unwrapAllMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unwrapAll\", Address], void, TransactionResult> {\n return {\n mutationKey: [\"zama.unwrapAll\", token.address] as const,\n mutationFn: async () => token.unwrapAll(),\n };\n}\n","import type { EncryptedValue } from \"../relayer/relayer-sdk.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\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, EncryptResult } from \"../relayer/relayer-sdk.types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\nexport function encryptMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<readonly [\"zama.encrypt\"], EncryptParams, EncryptResult> {\n return {\n mutationKey: [\"zama.encrypt\"],\n mutationFn: async (params) => sdk.encrypt(params),\n };\n}\n","import type { Address } from \"viem\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/relayer-sdk.types\";\nimport type { EncryptedInput } from \"./user-decrypt\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\nexport interface DelegatedDecryptValuesMutationParams {\n encryptedInputs: EncryptedInput[];\n delegatorAddress: Address;\n}\n\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, PublicDecryptResult } from \"../relayer/relayer-sdk.types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\n\nexport function decryptPublicValuesMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<\n readonly [\"zama.decryptPublicValues\"],\n EncryptedValue[],\n PublicDecryptResult\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\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 { 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\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\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 {\n mutationKey: [\"zama.clearCredentials\"],\n mutationFn: () => sdk.permits.clear(),\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 delegateDecryptionMutationOptions}. */\nexport interface DelegateDecryptionParams {\n delegateAddress: Address;\n expirationDate?: Date;\n}\n\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 { UserDecryptResults } from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/relayer-sdk.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\nexport interface EncryptedInput {\n encryptedValue: EncryptedValue;\n contractAddress: Address;\n}\n\n/** Alias for {@link UserDecryptResults}. */\nexport type DecryptResult = UserDecryptResults;\n\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 delegatorAddress: Address;\n accountAddress?: Address;\n}\n\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\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 delegateAddress: Address;\n}\n\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 { MAX_UINT64 } from \"../contracts\";\nimport { getDelegationExpiryContract } from \"../contracts/acl\";\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 interface DelegationStatusData {\n isActive: boolean;\n expiryTimestamp: bigint;\n}\n\nexport interface DelegationStatusQueryConfig {\n contractAddress: Address | undefined;\n delegatorAddress?: Address;\n delegateAddress?: Address;\n query?: Record<string, unknown>;\n}\n\nexport function delegationStatusQueryOptions(\n sdk: ZamaSDK,\n config: DelegationStatusQueryConfig,\n): QueryFactoryOptions<\n DelegationStatusData,\n Error,\n DelegationStatusData,\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 const acl = await sdk.relayer.getAclAddress();\n const expiryTimestamp = await sdk.provider.readContract(\n getDelegationExpiryContract(acl, delegatorAddress, delegateAddress, contractAddress),\n );\n // Derive isActive from expiry + chain time to stay consistent\n // with sdk.delegations.isActive() (avoids client-clock skew).\n let isActive: boolean;\n if (expiryTimestamp === 0n) {\n isActive = false;\n } else if (expiryTimestamp === MAX_UINT64) {\n isActive = true;\n } else {\n const now = await sdk.provider.getBlockTimestamp();\n isActive = expiryTimestamp > now;\n }\n return { isActive, expiryTimestamp };\n },\n enabled:\n Boolean(config.contractAddress && config.delegatorAddress && config.delegateAddress) &&\n config.query?.enabled !== false,\n } as const;\n}\n"],"mappings":"qYAEA,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,CAG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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/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/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":["// 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\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 .toSorted()\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).toSorted(),\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 .toSorted((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\nexport interface QueryLike {\n queryKey: readonly unknown[];\n}\n\nexport interface QueryFilterLike {\n queryKey?: readonly unknown[];\n predicate?: (query: QueryLike) => boolean;\n}\n\nexport interface QueryClientLike {\n invalidateQueries(filters: QueryFilterLike): void | Promise<void>;\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\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\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\nexport function invalidateAfterShield(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\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\nexport function invalidateAfterUnshieldSettled(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n invalidatePendingUnshieldQueries(queryClient, tokenAddress);\n}\n\nexport function invalidateAfterTransfer(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n}\n\nexport function invalidateAfterApproveUnderlying(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n}\n\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\nexport function invalidateWagmiBalanceQueries(queryClient: QueryClientLike): void {\n void queryClient.invalidateQueries({ predicate: isWagmiBalanceQuery });\n}\n\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 name: string;\n symbol: string;\n decimals: number;\n}\n\nexport interface TokenMetadataQueryConfig {\n query?: Record<string, unknown>;\n}\n\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\nexport interface IsConfidentialQueryConfig {\n query?: Record<string, unknown>;\n}\n\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\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\nexport interface TotalSupplyQueryConfig {\n query?: Record<string, unknown>;\n}\n\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\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 query?: Record<string, unknown>;\n}\n\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\nexport interface UnderlyingAllowanceQueryConfig {\n owner?: Address;\n query?: Record<string, unknown>;\n}\n\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\nexport interface PendingUnshieldQueryConfig {\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\nexport interface ConfidentialIsOperatorQueryConfig {\n holder?: Address;\n spender?: Address;\n query?: Record<string, unknown>;\n}\n\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\nexport interface ConfidentialBalanceQueryConfig {\n tokenAddress: Address;\n account?: Address;\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\nexport interface ConfidentialBalancesQueryConfig {\n account?: Address;\n query?: Record<string, unknown>;\n}\n\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\nexport interface WrappersRegistryQueryConfig {\n registryAddress: Address | undefined;\n query?: Record<string, unknown>;\n}\n\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\nexport interface ConfidentialTokenAddressQueryConfig extends WrappersRegistryQueryConfig {\n tokenAddress?: Address;\n}\n\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\nexport interface TokenAddressQueryConfig extends WrappersRegistryQueryConfig {\n confidentialTokenAddress?: Address;\n}\n\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\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\nexport interface TokenPairsSliceQueryConfig extends WrappersRegistryQueryConfig {\n fromIndex?: bigint;\n toIndex?: bigint;\n}\n\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\nexport interface TokenPairQueryConfig extends WrappersRegistryQueryConfig {\n index?: bigint;\n}\n\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\nexport interface IsConfidentialTokenValidQueryConfig extends WrappersRegistryQueryConfig {\n confidentialTokenAddress?: Address;\n}\n\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\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 page?: number;\n pageSize?: number;\n metadata?: boolean;\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: bigint;\n}\n\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 to: Address;\n amount: bigint;\n}\n\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 to: Address;\n amount: bigint;\n /** Opaque bytes forwarded to the recipient's ERC-7984 receiver hook. */\n data: Hex;\n}\n\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 from: Address;\n to: Address;\n amount: bigint;\n /** Optional progress callbacks for the multi-step transfer flow. */\n callbacks?: TransferCallbacks;\n}\n\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 from: Address;\n to: Address;\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\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;\n until?: number;\n}\n\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?: bigint;\n}\n\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: bigint;\n}\n\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\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 unwrapTxHash: Hex;\n}\n\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 { TransactionResult } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\n/** Variables for {@link unwrapMutationOptions}. */\nexport interface UnwrapParams {\n amount: bigint;\n}\n\nexport function unwrapMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unwrap\", Address], UnwrapParams, TransactionResult> {\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 } from \"../types\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport type { Address } from \"viem\";\n\nexport function unwrapAllMutationOptions(\n token: WrappedToken,\n): MutationFactoryOptions<readonly [\"zama.unwrapAll\", Address], void, TransactionResult> {\n return {\n mutationKey: [\"zama.unwrapAll\", token.address] as const,\n mutationFn: async () => token.unwrapAll(),\n };\n}\n","import type { EncryptedValue } from \"../relayer/relayer-sdk.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\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, EncryptResult } from \"../relayer/relayer-sdk.types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\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/relayer-sdk.types\";\nimport type { EncryptedInput } from \"./user-decrypt\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\n\nexport interface DelegatedDecryptValuesMutationParams {\n encryptedInputs: EncryptedInput[];\n delegatorAddress: Address;\n}\n\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, PublicDecryptResult } from \"../relayer/relayer-sdk.types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\nimport type { MutationFactoryOptions } from \"./factory-types\";\nimport { zamaQueryKeys } from \"./query-keys\";\n\nexport function decryptPublicValuesMutationOptions(\n sdk: ZamaSDK,\n): MutationFactoryOptions<\n readonly [\"zama.decryptPublicValues\"],\n EncryptedValue[],\n PublicDecryptResult\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\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 { 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\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\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 delegateAddress: Address;\n expirationDate?: Date;\n}\n\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 { UserDecryptResults } from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/relayer-sdk.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\nexport interface EncryptedInput {\n encryptedValue: EncryptedValue;\n contractAddress: Address;\n}\n\n/** Alias for {@link UserDecryptResults}. */\nexport type DecryptResult = UserDecryptResults;\n\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 delegatorAddress: Address;\n accountAddress?: Address;\n}\n\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\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 delegateAddress: Address;\n}\n\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 { MAX_UINT64 } from \"../contracts\";\nimport { getDelegationExpiryContract } from \"../contracts/acl\";\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 interface DelegationStatusData {\n isActive: boolean;\n expiryTimestamp: bigint;\n}\n\nexport interface DelegationStatusQueryConfig {\n contractAddress: Address | undefined;\n delegatorAddress?: Address;\n delegateAddress?: Address;\n query?: Record<string, unknown>;\n}\n\nexport function delegationStatusQueryOptions(\n sdk: ZamaSDK,\n config: DelegationStatusQueryConfig,\n): QueryFactoryOptions<\n DelegationStatusData,\n Error,\n DelegationStatusData,\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 const acl = await sdk.relayer.getAclAddress();\n const expiryTimestamp = await sdk.provider.readContract(\n getDelegationExpiryContract(acl, delegatorAddress, delegateAddress, contractAddress),\n );\n // Derive isActive from expiry + chain time to stay consistent\n // with sdk.delegations.isActive() (avoids client-clock skew).\n let isActive: boolean;\n if (expiryTimestamp === 0n) {\n isActive = false;\n } else if (expiryTimestamp === MAX_UINT64) {\n isActive = true;\n } else {\n const now = await sdk.provider.getBlockTimestamp();\n isActive = expiryTimestamp > now;\n }\n return { isActive, expiryTimestamp };\n },\n enabled:\n Boolean(config.contractAddress && config.delegatorAddress && config.delegateAddress) &&\n config.query?.enabled !== false,\n } as const;\n}\n"],"mappings":"kWAEA,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,CA2CA,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,EACV,eAAgB,GAChB,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,KA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,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,SAC3E,EAAkB,EAAiB,+CAA+C,EAClF,EAAkB,EAAkB,gDAAgD,EACpF,EAAkB,EAAiB,+CAA+C,EAClF,IAAM,EAAM,MAAM,EAAI,QAAQ,cAAc,EACtC,EAAkB,MAAM,EAAI,SAAS,aACzC,EAA4B,EAAK,EAAkB,EAAiB,CAAe,CACrF,EAGI,EASJ,MARA,CAME,EANE,IAAoB,GACX,GACF,IAAoB,EAClB,GAGA,EAAkB,MADX,EAAI,SAAS,kBAAkB,EAG5C,CAAE,WAAU,iBAAgB,CACrC,EACA,QACE,GAAQ,EAAO,iBAAmB,EAAO,kBAAoB,EAAO,kBACpE,EAAO,OAAO,UAAY,EAC9B,CACF"}
@@ -0,0 +1,2 @@
1
+ import{i as e,r as t,t as n}from"./relayer-eavK5bfZ.js";import{n as r,t as i}from"./encryption-x4Z_Icqk.js";import{privateKeyToAccount as a}from"viem/accounts";import{concat as o,createPublicClient as s,custom as c,encodePacked as l,getAddress as u,http as d,keccak256 as f,pad as p,parseAbi as m,toBytes as h,toHex as g}from"viem";import{mainnet as _,sepolia as v}from"viem/chains";var y=class extends t{encryptedValue;contractAddress;account;constructor(t,n){super(e.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}};const b=(e,t)=>({name:`InputVerification`,version:`1`,chainId:BigInt(e),verifyingContract:t}),x=(e,t)=>({name:`Decryption`,version:`1`,chainId:BigInt(e),verifyingContract:t}),S={domain:b,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},C={domain:x,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},w={domain:x,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},T={domain:x,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},E={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},D={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},O={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(E),Object.freeze(D),Object.freeze(O),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function k(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 A(e){return typeof e==`string`?e in E:!1}function j(e){if(!A(e))throw Error(`Invalid FheType name '${e}'`);return E[e]}function M(e){if(!k(e))throw Error(`Invalid FheType id '${e}'`);let t=O[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const N=h(`ZK-w_rct`),P=h(`ZK-w_hdl`);function F(e,t){let n=Math.ceil(M(t)/8);return h(p(g(e),{size:n}))}function I(e,t,n){if(n.length!==32)throw new r(`random32 must be exactly 32 bytes`);let i=F(t,e),a=f(o([g(new Uint8Array([e])),g(i),g(n)]));return f(o([g(N),a]))}function L(e,t,n,i,a){if(!Number.isInteger(t)||t<0||t>255)throw new r(`index must be an integer between 0 and 255`);let s=f(o([g(N),e])),c=f(l([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[g(P),s,t,i,a])),u=a&18446744073709551615n;return g(BigInt(c)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(t)<<80n|u<<16n|BigInt(n)<<8n|BigInt(0),{size:32})}const R=m([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),z=m([`function plaintexts(bytes32 handle) view returns (uint256)`]),B=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],V={EIP712Domain:B,UserDecryptRequestVerification:w.types.UserDecryptRequestVerification},H={EIP712Domain:B,DelegatedUserDecryptRequestVerification:T.types.DelegatedUserDecryptRequestVerification},U={EIP712Domain:B,PublicDecryptVerification:C.types.PublicDecryptVerification},W=new Set([_.id,v.id]);function G(e,t){let n=Number(BigInt(e)>>8n&255n);return n===0?t!==0n:n===7?g(t,{size:20}):t}function K(e){if(!A(e.type))throw new r(`Unsupported FHE type`);let t=j(e.type),n;if(e.type===`ebool`){if(typeof e.value==`boolean`)n=e.value?1n:0n;else if(n=e.value,n!==0n&&n!==1n)throw new r(`Bool value must be 0, 1, true, or false`)}else n=e.type===`eaddress`?BigInt(u(e.value)):e.value;if(n<0n)throw new r(`Only non-negative cleartext values are supported`);let i=M(t),a=(1n<<BigInt(i))-1n;if(n>a)throw new r(`Value ${n} exceeds max ${a} for FheType ${t}`);return{fheType:t,value:n}}var q=class{#e;#t;kmsSigner;inputSigner;constructor(e){if(W.has(e.id))throw new n(`Cleartext mode is not allowed on chain ${e.id}. It is intended for local development and testing only.`);if(!e.executorAddress)throw new n(`Cleartext transport requires an executorAddress for chain ${e.id}.`);this.#e=s({transport:typeof e.network==`string`?d(e.network):c(e.network)}),this.#t=e,this.kmsSigner=a(e.kmsSignerPrivateKey??`0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91`),this.inputSigner=a(e.inputSignerPrivateKey??`0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901`)}async generateTransportKeyPair(){let e=g(crypto.getRandomValues(new Uint8Array(32))),t=g(crypto.getRandomValues(new Uint8Array(32)));for(;t===e;)t=g(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:e,privateKey:t}}async createEIP712(e,t,n,r=7){return{domain:w.domain(this.#t.id,this.#t.verifyingContractAddressDecryption),types:V,primaryType:`UserDecryptRequestVerification`,message:{publicKey:e,contractAddresses:t,startTimestamp:String(n),durationDays:String(r),extraData:`0x00`}}}async encrypt(e){let t=e.values.map(K),n=u(e.contractAddress),r=u(e.userAddress),i=t.map(({fheType:e,value:t})=>I(e,t,crypto.getRandomValues(new Uint8Array(32)))),a=f(i.length>0?o(i):`0x`),s=t.map(({fheType:e},t)=>L(a,t,e,this.#t.aclContractAddress,BigInt(this.#t.id))),c=t.map(({value:e})=>p(g(e),{size:32})),l=c.length>0?o(c):`0x`,d=await this.inputSigner.signTypedData({domain:S.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressInputVerification),types:{CiphertextVerification:S.types.CiphertextVerification},primaryType:`CiphertextVerification`,message:{ctHandles:s,userAddress:r,contractAddress:n,contractChainId:BigInt(this.#t.id),extraData:l}});return{encryptedValues:s,inputProof:o([g(new Uint8Array([s.length])),g(new Uint8Array([1])),...s,d,l])}}async userDecrypt(e){return await this.#r(e.encryptedValues,u(e.signerAddress),u(e.contractAddress),`User`,`user decrypt`),this.#n(e.encryptedValues)}async publicDecrypt(e){let t=e,n=(await Promise.all(t.map(e=>this.#o(e)))).findIndex(e=>!e);if(n!==-1)throw new i(`Encrypted value ${t[n]} is not allowed for public decryption`);let r=await Promise.all(t.map(e=>this.#s(e))),a=Object.fromEntries(t.map((e,t)=>[e,G(e,r[t])])),s=o(r.map(e=>p(g(e),{size:32}))),c=await this.kmsSigner.signTypedData({domain:C.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressDecryption),types:U,primaryType:`PublicDecryptVerification`,message:{ctHandles:t,decryptedResult:s,extraData:`0x`}});return{clearValues:a,abiEncodedClearValues:s,decryptionProof:o([g(new Uint8Array([1])),c])}}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){let a={publicKey:e,contractAddresses:t,delegatorAddress:u(n),startTimestamp:String(r),durationDays:String(i),extraData:`0x00`};return{domain:T.domain(this.#t.id,this.#t.verifyingContractAddressDecryption),types:H,primaryType:`DelegatedUserDecryptRequestVerification`,message:a}}async delegatedUserDecrypt(e){return await this.#i(e.encryptedValues,u(e.delegatorAddress),u(e.delegateAddress),u(e.contractAddress)),this.#n(e.encryptedValues)}async requestZKProofVerification(e){throw new n(`Not implemented in cleartext mode`)}async fetchFheEncryptionKeyBytes(){return{publicKeyId:`mock-public-key-id`,publicKey:new Uint8Array([32])}}async getPublicParams(e){return{publicParams:new Uint8Array([32]),publicParamsId:`mock-public-params-id`}}async getAclAddress(){return this.#t.aclContractAddress}terminate(){}[Symbol.dispose](){this.terminate()}async#n(e){let t=await Promise.all(e.map(e=>this.#s(e)));return Object.fromEntries(e.map((e,n)=>[e,G(e,t[n])]))}async#r(e,t,n,r,a){if(t===n)throw new i(`${r} address ${t} must not equal contract address for ${a}`);let o=await Promise.all(e.flatMap(e=>[this.#a(e,t),this.#a(e,n)]));for(let r=0;r<e.length;r++){let s=o[r*2],c=o[r*2+1];if(!s)throw new y({encryptedValue:e[r],contractAddress:n,account:t});if(!c)throw new i(`Contract ${n} is not authorized for ${a} of encrypted value ${e[r]}`)}}async#i(e,t,n,r){let a=await Promise.all(e.map(e=>this.#e.readContract({address:this.#t.aclContractAddress,abi:R,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,e]})));for(let t=0;t<e.length;t++)if(!a[t])throw new i(`Encrypted value ${e[t]} is not delegated for user decryption`);let o=await Promise.all(e.map(e=>this.#a(e,t)));for(let n=0;n<e.length;n++)if(!o[n])throw new y({encryptedValue:e[n],contractAddress:r,account:t})}async#a(e,t){return this.#e.readContract({address:this.#t.aclContractAddress,abi:R,functionName:`persistAllowed`,args:[e,t]})}async#o(e){return this.#e.readContract({address:this.#t.aclContractAddress,abi:R,functionName:`isAllowedForDecryption`,args:[e]})}async#s(e){return this.#e.readContract({address:this.#t.executorAddress,abi:z,functionName:`plaintexts`,args:[e]})}};export{y as n,q as t};
2
+ //# sourceMappingURL=relayer-cleartext-Bp6jtxDd.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"relayer-cleartext-Bp6jtxDd.js","names":["#client","#config","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/errors/entitlement.ts","../../src/relayer/cleartext/eip712.ts","../../src/relayer/cleartext/constants.ts","../../src/relayer/cleartext/fhe-type.ts","../../src/relayer/cleartext/handle.ts","../../src/relayer/cleartext/relayer-cleartext.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * The signer (or delegator) lacks ACL permission to decrypt the encrypted value —\n * `persistAllowed` returned `false`. Terminal and **non-retryable**: the fix is\n * an on-chain grant (`FHE.allow`), or for indexers, to wait for a backfill once\n * the grant lands. Distinct from transient failures like {@link RpcRateLimitError}.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (e instanceof NotEntitledError) {\n * // don't retry — wait for an ACL grant / backfill\n * }\n * }\n * ```\n */\nexport class NotEntitledError extends ZamaError {\n /** The encrypted value the actor is not entitled to decrypt. */\n readonly encryptedValue: string;\n /** The contract the encrypted value belongs to. */\n readonly contractAddress: string;\n /** The actor (signer or delegator) that lacks ACL permission. */\n readonly account: string;\n\n constructor(\n args: { encryptedValue: string; contractAddress: string; account: string },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.NotEntitled,\n `Account ${args.account} is not entitled to decrypt encrypted value ${args.encryptedValue} ` +\n `on contract ${args.contractAddress}. This is not a transient failure — ` +\n `the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,\n options,\n );\n this.name = \"NotEntitledError\";\n this.encryptedValue = args.encryptedValue;\n this.contractAddress = args.contractAddress;\n this.account = args.account;\n }\n}\n","import type { Address } from \"viem\";\nimport type {\n CoprocessorEIP712DomainType,\n CoprocessorEIP712TypesType,\n KmsDelegatedUserDecryptEIP712TypesType,\n KmsEIP712DomainType,\n KmsPublicDecryptEIP712TypesType,\n KmsUserDecryptEIP712TypesType,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nconst inputDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): CoprocessorEIP712DomainType => ({\n name: \"InputVerification\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nconst decryptionDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): KmsEIP712DomainType => ({\n name: \"Decryption\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nexport const INPUT_VERIFICATION_EIP712 = {\n domain: inputDomain,\n types: {\n CiphertextVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"userAddress\", type: \"address\" },\n { name: \"contractAddress\", type: \"address\" },\n { name: \"contractChainId\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const KMS_DECRYPTION_EIP712 = {\n domain: decryptionDomain,\n types: {\n PublicDecryptVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"decryptedResult\", type: \"bytes\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n UserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const DELEGATED_USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n DelegatedUserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"delegatorAddress\", type: \"address\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\n// ── Compile-time structural checks against relayer-sdk types ──────────\n// These assertions ensure our local EIP-712 type arrays stay in sync with\n// the relayer-sdk's canonical definitions. A mismatch will cause a build error.\ntype AssertFieldsMatch<\n Local extends readonly { readonly name: string; readonly type: string }[],\n Canonical extends readonly { readonly name: string; readonly type: string }[],\n> = [Local[\"length\"]] extends [Canonical[\"length\"]]\n ? {\n [K in keyof Local]: Local[K] extends { readonly name: infer N; readonly type: infer T }\n ? Canonical[K & keyof Canonical] extends { readonly name: N; readonly type: T }\n ? true\n : { error: `Field mismatch at index ${K & string}` }\n : never;\n }\n : { error: \"Field count mismatch\" };\n\n// Wrapping in readonly true[] ensures a mismatch produces a compile error\n// (not just an inert type alias that TypeScript silently accepts).\ntype AssertAllTrue<T extends readonly true[]> = T;\n\ntype _CheckInput = AssertAllTrue<\n AssertFieldsMatch<\n typeof INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n CoprocessorEIP712TypesType[\"CiphertextVerification\"]\n >\n>;\ntype _CheckPublicDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n KmsPublicDecryptEIP712TypesType[\"PublicDecryptVerification\"]\n >\n>;\ntype _CheckUserDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n KmsUserDecryptEIP712TypesType[\"UserDecryptRequestVerification\"]\n >\n>;\ntype _CheckDelegatedDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n KmsDelegatedUserDecryptEIP712TypesType[\"DelegatedUserDecryptRequestVerification\"]\n >\n>;\n","export const HANDLE_VERSION = 0;\n\nexport const PREHANDLE_MASK = 0xffffffffffffffffffffffffffffffffffffffffff0000000000000000000000n;\n\n// Constants used for instanciation of the cleartext FHEVM instance.\nexport const MOCK_INPUT_SIGNER_PK =\n \"0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901\";\nexport const MOCK_KMS_SIGNER_PK =\n \"0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91\";\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import { concat, encodePacked, keccak256, pad, toBytes, toHex, type Address, type Hex } from \"viem\";\nimport { HANDLE_VERSION, PREHANDLE_MASK } from \"./constants\";\nimport { encryptionBitsFromFheTypeId, type FheTypeId } from \"./fhe-type\";\nimport { EncryptionFailedError } from \"../../errors\";\n\nconst RAW_CT_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_rct\");\nconst HANDLE_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_hdl\");\n\nfunction cleartextToBytes(cleartext: bigint, fheType: FheTypeId): Uint8Array {\n const byteLength = Math.ceil(encryptionBitsFromFheTypeId(fheType) / 8);\n return toBytes(pad(toHex(cleartext), { size: byteLength }));\n}\n\nexport function computeMockCiphertext(\n fheType: FheTypeId,\n cleartext: bigint,\n random32: Uint8Array,\n): Hex {\n if (random32.length !== 32) {\n throw new EncryptionFailedError(\"random32 must be exactly 32 bytes\");\n }\n\n const clearBytes = cleartextToBytes(cleartext, fheType);\n const inner = keccak256(\n concat([toHex(new Uint8Array([fheType])), toHex(clearBytes), toHex(random32)]),\n );\n\n return keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), inner]));\n}\n\nexport function computeInputHandle(\n mockCiphertext: Hex,\n index: number,\n fheType: FheTypeId,\n aclAddress: Address,\n chainId: bigint,\n): Hex {\n if (!Number.isInteger(index) || index < 0 || index > 255) {\n throw new EncryptionFailedError(\"index must be an integer between 0 and 255\");\n }\n\n const blobHash = keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), mockCiphertext]));\n const handleHash = keccak256(\n encodePacked(\n [\"bytes\", \"bytes32\", \"uint8\", \"address\", \"uint256\"],\n [toHex(HANDLE_HASH_DOMAIN_SEPARATOR), blobHash, index, aclAddress, chainId],\n ),\n );\n\n const chainId64 = chainId & 0xffff_ffff_ffff_ffffn;\n const handle =\n (BigInt(handleHash) & PREHANDLE_MASK) |\n (BigInt(index) << 80n) |\n (chainId64 << 16n) |\n (BigInt(fheType) << 8n) |\n BigInt(HANDLE_VERSION);\n\n return toHex(handle, { size: 32 });\n}\n","import type { PrivateKeyAccount } from \"viem/accounts\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n concat,\n createPublicClient,\n custom,\n getAddress,\n http,\n keccak256,\n pad,\n parseAbi,\n toHex,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { mainnet, sepolia } from \"viem/chains\";\nimport type {\n InputProofBytesType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nimport type { TransportKeyPair } from \"../../credentials/types\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValue,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n EncryptedValue,\n FheEncryptionKey,\n PublicDecryptResult,\n PublicParamsData,\n UserDecryptParams,\n} from \"../relayer-sdk.types\";\nimport {\n DELEGATED_USER_DECRYPT_EIP712,\n INPUT_VERIFICATION_EIP712,\n KMS_DECRYPTION_EIP712,\n USER_DECRYPT_EIP712,\n} from \"./eip712\";\nimport { MOCK_INPUT_SIGNER_PK, MOCK_KMS_SIGNER_PK } from \"./constants\";\nimport {\n encryptionBitsFromFheTypeId,\n fheTypeIdFromName,\n isFheTypeName,\n type FheTypeId,\n} from \"./fhe-type\";\nimport { computeInputHandle, computeMockCiphertext } from \"./handle\";\nimport type { FheChain } from \"../../chains/types\";\nimport {\n ConfigurationError,\n DecryptionFailedError,\n EncryptionFailedError,\n NotEntitledError,\n} from \"../../errors\";\n\nconst ACL_ABI = parseAbi([\n \"function persistAllowed(bytes32 handle, address account) view returns (bool)\",\n \"function isAllowedForDecryption(bytes32 handle) view returns (bool)\",\n \"function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)\",\n]);\n\nconst EXECUTOR_ABI = parseAbi([\"function plaintexts(bytes32 handle) view returns (uint256)\"]);\n\nconst STANDARD_EIP712_DOMAIN = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nconst USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n UserDecryptRequestVerification: USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n} satisfies KmsUserDecryptEIP712Type[\"types\"];\nconst DELEGATED_USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n DelegatedUserDecryptRequestVerification:\n DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n} satisfies KmsDelegatedUserDecryptEIP712Type[\"types\"];\nconst KMS_DECRYPTION_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n PublicDecryptVerification: KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n} satisfies KmsPublicDecryptEIP712Type[\"types\"];\n\nconst FORBIDDEN_CHAIN_IDS = new Set<number>([mainnet.id, sepolia.id]);\n\n// FheTypeId constants for hot-path comparisons\nconst EBOOL_ID: FheTypeId = 0;\nconst EADDRESS_ID: FheTypeId = 7;\n\nfunction decodeClearValue(encryptedValue: EncryptedValue, rawValue: bigint): ClearValue {\n const typeByte = Number((BigInt(encryptedValue) >> 8n) & 0xffn);\n if (typeByte === EBOOL_ID) {\n return rawValue !== 0n;\n }\n if (typeByte === EADDRESS_ID) {\n return toHex(rawValue, { size: 20 });\n }\n return rawValue;\n}\n\nfunction normalizeEncryptValue(entry: EncryptParams[\"values\"][number]): {\n fheType: FheTypeId;\n value: bigint;\n} {\n if (!isFheTypeName(entry.type)) {\n throw new EncryptionFailedError(\"Unsupported FHE type\");\n }\n\n const fheType = fheTypeIdFromName(entry.type);\n\n let value: bigint;\n if (entry.type === \"ebool\") {\n if (typeof entry.value === \"boolean\") {\n value = entry.value ? 1n : 0n;\n } else {\n value = entry.value;\n if (value !== 0n && value !== 1n) {\n throw new EncryptionFailedError(\"Bool value must be 0, 1, true, or false\");\n }\n }\n } else if (entry.type === \"eaddress\") {\n value = BigInt(getAddress(entry.value));\n } else {\n value = entry.value;\n }\n\n if (value < 0n) {\n throw new EncryptionFailedError(\"Only non-negative cleartext values are supported\");\n }\n\n const bits = encryptionBitsFromFheTypeId(fheType);\n const maxValue = (1n << BigInt(bits)) - 1n;\n if (value > maxValue) {\n throw new EncryptionFailedError(\n `Value ${value} exceeds max ${maxValue} for FheType ${fheType}`,\n );\n }\n\n return { fheType, value };\n}\n\nexport class RelayerCleartext implements RelayerSDK, Disposable {\n readonly #client: PublicClient;\n readonly #config: FheChain;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: FheChain) {\n if (FORBIDDEN_CHAIN_IDS.has(config.id)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.id}. ` +\n `It is intended for local development and testing only.`,\n );\n }\n if (!config.executorAddress) {\n throw new ConfigurationError(\n `Cleartext transport requires an executorAddress for chain ${config.id}.`,\n );\n }\n this.#client = createPublicClient({\n transport: typeof config.network === \"string\" ? http(config.network) : custom(config.network),\n });\n this.#config = config;\n this.kmsSigner = privateKeyToAccount(config.kmsSignerPrivateKey ?? MOCK_KMS_SIGNER_PK);\n this.inputSigner = privateKeyToAccount(config.inputSignerPrivateKey ?? MOCK_INPUT_SIGNER_PK);\n }\n\n async generateTransportKeyPair(): Promise<TransportKeyPair> {\n const publicKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n let privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n\n while (privateKey === publicKey) {\n privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n }\n\n return { publicKey, privateKey };\n }\n\n async createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays = 7,\n ): Promise<EIP712TypedData> {\n return {\n domain: USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: USER_DECRYPT_TYPES,\n primaryType: \"UserDecryptRequestVerification\",\n message: {\n publicKey,\n contractAddresses,\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n },\n };\n }\n\n async encrypt(params: EncryptParams): Promise<EncryptResult> {\n const entries = params.values.map(normalizeEncryptValue);\n const contractAddress = getAddress(params.contractAddress);\n const userAddress = getAddress(params.userAddress);\n\n const mockCiphertexts = entries.map(({ fheType, value }) =>\n computeMockCiphertext(fheType, value, crypto.getRandomValues(new Uint8Array(32))),\n );\n\n const ciphertextBlob = keccak256(mockCiphertexts.length > 0 ? concat(mockCiphertexts) : \"0x\");\n\n const handles = entries.map(({ fheType }, index) =>\n computeInputHandle(\n ciphertextBlob,\n index,\n fheType,\n this.#config.aclContractAddress as Address,\n BigInt(this.#config.id),\n ),\n );\n\n const cleartextParts = entries.map(({ value }) => pad(toHex(value), { size: 32 }));\n const cleartextBytes: Hex = cleartextParts.length > 0 ? concat(cleartextParts) : \"0x\";\n\n const signature = await this.inputSigner.signTypedData({\n domain: INPUT_VERIFICATION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressInputVerification as Address,\n ),\n types: { CiphertextVerification: INPUT_VERIFICATION_EIP712.types.CiphertextVerification },\n primaryType: \"CiphertextVerification\",\n message: {\n ctHandles: handles,\n userAddress,\n contractAddress,\n contractChainId: BigInt(this.#config.id),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]);\n\n return { encryptedValues: handles, inputProof };\n }\n\n async userDecrypt(\n params: UserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDecryptAuthorization(\n params.encryptedValues,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async publicDecrypt(encryptedValues: EncryptedValue[]): Promise<PublicDecryptResult> {\n const normalizedHandles = encryptedValues;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#isAllowedForDecryption(encryptedValue)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Encrypted value ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, orderedValues[index]!),\n ]),\n );\n\n const abiEncodedClearValues = concat(orderedValues.map((v) => pad(toHex(v), { size: 32 })));\n\n const signature = await this.kmsSigner.signTypedData({\n domain: KMS_DECRYPTION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: KMS_DECRYPTION_TYPES,\n primaryType: \"PublicDecryptVerification\",\n message: {\n ctHandles: normalizedHandles,\n decryptedResult: abiEncodedClearValues,\n extraData: \"0x\",\n },\n });\n\n const decryptionProof = concat([toHex(new Uint8Array([1])), signature]);\n\n return { clearValues, abiEncodedClearValues, decryptionProof };\n }\n\n async createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays = 7,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n const message: KmsDelegatedUserDecryptEIP712Type[\"message\"] = {\n publicKey,\n contractAddresses,\n delegatorAddress: getAddress(delegatorAddress),\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n };\n\n return {\n domain: DELEGATED_USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: DELEGATED_USER_DECRYPT_TYPES,\n primaryType: \"DelegatedUserDecryptRequestVerification\",\n message,\n };\n }\n\n async delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDelegation(\n params.encryptedValues,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async fetchFheEncryptionKeyBytes(): Promise<FheEncryptionKey | null> {\n return { publicKeyId: \"mock-public-key-id\", publicKey: new Uint8Array([32]) };\n }\n\n async getPublicParams(_bits: number): Promise<PublicParamsData | null> {\n return { publicParams: new Uint8Array([32]), publicParamsId: \"mock-public-params-id\" };\n }\n\n async getAclAddress(): Promise<Address> {\n return this.#config.aclContractAddress as Address;\n }\n\n terminate(): void {\n // No resources to release in cleartext mode.\n }\n\n /** Calls {@link terminate} (no-op in cleartext mode). */\n [Symbol.dispose](): void {\n this.terminate();\n }\n\n async #decryptHandles(\n normalizedEncryptedValues: EncryptedValue[],\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n const values = await Promise.all(\n normalizedEncryptedValues.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n\n return Object.fromEntries(\n normalizedEncryptedValues.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedEncryptedValues: EncryptedValue[],\n actorAddress: Address,\n contractAddress: Address,\n actorLabel: \"User\" | \"Delegator\",\n operationLabel: \"user decrypt\" | \"delegated decrypt\",\n ): Promise<void> {\n if (actorAddress === contractAddress) {\n throw new DecryptionFailedError(\n `${actorLabel} address ${actorAddress} must not equal contract address for ${operationLabel}`,\n );\n }\n\n const results = await Promise.all(\n normalizedEncryptedValues.flatMap((encryptedValue) => [\n this.#persistAllowed(encryptedValue, actorAddress),\n this.#persistAllowed(encryptedValue, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedEncryptedValues.length; i++) {\n const actorAllowed = results[i * 2];\n const contractAllowed = results[i * 2 + 1];\n if (!actorAllowed) {\n throw new NotEntitledError({\n encryptedValue: normalizedEncryptedValues[i]!,\n contractAddress,\n account: actorAddress,\n });\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of encrypted value ${normalizedEncryptedValues[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n encryptedValues: EncryptedValue[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n encryptedValues.map((encryptedValue) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, encryptedValue],\n }),\n ),\n );\n\n for (let i = 0; i < encryptedValues.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Encrypted value ${encryptedValues[i]!} is not delegated for user decryption`,\n );\n }\n }\n\n // Parity with the relayer/worker path: a delegated handle still requires the\n // *delegator* to hold the ACL grant (`persistAllowed`). Without this check,\n // the same condition surfaces differently in local cleartext dev than in\n // production — exactly where integrators wire up their error handling.\n // Cleartext is host-chain-only: `#persistAllowed` reads the ACL directly on\n // the local chain, with no gateway and no cross-chain sync. A failed check\n // here can never be a propagation lag — it is authoritative and permanent —\n // so it maps to the terminal NotEntitledError, not the retryable\n // DelegationNotPropagatedError (which would make the delegated-decrypt retry\n // loop spin its full budget on a local misconfig before failing).\n const delegatorAllowed = await Promise.all(\n encryptedValues.map((encryptedValue) =>\n this.#persistAllowed(encryptedValue, delegatorAddress),\n ),\n );\n\n for (let i = 0; i < encryptedValues.length; i++) {\n if (!delegatorAllowed[i]) {\n throw new NotEntitledError({\n encryptedValue: encryptedValues[i]!,\n contractAddress,\n account: delegatorAddress,\n });\n }\n }\n }\n\n async #persistAllowed(encryptedValue: EncryptedValue, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [encryptedValue, account],\n });\n }\n\n async #isAllowedForDecryption(encryptedValue: EncryptedValue): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [encryptedValue],\n });\n }\n\n async #readPlaintext(encryptedValue: EncryptedValue): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [encryptedValue],\n });\n }\n}\n"],"mappings":"+XAmBA,IAAa,EAAb,cAAsC,CAAU,CAE9C,eAEA,gBAEA,QAEA,YACE,EACA,EACA,CACA,MACE,EAAc,YACd,WAAW,EAAK,QAAQ,8CAA8C,EAAK,eAAe,eACzE,EAAK,gBAAgB,yHAEtC,CACF,EACA,KAAK,KAAO,mBACZ,KAAK,eAAiB,EAAK,eAC3B,KAAK,gBAAkB,EAAK,gBAC5B,KAAK,QAAU,EAAK,OACtB,CACF,ECjCA,MAAM,GACJ,EACA,KACiC,CACjC,KAAM,oBACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEM,GACJ,EACA,KACyB,CACzB,KAAM,aACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEa,EAA4B,CACvC,OAAQ,EACR,MAAO,CACL,uBAAwB,CACtB,CAAE,KAAM,YAAa,KAAM,WAAY,EACvC,CAAE,KAAM,cAAe,KAAM,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