@zama-fhe/sdk 3.5.0-alpha.8 → 3.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/cjs/base-signer.cjs +1 -1
- package/dist/cjs/base-signer.cjs.map +1 -1
- package/dist/cjs/chains/index.cjs +1 -1
- package/dist/cjs/chains.cjs +1 -1
- package/dist/cjs/chains.cjs.map +1 -1
- package/dist/cjs/fhevm-relayer.cjs +1 -1
- package/dist/cjs/fhevm-relayer.cjs.map +1 -1
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/node/index.cjs +1 -1
- package/dist/cjs/query/index.cjs +1 -1
- package/dist/cjs/query/index.cjs.map +1 -1
- package/dist/cjs/relayer.cjs +1 -1
- package/dist/cjs/relayer.cjs.map +1 -1
- package/dist/cjs/sdk-events.cjs +1 -1
- package/dist/cjs/sdk-events.cjs.map +1 -1
- package/dist/cjs/token.cjs +1 -1
- package/dist/cjs/token.cjs.map +1 -1
- package/dist/esm/{base-signer-CMcmGqJV.d.ts → base-signer-DttMQOKx.d.ts} +2 -2
- package/dist/esm/base-signer-GatxEuGN.js +2 -0
- package/dist/esm/base-signer-GatxEuGN.js.map +1 -0
- package/dist/esm/chains/index.d.ts +2 -2
- package/dist/esm/chains/index.js +1 -1
- package/dist/esm/chains-ByyCdrrd.js +2 -0
- package/dist/esm/chains-ByyCdrrd.js.map +1 -0
- package/dist/esm/cleartext/index.d.ts +2 -2
- package/dist/esm/cleartext/index.js +1 -1
- package/dist/esm/{cleartext-BWibWaD8.js → cleartext-BwzD7uJa.js} +2 -2
- package/dist/esm/{cleartext-BWibWaD8.js.map → cleartext-BwzD7uJa.js.map} +1 -1
- package/dist/esm/{cleartext-BEXEaFxR.d.ts → cleartext-Di1DDxqa.d.ts} +2 -2
- package/dist/esm/ethers/index.d.ts +4 -4
- package/dist/esm/ethers/index.js +1 -1
- package/dist/esm/fhevm-relayer-CTwFyl0v.js +2 -0
- package/dist/esm/{fhevm-relayer-BTab4pc9.js.map → fhevm-relayer-CTwFyl0v.js.map} +1 -1
- package/dist/esm/{index-DE92igPK.d.ts → index-C4xKY5Fw.d.ts} +4 -4
- package/dist/esm/{index-CLhOMZFu.d.ts → index-COrLsVKC.d.ts} +159 -10
- package/dist/esm/{index-B0XC8EfF.d.ts → index-ijgDL4IC.d.ts} +18 -3
- package/dist/esm/index.d.ts +8 -8
- package/dist/esm/index.js +1 -1
- package/dist/esm/index.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/index.js.map +1 -1
- package/dist/esm/query/index.d.ts +20 -5
- package/dist/esm/query/index.js +1 -1
- package/dist/esm/query/index.js.map +1 -1
- package/dist/esm/relayer-DC1OKWzW.js +2 -0
- package/dist/esm/relayer-DC1OKWzW.js.map +1 -0
- package/dist/esm/sdk-events-B1sUunjZ.js +2 -0
- package/dist/esm/sdk-events-B1sUunjZ.js.map +1 -0
- package/dist/esm/token-DOYtYc7P.js +2 -0
- package/dist/esm/token-DOYtYc7P.js.map +1 -0
- package/dist/esm/{types-CViUZmxp.d.ts → types-BSRyQBTx.d.ts} +3 -3
- package/dist/esm/{types-CDEEf-TG.d.ts → types-BxJzdNur.d.ts} +3 -3
- package/dist/esm/{types-GctypAZx.d.ts → types-CuDiV0Wy.d.ts} +15 -2
- package/dist/esm/viem/index.d.ts +4 -4
- package/dist/esm/viem/index.js +1 -1
- package/dist/esm/web/index.d.ts +1 -1
- package/dist/esm/web/index.js +1 -1
- package/package.json +2 -2
- package/dist/esm/base-signer-h-9UxLXW.js +0 -2
- package/dist/esm/base-signer-h-9UxLXW.js.map +0 -1
- package/dist/esm/chains-DkH7vYTf.js +0 -2
- package/dist/esm/chains-DkH7vYTf.js.map +0 -1
- package/dist/esm/fhevm-relayer-BTab4pc9.js +0 -2
- package/dist/esm/relayer-RDPkM3cB.js +0 -2
- package/dist/esm/relayer-RDPkM3cB.js.map +0 -1
- package/dist/esm/sdk-events-lFxSy5Zf.js +0 -2
- package/dist/esm/sdk-events-lFxSy5Zf.js.map +0 -1
- package/dist/esm/token-B0hgYraH.js +0 -2
- package/dist/esm/token-B0hgYraH.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"base-signer-h-9UxLXW.js","names":["#dbName","#dbVersion","#storeName","#db","#dbPromise","#withTransaction","#getDB","#map","#chains","#relayers","#chainId","#secret","#baseKey","#importBaseKey","#generator","#storage","#ttl","#logger","#scope","#derivationSecret","#pending","#epoch","#readByKey","#identityKey","#identity","#failLoudly","#discard","#discardIfExpired","#recover","#getOrCreateByKey","#storage","#logger","#deleteScope","#untrackScope","#trackScope","#readIndex","#vault","#store","#router","#signer","#permitTTL","#logger","#scope","#requireSigner","#signPermit","#logger","#prefix","#addresses","#ttlMs","#cache","#getCached","#setCached","#pairWithMetadata","#listeners","#snapshot","#resolved","#emit","#disposed"],"sources":["../../src/storage/indexeddb-storage.ts","../../src/storage/memory-storage.ts","../../src/config/resolve.ts","../../src/chains/router.ts","../../src/schemas/primitives.ts","../../src/credentials/keypair-wrapping.ts","../../src/credentials/utils.ts","../../src/credentials/schemas.ts","../../src/credentials/keypair-entry-codec.ts","../../src/credentials/storage-keys.ts","../../src/credentials/keypair-vault.ts","../../src/credentials/permissions.ts","../../src/credentials/permission-store.ts","../../src/credentials/credential-service.ts","../../src/services/logger-service.ts","../../src/validation.ts","../../src/wrappers-registry.ts","../../src/config/build.ts","../../src/signer/wallet-account-store.ts","../../src/signer/base-signer.ts"],"sourcesContent":["\"use client\";\n\nimport type { GenericStorage } from \"../types\";\n\n/**\n * IndexedDB-backed {@link GenericStorage}.\n *\n * Stores keypair and permit objects keyed by a hashed wallet address. The\n * SDK delegates security to the storage backend — values are persisted\n * verbatim with no SDK-layer encryption.\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 // Another tab upgraded the DB; close our handle so it can proceed.\n // Informational only and self-healing, so emit nothing to the console.\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 /**\n * Retrieve a value by key.\n * @returns The stored value, or `null` if the key does not exist.\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 /** Store a value under the given key, overwriting any existing entry. */\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 /** Remove the entry for the given key (no-op if absent). */\n async delete(key: string): Promise<void> {\n await this.#withTransaction<void>(\"readwrite\", (store) => store.delete(key));\n }\n\n /** Remove all stored entries. */\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 /**\n * Retrieve a value by key.\n * @returns The stored value, or `null` if the key does not exist.\n */\n async get<T = unknown>(key: string): Promise<T | null> {\n return (this.#map.get(key) as T) ?? null;\n }\n\n /** Store a value under the given key, overwriting any existing entry. */\n async set<T = unknown>(key: string, value: T): Promise<void> {\n this.#map.set(key, value);\n }\n\n /** Remove the entry for the given key (no-op if absent). */\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\n/** @internal */\nexport function resolveStorage(\n storage: GenericStorage | undefined = getDefaultStorage(),\n permitStorage: GenericStorage | undefined = storage,\n): { storage: GenericStorage; permitStorage: GenericStorage } {\n return { storage, permitStorage };\n}\n\n// ── Chain relayer resolution ────────────────────────────────────────────────\n\n/** @internal */\nexport interface ResolvedChainRelayer {\n chain: FheChain;\n relayerConfig: RelayerConfig;\n}\n\n/** @internal */\nexport function resolveChainRelayers(\n chains: readonly FheChain[],\n relayers: Readonly<Record<number, RelayerConfig>>,\n): Map<number, ResolvedChainRelayer> {\n const chainMap = new Map<number, FheChain>(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 chain = 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 (!chain) {\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, { chain, relayerConfig });\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 { FheChain } from \"./types\";\nimport { resolveChainRelayers } from \"../config/resolve\";\nimport type { RelayerConfig } from \"../config/types\";\nimport { ConfigurationError } from \"../errors\";\nimport type { RelayerSDK } from \"../relayer/types\";\n\n/**\n * Multichain router. Owns chain management (chains / chain / switchChain) and\n * hands out the single-chain {@link RelayerSDK} backend for the currently active\n * chain via {@link ChainRouter.relayer}. Builds one backend per chain from its\n * {@link RelayerConfig}.\n *\n * @internal\n */\nexport class ChainRouter {\n readonly #chains: Map<number, FheChain>;\n readonly #relayers: Map<number, RelayerSDK>;\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 // One backend per chain. A shared config object can yield the same backend\n // instance for several chains (createRelayer decides); terminate() dedupes.\n const relayers = new Map<number, RelayerSDK>();\n for (const [chainId, { relayerConfig, chain }] of resolveChainRelayers(chains, configs)) {\n relayers.set(chainId, relayerConfig.createRelayer(chain));\n }\n this.#relayers = relayers;\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 if (chain === undefined) {\n throw new ConfigurationError(\n `Chain ${this.#chainId} is not configured. Add it to the chains array.`,\n );\n }\n return chain;\n }\n\n /**\n * Point the router at `chainId`. The active chain follows the wallet even when\n * that chain has no configured backend: the {@link chain} / {@link relayer}\n * getters throw a {@link ConfigurationError} for an unconfigured chain, so an\n * unsupported chain fails loudly at the next operation rather than silently\n * routing to the previously active chain (which would encrypt against, and\n * sign an EIP-712 decryption permit for, the wrong chain's domain and ACL).\n * Switching back to a configured chain restores service.\n */\n switchChain(chainId: number): void {\n this.#chainId = chainId;\n }\n\n /** The single-chain backend for the currently active chain. */\n get relayer(): RelayerSDK {\n const relayer = this.#relayers.get(this.chain.id);\n if (relayer === undefined) {\n throw new ConfigurationError(\n `No relayer configured for chain ${this.#chainId}. Add it to the relayers object.`,\n );\n }\n return relayer;\n }\n}\n","import { type Address, getAddress, isAddress, isHex, type Hex } from \"viem\";\nimport { z } from \"zod/mini\";\n\ndeclare const checksummedTag: unique symbol;\n\n/** An EVM address that has been put through `getAddress` (EIP-55 checksum form). */\nexport type ChecksummedAddress = Address & { readonly [checksummedTag]: true };\n\n/** Stamp the brand on an arbitrary `Address` after normalizing it. */\nexport function checksum(value: Address): ChecksummedAddress {\n return getAddress(value) as ChecksummedAddress;\n}\n\n/** `0x`-prefixed hex string. */\nexport const hex = z.custom<Hex>(\n (v) => typeof v === \"string\" && isHex(v, { strict: true }),\n \"expected 0x-prefixed hex string\",\n);\n\n/** Validates an EVM address string. Output type is `Address` (`` `0x${string}` ``). */\nexport const evmAddress = z.custom<Address>(\n (v) => typeof v === \"string\" && isAddress(v, { strict: false }),\n \"expected EVM address\",\n);\n\n/** Validates and EIP-55 checksums an EVM address. Output is {@link ChecksummedAddress}. */\nexport const checksummedAddress = z.pipe(evmAddress, z.transform(checksum));\n\n/** Non-negative integer Unix timestamp in seconds. */\nexport const unixSeconds = z.int().check(z.nonnegative());\n\n/** Positive integer count of seconds (e.g. a TTL). */\nexport const positiveSeconds = z.int().check(z.positive());\n\n/** Non-negative integer count of seconds (e.g. a cache TTL where 0 disables caching). */\nexport const nonNegativeSeconds = z.int().check(z.nonnegative());\n\n/** Positive integer count of days (e.g. a permit duration). */\nexport const positiveDays = z.int().check(z.positive());\n\n/** Positive integer EVM chain ID. */\nexport const chainId = z.int().check(z.positive());\n","import { toBytes, toHex, type Hex } from \"viem\";\n\n/**\n * Parameters of wrapping scheme v1, in one place so the crypto path and the on-disk\n * format can never disagree about them. The `info` tag is versioned so a future scheme\n * can run alongside this one without silently reusing (and confusing) its derived keys,\n * and `version` is persisted with every entry so a future scheme is detectable on disk\n * instead of reading as corruption.\n */\nexport const WRAPPING_SCHEME_V1 = {\n version: 1,\n info: \"zama-sdk-keypair-wrapping-v1\",\n /** AES-GCM recommended nonce size. Generated fresh per wrap, never reused. */\n ivLengthBytes: 12,\n /** AES-GCM authentication tag size; any valid ciphertext is at least this long. */\n tagLengthBytes: 16,\n} as const;\n\nconst AES_KEY_LENGTH_BITS = 256;\n\n/** On-disk shape of a wrapped private key. Public key and timestamps are stored alongside, unwrapped. */\nexport interface WrappedPrivateKey {\n wrappedPrivateKey: Hex;\n iv: Hex;\n}\n\n/**\n * The sibling plaintext fields stored alongside the ciphertext. Bound as AES-GCM\n * additional authenticated data so a storage-level attacker who can't decrypt the\n * private key also can't silently tamper with these — e.g. mismatching `publicKey`\n * against the wrapped private key, or extending `expiresAt` past its intended TTL.\n */\nexport interface WrappedPrivateKeyMetadata {\n publicKey: Hex;\n createdAt: number;\n expiresAt: number;\n tkmsVersion?: string;\n}\n\n// `new Uint8Array(bytes)` copies into a fresh, plain ArrayBuffer-backed view — needed\n// because a consumer-supplied Uint8Array (or viem's `toBytes()` output) is typed as\n// `Uint8Array<ArrayBufferLike>`, which TS's DOM lib no longer accepts as `BufferSource`\n// (it admits `SharedArrayBuffer`, which `crypto.subtle` doesn't).\nfunction toBufferSource(bytes: Uint8Array): Uint8Array<ArrayBuffer> {\n return new Uint8Array(bytes);\n}\n\n/** Deterministic byte encoding of {@link WrappedPrivateKeyMetadata} for use as AES-GCM AAD.\n * An absent `tkmsVersion` encodes as `null`, distinct from any string value. */\nfunction metadataAad(metadata: WrappedPrivateKeyMetadata): Uint8Array<ArrayBuffer> {\n return toBufferSource(\n new TextEncoder().encode(\n JSON.stringify([\n metadata.publicKey,\n metadata.createdAt,\n metadata.expiresAt,\n metadata.tkmsVersion ?? null,\n ]),\n ),\n );\n}\n\nfunction ikmBytes(secret: string | Uint8Array): Uint8Array<ArrayBuffer> {\n return typeof secret === \"string\" ? new TextEncoder().encode(secret) : toBufferSource(secret);\n}\n\n/**\n * Owns the SDK's copy of a derivation secret and hands out the memoized, non-extractable\n * HKDF base key derived from it. Takes ownership of a `Uint8Array` secret: it is zeroized\n * once the import succeeds, which shortens the raw secret's lifetime and keeps it out of\n * accidental readback paths. It does not prevent exfiltration, since the returned key\n * stays usable for deriving.\n */\nexport class DerivationSecretHolder {\n #secret: string | Uint8Array | undefined;\n #baseKey: Promise<CryptoKey> | undefined;\n\n constructor(secret: string | Uint8Array) {\n this.#secret = secret;\n }\n\n async baseKey(): Promise<CryptoKey> {\n // Memoized so concurrent callers share one import, which consumes #secret exactly once.\n this.#baseKey ??= this.#importBaseKey(this.#secret as string | Uint8Array);\n return this.#baseKey;\n }\n\n async #importBaseKey(secret: string | Uint8Array): Promise<CryptoKey> {\n const ikm = ikmBytes(secret);\n const key = await crypto.subtle.importKey(\"raw\", ikm, \"HKDF\", false, [\"deriveKey\"]);\n ikm.fill(0);\n if (secret instanceof Uint8Array) {\n secret.fill(0);\n }\n // Strings can't be zeroized, so dropping the reference is all that's available.\n this.#secret = undefined;\n return key;\n }\n}\n\n/**\n * Derive a non-extractable AES-256-GCM key from the derivation secret's base key, bound\n * to `identity` (the same signer-address-or-scope identity used for storage keying — see\n * {@link TransportKeyPairVault} — not the storage key string itself, so a future rename\n * of storage-key formatting can never silently change already-wrapped keys).\n *\n * Non-extractable by construction: the raw derived key bytes can never be read back out\n * by any caller, this module included.\n */\nasync function deriveWrappingKey(\n derivationSecret: DerivationSecretHolder,\n identity: string,\n): Promise<CryptoKey> {\n const ikmKey = await derivationSecret.baseKey();\n return crypto.subtle.deriveKey(\n {\n name: \"HKDF\",\n hash: \"SHA-256\",\n salt: new TextEncoder().encode(identity),\n info: new TextEncoder().encode(WRAPPING_SCHEME_V1.info),\n },\n ikmKey,\n { name: \"AES-GCM\", length: AES_KEY_LENGTH_BITS },\n false,\n [\"encrypt\", \"decrypt\"],\n );\n}\n\n/** Wrap a private key for at-rest storage. Generates a fresh random IV every call. */\nexport async function wrapPrivateKey(\n privateKey: Hex,\n derivationSecret: DerivationSecretHolder,\n identity: string,\n metadata: WrappedPrivateKeyMetadata,\n): Promise<WrappedPrivateKey> {\n const key = await deriveWrappingKey(derivationSecret, identity);\n const iv = crypto.getRandomValues(new Uint8Array(WRAPPING_SCHEME_V1.ivLengthBytes));\n const ciphertext = await crypto.subtle.encrypt(\n { name: \"AES-GCM\", iv, additionalData: metadataAad(metadata) },\n key,\n toBufferSource(toBytes(privateKey)),\n );\n return { wrappedPrivateKey: toHex(new Uint8Array(ciphertext)), iv: toHex(iv) };\n}\n\n/**\n * Unwrap a private key. `metadata` must be the exact sibling fields stored alongside\n * the ciphertext — mismatching any of them (or a mismatched `derivationSecret`, or a\n * tampered ciphertext) fails the same way, closed.\n *\n * @throws a `DOMException` named `\"OperationError\"` on any AES-GCM authentication\n * failure: wrong `derivationSecret`, tampered ciphertext, or tampered `metadata`.\n * Any other thrown error (e.g. `crypto.subtle` unavailable) is a distinct failure\n * mode and must not be conflated with an authentication mismatch.\n */\nexport async function unwrapPrivateKey(\n wrapped: WrappedPrivateKey,\n derivationSecret: DerivationSecretHolder,\n identity: string,\n metadata: WrappedPrivateKeyMetadata,\n): Promise<Hex> {\n const key = await deriveWrappingKey(derivationSecret, identity);\n const plaintext = await crypto.subtle.decrypt(\n {\n name: \"AES-GCM\",\n iv: toBufferSource(toBytes(wrapped.iv)),\n additionalData: metadataAad(metadata),\n },\n key,\n toBufferSource(toBytes(wrapped.wrappedPrivateKey)),\n );\n return toHex(new Uint8Array(plaintext));\n}\n\n/** True for the specific AES-GCM authentication failure `unwrapPrivateKey` throws on\n * a wrong `derivationSecret`, tampered ciphertext, or tampered metadata — false for\n * anything else (e.g. `crypto.subtle` unavailable), which is not a routine mismatch\n * and should not be handled the same way. Checks `.name` rather than `instanceof\n * DOMException`/`instanceof Error`: those can disagree across realms (e.g. a VM-based\n * test sandbox, or a worker's `crypto.subtle` vs. the main thread's global classes). */\nexport function isUnwrapAuthFailure(error: unknown): boolean {\n return (\n typeof error === \"object\" &&\n error !== null &&\n \"name\" in error &&\n error.name === \"OperationError\"\n );\n}\n","import type { Address } from \"viem\";\nimport { type ChecksummedAddress, checksum } from \"../schemas/primitives\";\nexport { checksum, type ChecksummedAddress };\n\n/** Maximum number of contract addresses a single permit may bind, enforced by the FHE protocol. */\nexport const MAX_CONTRACTS_PER_PERMIT = 10;\n\nexport const SECONDS_PER_DAY = 86400;\n\n/** Current Unix time in whole seconds. */\nexport function nowSeconds(): number {\n return Math.floor(Date.now() / 1000);\n}\n\n/** Deduplicate and sort a list of addresses by their checksummed form. */\nexport function normalizeAddresses(addresses: readonly Address[]): ChecksummedAddress[] {\n return [...new Set(addresses.map(checksum))].sort();\n}\n","import { z } from \"zod/mini\";\nimport {\n checksummedAddress,\n hex,\n positiveDays,\n positiveSeconds,\n unixSeconds,\n} from \"../schemas/primitives\";\nimport { MAX_CONTRACTS_PER_PERMIT, SECONDS_PER_DAY } from \"./utils\";\n\nconst transportKeyPairTTLError = \"transportKeyPairTTL must be a positive integer number of seconds\";\nconst permitTTLError = \"permitTTL must be a positive integer number of days\";\nconst transportKeyPairScopeError = \"transportKeyPairScope must be a non-empty string\";\n/** 256 bits, matching the AES-256 wrapping key HKDF derives from this secret, so the derived key\n * is never weaker than the cipher. A length check can't verify entropy: this is a floor, not a\n * guarantee. */\nexport const MIN_DERIVATION_SECRET_LENGTH_BYTES = 32;\n/** Strings are encoded, so characters carry fewer bits than bytes: 64 covers hex's worst case\n * (4 bits per character), keeping a validated string at or above the same 256-bit floor. */\nexport const MIN_DERIVATION_SECRET_LENGTH_CHARS = 64;\nconst derivationSecretError = `transportKeyPairDerivationSecret must be a Uint8Array of at least ${MIN_DERIVATION_SECRET_LENGTH_BYTES} bytes or a string of at least ${MIN_DERIVATION_SECRET_LENGTH_CHARS} characters (256 bits of entropy): source it from a CSPRNG or secrets manager, not a human-memorable passphrase`;\n\n/** Maximum transportKeyPairTTL accepted by the fhevm ACL contract (365 days, in seconds). */\nexport const MAX_TRANSPORT_KEY_PAIR_TTL_SECONDS = 365 * SECONDS_PER_DAY;\n\n// z.int already rejects NaN, Infinity, and non-integers, so it covers\n// the previous .finite() + .int() combo with a single schema.\nexport const TransportKeyPairTTLSchema = z\n .int({ error: transportKeyPairTTLError })\n .check(\n z.positive({ error: transportKeyPairTTLError }),\n z.maximum(\n MAX_TRANSPORT_KEY_PAIR_TTL_SECONDS,\n `transportKeyPairTTL must not exceed the fhevm ACL maximum of ${MAX_TRANSPORT_KEY_PAIR_TTL_SECONDS}s (365 days)`,\n ),\n );\n\nexport const PermitTTLSchema = z\n .int({ error: permitTTLError })\n .check(z.positive({ error: permitTTLError }));\n\nexport const TransportKeyPairScopeSchema = z\n .string({ error: transportKeyPairScopeError })\n .check(z.minLength(1, transportKeyPairScopeError));\n\nexport const DerivationSecretSchema = z.union(\n [\n z\n .string({ error: derivationSecretError })\n .check(z.minLength(MIN_DERIVATION_SECRET_LENGTH_CHARS, derivationSecretError)),\n z\n .instanceof(Uint8Array, { error: derivationSecretError })\n .check(\n z.refine((v) => v.byteLength >= MIN_DERIVATION_SECRET_LENGTH_BYTES, {\n error: derivationSecretError,\n }),\n ),\n ],\n { error: derivationSecretError },\n);\n\n/** @internal */\nexport const StoredTransportKeyPairSchema = z.object({\n publicKey: hex,\n privateKey: hex,\n createdAt: unixSeconds,\n expiresAt: positiveSeconds,\n tkmsVersion: z.optional(z.string()),\n});\n\nexport const Eip712Schema = z.object({\n domain: z.record(z.string(), z.unknown()),\n primaryType: z.optional(z.string()),\n types: z.record(z.string(), z.array(z.object({ name: z.string(), type: z.string() }))),\n message: z.record(z.string(), z.unknown()),\n});\n\nexport const SerializedPermitSchema = z.object({\n version: z.int().check(z.positive()),\n eip712: Eip712Schema,\n signature: hex,\n signerAddress: checksummedAddress,\n});\n\n/** @internal */\nexport const PermissionSchema = z.object({\n keypairPublicKey: hex,\n contractAddresses: z.array(checksummedAddress).check(z.maxLength(MAX_CONTRACTS_PER_PERMIT)),\n serializedPermit: SerializedPermitSchema,\n startTimestamp: unixSeconds,\n durationDays: positiveDays,\n});\n\nexport const PermissionListSchema = z.array(PermissionSchema);\n\nexport const ScopeIndexSchema = z.array(z.string());\n","/**\n * Single owner of the persisted transport key pair format: what an entry looks like on\n * disk, how a value read back from storage is classified, and how the wrapped shape is\n * encoded and decoded. Everything version-specific lives in a codec descriptor, so a\n * future scheme is added here rather than branched on by every reader.\n */\nimport { z } from \"zod/mini\";\nimport { hex, positiveSeconds, unixSeconds } from \"../schemas/primitives\";\nimport {\n unwrapPrivateKey,\n wrapPrivateKey,\n WRAPPING_SCHEME_V1,\n type DerivationSecretHolder,\n type WrappedPrivateKeyMetadata,\n} from \"./keypair-wrapping\";\nimport { StoredTransportKeyPairSchema } from \"./schemas\";\nimport type { StoredTransportKeyPair } from \"./types\";\n\nconst wrappingVersionError = \"wrappingVersion must be a wrapping scheme this SDK can read\";\nconst ivLengthError = `iv must be a ${WRAPPING_SCHEME_V1.ivLengthBytes}-byte hex string`;\nconst wrappedPrivateKeyLengthError = `wrappedPrivateKey must be a whole number of bytes and at least ${WRAPPING_SCHEME_V1.tagLengthBytes} bytes (the AES-GCM authentication tag)`;\n\nfunction hexByteLength(v: string): number {\n return (v.length - 2) / 2;\n}\n\n/**\n * On-disk shape when `transportKeyPairDerivationSecret` is configured, distinct from the\n * plaintext shape every caller outside the vault still sees. `publicKey` is never\n * sensitive and stays unwrapped; only the private key half is encrypted.\n */\nconst WrappedEntryV1Schema = z.object({\n wrappingVersion: z.literal(WRAPPING_SCHEME_V1.version, { error: wrappingVersionError }),\n publicKey: hex,\n // Length-checked, not just shape-checked: a truncated ciphertext/IV (e.g. from a buggy\n // custom GenericStorage adapter) would otherwise reach crypto.subtle.decrypt and fail\n // with the same generic OperationError a genuine wrong-secret case does.\n // Even hex length checked first: an odd digit count is a fractional byte count that would\n // clear the minimum (33 digits reads as 16.5 bytes), and viem's toBytes then left-pads it\n // into a plausible-looking ciphertext that only fails at decrypt time.\n wrappedPrivateKey: hex.check(\n z.refine((v) => v.length % 2 === 0 && hexByteLength(v) >= WRAPPING_SCHEME_V1.tagLengthBytes, {\n error: wrappedPrivateKeyLengthError,\n }),\n ),\n iv: hex.check(\n z.refine((v) => hexByteLength(v) === WRAPPING_SCHEME_V1.ivLengthBytes, {\n error: ivLengthError,\n }),\n ),\n createdAt: unixSeconds,\n expiresAt: positiveSeconds,\n tkmsVersion: z.optional(z.string()),\n});\n\n/** @internal */\nexport type WrappedPrivateKeyEntry = z.infer<typeof WrappedEntryV1Schema>;\n\n/** Everything this vault ever hands to `storage.set`. @internal */\nexport type PersistedTransportKeyPair = StoredTransportKeyPair | WrappedPrivateKeyEntry;\n\n/** One wrapping scheme: its identity on disk, its entry schema, and its codec. */\ninterface WrappedEntryCodec {\n readonly version: number;\n readonly schema: z.ZodMiniType<WrappedPrivateKeyEntry>;\n encode(\n keyPair: StoredTransportKeyPair,\n derivationSecret: DerivationSecretHolder,\n identity: string,\n ): Promise<WrappedPrivateKeyEntry>;\n decode(\n entry: WrappedPrivateKeyEntry,\n derivationSecret: DerivationSecretHolder,\n identity: string,\n ): Promise<StoredTransportKeyPair>;\n}\n\n/** The sibling plaintext fields bound as AES-GCM additional authenticated data. */\nfunction metadataOf(entry: {\n publicKey: WrappedPrivateKeyMetadata[\"publicKey\"];\n createdAt: number;\n expiresAt: number;\n tkmsVersion?: string;\n}): WrappedPrivateKeyMetadata {\n const metadata: WrappedPrivateKeyMetadata = {\n publicKey: entry.publicKey,\n createdAt: entry.createdAt,\n expiresAt: entry.expiresAt,\n };\n if (entry.tkmsVersion) {\n metadata.tkmsVersion = entry.tkmsVersion;\n }\n return metadata;\n}\n\nconst CODEC_V1: WrappedEntryCodec = {\n version: WRAPPING_SCHEME_V1.version,\n schema: WrappedEntryV1Schema,\n async encode(keyPair, derivationSecret, identity) {\n const { wrappedPrivateKey, iv } = await wrapPrivateKey(\n keyPair.privateKey,\n derivationSecret,\n identity,\n metadataOf(keyPair),\n );\n const entry: WrappedPrivateKeyEntry = {\n wrappingVersion: WRAPPING_SCHEME_V1.version,\n publicKey: keyPair.publicKey,\n wrappedPrivateKey,\n iv,\n createdAt: keyPair.createdAt,\n expiresAt: keyPair.expiresAt,\n };\n if (keyPair.tkmsVersion) {\n entry.tkmsVersion = keyPair.tkmsVersion;\n }\n return entry;\n },\n async decode(entry, derivationSecret, identity) {\n const privateKey = await unwrapPrivateKey(\n { wrappedPrivateKey: entry.wrappedPrivateKey, iv: entry.iv },\n derivationSecret,\n identity,\n metadataOf(entry),\n );\n const keyPair: StoredTransportKeyPair = {\n publicKey: entry.publicKey,\n privateKey,\n createdAt: entry.createdAt,\n expiresAt: entry.expiresAt,\n };\n if (entry.tkmsVersion) {\n keyPair.tkmsVersion = entry.tkmsVersion;\n }\n return keyPair;\n },\n};\n\n/** Every scheme this build can read, keyed by the version persisted with the entry. */\nconst CODECS = new Map<number, WrappedEntryCodec>([[CODEC_V1.version, CODEC_V1]]);\n\n/** The scheme new entries are written under. */\nconst WRITER_CODEC = CODEC_V1;\n\n/**\n * How a raw stored value reads under this build's knowledge of the format. The three\n * failure kinds are distinct because they call for different operator action: an\n * unsupported version needs a build that knows it, a corrupt wrapped entry still holds\n * someone's ciphertext, and an unrecognized value holds nothing worth protecting.\n */\nexport type ClassifiedEntry =\n | { readonly kind: \"plaintext\"; readonly keyPair: StoredTransportKeyPair }\n | {\n readonly kind: \"wrapped\";\n readonly expiresAt: number;\n readonly decode: (\n derivationSecret: DerivationSecretHolder,\n identity: string,\n ) => Promise<StoredTransportKeyPair>;\n }\n | { readonly kind: \"unsupported-version\"; readonly version: unknown }\n | { readonly kind: \"corrupt-wrapped\" }\n | { readonly kind: \"unrecognized\" };\n\n/**\n * Version-agnostic probe for a value that carries a wrapped private key. Deliberately\n * shallow and independent of any codec: an entry written by a scheme this build cannot\n * read must still be recognized as someone's ciphertext, or it gets regenerated over.\n */\nfunction isWrappedEnvelope(raw: object): boolean {\n const entry = raw as Record<string, unknown>;\n return (\n entry.wrappingVersion !== undefined ||\n (entry.wrappedPrivateKey !== undefined && entry.iv !== undefined)\n );\n}\n\n/** Classify a value read back from storage. Never throws and never decrypts. */\nexport function classifyPersistedEntry(raw: unknown): ClassifiedEntry {\n if (typeof raw !== \"object\" || raw === null || !isWrappedEnvelope(raw)) {\n const plaintext = StoredTransportKeyPairSchema.safeParse(raw);\n return plaintext.success\n ? { kind: \"plaintext\", keyPair: plaintext.data }\n : { kind: \"unrecognized\" };\n }\n\n const version = (raw as Record<string, unknown>).wrappingVersion;\n const codec = typeof version === \"number\" ? CODECS.get(version) : undefined;\n if (codec === undefined) {\n return { kind: \"unsupported-version\", version };\n }\n\n const parsed = codec.schema.safeParse(raw);\n if (!parsed.success) {\n return { kind: \"corrupt-wrapped\" };\n }\n const entry = parsed.data;\n return {\n kind: \"wrapped\",\n expiresAt: entry.expiresAt,\n decode: (derivationSecret, identity) => codec.decode(entry, derivationSecret, identity),\n };\n}\n\n/** Encode a key pair under the scheme this build writes. */\nexport function encodeWrappedEntry(\n keyPair: StoredTransportKeyPair,\n derivationSecret: DerivationSecretHolder,\n identity: string,\n): Promise<WrappedPrivateKeyEntry> {\n return WRITER_CODEC.encode(keyPair, derivationSecret, identity);\n}\n","import type { ChecksummedAddress } from \"../schemas/primitives\";\n\nexport interface PermissionScope {\n signerAddress: ChecksummedAddress;\n chainId: number;\n delegatorAddress: ChecksummedAddress;\n}\n\nexport function transportKeyPairStorageKey(signerAddress: ChecksummedAddress): string {\n // The \"keypair:\" prefix is intentionally preserved for back-compat with already-persisted entries.\n return `keypair:${signerAddress}`;\n}\n\n/**\n * Storage key for a scope-shared transport key pair (opt-in, B2B2C/WaaS operators).\n * Namespaced under \"keypair:scope:\" so it can never collide with a per-signer key,\n * whose suffix is always a checksummed `0x`-address.\n */\nexport function transportKeyPairScopeStorageKey(scope: string): string {\n return `keypair:scope:${scope}`;\n}\n\nexport function permissionScopeKey(scope: PermissionScope): string {\n return `permits:${scope.signerAddress}:${scope.chainId}:${scope.delegatorAddress}`;\n}\n\nexport function permissionIndexKey(signerAddress: ChecksummedAddress): string {\n return `permits-index:${signerAddress}`;\n}\n","import type { SerializeTransportKeyPairReturnType } from \"@fhevm/sdk/actions/chain\";\nimport { KeyWrappingError } from \"../errors/credential\";\nimport type { ChecksummedAddress } from \"../schemas/primitives\";\nimport type { GenericLogger, GenericStorage } from \"../types\";\nimport { swallow } from \"../utils/swallow\";\nimport {\n classifyPersistedEntry,\n encodeWrappedEntry,\n type PersistedTransportKeyPair,\n} from \"./keypair-entry-codec\";\nimport { isUnwrapAuthFailure, type DerivationSecretHolder } from \"./keypair-wrapping\";\nimport { transportKeyPairScopeStorageKey, transportKeyPairStorageKey } from \"./storage-keys\";\nimport type { StoredTransportKeyPair } from \"./types\";\nimport { nowSeconds } from \"./utils\";\n\ninterface TransportKeyPairVaultConfig {\n generator: () => Promise<SerializeTransportKeyPairReturnType>;\n storage: GenericStorage;\n /** Transport key pair lifetime in seconds. Pre-validated by the caller. */\n ttl: number;\n /** SDK-wide logger for best-effort storage diagnostics. */\n logger: GenericLogger;\n /**\n * Opt-in shared-tenant scope (B2B2C/WaaS). When set, every signer configured with\n * this scope reads/creates the *same* key pair instead of one per signer address.\n * Undefined preserves the default per-signer behavior.\n */\n scope?: string;\n /**\n * Opt-in at-rest wrapping for headless contexts with no secure storage backend to\n * delegate to (CLI tools, bare-metal agents, local dev). When set, the private key\n * half is encrypted before every `storage.set()` and decrypted after every\n * `storage.get()` — transparently, at this vault's storage boundary only. Undefined\n * preserves the default: plaintext, security delegated to the storage backend.\n */\n derivationSecret?: DerivationSecretHolder;\n}\n\nfunction scopeIdentity(scope: string): string {\n return `scope:${scope}`;\n}\n\n/** Why a stored entry can't be served to this instance. */\ntype RecoveryReason =\n | \"wrapped-without-secret\"\n | \"unwrapped-under-secret\"\n | \"unwrap-failed\"\n | \"corrupt-wrapped\";\n\n/** Operator-facing diagnostic for a scope whose shared entry is left in place. */\nfunction scopedFailureMessage(reason: RecoveryReason, scope: string): string {\n const messages: Record<RecoveryReason, string> = {\n \"wrapped-without-secret\":\n `Transport key pair for scope \"${scope}\" is wrapped, but this instance has no ` +\n \"transportKeyPairDerivationSecret configured. Every instance sharing this scope must use \" +\n \"the same transportKeyPairDerivationSecret; once they do, call \" +\n \"permits.revokeTransportKeyPair() to rotate the entry.\",\n \"unwrapped-under-secret\":\n `Transport key pair for scope \"${scope}\" is stored unwrapped, but this instance is ` +\n \"configured with a transportKeyPairDerivationSecret. A peer instance sharing this scope \" +\n \"is running without the secret: configure the same transportKeyPairDerivationSecret \" +\n \"everywhere, then call permits.revokeTransportKeyPair() to migrate the scope to a \" +\n \"wrapped entry.\",\n \"unwrap-failed\":\n `Transport key pair for scope \"${scope}\" failed to unwrap. This usually means another ` +\n \"instance created it with a different transportKeyPairDerivationSecret: every instance \" +\n \"sharing this scope must use the same secret. It can also mean the stored entry is \" +\n \"corrupted.\",\n \"corrupt-wrapped\":\n `Transport key pair for scope \"${scope}\" is wrapped but structurally invalid: the stored ` +\n \"iv or ciphertext is not a shape this wrapping scheme can produce. This usually means \" +\n \"the stored entry is corrupted, or instances sharing this scope are running mismatched \" +\n \"wrapping-scheme versions.\",\n };\n return messages[reason];\n}\n\n/**\n * Operator-facing diagnostic for a per-signer entry this instance can't read at all: a\n * missing secret is a deployment mistake far more often than an intentional downgrade,\n * and self-healing would drop at-rest wrapping without anyone noticing.\n */\nconst UNSCOPED_WRAPPED_WITHOUT_SECRET_MESSAGE =\n \"Transport key pair for this signer is wrapped, but this instance has no \" +\n \"transportKeyPairDerivationSecret configured. Configure the same \" +\n \"transportKeyPairDerivationSecret the entry was written with. To downgrade to plaintext \" +\n \"at rest on purpose, discard the stored entry first by calling \" +\n \"permits.clear(), then run without the secret.\";\n\n/** Discard reason for a per-signer entry, which self-heals instead of failing loudly. */\nconst UNSCOPED_FAILURE_REASONS: Record<\n Exclude<RecoveryReason, \"wrapped-without-secret\">,\n string\n> = {\n \"unwrapped-under-secret\":\n \"unwrapped transport key pair entry found while a transportKeyPairDerivationSecret is configured\",\n \"unwrap-failed\":\n \"transport key pair entry failed to unwrap (wrong transportKeyPairDerivationSecret?)\",\n \"corrupt-wrapped\": \"structurally invalid wrapped transport key pair entry\",\n};\n\nfunction unsupportedVersionMessage(version: unknown, scope: string | undefined): string {\n const label =\n typeof version === \"number\"\n ? `wrappingVersion ${version}`\n : \"no wrappingVersion this build recognizes\";\n const target = scope !== undefined ? `for scope \"${scope}\"` : \"for this signer\";\n const remedy =\n scope !== undefined\n ? \"run a build that supports it everywhere, or call permits.revokeTransportKeyPair() to rotate the scope\"\n : \"run a build that supports it, or call permits.clear() to discard the entry deliberately\";\n return (\n `Transport key pair ${target} was written under a wrapping scheme this SDK build cannot ` +\n `read (${label}). The entry is preserved instead of regenerated, since an instance that ` +\n `understands the scheme may still be using it: ${remedy}.`\n );\n}\n\n/**\n * Identity-scoped, chain-independent vault for ML-KEM transport key pairs.\n *\n * One transport key pair per signer address by default; the key pair survives chain\n * switches and permit revocations. When `scope` is configured, reads/creates key\n * off the shared scope identity instead of the signer address. {@link clear} always\n * targets the per-signer key regardless of scope — an individual signer's teardown must\n * never delete a scope's shared key pair. Only {@link clearScope} can do that.\n *\n * When `derivationSecret` is configured, the private key half is wrapped at rest. That is\n * invisible to every method here and to every caller outside this class: `getOrCreate`/\n * `readStored` always return the plaintext {@link StoredTransportKeyPair} shape regardless\n * of how the entry is actually stored on disk.\n */\nexport class TransportKeyPairVault {\n readonly #generator: () => Promise<SerializeTransportKeyPairReturnType>;\n readonly #storage: GenericStorage;\n readonly #ttl: number;\n readonly #logger: GenericLogger;\n readonly #scope: string | undefined;\n readonly #derivationSecret: DerivationSecretHolder | undefined;\n readonly #pending = new Map<string, Promise<StoredTransportKeyPair>>();\n /**\n * Per-key generation counter, bumped by {@link clearScope}. Lets a generation that\n * was already in flight when a rotation happened detect it's stale once its\n * `#generator()` round trip completes, so it skips persisting a key that would\n * silently resurrect the one the rotation just deleted.\n */\n readonly #epoch = new Map<string, number>();\n\n constructor(config: TransportKeyPairVaultConfig) {\n this.#generator = config.generator;\n this.#storage = config.storage;\n this.#ttl = config.ttl;\n this.#logger = config.logger;\n this.#scope = config.scope;\n this.#derivationSecret = config.derivationSecret;\n }\n\n /**\n * Identity a wrapped key is bound to (the HKDF salt). Prefixed by kind so a scope\n * named after a checksummed address can never derive the same wrapping key as that\n * signer. Deliberately not the storage key string: that prefix is a storage-layer\n * detail, and renaming it must never stop already-wrapped keys from decrypting.\n */\n #identity(signerAddress: ChecksummedAddress): string {\n return this.#scope !== undefined ? scopeIdentity(this.#scope) : `signer:${signerAddress}`;\n }\n\n /** Storage key for reads/creates: the shared scope key when configured, else the per-signer key. */\n #identityKey(signerAddress: ChecksummedAddress): string {\n return this.#scope !== undefined\n ? transportKeyPairScopeStorageKey(this.#scope)\n : transportKeyPairStorageKey(signerAddress);\n }\n\n async readStored(signerAddress: ChecksummedAddress): Promise<StoredTransportKeyPair | null> {\n return this.#readByKey(this.#identityKey(signerAddress), this.#identity(signerAddress));\n }\n\n async #readByKey(key: string, identity: string): Promise<StoredTransportKeyPair | null> {\n const raw = await this.#storage.get(key);\n if (raw === null || raw === undefined) {\n return null;\n }\n\n const entry = classifyPersistedEntry(raw);\n if (entry.kind === \"unsupported-version\") {\n // Preserved for every configuration, scoped or not: only a build that knows the\n // scheme can read this ciphertext, and regenerating would destroy it for good.\n throw this.#failLoudly(key, unsupportedVersionMessage(entry.version, this.#scope));\n }\n\n if (entry.kind === \"unrecognized\") {\n // Neither shape holds a key pair any instance could read, so there is nothing to\n // protect by keeping it, scope or no scope.\n await this.#discard(key, \"malformed transport key pair entry\");\n return null;\n }\n\n const derivationSecret = this.#derivationSecret;\n if (derivationSecret === undefined) {\n if (entry.kind === \"plaintext\") {\n return (await this.#discardIfExpired(key, entry.keyPair.expiresAt)) ? null : entry.keyPair;\n }\n // Corrupt or intact, a wrapped entry is unreadable here for the same single reason.\n return this.#recover(key, \"wrapped-without-secret\");\n }\n\n if (entry.kind === \"plaintext\") {\n return this.#recover(key, \"unwrapped-under-secret\");\n }\n if (entry.kind === \"corrupt-wrapped\") {\n return this.#recover(key, \"corrupt-wrapped\");\n }\n if (await this.#discardIfExpired(key, entry.expiresAt)) {\n return null;\n }\n\n try {\n return await entry.decode(derivationSecret, identity);\n } catch (error) {\n if (!isUnwrapAuthFailure(error)) {\n // Not a wrong secret or a tampered entry but an environment problem (e.g.\n // crypto.subtle unavailable), which must not read as a routine cache miss.\n this.#logger.error(\"transport key pair unwrap failed unexpectedly\", { key, error });\n throw new KeyWrappingError(\"Transport key pair unwrap failed unexpectedly.\", {\n cause: error,\n });\n }\n return this.#recover(key, \"unwrap-failed\", error);\n }\n }\n\n /**\n * The one place that decides what happens to an entry this instance can't serve. A\n * scope's entry is shared, and AES-GCM can't distinguish a peer's valid entry wrapped\n * under a different secret from genuine corruption, so discarding it risks clobbering a\n * key pair the whole cohort is using: scoped vaults fail loudly and leave it in place,\n * unscoped ones self-heal since only this signer is affected. The one unscoped case that\n * also fails loudly is a wrapped entry with no secret configured, where self-healing\n * would turn a missing secret into a silent plaintext downgrade.\n */\n async #recover(key: string, reason: RecoveryReason, cause?: unknown): Promise<null> {\n if (this.#scope !== undefined) {\n throw this.#failLoudly(key, scopedFailureMessage(reason, this.#scope), cause);\n }\n if (reason === \"wrapped-without-secret\") {\n throw this.#failLoudly(key, UNSCOPED_WRAPPED_WITHOUT_SECRET_MESSAGE, cause);\n }\n const discardReason = UNSCOPED_FAILURE_REASONS[reason];\n // Warned, not just discarded: a regenerated entry can silently lose the at-rest\n // wrapping the discarded one had.\n this.#logger.warn(discardReason, { key });\n await this.#discard(key, discardReason);\n return null;\n }\n\n /** Logged where the storage key is still in hand, then thrown for the caller to act on. */\n #failLoudly(key: string, message: string, cause?: unknown): KeyWrappingError {\n this.#logger.error(message, { key });\n return new KeyWrappingError(message, { cause });\n }\n\n /** An entry past its TTL is a cache miss: dropped so the next call regenerates it. */\n async #discardIfExpired(key: string, expiresAt: number): Promise<boolean> {\n if (nowSeconds() < expiresAt) {\n return false;\n }\n await this.#discard(key, \"expired transport key pair entry\");\n return true;\n }\n\n async #discard(key: string, reason: string): Promise<void> {\n this.#logger.debug(\"discarding transport key pair entry\", { key, reason });\n await swallow(\"delete transport key pair entry\", () => this.#storage.delete(key), this.#logger);\n }\n\n /**\n * Return the cached transport key pair, generating and persisting a fresh one if absent or expired.\n *\n * @remarks Deduplicates concurrent calls within this process. Across separate\n * processes/instances sharing a scope, two first-time callers can still race the\n * underlying storage — unlike the per-signer version of this race, the loser here can\n * be a *different* end-user, whose existing permit then gets silently pruned as stale.\n * Pre-warm a scope once via {@link warmScope} before opening concurrent traffic to\n * avoid hitting this with a whole cohort at once.\n *\n * @throws if the stored entry was written under a wrapping scheme this build cannot\n * read, in any configuration: it is preserved rather than regenerated over.\n * {@link KeyWrappingError}\n * @throws if the stored entry is wrapped and no `derivationSecret` is configured, in\n * any configuration: regenerating would downgrade this signer to plaintext at rest\n * without a signal. {@link KeyWrappingError}\n * @throws if `derivationSecret` is configured together with `scope` and the stored\n * entry can't be served (fails to unwrap, or is stored in an unexpected shape),\n * since silently regenerating would overwrite a scope's shared entry that may simply\n * be wrapped under a different (but valid) `derivationSecret` by another instance.\n * The unscoped equivalent self-heals. {@link KeyWrappingError}\n * @throws if wrapping the freshly generated private key fails (e.g. `crypto.subtle`\n * unavailable in this environment). {@link KeyWrappingError}\n */\n async getOrCreate(signerAddress: ChecksummedAddress): Promise<StoredTransportKeyPair> {\n return this.#getOrCreateByKey(this.#identityKey(signerAddress), this.#identity(signerAddress));\n }\n\n /**\n * @param strict - When `true`, a `storage.set` failure during persistence rejects\n * instead of being logged and swallowed. Used by {@link warmScope}, which — like\n * {@link clearScope} — must not resolve successfully while its write silently failed.\n */\n async #getOrCreateByKey(\n key: string,\n identity: string,\n options?: { strict?: boolean },\n ): Promise<StoredTransportKeyPair> {\n const strict = options?.strict ?? false;\n // Keyed on (key, strict), not key alone: a strict caller (warmScope) and a\n // non-strict caller (getOrCreate) can target the same shared scope identity, and\n // must never adopt each other's persistence guarantee — whichever registers first\n // would otherwise silently impose its strictness on the other. See the strict\n // param doc above.\n const pendingKey = `${key}::${strict}`;\n const existing = this.#pending.get(pendingKey);\n if (existing) {\n return existing;\n }\n\n const epochAtStart = this.#epoch.get(key) ?? 0;\n\n const promise = (async () => {\n const cached = await this.#readByKey(key, identity);\n if (cached !== null) {\n return cached;\n }\n const fresh = await this.#generator();\n const createdAt = nowSeconds();\n const expiresAt = createdAt + this.#ttl;\n const stored: StoredTransportKeyPair = {\n publicKey: fresh.publicKey,\n privateKey: fresh.privateKey,\n createdAt,\n expiresAt,\n };\n // Persist the TKMS version so a later parse deserializes the private key\n // under the version it was generated with, surviving a KMS/TKMS rotation.\n if (fresh.tkmsVersion) {\n stored.tkmsVersion = fresh.tkmsVersion;\n }\n\n let entry: PersistedTransportKeyPair = stored;\n if (this.#derivationSecret !== undefined) {\n try {\n entry = await encodeWrappedEntry(stored, this.#derivationSecret, identity);\n } catch (error) {\n const message = \"Failed to wrap the transport private key for at-rest storage.\";\n this.#logger.error(message, { key, error });\n throw new KeyWrappingError(message, { cause: error });\n }\n }\n\n // If a rotation bumped this key's epoch while `#generator()` (and, when\n // derivationSecret is configured, the wrap above) were in flight, this\n // generation started before the rotation and must not persist — doing so would\n // silently resurrect the key the rotation just deleted (see `clearScope`). The\n // freshly generated key pair is still returned to whichever caller triggered this\n // round trip so their in-flight request succeeds; the next access regenerates and\n // persists properly against the new epoch.\n if ((this.#epoch.get(key) ?? 0) === epochAtStart) {\n if (strict) {\n await this.#storage.set(key, entry);\n } else {\n await swallow(\n \"persist transport key pair\",\n () => this.#storage.set(key, entry),\n this.#logger,\n );\n }\n }\n return stored;\n })().finally(() => {\n this.#pending.delete(pendingKey);\n });\n\n this.#pending.set(pendingKey, promise);\n return promise;\n }\n\n /**\n * Delete the stored transport key pair for the given signer address.\n *\n * Always targets the per-signer key, never the shared scope key — even when this\n * vault is configured with a scope. Signer-level teardown (disconnect, revoke) must\n * never take down a shared-tenant key pair; use {@link clearScope} for that.\n *\n * Best-effort: a storage failure is logged and swallowed. Worst case, one signer's\n * stale key lingers until its TTL — a low-stakes, self-correcting outcome.\n */\n async clear(signerAddress: ChecksummedAddress): Promise<void> {\n const key = transportKeyPairStorageKey(signerAddress);\n await swallow(\"delete transport key pair entry\", () => this.#storage.delete(key), this.#logger);\n }\n\n /**\n * Delete the stored key pair for this identity so the next {@link getOrCreate}\n * regenerates it. Unlike {@link clear}, this is **scope-aware** — it targets the\n * shared scope key when a scope is configured, else the per-signer key.\n *\n * The self-heal primitive for a key pair the relayer rejects as invalid (e.g. a\n * TKMS-version mismatch after a KMS rotation, which surfaces as\n * `invalid TransportKeyPairKeyPair`): the stored bytes can no longer be parsed,\n * so dropping and regenerating them is the only recovery. Best-effort — a\n * storage failure is logged and swallowed, so a wedged entry is retried on the\n * next call rather than hard-failing the current one.\n */\n async evict(signerAddress: ChecksummedAddress): Promise<void> {\n const key = this.#identityKey(signerAddress);\n await swallow(\"evict transport key pair entry\", () => this.#storage.delete(key), this.#logger);\n }\n\n /**\n * Delete the shared scope's transport key pair (operator-level rotation).\n *\n * Every permit in the scope embeds the old key pair's public key, so once it's gone,\n * `pruneUnusable` drops all of them as stale on next access — no separate permit\n * cleanup needed. No-op if no scope is configured on this vault.\n *\n * Unlike {@link clear}, this is **not** best-effort: a storage failure propagates\n * instead of being swallowed. This is the primitive operators reach for on suspected\n * key compromise — a caller that gets a resolved promise must be able to trust that\n * the key pair is actually gone, not silently still live because a transient storage\n * error (exactly the kind of failure likely during an incident) was logged and\n * dropped.\n *\n * Also bumps the key's generation epoch *before* deleting, so a `getOrCreate`/\n * `warmScope` generation already in flight for this same scope discards its result\n * instead of persisting it once the round trip completes — otherwise that write would\n * land after this delete and silently resurrect the key this call just removed. This\n * relies on the backing {@link GenericStorage} applying same-key writes in dispatch\n * order — true for `MemoryStorage` and conventional stores, but a custom async\n * adapter without that guarantee could still let an in-flight `set` land after this\n * `delete`.\n */\n async clearScope(): Promise<void> {\n if (this.#scope === undefined) {\n return;\n }\n const key = transportKeyPairScopeStorageKey(this.#scope);\n this.#epoch.set(key, (this.#epoch.get(key) ?? 0) + 1);\n await this.#storage.delete(key);\n }\n\n /**\n * Generate and persist the shared scope's transport key pair if absent — the\n * pre-warm counterpart to {@link clearScope}. No-op if no scope is configured.\n *\n * Unlike {@link getOrCreate}, this needs no signer address at all: a scoped identity\n * never depends on one. Operators use this to warm a scope once, deliberately,\n * before opening concurrent traffic to it — see the class docs on {@link getOrCreate}\n * for why that avoids a thundering-herd race across the whole cohort.\n *\n * Not best-effort: like {@link clearScope}, a `storage.set` failure during persistence\n * propagates instead of being swallowed. A resolved promise here is meant to mean the\n * key pair is actually warmed in shared storage — an operator pre-warming ahead of\n * traffic to avoid the thundering-herd race must be able to trust that, not silently\n * still be exposed to it because a transient write failure was logged and dropped.\n */\n async warmScope(): Promise<void> {\n if (this.#scope === undefined) {\n return;\n }\n await this.#getOrCreateByKey(\n transportKeyPairScopeStorageKey(this.#scope),\n scopeIdentity(this.#scope),\n { strict: true },\n );\n }\n}\n","import type { Hex } from \"viem\";\nimport type { Permission } from \"./types\";\nimport type { ChecksummedAddress } from \"../schemas/primitives\";\nimport { MAX_CONTRACTS_PER_PERMIT, SECONDS_PER_DAY } from \"./utils\";\n\n/** Contracts in `requested` not covered by the signed payload of any permission. */\nexport function uncoveredContracts(\n permissions: readonly Permission[],\n requested: readonly ChecksummedAddress[],\n): ChecksummedAddress[] {\n const covered = new Set(permissions.flatMap((p) => p.contractAddresses));\n return requested.filter((addr) => !covered.has(addr));\n}\n\n/** Split a list of addresses into permit-sized chunks (≤ {@link MAX_CONTRACTS_PER_PERMIT}). */\nexport function chunkContracts(addresses: readonly ChecksummedAddress[]): ChecksummedAddress[][] {\n const chunks: ChecksummedAddress[][] = [];\n for (let i = 0; i < addresses.length; i += MAX_CONTRACTS_PER_PERMIT) {\n chunks.push(addresses.slice(i, i + MAX_CONTRACTS_PER_PERMIT));\n }\n return chunks;\n}\n\n/** Drop permissions that are time-expired or bound to a stale keypair. */\nexport function pruneUnusable(\n permissions: readonly Permission[],\n keypairPublicKey: Hex,\n nowSeconds: number,\n): Permission[] {\n return permissions.filter(\n (p) =>\n p.keypairPublicKey === keypairPublicKey &&\n nowSeconds < p.startTimestamp + p.durationDays * SECONDS_PER_DAY,\n );\n}\n\n/** Drop every permission whose signed payload touches any address in `contracts`. */\nexport function withoutPermitsTouching(\n permissions: readonly Permission[],\n contracts: readonly ChecksummedAddress[],\n): Permission[] {\n const removeSet = new Set(contracts);\n return permissions.filter((p) => !p.contractAddresses.some((a) => removeSet.has(a)));\n}\n\n/** Deduplicate and sort the union of two pre-checksummed address lists. */\nexport function sortedUnion<T extends string>(a: readonly T[], b: readonly T[]): T[] {\n return [...new Set([...a, ...b])].sort();\n}\n\n/**\n * Find the in-scope permit best suited to be widened with `uncovered`.\n *\n * Returns the permit whose `contractAddresses ∪ uncovered` still fits\n * the 10-contract cap and that has the largest overlap with `requested`. Ties\n * broken by most-recent `startTimestamp`. Returns `null` when none fits.\n */\nexport function findPermitToWiden(\n permissions: readonly Permission[],\n uncovered: readonly ChecksummedAddress[],\n requested: readonly ChecksummedAddress[],\n): Permission | null {\n const requestedSet = new Set(requested);\n const feasible = permissions.filter(\n (p) => new Set([...p.contractAddresses, ...uncovered]).size <= MAX_CONTRACTS_PER_PERMIT,\n );\n if (feasible.length === 0) {\n return null;\n }\n\n function overlap(p: Permission) {\n return p.contractAddresses.reduce((n, a) => n + (requestedSet.has(a) ? 1 : 0), 0);\n }\n\n const maxOverlap = Math.max(...feasible.map(overlap));\n const topTier = feasible.filter((p) => overlap(p) === maxOverlap);\n return topTier.reduce((a, b) => (b.startTimestamp > a.startTimestamp ? b : a));\n}\n","import type { Hex } from \"viem\";\nimport type { GenericLogger, GenericStorage } from \"../types\";\nimport { swallow } from \"../utils/swallow\";\nimport { pruneUnusable, withoutPermitsTouching } from \"./permissions\";\nimport { PermissionListSchema, PermissionSchema, ScopeIndexSchema } from \"./schemas\";\nimport { permissionIndexKey, permissionScopeKey, type PermissionScope } from \"./storage-keys\";\nimport type { Permission } from \"./types\";\nimport type { ChecksummedAddress } from \"../schemas/primitives\";\n\nexport type { PermissionScope };\n\ninterface PermissionStoreConfig {\n storage: GenericStorage;\n /** SDK-wide logger for best-effort storage diagnostics. */\n logger: GenericLogger;\n}\n\n/**\n * Chain-scoped, 1-to-many store of EIP-712 permits.\n *\n * Permits are grouped by `(signerAddress, chainId, delegatorAddress)` so that\n * direct (`delegator === signer`) and delegated permits never collide. An\n * auxiliary per-signer index lists every scope so `clearAllForSigner` can\n * cascade across chains and delegators without enumerating storage keys.\n */\nexport class PermissionStore {\n readonly #storage: GenericStorage;\n readonly #logger: GenericLogger;\n\n constructor(config: PermissionStoreConfig) {\n this.#storage = config.storage;\n this.#logger = config.logger;\n }\n\n /** Read all stored permissions for the given scope. Returns `[]` if none. */\n async list(scope: PermissionScope): Promise<Permission[]> {\n const key = permissionScopeKey(scope);\n const raw = await this.#storage.get(key);\n if (raw === null || raw === undefined) {\n return [];\n }\n const parsed = PermissionListSchema.safeParse(raw);\n if (!parsed.success) {\n await this.#deleteScope(key);\n await this.#untrackScope(scope);\n return [];\n }\n return parsed.data;\n }\n\n /**\n * Return permissions still live and bound to the current keypair.\n * Expired or stale-keypair permissions are pruned in one storage pass.\n */\n async listUsableAndPrune(scope: PermissionScope, keypairPublicKey: Hex): Promise<Permission[]> {\n const all = await this.list(scope);\n const usable = pruneUnusable(all, keypairPublicKey, Math.floor(Date.now() / 1000));\n\n if (usable.length !== all.length) {\n const key = permissionScopeKey(scope);\n if (usable.length === 0) {\n await this.#deleteScope(key);\n await this.#untrackScope(scope);\n } else {\n await swallow(\"update permit entry\", () => this.#storage.set(key, usable), this.#logger);\n }\n }\n return usable;\n }\n\n /**\n * Append signed permits to the given scope. Every permission is run through\n * `PermissionSchema` so the schema is the single normalization point for both\n * read and write paths. Signed payloads themselves are immutable and never\n * edited — only addresses and types are normalized.\n */\n async append(scope: PermissionScope, permissions: readonly Permission[]): Promise<void> {\n if (permissions.length === 0) {\n return;\n }\n const validated = permissions.map((p) => PermissionSchema.parse(p));\n const existing = await this.list(scope);\n await this.#storage.set(permissionScopeKey(scope), [...existing, ...validated]);\n await this.#trackScope(scope);\n }\n\n /**\n * Replace the entry identified by `oldSignature` with `newPermission`.\n *\n * Atomic relative to the storage backend's `set`: the old entry survives in\n * storage until the new list is written. If `oldSignature` is not found\n * (raced eviction or concurrent prune), `newPermission` is still persisted —\n * equivalent to {@link append}.\n */\n async replace(\n scope: PermissionScope,\n oldSignature: Hex,\n newPermission: Permission,\n ): Promise<void> {\n const validated = PermissionSchema.parse(newPermission);\n const existing = await this.list(scope);\n const filtered = existing.filter((p) => p.serializedPermit.signature !== oldSignature);\n await this.#storage.set(permissionScopeKey(scope), [...filtered, validated]);\n await this.#trackScope(scope);\n }\n\n /**\n * Delete every permit whose signed payload touches any listed contract.\n *\n * The store never edits `contractAddresses`, because that field is part\n * of the EIP-712 payload covered by `signature`.\n */\n async deletePermitsTouching(\n scope: PermissionScope,\n contractsToRemove: ChecksummedAddress[],\n ): Promise<void> {\n const existing = await this.list(scope);\n if (existing.length === 0) {\n return;\n }\n const key = permissionScopeKey(scope);\n const next = withoutPermitsTouching(existing, contractsToRemove);\n if (next.length === 0) {\n await this.#deleteScope(key);\n await this.#untrackScope(scope);\n } else {\n await this.#storage.set(key, next);\n }\n }\n\n /**\n * Delete every permission for the given signer across all chains and delegators.\n * Uses the per-signer scope index to cascade without enumerating all storage keys.\n */\n async clearAllForSigner(signerAddress: ChecksummedAddress): Promise<void> {\n const indexKey = permissionIndexKey(signerAddress);\n const scopeKeys = await this.#readIndex(indexKey);\n await Promise.all(scopeKeys.map((k) => this.#deleteScope(k)));\n await swallow(\"delete permit index\", () => this.#storage.delete(indexKey), this.#logger);\n }\n\n async #readIndex(indexKey: string): Promise<string[]> {\n const raw = await this.#storage.get(indexKey);\n if (raw === null || raw === undefined) {\n return [];\n }\n const parsed = ScopeIndexSchema.safeParse(raw);\n if (!parsed.success) {\n await swallow(\"delete permit index\", () => this.#storage.delete(indexKey), this.#logger);\n return [];\n }\n return parsed.data;\n }\n\n async #trackScope(scope: PermissionScope): Promise<void> {\n const indexKey = permissionIndexKey(scope.signerAddress);\n const scopeKey = permissionScopeKey(scope);\n const list = await this.#readIndex(indexKey);\n if (list.includes(scopeKey)) {\n return;\n }\n await this.#storage.set(indexKey, [...list, scopeKey]);\n }\n\n async #untrackScope(scope: PermissionScope): Promise<void> {\n const indexKey = permissionIndexKey(scope.signerAddress);\n const scopeKey = permissionScopeKey(scope);\n const list = await this.#readIndex(indexKey);\n const next = list.filter((entry) => entry !== scopeKey);\n if (next.length === list.length) {\n return;\n }\n if (next.length === 0) {\n await swallow(\"delete permit index\", () => this.#storage.delete(indexKey), this.#logger);\n } else {\n await swallow(\"update permit index\", () => this.#storage.set(indexKey, next), this.#logger);\n }\n }\n\n async #deleteScope(scopeKey: string): Promise<void> {\n await swallow(\"delete permit entry\", () => this.#storage.delete(scopeKey), this.#logger);\n }\n}\n","import type { Address } from \"viem\";\nimport type { ChainRouter } from \"../chains/router\";\nimport { ZamaError } from \"../errors/base\";\nimport { KeyWrappingError } from \"../errors/credential\";\nimport { ConfigurationError } from \"../errors/relayer\";\nimport { SignerNotConfiguredError } from \"../errors/signer\";\nimport { wrapSigningError } from \"../errors/signing\";\nimport type { ChecksummedAddress } from \"../schemas/primitives\";\nimport { checksum } from \"../schemas/primitives\";\nimport type { GenericLogger, GenericSigner, GenericStorage } from \"../types\";\nimport { isInvalidTransportKeyPairMessage } from \"../utils/error\";\nimport { swallow } from \"../utils/swallow\";\nimport { TransportKeyPairVault } from \"./keypair-vault\";\nimport type { DerivationSecretHolder } from \"./keypair-wrapping\";\nimport { PermissionStore } from \"./permission-store\";\nimport { chunkContracts, findPermitToWiden, sortedUnion, uncoveredContracts } from \"./permissions\";\nimport { SerializedPermitSchema } from \"./schemas\";\nimport type { PermissionScope } from \"./storage-keys\";\nimport type {\n Permission,\n SerializedTransportKeyPairWithPermissions,\n StoredTransportKeyPair,\n} from \"./types\";\nimport { normalizeAddresses, nowSeconds, SECONDS_PER_DAY } from \"./utils\";\n\nexport const DEFAULT_TRANSPORT_KEY_PAIR_TTL_SECONDS = 30 * SECONDS_PER_DAY;\nexport const DEFAULT_PERMIT_DURATION_DAYS = 30;\n\n/** Configuration for {@link CredentialService}. TTLs are pre-validated by the caller. */\nexport interface CredentialServiceConfig {\n router: ChainRouter;\n /**\n * Optional signer. Required for {@link CredentialService.grantPermit},\n * {@link CredentialService.revokePermits}, and\n * {@link CredentialService.clearCredentials} — each throws\n * {@link SignerNotConfiguredError} without one. Omitted for signer-less\n * usage (public decryption / encryption, or construction before a wallet\n * connects). Deferred/custody signing is served by passing an\n * out-of-process signer here, not by a separate signer-less code path.\n */\n signer?: GenericSigner;\n /** Transport key pair lifetime in seconds. Pre-validated. */\n transportKeyPairTTL: number;\n /** Permit lifetime in days. Pre-validated. */\n permitTTL: number;\n /** Backing storage for transport key pairs (and permits if `permitStorage` is omitted). */\n storage: GenericStorage;\n /** Optional dedicated storage for permits; defaults to `storage`. */\n permitStorage?: GenericStorage;\n /** SDK-wide logger for credential-path diagnostics. */\n logger: GenericLogger;\n /**\n * Opt-in shared-tenant scope (B2B2C/WaaS operators). When set, every signer\n * configured with the same scope shares one transport key pair instead of one\n * per signer address. Permits stay per-signer regardless — see\n * {@link revokeTransportKeyPair} for the operator-level counterpart to\n * signer-level revocation.\n */\n scope?: string;\n /**\n * Opt-in at-rest wrapping of the transport key pair's private half, for headless\n * contexts with no secure storage backend to delegate to. See\n * {@link TransportKeyPairVault}.\n */\n derivationSecret?: DerivationSecretHolder;\n}\n\n/**\n * Single facade coordinating the keypair vault and the permission store.\n *\n * `CredentialService` is the only credentials object held by {@link ZamaSDK}. It accepts identity\n * transitions via `handleWalletAccountChange`.\n *\n * Two distinct revocation tiers exist and must not be conflated: {@link clearCredentials}\n * (signer-level, e.g. an end-user \"disconnect\") only ever removes that signer's own\n * key-pair slot and permits — when a scope is configured, the shared key pair was never\n * stored there, so it's untouched. {@link revokeTransportKeyPair} (operator-level) is\n * the only way to invalidate a scope's shared key pair, and it does so for every signer\n * in the scope at once.\n *\n * @internal\n */\nexport class CredentialService {\n readonly #vault: TransportKeyPairVault;\n readonly #store: PermissionStore;\n readonly #router: ChainRouter;\n readonly #signer: GenericSigner | undefined;\n readonly #permitTTL: number;\n readonly #logger: GenericLogger;\n readonly #scope: string | undefined;\n\n constructor(config: CredentialServiceConfig) {\n this.#vault = new TransportKeyPairVault({\n generator: async () => {\n const relayer = config.router.relayer;\n const transportKeyPair = await relayer.generateTransportKeyPair();\n return relayer.serializeTransportKeyPair({ transportKeyPair });\n },\n storage: config.storage,\n ttl: config.transportKeyPairTTL,\n logger: config.logger,\n scope: config.scope,\n derivationSecret: config.derivationSecret,\n });\n this.#store = new PermissionStore({\n storage: config.permitStorage ?? config.storage,\n logger: config.logger,\n });\n this.#router = config.router;\n this.#signer = config.signer;\n this.#permitTTL = config.permitTTL;\n this.#logger = config.logger;\n this.#scope = config.scope;\n }\n\n #requireSigner(operation: string): GenericSigner {\n if (!this.#signer) {\n throw new SignerNotConfiguredError(operation);\n }\n return this.#signer;\n }\n\n /**\n * Resolve a keypair and permissions covering `contracts`, minimizing wallet\n * prompts by reusing or widening existing permits where possible. Empty\n * `contracts` warms the keypair without prompting.\n *\n * @returns The resolved keypair and permits covering the requested contracts.\n * @throws if the user rejects a wallet signature prompt. {@link SigningRejectedError}\n * @throws if signing fails for any other reason. {@link SigningFailedError}\n * @throws if `derivationSecret` is configured and the keypair fails to wrap or\n * unwrap — see {@link TransportKeyPairVault.getOrCreate}. {@link KeyWrappingError}\n */\n async grantPermit(\n contracts: readonly Address[],\n delegator?: Address,\n ): Promise<SerializedTransportKeyPairWithPermissions> {\n const signer = this.#requireSigner(\"grantPermit\");\n const account = signer.requireWalletAccount(\"grantPermit\");\n const signerAddress = checksum(account.address);\n const requested = normalizeAddresses(contracts);\n const keypair = await this.#vault.getOrCreate(signerAddress);\n if (requested.length === 0) {\n return { keypair, permissions: [] };\n }\n\n // Key permits by the router's active chain — the same source the permit's\n // EIP-712 domain is signed against (#signPermit uses this.#router.relayer) —\n // so the storage key and the signature can never disagree on the chain.\n const chainId = this.#router.chain.id;\n const scope: PermissionScope = {\n signerAddress,\n chainId,\n delegatorAddress: delegator ? checksum(delegator) : signerAddress,\n };\n const permissions = await this.#store.listUsableAndPrune(scope, keypair.publicKey);\n\n const uncovered = uncoveredContracts(permissions, requested);\n if (uncovered.length > 0) {\n const candidate = findPermitToWiden(permissions, uncovered, requested);\n if (candidate !== null) {\n const widenedSet = sortedUnion(candidate.contractAddresses, uncovered);\n const widened = await this.#signPermit({ chunk: widenedSet, keypair, scope });\n await swallow(\n \"replace permit\",\n () => this.#store.replace(scope, candidate.serializedPermit.signature, widened),\n this.#logger,\n );\n permissions[permissions.indexOf(candidate)] = widened;\n } else {\n for (const chunk of chunkContracts(uncovered)) {\n const permission = await this.#signPermit({ chunk, keypair, scope });\n permissions.push(permission);\n await swallow(\n \"persist permit\",\n () => this.#store.append(scope, [permission]),\n this.#logger,\n );\n }\n }\n }\n\n const requestedSet = new Set(requested);\n return {\n keypair,\n permissions: permissions.filter((p) => p.contractAddresses.some((a) => requestedSet.has(a))),\n };\n }\n\n /**\n * Pure store lookup: are stored permits sufficient to cover `contracts`? No wallet prompt.\n *\n * Never throws on a `KeyWrappingError`: a stored keypair that fails to unwrap reports\n * no permit instead, since this is a read-only status check. `grantPermit()` still\n * surfaces that same failure normally.\n *\n * @returns `true` if cached permits cover all requested contracts (vacuously\n * true for an empty list); `false` if no keypair exists, it fails to unwrap, or\n * coverage is incomplete.\n * @throws if the backing storage read fails for a reason unrelated to `derivationSecret`\n * wrapping: this is not swallowed, unlike a `KeyWrappingError`.\n */\n async hasPermit(contracts: readonly Address[], delegator?: Address): Promise<boolean> {\n if (contracts.length === 0) {\n return true;\n }\n const account = this.#signer?.walletAccount.getSnapshot();\n if (!account) {\n return false;\n }\n const signerAddress = checksum(account.address);\n let keypair: StoredTransportKeyPair | null;\n try {\n keypair = await this.#vault.readStored(signerAddress);\n } catch (error) {\n if (!(error instanceof KeyWrappingError)) {\n throw error;\n }\n // The vault already logged this failure; this read-only status check must not\n // surface it a second time as a rejection.\n return false;\n }\n if (keypair === null) {\n return false;\n }\n const chainId = this.#router.chain.id;\n const delegatorAddress = delegator ? checksum(delegator) : signerAddress;\n const scope: PermissionScope = { signerAddress, chainId, delegatorAddress };\n const permits = await this.#store.listUsableAndPrune(scope, keypair.publicKey);\n return uncoveredContracts(permits, normalizeAddresses(contracts)).length === 0;\n }\n\n /**\n * Wipe FHE permits for the current signer.\n *\n * - With no argument: every permit referencing this signer is removed across\n * all chains and delegators. The keypair survives — use\n * {@link clearCredentials} to also wipe the keypair.\n * - With a contract list: every signed permit in the direct-decrypt scope\n * (current chain) whose immutable payload touches any listed address is\n * removed. Delegated permits are not touched in this mode.\n *\n * @throws if reading the signer address fails. {@link SigningFailedError}\n */\n async revokePermits(contracts?: readonly Address[]): Promise<void> {\n const signer = this.#requireSigner(\"revokePermits\");\n const account = signer.requireWalletAccount(\"revokePermits\");\n const signerAddress = checksum(account.address);\n if (contracts === undefined) {\n await this.#store.clearAllForSigner(signerAddress);\n return;\n }\n const normalized = normalizeAddresses(contracts);\n if (normalized.length === 0) {\n return;\n }\n const chainId = this.#router.chain.id;\n await this.#store.deletePermitsTouching(\n { signerAddress, chainId, delegatorAddress: signerAddress },\n normalized,\n );\n }\n\n /**\n * Wipe the keypair for the current signer and cascade-delete every\n * permission referencing it across all chains and delegators.\n *\n * Signer-level only: when a scope is configured, the shared key pair was never\n * stored under this signer's own slot, so it survives untouched — only this\n * signer's permits are removed. Use {@link revokeTransportKeyPair} to invalidate\n * the shared key pair itself.\n *\n * @throws if reading the signer address fails. {@link SigningFailedError}\n */\n async clearCredentials(): Promise<void> {\n const signer = this.#requireSigner(\"clearCredentials\");\n const account = signer.requireWalletAccount(\"clearCredentials\");\n const signerAddress = checksum(account.address);\n await this.#vault.clear(signerAddress);\n await this.#store.clearAllForSigner(signerAddress);\n }\n\n /**\n * Revoke this scope's shared transport key pair (operator-level action).\n *\n * Deletes the shared key pair. Every permit signed under it embeds the old\n * public key, so `listUsableAndPrune` treats them all as stale on next access —\n * no permit is touched directly, and no connected wallet is required. This is\n * the only operation that can invalidate a shared key pair; signer-level\n * {@link clearCredentials} never does.\n *\n * Not best-effort: unlike {@link clearCredentials}, a storage failure here rejects\n * instead of being logged and swallowed — see {@link TransportKeyPairVault.clearScope}.\n *\n * Only stops the SDK from reissuing or reusing the deleted key going forward — does\n * not revoke any permit already issued under it. A permit is a self-contained,\n * bearer-style EIP-712 signature the relayer accepts independently of this SDK's\n * storage; one already exfiltrated alongside the key remains usable until its own\n * `permitTTL` expiry regardless of this call.\n *\n * @param scopeId - Must match the scope this service was configured with. Requiring\n * the caller to name it guards against revoking the wrong scope by mistake.\n * @throws if no scope is configured, or `scopeId` doesn't match it. {@link ConfigurationError}\n * @throws if the underlying storage delete fails.\n */\n async revokeTransportKeyPair(scopeId: string): Promise<void> {\n if (this.#scope === undefined) {\n throw new ConfigurationError(\n \"revokeTransportKeyPair() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to revoke.\",\n );\n }\n if (scopeId !== this.#scope) {\n throw new ConfigurationError(\n `revokeTransportKeyPair(\"${scopeId}\") does not match the configured scope (\"${this.#scope}\").`,\n );\n }\n await this.#vault.clearScope();\n }\n\n /**\n * Warm the signer transport key pair cache for a known address.\n *\n * Best-effort prefetch primitive: correctness still comes from `grantPermit`,\n * which lazily creates the transport key pair when needed. Errors (storage failure,\n * relayer 4xx, missing Worker in SSR) are **not** swallowed here — the caller\n * decides whether to log, ignore, or surface them.\n *\n * Not for pre-warming a shared scope: `address` is ignored for storage keying once\n * a scope is configured (see {@link TransportKeyPairVault}), so this call's actual\n * effect wouldn't match its apparent per-signer intent. Use\n * {@link warmTransportKeyPairScope} instead.\n *\n * @throws if `derivationSecret` is configured and the keypair fails to wrap or\n * unwrap — see {@link TransportKeyPairVault.getOrCreate}. {@link KeyWrappingError}\n */\n async warmTransportKeyPair(address: Address): Promise<void> {\n await this.#vault.getOrCreate(checksum(address));\n }\n\n /**\n * Warm this scope's shared transport key pair (operator-level, no wallet needed) —\n * the pre-warm counterpart to {@link revokeTransportKeyPair}.\n *\n * @param scopeId - Must match the scope this service was configured with. Requiring\n * the caller to name it guards against warming the wrong scope by mistake.\n * @throws if no scope is configured, or `scopeId` doesn't match it. {@link ConfigurationError}\n * @throws if `derivationSecret` is configured and the keypair fails to wrap or\n * unwrap — see {@link TransportKeyPairVault.getOrCreate}. {@link KeyWrappingError}\n */\n async warmTransportKeyPairScope(scopeId: string): Promise<void> {\n if (this.#scope === undefined) {\n throw new ConfigurationError(\n \"warmTransportKeyPairScope() requires a transportKeyPairScope to be configured on this SDK instance — there is no shared key pair to warm.\",\n );\n }\n if (scopeId !== this.#scope) {\n throw new ConfigurationError(\n `warmTransportKeyPairScope(\"${scopeId}\") does not match the configured scope (\"${this.#scope}\").`,\n );\n }\n await this.#vault.warmScope();\n }\n\n /**\n * Apply a wallet account transition.\n *\n * Address change clears persisted credentials for the previous account.\n * Chain-only changes keep credentials intact because permits are chain-scoped\n * already and stale decrypt plaintext is cleared by {@link ZamaSDK}.\n */\n async handleWalletAccountChange(\n prev?: { address: Address },\n next?: { address: Address },\n ): Promise<void> {\n const prevAddr = prev ? checksum(prev.address) : undefined;\n const nextAddr = next ? checksum(next.address) : undefined;\n if (prevAddr === nextAddr) {\n return;\n }\n if (prevAddr) {\n await this.#vault.clear(prevAddr);\n await this.#store.clearAllForSigner(prevAddr);\n }\n }\n\n async #signPermit(input: {\n chunk: ChecksummedAddress[];\n keypair: StoredTransportKeyPair;\n scope: PermissionScope;\n }): Promise<Permission> {\n const { chunk, keypair, scope } = input;\n const startTimestamp = nowSeconds();\n const isDelegated = scope.delegatorAddress !== scope.signerAddress;\n const relayer = this.#router.relayer;\n try {\n const transportKeyPair = await relayer.parseTransportKeyPair(keypair);\n const permitInput = {\n transportKeyPair,\n contractAddresses: chunk,\n startTimestamp,\n durationSeconds: this.#permitTTL * SECONDS_PER_DAY,\n signerAddress: scope.signerAddress,\n signer: this.#requireSigner(\"signPermit\"),\n };\n const signedPermit = isDelegated\n ? await relayer.signDecryptionPermit({\n ...permitInput,\n delegatorAddress: scope.delegatorAddress,\n })\n : await relayer.signDecryptionPermit(permitInput);\n\n const serializedPermit = SerializedPermitSchema.parse(\n await relayer.serializeSignedDecryptionPermit({ signedPermit }),\n );\n\n return {\n keypairPublicKey: keypair.publicKey,\n contractAddresses: chunk,\n serializedPermit,\n startTimestamp,\n durationDays: this.#permitTTL,\n };\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n // A key pair the relayer can't re-derive (post KMS/TKMS rotation) is\n // unusable: evict it so the next grantPermit regenerates a valid one, then\n // surface the typed InvalidTransportKeyPairError via wrapSigningError.\n if (error instanceof Error && isInvalidTransportKeyPairMessage(error.message)) {\n await this.#vault.evict(scope.signerAddress);\n }\n throw wrapSigningError(error, \"Credential signing failed\");\n }\n }\n\n /**\n * Evict the current signer's transport key pair so the next credential\n * resolution regenerates it — the self-heal hook the decrypt path calls when\n * the relayer rejects the stored key pair as invalid (see\n * {@link InvalidTransportKeyPairError}). No-op when no wallet is connected;\n * best-effort, never throws.\n */\n async evictTransportKeyPair(): Promise<void> {\n const account = this.#signer?.walletAccount.getSnapshot();\n if (!account) {\n return;\n }\n await this.#vault.evict(checksum(account.address));\n }\n}\n","import type { GenericLogger } from \"../types\";\n\n/**\n * Internal logger with a consistent, always-present shape.\n *\n * The consumer supplies an optional {@link GenericLogger} via configuration;\n * it is wrapped once into a `LoggerService` that is threaded through the SDK.\n * Internal code therefore calls `logger.warn(...)` directly — no optional\n * chaining, no per-call `undefined` checks — and a single place (this class)\n * owns the \"silent by default\" behavior: when no logger was supplied, every\n * level is a no-op.\n *\n * Every message is prefixed with `[zama-sdk]` here, so call sites pass only\n * their own message (and optional component tag) without repeating the prefix.\n *\n * `LoggerService` itself satisfies `GenericLogger`, so it can be passed\n * anywhere a logger is expected.\n */\nexport class LoggerService implements GenericLogger {\n readonly #logger: GenericLogger | undefined;\n readonly #prefix = \"[zama-sdk]\";\n\n constructor(logger?: GenericLogger) {\n this.#logger = logger;\n }\n\n error(message: string, data?: Record<string, unknown>): void {\n this.#logger?.error(`${this.#prefix} ${message}`, data);\n }\n\n warn(message: string, data?: Record<string, unknown>): void {\n this.#logger?.warn(`${this.#prefix} ${message}`, data);\n }\n\n info(message: string, data?: Record<string, unknown>): void {\n this.#logger?.info(`${this.#prefix} ${message}`, data);\n }\n\n debug(message: string, data?: Record<string, unknown>): void {\n this.#logger?.debug(`${this.#prefix} ${message}`, data);\n }\n}\n","import { z } from \"zod/mini\";\nimport { ConfigurationError } from \"./errors\";\n\nexport function parseSchema<T>(schema: z.core.$ZodType<T>, value: unknown): T {\n const parsed = z.safeParse(schema, value);\n if (parsed.success) {\n return parsed.data;\n }\n throw new ConfigurationError(z.prettifyError(parsed.error), { cause: parsed.error });\n}\n","import { type Address, getAddress, zeroAddress } from \"viem\";\nimport { z } from \"zod/mini\";\nimport type { TokenWrapperPairWithMetadata, PaginatedResult, TokenWrapperPair } from \"./contracts\";\nimport {\n decimalsContract,\n erc20TotalSupplyContract,\n getConfidentialTokenAddressContract,\n getTokenAddressContract,\n getTokenPairContract,\n getTokenPairsContract,\n getTokenPairsLengthContract,\n getTokenPairsSliceContract,\n isConfidentialTokenValidContract,\n nameContract,\n symbolContract,\n} from \"./contracts\";\nimport { ConfigurationError } from \"./errors/relayer\";\nimport { mainnet, sepolia, polygonAmoy, hoodi, ingenTestnet, bscTestnet } from \"./chains\";\nimport { checksummedAddress, nonNegativeSeconds } from \"./schemas/primitives\";\nimport type { GenericProvider } from \"./types/provider\";\nimport { parseSchema } from \"./validation\";\n\n/**\n * Default wrappers registry addresses for known chains.\n * Only includes chains where a registry is deployed (excludes Hardhat).\n *\n * @deprecated Read `registryAddress` from the chain presets instead (e.g.\n * `sepolia.registryAddress`). Will be removed in the next major version.\n */\nexport const DefaultRegistryAddresses: Record<number, Address> = {\n [mainnet.id]: mainnet.registryAddress,\n [sepolia.id]: sepolia.registryAddress,\n [polygonAmoy.id]: polygonAmoy.registryAddress,\n [hoodi.id]: hoodi.registryAddress,\n [ingenTestnet.id]: ingenTestnet.registryAddress,\n [bscTestnet.id]: bscTestnet.registryAddress,\n};\n\n/** Default registry TTL in seconds (24 hours). */\nexport const DEFAULT_REGISTRY_TTL_SECONDS = 86_400;\n\n/** Per-chain wrappers-registry address overrides. */\nexport const RegistryAddressesSchema = z.record(\n z.string().check(z.regex(/^\\d+$/, \"expected numeric chain id key\")),\n checksummedAddress,\n);\n\n/** TTL (seconds) for cached registry results. `0` means entries expire immediately. */\nexport const RegistryTTLSchema = nonNegativeSeconds;\n\n/** Default page size for {@link WrappersRegistry.listPairs}. */\nconst DEFAULT_PAGE_SIZE = 100;\n\n/** Configuration for {@link WrappersRegistry}. */\nexport interface WrappersRegistryConfig {\n /** Read-only chain provider used for every registry lookup. */\n provider: GenericProvider;\n /**\n * Per-chain registry address overrides, merged on top of\n * {@link DefaultRegistryAddresses}. Use this to supply a registry\n * address for custom or local chains (e.g. Hardhat).\n *\n * @example\n * ```ts\n * new WrappersRegistry({\n * provider,\n * registryAddresses: { [31337]: \"0xYourHardhatRegistry\" },\n * });\n * ```\n */\n registryAddresses?: Record<number, Address>;\n /**\n * How long cached registry results remain valid, in seconds.\n * Default: `86400` (24 hours).\n */\n registryTTL?: number;\n}\n\n/** Options for {@link WrappersRegistry.listPairs}. */\nexport interface ListPairsOptions {\n /** Page number (1-indexed). Default: `1`. */\n page?: number;\n /** Number of items per page. Default: `100`. */\n pageSize?: number;\n /**\n * When `true`, fetches on-chain metadata (name, symbol, decimals) for both\n * the ERC-20 and confidential token, plus totalSupply for the ERC-20.\n * Default: `false`.\n */\n metadata?: boolean;\n}\n\n/** Shorter TTL for negative lookups (5 minutes) so newly registered tokens are discoverable quickly. */\nconst NEGATIVE_CACHE_TTL_MS = 5 * 60 * 1000;\n\n/** Cache entry with expiry timestamp. */\ninterface CacheEntry<T> {\n data: T;\n expiresAt: number;\n}\n\n/**\n * High-level interface for the on-chain token wrappers registry.\n *\n * Uses the configured {@link GenericProvider} to resolve the correct registry\n * contract address for the current chain and exposes typed read helpers for\n * every registry query. Results are cached in memory with a configurable TTL\n * (default 24 hours).\n *\n * @example\n * ```ts\n * const registry = new WrappersRegistry({ provider });\n *\n * // Paginated listing\n * const page1 = await registry.listPairs({ page: 1, pageSize: 20 });\n *\n * // Structured lookups\n * const result = await registry.getConfidentialToken(erc20Address);\n * if (result) console.log(result.confidentialTokenAddress);\n *\n * // Force refresh\n * registry.refresh();\n * ```\n */\nexport class WrappersRegistry {\n /** Read-only chain access used for registry contract reads. */\n readonly provider: GenericProvider;\n readonly #addresses: Record<number, Address>;\n readonly #ttlMs: number;\n readonly #cache = new Map<string, CacheEntry<unknown>>();\n\n constructor(config: WrappersRegistryConfig) {\n this.provider = config.provider;\n this.#addresses = Object.assign(\n {},\n DefaultRegistryAddresses,\n parseSchema(z.optional(RegistryAddressesSchema), config.registryAddresses),\n );\n this.#ttlMs =\n parseSchema(RegistryTTLSchema, config.registryTTL ?? DEFAULT_REGISTRY_TTL_SECONDS) * 1000;\n }\n\n /**\n * Synchronous lookup of the registry address for a given chain ID.\n * Returns `undefined` if no address is configured for that chain.\n */\n getAddress(chainId: number): Address | undefined {\n return this.#addresses[chainId];\n }\n\n // ---------------------------------------------------------------------------\n // Cache helpers\n // ---------------------------------------------------------------------------\n\n #getCached<T>(key: string): T | undefined {\n const entry = this.#cache.get(key);\n if (!entry) {\n return undefined;\n }\n if (Date.now() >= entry.expiresAt) {\n this.#cache.delete(key);\n return undefined;\n }\n return entry.data as T;\n }\n\n #setCached<T>(key: string, data: T, ttlMs = this.#ttlMs): T {\n this.#cache.set(key, { data, expiresAt: Date.now() + ttlMs });\n return data;\n }\n\n /**\n * Force-invalidate the in-memory cache. The next call to any read method\n * will fetch fresh data from the chain.\n */\n refresh(): void {\n this.#cache.clear();\n }\n\n /**\n * The cache TTL in milliseconds.\n * Exposed so query option factories can set a matching `staleTime`.\n */\n get ttlMs(): number {\n return this.#ttlMs;\n }\n\n // ---------------------------------------------------------------------------\n // Registry address resolution\n // ---------------------------------------------------------------------------\n\n /**\n * Resolve the registry contract address for the current chain.\n *\n * Priority: `registryAddresses[chainId]` \\> built-in default.\n *\n * @returns The registry contract address for the connected chain.\n * @throws if no address is configured for the chain. {@link ConfigurationError}\n */\n async getRegistryAddress(): Promise<Address> {\n const chainId = await this.provider.getChainId();\n const address = this.#addresses[chainId];\n\n if (!address) {\n throw new ConfigurationError(\n `No wrappers registry address configured for chain ${chainId}.\\n` +\n `Pass a registryAddresses entry for this chain.`,\n );\n }\n\n return getAddress(address);\n }\n\n // ---------------------------------------------------------------------------\n // Paginated listing\n // ---------------------------------------------------------------------------\n\n /**\n * List token wrapper pairs with page-based pagination.\n *\n * Internally maps to `getTokenConfidentialTokenPairsSlice` on-chain.\n *\n * @param options - Pagination and enrichment options.\n * @returns A {@link PaginatedResult} of pairs.\n *\n * @example\n * ```ts\n * const result = await registry.listPairs({ page: 1, pageSize: 20 });\n * console.log(`${result.total} pairs, showing page ${result.page}`);\n *\n * // With on-chain metadata\n * const withMeta = await registry.listPairs({ metadata: true, pageSize: 10 });\n * for (const pair of withMeta.items) {\n * console.log(pair.underlying.symbol, \"→\", pair.confidential.symbol);\n * }\n * ```\n */\n async listPairs(\n options: ListPairsOptions & { metadata: true },\n ): Promise<PaginatedResult<TokenWrapperPairWithMetadata>>;\n /** Lists registered underlying/confidential token pairs; pass `{ metadata: true }` to include on-chain token metadata. */\n async listPairs(options?: ListPairsOptions): Promise<PaginatedResult<TokenWrapperPair>>;\n async listPairs(\n options: ListPairsOptions = {},\n ): Promise<PaginatedResult<TokenWrapperPair | TokenWrapperPairWithMetadata>> {\n const page = options.page ?? 1;\n const pageSize = options.pageSize ?? DEFAULT_PAGE_SIZE;\n const metadata = options.metadata ?? false;\n\n if (page < 1) {\n throw new ConfigurationError(`page must be >= 1, got ${page}`);\n }\n if (pageSize < 1) {\n throw new ConfigurationError(`pageSize must be >= 1, got ${pageSize}`);\n }\n\n const registry = await this.getRegistryAddress();\n\n // Fetch total (cached)\n const totalCacheKey = `total:${registry}`;\n let total = this.#getCached<number>(totalCacheKey);\n if (total === undefined) {\n const raw = await this.provider.readContract(getTokenPairsLengthContract(registry));\n total = this.#setCached(totalCacheKey, Number(raw));\n }\n\n // Compute slice indices, clamping toIndex to total\n const fromIndex = BigInt((page - 1) * pageSize);\n const clampedToIndex =\n fromIndex + BigInt(pageSize) > BigInt(total) ? BigInt(total) : fromIndex + BigInt(pageSize);\n\n // Page beyond total — return empty\n if (fromIndex >= BigInt(total)) {\n return { items: [], total, page, pageSize };\n }\n\n // Fetch slice (cached)\n const sliceCacheKey = `slice:${registry}:${fromIndex}:${clampedToIndex}`;\n let items = this.#getCached<TokenWrapperPair[]>(sliceCacheKey);\n if (items === undefined) {\n const raw = await this.provider.readContract(\n getTokenPairsSliceContract(registry, fromIndex, clampedToIndex),\n );\n items = this.#setCached(sliceCacheKey, [...raw]);\n }\n\n if (!metadata) {\n return { items, total, page, pageSize };\n }\n\n // Enrich with on-chain metadata (resilient — individual failures don't break the batch)\n const metadataCacheKey = `metadata:${registry}:${fromIndex}:${clampedToIndex}`;\n let metadataItems = this.#getCached<TokenWrapperPairWithMetadata[]>(metadataCacheKey);\n if (metadataItems === undefined) {\n const settled = await Promise.allSettled(items.map((pair) => this.#pairWithMetadata(pair)));\n const hasFailures = settled.some((r) => r.status === \"rejected\");\n const enriched = settled.map((result, i) =>\n result.status === \"fulfilled\"\n ? result.value\n : Object.assign({}, items[i], {\n metadataFailed: true as const,\n underlying: { name: \"Unknown\", symbol: \"???\", decimals: 0, totalSupply: 0n },\n confidential: { name: \"Unknown\", symbol: \"???\", decimals: 0 },\n }),\n );\n // Use negative cache TTL when any metadata fetch failed so retries happen sooner\n metadataItems = this.#setCached(\n metadataCacheKey,\n enriched,\n hasFailures ? NEGATIVE_CACHE_TTL_MS : undefined,\n );\n }\n\n return { items: metadataItems, total, page, pageSize };\n }\n\n async #pairWithMetadata(pair: TokenWrapperPair): Promise<TokenWrapperPairWithMetadata> {\n const [uName, uSymbol, uDecimals, uTotalSupply, cName, cSymbol, cDecimals] = await Promise.all([\n this.provider.readContract(nameContract(pair.tokenAddress)),\n this.provider.readContract(symbolContract(pair.tokenAddress)),\n this.provider.readContract(decimalsContract(pair.tokenAddress)),\n this.provider.readContract(erc20TotalSupplyContract(pair.tokenAddress)),\n this.provider.readContract(nameContract(pair.confidentialTokenAddress)),\n this.provider.readContract(symbolContract(pair.confidentialTokenAddress)),\n this.provider.readContract(decimalsContract(pair.confidentialTokenAddress)),\n ]);\n\n return {\n ...pair,\n underlying: { name: uName, symbol: uSymbol, decimals: uDecimals, totalSupply: uTotalSupply },\n confidential: { name: cName, symbol: cSymbol, decimals: cDecimals },\n };\n }\n\n // ---------------------------------------------------------------------------\n // Structured single-pair lookups\n // ---------------------------------------------------------------------------\n\n /**\n * Look up the confidential token for a given plain ERC-20 address.\n *\n * @param tokenAddress - The plain ERC-20 token address.\n * @returns The lookup result, or `null` if the token has never been registered.\n * **Note:** revoked tokens (registered then invalidated) return a non-null result\n * with `isValid: false`. Check `result.isValid` explicitly rather than using\n * `if (result)` to guard against processing revoked tokens.\n *\n * @example\n * ```ts\n * const result = await registry.getConfidentialToken(usdcAddress);\n * if (result?.isValid) {\n * console.log(result.confidentialTokenAddress);\n * }\n * ```\n */\n async getConfidentialToken(\n tokenAddress: Address,\n ): Promise<{ confidentialTokenAddress: Address; isValid: boolean } | null> {\n const registry = await this.getRegistryAddress();\n const normalized = getAddress(tokenAddress);\n\n const cacheKey = `ct:${registry}:${normalized}`;\n const cached = this.#getCached<{ confidentialTokenAddress: Address; isValid: boolean } | null>(\n cacheKey,\n );\n if (cached !== undefined) {\n return cached;\n }\n\n const [isValid, confidentialTokenAddress] = await this.provider.readContract(\n getConfidentialTokenAddressContract(registry, normalized),\n );\n\n // Zero address means the token is not registered at all (never seen by the registry).\n // A non-zero address with isValid=false means it was registered but later revoked.\n if (confidentialTokenAddress === zeroAddress) {\n return this.#setCached(cacheKey, null, NEGATIVE_CACHE_TTL_MS);\n }\n\n return this.#setCached(cacheKey, { confidentialTokenAddress, isValid });\n }\n\n /**\n * Reverse lookup — find the plain ERC-20 for a given confidential token.\n *\n * @param confidentialTokenAddress - The confidential token address.\n * @returns The lookup result, or `null` if no pair is registered.\n *\n * @example\n * ```ts\n * const result = await registry.getUnderlyingToken(cUsdcAddress);\n * if (result) {\n * console.log(result.tokenAddress, result.isValid);\n * }\n * ```\n */\n async getUnderlyingToken(\n confidentialTokenAddress: Address,\n ): Promise<{ tokenAddress: Address; isValid: boolean } | null> {\n const registry = await this.getRegistryAddress();\n const normalized = getAddress(confidentialTokenAddress);\n\n const cacheKey = `ut:${registry}:${normalized}`;\n const cached = this.#getCached<{ tokenAddress: Address; isValid: boolean } | null>(cacheKey);\n if (cached !== undefined) {\n return cached;\n }\n\n const [isValid, tokenAddress] = await this.provider.readContract(\n getTokenAddressContract(registry, normalized),\n );\n\n // Zero address means the confidential token is not registered at all.\n // A non-zero address with isValid=false means it was registered but later revoked.\n if (tokenAddress === zeroAddress) {\n return this.#setCached(cacheKey, null, NEGATIVE_CACHE_TTL_MS);\n }\n\n return this.#setCached(cacheKey, { tokenAddress, isValid });\n }\n\n // ---------------------------------------------------------------------------\n // Low-level pass-through methods (backward compatible)\n // ---------------------------------------------------------------------------\n\n /**\n * Fetch all token wrapper pairs from the registry.\n *\n * @returns All registered `TokenWrapperPair` entries.\n */\n async getTokenPairs(): Promise<readonly TokenWrapperPair[]> {\n const registry = await this.getRegistryAddress();\n return this.provider.readContract(getTokenPairsContract(registry));\n }\n\n /**\n * Get the total number of token wrapper pairs.\n *\n * @returns The count as a bigint.\n */\n async getTokenPairsLength(): Promise<bigint> {\n const registry = await this.getRegistryAddress();\n return this.provider.readContract(getTokenPairsLengthContract(registry));\n }\n\n /**\n * Fetch a range of token wrapper pairs (paginated by index).\n *\n * @param fromIndex - Start index (inclusive).\n * @param toIndex - End index (exclusive).\n * @returns The slice of `TokenWrapperPair` entries.\n */\n async getTokenPairsSlice(\n fromIndex: bigint,\n toIndex: bigint,\n ): Promise<readonly TokenWrapperPair[]> {\n const registry = await this.getRegistryAddress();\n return this.provider.readContract(getTokenPairsSliceContract(registry, fromIndex, toIndex));\n }\n\n /**\n * Fetch a single token wrapper pair by index.\n *\n * @param index - Zero-based pair index.\n * @returns The `TokenWrapperPair` at that index.\n */\n async getTokenPair(index: bigint): Promise<TokenWrapperPair> {\n const registry = await this.getRegistryAddress();\n return this.provider.readContract(getTokenPairContract(registry, index));\n }\n\n /**\n * Look up the confidential token address for a given plain ERC-20 token.\n *\n * @param tokenAddress - The plain ERC-20 token address.\n * @returns A tuple `[isValid, confidentialTokenAddress]`. `isValid` is `true` only for a\n * registered, non-revoked wrapper. The address is the zero address when no pair is registered.\n * A non-zero address with `isValid=false` means the wrapper was registered but later revoked.\n */\n async getConfidentialTokenAddress(tokenAddress: Address): Promise<readonly [boolean, Address]> {\n const registry = await this.getRegistryAddress();\n return this.provider.readContract(\n getConfidentialTokenAddressContract(registry, getAddress(tokenAddress)),\n );\n }\n\n /**\n * Reverse lookup — find the plain ERC-20 for a given confidential token.\n *\n * @param confidentialTokenAddress - The confidential token address.\n * @returns A tuple `[isValid, tokenAddress]`. `isValid` is `true` only for a registered,\n * non-revoked wrapper. The address is the zero address when no pair is registered.\n * A non-zero address with `isValid=false` means the wrapper was registered but later revoked.\n */\n async getTokenAddress(confidentialTokenAddress: Address): Promise<readonly [boolean, Address]> {\n const registry = await this.getRegistryAddress();\n return this.provider.readContract(\n getTokenAddressContract(registry, getAddress(confidentialTokenAddress)),\n );\n }\n\n /**\n * Check whether a confidential token is registered and valid.\n *\n * @param confidentialTokenAddress - The confidential token address to check.\n * @returns `true` if the token is a known valid wrapper in the registry.\n */\n async isConfidentialTokenValid(confidentialTokenAddress: Address): Promise<boolean> {\n const registry = await this.getRegistryAddress();\n return this.provider.readContract(\n isConfidentialTokenValidContract(registry, getAddress(confidentialTokenAddress)),\n );\n }\n}\n","import { hasFhevmRuntimeConfig, setFhevmRuntimeConfig } from \"@fhevm/sdk/viem\";\nimport { ChainRouter } from \"../chains/router\";\nimport {\n DEFAULT_PERMIT_DURATION_DAYS,\n DEFAULT_TRANSPORT_KEY_PAIR_TTL_SECONDS,\n} from \"../credentials/credential-service\";\nimport {\n PermitTTLSchema,\n TransportKeyPairScopeSchema,\n TransportKeyPairTTLSchema,\n} from \"../credentials/schemas\";\nimport { LoggerService } from \"../services/logger-service\";\nimport type { GenericProvider, GenericSigner } from \"../types\";\nimport { parseSchema } from \"../validation\";\nimport { DEFAULT_REGISTRY_TTL_SECONDS, RegistryTTLSchema } from \"../wrappers-registry\";\nimport { resolveStorage } from \"./resolve\";\nimport type { ZamaConfig, ZamaConfigBase } from \"./types\";\n\n/**\n * @internal Shared config builder — not part of the public API.\n *\n * Applies defaults, validates TTLs, and resolves storage so the\n * returned config is fully populated and ready for `ZamaSDK`.\n */\nexport function buildZamaConfig(\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n params: ZamaConfigBase,\n): ZamaConfig {\n const logger = new LoggerService(params.logger);\n const consumerLogger = params.logger;\n\n if (hasFhevmRuntimeConfig()) {\n // One config per signer is a supported pattern, so a second call is only worth warning about\n // when it carries runtime options that the already-locked runtime config will ignore.\n const message = \"runtime configuration is already set and cannot be changed.\";\n if (params.runtime === undefined) {\n logger.debug(message);\n } else {\n logger.warn(message);\n }\n } else {\n setFhevmRuntimeConfig({\n wasmAssetLoadMode: \"auto\",\n moduleVersions: \"auto\",\n logger: {\n error: (message, cause) => consumerLogger?.error(message, { cause }),\n warn: (message) => consumerLogger?.warn(message),\n debug: (message) => consumerLogger?.debug(message),\n },\n ...params.runtime,\n });\n }\n\n const { storage, permitStorage } = resolveStorage(params.storage, params.permitStorage);\n\n const router = new ChainRouter(params.chains, params.relayers);\n\n return {\n chains: params.chains,\n router,\n provider,\n signer,\n storage,\n permitStorage,\n transportKeyPairTTL: parseSchema(\n TransportKeyPairTTLSchema,\n params.transportKeyPairTTL ?? DEFAULT_TRANSPORT_KEY_PAIR_TTL_SECONDS,\n ),\n permitTTL: parseSchema(PermitTTLSchema, params.permitTTL ?? DEFAULT_PERMIT_DURATION_DAYS),\n transportKeyPairScope:\n params.transportKeyPairScope === undefined\n ? undefined\n : parseSchema(TransportKeyPairScopeSchema, params.transportKeyPairScope),\n registryTTL: parseSchema(RegistryTTLSchema, params.registryTTL ?? DEFAULT_REGISTRY_TTL_SECONDS),\n logger,\n onEvent: params.onEvent,\n } as unknown as ZamaConfig;\n}\n","import type {\n WalletAccount,\n WalletAccountChange,\n WalletAccountListener,\n WalletAccountStore,\n} from \"../types\";\n\nexport function walletAccountsEqual(\n a: WalletAccount | undefined,\n b: WalletAccount | undefined,\n): boolean {\n return a?.address === b?.address && a?.chainId === b?.chainId;\n}\n\n/**\n * Writable {@link WalletAccountStore} for custom signer adapters. Adapters call\n * {@link MutableWalletAccountStore.setSnapshot} when their underlying wallet\n * provider notifies of a connect, disconnect, account change, or chain change.\n *\n * Most custom adapters should use the {@link createWalletAccountStore} factory\n * rather than instantiating this class directly.\n */\nexport class MutableWalletAccountStore implements WalletAccountStore {\n readonly #listeners = new Set<WalletAccountListener>();\n #snapshot: WalletAccount | undefined;\n #resolved: boolean;\n\n constructor(initial?: WalletAccount) {\n this.#snapshot = initial;\n this.#resolved = initial !== undefined;\n }\n\n /** Return the current wallet account snapshot, or `undefined` when none is set. */\n getSnapshot(): WalletAccount | undefined {\n return this.#snapshot;\n }\n\n /**\n * Whether the store has received at least one snapshot (via the constructor\n * or {@link setSnapshot}). Adapters whose initial account is only available\n * asynchronously start unresolved; callers can distinguish \"still loading\"\n * from \"wallet not connected\".\n */\n isReady(): boolean {\n return this.#resolved;\n }\n\n /**\n * Push a new wallet account snapshot. No-op when the next value is\n * value-equal to the current one. Emits `{ previous, next }` to every\n * subscriber otherwise.\n */\n setSnapshot(next: WalletAccount | undefined): void {\n this.#resolved = true;\n const previous = this.#snapshot;\n if (walletAccountsEqual(previous, next)) {\n return;\n }\n this.#snapshot = next;\n this.#emit({ previous, next });\n }\n\n /**\n * Register a listener for wallet account changes, emitting the current\n * snapshot immediately if one exists.\n * @returns An unsubscribe function.\n */\n subscribe(listener: WalletAccountListener): () => void {\n this.#listeners.add(listener);\n const snapshot = this.#snapshot;\n if (snapshot) {\n listener({ previous: undefined, next: snapshot });\n }\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n #emit(change: WalletAccountChange): void {\n for (const listener of this.#listeners) {\n listener(change);\n }\n }\n}\n\n/**\n * Create a {@link MutableWalletAccountStore} for a custom {@link GenericSigner}\n * adapter.\n *\n * @param initial - Optional initial wallet account snapshot.\n */\nexport function createWalletAccountStore(initial?: WalletAccount): MutableWalletAccountStore {\n return new MutableWalletAccountStore(initial);\n}\n","import type { Hex } from \"viem\";\nimport { WalletNotConnectedError } from \"../errors\";\nimport type { EIP712TypedData } from \"../relayer/types\";\nimport type {\n ContractAbi,\n GenericSigner,\n WalletAccount,\n WriteContractArgs,\n WriteContractConfig,\n WriteFunctionName,\n} from \"../types\";\nimport { MutableWalletAccountStore } from \"./wallet-account-store\";\n\n/**\n * Abstract base class that supplies the wallet-account / dispose\n * boilerplate every signer adapter needs: an observable wallet-account\n * store, `requireWalletAccount`, and an idempotent `dispose` /\n * `Disposable`. Subclasses provide `signTypedData` and `writeContract` — the\n * resulting concrete class automatically satisfies {@link GenericSigner}.\n *\n * Using this class is optional — implementing {@link GenericSigner} directly\n * with {@link createWalletAccountStore} remains fully supported.\n */\nexport abstract class BaseSigner implements GenericSigner, Disposable {\n /** Observable wallet account readiness state. */\n readonly walletAccount: MutableWalletAccountStore;\n #disposed = false;\n\n constructor(initial?: WalletAccount) {\n this.walletAccount = new MutableWalletAccountStore(initial);\n }\n\n /** Return the connected wallet account or throw {@link WalletNotConnectedError}. */\n requireWalletAccount(operation: string): WalletAccount {\n const account = this.walletAccount.getSnapshot();\n if (!account) {\n throw new WalletNotConnectedError(operation);\n }\n return account;\n }\n\n /** Sign EIP-712 typed data (used for decrypt authorization). */\n abstract signTypedData(typedData: EIP712TypedData): Promise<Hex>;\n\n /** Send a write transaction and return the tx hash. */\n abstract writeContract<\n const TAbi extends ContractAbi,\n TFunctionName extends WriteFunctionName<TAbi>,\n const TArgs extends WriteContractArgs<TAbi, TFunctionName>,\n >(config: WriteContractConfig<TAbi, TFunctionName, TArgs>): Promise<Hex>;\n\n /** Release adapter-owned wallet watchers or provider event listeners; idempotent. */\n dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.onDispose();\n }\n\n /** `Disposable` support; delegates to {@link BaseSigner.dispose}. */\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n /** Subclass cleanup hook, invoked once on the first {@link BaseSigner.dispose} call. */\n protected onDispose(): void {}\n}\n"],"mappings":"wfAWA,IAAa,EAAb,KAAwD,CACtD,GAA0B,KAC1B,GAA0C,KAC1C,GACA,GACA,GAEA,YAAY,EAAS,kBAAmB,EAAY,EAAG,EAAY,cAAe,CAChF,KAAKA,GAAU,EACf,KAAKC,GAAa,EAClB,KAAKC,GAAa,CACpB,CAEA,IAA+B,CA0C7B,OAzCI,KAAKC,GACA,QAAQ,QAAQ,KAAKA,EAAG,GAE7B,AAIJ,KAAKC,KAAa,IAAI,SAAS,EAAS,IAAW,CACjD,IAAM,EAAU,UAAU,KAAK,KAAKJ,GAAS,KAAKC,EAAU,EAE5D,EAAQ,oBAAwB,CAC9B,IAAM,EAAK,EAAQ,OACd,EAAG,iBAAiB,SAAS,KAAKC,EAAU,GAC/C,EAAG,kBAAkB,KAAKA,GAAY,CAAE,QAAS,KAAM,CAAC,CAE5D,EAEA,EAAQ,cAAkB,CACxB,KAAKC,GAAM,EAAQ,OACnB,KAAKC,GAAa,KAClB,KAAKD,GAAI,oBAAwB,CAG/B,KAAKA,IAAK,MAAM,EAChB,KAAKA,GAAM,KACX,KAAKC,GAAa,IACpB,EACA,KAAKD,GAAI,YAAgB,CACvB,KAAKA,GAAM,KACX,KAAKC,GAAa,IACpB,EACA,EAAQ,KAAKD,EAAG,CAClB,EAEA,EAAQ,YAAgB,CACtB,KAAKA,GAAM,KACX,KAA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CAOA,YAAY,EAAuC,CACjD,KAAKA,GAAY,GACjB,IAAM,EAAW,KAAKD,GAClB,GAAoB,EAAU,CAAI,IAGtC,KAAKA,GAAY,EACjB,KAAKE,GAAM,CAAE,WAAU,MAAK,CAAC,EAC/B,CAOA,UAAU,EAA6C,CACrD,KAAKH,GAAW,IAAI,CAAQ,EAC5B,IAAM,EAAW,KAAKC,GAItB,OAHI,GACF,EAAS,CAAE,SAAU,IAAA,GAAW,KAAM,CAAS,CAAC,MAErC,CACX,KAAKD,GAAW,OAAO,CAAQ,CACjC,CACF,CAEA,GAAM,EAAmC,CACvC,IAAK,IAAM,KAAY,KAAKA,GAC1B,EAAS,CAAM,CAEnB,CACF,EAQA,SAAgB,GAAyB,EAAoD,CAC3F,OAAO,IAAI,EAA0B,CAAO,CAC9C,CCtEA,IAAsB,GAAtB,KAAsE,CAEpE,cACA,GAAY,GAEZ,YAAY,EAAyB,CACnC,KAAK,cAAgB,IAAI,EAA0B,CAAO,CAC5D,CAGA,qBAAqB,EAAkC,CACrD,IAAM,EAAU,KAAK,cAAc,YAAY,EAC/C,GAAI,CAAC,EACH,MAAM,IAAI,EAAwB,CAAS,EAE7C,OAAO,CACT,CAaA,SAAgB,CACV,KAAKI,KAGT,KAAKA,GAAY,GACjB,KAAK,UAAU,EACjB,CAGA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CAGA,WAA4B,CAAC,CAC/B"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e={id:1,gatewayChainId:261131,relayerUrl:`https://relayer.mainnet.zama.org`,network:`https://ethereum-rpc.publicnode.com`,aclContractAddress:`0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6`,kmsContractAddress:`0x77627828a55156b04Ac0DC0eb30467f1a552BB03`,inputVerifierContractAddress:`0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2`,verifyingContractAddressDecryption:`0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24`,verifyingContractAddressInputVerification:`0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287`,registryAddress:`0xeb5015fF021DB115aCe010f23F55C2591059bBA0`},t={id:11155111,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org`,network:`https://ethereum-sepolia-rpc.publicnode.com`,aclContractAddress:`0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D`,kmsContractAddress:`0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A`,inputVerifierContractAddress:`0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0x2f0750Bbb0A246059d80e94c454586a7F27a128e`},n={id:80002,gatewayChainId:10901,relayerUrl:`https://relayer.testnet.zama.org`,network:`https://polygon-amoy-bor-rpc.publicnode.com`,aclContractAddress:`0xD99Cb9Fc3c42c87f2A4A12e8Fd60318d6bDdf985`,kmsContractAddress:`0xCD1D89E311bce4C8DEa9a0857a0c9A4E153D4041`,inputVerifierContractAddress:`0x6e5A7D8b0c645467Cba7e62D6624917085118631`,verifyingContractAddressDecryption:`0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478`,verifyingContractAddressInputVerification:`0x483b9dE06E4E4C7D35CCf5837A1668487406D955`,registryAddress:`0xF486c3D4F4562760A43883e72E8D6f6Cf2EFdA94`},r={id:560048,gatewayChainId:10901,relayerUrl:``,network:`https://rpc.hoodi.ethpandaops.io`,aclContractAddress:`0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68`,kmsContractAddress:`0x822BE20679CfAfdc352F05dEdfe12a07E912212e`,inputVerifierContractAddress:`0xf3D9A51f32D9bC23E1eECb0fAbF1f1DA4d9Bba26`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0x1807aE2f693F8530DFB126D0eF98F2F2518F292f`,executorAddress:`0xC316692627de536368d82e9121F1D44a550894E6`},i={id:364301,gatewayChainId:10901,relayerUrl:``,network:`https://rpc.ingen.t-rex.network`,aclContractAddress:`0x09a4710BfBe7B557cD5CFE88BB31e9b5b85C419b`,kmsContractAddress:`0xd885DEa6a924785fCcdf9CE993FEe27EA11832e6`,inputVerifierContractAddress:`0x90f05B10db153365D8cB143EA17f5E5714D0bCD5`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0x7FC3D79EF9d01fA318CF2Aa5D91dDC492383Be0F`,executorAddress:`0x1B05DE5b67b8f8363DC04E3a5996a616f11f8C7B`},a={id:97,gatewayChainId:10901,relayerUrl:``,network:`https://bsc-testnet.bnbchain.org`,aclContractAddress:`0x52470e945521E247Cb4754088a836Dc4b838AFBE`,kmsContractAddress:`0x788F5BB2d93aB4Cb67Fe2277757aE95006504F6F`,inputVerifierContractAddress:`0x49e0BAB39904E4192c30CFB58573Cbe27B7E398E`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:`0xc0E8B73b1C58D846e1d4f8fAE2E1466C85BCeAeC`,executorAddress:`0x5985e48689550c1b2893ABfBbe4cc0eE3A22cc54`},o={id:31337,gatewayChainId:10901,relayerUrl:``,network:`http://127.0.0.1:8545`,aclContractAddress:`0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D`,inputVerifierContractAddress:`0x36772142b74871f255CbD7A3e89B401d3e45825f`,kmsContractAddress:`0x901F8942346f7AB3a01F6D7613119Bca447Bb030`,verifyingContractAddressDecryption:`0x5ffdaAB0373E62E2ea2944776209aEf29E631A64`,verifyingContractAddressInputVerification:`0x812b06e1CDCE800494b79fFE4f925A504a9A9810`,registryAddress:void 0,executorAddress:`0xe3a9105a3a932253A70F126eb1E3b589C643dD24`},s=o,c={[e.id]:e,[t.id]:t,[n.id]:n,[r.id]:r,[i.id]:i,[a.id]:a,[o.id]:o};export{r as a,n as c,o as i,t as l,a as n,i as o,c as r,e as s,s as t};
|
|
2
|
-
//# sourceMappingURL=chains-DkH7vYTf.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"chains-DkH7vYTf.js","names":[],"sources":["../../src/chains/configs.ts"],"sourcesContent":["import type { FheChain } from \"./types\";\n\n/**\n * Mainnet network configuration (chainId 1).\n */\nexport const mainnet = {\n id: 1,\n gatewayChainId: 261131,\n relayerUrl: \"https://relayer.mainnet.zama.org\",\n network: \"https://ethereum-rpc.publicnode.com\",\n aclContractAddress: \"0xcA2E8f1F656CD25C01F05d0b243Ab1ecd4a8ffb6\",\n kmsContractAddress: \"0x77627828a55156b04Ac0DC0eb30467f1a552BB03\",\n inputVerifierContractAddress: \"0xCe0FC2e05CFff1B719EFF7169f7D80Af770c8EA2\",\n verifyingContractAddressDecryption: \"0x0f6024a97684f7d90ddb0fAAD79cB15F2C888D24\",\n verifyingContractAddressInputVerification: \"0xcB1bB072f38bdAF0F328CdEf1Fc6eDa1DF029287\",\n registryAddress: \"0xeb5015fF021DB115aCe010f23F55C2591059bBA0\",\n} as const satisfies FheChain;\n\n/**\n * Sepolia testnet network configuration (chainId 11155111).\n */\nexport const sepolia = {\n id: 11155111,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org\",\n network: \"https://ethereum-sepolia-rpc.publicnode.com\",\n aclContractAddress: \"0xf0Ffdc93b7E186bC2f8CB3dAA75D86d1930A433D\",\n kmsContractAddress: \"0xbE0E383937d564D7FF0BC3b46c51f0bF8d5C311A\",\n inputVerifierContractAddress: \"0xBBC1fFCdc7C316aAAd72E807D9b0272BE8F84DA0\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0x2f0750Bbb0A246059d80e94c454586a7F27a128e\",\n} as const satisfies FheChain;\n\n/**\n * Polygon Amoy testnet network configuration (chainId 80002).\n */\nexport const polygonAmoy = {\n id: 80002,\n gatewayChainId: 10901,\n relayerUrl: \"https://relayer.testnet.zama.org\",\n network: \"https://polygon-amoy-bor-rpc.publicnode.com\",\n aclContractAddress: \"0xD99Cb9Fc3c42c87f2A4A12e8Fd60318d6bDdf985\",\n kmsContractAddress: \"0xCD1D89E311bce4C8DEa9a0857a0c9A4E153D4041\",\n inputVerifierContractAddress: \"0x6e5A7D8b0c645467Cba7e62D6624917085118631\",\n verifyingContractAddressDecryption: \"0x5D8BD78e2ea6bbE41f26dFe9fdaEAa349e077478\",\n verifyingContractAddressInputVerification: \"0x483b9dE06E4E4C7D35CCf5837A1668487406D955\",\n registryAddress: \"0xF486c3D4F4562760A43883e72E8D6f6Cf2EFdA94\",\n} as const satisfies FheChain;\n\n/**\n * Hoodi testnet configuration (chainId 560048).\n *\n * Hoodi does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const hoodi = {\n id: 560048,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://rpc.hoodi.ethpandaops.io\",\n aclContractAddress: \"0x6D3FAf6f86e1fF9F3B0831Dda920AbA1cBd5bd68\",\n kmsContractAddress: \"0x822BE20679CfAfdc352F05dEdfe12a07E912212e\",\n inputVerifierContractAddress: \"0xf3D9A51f32D9bC23E1eECb0fAbF1f1DA4d9Bba26\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0x1807aE2f693F8530DFB126D0eF98F2F2518F292f\",\n executorAddress: \"0xC316692627de536368d82e9121F1D44a550894E6\",\n} as const satisfies FheChain;\n\n/**\n * T-Rex InGen testnet configuration (chainId 364301).\n *\n * InGen does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const ingenTestnet = {\n id: 364301,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://rpc.ingen.t-rex.network\",\n aclContractAddress: \"0x09a4710BfBe7B557cD5CFE88BB31e9b5b85C419b\",\n kmsContractAddress: \"0xd885DEa6a924785fCcdf9CE993FEe27EA11832e6\",\n inputVerifierContractAddress: \"0x90f05B10db153365D8cB143EA17f5E5714D0bCD5\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0x7FC3D79EF9d01fA318CF2Aa5D91dDC492383Be0F\",\n executorAddress: \"0x1B05DE5b67b8f8363DC04E3a5996a616f11f8C7B\",\n} as const satisfies FheChain;\n\n/**\n * BNB Smart Chain testnet configuration (chainId 97, Chapel).\n *\n * BSC testnet does not have full FHE infrastructure — use with `cleartext()` transport.\n * Contract addresses match the cleartext deployment.\n */\nexport const bscTestnet = {\n id: 97,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"https://bsc-testnet.bnbchain.org\",\n aclContractAddress: \"0x52470e945521E247Cb4754088a836Dc4b838AFBE\",\n kmsContractAddress: \"0x788F5BB2d93aB4Cb67Fe2277757aE95006504F6F\",\n inputVerifierContractAddress: \"0x49e0BAB39904E4192c30CFB58573Cbe27B7E398E\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: \"0xc0E8B73b1C58D846e1d4f8fAE2E1466C85BCeAeC\",\n executorAddress: \"0x5985e48689550c1b2893ABfBbe4cc0eE3A22cc54\",\n} as const satisfies FheChain;\n\n/**\n * Hardhat local network configuration (chainId 31337).\n *\n * The addresses in this configuration must match those of your deployment.\n */\nexport const hardhat = {\n id: 31337,\n gatewayChainId: 10901,\n relayerUrl: \"\",\n network: \"http://127.0.0.1:8545\",\n aclContractAddress: \"0x50157CFfD6bBFA2DECe204a89ec419c23ef5755D\",\n inputVerifierContractAddress: \"0x36772142b74871f255CbD7A3e89B401d3e45825f\",\n kmsContractAddress: \"0x901F8942346f7AB3a01F6D7613119Bca447Bb030\",\n verifyingContractAddressDecryption: \"0x5ffdaAB0373E62E2ea2944776209aEf29E631A64\",\n verifyingContractAddressInputVerification: \"0x812b06e1CDCE800494b79fFE4f925A504a9A9810\",\n registryAddress: undefined,\n executorAddress: \"0xe3a9105a3a932253A70F126eb1E3b589C643dD24\",\n} as const satisfies FheChain;\n\n/** Alias for {@link hardhat}. */\nexport const anvil = hardhat;\n\n/**\n * Built-in chain configurations keyed by chain ID.\n */\nexport const chains: Record<number, FheChain> = {\n [mainnet.id]: mainnet,\n [sepolia.id]: sepolia,\n [polygonAmoy.id]: polygonAmoy,\n [hoodi.id]: hoodi,\n [ingenTestnet.id]: ingenTestnet,\n [bscTestnet.id]: bscTestnet,\n [hardhat.id]: hardhat,\n} as const;\n"],"mappings":"AAKA,MAAa,EAAU,CACrB,GAAI,EACJ,eAAgB,OAChB,WAAY,mCACZ,QAAS,sCACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,4CACnB,EAKa,EAAU,CACrB,GAAI,SACJ,eAAgB,MAChB,WAAY,mCACZ,QAAS,8CACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,4CACnB,EAKa,EAAc,CACzB,GAAI,MACJ,eAAgB,MAChB,WAAY,mCACZ,QAAS,8CACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,4CACnB,EAQa,EAAQ,CACnB,GAAI,OACJ,eAAgB,MAChB,WAAY,GACZ,QAAS,mCACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,6CACjB,gBAAiB,4CACnB,EAQa,EAAe,CAC1B,GAAI,OACJ,eAAgB,MAChB,WAAY,GACZ,QAAS,kCACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,6CACjB,gBAAiB,4CACnB,EAQa,EAAa,CACxB,GAAI,GACJ,eAAgB,MAChB,WAAY,GACZ,QAAS,mCACT,mBAAoB,6CACpB,mBAAoB,6CACpB,6BAA8B,6CAC9B,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,6CACjB,gBAAiB,4CACnB,EAOa,EAAU,CACrB,GAAI,MACJ,eAAgB,MAChB,WAAY,GACZ,QAAS,wBACT,mBAAoB,6CACpB,6BAA8B,6CAC9B,mBAAoB,6CACpB,mCAAoC,6CACpC,0CAA2C,6CAC3C,gBAAiB,IAAA,GACjB,gBAAiB,4CACnB,EAGa,EAAQ,EAKR,EAAmC,EAC7C,EAAQ,IAAK,GACb,EAAQ,IAAK,GACb,EAAY,IAAK,GACjB,EAAM,IAAK,GACX,EAAa,IAAK,GAClB,EAAW,IAAK,GAChB,EAAQ,IAAK,CAChB"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./relayer-RDPkM3cB.js";import{createFhevmBaseClient as t,createFhevmDecryptClient as n,createFhevmEncryptClient as r}from"@fhevm/sdk/viem";import{createFhevmCleartextBaseClient as i,createFhevmCleartextDecryptClient as a,createFhevmCleartextEncryptClient as o}from"@fhevm/sdk/viem/cleartext";import{createPublicClient as s,custom as c,http as l}from"viem";function u(e){return{id:e.id,fhevm:{contracts:{acl:{address:e.aclContractAddress},inputVerifier:{address:e.inputVerifierContractAddress},kmsVerifier:{address:e.kmsContractAddress},protocolConfig:void 0},relayerUrl:e.relayerUrl,gateway:{id:e.gatewayChainId,contracts:{decryption:{address:e.verifyingContractAddressDecryption},inputVerification:{address:e.verifyingContractAddressInputVerification}}}}}}var d=class{#e;#t;#n;#r;#i;#a;constructor(e){this.#e=e.chain;let{timeout:d,debug:p,batchRpcCalls:m,moduleVersions:h,fheEncryptionKey:g}=e.options??{},_=this.#e.auth?f(this.#e.auth):void 0,v={publicClient:s({transport:typeof this.#e.network==`string`?l(this.#e.network):c(this.#e.network)}),chain:u(this.#e),options:{batchRpcCalls:m,moduleVersions:h,fheEncryptionKey:g}};e.cleartext?(this.#t=i(v),this.#n=a(v),this.#r=o(v)):(this.#t=t(v),this.#n=n(v),this.#r=r(v)),this.#i={..._!==void 0&&{auth:_},...d!==void 0&&{timeout:d},...p!==void 0&&{debug:p}}}get chain(){return this.#e}#o=()=>(this.#a??=this.#t.fetchFheEncryptionKeyBytes({options:this.#i}).then(()=>this.#r.init()),this.#a);decryptPublicValue=async e=>(await this.#t.init(),this.#t.decryptPublicValue({...e,options:{...this.#i,...e.options}}));decryptPublicValues=async e=>(await this.#t.init(),this.#t.decryptPublicValues({...e,options:{...this.#i,...e.options}}));decryptPublicValuesWithSignatures=async e=>(await this.#t.init(),this.#t.decryptPublicValuesWithSignatures({...e,options:{...this.#i,...e.options}}));encryptValue=async e=>(await this.#o(),this.#r.encryptValue({...e,options:{...this.#i,...e.options}}));encryptValues=async e=>(await this.#o(),this.#r.encryptValues({...e,options:{...this.#i,...e.options}}));decryptValue=async e=>(await this.#n.init(),this.#n.decryptValue({...e,options:{...this.#i,...e.options}}));decryptValues=async e=>(await this.#n.init(),this.#n.decryptValues({...e,options:{...this.#i,...e.options}}));decryptValuesFromPairs=async e=>(await this.#n.init(),this.#n.decryptValuesFromPairs({...e,options:{...this.#i,...e.options}}));fetchFheEncryptionKeyBytes=async e=>(await this.#o(),this.#r.fetchFheEncryptionKeyBytes({...e,options:{...this.#i,...e?.options}}));signDecryptionPermit=async e=>(await this.#t.init(),this.#t.signDecryptionPermit(e));serializeTransportKeyPair=e=>this.#n.serializeTransportKeyPair(e);serializeSignedDecryptionPermit=e=>this.#t.serializeSignedDecryptionPermit(e);parseTransportKeyPair=async e=>(await this.#n.init(),this.#n.parseTransportKeyPair(e));parseSignedDecryptionPermit=async e=>(await this.#t.init(),this.#t.parseSignedDecryptionPermit(e));generateTransportKeyPair=async()=>(await this.#n.init(),this.#n.generateTransportKeyPair())};function f(t){let n=t.__type;switch(n){case`ApiKeyHeader`:return{type:n,value:t.value,header:t.header};case`ApiKeyCookie`:return{type:n,value:t.value,cookie:t.cookie};case`BearerToken`:return{type:n,token:t.token};default:throw new e(`Unknown auth type: ${String(n)}`)}}export{d as t};
|
|
2
|
-
//# sourceMappingURL=fhevm-relayer-BTab4pc9.js.map
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function e(e){return e instanceof Error?e:typeof e==`object`&&e&&`message`in e?Error(String(e.message)):Error(String(e))}function t(e){if(!(e instanceof Error))return!1;if(e.name===`ContractFunctionExecutionError`||e.name===`ContractFunctionRevertedError`||`code`in e&&e.code===`CALL_EXCEPTION`)return!0;let t=e.message.toLowerCase();return t.includes(`execution reverted`)||t.includes(`call revert exception`)}const n=[`cause`,`error`,`info`];function r(e,t,i=6){if(i<0||typeof e!=`object`||!e)return;let a=e;if(t(a))return a;for(let e of n){let n=a[e];if(typeof n==`object`&&n){let e=r(n,t,i-1);if(e)return e}}}function i(e){if(e.code===-32005||e.status===429||e.code===429)return!0;if(e.code===`SERVER_ERROR`&&typeof e.info==`object`&&e.info!==null){let t=e.info.responseStatus;if(typeof t==`string`&&/^\s*429\b/.test(t))return!0}return!1}function a(e){if(i(e))return!0;if(typeof e.message==`string`){let t=e.message.toLowerCase();return t.includes(`too many requests`)||t.includes(`rate limit`)||t.includes(`rate-limit`)}return!1}function o(e){return r(e,e=>typeof e.name==`string`&&e.name.startsWith(`Relayer`))!==void 0}function s(e){return r(e,e=>e.name===`RelayerTimeoutError`)!==void 0}function c(e){return!o(e)&&r(e,a)!==void 0}function l(e){return!o(e)&&r(e,i)!==void 0}function u(e){return e.toLowerCase().includes(`is not authorized to decrypt handle`)}function d(e){return e.toLowerCase().includes(`invalid transportkeypair`)}function f(e){return/handle (0x[0-9a-fA-F]{64})/.exec(e)?.[1]}function p(e){if(e==null)return;let t=e.trim();if(t!==``){if(/^\d+$/.test(t))return Number(t);if(/[a-zA-Z]/.test(t)){let e=Date.parse(t);if(!Number.isNaN(e))return Math.max(0,Math.round((e-Date.now())/1e3))}}}function m(e){if(typeof e!=`object`||!e)return;let t=e.get;if(typeof t==`function`)return p(t.call(e,`Retry-After`))}function h(e){let t=e.response;if(typeof t==`object`&&t)return m(t.headers)}function g(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function _(e){return g(e.retryAfter)?e.retryAfter:h(e)}function v(e){let t=r(e,e=>_(e)!==void 0);return t?_(t):void 0}function y(e){let t=r(e,e=>typeof e.statusCode==`number`||typeof e.status==`number`);if(t)return typeof t.statusCode==`number`?t.statusCode:t.status}const b={SigningRejected:`SIGNING_REJECTED`,SigningFailed:`SIGNING_FAILED`,EncryptionFailed:`ENCRYPTION_FAILED`,DecryptionFailed:`DECRYPTION_FAILED`,TransactionReverted:`TRANSACTION_REVERTED`,TransportKeyPairExpired:`KEYPAIR_EXPIRED`,InvalidTransportKeyPair:`INVALID_KEYPAIR`,NoCiphertext:`NO_CIPHERTEXT`,RelayerRequestFailed:`RELAYER_REQUEST_FAILED`,NotEntitled:`NOT_ENTITLED`,RpcRateLimited:`RPC_RATE_LIMITED`,Configuration:`CONFIGURATION`,DelegationSelfNotAllowed:`DELEGATION_SELF_NOT_ALLOWED`,DelegationCooldown:`DELEGATION_COOLDOWN`,DelegationNotFound:`DELEGATION_NOT_FOUND`,DelegationExpired:`DELEGATION_EXPIRED`,InsufficientConfidentialBalance:`INSUFFICIENT_CONFIDENTIAL_BALANCE`,InsufficientERC20Balance:`INSUFFICIENT_ERC20_BALANCE`,InsufficientAllowance:`INSUFFICIENT_ALLOWANCE`,BalanceCheckUnavailable:`BALANCE_CHECK_UNAVAILABLE`,ERC20ReadFailed:`ERC20_READ_FAILED`,DelegationExpiryUnchanged:`DELEGATION_EXPIRY_UNCHANGED`,DelegationDelegateEqualsContract:`DELEGATION_DELEGATE_EQUALS_CONTRACT`,DelegationContractIsSelf:`DELEGATION_CONTRACT_IS_SELF`,AclPaused:`ACL_PAUSED`,DelegationExpirationTooSoon:`DELEGATION_EXPIRATION_TOO_SOON`,DelegationNotPropagated:`DELEGATION_NOT_PROPAGATED`,ChainMismatch:`CHAIN_MISMATCH`,SignerNotConfigured:`SIGNER_NOT_CONFIGURED`,WalletNotConnected:`WALLET_NOT_CONNECTED`,WalletAccountNotReady:`WALLET_ACCOUNT_NOT_READY`,KeyWrappingFailed:`KEY_WRAPPING_FAILED`},x={[b.SigningRejected]:!1,[b.SigningFailed]:!1,[b.EncryptionFailed]:!1,[b.DecryptionFailed]:!1,[b.TransactionReverted]:!1,[b.TransportKeyPairExpired]:!1,[b.InvalidTransportKeyPair]:!1,[b.NoCiphertext]:!1,[b.RelayerRequestFailed]:!1,[b.NotEntitled]:!1,[b.RpcRateLimited]:!0,[b.Configuration]:!1,[b.DelegationSelfNotAllowed]:!1,[b.DelegationCooldown]:!0,[b.DelegationNotFound]:!1,[b.DelegationExpired]:!1,[b.InsufficientConfidentialBalance]:!1,[b.InsufficientERC20Balance]:!1,[b.InsufficientAllowance]:!1,[b.BalanceCheckUnavailable]:!1,[b.ERC20ReadFailed]:!1,[b.DelegationExpiryUnchanged]:!1,[b.DelegationDelegateEqualsContract]:!1,[b.DelegationContractIsSelf]:!1,[b.AclPaused]:!1,[b.DelegationExpirationTooSoon]:!1,[b.DelegationNotPropagated]:!0,[b.ChainMismatch]:!1,[b.SignerNotConfigured]:!1,[b.WalletNotConnected]:!1,[b.WalletAccountNotReady]:!0,[b.KeyWrappingFailed]:!1};var S=class extends Error{code;retryable;constructor(e,t,n){super(t,n),Object.setPrototypeOf(this,new.target.prototype),this.name=`ZamaError`,this.code=e,this.retryable=n?.retryable??x[e]}};function C(e){return e instanceof S&&e.retryable}function w(e){if(!C(e)||!(`retryAfter`in e))return;let t=e.retryAfter;return g(t)?t:void 0}var T=class extends S{statusCode;retryAfter;constructor(e,t,n){let r=n?.retryable??t===429;super(b.RelayerRequestFailed,e,{...n,retryable:r}),this.name=`RelayerRequestFailedError`,this.statusCode=t,this.retryAfter=r?n?.retryAfter:void 0}},E=class extends S{constructor(e,t){super(b.Configuration,e,t),this.name=`ConfigurationError`}};export{e as _,C as a,v as c,d,u as f,f as g,c as h,b as i,l,s as m,T as n,w as o,o as p,S as r,y as s,E as t,t as u};
|
|
2
|
-
//# sourceMappingURL=relayer-RDPkM3cB.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"relayer-RDPkM3cB.js","names":[],"sources":["../../src/utils/error.ts","../../src/errors/base.ts","../../src/errors/relayer.ts"],"sourcesContent":["/** Coerce an unknown caught value to an Error instance. */\nexport function toError(error: unknown): Error {\n if (error instanceof Error) {\n return error;\n }\n if (typeof error === \"object\" && error !== null && \"message\" in error) {\n return new Error(String(error.message));\n }\n return new Error(String(error));\n}\n\n/**\n * Returns true if the error is a contract call revert (as opposed to a network/transport error).\n * Detects viem's ContractFunctionExecutionError / ContractFunctionRevertedError\n * and ethers' CALL_EXCEPTION.\n */\nexport function isContractCallError(error: unknown): boolean {\n if (!(error instanceof Error)) {\n return false;\n }\n // viem: ContractFunctionExecutionError, ContractFunctionRevertedError\n if (\n error.name === \"ContractFunctionExecutionError\" ||\n error.name === \"ContractFunctionRevertedError\"\n ) {\n return true;\n }\n // ethers: error.code === \"CALL_EXCEPTION\"\n if (\"code\" in error && error.code === \"CALL_EXCEPTION\") {\n return true;\n }\n // Fallback: common revert message patterns from various providers\n const msg = error.message.toLowerCase();\n return msg.includes(\"execution reverted\") || msg.includes(\"call revert exception\");\n}\n\n/** JSON-RPC error code providers use for rate limiting (\"limit exceeded\"). */\nconst JSON_RPC_LIMIT_EXCEEDED = -32005;\n\n/** Properties that may nest a lower-level cause across viem / ethers / fetch. */\nconst NESTED_ERROR_KEYS = [\"cause\", \"error\", \"info\"] as const;\n\n/**\n * Walk an error and its nested causes (`cause` / `error` / `info`, as used by\n * viem, ethers, and fetch wrappers), applying `predicate` to each object node.\n * Returns the first node for which `predicate` returns true, or `undefined`.\n * Depth-bounded to avoid pathological / cyclic structures.\n */\nfunction findInErrorChain(\n error: unknown,\n predicate: (node: Record<string, unknown>) => boolean,\n depth = 6,\n): Record<string, unknown> | undefined {\n if (depth < 0 || error === null || error === undefined || typeof error !== \"object\") {\n return undefined;\n }\n const node = error as Record<string, unknown>;\n if (predicate(node)) {\n return node;\n }\n for (const key of NESTED_ERROR_KEYS) {\n const next = node[key];\n if (next !== undefined && next !== null && typeof next === \"object\") {\n const found = findInErrorChain(next, predicate, depth - 1);\n if (found) {\n return found;\n }\n }\n }\n return undefined;\n}\n\n// ============================================================================\n// Classification detectors\n// ============================================================================\n\n/**\n * Structured (unambiguous) consumer rate-limit signal across the RPC providers\n * the SDK reads through:\n * - JSON-RPC `-32005` (\"limit exceeded\");\n * - viem-style numeric `status: 429`, and viem's own `shouldRetry` shape where\n * the JSON-RPC error `code` is `429`;\n * - ethers' 429, which surfaces as `code: \"SERVER_ERROR\"` with the status only\n * in `info.responseStatus` (a string like `\"429 Too Many Requests\"`) and no\n * numeric top-level status — the leading code is parsed out of it.\n *\n * Deliberately NOT `statusCode: 429` — that is the relayer / node-fetch HTTP\n * shape, which stays {@link RelayerRequestFailedError} (SDK-236), so a relayer\n * 429 is never mistaken for a consumer-RPC throttle.\n */\nfunction nodeHasStructuredRateLimit(node: Record<string, unknown>): boolean {\n if (node.code === JSON_RPC_LIMIT_EXCEEDED || node.status === 429 || node.code === 429) {\n return true;\n }\n // ethers: `code: \"SERVER_ERROR\"`, status lives in `info.responseStatus`.\n if (node.code === \"SERVER_ERROR\" && typeof node.info === \"object\" && node.info !== null) {\n const responseStatus = (node.info as Record<string, unknown>).responseStatus;\n if (typeof responseStatus === \"string\" && /^\\s*429\\b/.test(responseStatus)) {\n return true;\n }\n }\n return false;\n}\n\nfunction nodeIsRpcRateLimit(node: Record<string, unknown>): boolean {\n if (nodeHasStructuredRateLimit(node)) {\n return true;\n }\n // Message fallback for providers without a structured code. Deliberately\n // narrow (specific throttling phrases, no bare \"429\") to avoid false positives\n // that would turn a terminal error into a retryable one.\n if (typeof node.message === \"string\") {\n const msg = node.message.toLowerCase();\n return (\n msg.includes(\"too many requests\") || msg.includes(\"rate limit\") || msg.includes(\"rate-limit\")\n );\n }\n return false;\n}\n\n/**\n * True when a failure originates from `@fhevm/sdk`'s relayer transport. Every\n * relayer error it throws — `RelayerResponseStatusError`, `RelayerResponseApiError`,\n * `RelayerMaxRetryError`, `RelayerTimeoutError`, … — carries the `Relayer` `name`\n * prefix. Such errors stay the relayer's domain ({@link RelayerRequestFailedError}\n * / SDK-236), never {@link RpcRateLimitError}, even on a 429 (which `@fhevm/sdk`\n * retries internally, honoring `Retry-After`, before surfacing).\n */\nexport function isRelayerError(error: unknown): boolean {\n return (\n findInErrorChain(\n error,\n (node) => typeof node.name === \"string\" && node.name.startsWith(\"Relayer\"),\n ) !== undefined\n );\n}\n\n/**\n * True when the failure is an `@fhevm/sdk` relayer *timeout* (`RelayerTimeoutError`,\n * thrown when a request exceeds the relayer's global deadline without a verdict).\n * Unlike a terminal 4xx/5xx, the operation itself is safe to retry, so callers map\n * it to a {@link RelayerRequestFailedError} with `retryable: true` — mirroring the\n * former `WorkerTimeoutError`, which was likewise documented retryable.\n */\nexport function isRelayerTimeoutError(error: unknown): boolean {\n return findInErrorChain(error, (node) => node.name === \"RelayerTimeoutError\") !== undefined;\n}\n\n/**\n * True if the error is the consumer's RPC provider throttling an on-chain read\n * (HTTP 429 / JSON-RPC -32005). Relayer-originated 429s are excluded.\n */\nexport function isRpcRateLimitError(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeIsRpcRateLimit) !== undefined;\n}\n\n/**\n * Like {@link isRpcRateLimitError} but only matches an unambiguous **structured**\n * signal (`-32005` or a viem `status: 429`), ignoring message text. The classifier\n * promotes this ahead of any HTTP status, while a message-only throttle is only\n * trusted when no status is present — so a relayer HTTP error whose body happens\n * to say \"rate limit\" still maps to {@link RelayerRequestFailedError}.\n */\nexport function hasStructuredRpcRateLimitSignal(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n return findInErrorChain(error, nodeHasStructuredRateLimit) !== undefined;\n}\n\n/**\n * Transport-error signatures of the consumer's own RPC client (viem / ethers).\n * The SDK's on-chain reads (the ACL `persistAllowed` pre-check) go through that\n * client, which already retries transport faults internally — so a failure\n * carrying one of these shapes must NOT be retried again by the SDK on top.\n */\nfunction nodeHasConsumerRpcSignature(node: Record<string, unknown>): boolean {\n // ethers transient transport codes.\n const code = node.code;\n if (code === \"NETWORK_ERROR\" || code === \"SERVER_ERROR\" || code === \"TIMEOUT\") {\n return true;\n }\n // viem transport error classes, matched by `name`.\n const name = node.name;\n return (\n name === \"HttpRequestError\" ||\n name === \"RpcRequestError\" ||\n name === \"TimeoutError\" ||\n name === \"WebSocketRequestError\"\n );\n}\n\n/**\n * True when a failure originates from the **consumer's RPC provider** (viem /\n * ethers) rather than the relayer. Keeps the SDK's relayer retry from\n * double-retrying transport faults the integrator's client already retried.\n * A relayer error (`Relayer*`) is never consumer-RPC.\n */\nexport function isConsumerRpcError(error: unknown): boolean {\n if (isRelayerError(error)) {\n return false;\n }\n if (hasStructuredRpcRateLimitSignal(error)) {\n return true;\n }\n return findInErrorChain(error, nodeHasConsumerRpcSignature) !== undefined;\n}\n\n/**\n * `@fhevm/sdk`'s ACL gate (`checkPersistAllowed`) throws an `AclUserDecryptionError`\n * when the requesting actor isn't allowed: `User <a> is not authorized to decrypt\n * handle <h>!`. Matching that phrase is what lets {@link wrapDecryptError} surface\n * a typed NotEntitledError with the parsed handle.\n *\n * Deliberately excludes the sibling `Dapp contract <a> is not authorized to\n * **user** decrypt handle <h>!` — a dapp ACL misconfig, intentionally left to\n * DecryptionFailedError. The differentiator is the inserted \"user\": the actor\n * message reads \"…to decrypt handle\", the dapp message \"…to user decrypt handle\",\n * so keying on \"is not authorized to decrypt handle\" matches only the former.\n *\n * The `error.test.ts` drift guard reads the installed `@fhevm/sdk` source and\n * fails loudly if the message is reworded.\n */\nexport function isNotEntitledMessage(message: string): boolean {\n return message.toLowerCase().includes(\"is not authorized to decrypt handle\");\n}\n\n/**\n * `@fhevm/sdk`'s `verifyTkmsPublicKey` throws `invalid TransportKeyPairKeyPair`\n * when a stored transport key pair can't be re-derived under the current TKMS\n * version — the signal that the persisted key pair is stale (typically after a\n * KMS/TKMS rotation) and must be evicted and regenerated. Matching it lets the\n * signing and decrypt paths surface a typed {@link InvalidTransportKeyPairError}\n * and self-heal the vault entry.\n */\nexport function isInvalidTransportKeyPairMessage(message: string): boolean {\n return message.toLowerCase().includes(\"invalid transportkeypair\");\n}\n\n/** Parse the on-chain handle out of the not-entitled message. */\nexport function parseHandleFromMessage(message: string): string | undefined {\n return /handle (0x[0-9a-fA-F]{64})/.exec(message)?.[1];\n}\n\n/**\n * Parse an HTTP `Retry-After` header value into **seconds** (the SDK's duration\n * unit and the header's own unit), or `undefined` when absent/unparseable. Per\n * RFC 9110 the value is either a non-negative number of seconds (`\"120\"`) or an\n * HTTP-date; a past date floors to `0`.\n */\nexport function parseRetryAfterHeader(value: string | null | undefined): number | undefined {\n if (value === null || value === undefined) {\n return undefined;\n }\n const trimmed = value.trim();\n if (trimmed === \"\") {\n return undefined;\n }\n // delta-seconds: a non-negative integer (already the unit we want).\n if (/^\\d+$/.test(trimmed)) {\n return Number(trimmed);\n }\n // HTTP-date — an IMF-fixdate always carries alphabetic day/month names, so\n // require a letter before deferring to the lenient Date.parse.\n if (/[a-zA-Z]/.test(trimmed)) {\n const dateMs = Date.parse(trimmed);\n if (!Number.isNaN(dateMs)) {\n return Math.max(0, Math.round((dateMs - Date.now()) / 1000));\n }\n }\n return undefined;\n}\n\n/** Read a `Retry-After` header (→ seconds) off a `Headers`-like object, if present. */\nfunction readRetryAfterHeader(headers: unknown): number | undefined {\n if (headers === null || typeof headers !== \"object\") {\n return undefined;\n }\n const get = (headers as { get?: unknown }).get;\n if (typeof get !== \"function\") {\n return undefined;\n }\n return parseRetryAfterHeader(\n (get as (name: string) => string | null).call(headers, \"Retry-After\"),\n );\n}\n\n/**\n * A node's **relayer** `Retry-After` header (seconds), read from a wrapped fetch\n * `Response` (the relayer's `cause.response.headers`). The SDK owns the\n * relayer fetch, so parsing the header there is legitimate.\n *\n * The viem/chain side (`HttpRequestError.headers`) is deliberately **not** read:\n * for consumer RPC the integrator's viem/ethers transport already honors\n * `Retry-After` in its own retry loop (and retries) before the error ever\n * surfaces, so re-reading it here would re-implement a transport concern.\n * Chain-RPC backoff is configured on the consumer's transport (`chain.network`).\n */\nfunction retryAfterFromHeader(node: Record<string, unknown>): number | undefined {\n const response = node.response;\n if (response !== null && typeof response === \"object\") {\n return readRetryAfterHeader((response as Record<string, unknown>).headers);\n }\n return undefined;\n}\n\n/**\n * True for a well-formed server-driven retry delay, in seconds: a finite,\n * positive number. Shared by the chain-walking extractor below and the public\n * {@link retryAfterSeconds} accessor (`errors/base.ts`), so a malformed value\n * (`0`, negative, `NaN`) is rejected the same way everywhere instead of being\n * handed unchanged to a `setTimeout` backoff.\n */\nexport function isValidRetryAfterSeconds(value: unknown): value is number {\n return typeof value === \"number\" && Number.isFinite(value) && value > 0;\n}\n\n/**\n * A single node's server-driven retry delay (seconds): a numeric `retryAfter`\n * (a non-positive synthetic value is ignored), else a `Retry-After` header.\n */\nfunction retryAfterFromNode(node: Record<string, unknown>): number | undefined {\n if (isValidRetryAfterSeconds(node.retryAfter)) {\n return node.retryAfter;\n }\n return retryAfterFromHeader(node);\n}\n\n/**\n * Best-effort extraction of a server-driven retry delay, in **seconds**, from\n * anywhere in an error's cause chain. Reads a numeric `retryAfter` property and\n * the **relayer's** `Retry-After` header (`cause.response.headers`). The\n * consumer-RPC/chain side is intentionally not read — viem/ethers own that\n * backoff (see {@link retryAfterFromHeader}). `undefined` when absent.\n */\nexport function extractRetryAfter(error: unknown): number | undefined {\n const node = findInErrorChain(error, (n) => retryAfterFromNode(n) !== undefined);\n return node ? retryAfterFromNode(node) : undefined;\n}\n\n/**\n * Extract an HTTP status code from an error or anywhere in its cause chain.\n * Relayer SDK errors may carry a `status` or `statusCode` property; walking the\n * full chain (rather than just depth-1) keeps this in step with the other\n * chain-walking detectors and avoids a depth asymmetry between them.\n */\nexport function extractHttpStatus(error: unknown): number | undefined {\n const node = findInErrorChain(\n error,\n (n) => typeof n.statusCode === \"number\" || typeof n.status === \"number\",\n );\n if (!node) {\n return undefined;\n }\n return (typeof node.statusCode === \"number\" ? node.statusCode : node.status) as number;\n}\n","import { isValidRetryAfterSeconds } from \"../utils/error\";\n\n/**\n * Typed error codes thrown by the SDK.\n * Use `error.code` or `instanceof` to programmatically handle specific failure modes.\n *\n * @example\n * ```ts\n * try {\n * await token.confidentialTransfer(\"0xTo\", 100n);\n * } catch (e) {\n * if (e instanceof SigningRejectedError) {\n * // User rejected the wallet signature\n * }\n * }\n * ```\n */\nexport const ZamaErrorCode = {\n /** User rejected the wallet signature prompt. */\n SigningRejected: \"SIGNING_REJECTED\",\n /** Wallet signature failed for a reason other than rejection. */\n SigningFailed: \"SIGNING_FAILED\",\n /** FHE encryption failed. */\n EncryptionFailed: \"ENCRYPTION_FAILED\",\n /** FHE decryption failed. */\n DecryptionFailed: \"DECRYPTION_FAILED\",\n /** On-chain transaction reverted. */\n TransactionReverted: \"TRANSACTION_REVERTED\",\n /** Transport key pair has expired and needs regeneration. */\n TransportKeyPairExpired: \"KEYPAIR_EXPIRED\",\n /** Relayer rejected transport key pair (stale, expired, or malformed). */\n InvalidTransportKeyPair: \"INVALID_KEYPAIR\",\n /** No FHE ciphertext exists for this account (never shielded). */\n NoCiphertext: \"NO_CIPHERTEXT\",\n /** Relayer HTTP request failed. */\n RelayerRequestFailed: \"RELAYER_REQUEST_FAILED\",\n /** The configured signer/account is not entitled (ACL) to decrypt this encrypted value. Don't retry — wait for a grant. */\n NotEntitled: \"NOT_ENTITLED\",\n /** The consumer's RPC provider rate-limited an on-chain read (e.g. HTTP 429 / JSON-RPC -32005). Retryable. */\n RpcRateLimited: \"RPC_RATE_LIMITED\",\n /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\n Configuration: \"CONFIGURATION\",\n /** Delegation cannot target self (delegate === msg.sender). */\n DelegationSelfNotAllowed: \"DELEGATION_SELF_NOT_ALLOWED\",\n /** Only one delegate/revoke per (delegator, delegate, contract) per block. */\n DelegationCooldown: \"DELEGATION_COOLDOWN\",\n /** No active delegation found for this (delegator, delegate, contract) tuple. */\n DelegationNotFound: \"DELEGATION_NOT_FOUND\",\n /** The delegation has expired. */\n DelegationExpired: \"DELEGATION_EXPIRED\",\n /** Confidential (cToken) balance is insufficient for the requested operation. */\n InsufficientConfidentialBalance: \"INSUFFICIENT_CONFIDENTIAL_BALANCE\",\n /** ERC-20 balance is insufficient for the requested shield amount. */\n InsufficientERC20Balance: \"INSUFFICIENT_ERC20_BALANCE\",\n /** ERC-20 allowance granted to the wrapper is insufficient for the requested wrap amount. */\n InsufficientAllowance: \"INSUFFICIENT_ALLOWANCE\",\n /** Balance validation could not be performed (no cached credentials and decryption not possible). */\n BalanceCheckUnavailable: \"BALANCE_CHECK_UNAVAILABLE\",\n /** Public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\n ERC20ReadFailed: \"ERC20_READ_FAILED\",\n /** The new expiration date equals the current one — no on-chain change needed. */\n DelegationExpiryUnchanged: \"DELEGATION_EXPIRY_UNCHANGED\",\n /** Delegate address cannot be the contract address. */\n DelegationDelegateEqualsContract: \"DELEGATION_DELEGATE_EQUALS_CONTRACT\",\n /** Contract address cannot be the sender address. */\n DelegationContractIsSelf: \"DELEGATION_CONTRACT_IS_SELF\",\n /** The ACL contract is paused. */\n AclPaused: \"ACL_PAUSED\",\n /** Expiration date is too soon (must be at least 1 hour in the future). */\n DelegationExpirationTooSoon: \"DELEGATION_EXPIRATION_TOO_SOON\",\n /** Delegation exists on-chain but hasn't propagated to the gateway yet. */\n DelegationNotPropagated: \"DELEGATION_NOT_PROPAGATED\",\n /** Signer and provider are connected to different chains. */\n ChainMismatch: \"CHAIN_MISMATCH\",\n /** Operation requires a signer but none is configured. */\n SignerNotConfigured: \"SIGNER_NOT_CONFIGURED\",\n /** Operation requires a connected wallet account. */\n WalletNotConnected: \"WALLET_NOT_CONNECTED\",\n /** Wallet account discovery is still resolving. */\n WalletAccountNotReady: \"WALLET_ACCOUNT_NOT_READY\",\n /** Wrapping or unwrapping the transport private key with `transportKeyPairDerivationSecret` failed. */\n KeyWrappingFailed: \"KEY_WRAPPING_FAILED\",\n} as const;\n\n/** Union of all {@link ZamaErrorCode} string values. */\nexport type ZamaErrorCode = (typeof ZamaErrorCode)[keyof typeof ZamaErrorCode];\n\n/** Identity type that fails to instantiate unless `T` maps every {@link ZamaErrorCode} to a `boolean`. */\ntype Complete<T extends Record<ZamaErrorCode, boolean>> = T;\n\n/**\n * Default retryability for each {@link ZamaErrorCode}. `Complete` fails the build\n * if a new code is added without an entry here — the same exhaustiveness guard\n * `matchZamaError`'s `ErrorForCode` map uses (see `match.ts`) — so a new\n * transient (or terminal) cause can't silently default to the wrong signal.\n *\n * {@link RelayerRequestFailedError} is the one exception: its retryability\n * depends on the HTTP status (only a 429 is retryable), not just the code, so\n * it overrides this default via the constructor's `retryable` option instead\n * of being read from here.\n */\nconst RETRYABLE_BY_CODE: Complete<Record<ZamaErrorCode, boolean>> = {\n [ZamaErrorCode.SigningRejected]: false,\n [ZamaErrorCode.SigningFailed]: false,\n [ZamaErrorCode.EncryptionFailed]: false,\n [ZamaErrorCode.DecryptionFailed]: false,\n [ZamaErrorCode.TransactionReverted]: false,\n [ZamaErrorCode.TransportKeyPairExpired]: false,\n [ZamaErrorCode.InvalidTransportKeyPair]: false,\n [ZamaErrorCode.NoCiphertext]: false,\n [ZamaErrorCode.RelayerRequestFailed]: false, // conditional — see doc above\n [ZamaErrorCode.NotEntitled]: false,\n [ZamaErrorCode.RpcRateLimited]: true,\n [ZamaErrorCode.Configuration]: false,\n [ZamaErrorCode.DelegationSelfNotAllowed]: false,\n [ZamaErrorCode.DelegationCooldown]: true, // per-block timing gate, resolves on next-block retry\n [ZamaErrorCode.DelegationNotFound]: false,\n [ZamaErrorCode.DelegationExpired]: false,\n [ZamaErrorCode.InsufficientConfidentialBalance]: false,\n [ZamaErrorCode.InsufficientERC20Balance]: false,\n [ZamaErrorCode.InsufficientAllowance]: false, // terminal: caller must approve a larger allowance\n [ZamaErrorCode.BalanceCheckUnavailable]: false,\n [ZamaErrorCode.ERC20ReadFailed]: false, // conservative: conflates network (transient) and contract (terminal) faults, see class doc\n [ZamaErrorCode.DelegationExpiryUnchanged]: false,\n [ZamaErrorCode.DelegationDelegateEqualsContract]: false,\n [ZamaErrorCode.DelegationContractIsSelf]: false,\n [ZamaErrorCode.AclPaused]: false,\n [ZamaErrorCode.DelegationExpirationTooSoon]: false,\n [ZamaErrorCode.DelegationNotPropagated]: true,\n [ZamaErrorCode.ChainMismatch]: false,\n [ZamaErrorCode.SignerNotConfigured]: false,\n [ZamaErrorCode.WalletNotConnected]: false,\n [ZamaErrorCode.WalletAccountNotReady]: true, // async wallet-account discovery still resolving\n [ZamaErrorCode.KeyWrappingFailed]: false, // a transportKeyPairDerivationSecret mismatch or environment capability issue, not transient\n};\n\n/**\n * Base error thrown by all SDK operations.\n * Carries a {@link ZamaErrorCode} for programmatic error handling.\n * Prefer catching specific subclasses (e.g. {@link EncryptionFailedError}).\n */\nexport class ZamaError extends Error {\n /** Machine-readable error code. */\n readonly code: ZamaErrorCode;\n\n /**\n * Whether the operation that threw this error is safe to retry. Defaults to\n * {@link RETRYABLE_BY_CODE}'s entry for `code`; only {@link RelayerRequestFailedError}\n * overrides it per-instance (its retryability depends on the HTTP status).\n * Prefer {@link isRetryable} over reading this directly, so a new `unknown`\n * caught value doesn't need an `instanceof ZamaError` check first.\n */\n readonly retryable: boolean;\n\n constructor(\n code: ZamaErrorCode,\n message: string,\n options?: ErrorOptions & { retryable?: boolean },\n ) {\n super(message, options);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"ZamaError\";\n this.code = code;\n this.retryable = options?.retryable ?? RETRYABLE_BY_CODE[code];\n }\n}\n\n/**\n * True if `error` is a {@link ZamaError} whose failure is transient and safe to\n * retry (rate-limited, back-pressured, a delegation still propagating or in\n * its per-block cooldown, or a wallet account still resolving).\n * Compiler-guaranteed to stay in sync with the\n * taxonomy: every {@link ZamaError} subclass declares its own retryability via\n * {@link ZamaError.retryable}, so a consumer never has to hardcode a set of\n * retryable codes.\n *\n * @example\n * ```ts\n * try {\n * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);\n * } catch (e) {\n * if (isRetryable(e)) {\n * // back off and retry (see retryAfterSeconds for a server-suggested delay)\n * } else {\n * throw e; // terminal — surface it\n * }\n * }\n * ```\n */\nexport function isRetryable(error: unknown): error is ZamaError & { retryable: true } {\n return error instanceof ZamaError && error.retryable;\n}\n\n/**\n * The server-suggested retry delay, in **seconds**, for a retryable\n * {@link ZamaError} — unifying the `retryAfter` field that today lives on\n * {@link RelayerRequestFailedError} and {@link RpcRateLimitError} only.\n * `undefined` when the error isn't retryable, or is retryable but carries no\n * server-driven delay (e.g. {@link DelegationNotPropagatedError} — retry that\n * with your own backoff).\n */\nexport function retryAfterSeconds(error: unknown): number | undefined {\n if (!isRetryable(error) || !(\"retryAfter\" in error)) {\n return undefined;\n }\n const retryAfter = (error as ZamaError & { retryAfter?: unknown }).retryAfter;\n return isValidRetryAfterSeconds(retryAfter) ? retryAfter : undefined;\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Relayer HTTP request failed. */\nexport class RelayerRequestFailedError extends ZamaError {\n /** HTTP status code from the relayer, if available. */\n readonly statusCode: number | undefined;\n\n /**\n * Server-driven retry delay in **seconds** (the SDK's duration unit and the\n * header's own unit), from the relayer's `Retry-After` header. Set only on\n * back-pressure (HTTP 429) responses that carry the header; `undefined`\n * otherwise. Implies {@link ZamaError.retryable}.\n */\n readonly retryAfter: number | undefined;\n\n constructor(\n message: string,\n statusCode?: number,\n options?: ErrorOptions & { retryAfter?: number; retryable?: boolean },\n ) {\n // Retryable on relayer back-pressure (HTTP 429) by default, or when the\n // caller forces it (a relayer timeout has no status but is safe to retry).\n const retryable = options?.retryable ?? statusCode === 429;\n super(ZamaErrorCode.RelayerRequestFailed, message, { ...options, retryable });\n this.name = \"RelayerRequestFailedError\";\n this.statusCode = statusCode;\n // Keep the two fields consistent: a delay only makes sense when retryable,\n // and only a 429 actually carries a server-supplied `Retry-After`.\n this.retryAfter = retryable ? options?.retryAfter : undefined;\n }\n}\n\n/** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */\nexport class ConfigurationError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.Configuration, message, options);\n this.name = \"ConfigurationError\";\n }\n}\n"],"mappings":"AACA,SAAgB,EAAQ,EAAuB,CAO7C,OANI,aAAiB,MACZ,EAEL,OAAO,GAAU,UAAY,GAAkB,YAAa,EACnD,MAAM,OAAO,EAAM,OAAO,CAAC,EAE7B,MAAM,OAAO,CAAK,CAAC,CAChC,CAOA,SAAgB,EAAoB,EAAyB,CAC3D,GAAI,EAAE,aAAiB,OACrB,MAAO,GAUT,GANE,EAAM,OAAS,kCACf,EAAM,OAAS,iCAKb,SAAU,GAAS,EAAM,OAAS,iBACpC,MAAO,GAGT,IAAM,EAAM,EAAM,QAAQ,YAAY,EACtC,OAAO,EAAI,SAAS,oBAAoB,GAAK,EAAI,SAAS,uBAAuB,CACnF,CAGA,MAGM,EA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,IACxC,EAAc,iBAAkB,IAChC,EAAc,2BAA4B,IAC1C,EAAc,kCAAmC,IACjD,EAAc,0BAA2B,IACzC,EAAc,WAAY,IAC1B,EAAc,6BAA8B,IAC5C,EAAc,yBAA0B,IACxC,EAAc,eAAgB,IAC9B,EAAc,qBAAsB,IACpC,EAAc,oBAAqB,IACnC,EAAc,uBAAwB,IACtC,EAAc,mBAAoB,EACrC,EAOA,IAAa,EAAb,cAA+B,KAAM,CAEnC,KASA,UAEA,YACE,EACA,EACA,EACA,CACA,MAAM,EAAS,CAAO,EACtB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,EAChD,KAAK,KAAO,YACZ,KAAK,KAAO,EACZ,KAAK,UAAY,GAAS,WAAa,EAAkB,EAC3D,CACF,EAwBA,SAAgB,EAAY,EAA0D,CACpF,OAAO,aAAiB,GAAa,EAAM,SAC7C,CAUA,SAAgB,EAAkB,EAAoC,CACpE,GAAI,CAAC,EAAY,CAAK,GAAK,EAAE,eAAgB,GAC3C,OAEF,IAAM,EAAc,EAA+C,WACnE,OAAO,EAAyB,CAAU,EAAI,EAAa,IAAA,EAC7D,CC5MA,IAAa,EAAb,cAA+C,CAAU,CAEvD,WAQA,WAEA,YACE,EACA,EACA,EACA,CAGA,IAAM,EAAY,GAAS,WAAa,IAAe,IACvD,MAAM,EAAc,qBAAsB,EAAS,CAAE,GAAG,EAAS,WAAU,CAAC,EAC5E,KAAK,KAAO,4BACZ,KAAK,WAAa,EAGlB,KAAK,WAAa,EAAY,GAAS,WAAa,IAAA,EACtD,CACF,EAGa,EAAb,cAAwC,CAAU,CAChD,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAc,cAAe,EAAS,CAAO,EACnD,KAAK,KAAO,oBACd,CACF"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{d as e,i as t,r as n}from"./relayer-RDPkM3cB.js";import{erc20Abi as r}from"viem";var i=class extends n{constructor(e,n){super(t.TransportKeyPairExpired,e,n),this.name=`TransportKeyPairExpiredError`}},a=class extends n{constructor(e,n){super(t.InvalidTransportKeyPair,e,n),this.name=`InvalidTransportKeyPairError`}},o=class extends n{constructor(e,n){super(t.NoCiphertext,e,n),this.name=`NoCiphertextError`}},s=class extends n{constructor(e,n){super(t.KeyWrappingFailed,e,n),this.name=`KeyWrappingError`}},c=class extends n{constructor(e,n){super(t.SigningRejected,e,n),this.name=`SigningRejectedError`}},l=class extends n{constructor(e,n){super(t.SigningFailed,e,n),this.name=`SigningFailedError`}};function u(t,n){let r=typeof t==`object`&&!!t&&`code`in t&&t.code===4001,i=t instanceof Error?t.message:String(t),o=i.toLowerCase(),s=o.includes(`user rejected`)||o.includes(`user denied`),u=`${n}: ${i}`;throw r||s?new c(u,{cause:t}):e(i)?new a(u,{cause:t}):new l(u,{cause:t})}var d=class extends n{constructor(e,n){super(t.TransactionReverted,e,n),this.name=`TransactionRevertedError`}},f=class extends n{operation;constructor(e,t,n,r){super(e,n,r),this.name=`SignerRequiredError`,this.operation=t}},p=class extends f{constructor(e,n){super(t.SignerNotConfigured,e,`Cannot ${e} without a signer. Configure one via createConfig({ signer: ... }) or <ZamaProvider config={createConfig({ signer: ... })}>.`,n),this.name=`SignerNotConfiguredError`}},m=class extends f{constructor(e,n){super(t.WalletNotConnected,e,`Cannot ${e} without a connected wallet account.`,n),this.name=`WalletNotConnectedError`}},h=class extends f{constructor(e,n){super(t.WalletAccountNotReady,e,`Cannot ${e} before the wallet account is ready.`,n),this.name=`WalletAccountNotReadyError`}};function g(e,t){if(e==null)throw new p(t);return e}async function _(e,t,n){try{await t()}catch(t){n?.warn(`${e} failed`,{error:t})}}const v=[{type:`function`,name:`UPGRADE_INTERFACE_VERSION`,inputs:[],outputs:[{name:``,type:`string`,internalType:`string`}],stateMutability:`view`},{type:`function`,name:`acceptOwnership`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`blockUser`,inputs:[{name:`user`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`confidentialBalanceOf`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`confidentialProtocolId`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`confidentialTotalSupply`,inputs:[],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`confidentialTransfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`confidentialTransfer`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`euint64`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`confidentialTransferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`euint64`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`transferred`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`confidentialTransferAndCall`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`transferred`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`confidentialTransferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`transferred`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`confidentialTransferFrom`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`euint64`}],outputs:[{name:`transferred`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`confidentialTransferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`transferred`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`confidentialTransferFromAndCall`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`euint64`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:`transferred`,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`function`,name:`contractURI`,inputs:[],outputs:[{name:``,type:`string`,internalType:`string`}],stateMutability:`view`},{type:`function`,name:`decimals`,inputs:[],outputs:[{name:``,type:`uint8`,internalType:`uint8`}],stateMutability:`view`},{type:`function`,name:`discloseEncryptedAmount`,inputs:[{name:`encryptedAmount`,type:`bytes32`,internalType:`euint64`},{name:`cleartextAmount`,type:`uint64`,internalType:`uint64`},{name:`decryptionProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`finalizeUnwrap`,inputs:[{name:`unwrapRequestId`,type:`bytes32`,internalType:`bytes32`},{name:`unwrapAmountCleartext`,type:`uint64`,internalType:`uint64`},{name:`decryptionProof`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUnderlyingDenyListSelector`,inputs:[],outputs:[{name:`isSet`,type:`bool`,internalType:`bool`},{name:`selector`,type:`bytes4`,internalType:`bytes4`}],stateMutability:`view`},{type:`function`,name:`inferredTotalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`initialize`,inputs:[{name:`name_`,type:`string`,internalType:`string`},{name:`symbol_`,type:`string`,internalType:`string`},{name:`contractURI_`,type:`string`,internalType:`string`},{name:`underlying_`,type:`address`,internalType:`contract IERC20`},{name:`owner_`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`isBlocked`,inputs:[{name:`user`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isOperator`,inputs:[{name:`holder`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`maxTotalSupply`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`name`,inputs:[],outputs:[{name:``,type:`string`,internalType:`string`}],stateMutability:`view`},{type:`function`,name:`onTransferReceived`,inputs:[{name:`operator`,type:`address`,internalType:`address`},{name:`from`,type:`address`,internalType:`address`},{name:`amount`,type:`uint256`,internalType:`uint256`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bytes4`,internalType:`bytes4`}],stateMutability:`nonpayable`},{type:`function`,name:`owner`,inputs:[],outputs:[{name:``,type:`address`,internalType:`address`}],stateMutability:`view`},{type:`function`,name:`pendingOwner`,inputs:[],outputs:[{name:``,type:`address`,internalType:`address`}],stateMutability:`view`},{type:`function`,name:`proxiableUUID`,inputs:[],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`view`},{type:`function`,name:`rate`,inputs:[],outputs:[{name:``,type:`uint256`,internalType:`uint256`}],stateMutability:`view`},{type:`function`,name:`reinitializeV2`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`reinitializeV3`,inputs:[{name:`blockedUsers`,type:`address[]`,internalType:`address[]`},{name:`underlyingDenyListSelector`,type:`bytes4`,internalType:`bytes4`},{name:`hasUnderlyingDenyListSelector_`,type:`bool`,internalType:`bool`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`renounceOwnership`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`requestDiscloseEncryptedAmount`,inputs:[{name:`encryptedAmount`,type:`bytes32`,internalType:`euint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`setOperator`,inputs:[{name:`operator`,type:`address`,internalType:`address`},{name:`until`,type:`uint48`,internalType:`uint48`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`symbol`,inputs:[],outputs:[{name:``,type:`string`,internalType:`string`}],stateMutability:`view`},{type:`function`,name:`transferOwnership`,inputs:[{name:`newOwner`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`unblockUser`,inputs:[{name:`user`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`underlying`,inputs:[],outputs:[{name:``,type:`address`,internalType:`address`}],stateMutability:`view`},{type:`function`,name:`unwrap`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`encryptedAmount`,type:`bytes32`,internalType:`externalEuint64`},{name:`inputProof`,type:`bytes`,internalType:`bytes`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`nonpayable`},{type:`function`,name:`unwrap`,inputs:[{name:`from`,type:`address`,internalType:`address`},{name:`to`,type:`address`,internalType:`address`},{name:`amount`,type:`bytes32`,internalType:`euint64`}],outputs:[{name:``,type:`bytes32`,internalType:`bytes32`}],stateMutability:`nonpayable`},{type:`function`,name:`unwrapAmount`,inputs:[{name:`unwrapRequestId`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`view`},{type:`function`,name:`unwrapRequester`,inputs:[{name:`unwrapRequestId`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`address`,internalType:`address`}],stateMutability:`view`},{type:`function`,name:`upgradeToAndCall`,inputs:[{name:`newImplementation`,type:`address`,internalType:`address`},{name:`data`,type:`bytes`,internalType:`bytes`}],outputs:[],stateMutability:`payable`},{type:`function`,name:`wrap`,inputs:[{name:`to`,type:`address`,internalType:`address`},{name:`amount`,type:`uint256`,internalType:`uint256`}],outputs:[{name:``,type:`bytes32`,internalType:`euint64`}],stateMutability:`nonpayable`},{type:`event`,name:`AmountDiscloseRequested`,inputs:[{name:`encryptedAmount`,type:`bytes32`,indexed:!0,internalType:`euint64`},{name:`requester`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`AmountDisclosed`,inputs:[{name:`encryptedAmount`,type:`bytes32`,indexed:!0,internalType:`euint64`},{name:`amount`,type:`uint64`,indexed:!1,internalType:`uint64`}],anonymous:!1},{type:`event`,name:`ConfidentialTransfer`,inputs:[{name:`from`,type:`address`,indexed:!0,internalType:`address`},{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`amount`,type:`bytes32`,indexed:!0,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Initialized`,inputs:[{name:`version`,type:`uint64`,indexed:!1,internalType:`uint64`}],anonymous:!1},{type:`event`,name:`OperatorSet`,inputs:[{name:`holder`,type:`address`,indexed:!0,internalType:`address`},{name:`operator`,type:`address`,indexed:!0,internalType:`address`},{name:`until`,type:`uint48`,indexed:!1,internalType:`uint48`}],anonymous:!1},{type:`event`,name:`OwnershipTransferStarted`,inputs:[{name:`previousOwner`,type:`address`,indexed:!0,internalType:`address`},{name:`newOwner`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`OwnershipTransferred`,inputs:[{name:`previousOwner`,type:`address`,indexed:!0,internalType:`address`},{name:`newOwner`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`PublicDecryptionVerified`,inputs:[{name:`handlesList`,type:`bytes32[]`,indexed:!1,internalType:`bytes32[]`},{name:`abiEncodedCleartexts`,type:`bytes`,indexed:!1,internalType:`bytes`}],anonymous:!1},{type:`event`,name:`UnwrapFinalized`,inputs:[{name:`receiver`,type:`address`,indexed:!0,internalType:`address`},{name:`unwrapRequestId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`encryptedAmount`,type:`bytes32`,indexed:!1,internalType:`euint64`},{name:`cleartextAmount`,type:`uint64`,indexed:!1,internalType:`uint64`}],anonymous:!1},{type:`event`,name:`UnwrapRequested`,inputs:[{name:`receiver`,type:`address`,indexed:!0,internalType:`address`},{name:`unwrapRequestId`,type:`bytes32`,indexed:!0,internalType:`bytes32`},{name:`amount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`event`,name:`Upgraded`,inputs:[{name:`implementation`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`UserBlocked`,inputs:[{name:`user`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`UserUnblocked`,inputs:[{name:`user`,type:`address`,indexed:!0,internalType:`address`}],anonymous:!1},{type:`event`,name:`Wrap`,inputs:[{name:`to`,type:`address`,indexed:!0,internalType:`address`},{name:`roundedAmount`,type:`uint256`,indexed:!1,internalType:`uint256`},{name:`encryptedWrappedAmount`,type:`bytes32`,indexed:!1,internalType:`euint64`}],anonymous:!1},{type:`error`,name:`AddressEmptyCode`,inputs:[{name:`target`,type:`address`,internalType:`address`}]},{type:`error`,name:`BlockedUser`,inputs:[{name:`user`,type:`address`,internalType:`address`}]},{type:`error`,name:`ERC1967InvalidImplementation`,inputs:[{name:`implementation`,type:`address`,internalType:`address`}]},{type:`error`,name:`ERC1967NonPayable`,inputs:[]},{type:`error`,name:`ERC7984InvalidReceiver`,inputs:[{name:`receiver`,type:`address`,internalType:`address`}]},{type:`error`,name:`ERC7984InvalidReceiver`,inputs:[{name:`receiver`,type:`address`,internalType:`address`}]},{type:`error`,name:`ERC7984InvalidSender`,inputs:[{name:`sender`,type:`address`,internalType:`address`}]},{type:`error`,name:`ERC7984TotalSupplyOverflow`,inputs:[]},{type:`error`,name:`ERC7984UnauthorizedCaller`,inputs:[{name:`caller`,type:`address`,internalType:`address`}]},{type:`error`,name:`ERC7984UnauthorizedSpender`,inputs:[{name:`holder`,type:`address`,internalType:`address`},{name:`spender`,type:`address`,internalType:`address`}]},{type:`error`,name:`ERC7984UnauthorizedUseOfEncryptedAmount`,inputs:[{name:`amount`,type:`bytes32`,internalType:`euint64`},{name:`user`,type:`address`,internalType:`address`}]},{type:`error`,name:`ERC7984ZeroBalance`,inputs:[{name:`holder`,type:`address`,internalType:`address`}]},{type:`error`,name:`FailedCall`,inputs:[]},{type:`error`,name:`InvalidInitialization`,inputs:[]},{type:`error`,name:`InvalidKMSSignatures`,inputs:[]},{type:`error`,name:`InvalidUnderlyingDenyListResponse`,inputs:[]},{type:`error`,name:`InvalidUnwrapRequest`,inputs:[{name:`unwrapRequestId`,type:`bytes32`,internalType:`bytes32`}]},{type:`error`,name:`NotInitializing`,inputs:[]},{type:`error`,name:`OwnableInvalidOwner`,inputs:[{name:`owner`,type:`address`,internalType:`address`}]},{type:`error`,name:`OwnableUnauthorizedAccount`,inputs:[{name:`account`,type:`address`,internalType:`address`}]},{type:`error`,name:`SafeCastOverflowedUintDowncast`,inputs:[{name:`bits`,type:`uint8`,internalType:`uint8`},{name:`value`,type:`uint256`,internalType:`uint256`}]},{type:`error`,name:`SafeERC20FailedOperation`,inputs:[{name:`token`,type:`address`,internalType:`address`}]},{type:`error`,name:`SenderNotAllowedToUseHandle`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`sender`,type:`address`,internalType:`address`}]},{type:`error`,name:`UUPSUnauthorizedCallContext`,inputs:[]},{type:`error`,name:`UUPSUnsupportedProxiableUUID`,inputs:[{name:`slot`,type:`bytes32`,internalType:`bytes32`}]},{type:`error`,name:`UnderlyingDenyListCallFailed`,inputs:[]},{type:`error`,name:`UnderlyingDenyListedAddress`,inputs:[{name:`user`,type:`address`,internalType:`address`}]},{type:`error`,name:`UserAlreadyBlocked`,inputs:[{name:`user`,type:`address`,internalType:`address`}]},{type:`error`,name:`UserAlreadyUnblocked`,inputs:[{name:`user`,type:`address`,internalType:`address`}]},{type:`error`,name:`ZamaProtocolUnsupported`,inputs:[]}];function y(e,t){return{address:e,abi:v,functionName:`confidentialBalanceOf`,args:[t]}}function ee(e,t,n,r){return{address:e,abi:v,functionName:`confidentialTransfer`,args:[t,n,r]}}function b(e,t,n,r,i){return{address:e,abi:v,functionName:`confidentialTransferFrom`,args:[t,n,r,i]}}function x(e,t,n,r,i){return{address:e,abi:v,functionName:`confidentialTransferAndCall`,args:[t,n,r,i]}}function S(e,t,n,r,i,a){return{address:e,abi:v,functionName:`confidentialTransferFromAndCall`,args:[t,n,r,i,a]}}function C(e,t,n){return{address:e,abi:v,functionName:`isOperator`,args:[t,n]}}function w(e,t,n){return{address:e,abi:v,functionName:`setOperator`,args:[t,n??Math.floor(Date.now()/1e3)+3600]}}function T(e,t,n,r,i){return{address:e,abi:v,functionName:`unwrap`,args:[t,n,r,i]}}function E(e,t,n,r){return{address:e,abi:v,functionName:`unwrap`,args:[t,n,r]}}function D(e){return{address:e,abi:v,functionName:`confidentialTotalSupply`,args:[]}}function O(e){return{address:e,abi:v,functionName:`rate`,args:[]}}function k(e,t,n,r){return{address:e,abi:v,functionName:`finalizeUnwrap`,args:[t,n,r]}}function A(e){return{address:e,abi:v,functionName:`underlying`,args:[]}}function j(e){return{address:e,abi:v,functionName:`inferredTotalSupply`,args:[]}}function M(e,t,n){return{address:e,abi:v,functionName:`wrap`,args:[t,n]}}function N(e){return{address:e,abi:r,functionName:`name`,args:[]}}function P(e){return{address:e,abi:r,functionName:`symbol`,args:[]}}function F(e){return{address:e,abi:r,functionName:`decimals`,args:[]}}function te(e){return{address:e,abi:r,functionName:`totalSupply`,args:[]}}function I(e,t){return{address:e,abi:r,functionName:`balanceOf`,args:[t]}}function L(e,t,n){return{address:e,abi:r,functionName:`allowance`,args:[t,n]}}function R(e,t,n){return{address:e,abi:r,functionName:`approve`,args:[t,n]}}const z=[{type:`function`,name:`supportsInterface`,inputs:[{name:`interfaceId`,type:`bytes4`,internalType:`bytes4`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`}],B=`0x4958f2a4`,V=`0x1f1c62b2`,H=`0xb0202a11`;function U(e,t){return{address:e,abi:z,functionName:`supportsInterface`,args:[t]}}function W(e){return U(e,B)}function G(e){return U(e,V)}function K(e){return U(e,H)}const q=[{inputs:[],name:`getTokenConfidentialTokenPairs`,outputs:[{components:[{internalType:`address`,name:`tokenAddress`,type:`address`},{internalType:`address`,name:`confidentialTokenAddress`,type:`address`},{internalType:`bool`,name:`isValid`,type:`bool`}],internalType:`struct ConfidentialTokenWrappersRegistry.TokenWrapperPair[]`,name:``,type:`tuple[]`}],stateMutability:`view`,type:`function`},{inputs:[],name:`getTokenConfidentialTokenPairsLength`,outputs:[{internalType:`uint256`,name:``,type:`uint256`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint256`,name:`fromIndex`,type:`uint256`},{internalType:`uint256`,name:`toIndex`,type:`uint256`}],name:`getTokenConfidentialTokenPairsSlice`,outputs:[{components:[{internalType:`address`,name:`tokenAddress`,type:`address`},{internalType:`address`,name:`confidentialTokenAddress`,type:`address`},{internalType:`bool`,name:`isValid`,type:`bool`}],internalType:`struct ConfidentialTokenWrappersRegistry.TokenWrapperPair[]`,name:``,type:`tuple[]`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`uint256`,name:`index`,type:`uint256`}],name:`getTokenConfidentialTokenPair`,outputs:[{components:[{internalType:`address`,name:`tokenAddress`,type:`address`},{internalType:`address`,name:`confidentialTokenAddress`,type:`address`},{internalType:`bool`,name:`isValid`,type:`bool`}],internalType:`struct ConfidentialTokenWrappersRegistry.TokenWrapperPair`,name:``,type:`tuple`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`tokenAddress`,type:`address`}],name:`getConfidentialTokenAddress`,outputs:[{internalType:`bool`,name:``,type:`bool`},{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`confidentialTokenAddress`,type:`address`}],name:`getTokenAddress`,outputs:[{internalType:`bool`,name:``,type:`bool`},{internalType:`address`,name:``,type:`address`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`confidentialTokenAddress`,type:`address`}],name:`isConfidentialTokenValid`,outputs:[{internalType:`bool`,name:``,type:`bool`}],stateMutability:`view`,type:`function`},{inputs:[{internalType:`address`,name:`initialOwner`,type:`address`}],name:`initialize`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`tokenAddress`,type:`address`},{internalType:`address`,name:`confidentialTokenAddress`,type:`address`}],name:`registerConfidentialToken`,outputs:[],stateMutability:`nonpayable`,type:`function`},{inputs:[{internalType:`address`,name:`confidentialTokenAddress`,type:`address`}],name:`revokeConfidentialToken`,outputs:[],stateMutability:`nonpayable`,type:`function`}];function J(e){return{address:e,abi:q,functionName:`getTokenConfidentialTokenPairs`,args:[]}}function Y(e){return{address:e,abi:q,functionName:`getTokenConfidentialTokenPairsLength`,args:[]}}function X(e,t,n){return{address:e,abi:q,functionName:`getTokenConfidentialTokenPairsSlice`,args:[t,n]}}function Z(e,t){return{address:e,abi:q,functionName:`getTokenConfidentialTokenPair`,args:[t]}}function Q(e,t){return{address:e,abi:q,functionName:`getConfidentialTokenAddress`,args:[t]}}function ne(e,t){return{address:e,abi:q,functionName:`getTokenAddress`,args:[t]}}function re(e,t){return{address:e,abi:q,functionName:`isConfidentialTokenValid`,args:[t]}}const $={EncryptStart:`encrypt:start`,EncryptEnd:`encrypt:end`,EncryptError:`encrypt:error`,DecryptStart:`decrypt:start`,DecryptEnd:`decrypt:end`,DecryptError:`decrypt:error`,TransactionError:`transaction:error`,ShieldSubmitted:`shield:submitted`,TransferSubmitted:`transfer:submitted`,TransferFromSubmitted:`transferFrom:submitted`,SetOperatorSubmitted:`setOperator:submitted`,ApproveUnderlyingSubmitted:`approveUnderlying:submitted`,WrapSubmitted:`wrap:submitted`,UnwrapSubmitted:`unwrap:submitted`,FinalizeUnwrapSubmitted:`finalizeUnwrap:submitted`,DelegationSubmitted:`delegation:submitted`,RevokeDelegationSubmitted:`revokeDelegation:submitted`,UnshieldPhase1Submitted:`unshield:phase1_submitted`,UnshieldPhase2Started:`unshield:phase2_started`,UnshieldPhase2Submitted:`unshield:phase2_submitted`},ie={approveUnderlying:{submittedEvent:e=>({type:$.ApproveUnderlyingSubmitted,txHash:e,step:`approve`})},"approveUnderlying:reset":{submittedEvent:e=>({type:$.ApproveUnderlyingSubmitted,txHash:e,step:`reset`})},delegateDecryption:{submittedEvent:e=>({type:$.DelegationSubmitted,txHash:e})},finalizeUnwrap:{submittedEvent:e=>({type:$.FinalizeUnwrapSubmitted,txHash:e})},revokeDelegation:{submittedEvent:e=>({type:$.RevokeDelegationSubmitted,txHash:e})},setOperator:{submittedEvent:e=>({type:$.SetOperatorSubmitted,txHash:e})},"shield:transferAndCall":{submittedEvent:e=>({type:$.ShieldSubmitted,txHash:e,shieldPath:`transferAndCall`})},"shield:approveAndWrap":{submittedEvent:e=>({type:$.ShieldSubmitted,txHash:e,shieldPath:`approveAndWrap`})},wrap:{submittedEvent:e=>({type:$.WrapSubmitted,txHash:e})},transfer:{submittedEvent:e=>({type:$.TransferSubmitted,txHash:e})},transferAndCall:{submittedEvent:e=>({type:$.TransferSubmitted,txHash:e})},transferFrom:{submittedEvent:e=>({type:$.TransferFromSubmitted,txHash:e})},transferFromAndCall:{submittedEvent:e=>({type:$.TransferFromSubmitted,txHash:e})},unwrap:{submittedEvent:e=>({type:$.UnwrapSubmitted,txHash:e})},unwrapAll:{submittedEvent:e=>({type:$.UnwrapSubmitted,txHash:e})}};export{k as A,p as B,P as C,ee as D,x as E,A as F,d as G,h as H,T as I,u as J,l as K,E as L,C as M,O as N,S as O,w as P,i as Q,M as R,N as S,D as T,m as U,f as V,g as W,s as X,a as Y,o as Z,L as _,Z as a,F as b,X as c,B as d,V as f,U as g,K as h,ne as i,j,b as k,re as l,G as m,ie as n,J as o,W as p,c as q,Q as r,Y as s,$ as t,H as u,R as v,y as w,te as x,I as y,_ as z};
|
|
2
|
-
//# sourceMappingURL=sdk-events-lFxSy5Zf.js.map
|