@zama-fhe/sdk 3.0.0-alpha.28 → 3.0.0-alpha.29
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/dist/cjs/ethers/index.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/readonly-token.cjs +1 -1
- package/dist/cjs/readonly-token.cjs.map +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/cjs/wrappers-registry.cjs.map +1 -1
- package/dist/esm/{cleartext-Cr8QJJZy.d.ts → cleartext-D0fG1vxX.d.ts} +2 -2
- package/dist/esm/ethers/index.d.ts +3 -3
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/{index-L1u8Jsrx.d.ts → index-BUdoZMvX.d.ts} +16 -16
- package/dist/esm/index.d.ts +6 -6
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/node/index.d.ts +2 -2
- package/dist/esm/query/index.d.ts +12 -12
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/readonly-token-B1kmoWQf.js +2 -0
- package/dist/esm/readonly-token-B1kmoWQf.js.map +1 -0
- package/dist/esm/{types-CmfU2ovm.d.ts → types-BnEKfr_J.d.ts} +6 -6
- package/dist/esm/{types-BwSAux96.d.ts → types-CZTkF687.d.ts} +2 -2
- package/dist/esm/{types-CO3wLcMI.d.ts → types-D-8TJ_H5.d.ts} +2 -2
- package/dist/esm/viem/index.d.ts +3 -3
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/web/index.d.ts +1 -1
- package/dist/esm/wrappers-registry-D5orGELU.js.map +1 -1
- package/package.json +1 -1
- package/dist/esm/readonly-token-CDCsK14J.js +0 -2
- package/dist/esm/readonly-token-CDCsK14J.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":["#readProvider","BrowserProvider","#signerPromise","#eip1193","BrowserProvider","eip1193Subscribe","buildZamaConfig","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/ethers/ethers-provider.ts","../../../src/ethers/ethers-signer.ts","../../../src/ethers/config.ts","../../../src/ethers/contracts.ts"],"sourcesContent":["import { ethers, BrowserProvider } from \"ethers\";\nimport type {\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n EIP1193Provider,\n Hex,\n} from \"viem\";\nimport type { GenericProvider, ReadContractConfig, TransactionReceipt } from \"../types\";\n\n/**\n * Configuration for {@link EthersProvider}.\n *\n * Two variants:\n *\n * - **EIP-1193** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally.\n *\n * - **Pre-built** — `{ provider }`: pass any ethers `Provider`\n * (e.g. `JsonRpcProvider`, `WebSocketProvider`).\n */\nexport type EthersProviderConfig = { ethereum: EIP1193Provider } | { provider: ethers.Provider };\n\n/**\n * Read-only {@link GenericProvider} backed by ethers v6.\n *\n * Use this for integrations that only need public chain reads before the user has connected their\n * wallet.\n *\n * @example\n * ```ts\n * // Dedicated RPC\n * const provider = new EthersProvider({\n * provider: new ethers.JsonRpcProvider(ALCHEMY_URL),\n * });\n *\n * // Wallet-sourced RPC (shares transport with EthersSigner)\n * const provider = new EthersProvider({ ethereum: window.ethereum });\n * ```\n */\nexport class EthersProvider implements GenericProvider {\n readonly #readProvider: ethers.Provider;\n\n constructor(config: EthersProviderConfig) {\n if (\"ethereum\" in config) {\n this.#readProvider = new BrowserProvider(config.ethereum);\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n async getChainId(): Promise<number> {\n const network = await this.#readProvider.getNetwork();\n return Number(network.chainId);\n }\n\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n const contract = new ethers.Contract(\n config.address,\n config.abi as ethers.InterfaceAbi,\n this.#readProvider,\n );\n const fn = contract.getFunction(config.functionName);\n return fn(...(config.args as readonly unknown[])) as Promise<\n ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>\n >;\n }\n\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#readProvider.getBlock(\"latest\");\n if (!block) {\n throw new Error(\"Failed to fetch latest block\");\n }\n if (block.timestamp === null) {\n throw new Error(\"Latest block has no timestamp\");\n }\n return BigInt(block.timestamp);\n }\n\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#readProvider.waitForTransaction(hash);\n if (!receipt) {\n throw new Error(\"Transaction receipt not found\");\n }\n return {\n logs: receipt.logs.map((log) => ({\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\n }\n}\n","import { 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 EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport type { EIP712TypedData } from \"../relayer/relayer-sdk.types\";\nimport type { GenericSigner, SignerIdentityListener, WriteContractConfig } from \"../types\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Two variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and `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 * For public chain reads, construct a separate {@link EthersProvider}.\n */\nexport type EthersSignerConfig = { ethereum: EIP1193Provider } | { signer: Signer };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner implements GenericSigner {\n readonly #signerPromise: Promise<Signer>;\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.#eip1193 = config.ethereum;\n } else {\n this.#signerPromise = Promise.resolve(config.signer);\n }\n }\n\n async getChainId(): Promise<number> {\n const signer = await this.#signerPromise;\n const provider = signer.provider;\n if (!provider) {\n throw new TypeError(\"Signer has no provider — cannot read chain ID\");\n }\n const network = await provider.getNetwork();\n return Number(network.chainId);\n }\n\n async getAddress(): Promise<Address> {\n const signer = await this.#signerPromise;\n return getAddress(await signer.getAddress());\n }\n\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#signerPromise;\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.#signerPromise;\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 subscribe(onIdentityChange: SignerIdentityListener): () => void {\n return eip1193Subscribe({\n provider: this.#eip1193,\n getInitialIdentity: async () => {\n const signer = await this.#signerPromise;\n const provider = signer.provider;\n if (!provider) {\n return undefined;\n }\n const [address, network] = await Promise.all([signer.getAddress(), provider.getNetwork()]);\n const chainId = Number(network.chainId);\n return { address: getAddress(address), chainId };\n },\n onIdentityChange,\n });\n }\n}\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"../config/build\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { EthersProvider } from \"./ethers-provider\";\nimport { EthersSigner } from \"./ethers-signer\";\nimport type { ZamaConfigEthers } from \"./types\";\n\n/** Create a {@link ZamaConfig} from ethers types. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigEthers<TChains>,\n): ZamaConfig {\n if (\"signer\" in params && params.signer) {\n const signer = new EthersSigner({ signer: params.signer });\n if (!params.signer.provider) {\n throw new Error(\"createConfig requires a Signer with an attached provider for chain reads\");\n }\n const provider = new EthersProvider({ provider: params.signer.provider });\n return buildZamaConfig(signer, provider, params);\n }\n\n const signer = new EthersSigner({ ethereum: params.ethereum });\n const provider =\n \"provider\" in params && params.provider\n ? new EthersProvider({ provider: params.provider })\n : new EthersProvider({ ethereum: params.ethereum });\n return buildZamaConfig(signer, provider, params);\n}\n","import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { 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":"yNAyCA,IAAa,EAAb,KAAuD,CACrD,GAEA,YAAY,EAA8B,CACpC,aAAc,EAChB,MAAA,EAAqB,IAAIC,EAAAA,gBAAgB,EAAO,SAAS,CAEzD,MAAA,EAAqB,EAAO,SAIhC,MAAM,YAA8B,CAClC,IAAM,EAAU,MAAM,MAAA,EAAmB,YAAY,CACrD,OAAO,OAAO,EAAQ,QAAQ,CAGhC,MAAM,aAKJ,EACkF,CAO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EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAiC,EAAU,EAAyB,CAAC"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["#readProvider","BrowserProvider","#signerPromise","#eip1193","BrowserProvider","eip1193Subscribe","buildZamaConfig","confidentialBalanceOfContract","underlyingContract","supportsInterfaceContract","confidentialTransferContract","unwrapContract","unwrapFromBalanceContract","finalizeUnwrapContract","setOperatorContract","wrapContract","getTokenPairsContract","getTokenPairsLengthContract","getTokenPairsSliceContract","getTokenPairContract","getConfidentialTokenAddressContract","getTokenAddressContract","isConfidentialTokenValidContract"],"sources":["../../../src/ethers/ethers-provider.ts","../../../src/ethers/ethers-signer.ts","../../../src/ethers/config.ts","../../../src/ethers/contracts.ts"],"sourcesContent":["import { ethers, BrowserProvider } from \"ethers\";\nimport type {\n Abi,\n ContractFunctionArgs,\n ContractFunctionName,\n ContractFunctionReturnType,\n EIP1193Provider,\n Hex,\n} from \"viem\";\nimport type { GenericProvider, ReadContractConfig, TransactionReceipt } from \"../types\";\n\n/**\n * Configuration for {@link EthersProvider}.\n *\n * Two variants:\n *\n * - **EIP-1193** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally.\n *\n * - **Pre-built** — `{ provider }`: pass any ethers `Provider`\n * (e.g. `JsonRpcProvider`, `WebSocketProvider`).\n */\nexport type EthersProviderConfig = { ethereum: EIP1193Provider } | { provider: ethers.Provider };\n\n/**\n * Read-only {@link GenericProvider} backed by ethers v6.\n *\n * Use this for integrations that only need public chain reads before the user has connected their\n * wallet.\n *\n * @example\n * ```ts\n * // Dedicated RPC\n * const provider = new EthersProvider({\n * provider: new ethers.JsonRpcProvider(ALCHEMY_URL),\n * });\n *\n * // Wallet-sourced RPC (shares transport with EthersSigner)\n * const provider = new EthersProvider({ ethereum: window.ethereum });\n * ```\n */\nexport class EthersProvider implements GenericProvider {\n readonly #readProvider: ethers.Provider;\n\n constructor(config: EthersProviderConfig) {\n if (\"ethereum\" in config) {\n this.#readProvider = new BrowserProvider(config.ethereum);\n } else {\n this.#readProvider = config.provider;\n }\n }\n\n async getChainId(): Promise<number> {\n const network = await this.#readProvider.getNetwork();\n return Number(network.chainId);\n }\n\n async readContract<\n const TAbi extends Abi | readonly unknown[],\n TFunctionName extends ContractFunctionName<TAbi, \"pure\" | \"view\">,\n const TArgs extends ContractFunctionArgs<TAbi, \"pure\" | \"view\", TFunctionName>,\n >(\n config: ReadContractConfig<TAbi, TFunctionName, TArgs>,\n ): Promise<ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>> {\n const contract = new ethers.Contract(\n config.address,\n config.abi as ethers.InterfaceAbi,\n this.#readProvider,\n );\n const fn = contract.getFunction(config.functionName);\n return fn(...(config.args as readonly unknown[])) as Promise<\n ContractFunctionReturnType<TAbi, \"pure\" | \"view\", TFunctionName, TArgs>\n >;\n }\n\n async getBlockTimestamp(): Promise<bigint> {\n const block = await this.#readProvider.getBlock(\"latest\");\n if (!block) {\n throw new Error(\"Failed to fetch latest block\");\n }\n if (block.timestamp === null) {\n throw new Error(\"Latest block has no timestamp\");\n }\n return BigInt(block.timestamp);\n }\n\n async waitForTransactionReceipt(hash: Hex): Promise<TransactionReceipt> {\n const receipt = await this.#readProvider.waitForTransaction(hash);\n if (!receipt) {\n throw new Error(\"Transaction receipt not found\");\n }\n return {\n logs: receipt.logs.map((log) => ({\n topics: log.topics.filter((t): t is Hex => t !== null),\n data: log.data as Hex,\n })),\n };\n }\n}\n","import { 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 EIP1193Provider,\n type Hex,\n} from \"viem\";\nimport type { EIP712TypedData } from \"../relayer/relayer-sdk.types\";\nimport type { GenericSigner, SignerIdentityListener, WriteContractConfig } from \"../types\";\nimport { eip1193Subscribe } from \"../signer/eip1193-subscribe\";\n\n/**\n * Configuration for {@link EthersSigner}.\n *\n * Two variants:\n *\n * - **Browser** — `{ ethereum }`: pass the raw EIP-1193 provider (e.g. `window.ethereum`).\n * A `BrowserProvider` is created internally and `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 * For public chain reads, construct a separate {@link EthersProvider}.\n */\nexport type EthersSignerConfig = { ethereum: EIP1193Provider } | { signer: Signer };\n\n/**\n * GenericSigner backed by ethers.\n *\n * Accepts either a raw EIP-1193 provider (`{ ethereum }`) which creates a\n * `BrowserProvider` internally, or a `Signer` directly (`{ signer }`)\n * for Node.js scripts.\n *\n * @param config - {@link EthersSignerConfig}\n */\nexport class EthersSigner implements GenericSigner {\n readonly #signerPromise: Promise<Signer>;\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.#eip1193 = config.ethereum;\n } else {\n this.#signerPromise = Promise.resolve(config.signer);\n }\n }\n\n async getChainId(): Promise<number> {\n const signer = await this.#signerPromise;\n const provider = signer.provider;\n if (!provider) {\n throw new TypeError(\"Signer has no provider — cannot read chain ID\");\n }\n const network = await provider.getNetwork();\n return Number(network.chainId);\n }\n\n async getAddress(): Promise<Address> {\n const signer = await this.#signerPromise;\n return getAddress(await signer.getAddress());\n }\n\n async signTypedData(typedData: EIP712TypedData): Promise<Hex> {\n const signer = await this.#signerPromise;\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.#signerPromise;\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 subscribe(onIdentityChange: SignerIdentityListener): () => void {\n return eip1193Subscribe({\n provider: this.#eip1193,\n getInitialIdentity: async () => {\n const signer = await this.#signerPromise;\n const provider = signer.provider;\n if (!provider) {\n return undefined;\n }\n const [address, network] = await Promise.all([signer.getAddress(), provider.getNetwork()]);\n const chainId = Number(network.chainId);\n return { address: getAddress(address), chainId };\n },\n onIdentityChange,\n });\n }\n}\n","import type { FheChain } from \"../chains\";\nimport { buildZamaConfig } from \"../config/build\";\nimport type { ZamaConfig } from \"../config/types\";\nimport { EthersProvider } from \"./ethers-provider\";\nimport { EthersSigner } from \"./ethers-signer\";\nimport type { ZamaConfigEthers } from \"./types\";\n\n/** Create a {@link ZamaConfig} from ethers types. */\nexport function createConfig<const TChains extends readonly [FheChain, ...FheChain[]]>(\n params: ZamaConfigEthers<TChains>,\n): ZamaConfig {\n if (\"signer\" in params && params.signer) {\n const signer = new EthersSigner({ signer: params.signer });\n if (!params.signer.provider) {\n throw new Error(\"createConfig requires a Signer with an attached provider for chain reads\");\n }\n const provider = new EthersProvider({ provider: params.signer.provider });\n return buildZamaConfig(signer, provider, params);\n }\n\n const signer = new EthersSigner({ ethereum: params.ethereum });\n const provider =\n \"provider\" in params && params.provider\n ? new EthersProvider({ provider: params.provider })\n : new EthersProvider({ ethereum: params.ethereum });\n return buildZamaConfig(signer, provider, params);\n}\n","import {\n decodeFunctionResult,\n encodeFunctionData,\n isHex,\n type Abi,\n type Address,\n type Hex,\n} from \"viem\";\n\nimport type { 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 operator: Address,\n until?: number,\n) {\n return ethersWrite(signer, setOperatorContract(tokenAddress, operator, until));\n}\n\nexport function writeWrapContract(\n signer: EthersTransactionSigner,\n wrapperAddress: Address,\n to: Address,\n amount: bigint,\n) {\n return ethersWrite(signer, wrapContract(wrapperAddress, to, amount));\n}\n\n// ── Registry read helpers ──────────────────────────────────\n\nexport function readTokenPairsContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsContract(registry));\n}\n\nexport function readTokenPairsLengthContract(provider: EthersCallProvider, registry: Address) {\n return ethersRead(provider, getTokenPairsLengthContract(registry));\n}\n\nexport function readTokenPairsSliceContract(\n provider: EthersCallProvider,\n registry: Address,\n fromIndex: bigint,\n toIndex: bigint,\n) {\n return ethersRead(provider, getTokenPairsSliceContract(registry, fromIndex, toIndex));\n}\n\nexport function readTokenPairContract(\n provider: EthersCallProvider,\n registry: Address,\n index: bigint,\n) {\n return ethersRead(provider, getTokenPairContract(registry, index));\n}\n\nexport function readConfidentialTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n tokenAddress: Address,\n) {\n return ethersRead(provider, getConfidentialTokenAddressContract(registry, tokenAddress));\n}\n\nexport function readTokenAddressContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, getTokenAddressContract(registry, confidentialTokenAddress));\n}\n\nexport function readIsConfidentialTokenValidContract(\n provider: EthersCallProvider,\n registry: Address,\n confidentialTokenAddress: Address,\n) {\n return ethersRead(provider, isConfidentialTokenValidContract(registry, confidentialTokenAddress));\n}\n"],"mappings":"yNAyCA,IAAa,EAAb,KAAuD,CACrD,GAEA,YAAY,EAA8B,CACpC,aAAc,EAChB,MAAA,EAAqB,IAAIC,EAAAA,gBAAgB,EAAO,SAAS,CAEzD,MAAA,EAAqB,EAAO,SAIhC,MAAM,YAA8B,CAClC,IAAM,EAAU,MAAM,MAAA,EAAmB,YAAY,CACrD,OA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AA,EAAwB,EAAU,EAAyB,CAAC,CAG1F,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAiC,EAAU,EAAyB,CAAC"}
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./readonly-token.cjs`),n=require(`./encryption.cjs`),r=require(`./signer.cjs`),i=require(`./relayer-cleartext.cjs`),a=require(`./indexeddb-storage.cjs`),o=require(`./build.cjs`),s=require(`./assertions.cjs`),c=require(`./chains.cjs`),l=require(`./wrappers-registry.cjs`);let u=require(`viem`);var d=class extends e.r{constructor(t,n){super(e.i.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},f=class extends e.r{constructor(t,n){super(e.i.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},p=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},m=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},h=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},g=class extends e.r{operation;signerChainId;providerChainId;constructor({operation:t,signerChainId:n,providerChainId:r},i){super(e.i.ChainMismatch,`Operation "${t}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=t,this.signerChainId=n,this.providerChainId=r}},ee=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},te=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},ne=class extends e.r{constructor(t,n){super(e.i.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},_=class extends e.r{constructor(t,n){super(e.i.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function re(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const v={AlreadyDelegatedOrRevokedInSameBlock:e=>new t.b(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.y(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.v(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.D(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.w(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.T(`Cannot revoke: no active delegation exists.`,{cause:e})};function y(e){let t=e instanceof Error?e:void 0,n=re(e);if(n&&n in v)return v[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(v))if(r.includes(e))return n(t);return null}function b(r,i,a=!1){if(r instanceof n.t||r instanceof h||r instanceof e.n||r instanceof t.E||r instanceof t.k||r instanceof t.O)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new h(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new t.E(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet — after granting delegation, allow 1–2 minutes for cross-chain synchronization before retrying. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):o===void 0?new n.t(i,{cause:r}):new e.n(r instanceof Error?r.message:i,o,{cause:r})}function ie(){return{type:`cleartext`,createRelayer:t=>{if(!t.executorAddress)throw new e.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new i.t(t)}}}function x(e){return e.startsWith(`0x`)?e:`0x${e}`}function ae(e){return o.t(e.signer,e.provider,e)}var S=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,u.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,a)}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,u.getAddress)(e)}:${(0,u.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))}},oe=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 x(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 C(e){s.o(e,`Stored credentials`),s.s(e.publicKey,`credentials.publicKey`),s.t(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)s.r(typeof t==`string`&&(0,u.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);s.o(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),s.s(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),s.s(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),s.r(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),s.r(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function se(e){C(e);let t=e;s.r(typeof t.delegatorAddress==`string`&&(0,u.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),s.r(typeof t.delegateAddress==`string`&&(0,u.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),s.r(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),s.r(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function w(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function T(e,t){let n=new Set(t.map(e=>(0,u.getAddress)(e))),r=new Set(e.map(e=>(0,u.getAddress)(e)));return n.isSubsetOf(r)}function E(e,t){return w(e)?T(e.contractAddresses,t):!1}function D(e){return[...new Set(e.map(e=>(0,u.getAddress)(e)))].toSorted()}async function O(...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 ce=class{#e;constructor(e){this.#e=e}#t(e){s.o(e,`Session entry`),s.s(e.signature,`session.signature`),s.r(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),s.r(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}},le=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 ce(e.sessionStorage),this.crypto=new oe,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(E(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(w(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(w(e)){if(T(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.r)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:t.r.CredentialsCorrupted,error:s.u(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),!E(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),E(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.r)throw n;return t.A(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(T(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(T(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=D([...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:s.u(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:s.u(e)})}}};function ue(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 de=class e extends le{#e;#t=null;#n=null;static async computeStoreKey(e,t){return O((0,u.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,ue(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof o.i&&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=D(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 revokeFor(t){await this.revokeSession(await e.computeStoreKey(t.address,t.chainId))}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=D(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){C(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,u.getAddress)(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await e.computeStoreKey(t,n);return this.#n=r,this.#t=i,i}},fe=class e extends le{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return O((0,u.getAddress)(e),(0,u.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,u.getAddress)(e),r=D(t),i=await this.#i(n);return this.resolveCredentials({key:i,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,u.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,u.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,u.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,u.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){se(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(),i=`${(0,u.getAddress)(n)}:${(0,u.getAddress)(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(n,t,r);return this.#n=i,this.#t=a,a}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}};function k(e){return(0,u.keccak256)((0,u.toBytes)(e))}const A={ConfidentialTransfer:k(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:k(`Wrapped(address,uint256)`),UnwrapRequested:k(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:k(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:k(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:k(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:k(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:k(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function j(e){return(0,u.getAddress)(x(e.slice(-40)))}function pe(e){return BigInt(e)}function M(e){return e}function N(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function P(e,t){return(0,u.getAddress)(x(N(e,t).slice(-40)))}function F(e,t){return BigInt(`0x`+N(e,t))}function me(e,t){return BigInt(`0x`+N(e,t))!==0n}function I(e,t){return x(N(e,t))}function L(e){return e.topics[0]!==A.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:j(e.topics[1]),to:j(e.topics[2]),encryptedAmountHandle:M(e.topics[3])}}function R(e){return e.topics[0]!==A.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:j(e.topics[1]),amountIn:F(e.data,0)}}function z(e){return e.topics[0]===A.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:j(e.topics[1]),unwrapRequestId:M(e.topics[2]),encryptedAmount:I(e.data,0)}:e.topics[0]===A.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:j(e.topics[1]),encryptedAmount:I(e.data,0)}:null}function B(e){return e.topics[0]===A.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:j(e.topics[1]),unwrapRequestId:M(e.topics[2]),encryptedAmount:I(e.data,0),cleartextAmount:F(e.data,1)}:e.topics[0]===A.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:j(e.topics[1]),encryptedAmount:I(e.data,0),cleartextAmount:F(e.data,1)}:null}function he(e){let t=B(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function ge(e){if(e.topics[0]!==A.UnwrapFinalizedLegacy)return null;let t=B(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function V(e){return e.topics[0]!==A.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:pe(e.topics[1]),txId:pe(e.topics[2]),to:j(e.topics[3]),returnVal:me(e.data,0),refund:P(e.data,1),requestedAmount:I(e.data,2),burnAmount:I(e.data,3)}}function H(e){return L(e)??R(e)??z(e)??ge(e)??B(e)??V(e)}function _e(e){let t=[];for(let n of e){let e=H(n);e&&t.push(e)}return t}function U(e){for(let t of e){let e=z(t);if(e)return e}return null}function ve(e){for(let t of e){let e=R(t);if(e)return e}return null}const ye=[A.ConfidentialTransfer,A.Wrapped,A.UnwrapRequested,A.UnwrapRequestedLegacy,A.UnwrapFinalized,A.UnwrapFinalizedLegacy,A.UnwrappedStarted],W={DelegatedForUserDecryption:k(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:k(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function G(e){return e.topics[0]!==W.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:j(e.topics[1]),delegate:j(e.topics[2]),contractAddress:P(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2),newExpirationDate:F(e.data,3)}}function K(e){return e.topics[0]!==W.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:j(e.topics[1]),delegate:j(e.topics[2]),contractAddress:P(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2)}}function be(e){return G(e)??K(e)}function xe(e){let t=[];for(let n of e){let e=be(n);e&&t.push(e)}return t}function Se(e){for(let t of e){let e=G(t);if(e)return e}return null}function Ce(e){for(let t of e){let e=K(t);if(e)return e}return null}const we=[W.DelegatedForUserDecryption,W.RevokedDelegationForUserDecryption];var Te=class r extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,u.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(l.g(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(r,i,a){let o=this.sdk.requireSigner(`confidentialTransfer`);await this.sdk.requireChainAlignment(`confidentialTransfer`);let{skipBalanceCheck:c=!1,onEncryptComplete:d,onTransferSubmitted:p}=a??{},m=(0,u.getAddress)(r);c||await this.#i(i);let{handles:h,inputProof:g}=await this.sdk.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await o.getAddress()});if(q(()=>d?.()),h.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await o.writeContract(l.b(this.address,m,h[0],g));return this.emit({type:t.r.TransferSubmitted,txHash:e}),q(()=>p?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:s.u(n)}),n instanceof e.r?n:new f(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(r,i,a,o){let c=this.sdk.requireSigner(`confidentialTransferFrom`);await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let d=(0,u.getAddress)(r),p=(0,u.getAddress)(i),{handles:m,inputProof:h}=await this.sdk.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:d});if(q(()=>o?.onEncryptComplete?.()),m.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await c.writeContract(l.x(this.address,d,p,m[0],h));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),q(()=>o?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:s.u(n)}),n instanceof e.r?n:new f(`TransferFrom transaction failed`,{cause:n})}}async approve(n,r){let i=this.sdk.requireSigner(`approve`);await this.sdk.requireChainAlignment(`approve`);let a=(0,u.getAddress)(n);try{let e=await i.writeContract(l.w(this.address,a,r));return this.emit({type:t.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approve`,error:s.u(n)}),n instanceof e.r?n:new d(`Operator approval failed`,{cause:n})}}async isApproved(e,t){return this.sdk.provider.readContract(l.S(this.address,(0,u.getAddress)(t),(0,u.getAddress)(e)))}async shield(n,r){let i=this.sdk.requireSigner(`shield`);await this.sdk.requireChainAlignment(`shield`);let a=await this.#n(),o;try{let e=await i.getAddress();o=await this.sdk.provider.readContract(t.d(a,e))}catch(t){throw t instanceof e.r?t:new _(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:s.u(t)})}if(o<n)throw new te(`Insufficient ERC-20 balance: requested ${n}, available ${o} (token: ${a})`,{requested:n,available:o,token:a});let c=r?.approvalStrategy??`exact`;c!==`skip`&&await this.#o(n,c===`max`,r);try{let e=r?.to?(0,u.getAddress)(r.to):await i.getAddress(),a=await i.writeContract(l._(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:a}),q(()=>r?.onShieldSubmitted?.(a)),{txHash:a,receipt:await this.sdk.provider.waitForTransactionReceipt(a)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield`,error:s.u(n)}),n instanceof e.r?n:new f(`Shield transaction failed`,{cause:n})}}async unwrap(r){let i=this.sdk.requireSigner(`unwrap`);await this.sdk.requireChainAlignment(`unwrap`);let a=await i.getAddress(),{handles:o,inputProof:c}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:a});if(o.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await i.writeContract(l.E(this.address,a,a,o[0],c));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let r=this.sdk.requireSigner(`unwrapAll`);await this.sdk.requireChainAlignment(`unwrapAll`);let i=await r.getAddress(),a=await this.readConfidentialBalanceOf(i);if(t._(a))throw new n.t(`Cannot unshield: balance is zero`);try{let e=await r.writeContract(l.D(this.address,i,i,a));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`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 q(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return q(()=>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 r=this.sdk.requireSigner(`finalizeUnwrap`);await this.sdk.requireChainAlignment(`finalizeUnwrap`);let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];s.n(a,`finalizeUnwrap: clearValue`);try{let e=await r.writeContract(l.m(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=this.sdk.requireSigner(`approveUnderlying`);await this.sdk.requireChainAlignment(`approveUnderlying`);let i=await this.#n(),a=n??2n**256n-1n;try{if(a>0n){let e=await r.getAddress();await this.sdk.provider.readContract(t.l(i,e,this.wrapper))>0n&&await r.writeContract(t.u(i,this.wrapper,0n))}let e=await r.writeContract(t.u(i,this.wrapper,a));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:s.u(n)}),n instanceof e.r?n:new d(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){let i=this.sdk.requireSigner(`delegateDecryption`);if(await this.sdk.requireChainAlignment(`delegateDecryption`),r&&r.getTime()<Date.now()+36e5)throw new t.S(`Expiration date must be at least 1 hour in the future`);let a=(0,u.getAddress)(n),o=await i.getAddress();if(a===(0,u.getAddress)(o))throw new t.D(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.x(`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,d;try{d=await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:a})}catch{d=-1n}if(d===l)throw new t.w(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await i.writeContract(t.a(c,a,this.address,l));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:s.u(n)}),n instanceof e.r?n:y(n)||new f(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=this.sdk.requireSigner(`revokeDelegation`);await this.sdk.requireChainAlignment(`revokeDelegation`);let i=(0,u.getAddress)(n),a=await r.getAddress(),o=await this.getAclAddress(),c;try{c=await this.getDelegationExpiry({delegatorAddress:a,delegateAddress:i})}catch{c=1n}if(c===0n)throw new t.T(`No active delegation found for delegate ${i} on contract ${this.address}.`);try{let e=await r.writeContract(t.c(o,i,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:s.u(n)}),n instanceof e.r?n:y(n)||new f(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:n}){return r.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:n}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return r.#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.r?i.set(t[a].address,n):i.set(t[a].address,new f(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{let e=this.sdk.requireSigner(`assertConfidentialBalance`);n=await this.balanceOf(await e.getAddress())}catch(t){throw t instanceof e.r?t:new ne(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new ee(`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.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new f(`Failed to get unshield receipt`,{cause:t})}let o=U(a.logs);if(!o)throw new f(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),q(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),q(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#o(n,r,i){let a=this.sdk.requireSigner(`approveUnderlying`),o=await this.#n(),s=await a.getAddress(),c=await this.sdk.provider.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{if(c>0n){let e=await a.writeContract(t.u(o,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let e=r?2n**256n-1n:n,s=await a.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:s}),q(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(t){throw t instanceof e.r?t:new d(`ERC-20 approval failed`,{cause:t})}}};function q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Ee={[c.a.id]:c.a.registryAddress,[c.o.id]:c.o.registryAddress,[c.i.id]:c.i.registryAddress},J=300*1e3;var Y=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},Ee,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.provider.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,u.getAddress)(n)}async listPairs(t={}){let n=t.page??1,r=t.pageSize??100,i=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(r<1)throw new e.t(`pageSize must be >= 1, got ${r}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.provider.readContract(l.a(a));s=this.#i(o,Number(e))}let c=BigInt((n-1)*r),u=c+BigInt(r)>BigInt(s)?BigInt(s):c+BigInt(r);if(c>=BigInt(s))return{items:[],total:s,page:n,pageSize:r};let d=`slice:${a}:${c}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(l.o(a,c,u));f=this.#i(d,[...e])}if(!i)return{items:f,total:s,page:n,pageSize:r};let p=`metadata:${a}:${c}:${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?J:void 0)}return{items:m,total:s,page:n,pageSize:r}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.m(e.tokenAddress)),this.provider.readContract(t.h(e.tokenAddress)),this.provider.readContract(t.f(e.tokenAddress)),this.provider.readContract(t.p(e.tokenAddress)),this.provider.readContract(t.m(e.confidentialTokenAddress)),this.provider.readContract(t.h(e.confidentialTokenAddress)),this.provider.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,u.getAddress)(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.t(t,n));return o===u.zeroAddress?this.#i(r,null,J):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,u.getAddress)(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.n(t,n));return o===u.zeroAddress?this.#i(r,null,J):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(l.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(l.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(l.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.t(t,(0,u.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.n(t,(0,u.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.s(t,(0,u.getAddress)(e)))}};const X=365*86400;async function Z(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var De=class{relayer;provider;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n=new Set;#r;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new o.i,this.cache=new S(e.storage),this.#t=e.onEvent??function(){};let t={};for(let n of e.chains??[])n.registryAddress&&(t[n.id]=n.registryAddress);Object.assign(t,e.registryAddresses),this.registry=new Y({provider:this.provider,registryTTL:e.registryTTL,registryAddresses:t}),this.#e=e.registryTTL;let n=(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>X?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${X}s); capping to ${X}s.`),X):t})();if(e.signer){let t={relayer:this.relayer,signer:e.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:n,sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};this.credentials=new de(t),this.delegatedCredentials=new fe(t),this.#r=e.signer.subscribe?.(e=>{this.#i(e)})}else this.credentials=void 0,this.delegatedCredentials=void 0}requireSigner(e){if(!this.signer)throw new r.t(e);return this.signer}requireCredentials(e){if(!this.credentials)throw new r.t(e);return this.credentials}requireDelegatedCredentials(e){if(!this.delegatedCredentials)throw new r.t(e);return this.delegatedCredentials}onIdentityChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireChainAlignment(e){let t=this.requireSigner(e),[n,r]=await Promise.all([t.getChainId(),this.provider.getChainId()]);if(n!==r)throw new g({operation:e,signerChainId:n,providerChainId:r});return n}async#i(e){let t=this.credentials;if(e.previous&&t){let n=e.previous;await Z(`revoke previous identity`,()=>t.revokeFor(n)),await Z(`clear decrypt cache`,()=>this.cache.clearForRequester(n.address))}let n=e.next?.chainId;if(n!==void 0)try{this.relayer.switchChain(n)}catch(e){console.warn(`[zama-sdk] switch relayer chain failed:`,e);return}await Promise.all(Array.from(this.#n,t=>Z(`identity listener`,()=>t(e))))}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new Te(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 Y({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.requireCredentials(`allow`).allow(...e)}async userDecrypt(e){let n=this.requireSigner(`userDecrypt`),r=this.requireCredentials(`userDecrypt`);if(await this.requireChainAlignment(`userDecrypt`),e.length===0)return{};let i=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),a={},o=[];for(let e of i)t._(e.handle)?a[e.handle]=0n:o.push(e);if(o.length===0)return a;let c=await n.getAddress(),l=[];for(let e of o){let t=await this.cache.get(c,e.contractAddress,e.handle);t===null?l.push(e):a[e.handle]=t}if(l.length===0)return a;let d=await r.allow(...new Set(i.map(e=>e.contractAddress))),f=new Map;for(let e of l){let t=f.get(e.contractAddress);t?t.push(e.handle):f.set(e.contractAddress,[e.handle])}let p=Date.now(),m=l.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:m}),await t.n([...f.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:d.contractAddresses,privateKey:d.privateKey,publicKey:d.publicKey,signature:d.signature,signerAddress:c,startTimestamp:d.startTimestamp,durationDays:d.durationDays});for(let[t,r]of Object.entries(n))a[t]=r,await this.cache.set(c,e,t,r)}),5);let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-p,handles:m,result:e}),a}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:s.u(e),durationMs:Date.now()-p,handles:m}),b(e,`Failed to decrypt handles`)}}async delegatedUserDecrypt(e,n,r=n){this.requireSigner(`delegatedUserDecrypt`);let i=this.requireDelegatedCredentials(`delegatedUserDecrypt`);if(await this.requireChainAlignment(`delegatedUserDecrypt`),e.length===0)return{};let a=(0,u.getAddress)(n),o=(0,u.getAddress)(r),c=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),l={},d=[];for(let e of c)t._(e.handle)?l[e.handle]=0n:d.push(e);if(d.length===0)return l;let f=[];for(let e of d){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?f.push(e):l[e.handle]=t}if(f.length===0)return l;let p=await i.allow(a,...new Set(c.map(e=>e.contractAddress))),m=new Map;for(let e of f){let t=m.get(e.contractAddress);t?t.push(e.handle):m.set(e.contractAddress,[e.handle])}let h=Date.now(),g=f.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:g}),await t.n([...m.entries()].map(([e,t])=>async()=>{let n=await this.relayer.delegatedUserDecrypt({handles:t,contractAddress:e,signedContractAddresses:p.contractAddresses,privateKey:p.privateKey,publicKey:p.publicKey,signature:p.signature,delegatorAddress:p.delegatorAddress,delegateAddress:p.delegateAddress,startTimestamp:p.startTimestamp,durationDays:p.durationDays});for(let[t,r]of Object.entries(n))l[t]=r,await this.cache.set(o,e,t,r)}),5);let e={};for(let t of g){let n=l[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-h,handles:g,result:e}),l}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:s.u(e),durationMs:Date.now()-h,handles:g}),b(e,`Failed to decrypt delegated handles`,!0)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw b(e,`Public decryption failed`)}}async encrypt(r){let i=Date.now();try{this.emitEvent({type:t.r.EncryptStart},r.contractAddress);let e=await this.relayer.encrypt(r);return this.emitEvent({type:t.r.EncryptEnd,durationMs:Date.now()-i},r.contractAddress),e}catch(a){throw this.emitEvent({type:t.r.EncryptError,error:s.u(a),durationMs:Date.now()-i},r.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}async revokeSession(){let e=this.requireSigner(`revokeSession`),t=this.requireCredentials(`revokeSession`),n=await e.getAddress(),r=await e.getChainId();try{await t.revokeFor({address:n,chainId:r})}finally{await this.cache.clearForRequester(n)}}dispose(){this.#r?.(),this.#r=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}function Oe(e){return e===null?null:typeof e==`string`?{unwrapTxHash:e}:typeof e==`object`&&`unwrapTxHash`in e?{unwrapTxHash:e.unwrapTxHash,unwrapRequestId:e.unwrapRequestId}:null}async function ke(e,t,n,r){if(r===void 0){await e.set(Q(t),n);return}await e.set(Q(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ae(e,t){return(await je(e,t))?.unwrapTxHash??null}async function je(e,t){return Oe(await e.get(Q(t)))}async function Me(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 Ne=new $;exports.ACL_TOPICS=we,exports.AclPausedError=t.v,exports.AclTopics=W,exports.ApprovalFailedError=d,exports.BalanceCheckUnavailableError=ne,exports.ChainMismatchError=g,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.CredentialsManager=de,exports.DecryptCache=S,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=Ee,exports.DelegatedCredentialsManager=fe,exports.DelegationContractIsSelfError=t.y,exports.DelegationCooldownError=t.b,exports.DelegationDelegateEqualsContractError=t.x,exports.DelegationExpirationTooSoonError=t.S,exports.DelegationExpiredError=t.C,exports.DelegationExpiryUnchangedError=t.w,exports.DelegationNotFoundError=t.T,exports.DelegationNotPropagatedError=t.E,exports.DelegationSelfNotAllowedError=t.D,exports.ERC20ReadFailedError=_,exports.ERC7984_INTERFACE_ID=l.c,exports.ERC7984_WRAPPER_INTERFACE_ID=l.l,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=l.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=a.t,exports.InsufficientConfidentialBalanceError=ee,exports.InsufficientERC20BalanceError=te,exports.InvalidKeypairError=m,exports.KeypairExpiredError=p,exports.MemoryStorage=o.i,exports.NoCiphertextError=h,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.SignerRequiredError=r.t,exports.SigningFailedError=t.O,exports.SigningRejectedError=t.k,exports.TOKEN_TOPICS=ye,exports.Token=Te,exports.Topics=A,exports.TransactionRevertedError=f,exports.WrappersRegistry=Y,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=De,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.anvil=c.t,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.buildZamaConfig=o.t,exports.chains=c.n,exports.chromeSessionStorage=Ne,exports.clearPendingUnshield=Me,exports.cleartext=ie,exports.confidentialBalanceOfContract=l.v,exports.confidentialTotalSupplyContract=l.y,exports.confidentialTransferContract=l.b,exports.confidentialTransferFromContract=l.x,exports.createConfig=ae,exports.decimalsContract=t.f,exports.decodeAclEvent=be,exports.decodeAclEvents=xe,exports.decodeConfidentialTransfer=L,exports.decodeDelegatedForUserDecryption=G,exports.decodeOnChainEvent=H,exports.decodeOnChainEvents=_e,exports.decodeRevokedDelegationForUserDecryption=K,exports.decodeUnwrapFinalized=B,exports.decodeUnwrapRequested=z,exports.decodeUnwrappedFinalized=he,exports.decodeUnwrappedStarted=V,exports.decodeWrapped=R,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=l.m,exports.findDelegatedForUserDecryption=Se,exports.findRevokedDelegationForUserDecryption=Ce,exports.findUnwrapRequested=U,exports.findWrapped=ve,exports.getConfidentialTokenAddressContract=l.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=l.n,exports.getTokenPairContract=l.r,exports.getTokenPairsContract=l.i,exports.getTokenPairsLengthContract=l.a,exports.getTokenPairsSliceContract=l.o,exports.hardhat=c.r,exports.hoodi=c.i,exports.indexedDBStorage=a.n,exports.inferredTotalSupplyContract=l.h,exports.isConfidentialTokenContract=l.d,exports.isConfidentialTokenValidContract=l.s,exports.isConfidentialWrapperContract=l.f,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=l.S,exports.isZeroHandle=t._,exports.loadPendingUnshield=Ae,exports.loadPendingUnshieldRequest=je,exports.mainnet=c.a,exports.matchAclRevert=y,exports.matchZamaError=e.a,exports.memoryStorage=o.a,exports.nameContract=t.m,exports.rateContract=l.C,exports.resolveChainRelayers=o.n,exports.resolveStorage=o.r,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=ke,exports.sepolia=c.o,exports.setOperatorContract=l.w,exports.supportsInterfaceContract=l.p,exports.symbolContract=t.h,exports.totalSupplyContract=l.T,exports.underlyingContract=l.g,exports.unwrapContract=l.E,exports.unwrapFromBalanceContract=l.D,exports.wrapContract=l._;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./relayer.cjs`),t=require(`./readonly-token.cjs`),n=require(`./encryption.cjs`),r=require(`./signer.cjs`),i=require(`./relayer-cleartext.cjs`),a=require(`./indexeddb-storage.cjs`),o=require(`./build.cjs`),s=require(`./assertions.cjs`),c=require(`./chains.cjs`),l=require(`./wrappers-registry.cjs`);let u=require(`viem`);var d=class extends e.r{constructor(t,n){super(e.i.ApprovalFailed,t,n),this.name=`ApprovalFailedError`}},f=class extends e.r{constructor(t,n){super(e.i.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},p=class extends e.r{constructor(t,n){super(e.i.KeypairExpired,t,n),this.name=`KeypairExpiredError`}},m=class extends e.r{constructor(t,n){super(e.i.InvalidKeypair,t,n),this.name=`InvalidKeypairError`}},h=class extends e.r{constructor(t,n){super(e.i.NoCiphertext,t,n),this.name=`NoCiphertextError`}},g=class extends e.r{operation;signerChainId;providerChainId;constructor({operation:t,signerChainId:n,providerChainId:r},i){super(e.i.ChainMismatch,`Operation "${t}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=t,this.signerChainId=n,this.providerChainId=r}},ee=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},te=class extends e.r{requested;available;token;constructor(t,n,r){super(e.i.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},ne=class extends e.r{constructor(t,n){super(e.i.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},_=class extends e.r{constructor(t,n){super(e.i.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function re(e){if(!(e instanceof Error))return null;let t=e.cause;if(typeof t!=`object`||!t||!(`data`in t))return null;let{data:n}=t;return typeof n!=`object`||!n||!(`errorName`in n)?null:typeof n.errorName==`string`?n.errorName:null}const v={AlreadyDelegatedOrRevokedInSameBlock:e=>new t.b(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new t.y(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new t.v(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new t.D(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new t.x(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new t.S(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new t.w(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new t.T(`Cannot revoke: no active delegation exists.`,{cause:e})};function y(e){let t=e instanceof Error?e:void 0,n=re(e);if(n&&n in v)return v[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(v))if(r.includes(e))return n(t);return null}function b(r,i,a=!1){if(r instanceof n.t||r instanceof h||r instanceof e.n||r instanceof t.E||r instanceof t.k||r instanceof t.O)return r;let o=typeof r==`object`&&r&&`statusCode`in r&&typeof r.statusCode==`number`?r.statusCode:void 0;return o===400?new h(r instanceof Error?r.message:`No ciphertext for this account`,{cause:r}):a&&o===500?new t.E(`Delegated decryption failed with a server error. This is most commonly caused by the delegation not having propagated to the gateway yet — after granting delegation, allow 1–2 minutes for cross-chain synchronization before retrying. If the error persists, the gateway or relayer may be experiencing an unrelated issue.`,{cause:r}):o===void 0?new n.t(i,{cause:r}):new e.n(r instanceof Error?r.message:i,o,{cause:r})}function ie(){return{type:`cleartext`,createRelayer:t=>{if(!t.executorAddress)throw new e.t(`Cleartext relayer requires an executorAddress. Either use a chain preset that includes it (e.g. hardhat, hoodi) or set it on the chain definition.`);return new i.t(t)}}}function x(e){return e.startsWith(`0x`)?e:`0x${e}`}function ae(e){return o.t(e.signer,e.provider,e)}var S=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,u.getAddress)(e),n=`${this.#t}:${t}:`,r=await this.#s(),i=[],a=[];for(let e of r)e.startsWith(n)?i.push(e):a.push(e);await Promise.all(i.map(e=>this.#e.delete(e).catch(()=>{}))),await this.#e.set(this.#n,a)}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,u.getAddress)(e)}:${(0,u.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))}},oe=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 x(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 C(e){s.o(e,`Stored credentials`),s.s(e.publicKey,`credentials.publicKey`),s.t(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)s.r(typeof t==`string`&&(0,u.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);s.o(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),s.s(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),s.s(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),s.r(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),s.r(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function se(e){C(e);let t=e;s.r(typeof t.delegatorAddress==`string`&&(0,u.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),s.r(typeof t.delegateAddress==`string`&&(0,u.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),s.r(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),s.r(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function w(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function T(e,t){let n=new Set(t.map(e=>(0,u.getAddress)(e))),r=new Set(e.map(e=>(0,u.getAddress)(e)));return n.isSubsetOf(r)}function E(e,t){return w(e)?T(e.contractAddresses,t):!1}function D(e){return[...new Set(e.map(e=>(0,u.getAddress)(e)))].toSorted()}async function O(...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 ce=class{#e;constructor(e){this.#e=e}#t(e){s.o(e,`Session entry`),s.s(e.signature,`session.signature`),s.r(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),s.r(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}},le=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 ce(e.sessionStorage),this.crypto=new oe,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(E(a,r))return this.emit({type:t.r.CredentialsCached,contractAddresses:r}),this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),a;if(w(a))return this.#a({key:n,credentials:a,requiredContracts:r});this.emit({type:t.r.CredentialsExpired,contractAddresses:r})}if(w(e)){if(T(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.r)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:t.r.CredentialsCorrupted,error:s.u(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),!E(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),E(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.r)throw n;return t.A(n,a)}}async#a({key:e,credentials:n,requiredContracts:r}){if(this.#r){let e=await this.#r;if(T(e.contractAddresses,r))return this.emit({type:t.r.CredentialsAllowed,contractAddresses:r}),e;n=e}else if(this.#i){let e=this.#i;if(T(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=D([...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:s.u(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:s.u(e)})}}};function ue(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 de=class e extends le{#e;#t=null;#n=null;static async computeStoreKey(e,t){return O((0,u.getAddress)(e),t)}constructor(e){super(e),this.#e=e.relayer,ue(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&e.sessionStorage instanceof o.i&&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=D(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 revokeFor(t){await this.revokeSession(await e.computeStoreKey(t.address,t.chainId))}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=D(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){C(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,u.getAddress)(t)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await e.computeStoreKey(t,n);return this.#n=r,this.#t=i,i}},fe=class e extends le{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return O((0,u.getAddress)(e),(0,u.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,u.getAddress)(e),r=D(t),i=await this.#i(n);return this.resolveCredentials({key:i,contracts:r,createKey:`${n}:${r.join(`,`)}`,createFn:()=>this.#r(n,r)})}async isExpired(e,t){return this.checkExpired(await this.#i((0,u.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,u.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,u.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,u.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){se(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(),i=`${(0,u.getAddress)(n)}:${(0,u.getAddress)(t)}:${r}`;if(this.#t&&this.#n===i)return this.#t;let a=await e.computeStoreKey(n,t,r);return this.#n=i,this.#t=a,a}async#a(e,t){let n=await this.#e.createDelegatedUserDecryptEIP712(e.publicKey,t,e.delegatorAddress,e.startTimestamp,e.durationDays);return this.signer.signTypedData(n)}};function k(e){return(0,u.keccak256)((0,u.toBytes)(e))}const A={ConfidentialTransfer:k(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:k(`Wrapped(address,uint256)`),UnwrapRequested:k(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:k(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:k(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:k(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:k(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:k(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function j(e){return(0,u.getAddress)(x(e.slice(-40)))}function pe(e){return BigInt(e)}function M(e){return e}function N(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function P(e,t){return(0,u.getAddress)(x(N(e,t).slice(-40)))}function F(e,t){return BigInt(`0x`+N(e,t))}function me(e,t){return BigInt(`0x`+N(e,t))!==0n}function I(e,t){return x(N(e,t))}function L(e){return e.topics[0]!==A.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:j(e.topics[1]),to:j(e.topics[2]),encryptedAmountHandle:M(e.topics[3])}}function R(e){return e.topics[0]!==A.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:j(e.topics[1]),amountIn:F(e.data,0)}}function z(e){return e.topics[0]===A.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:j(e.topics[1]),unwrapRequestId:M(e.topics[2]),encryptedAmount:I(e.data,0)}:e.topics[0]===A.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:j(e.topics[1]),encryptedAmount:I(e.data,0)}:null}function B(e){return e.topics[0]===A.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:j(e.topics[1]),unwrapRequestId:M(e.topics[2]),encryptedAmount:I(e.data,0),cleartextAmount:F(e.data,1)}:e.topics[0]===A.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:j(e.topics[1]),encryptedAmount:I(e.data,0),cleartextAmount:F(e.data,1)}:null}function he(e){let t=B(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function ge(e){if(e.topics[0]!==A.UnwrapFinalizedLegacy)return null;let t=B(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function V(e){return e.topics[0]!==A.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:pe(e.topics[1]),txId:pe(e.topics[2]),to:j(e.topics[3]),returnVal:me(e.data,0),refund:P(e.data,1),requestedAmount:I(e.data,2),burnAmount:I(e.data,3)}}function H(e){return L(e)??R(e)??z(e)??ge(e)??B(e)??V(e)}function _e(e){let t=[];for(let n of e){let e=H(n);e&&t.push(e)}return t}function U(e){for(let t of e){let e=z(t);if(e)return e}return null}function ve(e){for(let t of e){let e=R(t);if(e)return e}return null}const ye=[A.ConfidentialTransfer,A.Wrapped,A.UnwrapRequested,A.UnwrapRequestedLegacy,A.UnwrapFinalized,A.UnwrapFinalizedLegacy,A.UnwrappedStarted],W={DelegatedForUserDecryption:k(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:k(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function G(e){return e.topics[0]!==W.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:j(e.topics[1]),delegate:j(e.topics[2]),contractAddress:P(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2),newExpirationDate:F(e.data,3)}}function K(e){return e.topics[0]!==W.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:j(e.topics[1]),delegate:j(e.topics[2]),contractAddress:P(e.data,0),delegationCounter:F(e.data,1),oldExpirationDate:F(e.data,2)}}function be(e){return G(e)??K(e)}function xe(e){let t=[];for(let n of e){let e=be(n);e&&t.push(e)}return t}function Se(e){for(let t of e){let e=G(t);if(e)return e}return null}function Ce(e){for(let t of e){let e=K(t);if(e)return e}return null}const we=[W.DelegatedForUserDecryption,W.RevokedDelegationForUserDecryption];var Te=class r extends t.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,u.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(l.g(this.wrapper)).then(e=>(this.#e=e,this.#t=null,e)).catch(e=>{throw this.#t=null,e}),this.#t):this.#e}async confidentialTransfer(r,i,a){let o=this.sdk.requireSigner(`confidentialTransfer`);await this.sdk.requireChainAlignment(`confidentialTransfer`);let{skipBalanceCheck:c=!1,onEncryptComplete:d,onTransferSubmitted:p}=a??{},m=(0,u.getAddress)(r);c||await this.#i(i);let{handles:h,inputProof:g}=await this.sdk.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await o.getAddress()});if(q(()=>d?.()),h.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await o.writeContract(l.b(this.address,m,h[0],g));return this.emit({type:t.r.TransferSubmitted,txHash:e}),q(()=>p?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transfer`,error:s.u(n)}),n instanceof e.r?n:new f(`Transfer transaction failed`,{cause:n})}}async confidentialTransferFrom(r,i,a,o){let c=this.sdk.requireSigner(`confidentialTransferFrom`);await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let d=(0,u.getAddress)(r),p=(0,u.getAddress)(i),{handles:m,inputProof:h}=await this.sdk.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:d});if(q(()=>o?.onEncryptComplete?.()),m.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await c.writeContract(l.x(this.address,d,p,m[0],h));return this.emit({type:t.r.TransferFromSubmitted,txHash:e}),q(()=>o?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`transferFrom`,error:s.u(n)}),n instanceof e.r?n:new f(`TransferFrom transaction failed`,{cause:n})}}async setOperator(n,r){let i=this.sdk.requireSigner(`setOperator`);await this.sdk.requireChainAlignment(`setOperator`);let a=(0,u.getAddress)(n);try{let e=await i.writeContract(l.w(this.address,a,r));return this.emit({type:t.r.SetOperatorSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`setOperator`,error:s.u(n)}),n instanceof e.r?n:new d(`Operator approval failed`,{cause:n})}}async isOperator(e,t){return this.sdk.provider.readContract(l.S(this.address,(0,u.getAddress)(e),(0,u.getAddress)(t)))}async shield(n,r){let i=this.sdk.requireSigner(`shield`);await this.sdk.requireChainAlignment(`shield`);let a=await this.#n(),o;try{let e=await i.getAddress();o=await this.sdk.provider.readContract(t.d(a,e))}catch(t){throw t instanceof e.r?t:new _(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:s.u(t)})}if(o<n)throw new te(`Insufficient ERC-20 balance: requested ${n}, available ${o} (token: ${a})`,{requested:n,available:o,token:a});let c=r?.approvalStrategy??`exact`;c!==`skip`&&await this.#o(n,c===`max`,r);try{let e=r?.to?(0,u.getAddress)(r.to):await i.getAddress(),a=await i.writeContract(l._(this.wrapper,e,n));return this.emit({type:t.r.ShieldSubmitted,txHash:a}),q(()=>r?.onShieldSubmitted?.(a)),{txHash:a,receipt:await this.sdk.provider.waitForTransactionReceipt(a)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`shield`,error:s.u(n)}),n instanceof e.r?n:new f(`Shield transaction failed`,{cause:n})}}async unwrap(r){let i=this.sdk.requireSigner(`unwrap`);await this.sdk.requireChainAlignment(`unwrap`);let a=await i.getAddress(),{handles:o,inputProof:c}=await this.sdk.encrypt({values:[{value:r,type:`euint64`}],contractAddress:this.wrapper,userAddress:a});if(o.length===0)throw new n.n(`Encryption returned no handles`);try{let e=await i.writeContract(l.E(this.address,a,a,o[0],c));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`Unshield transaction failed`,{cause:n})}}async unwrapAll(){let r=this.sdk.requireSigner(`unwrapAll`);await this.sdk.requireChainAlignment(`unwrapAll`);let i=await r.getAddress(),a=await this.readConfidentialBalanceOf(i);if(t._(a))throw new n.t(`Cannot unshield: balance is zero`);try{let e=await r.writeContract(l.D(this.address,i,i,a));return this.emit({type:t.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`unwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`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 q(()=>r?.(c.txHash)),this.#a(c.txHash,s,o)}async unshieldAll(e){let t=crypto.randomUUID(),n=await this.unwrapAll();return q(()=>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 r=this.sdk.requireSigner(`finalizeUnwrap`);await this.sdk.requireChainAlignment(`finalizeUnwrap`);let i=await this.sdk.publicDecrypt([n]),a=i.clearValues[n];s.n(a,`finalizeUnwrap: clearValue`);try{let e=await r.writeContract(l.m(this.wrapper,n,a,i.decryptionProof));return this.emit({type:t.r.FinalizeUnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`finalizeUnwrap`,error:s.u(n)}),n instanceof e.r?n:new f(`Failed to finalize unshield`,{cause:n})}}async approveUnderlying(n){let r=this.sdk.requireSigner(`approveUnderlying`);await this.sdk.requireChainAlignment(`approveUnderlying`);let i=await this.#n(),a=n??2n**256n-1n;try{if(a>0n){let e=await r.getAddress();await this.sdk.provider.readContract(t.l(i,e,this.wrapper))>0n&&await r.writeContract(t.u(i,this.wrapper,0n))}let e=await r.writeContract(t.u(i,this.wrapper,a));return this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`approveUnderlying`,error:s.u(n)}),n instanceof e.r?n:new d(`ERC-20 approval failed`,{cause:n})}}async delegateDecryption({delegateAddress:n,expirationDate:r}){let i=this.sdk.requireSigner(`delegateDecryption`);if(await this.sdk.requireChainAlignment(`delegateDecryption`),r&&r.getTime()<Date.now()+36e5)throw new t.S(`Expiration date must be at least 1 hour in the future`);let a=(0,u.getAddress)(n),o=await i.getAddress();if(a===(0,u.getAddress)(o))throw new t.D(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new t.x(`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,d;try{d=await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:a})}catch{d=-1n}if(d===l)throw new t.w(`The new expiration date (${l}) is the same as the current one. No on-chain change needed.`);try{let e=await i.writeContract(t.a(c,a,this.address,l));return this.emit({type:t.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`delegateDecryption`,error:s.u(n)}),n instanceof e.r?n:y(n)||new f(`Delegation transaction failed`,{cause:n})}}async revokeDelegation({delegateAddress:n}){let r=this.sdk.requireSigner(`revokeDelegation`);await this.sdk.requireChainAlignment(`revokeDelegation`);let i=(0,u.getAddress)(n),a=await r.getAddress(),o=await this.getAclAddress(),c;try{c=await this.getDelegationExpiry({delegatorAddress:a,delegateAddress:i})}catch{c=1n}if(c===0n)throw new t.T(`No active delegation found for delegate ${i} on contract ${this.address}.`);try{let e=await r.writeContract(t.c(o,i,this.address));return this.emit({type:t.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(n){throw this.emit({type:t.r.TransactionError,operation:`revokeDelegation`,error:s.u(n)}),n instanceof e.r?n:y(n)||new f(`Revoke delegation transaction failed`,{cause:n})}}static async batchDelegateDecryption({tokens:e,delegateAddress:t,expirationDate:n}){return r.#r(e,e=>e.delegateDecryption({delegateAddress:t,expirationDate:n}),`Delegation failed`)}static async batchRevokeDelegation({tokens:e,delegateAddress:t}){return r.#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.r?i.set(t[a].address,n):i.set(t[a].address,new f(r,{cause:n}))}return i}async#i(t){if(t===0n)return;let n;try{let e=this.sdk.requireSigner(`assertConfidentialBalance`);n=await this.balanceOf(await e.getAddress())}catch(t){throw t instanceof e.r?t:new ne(`Balance validation failed (token: ${this.address})`,{cause:t})}if(n<t)throw new ee(`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.provider.waitForTransactionReceipt(n)}catch(t){throw t instanceof e.r?t:new f(`Failed to get unshield receipt`,{cause:t})}let o=U(a.logs);if(!o)throw new f(`No UnwrapRequested event found in unshield receipt`);this.emit({type:t.r.UnshieldPhase2Started,operationId:r}),q(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:t.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),q(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#o(n,r,i){let a=this.sdk.requireSigner(`approveUnderlying`),o=await this.#n(),s=await a.getAddress(),c=await this.sdk.provider.readContract(t.l(o,s,this.wrapper));if(!(c>=n))try{if(c>0n){let e=await a.writeContract(t.u(o,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let e=r?2n**256n-1n:n,s=await a.writeContract(t.u(o,this.wrapper,e));this.emit({type:t.r.ApproveUnderlyingSubmitted,txHash:s}),q(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(t){throw t instanceof e.r?t:new d(`ERC-20 approval failed`,{cause:t})}}};function q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Ee={[c.a.id]:c.a.registryAddress,[c.o.id]:c.o.registryAddress,[c.i.id]:c.i.registryAddress},J=300*1e3;var Y=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},Ee,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.provider.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,u.getAddress)(n)}async listPairs(t={}){let n=t.page??1,r=t.pageSize??100,i=t.metadata??!1;if(n<1)throw new e.t(`page must be >= 1, got ${n}`);if(r<1)throw new e.t(`pageSize must be >= 1, got ${r}`);let a=await this.getRegistryAddress(),o=`total:${a}`,s=this.#r(o);if(s===void 0){let e=await this.provider.readContract(l.a(a));s=this.#i(o,Number(e))}let c=BigInt((n-1)*r),u=c+BigInt(r)>BigInt(s)?BigInt(s):c+BigInt(r);if(c>=BigInt(s))return{items:[],total:s,page:n,pageSize:r};let d=`slice:${a}:${c}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(l.o(a,c,u));f=this.#i(d,[...e])}if(!i)return{items:f,total:s,page:n,pageSize:r};let p=`metadata:${a}:${c}:${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?J:void 0)}return{items:m,total:s,page:n,pageSize:r}}async#a(e){let[n,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(t.m(e.tokenAddress)),this.provider.readContract(t.h(e.tokenAddress)),this.provider.readContract(t.f(e.tokenAddress)),this.provider.readContract(t.p(e.tokenAddress)),this.provider.readContract(t.m(e.confidentialTokenAddress)),this.provider.readContract(t.h(e.confidentialTokenAddress)),this.provider.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,u.getAddress)(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.t(t,n));return o===u.zeroAddress?this.#i(r,null,J):this.#i(r,{confidentialTokenAddress:o,isValid:a})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,u.getAddress)(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[a,o]=await this.provider.readContract(l.n(t,n));return o===u.zeroAddress?this.#i(r,null,J):this.#i(r,{tokenAddress:o,isValid:a})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(l.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(l.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(l.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.t(t,(0,u.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.n(t,(0,u.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(l.s(t,(0,u.getAddress)(e)))}};const X=365*86400;async function Z(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var De=class{relayer;provider;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n=new Set;#r;constructor(e){this.relayer=e.relayer,this.provider=e.provider,this.signer=e.signer,this.storage=e.storage,this.sessionStorage=e.sessionStorage??new o.i,this.cache=new S(e.storage),this.#t=e.onEvent??function(){};let t={};for(let n of e.chains??[])n.registryAddress&&(t[n.id]=n.registryAddress);Object.assign(t,e.registryAddresses),this.registry=new Y({provider:this.provider,registryTTL:e.registryTTL,registryAddresses:t}),this.#e=e.registryTTL;let n=(()=>{let t=e.keypairTTL??2592e3;if(t<=0||isNaN(t))throw Error(`keypairTTL must be a positive number (seconds)`);return t>X?(console.warn(`[zama-sdk] keypairTTL (${t}s) exceeds the fhevm maximum of 365 days (${X}s); capping to ${X}s.`),X):t})();if(e.signer){let t={relayer:this.relayer,signer:e.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:n,sessionTTL:e.sessionTTL??2592e3,onEvent:this.#t};this.credentials=new de(t),this.delegatedCredentials=new fe(t),this.#r=e.signer.subscribe?.(e=>{this.#i(e)})}else this.credentials=void 0,this.delegatedCredentials=void 0}requireSigner(e){if(!this.signer)throw new r.t(e);return this.signer}requireCredentials(e){if(!this.credentials)throw new r.t(e);return this.credentials}requireDelegatedCredentials(e){if(!this.delegatedCredentials)throw new r.t(e);return this.delegatedCredentials}onIdentityChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireChainAlignment(e){let t=this.requireSigner(e),[n,r]=await Promise.all([t.getChainId(),this.provider.getChainId()]);if(n!==r)throw new g({operation:e,signerChainId:n,providerChainId:r});return n}async#i(e){let t=this.credentials;if(e.previous&&t){let n=e.previous;await Z(`revoke previous identity`,()=>t.revokeFor(n)),await Z(`clear decrypt cache`,()=>this.cache.clearForRequester(n.address))}let n=e.next?.chainId;if(n!==void 0)try{this.relayer.switchChain(n)}catch(e){console.warn(`[zama-sdk] switch relayer chain failed:`,e);return}await Promise.all(Array.from(this.#n,t=>Z(`identity listener`,()=>t(e))))}createReadonlyToken(e){return new t.t(this,e)}createToken(e,t){return new Te(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 Y({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.requireCredentials(`allow`).allow(...e)}async userDecrypt(e){let n=this.requireSigner(`userDecrypt`),r=this.requireCredentials(`userDecrypt`);if(await this.requireChainAlignment(`userDecrypt`),e.length===0)return{};let i=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),a={},o=[];for(let e of i)t._(e.handle)?a[e.handle]=0n:o.push(e);if(o.length===0)return a;let c=await n.getAddress(),l=[];for(let e of o){let t=await this.cache.get(c,e.contractAddress,e.handle);t===null?l.push(e):a[e.handle]=t}if(l.length===0)return a;let d=await r.allow(...new Set(i.map(e=>e.contractAddress))),f=new Map;for(let e of l){let t=f.get(e.contractAddress);t?t.push(e.handle):f.set(e.contractAddress,[e.handle])}let p=Date.now(),m=l.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:m}),await t.n([...f.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:d.contractAddresses,privateKey:d.privateKey,publicKey:d.publicKey,signature:d.signature,signerAddress:c,startTimestamp:d.startTimestamp,durationDays:d.durationDays});for(let[t,r]of Object.entries(n))a[t]=r,await this.cache.set(c,e,t,r)}),5);let e={};for(let t of m){let n=a[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-p,handles:m,result:e}),a}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:s.u(e),durationMs:Date.now()-p,handles:m}),b(e,`Failed to decrypt handles`)}}async delegatedUserDecrypt(e,n,r=n){this.requireSigner(`delegatedUserDecrypt`);let i=this.requireDelegatedCredentials(`delegatedUserDecrypt`);if(await this.requireChainAlignment(`delegatedUserDecrypt`),e.length===0)return{};let a=(0,u.getAddress)(n),o=(0,u.getAddress)(r),c=e.map(e=>({handle:e.handle,contractAddress:(0,u.getAddress)(e.contractAddress)})),l={},d=[];for(let e of c)t._(e.handle)?l[e.handle]=0n:d.push(e);if(d.length===0)return l;let f=[];for(let e of d){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?f.push(e):l[e.handle]=t}if(f.length===0)return l;let p=await i.allow(a,...new Set(c.map(e=>e.contractAddress))),m=new Map;for(let e of f){let t=m.get(e.contractAddress);t?t.push(e.handle):m.set(e.contractAddress,[e.handle])}let h=Date.now(),g=f.map(e=>e.handle);try{this.emitEvent({type:t.r.DecryptStart,handles:g}),await t.n([...m.entries()].map(([e,t])=>async()=>{let n=await this.relayer.delegatedUserDecrypt({handles:t,contractAddress:e,signedContractAddresses:p.contractAddresses,privateKey:p.privateKey,publicKey:p.publicKey,signature:p.signature,delegatorAddress:p.delegatorAddress,delegateAddress:p.delegateAddress,startTimestamp:p.startTimestamp,durationDays:p.durationDays});for(let[t,r]of Object.entries(n))l[t]=r,await this.cache.set(o,e,t,r)}),5);let e={};for(let t of g){let n=l[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:t.r.DecryptEnd,durationMs:Date.now()-h,handles:g,result:e}),l}catch(e){throw this.emitEvent({type:t.r.DecryptError,error:s.u(e),durationMs:Date.now()-h,handles:g}),b(e,`Failed to decrypt delegated handles`,!0)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw b(e,`Public decryption failed`)}}async encrypt(r){let i=Date.now();try{this.emitEvent({type:t.r.EncryptStart},r.contractAddress);let e=await this.relayer.encrypt(r);return this.emitEvent({type:t.r.EncryptEnd,durationMs:Date.now()-i},r.contractAddress),e}catch(a){throw this.emitEvent({type:t.r.EncryptError,error:s.u(a),durationMs:Date.now()-i},r.contractAddress),a instanceof e.r?a:new n.n(`Encryption failed`,{cause:a})}}async revokeSession(){let e=this.requireSigner(`revokeSession`),t=this.requireCredentials(`revokeSession`),n=await e.getAddress(),r=await e.getChainId();try{await t.revokeFor({address:n,chainId:r})}finally{await this.cache.clearForRequester(n)}}dispose(){this.#r?.(),this.#r=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function Q(e){return`zama:pending-unshield:${e}`}function Oe(e){return e===null?null:typeof e==`string`?{unwrapTxHash:e}:typeof e==`object`&&`unwrapTxHash`in e?{unwrapTxHash:e.unwrapTxHash,unwrapRequestId:e.unwrapRequestId}:null}async function ke(e,t,n,r){if(r===void 0){await e.set(Q(t),n);return}await e.set(Q(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ae(e,t){return(await je(e,t))?.unwrapTxHash??null}async function je(e,t){return Oe(await e.get(Q(t)))}async function Me(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 Ne=new $;exports.ACL_TOPICS=we,exports.AclPausedError=t.v,exports.AclTopics=W,exports.ApprovalFailedError=d,exports.BalanceCheckUnavailableError=ne,exports.ChainMismatchError=g,exports.ChromeSessionStorage=$,exports.ConfigurationError=e.t,exports.CredentialsManager=de,exports.DecryptCache=S,exports.DecryptionFailedError=n.t,exports.DefaultRegistryAddresses=Ee,exports.DelegatedCredentialsManager=fe,exports.DelegationContractIsSelfError=t.y,exports.DelegationCooldownError=t.b,exports.DelegationDelegateEqualsContractError=t.x,exports.DelegationExpirationTooSoonError=t.S,exports.DelegationExpiredError=t.C,exports.DelegationExpiryUnchangedError=t.w,exports.DelegationNotFoundError=t.T,exports.DelegationNotPropagatedError=t.E,exports.DelegationSelfNotAllowedError=t.D,exports.ERC20ReadFailedError=_,exports.ERC7984_INTERFACE_ID=l.c,exports.ERC7984_WRAPPER_INTERFACE_ID=l.l,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=l.u,exports.EncryptionFailedError=n.n,exports.IndexedDBStorage=a.t,exports.InsufficientConfidentialBalanceError=ee,exports.InsufficientERC20BalanceError=te,exports.InvalidKeypairError=m,exports.KeypairExpiredError=p,exports.MemoryStorage=o.i,exports.NoCiphertextError=h,exports.ReadonlyToken=t.t,exports.RelayerRequestFailedError=e.n,exports.SignerRequiredError=r.t,exports.SigningFailedError=t.O,exports.SigningRejectedError=t.k,exports.TOKEN_TOPICS=ye,exports.Token=Te,exports.Topics=A,exports.TransactionRevertedError=f,exports.WrappersRegistry=Y,exports.ZERO_HANDLE=t.g,exports.ZamaError=e.r,exports.ZamaErrorCode=e.i,exports.ZamaSDK=De,exports.ZamaSDKEvents=t.r,exports.allowanceContract=t.l,exports.anvil=c.t,exports.approveContract=t.u,exports.balanceOfContract=t.d,exports.buildZamaConfig=o.t,exports.chains=c.n,exports.chromeSessionStorage=Ne,exports.clearPendingUnshield=Me,exports.cleartext=ie,exports.confidentialBalanceOfContract=l.v,exports.confidentialTotalSupplyContract=l.y,exports.confidentialTransferContract=l.b,exports.confidentialTransferFromContract=l.x,exports.createConfig=ae,exports.decimalsContract=t.f,exports.decodeAclEvent=be,exports.decodeAclEvents=xe,exports.decodeConfidentialTransfer=L,exports.decodeDelegatedForUserDecryption=G,exports.decodeOnChainEvent=H,exports.decodeOnChainEvents=_e,exports.decodeRevokedDelegationForUserDecryption=K,exports.decodeUnwrapFinalized=B,exports.decodeUnwrapRequested=z,exports.decodeUnwrappedFinalized=he,exports.decodeUnwrappedStarted=V,exports.decodeWrapped=R,exports.delegateForUserDecryptionContract=t.a,exports.finalizeUnwrapContract=l.m,exports.findDelegatedForUserDecryption=Se,exports.findRevokedDelegationForUserDecryption=Ce,exports.findUnwrapRequested=U,exports.findWrapped=ve,exports.getConfidentialTokenAddressContract=l.t,exports.getDelegationExpiryContract=t.o,exports.getTokenAddressContract=l.n,exports.getTokenPairContract=l.r,exports.getTokenPairsContract=l.i,exports.getTokenPairsLengthContract=l.a,exports.getTokenPairsSliceContract=l.o,exports.hardhat=c.r,exports.hoodi=c.i,exports.indexedDBStorage=a.n,exports.inferredTotalSupplyContract=l.h,exports.isConfidentialTokenContract=l.d,exports.isConfidentialTokenValidContract=l.s,exports.isConfidentialWrapperContract=l.f,exports.isHandleDelegatedContract=t.s,exports.isOperatorContract=l.S,exports.isZeroHandle=t._,exports.loadPendingUnshield=Ae,exports.loadPendingUnshieldRequest=je,exports.mainnet=c.a,exports.matchAclRevert=y,exports.matchZamaError=e.a,exports.memoryStorage=o.a,exports.nameContract=t.m,exports.rateContract=l.C,exports.resolveChainRelayers=o.n,exports.resolveStorage=o.r,exports.revokeDelegationContract=t.c,exports.savePendingUnshield=ke,exports.sepolia=c.o,exports.setOperatorContract=l.w,exports.supportsInterfaceContract=l.p,exports.symbolContract=t.h,exports.totalSupplyContract=l.T,exports.underlyingContract=l.g,exports.unwrapContract=l.E,exports.unwrapFromBalanceContract=l.D,exports.wrapContract=l._;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|