@zama-fhe/sdk 3.4.0-alpha.9 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/cjs/base-signer.cjs +1 -1
  2. package/dist/cjs/base-signer.cjs.map +1 -1
  3. package/dist/cjs/ethers/index.cjs +1 -1
  4. package/dist/cjs/ethers/index.cjs.map +1 -1
  5. package/dist/cjs/fhevm-relayer.cjs +1 -1
  6. package/dist/cjs/fhevm-relayer.cjs.map +1 -1
  7. package/dist/cjs/index.cjs +1 -1
  8. package/dist/cjs/index.cjs.map +1 -1
  9. package/dist/cjs/node/index.cjs.map +1 -1
  10. package/dist/cjs/query/index.cjs +1 -1
  11. package/dist/cjs/query/index.cjs.map +1 -1
  12. package/dist/cjs/relayer.cjs +1 -1
  13. package/dist/cjs/relayer.cjs.map +1 -1
  14. package/dist/cjs/sdk-events.cjs +2 -0
  15. package/dist/cjs/sdk-events.cjs.map +1 -0
  16. package/dist/cjs/token.cjs +1 -1
  17. package/dist/cjs/token.cjs.map +1 -1
  18. package/dist/cjs/viem/index.cjs +1 -1
  19. package/dist/cjs/viem/index.cjs.map +1 -1
  20. package/dist/esm/{base-signer-Ds8CoYy0.d.ts → base-signer-BvL-jMNO.d.ts} +15 -2
  21. package/dist/esm/base-signer-YpkEmlp2.js +2 -0
  22. package/dist/esm/base-signer-YpkEmlp2.js.map +1 -0
  23. package/dist/esm/chains/index.d.ts +1 -1
  24. package/dist/esm/cleartext/index.d.ts +2 -2
  25. package/dist/esm/cleartext/index.js +1 -1
  26. package/dist/esm/{cleartext-_RCZVPOe.d.ts → cleartext-CxlICeUh.d.ts} +2 -2
  27. package/dist/esm/{cleartext-DfX0GUj1.js → cleartext-Qqh5JohW.js} +2 -2
  28. package/dist/esm/{cleartext-DfX0GUj1.js.map → cleartext-Qqh5JohW.js.map} +1 -1
  29. package/dist/esm/ethers/index.d.ts +53 -5
  30. package/dist/esm/ethers/index.js +1 -1
  31. package/dist/esm/ethers/index.js.map +1 -1
  32. package/dist/esm/fhevm-relayer-4Zd4QkKq.js +2 -0
  33. package/dist/esm/fhevm-relayer-4Zd4QkKq.js.map +1 -0
  34. package/dist/esm/{zama-sdk-BhD6nWLL.d.ts → index-DLaQtvYu.d.ts} +1253 -1780
  35. package/dist/esm/index-DNofJMCK.d.ts +61 -0
  36. package/dist/esm/{index-doNE2KoX.d.ts → index-S6_V7aAH.d.ts} +10 -1
  37. package/dist/esm/index.d.ts +8 -79
  38. package/dist/esm/index.js +1 -1
  39. package/dist/esm/index.js.map +1 -1
  40. package/dist/esm/node/index.d.ts +5 -5
  41. package/dist/esm/node/index.js +1 -1
  42. package/dist/esm/node/index.js.map +1 -1
  43. package/dist/esm/query/index.d.ts +522 -3
  44. package/dist/esm/query/index.js +1 -1
  45. package/dist/esm/query/index.js.map +1 -1
  46. package/dist/esm/relayer-BWHOLVcG.js +2 -0
  47. package/dist/esm/relayer-BWHOLVcG.js.map +1 -0
  48. package/dist/esm/sdk-events-D68bJ5jT.js +2 -0
  49. package/dist/esm/sdk-events-D68bJ5jT.js.map +1 -0
  50. package/dist/esm/token-Bn8I7xAu.js +2 -0
  51. package/dist/esm/token-Bn8I7xAu.js.map +1 -0
  52. package/dist/esm/{types-Tk8PiPCk.d.ts → types-BEz-VgR_.d.ts} +6 -3
  53. package/dist/esm/{types-CELdIAFG.d.ts → types-CWPSTRF6.d.ts} +98 -146
  54. package/dist/esm/{types-DlSUyFe2.d.ts → types-Dr7AmEs1.d.ts} +3 -3
  55. package/dist/esm/viem/index.d.ts +34 -5
  56. package/dist/esm/viem/index.js +1 -1
  57. package/dist/esm/viem/index.js.map +1 -1
  58. package/dist/esm/web/index.d.ts +2 -2
  59. package/dist/esm/web/index.js +1 -1
  60. package/package.json +3 -3
  61. package/dist/cjs/wrappers-registry.cjs +0 -2
  62. package/dist/cjs/wrappers-registry.cjs.map +0 -1
  63. package/dist/esm/base-signer-9CqICeQ8.js +0 -2
  64. package/dist/esm/base-signer-9CqICeQ8.js.map +0 -1
  65. package/dist/esm/fhevm-relayer-Bb_-KFJA.js +0 -2
  66. package/dist/esm/fhevm-relayer-Bb_-KFJA.js.map +0 -1
  67. package/dist/esm/index-9Cn2VKDw.d.ts +0 -329
  68. package/dist/esm/relayer-DLlyoabr.js +0 -2
  69. package/dist/esm/relayer-DLlyoabr.js.map +0 -1
  70. package/dist/esm/token-BBGMtloT.js +0 -2
  71. package/dist/esm/token-BBGMtloT.js.map +0 -1
  72. package/dist/esm/wrappers-registry-B1GuTt5t.js +0 -2
  73. package/dist/esm/wrappers-registry-B1GuTt5t.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#readProvider","BrowserProvider","BaseSigner","#browserProvider","#directSigner","#eip1193","#unsubscribeProvider","BrowserProvider","eip1193Subscribe","#loadBrowserWalletAccount","swallow","WalletAccountNotReadyError","WalletNotConnectedError","#refreshFromEthereum","#refreshFromSigner","#resolveSigner","SignerNotConfiguredError","#walletAccountFromSigner","Contract","#accountPromise","buildZamaConfig","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/ethers/ethers-provider.ts","../../../src/ethers/ethers-signer.ts","../../../src/ethers/config.ts","../../../src/ethers/contracts.ts"],"sourcesContent":["import { ethers, BrowserProvider } from \"ethers\";\nimport type {\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n EIP1193Provider,\n Hex,\n} from \"viem\";\nimport type { GenericProvider, ReadContractConfig, TransactionReceipt } from \"../types\";\n\n/**\n * Configuration for {@link EthersProvider}.\n *\n * Two variants:\n *\n * - **EIP-1193** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally.\n *\n * - **Pre-built** — `{ provider }`: pass any ethers `Provider`\n * (e.g. `JsonRpcProvider`, `WebSocketProvider`).\n */\nexport type EthersProviderConfig = { ethereum: EIP1193Provider } | { provider: ethers.Provider };\n\n/**\n * Read-only {@link GenericProvider} backed by ethers v6.\n *\n * Use this for integrations that only need public chain reads before the user has connected their\n * wallet.\n *\n * @example\n * ```ts\n * // Dedicated RPC\n * const provider = new EthersProvider({\n * provider: new ethers.JsonRpcProvider(ALCHEMY_URL),\n * });\n *\n * // Wallet-sourced RPC (shares transport with EthersSigner)\n * const provider = new EthersProvider({ ethereum: window.ethereum });\n * ```\n */\nexport class EthersProvider implements GenericProvider {\n readonly #readProvider: ethers.Provider;\n\n constructor(config: EthersProviderConfig) {\n if (\"ethereum\" in config) {\n this.#readProvider = new BrowserProvider(config.ethereum);\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n async getChainId(): Promise<number> {\n const network = await this.#readProvider.getNetwork();\n return Number(network.chainId);\n }\n\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n const contract = new ethers.Contract(\n config.address,\n config.abi as ethers.InterfaceAbi,\n this.#readProvider,\n );\n const fn = contract.getFunction(config.functionName);\n return fn(...(config.args as readonly unknown[])) as Promise<\n ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>\n >;\n }\n\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#readProvider.getBlock(\"latest\");\n if (!block) {\n throw new Error(\"Failed to fetch latest block\");\n }\n if (block.timestamp === null) {\n throw new Error(\"Latest block has no timestamp\");\n }\n return BigInt(block.timestamp);\n }\n\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#readProvider.waitForTransaction(hash);\n if (!receipt) {\n throw new Error(\"Transaction receipt not found\");\n }\n return {\n logs: receipt.logs.map((log) => ({\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\n }\n}\n","import {\n BrowserProvider,\n Contract,\n type InterfaceAbi,\n type Signer,\n type TypedDataDomain,\n} from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport {\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n WalletNotConnectedError,\n} from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\nimport { swallow } from \"../utils\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Two variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and wallet events update `walletAccount`.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * The initial wallet account is discovered asynchronously and emitted through\n * `walletAccount` once available.\n *\n * For public chain reads, construct a separate {@link EthersProvider}.\n */\nexport type EthersSignerConfig = { ethereum: EIP1193Provider } | { signer: Signer };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner extends BaseSigner {\n readonly #browserProvider?: BrowserProvider;\n readonly #directSigner?: Signer;\n readonly #eip1193?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n #accountPromise: Promise<WalletAccount | undefined> | undefined;\n\n constructor(config: EthersSignerConfig) {\n super();\n if (\"ethereum\" in config) {\n this.#browserProvider = new BrowserProvider(config.ethereum);\n this.#eip1193 = config.ethereum;\n this.#unsubscribeProvider = eip1193Subscribe({\n provider: config.ethereum,\n getInitialWalletAccount: () => this.#loadBrowserWalletAccount(),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n } else {\n this.#directSigner = config.signer;\n this.#unsubscribeProvider = () => {};\n // The signer is constructed before `createConfig`, so it cannot reach the\n // SDK-wide logger; this best-effort refresh stays silent. A failed refresh\n // still surfaces via the typed WalletAccountNotReadyError on next use.\n void swallow(\"refresh wallet account\", async () => {\n await this.refreshWalletAccount();\n });\n }\n }\n\n override requireWalletAccount(operation: string): WalletAccount {\n const account = this.walletAccount.getSnapshot();\n if (!account && !this.walletAccount.isReady()) {\n throw new WalletAccountNotReadyError(operation);\n }\n if (!account) {\n throw new WalletNotConnectedError(operation);\n }\n return account;\n }\n\n refreshWalletAccount(): Promise<WalletAccount | undefined> {\n if (this.#eip1193) {\n return this.#refreshFromEthereum();\n }\n if (this.#directSigner) {\n return this.#refreshFromSigner(this.#directSigner);\n }\n return Promise.resolve(undefined);\n }\n\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n\n async #resolveSigner(): Promise<Signer> {\n if (this.#directSigner) {\n return this.#directSigner;\n }\n if (!this.#browserProvider) {\n throw new SignerNotConfiguredError(\"resolveSigner\");\n }\n return this.#browserProvider.getSigner();\n }\n\n async #walletAccountFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n const provider = signer.provider;\n if (!provider) {\n return undefined;\n }\n const [address, network] = await Promise.all([signer.getAddress(), provider.getNetwork()]);\n return { address: getAddress(address), chainId: Number(network.chainId) };\n }\n\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([name, fields]) => [name, [...fields]]),\n );\n const sig = await signer.signTypedData(domain as TypedDataDomain, mutableSigTypes, message);\n if (!isHex(sig)) {\n throw new TypeError(`Expected hex string, got: ${sig}`);\n }\n return sig;\n }\n\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const contract = new Contract(config.address, config.abi as InterfaceAbi, signer);\n const overrides: { gasLimit?: bigint; value?: bigint } = {};\n if (config.value !== undefined) {\n overrides.value = config.value;\n }\n if (config.gas !== undefined) {\n overrides.gasLimit = config.gas;\n }\n const fn = contract.getFunction(config.functionName);\n const tx = await fn(...(config.args as readonly unknown[]), overrides);\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n }\n\n async #refreshFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n this.#accountPromise ??= this.#walletAccountFromSigner(signer)\n .then((account) => {\n this.walletAccount.setSnapshot(account);\n return account;\n })\n .finally(() => {\n this.#accountPromise = undefined;\n });\n return this.#accountPromise;\n }\n\n async #refreshFromEthereum(): Promise<WalletAccount | undefined> {\n const account = await this.#loadBrowserWalletAccount();\n this.walletAccount.setSnapshot(account);\n return account;\n }\n\n async #loadBrowserWalletAccount(): Promise<WalletAccount | undefined> {\n const ethereum = this.#eip1193;\n if (!ethereum) {\n return undefined;\n }\n const [accounts, chainIdValue] = await Promise.all([\n ethereum.request({ method: \"eth_accounts\" }),\n ethereum.request({ method: \"eth_chainId\" }),\n ]);\n if (!Array.isArray(accounts) || typeof accounts[0] !== \"string\") {\n return undefined;\n }\n const chainId = Number(chainIdValue);\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n return undefined;\n }\n return { address: getAddress(accounts[0]), chainId };\n }\n}\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"../config/build\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { EthersProvider } from \"./ethers-provider\";\nimport { EthersSigner } from \"./ethers-signer\";\nimport type { ZamaConfigEthers } from \"./types\";\n\n/** Create a {@link ZamaConfig} from ethers types. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigEthers<TChains>,\n): ZamaConfig {\n if (\"signer\" in params && params.signer) {\n const signer = new EthersSigner({ signer: params.signer });\n if (!params.signer.provider) {\n throw new Error(\"createConfig requires a Signer with an attached provider for chain reads\");\n }\n const provider = new EthersProvider({ provider: params.signer.provider });\n return buildZamaConfig(signer, provider, params);\n }\n\n const signer = new EthersSigner({ ethereum: params.ethereum });\n const provider =\n \"provider\" in params && params.provider\n ? new EthersProvider({ provider: params.provider })\n : new EthersProvider({ ethereum: params.ethereum });\n return buildZamaConfig(signer, provider, params);\n}\n","import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { EncryptedValue } from \"../relayer/types\";\n\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\ninterface TransactionRequestConfig {\n address: Address;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n gas?: bigint;\n value?: bigint;\n}\n\ninterface EthersTransactionRequest {\n to: Address;\n data: Hex;\n gasLimit?: bigint;\n value?: bigint;\n}\n\ninterface EthersTransactionResponse {\n hash: string;\n}\n\ninterface EthersCallProvider {\n call(tx: EthersTransactionRequest): Promise<string>;\n}\n\ninterface EthersTransactionSigner extends EthersCallProvider {\n sendTransaction(tx: EthersTransactionRequest): Promise<EthersTransactionResponse>;\n}\n\nfunction toTransactionRequest(config: TransactionRequestConfig): EthersTransactionRequest {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n args: config.args as never,\n }),\n ...(config.gas !== undefined ? { gasLimit: config.gas } : {}),\n ...(config.value !== undefined ? { value: config.value } : {}),\n };\n}\n\nasync function ethersRead<T>(\n provider: EthersCallProvider,\n config: TransactionRequestConfig,\n): Promise<T> {\n const data = await provider.call(toTransactionRequest(config));\n if (!isHex(data)) {\n throw new TypeError(`Expected hex string, got: ${data}`);\n }\n return decodeFunctionResult({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n data,\n }) as T;\n}\n\nasync function ethersWrite(\n signer: EthersTransactionSigner,\n config: TransactionRequestConfig,\n): Promise<Hex> {\n const tx = await signer.sendTransaction(toTransactionRequest(config));\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\nexport function readConfidentialBalanceOfContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return ethersRead(provider, confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\nexport function readUnderlyingTokenContract(provider: EthersCallProvider, wrapperAddress: Address) {\n return ethersRead(provider, underlyingContract(wrapperAddress));\n}\n\nexport function readSupportsInterfaceContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return ethersRead(provider, supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\nexport function writeConfidentialTransferContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(\n signer,\n confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n );\n}\n\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(signer, unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof));\n}\n\nexport function writeUnwrapFromBalanceContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n );\n}\n\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, operator, until));\n}\n\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"+NAyCA,IAAa,EAAb,KAAuD,CACrD,GAEA,YAAY,EAA8B,CACpC,aAAc,EAChB,KAAKA,GAAgB,IAAIC,EAAAA,gBAAgB,EAAO,QAAQ,EAExD,KAAKD,GAAgB,EAAO,QAEhC,CAEA,MAAM,YAA8B,CAClC,IAAM,EAAU,MAAM,KAAKA,GAAc,WAAW,EACpD,OAAO,OAAO,EAAQ,OAAO,CAC/B,CAEA,MAAM,aAKJ,EACkF,CAOlF,OADW,IALU,EAAA,OAAO,SAC1B,EAAO,QACP,EAAO,IACP,KAAKA,EAEW,CAAC,CAAC,YAAY,EAAO,YAC/B,CAAC,CAAC,GAAI,EAAO,IAA2B,CAGlD,CAEA,MAAM,mBAAqC,CACzC,IAAM,EAAQ,MAAM,KAAKA,GAAc,SAAS,QAAQ,EACxD,GAAI,CAAC,EACH,MAAU,MAAM,8BAA8B,EAEhD,GAAI,EAAM,YAAc,KACtB,MAAU,MAAM,+BAA+B,EAEjD,OAAO,OAAO,EAAM,SAAS,CAC/B,CAEA,MAAM,0BAA0B,EAAwC,CACtE,IAAM,EAAU,MAAM,KAAKA,GAAc,mBAAmB,CAAI,EAChE,GAAI,CAAC,EACH,MAAU,MAAM,+BAA+B,EAEjD,MAAO,CACL,KAAM,EAAQ,KAAK,IAAK,IAAS,CAC/B,OAAQ,EAAI,OAAO,OAAQ,GAAgB,IAAM,IAAI,E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EACA,EACA,EACA,EACA,EACA,CACA,OAAO,EACL,EACAC,EAAAA,EAAuB,EAAS,EAAiB,EAAuB,CAAe,CACzF,CACF,CAEA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAY,EAAQC,EAAAA,EAAoB,EAAc,EAAU,CAAK,CAAC,CAC/E,CAEA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAY,EAAQC,EAAAA,EAAa,EAAgB,EAAI,CAAM,CAAC,CACrE,CAIA,SAAgB,EAAuB,EAA8B,EAAmB,CACtF,OAAO,EAAW,EAAUC,EAAAA,EAAsB,CAAQ,CAAC,CAC7D,CAEA,SAAgB,EAA6B,EAA8B,EAAmB,CAC5F,OAAO,EAAW,EAAUC,EAAAA,EAA4B,CAAQ,CAAC,CACnE,CAEA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAA2B,EAAU,EAAW,CAAO,CAAC,CACtF,CAEA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAqB,EAAU,CAAK,CAAC,CACnE,CAEA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAoC,EAAU,CAAY,CAAC,CACzF,CAEA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAwB,EAAU,CAAwB,CAAC,CACzF,CAEA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAiC,EAAU,CAAwB,CAAC,CAClG"}
1
+ {"version":3,"file":"index.cjs","names":["confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract","#readProvider","BrowserProvider","BaseSigner","#browserProvider","#directSigner","#eip1193","#unsubscribeProvider","BrowserProvider","eip1193Subscribe","#loadBrowserWalletAccount","swallow","WalletAccountNotReadyError","WalletNotConnectedError","#refreshFromEthereum","#refreshFromSigner","#resolveSigner","SignerNotConfiguredError","#walletAccountFromSigner","Contract","#accountPromise","buildZamaConfig"],"sources":["../../../src/ethers/contracts.ts","../../../src/ethers/ethers-provider.ts","../../../src/ethers/ethers-signer.ts","../../../src/ethers/config.ts"],"sourcesContent":["import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { EncryptedValue } from \"../relayer/types\";\n\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n finalizeUnwrapContract,\n setOperatorContract,\n supportsInterfaceContract,\n underlyingContract,\n unwrapContract,\n unwrapFromBalanceContract,\n wrapContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n getTokenPairContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n isConfidentialTokenValidContract,\n} from \"../contracts\";\n\ninterface TransactionRequestConfig {\n address: Address;\n abi: readonly unknown[];\n functionName: string;\n args: readonly unknown[];\n gas?: bigint;\n value?: bigint;\n}\n\n/** Minimal transaction request accepted by the ethers contract helpers. */\nexport interface EthersTransactionRequest {\n /** Target contract address. */\n to: Address;\n /** ABI-encoded call data. */\n data: Hex;\n /** Optional gas limit for the transaction. */\n gasLimit?: bigint;\n /** Optional native-token value to send with the call, in wei. */\n value?: bigint;\n}\n\n/** Minimal transaction response returned by an {@link EthersTransactionSigner}. */\nexport interface EthersTransactionResponse {\n /** Hash of the submitted transaction. */\n hash: string;\n}\n\n/** Minimal read-only ethers provider shape used by the read contract helpers. */\nexport interface EthersCallProvider {\n /** Performs an `eth_call` and resolves to the raw hex return data. */\n call(tx: EthersTransactionRequest): Promise<string>;\n}\n\n/** Minimal ethers signer shape used by the write contract helpers. */\nexport interface EthersTransactionSigner extends EthersCallProvider {\n /** Signs and broadcasts a transaction, resolving to the transaction response. */\n sendTransaction(tx: EthersTransactionRequest): Promise<EthersTransactionResponse>;\n}\n\nfunction toTransactionRequest(config: TransactionRequestConfig): EthersTransactionRequest {\n return {\n to: config.address,\n data: encodeFunctionData({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n args: config.args as never,\n }),\n ...(config.gas !== undefined ? { gasLimit: config.gas } : {}),\n ...(config.value !== undefined ? { value: config.value } : {}),\n };\n}\n\n/**\n * Performs an `eth_call` through an ethers provider and decodes the result with viem, so every\n * ethers-backed read — the generic {@link EthersProvider.readContract} and the pre-built\n * `readXxxContract` helpers alike — produces viem-identical shapes (small ints as `number`, named\n * tuples as keyed objects, empty output as `undefined`). ethers is the transport only; viem owns\n * encoding and decoding.\n *\n * @internal\n */\nexport async function ethersRead<T>(\n provider: EthersCallProvider,\n config: TransactionRequestConfig,\n): Promise<T> {\n const data = await provider.call(toTransactionRequest(config));\n if (!isHex(data)) {\n throw new TypeError(`Expected hex string, got: ${data}`);\n }\n return decodeFunctionResult({\n abi: config.abi as Abi,\n functionName: config.functionName as never,\n data,\n }) as T;\n}\n\nasync function ethersWrite(\n signer: EthersTransactionSigner,\n config: TransactionRequestConfig,\n): Promise<Hex> {\n const tx = await signer.sendTransaction(toTransactionRequest(config));\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n}\n\n// ── Read helpers ────────────────────────────────────────────\n\n/** Reads a token's confidential (encrypted) balance handle for `userAddress` via an ethers provider. */\nexport function readConfidentialBalanceOfContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n userAddress: Address,\n) {\n return ethersRead(provider, confidentialBalanceOfContract(tokenAddress, userAddress));\n}\n\n/** Reads the underlying ERC-20 address wrapped by a confidential wrapper via an ethers provider. */\nexport function readUnderlyingTokenContract(provider: EthersCallProvider, wrapperAddress: Address) {\n return ethersRead(provider, underlyingContract(wrapperAddress));\n}\n\n/** Reads whether a token implements the given ERC-165 interface id via an ethers provider. */\nexport function readSupportsInterfaceContract(\n provider: EthersCallProvider,\n tokenAddress: Address,\n interfaceId: Address,\n) {\n return ethersRead(provider, supportsInterfaceContract(tokenAddress, interfaceId));\n}\n\n// ── Write helpers ───────────────────────────────────────────\n\n/** Submits a confidential transfer of an encrypted amount to `to` via an ethers signer. */\nexport function writeConfidentialTransferContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(\n signer,\n confidentialTransferContract(tokenAddress, to, encryptedAmount, inputProof),\n );\n}\n\n/** Submits an unwrap of an encrypted amount from `from` to `to` on a confidential ERC-20 via an ethers signer. */\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: EncryptedValue,\n inputProof: Hex,\n) {\n return ethersWrite(signer, unwrapContract(encryptedErc20, from, to, encryptedAmount, inputProof));\n}\n\n/** Submits an unwrap of the full encrypted balance from `from` to `to` via an ethers signer. */\nexport function writeUnwrapFromBalanceContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedBalance: EncryptedValue,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\n/** Finalizes a pending unwrap request with the decrypted amount and decryption proof via an ethers signer. */\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n unwrapRequestId: EncryptedValue,\n unwrapAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, unwrapRequestId, unwrapAmountCleartext, decryptionProof),\n );\n}\n\n/** Authorizes `operator` on a token, until an optional expiry timestamp, via an ethers signer. */\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n operator: Address,\n until?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, operator, until));\n}\n\n/** Wraps `amount` of the underlying ERC-20 into confidential tokens credited to `to` via an ethers signer. */\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\n/** Reads all underlying/confidential token pairs from a wrappers registry via an ethers provider. */\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\n/** Reads the number of token pairs in a wrappers registry via an ethers provider. */\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\n/** Reads a slice of token pairs (`fromIndex` to `toIndex`) from a wrappers registry via an ethers provider. */\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\n/** Reads the token pair at `index` from a wrappers registry via an ethers provider. */\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\n/** Reads the confidential token registered for a given underlying token in a wrappers registry via an ethers provider. */\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\n/** Reads the underlying token registered for a given confidential token in a wrappers registry via an ethers provider. */\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\n/** Reads whether a confidential token is registered and valid in a wrappers registry via an ethers provider. */\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n","import { BrowserProvider } from \"ethers\";\nimport type { ethers } from \"ethers\";\nimport type {\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n EIP1193Provider,\n Hex,\n} from \"viem\";\nimport type { GenericProvider, ReadContractConfig, TransactionReceipt } from \"../types\";\nimport { ethersRead } from \"./contracts\";\n\n/**\n * Configuration for {@link EthersProvider}.\n *\n * Two variants:\n *\n * - **EIP-1193** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally.\n *\n * - **Pre-built** — `{ provider }`: pass any ethers `Provider`\n * (e.g. `JsonRpcProvider`, `WebSocketProvider`).\n */\nexport type EthersProviderConfig = { ethereum: EIP1193Provider } | { provider: ethers.Provider };\n\n/**\n * Read-only {@link GenericProvider} backed by ethers v6.\n *\n * Use this for integrations that only need public chain reads before the user has connected their\n * wallet.\n *\n * @example\n * ```ts\n * // Dedicated RPC\n * const provider = new EthersProvider({\n * provider: new ethers.JsonRpcProvider(ALCHEMY_URL),\n * });\n *\n * // Wallet-sourced RPC (shares transport with EthersSigner)\n * const provider = new EthersProvider({ ethereum: window.ethereum });\n * ```\n */\nexport class EthersProvider implements GenericProvider {\n readonly #readProvider: ethers.Provider;\n\n constructor(config: EthersProviderConfig) {\n if (\"ethereum\" in config) {\n this.#readProvider = new BrowserProvider(config.ethereum);\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n /** Return the chain ID of the connected network. */\n async getChainId(): Promise<number> {\n const network = await this.#readProvider.getNetwork();\n return Number(network.chainId);\n }\n\n /**\n * Execute a read-only call and return the decoded result.\n *\n * ethers is the transport only: the call goes out over `provider.call`, and viem does the\n * encoding and decoding (via {@link ethersRead}). That keeps the result identical to\n * `ViemProvider` — the return-type contract both providers implement — rather than re-deriving\n * viem's decoding rules (small ints as `number`, named tuples as keyed objects, empty output as\n * `undefined`) from ethers' own decoded values.\n */\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n return ethersRead(this.#readProvider, {\n address: config.address,\n abi: config.abi as readonly unknown[],\n functionName: config.functionName,\n args: config.args as readonly unknown[],\n });\n }\n\n /** Return the latest block timestamp in seconds. */\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#readProvider.getBlock(\"latest\");\n if (!block) {\n throw new Error(\"Failed to fetch latest block\");\n }\n if (block.timestamp === null) {\n throw new Error(\"Latest block has no timestamp\");\n }\n return BigInt(block.timestamp);\n }\n\n /** Wait for a transaction to be mined and return its receipt. */\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#readProvider.waitForTransaction(hash);\n if (!receipt) {\n throw new Error(\"Transaction receipt not found\");\n }\n return {\n logs: receipt.logs.map((log) => ({\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\n }\n}\n","import {\n BrowserProvider,\n Contract,\n type InterfaceAbi,\n type Signer,\n type TypedDataDomain,\n} from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport {\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n WalletNotConnectedError,\n} from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport { BaseSigner } from \"../signer/base-signer\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\nimport type { WalletAccount, WriteContractConfig } from \"../types\";\nimport { swallow } from \"../utils\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Two variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and wallet events update `walletAccount`.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * The initial wallet account is discovered asynchronously and emitted through\n * `walletAccount` once available.\n *\n * For public chain reads, construct a separate {@link EthersProvider}.\n */\nexport type EthersSignerConfig = { ethereum: EIP1193Provider } | { signer: Signer };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner extends BaseSigner {\n readonly #browserProvider?: BrowserProvider;\n readonly #directSigner?: Signer;\n readonly #eip1193?: EIP1193Provider;\n readonly #unsubscribeProvider: () => void;\n #accountPromise: Promise<WalletAccount | undefined> | undefined;\n\n constructor(config: EthersSignerConfig) {\n super();\n if (\"ethereum\" in config) {\n this.#browserProvider = new BrowserProvider(config.ethereum);\n this.#eip1193 = config.ethereum;\n this.#unsubscribeProvider = eip1193Subscribe({\n provider: config.ethereum,\n getInitialWalletAccount: () => this.#loadBrowserWalletAccount(),\n onWalletAccountChange: ({ next }) => {\n this.walletAccount.setSnapshot(next);\n },\n });\n } else {\n this.#directSigner = config.signer;\n this.#unsubscribeProvider = () => {};\n // The signer is constructed before `createConfig`, so it cannot reach the\n // SDK-wide logger; this best-effort refresh stays silent. A failed refresh\n // still surfaces via the typed WalletAccountNotReadyError on next use.\n void swallow(\"refresh wallet account\", async () => {\n await this.refreshWalletAccount();\n });\n }\n }\n\n /**\n * Return the connected wallet account, or throw {@link WalletAccountNotReadyError}\n * while the initial async lookup is pending, or {@link WalletNotConnectedError}\n * when no wallet is connected.\n */\n override requireWalletAccount(operation: string): WalletAccount {\n const account = this.walletAccount.getSnapshot();\n if (!account && !this.walletAccount.isReady()) {\n throw new WalletAccountNotReadyError(operation);\n }\n if (!account) {\n throw new WalletNotConnectedError(operation);\n }\n return account;\n }\n\n /** Re-fetch the wallet account from the provider or signer and update `walletAccount`. */\n refreshWalletAccount(): Promise<WalletAccount | undefined> {\n if (this.#eip1193) {\n return this.#refreshFromEthereum();\n }\n if (this.#directSigner) {\n return this.#refreshFromSigner(this.#directSigner);\n }\n return Promise.resolve(undefined);\n }\n\n /** Unsubscribe from the EIP-1193 provider's wallet lifecycle events. */\n protected override onDispose(): void {\n this.#unsubscribeProvider();\n }\n\n async #resolveSigner(): Promise<Signer> {\n if (this.#directSigner) {\n return this.#directSigner;\n }\n if (!this.#browserProvider) {\n throw new SignerNotConfiguredError(\"resolveSigner\");\n }\n return this.#browserProvider.getSigner();\n }\n\n async #walletAccountFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n const provider = signer.provider;\n if (!provider) {\n return undefined;\n }\n const [address, network] = await Promise.all([signer.getAddress(), provider.getNetwork()]);\n return { address: getAddress(address), chainId: Number(network.chainId) };\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([name, fields]) => [name, [...fields]]),\n );\n const sig = await signer.signTypedData(domain as TypedDataDomain, mutableSigTypes, message);\n if (!isHex(sig)) {\n throw new TypeError(`Expected hex string, got: ${sig}`);\n }\n return sig;\n }\n\n /** Send a write transaction and return the tx hash. */\n async writeContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"nonpayable\" | \"payable\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"nonpayable\" | \"payable\", TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex> {\n const signer = await this.#resolveSigner();\n const contract = new Contract(config.address, config.abi as InterfaceAbi, signer);\n const overrides: { gasLimit?: bigint; value?: bigint } = {};\n if (config.value !== undefined) {\n overrides.value = config.value;\n }\n if (config.gas !== undefined) {\n overrides.gasLimit = config.gas;\n }\n const fn = contract.getFunction(config.functionName);\n const tx = await fn(...(config.args as readonly unknown[]), overrides);\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\n }\n\n async #refreshFromSigner(signer: Signer): Promise<WalletAccount | undefined> {\n this.#accountPromise ??= this.#walletAccountFromSigner(signer)\n .then((account) => {\n this.walletAccount.setSnapshot(account);\n return account;\n })\n .finally(() => {\n this.#accountPromise = undefined;\n });\n return this.#accountPromise;\n }\n\n async #refreshFromEthereum(): Promise<WalletAccount | undefined> {\n const account = await this.#loadBrowserWalletAccount();\n this.walletAccount.setSnapshot(account);\n return account;\n }\n\n async #loadBrowserWalletAccount(): Promise<WalletAccount | undefined> {\n const ethereum = this.#eip1193;\n if (!ethereum) {\n return undefined;\n }\n const [accounts, chainIdValue] = await Promise.all([\n ethereum.request({ method: \"eth_accounts\" }),\n ethereum.request({ method: \"eth_chainId\" }),\n ]);\n if (!Array.isArray(accounts) || typeof accounts[0] !== \"string\") {\n return undefined;\n }\n const chainId = Number(chainIdValue);\n if (!Number.isSafeInteger(chainId) || chainId <= 0) {\n return undefined;\n }\n return { address: getAddress(accounts[0]), chainId };\n }\n}\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"../config/build\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { EthersProvider } from \"./ethers-provider\";\nimport { EthersSigner } from \"./ethers-signer\";\nimport type { ZamaConfigEthers } from \"./types\";\n\n/** Create a {@link ZamaConfig} from ethers types. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigEthers<TChains>,\n): ZamaConfig {\n if (\"signer\" in params && params.signer) {\n const signer = new EthersSigner({ signer: params.signer });\n if (!params.signer.provider) {\n throw new Error(\"createConfig requires a Signer with an attached provider for chain reads\");\n }\n const provider = new EthersProvider({ provider: params.signer.provider });\n return buildZamaConfig(signer, provider, params);\n }\n\n const signer = new EthersSigner({ ethereum: params.ethereum });\n const provider =\n \"provider\" in params && params.provider\n ? new EthersProvider({ provider: params.provider })\n : new EthersProvider({ ethereum: params.ethereum });\n return buildZamaConfig(signer, provider, params);\n}\n"],"mappings":"wNAqEA,SAAS,EAAqB,EAA4D,CACxF,MAAO,CACL,GAAI,EAAO,QACX,MAAA,EAAA,EAAA,mBAAA,CAAyB,CACvB,IAAK,EAAO,IACZ,aAAc,EAAO,aACrB,KAAM,EAAO,IACf,CAAC,EACD,GAAI,EAAO,MAAQ,IAAA,GAAuC,CAAC,EAA5B,CAAE,SAAU,EAAO,GAAI,EACtD,GAAI,EAAO,QAAU,IAAA,GAAsC,CAAC,EAA3B,CAAE,MAAO,EAAO,KAAM,CACzD,CACF,CAWA,eAAsB,EACpB,EACA,EACY,CACZ,IAAM,EAAO,MAAM,EAAS,KAAK,EAAqB,CAAM,CAAC,EAC7D,GAAI,EAAA,EAAA,EAAA,MAAA,CAAO,CAAI,EACb,MAAU,UAAU,6BAA6B,GAAM,EAEzD,OAAA,EAAA,EAAA,qBAAA,CAA4B,CAC1B,IAAK,EAAO,IACZ,aAAc,EAAO,aACrB,MACF,CAAC,CACH,CAEA,eAAe,EACb,EACA,EACc,CACd,IAAM,EAAK,MAAM,EAAO,gBAAgB,EAAqB,CAAM,CAAC,EACpE,GAAI,EAAA,EAAA,EAAA,MAAA,CAAO,EAAG,IAAI,EAChB,MAAU,UAAU,6BAA6B,EAAG,MAAM,EAE5D,OAAO,EAAG,IACZ,CAKA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUA,EAAAA,EAA8B,EAAc,CAAW,CAAC,CACtF,CAGA,SAAgB,EAA4B,EAA8B,EAAyB,CACjG,OAAO,EAAW,EAAUC,EAAAA,EAAmB,CAAc,CAAC,CAChE,CAGA,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,E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Q,CAAE,OAAQ,cAAe,CAAC,EAC3C,EAAS,QAAQ,CAAE,OAAQ,aAAc,CAAC,CAC5C,CAAC,EACD,GAAI,CAAC,MAAM,QAAQ,CAAQ,GAAK,OAAO,EAAS,IAAO,SACrD,OAEF,IAAM,EAAU,OAAO,CAAY,EAC/B,MAAC,OAAO,cAAc,CAAO,GAAK,GAAW,GAGjD,MAAO,CAAE,SAAA,EAAA,EAAA,WAAA,CAAoB,EAAS,EAAE,EAAG,SAAQ,CACrD,CACF,ECxMA,SAAgB,EACd,EACY,CACZ,GAAI,WAAY,GAAU,EAAO,OAAQ,CACvC,IAAM,EAAS,IAAI,EAAa,CAAE,OAAQ,EAAO,MAAO,CAAC,EACzD,GAAI,CAAC,EAAO,OAAO,SACjB,MAAU,MAAM,0EAA0E,EAG5F,OAAOe,EAAAA,EAAgB,EAAQ,IADV,EAAe,CAAE,SAAU,EAAO,OAAO,QAAS,CACjC,EAAG,CAAM,CACjD,CAOA,OAAOA,EAAAA,EAAgB,IALJ,EAAa,CAAE,SAAU,EAAO,QAAS,CAKhC,EAH1B,aAAc,GAAU,EAAO,SAC3B,IAAI,EAAe,CAAE,SAAU,EAAO,QAAS,CAAC,EAChD,IAAI,EAAe,CAAE,SAAU,EAAO,QAAS,CAAC,EACb,CAAM,CACjD"}
@@ -1,2 +1,2 @@
1
- const e=require("./relayer.cjs");let t=require("@fhevm/sdk/viem"),n=require("@fhevm/sdk/viem/cleartext"),r=require("viem");function i(e){return{id:e.id,fhevm:{contracts:{acl:{address:e.aclContractAddress},inputVerifier:{address:e.inputVerifierContractAddress},kmsVerifier:{address:e.kmsContractAddress},protocolConfig:void 0},relayerUrl:e.relayerUrl,gateway:{id:e.gatewayChainId,contracts:{decryption:{address:e.verifyingContractAddressDecryption},inputVerification:{address:e.verifyingContractAddressInputVerification}}}}}}var a=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.chain;let{timeout:a,debug:s,batchRpcCalls:c,moduleVersions:l,fheEncryptionKey:u}=e.options??{},d={publicClient:(0,r.createPublicClient)({transport:typeof this.#e.network==`string`?(0,r.http)(this.#e.network):(0,r.custom)(this.#e.network)}),chain:i(this.#e),options:{batchRpcCalls:c,moduleVersions:l,fheEncryptionKey:u}};e.cleartext?(this.#t=(0,n.createFhevmCleartextBaseClient)(d),this.#n=(0,n.createFhevmCleartextDecryptClient)(d),this.#r=(0,n.createFhevmCleartextEncryptClient)(d)):(this.#t=(0,t.createFhevmBaseClient)(d),this.#n=(0,t.createFhevmDecryptClient)(d),this.#r=(0,t.createFhevmEncryptClient)(d)),this.#i={...this.#e.auth!==void 0&&{auth:o(this.#e.auth)},...a!==void 0&&{timeout:a},...s!==void 0&&{debug:s}}}get chain(){return this.#e}#o=()=>(this.#a??=this.#r.fetchFheEncryptionKeyBytes({options:this.#i}).then(()=>this.#r.init()),this.#a);decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:{...this.#i,...e.options}}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:{...this.#i,...e.options}}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:{...this.#i,...e.options}}));encryptValue=async e=>(await this.#o(),this.#r.encryptValue({...e,options:{...this.#i,...e.options}}));encryptValues=async e=>(await this.#o(),this.#r.encryptValues({...e,options:{...this.#i,...e.options}}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:{...this.#i,...e.options}}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:{...this.#i,...e.options}}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:{...this.#i,...e.options}}));fetchFheEncryptionKeyBytes=async e=>(await this.#o(),this.#r.fetchFheEncryptionKeyBytes({...e,options:{...this.#i,...e?.options}}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>(await this.#t.init(),this.#t.parseSignedDecryptionPermit(e));generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function o(t){let n=t.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:t.value,header:t.header};case`ApiKeyCookie`:return{type:n,value:t.value,cookie:t.cookie};case`BearerToken`:return{type:n,token:t.token};default:throw new e.t(`Unknown auth type: ${String(n)}`)}}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
1
+ const e=require("./relayer.cjs");let t=require("@fhevm/sdk/viem"),n=require("@fhevm/sdk/viem/cleartext"),r=require("viem");function i(e){return{id:e.id,fhevm:{contracts:{acl:{address:e.aclContractAddress},inputVerifier:{address:e.inputVerifierContractAddress},kmsVerifier:{address:e.kmsContractAddress},protocolConfig:void 0},relayerUrl:e.relayerUrl,gateway:{id:e.gatewayChainId,contracts:{decryption:{address:e.verifyingContractAddressDecryption},inputVerification:{address:e.verifyingContractAddressInputVerification}}}}}}var a=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.chain;let{timeout:a,debug:s,batchRpcCalls:c,moduleVersions:l,fheEncryptionKey:u}=e.options??{},d=this.#e.auth?o(this.#e.auth):void 0,f={publicClient:(0,r.createPublicClient)({transport:typeof this.#e.network==`string`?(0,r.http)(this.#e.network):(0,r.custom)(this.#e.network)}),chain:i(this.#e),options:{batchRpcCalls:c,moduleVersions:l,fheEncryptionKey:u}};e.cleartext?(this.#t=(0,n.createFhevmCleartextBaseClient)(f),this.#n=(0,n.createFhevmCleartextDecryptClient)(f),this.#r=(0,n.createFhevmCleartextEncryptClient)(f)):(this.#t=(0,t.createFhevmBaseClient)(f),this.#n=(0,t.createFhevmDecryptClient)(f),this.#r=(0,t.createFhevmEncryptClient)(f)),this.#i={...d!==void 0&&{auth:d},...a!==void 0&&{timeout:a},...s!==void 0&&{debug:s}}}get chain(){return this.#e}#o=()=>(this.#a??=this.#t.fetchFheEncryptionKeyBytes({options:this.#i}).then(()=>this.#r.init()),this.#a);decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:{...this.#i,...e.options}}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:{...this.#i,...e.options}}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:{...this.#i,...e.options}}));encryptValue=async e=>(await this.#o(),this.#r.encryptValue({...e,options:{...this.#i,...e.options}}));encryptValues=async e=>(await this.#o(),this.#r.encryptValues({...e,options:{...this.#i,...e.options}}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:{...this.#i,...e.options}}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:{...this.#i,...e.options}}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:{...this.#i,...e.options}}));fetchFheEncryptionKeyBytes=async e=>(await this.#o(),this.#r.fetchFheEncryptionKeyBytes({...e,options:{...this.#i,...e?.options}}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>(await this.#t.init(),this.#t.parseSignedDecryptionPermit(e));generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function o(t){let n=t.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:t.value,header:t.header};case`ApiKeyCookie`:return{type:n,value:t.value,cookie:t.cookie};case`BearerToken`:return{type:n,token:t.token};default:throw new e.t(`Unknown auth type: ${String(n)}`)}}Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return a}});
2
2
  //# sourceMappingURL=fhevm-relayer.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"fhevm-relayer.cjs","names":["#chain","#base","#decrypt","#encrypt","#defaultOptions","#encryptInitPromise","#initEncrypt","ConfigurationError"],"sources":["../../src/chains/to-fhevm-chain.ts","../../src/relayer/fhevm-relayer.ts"],"sourcesContent":["import type { FhevmChain } from \"@fhevm/sdk/chains\";\nimport type { FheChain } from \"./types\";\n\n/**\n * Derive an `@fhevm/sdk` {@link FhevmChain} from zama-sdk's richer\n * {@link FheChain}.\n *\n * `FheChain` carries fields `@fhevm/sdk` does not model (RPC `network`,\n * `registryAddress`, `executorAddress`, cleartext signer keys); those stay on\n * `FheChain` for the token layer. This adapter projects only the subset the\n * FHE runtime needs: contract addresses, relayer URL, and gateway.\n */\nexport function toFhevmChain(chain: FheChain): FhevmChain {\n return {\n id: chain.id,\n fhevm: {\n contracts: {\n acl: { address: chain.aclContractAddress },\n inputVerifier: { address: chain.inputVerifierContractAddress },\n kmsVerifier: { address: chain.kmsContractAddress },\n protocolConfig: undefined,\n },\n relayerUrl: chain.relayerUrl,\n gateway: {\n id: chain.gatewayChainId,\n contracts: {\n decryption: { address: chain.verifyingContractAddressDecryption },\n inputVerification: { address: chain.verifyingContractAddressInputVerification },\n },\n },\n },\n } satisfies FhevmChain;\n}\n","import {\n createFhevmBaseClient,\n createFhevmDecryptClient,\n createFhevmEncryptClient,\n} from \"@fhevm/sdk/viem\";\nimport {\n createFhevmCleartextBaseClient,\n createFhevmCleartextDecryptClient,\n createFhevmCleartextEncryptClient,\n} from \"@fhevm/sdk/viem/cleartext\";\nimport { createPublicClient, custom, http } from \"viem\";\nimport { toFhevmChain } from \"../chains/to-fhevm-chain\";\nimport type { FheChain } from \"../chains/types\";\nimport type {\n FhevmBaseClient,\n FhevmClient,\n FhevmDecryptClient,\n FhevmEncryptClient,\n FhevmRelayerOptions,\n FhevmRelayerSDK,\n RelayerOptions,\n} from \"./types\";\nimport { ConfigurationError } from \"../errors\";\n\n/** Construction config for {@link FhevmRelayer}. */\nexport interface FhevmRelayerConfig {\n /** FHE chain configuration. */\n chain: FheChain;\n /**\n * Cleartext mode for local dev/test chains without FHE infrastructure — reads\n * mock cleartexts from the on-chain executor (discovered automatically)\n * instead of calling the relayer.\n */\n cleartext?: boolean;\n /**\n * Per-transport {@link RelayerOptions}: `@fhevm/sdk` client options plus a\n * default request `timeout` applied to every relayer round-trip on the chain.\n */\n options?: RelayerOptions;\n}\n\n/**\n * Single-chain FHE backend that drives `@fhevm/sdk` on the calling thread with\n * capability-scoped lazy initialization.\n * EIP-712 signing is done by the signer layer; this backend builds the typed\n * data and, on decrypt, reassembles the new SDK's signed permit from the\n * interface's params + the previously returned signature.\n *\n * @remarks\n * Each method delegates to the narrowest base, decrypt, or encrypt client,\n * adding two cross-cutting behaviors that the delegated signatures don't\n * express:\n *\n * - **Lazy init.** Each operation initializes only the capability it requires.\n * Public decrypt avoids WASM, private decrypt loads TKMS only, and encryption\n * alone loads TFHE and the FHE encryption key.\n * - **Option merging.** The chain's default options (`auth`, `timeout`, `debug`)\n * are spread in first, then the per-call `options`, so a per-call value always\n * wins over the chain default. Serialization helpers make no relayer\n * round-trip, so they inject no options.\n */\nexport class FhevmRelayer implements FhevmRelayerSDK {\n readonly #chain: FheChain;\n readonly #base: FhevmBaseClient;\n readonly #decrypt: FhevmDecryptClient;\n readonly #encrypt: FhevmEncryptClient;\n readonly #defaultOptions: Partial<FhevmRelayerOptions>;\n #encryptInitPromise: Promise<void> | undefined;\n\n /**\n * Builds capability-scoped `@fhevm/sdk` clients for the chain and captures\n * the chain's `auth`/`timeout`/`debug` as request defaults. Construction is\n * cheap; each client's one-time init is deferred to its first operation.\n */\n constructor(config: FhevmRelayerConfig) {\n this.#chain = config.chain;\n const { timeout, debug, batchRpcCalls, moduleVersions, fheEncryptionKey } =\n config.options ?? {};\n const params = {\n publicClient: createPublicClient({\n transport:\n typeof this.#chain.network === \"string\"\n ? http(this.#chain.network)\n : custom(this.#chain.network),\n }),\n chain: toFhevmChain(this.#chain),\n options: { batchRpcCalls, moduleVersions, fheEncryptionKey },\n };\n if (config.cleartext) {\n this.#base = createFhevmCleartextBaseClient(params);\n this.#decrypt = createFhevmCleartextDecryptClient(params);\n this.#encrypt = createFhevmCleartextEncryptClient(params);\n } else {\n this.#base = createFhevmBaseClient(params);\n this.#decrypt = createFhevmDecryptClient(params);\n this.#encrypt = createFhevmEncryptClient(params);\n }\n this.#defaultOptions = {\n ...(this.#chain.auth !== undefined && { auth: toFhevmAuth(this.#chain.auth) }),\n ...(timeout !== undefined && { timeout }),\n ...(debug !== undefined && { debug }),\n };\n }\n\n /** The FHE chain this backend is bound to. */\n get chain() {\n return this.#chain;\n }\n\n #initEncrypt = (): Promise<void> => {\n this.#encryptInitPromise ??= this.#encrypt\n .fetchFheEncryptionKeyBytes({ options: this.#defaultOptions })\n .then(() => this.#encrypt.init());\n return this.#encryptInitPromise;\n };\n\n /**\n * Decrypts a single publicly-decryptable value — one whose contract granted\n * public access, so no permit or key pair is needed — into its typed clear\n * value.\n *\n * @example\n * ```ts\n * const { type, value } = await relayer.decryptPublicValue({\n * encryptedValue: handle, // a bytes32 ciphertext reference\n * });\n * ```\n */\n decryptPublicValue: FhevmClient[\"decryptPublicValue\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.decryptPublicValue({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Batch form of {@link decryptPublicValue}: decrypts many publicly-decryptable\n * values in one relayer round-trip, returning their typed clear values in\n * order.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptPublicValues({\n * encryptedValues: [handleA, handleB],\n * });\n * ```\n */\n decryptPublicValues: FhevmClient[\"decryptPublicValues\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.decryptPublicValues({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Like {@link decryptPublicValues}, but also returns the KMS signature bundle —\n * the handles list, ABI-encoded cleartexts, and decryption proof — needed to\n * verify or replay the result on-chain.\n *\n * @example\n * ```ts\n * const { clearValues, checkSignaturesArgs } =\n * await relayer.decryptPublicValuesWithSignatures({ encryptedValues: [handle] });\n * // checkSignaturesArgs: { handlesList, abiEncodedCleartexts, decryptionProof }\n * ```\n */\n decryptPublicValuesWithSignatures: FhevmClient[\"decryptPublicValuesWithSignatures\"] = async (\n parameters,\n ) => {\n await this.#base.init();\n return this.#base.decryptPublicValuesWithSignatures({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Encrypts one typed input under the chain's FHE key, bound to the contract it\n * targets and the user submitting it, and returns the ciphertext handle plus\n * the input proof the contract verifies on-chain. `type` is the FHE type\n * with the `e` prefix (`\"euint64\"`, `\"ebool\"`, `\"eaddress\"`).\n *\n * @example\n * ```ts\n * const { encryptedValue, inputProof } = await relayer.encryptValue({\n * value: { type: \"euint64\", value: 1000n },\n * contractAddress: \"0xToken…\",\n * userAddress: \"0xUser…\",\n * });\n * ```\n */\n encryptValue: FhevmClient[\"encryptValue\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.encryptValue({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Batch form of {@link encryptValue}: encrypts several inputs for the same\n * contract and user in one call, returning all ciphertext handles under a\n * single shared input proof.\n *\n * @example\n * ```ts\n * const { encryptedValues, inputProof } = await relayer.encryptValues({\n * values: [\n * { type: \"euint64\", value: 1000n },\n * { type: \"ebool\", value: true },\n * ],\n * contractAddress: \"0xToken…\",\n * userAddress: \"0xUser…\",\n * });\n * ```\n */\n encryptValues: FhevmClient[\"encryptValues\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.encryptValues({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * User-decrypts a single access-controlled value: the relayer re-encrypts it\n * to the ephemeral transport key pair, gated by the signed permit, and this\n * returns the typed clear value. Build the key pair with\n * {@link generateTransportKeyPair} and the permit with\n * {@link signDecryptionPermit}.\n *\n * @example\n * ```ts\n * const { type, value } = await relayer.decryptValue({\n * encryptedValue: handle,\n * contractAddress: \"0xToken…\",\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValue: FhevmClient[\"decryptValue\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValue({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Batch form of {@link decryptValue} for values that all belong to the same\n * contract; returns the typed clear values positionally. For values spanning\n * multiple contracts, use {@link decryptValuesFromPairs}.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptValues({\n * encryptedValues: [handleA, handleB],\n * contractAddress: \"0xToken…\",\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValues: FhevmClient[\"decryptValues\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValues({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * User-decrypts values that span multiple contracts: each pair carries its own\n * `contractAddress`, so one permit covering those contracts decrypts them all\n * in a single round-trip. Returns the typed clear values positionally.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptValuesFromPairs({\n * pairs: [\n * { encryptedValue: handleA, contractAddress: \"0xTokenA…\" },\n * { encryptedValue: handleB, contractAddress: \"0xTokenB…\" },\n * ],\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValuesFromPairs: FhevmClient[\"decryptValuesFromPairs\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValuesFromPairs({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Fetches the chain's raw FHE public-key bytes — the key encryption uses —\n * served from cache unless `ignoreCache` forces a refetch. Rarely called\n * directly: {@link encryptValue}/{@link encryptValues} fetch the key for you.\n *\n * @example\n * ```ts\n * const keyBytes = await relayer.fetchFheEncryptionKeyBytes();\n * const fresh = await relayer.fetchFheEncryptionKeyBytes({ ignoreCache: true });\n * ```\n */\n fetchFheEncryptionKeyBytes: FhevmClient[\"fetchFheEncryptionKeyBytes\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.fetchFheEncryptionKeyBytes({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters?.options },\n });\n };\n\n /**\n * Builds the EIP-712 user-decrypt permit and signs it with the given signer,\n * authorizing the transport key pair to decrypt the listed contracts' values\n * for `durationSeconds` starting at `startTimestamp`. Pass `delegatorAddress`\n * to sign a delegated permit — decrypting values owned by that account instead\n * of the signer's own. Persist the result via\n * {@link serializeSignedDecryptionPermit}.\n *\n * @example\n * ```ts\n * const signedPermit = await relayer.signDecryptionPermit({\n * transportKeyPair,\n * contractAddresses: [\"0xToken…\"],\n * startTimestamp: Math.floor(Date.now() / 1000),\n * durationSeconds: 60 * 60 * 24,\n * signerAddress: \"0xUser…\",\n * signer,\n * // delegatorAddress: \"0xOwner…\", // omit for a self permit\n * });\n * ```\n */\n signDecryptionPermit: FhevmClient[\"signDecryptionPermit\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.signDecryptionPermit(parameters);\n };\n\n // Permit/key-pair helpers carry no request options. Parsing initializes the\n // capability needed to validate the restored value; serialization stays local.\n\n /**\n * Serializes a transport key pair to a hex `{ publicKey, privateKey }` pair for\n * storage or transport, so a decryption session can resume without regenerating\n * keys. Reverse of {@link parseTransportKeyPair}. Purely local — no round-trip.\n *\n * @example\n * ```ts\n * const stored = relayer.serializeTransportKeyPair({ transportKeyPair });\n * // { publicKey: \"0x…\", privateKey: \"0x…\" }\n * ```\n */\n serializeTransportKeyPair: FhevmClient[\"serializeTransportKeyPair\"] = (parameters) =>\n this.#decrypt.serializeTransportKeyPair(parameters);\n\n /**\n * Serializes a signed permit to a plain, JSON-stringifiable object (version,\n * EIP-712 payload, signature, signer) for caching or transport. Reverse of\n * {@link parseSignedDecryptionPermit}. Purely local — no round-trip.\n *\n * @example\n * ```ts\n * const serialized = relayer.serializeSignedDecryptionPermit({ signedPermit });\n * localStorage.setItem(\"permit\", JSON.stringify(serialized));\n * ```\n */\n serializeSignedDecryptionPermit: FhevmClient[\"serializeSignedDecryptionPermit\"] = (parameters) =>\n this.#base.serializeSignedDecryptionPermit(parameters);\n\n /**\n * Rebuilds a transport key pair from its serialized hex\n * `{ publicKey, privateKey }` form. Reverse of {@link serializeTransportKeyPair}.\n *\n * @example\n * ```ts\n * const transportKeyPair = await relayer.parseTransportKeyPair({\n * publicKey: stored.publicKey,\n * privateKey: stored.privateKey,\n * });\n * ```\n */\n parseTransportKeyPair: FhevmClient[\"parseTransportKeyPair\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.parseTransportKeyPair(parameters);\n };\n\n /**\n * Rebuilds a signed permit from its serialized form and validates it: checks\n * the EIP-712 structure, verifies the signature against the on-chain verifier,\n * and confirms the permit's public key matches `transportKeyPair`. Reverse of\n * {@link serializeSignedDecryptionPermit}.\n *\n * @throws if the permit is malformed, expired, or its signature is invalid.\n *\n * @example\n * ```ts\n * const signedPermit = await relayer.parseSignedDecryptionPermit({\n * serializedPermit,\n * transportKeyPair,\n * });\n * ```\n */\n parseSignedDecryptionPermit: FhevmClient[\"parseSignedDecryptionPermit\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.parseSignedDecryptionPermit(parameters);\n };\n\n /**\n * Generates a fresh ephemeral transport key pair for a user-decrypt session.\n * The relayer re-encrypts decrypted values to this pair's public key, so only\n * the holder of the private key can read them; bind it to a permit via\n * {@link signDecryptionPermit}.\n *\n * @example\n * ```ts\n * const transportKeyPair = await relayer.generateTransportKeyPair();\n * ```\n */\n generateTransportKeyPair: FhevmClient[\"generateTransportKeyPair\"] = async () => {\n await this.#decrypt.init();\n return this.#decrypt.generateTransportKeyPair();\n };\n}\n\nfunction toFhevmAuth(\n auth: NonNullable<FheChain[\"auth\"]>,\n): NonNullable<FhevmRelayerOptions[\"auth\"]> {\n const type = auth[\"__type\"];\n switch (type) {\n case \"ApiKeyHeader\":\n return { type, value: auth.value, header: auth.header };\n case \"ApiKeyCookie\":\n return { type, value: auth.value, cookie: auth.cookie };\n case \"BearerToken\":\n return { type, token: auth.token };\n default:\n throw new ConfigurationError(`Unknown auth type: ${String(type)}`);\n }\n}\n"],"mappings":"2HAYA,SAAgB,EAAa,EAA6B,CACxD,MAAO,CACL,GAAI,EAAM,GACV,MAAO,CACL,UAAW,CACT,IAAK,CAAE,QAAS,EAAM,kBAAmB,EACzC,cAAe,CAAE,QAAS,EAAM,4BAA6B,EAC7D,YAAa,CAAE,QAAS,EAAM,kBAAmB,EACjD,eAAgB,IAAA,EAClB,EACA,WAAY,EAAM,WAClB,QAAS,CACP,GAAI,EAAM,eACV,UAAW,CACT,WAAY,CAAE,QAAS,EAAM,kCAAmC,EAChE,kBAAmB,CAAE,QAAS,EAAM,yCAA0C,CAChF,CACF,CACF,CACF,CACF,CC6BA,IAAa,EAAb,KAAqD,CACnD,GACA,GACA,GACA,GACA,GACA,GAOA,YAAY,EAA4B,CACtC,KAAKA,GAAS,EAAO,MACrB,GAAM,CAAE,UAAS,QAAO,gBAAe,iBAAgB,oBACrD,EAAO,SAAW,CAAC,EACf,EAAS,CACb,cAAA,EAAA,EAAA,mBAAA,CAAiC,CAC/B,UACE,OAAO,KAAKA,GAAO,SAAY,UAAA,EAAA,EAAA,KAAA,CACtB,KAAKA,GAAO,OAAO,GAAA,EAAA,EAAA,OAAA,CACjB,KAAKA,GAAO,OAAO,CAClC,CAAC,EACD,MAAO,EAAa,KAAKA,EAAM,EAC/B,QAAS,CAAE,gBAAe,iBAAgB,kBAAiB,CAC7D,EACI,EAAO,WACT,KAAKC,IAAAA,EAAAA,EAAAA,+BAAAA,CAAuC,CAAM,EAClD,KAAKC,IAAAA,EAAAA,EAAAA,kCAAAA,CAA6C,CAAM,EACxD,KAAKC,IAAAA,EAAAA,EAAAA,kCAAAA,CAA6C,CAAM,IAExD,KAAKF,IAAAA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AQ,EAAR,CACE,IAAK,eACH,MAAO,CAAE,OAAM,MAAO,EAAK,MAAO,OAAQ,EAAK,MAAO,EACxD,IAAK,eACH,MAAO,CAAE,OAAM,MAAO,EAAK,MAAO,OAAQ,EAAK,MAAO,EACxD,IAAK,cACH,MAAO,CAAE,OAAM,MAAO,EAAK,KAAM,EACnC,QACE,MAAM,IAAIK,EAAAA,EAAmB,sBAAsB,OAAO,CAAI,GAAG,CACrE,CACF"}
1
+ {"version":3,"file":"fhevm-relayer.cjs","names":["#chain","#base","#decrypt","#encrypt","#defaultOptions","#encryptInitPromise","#initEncrypt","ConfigurationError"],"sources":["../../src/chains/to-fhevm-chain.ts","../../src/relayer/fhevm-relayer.ts"],"sourcesContent":["import type { FhevmChain } from \"@fhevm/sdk/chains\";\nimport type { FheChain } from \"./types\";\n\n/**\n * Derive an `@fhevm/sdk` {@link FhevmChain} from zama-sdk's richer\n * {@link FheChain}.\n *\n * `FheChain` carries fields `@fhevm/sdk` does not model (RPC `network`,\n * `registryAddress`, `executorAddress`, cleartext signer keys); those stay on\n * `FheChain` for the token layer. This adapter projects only the subset the\n * FHE runtime needs: contract addresses, relayer URL, and gateway.\n */\nexport function toFhevmChain(chain: FheChain): FhevmChain {\n return {\n id: chain.id,\n fhevm: {\n contracts: {\n acl: { address: chain.aclContractAddress },\n inputVerifier: { address: chain.inputVerifierContractAddress },\n kmsVerifier: { address: chain.kmsContractAddress },\n protocolConfig: undefined,\n },\n relayerUrl: chain.relayerUrl,\n gateway: {\n id: chain.gatewayChainId,\n contracts: {\n decryption: { address: chain.verifyingContractAddressDecryption },\n inputVerification: { address: chain.verifyingContractAddressInputVerification },\n },\n },\n },\n } satisfies FhevmChain;\n}\n","import {\n createFhevmBaseClient,\n createFhevmDecryptClient,\n createFhevmEncryptClient,\n} from \"@fhevm/sdk/viem\";\nimport {\n createFhevmCleartextBaseClient,\n createFhevmCleartextDecryptClient,\n createFhevmCleartextEncryptClient,\n} from \"@fhevm/sdk/viem/cleartext\";\nimport { createPublicClient, custom, http } from \"viem\";\nimport { toFhevmChain } from \"../chains/to-fhevm-chain\";\nimport type { FheChain } from \"../chains/types\";\nimport { ConfigurationError } from \"../errors\";\nimport type {\n FhevmBaseClient,\n FhevmClient,\n FhevmDecryptClient,\n FhevmEncryptClient,\n FhevmRelayerOptions,\n RelayerSDK,\n RelayerOptions,\n} from \"./types\";\n\n/** Construction config for {@link FhevmRelayer}. */\nexport interface FhevmRelayerConfig {\n /** FHE chain configuration. */\n chain: FheChain;\n /**\n * Cleartext mode for local dev/test chains without FHE infrastructure — reads\n * mock cleartexts from the on-chain executor (discovered automatically)\n * instead of calling the relayer.\n */\n cleartext?: boolean;\n /**\n * Per-transport {@link RelayerOptions}: `@fhevm/sdk` client options plus a\n * default request `timeout` applied to every relayer round-trip on the chain.\n */\n options?: RelayerOptions;\n}\n\n/**\n * Single-chain FHE backend that drives `@fhevm/sdk` on the calling thread with\n * capability-scoped lazy initialization.\n * EIP-712 signing is done by the signer layer; this backend builds the typed\n * data and, on decrypt, reassembles the new SDK's signed permit from the\n * interface's params + the previously returned signature.\n *\n * @remarks\n * Each method delegates to the narrowest base, decrypt, or encrypt client,\n * adding two cross-cutting behaviors that the delegated signatures don't\n * express:\n *\n * - **Lazy init.** Each operation initializes only the capability it requires.\n * Public decrypt avoids WASM, private decrypt loads TKMS only, and encryption\n * alone loads TFHE and the FHE encryption key.\n * - **Option merging.** The chain's default options (`auth`, `timeout`, `debug`)\n * are spread in first, then the per-call `options`, so a per-call value always\n * wins over the chain default. Serialization helpers make no relayer\n * round-trip, so they inject no options.\n *\n * @internal\n */\nexport class FhevmRelayer implements RelayerSDK {\n readonly #chain: FheChain;\n readonly #base: FhevmBaseClient;\n readonly #decrypt: FhevmDecryptClient;\n readonly #encrypt: FhevmEncryptClient;\n readonly #defaultOptions: Partial<FhevmRelayerOptions>;\n #encryptInitPromise: Promise<void> | undefined;\n\n /**\n * Builds capability-scoped `@fhevm/sdk` clients for the chain and captures\n * the chain's `auth`/`timeout`/`debug` as request defaults. Construction is\n * cheap; each client's one-time init is deferred to its first operation.\n */\n constructor(config: FhevmRelayerConfig) {\n this.#chain = config.chain;\n const { timeout, debug, batchRpcCalls, moduleVersions, fheEncryptionKey } =\n config.options ?? {};\n const auth = this.#chain.auth ? toFhevmAuth(this.#chain.auth) : undefined;\n const transport =\n typeof this.#chain.network === \"string\"\n ? http(this.#chain.network)\n : custom(this.#chain.network);\n const params = {\n publicClient: createPublicClient({ transport }),\n chain: toFhevmChain(this.#chain),\n options: { batchRpcCalls, moduleVersions, fheEncryptionKey },\n };\n if (config.cleartext) {\n this.#base = createFhevmCleartextBaseClient(params);\n this.#decrypt = createFhevmCleartextDecryptClient(params);\n this.#encrypt = createFhevmCleartextEncryptClient(params);\n } else {\n this.#base = createFhevmBaseClient(params);\n this.#decrypt = createFhevmDecryptClient(params);\n this.#encrypt = createFhevmEncryptClient(params);\n }\n this.#defaultOptions = {\n ...(auth !== undefined && { auth }),\n ...(timeout !== undefined && { timeout }),\n ...(debug !== undefined && { debug }),\n };\n }\n\n /** The FHE chain this backend is bound to. */\n get chain() {\n return this.#chain;\n }\n\n #initEncrypt = (): Promise<void> => {\n this.#encryptInitPromise ??= this.#base\n .fetchFheEncryptionKeyBytes({ options: this.#defaultOptions })\n .then(() => this.#encrypt.init());\n return this.#encryptInitPromise;\n };\n\n /**\n * Decrypts a single publicly-decryptable value — one whose contract granted\n * public access, so no permit or key pair is needed — into its typed clear\n * value.\n *\n * @example\n * ```ts\n * const { type, value } = await relayer.decryptPublicValue({\n * encryptedValue: handle, // a bytes32 ciphertext reference\n * });\n * ```\n */\n decryptPublicValue: FhevmClient[\"decryptPublicValue\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.decryptPublicValue({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Batch form of {@link decryptPublicValue}: decrypts many publicly-decryptable\n * values in one relayer round-trip, returning their typed clear values in\n * order.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptPublicValues({\n * encryptedValues: [handleA, handleB],\n * });\n * ```\n */\n decryptPublicValues: FhevmClient[\"decryptPublicValues\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.decryptPublicValues({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Like {@link decryptPublicValues}, but also returns the KMS signature bundle —\n * the handles list, ABI-encoded cleartexts, and decryption proof — needed to\n * verify or replay the result on-chain.\n *\n * @example\n * ```ts\n * const { clearValues, checkSignaturesArgs } =\n * await relayer.decryptPublicValuesWithSignatures({ encryptedValues: [handle] });\n * // checkSignaturesArgs: { handlesList, abiEncodedCleartexts, decryptionProof }\n * ```\n */\n decryptPublicValuesWithSignatures: FhevmClient[\"decryptPublicValuesWithSignatures\"] = async (\n parameters,\n ) => {\n await this.#base.init();\n return this.#base.decryptPublicValuesWithSignatures({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Encrypts one typed input under the chain's FHE key, bound to the contract it\n * targets and the user submitting it, and returns the ciphertext handle plus\n * the input proof the contract verifies on-chain. `type` is the FHE type\n * with the `e` prefix (`\"euint64\"`, `\"ebool\"`, `\"eaddress\"`).\n *\n * @example\n * ```ts\n * const { encryptedValue, inputProof } = await relayer.encryptValue({\n * value: { type: \"euint64\", value: 1000n },\n * contractAddress: \"0xToken…\",\n * userAddress: \"0xUser…\",\n * });\n * ```\n */\n encryptValue: FhevmClient[\"encryptValue\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.encryptValue({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Batch form of {@link encryptValue}: encrypts several inputs for the same\n * contract and user in one call, returning all ciphertext handles under a\n * single shared input proof.\n *\n * @example\n * ```ts\n * const { encryptedValues, inputProof } = await relayer.encryptValues({\n * values: [\n * { type: \"euint64\", value: 1000n },\n * { type: \"ebool\", value: true },\n * ],\n * contractAddress: \"0xToken…\",\n * userAddress: \"0xUser…\",\n * });\n * ```\n */\n encryptValues: FhevmClient[\"encryptValues\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.encryptValues({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * User-decrypts a single access-controlled value: the relayer re-encrypts it\n * to the ephemeral transport key pair, gated by the signed permit, and this\n * returns the typed clear value. Build the key pair with\n * {@link generateTransportKeyPair} and the permit with\n * {@link signDecryptionPermit}.\n *\n * @example\n * ```ts\n * const { type, value } = await relayer.decryptValue({\n * encryptedValue: handle,\n * contractAddress: \"0xToken…\",\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValue: FhevmClient[\"decryptValue\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValue({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Batch form of {@link decryptValue} for values that all belong to the same\n * contract; returns the typed clear values positionally. For values spanning\n * multiple contracts, use {@link decryptValuesFromPairs}.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptValues({\n * encryptedValues: [handleA, handleB],\n * contractAddress: \"0xToken…\",\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValues: FhevmClient[\"decryptValues\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValues({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * User-decrypts values that span multiple contracts: each pair carries its own\n * `contractAddress`, so one permit covering those contracts decrypts them all\n * in a single round-trip. Returns the typed clear values positionally.\n *\n * @example\n * ```ts\n * const values = await relayer.decryptValuesFromPairs({\n * pairs: [\n * { encryptedValue: handleA, contractAddress: \"0xTokenA…\" },\n * { encryptedValue: handleB, contractAddress: \"0xTokenB…\" },\n * ],\n * transportKeyPair,\n * signedPermit,\n * });\n * ```\n */\n decryptValuesFromPairs: FhevmClient[\"decryptValuesFromPairs\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.decryptValuesFromPairs({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters.options },\n });\n };\n\n /**\n * Fetches the chain's raw FHE public-key bytes — the key encryption uses —\n * served from cache unless `ignoreCache` forces a refetch. Rarely called\n * directly: {@link encryptValue}/{@link encryptValues} fetch the key for you.\n *\n * @example\n * ```ts\n * const keyBytes = await relayer.fetchFheEncryptionKeyBytes();\n * const fresh = await relayer.fetchFheEncryptionKeyBytes({ ignoreCache: true });\n * ```\n */\n fetchFheEncryptionKeyBytes: FhevmClient[\"fetchFheEncryptionKeyBytes\"] = async (parameters) => {\n await this.#initEncrypt();\n return this.#encrypt.fetchFheEncryptionKeyBytes({\n ...parameters,\n options: { ...this.#defaultOptions, ...parameters?.options },\n });\n };\n\n /**\n * Builds the EIP-712 user-decrypt permit and signs it with the given signer,\n * authorizing the transport key pair to decrypt the listed contracts' values\n * for `durationSeconds` starting at `startTimestamp`. Pass `delegatorAddress`\n * to sign a delegated permit — decrypting values owned by that account instead\n * of the signer's own. Persist the result via\n * {@link serializeSignedDecryptionPermit}.\n *\n * @example\n * ```ts\n * const signedPermit = await relayer.signDecryptionPermit({\n * transportKeyPair,\n * contractAddresses: [\"0xToken…\"],\n * startTimestamp: Math.floor(Date.now() / 1000),\n * durationSeconds: 60 * 60 * 24,\n * signerAddress: \"0xUser…\",\n * signer,\n * // delegatorAddress: \"0xOwner…\", // omit for a self permit\n * });\n * ```\n */\n signDecryptionPermit: FhevmClient[\"signDecryptionPermit\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.signDecryptionPermit(parameters);\n };\n\n // Permit/key-pair helpers carry no request options. Parsing explicitly\n // initializes the capability that validates the restored value; serialization\n // resolves the frozen context internally (via initPublicAction), which reads\n // on-chain state.\n\n /**\n * Serializes a transport key pair to a hex `{ publicKey, privateKey }` pair for\n * storage or transport, so a decryption session can resume without regenerating\n * keys. Reverse of {@link parseTransportKeyPair}.\n *\n * @example\n * ```ts\n * const stored = await relayer.serializeTransportKeyPair({ transportKeyPair });\n * // { publicKey: \"0x…\", privateKey: \"0x…\" }\n * ```\n */\n serializeTransportKeyPair: FhevmClient[\"serializeTransportKeyPair\"] = (parameters) =>\n this.#decrypt.serializeTransportKeyPair(parameters);\n\n /**\n * Serializes a signed permit to a plain, JSON-stringifiable object (version,\n * EIP-712 payload, signature, signer) for caching or transport. Reverse of\n * {@link parseSignedDecryptionPermit}.\n *\n * @example\n * ```ts\n * const serialized = await relayer.serializeSignedDecryptionPermit({ signedPermit });\n * localStorage.setItem(\"permit\", JSON.stringify(serialized));\n * ```\n */\n serializeSignedDecryptionPermit: FhevmClient[\"serializeSignedDecryptionPermit\"] = (parameters) =>\n this.#base.serializeSignedDecryptionPermit(parameters);\n\n /**\n * Rebuilds a transport key pair from its serialized hex\n * `{ publicKey, privateKey }` form. Reverse of {@link serializeTransportKeyPair}.\n *\n * @example\n * ```ts\n * const transportKeyPair = await relayer.parseTransportKeyPair({\n * publicKey: stored.publicKey,\n * privateKey: stored.privateKey,\n * });\n * ```\n */\n parseTransportKeyPair: FhevmClient[\"parseTransportKeyPair\"] = async (parameters) => {\n await this.#decrypt.init();\n return this.#decrypt.parseTransportKeyPair(parameters);\n };\n\n /**\n * Rebuilds a signed permit from its serialized form and validates it: checks\n * the EIP-712 structure, verifies the signature against the on-chain verifier,\n * and confirms the permit's public key matches `transportKeyPair`. Reverse of\n * {@link serializeSignedDecryptionPermit}.\n *\n * @throws if the permit is malformed, expired, or its signature is invalid.\n *\n * @example\n * ```ts\n * const signedPermit = await relayer.parseSignedDecryptionPermit({\n * serializedPermit,\n * transportKeyPair,\n * });\n * ```\n */\n parseSignedDecryptionPermit: FhevmClient[\"parseSignedDecryptionPermit\"] = async (parameters) => {\n await this.#base.init();\n return this.#base.parseSignedDecryptionPermit(parameters);\n };\n\n /**\n * Generates a fresh ephemeral transport key pair for a user-decrypt session.\n * The relayer re-encrypts decrypted values to this pair's public key, so only\n * the holder of the private key can read them; bind it to a permit via\n * {@link signDecryptionPermit}.\n *\n * @example\n * ```ts\n * const transportKeyPair = await relayer.generateTransportKeyPair();\n * ```\n */\n generateTransportKeyPair: FhevmClient[\"generateTransportKeyPair\"] = async () => {\n await this.#decrypt.init();\n return this.#decrypt.generateTransportKeyPair();\n };\n}\n\n/**\n * Translates the SDK's public {@link FheChain.auth} shape (discriminated by\n * `__type`) into the `type`-discriminated `auth` that `@fhevm/sdk` expects.\n *\n * @throws if the auth discriminator is not one of the supported kinds.\n */\nfunction toFhevmAuth(\n auth: NonNullable<FheChain[\"auth\"]>,\n): NonNullable<FhevmRelayerOptions[\"auth\"]> {\n const type = auth[\"__type\"];\n switch (type) {\n case \"ApiKeyHeader\":\n return { type, value: auth.value, header: auth.header };\n case \"ApiKeyCookie\":\n return { type, value: auth.value, cookie: auth.cookie };\n case \"BearerToken\":\n return { type, token: auth.token };\n default:\n throw new ConfigurationError(`Unknown auth type: ${String(type)}`);\n }\n}\n"],"mappings":"2HAYA,SAAgB,EAAa,EAA6B,CACxD,MAAO,CACL,GAAI,EAAM,GACV,MAAO,CACL,UAAW,CACT,IAAK,CAAE,QAAS,EAAM,kBAAmB,EACzC,cAAe,CAAE,QAAS,EAAM,4BAA6B,EAC7D,YAAa,CAAE,QAAS,EAAM,kBAAmB,EACjD,eAAgB,IAAA,EAClB,EACA,WAAY,EAAM,WAClB,QAAS,CACP,GAAI,EAAM,eACV,UAAW,CACT,WAAY,CAAE,QAAS,EAAM,kCAAmC,EAChE,kBAAmB,CAAE,QAAS,EAAM,yCAA0C,CAChF,CACF,CACF,CACF,CACF,CC+BA,IAAa,EAAb,KAAgD,CAC9C,GACA,GACA,GACA,GACA,GACA,GAOA,YAAY,EAA4B,CACtC,KAAKA,GAAS,EAAO,MACrB,GAAM,CAAE,UAAS,QAAO,gBAAe,iBAAgB,oBACrD,EAAO,SAAW,CAAC,EACf,EAAO,KAAKA,GAAO,KAAO,EAAY,KAAKA,GAAO,IAAI,EAAI,IAAA,GAK1D,EAAS,CACb,cAA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AU,GAmBnD,0BAAuE,GACrE,KAAKC,GAAS,0BAA0B,CAAU,EAapD,gCAAmF,GACjF,KAAKD,GAAM,gCAAgC,CAAU,EAcvD,sBAA8D,KAAO,KACnE,MAAM,KAAKC,GAAS,KAAK,EAClB,KAAKA,GAAS,sBAAsB,CAAU,GAmBvD,4BAA0E,KAAO,KAC/E,MAAM,KAAKD,GAAM,KAAK,EACf,KAAKA,GAAM,4BAA4B,CAAU,GAc1D,yBAAoE,UAClE,MAAM,KAAKC,GAAS,KAAK,EAClB,KAAKA,GAAS,yBAAyB,EAElD,EAQA,SAAS,EACP,EAC0C,CAC1C,IAAM,EAAO,EAAK,OAClB,OAAQ,EAAR,CACE,IAAK,eACH,MAAO,CAAE,OAAM,MAAO,EAAK,MAAO,OAAQ,EAAK,MAAO,EACxD,IAAK,eACH,MAAO,CAAE,OAAM,MAAO,EAAK,MAAO,OAAQ,EAAK,MAAO,EACxD,IAAK,cACH,MAAO,CAAE,OAAM,MAAO,EAAK,KAAM,EACnC,QACE,MAAM,IAAIK,EAAAA,EAAmB,sBAAsB,OAAO,CAAI,GAAG,CACrE,CACF"}
@@ -1,2 +1,2 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./wrappers-registry.cjs"),n=require("./token.cjs"),r=require("./cleartext.cjs"),i=require("./base-signer.cjs"),a=require("./chains.cjs");let o=require("viem"),s=require("zod/mini");function c(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var l=class extends e.r{constructor(t,n){super(e.i.TransportKeyPairExpired,t,n),this.name=`TransportKeyPairExpiredError`}},u=class extends e.r{constructor(t,n){super(e.i.InvalidTransportKeyPair,t,n),this.name=`InvalidTransportKeyPairError`}},d=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},f=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}},p=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},_=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},b=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},x=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},S=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};const ee=[n.x,d,e.n,S,t.W,t.U,f,n.y];function C(t,r,i={}){if(ee.some(e=>t instanceof e))return t;let a=t instanceof Error?t.message:r;if(t instanceof Error&&e.d(t.message))return i.isDelegated?new S(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:t}):new f({encryptedValue:e.h(t.message)??``,contractAddress:i.contractAddress??``,account:i.account??``},{cause:t});if(e.l(t))return new n.y(a,{cause:t,retryAfter:e.c(t)});let o=e.s(t);return o===void 0&&e.m(t)?new n.y(a,{cause:t,retryAfter:e.c(t)}):o===400?new d(t instanceof Error?t.message:`No ciphertext for this account`,{cause:t}):i.isDelegated&&o===500?new S(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:t}):e.f(t)||o!==void 0?new e.n(a,o,{cause:t,retryAfter:e.c(t),retryable:e.p(t)||void 0}):new n.x(r,{cause:t})}function te(t,r){if(t instanceof e.r)return t;let i=e.s(t),a=e.p(t);return i!==void 0||e.f(t)?new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:e.c(t),retryable:a||void 0}):new n.S(r,{cause:t})}const ne=[{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 w(e,t,n,r=`0x`){return{address:e,abi:ne,functionName:`transferAndCall`,args:[t,n,r]}}const T=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function E(e,t,n,r){return{address:e,abi:T,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function D(e,t,n){return{address:e,abi:T,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function O(e,t,n,r){return{address:e,abi:T,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function re(e,t,n,r,i){return{address:e,abi:T,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const k=2n**64n-1n;function ie(e){return i.i(e.signer,e.provider,e)}function A(e){return e.startsWith(`0x`)?e:`0x${e}`}var j=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return t.H(this.#r,e)}async decryptValues(e,t){let r=this.#i(`decryptValues`),i=await n.u(`decryptValues`,this.#e,this.#t);return r.decryptValues(e,i.address,t)}async delegatedDecryptValues(e,t,r=t,i){let a=this.#i(`delegatedDecryptValues`),o=await n.u(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,r,i)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let r=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),i={};return r.checkSignaturesArgs.handlesList.forEach((e,t)=>{n.l(r.clearValues[t],`result.clearValues[${t}]`),i[e]=r.clearValues[t].value}),{clearValues:i,abiEncodedClearValues:r.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:r.checkSignaturesArgs.decryptionProof}}catch(e){throw C(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:r=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await n.u(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:r,maxConcurrency:i,waitForPropagation:a})}},M=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.H(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:r}){let i=this.#r(`delegateDecryption`),a=await n.u(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:r})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let r=this.#r(`revokeDelegation`),i=await n.u(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},N=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return t.H(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await n.d(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let r=this.#a(`grantDelegationPermit`);await n.d(`grantDelegationPermit`,this.#e,this.#t),await r.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async revokePermits(e){let t=this.#a(`revokePermits`),r=(0,o.getAddress)((await n.u(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(r)}}async clear(){let e=this.#a(`clear`),t=(0,o.getAddress)((await n.u(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await t.L(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}};const ae=s.z.union([s.z.bigint(),s.z.boolean(),i.l]),oe=s.z.array(s.z.string());var se=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=ae.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=(0,o.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${(0,o.getAddress)(e)}:${(0,o.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=oe.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function ce(e,t){let r=le(e,t);if(!r)throw new n.x(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:r.serializedPermit}}function le(e,t){let n=i.c(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const ue=e=>new Promise(t=>setTimeout(t,e));var de=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=(0,o.getAddress)(t);return this.#s(e,{requesterAddress:r,aclActorAddress:r,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=(0,o.getAddress)(t),s=(0,o.getAddress)(n);return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,o.getAddress)(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#f(e,{delegatorAddress:a,delegateAddress:s}),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt delegated encrypted values`,delegated:!0}))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof S))throw t;await ue(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:r,accountAddress:i,maxConcurrency:a=5,waitForPropagation:s=!0}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,o.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let l=(0,o.getAddress)(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,r,l,{waitForPropagation:s});for(let t of c)this.#l(t,e);return{items:c}}catch(e){if(n.f(e))throw e;if(c.length===1){let[n=this.#d()]=c;return n.error=this.#u(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,o.getAddress)(t)}),{items:c}}}let u=!1;return await n.o(c.map(e=>async()=>{if(!u)try{let n=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,r,l,{waitForPropagation:!1});this.#l(e,n)}catch(r){if(n.f(r))throw u=!0,r;e.error=this.#u(r,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,o.getAddress)(t)})}}),a),{items:c}}async#o(e,t,n,r){let i=ce(e,t),a=await this.#r.relayer.parseTransportKeyPair({publicKey:i.publicKey,privateKey:i.privateKey}),o=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:a,serializedPermit:i.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:a,signedPermit:o,encryptedValues:n,contractAddress:t,options:r})}async#s(t,r,i){if(t.length===0)return{};let a=t.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,o.getAddress)(e.contractAddress)})),s={},c=[];for(let e of a)n.a(e.encryptedValue)?s[e.encryptedValue]=0n:c.push(e);if(c.length===0)return s;let l=Array.from(new Set(a.map(e=>e.contractAddress))),u=Array.from(new Set(c.map(e=>e.contractAddress)));if(r.validate)try{await r.validate(u)}catch(t){throw e.m(t)?this.#c(t,`the delegation pre-check`):t}let d=[];for(let e of c){let t=await this.#e.get(r.requesterAddress,e.contractAddress,e.encryptedValue);t===null?d.push(e):s[e.encryptedValue]=t}if(d.length===0)return s;let f=await r.resolveCredentials(l),p=new Map;for(let e of d){let t=p.get(e.contractAddress);t?t.push(e.encryptedValue):p.set(e.contractAddress,[e.encryptedValue])}let m=[];for(let[e,t]of p)for(let r of n.i(t))m.push({contractAddress:e,encryptedValues:r});let h=Date.now(),g=d.map(e=>e.encryptedValue);try{this.#i({type:n.s.DecryptStart,encryptedValues:g}),await n.o(m.map(({contractAddress:e,encryptedValues:t})=>async()=>{let a;try{a=await r.decryptContract({credentials:f,contractAddress:e,encryptedValues:t,options:i})}catch(t){throw C(t,r.errorMessage,{isDelegated:r.delegated,contractAddress:e,account:r.aclActorAddress})}for(let n=0;n<t.length;n++){let i=t[n],o=a[n]?.value;i===void 0||o===void 0||(s[i]=o,await this.#e.set(r.requesterAddress,e,i,o))}let o=t.filter(e=>s[e]===void 0);if(o.length>0)throw new n.x(`${r.errorMessage}: relayer returned no clear value for ${o.length} of ${t.length} handle(s) on ${e}`,{cause:AggregateError(o.map(t=>new n.x(`No clear value for handle ${t} on ${e}`)),`${o.length} handle(s) missing a clear value on ${e}`)})}),5);let e={};for(let t of g){let n=s[t];n!==void 0&&(e[t]=n)}return this.#i({type:n.s.DecryptEnd,durationMs:Date.now()-h,encryptedValues:g,result:e}),s}catch(t){let i=t instanceof e.r&&t.cause instanceof Error?t.cause:t;throw this.#i({type:n.s.DecryptError,error:e.g(i),durationMs:Date.now()-h,encryptedValues:g}),C(t,r.errorMessage,{isDelegated:r.delegated})}}#c(t,r){return new n.y(`RPC provider rate-limited ${r}; retry with backoff.`,{cause:t,retryAfter:e.c(t)})}#l(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n.x(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#u(t,n,r){return t instanceof e.r?t:C(t,n,r)}#d(){throw new n.x(`Batch delegated decryption invariant failed: missing item`)}async#f(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function fe(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}const P={AlreadyDelegatedOrRevokedInSameBlock:e=>new m(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new y(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new b(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new p(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new v(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new x(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new _(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new h(`Cannot revoke: no active delegation exists.`,{cause:e})};function pe(e){return e in P}function me(e,t){let n=fe(e);if(n&&pe(n))return P[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(P))if(r.includes(e))return n(t);return null}var he=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new x(`Expiration date must be at least 1 hour in the future`);let a=(0,o.getAddress)(t),s=(0,o.getAddress)(n),c=(0,o.getAddress)(r);if(s===c)throw new p(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===a)throw new v(`Delegate address cannot be the same as the contract address (${a}).`);let l=this.#e.relayer.chain.aclContractAddress,u=i?BigInt(Math.floor(i.getTime()/1e3)):k,d;try{d=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:c,delegateAddress:s})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),d=-1n}if(d===u)throw new _(`The new expiration date (${u}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:t,config:E(l,s,a,u)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=(0,o.getAddress)(t),a=(0,o.getAddress)(n),s=(0,o.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:s,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new h(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:t,config:D(c,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===k?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(O(r,(0,o.getAddress)(t),(0,o.getAddress)(n),(0,o.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:r,config:i}){try{return await n.n({operation:e,signer:t,provider:this.#t,config:i,emit:e=>this.#n(e,r),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof n.b))return;let t=me(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof h||t instanceof g){let n=(0,o.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,o.getAddress)(e),i=(0,o.getAddress)(t),a=(0,o.getAddress)(n),{isActive:s,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!s)throw c===0n?new h(`No active delegation from ${i} to ${a} for ${r}`):new g(`Delegation from ${i} to ${a} for ${r} has expired`)}},ge=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(t,r){let i=Date.now(),a=(0,o.getAddress)(t.contractAddress);try{this.#t({type:n.s.EncryptStart},a);let e=await this.#e.relayer.encryptValues({...t,options:r});return this.#t({type:n.s.EncryptEnd,durationMs:Date.now()-i},a),e}catch(t){throw this.#t({type:n.s.EncryptError,error:e.g(t),durationMs:Date.now()-i},a),te(t,`Encryption failed`)}}},_e=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.L(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.L(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.L(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.L(`wallet account listener`,()=>n(e),this.#i)))}};function F(e){return(0,o.keccak256)((0,o.toBytes)(e))}const I={ConfidentialTransfer:F(`ConfidentialTransfer(address,address,bytes32)`),Wrap:F(`Wrap(address,uint256,bytes32)`),UnwrapRequested:F(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:F(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function L(e){return(0,o.getAddress)(A(e.slice(-40)))}function R(e){return e}function z(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function B(e,t){return(0,o.getAddress)(A(z(e,t).slice(-40)))}function V(e,t){return BigInt(`0x`+z(e,t))}function H(e,t){return A(z(e,t))}function U(e){return e.topics[0]!==I.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:L(e.topics[1]),to:L(e.topics[2]),encryptedAmount:R(e.topics[3])}}function W(e){return e.topics[0]!==I.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:L(e.topics[1]),roundedAmount:V(e.data,0),encryptedWrappedAmount:H(e.data,1)}}function G(e){return e.topics[0]!==I.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:L(e.topics[1]),unwrapRequestId:R(e.topics[2]),encryptedAmount:H(e.data,0)}}function K(e){return e.topics[0]!==I.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:L(e.topics[1]),unwrapRequestId:R(e.topics[2]),encryptedAmount:H(e.data,0),cleartextAmount:V(e.data,1)}}function q(e){return U(e)??W(e)??G(e)??K(e)}function ve(e){let t=[];for(let n of e){let e=q(n);e&&t.push(e)}return t}function J(e){for(let t of e){let e=G(t);if(e)return e}return null}function ye(e){for(let t of e){let e=W(t);if(e)return e}return null}const be=[I.ConfidentialTransfer,I.Wrap,I.UnwrapRequested,I.UnwrapFinalized],Y={DelegatedForUserDecryption:F(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:F(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function X(e){return e.topics[0]!==Y.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:L(e.topics[1]),delegate:L(e.topics[2]),contractAddress:B(e.data,0),delegationCounter:V(e.data,1),oldExpirationDate:V(e.data,2),newExpirationDate:V(e.data,3)}}function Z(e){return e.topics[0]!==Y.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:L(e.topics[1]),delegate:L(e.topics[2]),contractAddress:B(e.data,0),delegationCounter:V(e.data,1),oldExpirationDate:V(e.data,2)}}function Q(e){return X(e)??Z(e)}function xe(e){let t=[];for(let n of e){let e=Q(n);e&&t.push(e)}return t}function Se(e){for(let t of e){let e=X(t);if(e)return e}return null}function Ce(e){for(let t of e){let e=Z(t);if(e)return e}return null}const we=[Y.DelegatedForUserDecryption,Y.RevokedDelegationForUserDecryption];function $(e){return`zama:pending-unshield:${i.c(e)}`}const Te=s.z.union([s.z.pipe(i.u,s.z.transform(e=>({unwrapTxHash:e}))),s.z.pipe(s.z.object({version:s.z.literal(1),unwrapTxHash:i.u,unwrapRequestId:s.z.optional(i.u)}),s.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function Ee(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function De(e,t){return(await Oe(e,t))?.unwrapTxHash??null}async function Oe(e,t){let n=$(t),r=await e.get(n);if(r==null)return null;let i=Te.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function ke(e,t){await e.delete($(t))}var Ae=class extends n.t{#e;#t=null;#n=null;#r(e){try{return n.l(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.R(e,{cause:n})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(t.p(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#s();return this.sdk.provider.readContract(t.h(n,(0,o.getAddress)(e),this.address))}async shield(r,i){let a=await n.u(`shield`,this.sdk.signer,this.sdk.provider),s=await this.isPayable(),c=await this.#s(),l=(0,o.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t._(c,l))}catch(t){throw t instanceof e.r?t:new n.m(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e.g(t)})}if(u<r)throw new n._(`Insufficient ERC-20 balance: requested ${r}, available ${u} (token: ${c})`,{requested:r,available:u,token:c});return s?this.#i(r,c,l,i):this.#a(r,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,o.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:w(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(r,i){this.#r(`wrap`);let a=await n.u(`wrap`,this.sdk.signer,this.sdk.provider),s=await this.#s(),c=(0,o.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t._(s,c))}catch(t){throw t instanceof e.r?t:new n.m(`Could not read ERC-20 balance for wrap validation (token: ${s})`,{cause:e.g(t)})}if(l<r)throw new n._(`Insufficient ERC-20 balance: requested ${r}, available ${l} (token: ${s})`,{requested:r,available:l,token:s});let u;try{u=await this.sdk.provider.readContract(t.h(s,c,this.address))}catch(t){throw t instanceof e.r?t:new n.m(`Could not read ERC-20 allowance for wrap validation (token: ${s})`,{cause:e.g(t)})}if(u<r)throw new n.h(`Insufficient allowance for wrap: requested ${r}, approved ${u}. Call approveUnderlying() first (token: ${s}).`,{requested:r,available:u,token:s});let d=i?.to?(0,o.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.I(this.address,d,r),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#l(e,i===`max`,r);let a=r?.to?(0,o.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.I(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let r=await n.u(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#s(),a=(0,o.getAddress)(r.address),s=e??2n**256n-1n;return s>0n&&await this.sdk.provider.readContract(t.h(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.g(i,this.address,s)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.L(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#c(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.L(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#c(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(t,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(t)}catch(t){throw t instanceof e.r?t:new n.b(`Failed to get unwrap receipt`,{cause:t})}let a=this.#o(i.logs);return this.#c(a,t,crypto.randomUUID(),r)}async getPendingUnshield(){return De(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let r=(0,o.getAddress)((await n.u(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r}),[s]=i;if(!s)throw new n.S(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:t.P(this.address,r,r,s,a)});return{...c,unwrapRequestId:this.#o(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,o.getAddress)((await n.u(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),r=await this.readConfidentialBalanceOf(e);if(n.a(r))throw new n.x(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:t.F(this.address,e,e,r)});return{...i,unwrapRequestId:this.#o(i.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await n.d(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let r=await this.sdk.decryption.decryptPublicValues([e]),i=r.clearValues[e];return n.c(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.O(this.address,e,i,r.decryptionProof)})}#o(e){let t=J(e);if(!t)throw new n.b(`No UnwrapRequested event found in unwrap receipt`);return t.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.N(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,r,i,a){this.emit({type:n.s.UnshieldPhase1Submitted,txHash:r,operationId:i}),await t.L(`unshield: savePendingUnshield`,()=>Ee(this.sdk.storage,this.address,r),this.sdk.logger),this.emit({type:n.s.UnshieldPhase2Started,operationId:i}),t.L(`unshield: onFinalizing`,()=>a?.onFinalizing?.(),this.sdk.logger);let o=await this.finalizeUnwrap(e);return this.emit({type:n.s.UnshieldPhase2Submitted,txHash:o.txHash,operationId:i}),t.L(`unshield: onFinalizeSubmitted`,()=>a?.onFinalizeSubmitted?.(o.txHash),this.sdk.logger),await t.L(`unshield: clearPendingUnshield`,()=>ke(this.sdk.storage,this.address),this.sdk.logger),o}async#l(e,r,i){this.#r(`approveUnderlying`);let a=await this.#s(),s=(0,o.getAddress)((await n.u(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t.h(a,s,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.g(a,this.address,0n)});let l=r?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.g(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}},je=class{#e;provider;signer;storage;registry;permits;delegations;decryption;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;constructor(e){this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new se(e.storage,this.#i),this.#u=new he({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new i.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#n=t,this.#t=e.registryTTL,e.signer&&(this.#l=new i.s({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),this.#c=new de({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new ge({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new _e({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.permits=new N({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new M({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new j({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c})}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new i.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new n.t(this,e)}createWrappedToken(e){return new Ae(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}},Me=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const Ne=new Me;exports.ACL_TOPICS=we,exports.AclPausedError=b,exports.AclTopics=Y,exports.BalanceCheckUnavailableError=n.p,exports.BaseSigner=i.t,exports.ChainMismatchError=n.v,exports.ChromeSessionStorage=Me,exports.ConfigurationError=e.t,exports.Decryption=j,exports.DecryptionFailedError=n.x,exports.DefaultRegistryAddresses=i.a,exports.DelegationContractIsSelfError=y,exports.DelegationCooldownError=m,exports.DelegationDelegateEqualsContractError=v,exports.DelegationExpirationTooSoonError=x,exports.DelegationExpiredError=g,exports.DelegationExpiryUnchangedError=_,exports.DelegationNotFoundError=h,exports.DelegationNotPropagatedError=S,exports.DelegationSelfNotAllowedError=p,exports.Delegations=M,exports.ERC1363_INTERFACE_ID=t.c,exports.ERC20ReadFailedError=n.m,exports.ERC7984_INTERFACE_ID=t.l,exports.ERC7984_WRAPPER_INTERFACE_ID=t.u,exports.EncryptionFailedError=n.S,exports.IndexedDBStorage=i.h,exports.InsufficientAllowanceError=n.h,exports.InsufficientConfidentialBalanceError=n.g,exports.InsufficientERC20BalanceError=n._,exports.InvalidTransportKeyPairError=u,exports.MemoryStorage=i.p,exports.MutableWalletAccountStore=i.n,exports.NoCiphertextError=d,exports.NotEntitledError=f,exports.Permits=N,exports.RelayerRequestFailedError=e.n,exports.RpcRateLimitError=n.y,exports.SignerNotConfiguredError=t.R,exports.SignerRequiredError=t.z,exports.SigningFailedError=t.U,exports.SigningRejectedError=t.W,exports.TOKEN_TOPICS=be,exports.Token=n.t,exports.Topics=I,exports.TransactionRevertedError=n.b,exports.TransportKeyPairExpiredError=l,exports.WalletAccountNotReadyError=t.B,exports.WalletNotConnectedError=t.V,exports.WrappedToken=Ae,exports.WrappersRegistry=i.o,exports.ZERO_ENCRYPTED_VALUE=n.r,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=je,exports.ZamaSDKEvents=n.s,exports.allowanceContract=t.h,exports.anvil=a.t,exports.approveContract=t.g,exports.balanceOfContract=t._,exports.bscTestnet=a.n,exports.chains=a.r,exports.chromeSessionStorage=Ne,exports.cleartext=r.t,exports.confidentialBalanceOfContract=t.S,exports.confidentialTotalSupplyContract=t.C,exports.confidentialTransferContract=t.T,exports.confidentialTransferFromContract=t.D,exports.createConfig=ie,exports.createWalletAccountStore=i.r,exports.decimalsContract=t.v,exports.decodeAclEvent=Q,exports.decodeAclEvents=xe,exports.decodeConfidentialTransfer=U,exports.decodeDelegatedForUserDecryption=X,exports.decodeOnChainEvent=q,exports.decodeOnChainEvents=ve,exports.decodeRevokedDelegationForUserDecryption=Z,exports.decodeUnwrapFinalized=K,exports.decodeUnwrapRequested=G,exports.decodeWrap=W,exports.delegateForUserDecryptionContract=E,exports.finalizeUnwrapContract=t.O,exports.findDelegatedForUserDecryption=Se,exports.findRevokedDelegationForUserDecryption=Ce,exports.findUnwrapRequested=J,exports.findWrap=ye,exports.getConfidentialTokenAddressContract=t.t,exports.getDelegationExpiryContract=O,exports.getTokenAddressContract=t.n,exports.getTokenPairContract=t.r,exports.getTokenPairsContract=t.i,exports.getTokenPairsLengthContract=t.a,exports.getTokenPairsSliceContract=t.o,exports.hardhat=a.i,exports.hoodi=a.a,exports.indexedDBStorage=i.g,exports.inferredTotalSupplyContract=t.k,exports.ingenTestnet=a.o,exports.isConfidentialTokenContract=t.d,exports.isConfidentialTokenValidContract=t.s,exports.isConfidentialWrapperContract=t.f,exports.isEncryptedValueZero=n.a,exports.isHandleDelegatedContract=re,exports.isOperatorContract=t.A,exports.isRetryable=e.a,exports.mainnet=a.s,exports.matchZamaError=c,exports.memoryStorage=i.m,exports.nameContract=t.b,exports.rateContract=t.j,exports.resolveChainRelayers=i.d,exports.resolveStorage=i.f,exports.retryAfterSeconds=e.o,exports.revokeDelegationContract=D,exports.sepolia=a.c,exports.setOperatorContract=t.M,exports.supportsInterfaceContract=t.m,exports.symbolContract=t.x,exports.transferAndCallContract=w,exports.underlyingContract=t.N,exports.unwrapContract=t.P,exports.unwrapFromBalanceContract=t.F,exports.wrapContract=t.I;
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./relayer.cjs"),t=require("./sdk-events.cjs"),n=require("./token.cjs"),r=require("./cleartext.cjs"),i=require("./base-signer.cjs"),a=require("./chains.cjs");let o=require("viem"),s=require("zod/mini");function c(t,n){if(t instanceof e.r){let e=n[t.code];if(e)return e(t)}return n._?.(t)}var l=class extends e.r{encryptedValue;contractAddress;account;constructor(t,n){super(e.i.NotEntitled,`Account ${t.account} is not entitled to decrypt encrypted value ${t.encryptedValue} on contract ${t.contractAddress}. This is not a transient failure — the account needs an on-chain ACL grant before it can decrypt this encrypted value.`,n),this.name=`NotEntitledError`,this.encryptedValue=t.encryptedValue,this.contractAddress=t.contractAddress,this.account=t.account}},u=class extends e.r{constructor(t,n){super(e.i.DelegationSelfNotAllowed,t,n),this.name=`DelegationSelfNotAllowedError`}},d=class extends e.r{constructor(t,n){super(e.i.DelegationCooldown,t,n),this.name=`DelegationCooldownError`}},f=class extends e.r{constructor(t,n){super(e.i.DelegationNotFound,t,n),this.name=`DelegationNotFoundError`}},p=class extends e.r{constructor(t,n){super(e.i.DelegationExpired,t,n),this.name=`DelegationExpiredError`}},m=class extends e.r{constructor(t,n){super(e.i.DelegationExpiryUnchanged,t,n),this.name=`DelegationExpiryUnchangedError`}},h=class extends e.r{constructor(t,n){super(e.i.DelegationDelegateEqualsContract,t,n),this.name=`DelegationDelegateEqualsContractError`}},g=class extends e.r{constructor(t,n){super(e.i.DelegationContractIsSelf,t,n),this.name=`DelegationContractIsSelfError`}},_=class extends e.r{constructor(t,n){super(e.i.AclPaused,t,n),this.name=`AclPausedError`}},v=class extends e.r{constructor(t,n){super(e.i.DelegationExpirationTooSoon,t,n),this.name=`DelegationExpirationTooSoonError`}},y=class extends e.r{constructor(t,n){super(e.i.DelegationNotPropagated,t,n),this.name=`DelegationNotPropagatedError`}};const ee=[n.b,t.Y,e.n,y,t.K,t.G,l,n.v,t.J];function b(r,i,a={}){if(ee.some(e=>r instanceof e))return r;let o=r instanceof Error?r.message:i;if(r instanceof Error&&e.d(r.message))return new t.J(r.message,{cause:r});if(r instanceof Error&&e.f(r.message))return a.isDelegated?new y(`Delegated decryption was denied by the on-chain ACL check. This is most commonly caused by the delegation not having propagated yet, or by the RPC node serving a stale block. Propagation usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time. Retry shortly (and prefer a fresh, low-lag RPC endpoint). If it persists, the delegator may genuinely lack the on-chain ACL grant.`,{cause:r}):new l({encryptedValue:e.g(r.message)??``,contractAddress:a.contractAddress??``,account:a.account??``},{cause:r});if(e.l(r))return new n.v(o,{cause:r,retryAfter:e.c(r)});let s=e.s(r);return s===void 0&&e.h(r)?new n.v(o,{cause:r,retryAfter:e.c(r)}):s===400?new t.Y(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a.isDelegated&&s===500?new y(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet. Cross-chain sync usually completes within ~10 blocks (a few seconds) and the SDK retries across that window; seeing this means it did not sync in time — retry shortly. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):e.p(r)||s!==void 0?new e.n(o,s,{cause:r,retryAfter:e.c(r),retryable:e.m(r)||void 0}):new n.b(i,{cause:r})}function te(t,r){if(t instanceof e.r)return t;let i=e.s(t),a=e.m(t);return i!==void 0||e.p(t)?new e.n(t instanceof Error?t.message:r,i,{cause:t,retryAfter:e.c(t),retryable:a||void 0}):new n.x(r,{cause:t})}const ne=[{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 x(e,t,n,r=`0x`){return{address:e,abi:ne,functionName:`transferAndCall`,args:[t,n,r]}}const S=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function C(e,t,n,r){return{address:e,abi:S,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function w(e,t,n){return{address:e,abi:S,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function T(e,t,n,r){return{address:e,abi:S,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function re(e,t,n,r,i){return{address:e,abi:S,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const E=2n**64n-1n;function ie(e){return i.i(e.signer,e.provider,e)}function D(e){return e.startsWith(`0x`)?e:`0x${e}`}var O=class{#e;#t;#n;#r;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.router,this.#r=e.decryptionService}#i(e){return t.W(this.#r,e)}async decryptValues(e,t){let r=this.#i(`decryptValues`),i=await n.l(`decryptValues`,this.#e,this.#t);return r.decryptValues(e,i.address,t)}async delegatedDecryptValues(e,t,r=t,i){let a=this.#i(`delegatedDecryptValues`),o=await n.l(`delegatedDecryptValues`,this.#e,this.#t);return a.delegatedDecryptValues(e,t,o.address,r,i)}async decryptPublicValues(e,t){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{let r=await this.#n.relayer.decryptPublicValuesWithSignatures({encryptedValues:e,options:t}),i={};return r.checkSignaturesArgs.handlesList.forEach((e,t)=>{n.c(r.clearValues[t],`result.clearValues[${t}]`),i[e]=r.clearValues[t].value}),{clearValues:i,abiEncodedClearValues:r.checkSignaturesArgs.abiEncodedCleartexts,decryptionProof:r.checkSignaturesArgs.decryptionProof}}catch(e){throw b(e,`Public decryption failed`)}}async delegatedBatchDecryptValues({encryptedInputs:e,delegatorAddress:t,accountAddress:r=t,maxConcurrency:i,waitForPropagation:a}){let o=this.#i(`delegatedBatchDecryptValues`),s=await n.l(`delegatedBatchDecryptValues`,this.#e,this.#t);return o.delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:s.address,accountAddress:r,maxConcurrency:i,waitForPropagation:a})}},k=class{#e;#t;#n;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.delegationService}#r(e){return t.W(this.#e,e)}async delegateDecryption({contractAddress:e,delegateAddress:t,expirationDate:r}){let i=this.#r(`delegateDecryption`),a=await n.l(`delegateDecryption`,this.#e,this.#t);return this.#n.delegateDecryption(i,{contractAddress:e,delegateAddress:t,delegatorAddress:a.address,expirationDate:r})}async revokeDelegation({contractAddress:e,delegateAddress:t}){let r=this.#r(`revokeDelegation`),i=await n.l(`revokeDelegation`,this.#e,this.#t);return this.#n.revokeDelegation(r,{contractAddress:e,delegateAddress:t,delegatorAddress:i.address})}async isActive(e){return this.#n.isDelegated(e)}async getExpiry(e){return this.#n.getDelegationExpiry(e)}async getStatus(e){return this.#n.getStatus(e)}},A=class{#e;#t;#n;#r;#i;constructor(e){this.#e=e.signer,this.#t=e.provider,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger}#a(e){return t.W(this.#r,e)}async grantPermit(e){if(e.length===0)return;let t=this.#a(`grantPermit`);await n.u(`grantPermit`,this.#e,this.#t),await t.grantPermit(e)}async grantDelegationPermit(e,t){if(t.length===0)return;let r=this.#a(`grantDelegationPermit`);await n.u(`grantDelegationPermit`,this.#e,this.#t),await r.grantPermit(t,e)}async hasPermit(e){return this.#r?this.#r.hasPermit(e):!1}async hasDelegationPermit(e,t){return this.#r?this.#r.hasPermit(t,e):!1}async warmTransportKeyPair(){let e=this.#r;if(!e)return;let t=this.#e?.walletAccount.getSnapshot();t&&await e.warmTransportKeyPair(t.address)}async revokePermits(e){let t=this.#a(`revokePermits`),r=(0,o.getAddress)((await n.l(`revokePermits`,this.#e,this.#t)).address);try{await t.revokePermits(e)}finally{await this.#o(r)}}async clear(){let e=this.#a(`clear`),t=(0,o.getAddress)((await n.l(`clear`,this.#e,this.#t)).address);try{await e.clearCredentials()}finally{await this.#o(t)}}async#o(e){await t.z(`clear decrypt cache`,()=>this.#n.clearForRequester(e),this.#i)}async revokeTransportKeyPair(e){await this.#a(`revokeTransportKeyPair`).revokeTransportKeyPair(e)}async warmTransportKeyPairScope(e){await this.#a(`warmTransportKeyPairScope`).warmTransportKeyPairScope(e)}};const ae=s.z.union([s.z.bigint(),s.z.boolean(),i.l]),oe=s.z.array(s.z.string());var se=class{#e;#t;#n=`zama:decrypt`;#r=`${this.#n}:keys`;#i=Promise.resolve();constructor(e,t){this.#e=e,this.#t=t}async get(e,t,n){try{let r=this.#c(e,t,n),i=await this.#e.get(r);if(i===null)return null;let a=ae.safeParse(i);return a.success?a.data:(await this.delete(e,t,n),null)}catch(e){return this.#t.warn(`CachingService.get failed`,{error:e}),null}}async set(e,t,n,r){try{let i=this.#c(e,t,n);await this.#e.set(i,r),this.#i=this.#i.then(()=>this.#u(i).catch(e=>{this.#t.warn(`CachingService index write failed`,{error:e})})),await this.#i}catch(e){this.#t.warn(`CachingService.set failed`,{error:e})}}async delete(e,t,n){let r=this.#c(e,t,n);this.#i=this.#i.then(()=>this.#a(r).catch(e=>{this.#t.warn(`CachingService.delete failed`,{error:e})})),await this.#i}async clearForRequester(e){this.#i=this.#i.then(()=>this.#o(e).catch(e=>{this.#t.warn(`CachingService.clearForRequester failed`,{error:e})})),await this.#i}async clearAll(){this.#i=this.#i.then(()=>this.#s().catch(e=>{this.#t.warn(`CachingService.clearAll failed`,{error:e})})),await this.#i}async#a(e){await this.#e.delete(e).catch(()=>{});let t=await this.#l(),n=t.filter(t=>t!==e);n.length!==t.length&&await this.#e.set(this.#r,n)}async#o(e){let t=(0,o.getAddress)(e),n=`${this.#n}:${t}:`,r=await this.#l(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#r,a)}async#s(){let e=await this.#l();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#r)}#c(e,t,n){return`${this.#n}:${(0,o.getAddress)(e)}:${(0,o.getAddress)(t)}:${n.toLowerCase()}`}async#l(){let e=await this.#e.get(this.#r);if(e===null)return[];let t=oe.safeParse(e);return t.success?t.data:(await this.#e.delete(this.#r).catch(()=>{}),[])}async#u(e){let t=await this.#l();t.includes(e)||(t.push(e),await this.#e.set(this.#r,t))}};function ce(e,t){let r=le(e,t);if(!r)throw new n.b(`No permit covers contract ${t} after allow()`);return{privateKey:e.keypair.privateKey,publicKey:e.keypair.publicKey,serializedPermit:r.serializedPermit}}function le(e,t){let n=i.c(t);return e.permissions.find(e=>e.contractAddresses.includes(n))}const ue=e=>new Promise(t=>setTimeout(t,e));var de=class{#e;#t;#n;#r;#i;constructor({cache:e,credentialService:t,delegationService:n,router:r,emitEvent:i}){this.#e=e,this.#t=t,this.#n=n,this.#r=r,this.#i=i}async decryptValues(e,t,n){let r=(0,o.getAddress)(t);return this.#s(e,{requesterAddress:r,aclActorAddress:r,resolveCredentials:e=>this.#t.grantPermit(e),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt encrypted values`},n)}async delegatedDecryptValues(e,t,n,r,i){let a=(0,o.getAddress)(t),s=(0,o.getAddress)(n);return this.#a(i?.waitForPropagation??!0,()=>this.#s(e,{requesterAddress:(0,o.getAddress)(r),aclActorAddress:a,resolveCredentials:e=>this.#t.grantPermit(e,a),validate:e=>this.#f(e,{delegatorAddress:a,delegateAddress:s}),decryptContract:({credentials:e,contractAddress:t,encryptedValues:n,options:r})=>this.#o(e,t,n,r),errorMessage:`Failed to decrypt delegated encrypted values`,delegated:!0}))}async#a(e,t){let n;for(let r=0;r<16;r++)try{return await t()}catch(t){if(n=t,!(r<15&&e&&t instanceof y))throw t;await ue(2e3)}throw n}async delegatedBatchDecryptHandlesAs({encryptedInputs:e,delegatorAddress:t,delegateAddress:r,accountAddress:i,maxConcurrency:a=5,waitForPropagation:s=!0}){let c=e.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,o.getAddress)(e.contractAddress)}));if(c.length===0)return{items:c};let l=(0,o.getAddress)(i);try{let e=await this.delegatedDecryptValues(c.map(({encryptedValue:e,contractAddress:t})=>({encryptedValue:e,contractAddress:t})),t,r,l,{waitForPropagation:s});for(let t of c)this.#l(t,e);return{items:c}}catch(e){if(n.d(e))throw e;if(c.length===1){let[n=this.#d()]=c;return n.error=this.#u(e,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:n.contractAddress,account:(0,o.getAddress)(t)}),{items:c}}}let u=!1;return await n.r(c.map(e=>async()=>{if(!u)try{let n=await this.delegatedDecryptValues([{encryptedValue:e.encryptedValue,contractAddress:e.contractAddress}],t,r,l,{waitForPropagation:!1});this.#l(e,n)}catch(r){if(n.d(r))throw u=!0,r;e.error=this.#u(r,`Failed to decrypt delegated encrypted values`,{isDelegated:!0,contractAddress:e.contractAddress,account:(0,o.getAddress)(t)})}}),a),{items:c}}async#o(t,n,r,i){let a=ce(t,n),o;try{o=await this.#r.relayer.parseTransportKeyPair({publicKey:a.publicKey,privateKey:a.privateKey,tkmsVersion:t.keypair.tkmsVersion})}catch(t){throw t instanceof Error&&e.d(t.message)&&await this.#t.evictTransportKeyPair(),t}let s=await this.#r.relayer.parseSignedDecryptionPermit({transportKeyPair:o,serializedPermit:a.serializedPermit});return this.#r.relayer.decryptValues({transportKeyPair:o,signedPermit:s,encryptedValues:r,contractAddress:n,options:i})}async#s(r,i,a){if(r.length===0)return{};let s=r.map(e=>({encryptedValue:e.encryptedValue,contractAddress:(0,o.getAddress)(e.contractAddress)})),c={},l=[];for(let e of s)n.o(e.encryptedValue)?c[e.encryptedValue]=0n:l.push(e);if(l.length===0)return c;let u=Array.from(new Set(s.map(e=>e.contractAddress))),d=Array.from(new Set(l.map(e=>e.contractAddress)));if(i.validate)try{await i.validate(d)}catch(t){throw e.h(t)?this.#c(t,`the delegation pre-check`):t}let f=[];for(let e of l){let t=await this.#e.get(i.requesterAddress,e.contractAddress,e.encryptedValue);t===null?f.push(e):c[e.encryptedValue]=t}if(f.length===0)return c;let p=await i.resolveCredentials(u),m=new Map;for(let e of f){let t=m.get(e.contractAddress);t?t.push(e.encryptedValue):m.set(e.contractAddress,[e.encryptedValue])}let h=[];for(let[e,t]of m)for(let r of n.a(t))h.push({contractAddress:e,encryptedValues:r});let g=Date.now(),_=f.map(e=>e.encryptedValue);try{this.#i({type:t.t.DecryptStart,encryptedValues:_}),await n.r(h.map(({contractAddress:e,encryptedValues:t})=>async()=>{let r;try{r=await i.decryptContract({credentials:p,contractAddress:e,encryptedValues:t,options:a})}catch(t){throw b(t,i.errorMessage,{isDelegated:i.delegated,contractAddress:e,account:i.aclActorAddress})}for(let n=0;n<t.length;n++){let a=t[n],o=r[n]?.value;a!==void 0&&o!==void 0&&(c[a]=o,await this.#e.set(i.requesterAddress,e,a,o))}let o=t.filter(e=>c[e]===void 0);if(o.length>0)throw new n.b(`${i.errorMessage}: relayer returned no clear value for ${o.length} of ${t.length} handle(s) on ${e}`,{cause:AggregateError(o.map(t=>new n.b(`No clear value for handle ${t} on ${e}`)),`${o.length} handle(s) missing a clear value on ${e}`)})}),5);let e={};for(let t of _){let n=c[t];n!==void 0&&(e[t]=n)}return this.#i({type:t.t.DecryptEnd,durationMs:Date.now()-g,encryptedValues:_,result:e}),c}catch(n){let r=n instanceof e.r&&n.cause instanceof Error?n.cause:n;throw this.#i({type:t.t.DecryptError,error:e._(r),durationMs:Date.now()-g,encryptedValues:_}),b(n,i.errorMessage,{isDelegated:i.delegated})}}#c(t,r){return new n.v(`RPC provider rate-limited ${r}; retry with backoff.`,{cause:t,retryAfter:e.c(t)})}#l(e,t){let r=t[e.encryptedValue];if(r===void 0){e.error=new n.b(`Batch delegated decryption returned no value for encrypted value ${e.encryptedValue} on contract ${e.contractAddress}`);return}e.value=r}#u(t,n,r){return t instanceof e.r?t:b(t,n,r)}#d(){throw new n.b(`Batch delegated decryption invariant failed: missing item`)}async#f(e,{delegatorAddress:t,delegateAddress:n}){let r=await this.#n.findInactiveDelegations(e,t,n);if(r.size!==0)for(let e of r.values())throw e}};function fe(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}const j={AlreadyDelegatedOrRevokedInSameBlock:e=>new d(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new g(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new _(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new u(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new h(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new v(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new m(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new f(`Cannot revoke: no active delegation exists.`,{cause:e})};function pe(e){return e in j}function me(e,t){let n=fe(e);if(n&&pe(n))return j[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(j))if(r.includes(e))return n(t);return null}var he=class{#e;#t;#n;#r;constructor({provider:e,router:t,emitEvent:n=()=>{},logger:r}){this.#t=e,this.#e=t,this.#r=r,this.#n=n}async delegateDecryption(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r,expirationDate:i}){if(i&&i.getTime()<Date.now()+36e5)throw new v(`Expiration date must be at least 1 hour in the future`);let a=(0,o.getAddress)(t),s=(0,o.getAddress)(n),c=(0,o.getAddress)(r);if(s===c)throw new u(`Cannot delegate to yourself (delegate === msg.sender).`);if(s===a)throw new h(`Delegate address cannot be the same as the contract address (${a}).`);let l=this.#e.relayer.chain.aclContractAddress,d=i?BigInt(Math.floor(i.getTime()/1e3)):E,f;try{f=await this.getDelegationExpiry({contractAddress:a,delegatorAddress:c,delegateAddress:s})}catch(e){this.#r.warn(`delegateDecryption: pre-flight expiry check failed`,{error:e}),f=-1n}if(f===d)throw new m(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);return this.#i({operation:`delegateDecryption`,signer:e,contractAddress:t,config:C(l,s,a,d)})}async revokeDelegation(e,{contractAddress:t,delegateAddress:n,delegatorAddress:r}){let i=(0,o.getAddress)(t),a=(0,o.getAddress)(n),s=(0,o.getAddress)(r),c=this.#e.relayer.chain.aclContractAddress,l;try{l=await this.getDelegationExpiry({contractAddress:i,delegatorAddress:s,delegateAddress:a})}catch(e){this.#r.warn(`revokeDelegation: pre-flight expiry check failed`,{error:e}),l=1n}if(l===0n)throw new f(`No active delegation found for delegate ${a} on contract ${i}.`);return this.#i({operation:`revokeDelegation`,signer:e,contractAddress:t,config:w(c,a,i)})}async isDelegated(e){return(await this.getStatus(e)).isActive}async getStatus(e){let t=await this.getDelegationExpiry(e);return t===0n?{isActive:!1,expiryTimestamp:t}:t===E?{isActive:!0,expiryTimestamp:t}:{isActive:t>await this.#t.getBlockTimestamp(),expiryTimestamp:t}}async getDelegationExpiry({contractAddress:e,delegatorAddress:t,delegateAddress:n}){let r=this.#e.relayer.chain.aclContractAddress;return this.#t.readContract(T(r,(0,o.getAddress)(t),(0,o.getAddress)(n),(0,o.getAddress)(e)))}async#i({operation:e,signer:t,contractAddress:r,config:i}){try{return await n.n({operation:e,signer:t,provider:this.#t,config:i,emit:e=>this.#n(e,r),logger:this.#r})}catch(e){throw this.#a(e),e}}#a(e){if(!(e instanceof n.y))return;let t=me(e.cause??e,e);if(t)throw t}async findInactiveDelegations(e,t,n){let r=new Map;return await Promise.all(e.map(async e=>{try{await this.assertDelegationActive(e,t,n)}catch(t){if(t instanceof f||t instanceof p){let n=(0,o.getAddress)(e);r.set(n,t);return}throw t}})),r}async assertDelegationActive(e,t,n){let r=(0,o.getAddress)(e),i=(0,o.getAddress)(t),a=(0,o.getAddress)(n),{isActive:s,expiryTimestamp:c}=await this.getStatus({contractAddress:r,delegatorAddress:i,delegateAddress:a});if(!s)throw c===0n?new f(`No active delegation from ${i} to ${a} for ${r}`):new p(`Delegation from ${i} to ${a} for ${r} has expired`)}},ge=class{#e;#t;constructor({router:e,emitEvent:t}){this.#e=e,this.#t=t}async encryptValues(n,r){let i=Date.now(),a=(0,o.getAddress)(n.contractAddress);try{this.#t({type:t.t.EncryptStart},a);let e=await this.#e.relayer.encryptValues({...n,options:r});return this.#t({type:t.t.EncryptEnd,durationMs:Date.now()-i},a),e}catch(n){throw this.#t({type:t.t.EncryptError,error:e._(n),durationMs:Date.now()-i},a),te(n,`Encryption failed`)}}},_e=class{#e;#t;#n;#r;#i;#a=new Set;#o;constructor(e){this.#e=e.signer,this.#t=e.router,this.#n=e.cachingService,this.#r=e.credentialService,this.#i=e.logger,this.#e&&(this.#o=this.#e.walletAccount.subscribe(e=>{this.#s(e).catch(e=>{this.#i.warn(`wallet account handler failed`,{error:e})})}))}onWalletAccountChange(e){return this.#a.add(e),()=>{this.#a.delete(e)}}dispose(){this.#o?.(),this.#o=void 0,this.#a.clear()}async#s(e){let n=e.previous,r=e.next,i=r?.chainId;i!==void 0&&await t.z(`switch relayer chain`,()=>this.#t.switchChain(i),this.#i);let a=this.#r;a&&await t.z(`credential wallet account change`,()=>a.handleWalletAccountChange(n,r),this.#i),n&&await t.z(`clear decrypt cache`,()=>this.#n.clearForRequester(n.address),this.#i),await Promise.all(Array.from(this.#a,n=>t.z(`wallet account listener`,()=>n(e),this.#i)))}};function M(e){return(0,o.keccak256)((0,o.toBytes)(e))}const N={ConfidentialTransfer:M(`ConfidentialTransfer(address,address,bytes32)`),Wrap:M(`Wrap(address,uint256,bytes32)`),UnwrapRequested:M(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapFinalized:M(`UnwrapFinalized(address,bytes32,bytes32,uint64)`)};function P(e){return(0,o.getAddress)(D(e.slice(-40)))}function F(e){return e}function I(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function L(e,t){return(0,o.getAddress)(D(I(e,t).slice(-40)))}function R(e,t){return BigInt(`0x`+I(e,t))}function z(e,t){return D(I(e,t))}function B(e){return e.topics[0]!==N.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:P(e.topics[1]),to:P(e.topics[2]),encryptedAmount:F(e.topics[3])}}function V(e){return e.topics[0]!==N.Wrap||e.topics.length<2?null:{eventName:`Wrap`,to:P(e.topics[1]),roundedAmount:R(e.data,0),encryptedWrappedAmount:z(e.data,1)}}function H(e){return e.topics[0]!==N.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:P(e.topics[1]),unwrapRequestId:F(e.topics[2]),encryptedAmount:z(e.data,0)}}function U(e){return e.topics[0]!==N.UnwrapFinalized||e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:P(e.topics[1]),unwrapRequestId:F(e.topics[2]),encryptedAmount:z(e.data,0),cleartextAmount:R(e.data,1)}}function W(e){return B(e)??V(e)??H(e)??U(e)}function ve(e){let t=[];for(let n of e){let e=W(n);e&&t.push(e)}return t}function G(e){for(let t of e){let e=H(t);if(e)return e}return null}function ye(e){for(let t of e){let e=V(t);if(e)return e}return null}const be=[N.ConfidentialTransfer,N.Wrap,N.UnwrapRequested,N.UnwrapFinalized],K={DelegatedForUserDecryption:M(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:M(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function q(e){return e.topics[0]!==K.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:P(e.topics[1]),delegate:P(e.topics[2]),contractAddress:L(e.data,0),delegationCounter:R(e.data,1),oldExpirationDate:R(e.data,2),newExpirationDate:R(e.data,3)}}function J(e){return e.topics[0]!==K.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:P(e.topics[1]),delegate:P(e.topics[2]),contractAddress:L(e.data,0),delegationCounter:R(e.data,1),oldExpirationDate:R(e.data,2)}}function Y(e){return q(e)??J(e)}function xe(e){let t=[];for(let n of e){let e=Y(n);e&&t.push(e)}return t}function Se(e){for(let t of e){let e=q(t);if(e)return e}return null}function Ce(e){for(let t of e){let e=J(t);if(e)return e}return null}const we=[K.DelegatedForUserDecryption,K.RevokedDelegationForUserDecryption];function X(e){return`zama:pending-unshield:${i.c(e)}`}const Te=s.z.union([s.z.pipe(i.u,s.z.transform(e=>({unwrapTxHash:e}))),s.z.pipe(s.z.object({version:s.z.literal(1),unwrapTxHash:i.u,unwrapRequestId:s.z.optional(i.u)}),s.z.transform(({unwrapTxHash:e,unwrapRequestId:t})=>({unwrapTxHash:e,unwrapRequestId:t})))]);async function Z(e,t,n,r){if(r===void 0){await e.set(X(t),n);return}await e.set(X(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ee(e,t){return(await De(e,t))?.unwrapTxHash??null}async function De(e,t){let n=X(t),r=await e.get(n);if(r==null)return null;let i=Te.safeParse(r);return i.success?i.data:(await e.delete(n),null)}async function Oe(e,t){await e.delete(X(t))}var Q=class extends n.t{#e;#t=null;#n=null;#r(e){try{return n.c(this.sdk.signer,`WrappedToken.sdk.signer`),this.sdk.signer}catch(n){throw new t.B(e,{cause:n})}}async underlying(){return this.#s()}async isPayable(){if(this.#n!==null)return this.#n;try{let e=await this.#s();this.#n=await this.sdk.provider.readContract(t.h(e))}catch{this.#n=!1}return this.#n}async allowance(e){let n=await this.#s();return this.sdk.provider.readContract(t._(n,(0,o.getAddress)(e),this.address))}async shield(r,i){let a=await n.l(`shield`,this.sdk.signer,this.sdk.provider),s=await this.isPayable(),c=await this.#s(),l=(0,o.getAddress)(a.address),u;try{u=await this.sdk.provider.readContract(t.y(c,l))}catch(t){throw t instanceof e.r?t:new n.p(`Could not read ERC-20 balance for shield validation (token: ${c})`,{cause:e._(t)})}if(u<r)throw new n.g(`Insufficient ERC-20 balance: requested ${r}, available ${u} (token: ${c})`,{requested:r,available:u,token:c});return s?this.#i(r,c,l,i):this.#a(r,l,i)}async#i(e,t,n,r){this.#r(`shield`);let i=r?.to?(0,o.getAddress)(r.to):n,a=i===n?`0x`:i;return this.submitTransaction({operation:`shield:transferAndCall`,config:x(t,this.address,e,a),onSubmitted:r?.onShieldSubmitted})}async wrap(r,i){this.#r(`wrap`);let a=await n.l(`wrap`,this.sdk.signer,this.sdk.provider),s=await this.#s(),c=(0,o.getAddress)(a.address),l;try{l=await this.sdk.provider.readContract(t.y(s,c))}catch(t){throw t instanceof e.r?t:new n.p(`Could not read ERC-20 balance for wrap validation (token: ${s})`,{cause:e._(t)})}if(l<r)throw new n.g(`Insufficient ERC-20 balance: requested ${r}, available ${l} (token: ${s})`,{requested:r,available:l,token:s});let u;try{u=await this.sdk.provider.readContract(t._(s,c,this.address))}catch(t){throw t instanceof e.r?t:new n.p(`Could not read ERC-20 allowance for wrap validation (token: ${s})`,{cause:e._(t)})}if(u<r)throw new n.m(`Insufficient allowance for wrap: requested ${r}, approved ${u}. Call approveUnderlying() first (token: ${s}).`,{requested:r,available:u,token:s});let d=i?.to?(0,o.getAddress)(i.to):c;return this.submitTransaction({operation:`wrap`,config:t.R(this.address,d,r),onSubmitted:i?.onWrapSubmitted})}async#a(e,n,r){this.#r(`shield`);let i=r?.approvalStrategy??`exact`;i!==`skip`&&await this.#l(e,i===`max`,r);let a=r?.to?(0,o.getAddress)(r.to):n;return this.submitTransaction({operation:`shield:approveAndWrap`,config:t.R(this.address,a,e),onSubmitted:r?.onShieldSubmitted})}async approveUnderlying(e){this.#r(`approveUnderlying`);let r=await n.l(`approveUnderlying`,this.sdk.signer,this.sdk.provider),i=await this.#s(),a=(0,o.getAddress)(r.address),s=e??2n**256n-1n;return s>0n&&await this.sdk.provider.readContract(t._(i,a,this.address))>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(i,this.address,0n)}),this.submitTransaction({operation:`approveUnderlying`,config:t.v(i,this.address,s)})}async unshield(e,n){let{skipBalanceCheck:r=!1,onUnwrapSubmitted:i,onFinalizing:a,onFinalizeSubmitted:o}=n??{};r||await this.assertConfidentialBalance(e);let s={onFinalizing:a,onFinalizeSubmitted:o},c=crypto.randomUUID(),l=await this.unwrap(e);return t.z(`unshield: onUnwrapSubmitted`,()=>i?.(l.txHash),this.sdk.logger),this.#c(l.unwrapRequestId,l.txHash,c,s)}async unshieldAll(e){let n=crypto.randomUUID(),r=await this.unwrapAll();return t.z(`unshieldAll: onUnwrapSubmitted`,()=>e?.onUnwrapSubmitted?.(r.txHash),this.sdk.logger),this.#c(r.unwrapRequestId,r.txHash,n,e)}async resumeUnshield(t,r){let i;try{i=await this.sdk.provider.waitForTransactionReceipt(t)}catch(t){throw t instanceof e.r?t:new n.y(`Failed to get unwrap receipt`,{cause:t})}let a=this.#o(i.logs);return this.#c(a,t,crypto.randomUUID(),r)}async getPendingUnshield(){return Ee(this.sdk.storage,this.address)}async unwrap(e){this.#r(`unwrap`);let r=(0,o.getAddress)((await n.l(`unwrap`,this.sdk.signer,this.sdk.provider)).address),{encryptedValues:i,inputProof:a}=await this.sdk.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.address,userAddress:r}),[s]=i;if(!s)throw new n.x(`Encryption returned no encrypted values`);let c=await this.submitTransaction({operation:`unwrap`,config:t.I(this.address,r,r,s,a)});return{...c,unwrapRequestId:this.#o(c.receipt.logs)}}async unwrapAll(){this.#r(`unwrapAll`);let e=(0,o.getAddress)((await n.l(`unwrapAll`,this.sdk.signer,this.sdk.provider)).address),r=await this.readConfidentialBalanceOf(e);if(n.o(r))throw new n.b(`Cannot unshield: balance is zero`);let i=await this.submitTransaction({operation:`unwrapAll`,config:t.L(this.address,e,e,r)});return{...i,unwrapRequestId:this.#o(i.receipt.logs)}}async finalizeUnwrap(e){this.#r(`finalizeUnwrap`),await n.u(`finalizeUnwrap`,this.sdk.signer,this.sdk.provider);let r=await this.sdk.decryption.decryptPublicValues([e]),i=r.clearValues[e];return n.s(i,`finalizeUnwrap: clearValue`),this.submitTransaction({operation:`finalizeUnwrap`,config:t.A(this.address,e,i,r.decryptionProof)})}#o(e){let t=G(e);if(!t)throw new n.y(`No UnwrapRequested event found in unwrap receipt`);return t.unwrapRequestId}async#s(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(t.F(this.address)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async#c(e,n,r,i){this.emit({type:t.t.UnshieldPhase1Submitted,txHash:n,operationId:r}),await t.z(`unshield: savePendingUnshield`,()=>Z(this.sdk.storage,this.address,n),this.sdk.logger),this.emit({type:t.t.UnshieldPhase2Started,operationId:r}),t.z(`unshield: onFinalizing`,()=>i?.onFinalizing?.(),this.sdk.logger);let a=await this.finalizeUnwrap(e);return this.emit({type:t.t.UnshieldPhase2Submitted,txHash:a.txHash,operationId:r}),t.z(`unshield: onFinalizeSubmitted`,()=>i?.onFinalizeSubmitted?.(a.txHash),this.sdk.logger),await t.z(`unshield: clearPendingUnshield`,()=>Oe(this.sdk.storage,this.address),this.sdk.logger),a}async#l(e,r,i){this.#r(`approveUnderlying`);let a=await this.#s(),s=(0,o.getAddress)((await n.l(`approveUnderlying`,this.sdk.signer,this.sdk.provider)).address),c=await this.sdk.provider.readContract(t._(a,s,this.address));if(c>=e)return;c>0n&&await this.submitTransaction({operation:`approveUnderlying:reset`,config:t.v(a,this.address,0n)});let l=r?2n**256n-1n:e;await this.submitTransaction({operation:`approveUnderlying`,config:t.v(a,this.address,l),onSubmitted:i?.onApprovalSubmitted})}},ke=class{#e;provider;signer;storage;registry;permits;delegations;decryption;#t;#n;#r;#i;#a;#o;#s;#c;#l;#u;constructor(e){this.#e=e.router,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.#r=e.onEvent??function(){},this.#i=e.logger,this.#a=new se(e.storage,this.#i),this.#u=new he({provider:this.provider,router:e.router,emitEvent:this.emitEvent.bind(this),logger:this.#i});let t={};for(let n of e.chains)n.registryAddress&&(t[n.id]=n.registryAddress);this.registry=new i.o({provider:this.provider,registryAddresses:t,registryTTL:e.registryTTL}),this.#n=t,this.#t=e.registryTTL,e.signer&&(this.#l=new i.s({router:e.router,signer:e.signer,transportKeyPairTTL:e.transportKeyPairTTL,permitTTL:e.permitTTL,scope:e.transportKeyPairScope,storage:this.storage,permitStorage:e.permitStorage,logger:this.#i}),this.#c=new de({cache:this.#a,credentialService:this.#l,delegationService:this.#u,router:e.router,emitEvent:this.emitEvent.bind(this)})),this.#s=new ge({router:e.router,emitEvent:this.emitEvent.bind(this)}),this.#o=new _e({signer:e.signer,router:e.router,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.permits=new A({signer:this.signer,provider:this.provider,cachingService:this.#a,credentialService:this.#l,logger:this.#i}),this.delegations=new k({signer:this.signer,provider:this.provider,delegationService:this.#u}),this.decryption=new O({signer:this.signer,provider:this.provider,router:e.router,decryptionService:this.#c})}onWalletAccountChange(e){return this.#o.onWalletAccountChange(e)}get logger(){return this.#i}get relayer(){return this.#e.relayer}emitEvent(e,t){try{this.#r({...e,tokenAddress:t,timestamp:Date.now()})}catch(t){this.#i.warn(`${e.type} event listener silently failed`,{error:t})}}createWrappersRegistry(e){return new i.o({provider:this.provider,registryAddresses:{...this.#n,...e},registryTTL:this.#t})}async encrypt(e,t){return this.#s.encryptValues(e,t)}createToken(e){return new n.t(this,e)}createWrappedToken(e){return new Q(this,e)}dispose(){this.#o.dispose()}terminate(){this.dispose(),this.signer?.dispose?.()}[Symbol.dispose](){this.terminate()}},$=class{async get(e){return(await chrome.storage.session.get(e))[e]??null}async set(e,t){await chrome.storage.session.set({[e]:t})}async delete(e){await chrome.storage.session.remove(e)}};const Ae=new $;exports.ACL_TOPICS=we,exports.AclPausedError=_,exports.AclTopics=K,exports.BalanceCheckUnavailableError=n.f,exports.BaseSigner=i.t,exports.ChainMismatchError=n._,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.Decryption=O,exports.DecryptionFailedError=n.b,exports.DefaultRegistryAddresses=i.a,exports.DelegationContractIsSelfError=g,exports.DelegationCooldownError=d,exports.DelegationDelegateEqualsContractError=h,exports.DelegationExpirationTooSoonError=v,exports.DelegationExpiredError=p,exports.DelegationExpiryUnchangedError=m,exports.DelegationNotFoundError=f,exports.DelegationNotPropagatedError=y,exports.DelegationSelfNotAllowedError=u,exports.Delegations=k,exports.ERC1363_INTERFACE_ID=t.u,exports.ERC20ReadFailedError=n.p,exports.ERC7984_INTERFACE_ID=t.d,exports.ERC7984_WRAPPER_INTERFACE_ID=t.f,exports.EncryptionFailedError=n.x,exports.IndexedDBStorage=i.p,exports.InsufficientAllowanceError=n.m,exports.InsufficientConfidentialBalanceError=n.h,exports.InsufficientERC20BalanceError=n.g,exports.InvalidTransportKeyPairError=t.J,exports.MemoryStorage=i.d,exports.MutableWalletAccountStore=i.n,exports.NoCiphertextError=t.Y,exports.NotEntitledError=l,exports.Permits=A,exports.RelayerRequestFailedError=e.n,exports.RpcRateLimitError=n.v,exports.SignerNotConfiguredError=t.B,exports.SignerRequiredError=t.V,exports.SigningFailedError=t.G,exports.SigningRejectedError=t.K,exports.TOKEN_TOPICS=be,exports.Token=n.t,exports.Topics=N,exports.TransactionRevertedError=n.y,exports.TransportKeyPairExpiredError=t.X,exports.WalletAccountNotReadyError=t.H,exports.WalletNotConnectedError=t.U,exports.WrappedToken=Q,exports.WrappersRegistry=i.o,exports.ZERO_ENCRYPTED_VALUE=n.i,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=ke,exports.ZamaSDKEvents=t.t,exports.allowanceContract=t._,exports.anvil=a.t,exports.approveContract=t.v,exports.balanceOfContract=t.y,exports.bscTestnet=a.n,exports.chains=a.r,exports.chromeSessionStorage=Ae,exports.cleartext=r.t,exports.confidentialBalanceOfContract=t.w,exports.confidentialTotalSupplyContract=t.T,exports.confidentialTransferContract=t.D,exports.confidentialTransferFromContract=t.k,exports.createConfig=ie,exports.createWalletAccountStore=i.r,exports.decimalsContract=t.b,exports.decodeAclEvent=Y,exports.decodeAclEvents=xe,exports.decodeConfidentialTransfer=B,exports.decodeDelegatedForUserDecryption=q,exports.decodeOnChainEvent=W,exports.decodeOnChainEvents=ve,exports.decodeRevokedDelegationForUserDecryption=J,exports.decodeUnwrapFinalized=U,exports.decodeUnwrapRequested=H,exports.decodeWrap=V,exports.delegateForUserDecryptionContract=C,exports.finalizeUnwrapContract=t.A,exports.findDelegatedForUserDecryption=Se,exports.findRevokedDelegationForUserDecryption=Ce,exports.findUnwrapRequested=G,exports.findWrap=ye,exports.getConfidentialTokenAddressContract=t.r,exports.getDelegationExpiryContract=T,exports.getTokenAddressContract=t.i,exports.getTokenPairContract=t.a,exports.getTokenPairsContract=t.o,exports.getTokenPairsLengthContract=t.s,exports.getTokenPairsSliceContract=t.c,exports.hardhat=a.i,exports.hoodi=a.a,exports.indexedDBStorage=i.m,exports.inferredTotalSupplyContract=t.j,exports.ingenTestnet=a.o,exports.isConfidentialTokenContract=t.p,exports.isConfidentialTokenValidContract=t.l,exports.isConfidentialWrapperContract=t.m,exports.isEncryptedValueZero=n.o,exports.isHandleDelegatedContract=re,exports.isOperatorContract=t.M,exports.isRetryable=e.a,exports.mainnet=a.s,exports.matchZamaError=c,exports.memoryStorage=i.f,exports.nameContract=t.S,exports.rateContract=t.N,exports.retryAfterSeconds=e.o,exports.revokeDelegationContract=w,exports.sepolia=a.c,exports.setOperatorContract=t.P,exports.supportsInterfaceContract=t.g,exports.symbolContract=t.C,exports.transferAndCallContract=x,exports.underlyingContract=t.F,exports.unwrapContract=t.I,exports.unwrapFromBalanceContract=t.L,exports.wrapContract=t.R;
2
2
  //# sourceMappingURL=index.cjs.map