@zama-fhe/sdk 3.0.0-alpha.1 → 3.0.0-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -186,7 +186,7 @@ Full read/write interface for a single confidential ERC-20. Extends `ReadonlyTok
186
186
  | `unwrap(amount)` | Request unwrap for a specific amount (low-level, requires manual finalization). |
187
187
  | `unwrapAll()` | Request unwrap for the entire balance (low-level, requires manual finalization). |
188
188
  | `resumeUnshield(unwrapTxHash, callbacks?)` | Resume an interrupted unshield from an existing unwrap tx hash. Goes straight to wait receipt → finalize. |
189
- | `finalizeUnwrap(burnAmountHandle)` | Complete unwrap with public decryption proof. |
189
+ | `finalizeUnwrap(unwrapRequestId)` | Complete unwrap with public decryption proof. |
190
190
  | `confidentialTransfer(to, amount)` | Encrypted transfer. Encrypts amount, then calls the contract. |
191
191
  | `confidentialTransferFrom(from, to, amt)` | Operator encrypted transfer. |
192
192
  | `approve(spender, until?)` | Set operator approval. `until` defaults to now + 1 hour. |
@@ -534,15 +534,15 @@ interface ContractCallConfig {
534
534
 
535
535
  ### Wrapper
536
536
 
537
- | Function | Description |
538
- | ---------------------------------------------------------------- | --------------------------------------------------- |
539
- | `wrapContract(wrapper, to, amount)` | Wrap ERC-20 tokens. |
540
- | `unwrapContract(token, from, to, encryptedAmount, inputProof)` | Request unwrap with encrypted amount. |
541
- | `unwrapFromBalanceContract(token, from, to, encryptedBalance)` | Request unwrap using on-chain balance handle. |
542
- | `finalizeUnwrapContract(wrapper, burntAmount, cleartext, proof)` | Finalize unwrap with decryption proof. |
543
- | `underlyingContract(wrapper)` | Read underlying ERC-20 address. |
544
- | `inferredTotalSupplyContract(wrapper)` | Read inferred plaintext total supply. |
545
- | `totalSupplyContract(wrapper)` | Deprecated alias for `inferredTotalSupplyContract`. |
537
+ | Function | Description |
538
+ | -------------------------------------------------------------------- | --------------------------------------------------- |
539
+ | `wrapContract(wrapper, to, amount)` | Wrap ERC-20 tokens. |
540
+ | `unwrapContract(token, from, to, encryptedAmount, inputProof)` | Request unwrap with encrypted amount. |
541
+ | `unwrapFromBalanceContract(token, from, to, encryptedBalance)` | Request unwrap using on-chain balance handle. |
542
+ | `finalizeUnwrapContract(wrapper, unwrapRequestId, cleartext, proof)` | Finalize unwrap with decryption proof. |
543
+ | `underlyingContract(wrapper)` | Read underlying ERC-20 address. |
544
+ | `inferredTotalSupplyContract(wrapper)` | Read inferred plaintext total supply. |
545
+ | `totalSupplyContract(wrapper)` | Deprecated alias for `inferredTotalSupplyContract`. |
546
546
 
547
547
  ### ERC-165
548
548
 
@@ -626,8 +626,8 @@ Individual topic hashes are accessible via the `Topics` object: `Topics.Confiden
626
626
  | --------------------------------- | ----------------------------------------------------------------------------------------------------------- |
627
627
  | `decodeConfidentialTransfer(log)` | `ConfidentialTransferEvent \| null` — `{ from, to, encryptedAmountHandle }` |
628
628
  | `decodeWrapped(log)` | `WrappedEvent \| null` — `{ to, amountIn }` |
629
- | `decodeUnwrapRequested(log)` | `UnwrapRequestedEvent \| null` — `{ receiver, encryptedAmount }` |
630
- | `decodeUnwrappedFinalized(log)` | `UnwrappedFinalizedEvent \| null` — `{ receiver, encryptedAmount, cleartextAmount }` |
629
+ | `decodeUnwrapRequested(log)` | `UnwrapRequestedEvent \| null` — `{ receiver, unwrapRequestId, encryptedAmount }` |
630
+ | `decodeUnwrappedFinalized(log)` | `UnwrappedFinalizedEvent \| null` — `{ receiver, unwrapRequestId, encryptedAmount, cleartextAmount }` |
631
631
  | `decodeUnwrappedStarted(log)` | `UnwrappedStartedEvent \| null` — `{ returnVal, requestId, txId, to, refund, requestedAmount, burnAmount }` |
632
632
  | `decodeOnChainEvent(log)` | `OnChainEvent \| null` — tries all decoders |
633
633
  | `decodeOnChainEvents(logs)` | `OnChainEvent[]` — batch decode, skips unrecognized logs |
@@ -752,7 +752,7 @@ Low-level FHE operations are available on the relayer backend via `sdk.relayer`:
752
752
  | ------------------------------ | --------------------------------- | --------------------------------------------- |
753
753
  | `ZERO_HANDLE` | `"0x0000...0000"` (32 zero bytes) | Sentinel for empty/zero encrypted values. |
754
754
  | `ERC7984_INTERFACE_ID` | `"0x4958f2a4"` | ERC-165 interface ID for confidential tokens. |
755
- | `ERC7984_WRAPPER_INTERFACE_ID` | `"0xd04584ba"` | ERC-165 interface ID for wrapper contracts. |
755
+ | `ERC7984_WRAPPER_INTERFACE_ID` | `"0xf1f4c25a"` | ERC-165 interface ID for wrapper contracts. |
756
756
 
757
757
  ## Exported ABIs
758
758
 
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["#readProvider","#eip1193","BrowserProvider","#signerPromise","#requireSigner","#requireProvider","eip1193Subscribe","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/ethers/ethers-signer.ts","../../../src/ethers/contracts.ts"],"sourcesContent":["import { ethers, BrowserProvider, type Signer } from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport type { EIP712TypedData } from \"../relayer/relayer-sdk.types\";\nimport type {\n GenericSigner,\n ReadContractConfig,\n SignerLifecycleCallbacks,\n TransactionReceipt,\n WriteContractConfig,\n} from \"../types\";\nimport { eip1193Subscribe } from \"../token/eip1193-subscribe\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Three variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and `subscribe()` works automatically.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * `subscribe()` is not available since there is no EIP-1193 provider.\n *\n * - **Read-only** — `{ provider }`: pass an ethers `Provider` for read-only contract calls.\n * Signing and write operations will throw at runtime.\n */\nexport type EthersSignerConfig =\n | { ethereum: EIP1193Provider }\n | { signer: Signer }\n | { provider: ethers.Provider };\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 implements GenericSigner {\n #signerPromise?: Promise<Signer>;\n readonly #readProvider?: ethers.Provider;\n readonly #eip1193?: EIP1193Provider;\n\n constructor(config: EthersSignerConfig) {\n if (\"ethereum\" in config) {\n const browserProvider = new BrowserProvider(config.ethereum);\n this.#signerPromise = browserProvider.getSigner();\n this.#readProvider = browserProvider;\n this.#eip1193 = config.ethereum;\n } else if (\"signer\" in config) {\n this.#signerPromise = Promise.resolve(config.signer);\n this.#readProvider = config.signer.provider ?? undefined;\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n async #requireSigner(): Promise<Signer> {\n if (!this.#signerPromise) {\n throw new TypeError(\"No signer configured — read-only mode\");\n }\n return this.#signerPromise;\n }\n\n #requireProvider(): ethers.Provider {\n if (!this.#readProvider) {\n throw new TypeError(\"Signer has no provider\");\n }\n return this.#readProvider;\n }\n\n async getChainId(): Promise<number> {\n const network = await this.#requireProvider().getNetwork();\n return Number(network.chainId);\n }\n\n async getAddress(): Promise<Address> {\n const signer = await this.#requireSigner();\n return getAddress(await signer.getAddress());\n }\n\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#requireSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([key, fields]) => [key, [...fields]]),\n );\n const sig = await signer.signTypedData(domain, 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.#requireSigner();\n const contract = new ethers.Contract(config.address, config.abi as ethers.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 tx = await contract[config.functionName]!(\n ...(config.args as readonly unknown[]),\n overrides,\n );\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\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 provider = this.#requireProvider();\n const contract = new ethers.Contract(\n config.address,\n config.abi as ethers.InterfaceAbi,\n provider,\n );\n return contract[config.functionName]!(...(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.#requireProvider().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.#requireProvider().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 subscribe(callbacks: SignerLifecycleCallbacks): () => void {\n return eip1193Subscribe(this.#eip1193, () => this.getAddress(), callbacks);\n }\n}\n","import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { Handle } from \"../relayer/relayer-sdk.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 handle: Uint8Array,\n inputProof: Uint8Array,\n) {\n return ethersWrite(signer, confidentialTransferContract(tokenAddress, to, handle, inputProof));\n}\n\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: Uint8Array,\n inputProof: Uint8Array,\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: Handle,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n burntAmount: Handle,\n burntAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, burntAmount, burntAmountCleartext, decryptionProof),\n );\n}\n\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n spender: Address,\n timestamp?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, spender, timestamp));\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":"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"}
1
+ {"version":3,"file":"index.cjs","names":["#readProvider","#eip1193","BrowserProvider","#signerPromise","#requireSigner","#requireProvider","eip1193Subscribe","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/ethers/ethers-signer.ts","../../../src/ethers/contracts.ts"],"sourcesContent":["import { ethers, BrowserProvider, type Signer } from \"ethers\";\nimport {\n getAddress,\n isHex,\n type Abi,\n type Address,\n type ContractFunctionArgs,\n type ContractFunctionName,\n type ContractFunctionReturnType,\n type EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport type { EIP712TypedData } from \"../relayer/relayer-sdk.types\";\nimport type {\n GenericSigner,\n ReadContractConfig,\n SignerLifecycleCallbacks,\n TransactionReceipt,\n WriteContractConfig,\n} from \"../types\";\nimport { eip1193Subscribe } from \"../token/eip1193-subscribe\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Three variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and `subscribe()` works automatically.\n *\n * - **Node / direct signer** — `{ signer }`: pass an ethers `Signer` (e.g. `Wallet`).\n * `subscribe()` is not available since there is no EIP-1193 provider.\n *\n * - **Read-only** — `{ provider }`: pass an ethers `Provider` for read-only contract calls.\n * Signing and write operations will throw at runtime.\n */\nexport type EthersSignerConfig =\n | { ethereum: EIP1193Provider }\n | { signer: Signer }\n | { provider: ethers.Provider };\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 implements GenericSigner {\n #signerPromise?: Promise<Signer>;\n readonly #readProvider?: ethers.Provider;\n readonly #eip1193?: EIP1193Provider;\n\n constructor(config: EthersSignerConfig) {\n if (\"ethereum\" in config) {\n const browserProvider = new BrowserProvider(config.ethereum);\n this.#signerPromise = browserProvider.getSigner();\n this.#readProvider = browserProvider;\n this.#eip1193 = config.ethereum;\n } else if (\"signer\" in config) {\n this.#signerPromise = Promise.resolve(config.signer);\n this.#readProvider = config.signer.provider ?? undefined;\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n async #requireSigner(): Promise<Signer> {\n if (!this.#signerPromise) {\n throw new TypeError(\"No signer configured — read-only mode\");\n }\n return this.#signerPromise;\n }\n\n #requireProvider(): ethers.Provider {\n if (!this.#readProvider) {\n throw new TypeError(\"Signer has no provider\");\n }\n return this.#readProvider;\n }\n\n async getChainId(): Promise<number> {\n const network = await this.#requireProvider().getNetwork();\n return Number(network.chainId);\n }\n\n async getAddress(): Promise<Address> {\n const signer = await this.#requireSigner();\n return getAddress(await signer.getAddress());\n }\n\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#requireSigner();\n const { domain, types, message } = typedData;\n const { EIP712Domain: _, ...sigTypes } = types;\n const mutableSigTypes = Object.fromEntries(\n Object.entries(sigTypes).map(([key, fields]) => [key, [...fields]]),\n );\n const sig = await signer.signTypedData(domain, 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.#requireSigner();\n const contract = new ethers.Contract(config.address, config.abi as ethers.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 tx = await contract[config.functionName]!(\n ...(config.args as readonly unknown[]),\n overrides,\n );\n if (!isHex(tx.hash)) {\n throw new TypeError(`Expected hex string, got: ${tx.hash}`);\n }\n return tx.hash;\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 provider = this.#requireProvider();\n const contract = new ethers.Contract(\n config.address,\n config.abi as ethers.InterfaceAbi,\n provider,\n );\n return contract[config.functionName]!(...(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.#requireProvider().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.#requireProvider().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 subscribe(callbacks: SignerLifecycleCallbacks): () => void {\n return eip1193Subscribe(this.#eip1193, () => this.getAddress(), callbacks);\n }\n}\n","import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { Handle } from \"../relayer/relayer-sdk.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 handle: Uint8Array,\n inputProof: Uint8Array,\n) {\n return ethersWrite(signer, confidentialTransferContract(tokenAddress, to, handle, inputProof));\n}\n\nexport function writeUnwrapContract(\n signer: EthersTransactionSigner,\n encryptedErc20: Address,\n from: Address,\n to: Address,\n encryptedAmount: Uint8Array,\n inputProof: Uint8Array,\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: Handle,\n) {\n return ethersWrite(signer, unwrapFromBalanceContract(encryptedErc20, from, to, encryptedBalance));\n}\n\nexport function writeFinalizeUnwrapContract(\n signer: EthersTransactionSigner,\n wrapper: Address,\n unwrapRequestId: Handle,\n burntAmountCleartext: bigint,\n decryptionProof: Hex,\n) {\n return ethersWrite(\n signer,\n finalizeUnwrapContract(wrapper, unwrapRequestId, burntAmountCleartext, decryptionProof),\n );\n}\n\nexport function writeSetOperatorContract(\n signer: EthersTransactionSigner,\n tokenAddress: Address,\n spender: Address,\n timestamp?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, spender, timestamp));\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":"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"}
@@ -511,5 +511,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
511
511
  };
512
512
  //#endregion
513
513
  })();
514
- `],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};function g(e){return e.startsWith(`0x`)?e:`0x${e}`}const _=8192,v=300*1e3;function y(e){let t=[];for(let n=0;n<e.length;n+=_)t.push(String.fromCharCode(...e.subarray(n,n+_)));return btoa(t.join(``))}function ae(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function b(e){return`fhe:pubkey:${e}`}function x(e,t){return`fhe:params:${e}:${t}`}function S(e){return`fhe:params-index:${e}`}function C(e){t.T(e,`CachedPublicKey`),t.D(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.D(e,`publicKey`,`CachedPublicKey.publicKey`)}function oe(e){t.T(e,`CachedPublicParams`),t.D(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.D(e,`publicParams`,`CachedPublicParams.publicParams`)}var se=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let n=b(this.#t);try{let e=await this.#e.get(n);if(e){C(e);let t={publicKeyId:e.publicKeyId,publicKey:ae(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.y(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:y(r.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:t.y(e).message})}return r}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,n){let r=x(this.#t,e);try{let t=await this.#e.get(r);if(t){oe(t);let n={publicParamsId:t.publicParamsId,publicParams:ae(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.y(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:y(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=S(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.y(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.y(n).message})}return i}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let n=b(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{C(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.y(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+v;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+v;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.y(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+v;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:t.y(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=S(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.y(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=x(this.#t,e),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:t.y(n).message}),null}if(!r)return null;try{return oe(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.y(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.y(n).message})})}async#_(e,n){let r=S(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:t.y(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,n,r){let i=[this.#e.set(e,n).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:t.y(e).message})}),...r.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:t.y(e).message})}))];await Promise.all(i)}},ce=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new m(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new se({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new ie(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,r,i=7){let a=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:r,durationDays:i}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:n.c(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.l(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.l(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},w=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#o(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#o(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#c(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async clearForRequester(e){this.#r=this.#r.then(()=>this.#i(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#i(e){let t=(0,i.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),a=[],o=[];for(let e of r)e.startsWith(n)?a.push(e):o.push(e);await Promise.all(a.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,o)}async clearAll(){this.#r=this.#r.then(()=>this.#a().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#a(){let e=await this.#s();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#o(e,t,n){return`${this.#t}:${(0,i.getAddress)(e)}:${(0,i.getAddress)(t)}:${n.toLowerCase()}`}async#s(){return await this.#e.get(this.#n)??[]}async#c(e){let t=await this.#s();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}},T=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const le=new T;var ue=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return g(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function de(e){t.T(e,`Stored credentials`),t.E(e.publicKey,`credentials.publicKey`),t.b(e.contractAddresses,`credentials.contractAddresses`);for(let n of e.contractAddresses)t.S(typeof n==`string`&&(0,i.isAddress)(n,{strict:!1}),`Expected each contractAddress to be a valid hex address`);t.T(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),t.E(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),t.E(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),t.S(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),t.S(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function fe(e){de(e);let n=e;t.S(typeof n.delegatorAddress==`string`&&(0,i.isAddress)(n.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),t.S(typeof n.delegateAddress==`string`&&(0,i.isAddress)(n.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),t.S(typeof n.startTimestamp==`number`,`Expected startTimestamp to be a number`),t.S(typeof n.durationDays==`number`,`Expected durationDays to be a number`)}function E(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function D(e,t){let n=new Set(t.map(e=>(0,i.getAddress)(e))),r=new Set(e.map(e=>(0,i.getAddress)(e)));return n.isSubsetOf(r)}function O(e,t){return E(e)?D(e.contractAddresses,t):!1}function k(e){return[...new Set(e.map(e=>(0,i.getAddress)(e)))].toSorted()}async function A(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var pe=class{#e;constructor(e){this.#e=e}#t(e){t.T(e,`Session entry`),t.E(e.signature,`session.signature`),t.S(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),t.S(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},j=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;#i=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new pe(e.sessionStorage),this.crypto=new ue,this.keypairTTL=e.keypairTTL??2592e3,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:n,contracts:r,createKey:i,createFn:a}){this.emit({type:t.r.CredentialsLoading,contractAddresses:r});try{let e=await this.storage.get(n);if(e){this.assertEncrypted(e);let i=await this.sessionSignatures.get(n);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(n),this.emit({type:t.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(e,i.signature);if(O(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(E(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(E(e)){if(D(e.contractAddresses,r)){let i=await this.signForContracts(e,e.contractAddresses);await this.sessionSignatures.set({key:n,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(e,i);return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(e,e.contractAddresses),a=await this.decryptCredentials(e,i);return this.#a({key:n,credentials:a,requiredContracts:r})}this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof e.a)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:t.r.CredentialsCorrupted,error:t.y(r)}),await this.#s(n)}return(!this.#t||this.#n!==i)&&(this.#n=i,this.#t=a().then(e=>(this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!O(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,n){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:t.r.CredentialsRevoked,...n?{contractAddresses:n}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),O(n,t)):!1}catch{return!1}}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#s(e)}clearCaches(){this.crypto.clearCache(),this.#i=null}async createCredentials({key:n,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:t.r.CredentialsCreating,contractAddresses:r});try{let e=await i();return await this.persistCredentials(n,e),await this.sessionSignatures.set({key:n,signature:e.signature,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsCreated,contractAddresses:r}),e}catch(n){if(n instanceof e.a)throw n;return t.W(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(D(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(D(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}let i=this.#o({key:e,credentials:n,requiredContracts:r});this.#r=i;try{let e=await i;return this.#i=e,e}finally{this.#r===i&&(this.#r=null)}}async#o({key:e,credentials:n,requiredContracts:r}){let i=k([...n.contractAddresses,...r]),a=await this.signForContracts(n,i),o={...n,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,n){try{let t=await this.encryptCredentials(n);await this.storage.set(e,t)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:t.y(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:t.y(e)})}}};function me(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var M=class e extends j{#e;#t=null;#n=null;static async computeStoreKey(e,t){return A((0,i.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,me(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof T&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=k(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeByKey(e){await this.revokeSession(e)}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=k(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){de(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,i.getAddress)(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let a=await e.computeStoreKey(t,n);return this.#n=r,this.#t=a,a}},N=class e extends j{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return A((0,i.getAddress)(e),(0,i.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,i.getAddress)(e),r=k(t),a=await this.#i(n);return this.resolveCredentials({key:a,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,i.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,i.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,i.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,i.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){fe(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),a=`${(0,i.getAddress)(n)}:${(0,i.getAddress)(t)}:${r}`;if(this.#t&&this.#n===a)return this.#t;let o=await e.computeStoreKey(n,t,r);return this.#n=a,this.#t=o,o}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData({domain:{...n.domain,chainId:Number(n.domain.chainId)},types:n.types,message:{...n.message,startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays)}})}};const P={ConfidentialTransfer:`0x67500e8d0ed826d2194f514dd0d8124f35648ab6e3fb5e6ed867134cffe661e9`,Wrapped:`0x4700c1726b4198077cd40320a32c45265a1910521eb0ef713dd1d8412413d7fc`,UnwrapRequested:`0x77d02d353c5629272875d11f1b34ec4c65d7430b075575b78cd2502034c469ee`,UnwrappedFinalized:`0x2d4edf3c2943002120f53dab3f8940043f34799f4a92ab90f2f81f7dd004a49e`,UnwrappedStarted:`0x3838891d4843c6d7f9f494570b6fd8843f4e3c3ddb817c1411760bd31b819806`};function F(e){return(0,i.getAddress)(g(e.slice(-40)))}function I(e){return BigInt(e)}function he(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return(0,i.getAddress)(g(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function ge(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return g(L(e,t))}function V(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmountHandle:he(e.topics[3])}}function H(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:z(e.data,0)}}function U(e){return e.topics[0]!==P.UnwrapRequested||e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0)}}function W(e){return e.topics[0]!==P.UnwrappedFinalized||e.topics.length<2?null:{eventName:`UnwrappedFinalized`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}}function G(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:I(e.topics[1]),txId:I(e.topics[2]),to:F(e.topics[3]),returnVal:ge(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function _e(e){return V(e)??H(e)??U(e)??W(e)??G(e)}function ve(e){let t=[];for(let n of e){let e=_e(n);e&&t.push(e)}return t}function ye(e){for(let t of e){let e=U(t);if(e)return e}return null}function be(e){for(let t of e){let e=H(t);if(e)return e}return null}const xe=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrappedFinalized,P.UnwrappedStarted],K={DelegatedForUserDecryption:`0x527b025d7ff06689c1ab9d32dfd7881c964cce72ce8ac5b2fe1d3be8cfda5bfc`,RevokedDelegationForUserDecryption:`0x7aca80b6b7928b9038f186e3d9922a0fc5d52c398fbf144725c142c52a5277e4`};function q(e){return e.topics[0]!==K.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function J(e){return e.topics[0]!==K.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function Se(e){return q(e)??J(e)}function Ce(e){let t=[];for(let n of e){let e=Se(n);e&&t.push(e)}return t}function we(e){for(let t of e){let e=q(t);if(e)return e}return null}function Te(e){for(let t of e){let e=J(t);if(e)return e}return null}const Ee=[K.DelegatedForUserDecryption,K.RevokedDelegationForUserDecryption];var De=class n extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,i.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.signer.readContract(r.T(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,a,s){let{skipBalanceCheck:c=!1,onEncryptComplete:l,onTransferSubmitted:u}=s??{},d=(0,i.getAddress)(n);c||await this.#i(a);let f,p,m=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:f,inputProof:p}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-m}),Y(()=>l?.())}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-m}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(f.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.h(this.address,d,f[0],p));return this.emit({type:t.r.TransferSubmitted,txHash:e}),Y(()=>u?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:t.y(n)}),n instanceof e.a?n:new o(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,a,s,c){let l=(0,i.getAddress)(n),u=(0,i.getAddress)(a),d,f,p=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:d,inputProof:f}=await this.sdk.relayer.encrypt({values:[{value:s,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-p}),Y(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.g(this.address,l,u,d[0],f));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),Y(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:t.y(n)}),n instanceof e.a?n:new o(`TransferFrom transaction failed`,{cause:n})}}async approve(n,o){let s=(0,i.getAddress)(n);try{let e=await this.sdk.signer.writeContract(r.y(this.address,s,o));return this.emit({type:t.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approve`,error:t.y(n)}),n instanceof e.a?n:new a(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,i.getAddress)(e),a=t?(0,i.getAddress)(t):await this.sdk.signer.getAddress();return this.sdk.signer.readContract(r._(this.address,a,n))}async shield(n,a){let s=await this.#n(),l;try{let e=await this.sdk.signer.getAddress();l=await this.sdk.signer.readContract(t.d(s,e))}catch(n){throw n instanceof e.a?n:new u(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:t.y(n)})}if(l<n)throw new c(`Insufficient ERC-20 balance: requested ${n}, available ${l} (token: ${s})`,{requested:n,available:l,token:s});let d=a?.approvalStrategy??`exact`;d!==`skip`&&await this.#o(n,d===`max`,a);try{let e=a?.to?(0,i.getAddress)(a.to):await this.sdk.signer.getAddress(),o=await this.sdk.signer.writeContract(r.E(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:o}),Y(()=>a?.onShieldSubmitted?.(o)),{txHash:o,receipt:await this.sdk.signer.waitForTransactionReceipt(o)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield`,error:t.y(n)}),n instanceof e.a?n:new o(`Shield transaction failed`,{cause:n})}}async unwrap(n){let i=await this.sdk.signer.getAddress(),a,s,c=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:a,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.x(this.address,i,i,a[0],s));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.sdk.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(t._(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.sdk.signer.writeContract(r.S(this.address,n,n,i));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return Y(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return Y(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];t.x(a,`finalizeUnwrap: clearValue`);try{let e=await this.sdk.signer.writeContract(r.C(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.sdk.signer.getAddress();await this.sdk.signer.readContract(t.l(r,e,this.wrapper))>0n&&await this.sdk.signer.writeContract(t.u(r,this.wrapper,0n))}let e=await this.sdk.signer.writeContract(t.u(r,this.wrapper,i));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:t.y(n)}),n instanceof e.a?n:new a(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.N(`Expiration date must be at least 1 hour in the future`);let a=(0,i.getAddress)(n),s=await this.sdk.signer.getAddress();if(a===(0,i.getAddress)(s))throw new t.R(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.M(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.i,u;try{u=await this.getDelegationExpiry({delegatorAddress:s,delegateAddress:a})}catch{u=-1n}if(u===l)throw new t.F(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.sdk.signer.writeContract(t.a(c,a,this.address,l));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:t.y(n)}),n instanceof e.a?n:p(n)||new o(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,i.getAddress)(n),a=await this.sdk.signer.getAddress(),s=await this.getAclAddress(),c;try{c=await this.getDelegationExpiry({delegatorAddress:a,delegateAddress:r})}catch{c=1n}if(c===0n)throw new t.I(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.sdk.signer.writeContract(t.c(s,r,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:t.y(n)}),n instanceof e.a?n:p(n)||new o(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new o(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{n=await this.balanceOf()}catch(t){throw t instanceof e.a?t:new l(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new s(`Insufficient confidential balance: requested ${t}, available ${n} (token: ${this.address})`,{requested:t,available:n,token:this.address})}async#a(n,r,i){this.emit({type:t.r.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.sdk.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new o(`Failed to get unshield receipt`,{cause:t})}let s=ye(a.logs);if(!s)throw new o(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),Y(()=>i?.onFinalizing?.());let c=await this.finalizeUnwrap(s.encryptedAmount);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:c.txHash,operationId:r}),Y(()=>i?.onFinalizeSubmitted?.(c.txHash)),c}async#o(n,r,i){let o=await this.#n(),s=await this.sdk.signer.getAddress(),c=await this.sdk.signer.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.sdk.signer.writeContract(t.u(o,this.wrapper,0n));let e=r?2n**256n-1n:n,a=await this.sdk.signer.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:a}),Y(()=>i?.onApprovalSubmitted?.(a))}catch(t){throw t instanceof e.a?t:new a(`ERC-20 approval failed`,{cause:t})}}};function Y(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Oe={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},X=300*1e3;var Z=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},Oe,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,i.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?X:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.m(e.tokenAddress)),this.signer.readContract(t.h(e.tokenAddress)),this.signer.readContract(t.f(e.tokenAddress)),this.signer.readContract(t.p(e.tokenAddress)),this.signer.readContract(t.m(e.confidentialTokenAddress)),this.signer.readContract(t.h(e.confidentialTokenAddress)),this.signer.readContract(t.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ct:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));if(!s)return this.#i(a,null,X);let l=await this.signer.readContract(r.s(t,c));return this.#i(a,{confidentialTokenAddress:c,isValid:l})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ut:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));if(!s)return this.#i(a,null,X);let l=await this.signer.readContract(r.s(t,n));return this.#i(a,{tokenAddress:c,isValid:l})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,i.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,i.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,i.getAddress)(e)))}};const Q=365*86400;var ke=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new T,this.cache=new w(e.storage),this.#t=e.onEvent??function(){},this.registry=new Z({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>Q?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${Q}s); capping to ${Q}s.`),Q):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new M(n),this.delegatedCredentials=new N(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.emitEvent({type:t.r.TransactionError,operation:e,error:t.y(n)})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=(0,i.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await M.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new De(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new Z({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(e.length===0)return{};let n=e.map(e=>({handle:e.handle,contractAddress:(0,i.getAddress)(e.contractAddress)})),r={},a=[];for(let e of n)t._(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;let o=await this.signer.getAddress(),s=[];for(let e of a){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?s.push(e):r[e.handle]=t}if(s.length===0)return r;let c=await this.credentials.allow(...new Set(n.map(e=>e.contractAddress))),l=new Map;for(let e of s){let t=l.get(e.contractAddress);t?t.push(e.handle):l.set(e.contractAddress,[e.handle])}let u=Date.now(),d=s.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:d}),await t.n([...l.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:c.contractAddresses,privateKey:c.privateKey,publicKey:c.publicKey,signature:c.signature,signerAddress:o,startTimestamp:c.startTimestamp,durationDays:c.durationDays});for(let[t,i]of Object.entries(n))r[t]=i,await this.cache.set(o,e,t,i)}),5);let e={};for(let t of d){let n=r[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-u,handles:d,result:e}),r}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:t.y(e),durationMs:Date.now()-u,handles:d}),t.O(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw t.O(e,`Public decryption failed`)}}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await M.computeStoreKey(e,t);await this.credentials.revokeByKey(n),await this.cache.clearForRequester(e)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${e}`}async function Ae(e,t,n){await e.set($(t),n)}async function je(e,t){return e.get($(t))}async function Me(e,t){await e.delete($(t))}var Ne=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 Pe=new Ne;exports.ACL_TOPICS=Ee,exports.AclPausedError=t.k,exports.AclTopics=K,exports.ApprovalFailedError=a,exports.BalanceCheckUnavailableError=l,exports.ChromeSessionStorage=Ne,exports.ConfigurationError=e.t,exports.CredentialsManager=M,exports.DecryptCache=w,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=Oe,exports.DelegatedCredentialsManager=N,exports.DelegationContractIsSelfError=t.A,exports.DelegationCooldownError=t.j,exports.DelegationDelegateEqualsContractError=t.M,exports.DelegationExpirationTooSoonError=t.N,exports.DelegationExpiredError=t.P,exports.DelegationExpiryUnchangedError=t.F,exports.DelegationNotFoundError=t.I,exports.DelegationNotPropagatedError=t.L,exports.DelegationSelfNotAllowedError=t.R,exports.ERC20ReadFailedError=u,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=m,exports.InsufficientConfidentialBalanceError=s,exports.InsufficientERC20BalanceError=c,exports.InvalidKeypairError=t.z,exports.KeypairExpiredError=t.B,exports.MainnetConfig=n.o,exports.MemoryStorage=T,exports.NoCiphertextError=t.V,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=ce,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.H,exports.SigningRejectedError=t.U,exports.TOKEN_TOPICS=xe,exports.Token=De,exports.Topics=P,exports.TransactionRevertedError=o,exports.WrappersRegistry=Z,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=ke,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.chromeSessionStorage=Pe,exports.clearPendingUnshield=Me,exports.confidentialBalanceOfContract=r.p,exports.confidentialTotalSupplyContract=r.m,exports.confidentialTransferContract=r.h,exports.confidentialTransferFromContract=r.g,exports.decimalsContract=t.f,exports.decodeAclEvent=Se,exports.decodeAclEvents=Ce,exports.decodeConfidentialTransfer=V,exports.decodeDelegatedForUserDecryption=q,exports.decodeOnChainEvent=_e,exports.decodeOnChainEvents=ve,exports.decodeRevokedDelegationForUserDecryption=J,exports.decodeUnwrapRequested=U,exports.decodeUnwrappedFinalized=W,exports.decodeUnwrappedStarted=G,exports.decodeWrapped=H,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=r.C,exports.findDelegatedForUserDecryption=we,exports.findRevokedDelegationForUserDecryption=Te,exports.findUnwrapRequested=ye,exports.findWrapped=be,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.indexedDBStorage=ee,exports.inferredTotalSupplyContract=r.w,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=r._,exports.isZeroHandle=t._,exports.loadPendingUnshield=je,exports.matchAclRevert=p,exports.matchZamaError=e.s,exports.memoryStorage=le,exports.nameContract=t.m,exports.rateContract=r.v,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=Ae,exports.setOperatorContract=r.y,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.h,exports.totalSupplyContract=r.b,exports.underlyingContract=r.T,exports.unwrapContract=r.x,exports.unwrapFromBalanceContract=r.S,exports.wrapContract=r.E;
514
+ `],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{cdnUrl:e,fhevmConfig:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};function g(e){return e.startsWith(`0x`)?e:`0x${e}`}const _=8192,v=300*1e3;function y(e){let t=[];for(let n=0;n<e.length;n+=_)t.push(String.fromCharCode(...e.subarray(n,n+_)));return btoa(t.join(``))}function b(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function ae(e){return`fhe:pubkey:${e}`}function oe(e,t){return`fhe:params:${e}:${t}`}function x(e){return`fhe:params-index:${e}`}function se(e){t.T(e,`CachedPublicKey`),t.D(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),t.D(e,`publicKey`,`CachedPublicKey.publicKey`)}function S(e){t.T(e,`CachedPublicParams`),t.D(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),t.D(e,`publicParams`,`CachedPublicParams.publicParams`)}var ce=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let n=ae(this.#t);try{let e=await this.#e.get(n);if(e){se(e);let t={publicKeyId:e.publicKeyId,publicKey:b(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(n),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:t.y(e).message})}let r=await e();if(r===null)return null;this.#a=r;try{let e={publicKeyId:r.publicKeyId,publicKey:y(r.publicKey),lastValidatedAt:Date.now()};await this.#e.set(n,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:t.y(e).message})}return r}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,n){let r=oe(this.#t,e);try{let t=await this.#e.get(r);if(t){S(t);let n={publicParamsId:t.publicParamsId,publicParams:b(t.publicParams)};return this.#o.set(e,n),n}}catch(n){await this.#g(r),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:t.y(n).message})}let i=await n();if(i===null)return null;this.#o.set(e,i);try{let n={publicParamsId:i.publicParamsId,publicParams:y(i.publicParams),lastValidatedAt:Date.now()};await this.#e.set(r,n);let a=x(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:t.y(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(n){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:t.y(n).message})}return i}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let n=ae(this.#t),r=null,i=[];try{let[a,o]=await Promise.all([this.#e.get(n),this.#h()]);if(a)try{se(a),r={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:t.y(e).message}),await this.#g(n)}if(i=o,!r)return!1;if([r,...i.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let t=e-this.#r+v;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let c=await s.json();if(!c||typeof c!=`object`||!(`fhePublicKey`in c)||!c.fhePublicKey?.urls?.length||!(`crs`in c)||typeof c.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let t=e-this.#r+v;return await this.#v(n,{...r,lastValidatedAt:t},i.map(e=>({...e,data:{...e.data,lastValidatedAt:t}}))),this.#u=t,!1}let l=c,u=l.fhePublicKey.urls[0];if(r.artifactUrl&&u&&u!==r.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let d={...r,lastValidatedAt:e};if(u){let e=await this.#m(u,r);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;d={...d,artifactUrl:u,etag:e.etag,lastModified:e.lastModified}}let f=[];for(let t of i){let r=l.crs[String(t.bits)]?.urls[0];if(t.data.artifactUrl&&r&&r!==t.data.artifactUrl)return await this.#_(n,i),this.#u=null,!0;let a={...t.data,lastValidatedAt:e};if(r){let e=await this.#m(r,t.data);if(!e.fresh)return await this.#_(n,i),this.#u=null,!0;a={...a,artifactUrl:r,etag:e.etag,lastModified:e.lastModified}}f.push({...t,data:a})}return await this.#v(n,d,f),this.#u=e,!1}catch(a){let o=t.y(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+v;try{r&&await this.#v(n,{...r,lastValidatedAt:l},i.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:t.y(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=x(this.#t),n=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:t.y(e).message}),null))??[],r=new Set([...this.#o.keys(),...n]),i=Array.from(r);return(await Promise.all(i.map(async e=>{let n=oe(this.#t,e),r;try{r=await this.#e.get(n)}catch(n){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:t.y(n).message}),null}if(!r)return null;try{return S(r),{bits:e,key:n,data:{...r,lastValidatedAt:r.lastValidatedAt??0}}}catch(r){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:t.y(r).message}),await this.#g(n),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(n=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:t.y(n).message})})}async#_(e,n){let r=x(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(r),...n.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:t.y(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,n,r){let i=[this.#e.set(e,n).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:t.y(e).message})}),...r.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:t.y(e).message})}))];await Promise.all(i)}},le=class{#e=null;#t=null;#n=null;#r=!1;#i=null;#a=null;#o=null;#s=`idle`;#c;#l;constructor(e){this.#l=e}get status(){return this.#s}get initError(){return this.#c}#u(e,t){this.#s=e,this.#c=t,this.#l.onStatusChange?.(e,t)}async#d(){let e=await this.#l.getChainId(),{transports:t,security:r,threads:i}=this.#l;if(i!==void 0&&(!Number.isInteger(i)||i<1))throw Error(`Invalid thread count: ${i}. Must be a positive integer.`);return i!==void 0&&globalThis.SharedArrayBuffer===void 0&&this.#l.logger?.warn(`threads option requires SharedArrayBuffer (COOP/COEP headers). Falling back to single-threaded.`),{cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,fhevmConfig:Object.assign({},n.i[e],t[e]),csrfToken:r?.getCsrfToken?.()??``,integrity:r?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:this.#l.logger,thread:i}}async#f(){if(this.#n)return this.#n;this.#n=this.#m();try{return await this.#n}finally{this.#n=null}}#p(){this.#e?.terminate(),this.#e=null,this.#t=null,this.#a=null}async#m(){this.#r&&(this.#r=!1,this.#e=null,this.#t=null,this.#i=null);let t=await this.#l.getChainId();if(this.#i!==null&&t!==this.#i&&this.#p(),this.#i=t,this.#o||=this.#l.fheArtifactStorage??new m(`FheArtifactCache`,1,`artifacts`),!this.#a){let e=Object.assign({},n.i[t],this.#l.transports[t]);this.#a=new ce({storage:this.#o,chainId:t,relayerUrl:e.relayerUrl,ttl:this.#l.fheArtifactCacheTTL,logger:this.#l.logger})}if(this.#a){let e=!1;try{e=await this.#a.revalidateIfDue()}catch(e){this.#l.logger?.warn(`Artifact revalidation failed, proceeding with potentially stale cache`,{error:e instanceof Error?e.message:String(e)})}e&&(this.#l.logger?.info(`Cached FHE artifacts are stale — reinitializing`),this.#p())}return this.#t||=(this.#u(`initializing`),this.#h().then(e=>(this.#u(`ready`),e)).catch(t=>{this.#t=null;let n=t instanceof e.a?t:new e.t(`Failed to initialize FHE worker`,{cause:t});throw this.#u(`error`,n),n})),this.#t}async#h(){let e=new ie(await this.#d());if(await e.initWorker(),this.#r)throw e.terminate(),Error(`RelayerWeb was terminated during initialization`);return this.#e=e,e}terminate(){this.#r=!0,this.#e&&=(this.#e.terminate(),null),this.#t=null,this.#n=null}[Symbol.dispose](){this.terminate()}async#g(){if(this.#e){let e=this.#l.security?.getCsrfToken?.()??``;e&&await this.#e.updateCsrf(e)}}async generateKeypair(){let e=await(await this.#f()).generateKeypair();return{publicKey:e.publicKey,privateKey:e.privateKey}}async createEIP712(e,t,r,i=7){let a=await(await this.#f()).createEIP712({publicKey:e,contractAddresses:t,startTimestamp:r,durationDays:i}),o={name:a.domain.name,version:a.domain.version,chainId:a.domain.chainId,verifyingContract:a.domain.verifyingContract};return{domain:o,types:{EIP712Domain:n.c(o),UserDecryptRequestVerification:a.types.UserDecryptRequestVerification},message:{publicKey:a.message.publicKey,contractAddresses:a.message.contractAddresses,startTimestamp:a.message.startTimestamp,durationDays:a.message.durationDays,extraData:a.message.extraData}}}async encrypt(e){let{values:t,contractAddress:r,userAddress:i}=e;return n.l(async()=>{let e=await this.#f();await this.#g();let n=await e.encrypt({values:t,contractAddress:r,userAddress:i});return{handles:n.handles,inputProof:n.inputProof}})}async userDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.userDecrypt(e)).clearValues})}async publicDecrypt(e){return n.l(async()=>{let t=await this.#f();await this.#g();let n=await t.publicDecrypt(e);return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){return(await this.#f()).createDelegatedUserDecryptEIP712({publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),(await t.delegatedUserDecrypt(e)).clearValues})}async requestZKProofVerification(e){return n.l(async()=>{let t=await this.#f();return await this.#g(),t.requestZKProofVerification(e)})}async getPublicKey(){let e=await this.#f();return this.#a?this.#a.getPublicKey(async()=>(await e.getPublicKey()).result):(await e.getPublicKey()).result}async getPublicParams(e){let t=await this.#f();return this.#a?this.#a.getPublicParams(e,async()=>(await t.getPublicParams(e)).result):(await t.getPublicParams(e)).result}async getAclAddress(){let t=await this.#l.getChainId(),r=Object.assign({},n.i[t],this.#l.transports[t]);if(!r.aclContractAddress)throw new e.t(`No ACL address configured for chain ${t}`);return r.aclContractAddress}},ue=class{#e;#t=`zama:decrypt`;#n=`${this.#t}:keys`;#r=Promise.resolve();constructor(e){this.#e=e}async get(e,t,n){try{let r=this.#o(e,t,n);return await this.#e.get(r)}catch(e){return console.warn(`[zama-sdk] DecryptCache.get failed:`,e),null}}async set(e,t,n,r){try{let i=this.#o(e,t,n);await this.#e.set(i,r),this.#r=this.#r.then(()=>this.#c(i).catch(e=>{console.warn(`[zama-sdk] DecryptCache index write failed:`,e)})),await this.#r}catch(e){console.warn(`[zama-sdk] DecryptCache.set failed:`,e)}}async clearForRequester(e){this.#r=this.#r.then(()=>this.#i(e).catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearForRequester failed:`,e)})),await this.#r}async#i(e){let t=(0,i.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),a=[],o=[];for(let e of r)e.startsWith(n)?a.push(e):o.push(e);await Promise.all(a.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,o)}async clearAll(){this.#r=this.#r.then(()=>this.#a().catch(e=>{console.warn(`[zama-sdk] DecryptCache.clearAll failed:`,e)})),await this.#r}async#a(){let e=await this.#s();await Promise.all(e.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.delete(this.#n)}#o(e,t,n){return`${this.#t}:${(0,i.getAddress)(e)}:${(0,i.getAddress)(t)}:${n.toLowerCase()}`}async#s(){return await this.#e.get(this.#n)??[]}async#c(e){let t=await this.#s();t.includes(e)||(t.push(e),await this.#e.set(this.#n,t))}},C=class{#e=new Map;async get(e){return this.#e.get(e)??null}async set(e,t){this.#e.set(e,t)}async delete(e){this.#e.delete(e)}};const de=new C;var fe=class{#e=null;#t=null;clearCache(){this.#e=null,this.#t=null}async encrypt(e,t,n){let r=await this.#n(t,n),i=crypto.getRandomValues(new Uint8Array(12)),a=new TextEncoder,o=await crypto.subtle.encrypt({name:`AES-GCM`,iv:i},r,a.encode(e));return{iv:btoa(String.fromCharCode(...i)),ciphertext:btoa(String.fromCharCode(...new Uint8Array(o)))}}async decrypt(e,t,n){let r=await this.#n(t,n),i=Uint8Array.from(atob(e.iv),e=>e.charCodeAt(0)),a=Uint8Array.from(atob(e.ciphertext),e=>e.charCodeAt(0)),o=await crypto.subtle.decrypt({name:`AES-GCM`,iv:i},r,a);return g(new TextDecoder().decode(o))}async#n(e,t){let n=`${e}:${t}`;if(this.#e&&this.#t===n)return this.#e;let r=new TextEncoder,i=await crypto.subtle.importKey(`raw`,r.encode(e),`PBKDF2`,!1,[`deriveKey`]),a=await crypto.subtle.deriveKey({name:`PBKDF2`,salt:r.encode(t),iterations:6e5,hash:`SHA-256`},i,{name:`AES-GCM`,length:256},!1,[`encrypt`,`decrypt`]);return this.#t=n,this.#e=a,a}};function w(e){t.T(e,`Stored credentials`),t.E(e.publicKey,`credentials.publicKey`),t.b(e.contractAddresses,`credentials.contractAddresses`);for(let n of e.contractAddresses)t.S(typeof n==`string`&&(0,i.isAddress)(n,{strict:!1}),`Expected each contractAddress to be a valid hex address`);t.T(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),t.E(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),t.E(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),t.S(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),t.S(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function pe(e){w(e);let n=e;t.S(typeof n.delegatorAddress==`string`&&(0,i.isAddress)(n.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),t.S(typeof n.delegateAddress==`string`&&(0,i.isAddress)(n.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),t.S(typeof n.startTimestamp==`number`,`Expected startTimestamp to be a number`),t.S(typeof n.durationDays==`number`,`Expected durationDays to be a number`)}function T(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function E(e,t){let n=new Set(t.map(e=>(0,i.getAddress)(e))),r=new Set(e.map(e=>(0,i.getAddress)(e)));return n.isSubsetOf(r)}function D(e,t){return T(e)?E(e.contractAddresses,t):!1}function O(e){return[...new Set(e.map(e=>(0,i.getAddress)(e)))].toSorted()}async function me(...e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e.map(String).join(`:`)));return Array.from(new Uint8Array(t)).map(e=>e.toString(16).padStart(2,`0`)).join(``).slice(0,32)}var he=class{#e;constructor(e){this.#e=e}#t(e){t.T(e,`Session entry`),t.E(e.signature,`session.signature`),t.S(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),t.S(typeof e.ttl==`number`||e.ttl===`infinite`,`Expected session.ttl to be a number or "infinite"`)}async get(e){let t=await this.#e.get(e);return t===null?null:(this.#t(t),t)}async set(e){let t={signature:e.signature,createdAt:Math.floor(Date.now()/1e3),ttl:e.ttl};await this.#e.set(e.key,t)}async delete(e){await this.#e.delete(e)}isExpired(e){return e.ttl===`infinite`?!1:e.ttl===0?!0:Math.floor(Date.now()/1e3)-e.createdAt>=e.ttl}},k=class{signer;storage;sessionSignatures;crypto;keypairTTL;sessionTTL;#e;#t=null;#n=null;#r=null;#i=null;constructor(e){if(this.signer=e.signer,this.storage=e.storage,this.sessionSignatures=new he(e.sessionStorage),this.crypto=new fe,this.keypairTTL=e.keypairTTL??2592e3,this.sessionTTL=e.sessionTTL??2592e3,this.#e=e.onEvent??(()=>{}),typeof this.keypairTTL==`number`&&this.keypairTTL<0)throw Error(`keypairTTL must be >= 0`);if(typeof this.sessionTTL==`number`&&this.sessionTTL<0)throw Error(`sessionTTL must be >= 0`);typeof this.sessionTTL==`number`&&this.sessionTTL>this.keypairTTL&&(this.sessionTTL=this.keypairTTL,console.warn(`[zama-sdk] sessionTTL was clamped to keypairTTL (${this.keypairTTL}s). A session that outlives the keypair causes isAllowed() to return true after the keypair expires, leading to unexpected wallet prompts.`))}emit(e){this.#e({...e,timestamp:Date.now()})}async resolveCredentials({key:n,contracts:r,createKey:i,createFn:a}){this.emit({type:t.r.CredentialsLoading,contractAddresses:r});try{let e=await this.storage.get(n);if(e){this.assertEncrypted(e);let i=await this.sessionSignatures.get(n);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(n),this.emit({type:t.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(e,i.signature);if(D(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(T(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(T(e)){if(E(e.contractAddresses,r)){let i=await this.signForContracts(e,e.contractAddresses);await this.sessionSignatures.set({key:n,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(e,i);return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(e,e.contractAddresses),a=await this.decryptCredentials(e,i);return this.#a({key:n,credentials:a,requiredContracts:r})}this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof e.a)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:t.r.CredentialsCorrupted,error:t.y(r)}),await this.#s(n)}return(!this.#t||this.#n!==i)&&(this.#n=i,this.#t=a().then(e=>(this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!D(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,n){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:t.r.CredentialsRevoked,...n?{contractAddresses:n}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),D(n,t)):!1}catch{return!1}}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#s(e)}clearCaches(){this.crypto.clearCache(),this.#i=null}async createCredentials({key:n,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:t.r.CredentialsCreating,contractAddresses:r});try{let e=await i();return await this.persistCredentials(n,e),await this.sessionSignatures.set({key:n,signature:e.signature,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsCreated,contractAddresses:r}),e}catch(n){if(n instanceof e.a)throw n;return t.W(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(E(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(E(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}let i=this.#o({key:e,credentials:n,requiredContracts:r});this.#r=i;try{let e=await i;return this.#i=e,e}finally{this.#r===i&&(this.#r=null)}}async#o({key:e,credentials:n,requiredContracts:r}){let i=O([...n.contractAddresses,...r]),a=await this.signForContracts(n,i),o={...n,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,n){try{let t=await this.encryptCredentials(n);await this.storage.set(e,t)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:t.y(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:t.r.CredentialsPersistFailed,error:t.y(e)})}}};function ge(e){if(typeof e!=`object`||!e)return!1;let t=Reflect.get(e,`runtime`);return typeof t!=`object`||!t?!1:typeof Reflect.get(t,`id`)==`string`}var A=class e extends k{#e;#t=null;#n=null;static async computeStoreKey(e,t){return me((0,i.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,ge(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof C&&console.warn(`[zama-sdk] Detected Chrome extension context with in-memory session storage. Session signatures will be lost on service worker restart and won't be shared across contexts. Consider using chromeSessionStorage instead. `)}async allow(...e){let t=O(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeByKey(e){await this.revokeSession(e)}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=O(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){w(e)}async signForContracts(e,t){let n=await this.#e.createEIP712(e.publicKey,t,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#r(){let t=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,i.getAddress)(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let a=await e.computeStoreKey(t,n);return this.#n=r,this.#t=a,a}},j=class e extends k{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return me((0,i.getAddress)(e),(0,i.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,i.getAddress)(e),r=O(t),a=await this.#i(n);return this.resolveCredentials({key:a,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,i.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,i.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,i.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,i.getAddress)(e)))}async#r(e,t){let n=await this.#i(e);return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let n=await this.#e.generateKeypair(),r=await this.signer.getAddress(),i=Math.floor(Date.now()/1e3),a=Math.ceil(this.keypairTTL/86400),o={publicKey:n.publicKey,startTimestamp:i,durationDays:a,delegatorAddress:e},s=await this.#a(o,t);return{publicKey:n.publicKey,privateKey:n.privateKey,signature:s,contractAddresses:t,startTimestamp:i,durationDays:a,delegatorAddress:e,delegateAddress:r}},errorContext:`Failed to create delegated decrypt credentials`})}assertEncrypted(e){pe(e)}async signForContracts(e,t){return this.#a(e,t)}async encryptCredentials(e){let t=await this.signer.getAddress(),n=await this.crypto.encrypt(e.privateKey,e.signature,t),{privateKey:r,signature:i,...a}=e;return{...a,encryptedPrivateKey:n}}async decryptCredentials(e,t){let n=await this.signer.getAddress(),r=await this.crypto.decrypt(e.encryptedPrivateKey,t,n),{encryptedPrivateKey:i,...a}=e;return{...a,privateKey:r,signature:t}}clearCaches(){this.#t=null,this.#n=null,super.clearCaches()}async#i(t){let n=await this.signer.getAddress(),r=await this.signer.getChainId(),a=`${(0,i.getAddress)(n)}:${(0,i.getAddress)(t)}:${r}`;if(this.#t&&this.#n===a)return this.#t;let o=await e.computeStoreKey(n,t,r);return this.#n=a,this.#t=o,o}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData({domain:{...n.domain,chainId:Number(n.domain.chainId)},types:n.types,message:{...n.message,startTimestamp:BigInt(n.message.startTimestamp),durationDays:BigInt(n.message.durationDays)}})}};function M(e){return(0,i.keccak256)((0,i.toBytes)(e))}const N={ConfidentialTransfer:M(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:M(`Wrapped(address,uint256)`),UnwrapRequested:M(`UnwrapRequested(address,bytes32,bytes32)`),UnwrappedFinalized:M(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:M(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function P(e){return(0,i.getAddress)(g(e.slice(-40)))}function F(e){return BigInt(e)}function I(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return(0,i.getAddress)(g(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function _e(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return g(L(e,t))}function V(e){return e.topics[0]!==N.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:P(e.topics[1]),to:P(e.topics[2]),encryptedAmountHandle:I(e.topics[3])}}function H(e){return e.topics[0]!==N.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:P(e.topics[1]),amountIn:z(e.data,0)}}function U(e){return e.topics[0]!==N.UnwrapRequested||e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:P(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}}function W(e){return e.topics[0]!==N.UnwrappedFinalized||e.topics.length<3?null:{eventName:`UnwrappedFinalized`,receiver:P(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}}function ve(e){return e.topics[0]!==N.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:F(e.topics[1]),txId:F(e.topics[2]),to:P(e.topics[3]),returnVal:_e(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function ye(e){return V(e)??H(e)??U(e)??W(e)??ve(e)}function be(e){let t=[];for(let n of e){let e=ye(n);e&&t.push(e)}return t}function xe(e){for(let t of e){let e=U(t);if(e)return e}return null}function Se(e){for(let t of e){let e=H(t);if(e)return e}return null}const Ce=[N.ConfidentialTransfer,N.Wrapped,N.UnwrapRequested,N.UnwrappedFinalized,N.UnwrappedStarted],G={DelegatedForUserDecryption:M(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:M(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function K(e){return e.topics[0]!==G.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:P(e.topics[1]),delegate:P(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function q(e){return e.topics[0]!==G.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:P(e.topics[1]),delegate:P(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function we(e){return K(e)??q(e)}function Te(e){let t=[];for(let n of e){let e=we(n);e&&t.push(e)}return t}function Ee(e){for(let t of e){let e=K(t);if(e)return e}return null}function De(e){for(let t of e){let e=q(t);if(e)return e}return null}const Oe=[G.DelegatedForUserDecryption,G.RevokedDelegationForUserDecryption];var ke=class n extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,i.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.signer.readContract(r.T(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(n,a,s){let{skipBalanceCheck:c=!1,onEncryptComplete:l,onTransferSubmitted:u}=s??{},d=(0,i.getAddress)(n);c||await this.#i(a);let f,p,m=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:f,inputProof:p}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-m}),J(()=>l?.())}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-m}),n instanceof e.a?n:new e.i(`Failed to encrypt transfer amount`,{cause:n})}if(f.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.h(this.address,d,f[0],p));return this.emit({type:t.r.TransferSubmitted,txHash:e}),J(()=>u?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:t.y(n)}),n instanceof e.a?n:new o(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(n,a,s,c){let l=(0,i.getAddress)(n),u=(0,i.getAddress)(a),d,f,p=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:d,inputProof:f}=await this.sdk.relayer.encrypt({values:[{value:s,type:`euint64`}],contractAddress:this.address,userAddress:l}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-p}),J(()=>c?.onEncryptComplete?.())}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-p}),n instanceof e.a?n:new e.i(`Failed to encrypt transferFrom amount`,{cause:n})}if(d.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.g(this.address,l,u,d[0],f));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),J(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:t.y(n)}),n instanceof e.a?n:new o(`TransferFrom transaction failed`,{cause:n})}}async approve(n,o){let s=(0,i.getAddress)(n);try{let e=await this.sdk.signer.writeContract(r.y(this.address,s,o));return this.emit({type:t.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approve`,error:t.y(n)}),n instanceof e.a?n:new a(`Operator approval failed`,{cause:n})}}async isApproved(e,t){let n=(0,i.getAddress)(e),a=t?(0,i.getAddress)(t):await this.sdk.signer.getAddress();return this.sdk.signer.readContract(r._(this.address,a,n))}async shield(n,a){let s=await this.#n(),l;try{let e=await this.sdk.signer.getAddress();l=await this.sdk.signer.readContract(t.d(s,e))}catch(n){throw n instanceof e.a?n:new u(`Could not read ERC-20 balance for shield validation (token: ${s})`,{cause:t.y(n)})}if(l<n)throw new c(`Insufficient ERC-20 balance: requested ${n}, available ${l} (token: ${s})`,{requested:n,available:l,token:s});let d=a?.approvalStrategy??`exact`;d!==`skip`&&await this.#o(n,d===`max`,a);try{let e=a?.to?(0,i.getAddress)(a.to):await this.sdk.signer.getAddress(),o=await this.sdk.signer.writeContract(r.E(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:o}),J(()=>a?.onShieldSubmitted?.(o)),{txHash:o,receipt:await this.sdk.signer.waitForTransactionReceipt(o)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield`,error:t.y(n)}),n instanceof e.a?n:new o(`Shield transaction failed`,{cause:n})}}async unwrap(n){let i=await this.sdk.signer.getAddress(),a,s,c=Date.now();try{this.emit({type:t.r.EncryptStart}),{handles:a,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.wrapper,userAddress:i}),this.emit({type:t.r.EncryptEnd,durationMs:Date.now()-c})}catch(n){throw this.emit({type:t.r.EncryptError,error:t.y(n),durationMs:Date.now()-c}),n instanceof e.a?n:new e.i(`Failed to encrypt unshield amount`,{cause:n})}if(a.length===0)throw new e.i(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(r.x(this.address,i,i,a[0],s));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let n=await this.sdk.signer.getAddress(),i=await this.readConfidentialBalanceOf(n);if(t._(i))throw new e.r(`Cannot unshield: balance is zero`);try{let e=await this.sdk.signer.writeContract(r.S(this.address,n,n,i));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Unshield-all transaction failed`,{cause:n})}}async unshield(e,t){let{skipBalanceCheck:n=!1,onUnwrapSubmitted:r,onFinalizing:i,onFinalizeSubmitted:a}=t??{};n||await this.#i(e);let o={onFinalizing:i,onFinalizeSubmitted:a},s=crypto.randomUUID(),c=await this.unwrap(e);return J(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return J(()=>e?.onUnwrapSubmitted?.(n.txHash)),this.#a(n.txHash,t,e)}async resumeUnshield(e,t){return this.#a(e,crypto.randomUUID(),t)}async finalizeUnwrap(n){let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];t.x(a,`finalizeUnwrap: clearValue`);try{let e=await this.sdk.signer.writeContract(r.C(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:t.y(n)}),n instanceof e.a?n:new o(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=await this.#n(),i=n??2n**256n-1n;try{if(i>0n){let e=await this.sdk.signer.getAddress();await this.sdk.signer.readContract(t.l(r,e,this.wrapper))>0n&&await this.sdk.signer.writeContract(t.u(r,this.wrapper,0n))}let e=await this.sdk.signer.writeContract(t.u(r,this.wrapper,i));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:t.y(n)}),n instanceof e.a?n:new a(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){if(r&&r.getTime()<Date.now()+36e5)throw new t.N(`Expiration date must be at least 1 hour in the future`);let a=(0,i.getAddress)(n),s=await this.sdk.signer.getAddress();if(a===(0,i.getAddress)(s))throw new t.R(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.M(`Delegate address cannot be the same as the contract address (${this.address}).`);let c=await this.getAclAddress(),l=r?BigInt(Math.floor(r.getTime()/1e3)):t.i,u;try{u=await this.getDelegationExpiry({delegatorAddress:s,delegateAddress:a})}catch{u=-1n}if(u===l)throw new t.F(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await this.sdk.signer.writeContract(t.a(c,a,this.address,l));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:t.y(n)}),n instanceof e.a?n:p(n)||new o(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=(0,i.getAddress)(n),a=await this.sdk.signer.getAddress(),s=await this.getAclAddress(),c;try{c=await this.getDelegationExpiry({delegatorAddress:a,delegateAddress:r})}catch{c=1n}if(c===0n)throw new t.I(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await this.sdk.signer.writeContract(t.c(s,r,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.signer.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:t.y(n)}),n instanceof e.a?n:p(n)||new o(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:r}){return n.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return n.#r(e,e=>e.revokeDelegation({delegateAddress:t}),`Revoke delegation failed`)}static async#r(t,n,r){let i=new Map;for(let a=0;a<t.length;a++)try{i.set(t[a].address,await n(t[a]))}catch(n){n instanceof e.a?i.set(t[a].address,n):i.set(t[a].address,new o(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{n=await this.balanceOf()}catch(t){throw t instanceof e.a?t:new l(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new s(`Insufficient confidential balance: requested ${t}, available ${n} (token: ${this.address})`,{requested:t,available:n,token:this.address})}async#a(n,r,i){this.emit({type:t.r.UnshieldPhase1Submitted,txHash:n,operationId:r});let a;try{a=await this.sdk.signer.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.a?t:new o(`Failed to get unshield receipt`,{cause:t})}let s=xe(a.logs);if(!s)throw new o(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),J(()=>i?.onFinalizing?.());let c=await this.finalizeUnwrap(s.unwrapRequestId);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:c.txHash,operationId:r}),J(()=>i?.onFinalizeSubmitted?.(c.txHash)),c}async#o(n,r,i){let o=await this.#n(),s=await this.sdk.signer.getAddress(),c=await this.sdk.signer.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{c>0n&&await this.sdk.signer.writeContract(t.u(o,this.wrapper,0n));let e=r?2n**256n-1n:n,a=await this.sdk.signer.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:a}),J(()=>i?.onApprovalSubmitted?.(a))}catch(t){throw t instanceof e.a?t:new a(`ERC-20 approval failed`,{cause:t})}}};function J(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Ae={[n.o.chainId]:n.o.registryAddress,[n.s.chainId]:n.s.registryAddress,[n.n.chainId]:n.n.registryAddress},Y=300*1e3;var X=class{signer;#e;#t;#n=new Map;constructor(e){this.signer=e.signer,this.#e=Object.assign({},Ae,e.registryAddresses),this.#t=(e.registryTTL??86400)*1e3}getAddress(e){return this.#e[e]}#r(e){let t=this.#n.get(e);if(t){if(Date.now()>=t.expiresAt){this.#n.delete(e);return}return t.data}}#i(e,t,n=this.#t){return this.#n.set(e,{data:t,expiresAt:Date.now()+n}),t}refresh(){this.#n.clear()}get ttlMs(){return this.#t}async getRegistryAddress(){let t=await this.signer.getChainId(),n=this.#e[t];if(!n)throw new e.t(`No wrappers registry address configured for chain ${t}.\nPass a registryAddresses entry for this chain.`);return(0,i.getAddress)(n)}async listPairs(t={}){let n=t.page??1,i=t.pageSize??100,a=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(i<1)throw new e.t(`pageSize must be >= 1, got ${i}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.signer.readContract(r.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*i),u=l+BigInt(i)>BigInt(c)?BigInt(c):l+BigInt(i);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:i};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.signer.readContract(r.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:i};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:c,page:n,pageSize:i}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.signer.readContract(t.m(e.tokenAddress)),this.signer.readContract(t.h(e.tokenAddress)),this.signer.readContract(t.f(e.tokenAddress)),this.signer.readContract(t.p(e.tokenAddress)),this.signer.readContract(t.m(e.confidentialTokenAddress)),this.signer.readContract(t.h(e.confidentialTokenAddress)),this.signer.readContract(t.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:n,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ct:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.t(t,n));return c===i.zeroAddress?this.#i(a,null,Y):this.#i(a,{confidentialTokenAddress:c,isValid:s})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,i.getAddress)(e),a=`ut:${t}:${n}`,o=this.#r(a);if(o!==void 0)return o;let[s,c]=await this.signer.readContract(r.n(t,n));return c===i.zeroAddress?this.#i(a,null,Y):this.#i(a,{tokenAddress:c,isValid:s})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.signer.readContract(r.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.signer.readContract(r.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.signer.readContract(r.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.t(t,(0,i.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.n(t,(0,i.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.signer.readContract(r.s(t,(0,i.getAddress)(e)))}};const Z=365*86400;var je=class{relayer;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n;#r;#i=null;#a=null;constructor(e){this.relayer=e.relayer,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new C,this.cache=new ue(e.storage),this.#t=e.onEvent??function(){},this.registry=new X({signer:this.signer,registryAddresses:e.registryAddresses,registryTTL:e.registryTTL}),this.#e=e.registryTTL;let n={relayer:this.relayer,signer:this.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>Z?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${Z}s); capping to ${Z}s.`),Z):t})(),sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};if(this.credentials=new A(n),this.delegatedCredentials=new j(n),this.#r=this.#o(),this.signer.subscribe){let n=e.signerLifecycleCallbacks,r=(e,n)=>{n().catch(n=>{this.emitEvent({type:t.r.TransactionError,operation:e,error:t.y(n)})})};this.#n=this.signer.subscribe({onDisconnect:()=>{r(`signerDisconnect`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=null,this.#a=null,n?.onDisconnect?.()})},onAccountChange:e=>{r(`signerAccountChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#i=(0,i.getAddress)(e);try{this.#a=await this.signer.getChainId()}catch{}n?.onAccountChange?.(e)})},onChainChange:e=>{r(`signerChainChange`,async()=>{await this.#s(),await this.cache.clearAll(),this.#a=e;try{this.#i=await this.signer.getAddress()}catch{}n?.onChainChange?.(e)})}})}}async#o(){try{let e=await this.signer.getAddress(),t=await this.signer.getChainId();this.#i=e,this.#a=t}catch{}}async#s(){if(await this.#r,this.#i===null||this.#a===null)return;let e=await A.computeStoreKey(this.#i,this.#a);await this.credentials.revokeByKey(e)}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new ke(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new X({signer:this.signer,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(e.length===0)return{};let n=e.map(e=>({handle:e.handle,contractAddress:(0,i.getAddress)(e.contractAddress)})),r={},a=[];for(let e of n)t._(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;let o=await this.signer.getAddress(),s=[];for(let e of a){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?s.push(e):r[e.handle]=t}if(s.length===0)return r;let c=await this.credentials.allow(...new Set(n.map(e=>e.contractAddress))),l=new Map;for(let e of s){let t=l.get(e.contractAddress);t?t.push(e.handle):l.set(e.contractAddress,[e.handle])}let u=Date.now(),d=s.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:d}),await t.n([...l.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:c.contractAddresses,privateKey:c.privateKey,publicKey:c.publicKey,signature:c.signature,signerAddress:o,startTimestamp:c.startTimestamp,durationDays:c.durationDays});for(let[t,i]of Object.entries(n))r[t]=i,await this.cache.set(o,e,t,i)}),5);let e={};for(let t of d){let n=r[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-u,handles:d,result:e}),r}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:t.y(e),durationMs:Date.now()-u,handles:d}),t.O(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw t.O(e,`Public decryption failed`)}}async revokeSession(){await this.#r;let e=this.#i??await this.signer.getAddress(),t=this.#a??await this.signer.getChainId(),n=await A.computeStoreKey(e,t);await this.credentials.revokeByKey(n),await this.cache.clearForRequester(e)}dispose(){this.#n?.(),this.#n=void 0}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}async function Me(e,t,n){await e.set(Q(t),n)}async function Ne(e,t){return e.get(Q(t))}async function Pe(e,t){await e.delete(Q(t))}var $=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 Fe=new $;exports.ACL_TOPICS=Oe,exports.AclPausedError=t.k,exports.AclTopics=G,exports.ApprovalFailedError=a,exports.BalanceCheckUnavailableError=l,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.CredentialsManager=A,exports.DecryptCache=ue,exports.DecryptionFailedError=e.r,exports.DefaultRegistryAddresses=Ae,exports.DelegatedCredentialsManager=j,exports.DelegationContractIsSelfError=t.A,exports.DelegationCooldownError=t.j,exports.DelegationDelegateEqualsContractError=t.M,exports.DelegationExpirationTooSoonError=t.N,exports.DelegationExpiredError=t.P,exports.DelegationExpiryUnchangedError=t.F,exports.DelegationNotFoundError=t.I,exports.DelegationNotPropagatedError=t.L,exports.DelegationSelfNotAllowedError=t.R,exports.ERC20ReadFailedError=u,exports.ERC7984_INTERFACE_ID=r.c,exports.ERC7984_WRAPPER_INTERFACE_ID=r.l,exports.EncryptionFailedError=e.i,exports.HardhatConfig=n.a,exports.IndexedDBStorage=m,exports.InsufficientConfidentialBalanceError=s,exports.InsufficientERC20BalanceError=c,exports.InvalidKeypairError=t.z,exports.KeypairExpiredError=t.B,exports.MainnetConfig=n.o,exports.MemoryStorage=C,exports.NoCiphertextError=t.V,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.RelayerWeb=le,exports.SepoliaConfig=n.s,exports.SigningFailedError=t.H,exports.SigningRejectedError=t.U,exports.TOKEN_TOPICS=Ce,exports.Token=ke,exports.Topics=N,exports.TransactionRevertedError=o,exports.WrappersRegistry=X,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.a,exports.ZamaErrorCode=e.o,exports.ZamaSDK=je,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.chromeSessionStorage=Fe,exports.clearPendingUnshield=Pe,exports.confidentialBalanceOfContract=r.p,exports.confidentialTotalSupplyContract=r.m,exports.confidentialTransferContract=r.h,exports.confidentialTransferFromContract=r.g,exports.decimalsContract=t.f,exports.decodeAclEvent=we,exports.decodeAclEvents=Te,exports.decodeConfidentialTransfer=V,exports.decodeDelegatedForUserDecryption=K,exports.decodeOnChainEvent=ye,exports.decodeOnChainEvents=be,exports.decodeRevokedDelegationForUserDecryption=q,exports.decodeUnwrapRequested=U,exports.decodeUnwrappedFinalized=W,exports.decodeUnwrappedStarted=ve,exports.decodeWrapped=H,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=r.C,exports.findDelegatedForUserDecryption=Ee,exports.findRevokedDelegationForUserDecryption=De,exports.findUnwrapRequested=xe,exports.findWrapped=Se,exports.getConfidentialTokenAddressContract=r.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=r.n,exports.getTokenPairContract=r.r,exports.getTokenPairsContract=r.i,exports.getTokenPairsLengthContract=r.a,exports.getTokenPairsSliceContract=r.o,exports.indexedDBStorage=ee,exports.inferredTotalSupplyContract=r.w,exports.isConfidentialTokenContract=r.u,exports.isConfidentialTokenValidContract=r.s,exports.isConfidentialWrapperContract=r.d,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=r._,exports.isZeroHandle=t._,exports.loadPendingUnshield=Ne,exports.matchAclRevert=p,exports.matchZamaError=e.s,exports.memoryStorage=de,exports.nameContract=t.m,exports.rateContract=r.v,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=Me,exports.setOperatorContract=r.y,exports.supportsInterfaceContract=r.f,exports.symbolContract=t.h,exports.totalSupplyContract=r.b,exports.underlyingContract=r.T,exports.unwrapContract=r.x,exports.unwrapFromBalanceContract=r.S,exports.wrapContract=r.E;
515
515
  //# sourceMappingURL=index.cjs.map