@zama-fhe/sdk 3.8.0-beta.20 → 3.8.0-beta.21

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 (112) hide show
  1. package/dist/cjs/alignment.cjs +1 -1
  2. package/dist/cjs/alignment.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/ethers/index.cjs.map +1 -1
  7. package/dist/cjs/fhevm-relayer.cjs +2 -2
  8. package/dist/cjs/fhevm-relayer.cjs.map +1 -1
  9. package/dist/cjs/index.cjs +1 -1
  10. package/dist/cjs/index.cjs.map +1 -1
  11. package/dist/cjs/log-decoding.cjs +2 -0
  12. package/dist/cjs/log-decoding.cjs.map +1 -0
  13. package/dist/cjs/query/index.cjs +1 -1
  14. package/dist/cjs/query/index.cjs.map +1 -1
  15. package/dist/cjs/query-keys.cjs +2 -0
  16. package/dist/cjs/query-keys.cjs.map +1 -0
  17. package/dist/cjs/relayer.cjs +1 -1
  18. package/dist/cjs/relayer.cjs.map +1 -1
  19. package/dist/cjs/telemetry.cjs +1 -1
  20. package/dist/cjs/telemetry.cjs.map +1 -1
  21. package/dist/cjs/token.cjs +1 -1
  22. package/dist/cjs/token.cjs.map +1 -1
  23. package/dist/cjs/vaults/index.cjs +1 -1
  24. package/dist/cjs/vaults/index.cjs.map +1 -1
  25. package/dist/cjs/viem/index.cjs +1 -1
  26. package/dist/cjs/viem/index.cjs.map +1 -1
  27. package/dist/cjs/wrappers-registry.cjs +2 -0
  28. package/dist/cjs/wrappers-registry.cjs.map +1 -0
  29. package/dist/esm/alignment-o-YIndFR.js +2 -0
  30. package/dist/esm/alignment-o-YIndFR.js.map +1 -0
  31. package/dist/esm/{base-signer-C4P_Y-TS.d.ts → base-signer-nenGJU9U.d.ts} +1 -1
  32. package/dist/esm/base-signer-p5iz9eeb.js +2 -0
  33. package/dist/esm/base-signer-p5iz9eeb.js.map +1 -0
  34. package/dist/esm/cleartext/index.d.ts +2 -2
  35. package/dist/esm/cleartext/index.js +1 -1
  36. package/dist/esm/{cleartext-D587CgVj.d.ts → cleartext-BLMLdKFh.d.ts} +1 -1
  37. package/dist/esm/{cleartext-BrJewisr.js → cleartext-C1Y5zc1Y.js} +2 -2
  38. package/dist/esm/{cleartext-BrJewisr.js.map → cleartext-C1Y5zc1Y.js.map} +1 -1
  39. package/dist/esm/{index-TuEeFx9Z.d.ts → decryption-Cp8calaa.d.ts} +1110 -1575
  40. package/dist/esm/{encrypt-worker-client-Bjab5Grh.d.ts → encrypt-worker-client-CkEIA0Tp.d.ts} +1 -1
  41. package/dist/esm/{encryption-DDP0UpGa.js → encryption-BT886Jlj.js} +2 -2
  42. package/dist/esm/{encryption-DDP0UpGa.js.map → encryption-BT886Jlj.js.map} +1 -1
  43. package/dist/esm/ethers/index.d.ts +12 -4
  44. package/dist/esm/ethers/index.js +1 -1
  45. package/dist/esm/ethers/index.js.map +1 -1
  46. package/dist/esm/{fatal-batch-BqKg7m3V.js → fatal-batch-BYeHrf0V.js} +2 -2
  47. package/dist/esm/{fatal-batch-BqKg7m3V.js.map → fatal-batch-BYeHrf0V.js.map} +1 -1
  48. package/dist/esm/{fhevm-relayer-B-Ve8Yyz.js → fhevm-relayer-BEzN0aev.js} +2 -2
  49. package/dist/esm/{fhevm-relayer-B-Ve8Yyz.js.map → fhevm-relayer-BEzN0aev.js.map} +1 -1
  50. package/dist/esm/{index-Dae8rZWN.d.ts → index-CI6f4jxt.d.ts} +5 -5
  51. package/dist/esm/{index-yCC7GnOx.d.ts → index-ClNBSbRy.d.ts} +2 -2
  52. package/dist/esm/index.d.ts +8 -8
  53. package/dist/esm/index.js +1 -1
  54. package/dist/esm/index.js.map +1 -1
  55. package/dist/esm/internal/index.d.ts +3 -3
  56. package/dist/esm/internal/index.js +1 -1
  57. package/dist/esm/log-decoding-ZthqwHOv.js +2 -0
  58. package/dist/esm/log-decoding-ZthqwHOv.js.map +1 -0
  59. package/dist/esm/node/index.d.ts +3 -3
  60. package/dist/esm/node/index.js +1 -1
  61. package/dist/esm/query/index.d.ts +5 -5
  62. package/dist/esm/query/index.js +1 -1
  63. package/dist/esm/query/index.js.map +1 -1
  64. package/dist/esm/query-keys-CSPxPLBB.js +2 -0
  65. package/dist/esm/query-keys-CSPxPLBB.js.map +1 -0
  66. package/dist/esm/{relayer-CqdiNLZH.js → relayer-nWfQAlo7.js} +2 -2
  67. package/dist/esm/{relayer-CqdiNLZH.js.map → relayer-nWfQAlo7.js.map} +1 -1
  68. package/dist/esm/{signing-BIlZhi5G.js → signing-CVEOw21I.js} +2 -2
  69. package/dist/esm/{signing-BIlZhi5G.js.map → signing-CVEOw21I.js.map} +1 -1
  70. package/dist/esm/telemetry-YFH36F_7.js +2 -0
  71. package/dist/esm/telemetry-YFH36F_7.js.map +1 -0
  72. package/dist/esm/token-AXsOIUDB.js +2 -0
  73. package/dist/esm/{token-CxDfm7V-.js.map → token-AXsOIUDB.js.map} +1 -1
  74. package/dist/esm/{types-Bi-kDUxb.d.ts → types-D253qkvB.d.ts} +1 -1
  75. package/dist/esm/{types-D1qhoqkF.d.ts → types-DH06Ap0n.d.ts} +1 -1
  76. package/dist/esm/{types-DbnDm2O9.d.ts → types-Ubeo72FV.d.ts} +13 -1
  77. package/dist/esm/{validation-CL7MJT6k.js → validation-CZfDLOUh.js} +2 -2
  78. package/dist/esm/{validation-CL7MJT6k.js.map → validation-CZfDLOUh.js.map} +1 -1
  79. package/dist/esm/vaults/index.d.ts +262 -15600
  80. package/dist/esm/vaults/index.js +1 -1
  81. package/dist/esm/vaults/index.js.map +1 -1
  82. package/dist/esm/viem/index.d.ts +12 -4
  83. package/dist/esm/viem/index.js +1 -1
  84. package/dist/esm/viem/index.js.map +1 -1
  85. package/dist/esm/web/index.d.ts +2 -2
  86. package/dist/esm/web/index.js +1 -1
  87. package/dist/esm/wrappers-registry-Cm3JJeqx.js +2 -0
  88. package/dist/esm/wrappers-registry-Cm3JJeqx.js.map +1 -0
  89. package/package.json +1 -1
  90. package/dist/cjs/applied-runtime.cjs +0 -2
  91. package/dist/cjs/applied-runtime.cjs.map +0 -1
  92. package/dist/cjs/invalidation.cjs +0 -2
  93. package/dist/cjs/invalidation.cjs.map +0 -1
  94. package/dist/cjs/primitives.cjs +0 -2
  95. package/dist/cjs/primitives.cjs.map +0 -1
  96. package/dist/cjs/wrapped-token.cjs +0 -2
  97. package/dist/cjs/wrapped-token.cjs.map +0 -1
  98. package/dist/esm/alignment-CYa0d0Ud.js +0 -2
  99. package/dist/esm/alignment-CYa0d0Ud.js.map +0 -1
  100. package/dist/esm/applied-runtime-3fzqBC2V.js +0 -2
  101. package/dist/esm/applied-runtime-3fzqBC2V.js.map +0 -1
  102. package/dist/esm/base-signer-DvCCKQfk.js +0 -2
  103. package/dist/esm/base-signer-DvCCKQfk.js.map +0 -1
  104. package/dist/esm/invalidation-CzspPBR7.js +0 -2
  105. package/dist/esm/invalidation-CzspPBR7.js.map +0 -1
  106. package/dist/esm/primitives-Cym-3HKa.js +0 -2
  107. package/dist/esm/primitives-Cym-3HKa.js.map +0 -1
  108. package/dist/esm/telemetry-CmBkkrXK.js +0 -2
  109. package/dist/esm/telemetry-CmBkkrXK.js.map +0 -1
  110. package/dist/esm/token-CxDfm7V-.js +0 -2
  111. package/dist/esm/wrapped-token-BWMNyFj2.js +0 -2
  112. package/dist/esm/wrapped-token-BWMNyFj2.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"invalidation-CzspPBR7.js","names":["isPlainObject","hasObjectPrototype","value","ctor","prot","o","filterQueryOptions","_gcTime","_staleTime","_enabled","_select","_refetchInterval","_refetchOnMount","_refetchOnWindowFocus","_refetchOnReconnect","_retry","_retryDelay","_retryOnMount","_queryFn","_queryKey","_queryKeyHashFn","_initialData","_initialDataUpdatedAt","_placeholderData","_structuralSharing","_throwOnError","_meta","_query","_pollingInterval","rest","options","hashFn","queryKey","key","result","normalizeAddresses","addresses","getAddress","address","normalizeAddress","walletAccountKey","walletAccount","zamaQueryKeys","tokenAddress","owner","tokenAddresses","t","e","erc20Address","r","registryAddress","h","holder","s","spender","contractAddresses","contractAddress","dr","delegator","de","delegate","encryptedInputs","a","b","walletChainId","confidentialTokenAddress","invalidateUnderlyingAllowanceQueries","queryClient","invalidatePendingUnshieldQueries","invalidateAfterUnwrap","invalidateBalanceQueries","invalidateWagmiBalanceQueries","invalidateAfterWrap","invalidateAfterShield","invalidateAfterUnshield","invalidateAfterUnshieldSettled","invalidateAfterTransfer","invalidateAfterApproveUnderlying","invalidateAfterSetOperator","isZamaQuery","query","balanceFunctionName","z","balanceReadArgs","batchedReadArgs","isBalanceReadPart","part","batched","c","isWagmiBalanceQuery","invalidateWalletLifecycleQueries"],"sources":["../../src/query/utils.ts","../../src/query/query-keys.ts","../../src/query/invalidation.ts"],"sourcesContent":["// Adapted from the wagmi codebase\n// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-wrapper-object-types\nfunction isPlainObject(value: any): value is Object {\n if (!hasObjectPrototype(value)) {\n return false;\n }\n\n // If has modified constructor\n const ctor = value.constructor;\n if (ctor === undefined) {\n return true;\n }\n\n // If has modified prototype\n const prot = ctor.prototype;\n if (!hasObjectPrototype(prot)) {\n return false;\n }\n\n // If constructor does not have an Object-specific method\n // eslint-disable-next-line no-prototype-builtins\n if (!prot.hasOwnProperty(\"isPrototypeOf\")) {\n return false;\n }\n\n // Most likely a plain Object\n return true;\n}\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction hasObjectPrototype(o: any): boolean {\n return Object.prototype.toString.call(o) === \"[object Object]\";\n}\n\n/** Union of TanStack Query option keys stripped by {@link filterQueryOptions}, leaving only domain parameters. */\nexport type StrippedQueryOptionKeys =\n // Keep this union aligned with @tanstack/query-core behavioral options\n // (for example QueryObserverOptions). Revisit on every upgrade to avoid\n // leaking query controls into lower-level query factories.\n | \"gcTime\"\n | \"staleTime\"\n | \"enabled\"\n | \"select\"\n | \"refetchInterval\"\n | \"refetchOnMount\"\n | \"refetchOnWindowFocus\"\n | \"refetchOnReconnect\"\n | \"retry\"\n | \"retryDelay\"\n | \"retryOnMount\"\n | \"queryFn\"\n | \"queryKey\"\n | \"queryKeyHashFn\"\n | \"initialData\"\n | \"initialDataUpdatedAt\"\n | \"placeholderData\"\n | \"structuralSharing\"\n | \"throwOnError\"\n | \"meta\"\n | \"query\"\n | \"pollingInterval\";\n\n/**\n * Remove TanStack behavioral options from a query config object so only domain\n * parameters remain for the lower-level factory.\n *\n * @example\n * ```ts\n * const params = filterQueryOptions({\n * query: { enabled: false },\n * gcTime: 60_000,\n * owner: \"0xabc\",\n * });\n * // => { owner: \"0xabc\" }\n * ```\n */\nexport function filterQueryOptions<TOptions extends Record<string, unknown>>(\n options: TOptions,\n): Omit<TOptions, StrippedQueryOptionKeys> {\n const {\n gcTime: _gcTime,\n staleTime: _staleTime,\n enabled: _enabled,\n select: _select,\n refetchInterval: _refetchInterval,\n refetchOnMount: _refetchOnMount,\n refetchOnWindowFocus: _refetchOnWindowFocus,\n refetchOnReconnect: _refetchOnReconnect,\n retry: _retry,\n retryDelay: _retryDelay,\n retryOnMount: _retryOnMount,\n queryFn: _queryFn,\n queryKey: _queryKey,\n queryKeyHashFn: _queryKeyHashFn,\n initialData: _initialData,\n initialDataUpdatedAt: _initialDataUpdatedAt,\n placeholderData: _placeholderData,\n structuralSharing: _structuralSharing,\n throwOnError: _throwOnError,\n meta: _meta,\n query: _query,\n pollingInterval: _pollingInterval,\n ...rest\n } = options;\n\n return rest;\n}\n\n/**\n * Stable hash function for query keys.\n * Sorts object keys recursively and converts bigint values to strings.\n *\n * @remarks\n * bigint values are serialized as decimal strings, so `42n` and `\"42\"` hash to\n * the same token when they occupy the same position. This collision is accepted\n * by design for the current query-key conventions in this package.\n */\nexport function hashFn(queryKey: readonly unknown[]): string {\n return JSON.stringify(queryKey, (_, value) => {\n if (isPlainObject(value)) {\n return Object.keys(value)\n .sort()\n .reduce(\n (result, key) => {\n result[key] = value[key];\n return result;\n },\n {} as Record<string, unknown>,\n );\n }\n\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n\n return value;\n });\n}\n","import { getAddress } from \"viem\";\nimport type { Address, Hex } from \"viem\";\nimport type { WalletAccount } from \"../types\";\n\nconst normalizeAddresses = (addresses: Address[]): Address[] =>\n addresses.map((address) => getAddress(address));\nconst normalizeAddress = (address?: Address): Address | undefined =>\n address === undefined ? undefined : getAddress(address);\nconst walletAccountKey = (walletAccount?: WalletAccount) =>\n walletAccount\n ? { walletAddress: getAddress(walletAccount.address), walletChainId: walletAccount.chainId }\n : {};\n\n/**\n * Canonical query-key namespace for `@zama-fhe/sdk/query`.\n *\n * @example\n * ```ts\n * queryClient.invalidateQueries({\n * queryKey: zamaQueryKeys.confidentialBalance.token(\"0xToken\"),\n * });\n * ```\n */\nexport const zamaQueryKeys = {\n confidentialBalance: {\n all: [\"zama.confidentialBalance\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.confidentialBalance\", { tokenAddress: getAddress(tokenAddress) }] as const,\n owner: (tokenAddress: Address, owner?: Address, walletAccount?: WalletAccount) =>\n [\n \"zama.confidentialBalance\",\n {\n tokenAddress: getAddress(tokenAddress),\n ...walletAccountKey(walletAccount),\n ...(owner ? { owner: getAddress(owner) } : {}),\n },\n ] as const,\n },\n\n confidentialBalances: {\n all: [\"zama.confidentialBalances\"] as const,\n tokens: (tokenAddresses: Address[], owner?: Address, walletAccount?: WalletAccount) =>\n [\n \"zama.confidentialBalances\",\n {\n tokenAddresses: normalizeAddresses(tokenAddresses),\n ...walletAccountKey(walletAccount),\n ...(owner ? { owner: getAddress(owner) } : {}),\n },\n ] as const,\n },\n\n tokenMetadata: {\n all: [\"zama.tokenMetadata\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.tokenMetadata\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n isConfidential: {\n all: [\"zama.isConfidential\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.isConfidential\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n isWrapper: {\n all: [\"zama.isWrapper\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.isWrapper\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n wrapperDiscovery: {\n all: [\"zama.wrapperDiscovery\"] as const,\n token: (tokenAddress?: Address, erc20Address?: Address, registryAddress?: Address) => {\n const t = normalizeAddress(tokenAddress);\n const e = normalizeAddress(erc20Address);\n const r = normalizeAddress(registryAddress);\n return [\n \"zama.wrapperDiscovery\",\n {\n ...(t ? { tokenAddress: t } : {}),\n ...(e ? { erc20Address: e } : {}),\n ...(r ? { registryAddress: r } : {}),\n },\n ] as const;\n },\n },\n\n underlyingAllowance: {\n all: [\"zama.underlyingAllowance\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.underlyingAllowance\", { tokenAddress: getAddress(tokenAddress) }] as const,\n scope: (tokenAddress: Address, owner?: Address) =>\n [\n \"zama.underlyingAllowance\",\n { tokenAddress: getAddress(tokenAddress), ...(owner ? { owner: getAddress(owner) } : {}) },\n ] as const,\n },\n\n confidentialIsOperator: {\n all: [\"zama.confidentialIsOperator\"] as const,\n token: (tokenAddress?: Address) => {\n const t = normalizeAddress(tokenAddress);\n return [\"zama.confidentialIsOperator\", t ? { tokenAddress: t } : {}] as const;\n },\n scope: (tokenAddress?: Address, holder?: Address, spender?: Address) => {\n const t = normalizeAddress(tokenAddress);\n const h = normalizeAddress(holder);\n const s = normalizeAddress(spender);\n return [\n \"zama.confidentialIsOperator\",\n {\n ...(t ? { tokenAddress: t } : {}),\n ...(h ? { holder: h } : {}),\n ...(s ? { spender: s } : {}),\n },\n ] as const;\n },\n },\n\n totalSupply: {\n all: [\"zama.totalSupply\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.totalSupply\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n pendingUnshield: {\n all: [\"zama.pendingUnshield\"] as const,\n token: (tokenAddress: Address) =>\n [\"zama.pendingUnshield\", { tokenAddress: getAddress(tokenAddress) }] as const,\n },\n\n hasPermit: {\n all: [\"zama.hasPermit\"] as const,\n scope: (contractAddresses: Address[], walletAccount?: WalletAccount) =>\n [\n \"zama.hasPermit\",\n {\n ...walletAccountKey(walletAccount),\n contractAddresses: normalizeAddresses(contractAddresses).sort(),\n },\n ] as const,\n },\n\n delegationStatus: {\n all: [\"zama.delegationStatus\"] as const,\n contract: (contractAddress?: Address) => {\n const t = normalizeAddress(contractAddress);\n return [\"zama.delegationStatus\", t ? { contractAddress: t } : {}] as const;\n },\n scope: (contractAddress?: Address, delegator?: Address, delegate?: Address) => {\n const t = normalizeAddress(contractAddress);\n const dr = normalizeAddress(delegator);\n const de = normalizeAddress(delegate);\n return [\n \"zama.delegationStatus\",\n {\n ...(t ? { contractAddress: t } : {}),\n ...(dr ? { delegatorAddress: dr } : {}),\n ...(de ? { delegateAddress: de } : {}),\n },\n ] as const;\n },\n },\n\n decryption: {\n all: [\"zama.decryption\"] as const,\n encryptedValue: (encryptedValue: string, contractAddress?: Address) =>\n [\n \"zama.decryption\",\n {\n encryptedValue,\n ...(contractAddress === undefined\n ? {}\n : { contractAddress: getAddress(contractAddress) }),\n },\n ] as const,\n encryptedInputs: (\n encryptedInputs: readonly { encryptedValue: string; contractAddress: Address }[],\n walletAccount?: WalletAccount,\n ) =>\n [\n \"zama.decryption\",\n {\n ...walletAccountKey(walletAccount),\n encryptedInputs: [...encryptedInputs]\n .sort((a, b) => a.encryptedValue.localeCompare(b.encryptedValue))\n .map((h) => ({\n encryptedValue: h.encryptedValue as Hex,\n contractAddress: getAddress(h.contractAddress),\n })),\n },\n ] as const,\n },\n\n wrappersRegistry: {\n all: [\"zama.wrappersRegistry\"] as const,\n chainId: (walletChainId?: number) =>\n [\n \"zama.wrappersRegistry\",\n { type: \"chainId\", ...(walletChainId === undefined ? {} : { walletChainId }) },\n ] as const,\n tokenPairs: (registryAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n { type: \"tokenPairs\", registryAddress: getAddress(registryAddress) },\n ] as const,\n confidentialTokenAddress: (registryAddress: Address, tokenAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"confidentialTokenAddress\",\n registryAddress: getAddress(registryAddress),\n tokenAddress: getAddress(tokenAddress),\n },\n ] as const,\n tokenAddress: (registryAddress: Address, confidentialTokenAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"tokenAddress\",\n registryAddress: getAddress(registryAddress),\n confidentialTokenAddress: getAddress(confidentialTokenAddress),\n },\n ] as const,\n tokenPairsLength: (registryAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n { type: \"tokenPairsLength\", registryAddress: getAddress(registryAddress) },\n ] as const,\n tokenPairsSlice: (registryAddress: Address, fromIndex: string, toIndex: string) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"tokenPairsSlice\",\n registryAddress: getAddress(registryAddress),\n fromIndex,\n toIndex,\n },\n ] as const,\n tokenPair: (registryAddress: Address, index: string) =>\n [\n \"zama.wrappersRegistry\",\n { type: \"tokenPair\", registryAddress: getAddress(registryAddress), index },\n ] as const,\n isConfidentialTokenValid: (registryAddress: Address, confidentialTokenAddress: Address) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"isConfidentialTokenValid\",\n registryAddress: getAddress(registryAddress),\n confidentialTokenAddress: getAddress(confidentialTokenAddress),\n },\n ] as const,\n listPairs: (registryAddress: Address, page: number, pageSize: number, metadata: boolean) =>\n [\n \"zama.wrappersRegistry\",\n {\n type: \"listPairs\",\n registryAddress: getAddress(registryAddress),\n page,\n pageSize,\n metadata,\n },\n ] as const,\n },\n} as const;\n","import type { Address } from \"viem\";\nimport { z } from \"zod/mini\";\nimport { zamaQueryKeys } from \"./query-keys\";\n\n/** Minimal query shape read by the invalidation predicates. */\nexport interface QueryLike {\n /** The query's cache key. */\n queryKey: readonly unknown[];\n}\n\n/** Minimal filter shape accepted by the invalidation helpers, matching TanStack Query's `QueryFilters`. */\nexport interface QueryFilterLike {\n /** Match queries whose key starts with this prefix. */\n queryKey?: readonly unknown[];\n /** Match queries for which this returns `true`. */\n predicate?: (query: QueryLike) => boolean;\n}\n\n/** Minimal `QueryClient` surface used by the invalidation helpers. */\nexport interface QueryClientLike {\n /** Mark matching queries stale so they refetch. */\n invalidateQueries(filters: QueryFilterLike): void | Promise<void>;\n /** Remove matching queries from the cache entirely. */\n removeQueries(filters: QueryFilterLike): void;\n}\n\nfunction invalidateUnderlyingAllowanceQueries(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: zamaQueryKeys.underlyingAllowance.token(tokenAddress),\n });\n}\n\nfunction invalidatePendingUnshieldQueries(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: zamaQueryKeys.pendingUnshield.token(tokenAddress),\n });\n}\n\n/** Invalidates the caches affected by an unwrap: confidential balances, underlying allowance, and pending unshields. */\nexport function invalidateAfterUnwrap(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidatePendingUnshieldQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\n/** Invalidates the caches affected by a wrap: confidential balances and underlying allowance. */\nexport function invalidateAfterWrap(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\n/** Invalidates the confidential balance queries for a token (single-token and batched). */\nexport function invalidateBalanceQueries(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: zamaQueryKeys.confidentialBalance.token(tokenAddress),\n });\n void queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalances.all });\n}\n\n/** Invalidates the caches affected by a shield: confidential balances and underlying allowance. */\nexport function invalidateAfterShield(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\n/** Invalidates the caches affected by an unshield request: confidential balances, underlying allowance, and pending unshields. */\nexport function invalidateAfterUnshield(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n invalidatePendingUnshieldQueries(queryClient, tokenAddress);\n invalidateWagmiBalanceQueries(queryClient);\n}\n\n/** Invalidates the pending-unshield cache once an unshield has settled on-chain. */\nexport function invalidateAfterUnshieldSettled(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n invalidatePendingUnshieldQueries(queryClient, tokenAddress);\n}\n\n/** Invalidates the confidential balance caches affected by a transfer. */\nexport function invalidateAfterTransfer(queryClient: QueryClientLike, tokenAddress: Address): void {\n invalidateBalanceQueries(queryClient, tokenAddress);\n}\n\n/** Invalidates the underlying-allowance cache after approving the underlying ERC-20. */\nexport function invalidateAfterApproveUnderlying(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n invalidateUnderlyingAllowanceQueries(queryClient, tokenAddress);\n}\n\n/** Invalidates the operator-status cache after changing a token operator. */\nexport function invalidateAfterSetOperator(\n queryClient: QueryClientLike,\n tokenAddress: Address,\n): void {\n void queryClient.invalidateQueries({\n queryKey: zamaQueryKeys.confidentialIsOperator.token(tokenAddress),\n });\n}\n\nfunction isZamaQuery(query: QueryLike): boolean {\n return Array.isArray(query.queryKey) && typeof query.queryKey[0] === \"string\"\n ? query.queryKey[0].startsWith(\"zama.\")\n : false;\n}\n\nconst balanceFunctionName = z.enum([\"balanceOf\", \"confidentialBalanceOf\"]);\n\nconst balanceReadArgs = z.object({ functionName: balanceFunctionName });\n\nconst batchedReadArgs = z.object({ contracts: z.array(z.unknown()) });\n\nfunction isBalanceReadPart(part: unknown): boolean {\n if (balanceReadArgs.safeParse(part).success) {\n return true;\n }\n const batched = batchedReadArgs.safeParse(part);\n return (\n batched.success && batched.data.contracts.some((c) => balanceReadArgs.safeParse(c).success)\n );\n}\n\nfunction isWagmiBalanceQuery(query: QueryLike): boolean {\n return Array.isArray(query.queryKey) && query.queryKey.some(isBalanceReadPart);\n}\n\n/** Invalidates any wagmi `useBalance`/`readContract` balance queries so ERC-20 balances refresh. */\nexport function invalidateWagmiBalanceQueries(queryClient: QueryClientLike): void {\n void queryClient.invalidateQueries({ predicate: isWagmiBalanceQuery });\n}\n\n/** Clears wallet-local caches (decryption, permits) and invalidates all Zama queries — call on wallet connect/disconnect so a stale entitlement can't leak across accounts. */\nexport function invalidateWalletLifecycleQueries(queryClient: QueryClientLike): void {\n // Remove (not just invalidate) wallet-local caches so a stale allowed/true\n // cannot surface between wallet disconnect and the next refetch.\n queryClient.removeQueries({ queryKey: zamaQueryKeys.decryption.all });\n queryClient.removeQueries({ queryKey: zamaQueryKeys.hasPermit.all });\n void queryClient.invalidateQueries({ predicate: isZamaQuery });\n invalidateWagmiBalanceQueries(queryClient);\n}\n"],"mappings":"A,+DAEA,SAASA,EAAc,EAA6B,CAClD,GAAI,CAACC,EAAmBC,CAAK,EAC3B,MAAO,GAIT,IAAMC,EAAOD,EAAM,YACnB,GAAIC,IAAS,IAAA,GACX,MAAO,GAIT,IAAMC,EAAOD,EAAK,UAYlB,MALA,EANI,CAACF,EAAmBG,CAAI,GAMxB,CAACA,EAAK,eAAe,eAAe,EAM1C,CAGA,SAASH,EAAmB,EAAiB,CAC3C,OAAO,OAAO,UAAU,SAAS,KAAKI,CAAC,IAAM,iBAC/C,CA4CA,SAAgBC,EACd,EACyC,CACzC,GAAM,CACJ,OAAQC,EACR,UAAWC,EACX,QAASC,EACT,OAAQC,EACR,gBAAiBC,EACjB,eAAgBC,EAChB,qBAAsBC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BJ,CAAW,CAC3C,C"}
@@ -1,2 +0,0 @@
1
- import{getAddress as e,isAddress as t,isHex as n}from"viem";import{z as r}from"zod/mini";function i(t){return e(t)}const a=r.custom(e=>typeof e==`string`&&n(e,{strict:!0}),`expected 0x-prefixed hex string`),o=r.custom(e=>typeof e==`string`&&t(e,{strict:!1}),`expected EVM address`),s=r.pipe(o,r.transform(i)),c=r.int().check(r.nonnegative()),l=r.int().check(r.positive()),u=r.int().check(r.nonnegative()),d=r.int().check(r.positive());r.int().check(r.positive());export{d as a,u as i,s as n,l as o,a as r,c as s,i as t};
2
- //# sourceMappingURL=primitives-Cym-3HKa.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"primitives-Cym-3HKa.js","names":["checksum","getAddress","value","hex","z","v","isHex","evmAddress","isAddress","checksummedAddress","unixSeconds","positiveSeconds","nonNegativeSeconds","positiveDays"],"sources":["../../src/schemas/primitives.ts"],"sourcesContent":["import { type Address, getAddress, isAddress, isHex, type Hex } from \"viem\";\nimport { z } from \"zod/mini\";\n\ndeclare const checksummedTag: unique symbol;\n\n/** An EVM address that has been put through `getAddress` (EIP-55 checksum form). */\nexport type ChecksummedAddress = Address & { readonly [checksummedTag]: true };\n\n/** Stamp the brand on an arbitrary `Address` after normalizing it. */\nexport function checksum(value: Address): ChecksummedAddress {\n return getAddress(value) as ChecksummedAddress;\n}\n\n/** `0x`-prefixed hex string. */\nexport const hex = z.custom<Hex>(\n (v) => typeof v === \"string\" && isHex(v, { strict: true }),\n \"expected 0x-prefixed hex string\",\n);\n\n/** Validates an EVM address string. Output type is `Address` (`` `0x${string}` ``). */\nexport const evmAddress = z.custom<Address>(\n (v) => typeof v === \"string\" && isAddress(v, { strict: false }),\n \"expected EVM address\",\n);\n\n/** Validates and EIP-55 checksums an EVM address. Output is {@link ChecksummedAddress}. */\nexport const checksummedAddress = z.pipe(evmAddress, z.transform(checksum));\n\n/** Non-negative integer Unix timestamp in seconds. */\nexport const unixSeconds = z.int().check(z.nonnegative());\n\n/** Positive integer count of seconds (e.g. a TTL). */\nexport const positiveSeconds = z.int().check(z.positive());\n\n/** Non-negative integer count of seconds (e.g. a cache TTL where 0 disables caching). */\nexport const nonNegativeSeconds = z.int().check(z.nonnegative());\n\n/** Positive integer count of days (e.g. a permit duration). */\nexport const positiveDays = z.int().check(z.positive());\n\n/** Positive integer EVM chain ID. */\nexport const chainId = z.int().check(z.positive());\n"],"mappings":"A,yFASA,SAAgBA,EAAS,EAAoC,CAC3D,OAAOC,EAAWC,CAAK,CACzB,CAGA,MAAaC,EAAMC,EAAE,OAClB,GAAM,OAAOC,GAAM,UAAYC,EAAMD,EAAG,CAAE,OAAQ,EAAK,CAAC,EACzD,iCACF,EAGaE,EAAaH,EAAE,OACzB,GAAM,OAAOC,GAAM,UAAYG,EAAUH,EAAG,CAAE,OAAQ,EAAM,CAAC,EAC9D,sBACF,EAGaI,EAAqBL,EAAE,KAAKG,EAAYH,EAAE,UAAUJ,CAAQ,CAAC,EAG7DU,EAAcN,EAAE,IAAI,CAAC,CAAC,MAAMA,EAAE,YAAY,CAAC,EAG3CO,EAAkBP,EAAE,IAAI,CAAC,CAAC,MAAMA,EAAE,SAAS,CAAC,EAG5CQ,EAAqBR,EAAE,IAAI,CAAC,CAAC,MAAMA,EAAE,YAAY,CAAC,EAGlDS,EAAeT,EAAE,IAAI,CAAC,CAAC,MAAMA,EAAE,SAAS,CAAC,EAG/BA,EAAE,IAAI,CAAC,CAAC,MAAMA,EAAE,SAAS,CAAC,E"}
@@ -1,2 +0,0 @@
1
- function e(e,t){let n=Object.entries({version:`3.8.0-beta.20`,layer:e.state.layer,runtime:e.runtime,...t!==void 0&&{operation:t}}),r=e=>Object.fromEntries(n.map(([t,n])=>[`${e}${t}`,n]));return e.mode===`query`?{query:r(`zama_sdk_`)}:{headers:r(`x-zama-sdk-`)}}function t(e,t){return Object.assign({},e,{operation:e?.operation??t})}function n(e){if(typeof e==`boolean`)return e?`header`:`off`;let t=typeof e==`string`?e.trim().toLowerCase():void 0;return t===`0`||t===`false`?`off`:t===`header`||t===`query`||t===`off`?t:void 0}export{e as n,t as r,n as t};
2
- //# sourceMappingURL=telemetry-CmBkkrXK.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"telemetry-CmBkkrXK.js","names":["packageJson.version","telemetryRequestOptions","fields","telemetry","operation","prefixed","name","value","prefix","withOperation","options","parseTelemetryMode","mode"],"sources":["../../package.json","../../src/version.ts","../../src/telemetry.ts"],"sourcesContent":["","import packageJson from \"../package.json\" with { type: \"json\" };\n\nexport const SDK_VERSION: string = packageJson.version;\n","import { SDK_VERSION } from \"./version\";\n\n// No telemetry field may carry a wallet address, encrypted value, amount or identifier.\n\nexport type TelemetryLayer = \"core\" | \"react\";\n\nexport type TelemetryRuntime = \"web\" | \"node\";\n\nexport type TelemetryMode = \"header\" | \"query\" | \"off\";\n\n/** Values are frozen once shipped, so that dashboards keyed on them survive method renames. */\nexport type TelemetryOperation =\n | \"balance-of\"\n | \"decrypt-balance-as\"\n | \"batch-balances-of\"\n | \"batch-decrypt-balances-as\"\n | \"confidential-transfer\"\n | \"confidential-transfer-from\"\n | \"confidential-transfer-and-call\"\n | \"confidential-transfer-from-and-call\"\n | \"unshield\"\n | \"unshield-all\"\n | \"resume-unshield\"\n | \"unwrap\"\n | \"finalize-unwrap\"\n | \"vault-deposit\"\n | \"vault-redeem\"\n | \"vault-join\"\n | \"vault-group-deposit\"\n | \"vault-group-redeem\"\n | \"vault-deposit-of\"\n | \"vault-finalize\"\n | \"encrypt\"\n | \"decrypt-values\"\n | \"delegated-decrypt-values\"\n | \"delegated-batch-decrypt-values\"\n | \"decrypt-public-values\"\n | \"offline-confidential-transfer\"\n | \"offline-confidential-transfer-from\"\n | \"offline-unwrap\"\n | \"offline-finalize-unwrap\";\n\n/**\n * Shared by every relayer of a config. `layer` flips to `react` once\n * `ZamaProvider` marks the config, after the relayers exist.\n *\n * @internal\n */\nexport interface TelemetryState {\n layer: TelemetryLayer;\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport interface RelayerTelemetry {\n readonly state: TelemetryState;\n readonly runtime: TelemetryRuntime;\n /** The config's `mode`, unless `ZAMA_SDK_TELEMETRY` overrode it on Node. */\n readonly mode: Exclude<TelemetryMode, \"off\">;\n}\n\nexport function telemetryRequestOptions(\n telemetry: RelayerTelemetry,\n operation: TelemetryOperation | undefined,\n): { headers?: Record<string, string>; query?: Record<string, string> } {\n const fields = Object.entries({\n version: SDK_VERSION,\n layer: telemetry.state.layer,\n runtime: telemetry.runtime,\n ...(operation !== undefined && { operation }),\n });\n const prefixed = (prefix: string) =>\n Object.fromEntries(fields.map(([name, value]) => [`${prefix}${name}`, value]));\n return telemetry.mode === \"query\"\n ? { query: prefixed(\"zama_sdk_\") }\n : { headers: prefixed(\"x-zama-sdk-\") };\n}\n\n/** `options` labelled with `operation`, unless the caller already labelled it. */\nexport function withOperation<T extends { readonly operation?: TelemetryOperation }>(\n options: T | undefined,\n operation: TelemetryOperation,\n): Partial<T> & { readonly operation: TelemetryOperation } {\n return Object.assign({}, options, { operation: options?.operation ?? operation });\n}\n\nexport function parseTelemetryMode(value: string | boolean | undefined): TelemetryMode | undefined {\n if (typeof value === \"boolean\") {\n return value ? \"header\" : \"off\";\n }\n // JavaScript callers can pass anything; only a string can name a mode.\n const mode = typeof value === \"string\" ? value.trim().toLowerCase() : undefined;\n // `0` and `false` predate the named modes and still mean off.\n if (mode === \"0\" || mode === \"false\") {\n return \"off\";\n }\n return mode === \"header\" || mode === \"query\" || mode === \"off\" ? mode : undefined;\n}\n"],"mappings":"AE4DA,SAAgBC,EACd,EACA,EACsE,CACtE,IAAMC,EAAS,OAAO,QAAQ,CAC5B,QAAS,gBACT,MAAOC,EAAU,MAAM,MACvB,QAASA,EAAU,QACnB,GAAIC,IAAc,IAAA,IAAa,CAAE,WAAU,CAC7C,CAAC,EACKC,EAAY,GAChB,OAAO,YAAYH,EAAO,KAAK,CAACI,EAAMC,KAAW,CAAC,GAAGC,IAASF,IAAQC,CAAK,CAAC,CAAC,EAC/E,OAAOJ,EAAU,OAAS,QACtB,CAAE,MAAOE,EAAS,WAAW,CAAE,EAC/B,CAAE,QAASA,EAAS,aAAa,CAAE,CACzC,CAGA,SAAgBI,EACd,EACA,EACyD,CACzD,OAAO,OAAO,OAAO,CAAC,EAAGC,EAAS,CAAE,UAAWA,GAAS,WAAaN,CAAU,CAAC,CAClF,CAEA,SAAgBO,EAAmB,EAAgE,CACjG,GAAI,OAAOJ,GAAU,UACnB,OAAOA,EAAQ,SAAW,MAG5B,IAAMK,EAAO,OAAOL,GAAU,SAAWA,EAAM,KAAK,CAAC,CAAC,YAAY,EAAI,IAAA,GAKtE,OAHIK,IAAS,KAAOA,IAAS,QACpB,MAEFA,IAAS,UAAYA,IAAS,SAAWA,IAAS,MAAQA,EAAO,IAAA,EAC1E,C"}
@@ -1,2 +0,0 @@
1
- import{$ as e,A as t,E as n,I as r,J as i,O as a,P as o,S as s,T as c,U as l,W as u,j as d,k as f,m as p,n as m,nt as h,p as g,q as _,rt as v,t as y,tt as b,v as x,w as S}from"./alignment-CYa0d0Ud.js";import{C,d as w,i as T,r as E,t as D}from"./relayer-CqdiNLZH.js";import{r as O,t as k}from"./encryption-DDP0UpGa.js";import{n as A}from"./fatal-batch-BqKg7m3V.js";import{getAddress as j}from"viem";var M=class extends E{requested;available;token;constructor(e,t,n){super(T.InsufficientConfidentialBalance,e,n),this.name=`InsufficientConfidentialBalanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},N=class extends E{requested;available;token;constructor(e,t,n){super(T.InsufficientERC20Balance,e,n),this.name=`InsufficientERC20BalanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},P=class extends E{requested;available;token;constructor(e,t,n){super(T.InsufficientAllowance,e,n),this.name=`InsufficientAllowanceError`,this.requested=t.requested,this.available=t.available,this.token=t.token}},F=class extends E{constructor(e,t){super(T.BalanceCheckUnavailable,e,t),this.name=`BalanceCheckUnavailableError`}},I=class extends E{constructor(e,t){super(T.ERC20ReadFailed,e,t),this.name=`ERC20ReadFailedError`}};const L={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},R={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},z={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(L),Object.freeze(R),Object.freeze(z),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function B(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 V(e){if(!B(e))throw Error(`Invalid FheType id '${e}'`);let t=z[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const H=`0x0000000000000000000000000000000000000000000000000000000000000000`;function U(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}function W(e){let t;try{t=BigInt(e)}catch{return 256}let n=Number(t>>8n&255n);return B(n)?V(n):256}function G(e,t=2048){let n=[],r=[],i=0;for(let a of e){let e=W(a);r.length>0&&i+e>t&&(n.push(r),r=[],i=0),r.push(a),i+=e}return r.length>0&&n.push(r),n}async function K(e){let{operation:t,tokenAddress:n,amount:r,signer:i,provider:a,readBalance:o}=e;if(r===0n)return;let s;try{let n=e.account??(await y(t,i,a)).address;s=await o(j(n))}catch(e){throw e instanceof E?e:new F(`Balance validation failed (token: ${n})`,{cause:e})}if(s<r)throw new M(`Insufficient confidential balance: requested ${r}, available ${s} (token: ${n})`,{requested:r,available:s,token:n})}async function q(e,t=1/0){if(Number.isFinite(t)&&t<=0)throw Error(`maxConcurrency must be a positive number`);if(!Number.isFinite(t)||t>=e.length)return Promise.all(e.map(e=>e()));let n=Array.from({length:e.length}),r=0;async function i(){for(;r<e.length;){let t=r++;e[t]&&(n[t]=await e[t]())}}return await Promise.all(Array.from({length:t},i)),n}const J=[{selector:`0xad251174`,name:`HCUBlockLimitExceeded`,ErrorClass:b,message:`The block's FHE compute budget (HCU) is spent. Retry in the next block.`},{selector:`0x77e3c293`,name:`HCUTransactionLimitExceeded`,ErrorClass:h,message:`The transaction needs more total FHE compute (HCU) than one transaction may use.`},{selector:`0xfc344870`,name:`HCUTransactionDepthLimitExceeded`,ErrorClass:h,message:`The transaction chains more sequential FHE compute (HCU depth) than one transaction may use.`}];function Y(e,t){let n=J.find(t=>w(e,t.selector,t.name));return n?new n.ErrorClass(`Transaction failed during ${t}: ${n.message}`,{cause:e}):null}async function X(e){let{operation:t,signer:n,provider:r,config:a,emit:o,onSubmitted:s,logger:c}=e,u=i[t];try{let e=await n.writeContract(a);o(u.submittedEvent(e)),l(`${t}: onSubmitted`,()=>s?.(e),c);let i=await r.waitForTransactionReceipt(e);if(i.status===`reverted`)throw new v(`Transaction ${e} reverted during ${t}`);return{txHash:e,receipt:i}}catch(e){let n=e instanceof E?e:Y(e,t)??new v(`Transaction failed during ${t}`,{cause:e});throw o({type:_.TransactionError,operation:t,error:n}),n}}var Z=class i{sdk;address;constructor(e,t){this.sdk=e,this.address=j(t)}#e(t){return e(this.sdk.signer,t)}async name(){return this.sdk.provider.readContract(S(this.address))}async symbol(){return this.sdk.provider.readContract(c(this.address))}async decimals(){return this.sdk.provider.readContract(s(this.address))}async isConfidential(){return this.sdk.provider.readContract(x(this.address,g))}async isWrapper(){return this.sdk.provider.readContract(x(this.address,p))}async balanceOf(e){return this.decryptBalance(e,`balance-of`)}async decryptBalance(e,t){let n=j(e),r=await this.readConfidentialBalanceOf(n),i=(await this.sdk.decryption.decryptValues([{encryptedValue:r,contractAddress:this.address}],{operation:t}))[r];if(i===void 0)throw new k(`Decryption returned no value for ${r}`);return u(i,`balanceOf: result[encryptedValue]`),i}async confidentialBalanceOf(e){return this.readConfidentialBalanceOf(j(e))}async decryptBalanceAs({delegatorAddress:e,accountAddress:t}){await m(`decryptBalanceAs`,this.sdk.signer,this.sdk.provider);let n=j(e),r=t?j(t):n,i=await this.readConfidentialBalanceOf(r);if(U(i))return 0n;let a=(await this.sdk.decryption.delegatedDecryptValues([{encryptedValue:i,contractAddress:this.address}],n,r,{operation:`decrypt-balance-as`}))[i];if(a===void 0)throw new k(`Delegated decryption returned no value for ${i}`);return u(a,`decryptBalanceAs: result[encryptedValue]`),a}static async batchBalancesOf(e,t){let n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map;if(e.length===0)return{results:n,errors:r};let a=i.assertSameSdk(e);await m(`batchBalancesOf`,a.signer,a.provider),await a.permits.grantPermit(e.map(e=>e.address));let o=!1,s,c=await q(e.map(e=>async()=>{if(o)return{status:`aborted`};try{return{status:`fulfilled`,value:await e.decryptBalance(t,`batch-balances-of`)}}catch(e){return A(e)?(o=!0,s??=e,{status:`aborted`}):{status:`rejected`,reason:e}}}),5);if(s!==void 0)throw s;for(let t=0;t<e.length;t++){let i=e[t].address,a=c[t];if(a.status!==`aborted`){if(a.status===`fulfilled`)n.set(i,a.value);else{let e=a.reason,t=e instanceof E?e:new k(C(e).message,{cause:e});r.set(i,t)}}}if(r.size===e.length)throw r.values().next().value??new k(`All token balance decryptions failed`);return{results:n,errors:r}}static async batchDecryptBalancesAs(e,t){if(e.length===0)return/* @__PURE__ */ new Map;let n=i.assertSameSdk(e),r=/* @__PURE__ */ new Map,a=/* @__PURE__ */ new Map,o=t.accountAddress?j(t.accountAddress):j(t.delegatorAddress),s=t.maxConcurrency??10;if(t.encryptedValues&&e.length!==t.encryptedValues.length)throw new k(`tokens.length (${e.length}) must equal encryptedValues.length (${t.encryptedValues.length})`);let c=t.encryptedValues??await i.readBalanceHandlesBatch(e,o,a,s),l=[];for(let[t,n]of e.entries()){let e=c[t];e&&!a.has(n.address)&&(U(e)?r.set(n.address,0n):l.push({token:n,encryptedValue:e}))}if(l.length>0){let e=await n.decryption.delegatedBatchDecryptValues({encryptedInputs:l.map(({token:e,encryptedValue:t})=>({encryptedValue:t,contractAddress:e.address})),delegatorAddress:t.delegatorAddress,accountAddress:t.accountAddress,maxConcurrency:s,operation:`batch-decrypt-balances-as`});for(let[t,n]of e.items.entries()){let e=l[t];if(!e)continue;if(n.error){a.set(e.token.address,n.error);continue}let i=n.value;i===void 0?a.set(e.token.address,new k(`Batch delegated decryption returned no value for ${n.encryptedValue} on token ${e.token.address}`)):(u(i,`batchDecryptBalancesAs: result[encryptedValue]`),r.set(e.token.address,i))}}if(a.size===0)return r;if(t.onError){let e=[];for(let[n,i]of a)try{r.set(n,t.onError(i,n))}catch(t){e.push({address:n,error:C(t)})}if(e.length>0){let t=e.map(({address:e,error:t})=>`${e}: ${t.message}`).join(`; `);throw new k(`Batch delegated decryption onError callback failed for ${e.length} token(s): ${t}`,{cause:e[0]?.error})}return r}let d=Array.from(a.entries()),f=d.map(([e,t])=>`${e}: ${t.message}`).join(`; `);throw new k(`Batch delegated decryption failed for ${a.size} token(s): ${f}`,{cause:d[0]?.[1]})}static async readBalanceHandlesBatch(e,t,n,r){let i=!1,a,o=await q(e.map(e=>async()=>{if(i)return{status:`aborted`};try{return{status:`fulfilled`,value:await e.readConfidentialBalanceOf(t)}}catch(e){return A(e)?(i=!0,a??=e,{status:`aborted`}):{status:`rejected`,reason:e}}}),r);if(a!==void 0)throw a;let s=[];for(let[t,r]of e.entries()){let e=o[t];e&&e.status!==`aborted`&&(e.status===`fulfilled`?s[t]=e.value:n.set(r.address,e.reason instanceof E?e.reason:new k(C(e.reason).message,{cause:e.reason})))}return s}async confidentialTransfer(e,t,n){this.#e(`confidentialTransfer`);let r=await y(`confidentialTransfer`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:i=!1,onEncryptComplete:a,onTransferSubmitted:o}=n??{},s=j(e);i||await this.assertConfidentialBalance(t,`confidential-transfer`);let{encryptedValues:c,inputProof:u}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:j(r.address)},{operation:`confidential-transfer`});if(l(`transfer: onEncryptComplete`,()=>a?.(),this.sdk.logger),c.length===0)throw new O(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transfer`,config:f(this.address,s,c[0],u),onSubmitted:o})}async confidentialTransferFrom(e,t,n,r){this.#e(`confidentialTransferFrom`);let i=await y(`confidentialTransferFrom`,this.sdk.signer,this.sdk.provider),a=j(e),o=j(t),{encryptedValues:s,inputProof:c}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:j(i.address)},{operation:`confidential-transfer-from`});if(l(`transferFrom: onEncryptComplete`,()=>r?.onEncryptComplete?.(),this.sdk.logger),s.length===0)throw new O(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFrom`,config:d(this.address,a,o,s[0],c),onSubmitted:r?.onTransferSubmitted})}async confidentialTransferAndCall(e,t,n,r){this.#e(`confidentialTransferAndCall`);let i=await y(`confidentialTransferAndCall`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:o=!1,onEncryptComplete:s,onTransferSubmitted:c}=r??{},u=j(e);o||await this.assertConfidentialBalance(t,`confidential-transfer-and-call`);let{encryptedValues:d,inputProof:f}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:j(i.address)},{operation:`confidential-transfer-and-call`});if(l(`transferAndCall: onEncryptComplete`,()=>s?.(),this.sdk.logger),d.length===0)throw new O(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferAndCall`,config:a(this.address,u,d[0],f,n),onSubmitted:c})}async confidentialTransferFromAndCall(e,n,r,i,a){this.#e(`confidentialTransferFromAndCall`);let o=await y(`confidentialTransferFromAndCall`,this.sdk.signer,this.sdk.provider),s=j(e),c=j(n),{encryptedValues:u,inputProof:d}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.address,userAddress:j(o.address)},{operation:`confidential-transfer-from-and-call`});if(l(`transferFromAndCall: onEncryptComplete`,()=>a?.onEncryptComplete?.(),this.sdk.logger),u.length===0)throw new O(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFromAndCall`,config:t(this.address,s,c,u[0],d,i),onSubmitted:a?.onTransferSubmitted})}async setOperator(e,t){this.#e(`setOperator`),await m(`setOperator`,this.sdk.signer,this.sdk.provider);let n=j(e);return this.submitTransaction({operation:`setOperator`,config:r(this.address,n,t)})}async isOperator(e,t){return this.sdk.provider.readContract(o(this.address,j(e),j(t)))}async readConfidentialBalanceOf(e){return await this.sdk.provider.readContract(n(this.address,e))}async assertConfidentialBalance(e,t){return K({operation:`assertConfidentialBalance`,tokenAddress:this.address,amount:e,signer:this.sdk.signer,provider:this.sdk.provider,readBalance:e=>this.decryptBalance(e,t)})}emit(e){this.sdk.emitEvent(e,this.address)}async submitTransaction(e){let{operation:t,config:n,onSubmitted:r}=e;return X({operation:t,signer:this.#e(t),provider:this.sdk.provider,config:n,emit:e=>this.emit(e),onSubmitted:r,logger:this.sdk.logger})}static assertSameSdk(e){let t=e[0].sdk;for(let n=1;n<e.length;n++)if(e[n].sdk!==t)throw new D(`All tokens in a batch operation must share the same ZamaSDK instance`);return t}};export{K as a,U as c,P as d,M as f,q as i,F as l,X as n,H as o,N as p,Y as r,G as s,Z as t,I as u};
2
- //# sourceMappingURL=token-CxDfm7V-.js.map
@@ -1,2 +0,0 @@
1
- import{C as e,i as t,r as n}from"./relayer-CqdiNLZH.js";import{r,t as i}from"./encryption-DDP0UpGa.js";import{B as a,H as o,K as s,L as c,M as l,U as u,V as ee,W as te,Y as ne,_ as re,b as d,n as f,q as p,rt as m,t as h,x as g,y as _,z as v}from"./alignment-CYa0d0Ud.js";import{c as y,d as b,p as x,t as ie,u as S}from"./token-CxDfm7V-.js";import{r as C,t as ae}from"./primitives-Cym-3HKa.js";import{getAddress as w,keccak256 as T,toBytes as E,zeroAddress as D}from"viem";import{z as O}from"zod/mini";function k(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}var A=class extends n{unwrapTxHash;unwrapRequestId;constructor(e,n,r){super(t.UnshieldAlreadyFinalized,e,r),this.name=`UnshieldAlreadyFinalizedError`,this.unwrapTxHash=n.unwrapTxHash,this.unwrapRequestId=n.unwrapRequestId}};const j=`InvalidUnwrapRequest`,oe=T(E(`${j}(bytes32)`)).slice(0,10);function se(e){for(let t=e;t instanceof Error;t=t.cause)if(k(t)===j||t.message.includes(j)||t.message.includes(oe))return!0;return!1}var ce=class extends n{token;registry;constructor(e,n,r){super(t.UnlistedConfidentialToken,e,r),this.name=`UnlistedConfidentialTokenError`,this.token=n.token,this.registry=n.registry}},le=class extends n{batcher;vaultId;constructor(e,n,r){super(t.VaultBatcherPaused,e,r),this.name=`VaultBatcherPausedError`,this.batcher=n.batcher,this.vaultId=n.vaultId}},ue=class extends n{batcher;batchId;state;constructor(e,n,r){super(t.VaultBatchNotDispatched,e,r),this.name=`VaultBatchNotDispatchedError`,this.batcher=n.batcher,this.batchId=n.batchId,this.state=n.state}},de=class extends n{txHash;receipt;joins;unconfirmed;constructor(e,n,r){super(t.VaultGroupJoinUnconfirmed,e,r),this.name=`VaultGroupJoinUnconfirmedError`,this.txHash=n.txHash,this.receipt=n.receipt,this.joins=n.joins,this.unconfirmed=n.unconfirmed}};const fe=[{type:`function`,name:`allowance`,inputs:[{name:`owner`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`approve`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`approveAndCall`,inputs:[{name:`spender`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`balanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`totalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`transfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`function`,name:`transferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`value`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`nonpayable`},{type:`event`,name:`Approval`,inputs:[{name:`owner`,type:`address`,indexed:!0,internalType:`address`},{name:`spender`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1},{type:`event`,name:`Transfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`value`,type:`uint256`,indexed:!1,internalType:`uint256`}],anonymous:!1}];function M(e,t,n,r=`0x`){return{address:e,abi:fe,functionName:`transferAndCall`,args:[t,n,r]}}function N(e){return e.startsWith(`0x`)?e:`0x${e}`}function P(e){return T(E(e))}function F(e){return w(N(e.slice(-40)))}function I(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return w(N(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function B(e,t){return N(L(e,t))}const V={ConfidentialTransfer:P(`ConfidentialTransfer(address,address,bytes32)`),Wrap:P(`Wrap(address,uint256,bytes32)`),UnwrapRequested:P(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:P(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function H(e){return e.topics[0]!==V.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmount:I(e.topics[3])}}function U(e){return e.topics[0]!==V.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:F(e.topics[1]),roundedAmount:z(e.data,0),encryptedWrappedAmount:B(e.data,1)}}function W(e){return e.topics[0]!==V.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}}function G(e){return e.topics[0]!==V.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}}function K(e){return H(e)??U(e)??W(e)??G(e)}function pe(e){let t=[];for(let n of e){let e=K(n);e&&t.push(e)}return t}function q(e){for(let t of e){let e=W(t);if(e)return e}return null}function me(e){for(let t of e){let e=U(t);if(e)return e}return null}const he=[V.ConfidentialTransfer,V.Wrap,V.UnwrapRequested,V.UnwrapFinalized],J={DelegatedForUserDecryption:P(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:P(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function Y(e){return e.topics[0]!==J.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function X(e){return e.topics[0]!==J.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function Z(e){return Y(e)??X(e)}function ge(e){let t=[];for(let n of e){let e=Z(n);e&&t.push(e)}return t}function _e(e){for(let t of e){let e=Y(t);if(e)return e}return null}function Q(e){for(let t of e){let e=X(t);if(e)return e}return null}const ve=[J.DelegatedForUserDecryption,J.RevokedDelegationForUserDecryption];function $(e){return`zama:pending-unshield:${ae(e)}`}const ye=O.union([O.pipe(C,O.transform(e=>({unwrapTxHash:e}))),O.pipe(O.object({version:O.literal(1),unwrapTxHash:C,unwrapRequestId:O.optional(C)}),O.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function be(e,t,n,r){r===void 0?await e.set($(t),n):await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function xe(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=ye.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Se(e,t){await e.delete($(t))}var Ce=class extends ie{#e;#t=null;#n=null;#r(e){try{return s(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(t){throw new ne(e,{cause:t})}}async underlying(){return this.#f()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#f();this.#n=await this.sdk.provider.readContract(re(e))}catch{this.#n=!1}return this.#n}async allowance(e){let t=await this.#f();return this.sdk.provider.readContract(_(t,w(e),this.address))}async shield(t,r){let i=await h(`shield`,this.sdk.signer,this.sdk.provider),a=await this.isPayable(),o=await this.#f(),s=w(i.address),c;try{c=await this.sdk.provider.readContract(g(o,s))}catch(t){throw t instanceof n?t:new S(`Could not read ERC-20 balance for shield validation (token: ${o})`,{cause:e(t)})}if(c<t)throw new x(`Insufficient ERC-20 balance: requested ${t}, available ${c} (token: ${o})`,{requested:t,available:c,token:o});return a?this.#i(t,o,s,r):this.#a(t,s,r)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?w(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:M(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(t,r){this.#r(`wrap`);let i=await h(`wrap`,this.sdk.signer,this.sdk.provider),a=await this.#f(),s=w(i.address),c;try{c=await this.sdk.provider.readContract(g(a,s))}catch(t){throw t instanceof n?t:new S(`Could not read ERC-20 balance for wrap validation (token: ${a})`,{cause:e(t)})}if(c<t)throw new x(`Insufficient ERC-20 balance: requested ${t}, available ${c} (token: ${a})`,{requested:t,available:c,token:a});let l;try{l=await this.sdk.provider.readContract(_(a,s,this.address))}catch(t){throw t instanceof n?t:new S(`Could not read ERC-20 allowance for wrap validation (token: ${a})`,{cause:e(t)})}if(l<t)throw new b(`Insufficient allowance for wrap: requested ${t}, approved ${l}. Call approveUnderlying() first (token: ${a}).`,{requested:t,available:l,token:a});let u=r?.to?w(r.to):s;return this.submitTransaction({operation:`wrap`,config:o(this.address,u,t),onSubmitted:r?.onWrapSubmitted})}async#a(e,t,n){this.#r(`shield`);let r=n?.approvalStrategy??`exact`;r!==`skip`&&await this.#m(e,r===`max`,n);let i=n?.to?w(n.to):t;return this.submitTransaction({operation:`shield:approveAndWrap`,config:o(this.address,i,e),onSubmitted:n?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let t=await h(`approveUnderlying`,this.sdk.signer,this.sdk.provider),n=await this.#f(),r=w(t.address),i=e??2n**256n-1n;return i>0n&&await this.sdk.provider.readContract(_(n,r,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:d(n,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:d(n,this.address,i)})}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.assertConfidentialBalance(e,`unshield`);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.#o(e,`unshield`);return u(`unshield: onUnwrapSubmitted`,()=>r?.(c.txHash),this.sdk.logger),this.#p(c.unwrapRequestId,c.txHash,s,o,`unshield`)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return u(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(n.txHash),this.sdk.logger),this.#p(n.unwrapRequestId,n.txHash,t,e,`unshield-all`)}async resumeUnshield(e,t){let r;try{r=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof n?e:new m(`Failed to get unwrap receipt`,{cause:e})}if(r.status===`reverted`)throw new m(`Unwrap transaction ${e} reverted, so there is nothing to resume`);let i=this.#c(r.logs);if(await this.#l(i))throw await this.#d(`resumeUnshield`),new A(`Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.`,{unwrapTxHash:e,unwrapRequestId:i});return this.#p(i,e,crypto.randomUUID(),t,`resume-unshield`)}async getPendingUnshield(){let e=await xe(this.sdk.storage,this.address);return e?await this.#u(e)?(await this.#d(`getPendingUnshield`),null):e.unwrapTxHash:null}async unwrap(e){return this.#o(e,`unwrap`)}async#o(e,t){this.#r(`unwrap`);let n=await h(`unwrap`,this.sdk.signer,this.sdk.provider),i=w(n.address),{encryptedValues:a,inputProof:o}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:i},{operation:t}),[s]=a;if(!s)throw new r(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:v(this.address,i,i,s,o)});return{...c,unwrapRequestId:this.#c(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=await h(`unwrapAll`,this.sdk.signer,this.sdk.provider),t=w(e.address),n=await this.readConfidentialBalanceOf(t);if(y(n))throw new i(`Cannot unshield: balance is zero`);let r=await this.submitTransaction({operation:`unwrapAll`,config:a(this.address,t,t,n)});return{...r,unwrapRequestId:this.#c(r.receipt.logs)}}async finalizeUnwrap(e){return this.#s(e,`finalize-unwrap`)}async#s(e,t){this.#r(`finalizeUnwrap`),await f(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let n=await this.sdk.decryption.decryptPublicValues([e],{operation:t}),r=n.clearValues[e];return te(r,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:l(this.address,e,r,n.decryptionProof)})}#c(e){let t=q(e.filter(e=>e.address===void 0||w(e.address)===this.address));if(!t)throw new m(`No UnwrapRequested event from this wrapper found in the unwrap receipt`);return t.unwrapRequestId}async#l(e){try{return await this.sdk.provider.readContract(ee(this.address,e))===D}catch{return!1}}async#u(e){let t=e.unwrapRequestId;if(t===void 0)try{let n=await this.sdk.provider.waitForTransactionReceipt(e.unwrapTxHash);t=this.#c(n.logs)}catch{return!1}return this.#l(t)}async#d(e){await u(`${e}: clearPendingUnshield`,()=>Se(this.sdk.storage,this.address),this.sdk.logger)}async#f(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(c(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#p(e,t,n,r,i){this.emit({type:p.UnshieldPhase1Submitted,txHash:t,operationId:n}),await u(`unshield: savePendingUnshield`,()=>be(this.sdk.storage,this.address,t,e),this.sdk.logger),this.emit({type:p.UnshieldPhase2Started,operationId:n}),u(`unshield: onFinalizing`,()=>r?.onFinalizing?.(),this.sdk.logger);let a;try{a=await this.#s(e,i)}catch(n){throw se(n)||n instanceof m&&await this.#l(e)?(await this.#d(`unshield`),new A(`The unwrap request was finalized concurrently — the funds were already delivered.`,{unwrapTxHash:t,unwrapRequestId:e},{cause:n})):n}return this.emit({type:p.UnshieldPhase2Submitted,txHash:a.txHash,operationId:n}),u(`unshield: onFinalizeSubmitted`,()=>r?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await this.#d(`unshield`),a}async#m(e,t,n){this.#r(`approveUnderlying`);let r=await this.#f(),i=await h(`approveUnderlying`,this.sdk.signer,this.sdk.provider),a=w(i.address),o=await this.sdk.provider.readContract(_(r,a,this.address));if(o>=e)return;o>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:d(r,this.address,0n)});let s=t?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:d(r,this.address,s),onSubmitted:n?.onApprovalSubmitted})}};export{M as C,de as D,le as E,A as O,B as S,ue as T,Q as _,V as a,P as b,H as c,pe as d,X as f,_e as g,U as h,he as i,k,Y as l,W as m,ve as n,Z as o,G as p,J as r,ge as s,Ce as t,K as u,q as v,ce as w,F as x,me as y};
2
- //# sourceMappingURL=wrapped-token-BWMNyFj2.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"wrapped-token-BWMNyFj2.js","names":["toError","ZamaErrorCode","ZamaError","DecryptionFailedError","unwrapFromBalanceContract","wrapContract","assertNonNullable","underlyingContract","finalizeUnwrapContract","swallow","unwrapRequesterContract","assertBigint","SignerNotConfiguredError","isPayableTokenContract","approveContract","requireChainAlignment","ZamaSDKEvents","TransactionRevertedError","requireAlignedWalletAccount","balanceOfContract","allowanceContract","unwrapContract","isEncryptedValueZero","InsufficientAllowanceError","InsufficientERC20BalanceError","Token","ERC20ReadFailedError","hex","checksum","extractRevertErrorName","error","cause","data","UnshieldAlreadyFinalizedError","message","options","details","INVALID_UNWRAP_REQUEST","INVALID_UNWRAP_REQUEST_SELECTOR","keccak256","toBytes","isInvalidUnwrapRequestRevert","current","UnlistedConfidentialTokenError","VaultBatcherPausedError","VaultBatchNotDispatchedError","VaultGroupJoinUnconfirmedError","erc1363Abi","transferAndCallContract","tokenAddress","to","amount","prefixHex","value","eventTopic","signature","topicToAddress","getAddress","topic","topicToBytes32","wordAt","start","index","word","wordToAddress","wordToBigInt","wordToBytes32","Topics","decodeConfidentialTransfer","log","decodeWrap","decodeUnwrapRequested","decodeUnwrapFinalized","decodeOnChainEvent","decodeOnChainEvents","events","logs","event","findUnwrapRequested","findWrap","TOKEN_TOPICS","AclTopics","decodeDelegatedForUserDecryption","decodeRevokedDelegationForUserDecryption","decodeAclEvent","decodeAclEvents","findDelegatedForUserDecryption","findRevokedDelegationForUserDecryption","ACL_TOPICS","storageKey","wrapperAddress","PendingUnshieldRequestSchema","z","savePendingUnshield","unwrapRequestId","storage","unwrapTxHash","loadPendingUnshieldRequest","key","parsed","clearPendingUnshield","WrappedToken","operation","#getUnderlying","#isPayable","underlying","owner","account","isPayableToken","userAddress","erc20Balance","#shieldViaTransferAndCall","#shieldViaApproveAndWrap","#requireSigner","recipient","allowance","strategy","#ensureAllowance","approvalAmount","skipBalanceCheck","callbacks","operationId","unwrapResult","#unwrap","onUnwrapSubmitted","#finalizeUnshield","receipt","#extractUnwrapRequestId","#isUnwrapRequestConsumed","#clearStoredPendingUnshield","pending","#isPendingUnshieldConsumed","telemetryOperation","encryptedAmount","encryptedValues","EncryptionFailedError","result","inputProof","encryptedValue","#finalizeUnwrap","clearValue","zeroAddress","#underlying","#underlyingPromise","v","finalizeResult","maxApproval"],"sources":["../../src/errors/revert.ts","../../src/errors/unshield.ts","../../src/errors/vaults.ts","../../src/abi/erc1363.abi.ts","../../src/contracts/erc1363.ts","../../src/utils/hex.ts","../../src/events/log-decoding.ts","../../src/events/onchain-events.ts","../../src/token/pending-unshield.ts","../../src/token/wrapped-token.ts"],"sourcesContent":["/**\n * Extract the decoded custom error name from a viem ContractFunctionRevertedError,\n * or `null` when the error carries no structured revert data.\n * @internal\n */\nexport function extractRevertErrorName(error: unknown): string | null {\n if (!(error instanceof Error)) {\n return null;\n }\n const cause = error.cause;\n if (typeof cause !== \"object\" || cause === null || !(\"data\" in cause)) {\n return null;\n }\n const { data } = cause;\n if (typeof data !== \"object\" || data === null || !(\"errorName\" in data)) {\n return null;\n }\n return typeof data.errorName === \"string\" ? data.errorName : null;\n}\n","import { keccak256, toBytes, type Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\nimport { extractRevertErrorName } from \"./revert\";\n\n/** Structured details identifying the consumed unwrap request. */\nexport interface UnshieldAlreadyFinalizedDetails {\n /** Transaction hash of the original unwrap request. */\n readonly unwrapTxHash: Hex;\n /** Request identifier from the `UnwrapRequested` event. */\n readonly unwrapRequestId: EncryptedValue;\n}\n\n/**\n * The unwrap request was already finalized on-chain: the underlying ERC-20\n * tokens were delivered and there is nothing left to resume. The SDK clears\n * the persisted pending-unshield pointer before throwing, so treat this as a\n * success signal: refresh balances and dismiss any \"resume unshield\" prompt.\n */\nexport class UnshieldAlreadyFinalizedError extends ZamaError {\n /** Transaction hash of the original unwrap request. */\n readonly unwrapTxHash: Hex;\n /** Request identifier from the `UnwrapRequested` event. */\n readonly unwrapRequestId: EncryptedValue;\n\n constructor(message: string, details: UnshieldAlreadyFinalizedDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.UnshieldAlreadyFinalized, message, options);\n this.name = \"UnshieldAlreadyFinalizedError\";\n this.unwrapTxHash = details.unwrapTxHash;\n this.unwrapRequestId = details.unwrapRequestId;\n }\n}\n\nconst INVALID_UNWRAP_REQUEST = \"InvalidUnwrapRequest\";\nconst INVALID_UNWRAP_REQUEST_SELECTOR = keccak256(\n toBytes(`${INVALID_UNWRAP_REQUEST}(bytes32)`),\n).slice(0, 10);\n\n/**\n * True if `error` (or anything on its `cause` chain) is the wrapper's\n * `InvalidUnwrapRequest` custom revert. Prefers viem's structured\n * `cause.data.errorName`, falling back to message matching on the error name\n * and the raw 4-byte selector for non-viem providers.\n * @internal\n */\nexport function isInvalidUnwrapRequestRevert(error: unknown): boolean {\n for (let current = error; current instanceof Error; current = current.cause) {\n if (extractRevertErrorName(current) === INVALID_UNWRAP_REQUEST) {\n return true;\n }\n if (\n current.message.includes(INVALID_UNWRAP_REQUEST) ||\n current.message.includes(INVALID_UNWRAP_REQUEST_SELECTOR)\n ) {\n return true;\n }\n }\n return false;\n}\n","import type { Address, Hex } from \"viem\";\nimport type { TransactionReceipt } from \"../types/transaction\";\nimport type { BatchState } from \"../vaults/types\";\nimport type { VaultGroupJoin } from \"../vaults/vault-group-types\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** What an {@link UnlistedConfidentialTokenError} carries. */\nexport interface UnlistedConfidentialTokenDetails {\n /** The confidential token the registry does not list. */\n readonly token: Address;\n /** The token wrapper registry the router checks. */\n readonly registry: Address;\n}\n\n/**\n * A confidential token is not listed in the registry the vault router checks,\n * so the router would reject a transfer of it.\n */\nexport class UnlistedConfidentialTokenError extends ZamaError {\n /** The confidential token the registry does not list. */\n readonly token: Address;\n /** The token wrapper registry the router checks. */\n readonly registry: Address;\n\n constructor(message: string, details: UnlistedConfidentialTokenDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.UnlistedConfidentialToken, message, options);\n this.name = \"UnlistedConfidentialTokenError\";\n this.token = details.token;\n this.registry = details.registry;\n }\n}\n\n/** What a {@link VaultBatcherPausedError} carries. */\nexport interface VaultBatcherPausedDetails {\n /** The batcher that reported `paused()`. */\n readonly batcher: Address;\n /** The id of the group member whose leg would have joined it. */\n readonly vaultId: string;\n}\n\n/**\n * A batcher one leg of a group submission would join is paused, so the whole\n * submission would revert. Pausing gates `join` and `dispatchBatch`; quitting\n * and claiming on it still work.\n */\nexport class VaultBatcherPausedError extends ZamaError {\n /** The batcher that reported `paused()`. */\n readonly batcher: Address;\n /** The id of the group member whose leg would have joined it. */\n readonly vaultId: string;\n\n constructor(message: string, details: VaultBatcherPausedDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.VaultBatcherPaused, message, options);\n this.name = \"VaultBatcherPausedError\";\n this.batcher = details.batcher;\n this.vaultId = details.vaultId;\n }\n}\n\n/** What a {@link VaultBatchNotDispatchedError} carries. */\nexport interface VaultBatchNotDispatchedDetails {\n /** The batcher the batch belongs to. */\n readonly batcher: Address;\n /** The batch that was to be finalized. */\n readonly batchId: bigint;\n /** The state the batch is in instead. */\n readonly state: BatchState;\n}\n\n/**\n * A batch cannot be finalized because it is not `Dispatched`: it is still\n * open, or it was already settled or canceled, by a keeper or anyone else.\n */\nexport class VaultBatchNotDispatchedError extends ZamaError {\n /** The batcher the batch belongs to. */\n readonly batcher: Address;\n /** The batch that was to be finalized. */\n readonly batchId: bigint;\n /** The state the batch is in instead. */\n readonly state: BatchState;\n\n constructor(message: string, details: VaultBatchNotDispatchedDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.VaultBatchNotDispatched, message, options);\n this.name = \"VaultBatchNotDispatchedError\";\n this.batcher = details.batcher;\n this.batchId = details.batchId;\n this.state = details.state;\n }\n}\n\n/** What a {@link VaultGroupJoinUnconfirmedError} carries. */\nexport interface VaultGroupJoinUnconfirmedDetails {\n /** The mined transaction. */\n readonly txHash: Hex;\n /** Its receipt, for callers that want to inspect the logs themselves. */\n readonly receipt: TransactionReceipt;\n /** The legs whose `Joined` log the SDK matched, with the batch each landed in. */\n readonly joins: readonly VaultGroupJoin[];\n /** The ids of the members whose `Joined` log the SDK could not match; not a list of legs that did not join. */\n readonly unconfirmed: readonly string[];\n}\n\n/**\n * A group submission was mined, but the SDK could not match a `Joined` event\n * in its receipt to every leg. The router is all-or-nothing, so either the\n * transaction reverted and nothing moved, or it succeeded and *every* leg\n * joined, the `unconfirmed` ones included; look the transaction up before\n * resubmitting. `joins` gives the batch ids the SDK could read.\n */\nexport class VaultGroupJoinUnconfirmedError extends ZamaError {\n /** The mined transaction. */\n readonly txHash: Hex;\n /** Its receipt, for callers that want to inspect the logs themselves. */\n readonly receipt: TransactionReceipt;\n /** The legs whose `Joined` log the SDK matched, with the batch each landed in. */\n readonly joins: readonly VaultGroupJoin[];\n /** The ids of the members whose `Joined` log the SDK could not match; not a list of legs that did not join. */\n readonly unconfirmed: readonly string[];\n\n constructor(message: string, details: VaultGroupJoinUnconfirmedDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.VaultGroupJoinUnconfirmed, message, options);\n this.name = \"VaultGroupJoinUnconfirmedError\";\n this.txHash = details.txHash;\n this.receipt = details.receipt;\n this.joins = details.joins;\n this.unconfirmed = details.unconfirmed;\n }\n}\n","// DO NOT EDIT: generated by `pnpm abi:build` from\n// contracts/out/IERC1363.sol/IERC1363.json.\n// Regenerate after `pnpm contracts:build`; `pnpm abi:check` enforces this in CI.\nexport const erc1363Abi = [\n {\n type: \"function\",\n name: \"allowance\",\n inputs: [\n { name: \"owner\", type: \"address\", internalType: \"address\" },\n { name: \"spender\", type: \"address\", internalType: \"address\" },\n ],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"approve\",\n inputs: [\n { name: \"spender\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"approveAndCall\",\n inputs: [\n { name: \"spender\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"approveAndCall\",\n inputs: [\n { name: \"spender\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"data\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"balanceOf\",\n inputs: [{ name: \"account\", type: \"address\", internalType: \"address\" }],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"supportsInterface\",\n inputs: [{ name: \"interfaceId\", type: \"bytes4\", internalType: \"bytes4\" }],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"totalSupply\",\n inputs: [],\n outputs: [{ name: \"\", type: \"uint256\", internalType: \"uint256\" }],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"transfer\",\n inputs: [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferAndCall\",\n inputs: [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferAndCall\",\n inputs: [\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"data\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferFrom\",\n inputs: [\n { name: \"from\", type: \"address\", internalType: \"address\" },\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferFromAndCall\",\n inputs: [\n { name: \"from\", type: \"address\", internalType: \"address\" },\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n { name: \"data\", type: \"bytes\", internalType: \"bytes\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"transferFromAndCall\",\n inputs: [\n { name: \"from\", type: \"address\", internalType: \"address\" },\n { name: \"to\", type: \"address\", internalType: \"address\" },\n { name: \"value\", type: \"uint256\", internalType: \"uint256\" },\n ],\n outputs: [{ name: \"\", type: \"bool\", internalType: \"bool\" }],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"event\",\n name: \"Approval\",\n inputs: [\n { name: \"owner\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"spender\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"value\", type: \"uint256\", indexed: false, internalType: \"uint256\" },\n ],\n anonymous: false,\n },\n {\n type: \"event\",\n name: \"Transfer\",\n inputs: [\n { name: \"from\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"to\", type: \"address\", indexed: true, internalType: \"address\" },\n { name: \"value\", type: \"uint256\", indexed: false, internalType: \"uint256\" },\n ],\n anonymous: false,\n },\n] as const;\n","import type { Address, Hex } from \"viem\";\nimport { erc1363Abi } from \"../abi/erc1363.abi\";\n\n/**\n * Returns the contract config for an ERC-1363 `transferAndCall`.\n *\n * @param tokenAddress - The ERC-20 token to transfer from (the underlying, not the wrapper).\n * @param to - The recipient of the ERC-20 transfer. In `Token.shield`, this is\n * the wrapper contract whose `onTransferReceived` callback mints\n * confidential tokens to the address encoded in `data`.\n * @param amount - The amount to transfer.\n * @param data - Raw 20-byte recipient address for shield-to-other (decoded by\n * the wrapper as `address(bytes20(data))`). Empty `0x` for self-shield —\n * the wrapper falls back to `from`.\n */\nexport function transferAndCallContract(\n tokenAddress: Address,\n to: Address,\n amount: bigint,\n data: Hex = \"0x\",\n) {\n return {\n address: tokenAddress,\n abi: erc1363Abi,\n functionName: \"transferAndCall\",\n args: [to, amount, data],\n } as const;\n}\n","import type { Hex } from \"viem\";\nimport { assertCondition } from \"./assertions\";\n\n/** Normalize a un-prefixed hex payload to a 0x-prefixed `Hex` value. */\nexport function prefixHex(value: string): Hex {\n return (value.startsWith(\"0x\") ? value : `0x${value}`) as Hex;\n}\n\n/** Convert a public `Hex` value back an unprefixed format. */\nexport function unprefixHex(value: Hex): string {\n assertCondition(value.startsWith(\"0x\"), `Expected 0x-prefixed hex, got: ${value}`);\n return value.slice(2);\n}\n","/**\n * Primitives for decoding raw EVM logs without an ABI decoder.\n *\n * @internal\n */\n\nimport { getAddress, keccak256, toBytes, type Address, type Hex } from \"viem\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport { prefixHex } from \"../utils\";\n\n/** Hashes the canonical signature — `Joined(uint256,address,bytes32)`, not the declaration with parameter names. */\nexport function eventTopic(signature: string): Hex {\n return keccak256(toBytes(signature));\n}\n\nexport function topicToAddress(topic: Hex): Address {\n return getAddress(prefixHex(topic.slice(-40)));\n}\n\nexport function topicToBytes32(topic: Hex): EncryptedValue {\n // EVM topics are already 32-byte 0x-prefixed hex — cast directly\n return topic as EncryptedValue;\n}\n\nexport function wordAt(data: Hex, index: number): string {\n // data starts with \"0x\", each word is 64 hex chars (32 bytes)\n const start = 2 + index * 64;\n const word = data.slice(start, start + 64);\n return word.length === 64 ? word : word.padEnd(64, \"0\");\n}\n\nexport function wordToAddress(data: Hex, index: number): Address {\n return getAddress(prefixHex(wordAt(data, index).slice(-40)));\n}\n\nexport function wordToBigInt(data: Hex, index: number): bigint {\n return BigInt(\"0x\" + wordAt(data, index));\n}\n\nexport function wordToBytes32(data: Hex, index: number): EncryptedValue {\n // wordAt returns exactly 64 hex chars — prefix and cast directly\n return prefixHex(wordAt(data, index)) as EncryptedValue;\n}\n","/**\n * Framework-agnostic event decoders for confidential token contracts.\n * Works with raw log data from any provider.\n */\n\nimport type { EncryptedValue } from \"../relayer/types\";\nimport type { Address } from \"viem\";\nimport type { RawLog } from \"../types/transaction\";\nimport {\n eventTopic,\n topicToAddress,\n topicToBytes32,\n wordToAddress,\n wordToBigInt,\n wordToBytes32,\n} from \"./log-decoding\";\nexport type { RawLog } from \"../types/transaction\";\n\n// ---------------------------------------------------------------------------\n// Event topic0 constants (keccak256 of canonical signature)\n// ---------------------------------------------------------------------------\n\n/**\n * Event topic0 constants (keccak256 of the canonical Solidity signature).\n * Pass to `getLogs({ topics: [Object.values(Topics)] })` to fetch all events.\n */\nexport const Topics = {\n /** `ConfidentialTransfer(address indexed from, address indexed to, bytes32 indexed amount)` */\n ConfidentialTransfer: eventTopic(\"ConfidentialTransfer(address,address,bytes32)\"),\n /** `Wrap(address indexed to, uint256 roundedAmount, euint64 encryptedWrappedAmount)` */\n Wrap: eventTopic(\"Wrap(address,uint256,bytes32)\"),\n /** `UnwrapRequested(address indexed receiver, bytes32 indexed unwrapRequestId, bytes32 amount)` */\n UnwrapRequested: eventTopic(\"UnwrapRequested(address,bytes32,bytes32)\"),\n /** `UnwrapFinalized(address indexed receiver, bytes32 indexed unwrapRequestId, bytes32 encryptedAmount, uint64 cleartextAmount)` */\n UnwrapFinalized: eventTopic(\"UnwrapFinalized(address,bytes32,bytes32,uint64)\"),\n} as const;\n\n// ---------------------------------------------------------------------------\n// Typed event interfaces\n// ---------------------------------------------------------------------------\n\n/** Decoded `ConfidentialTransfer` event — an encrypted token transfer. */\nexport interface ConfidentialTransferEvent {\n /** Event name discriminant. */\n readonly eventName: \"ConfidentialTransfer\";\n /** Sender address. */\n readonly from: Address;\n /** Receiver address. */\n readonly to: Address;\n /** FHE encrypted value for the transferred amount. */\n readonly encryptedAmount: EncryptedValue;\n}\n\n/**\n * Decoded `Wrap` event — an ERC-20 shield (wrap) operation. Emitted alongside a\n * `ConfidentialTransfer(from=zeroAddress, ...)`; `encryptedWrappedAmount` is the same FHE\n * handle that lands in `ConfidentialTransfer.encryptedAmount`.\n */\nexport interface WrapEvent {\n /** Event name discriminant. */\n readonly eventName: \"Wrap\";\n /** Receiver of the minted confidential tokens. */\n readonly to: Address;\n /** Cleartext underlying ERC-20 tokens deposited, rounded down to a multiple of the rate. */\n readonly roundedAmount: bigint;\n /** FHE encrypted value for the wrapped (minted) amount. */\n readonly encryptedWrappedAmount: EncryptedValue;\n}\n\n/** Decoded `UnwrapRequested` event — an unshield request submitted. */\nexport interface UnwrapRequestedEvent {\n /** Event name discriminant. */\n readonly eventName: \"UnwrapRequested\";\n /** Address that will receive the unwrapped ERC-20 tokens. */\n readonly receiver: Address;\n /** FHE encrypted value for the requested unshield amount. */\n readonly encryptedAmount: EncryptedValue;\n /** Request identifier from the `UnwrapRequested` event topic. */\n readonly unwrapRequestId: EncryptedValue;\n}\n\n/** Decoded `UnwrapFinalized` event — an unshield completed on-chain. */\nexport interface UnwrapFinalizedEvent {\n /** Event name discriminant. */\n readonly eventName: \"UnwrapFinalized\";\n /** Address receiving the unwrapped ERC-20 tokens. */\n readonly receiver: Address;\n /** FHE encrypted value of the burnt confidential balance. */\n readonly encryptedAmount: EncryptedValue;\n /** Cleartext amount of underlying ERC-20 tokens returned. */\n readonly cleartextAmount: bigint;\n /** Request identifier from the `UnwrapFinalized` event topic. */\n readonly unwrapRequestId: EncryptedValue;\n}\n\n/** Union of all decoded confidential token event types. */\nexport type OnChainEvent =\n | ConfidentialTransferEvent\n | WrapEvent\n | UnwrapRequestedEvent\n | UnwrapFinalizedEvent;\n\n// ---------------------------------------------------------------------------\n// Individual decoders\n// ---------------------------------------------------------------------------\n\n/**\n * ConfidentialTransfer(address indexed from, address indexed to, bytes32 indexed amount)\n * All 3 params indexed → topics[1..3], no data.\n */\nexport function decodeConfidentialTransfer(log: RawLog): ConfidentialTransferEvent | null {\n if (log.topics[0] !== Topics.ConfidentialTransfer) {\n return null;\n }\n if (log.topics.length < 4) {\n return null;\n }\n\n return {\n eventName: \"ConfidentialTransfer\",\n from: topicToAddress(log.topics[1]!),\n to: topicToAddress(log.topics[2]!),\n encryptedAmount: topicToBytes32(log.topics[3]!),\n };\n}\n\n/**\n * Wrap(address indexed to, uint256 roundedAmount, euint64 encryptedWrappedAmount)\n * Indexed: to (topics[1])\n * Data: roundedAmount (uint256), encryptedWrappedAmount (bytes32)\n */\nexport function decodeWrap(log: RawLog): WrapEvent | null {\n if (log.topics[0] !== Topics.Wrap) {\n return null;\n }\n if (log.topics.length < 2) {\n return null;\n }\n\n return {\n eventName: \"Wrap\",\n to: topicToAddress(log.topics[1]!),\n roundedAmount: wordToBigInt(log.data, 0),\n encryptedWrappedAmount: wordToBytes32(log.data, 1),\n };\n}\n\n/**\n * UnwrapRequested(address indexed receiver, bytes32 indexed unwrapRequestId, bytes32 amount)\n */\nexport function decodeUnwrapRequested(log: RawLog): UnwrapRequestedEvent | null {\n if (log.topics[0] !== Topics.UnwrapRequested) {\n return null;\n }\n if (log.topics.length < 3) {\n return null;\n }\n\n return {\n eventName: \"UnwrapRequested\",\n receiver: topicToAddress(log.topics[1]!),\n unwrapRequestId: topicToBytes32(log.topics[2]!),\n encryptedAmount: wordToBytes32(log.data, 0),\n };\n}\n\n/**\n * UnwrapFinalized(address indexed receiver, bytes32 indexed unwrapRequestId, bytes32 encryptedAmount, uint64 cleartextAmount)\n */\nexport function decodeUnwrapFinalized(log: RawLog): UnwrapFinalizedEvent | null {\n if (log.topics[0] !== Topics.UnwrapFinalized) {\n return null;\n }\n if (log.topics.length < 3) {\n return null;\n }\n\n return {\n eventName: \"UnwrapFinalized\",\n receiver: topicToAddress(log.topics[1]!),\n unwrapRequestId: topicToBytes32(log.topics[2]!),\n encryptedAmount: wordToBytes32(log.data, 0),\n cleartextAmount: wordToBigInt(log.data, 1),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Convenience helpers\n// ---------------------------------------------------------------------------\n\n/**\n * Try all decoders on a single log and return the first match, or `null`.\n *\n * @example\n * ```ts\n * const event = decodeOnChainEvent(log);\n * if (event?.eventName === \"ConfidentialTransfer\") {\n * console.log(event.from, event.to);\n * }\n * ```\n */\nexport function decodeOnChainEvent(log: RawLog): OnChainEvent | null {\n return (\n decodeConfidentialTransfer(log) ??\n decodeWrap(log) ??\n decodeUnwrapRequested(log) ??\n decodeUnwrapFinalized(log)\n );\n}\n\n/**\n * Batch-decode an array of logs, skipping unrecognized entries.\n *\n * @example\n * ```ts\n * const events = decodeOnChainEvents(receipt.logs);\n * ```\n */\nexport function decodeOnChainEvents(logs: readonly RawLog[]): OnChainEvent[] {\n const events: OnChainEvent[] = [];\n for (const log of logs) {\n const event = decodeOnChainEvent(log);\n if (event) {\n events.push(event);\n }\n }\n return events;\n}\n\n/**\n * Find the first {@link UnwrapRequestedEvent} in a logs array.\n *\n * @example\n * ```ts\n * const event = findUnwrapRequested(receipt.logs);\n * if (event) console.log(event.receiver, event.encryptedAmount);\n * ```\n */\nexport function findUnwrapRequested(logs: readonly RawLog[]): UnwrapRequestedEvent | null {\n for (const log of logs) {\n const event = decodeUnwrapRequested(log);\n if (event) {\n return event;\n }\n }\n return null;\n}\n\n/**\n * Find the first {@link WrapEvent} in a logs array.\n *\n * @example\n * ```ts\n * const event = findWrap(receipt.logs);\n * if (event) console.log(event.to, event.roundedAmount);\n * ```\n */\nexport function findWrap(logs: readonly RawLog[]): WrapEvent | null {\n for (const log of logs) {\n const event = decodeWrap(log);\n if (event) {\n return event;\n }\n }\n return null;\n}\n\n/**\n * All confidential token event topic0 hashes.\n * Pass to `getLogs({ topics: [TOKEN_TOPICS] })` to fetch\n * all confidential token events in a single RPC call.\n */\nexport const TOKEN_TOPICS = [\n Topics.ConfidentialTransfer,\n Topics.Wrap,\n Topics.UnwrapRequested,\n Topics.UnwrapFinalized,\n] as const;\n\n// ---------------------------------------------------------------------------\n// ACL delegation event topic0 constants\n// ---------------------------------------------------------------------------\n\n/**\n * ACL delegation event topic0 constants (keccak256 of the canonical Solidity signature).\n * These are ACL events, NOT token events — they are emitted by the ACL contract.\n */\nexport const AclTopics = {\n /** `DelegatedForUserDecryption(address indexed delegator, address indexed delegate, address contractAddress, uint64 delegationCounter, uint64 oldExpirationDate, uint64 newExpirationDate)` */\n DelegatedForUserDecryption: eventTopic(\n \"DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)\",\n ),\n /** `RevokedDelegationForUserDecryption(address indexed delegator, address indexed delegate, address contractAddress, uint64 delegationCounter, uint64 oldExpirationDate)` */\n RevokedDelegationForUserDecryption: eventTopic(\n \"RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)\",\n ),\n} as const;\n\n// ---------------------------------------------------------------------------\n// ACL delegation event interfaces\n// ---------------------------------------------------------------------------\n\n/** Decoded `DelegatedForUserDecryption` event — a delegation was created or renewed. */\nexport interface DelegatedForUserDecryptionEvent {\n /** Event name discriminant. */\n readonly eventName: \"DelegatedForUserDecryption\";\n /** Address of the delegator (the account granting access). */\n readonly delegator: Address;\n /** Address of the delegate (the account receiving access). */\n readonly delegate: Address;\n /** Contract address the delegation applies to. */\n readonly contractAddress: Address;\n /** Monotonic delegation counter. */\n readonly delegationCounter: bigint;\n /** Previous expiration timestamp (0 if first delegation). */\n readonly oldExpirationDate: bigint;\n /** New expiration timestamp. */\n readonly newExpirationDate: bigint;\n}\n\n/** Decoded `RevokedDelegationForUserDecryption` event — a delegation was revoked. */\nexport interface RevokedDelegationForUserDecryptionEvent {\n /** Event name discriminant. */\n readonly eventName: \"RevokedDelegationForUserDecryption\";\n /** Address of the delegator. */\n readonly delegator: Address;\n /** Address of the delegate. */\n readonly delegate: Address;\n /** Contract address the revocation applies to. */\n readonly contractAddress: Address;\n /** Monotonic delegation counter. */\n readonly delegationCounter: bigint;\n /** Expiration date that was active before revocation. */\n readonly oldExpirationDate: bigint;\n}\n\n/** Union of all decoded ACL delegation event types. */\nexport type AclEvent = DelegatedForUserDecryptionEvent | RevokedDelegationForUserDecryptionEvent;\n\n// ---------------------------------------------------------------------------\n// ACL delegation event decoders\n// ---------------------------------------------------------------------------\n\n/**\n * DelegatedForUserDecryption(address indexed delegator, address indexed delegate,\n * address contractAddress, uint64 delegationCounter, uint64 oldExpirationDate, uint64 newExpirationDate)\n * Indexed: delegator (topics[1]), delegate (topics[2])\n * Data: contractAddress, delegationCounter, oldExpirationDate, newExpirationDate\n */\nexport function decodeDelegatedForUserDecryption(\n log: RawLog,\n): DelegatedForUserDecryptionEvent | null {\n if (log.topics[0] !== AclTopics.DelegatedForUserDecryption) {\n return null;\n }\n if (log.topics.length < 3) {\n return null;\n }\n\n return {\n eventName: \"DelegatedForUserDecryption\",\n delegator: topicToAddress(log.topics[1]!),\n delegate: topicToAddress(log.topics[2]!),\n contractAddress: wordToAddress(log.data, 0),\n delegationCounter: wordToBigInt(log.data, 1),\n oldExpirationDate: wordToBigInt(log.data, 2),\n newExpirationDate: wordToBigInt(log.data, 3),\n };\n}\n\n/**\n * RevokedDelegationForUserDecryption(address indexed delegator, address indexed delegate,\n * address contractAddress, uint64 delegationCounter, uint64 oldExpirationDate)\n * Indexed: delegator (topics[1]), delegate (topics[2])\n * Data: contractAddress, delegationCounter, oldExpirationDate\n */\nexport function decodeRevokedDelegationForUserDecryption(\n log: RawLog,\n): RevokedDelegationForUserDecryptionEvent | null {\n if (log.topics[0] !== AclTopics.RevokedDelegationForUserDecryption) {\n return null;\n }\n if (log.topics.length < 3) {\n return null;\n }\n\n return {\n eventName: \"RevokedDelegationForUserDecryption\",\n delegator: topicToAddress(log.topics[1]!),\n delegate: topicToAddress(log.topics[2]!),\n contractAddress: wordToAddress(log.data, 0),\n delegationCounter: wordToBigInt(log.data, 1),\n oldExpirationDate: wordToBigInt(log.data, 2),\n };\n}\n\n/**\n * Try all ACL delegation decoders on a single log and return the first match, or `null`.\n */\nexport function decodeAclEvent(log: RawLog): AclEvent | null {\n return decodeDelegatedForUserDecryption(log) ?? decodeRevokedDelegationForUserDecryption(log);\n}\n\n/**\n * Batch-decode an array of logs for ACL delegation events, skipping unrecognized entries.\n */\nexport function decodeAclEvents(logs: readonly RawLog[]): AclEvent[] {\n const events: AclEvent[] = [];\n for (const log of logs) {\n const event = decodeAclEvent(log);\n if (event) {\n events.push(event);\n }\n }\n return events;\n}\n\n/**\n * Find the first {@link DelegatedForUserDecryptionEvent} in a logs array.\n */\nexport function findDelegatedForUserDecryption(\n logs: readonly RawLog[],\n): DelegatedForUserDecryptionEvent | null {\n for (const log of logs) {\n const event = decodeDelegatedForUserDecryption(log);\n if (event) {\n return event;\n }\n }\n return null;\n}\n\n/**\n * Find the first {@link RevokedDelegationForUserDecryptionEvent} in a logs array.\n */\nexport function findRevokedDelegationForUserDecryption(\n logs: readonly RawLog[],\n): RevokedDelegationForUserDecryptionEvent | null {\n for (const log of logs) {\n const event = decodeRevokedDelegationForUserDecryption(log);\n if (event) {\n return event;\n }\n }\n return null;\n}\n\n/**\n * Both ACL delegation event topic0 hashes.\n * Pass to `getLogs({ topics: [ACL_TOPICS] })` to fetch\n * all delegation events in a single RPC call.\n */\nexport const ACL_TOPICS = [\n AclTopics.DelegatedForUserDecryption,\n AclTopics.RevokedDelegationForUserDecryption,\n] as const;\n","import type { Address, Hex } from \"viem\";\nimport { z } from \"zod/mini\";\nimport { checksum, hex } from \"../schemas/primitives\";\nimport type { GenericStorage } from \"../types\";\nimport type { EncryptedValue } from \"../relayer/types\";\n\nconst STORAGE_PREFIX = \"zama:pending-unshield:\";\nconst CURRENT_VERSION = 1;\n\n/**\n * Persisted state for an in-progress unshield request.\n * Used to resume an interrupted unshield after page reload.\n *\n * @internal\n */\nexport interface PendingUnshieldRequest {\n /** Transaction hash of the original unwrap call. */\n readonly unwrapTxHash: Hex;\n /**\n * Request identifier from the `UnwrapRequested` event.\n * Always populated for entries persisted by this SDK version; pass it as\n * `unwrapRequestId` to `finalizeUnwrap`. Absent only when re-loading a\n * pending unshield serialized by an older SDK version that did not\n * record this field — in that case pass the `encryptedAmount` from the\n * `UnwrapRequested` event to `finalizeUnwrap` instead.\n */\n readonly unwrapRequestId?: EncryptedValue;\n}\n\ninterface StoredPendingUnshieldRequest extends PendingUnshieldRequest {\n readonly version: typeof CURRENT_VERSION;\n}\n\nfunction storageKey(wrapperAddress: Address): string {\n return `${STORAGE_PREFIX}${checksum(wrapperAddress)}`;\n}\n\nconst PendingUnshieldRequestSchema = z.union([\n z.pipe(\n hex,\n z.transform((unwrapTxHash: Hex) => ({ unwrapTxHash })),\n ),\n z.pipe(\n z.object({\n version: z.literal(CURRENT_VERSION),\n unwrapTxHash: hex,\n unwrapRequestId: z.optional(hex),\n }),\n z.transform(\n ({\n unwrapTxHash,\n unwrapRequestId,\n }: {\n version: typeof CURRENT_VERSION;\n unwrapTxHash: Hex;\n unwrapRequestId?: Hex;\n }) => ({ unwrapTxHash, unwrapRequestId }),\n ),\n ),\n]);\n\n/**\n * Persist the unwrap tx hash so an interrupted unshield can be resumed later\n * (e.g. after a page reload).\n *\n * @internal\n */\nexport async function savePendingUnshield(\n storage: GenericStorage,\n wrapperAddress: Address,\n unwrapTxHash: Hex,\n unwrapRequestId?: EncryptedValue,\n): Promise<void> {\n if (unwrapRequestId === undefined) {\n await storage.set(storageKey(wrapperAddress), unwrapTxHash);\n return;\n }\n\n await storage.set(storageKey(wrapperAddress), {\n version: CURRENT_VERSION,\n unwrapTxHash,\n unwrapRequestId,\n } satisfies StoredPendingUnshieldRequest);\n}\n\n/**\n * Load a previously saved unwrap tx hash, or `null` if none exists.\n *\n * @internal\n */\nexport async function loadPendingUnshield(\n storage: GenericStorage,\n wrapperAddress: Address,\n): Promise<Hex | null> {\n const request = await loadPendingUnshieldRequest(storage, wrapperAddress);\n return request?.unwrapTxHash ?? null;\n}\n\n/**\n * Load a previously saved unwrap request, including `unwrapRequestId` when available.\n *\n * `resumeUnshield()` only needs `unwrapTxHash`: it reloads the transaction receipt and\n * rediscovers the right finalize input from the emitted `UnwrapRequested` event.\n * Use `unwrapRequestId` directly only for custom flows that call `finalizeUnwrap()`\n * without reloading the original unwrap receipt.\n *\n * @internal\n */\nexport async function loadPendingUnshieldRequest(\n storage: GenericStorage,\n wrapperAddress: Address,\n): Promise<PendingUnshieldRequest | null> {\n const key = storageKey(wrapperAddress);\n const value = await storage.get<Hex | StoredPendingUnshieldRequest>(key);\n if (value === null || value === undefined) {\n return null;\n }\n const parsed = PendingUnshieldRequestSchema.safeParse(value);\n if (!parsed.success) {\n await storage.delete(key);\n return null;\n }\n return parsed.data as PendingUnshieldRequest;\n}\n\n/**\n * Clear the saved unwrap tx hash after a successful finalization.\n *\n * @internal\n */\nexport async function clearPendingUnshield(\n storage: GenericStorage,\n wrapperAddress: Address,\n): Promise<void> {\n await storage.delete(storageKey(wrapperAddress));\n}\n","import { getAddress, zeroAddress, type Address, type Hex } from \"viem\";\nimport {\n allowanceContract,\n approveContract,\n balanceOfContract,\n finalizeUnwrapContract,\n isPayableTokenContract,\n transferAndCallContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n unwrapRequesterContract,\n wrapContract,\n} from \"../contracts\";\nimport {\n DecryptionFailedError,\n ERC20ReadFailedError,\n EncryptionFailedError,\n InsufficientAllowanceError,\n InsufficientERC20BalanceError,\n SignerNotConfiguredError,\n TransactionRevertedError,\n UnshieldAlreadyFinalizedError,\n ZamaError,\n} from \"../errors\";\nimport { isInvalidUnwrapRequestRevert } from \"../errors/unshield\";\nimport { findUnwrapRequested } from \"../events/onchain-events\";\nimport { ZamaSDKEvents } from \"../events/sdk-events\";\nimport type { EncryptedValue } from \"../relayer/types\";\nimport type {\n GenericSigner,\n ShieldCallbacks,\n ShieldOptions,\n TransactionResult,\n UnshieldCallbacks,\n UnshieldOptions,\n UnwrapResult,\n WrapOptions,\n} from \"../types\";\nimport type { RawLog } from \"../types/transaction\";\nimport { toError } from \"../utils\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\nimport { assertBigint, assertNonNullable } from \"../utils/assertions\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport type { TelemetryOperation } from \"../telemetry\";\nimport { swallow } from \"../utils/swallow\";\nimport {\n clearPendingUnshield,\n loadPendingUnshieldRequest,\n savePendingUnshield,\n type PendingUnshieldRequest,\n} from \"./pending-unshield\";\nimport { Token } from \"./token\";\n\n/**\n * Confidential ERC-20 wrapper (ERC-7984 ERC20Wrapper).\n *\n * Extends {@link Token} with wrapper-specific operations:\n * - `shield` / `unshield` — convert between the underlying ERC-20 and confidential balance\n * - `unwrap` / `unwrapAll` / `finalizeUnwrap` — low-level two-phase primitives\n * - `underlying` / `allowance` — wrapper reads\n *\n * `WrappedToken.address` is the wrapper contract address itself — the wrapper\n * IS the confidential token.\n */\nexport class WrappedToken extends Token {\n #underlying: Address | undefined;\n #underlyingPromise: Promise<Address> | null = null;\n #isPayable: boolean | null = null;\n\n /** Resolve `sdk.signer` or throw {@link SignerNotConfiguredError} tagged with `operation`. */\n #requireSigner(operation: string): GenericSigner {\n try {\n assertNonNullable(this.sdk.signer, \"WrappedToken.sdk.signer\");\n return this.sdk.signer;\n } catch (cause) {\n throw new SignerNotConfiguredError(operation, { cause });\n }\n }\n\n // WRAPPER READS\n\n /**\n * Read the underlying ERC-20 token address from the wrapper contract.\n *\n * @returns The underlying ERC-20 token address.\n */\n async underlying(): Promise<Address> {\n return this.#getUnderlying();\n }\n\n /**\n * Check whether the underlying ERC-20 supports ERC-1363 (payable token).\n * Result is cached per WrappedToken instance (negative results included):\n * once we know an underlying does not support ERC-1363, subsequent shields\n * go straight to the `approve` + `wrap` path without re-probing.\n */\n async isPayable(): Promise<boolean> {\n if (this.#isPayable !== null) {\n return this.#isPayable;\n }\n try {\n const underlying = await this.#getUnderlying();\n this.#isPayable = await this.sdk.provider.readContract(isPayableTokenContract(underlying));\n } catch {\n this.#isPayable = false;\n }\n return this.#isPayable;\n }\n\n /**\n * Read the ERC-20 allowance granted by `owner` to this wrapper for the\n * underlying token.\n *\n * @param owner - The owner address whose allowance to read.\n * @returns The current allowance as a bigint.\n */\n async allowance(owner: Address): Promise<bigint> {\n const underlying = await this.#getUnderlying();\n return this.sdk.provider.readContract(\n allowanceContract(underlying, getAddress(owner), this.address),\n );\n }\n\n // SHIELD (ERC-20 → confidential)\n\n /**\n * Shield public ERC-20 tokens into confidential tokens.\n *\n * The execution path is decided automatically by ERC-165 introspection on\n * the underlying ERC-20:\n * - **`transferAndCall`** (single tx): when the underlying supports\n * ERC-1363, no approval is required — the wrapper's `onTransferReceived`\n * callback mints confidential tokens directly. `approvalStrategy` is\n * **ignored** on this path. See {@link ShieldPath}.\n * - **`approveAndWrap`** (two-tx fallback): otherwise, an `approve` is\n * followed by a `wrap`. Approval is controlled by `approvalStrategy`\n * (`\"exact\"` by default, `\"max\"` for unlimited, `\"skip\"` to opt out).\n *\n * The ERC-20 balance is validated before submitting (public read, no\n * signing required) so the call works for all wallet types, including\n * smart wallets.\n *\n * @param amount - The plaintext amount to shield.\n * @param options - Optional: `approvalStrategy`, `to`, callbacks.\n * @returns The transaction hash and mined receipt.\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the ERC-20 balance is less than `amount`. {@link InsufficientERC20BalanceError}\n * @throws if the ERC-20 approval or shield transaction reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await wrappedToken.shield(1000n);\n * ```\n */\n async shield(amount: bigint, options?: ShieldOptions): Promise<TransactionResult> {\n const account = await requireAlignedWalletAccount(\"shield\", this.sdk.signer, this.sdk.provider);\n\n const isPayableToken = await this.isPayable();\n const underlying = await this.#getUnderlying();\n const userAddress = getAddress(account.address);\n\n // ERC-20 balance check always runs (public read, no signing needed, works for all wallet types)\n let erc20Balance: bigint;\n try {\n erc20Balance = await this.sdk.provider.readContract(\n balanceOfContract(underlying, userAddress),\n );\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new ERC20ReadFailedError(\n `Could not read ERC-20 balance for shield validation (token: ${underlying})`,\n { cause: toError(error) },\n );\n }\n if (erc20Balance < amount) {\n throw new InsufficientERC20BalanceError(\n `Insufficient ERC-20 balance: requested ${amount}, available ${erc20Balance} (token: ${underlying})`,\n { requested: amount, available: erc20Balance, token: underlying },\n );\n }\n\n if (isPayableToken) {\n return this.#shieldViaTransferAndCall(amount, underlying, userAddress, options);\n }\n return this.#shieldViaApproveAndWrap(amount, userAddress, options);\n }\n\n async #shieldViaTransferAndCall(\n amount: bigint,\n underlying: Address,\n userAddress: Address,\n options?: ShieldOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"shield\");\n const recipient = options?.to ? getAddress(options.to) : userAddress;\n // ERC7984ERC20Wrapper.onTransferReceived decodes the recipient via\n // `address(bytes20(data))` — i.e. the first 20 bytes of `data`. We pass\n // the raw 20-byte address (not ABI-encoded), and the empty payload `0x`\n // for self-shield so the wrapper falls back to `from`.\n const data: Hex = recipient === userAddress ? \"0x\" : recipient;\n\n return this.submitTransaction({\n operation: \"shield:transferAndCall\",\n config: transferAndCallContract(underlying, this.address, amount, data),\n onSubmitted: options?.onShieldSubmitted,\n });\n }\n\n /**\n * Wrap already-approved underlying ERC-20 into confidential tokens.\n *\n * Escape hatch for splitting shield across two signatures: call\n * {@link approveUnderlying} first, then `wrap`. Most callers should use\n * {@link shield}, which routes and orchestrates approval automatically.\n *\n * Validates the ERC-20 balance and the allowance granted to this wrapper\n * (public reads, no signing) and fails early with a clear error.\n *\n * @param amount - The plaintext amount to wrap.\n * @param options - Optional `to` recipient and `onWrapSubmitted` callback.\n * @returns The transaction hash and mined receipt.\n * @throws if reading the ERC-20 balance or allowance fails. {@link ERC20ReadFailedError}\n * @throws if the ERC-20 balance is less than `amount`. {@link InsufficientERC20BalanceError}\n * @throws if the allowance granted to the wrapper is less than `amount`. {@link InsufficientAllowanceError}\n *\n * @example\n * ```ts\n * await wrappedToken.approveUnderlying(1000n);\n * await wrappedToken.wrap(1000n);\n * ```\n */\n async wrap(amount: bigint, options?: WrapOptions): Promise<TransactionResult> {\n this.#requireSigner(\"wrap\");\n const account = await requireAlignedWalletAccount(\"wrap\", this.sdk.signer, this.sdk.provider);\n const underlying = await this.#getUnderlying();\n const userAddress = getAddress(account.address);\n\n let erc20Balance: bigint;\n try {\n erc20Balance = await this.sdk.provider.readContract(\n balanceOfContract(underlying, userAddress),\n );\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new ERC20ReadFailedError(\n `Could not read ERC-20 balance for wrap validation (token: ${underlying})`,\n { cause: toError(error) },\n );\n }\n if (erc20Balance < amount) {\n throw new InsufficientERC20BalanceError(\n `Insufficient ERC-20 balance: requested ${amount}, available ${erc20Balance} (token: ${underlying})`,\n { requested: amount, available: erc20Balance, token: underlying },\n );\n }\n\n let allowance: bigint;\n try {\n allowance = await this.sdk.provider.readContract(\n allowanceContract(underlying, userAddress, this.address),\n );\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new ERC20ReadFailedError(\n `Could not read ERC-20 allowance for wrap validation (token: ${underlying})`,\n { cause: toError(error) },\n );\n }\n if (allowance < amount) {\n throw new InsufficientAllowanceError(\n `Insufficient allowance for wrap: requested ${amount}, approved ${allowance}. Call approveUnderlying() first (token: ${underlying}).`,\n { requested: amount, available: allowance, token: underlying },\n );\n }\n\n const recipient = options?.to ? getAddress(options.to) : userAddress;\n return this.submitTransaction({\n operation: \"wrap\",\n config: wrapContract(this.address, recipient, amount),\n onSubmitted: options?.onWrapSubmitted,\n });\n }\n\n async #shieldViaApproveAndWrap(\n amount: bigint,\n userAddress: Address,\n options?: ShieldOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"shield\");\n const strategy = options?.approvalStrategy ?? \"exact\";\n if (strategy !== \"skip\") {\n await this.#ensureAllowance(amount, strategy === \"max\", options);\n }\n const recipient = options?.to ? getAddress(options.to) : userAddress;\n return this.submitTransaction({\n operation: \"shield:approveAndWrap\",\n config: wrapContract(this.address, recipient, amount),\n onSubmitted: options?.onShieldSubmitted,\n });\n }\n\n /**\n * Approve this wrapper contract to spend the underlying ERC-20.\n * Defaults to max uint256. Resets to zero first if there's an existing\n * non-zero allowance (required by tokens like USDT).\n *\n * @param amount - Optional approval amount. Defaults to max uint256.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * await wrappedToken.approveUnderlying(); // max approval\n * await wrappedToken.approveUnderlying(1000n); // exact amount\n * ```\n */\n async approveUnderlying(amount?: bigint): Promise<TransactionResult> {\n this.#requireSigner(\"approveUnderlying\");\n const account = await requireAlignedWalletAccount(\n \"approveUnderlying\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const underlying = await this.#getUnderlying();\n const userAddress = getAddress(account.address);\n\n const approvalAmount = amount ?? 2n ** 256n - 1n;\n\n if (approvalAmount > 0n) {\n const currentAllowance = await this.sdk.provider.readContract(\n allowanceContract(underlying, userAddress, this.address),\n );\n\n if (currentAllowance > 0n) {\n await this.submitTransaction({\n operation: \"approveUnderlying:reset\",\n config: approveContract(underlying, this.address, 0n),\n });\n }\n }\n\n return this.submitTransaction({\n operation: \"approveUnderlying\",\n config: approveContract(underlying, this.address, approvalAmount),\n });\n }\n\n // UNSHIELD (confidential → ERC-20)\n\n /**\n * Unshield a specific amount and finalize in one call.\n * Orchestrates: unshield → wait for receipt → parse event → finalize.\n *\n * By default, the SDK validates the confidential balance before submitting.\n * Set `skipBalanceCheck: true` to bypass this validation (e.g. for smart wallets).\n *\n * @param amount - The plaintext amount to unshield.\n * @param options - Optional: `skipBalanceCheck` (default `false`), callbacks.\n * @returns The finalize transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await wrappedToken.unshield(500n);\n * ```\n */\n async unshield(amount: bigint, options?: UnshieldOptions): Promise<TransactionResult> {\n const {\n skipBalanceCheck = false,\n onUnwrapSubmitted,\n onFinalizing,\n onFinalizeSubmitted,\n } = options ?? {};\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount, \"unshield\");\n }\n\n const callbacks: UnshieldCallbacks = { onFinalizing, onFinalizeSubmitted };\n const operationId = crypto.randomUUID();\n const unwrapResult = await this.#unwrap(amount, \"unshield\");\n void swallow(\n \"unshield: onUnwrapSubmitted\",\n () => onUnwrapSubmitted?.(unwrapResult.txHash),\n this.sdk.logger,\n );\n // Reuse the id the unwrap already decoded — no second receipt fetch or decode.\n return this.#finalizeUnshield(\n unwrapResult.unwrapRequestId,\n unwrapResult.txHash,\n operationId,\n callbacks,\n \"unshield\",\n );\n }\n\n /**\n * Unshield the entire balance and finalize in one call.\n * Orchestrates: unshieldAll → wait for receipt → parse event → finalize.\n *\n * @param callbacks - Optional progress callbacks for each phase.\n * @returns The finalize transaction hash and mined receipt.\n * @throws if the balance is zero. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const txHash = await wrappedToken.unshieldAll();\n * ```\n */\n async unshieldAll(callbacks?: UnshieldCallbacks): Promise<TransactionResult> {\n const operationId = crypto.randomUUID();\n const unwrapResult = await this.unwrapAll();\n void swallow(\n \"unshieldAll: onUnwrapSubmitted\",\n () => callbacks?.onUnwrapSubmitted?.(unwrapResult.txHash),\n this.sdk.logger,\n );\n // Reuse the id `unwrapAll()` already decoded — no second receipt fetch or decode.\n return this.#finalizeUnshield(\n unwrapResult.unwrapRequestId,\n unwrapResult.txHash,\n operationId,\n callbacks,\n \"unshield-all\",\n );\n }\n\n /**\n * Resume an in-progress unshield from an existing unwrap tx hash.\n * Useful when the user already submitted the unwrap but the finalize step\n * was interrupted (e.g. page reload, network error).\n *\n * @param unwrapTxHash - The transaction hash of the previously submitted unwrap.\n * @param callbacks - Optional progress callbacks.\n * @returns The finalize transaction hash and mined receipt.\n * @throws if the unwrap request was already finalized on-chain; the persisted\n * pending-unshield state is cleared first. {@link UnshieldAlreadyFinalizedError}\n *\n * @example\n * ```ts\n * const txHash = await wrappedToken.resumeUnshield(previousUnwrapTxHash);\n * ```\n */\n async resumeUnshield(\n unwrapTxHash: Hex,\n callbacks?: UnshieldCallbacks,\n ): Promise<TransactionResult> {\n // The only entry point that starts from a bare hash, so it's the only one\n // that has to fetch the receipt and decode the id from chain.\n let receipt;\n try {\n receipt = await this.sdk.provider.waitForTransactionReceipt(unwrapTxHash);\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new TransactionRevertedError(\"Failed to get unwrap receipt\", { cause: error });\n }\n if (receipt.status === \"reverted\") {\n throw new TransactionRevertedError(\n `Unwrap transaction ${unwrapTxHash} reverted, so there is nothing to resume`,\n );\n }\n const unwrapRequestId = this.#extractUnwrapRequestId(receipt.logs);\n if (await this.#isUnwrapRequestConsumed(unwrapRequestId)) {\n await this.#clearStoredPendingUnshield(\"resumeUnshield\");\n throw new UnshieldAlreadyFinalizedError(\n \"Nothing to resume: the unwrap request was already finalized on-chain and the funds were delivered.\",\n { unwrapTxHash, unwrapRequestId },\n );\n }\n return this.#finalizeUnshield(\n unwrapRequestId,\n unwrapTxHash,\n crypto.randomUUID(),\n callbacks,\n \"resume-unshield\",\n );\n }\n\n /**\n * Return the unwrap tx hash of an unshield that was interrupted between its\n * two phases, or `null` if none is pending for this wrapper.\n *\n * The SDK persists this automatically when {@link unshield}/{@link unshieldAll}\n * submit phase 1, and clears it once phase 2 finalizes. Use the returned hash\n * to surface a \"resume\" affordance, then pass it to {@link resumeUnshield}.\n * Resuming is intentionally caller-driven — auto-resuming on load would fire a\n * wallet transaction unprompted.\n *\n * The pointer is verified on-chain before it is reported: if the unwrap\n * request was already finalized (e.g. the tab closed before the SDK could\n * clear storage), the stale pointer is cleared and `null` is returned. When\n * the verification read fails, the pointer is returned unverified: a\n * network error never deletes recovery state.\n *\n * @returns The pending unwrap tx hash, or `null`.\n *\n * @example\n * ```ts\n * const unwrapTxHash = await wrappedToken.getPendingUnshield();\n * if (unwrapTxHash) await wrappedToken.resumeUnshield(unwrapTxHash);\n * ```\n */\n async getPendingUnshield(): Promise<Hex | null> {\n const pending = await loadPendingUnshieldRequest(this.sdk.storage, this.address);\n if (!pending) {\n return null;\n }\n if (await this.#isPendingUnshieldConsumed(pending)) {\n await this.#clearStoredPendingUnshield(\"getPendingUnshield\");\n return null;\n }\n return pending.unwrapTxHash;\n }\n\n // UNSHIELD LOW-LEVEL PRIMITIVES\n\n /**\n * Request an unwrap for a specific amount. Encrypts the amount first.\n * Pass the result's `unwrapRequestId` to {@link finalizeUnwrap} once the\n * request is processed on-chain.\n *\n * @param amount - The plaintext amount to unwrap (encrypted automatically).\n * @returns The tx hash, mined receipt, and the `unwrapRequestId` for `finalizeUnwrap`.\n *\n * @example\n * ```ts\n * const result = await wrappedToken.unwrap(500n);\n * await wrappedToken.finalizeUnwrap(result.unwrapRequestId);\n * ```\n */\n async unwrap(amount: bigint): Promise<UnwrapResult> {\n return this.#unwrap(amount, \"unwrap\");\n }\n\n async #unwrap(amount: bigint, telemetryOperation: TelemetryOperation): Promise<UnwrapResult> {\n this.#requireSigner(\"unwrap\");\n const account = await requireAlignedWalletAccount(\"unwrap\", this.sdk.signer, this.sdk.provider);\n const userAddress = getAddress(account.address);\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt(\n { values: [{ value: amount, type: \"euint64\" }], contractAddress: this.address, userAddress },\n { operation: telemetryOperation },\n );\n\n const [encryptedAmount] = encryptedValues;\n if (!encryptedAmount) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n const result = await this.submitTransaction({\n operation: \"unwrap\",\n config: unwrapContract(this.address, userAddress, userAddress, encryptedAmount, inputProof),\n });\n\n return { ...result, unwrapRequestId: this.#extractUnwrapRequestId(result.receipt.logs) };\n }\n\n /**\n * Request an unwrap for the entire confidential balance.\n * Uses the on-chain encrypted balance directly (no encryption needed).\n * Throws if the balance is zero.\n *\n * @returns The tx hash, mined receipt, and the `unwrapRequestId` for `finalizeUnwrap`.\n * @throws if the balance is zero. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const result = await wrappedToken.unwrapAll();\n * await wrappedToken.finalizeUnwrap(result.unwrapRequestId);\n * ```\n */\n async unwrapAll(): Promise<UnwrapResult> {\n this.#requireSigner(\"unwrapAll\");\n const account = await requireAlignedWalletAccount(\n \"unwrapAll\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const userAddress = getAddress(account.address);\n const encryptedValue = await this.readConfidentialBalanceOf(userAddress);\n\n if (isEncryptedValueZero(encryptedValue)) {\n throw new DecryptionFailedError(\"Cannot unshield: balance is zero\");\n }\n\n const result = await this.submitTransaction({\n operation: \"unwrapAll\",\n config: unwrapFromBalanceContract(this.address, userAddress, userAddress, encryptedValue),\n });\n\n return { ...result, unwrapRequestId: this.#extractUnwrapRequestId(result.receipt.logs) };\n }\n\n /**\n * Complete an unwrap by fetching the public decryption proof and finalizing.\n * Call this once the unwrap request has been processed on-chain.\n *\n * @param unwrapRequestId - The `unwrapRequestId` from an {@link UnwrapResult}\n * (`result.unwrapRequestId`) returned by {@link unwrap} / {@link unwrapAll},\n * or one decoded from an `UnwrapRequested` event (e.g. when finalizing\n * across sessions).\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const { unwrapRequestId } = await wrappedToken.unwrap(500n);\n * await wrappedToken.finalizeUnwrap(unwrapRequestId);\n * ```\n */\n async finalizeUnwrap(unwrapRequestId: EncryptedValue): Promise<TransactionResult> {\n return this.#finalizeUnwrap(unwrapRequestId, \"finalize-unwrap\");\n }\n\n async #finalizeUnwrap(\n unwrapRequestId: EncryptedValue,\n telemetryOperation: TelemetryOperation,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"finalizeUnwrap\");\n await requireChainAlignment(\"finalizeUnwrap\", this.sdk.signer, this.sdk.provider);\n const result = await this.sdk.decryption.decryptPublicValues([unwrapRequestId], {\n operation: telemetryOperation,\n });\n const clearValue = result.clearValues[unwrapRequestId];\n assertBigint(clearValue, \"finalizeUnwrap: clearValue\");\n return this.submitTransaction({\n operation: \"finalizeUnwrap\",\n config: finalizeUnwrapContract(\n this.address,\n unwrapRequestId,\n clearValue,\n result.decryptionProof,\n ),\n });\n }\n\n // PRIVATE HELPERS\n\n /**\n * Decode the `unwrapRequestId` from an unwrap/unshield receipt's logs.\n * Only logs emitted by this wrapper count: a caller-supplied tx hash from a\n * different wrapper must fail here, not decode a foreign request id. Logs\n * without an emitter address (older custom adapters) are kept.\n * Throws when no matching `UnwrapRequested` event is found.\n */\n #extractUnwrapRequestId(logs: readonly RawLog[]): EncryptedValue {\n const ownLogs = logs.filter(\n (log) => log.address === undefined || getAddress(log.address) === this.address,\n );\n const event = findUnwrapRequested(ownLogs);\n if (!event) {\n throw new TransactionRevertedError(\n \"No UnwrapRequested event from this wrapper found in the unwrap receipt\",\n );\n }\n return event.unwrapRequestId;\n }\n\n /**\n * True only when the unwrap request is definitely gone. `unwrapRequester`\n * returns the zero address once finalize deletes the request, and the id\n * always comes from the unwrap tx's own `UnwrapRequested` event, so zero can\n * only mean \"already finalized\". A failed read returns `false`: the check\n * fails open, so a network error never heals recovery state.\n */\n async #isUnwrapRequestConsumed(unwrapRequestId: EncryptedValue): Promise<boolean> {\n try {\n const requester = await this.sdk.provider.readContract(\n unwrapRequesterContract(this.address, unwrapRequestId),\n );\n return requester === zeroAddress;\n } catch {\n return false;\n }\n }\n\n /**\n * Consumed-request check for a persisted pointer; legacy hash-only entries\n * re-derive the request id from the unwrap receipt.\n */\n async #isPendingUnshieldConsumed(pending: PendingUnshieldRequest): Promise<boolean> {\n let unwrapRequestId = pending.unwrapRequestId;\n if (unwrapRequestId === undefined) {\n try {\n const receipt = await this.sdk.provider.waitForTransactionReceipt(pending.unwrapTxHash);\n unwrapRequestId = this.#extractUnwrapRequestId(receipt.logs);\n } catch {\n return false;\n }\n }\n return this.#isUnwrapRequestConsumed(unwrapRequestId);\n }\n\n async #clearStoredPendingUnshield(operation: string): Promise<void> {\n await swallow(\n `${operation}: clearPendingUnshield`,\n () => clearPendingUnshield(this.sdk.storage, this.address),\n this.sdk.logger,\n );\n }\n\n async #getUnderlying(): Promise<Address> {\n if (this.#underlying !== undefined) {\n return this.#underlying;\n }\n if (!this.#underlyingPromise) {\n this.#underlyingPromise = this.sdk.provider\n .readContract(underlyingContract(this.address))\n .then((v) => {\n this.#underlying = v;\n this.#underlyingPromise = null;\n return v;\n })\n .catch((error) => {\n this.#underlyingPromise = null;\n throw error;\n });\n }\n return this.#underlyingPromise;\n }\n\n /**\n * Phase 2 of unshield, shared by {@link unshield}/{@link unshieldAll} (which\n * pass the id `unwrap`/`unwrapAll` already decoded) and {@link resumeUnshield}\n * (which decoded it from a fetched receipt). Persists the unwrap hash for\n * recovery, finalizes, then clears the persisted state.\n */\n async #finalizeUnshield(\n unwrapRequestId: EncryptedValue,\n unwrapTxHash: Hex,\n operationId: string,\n callbacks: UnshieldCallbacks | undefined,\n telemetryOperation: TelemetryOperation,\n ): Promise<TransactionResult> {\n this.emit({ type: ZamaSDKEvents.UnshieldPhase1Submitted, txHash: unwrapTxHash, operationId });\n await swallow(\n \"unshield: savePendingUnshield\",\n () => savePendingUnshield(this.sdk.storage, this.address, unwrapTxHash, unwrapRequestId),\n this.sdk.logger,\n );\n this.emit({ type: ZamaSDKEvents.UnshieldPhase2Started, operationId });\n void swallow(\"unshield: onFinalizing\", () => callbacks?.onFinalizing?.(), this.sdk.logger);\n let finalizeResult: TransactionResult;\n try {\n finalizeResult = await this.#finalizeUnwrap(unwrapRequestId, telemetryOperation);\n } catch (error) {\n // The id comes from this wrapper's own UnwrapRequested event and the only\n // transition to \"gone\" is a successful finalize, so this revert means a\n // concurrent finalize won the race (second tab, double click, third\n // party). The funds arrived; heal. A finalize mined as reverted carries no\n // revert reason, so for a plain revert ask the chain whether the request is gone.\n const finalizedElsewhere =\n isInvalidUnwrapRequestRevert(error) ||\n (error instanceof TransactionRevertedError &&\n (await this.#isUnwrapRequestConsumed(unwrapRequestId)));\n if (!finalizedElsewhere) {\n throw error;\n }\n await this.#clearStoredPendingUnshield(\"unshield\");\n throw new UnshieldAlreadyFinalizedError(\n \"The unwrap request was finalized concurrently — the funds were already delivered.\",\n { unwrapTxHash, unwrapRequestId },\n { cause: error },\n );\n }\n this.emit({\n type: ZamaSDKEvents.UnshieldPhase2Submitted,\n txHash: finalizeResult.txHash,\n operationId,\n });\n void swallow(\n \"unshield: onFinalizeSubmitted\",\n () => callbacks?.onFinalizeSubmitted?.(finalizeResult.txHash),\n this.sdk.logger,\n );\n // Phase 2 landed: the persisted recovery state is no longer needed.\n await this.#clearStoredPendingUnshield(\"unshield\");\n return finalizeResult;\n }\n\n async #ensureAllowance(\n amount: bigint,\n maxApproval: boolean,\n callbacks?: ShieldCallbacks,\n ): Promise<void> {\n this.#requireSigner(\"approveUnderlying\");\n const underlying = await this.#getUnderlying();\n const account = await requireAlignedWalletAccount(\n \"approveUnderlying\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const userAddress = getAddress(account.address);\n const allowance = await this.sdk.provider.readContract(\n allowanceContract(underlying, userAddress, this.address),\n );\n\n if (allowance >= amount) {\n return;\n }\n\n // Reset to zero first when there's an existing non-zero allowance.\n // Required by non-standard tokens like USDT, and also mitigates the\n // ERC-20 approve race condition for all tokens.\n if (allowance > 0n) {\n await this.submitTransaction({\n operation: \"approveUnderlying:reset\",\n config: approveContract(underlying, this.address, 0n),\n });\n }\n\n const approvalAmount = maxApproval ? 2n ** 256n - 1n : amount;\n\n await this.submitTransaction({\n operation: \"approveUnderlying\",\n config: approveContract(underlying, this.address, approvalAmount),\n onSubmitted: callbacks?.onApprovalSubmitted,\n });\n }\n}\n"],"mappings":"A,qfAKA,SAAgB6B,EAAuB,EAA+B,CACpE,GAAI,EAAEC,aAAiB,OACrB,OAAO,KAET,IAAMC,EAAQD,EAAM,MACpB,GAAI,OAAOC,GAAU,WAAYA,GAAkB,EAAE,SAAUA,GAC7D,OAAO,KAET,GAAM,CAAE,QAAS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