@zama-fhe/sdk 3.0.0-alpha.20 → 3.0.0-alpha.22
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/build.cjs.map +1 -1
- package/dist/cjs/ethers/index.cjs.map +1 -1
- package/dist/cjs/index.cjs +2 -2
- 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/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/signer.cjs +2 -0
- package/dist/cjs/signer.cjs.map +1 -0
- package/dist/cjs/viem/index.cjs +1 -1
- package/dist/cjs/viem/index.cjs.map +1 -1
- package/dist/esm/{assertions-CfqI3AJv.js → assertions-C4d1oXDT.js} +1 -1
- package/dist/esm/{assertions-CfqI3AJv.js.map → assertions-C4d1oXDT.js.map} +1 -1
- package/dist/esm/{build-CvenCk6R.js → build-CI_bIF0v.js} +2 -2
- package/dist/esm/{build-CvenCk6R.js.map → build-CI_bIF0v.js.map} +1 -1
- package/dist/esm/chains/index.d.ts +2 -2
- package/dist/esm/chains/index.js +1 -1
- package/dist/esm/{chains-aHmrozPh.js → chains-CfhF8qk4.js} +1 -1
- package/dist/esm/{chains-aHmrozPh.js.map → chains-CfhF8qk4.js.map} +1 -1
- package/dist/esm/cleartext/index.d.ts +1 -1
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-I-etE_7S.js → cleartext-Bmwva0e0.js} +2 -2
- package/dist/esm/{cleartext-I-etE_7S.js.map → cleartext-Bmwva0e0.js.map} +1 -1
- package/dist/esm/{cleartext-BHu6-LCv.d.ts → cleartext-C1ohdTq4.d.ts} +2 -2
- package/dist/esm/{eip1193-subscribe-CcotSOIm.js → eip1193-subscribe-VpDDm5YQ.js} +1 -1
- package/dist/esm/{eip1193-subscribe-CcotSOIm.js.map → eip1193-subscribe-VpDDm5YQ.js.map} +1 -1
- package/dist/esm/{encryption-YS-Kb7qm.js → encryption-DAiaujC2.js} +2 -2
- package/dist/esm/{encryption-YS-Kb7qm.js.map → encryption-DAiaujC2.js.map} +1 -1
- package/dist/esm/{error-B6H-mBAh.js → error-DYq5VALn.js} +1 -1
- package/dist/esm/{error-B6H-mBAh.js.map → error-DYq5VALn.js.map} +1 -1
- package/dist/esm/ethers/index.d.ts +6 -7
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/ethers/index.js.map +1 -1
- package/dist/esm/{hex-BZVTzEK6.js → hex-gS4TMmUz.js} +2 -2
- package/dist/esm/{hex-BZVTzEK6.js.map → hex-gS4TMmUz.js.map} +1 -1
- package/dist/esm/{index-BTY0MxOt.d.ts → index-CKOcIi_A.d.ts} +2 -2
- package/dist/esm/{index-BdyljG1F.d.ts → index-OsF7gu_e.d.ts} +74 -27
- package/dist/esm/index.d.ts +10 -10
- package/dist/esm/index.js +2 -2
- package/dist/esm/index.js.map +1 -1
- package/dist/esm/{memory-storage-CFXqXUcm.js → memory-storage-BAFvlQMK.js} +1 -1
- package/dist/esm/{memory-storage-CFXqXUcm.js.map → memory-storage-BAFvlQMK.js.map} +1 -1
- package/dist/esm/node/index.d.ts +5 -5
- package/dist/esm/node/index.js +1 -1
- package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
- package/dist/esm/query/index.d.ts +9 -8
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/{readonly-token-DCLOYhws.js → readonly-token-Crqifvf_.js} +2 -2
- package/dist/esm/{readonly-token-DCLOYhws.js.map → readonly-token-Crqifvf_.js.map} +1 -1
- package/dist/esm/{relayer-7Hd00A6X.js → relayer-BWfMI7_m.js} +2 -2
- package/dist/esm/{relayer-7Hd00A6X.js.map → relayer-BWfMI7_m.js.map} +1 -1
- package/dist/esm/{relayer-cleartext-SZCM9wTx.js → relayer-cleartext-Bu3Ktt89.js} +2 -2
- package/dist/esm/{relayer-cleartext-SZCM9wTx.js.map → relayer-cleartext-Bu3Ktt89.js.map} +1 -1
- package/dist/esm/{relayer-cleartext-DJkSUlZ2.d.ts → relayer-cleartext-C6p281Q8.d.ts} +2 -2
- package/dist/esm/signer-C5D58_y1.js +2 -0
- package/dist/esm/signer-C5D58_y1.js.map +1 -0
- package/dist/esm/{types-FY7ciI37.d.ts → types-Bi2bEDi7.d.ts} +10 -5
- package/dist/esm/{types-C1S426x4.d.ts → types-C0NhSVkP.d.ts} +1 -1
- package/dist/esm/{types-CVyJHEya.d.ts → types-CeOUxM9p.d.ts} +3 -3
- package/dist/esm/{types-DePjTTbo.d.ts → types-DReZxq0j.d.ts} +3 -3
- package/dist/esm/viem/index.d.ts +6 -8
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/viem/index.js.map +1 -1
- package/dist/esm/{wrappers-registry-CXNs4eR0.js → wrappers-registry-CJn1d5py.js} +1 -1
- package/dist/esm/{wrappers-registry-CXNs4eR0.js.map → wrappers-registry-CJn1d5py.js.map} +1 -1
- package/package.json +1 -1
package/dist/cjs/build.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"build.cjs","names":["#dbName","#dbVersion","#storeName","#db","#dbPromise","#withTransaction","#getDB","#map","ConfigurationError","#chains","#relayers","#workers","ConfigurationError","#chainId","#active","toError"],"sources":["../../src/storage/indexeddb-storage.ts","../../src/storage/memory-storage.ts","../../src/config/resolve.ts","../../src/relayer/relayer-dispatcher.ts","../../src/config/build.ts"],"sourcesContent":["\"use client\";\n\nimport type { GenericStorage } from \"../types\";\n\n/**\n * IndexedDB-backed {@link GenericStorage}.\n *\n * Stores encrypted credential objects keyed by a hashed wallet address.\n * Encryption is handled by {@link CredentialsManager} — this store only\n * persists opaque values.\n */\nexport class IndexedDBStorage implements GenericStorage {\n #db: IDBDatabase | null = null;\n #dbPromise: Promise<IDBDatabase> | null = null;\n #dbName: string;\n #dbVersion: number;\n #storeName: string;\n\n constructor(dbName = \"CredentialStore\", dbVersion = 1, storeName = \"credentials\") {\n this.#dbName = dbName;\n this.#dbVersion = dbVersion;\n this.#storeName = storeName;\n }\n\n #getDB(): Promise<IDBDatabase> {\n if (this.#db) {\n return Promise.resolve(this.#db);\n }\n if (this.#dbPromise) {\n return this.#dbPromise;\n }\n\n this.#dbPromise = new Promise((resolve, reject) => {\n const request = indexedDB.open(this.#dbName, this.#dbVersion);\n\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(this.#storeName)) {\n db.createObjectStore(this.#storeName, { keyPath: \"key\" });\n }\n };\n\n request.onsuccess = () => {\n this.#db = request.result;\n this.#dbPromise = null;\n this.#db.onversionchange = () => {\n // oxlint-disable-next-line no-console\n console.warn(\n `IndexedDB \"${this.#dbName}\" closing due to version change from another tab`,\n );\n this.#db?.close();\n this.#db = null;\n this.#dbPromise = null;\n };\n this.#db.onclose = () => {\n this.#db = null;\n this.#dbPromise = null;\n };\n resolve(this.#db);\n };\n\n request.onerror = () => {\n this.#db = null;\n this.#dbPromise = null;\n reject(request.error);\n };\n });\n\n return this.#dbPromise;\n }\n\n async #withTransaction<T>(\n mode: IDBTransactionMode,\n fn: (store: IDBObjectStore) => IDBRequest,\n ): Promise<T> {\n const db = await this.#getDB();\n return new Promise((resolve, reject) => {\n const tx = db.transaction(this.#storeName, mode);\n tx.onabort = () => reject(tx.error ?? new Error(\"Transaction aborted\"));\n const request = fn(tx.objectStore(this.#storeName));\n if (mode === \"readonly\") {\n request.onsuccess = () => resolve(request.result);\n } else {\n tx.oncomplete = () => resolve(request.result);\n }\n request.onerror = () => reject(request.error);\n });\n }\n\n async get<T = unknown>(key: string): Promise<T | null> {\n const result = await this.#withTransaction<{ value: T } | undefined>(\"readonly\", (store) =>\n store.get(key),\n );\n return result?.value ?? null;\n }\n\n async set<T = unknown>(key: string, value: T): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.put({ key, value }));\n }\n\n async delete(key: string): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.delete(key));\n }\n\n async clear(): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.clear());\n }\n}\n\n/** Default singleton for application-wide use. */\nexport const indexedDBStorage = new IndexedDBStorage();\n","import type { GenericStorage } from \"../types\";\n\n/** In-memory credential store. Credentials are lost on page reload. */\nexport class MemoryStorage implements GenericStorage {\n #map = new Map<string, unknown>();\n\n async get<T = unknown>(key: string): Promise<T | null> {\n return (this.#map.get(key) as T) ?? null;\n }\n\n async set<T = unknown>(key: string, value: T): Promise<void> {\n this.#map.set(key, value);\n }\n\n async delete(key: string): Promise<void> {\n this.#map.delete(key);\n }\n}\n\n/** Default singleton for application-wide use. */\nexport const memoryStorage = new MemoryStorage();\n","import type { FheChain } from \"../chains\";\nimport { ConfigurationError } from \"../errors\";\nimport { IndexedDBStorage } from \"../storage/indexeddb-storage\";\nimport { MemoryStorage } from \"../storage/memory-storage\";\nimport type { GenericStorage } from \"../types\";\nimport type { RelayerConfig } from \"./types\";\n\n// ── Storage defaults ─────────────────────────────────────────────────────────\n\nfunction getDefaultStorage(): GenericStorage {\n return typeof window !== \"undefined\"\n ? new IndexedDBStorage(\"CredentialStore\")\n : new MemoryStorage();\n}\n\nfunction getDefaultSessionStorage(): GenericStorage {\n return typeof window !== \"undefined\" ? new IndexedDBStorage(\"SessionStore\") : new MemoryStorage();\n}\n\nexport function resolveStorage(\n storage: GenericStorage | undefined = getDefaultStorage(),\n sessionStorage: GenericStorage | undefined = getDefaultSessionStorage(),\n): { storage: GenericStorage; sessionStorage: GenericStorage } {\n return { storage, sessionStorage };\n}\n\n// ── Chain relayer resolution ────────────────────────────────────────────────\n\nexport interface ResolvedChainRelayer {\n chain: FheChain;\n relayer: RelayerConfig;\n}\n\nexport function resolveChainRelayers(\n chains: readonly FheChain[],\n relayers: Readonly<Record<number, RelayerConfig>>,\n): Map<number, ResolvedChainRelayer> {\n const chainMap = new Map(chains.map((c) => [c.id, c]));\n if (chainMap.size !== chains.length) {\n const ids = chains.map((c) => c.id);\n const dupes = [...new Set(ids.filter((id, i) => ids.indexOf(id) !== i))];\n throw new ConfigurationError(\n `Duplicate chain id(s) [${dupes.join(\", \")}] in the chains array. ` +\n `Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`,\n );\n }\n const relayerMap = new Map(Object.entries(relayers));\n const result = new Map<number, ResolvedChainRelayer>();\n\n for (const id of chainMap.keys()) {\n const chainConfig = chainMap.get(id);\n const relayerConfig = relayerMap.get(String(id));\n\n if (!relayerConfig) {\n throw new ConfigurationError(\n `Chain ${id} has no relayer configured. ` +\n `Add a relayer entry: relayers: { [${id}]: web() }`,\n );\n }\n\n if (!chainConfig) {\n throw new ConfigurationError(\n `Chain ${id} has a relayer configured but no entry in the chains array. ` +\n `Add the chain config to the chains array.`,\n );\n }\n\n result.set(id, {\n chain: chainConfig,\n relayer: relayerConfig,\n });\n }\n\n const relayerIdSet = new Set(Object.keys(relayers).map(Number));\n const orphaned = new Set([...relayerIdSet].filter((id) => !chainMap.has(id)));\n if (orphaned.size > 0) {\n throw new ConfigurationError(\n `Relayer entries for chain(s) [${[...orphaned].join(\", \")}] have no matching entry ` +\n `in the chains array. Remove them or add the corresponding chain config.`,\n );\n }\n\n return result;\n}\n","import type {\n InputProofBytesType,\n KeypairType,\n KmsDelegatedUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address, Hex } from \"viem\";\nimport type { FheChain } from \"../chains/types\";\nimport type { RelayerConfig } from \"../config/types\";\nimport { resolveChainRelayers } from \"../config/resolve\";\nimport { ConfigurationError } from \"../errors\";\nimport { assertNonNullable, toError } from \"../utils\";\nimport type { RelayerSDK } from \"./relayer-sdk\";\nimport type {\n ClearValueType,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n Handle,\n PublicDecryptResult,\n PublicKeyData,\n PublicParamsData,\n UserDecryptParams,\n} from \"./relayer-sdk.types\";\n\n/** Anything with a synchronous `terminate()` method (workers, pools). */\nexport interface WorkerLike {\n terminate(): void;\n}\n\n/**\n * Owns chain management (chains / activeChain / switchChain) and delegates\n * every {@link RelayerSDK} operation to the relayer for the currently active\n * chain.\n *\n * Groups chains by relayer config reference identity, calls `createWorker`\n * once per group with all chain configs, then calls `createRelayer`\n * per chain with the shared worker.\n *\n * Workers/pools are held separately from relayers so the dispatcher can\n * terminate them directly — relayers never own worker lifecycle.\n */\nexport class RelayerDispatcher implements RelayerSDK, Disposable {\n readonly #chains: Map<number, FheChain>;\n readonly #relayers: Map<number, RelayerSDK>;\n readonly #workers: readonly WorkerLike[];\n #chainId: number;\n\n constructor(\n chains: readonly [FheChain, ...FheChain[]],\n configs: Readonly<Record<number, RelayerConfig>>,\n ) {\n if (chains.length === 0) {\n throw new ConfigurationError(\"At least one chain is required.\");\n }\n this.#chains = new Map(chains.map((c) => [c.id, c]));\n this.#chainId = chains[0].id;\n\n const chainRelayers = resolveChainRelayers(chains, configs);\n\n // Group chains by relayer config reference — same object = same group = shared worker.\n const groups = new Map<RelayerConfig, Array<[number, FheChain]>>();\n for (const [chainId, config] of chainRelayers) {\n const key = config.relayer;\n let group = groups.get(key);\n if (!group) {\n group = [];\n groups.set(key, group);\n }\n group.push([chainId, config.chain]);\n }\n\n // For each group: create shared worker once, then create per-chain relayers.\n const relayers = new Map<number, RelayerSDK>();\n const workers: WorkerLike[] = [];\n try {\n for (const [relayerCfg, groupChains] of groups) {\n const allChainConfigs = groupChains.map(([, chain]) => chain);\n const worker = relayerCfg.createWorker?.(allChainConfigs);\n if (worker) {\n workers.push(worker);\n }\n for (const [chainId, chain] of groupChains) {\n relayers.set(chainId, relayerCfg.createRelayer(chain, worker));\n }\n }\n } catch (error) {\n for (const w of workers) {\n try {\n w.terminate();\n } catch {\n /* best-effort cleanup */\n }\n }\n throw error;\n }\n\n this.#relayers = relayers;\n this.#workers = workers;\n }\n\n get chains(): readonly FheChain[] {\n return [...this.#chains.values()];\n }\n\n get chain(): FheChain {\n const chain = this.#chains.get(this.#chainId);\n assertNonNullable(chain, \"RelayerDispatcher: chain\");\n return chain;\n }\n\n switchChain(chainId: number): void {\n if (!this.#chains.has(chainId)) {\n throw new ConfigurationError(\n `No relayer configured for chain ${chainId}. Add it to the chains array.`,\n );\n }\n this.#chainId = chainId;\n }\n\n get #active(): RelayerSDK {\n const relayer = this.#relayers.get(this.#chainId);\n assertNonNullable(relayer, \"RelayerDispatcher: relayer\");\n return relayer;\n }\n\n generateKeypair(): Promise<KeypairType<Hex>> {\n return this.#active.generateKeypair();\n }\n\n createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays?: number,\n ): Promise<EIP712TypedData> {\n return this.#active.createEIP712(publicKey, contractAddresses, startTimestamp, durationDays);\n }\n\n encrypt(params: EncryptParams): Promise<EncryptResult> {\n return this.#active.encrypt(params);\n }\n\n userDecrypt(params: UserDecryptParams): Promise<Readonly<Record<Handle, ClearValueType>>> {\n return this.#active.userDecrypt(params);\n }\n\n publicDecrypt(handles: Handle[]): Promise<PublicDecryptResult> {\n return this.#active.publicDecrypt(handles);\n }\n\n createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays?: number,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n return this.#active.createDelegatedUserDecryptEIP712(\n publicKey,\n contractAddresses,\n delegatorAddress,\n startTimestamp,\n durationDays,\n );\n }\n\n delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n return this.#active.delegatedUserDecrypt(params);\n }\n\n requestZKProofVerification(zkProof: ZKProofLike): Promise<InputProofBytesType> {\n return this.#active.requestZKProofVerification(zkProof);\n }\n\n getPublicKey(): Promise<PublicKeyData | null> {\n return this.#active.getPublicKey();\n }\n\n getPublicParams(bits: number): Promise<PublicParamsData | null> {\n return this.#active.getPublicParams(bits);\n }\n\n getAclAddress(): Promise<Address> {\n return this.#active.getAclAddress();\n }\n\n terminate(): void {\n const errors: Error[] = [];\n\n // Clean up relayer-owned caches (no worker termination).\n for (const r of new Set(this.#relayers.values())) {\n try {\n r.terminate();\n } catch (e) {\n errors.push(toError(e));\n }\n }\n\n // Terminate the actual workers/pools (deduplicated).\n for (const w of new Set(this.#workers)) {\n try {\n w.terminate();\n } catch (e) {\n errors.push(toError(e));\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Failed to terminate relayer resources\");\n }\n }\n\n [Symbol.dispose](): void {\n this.terminate();\n }\n}\n","import { RelayerDispatcher } from \"../relayer/relayer-dispatcher\";\nimport type { GenericProvider, GenericSigner } from \"../types\";\nimport { resolveStorage } from \"./resolve\";\nimport type { ZamaConfig, ZamaConfigBase } from \"./types\";\n\n/**\n * @internal Shared config builder — not part of the public API.\n */\nexport function buildZamaConfig(\n signer: GenericSigner,\n provider: GenericProvider,\n params: ZamaConfigBase,\n): ZamaConfig {\n const { storage, sessionStorage } = resolveStorage(params.storage, params.sessionStorage);\n\n const relayer = new RelayerDispatcher(params.chains, params.relayers);\n\n return {\n chains: params.chains,\n relayer,\n provider,\n signer,\n storage,\n sessionStorage,\n keypairTTL: params.keypairTTL,\n sessionTTL: params.sessionTTL,\n registryTTL: params.registryTTL,\n onEvent: params.onEvent,\n };\n}\n"],"mappings":"sEAWA,IAAa,EAAb,KAAwD,CACtD,GAA0B,KAC1B,GAA0C,KAC1C,GACA,GACA,GAEA,YAAY,EAAS,kBAAmB,EAAY,EAAG,EAAY,cAAe,CAChF,MAAA,EAAe,EACf,MAAA,EAAkB,EAClB,MAAA,EAAkB,EAGpB,IAA+B,CA4C7B,OA3CI,MAAA,EACK,QAAQ,QAAQ,MAAA,EAAS,EAE9B,AAIJ,MAAA,IAAkB,IAAI,SAAS,EAAS,IAAW,CACjD,IAAM,EAAU,UAAU,KAAK,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,gBAAgB,EAAgD,CAC9D,OAAO,MAAA,EAAa,gBAAgB,EAAK,CAG3C,eAAkC,CAChC,OAAO,MAAA,EAAa,eAAe,CAGrC,WAAkB,CAChB,IAAM,EAAkB,EAAE,CAG1B,IAAK,IAAM,KAAK,IAAI,IAAI,MAAA,EAAe,QAAQ,CAAC,CAC9C,GAAI,CACF,EAAE,WAAW,OACN,EAAG,CACV,EAAO,KAAKG,EAAAA,EAAQ,EAAE,CAAC,CAK3B,IAAK,IAAM,KAAK,IAAI,IAAI,MAAA,EAAc,CACpC,GAAI,CACF,EAAE,WAAW,OACN,EAAG,CACV,EAAO,KAAKA,EAAAA,EAAQ,EAAE,CAAC,CAI3B,GAAI,EAAO,OAAS,EAClB,MAAU,eAAe,EAAQ,wCAAwC,CAI7E,CAAC,OAAO,UAAiB,CACvB,KAAK,WAAW,GCjNpB,SAAgB,EACd,EACA,EACA,EACY,CACZ,GAAM,CAAE,UAAS,kBAAmB,EAAe,EAAO,QAAS,EAAO,eAAe,CAEnF,EAAU,IAAI,EAAkB,EAAO,OAAQ,EAAO,SAAS,CAErE,MAAO,CACL,OAAQ,EAAO,OACf,UACA,WACA,SACA,UACA,iBACA,WAAY,EAAO,WACnB,WAAY,EAAO,WACnB,YAAa,EAAO,YACpB,QAAS,EAAO,QACjB"}
|
|
1
|
+
{"version":3,"file":"build.cjs","names":["#dbName","#dbVersion","#storeName","#db","#dbPromise","#withTransaction","#getDB","#map","ConfigurationError","#chains","#relayers","#workers","ConfigurationError","#chainId","#active","toError"],"sources":["../../src/storage/indexeddb-storage.ts","../../src/storage/memory-storage.ts","../../src/config/resolve.ts","../../src/relayer/relayer-dispatcher.ts","../../src/config/build.ts"],"sourcesContent":["\"use client\";\n\nimport type { GenericStorage } from \"../types\";\n\n/**\n * IndexedDB-backed {@link GenericStorage}.\n *\n * Stores encrypted credential objects keyed by a hashed wallet address.\n * Encryption is handled by {@link CredentialsManager} — this store only\n * persists opaque values.\n */\nexport class IndexedDBStorage implements GenericStorage {\n #db: IDBDatabase | null = null;\n #dbPromise: Promise<IDBDatabase> | null = null;\n #dbName: string;\n #dbVersion: number;\n #storeName: string;\n\n constructor(dbName = \"CredentialStore\", dbVersion = 1, storeName = \"credentials\") {\n this.#dbName = dbName;\n this.#dbVersion = dbVersion;\n this.#storeName = storeName;\n }\n\n #getDB(): Promise<IDBDatabase> {\n if (this.#db) {\n return Promise.resolve(this.#db);\n }\n if (this.#dbPromise) {\n return this.#dbPromise;\n }\n\n this.#dbPromise = new Promise((resolve, reject) => {\n const request = indexedDB.open(this.#dbName, this.#dbVersion);\n\n request.onupgradeneeded = () => {\n const db = request.result;\n if (!db.objectStoreNames.contains(this.#storeName)) {\n db.createObjectStore(this.#storeName, { keyPath: \"key\" });\n }\n };\n\n request.onsuccess = () => {\n this.#db = request.result;\n this.#dbPromise = null;\n this.#db.onversionchange = () => {\n // oxlint-disable-next-line no-console\n console.warn(\n `IndexedDB \"${this.#dbName}\" closing due to version change from another tab`,\n );\n this.#db?.close();\n this.#db = null;\n this.#dbPromise = null;\n };\n this.#db.onclose = () => {\n this.#db = null;\n this.#dbPromise = null;\n };\n resolve(this.#db);\n };\n\n request.onerror = () => {\n this.#db = null;\n this.#dbPromise = null;\n reject(request.error);\n };\n });\n\n return this.#dbPromise;\n }\n\n async #withTransaction<T>(\n mode: IDBTransactionMode,\n fn: (store: IDBObjectStore) => IDBRequest,\n ): Promise<T> {\n const db = await this.#getDB();\n return new Promise((resolve, reject) => {\n const tx = db.transaction(this.#storeName, mode);\n tx.onabort = () => reject(tx.error ?? new Error(\"Transaction aborted\"));\n const request = fn(tx.objectStore(this.#storeName));\n if (mode === \"readonly\") {\n request.onsuccess = () => resolve(request.result);\n } else {\n tx.oncomplete = () => resolve(request.result);\n }\n request.onerror = () => reject(request.error);\n });\n }\n\n async get<T = unknown>(key: string): Promise<T | null> {\n const result = await this.#withTransaction<{ value: T } | undefined>(\"readonly\", (store) =>\n store.get(key),\n );\n return result?.value ?? null;\n }\n\n async set<T = unknown>(key: string, value: T): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.put({ key, value }));\n }\n\n async delete(key: string): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.delete(key));\n }\n\n async clear(): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.clear());\n }\n}\n\n/** Default singleton for application-wide use. */\nexport const indexedDBStorage = new IndexedDBStorage();\n","import type { GenericStorage } from \"../types\";\n\n/** In-memory credential store. Credentials are lost on page reload. */\nexport class MemoryStorage implements GenericStorage {\n #map = new Map<string, unknown>();\n\n async get<T = unknown>(key: string): Promise<T | null> {\n return (this.#map.get(key) as T) ?? null;\n }\n\n async set<T = unknown>(key: string, value: T): Promise<void> {\n this.#map.set(key, value);\n }\n\n async delete(key: string): Promise<void> {\n this.#map.delete(key);\n }\n}\n\n/** Default singleton for application-wide use. */\nexport const memoryStorage = new MemoryStorage();\n","import type { FheChain } from \"../chains\";\nimport { ConfigurationError } from \"../errors\";\nimport { IndexedDBStorage } from \"../storage/indexeddb-storage\";\nimport { MemoryStorage } from \"../storage/memory-storage\";\nimport type { GenericStorage } from \"../types\";\nimport type { RelayerConfig } from \"./types\";\n\n// ── Storage defaults ─────────────────────────────────────────────────────────\n\nfunction getDefaultStorage(): GenericStorage {\n return typeof window !== \"undefined\"\n ? new IndexedDBStorage(\"CredentialStore\")\n : new MemoryStorage();\n}\n\nfunction getDefaultSessionStorage(): GenericStorage {\n return typeof window !== \"undefined\" ? new IndexedDBStorage(\"SessionStore\") : new MemoryStorage();\n}\n\nexport function resolveStorage(\n storage: GenericStorage | undefined = getDefaultStorage(),\n sessionStorage: GenericStorage | undefined = getDefaultSessionStorage(),\n): { storage: GenericStorage; sessionStorage: GenericStorage } {\n return { storage, sessionStorage };\n}\n\n// ── Chain relayer resolution ────────────────────────────────────────────────\n\nexport interface ResolvedChainRelayer {\n chain: FheChain;\n relayer: RelayerConfig;\n}\n\nexport function resolveChainRelayers(\n chains: readonly FheChain[],\n relayers: Readonly<Record<number, RelayerConfig>>,\n): Map<number, ResolvedChainRelayer> {\n const chainMap = new Map(chains.map((c) => [c.id, c]));\n if (chainMap.size !== chains.length) {\n const ids = chains.map((c) => c.id);\n const dupes = [...new Set(ids.filter((id, i) => ids.indexOf(id) !== i))];\n throw new ConfigurationError(\n `Duplicate chain id(s) [${dupes.join(\", \")}] in the chains array. ` +\n `Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`,\n );\n }\n const relayerMap = new Map(Object.entries(relayers));\n const result = new Map<number, ResolvedChainRelayer>();\n\n for (const id of chainMap.keys()) {\n const chainConfig = chainMap.get(id);\n const relayerConfig = relayerMap.get(String(id));\n\n if (!relayerConfig) {\n throw new ConfigurationError(\n `Chain ${id} has no relayer configured. ` +\n `Add a relayer entry: relayers: { [${id}]: web() }`,\n );\n }\n\n if (!chainConfig) {\n throw new ConfigurationError(\n `Chain ${id} has a relayer configured but no entry in the chains array. ` +\n `Add the chain config to the chains array.`,\n );\n }\n\n result.set(id, {\n chain: chainConfig,\n relayer: relayerConfig,\n });\n }\n\n const relayerIdSet = new Set(Object.keys(relayers).map(Number));\n const orphaned = new Set([...relayerIdSet].filter((id) => !chainMap.has(id)));\n if (orphaned.size > 0) {\n throw new ConfigurationError(\n `Relayer entries for chain(s) [${[...orphaned].join(\", \")}] have no matching entry ` +\n `in the chains array. Remove them or add the corresponding chain config.`,\n );\n }\n\n return result;\n}\n","import type {\n InputProofBytesType,\n KeypairType,\n KmsDelegatedUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address, Hex } from \"viem\";\nimport type { FheChain } from \"../chains/types\";\nimport type { RelayerConfig } from \"../config/types\";\nimport { resolveChainRelayers } from \"../config/resolve\";\nimport { ConfigurationError } from \"../errors\";\nimport { assertNonNullable, toError } from \"../utils\";\nimport type { RelayerSDK } from \"./relayer-sdk\";\nimport type {\n ClearValueType,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n Handle,\n PublicDecryptResult,\n PublicKeyData,\n PublicParamsData,\n UserDecryptParams,\n} from \"./relayer-sdk.types\";\n\n/** Anything with a synchronous `terminate()` method (workers, pools). */\nexport interface WorkerLike {\n terminate(): void;\n}\n\n/**\n * Owns chain management (chains / activeChain / switchChain) and delegates\n * every {@link RelayerSDK} operation to the relayer for the currently active\n * chain.\n *\n * Groups chains by relayer config reference identity, calls `createWorker`\n * once per group with all chain configs, then calls `createRelayer`\n * per chain with the shared worker.\n *\n * Workers/pools are held separately from relayers so the dispatcher can\n * terminate them directly — relayers never own worker lifecycle.\n */\nexport class RelayerDispatcher implements RelayerSDK, Disposable {\n readonly #chains: Map<number, FheChain>;\n readonly #relayers: Map<number, RelayerSDK>;\n readonly #workers: readonly WorkerLike[];\n #chainId: number;\n\n constructor(\n chains: readonly [FheChain, ...FheChain[]],\n configs: Readonly<Record<number, RelayerConfig>>,\n ) {\n if (chains.length === 0) {\n throw new ConfigurationError(\"At least one chain is required.\");\n }\n this.#chains = new Map(chains.map((c) => [c.id, c]));\n this.#chainId = chains[0].id;\n\n const chainRelayers = resolveChainRelayers(chains, configs);\n\n // Group chains by relayer config reference — same object = same group = shared worker.\n const groups = new Map<RelayerConfig, Array<[number, FheChain]>>();\n for (const [chainId, config] of chainRelayers) {\n const key = config.relayer;\n let group = groups.get(key);\n if (!group) {\n group = [];\n groups.set(key, group);\n }\n group.push([chainId, config.chain]);\n }\n\n // For each group: create shared worker once, then create per-chain relayers.\n const relayers = new Map<number, RelayerSDK>();\n const workers: WorkerLike[] = [];\n try {\n for (const [relayerCfg, groupChains] of groups) {\n const allChainConfigs = groupChains.map(([, chain]) => chain);\n const worker = relayerCfg.createWorker?.(allChainConfigs);\n if (worker) {\n workers.push(worker);\n }\n for (const [chainId, chain] of groupChains) {\n relayers.set(chainId, relayerCfg.createRelayer(chain, worker));\n }\n }\n } catch (error) {\n for (const w of workers) {\n try {\n w.terminate();\n } catch {\n /* best-effort cleanup */\n }\n }\n throw error;\n }\n\n this.#relayers = relayers;\n this.#workers = workers;\n }\n\n get chains(): readonly FheChain[] {\n return [...this.#chains.values()];\n }\n\n get chain(): FheChain {\n const chain = this.#chains.get(this.#chainId);\n assertNonNullable(chain, \"RelayerDispatcher: chain\");\n return chain;\n }\n\n switchChain(chainId: number): void {\n if (!this.#chains.has(chainId)) {\n throw new ConfigurationError(\n `No relayer configured for chain ${chainId}. Add it to the chains array.`,\n );\n }\n this.#chainId = chainId;\n }\n\n get #active(): RelayerSDK {\n const relayer = this.#relayers.get(this.#chainId);\n assertNonNullable(relayer, \"RelayerDispatcher: relayer\");\n return relayer;\n }\n\n generateKeypair(): Promise<KeypairType<Hex>> {\n return this.#active.generateKeypair();\n }\n\n createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays?: number,\n ): Promise<EIP712TypedData> {\n return this.#active.createEIP712(publicKey, contractAddresses, startTimestamp, durationDays);\n }\n\n encrypt(params: EncryptParams): Promise<EncryptResult> {\n return this.#active.encrypt(params);\n }\n\n userDecrypt(params: UserDecryptParams): Promise<Readonly<Record<Handle, ClearValueType>>> {\n return this.#active.userDecrypt(params);\n }\n\n publicDecrypt(handles: Handle[]): Promise<PublicDecryptResult> {\n return this.#active.publicDecrypt(handles);\n }\n\n createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays?: number,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n return this.#active.createDelegatedUserDecryptEIP712(\n publicKey,\n contractAddresses,\n delegatorAddress,\n startTimestamp,\n durationDays,\n );\n }\n\n delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<Handle, ClearValueType>>> {\n return this.#active.delegatedUserDecrypt(params);\n }\n\n requestZKProofVerification(zkProof: ZKProofLike): Promise<InputProofBytesType> {\n return this.#active.requestZKProofVerification(zkProof);\n }\n\n getPublicKey(): Promise<PublicKeyData | null> {\n return this.#active.getPublicKey();\n }\n\n getPublicParams(bits: number): Promise<PublicParamsData | null> {\n return this.#active.getPublicParams(bits);\n }\n\n getAclAddress(): Promise<Address> {\n return this.#active.getAclAddress();\n }\n\n terminate(): void {\n const errors: Error[] = [];\n\n // Clean up relayer-owned caches (no worker termination).\n for (const r of new Set(this.#relayers.values())) {\n try {\n r.terminate();\n } catch (e) {\n errors.push(toError(e));\n }\n }\n\n // Terminate the actual workers/pools (deduplicated).\n for (const w of new Set(this.#workers)) {\n try {\n w.terminate();\n } catch (e) {\n errors.push(toError(e));\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Failed to terminate relayer resources\");\n }\n }\n\n [Symbol.dispose](): void {\n this.terminate();\n }\n}\n","import { RelayerDispatcher } from \"../relayer/relayer-dispatcher\";\nimport type { GenericProvider, GenericSigner } from \"../types\";\nimport { resolveStorage } from \"./resolve\";\nimport type { ZamaConfig, ZamaConfigBase } from \"./types\";\n\n/**\n * @internal Shared config builder — not part of the public API.\n */\nexport function buildZamaConfig(\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n params: ZamaConfigBase,\n): ZamaConfig {\n const { storage, sessionStorage } = resolveStorage(params.storage, params.sessionStorage);\n\n const relayer = new RelayerDispatcher(params.chains, params.relayers);\n\n return {\n chains: params.chains,\n relayer,\n provider,\n signer,\n storage,\n sessionStorage,\n keypairTTL: params.keypairTTL,\n sessionTTL: params.sessionTTL,\n registryTTL: params.registryTTL,\n onEvent: params.onEvent,\n };\n}\n"],"mappings":"sEAWA,IAAa,EAAb,KAAwD,CACtD,GAA0B,KAC1B,GAA0C,KAC1C,GACA,GACA,GAEA,YAAY,EAAS,kBAAmB,EAAY,EAAG,EAAY,cAAe,CAChF,MAAA,EAAe,EACf,MAAA,EAAkB,EAClB,MAAA,EAAkB,EAGpB,IAA+B,CA4C7B,OA3CI,MAAA,EACK,QAAQ,QAAQ,MAAA,EAAS,EAE9B,AAIJ,MAAA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2B,EAAQ,CAGzD,cAA8C,CAC5C,OAAO,MAAA,EAAa,cAAc,CAGpC,gBAAgB,EAAgD,CAC9D,OAAO,MAAA,EAAa,gBAAgB,EAAK,CAG3C,eAAkC,CAChC,OAAO,MAAA,EAAa,eAAe,CAGrC,WAAkB,CAChB,IAAM,EAAkB,EAAE,CAG1B,IAAK,IAAM,KAAK,IAAI,IAAI,MAAA,EAAe,QAAQ,CAAC,CAC9C,GAAI,CACF,EAAE,WAAW,OACN,EAAG,CACV,EAAO,KAAKG,EAAAA,EAAQ,EAAE,CAAC,CAK3B,IAAK,IAAM,KAAK,IAAI,IAAI,MAAA,EAAc,CACpC,GAAI,CACF,EAAE,WAAW,OACN,EAAG,CACV,EAAO,KAAKA,EAAAA,EAAQ,EAAE,CAAC,CAI3B,GAAI,EAAO,OAAS,EAClB,MAAU,eAAe,EAAQ,wCAAwC,CAI7E,CAAC,OAAO,UAAiB,CACvB,KAAK,WAAW,GCjNpB,SAAgB,EACd,EACA,EACA,EACY,CACZ,GAAM,CAAE,UAAS,kBAAmB,EAAe,EAAO,QAAS,EAAO,eAAe,CAEnF,EAAU,IAAI,EAAkB,EAAO,OAAQ,EAAO,SAAS,CAErE,MAAO,CACL,OAAQ,EAAO,OACf,UACA,WACA,SACA,UACA,iBACA,WAAY,EAAO,WACnB,WAAY,EAAO,WACnB,YAAa,EAAO,YACpB,QAAS,EAAO,QACjB"}
|
|
@@ -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 — server\n * indexers, SSR, dashboards, explorers, or dApps before the user has\n * connected their 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":"yNA0CA,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,CAOlF,OANiB,IAAI,EAAA,OAAO,SAC1B,EAAO,QACP,EAAO,IACP,MAAA,EACD,CACmB,YAAY,EAAO,aAAa,CAC1C,GAAI,EAAO,KAA4B,CAKnD,MAAM,mBAAqC,CACzC,IAAM,EAAQ,MAAM,MAAA,EAAmB,SAAS,SAAS,CACzD,GAAI,CAAC,EACH,MAAU,MAAM,+BAA+B,CAEjD,GAAI,EAAM,YAAc,KACtB,MAAU,MAAM,gCAAgC,CAElD,OAAO,OAAO,EAAM,UAAU,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B,EAAM,EAAI,EAAiB,CAAC,CAGnG,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,CACA,OAAO,EACL,EACAC,EAAAA,EAAuB,EAAS,EAAiB,EAAsB,EAAgB,CACxF,CAGH,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAY,EAAQC,EAAAA,EAAoB,EAAc,EAAS,EAAU,CAAC,CAGnF,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAY,EAAQC,EAAAA,EAAa,EAAgB,EAAI,EAAO,CAAC,CAKtE,SAAgB,EAAuB,EAA8B,EAAmB,CACtF,OAAO,EAAW,EAAUC,EAAAA,EAAsB,EAAS,CAAC,CAG9D,SAAgB,EAA6B,EAA8B,EAAmB,CAC5F,OAAO,EAAW,EAAUC,EAAAA,EAA4B,EAAS,CAAC,CAGpE,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAA2B,EAAU,EAAW,EAAQ,CAAC,CAGvF,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAqB,EAAU,EAAM,CAAC,CAGpE,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAoC,EAAU,EAAa,CAAC,CAG1F,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAwB,EAAU,EAAyB,CAAC,CAG1F,SAAgB,EACd,EACA,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 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,CAOlF,OANiB,IAAI,EAAA,OAAO,SAC1B,EAAO,QACP,EAAO,IACP,MAAA,EACD,CACmB,YAAY,EAAO,aAAa,CAC1C,GAAI,EAAO,KAA4B,CAKnD,MAAM,mBAAqC,CACzC,IAAM,EAAQ,MAAM,MAAA,EAAmB,SAAS,SAAS,CACzD,GAAI,CAAC,EACH,MAAU,MAAM,+BAA+B,CAEjD,GAAI,EAAM,Y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ACA,EACA,EACA,EACA,CACA,OAAO,EAAY,EAAQC,EAAAA,EAA0B,EAAgB,EAAM,EAAI,EAAiB,CAAC,CAGnG,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,CACA,OAAO,EACL,EACAC,EAAAA,EAAuB,EAAS,EAAiB,EAAsB,EAAgB,CACxF,CAGH,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAY,EAAQC,EAAAA,EAAoB,EAAc,EAAS,EAAU,CAAC,CAGnF,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAY,EAAQC,EAAAA,EAAa,EAAgB,EAAI,EAAO,CAAC,CAKtE,SAAgB,EAAuB,EAA8B,EAAmB,CACtF,OAAO,EAAW,EAAUC,EAAAA,EAAsB,EAAS,CAAC,CAG9D,SAAgB,EAA6B,EAA8B,EAAmB,CAC5F,OAAO,EAAW,EAAUC,EAAAA,EAA4B,EAAS,CAAC,CAGpE,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAA2B,EAAU,EAAW,EAAQ,CAAC,CAGvF,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAqB,EAAU,EAAM,CAAC,CAGpE,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,EAAoC,EAAU,EAAa,CAAC,CAG1F,SAAgB,EACd,EACA,EACA,EACA,CACA,OAAO,EAAW,EAAUC,EAAAA,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,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./build.cjs`),t=require(`./relayer.cjs`),n=require(`./readonly-token.cjs`),r=require(`./encryption.cjs`),i=require(`./wrappers-registry.cjs`),a=require(`./relayer-cleartext.cjs`),o=require(`./chains.cjs`);let s=require(`viem`);var c=class extends t.r{constructor(e,n){super(t.i.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},l=class extends t.r{constructor(e,n){super(t.i.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},u=class extends t.r{operation;signerChainId;providerChainId;constructor({operation:e,signerChainId:n,providerChainId:r},i){super(t.i.ChainMismatch,`Operation "${e}" 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=e,this.signerChainId=n,this.providerChainId=r}},d=class extends t.r{requested;available;token;constructor(e,n,r){super(t.i.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},f=class extends t.r{requested;available;token;constructor(e,n,r){super(t.i.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},p=class extends t.r{constructor(e,n){super(t.i.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},m=class extends t.r{constructor(e,n){super(t.i.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function h(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 g={AlreadyDelegatedOrRevokedInSameBlock:e=>new n.x(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new n.b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new n.y(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new n.O(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new n.S(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new n.C(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new n.T(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new n.E(`Cannot revoke: no active delegation exists.`,{cause:e})};function _(e){let t=e instanceof Error?e:void 0,n=h(e);if(n&&n in g)return g[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(g))if(r.includes(e))return n(t);return null}var ee=class{#e=null;async ensureInit(){return this.#e||=this.init().catch(e=>{throw this.#e=null,e}),this.#e}resetInit(){this.#e=null}async getAclAddress(){if(!this.chain.aclContractAddress)throw new t.t(`No ACL address configured for chain ${this.chain.id}`);return this.chain.aclContractAddress}};function v(e){return e.startsWith(`0x`)?e:`0x${e}`}const y=8192,b=300*1e3;function te(e){let t=[];for(let n=0;n<e.length;n+=y)t.push(String.fromCharCode(...e.subarray(n,n+y)));return btoa(t.join(``))}function ne(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function x(e){return`fhe:pubkey:${e}`}function S(e,t){return`fhe:params:${e}:${t}`}function C(e){return`fhe:params-index:${e}`}function re(e){i.N(e,`CachedPublicKey`),i.F(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),i.F(e,`publicKey`,`CachedPublicKey.publicKey`)}function ie(e){i.N(e,`CachedPublicParams`),i.F(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),i.F(e,`publicParams`,`CachedPublicParams.publicParams`)}var ae=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let t=x(this.#t);try{let e=await this.#e.get(t);if(e){re(e);let t={publicKeyId:e.publicKeyId,publicKey:ne(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(t),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:i.L(e).message})}let n=await e();if(n===null)return null;this.#a=n;try{let e={publicKeyId:n.publicKeyId,publicKey:te(n.publicKey),lastValidatedAt:Date.now()};await this.#e.set(t,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:i.L(e).message})}return n}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,t){let n=S(this.#t,e);try{let t=await this.#e.get(n);if(t){ie(t);let n={publicParamsId:t.publicParamsId,publicParams:ne(t.publicParams)};return this.#o.set(e,n),n}}catch(t){await this.#g(n),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:i.L(t).message})}let r=await t();if(r===null)return null;this.#o.set(e,r);try{let t={publicParamsId:r.publicParamsId,publicParams:te(r.publicParams),lastValidatedAt:Date.now()};await this.#e.set(n,t);let a=C(this.#t),o=await this.#e.get(a).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:i.L(e).message}),null))??[];o.includes(e)||await this.#e.set(a,[...o,e])}catch(t){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:i.L(t).message})}return r}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let t=x(this.#t),n=null,r=[];try{let[a,o]=await Promise.all([this.#e.get(t),this.#h()]);if(a)try{re(a),n={...a,lastValidatedAt:a.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:i.L(e).message}),await this.#g(t)}if(r=o,!n)return!1;if([n,...r.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let i=e-this.#r+b;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(t,{...n,lastValidatedAt:i},r.map(e=>({...e,data:{...e.data,lastValidatedAt:i}}))),this.#u=i,!1}let c=await s.json(),l=c?.response?.fheKeyInfo?.[0];if(!c||typeof c!=`object`||c.status!==`succeeded`||!l?.fhePublicKey?.urls?.length||typeof c.response?.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let i=e-this.#r+b;return await this.#v(t,{...n,lastValidatedAt:i},r.map(e=>({...e,data:{...e.data,lastValidatedAt:i}}))),this.#u=i,!1}let u=c.response,d=l.fhePublicKey.urls[0];if(n.artifactUrl&&d&&d!==n.artifactUrl)return await this.#_(t,r),this.#u=null,!0;let f={...n,lastValidatedAt:e};if(d){let e=await this.#m(d,n);if(!e.fresh)return await this.#_(t,r),this.#u=null,!0;f={...f,artifactUrl:d,etag:e.etag,lastModified:e.lastModified}}let p=[];for(let n of r){let i=u.crs[String(n.bits)]?.urls[0];if(n.data.artifactUrl&&i&&i!==n.data.artifactUrl)return await this.#_(t,r),this.#u=null,!0;let a={...n.data,lastValidatedAt:e};if(i){let e=await this.#m(i,n.data);if(!e.fresh)return await this.#_(t,r),this.#u=null,!0;a={...a,artifactUrl:i,etag:e.etag,lastModified:e.lastModified}}p.push({...n,data:a})}return await this.#v(t,f,p),this.#u=e,!1}catch(a){let o=i.L(a),s=a instanceof TypeError||a instanceof ReferenceError||a instanceof RangeError||a instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+b;try{n&&await this.#v(t,{...n,lastValidatedAt:l},r.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:i.L(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=C(this.#t),t=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:i.L(e).message}),null))??[],n=new Set([...this.#o.keys(),...t]),r=Array.from(n);return(await Promise.all(r.map(async e=>{let t=S(this.#t,e),n;try{n=await this.#e.get(t)}catch(t){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:i.L(t).message}),null}if(!n)return null;try{return ie(n),{bits:e,key:t,data:{...n,lastValidatedAt:n.lastValidatedAt??0}}}catch(n){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:i.L(n).message}),await this.#g(t),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(t=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:i.L(t).message})})}async#_(e,t){let n=C(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(n),...t.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:i.L(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,t,n){let r=[this.#e.set(e,t).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:i.L(e).message})}),...n.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:i.L(e).message})}))];await Promise.all(r)}};async function w(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&oe(e)){await se(500*2**r);continue}throw e}throw n}function oe(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`timed out`)||t.includes(`timeout`)||t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`network`)||t.includes(`fetch failed`)||t.includes(`socket hang up`)||t.includes(`502`)||t.includes(`503`)||t.includes(`504`)}function se(e){return new Promise(t=>setTimeout(t,e))}var ce=class extends ee{#e=null;#t=null;#n;constructor(e){super(),this.#n=e}get chain(){return this.#n.chain}async init(){await this.#r.initWorker()}get#r(){return this.#n.worker}#i(){return this.#e||=(this.#t||=this.#n.fheArtifactStorage??new e.o(`FheArtifactCache`,1,`artifacts`),new ae({storage:this.#t,chainId:this.chain.id,relayerUrl:this.chain.relayerUrl,ttl:this.#n.fheArtifactCacheTTL,logger:this.#n.logger})),this.#e}terminate(){this.#e=null,this.resetInit()}[Symbol.dispose](){this.terminate()}async#a(){let e=this.#n.security?.getCsrfToken?.()??``;e&&await this.#r.updateCsrf(e)}async generateKeypair(){await this.ensureInit();let e=this.chain.id,t=await this.#r.generateKeypair({chainId:e});return{publicKey:t.publicKey,privateKey:t.privateKey}}async createEIP712(e,t,n,r=7){await this.ensureInit();let i=this.chain.id;return this.#r.createEIP712({chainId:i,publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r})}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;await this.ensureInit();let i=this.chain.id;return w(async()=>{await this.#a();let e=await this.#r.encrypt({chainId:i,values:t,contractAddress:n,userAddress:r});return{handles:e.handles,inputProof:e.inputProof}})}async userDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),(await this.#r.userDecrypt({chainId:t,...e})).clearValues))}async publicDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>{await this.#a();let n=await this.#r.publicDecrypt({chainId:t,handles:e});return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){await this.ensureInit();let a=this.chain.id;return this.#r.createDelegatedUserDecryptEIP712({chainId:a,publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),(await this.#r.delegatedUserDecrypt({chainId:t,...e})).clearValues))}async requestZKProofVerification(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),this.#r.requestZKProofVerification({chainId:t,zkProof:e})))}async getPublicKey(){await this.ensureInit();let e=this.chain.id;return this.#i().getPublicKey(async()=>(await this.#r.getPublicKey({chainId:e})).result)}async getPublicParams(e){await this.ensureInit();let t=this.chain.id;return this.#i().getPublicParams(e,async()=>(await this.#r.getPublicParams({chainId:t,bits:e})).result)}};const le=3e4;var ue=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,6e4),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let t=this.#t.get(e.id);if(!t){this.logger?.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let n=Math.round(performance.now()-t.startTime);if(clearTimeout(t.timeoutId),this.#t.delete(e.id),e.success)this.logger?.debug(`[WorkerClient] ← ${t.type} OK`,{id:e.id,elapsed:n}),t.resolve(e.data);else{this.logger?.error(`[WorkerClient] ← ${t.type} FAILED`,{id:e.id,elapsed:n,error:e.error});let r=Error(e.error);`statusCode`in e&&typeof e.statusCode==`number`&&(r.statusCode=e.statusCode),t.reject(r)}}handleWorkerError(e){this.logger?.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#i(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger?.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#i(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(e,t,n,r=le){return new Promise((i,a)=>{let o=this.generateRequestId(),s=performance.now();this.logger?.debug(`[WorkerClient] → ${t}`,{id:o});let c=setTimeout(()=>{this.#t.delete(o);let e=Math.round(performance.now()-s);this.logger?.error(`[WorkerClient] ${t} timed out after ${r}ms`,{id:o,elapsed:e}),a(Error(`Request ${t} timed out after ${r}ms`))},r);this.#t.set(o,{resolve:i,reject:a,timeoutId:c,startTime:s,type:t});let l={id:o,type:t,payload:n};this.postMessage(e,l)})}async sendRequest(e,t,n=le){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n)}async generateKeypair(e){return this.sendRequest(`GENERATE_KEYPAIR`,e)}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,e)}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,e)}async getPublicKey(e){return this.sendRequest(`GET_PUBLIC_KEY`,e)}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,e)}#i(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function de(e){try{return i.N(e,`runtime`),i.F(e,`id`,`runtime.id`),i.j(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function fe(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(i.N(t,`ns`),de(t.runtime))return t.runtime}catch{continue}}var pe=class extends ue{env=`web`;constructor(e){super(e,e.logger)}createWorker(){let e=fe();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./build.cjs`),t=require(`./relayer.cjs`),n=require(`./readonly-token.cjs`),r=require(`./encryption.cjs`),i=require(`./signer.cjs`),a=require(`./wrappers-registry.cjs`),o=require(`./relayer-cleartext.cjs`),s=require(`./chains.cjs`);let c=require(`viem`);var l=class extends t.r{constructor(e,n){super(t.i.ApprovalFailed,e,n),this.name=`ApprovalFailedError`}},u=class extends t.r{constructor(e,n){super(t.i.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},d=class extends t.r{operation;signerChainId;providerChainId;constructor({operation:e,signerChainId:n,providerChainId:r},i){super(t.i.ChainMismatch,`Operation "${e}" 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=e,this.signerChainId=n,this.providerChainId=r}},f=class extends t.r{requested;available;token;constructor(e,n,r){super(t.i.InsufficientConfidentialBalance,e,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},p=class extends t.r{requested;available;token;constructor(e,n,r){super(t.i.InsufficientERC20Balance,e,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},m=class extends t.r{constructor(e,n){super(t.i.BalanceCheckUnavailable,e,n),this.name=`BalanceCheckUnavailableError`}},h=class extends t.r{constructor(e,n){super(t.i.ERC20ReadFailed,e,n),this.name=`ERC20ReadFailedError`}};function g(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 _={AlreadyDelegatedOrRevokedInSameBlock:e=>new n.x(`Only one delegate/revoke per (delegator, delegate, contract) per block. Wait for the next block before retrying.`,{cause:e}),SenderCannotBeContractAddress:e=>new n.b(`The contract address cannot be the caller address.`,{cause:e}),EnforcedPause:e=>new n.y(`The ACL contract is paused. Delegation operations are temporarily disabled.`,{cause:e}),SenderCannotBeDelegate:e=>new n.O(`Cannot delegate to yourself (delegate === msg.sender).`,{cause:e}),DelegateCannotBeContractAddress:e=>new n.S(`Delegate address cannot be the same as the contract address.`,{cause:e}),ExpirationDateBeforeOneHour:e=>new n.C(`Expiration date must be at least 1 hour in the future.`,{cause:e}),ExpirationDateAlreadySetToSameValue:e=>new n.T(`The new expiration date is the same as the current one.`,{cause:e}),NotDelegatedYet:e=>new n.E(`Cannot revoke: no active delegation exists.`,{cause:e})};function v(e){let t=e instanceof Error?e:void 0,n=g(e);if(n&&n in _)return _[n](t);let r=e instanceof Error?e.message:String(e);for(let[e,n]of Object.entries(_))if(r.includes(e))return n(t);return null}var ee=class{#e=null;async ensureInit(){return this.#e||=this.init().catch(e=>{throw this.#e=null,e}),this.#e}resetInit(){this.#e=null}async getAclAddress(){if(!this.chain.aclContractAddress)throw new t.t(`No ACL address configured for chain ${this.chain.id}`);return this.chain.aclContractAddress}};function y(e){return e.startsWith(`0x`)?e:`0x${e}`}const b=8192,x=300*1e3;function te(e){let t=[];for(let n=0;n<e.length;n+=b)t.push(String.fromCharCode(...e.subarray(n,n+b)));return btoa(t.join(``))}function S(e){let t;try{t=atob(e)}catch{throw Error(`Invalid base64 data (length: ${e.length})`)}if(t.length===0)throw Error(`Decoded artifact is empty`);let n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function ne(e){return`fhe:pubkey:${e}`}function re(e,t){return`fhe:params:${e}:${t}`}function C(e){return`fhe:params-index:${e}`}function ie(e){a.N(e,`CachedPublicKey`),a.F(e,`publicKeyId`,`CachedPublicKey.publicKeyId`),a.F(e,`publicKey`,`CachedPublicKey.publicKey`)}function ae(e){a.N(e,`CachedPublicParams`),a.F(e,`publicParamsId`,`CachedPublicParams.publicParamsId`),a.F(e,`publicParams`,`CachedPublicParams.publicParams`)}var oe=class{#e;#t;#n;#r;#i;#a;#o=new Map;#s=null;#c=new Map;#l=null;#u=null;constructor(e){this.#e=e.storage,this.#t=e.chainId,this.#n=e.relayerUrl,this.#r=(e.ttl??86400)*1e3,this.#i=e.logger??console}async getPublicKey(e){if(this.#a!==void 0)return this.#a;if(this.#s)return this.#s;this.#s=this.#d(e);try{return await this.#s}finally{this.#s=null}}async#d(e){let t=ne(this.#t);try{let e=await this.#e.get(t);if(e){ie(e);let t={publicKeyId:e.publicKeyId,publicKey:S(e.publicKey)};return this.#a=t,t}}catch(e){await this.#g(t),this.#i.warn(`Failed to read public key from persistent storage, falling back to network fetch`,{chainId:this.#t,error:a.L(e).message})}let n=await e();if(n===null)return null;this.#a=n;try{let e={publicKeyId:n.publicKeyId,publicKey:te(n.publicKey),lastValidatedAt:Date.now()};await this.#e.set(t,e)}catch(e){this.#i.warn(`Failed to persist public key to storage`,{chainId:this.#t,error:a.L(e).message})}return n}async getPublicParams(e,t){let n=this.#o.get(e);if(n!==void 0)return n;let r=this.#c.get(e);if(r)return r;let i=this.#f(e,t);this.#c.set(e,i);try{return await i}finally{this.#c.delete(e)}}async#f(e,t){let n=re(this.#t,e);try{let t=await this.#e.get(n);if(t){ae(t);let n={publicParamsId:t.publicParamsId,publicParams:S(t.publicParams)};return this.#o.set(e,n),n}}catch(t){await this.#g(n),this.#i.warn(`Failed to read public params from persistent storage, falling back to network fetch`,{chainId:this.#t,bits:e,error:a.L(t).message})}let r=await t();if(r===null)return null;this.#o.set(e,r);try{let t={publicParamsId:r.publicParamsId,publicParams:te(r.publicParams),lastValidatedAt:Date.now()};await this.#e.set(n,t);let i=C(this.#t),o=await this.#e.get(i).catch(e=>(this.#i.warn(`Failed to read params index from storage`,{chainId:this.#t,error:a.L(e).message}),null))??[];o.includes(e)||await this.#e.set(i,[...o,e])}catch(t){this.#i.warn(`Failed to persist public params to storage`,{chainId:this.#t,bits:e,error:a.L(t).message})}return r}async revalidateIfDue(){if(this.#l)return this.#l;this.#l=this.#p();try{return await this.#l}finally{this.#l=null}}async#p(){let e=Date.now();if(this.#u!==null&&e-this.#u<this.#r||!this.#n)return!1;let t=ne(this.#t),n=null,r=[];try{let[i,o]=await Promise.all([this.#e.get(t),this.#h()]);if(i)try{ie(i),n={...i,lastValidatedAt:i.lastValidatedAt??0}}catch(e){this.#i.warn(`Corrupt public key cache entry detected, deleting`,{chainId:this.#t,error:a.L(e).message}),await this.#g(t)}if(r=o,!n)return!1;if([n,...r.map(e=>e.data)].every(t=>e-t.lastValidatedAt<this.#r))return this.#u=e,!1;let s=await globalThis.fetch(`${this.#n}/keyurl`);if(!s.ok){let i=e-this.#r+x;return this.#i.warn(`Manifest fetch failed during revalidation, retrying in 5 min`,{status:s.status,relayerUrl:this.#n}),await this.#v(t,{...n,lastValidatedAt:i},r.map(e=>({...e,data:{...e.data,lastValidatedAt:i}}))),this.#u=i,!1}let c=await s.json(),l=c?.response?.fheKeyInfo?.[0];if(!c||typeof c!=`object`||c.status!==`succeeded`||!l?.fhePublicKey?.urls?.length||typeof c.response?.crs!=`object`){this.#i.error(`Relayer manifest has unexpected shape — check relayer URL and API version`,{relayerUrl:this.#n,manifestKeys:c&&typeof c==`object`?Object.keys(c):[]});let i=e-this.#r+x;return await this.#v(t,{...n,lastValidatedAt:i},r.map(e=>({...e,data:{...e.data,lastValidatedAt:i}}))),this.#u=i,!1}let u=c.response,d=l.fhePublicKey.urls[0];if(n.artifactUrl&&d&&d!==n.artifactUrl)return await this.#_(t,r),this.#u=null,!0;let f={...n,lastValidatedAt:e};if(d){let e=await this.#m(d,n);if(!e.fresh)return await this.#_(t,r),this.#u=null,!0;f={...f,artifactUrl:d,etag:e.etag,lastModified:e.lastModified}}let p=[];for(let n of r){let i=u.crs[String(n.bits)]?.urls[0];if(n.data.artifactUrl&&i&&i!==n.data.artifactUrl)return await this.#_(t,r),this.#u=null,!0;let a={...n.data,lastValidatedAt:e};if(i){let e=await this.#m(i,n.data);if(!e.fresh)return await this.#_(t,r),this.#u=null,!0;a={...a,artifactUrl:i,etag:e.etag,lastModified:e.lastModified}}p.push({...n,data:a})}return await this.#v(t,f,p),this.#u=e,!1}catch(i){let o=a.L(i),s=i instanceof TypeError||i instanceof ReferenceError||i instanceof RangeError||i instanceof SyntaxError,c=s?`error`:`warn`;this.#i[c](s?`Unexpected error during revalidation (possible bug)`:`Revalidation failed, using cached artifacts (fail-open)`,{chainId:this.#t,relayerUrl:this.#n,error:o.message});let l=e-this.#r+x;try{n&&await this.#v(t,{...n,lastValidatedAt:l},r.map(e=>({...e,data:{...e.data,lastValidatedAt:l}})))}catch(e){this.#i.warn(`Failed to update validation timestamps after revalidation error`,{chainId:this.#t,error:a.L(e).message})}return this.#u=l,!1}}async#m(e,t){let n=!!(t.etag||t.lastModified),r={};t.etag&&(r[`If-None-Match`]=t.etag),t.lastModified&&(r[`If-Modified-Since`]=t.lastModified);let i=await globalThis.fetch(e,{method:`HEAD`,headers:r});if(i.status===405&&(i=await globalThis.fetch(e,{headers:r})),!i.ok&&i.status!==304)throw Error(`Artifact freshness check failed: HEAD ${e} returned ${i.status}`);let a=i.headers.get(`etag`)??void 0,o=i.headers.get(`last-modified`)??void 0;return i.status===304?{fresh:!0,etag:a??t.etag,lastModified:o??t.lastModified}:n?{fresh:!1,etag:a,lastModified:o}:{fresh:!0,etag:a,lastModified:o}}async#h(){let e=C(this.#t),t=await this.#e.get(e).catch(e=>(this.#i.warn(`Failed to read params index, CRS revalidation may be incomplete`,{chainId:this.#t,error:a.L(e).message}),null))??[],n=new Set([...this.#o.keys(),...t]),r=Array.from(n);return(await Promise.all(r.map(async e=>{let t=re(this.#t,e),n;try{n=await this.#e.get(t)}catch(t){return this.#i.warn(`Failed to read cached params entry during revalidation`,{chainId:this.#t,bits:e,error:a.L(t).message}),null}if(!n)return null;try{return ae(n),{bits:e,key:t,data:{...n,lastValidatedAt:n.lastValidatedAt??0}}}catch(n){return this.#i.warn(`Corrupt params cache entry detected, deleting`,{chainId:this.#t,bits:e,error:a.L(n).message}),await this.#g(t),null}}))).filter(e=>e!==null)}async#g(e){await this.#e.delete(e).catch(t=>{this.#i.warn(`Failed to delete cache entry`,{chainId:this.#t,key:e,error:a.L(t).message})})}async#_(e,t){let n=C(this.#t);try{await Promise.all([this.#e.delete(e),this.#e.delete(n),...t.map(e=>this.#e.delete(e.key))])}catch(e){this.#i.warn(`Failed to clear stale artifacts from persistent storage`,{chainId:this.#t,error:a.L(e).message})}this.#a=void 0,this.#o.clear()}async#v(e,t,n){let r=[this.#e.set(e,t).catch(e=>{this.#i.warn(`Failed to update public key validation timestamp`,{chainId:this.#t,error:a.L(e).message})}),...n.map(e=>this.#e.set(e.key,e.data).catch(e=>{this.#i.warn(`Failed to update params validation timestamp`,{chainId:this.#t,error:a.L(e).message})}))];await Promise.all(r)}};async function w(e,t=2){let n;for(let r=0;r<=t;r++)try{return await e()}catch(e){if(n=e,r<t&&se(e)){await ce(500*2**r);continue}throw e}throw n}function se(e){if(!(e instanceof Error))return!1;let t=e.message.toLowerCase();return t.includes(`timed out`)||t.includes(`timeout`)||t.includes(`econnreset`)||t.includes(`econnrefused`)||t.includes(`network`)||t.includes(`fetch failed`)||t.includes(`socket hang up`)||t.includes(`502`)||t.includes(`503`)||t.includes(`504`)}function ce(e){return new Promise(t=>setTimeout(t,e))}var le=class extends ee{#e=null;#t=null;#n;constructor(e){super(),this.#n=e}get chain(){return this.#n.chain}async init(){await this.#r.initWorker()}get#r(){return this.#n.worker}#i(){return this.#e||=(this.#t||=this.#n.fheArtifactStorage??new e.o(`FheArtifactCache`,1,`artifacts`),new oe({storage:this.#t,chainId:this.chain.id,relayerUrl:this.chain.relayerUrl,ttl:this.#n.fheArtifactCacheTTL,logger:this.#n.logger})),this.#e}terminate(){this.#e=null,this.resetInit()}[Symbol.dispose](){this.terminate()}async#a(){let e=this.#n.security?.getCsrfToken?.()??``;e&&await this.#r.updateCsrf(e)}async generateKeypair(){await this.ensureInit();let e=this.chain.id,t=await this.#r.generateKeypair({chainId:e});return{publicKey:t.publicKey,privateKey:t.privateKey}}async createEIP712(e,t,n,r=7){await this.ensureInit();let i=this.chain.id;return this.#r.createEIP712({chainId:i,publicKey:e,contractAddresses:t,startTimestamp:n,durationDays:r})}async encrypt(e){let{values:t,contractAddress:n,userAddress:r}=e;await this.ensureInit();let i=this.chain.id;return w(async()=>{await this.#a();let e=await this.#r.encrypt({chainId:i,values:t,contractAddress:n,userAddress:r});return{handles:e.handles,inputProof:e.inputProof}})}async userDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),(await this.#r.userDecrypt({chainId:t,...e})).clearValues))}async publicDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>{await this.#a();let n=await this.#r.publicDecrypt({chainId:t,handles:e});return{clearValues:n.clearValues,abiEncodedClearValues:n.abiEncodedClearValues,decryptionProof:n.decryptionProof}})}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){await this.ensureInit();let a=this.chain.id;return this.#r.createDelegatedUserDecryptEIP712({chainId:a,publicKey:e,contractAddresses:t,delegatorAddress:n,startTimestamp:r,durationDays:i})}async delegatedUserDecrypt(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),(await this.#r.delegatedUserDecrypt({chainId:t,...e})).clearValues))}async requestZKProofVerification(e){await this.ensureInit();let t=this.chain.id;return w(async()=>(await this.#a(),this.#r.requestZKProofVerification({chainId:t,zkProof:e})))}async getPublicKey(){await this.ensureInit();let e=this.chain.id;return this.#i().getPublicKey(async()=>(await this.#r.getPublicKey({chainId:e})).result)}async getPublicParams(e){await this.ensureInit();let t=this.chain.id;return this.#i().getPublicParams(e,async()=>(await this.#r.getPublicParams({chainId:t,bits:e})).result)}};const ue=3e4;var de=class{#e=null;#t=new Map;#n=null;config;logger;constructor(e,t){this.config=e,this.logger=t}async initWorker(){return this.#e?this.#e:(this.#n||=this.#r().catch(e=>{throw this.#n=null,e}),this.#n)}async#r(){let e=this.createWorker();this.wireEvents(e);try{let{type:t,payload:n}=this.getInitPayload();await this.sendRequestTo(e,t,n,6e4),this.onWorkerReady?.(e),this.#e=e}catch(t){throw this.terminateWorker(e),t}return this.#e}terminate(){if(this.#e){for(let[e,t]of this.#t)clearTimeout(t.timeoutId),t.reject(Error(`Worker terminated`)),this.#t.delete(e);this.terminateWorker(this.#e),this.#e=null}this.#n=null}handleResponse(e){let t=this.#t.get(e.id);if(!t){this.logger?.warn(`[WorkerClient] Received response for unknown request`,{id:e.id});return}let n=Math.round(performance.now()-t.startTime);if(clearTimeout(t.timeoutId),this.#t.delete(e.id),e.success)this.logger?.debug(`[WorkerClient] ← ${t.type} OK`,{id:e.id,elapsed:n}),t.resolve(e.data);else{this.logger?.error(`[WorkerClient] ← ${t.type} FAILED`,{id:e.id,elapsed:n,error:e.error});let r=Error(e.error);`statusCode`in e&&typeof e.statusCode==`number`&&(r.statusCode=e.statusCode),t.reject(r)}}handleWorkerError(e){this.logger?.error(`[WorkerClient] Worker error`,{error:e});let t=this.#e;this.#e=null,this.#i(`Worker error: ${e}`),t&&this.terminateWorker(t)}handleWorkerMessageError(){this.logger?.error(`[WorkerClient] Message deserialization failed`);let e=this.#e;this.#e=null,this.#i(`Worker message deserialization failed`),e&&this.terminateWorker(e)}sendRequestTo(e,t,n,r=ue){return new Promise((i,a)=>{let o=this.generateRequestId(),s=performance.now();this.logger?.debug(`[WorkerClient] → ${t}`,{id:o});let c=setTimeout(()=>{this.#t.delete(o);let e=Math.round(performance.now()-s);this.logger?.error(`[WorkerClient] ${t} timed out after ${r}ms`,{id:o,elapsed:e}),a(Error(`Request ${t} timed out after ${r}ms`))},r);this.#t.set(o,{resolve:i,reject:a,timeoutId:c,startTime:s,type:t});let l={id:o,type:t,payload:n};this.postMessage(e,l)})}async sendRequest(e,t,n=ue){let r=await this.initWorker();return this.sendRequestTo(r,e,t,n)}async generateKeypair(e){return this.sendRequest(`GENERATE_KEYPAIR`,e)}async createEIP712(e){return this.sendRequest(`CREATE_EIP712`,e)}async encrypt(e){return this.sendRequest(`ENCRYPT`,e)}async userDecrypt(e){return this.sendRequest(`USER_DECRYPT`,e)}async publicDecrypt(e){return this.sendRequest(`PUBLIC_DECRYPT`,e)}async createDelegatedUserDecryptEIP712(e){return this.sendRequest(`CREATE_DELEGATED_EIP712`,e)}async delegatedUserDecrypt(e){return this.sendRequest(`DELEGATED_USER_DECRYPT`,e)}async requestZKProofVerification(e){return this.sendRequest(`REQUEST_ZK_PROOF_VERIFICATION`,e)}async getPublicKey(e){return this.sendRequest(`GET_PUBLIC_KEY`,e)}async getPublicParams(e){return this.sendRequest(`GET_PUBLIC_PARAMS`,e)}#i(e){for(let[t,n]of this.#t)clearTimeout(n.timeoutId),n.reject(Error(e)),this.#t.delete(t)}};function fe(e){try{return a.N(e,`runtime`),a.F(e,`id`,`runtime.id`),a.j(e,`getURL`,`runtime.getURL`),!0}catch{return!1}}function pe(){let e=globalThis;for(let t of[e.chrome,e.browser])try{if(a.N(t,`ns`),fe(t.runtime))return t.runtime}catch{continue}}var me=class extends de{env=`web`;constructor(e){super(e,e.logger)}createWorker(){let e=pe();if(e)return new Worker(e.getURL(`relayer-sdk.worker.js`));let t=URL.createObjectURL(new Blob([`(function() {
|
|
2
2
|
//#region src/utils/assertions.ts
|
|
3
3
|
function assertObject(value, context) {
|
|
4
4
|
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(\`\${context} must be an object, got \${typeof value}\`);
|
|
@@ -511,5 +511,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
511
511
|
};
|
|
512
512
|
//#endregion
|
|
513
513
|
})();
|
|
514
|
-
`],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{env:`web`,cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};function me(e){return{type:`web`,createWorker:t=>new pe({cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,chains:t,csrfToken:e?.security?.getCsrfToken?.()??``,integrity:e?.security?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:e?.logger,thread:e?.threads}),createRelayer:(t,n)=>new ce({chain:t,worker:n,...e})}}function he(){return{type:`cleartext`,createRelayer:e=>{if(!e.executorAddress)throw new t.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 a.t(e)}}}function ge(t){return e.t(t.signer,t.provider,t)}var _e=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,s.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,s.getAddress)(e)}:${(0,s.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))}},ve=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 v(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 ye(e){i.N(e,`Stored credentials`),i.P(e.publicKey,`credentials.publicKey`),i.O(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)i.A(typeof t==`string`&&(0,s.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);i.N(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),i.P(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),i.P(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),i.A(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),i.A(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function be(e){ye(e);let t=e;i.A(typeof t.delegatorAddress==`string`&&(0,s.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),i.A(typeof t.delegateAddress==`string`&&(0,s.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),i.A(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),i.A(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function T(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function E(e,t){let n=new Set(t.map(e=>(0,s.getAddress)(e))),r=new Set(e.map(e=>(0,s.getAddress)(e)));return n.isSubsetOf(r)}function D(e,t){return T(e)?E(e.contractAddresses,t):!1}function O(e){return[...new Set(e.map(e=>(0,s.getAddress)(e)))].toSorted()}async function k(...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 xe=class{#e;constructor(e){this.#e=e}#t(e){i.N(e,`Session entry`),i.P(e.signature,`session.signature`),i.A(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),i.A(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}},A=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 xe(e.sessionStorage),this.crypto=new ve,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:e,contracts:r,createKey:a,createFn:o}){this.emit({type:n.r.CredentialsLoading,contractAddresses:r});try{let t=await this.storage.get(e);if(t){this.assertEncrypted(t);let i=await this.sessionSignatures.get(e);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(e),this.emit({type:n.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(t,i.signature);if(D(a,r))return this.emit({type:n.r.CredentialsCached,contractAddresses:r}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),a;if(T(a))return this.#a({key:e,credentials:a,requiredContracts:r});this.emit({type:n.r.CredentialsExpired,contractAddresses:r})}if(T(t)){if(E(t.contractAddresses,r)){let i=await this.signForContracts(t,t.contractAddresses);await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(t,i);return this.emit({type:n.r.CredentialsCached,contractAddresses:r}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(t,t.contractAddresses),a=await this.decryptCredentials(t,i);return this.#a({key:e,credentials:a,requiredContracts:r})}this.emit({type:n.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof t.r)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:n.r.CredentialsCorrupted,error:i.L(r)}),await this.#s(e)}return(!this.#t||this.#n!==a)&&(this.#n=a,this.#t=o().then(e=>(this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!D(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,t){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:n.r.CredentialsRevoked,...t?{contractAddresses:t}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),D(n,t)):!1}catch{return!1}}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#s(e)}clearCaches(){this.crypto.clearCache(),this.#i=null}async createCredentials({key:e,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:n.r.CredentialsCreating,contractAddresses:r});try{let t=await i();return await this.persistCredentials(e,t),await this.sessionSignatures.set({key:e,signature:t.signature,ttl:this.sessionTTL}),this.emit({type:n.r.CredentialsCreated,contractAddresses:r}),t}catch(e){if(e instanceof t.r)throw e;return n.P(e,a)}}async#a({key:e,credentials:t,requiredContracts:r}){if(this.#r){let e=await this.#r;if(E(e.contractAddresses,r))return this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e;t=e}else if(this.#i){let e=this.#i;if(E(e.contractAddresses,r))return this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e;t=e}let i=this.#o({key:e,credentials:t,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:t,requiredContracts:r}){let i=O([...t.contractAddresses,...r]),a=await this.signForContracts(t,i),o={...t,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,t){try{let n=await this.encryptCredentials(t);await this.storage.set(e,n)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:n.r.CredentialsPersistFailed,error:i.L(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:n.r.CredentialsPersistFailed,error:i.L(e)})}}};function Se(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 j=class t extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t){return k((0,s.getAddress)(e),t)}constructor(t){super(t),this.#e=t.relayer,Se(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&t.sessionStorage instanceof e.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=O(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeFor(e){await this.revokeSession(await t.computeStoreKey(e.address,e.chainId))}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=O(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){ye(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 e=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,s.getAddress)(e)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await t.computeStoreKey(e,n);return this.#n=r,this.#t=i,i}},M=class e extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return k((0,s.getAddress)(e),(0,s.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,s.getAddress)(e),r=O(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,s.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,s.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,s.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,s.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){be(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,s.getAddress)(n)}:${(0,s.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 N(e){return(0,s.keccak256)((0,s.toBytes)(e))}const P={ConfidentialTransfer:N(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:N(`Wrapped(address,uint256)`),UnwrapRequested:N(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:N(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:N(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,s.getAddress)(v(e.slice(-40)))}function Ce(e){return BigInt(e)}function I(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return(0,s.getAddress)(v(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function we(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return v(L(e,t))}function Te(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmountHandle:I(e.topics[3])}}function V(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:z(e.data,0)}}function H(e){return e.topics[0]===P.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}:e.topics[0]===P.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0)}:null}function U(e){return e.topics[0]===P.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:e.topics[0]===P.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:null}function Ee(e){let t=U(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function De(e){if(e.topics[0]!==P.UnwrapFinalizedLegacy)return null;let t=U(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Oe(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:Ce(e.topics[1]),txId:Ce(e.topics[2]),to:F(e.topics[3]),returnVal:we(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function ke(e){return Te(e)??V(e)??H(e)??De(e)??U(e)??Oe(e)}function Ae(e){let t=[];for(let n of e){let e=ke(n);e&&t.push(e)}return t}function je(e){for(let t of e){let e=H(t);if(e)return e}return null}function Me(e){for(let t of e){let e=V(t);if(e)return e}return null}const Ne=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapRequestedLegacy,P.UnwrapFinalized,P.UnwrapFinalizedLegacy,P.UnwrappedStarted],W={DelegatedForUserDecryption:N(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:N(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function G(e){return e.topics[0]!==W.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function K(e){return e.topics[0]!==W.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function Pe(e){return G(e)??K(e)}function Fe(e){let t=[];for(let n of e){let e=Pe(n);e&&t.push(e)}return t}function Ie(e){for(let t of e){let e=G(t);if(e)return e}return null}function Le(e){for(let t of e){let e=K(t);if(e)return e}return null}const Re=[W.DelegatedForUserDecryption,W.RevokedDelegationForUserDecryption];var ze=class e extends n.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,s.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(i.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(e,a,o){await this.sdk.requireChainAlignment(`confidentialTransfer`);let{skipBalanceCheck:c=!1,onEncryptComplete:u,onTransferSubmitted:d}=o??{},f=(0,s.getAddress)(e);c||await this.#i(a);let p,m,h=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:p,inputProof:m}=await this.sdk.relayer.encrypt({values:[{value:a,type:`euint64`}],contractAddress:this.address,userAddress:await this.sdk.signer.getAddress()}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-h}),q(()=>u?.())}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-h}),e instanceof t.r?e:new r.n(`Failed to encrypt transfer amount`,{cause:e})}if(p.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.b(this.address,f,p[0],m));return this.emit({type:n.r.TransferSubmitted,txHash:e}),q(()=>d?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`transfer`,error:i.L(e)}),e instanceof t.r?e:new l(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,a,o,c){await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let u=(0,s.getAddress)(e),d=(0,s.getAddress)(a),f,p,m=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:f,inputProof:p}=await this.sdk.relayer.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:u}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-m}),q(()=>c?.onEncryptComplete?.())}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-m}),e instanceof t.r?e:new r.n(`Failed to encrypt transferFrom amount`,{cause:e})}if(f.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.x(this.address,u,d,f[0],p));return this.emit({type:n.r.TransferFromSubmitted,txHash:e}),q(()=>c?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`transferFrom`,error:i.L(e)}),e instanceof t.r?e:new l(`TransferFrom transaction failed`,{cause:e})}}async approve(e,r){await this.sdk.requireChainAlignment(`approve`);let a=(0,s.getAddress)(e);try{let e=await this.sdk.signer.writeContract(i.w(this.address,a,r));return this.emit({type:n.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`approve`,error:i.L(e)}),e instanceof t.r?e:new c(`Operator approval failed`,{cause:e})}}async isApproved(e,t){return this.sdk.provider.readContract(i.S(this.address,(0,s.getAddress)(t),(0,s.getAddress)(e)))}async shield(e,r){await this.sdk.requireChainAlignment(`shield`);let a=await this.#n(),o;try{let e=await this.sdk.signer.getAddress();o=await this.sdk.provider.readContract(n.d(a,e))}catch(e){throw e instanceof t.r?e:new m(`Could not read ERC-20 balance for shield validation (token: ${a})`,{cause:i.L(e)})}if(o<e)throw new f(`Insufficient ERC-20 balance: requested ${e}, available ${o} (token: ${a})`,{requested:e,available:o,token:a});let c=r?.approvalStrategy??`exact`;c!==`skip`&&await this.#o(e,c===`max`,r);try{let t=r?.to?(0,s.getAddress)(r.to):await this.sdk.signer.getAddress(),a=await this.sdk.signer.writeContract(i._(this.wrapper,t,e));return this.emit({type:n.r.ShieldSubmitted,txHash:a}),q(()=>r?.onShieldSubmitted?.(a)),{txHash:a,receipt:await this.sdk.provider.waitForTransactionReceipt(a)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`shield`,error:i.L(e)}),e instanceof t.r?e:new l(`Shield transaction failed`,{cause:e})}}async unwrap(e){await this.sdk.requireChainAlignment(`unwrap`);let a=await this.sdk.signer.getAddress(),o,s,c=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:o,inputProof:s}=await this.sdk.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:a}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-c})}catch(e){throw this.emit({type:n.r.EncryptError,error:i.L(e),durationMs:Date.now()-c}),e instanceof t.r?e:new r.n(`Failed to encrypt unshield amount`,{cause:e})}if(o.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await this.sdk.signer.writeContract(i.E(this.address,a,a,o[0],s));return this.emit({type:n.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`unwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){await this.sdk.requireChainAlignment(`unwrapAll`);let e=await this.sdk.signer.getAddress(),a=await this.readConfidentialBalanceOf(e);if(n._(a))throw new r.t(`Cannot unshield: balance is zero`);try{let t=await this.sdk.signer.writeContract(i.D(this.address,e,e,a));return this.emit({type:n.r.UnwrapSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`unwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Unshield-all transaction failed`,{cause:e})}}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(e){await this.sdk.requireChainAlignment(`finalizeUnwrap`);let r=await this.sdk.publicDecrypt([e]),a=r.clearValues[e];i.k(a,`finalizeUnwrap: clearValue`);try{let t=await this.sdk.signer.writeContract(i.m(this.wrapper,e,a,r.decryptionProof));return this.emit({type:n.r.FinalizeUnwrapSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`finalizeUnwrap`,error:i.L(e)}),e instanceof t.r?e:new l(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){await this.sdk.requireChainAlignment(`approveUnderlying`);let r=await this.#n(),a=e??2n**256n-1n;try{let e=this.sdk.signer;if(a>0n){let t=await e.getAddress();await this.sdk.provider.readContract(n.l(r,t,this.wrapper))>0n&&await e.writeContract(n.u(r,this.wrapper,0n))}let t=await e.writeContract(n.u(r,this.wrapper,a));return this.emit({type:n.r.ApproveUnderlyingSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`approveUnderlying`,error:i.L(e)}),e instanceof t.r?e:new c(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:r}){if(await this.sdk.requireChainAlignment(`delegateDecryption`),r&&r.getTime()<Date.now()+36e5)throw new n.C(`Expiration date must be at least 1 hour in the future`);let a=(0,s.getAddress)(e),o=this.sdk.signer,c=await o.getAddress();if(a===(0,s.getAddress)(c))throw new n.O(`Cannot delegate to yourself (delegate === msg.sender).`);if(a===this.address)throw new n.S(`Delegate address cannot be the same as the contract address (${this.address}).`);let u=await this.getAclAddress(),d=r?BigInt(Math.floor(r.getTime()/1e3)):n.i,f;try{f=await this.getDelegationExpiry({delegatorAddress:c,delegateAddress:a})}catch{f=-1n}if(f===d)throw new n.T(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);try{let e=await o.writeContract(n.a(u,a,this.address,d));return this.emit({type:n.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`delegateDecryption`,error:i.L(e)}),e instanceof t.r?e:_(e)||new l(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){await this.sdk.requireChainAlignment(`revokeDelegation`);let r=(0,s.getAddress)(e),a=this.sdk.signer,o=await a.getAddress(),c=await this.getAclAddress(),u;try{u=await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:r})}catch{u=1n}if(u===0n)throw new n.E(`No active delegation found for delegate ${r} on contract ${this.address}.`);try{let e=await a.writeContract(n.c(c,r,this.address));return this.emit({type:n.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`revokeDelegation`,error:i.L(e)}),e instanceof t.r?e:_(e)||new l(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,n,r){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await n(e[a]))}catch(n){n instanceof t.r?i.set(e[a].address,n):i.set(e[a].address,new l(r,{cause:n}))}return i}async#i(e){if(e===0n)return;let n;try{n=await this.balanceOf(await this.sdk.signer.getAddress())}catch(e){throw e instanceof t.r?e:new p(`Balance validation failed (token: ${this.address})`,{cause:e})}if(n<e)throw new d(`Insufficient confidential balance: requested ${e}, available ${n} (token: ${this.address})`,{requested:e,available:n,token:this.address})}async#a(e,r,i){this.emit({type:n.r.UnshieldPhase1Submitted,txHash:e,operationId:r});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof t.r?e:new l(`Failed to get unshield receipt`,{cause:e})}let o=je(a.logs);if(!o)throw new l(`No UnwrapRequested event found in unshield receipt`);this.emit({type:n.r.UnshieldPhase2Started,operationId:r}),q(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:n.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),q(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#o(e,r,i){let a=await this.#n(),o=this.sdk.signer,s=await o.getAddress(),l=await this.sdk.provider.readContract(n.l(a,s,this.wrapper));if(!(l>=e))try{if(l>0n){let e=await o.writeContract(n.u(a,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let t=r?2n**256n-1n:e,s=await o.writeContract(n.u(a,this.wrapper,t));this.emit({type:n.r.ApproveUnderlyingSubmitted,txHash:s}),q(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(e){throw e instanceof t.r?e:new c(`ERC-20 approval failed`,{cause:e})}}};function q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const J={[o.a.id]:o.a.registryAddress,[o.o.id]:o.o.registryAddress,[o.i.id]:o.i.registryAddress},Y=300*1e3;var X=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},J,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 e=await this.provider.getChainId(),n=this.#e[e];if(!n)throw new t.t(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return(0,s.getAddress)(n)}async listPairs(e={}){let n=e.page??1,r=e.pageSize??100,a=e.metadata??!1;if(n<1)throw new t.t(`page must be >= 1, got ${n}`);if(r<1)throw new t.t(`pageSize must be >= 1, got ${r}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.provider.readContract(i.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*r),u=l+BigInt(r)>BigInt(c)?BigInt(c):l+BigInt(r);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:r};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(i.o(o,l,u));f=this.#i(d,[...e])}if(!a)return{items:f,total:c,page:n,pageSize:r};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?Y:void 0)}return{items:m,total:c,page:n,pageSize:r}}async#a(e){let[t,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(n.m(e.tokenAddress)),this.provider.readContract(n.h(e.tokenAddress)),this.provider.readContract(n.f(e.tokenAddress)),this.provider.readContract(n.p(e.tokenAddress)),this.provider.readContract(n.m(e.confidentialTokenAddress)),this.provider.readContract(n.h(e.confidentialTokenAddress)),this.provider.readContract(n.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,s.getAddress)(e),r=`ct:${t}:${n}`,a=this.#r(r);if(a!==void 0)return a;let[o,c]=await this.provider.readContract(i.t(t,n));return c===s.zeroAddress?this.#i(r,null,Y):this.#i(r,{confidentialTokenAddress:c,isValid:o})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,s.getAddress)(e),r=`ut:${t}:${n}`,a=this.#r(r);if(a!==void 0)return a;let[o,c]=await this.provider.readContract(i.n(t,n));return c===s.zeroAddress?this.#i(r,null,Y):this.#i(r,{tokenAddress:c,isValid:o})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(i.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(i.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(i.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.t(t,(0,s.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.n(t,(0,s.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(i.s(t,(0,s.getAddress)(e)))}};const Z=365*86400;async function Q(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var Be=class{relayer;provider;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n=new Set;#r;constructor(t){this.relayer=t.relayer,this.provider=t.provider,this.signer=t.signer,this.storage=t.storage,this.sessionStorage=t.sessionStorage??new e.i,this.cache=new _e(t.storage),this.#t=t.onEvent??function(){};let n={};for(let e of t.chains??[])e.registryAddress&&(n[e.id]=e.registryAddress);Object.assign(n,t.registryAddresses),this.registry=new X({provider:this.provider,registryTTL:t.registryTTL,registryAddresses:n}),this.#e=t.registryTTL;let r={relayer:this.relayer,signer:t.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:(()=>{let e=t.keypairTTL??2592e3;if(e<=0||isNaN(e))throw Error(`keypairTTL must be a positive number (seconds)`);return e>Z?(console.warn(`[zama-sdk] keypairTTL (${e}s) exceeds the fhevm maximum of 365 days (${Z}s); capping to ${Z}s.`),Z):e})(),sessionTTL:t.sessionTTL??2592e3,onEvent:this.#t};this.credentials=new j(r),this.delegatedCredentials=new M(r),this.#r=this.signer.subscribe?.(e=>{this.#i(e)})}onIdentityChange(e){return this.#n.add(e),()=>{this.#n.delete(e)}}async requireChainAlignment(e){let[t,n]=await Promise.all([this.signer.getChainId(),this.provider.getChainId()]);if(t!==n)throw new u({operation:e,signerChainId:t,providerChainId:n});return t}async#i(e){if(e.previous){let t=e.previous;await Q(`revoke previous identity`,()=>this.credentials.revokeFor(t)),await Q(`clear decrypt cache`,()=>this.cache.clearForRequester(t.address))}let t=e.next?.chainId;t!==void 0&&await Q(`switch relayer chain`,()=>{this.relayer.switchChain(t)});for(let t of this.#n)await Q(`identity listener`,()=>t(e))}createReadonlyToken(e){return new n.t(this,e)}createToken(e,t){return new ze(this,e,t)}emitEvent(e,t){try{this.#t({...e,tokenAddress:t,timestamp:Date.now()})}catch(e){console.error(`[zama-sdk] onEvent listener threw:`,e)}}createWrappersRegistry(e){return new X({provider:this.provider,registryAddresses:e,registryTTL:this.#e})}async allow(e){e.length!==0&&await this.credentials.allow(...e)}async userDecrypt(e){if(await this.requireChainAlignment(`userDecrypt`),e.length===0)return{};let t=e.map(e=>({handle:e.handle,contractAddress:(0,s.getAddress)(e.contractAddress)})),r={},a=[];for(let e of t)n._(e.handle)?r[e.handle]=0n:a.push(e);if(a.length===0)return r;let o=await this.signer.getAddress(),c=[];for(let e of a){let t=await this.cache.get(o,e.contractAddress,e.handle);t===null?c.push(e):r[e.handle]=t}if(c.length===0)return r;let l=await this.credentials.allow(...new Set(t.map(e=>e.contractAddress))),u=new Map;for(let e of c){let t=u.get(e.contractAddress);t?t.push(e.handle):u.set(e.contractAddress,[e.handle])}let d=Date.now(),f=c.map(e=>e.handle);try{this.emitEvent({type:n.r.DecryptStart,handles:f}),await n.n([...u.entries()].map(([e,t])=>async()=>{let n=await this.relayer.userDecrypt({handles:t,contractAddress:e,signedContractAddresses:l.contractAddresses,privateKey:l.privateKey,publicKey:l.publicKey,signature:l.signature,signerAddress:o,startTimestamp:l.startTimestamp,durationDays:l.durationDays});for(let[t,i]of Object.entries(n))r[t]=i,await this.cache.set(o,e,t,i)}),5);let e={};for(let t of f){let n=r[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:n.r.DecryptEnd,durationMs:Date.now()-d,handles:f,result:e}),r}catch(e){throw this.emitEvent({type:n.r.DecryptError,error:i.L(e),durationMs:Date.now()-d,handles:f}),n.v(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw n.v(e,`Public decryption failed`)}}async revokeSession(){let e=await this.signer.getAddress(),t=await this.signer.getChainId();try{await this.credentials.revokeFor({address:e,chainId:t})}finally{await this.cache.clearForRequester(e)}}dispose(){this.#r?.(),this.#r=void 0,this.#n.clear()}terminate(){this.dispose(),this.relayer.terminate()}[Symbol.dispose](){this.terminate()}};function $(e){return`zama:pending-unshield:${e}`}function Ve(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 He(e,t,n,r){if(r===void 0){await e.set($(t),n);return}await e.set($(t),{version:1,unwrapTxHash:n,unwrapRequestId:r})}async function Ue(e,t){return(await We(e,t))?.unwrapTxHash??null}async function We(e,t){return Ve(await e.get($(t)))}async function Ge(e,t){await e.delete($(t))}var Ke=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 qe=new Ke;exports.ACL_TOPICS=Re,exports.AclPausedError=n.y,exports.AclTopics=W,exports.ApprovalFailedError=c,exports.BalanceCheckUnavailableError=p,exports.ChainMismatchError=u,exports.ChromeSessionStorage=Ke,exports.ConfigurationError=t.t,exports.CredentialsManager=j,exports.DecryptCache=_e,exports.DecryptionFailedError=r.t,exports.DefaultRegistryAddresses=J,exports.DelegatedCredentialsManager=M,exports.DelegationContractIsSelfError=n.b,exports.DelegationCooldownError=n.x,exports.DelegationDelegateEqualsContractError=n.S,exports.DelegationExpirationTooSoonError=n.C,exports.DelegationExpiredError=n.w,exports.DelegationExpiryUnchangedError=n.T,exports.DelegationNotFoundError=n.E,exports.DelegationNotPropagatedError=n.D,exports.DelegationSelfNotAllowedError=n.O,exports.ERC20ReadFailedError=m,exports.ERC7984_INTERFACE_ID=i.c,exports.ERC7984_WRAPPER_INTERFACE_ID=i.l,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=i.u,exports.EncryptionFailedError=r.n,exports.IndexedDBStorage=e.o,exports.InsufficientConfidentialBalanceError=d,exports.InsufficientERC20BalanceError=f,exports.InvalidKeypairError=n.k,exports.KeypairExpiredError=n.A,exports.MemoryStorage=e.i,exports.NoCiphertextError=n.j,exports.ReadonlyToken=n.t,exports.RelayerRequestFailedError=t.n,exports.RelayerWeb=ce,exports.SigningFailedError=n.M,exports.SigningRejectedError=n.N,exports.TOKEN_TOPICS=Ne,exports.Token=ze,exports.Topics=P,exports.TransactionRevertedError=l,exports.WrappersRegistry=X,exports.ZERO_HANDLE=n.g,exports.ZamaError=t.r,exports.ZamaErrorCode=t.i,exports.ZamaSDK=Be,exports.ZamaSDKEvents=n.r,exports.allowanceContract=n.l,exports.anvil=o.t,exports.approveContract=n.u,exports.balanceOfContract=n.d,exports.buildZamaConfig=e.t,exports.chains=o.n,exports.chromeSessionStorage=qe,exports.clearPendingUnshield=Ge,exports.cleartext=he,exports.confidentialBalanceOfContract=i.v,exports.confidentialTotalSupplyContract=i.y,exports.confidentialTransferContract=i.b,exports.confidentialTransferFromContract=i.x,exports.createConfig=ge,exports.decimalsContract=n.f,exports.decodeAclEvent=Pe,exports.decodeAclEvents=Fe,exports.decodeConfidentialTransfer=Te,exports.decodeDelegatedForUserDecryption=G,exports.decodeOnChainEvent=ke,exports.decodeOnChainEvents=Ae,exports.decodeRevokedDelegationForUserDecryption=K,exports.decodeUnwrapFinalized=U,exports.decodeUnwrapRequested=H,exports.decodeUnwrappedFinalized=Ee,exports.decodeUnwrappedStarted=Oe,exports.decodeWrapped=V,exports.delegateForUserDecryptionContract=n.a,exports.finalizeUnwrapContract=i.m,exports.findDelegatedForUserDecryption=Ie,exports.findRevokedDelegationForUserDecryption=Le,exports.findUnwrapRequested=je,exports.findWrapped=Me,exports.getConfidentialTokenAddressContract=i.t,exports.getDelegationExpiryContract=n.o,exports.getTokenAddressContract=i.n,exports.getTokenPairContract=i.r,exports.getTokenPairsContract=i.i,exports.getTokenPairsLengthContract=i.a,exports.getTokenPairsSliceContract=i.o,exports.hardhat=o.r,exports.hoodi=o.i,exports.indexedDBStorage=e.s,exports.inferredTotalSupplyContract=i.h,exports.isConfidentialTokenContract=i.d,exports.isConfidentialTokenValidContract=i.s,exports.isConfidentialWrapperContract=i.f,exports.isHandleDelegatedContract=n.s,exports.isOperatorContract=i.S,exports.isZeroHandle=n._,exports.loadPendingUnshield=Ue,exports.loadPendingUnshieldRequest=We,exports.mainnet=o.a,exports.matchAclRevert=_,exports.matchZamaError=t.a,exports.memoryStorage=e.a,exports.nameContract=n.m,exports.rateContract=i.C,exports.resolveChainRelayers=e.n,exports.resolveStorage=e.r,exports.revokeDelegationContract=n.c,exports.savePendingUnshield=He,exports.sepolia=o.o,exports.setOperatorContract=i.w,exports.supportsInterfaceContract=i.p,exports.symbolContract=n.h,exports.totalSupplyContract=i.T,exports.underlyingContract=i.g,exports.unwrapContract=i.E,exports.unwrapFromBalanceContract=i.D,exports.web=me,exports.wrapContract=i._;
|
|
514
|
+
`],{type:`application/javascript`}));try{return new Worker(t)}finally{URL.revokeObjectURL(t)}}wireEvents(e){e.onmessage=e=>this.handleResponse(e.data),e.onerror=e=>this.handleWorkerError(e.message),e.onmessageerror=()=>this.handleWorkerMessageError()}postMessage(e,t){e.postMessage(t)}terminateWorker(e){e.terminate()}generateRequestId(){return crypto.randomUUID()}getInitPayload(){let{cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}=this.config;return{type:`INIT`,payload:{env:`web`,cdnUrl:e,chains:t,csrfToken:n,integrity:r,thread:i}}}async updateCsrf(e){await this.sendRequest(`UPDATE_CSRF`,{csrfToken:e})}};function he(e){return{type:`web`,createWorker:t=>new me({cdnUrl:`https://cdn.zama.org/relayer-sdk-js/0.4.2/relayer-sdk-js.umd.cjs`,chains:t,csrfToken:e?.security?.getCsrfToken?.()??``,integrity:e?.security?.integrityCheck===!1?void 0:`114438b01d518b53a447fa3e8bfbe6e71031cb42ac43219bb9f53488456fdfa4bbc8989628366d436e68f6526c7647eb`,logger:e?.logger,thread:e?.threads}),createRelayer:(t,n)=>new le({chain:t,worker:n,...e})}}function ge(){return{type:`cleartext`,createRelayer:e=>{if(!e.executorAddress)throw new t.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 o.t(e)}}}function _e(t){return e.t(t.signer,t.provider,t)}var ve=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,c.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,c.getAddress)(e)}:${(0,c.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))}},ye=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 y(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 be(e){a.N(e,`Stored credentials`),a.P(e.publicKey,`credentials.publicKey`),a.O(e.contractAddresses,`credentials.contractAddresses`);for(let t of e.contractAddresses)a.A(typeof t==`string`&&(0,c.isAddress)(t,{strict:!1}),`Expected each contractAddress to be a valid hex address`);a.N(e.encryptedPrivateKey,`credentials.encryptedPrivateKey`),a.P(e.encryptedPrivateKey.iv,`encryptedPrivateKey.iv`),a.P(e.encryptedPrivateKey.ciphertext,`encryptedPrivateKey.ciphertext`),a.A(typeof e.startTimestamp==`number`,`Expected credentials.startTimestamp to be a number`),a.A(typeof e.durationDays==`number`,`Expected credentials.durationDays to be a number`)}function xe(e){be(e);let t=e;a.A(typeof t.delegatorAddress==`string`&&(0,c.isAddress)(t.delegatorAddress,{strict:!1}),`Expected credentials.delegatorAddress to be a valid address`),a.A(typeof t.delegateAddress==`string`&&(0,c.isAddress)(t.delegateAddress,{strict:!1}),`Expected credentials.delegateAddress to be a valid address`),a.A(typeof t.startTimestamp==`number`,`Expected startTimestamp to be a number`),a.A(typeof t.durationDays==`number`,`Expected durationDays to be a number`)}function T(e){return Math.floor(Date.now()/1e3)<e.startTimestamp+e.durationDays*86400}function E(e,t){let n=new Set(t.map(e=>(0,c.getAddress)(e))),r=new Set(e.map(e=>(0,c.getAddress)(e)));return n.isSubsetOf(r)}function D(e,t){return T(e)?E(e.contractAddresses,t):!1}function O(e){return[...new Set(e.map(e=>(0,c.getAddress)(e)))].toSorted()}async function k(...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 Se=class{#e;constructor(e){this.#e=e}#t(e){a.N(e,`Session entry`),a.P(e.signature,`session.signature`),a.A(typeof e.createdAt==`number`,`Expected session.createdAt to be a number`),a.A(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}},A=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 Se(e.sessionStorage),this.crypto=new ye,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:e,contracts:r,createKey:i,createFn:o}){this.emit({type:n.r.CredentialsLoading,contractAddresses:r});try{let t=await this.storage.get(e);if(t){this.assertEncrypted(t);let i=await this.sessionSignatures.get(e);if(i)if(this.sessionSignatures.isExpired(i))await this.sessionSignatures.delete(e),this.emit({type:n.r.SessionExpired,reason:`ttl`});else{let a=await this.decryptCredentials(t,i.signature);if(D(a,r))return this.emit({type:n.r.CredentialsCached,contractAddresses:r}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),a;if(T(a))return this.#a({key:e,credentials:a,requiredContracts:r});this.emit({type:n.r.CredentialsExpired,contractAddresses:r})}if(T(t)){if(E(t.contractAddresses,r)){let i=await this.signForContracts(t,t.contractAddresses);await this.sessionSignatures.set({key:e,signature:i,ttl:this.sessionTTL});let a=await this.decryptCredentials(t,i);return this.emit({type:n.r.CredentialsCached,contractAddresses:r}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),a}let i=await this.signForContracts(t,t.contractAddresses),a=await this.decryptCredentials(t,i);return this.#a({key:e,credentials:a,requiredContracts:r})}this.emit({type:n.r.CredentialsExpired,contractAddresses:r})}}catch(r){if(r instanceof t.r)throw r;console.warn(`[zama-sdk] Credential resolution failed, recreating:`,r),this.emit({type:n.r.CredentialsCorrupted,error:a.L(r)}),await this.#s(e)}return(!this.#t||this.#n!==i)&&(this.#n=i,this.#t=o().then(e=>(this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e)).finally(()=>{this.#t=null,this.#n=null})),this.#t}async checkExpired(e,t){try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),!D(n,t?[t]:[])):!1}catch(e){return console.warn(`[zama-sdk] isExpired check failed, treating as expired:`,e),!0}}async revokeSession(e,t){await this.sessionSignatures.delete(e),this.clearCaches(),this.emit({type:n.r.CredentialsRevoked,...t?{contractAddresses:t}:{}})}async checkAllowed(e,t){if(t.length===0)return!1;let n=await this.sessionSignatures.get(e);if(n===null||this.sessionSignatures.isExpired(n))return!1;try{let n=await this.storage.get(e);return n?(this.assertEncrypted(n),D(n,t)):!1}catch{return!1}}async clearAll(e){await this.sessionSignatures.delete(e),this.clearCaches(),await this.#s(e)}clearCaches(){this.crypto.clearCache(),this.#i=null}async createCredentials({key:e,contractAddresses:r,createFn:i,errorContext:a}){this.emit({type:n.r.CredentialsCreating,contractAddresses:r});try{let t=await i();return await this.persistCredentials(e,t),await this.sessionSignatures.set({key:e,signature:t.signature,ttl:this.sessionTTL}),this.emit({type:n.r.CredentialsCreated,contractAddresses:r}),t}catch(e){if(e instanceof t.r)throw e;return n.P(e,a)}}async#a({key:e,credentials:t,requiredContracts:r}){if(this.#r){let e=await this.#r;if(E(e.contractAddresses,r))return this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e;t=e}else if(this.#i){let e=this.#i;if(E(e.contractAddresses,r))return this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),e;t=e}let i=this.#o({key:e,credentials:t,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:t,requiredContracts:r}){let i=O([...t.contractAddresses,...r]),a=await this.signForContracts(t,i),o={...t,contractAddresses:i,signature:a};return await this.persistCredentials(e,o),await this.sessionSignatures.set({key:e,signature:a,ttl:this.sessionTTL}),this.emit({type:n.r.CredentialsAllowed,contractAddresses:r}),o}async persistCredentials(e,t){try{let n=await this.encryptCredentials(t);await this.storage.set(e,n)}catch(e){console.warn(`[zama-sdk] Failed to encrypt credentials for persistence:`,e),this.emit({type:n.r.CredentialsPersistFailed,error:a.L(e)})}}async#s(e){try{await this.storage.delete(e)}catch(e){console.warn(`[zama-sdk] Failed to delete credentials:`,e),this.emit({type:n.r.CredentialsPersistFailed,error:a.L(e)})}}};function Ce(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 j=class t extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t){return k((0,c.getAddress)(e),t)}constructor(t){super(t),this.#e=t.relayer,Ce(typeof globalThis<`u`?Reflect.get(globalThis,`chrome`):void 0)&&t.sessionStorage instanceof e.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=O(e),n=await this.#r();return this.resolveCredentials({key:n,contracts:t,createKey:t.join(`,`),createFn:()=>this.create(t)})}async isExpired(e){return this.checkExpired(await this.#r(),e)}async revoke(...e){await this.revokeSession(await this.#r(),e.length>0?e:void 0)}async revokeFor(e){await this.revokeSession(await t.computeStoreKey(e.address,e.chainId))}async isAllowed(e){return this.checkAllowed(await this.#r(),e)}async clear(){await this.clearAll(await this.#r())}async create(e){let t=O(e),n=await this.#r();return this.createCredentials({key:n,contractAddresses:t,createFn:async()=>{let e=await this.#e.generateKeypair(),n=Math.floor(Date.now()/1e3),r=Math.ceil(this.keypairTTL/86400),i=await this.#e.createEIP712(e.publicKey,t,n,r),a=await this.signer.signTypedData(i);return{publicKey:e.publicKey,privateKey:e.privateKey,signature:a,contractAddresses:t,startTimestamp:n,durationDays:r}},errorContext:`Failed to create decrypt credentials`})}assertEncrypted(e){be(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 e=await this.signer.getAddress(),n=await this.signer.getChainId(),r=`${(0,c.getAddress)(e)}:${n}`;if(this.#t&&this.#n===r)return this.#t;let i=await t.computeStoreKey(e,n);return this.#n=r,this.#t=i,i}},M=class e extends A{#e;#t=null;#n=null;static async computeStoreKey(e,t,n){return k((0,c.getAddress)(e),(0,c.getAddress)(t),n)}constructor(e){super(e),this.#e=e.relayer}async allow(e,...t){let n=(0,c.getAddress)(e),r=O(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,c.getAddress)(e)),t)}async revoke(e){await this.revokeSession(await this.#i((0,c.getAddress)(e)))}async isAllowed(e,t){return this.checkAllowed(await this.#i((0,c.getAddress)(e)),t)}async clear(e){await this.clearAll(await this.#i((0,c.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){xe(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,c.getAddress)(n)}:${(0,c.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 N(e){return(0,c.keccak256)((0,c.toBytes)(e))}const P={ConfidentialTransfer:N(`ConfidentialTransfer(address,address,bytes32)`),Wrapped:N(`Wrapped(address,uint256)`),UnwrapRequested:N(`UnwrapRequested(address,bytes32,bytes32)`),UnwrapRequestedLegacy:N(`UnwrapRequested(address,bytes32)`),UnwrapFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrapFinalizedLegacy:N(`UnwrapFinalized(address,bytes32,uint64)`),UnwrappedFinalized:N(`UnwrapFinalized(address,bytes32,bytes32,uint64)`),UnwrappedStarted:N(`UnwrappedStarted(bool,uint256,uint256,address,address,bytes32,bytes32)`)};function F(e){return(0,c.getAddress)(y(e.slice(-40)))}function we(e){return BigInt(e)}function I(e){return e}function L(e,t){let n=2+t*64,r=e.slice(n,n+64);return r.length===64?r:r.padEnd(64,`0`)}function R(e,t){return(0,c.getAddress)(y(L(e,t).slice(-40)))}function z(e,t){return BigInt(`0x`+L(e,t))}function Te(e,t){return BigInt(`0x`+L(e,t))!==0n}function B(e,t){return y(L(e,t))}function Ee(e){return e.topics[0]!==P.ConfidentialTransfer||e.topics.length<4?null:{eventName:`ConfidentialTransfer`,from:F(e.topics[1]),to:F(e.topics[2]),encryptedAmountHandle:I(e.topics[3])}}function V(e){return e.topics[0]!==P.Wrapped||e.topics.length<2?null:{eventName:`Wrapped`,to:F(e.topics[1]),amountIn:z(e.data,0)}}function H(e){return e.topics[0]===P.UnwrapRequested?e.topics.length<3?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0)}:e.topics[0]===P.UnwrapRequestedLegacy?e.topics.length<2?null:{eventName:`UnwrapRequested`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0)}:null}function U(e){return e.topics[0]===P.UnwrapFinalized?e.topics.length<3?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),unwrapRequestId:I(e.topics[2]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:e.topics[0]===P.UnwrapFinalizedLegacy?e.topics.length<2?null:{eventName:`UnwrapFinalized`,receiver:F(e.topics[1]),encryptedAmount:B(e.data,0),cleartextAmount:z(e.data,1)}:null}function De(e){let t=U(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function Oe(e){if(e.topics[0]!==P.UnwrapFinalizedLegacy)return null;let t=U(e);return t?{...t,eventName:`UnwrappedFinalized`}:null}function ke(e){return e.topics[0]!==P.UnwrappedStarted||e.topics.length<4?null:{eventName:`UnwrappedStarted`,requestId:we(e.topics[1]),txId:we(e.topics[2]),to:F(e.topics[3]),returnVal:Te(e.data,0),refund:R(e.data,1),requestedAmount:B(e.data,2),burnAmount:B(e.data,3)}}function Ae(e){return Ee(e)??V(e)??H(e)??Oe(e)??U(e)??ke(e)}function je(e){let t=[];for(let n of e){let e=Ae(n);e&&t.push(e)}return t}function Me(e){for(let t of e){let e=H(t);if(e)return e}return null}function Ne(e){for(let t of e){let e=V(t);if(e)return e}return null}const Pe=[P.ConfidentialTransfer,P.Wrapped,P.UnwrapRequested,P.UnwrapRequestedLegacy,P.UnwrapFinalized,P.UnwrapFinalizedLegacy,P.UnwrappedStarted],W={DelegatedForUserDecryption:N(`DelegatedForUserDecryption(address,address,address,uint64,uint64,uint64)`),RevokedDelegationForUserDecryption:N(`RevokedDelegationForUserDecryption(address,address,address,uint64,uint64)`)};function G(e){return e.topics[0]!==W.DelegatedForUserDecryption||e.topics.length<3?null:{eventName:`DelegatedForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2),newExpirationDate:z(e.data,3)}}function K(e){return e.topics[0]!==W.RevokedDelegationForUserDecryption||e.topics.length<3?null:{eventName:`RevokedDelegationForUserDecryption`,delegator:F(e.topics[1]),delegate:F(e.topics[2]),contractAddress:R(e.data,0),delegationCounter:z(e.data,1),oldExpirationDate:z(e.data,2)}}function Fe(e){return G(e)??K(e)}function Ie(e){let t=[];for(let n of e){let e=Fe(n);e&&t.push(e)}return t}function Le(e){for(let t of e){let e=G(t);if(e)return e}return null}function Re(e){for(let t of e){let e=K(t);if(e)return e}return null}const ze=[W.DelegatedForUserDecryption,W.RevokedDelegationForUserDecryption];var Be=class e extends n.t{static ZERO_ADDRESS=`0x0000000000000000000000000000000000000000`;wrapper;#e;#t=null;constructor(e,t,n){super(e,t),this.wrapper=n?(0,c.getAddress)(n):this.address}async#n(){return this.#e===void 0?(this.#t||=this.sdk.provider.readContract(a.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(e,i,o){let s=this.sdk.requireSigner(`confidentialTransfer`);await this.sdk.requireChainAlignment(`confidentialTransfer`);let{skipBalanceCheck:l=!1,onEncryptComplete:d,onTransferSubmitted:f}=o??{},p=(0,c.getAddress)(e);l||await this.#i(i);let m,h,g=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:m,inputProof:h}=await this.sdk.relayer.encrypt({values:[{value:i,type:`euint64`}],contractAddress:this.address,userAddress:await s.getAddress()}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-g}),q(()=>d?.())}catch(e){throw this.emit({type:n.r.EncryptError,error:a.L(e),durationMs:Date.now()-g}),e instanceof t.r?e:new r.n(`Failed to encrypt transfer amount`,{cause:e})}if(m.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await s.writeContract(a.b(this.address,p,m[0],h));return this.emit({type:n.r.TransferSubmitted,txHash:e}),q(()=>f?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`transfer`,error:a.L(e)}),e instanceof t.r?e:new u(`Transfer transaction failed`,{cause:e})}}async confidentialTransferFrom(e,i,o,s){let l=this.sdk.requireSigner(`confidentialTransferFrom`);await this.sdk.requireChainAlignment(`confidentialTransferFrom`);let d=(0,c.getAddress)(e),f=(0,c.getAddress)(i),p,m,h=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:p,inputProof:m}=await this.sdk.relayer.encrypt({values:[{value:o,type:`euint64`}],contractAddress:this.address,userAddress:d}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-h}),q(()=>s?.onEncryptComplete?.())}catch(e){throw this.emit({type:n.r.EncryptError,error:a.L(e),durationMs:Date.now()-h}),e instanceof t.r?e:new r.n(`Failed to encrypt transferFrom amount`,{cause:e})}if(p.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await l.writeContract(a.x(this.address,d,f,p[0],m));return this.emit({type:n.r.TransferFromSubmitted,txHash:e}),q(()=>s?.onTransferSubmitted?.(e)),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`transferFrom`,error:a.L(e)}),e instanceof t.r?e:new u(`TransferFrom transaction failed`,{cause:e})}}async approve(e,r){let i=this.sdk.requireSigner(`approve`);await this.sdk.requireChainAlignment(`approve`);let o=(0,c.getAddress)(e);try{let e=await i.writeContract(a.w(this.address,o,r));return this.emit({type:n.r.ApproveSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`approve`,error:a.L(e)}),e instanceof t.r?e:new l(`Operator approval failed`,{cause:e})}}async isApproved(e,t){return this.sdk.provider.readContract(a.S(this.address,(0,c.getAddress)(t),(0,c.getAddress)(e)))}async shield(e,r){let i=this.sdk.requireSigner(`shield`);await this.sdk.requireChainAlignment(`shield`);let o=await this.#n(),s;try{let e=await i.getAddress();s=await this.sdk.provider.readContract(n.d(o,e))}catch(e){throw e instanceof t.r?e:new h(`Could not read ERC-20 balance for shield validation (token: ${o})`,{cause:a.L(e)})}if(s<e)throw new p(`Insufficient ERC-20 balance: requested ${e}, available ${s} (token: ${o})`,{requested:e,available:s,token:o});let l=r?.approvalStrategy??`exact`;l!==`skip`&&await this.#o(e,l===`max`,r);try{let t=r?.to?(0,c.getAddress)(r.to):await i.getAddress(),o=await i.writeContract(a._(this.wrapper,t,e));return this.emit({type:n.r.ShieldSubmitted,txHash:o}),q(()=>r?.onShieldSubmitted?.(o)),{txHash:o,receipt:await this.sdk.provider.waitForTransactionReceipt(o)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`shield`,error:a.L(e)}),e instanceof t.r?e:new u(`Shield transaction failed`,{cause:e})}}async unwrap(e){let i=this.sdk.requireSigner(`unwrap`);await this.sdk.requireChainAlignment(`unwrap`);let o=await i.getAddress(),s,c,l=Date.now();try{this.emit({type:n.r.EncryptStart}),{handles:s,inputProof:c}=await this.sdk.relayer.encrypt({values:[{value:e,type:`euint64`}],contractAddress:this.wrapper,userAddress:o}),this.emit({type:n.r.EncryptEnd,durationMs:Date.now()-l})}catch(e){throw this.emit({type:n.r.EncryptError,error:a.L(e),durationMs:Date.now()-l}),e instanceof t.r?e:new r.n(`Failed to encrypt unshield amount`,{cause:e})}if(s.length===0)throw new r.n(`Encryption returned no handles`);try{let e=await i.writeContract(a.E(this.address,o,o,s[0],c));return this.emit({type:n.r.UnwrapSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`unwrap`,error:a.L(e)}),e instanceof t.r?e:new u(`Unshield transaction failed`,{cause:e})}}async unwrapAll(){let e=this.sdk.requireSigner(`unwrapAll`);await this.sdk.requireChainAlignment(`unwrapAll`);let i=await e.getAddress(),o=await this.readConfidentialBalanceOf(i);if(n._(o))throw new r.t(`Cannot unshield: balance is zero`);try{let t=await e.writeContract(a.D(this.address,i,i,o));return this.emit({type:n.r.UnwrapSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`unwrap`,error:a.L(e)}),e instanceof t.r?e:new u(`Unshield-all transaction failed`,{cause:e})}}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(e){let r=this.sdk.requireSigner(`finalizeUnwrap`);await this.sdk.requireChainAlignment(`finalizeUnwrap`);let i=await this.sdk.publicDecrypt([e]),o=i.clearValues[e];a.k(o,`finalizeUnwrap: clearValue`);try{let t=await r.writeContract(a.m(this.wrapper,e,o,i.decryptionProof));return this.emit({type:n.r.FinalizeUnwrapSubmitted,txHash:t}),{txHash:t,receipt:await this.sdk.provider.waitForTransactionReceipt(t)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`finalizeUnwrap`,error:a.L(e)}),e instanceof t.r?e:new u(`Failed to finalize unshield`,{cause:e})}}async approveUnderlying(e){let r=this.sdk.requireSigner(`approveUnderlying`);await this.sdk.requireChainAlignment(`approveUnderlying`);let i=await this.#n(),o=e??2n**256n-1n;try{if(o>0n){let e=await r.getAddress();await this.sdk.provider.readContract(n.l(i,e,this.wrapper))>0n&&await r.writeContract(n.u(i,this.wrapper,0n))}let e=await r.writeContract(n.u(i,this.wrapper,o));return this.emit({type:n.r.ApproveUnderlyingSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`approveUnderlying`,error:a.L(e)}),e instanceof t.r?e:new l(`ERC-20 approval failed`,{cause:e})}}async delegateDecryption({delegateAddress:e,expirationDate:r}){let i=this.sdk.requireSigner(`delegateDecryption`);if(await this.sdk.requireChainAlignment(`delegateDecryption`),r&&r.getTime()<Date.now()+36e5)throw new n.C(`Expiration date must be at least 1 hour in the future`);let o=(0,c.getAddress)(e),s=await i.getAddress();if(o===(0,c.getAddress)(s))throw new n.O(`Cannot delegate to yourself (delegate === msg.sender).`);if(o===this.address)throw new n.S(`Delegate address cannot be the same as the contract address (${this.address}).`);let l=await this.getAclAddress(),d=r?BigInt(Math.floor(r.getTime()/1e3)):n.i,f;try{f=await this.getDelegationExpiry({delegatorAddress:s,delegateAddress:o})}catch{f=-1n}if(f===d)throw new n.T(`The new expiration date (${d}) is the same as the current one. No on-chain change needed.`);try{let e=await i.writeContract(n.a(l,o,this.address,d));return this.emit({type:n.r.DelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`delegateDecryption`,error:a.L(e)}),e instanceof t.r?e:v(e)||new u(`Delegation transaction failed`,{cause:e})}}async revokeDelegation({delegateAddress:e}){let r=this.sdk.requireSigner(`revokeDelegation`);await this.sdk.requireChainAlignment(`revokeDelegation`);let i=(0,c.getAddress)(e),o=await r.getAddress(),s=await this.getAclAddress(),l;try{l=await this.getDelegationExpiry({delegatorAddress:o,delegateAddress:i})}catch{l=1n}if(l===0n)throw new n.E(`No active delegation found for delegate ${i} on contract ${this.address}.`);try{let e=await r.writeContract(n.c(s,i,this.address));return this.emit({type:n.r.RevokeDelegationSubmitted,txHash:e}),{txHash:e,receipt:await this.sdk.provider.waitForTransactionReceipt(e)}}catch(e){throw this.emit({type:n.r.TransactionError,operation:`revokeDelegation`,error:a.L(e)}),e instanceof t.r?e:v(e)||new u(`Revoke delegation transaction failed`,{cause:e})}}static async batchDelegateDecryption({tokens:t,delegateAddress:n,expirationDate:r}){return e.#r(t,e=>e.delegateDecryption({delegateAddress:n,expirationDate:r}),`Delegation failed`)}static async batchRevokeDelegation({tokens:t,delegateAddress:n}){return e.#r(t,e=>e.revokeDelegation({delegateAddress:n}),`Revoke delegation failed`)}static async#r(e,n,r){let i=new Map;for(let a=0;a<e.length;a++)try{i.set(e[a].address,await n(e[a]))}catch(n){n instanceof t.r?i.set(e[a].address,n):i.set(e[a].address,new u(r,{cause:n}))}return i}async#i(e){if(e===0n)return;let n;try{let e=this.sdk.requireSigner(`assertConfidentialBalance`);n=await this.balanceOf(await e.getAddress())}catch(e){throw e instanceof t.r?e:new m(`Balance validation failed (token: ${this.address})`,{cause:e})}if(n<e)throw new f(`Insufficient confidential balance: requested ${e}, available ${n} (token: ${this.address})`,{requested:e,available:n,token:this.address})}async#a(e,r,i){this.emit({type:n.r.UnshieldPhase1Submitted,txHash:e,operationId:r});let a;try{a=await this.sdk.provider.waitForTransactionReceipt(e)}catch(e){throw e instanceof t.r?e:new u(`Failed to get unshield receipt`,{cause:e})}let o=Me(a.logs);if(!o)throw new u(`No UnwrapRequested event found in unshield receipt`);this.emit({type:n.r.UnshieldPhase2Started,operationId:r}),q(()=>i?.onFinalizing?.());let s=await this.finalizeUnwrap(o.unwrapRequestId??o.encryptedAmount);return this.emit({type:n.r.UnshieldPhase2Submitted,txHash:s.txHash,operationId:r}),q(()=>i?.onFinalizeSubmitted?.(s.txHash)),s}async#o(e,r,i){let a=this.sdk.requireSigner(`approveUnderlying`),o=await this.#n(),s=await a.getAddress(),c=await this.sdk.provider.readContract(n.l(o,s,this.wrapper));if(!(c>=e))try{if(c>0n){let e=await a.writeContract(n.u(o,this.wrapper,0n));await this.sdk.provider.waitForTransactionReceipt(e)}let t=r?2n**256n-1n:e,s=await a.writeContract(n.u(o,this.wrapper,t));this.emit({type:n.r.ApproveUnderlyingSubmitted,txHash:s}),q(()=>i?.onApprovalSubmitted?.(s)),await this.sdk.provider.waitForTransactionReceipt(s)}catch(e){throw e instanceof t.r?e:new l(`ERC-20 approval failed`,{cause:e})}}};function q(e){try{e()}catch(e){console.warn(`[zama-sdk] Callback threw:`,e)}}const Ve={[s.a.id]:s.a.registryAddress,[s.o.id]:s.o.registryAddress,[s.i.id]:s.i.registryAddress},J=300*1e3;var Y=class{provider;#e;#t;#n=new Map;constructor(e){this.provider=e.provider,this.#e=Object.assign({},Ve,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 e=await this.provider.getChainId(),n=this.#e[e];if(!n)throw new t.t(`No wrappers registry address configured for chain ${e}.\nPass a registryAddresses entry for this chain.`);return(0,c.getAddress)(n)}async listPairs(e={}){let n=e.page??1,r=e.pageSize??100,i=e.metadata??!1;if(n<1)throw new t.t(`page must be >= 1, got ${n}`);if(r<1)throw new t.t(`pageSize must be >= 1, got ${r}`);let o=await this.getRegistryAddress(),s=`total:${o}`,c=this.#r(s);if(c===void 0){let e=await this.provider.readContract(a.a(o));c=this.#i(s,Number(e))}let l=BigInt((n-1)*r),u=l+BigInt(r)>BigInt(c)?BigInt(c):l+BigInt(r);if(l>=BigInt(c))return{items:[],total:c,page:n,pageSize:r};let d=`slice:${o}:${l}:${u}`,f=this.#r(d);if(f===void 0){let e=await this.provider.readContract(a.o(o,l,u));f=this.#i(d,[...e])}if(!i)return{items:f,total:c,page:n,pageSize:r};let p=`metadata:${o}:${l}:${u}`,m=this.#r(p);if(m===void 0){let e=await Promise.allSettled(f.map(e=>this.#a(e))),t=e.some(e=>e.status===`rejected`),n=e.map((e,t)=>e.status===`fulfilled`?e.value:Object.assign({},f[t],{metadataFailed:!0,underlying:{name:`Unknown`,symbol:`???`,decimals:0,totalSupply:0n},confidential:{name:`Unknown`,symbol:`???`,decimals:0}}));m=this.#i(p,n,t?J:void 0)}return{items:m,total:c,page:n,pageSize:r}}async#a(e){let[t,r,i,a,o,s,c]=await Promise.all([this.provider.readContract(n.m(e.tokenAddress)),this.provider.readContract(n.h(e.tokenAddress)),this.provider.readContract(n.f(e.tokenAddress)),this.provider.readContract(n.p(e.tokenAddress)),this.provider.readContract(n.m(e.confidentialTokenAddress)),this.provider.readContract(n.h(e.confidentialTokenAddress)),this.provider.readContract(n.f(e.confidentialTokenAddress))]);return{...e,underlying:{name:t,symbol:r,decimals:i,totalSupply:a},confidential:{name:o,symbol:s,decimals:c}}}async getConfidentialToken(e){let t=await this.getRegistryAddress(),n=(0,c.getAddress)(e),r=`ct:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[o,s]=await this.provider.readContract(a.t(t,n));return s===c.zeroAddress?this.#i(r,null,J):this.#i(r,{confidentialTokenAddress:s,isValid:o})}async getUnderlyingToken(e){let t=await this.getRegistryAddress(),n=(0,c.getAddress)(e),r=`ut:${t}:${n}`,i=this.#r(r);if(i!==void 0)return i;let[o,s]=await this.provider.readContract(a.n(t,n));return s===c.zeroAddress?this.#i(r,null,J):this.#i(r,{tokenAddress:s,isValid:o})}async getTokenPairs(){let e=await this.getRegistryAddress();return this.provider.readContract(a.i(e))}async getTokenPairsLength(){let e=await this.getRegistryAddress();return this.provider.readContract(a.a(e))}async getTokenPairsSlice(e,t){let n=await this.getRegistryAddress();return this.provider.readContract(a.o(n,e,t))}async getTokenPair(e){let t=await this.getRegistryAddress();return this.provider.readContract(a.r(t,e))}async getConfidentialTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(a.t(t,(0,c.getAddress)(e)))}async getTokenAddress(e){let t=await this.getRegistryAddress();return this.provider.readContract(a.n(t,(0,c.getAddress)(e)))}async isConfidentialTokenValid(e){let t=await this.getRegistryAddress();return this.provider.readContract(a.s(t,(0,c.getAddress)(e)))}};const X=365*86400;async function Z(e,t){try{await t()}catch(t){console.warn(`[zama-sdk] ${e} failed:`,t)}}var He=class{relayer;provider;signer;storage;sessionStorage;credentials;delegatedCredentials;cache;registry;#e;#t;#n=new Set;#r;constructor(t){this.relayer=t.relayer,this.provider=t.provider,this.signer=t.signer,this.storage=t.storage,this.sessionStorage=t.sessionStorage??new e.i,this.cache=new ve(t.storage),this.#t=t.onEvent??function(){};let n={};for(let e of t.chains??[])e.registryAddress&&(n[e.id]=e.registryAddress);Object.assign(n,t.registryAddresses),this.registry=new Y({provider:this.provider,registryTTL:t.registryTTL,registryAddresses:n}),this.#e=t.registryTTL;let r=(()=>{let e=t.keypairTTL??2592e3;if(e<=0||isNaN(e))throw Error(`keypairTTL must be a positive number (seconds)`);return e>X?(console.warn(`[zama-sdk] keypairTTL (${e}s) exceeds the fhevm maximum of 365 days (${X}s); capping to ${X}s.`),X):e})();if(t.signer){let e={relayer:this.relayer,signer:t.signer,storage:this.storage,sessionStorage:this.sessionStorage,keypairTTL:r,sessionTTL:t.sessionTTL??2592e3,onEvent:this.#t};this.credentials=new j(e),this.delegatedCredentials=new M(e),this.#r=t.signer.subscribe?.(e=>{this.#i(e)})}else this.credentials=void 0,this.delegatedCredentials=void 0}requireSigner(e){if(!this.signer)throw new i.t(e);return this.signer}requireCredentials(e){if(!this.credentials)throw new i.t(e);return this.credentials}requireDelegatedCredentials(e){if(!this.delegatedCredentials)throw new i.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 d({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 n.t(this,e)}createToken(e,t){return new Be(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 t=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,c.getAddress)(e.contractAddress)})),o={},s=[];for(let e of i)n._(e.handle)?o[e.handle]=0n:s.push(e);if(s.length===0)return o;let l=await t.getAddress(),u=[];for(let e of s){let t=await this.cache.get(l,e.contractAddress,e.handle);t===null?u.push(e):o[e.handle]=t}if(u.length===0)return o;let d=await r.allow(...new Set(i.map(e=>e.contractAddress))),f=new Map;for(let e of u){let t=f.get(e.contractAddress);t?t.push(e.handle):f.set(e.contractAddress,[e.handle])}let p=Date.now(),m=u.map(e=>e.handle);try{this.emitEvent({type:n.r.DecryptStart,handles:m}),await n.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:l,startTimestamp:d.startTimestamp,durationDays:d.durationDays});for(let[t,r]of Object.entries(n))o[t]=r,await this.cache.set(l,e,t,r)}),5);let e={};for(let t of m){let n=o[t];n!==void 0&&(e[t]=n)}return this.emitEvent({type:n.r.DecryptEnd,durationMs:Date.now()-p,handles:m,result:e}),o}catch(e){throw this.emitEvent({type:n.r.DecryptError,error:a.L(e),durationMs:Date.now()-p,handles:m}),n.v(e,`Failed to decrypt handles`)}}async publicDecrypt(e){if(e.length===0)return{clearValues:{},decryptionProof:`0x`,abiEncodedClearValues:`0x`};try{return await this.relayer.publicDecrypt(e)}catch(e){throw n.v(e,`Public decryption failed`)}}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 Ue(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 We(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 Ge(e,t){return(await Ke(e,t))?.unwrapTxHash??null}async function Ke(e,t){return Ue(await e.get(Q(t)))}async function qe(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 Je=new $;exports.ACL_TOPICS=ze,exports.AclPausedError=n.y,exports.AclTopics=W,exports.ApprovalFailedError=l,exports.BalanceCheckUnavailableError=m,exports.ChainMismatchError=d,exports.ChromeSessionStorage=$,exports.ConfigurationError=t.t,exports.CredentialsManager=j,exports.DecryptCache=ve,exports.DecryptionFailedError=r.t,exports.DefaultRegistryAddresses=Ve,exports.DelegatedCredentialsManager=M,exports.DelegationContractIsSelfError=n.b,exports.DelegationCooldownError=n.x,exports.DelegationDelegateEqualsContractError=n.S,exports.DelegationExpirationTooSoonError=n.C,exports.DelegationExpiredError=n.w,exports.DelegationExpiryUnchangedError=n.T,exports.DelegationNotFoundError=n.E,exports.DelegationNotPropagatedError=n.D,exports.DelegationSelfNotAllowedError=n.O,exports.ERC20ReadFailedError=h,exports.ERC7984_INTERFACE_ID=a.c,exports.ERC7984_WRAPPER_INTERFACE_ID=a.l,exports.ERC7984_WRAPPER_INTERFACE_ID_LEGACY=a.u,exports.EncryptionFailedError=r.n,exports.IndexedDBStorage=e.o,exports.InsufficientConfidentialBalanceError=f,exports.InsufficientERC20BalanceError=p,exports.InvalidKeypairError=n.k,exports.KeypairExpiredError=n.A,exports.MemoryStorage=e.i,exports.NoCiphertextError=n.j,exports.ReadonlyToken=n.t,exports.RelayerRequestFailedError=t.n,exports.RelayerWeb=le,exports.SignerRequiredError=i.t,exports.SigningFailedError=n.M,exports.SigningRejectedError=n.N,exports.TOKEN_TOPICS=Pe,exports.Token=Be,exports.Topics=P,exports.TransactionRevertedError=u,exports.WrappersRegistry=Y,exports.ZERO_HANDLE=n.g,exports.ZamaError=t.r,exports.ZamaErrorCode=t.i,exports.ZamaSDK=He,exports.ZamaSDKEvents=n.r,exports.allowanceContract=n.l,exports.anvil=s.t,exports.approveContract=n.u,exports.balanceOfContract=n.d,exports.buildZamaConfig=e.t,exports.chains=s.n,exports.chromeSessionStorage=Je,exports.clearPendingUnshield=qe,exports.cleartext=ge,exports.confidentialBalanceOfContract=a.v,exports.confidentialTotalSupplyContract=a.y,exports.confidentialTransferContract=a.b,exports.confidentialTransferFromContract=a.x,exports.createConfig=_e,exports.decimalsContract=n.f,exports.decodeAclEvent=Fe,exports.decodeAclEvents=Ie,exports.decodeConfidentialTransfer=Ee,exports.decodeDelegatedForUserDecryption=G,exports.decodeOnChainEvent=Ae,exports.decodeOnChainEvents=je,exports.decodeRevokedDelegationForUserDecryption=K,exports.decodeUnwrapFinalized=U,exports.decodeUnwrapRequested=H,exports.decodeUnwrappedFinalized=De,exports.decodeUnwrappedStarted=ke,exports.decodeWrapped=V,exports.delegateForUserDecryptionContract=n.a,exports.finalizeUnwrapContract=a.m,exports.findDelegatedForUserDecryption=Le,exports.findRevokedDelegationForUserDecryption=Re,exports.findUnwrapRequested=Me,exports.findWrapped=Ne,exports.getConfidentialTokenAddressContract=a.t,exports.getDelegationExpiryContract=n.o,exports.getTokenAddressContract=a.n,exports.getTokenPairContract=a.r,exports.getTokenPairsContract=a.i,exports.getTokenPairsLengthContract=a.a,exports.getTokenPairsSliceContract=a.o,exports.hardhat=s.r,exports.hoodi=s.i,exports.indexedDBStorage=e.s,exports.inferredTotalSupplyContract=a.h,exports.isConfidentialTokenContract=a.d,exports.isConfidentialTokenValidContract=a.s,exports.isConfidentialWrapperContract=a.f,exports.isHandleDelegatedContract=n.s,exports.isOperatorContract=a.S,exports.isZeroHandle=n._,exports.loadPendingUnshield=Ge,exports.loadPendingUnshieldRequest=Ke,exports.mainnet=s.a,exports.matchAclRevert=v,exports.matchZamaError=t.a,exports.memoryStorage=e.a,exports.nameContract=n.m,exports.rateContract=a.C,exports.resolveChainRelayers=e.n,exports.resolveStorage=e.r,exports.revokeDelegationContract=n.c,exports.savePendingUnshield=We,exports.sepolia=s.o,exports.setOperatorContract=a.w,exports.supportsInterfaceContract=a.p,exports.symbolContract=n.h,exports.totalSupplyContract=a.T,exports.underlyingContract=a.g,exports.unwrapContract=a.E,exports.unwrapFromBalanceContract=a.D,exports.web=he,exports.wrapContract=a._;
|
|
515
515
|
//# sourceMappingURL=index.cjs.map
|