@zama-fhe/sdk 3.2.0 → 3.3.0-alpha.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/dist/cjs/assertions.cjs +1 -1
  2. package/dist/cjs/assertions.cjs.map +1 -1
  3. package/dist/cjs/base-signer.cjs +1 -1
  4. package/dist/cjs/base-signer.cjs.map +1 -1
  5. package/dist/cjs/ethers/index.cjs +1 -1
  6. package/dist/cjs/index.cjs +1 -1
  7. package/dist/cjs/index.cjs.map +1 -1
  8. package/dist/cjs/query/index.cjs +1 -1
  9. package/dist/cjs/query/index.cjs.map +1 -1
  10. package/dist/cjs/relayer-cleartext.cjs +1 -1
  11. package/dist/cjs/relayer-cleartext.cjs.map +1 -1
  12. package/dist/cjs/relayer-sdk.worker.js +134 -34
  13. package/dist/cjs/relayer.cjs +1 -1
  14. package/dist/cjs/relayer.cjs.map +1 -1
  15. package/dist/cjs/timeout.cjs +2 -0
  16. package/dist/cjs/timeout.cjs.map +1 -0
  17. package/dist/cjs/token.cjs +1 -1
  18. package/dist/cjs/token.cjs.map +1 -1
  19. package/dist/cjs/viem/index.cjs +1 -1
  20. package/dist/cjs/viem/index.cjs.map +1 -1
  21. package/dist/cjs/web/index.cjs +136 -36
  22. package/dist/cjs/web/index.cjs.map +1 -1
  23. package/dist/cjs/wrappers-registry.cjs +1 -1
  24. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  25. package/dist/esm/assertions-zYseN5Xz.js +2 -0
  26. package/dist/esm/assertions-zYseN5Xz.js.map +1 -0
  27. package/dist/esm/{base-signer-ByGw5ReU.d.ts → base-signer-C3Wc5oi9.d.ts} +2 -2
  28. package/dist/esm/base-signer-DjytqPkd.js +2 -0
  29. package/dist/esm/base-signer-DjytqPkd.js.map +1 -0
  30. package/dist/esm/cleartext/index.d.ts +1 -1
  31. package/dist/esm/cleartext/index.js +1 -1
  32. package/dist/esm/{cleartext-DMW5nK1M.d.ts → cleartext-DAkOTlrE.d.ts} +2 -2
  33. package/dist/esm/{cleartext-CTla3A3O.js → cleartext-rTWFctyd.js} +2 -2
  34. package/dist/esm/{cleartext-CTla3A3O.js.map → cleartext-rTWFctyd.js.map} +1 -1
  35. package/dist/esm/{encryption-BGmINekJ.js → encryption-x4Z_Icqk.js} +2 -2
  36. package/dist/esm/{encryption-BGmINekJ.js.map → encryption-x4Z_Icqk.js.map} +1 -1
  37. package/dist/esm/ethers/index.d.ts +4 -4
  38. package/dist/esm/ethers/index.js +1 -1
  39. package/dist/esm/ethers/index.js.map +1 -1
  40. package/dist/esm/{hex-CxtyupeQ.js → hex-A72GrTf9.js} +2 -2
  41. package/dist/esm/{hex-CxtyupeQ.js.map → hex-A72GrTf9.js.map} +1 -1
  42. package/dist/esm/{index-DoVo9J1n.d.ts → index-C1Mtc8Rw.d.ts} +450 -163
  43. package/dist/esm/index.d.ts +17 -13
  44. package/dist/esm/index.js +1 -1
  45. package/dist/esm/index.js.map +1 -1
  46. package/dist/esm/node/index.d.ts +25 -7
  47. package/dist/esm/node/index.js +1 -1
  48. package/dist/esm/node/index.js.map +1 -1
  49. package/dist/esm/node/relayer-sdk.node-worker.js +1 -1
  50. package/dist/esm/node/relayer-sdk.node-worker.js.map +1 -1
  51. package/dist/esm/query/index.d.ts +42 -4
  52. package/dist/esm/query/index.js +1 -1
  53. package/dist/esm/query/index.js.map +1 -1
  54. package/dist/esm/relayer-cleartext-Bp6jtxDd.js +2 -0
  55. package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +1 -0
  56. package/dist/esm/{relayer-cleartext-DkKKjfI6.d.ts → relayer-cleartext-CSeMlmGO.d.ts} +102 -13
  57. package/dist/esm/relayer-eavK5bfZ.js +2 -0
  58. package/dist/esm/relayer-eavK5bfZ.js.map +1 -0
  59. package/dist/esm/relayer-sdk.worker.js +134 -34
  60. package/dist/esm/timeout-CNVfiaJD.js +2 -0
  61. package/dist/esm/timeout-CNVfiaJD.js.map +1 -0
  62. package/dist/esm/token-Bt33g0zQ.js +2 -0
  63. package/dist/esm/token-Bt33g0zQ.js.map +1 -0
  64. package/dist/esm/{types-BjDu-RZg.d.ts → types-Gn5MeDsr.d.ts} +14 -2
  65. package/dist/esm/{types-Xg_On_yY.d.ts → types-OHIaPwCy.d.ts} +2 -2
  66. package/dist/esm/{types-DiZhtG8i.d.ts → types-piBsdTIP.d.ts} +2 -2
  67. package/dist/esm/{validation-DHZ3JPOn.js → validation-DLszOweh.js} +2 -2
  68. package/dist/esm/{validation-DHZ3JPOn.js.map → validation-DLszOweh.js.map} +1 -1
  69. package/dist/esm/viem/index.d.ts +4 -4
  70. package/dist/esm/viem/index.js +1 -1
  71. package/dist/esm/viem/index.js.map +1 -1
  72. package/dist/esm/web/index.d.ts +2 -2
  73. package/dist/esm/web/index.js +135 -35
  74. package/dist/esm/web/index.js.map +1 -1
  75. package/dist/esm/worker.base-client-BVnT4yJa.js +2 -0
  76. package/dist/esm/worker.base-client-BVnT4yJa.js.map +1 -0
  77. package/dist/esm/{wrappers-registry-BWWG0aze.js → wrappers-registry-C1oK8Bi6.js} +2 -2
  78. package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +1 -0
  79. package/package.json +51 -51
  80. package/dist/esm/assertions-CnPIS0VN.js +0 -2
  81. package/dist/esm/assertions-CnPIS0VN.js.map +0 -1
  82. package/dist/esm/base-signer-BVqcM5jt.js +0 -2
  83. package/dist/esm/base-signer-BVqcM5jt.js.map +0 -1
  84. package/dist/esm/error-W1N-FGwV.js +0 -2
  85. package/dist/esm/error-W1N-FGwV.js.map +0 -1
  86. package/dist/esm/relayer-D-nicEYJ.js +0 -2
  87. package/dist/esm/relayer-D-nicEYJ.js.map +0 -1
  88. package/dist/esm/relayer-cleartext-DGcb5qtE.js +0 -2
  89. package/dist/esm/relayer-cleartext-DGcb5qtE.js.map +0 -1
  90. package/dist/esm/token-TQ-VFHS4.js +0 -2
  91. package/dist/esm/token-TQ-VFHS4.js.map +0 -1
  92. package/dist/esm/worker.base-client-x522sMBy.js +0 -2
  93. package/dist/esm/worker.base-client-x522sMBy.js.map +0 -1
  94. package/dist/esm/wrappers-registry-BWWG0aze.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"base-signer-BVqcM5jt.js","names":["#generator","#storage","#ttl","#logger","#pending","#storage","#logger","#deleteScope","#untrackScope","#trackScope","#readIndex","#vault","#store","#relayer","#signer","#permitTTL","#logger","#signPermit","#logger","#prefix","#chains","#relayers","#workers","#chainId","#active","#addresses","#ttlMs","#cache","#getCached","#setCached","#pairWithMetadata","#listeners","#snapshot","#resolved","#emit","#disposed"],"sources":["../../src/credentials/storage-keys.ts","../../src/schemas/primitives.ts","../../src/credentials/utils.ts","../../src/credentials/schemas.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/config/resolve.ts","../../src/relayer/relayer-dispatcher.ts","../../src/wrappers-registry.ts","../../src/config/build.ts","../../src/signer/wallet-account-store.ts","../../src/signer/base-signer.ts"],"sourcesContent":["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\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 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 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))].toSorted();\n}\n","import { z } from \"zod/mini\";\nimport {\n checksummedAddress,\n chainId,\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\";\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 StoredTransportKeyPairSchema = z.object({\n publicKey: hex,\n privateKey: hex,\n createdAt: unixSeconds,\n expiresAt: positiveSeconds,\n});\n\nexport const PermissionSchema = z.object({\n keypairPublicKey: hex,\n signerAddress: checksummedAddress,\n delegatorAddress: checksummedAddress,\n chainId,\n signedContractAddresses: z.array(checksummedAddress).check(z.maxLength(MAX_CONTRACTS_PER_PERMIT)),\n signature: hex,\n startTimestamp: unixSeconds,\n durationDays: positiveDays,\n});\n\nexport const PermissionListSchema = z.array(PermissionSchema);\n\nexport const ScopeIndexSchema = z.array(z.string());\n","import type { GenericStorage } from \"../types\";\nimport { swallow } from \"../utils/swallow\";\nimport { transportKeyPairStorageKey } from \"./storage-keys\";\nimport { StoredTransportKeyPairSchema } from \"./schemas\";\nimport type { TransportKeyPair, StoredTransportKeyPair } from \"./types\";\nimport type { ChecksummedAddress } from \"../schemas/primitives\";\nimport type { GenericLogger } from \"../worker/worker.types\";\nimport { nowSeconds } from \"./utils\";\n\ninterface TransportKeyPairVaultConfig {\n generator: () => Promise<TransportKeyPair>;\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\n/**\n * Identity-scoped, chain-independent vault for ML-KEM transport key pairs.\n *\n * One transport key pair per signer address; the key pair survives chain switches and\n * permit revocations. Storage entries are keyed only by the signer address.\n */\nexport class TransportKeyPairVault {\n readonly #generator: () => Promise<TransportKeyPair>;\n readonly #storage: GenericStorage;\n readonly #ttl: number;\n readonly #logger: GenericLogger;\n readonly #pending = new Map<ChecksummedAddress, Promise<StoredTransportKeyPair>>();\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 }\n\n async readStored(signerAddress: ChecksummedAddress): Promise<StoredTransportKeyPair | null> {\n const key = transportKeyPairStorageKey(signerAddress);\n const raw = await this.#storage.get(key);\n if (raw === null || raw === undefined) {\n return null;\n }\n const parsed = StoredTransportKeyPairSchema.safeParse(raw);\n if (!parsed.success) {\n await swallow(\n \"delete transport key pair entry\",\n () => this.#storage.delete(key),\n this.#logger,\n );\n return null;\n }\n const stored = parsed.data;\n if (nowSeconds() >= stored.expiresAt) {\n await swallow(\n \"delete transport key pair entry\",\n () => this.#storage.delete(key),\n this.#logger,\n );\n return null;\n }\n return stored;\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 — simultaneous requests share one generation promise.\n */\n async getOrCreate(signerAddress: ChecksummedAddress): Promise<StoredTransportKeyPair> {\n const existing = this.#pending.get(signerAddress);\n if (existing) {\n return existing;\n }\n\n const promise = (async () => {\n const cached = await this.readStored(signerAddress);\n if (cached !== null) {\n return cached;\n }\n const fresh = await this.#generator();\n const createdAt = nowSeconds();\n const stored: StoredTransportKeyPair = {\n publicKey: fresh.publicKey,\n privateKey: fresh.privateKey,\n createdAt,\n expiresAt: createdAt + this.#ttl,\n };\n const key = transportKeyPairStorageKey(signerAddress);\n await swallow(\n \"persist transport key pair\",\n () => this.#storage.set(key, stored),\n this.#logger,\n );\n return stored;\n })().finally(() => {\n this.#pending.delete(signerAddress);\n });\n\n this.#pending.set(signerAddress, promise);\n return promise;\n }\n\n /** Delete the stored transport key pair for the given address. */\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","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.signedContractAddresses));\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.signedContractAddresses.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])].toSorted();\n}\n\n/**\n * Find the in-scope permit best suited to be widened with `uncovered`.\n *\n * Returns the permit whose `signedContractAddresses ∪ 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 permits: readonly Permission[],\n uncovered: readonly ChecksummedAddress[],\n requested: readonly ChecksummedAddress[],\n): Permission | null {\n const requestedSet = new Set(requested);\n const feasible = permits.filter(\n (p) => new Set([...p.signedContractAddresses, ...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.signedContractAddresses.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 { 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\";\nimport type { GenericLogger } from \"../worker/worker.types\";\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.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 `signedContractAddresses`, 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 { GenericSigner, GenericStorage } from \"../types\";\nimport type { RelayerDispatcher } from \"../relayer/relayer-dispatcher\";\nimport { ZamaError } from \"../errors/base\";\nimport { wrapSigningError } from \"../errors/signing\";\nimport { swallow } from \"../utils/swallow\";\nimport { TransportKeyPairVault } from \"./keypair-vault\";\nimport { chunkContracts, findPermitToWiden, sortedUnion, uncoveredContracts } from \"./permissions\";\nimport { PermissionStore } from \"./permission-store\";\nimport type { PermissionScope } from \"./storage-keys\";\nimport type {\n StoredTransportKeyPairWithPermits,\n Permission,\n StoredTransportKeyPair,\n} from \"./types\";\nimport type { ChecksummedAddress } from \"../schemas/primitives\";\nimport { checksum } from \"../schemas/primitives\";\nimport type { GenericLogger } from \"../worker/worker.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 relayer: RelayerDispatcher;\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\n/**\n * Single facade coordinating the keypair vault and the permission store.\n *\n * `CredentialService` is the only credentials object held by `ZamaSDK`. It accepts identity\n * transitions via `handleWalletAccountChange`.\n */\nexport class CredentialService {\n readonly #vault: TransportKeyPairVault;\n readonly #store: PermissionStore;\n readonly #relayer: RelayerDispatcher;\n readonly #signer: GenericSigner;\n readonly #permitTTL: number;\n readonly #logger: GenericLogger;\n\n constructor(config: CredentialServiceConfig) {\n this.#vault = new TransportKeyPairVault({\n generator: () => config.relayer.generateTransportKeyPair(),\n storage: config.storage,\n ttl: config.transportKeyPairTTL,\n logger: config.logger,\n });\n this.#store = new PermissionStore({\n storage: config.permitStorage ?? config.storage,\n logger: config.logger,\n });\n this.#relayer = config.relayer;\n this.#signer = config.signer;\n this.#permitTTL = config.permitTTL;\n this.#logger = config.logger;\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 */\n async grantPermit(\n contracts: readonly Address[],\n delegator?: Address,\n ): Promise<StoredTransportKeyPairWithPermits> {\n const account = this.#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, permits: [] };\n }\n\n const chainId = account.chainId;\n const scope: PermissionScope = {\n signerAddress,\n chainId,\n delegatorAddress: delegator ? checksum(delegator) : signerAddress,\n };\n const permits = await this.#store.listUsableAndPrune(scope, keypair.publicKey);\n\n const uncovered = uncoveredContracts(permits, requested);\n if (uncovered.length > 0) {\n const candidate = findPermitToWiden(permits, uncovered, requested);\n if (candidate !== null) {\n const widenedSet = sortedUnion(candidate.signedContractAddresses, uncovered);\n const widened = await this.#signPermit({\n chunk: widenedSet,\n keypair,\n scope,\n });\n await swallow(\n \"replace permit\",\n () => this.#store.replace(scope, candidate.signature, widened),\n this.#logger,\n );\n permits[permits.indexOf(candidate)] = widened;\n } else {\n for (const chunk of chunkContracts(uncovered)) {\n const permission = await this.#signPermit({ chunk, keypair, scope });\n permits.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 permits: permits.filter((p) => p.signedContractAddresses.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 * @returns `true` if cached permits cover all requested contracts (vacuously\n * true for an empty list); `false` if no keypair exists or coverage is\n * incomplete.\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 const keypair = await this.#vault.readStored(signerAddress);\n if (keypair === null) {\n return false;\n }\n const chainId = account.chainId;\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 account = this.#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 = account.chainId;\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 * @throws if reading the signer address fails. {@link SigningFailedError}\n */\n async clearCredentials(): Promise<void> {\n const account = this.#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 * 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 async warmTransportKeyPair(address: Address): Promise<void> {\n await this.#vault.getOrCreate(checksum(address));\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 `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\n try {\n const eip712 = isDelegated\n ? await this.#relayer.createDelegatedUserDecryptEIP712(\n keypair.publicKey,\n chunk,\n scope.delegatorAddress,\n startTimestamp,\n this.#permitTTL,\n )\n : await this.#relayer.createEIP712(\n keypair.publicKey,\n chunk,\n startTimestamp,\n this.#permitTTL,\n );\n\n const signature = await this.#signer.signTypedData(eip712);\n\n return {\n keypairPublicKey: keypair.publicKey,\n signerAddress: scope.signerAddress,\n delegatorAddress: scope.delegatorAddress,\n chainId: scope.chainId,\n signedContractAddresses: chunk,\n signature,\n startTimestamp,\n durationDays: this.#permitTTL,\n };\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw wrapSigningError(error, \"Credential signing failed\");\n }\n }\n}\n","import type { GenericLogger } from \"../worker/worker.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 (e.g. the worker client).\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 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\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\nexport interface ResolvedChainRelayer {\n chain: FheChain;\n relayer: RelayerConfig;\n}\n\nexport function resolveChainRelayers(\n chains: readonly FheChain[],\n relayers: Readonly<Record<number, RelayerConfig>>,\n): Map<number, ResolvedChainRelayer> {\n const chainMap = new Map(chains.map((c) => [c.id, c]));\n if (chainMap.size !== chains.length) {\n const ids = chains.map((c) => c.id);\n const dupes = [...new Set(ids.filter((id, i) => ids.indexOf(id) !== i))];\n throw new ConfigurationError(\n `Duplicate chain id(s) [${dupes.join(\", \")}] in the chains array. ` +\n `Each chain id must appear only once. Note: hardhat and anvil are aliases (both use 31337).`,\n );\n }\n const relayerMap = new Map(Object.entries(relayers));\n const result = new Map<number, ResolvedChainRelayer>();\n\n for (const id of chainMap.keys()) {\n const chainConfig = chainMap.get(id);\n const relayerConfig = relayerMap.get(String(id));\n\n if (!relayerConfig) {\n throw new ConfigurationError(\n `Chain ${id} has no relayer configured. ` +\n `Add a relayer entry: relayers: { [${id}]: web() }`,\n );\n }\n\n if (!chainConfig) {\n throw new ConfigurationError(\n `Chain ${id} has a relayer configured but no entry in the chains array. ` +\n `Add the chain config to the chains array.`,\n );\n }\n\n result.set(id, {\n chain: chainConfig,\n relayer: relayerConfig,\n });\n }\n\n const relayerIdSet = new Set(Object.keys(relayers).map(Number));\n const orphaned = new Set([...relayerIdSet].filter((id) => !chainMap.has(id)));\n if (orphaned.size > 0) {\n throw new ConfigurationError(\n `Relayer entries for chain(s) [${[...orphaned].join(\", \")}] have no matching entry ` +\n `in the chains array. Remove them or add the corresponding chain config.`,\n );\n }\n\n return result;\n}\n","import type {\n InputProofBytesType,\n KmsDelegatedUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\nimport type { Address, Hex } from \"viem\";\nimport type { FheChain } from \"../chains/types\";\nimport type { RelayerConfig } from \"../config/types\";\nimport { resolveChainRelayers } from \"../config/resolve\";\nimport type { TransportKeyPair } from \"../credentials/types\";\nimport { ConfigurationError } from \"../errors\";\nimport { assertNonNullable, toError } from \"../utils\";\nimport type { GenericLogger } from \"../worker/worker.types\";\nimport type { RelayerSDK } from \"./relayer-sdk\";\nimport type {\n ClearValue,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n EncryptedValue,\n FheEncryptionKey,\n PublicDecryptResult,\n PublicParamsData,\n UserDecryptParams,\n} from \"./relayer-sdk.types\";\n\n/** Anything with a synchronous `terminate()` method (workers, pools). */\nexport interface WorkerLike {\n terminate(): void;\n}\n\n/**\n * Owns chain management (chains / activeChain / switchChain) and delegates\n * every {@link RelayerSDK} operation to the relayer for the currently active\n * chain.\n *\n * Groups chains by relayer config reference identity, calls `createWorker`\n * once per group with all chain configs, then calls `createRelayer`\n * per chain with the shared worker.\n *\n * Workers/pools are held separately from relayers so the dispatcher can\n * terminate them directly — relayers never own worker lifecycle.\n */\nexport class RelayerDispatcher implements RelayerSDK, Disposable {\n readonly #chains: Map<number, FheChain>;\n readonly #relayers: Map<number, RelayerSDK>;\n readonly #workers: readonly WorkerLike[];\n #chainId: number;\n\n constructor(\n chains: readonly [FheChain, ...FheChain[]],\n configs: Readonly<Record<number, RelayerConfig>>,\n logger: GenericLogger,\n ) {\n if (chains.length === 0) {\n throw new ConfigurationError(\"At least one chain is required.\");\n }\n this.#chains = new Map(chains.map((c) => [c.id, c]));\n this.#chainId = chains[0].id;\n\n const chainRelayers = resolveChainRelayers(chains, configs);\n\n // Group chains by relayer config reference — same object = same group = shared worker.\n const groups = new Map<RelayerConfig, Array<[number, FheChain]>>();\n for (const [chainId, config] of chainRelayers) {\n const key = config.relayer;\n let group = groups.get(key);\n if (!group) {\n group = [];\n groups.set(key, group);\n }\n group.push([chainId, config.chain]);\n }\n\n // For each group: create shared worker once, then create per-chain relayers.\n const relayers = new Map<number, RelayerSDK>();\n const workers: WorkerLike[] = [];\n try {\n for (const [relayerCfg, groupChains] of groups) {\n const allChainConfigs = groupChains.map(([, chain]) => chain);\n const worker = relayerCfg.createWorker?.(allChainConfigs, logger);\n if (worker) {\n workers.push(worker);\n }\n for (const [chainId, chain] of groupChains) {\n relayers.set(chainId, relayerCfg.createRelayer(chain, worker, logger));\n }\n }\n } catch (error) {\n for (const w of workers) {\n try {\n w.terminate();\n } catch {\n /* best-effort cleanup */\n }\n }\n throw error;\n }\n\n this.#relayers = relayers;\n this.#workers = workers;\n }\n\n get chains(): readonly FheChain[] {\n return [...this.#chains.values()];\n }\n\n get chain(): FheChain {\n const chain = this.#chains.get(this.#chainId);\n assertNonNullable(chain, \"RelayerDispatcher: chain\");\n return chain;\n }\n\n switchChain(chainId: number): void {\n if (!this.#chains.has(chainId)) {\n throw new ConfigurationError(\n `No relayer configured for chain ${chainId}. Add it to the chains array.`,\n );\n }\n this.#chainId = chainId;\n }\n\n get #active(): RelayerSDK {\n const relayer = this.#relayers.get(this.#chainId);\n assertNonNullable(relayer, \"RelayerDispatcher: relayer\");\n return relayer;\n }\n\n generateTransportKeyPair(): Promise<TransportKeyPair> {\n return this.#active.generateTransportKeyPair();\n }\n\n createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays?: number,\n ): Promise<EIP712TypedData> {\n return this.#active.createEIP712(publicKey, contractAddresses, startTimestamp, durationDays);\n }\n\n encrypt(params: EncryptParams): Promise<EncryptResult> {\n return this.#active.encrypt(params);\n }\n\n userDecrypt(params: UserDecryptParams): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n return this.#active.userDecrypt(params);\n }\n\n publicDecrypt(encryptedValues: EncryptedValue[]): Promise<PublicDecryptResult> {\n return this.#active.publicDecrypt(encryptedValues);\n }\n\n createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays?: number,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n return this.#active.createDelegatedUserDecryptEIP712(\n publicKey,\n contractAddresses,\n delegatorAddress,\n startTimestamp,\n durationDays,\n );\n }\n\n delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n return this.#active.delegatedUserDecrypt(params);\n }\n\n requestZKProofVerification(zkProof: ZKProofLike): Promise<InputProofBytesType> {\n return this.#active.requestZKProofVerification(zkProof);\n }\n\n fetchFheEncryptionKeyBytes(): Promise<FheEncryptionKey | null> {\n return this.#active.fetchFheEncryptionKeyBytes();\n }\n\n getPublicParams(bits: number): Promise<PublicParamsData | null> {\n return this.#active.getPublicParams(bits);\n }\n\n getAclAddress(): Promise<Address> {\n return this.#active.getAclAddress();\n }\n\n terminate(): void {\n const errors: Error[] = [];\n\n // Clean up relayer-owned caches (no worker termination).\n for (const r of new Set(this.#relayers.values())) {\n try {\n r.terminate();\n } catch (e) {\n errors.push(toError(e));\n }\n }\n\n // Terminate the actual workers/pools (deduplicated).\n for (const w of new Set(this.#workers)) {\n try {\n w.terminate();\n } catch (e) {\n errors.push(toError(e));\n }\n }\n\n if (errors.length > 0) {\n throw new AggregateError(errors, \"Failed to terminate relayer resources\");\n }\n }\n\n [Symbol.dispose](): void {\n this.terminate();\n }\n}\n","import { 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, hoodi, ingenTestnet, bscTestnet } from \"./chains\";\nimport { checksummedAddress, nonNegativeSeconds } from \"./schemas/primitives\";\nimport type { GenericProvider } from \"./types/provider\";\nimport { parseConfiguration } from \"./validation\";\n\n/**\n * Default wrappers registry addresses for known chains.\n * Only includes chains where a registry is deployed (excludes Hardhat).\n */\nexport const DefaultRegistryAddresses: Record<number, Address> = {\n [mainnet.id]: mainnet.registryAddress,\n [sepolia.id]: sepolia.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 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 parseConfiguration(z.optional(RegistryAddressesSchema), config.registryAddresses),\n );\n this.#ttlMs =\n parseConfiguration(RegistryTTLSchema, config.registryTTL ?? DEFAULT_REGISTRY_TTL_SECONDS) *\n 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, {\n data,\n expiresAt: Date.now() + ttlMs,\n });\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 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: {\n name: \"Unknown\",\n symbol: \"???\",\n decimals: 0,\n totalSupply: 0n,\n },\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: {\n name: uName,\n symbol: uSymbol,\n decimals: uDecimals,\n totalSupply: uTotalSupply,\n },\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<{\n confidentialTokenAddress: Address;\n isValid: boolean;\n } | null>(cacheKey);\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<{\n tokenAddress: Address;\n isValid: boolean;\n } | 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 {\n DEFAULT_TRANSPORT_KEY_PAIR_TTL_SECONDS,\n DEFAULT_PERMIT_DURATION_DAYS,\n} from \"../credentials/credential-service\";\nimport { TransportKeyPairTTLSchema, PermitTTLSchema } from \"../credentials/schemas\";\nimport { LoggerService } from \"../services/logger-service\";\nimport { RelayerDispatcher } from \"../relayer/relayer-dispatcher\";\nimport type { GenericProvider, GenericSigner } from \"../types\";\nimport { DEFAULT_REGISTRY_TTL_SECONDS, RegistryTTLSchema } from \"../wrappers-registry\";\nimport { parseConfiguration } from \"../validation\";\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 { storage, permitStorage } = resolveStorage(params.storage, params.permitStorage);\n const logger = new LoggerService(params.logger);\n const relayer = new RelayerDispatcher(params.chains, params.relayers, logger);\n\n return {\n chains: params.chains,\n relayer,\n provider,\n signer,\n storage,\n permitStorage,\n transportKeyPairTTL: parseConfiguration(\n TransportKeyPairTTLSchema,\n params.transportKeyPairTTL ?? DEFAULT_TRANSPORT_KEY_PAIR_TTL_SECONDS,\n ),\n permitTTL: parseConfiguration(\n PermitTTLSchema,\n params.permitTTL ?? DEFAULT_PERMIT_DURATION_DAYS,\n ),\n registryTTL: parseConfiguration(\n RegistryTTLSchema,\n params.registryTTL ?? DEFAULT_REGISTRY_TTL_SECONDS,\n ),\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 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 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/relayer-sdk.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 implements the shared {@link GenericSigner}\n * boilerplate: wallet-account store, `requireWalletAccount`, idempotent\n * `dispose` / `Disposable`. Subclasses provide `signTypedData`,\n * `writeContract`, and optionally override `onDispose` for cleanup.\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 readonly walletAccount: MutableWalletAccountStore;\n #disposed = false;\n\n constructor(initial?: WalletAccount) {\n this.walletAccount = new MutableWalletAccountStore(initial);\n }\n\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 abstract signTypedData(typedData: EIP712TypedData): Promise<Hex>;\n\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 dispose(): void {\n if (this.#disposed) {\n return;\n }\n this.#disposed = true;\n this.onDispose();\n }\n\n [Symbol.dispose](): void {\n this.dispose();\n }\n\n protected onDispose(): void {}\n}\n"],"mappings":"qlBAQA,SAAgB,EAA2B,EAA2C,CAEpF,MAAO,WAAW,GACpB,CAEA,SAAgB,EAAmB,EAAgC,CACjE,MAAO,WAAW,EAAM,cAAc,GAAG,EAAM,QAAQ,GAAG,EAAM,kBAClE,CAEA,SAAgB,EAAmB,EAA2C,CAC5E,MAAO,iBAAiB,GAC1B,CCVA,SAAgB,EAAS,EAAoC,CAC3D,OAAO,EAAW,CAAK,CACzB,CAGA,MAAa,EAAM,EAAE,OAClB,GAAM,OAAO,GAAM,UAAY,GAAM,EAAG,CAAE,OAAQ,EAAK,CAAC,EACzD,iCACF,EAGa,GAAa,EAAE,OACzB,GAAM,OAAO,GAAM,UAAY,GAAU,EAAG,CAAE,OAAQ,EAAM,CAAC,EAC9D,sBACF,EAGa,EAAqB,EAAE,KAAK,GAAY,EAAE,UAAU,CAAQ,CAAC,EAG7D,EAAc,EAAE,IAAI,CAAC,CAAC,MAAM,EAAE,YAAY,CAAC,EAG3C,EAAkB,EAAE,IAAI,CAAC,CAAC,MAAM,EAAE,SAAS,CAAC,EAG5C,GAAqB,EAAE,IAAI,CAAC,CAAC,MAAM,EAAE,YAAY,CAAC,EAGlD,GAAe,EAAE,IAAI,CAAC,CAAC,MAAM,EAAE,SAAS,CAAC,EAGzC,GAAU,EAAE,IAAI,CAAC,CAAC,MAAM,EAAE,SAAS,CAAC,EC/BjD,SAAgB,GAAqB,CACnC,OAAO,KAAK,MAAM,KAAK,IAAI,EAAI,GAAI,CACrC,CAGA,SAAgB,EAAmB,EAAqD,CACtF,MAAO,CAAC,GAAG,IAAI,IAAI,EAAU,IAAI,CAAQ,CAAC,CAAC,CAAC,CAAC,SAAS,CACxD,CCNA,MAAM,EAA2B,mEAC3B,EAAiB,sDAGV,EAAqC,IAAM,MAI3C,EAA4B,EAC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Y,IAAY,IAAA,EAC/B,CAEA,aAAyC,CACvC,OAAO,KAAKD,EACd,CAQA,SAAmB,CACjB,OAAO,KAAKC,EACd,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,CAEA,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,CCjEA,IAAsB,GAAtB,KAAsE,CACpE,cACA,GAAY,GAEZ,YAAY,EAAyB,CACnC,KAAK,cAAgB,IAAI,EAA0B,CAAO,CAC5D,CAEA,qBAAqB,EAAkC,CACrD,IAAM,EAAU,KAAK,cAAc,YAAY,EAC/C,GAAI,CAAC,EACH,MAAM,IAAI,EAAwB,CAAS,EAE7C,OAAO,CACT,CAUA,SAAgB,CACV,KAAKI,KAGT,KAAKA,GAAY,GACjB,KAAK,UAAU,EACjB,CAEA,CAAC,OAAO,UAAiB,CACvB,KAAK,QAAQ,CACf,CAEA,WAA4B,CAAC,CAC/B"}
@@ -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`)}function n(e){if(typeof e!=`object`||!e)return;let t=e;if(typeof t.statusCode==`number`)return t.statusCode;if(typeof t.status==`number`)return t.status;if(t.cause!==null&&t.cause!==void 0&&typeof t.cause==`object`){let e=t.cause;if(typeof e.statusCode==`number`)return e.statusCode;if(typeof e.status==`number`)return e.status}}export{t as n,e as r,n as t};
2
- //# sourceMappingURL=error-W1N-FGwV.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"error-W1N-FGwV.js","names":[],"sources":["../../src/utils/error.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/**\n * Extract an HTTP status code from an error, if present.\n * Relayer SDK errors may carry a `status` or `statusCode` property.\n */\nexport function extractHttpStatus(error: unknown): number | undefined {\n if (error === null || error === undefined || typeof error !== \"object\") {\n return undefined;\n }\n const e = error as Record<string, unknown>;\n if (typeof e.statusCode === \"number\") {\n return e.statusCode;\n }\n if (typeof e.status === \"number\") {\n return e.status;\n }\n // Check nested cause\n if (e.cause !== null && e.cause !== undefined && typeof e.cause === \"object\") {\n const cause = e.cause as Record<string, unknown>;\n if (typeof cause.statusCode === \"number\") {\n return cause.statusCode;\n }\n if (typeof cause.status === \"number\") {\n return cause.status;\n }\n }\n return undefined;\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,CAMA,SAAgB,EAAkB,EAAoC,CACpE,GAA6C,OAAO,GAAU,WAA1D,EACF,OAEF,IAAM,EAAI,EACV,GAAI,OAAO,EAAE,YAAe,SAC1B,OAAO,EAAE,WAEX,GAAI,OAAO,EAAE,QAAW,SACtB,OAAO,EAAE,OAGX,GAAI,EAAE,QAAU,MAAQ,EAAE,QAAU,IAAA,IAAa,OAAO,EAAE,OAAU,SAAU,CAC5E,IAAM,EAAQ,EAAE,MAChB,GAAI,OAAO,EAAM,YAAe,SAC9B,OAAO,EAAM,WAEf,GAAI,OAAO,EAAM,QAAW,SAC1B,OAAO,EAAM,MAEjB,CAEF"}
@@ -1,2 +0,0 @@
1
- const e={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`,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`,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`};var t=class extends Error{code;constructor(e,t,n){super(t,n),Object.setPrototypeOf(this,new.target.prototype),this.name=`ZamaError`,this.code=e}};function n(e,n){if(e instanceof t){let t=n[e.code];if(t)return t(e)}return n._?.(e)}var r=class extends t{statusCode;constructor(t,n,r){super(e.RelayerRequestFailed,t,r),this.name=`RelayerRequestFailedError`,this.statusCode=n}},i=class extends t{constructor(t,n){super(e.Configuration,t,n),this.name=`ConfigurationError`}};export{n as a,e as i,r as n,t as r,i as t};
2
- //# sourceMappingURL=relayer-D-nicEYJ.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"relayer-D-nicEYJ.js","names":[],"sources":["../../src/errors/base.ts","../../src/errors/relayer.ts"],"sourcesContent":["/**\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 /** 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 /** 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} as const;\n\n/** Union of all {@link ZamaErrorCode} string values. */\nexport type ZamaErrorCode = (typeof ZamaErrorCode)[keyof typeof ZamaErrorCode];\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 constructor(code: ZamaErrorCode, message: string, options?: ErrorOptions) {\n super(message, options);\n Object.setPrototypeOf(this, new.target.prototype);\n this.name = \"ZamaError\";\n this.code = code;\n }\n}\n\n/**\n * Pattern-match on a {@link ZamaError} by its error code.\n * Falls through to the `_` wildcard handler if no specific handler matches.\n * Returns `undefined` if the error is not a `ZamaError` and no `_` handler is provided.\n *\n * @example\n * ```ts\n * matchZamaError(error, {\n * SIGNING_REJECTED: () => toast(\"Please approve in wallet\"),\n * TRANSACTION_REVERTED: (e) => toast(`Tx failed: ${e.message}`),\n * _: () => toast(\"Unknown error\"),\n * });\n * ```\n */\nexport function matchZamaError<R>(\n error: unknown,\n handlers: Partial<Record<ZamaErrorCode, (error: ZamaError) => R>> & {\n _?: (error: unknown) => R;\n },\n): R | undefined {\n if (error instanceof ZamaError) {\n const handler = handlers[error.code];\n if (handler) {\n return handler(error);\n }\n }\n return handlers._?.(error);\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 constructor(message: string, statusCode?: number, options?: ErrorOptions) {\n super(ZamaErrorCode.RelayerRequestFailed, message, options);\n this.name = \"RelayerRequestFailedError\";\n this.statusCode = statusCode;\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":"AAeA,MAAa,EAAgB,CAE3B,gBAAiB,mBAEjB,cAAe,iBAEf,iBAAkB,oBAElB,iBAAkB,oBAElB,oBAAqB,uBAErB,wBAAyB,kBAEzB,wBAAyB,kBAEzB,aAAc,gBAEd,qBAAsB,yBAEtB,cAAe,gBAEf,yBAA0B,8BAE1B,mBAAoB,sBAEpB,mBAAoB,uBAEpB,kBAAmB,qBAEnB,gCAAiC,oCAEjC,yBAA0B,6BAE1B,wBAAyB,4BAEzB,gBAAiB,oBAEjB,0BAA2B,8BAE3B,iCAAkC,sCAElC,yBAA0B,8BAE1B,UAAW,aAEX,4BAA6B,iCAE7B,wBAAyB,4BAEzB,cAAe,iBAEf,oBAAqB,wBAErB,mBAAoB,uBAEpB,sBAAuB,0BACzB,EAUA,IAAa,EAAb,cAA+B,KAAM,CAEnC,KAEA,YAAY,EAAqB,EAAiB,EAAwB,CACxE,MAAM,EAAS,CAAO,EACtB,OAAO,eAAe,KAAM,IAAI,OAAO,SAAS,EAChD,KAAK,KAAO,YACZ,KAAK,KAAO,CACd,CACF,EAgBA,SAAgB,EACd,EACA,EAGe,CACf,GAAI,aAAiB,EAAW,CAC9B,IAAM,EAAU,EAAS,EAAM,MAC/B,GAAI,EACF,OAAO,EAAQ,CAAK,CAExB,CACA,OAAO,EAAS,IAAI,CAAK,CAC3B,CCtHA,IAAa,EAAb,cAA+C,CAAU,CAEvD,WAEA,YAAY,EAAiB,EAAqB,EAAwB,CACxE,MAAM,EAAc,qBAAsB,EAAS,CAAO,EAC1D,KAAK,KAAO,4BACZ,KAAK,WAAa,CACpB,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{t as e}from"./relayer-D-nicEYJ.js";import{n as t,t as n}from"./encryption-BGmINekJ.js";import{privateKeyToAccount as r}from"viem/accounts";import{concat as i,createPublicClient as a,custom as o,encodePacked as s,getAddress as c,http as l,keccak256 as u,pad as d,parseAbi as f,toBytes as p,toHex as m}from"viem";import{mainnet as h,sepolia as g}from"viem/chains";const _=(e,t)=>({name:`InputVerification`,version:`1`,chainId:BigInt(e),verifyingContract:t}),v=(e,t)=>({name:`Decryption`,version:`1`,chainId:BigInt(e),verifyingContract:t}),y={domain:_,types:{CiphertextVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`userAddress`,type:`address`},{name:`contractAddress`,type:`address`},{name:`contractChainId`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},b={domain:v,types:{PublicDecryptVerification:[{name:`ctHandles`,type:`bytes32[]`},{name:`decryptedResult`,type:`bytes`},{name:`extraData`,type:`bytes`}]}},x={domain:v,types:{UserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},S={domain:v,types:{DelegatedUserDecryptRequestVerification:[{name:`publicKey`,type:`bytes`},{name:`contractAddresses`,type:`address[]`},{name:`delegatorAddress`,type:`address`},{name:`startTimestamp`,type:`uint256`},{name:`durationDays`,type:`uint256`},{name:`extraData`,type:`bytes`}]}},C={ebool:0,euint8:2,euint16:3,euint32:4,euint64:5,euint128:6,eaddress:7,euint256:8},w={0:`ebool`,2:`euint8`,3:`euint16`,4:`euint32`,5:`euint64`,6:`euint128`,7:`eaddress`,8:`euint256`},T={0:2,2:8,3:16,4:32,5:64,6:128,7:160,8:256};Object.freeze(C),Object.freeze(w),Object.freeze(T),Object.freeze({2:0,8:2,16:3,32:4,64:5,128:6,160:7,256:8});function E(e){switch(e){case 0:case 2:case 3:case 4:case 5:case 6:case 7:case 8:return!0;default:return!1}}function D(e){return typeof e==`string`?e in C:!1}function O(e){if(!D(e))throw Error(`Invalid FheType name '${e}'`);return C[e]}function k(e){if(!E(e))throw Error(`Invalid FheType id '${e}'`);let t=T[e];if(t<2)throw Error(`Invalid FheType encryption bit width: ${t}. Minimum is 2 bits.`);return t}const A=p(`ZK-w_rct`),j=p(`ZK-w_hdl`);function M(e,t){let n=Math.ceil(k(t)/8);return p(d(m(e),{size:n}))}function N(e,n,r){if(r.length!==32)throw new t(`random32 must be exactly 32 bytes`);let a=M(n,e),o=u(i([m(new Uint8Array([e])),m(a),m(r)]));return u(i([m(A),o]))}function P(e,n,r,a,o){if(!Number.isInteger(n)||n<0||n>255)throw new t(`index must be an integer between 0 and 255`);let c=u(i([m(A),e])),l=u(s([`bytes`,`bytes32`,`uint8`,`address`,`uint256`],[m(j),c,n,a,o])),d=o&18446744073709551615n;return m(BigInt(l)&115792089237316195423570985008687907853269984665640254554447762662844404858880n|BigInt(n)<<80n|d<<16n|BigInt(r)<<8n|BigInt(0),{size:32})}const F=f([`function persistAllowed(bytes32 handle, address account) view returns (bool)`,`function isAllowedForDecryption(bytes32 handle) view returns (bool)`,`function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)`]),I=f([`function plaintexts(bytes32 handle) view returns (uint256)`]),L=[{name:`name`,type:`string`},{name:`version`,type:`string`},{name:`chainId`,type:`uint256`},{name:`verifyingContract`,type:`address`}],R={EIP712Domain:L,UserDecryptRequestVerification:x.types.UserDecryptRequestVerification},z={EIP712Domain:L,DelegatedUserDecryptRequestVerification:S.types.DelegatedUserDecryptRequestVerification},B={EIP712Domain:L,PublicDecryptVerification:b.types.PublicDecryptVerification},V=new Set([h.id,g.id]);function H(e,t){let n=Number(BigInt(e)>>8n&255n);return n===0?t!==0n:n===7?m(t,{size:20}):t}function U(e){if(!D(e.type))throw new t(`Unsupported FHE type`);let n=O(e.type),r;if(e.type===`ebool`){if(typeof e.value==`boolean`)r=e.value?1n:0n;else if(r=e.value,r!==0n&&r!==1n)throw new t(`Bool value must be 0, 1, true, or false`)}else r=e.type===`eaddress`?BigInt(c(e.value)):e.value;if(r<0n)throw new t(`Only non-negative cleartext values are supported`);let i=k(n),a=(1n<<BigInt(i))-1n;if(r>a)throw new t(`Value ${r} exceeds max ${a} for FheType ${n}`);return{fheType:n,value:r}}var W=class{#e;#t;kmsSigner;inputSigner;constructor(t){if(V.has(t.id))throw new e(`Cleartext mode is not allowed on chain ${t.id}. It is intended for local development and testing only.`);if(!t.executorAddress)throw new e(`Cleartext transport requires an executorAddress for chain ${t.id}.`);this.#e=a({transport:typeof t.network==`string`?l(t.network):o(t.network)}),this.#t=t,this.kmsSigner=r(t.kmsSignerPrivateKey??`0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91`),this.inputSigner=r(t.inputSignerPrivateKey??`0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901`)}async generateTransportKeyPair(){let e=m(crypto.getRandomValues(new Uint8Array(32))),t=m(crypto.getRandomValues(new Uint8Array(32)));for(;t===e;)t=m(crypto.getRandomValues(new Uint8Array(32)));return{publicKey:e,privateKey:t}}async createEIP712(e,t,n,r=7){return{domain:x.domain(this.#t.id,this.#t.verifyingContractAddressDecryption),types:R,primaryType:`UserDecryptRequestVerification`,message:{publicKey:e,contractAddresses:t,startTimestamp:String(n),durationDays:String(r),extraData:`0x00`}}}async encrypt(e){let t=e.values.map(U),n=c(e.contractAddress),r=c(e.userAddress),a=t.map(({fheType:e,value:t})=>N(e,t,crypto.getRandomValues(new Uint8Array(32)))),o=u(a.length>0?i(a):`0x`),s=t.map(({fheType:e},t)=>P(o,t,e,this.#t.aclContractAddress,BigInt(this.#t.id))),l=t.map(({value:e})=>d(m(e),{size:32})),f=l.length>0?i(l):`0x`,p=await this.inputSigner.signTypedData({domain:y.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressInputVerification),types:{CiphertextVerification:y.types.CiphertextVerification},primaryType:`CiphertextVerification`,message:{ctHandles:s,userAddress:r,contractAddress:n,contractChainId:BigInt(this.#t.id),extraData:f}});return{encryptedValues:s,inputProof:i([m(new Uint8Array([s.length])),m(new Uint8Array([1])),...s,p,f])}}async userDecrypt(e){return await this.#r(e.encryptedValues,c(e.signerAddress),c(e.contractAddress),`User`,`user decrypt`),this.#n(e.encryptedValues)}async publicDecrypt(e){let t=e,r=(await Promise.all(t.map(e=>this.#o(e)))).findIndex(e=>!e);if(r!==-1)throw new n(`Encrypted value ${t[r]} is not allowed for public decryption`);let a=await Promise.all(t.map(e=>this.#s(e))),o=Object.fromEntries(t.map((e,t)=>[e,H(e,a[t])])),s=i(a.map(e=>d(m(e),{size:32}))),c=await this.kmsSigner.signTypedData({domain:b.domain(this.#t.gatewayChainId,this.#t.verifyingContractAddressDecryption),types:B,primaryType:`PublicDecryptVerification`,message:{ctHandles:t,decryptedResult:s,extraData:`0x`}});return{clearValues:o,abiEncodedClearValues:s,decryptionProof:i([m(new Uint8Array([1])),c])}}async createDelegatedUserDecryptEIP712(e,t,n,r,i=7){let a={publicKey:e,contractAddresses:t,delegatorAddress:c(n),startTimestamp:String(r),durationDays:String(i),extraData:`0x00`};return{domain:S.domain(this.#t.id,this.#t.verifyingContractAddressDecryption),types:z,primaryType:`DelegatedUserDecryptRequestVerification`,message:a}}async delegatedUserDecrypt(e){return await this.#i(e.encryptedValues,c(e.delegatorAddress),c(e.delegateAddress),c(e.contractAddress)),this.#n(e.encryptedValues)}async requestZKProofVerification(t){throw new e(`Not implemented in cleartext mode`)}async fetchFheEncryptionKeyBytes(){return{publicKeyId:`mock-public-key-id`,publicKey:new Uint8Array([32])}}async getPublicParams(e){return{publicParams:new Uint8Array([32]),publicParamsId:`mock-public-params-id`}}async getAclAddress(){return this.#t.aclContractAddress}terminate(){}[Symbol.dispose](){this.terminate()}async#n(e){let t=await Promise.all(e.map(e=>this.#s(e)));return Object.fromEntries(e.map((e,n)=>[e,H(e,t[n])]))}async#r(e,t,r,i,a){if(t===r)throw new n(`${i} address ${t} must not equal contract address for ${a}`);let o=await Promise.all(e.flatMap(e=>[this.#a(e,t),this.#a(e,r)]));for(let s=0;s<e.length;s++){let c=o[s*2],l=o[s*2+1];if(!c)throw new n(`${i} ${t} is not authorized for ${a} of encrypted value ${e[s]}`);if(!l)throw new n(`Contract ${r} is not authorized for ${a} of encrypted value ${e[s]}`)}}async#i(e,t,r,i){let a=await Promise.all(e.map(e=>this.#e.readContract({address:this.#t.aclContractAddress,abi:F,functionName:`isHandleDelegatedForUserDecryption`,args:[t,r,i,e]})));for(let t=0;t<e.length;t++)if(!a[t])throw new n(`Encrypted value ${e[t]} is not delegated for user decryption`)}async#a(e,t){return this.#e.readContract({address:this.#t.aclContractAddress,abi:F,functionName:`persistAllowed`,args:[e,t]})}async#o(e){return this.#e.readContract({address:this.#t.aclContractAddress,abi:F,functionName:`isAllowedForDecryption`,args:[e]})}async#s(e){return this.#e.readContract({address:this.#t.executorAddress,abi:I,functionName:`plaintexts`,args:[e]})}};export{W as t};
2
- //# sourceMappingURL=relayer-cleartext-DGcb5qtE.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"relayer-cleartext-DGcb5qtE.js","names":["#client","#config","#assertDecryptAuthorization","#decryptHandles","#isAllowedForDecryption","#readPlaintext","#assertDelegation","#persistAllowed"],"sources":["../../src/relayer/cleartext/eip712.ts","../../src/relayer/cleartext/constants.ts","../../src/relayer/cleartext/fhe-type.ts","../../src/relayer/cleartext/handle.ts","../../src/relayer/cleartext/relayer-cleartext.ts"],"sourcesContent":["import type { Address } from \"viem\";\nimport type {\n CoprocessorEIP712DomainType,\n CoprocessorEIP712TypesType,\n KmsDelegatedUserDecryptEIP712TypesType,\n KmsEIP712DomainType,\n KmsPublicDecryptEIP712TypesType,\n KmsUserDecryptEIP712TypesType,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nconst inputDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): CoprocessorEIP712DomainType => ({\n name: \"InputVerification\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nconst decryptionDomain = (\n chainId: number | bigint,\n verifyingContract: Address,\n): KmsEIP712DomainType => ({\n name: \"Decryption\",\n version: \"1\",\n chainId: BigInt(chainId),\n verifyingContract,\n});\n\nexport const INPUT_VERIFICATION_EIP712 = {\n domain: inputDomain,\n types: {\n CiphertextVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"userAddress\", type: \"address\" },\n { name: \"contractAddress\", type: \"address\" },\n { name: \"contractChainId\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const KMS_DECRYPTION_EIP712 = {\n domain: decryptionDomain,\n types: {\n PublicDecryptVerification: [\n { name: \"ctHandles\", type: \"bytes32[]\" },\n { name: \"decryptedResult\", type: \"bytes\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n UserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\nexport const DELEGATED_USER_DECRYPT_EIP712 = {\n domain: decryptionDomain,\n types: {\n DelegatedUserDecryptRequestVerification: [\n { name: \"publicKey\", type: \"bytes\" },\n { name: \"contractAddresses\", type: \"address[]\" },\n { name: \"delegatorAddress\", type: \"address\" },\n { name: \"startTimestamp\", type: \"uint256\" },\n { name: \"durationDays\", type: \"uint256\" },\n { name: \"extraData\", type: \"bytes\" },\n ],\n },\n} as const;\n\n// ── Compile-time structural checks against relayer-sdk types ──────────\n// These assertions ensure our local EIP-712 type arrays stay in sync with\n// the relayer-sdk's canonical definitions. A mismatch will cause a build error.\ntype AssertFieldsMatch<\n Local extends readonly { readonly name: string; readonly type: string }[],\n Canonical extends readonly { readonly name: string; readonly type: string }[],\n> = [Local[\"length\"]] extends [Canonical[\"length\"]]\n ? {\n [K in keyof Local]: Local[K] extends { readonly name: infer N; readonly type: infer T }\n ? Canonical[K & keyof Canonical] extends { readonly name: N; readonly type: T }\n ? true\n : { error: `Field mismatch at index ${K & string}` }\n : never;\n }\n : { error: \"Field count mismatch\" };\n\n// Wrapping in readonly true[] ensures a mismatch produces a compile error\n// (not just an inert type alias that TypeScript silently accepts).\ntype AssertAllTrue<T extends readonly true[]> = T;\n\ntype _CheckInput = AssertAllTrue<\n AssertFieldsMatch<\n typeof INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n CoprocessorEIP712TypesType[\"CiphertextVerification\"]\n >\n>;\ntype _CheckPublicDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n KmsPublicDecryptEIP712TypesType[\"PublicDecryptVerification\"]\n >\n>;\ntype _CheckUserDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n KmsUserDecryptEIP712TypesType[\"UserDecryptRequestVerification\"]\n >\n>;\ntype _CheckDelegatedDecrypt = AssertAllTrue<\n AssertFieldsMatch<\n typeof DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n KmsDelegatedUserDecryptEIP712TypesType[\"DelegatedUserDecryptRequestVerification\"]\n >\n>;\n","export const HANDLE_VERSION = 0;\n\nexport const PREHANDLE_MASK = 0xffffffffffffffffffffffffffffffffffffffffff0000000000000000000000n;\n\n// Constants used for instanciation of the cleartext FHEVM instance.\nexport const MOCK_INPUT_SIGNER_PK =\n \"0x7ec8ada6642fc4ccfb7729bc29c17cf8d21b61abd5642d1db992c0b8672ab901\";\nexport const MOCK_KMS_SIGNER_PK =\n \"0x388b7680e4e1afa06efbfd45cdd1fe39f3c6af381df6555a19661f283b97de91\";\n","// Copied from @zama-fhe/relayer-sdk/src/sdk/FheType.ts\n// Pure utility functions with zero WASM dependency.\n// Adapted to use simple errors instead of RelayerErrorBase hierarchy.\n\n////////////////////////////////////////////////////////////////////////////////\n// Types (from types/primitives.d.ts)\n////////////////////////////////////////////////////////////////////////////////\n\nexport interface FheTypeNameToIdMap {\n ebool: 0;\n //euint4: 1; deprecated\n euint8: 2;\n euint16: 3;\n euint32: 4;\n euint64: 5;\n euint128: 6;\n eaddress: 7;\n euint256: 8;\n}\n\nexport interface FheTypeIdToNameMap {\n 0: \"ebool\";\n //1: 'euint4'; deprecated\n 2: \"euint8\";\n 3: \"euint16\";\n 4: \"euint32\";\n 5: \"euint64\";\n 6: \"euint128\";\n 7: \"eaddress\";\n 8: \"euint256\";\n}\n\nexport interface FheTypeEncryptionBitwidthToIdMap {\n 2: FheTypeNameToIdMap[\"ebool\"];\n 8: FheTypeNameToIdMap[\"euint8\"];\n 16: FheTypeNameToIdMap[\"euint16\"];\n 32: FheTypeNameToIdMap[\"euint32\"];\n 64: FheTypeNameToIdMap[\"euint64\"];\n 128: FheTypeNameToIdMap[\"euint128\"];\n 160: FheTypeNameToIdMap[\"eaddress\"];\n 256: FheTypeNameToIdMap[\"euint256\"];\n}\n\nexport type FheTypeIdToEncryptionBitwidthMap = {\n [K in keyof FheTypeEncryptionBitwidthToIdMap as FheTypeEncryptionBitwidthToIdMap[K]]: K;\n};\n\ntype Prettify<T> = { [K in keyof T]: T[K] } & {};\n\nexport type FheTypeName = Prettify<keyof FheTypeNameToIdMap>;\nexport type FheTypeId = Prettify<keyof FheTypeIdToNameMap>;\nexport type EncryptionBits = Prettify<keyof FheTypeEncryptionBitwidthToIdMap>;\n\n////////////////////////////////////////////////////////////////////////////////\n// Lookup Maps\n////////////////////////////////////////////////////////////////////////////////\n\nconst MINIMUM_ENCRYPTION_BIT_WIDTH = 2;\n\nconst FheTypeNameToId: FheTypeNameToIdMap = {\n ebool: 0,\n //euint4: 1, deprecated\n euint8: 2,\n euint16: 3,\n euint32: 4,\n euint64: 5,\n euint128: 6,\n eaddress: 7,\n euint256: 8,\n} as const;\n\nconst FheTypeIdToName: FheTypeIdToNameMap = {\n 0: \"ebool\",\n //1: 'euint4', deprecated\n 2: \"euint8\",\n 3: \"euint16\",\n 4: \"euint32\",\n 5: \"euint64\",\n 6: \"euint128\",\n 7: \"eaddress\",\n 8: \"euint256\",\n} as const;\n\nconst FheTypeIdToEncryptionBitwidth: FheTypeIdToEncryptionBitwidthMap = {\n 0: 2,\n //1:?, euint4 deprecated\n 2: 8,\n 3: 16,\n 4: 32,\n 5: 64,\n 6: 128,\n 7: 160,\n 8: 256,\n} as const;\n\nconst EncryptionBitwidthToFheTypeId: FheTypeEncryptionBitwidthToIdMap = {\n 2: 0,\n 8: 2,\n 16: 3,\n 32: 4,\n 64: 5,\n 128: 6,\n 160: 7,\n 256: 8,\n} as const;\n\nObject.freeze(FheTypeNameToId);\nObject.freeze(FheTypeIdToName);\nObject.freeze(FheTypeIdToEncryptionBitwidth);\nObject.freeze(EncryptionBitwidthToFheTypeId);\n\n////////////////////////////////////////////////////////////////////////////////\n// Type Guards\n////////////////////////////////////////////////////////////////////////////////\n\nexport function isFheTypeId(value: unknown): value is FheTypeId {\n switch (value as FheTypeId) {\n case 0:\n case 2:\n case 3:\n case 4:\n case 5:\n case 6:\n case 7:\n case 8:\n return true;\n default:\n return false;\n }\n}\n\nexport function isFheTypeName(value: unknown): value is FheTypeName {\n if (typeof value !== \"string\") {\n return false;\n }\n return value in FheTypeNameToId;\n}\n\nexport function isEncryptionBits(value: unknown): value is EncryptionBits {\n if (typeof value !== \"number\") {\n return false;\n }\n return value in EncryptionBitwidthToFheTypeId;\n}\n\n////////////////////////////////////////////////////////////////////////////////\n// Converters\n////////////////////////////////////////////////////////////////////////////////\n\nexport function fheTypeIdFromEncryptionBits(bitwidth: number): FheTypeId {\n if (!isEncryptionBits(bitwidth)) {\n throw new Error(`Invalid encryption bits ${bitwidth}`);\n }\n return EncryptionBitwidthToFheTypeId[bitwidth];\n}\n\nexport function fheTypeIdFromName(name: string): FheTypeId {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n return FheTypeNameToId[name];\n}\n\nexport function fheTypeNameFromId(id: number): FheTypeName {\n if (!isFheTypeId(id)) {\n throw new Error(`Invalid FheType id '${id}'`);\n }\n return FheTypeIdToName[id];\n}\n\nexport function encryptionBitsFromFheTypeId(typeId: number): EncryptionBits {\n if (!isFheTypeId(typeId)) {\n throw new Error(`Invalid FheType id '${typeId}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[typeId];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n\nexport function encryptionBitsFromFheTypeName(name: string): EncryptionBits {\n if (!isFheTypeName(name)) {\n throw new Error(`Invalid FheType name '${name}'`);\n }\n const bw = FheTypeIdToEncryptionBitwidth[FheTypeNameToId[name]];\n if (bw < MINIMUM_ENCRYPTION_BIT_WIDTH) {\n throw new Error(\n `Invalid FheType encryption bit width: ${bw}. Minimum is ${MINIMUM_ENCRYPTION_BIT_WIDTH} bits.`,\n );\n }\n return bw;\n}\n","import { concat, encodePacked, keccak256, pad, toBytes, toHex, type Address, type Hex } from \"viem\";\nimport { HANDLE_VERSION, PREHANDLE_MASK } from \"./constants\";\nimport { encryptionBitsFromFheTypeId, type FheTypeId } from \"./fhe-type\";\nimport { EncryptionFailedError } from \"../../errors\";\n\nconst RAW_CT_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_rct\");\nconst HANDLE_HASH_DOMAIN_SEPARATOR = toBytes(\"ZK-w_hdl\");\n\nfunction cleartextToBytes(cleartext: bigint, fheType: FheTypeId): Uint8Array {\n const byteLength = Math.ceil(encryptionBitsFromFheTypeId(fheType) / 8);\n return toBytes(pad(toHex(cleartext), { size: byteLength }));\n}\n\nexport function computeMockCiphertext(\n fheType: FheTypeId,\n cleartext: bigint,\n random32: Uint8Array,\n): Hex {\n if (random32.length !== 32) {\n throw new EncryptionFailedError(\"random32 must be exactly 32 bytes\");\n }\n\n const clearBytes = cleartextToBytes(cleartext, fheType);\n const inner = keccak256(\n concat([toHex(new Uint8Array([fheType])), toHex(clearBytes), toHex(random32)]),\n );\n\n return keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), inner]));\n}\n\nexport function computeInputHandle(\n mockCiphertext: Hex,\n index: number,\n fheType: FheTypeId,\n aclAddress: Address,\n chainId: bigint,\n): Hex {\n if (!Number.isInteger(index) || index < 0 || index > 255) {\n throw new EncryptionFailedError(\"index must be an integer between 0 and 255\");\n }\n\n const blobHash = keccak256(concat([toHex(RAW_CT_HASH_DOMAIN_SEPARATOR), mockCiphertext]));\n const handleHash = keccak256(\n encodePacked(\n [\"bytes\", \"bytes32\", \"uint8\", \"address\", \"uint256\"],\n [toHex(HANDLE_HASH_DOMAIN_SEPARATOR), blobHash, index, aclAddress, chainId],\n ),\n );\n\n const chainId64 = chainId & 0xffff_ffff_ffff_ffffn;\n const handle =\n (BigInt(handleHash) & PREHANDLE_MASK) |\n (BigInt(index) << 80n) |\n (chainId64 << 16n) |\n (BigInt(fheType) << 8n) |\n BigInt(HANDLE_VERSION);\n\n return toHex(handle, { size: 32 });\n}\n","import type { PrivateKeyAccount } from \"viem/accounts\";\nimport { privateKeyToAccount } from \"viem/accounts\";\nimport {\n concat,\n createPublicClient,\n custom,\n getAddress,\n http,\n keccak256,\n pad,\n parseAbi,\n toHex,\n type Address,\n type Hex,\n type PublicClient,\n} from \"viem\";\nimport { mainnet, sepolia } from \"viem/chains\";\nimport type {\n InputProofBytesType,\n KmsDelegatedUserDecryptEIP712Type,\n KmsPublicDecryptEIP712Type,\n KmsUserDecryptEIP712Type,\n ZKProofLike,\n} from \"@zama-fhe/relayer-sdk/bundle\";\n\nimport type { TransportKeyPair } from \"../../credentials/types\";\nimport type { RelayerSDK } from \"../relayer-sdk\";\nimport type {\n ClearValue,\n DelegatedUserDecryptParams,\n EIP712TypedData,\n EncryptParams,\n EncryptResult,\n EncryptedValue,\n FheEncryptionKey,\n PublicDecryptResult,\n PublicParamsData,\n UserDecryptParams,\n} from \"../relayer-sdk.types\";\nimport {\n DELEGATED_USER_DECRYPT_EIP712,\n INPUT_VERIFICATION_EIP712,\n KMS_DECRYPTION_EIP712,\n USER_DECRYPT_EIP712,\n} from \"./eip712\";\nimport { MOCK_INPUT_SIGNER_PK, MOCK_KMS_SIGNER_PK } from \"./constants\";\nimport {\n encryptionBitsFromFheTypeId,\n fheTypeIdFromName,\n isFheTypeName,\n type FheTypeId,\n} from \"./fhe-type\";\nimport { computeInputHandle, computeMockCiphertext } from \"./handle\";\nimport type { FheChain } from \"../../chains/types\";\nimport { ConfigurationError, DecryptionFailedError, EncryptionFailedError } from \"../../errors\";\n\nconst ACL_ABI = parseAbi([\n \"function persistAllowed(bytes32 handle, address account) view returns (bool)\",\n \"function isAllowedForDecryption(bytes32 handle) view returns (bool)\",\n \"function isHandleDelegatedForUserDecryption(address delegator, address delegate, address contractAddress, bytes32 handle) view returns (bool)\",\n]);\n\nconst EXECUTOR_ABI = parseAbi([\"function plaintexts(bytes32 handle) view returns (uint256)\"]);\n\nconst STANDARD_EIP712_DOMAIN = [\n { name: \"name\", type: \"string\" },\n { name: \"version\", type: \"string\" },\n { name: \"chainId\", type: \"uint256\" },\n { name: \"verifyingContract\", type: \"address\" },\n] as const;\n\nconst USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n UserDecryptRequestVerification: USER_DECRYPT_EIP712.types.UserDecryptRequestVerification,\n} satisfies KmsUserDecryptEIP712Type[\"types\"];\nconst DELEGATED_USER_DECRYPT_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n DelegatedUserDecryptRequestVerification:\n DELEGATED_USER_DECRYPT_EIP712.types.DelegatedUserDecryptRequestVerification,\n} satisfies KmsDelegatedUserDecryptEIP712Type[\"types\"];\nconst KMS_DECRYPTION_TYPES = {\n EIP712Domain: STANDARD_EIP712_DOMAIN,\n PublicDecryptVerification: KMS_DECRYPTION_EIP712.types.PublicDecryptVerification,\n} satisfies KmsPublicDecryptEIP712Type[\"types\"];\n\nconst FORBIDDEN_CHAIN_IDS = new Set<number>([mainnet.id, sepolia.id]);\n\n// FheTypeId constants for hot-path comparisons\nconst EBOOL_ID: FheTypeId = 0;\nconst EADDRESS_ID: FheTypeId = 7;\n\nfunction decodeClearValue(encryptedValue: EncryptedValue, rawValue: bigint): ClearValue {\n const typeByte = Number((BigInt(encryptedValue) >> 8n) & 0xffn);\n if (typeByte === EBOOL_ID) {\n return rawValue !== 0n;\n }\n if (typeByte === EADDRESS_ID) {\n return toHex(rawValue, { size: 20 });\n }\n return rawValue;\n}\n\nfunction normalizeEncryptValue(entry: EncryptParams[\"values\"][number]): {\n fheType: FheTypeId;\n value: bigint;\n} {\n if (!isFheTypeName(entry.type)) {\n throw new EncryptionFailedError(\"Unsupported FHE type\");\n }\n\n const fheType = fheTypeIdFromName(entry.type);\n\n let value: bigint;\n if (entry.type === \"ebool\") {\n if (typeof entry.value === \"boolean\") {\n value = entry.value ? 1n : 0n;\n } else {\n value = entry.value;\n if (value !== 0n && value !== 1n) {\n throw new EncryptionFailedError(\"Bool value must be 0, 1, true, or false\");\n }\n }\n } else if (entry.type === \"eaddress\") {\n value = BigInt(getAddress(entry.value));\n } else {\n value = entry.value;\n }\n\n if (value < 0n) {\n throw new EncryptionFailedError(\"Only non-negative cleartext values are supported\");\n }\n\n const bits = encryptionBitsFromFheTypeId(fheType);\n const maxValue = (1n << BigInt(bits)) - 1n;\n if (value > maxValue) {\n throw new EncryptionFailedError(\n `Value ${value} exceeds max ${maxValue} for FheType ${fheType}`,\n );\n }\n\n return { fheType, value };\n}\n\nexport class RelayerCleartext implements RelayerSDK, Disposable {\n readonly #client: PublicClient;\n readonly #config: FheChain;\n readonly kmsSigner: PrivateKeyAccount;\n readonly inputSigner: PrivateKeyAccount;\n\n constructor(config: FheChain) {\n if (FORBIDDEN_CHAIN_IDS.has(config.id)) {\n throw new ConfigurationError(\n `Cleartext mode is not allowed on chain ${config.id}. ` +\n `It is intended for local development and testing only.`,\n );\n }\n if (!config.executorAddress) {\n throw new ConfigurationError(\n `Cleartext transport requires an executorAddress for chain ${config.id}.`,\n );\n }\n this.#client = createPublicClient({\n transport: typeof config.network === \"string\" ? http(config.network) : custom(config.network),\n });\n this.#config = config;\n this.kmsSigner = privateKeyToAccount(config.kmsSignerPrivateKey ?? MOCK_KMS_SIGNER_PK);\n this.inputSigner = privateKeyToAccount(config.inputSignerPrivateKey ?? MOCK_INPUT_SIGNER_PK);\n }\n\n async generateTransportKeyPair(): Promise<TransportKeyPair> {\n const publicKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n let privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n\n while (privateKey === publicKey) {\n privateKey = toHex(crypto.getRandomValues(new Uint8Array(32)));\n }\n\n return { publicKey, privateKey };\n }\n\n async createEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n startTimestamp: number,\n durationDays = 7,\n ): Promise<EIP712TypedData> {\n return {\n domain: USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: USER_DECRYPT_TYPES,\n primaryType: \"UserDecryptRequestVerification\",\n message: {\n publicKey,\n contractAddresses,\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n },\n };\n }\n\n async encrypt(params: EncryptParams): Promise<EncryptResult> {\n const entries = params.values.map(normalizeEncryptValue);\n const contractAddress = getAddress(params.contractAddress);\n const userAddress = getAddress(params.userAddress);\n\n const mockCiphertexts = entries.map(({ fheType, value }) =>\n computeMockCiphertext(fheType, value, crypto.getRandomValues(new Uint8Array(32))),\n );\n\n const ciphertextBlob = keccak256(mockCiphertexts.length > 0 ? concat(mockCiphertexts) : \"0x\");\n\n const handles = entries.map(({ fheType }, index) =>\n computeInputHandle(\n ciphertextBlob,\n index,\n fheType,\n this.#config.aclContractAddress as Address,\n BigInt(this.#config.id),\n ),\n );\n\n const cleartextParts = entries.map(({ value }) => pad(toHex(value), { size: 32 }));\n const cleartextBytes: Hex = cleartextParts.length > 0 ? concat(cleartextParts) : \"0x\";\n\n const signature = await this.inputSigner.signTypedData({\n domain: INPUT_VERIFICATION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressInputVerification as Address,\n ),\n types: {\n CiphertextVerification: INPUT_VERIFICATION_EIP712.types.CiphertextVerification,\n },\n primaryType: \"CiphertextVerification\",\n message: {\n ctHandles: handles,\n userAddress,\n contractAddress,\n contractChainId: BigInt(this.#config.id),\n extraData: cleartextBytes,\n },\n });\n\n const inputProof = concat([\n toHex(new Uint8Array([handles.length])),\n toHex(new Uint8Array([1])),\n ...handles,\n signature,\n cleartextBytes,\n ]);\n\n return { encryptedValues: handles, inputProof };\n }\n\n async userDecrypt(\n params: UserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDecryptAuthorization(\n params.encryptedValues,\n getAddress(params.signerAddress),\n getAddress(params.contractAddress),\n \"User\",\n \"user decrypt\",\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async publicDecrypt(encryptedValues: EncryptedValue[]): Promise<PublicDecryptResult> {\n const normalizedHandles = encryptedValues;\n\n const allowedResults = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#isAllowedForDecryption(encryptedValue)),\n );\n const unauthorizedIndex = allowedResults.findIndex((isAllowed) => !isAllowed);\n if (unauthorizedIndex !== -1) {\n throw new DecryptionFailedError(\n `Encrypted value ${normalizedHandles[unauthorizedIndex]!} is not allowed for public decryption`,\n );\n }\n\n const orderedValues = await Promise.all(\n normalizedHandles.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n const clearValues: PublicDecryptResult[\"clearValues\"] = Object.fromEntries(\n normalizedHandles.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, orderedValues[index]!),\n ]),\n );\n\n const abiEncodedClearValues = concat(orderedValues.map((v) => pad(toHex(v), { size: 32 })));\n\n const signature = await this.kmsSigner.signTypedData({\n domain: KMS_DECRYPTION_EIP712.domain(\n this.#config.gatewayChainId,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: KMS_DECRYPTION_TYPES,\n primaryType: \"PublicDecryptVerification\",\n message: {\n ctHandles: normalizedHandles,\n decryptedResult: abiEncodedClearValues,\n extraData: \"0x\",\n },\n });\n\n const decryptionProof = concat([toHex(new Uint8Array([1])), signature]);\n\n return {\n clearValues,\n abiEncodedClearValues,\n decryptionProof,\n };\n }\n\n async createDelegatedUserDecryptEIP712(\n publicKey: Hex,\n contractAddresses: Address[],\n delegatorAddress: Address,\n startTimestamp: number,\n durationDays = 7,\n ): Promise<KmsDelegatedUserDecryptEIP712Type> {\n const message: KmsDelegatedUserDecryptEIP712Type[\"message\"] = {\n publicKey,\n contractAddresses,\n delegatorAddress: getAddress(delegatorAddress),\n startTimestamp: String(startTimestamp),\n durationDays: String(durationDays),\n extraData: \"0x00\",\n };\n\n return {\n domain: DELEGATED_USER_DECRYPT_EIP712.domain(\n this.#config.id,\n this.#config.verifyingContractAddressDecryption as Address,\n ),\n types: DELEGATED_USER_DECRYPT_TYPES,\n primaryType: \"DelegatedUserDecryptRequestVerification\",\n message,\n };\n }\n\n async delegatedUserDecrypt(\n params: DelegatedUserDecryptParams,\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n await this.#assertDelegation(\n params.encryptedValues,\n getAddress(params.delegatorAddress),\n getAddress(params.delegateAddress),\n getAddress(params.contractAddress),\n );\n\n return this.#decryptHandles(params.encryptedValues);\n }\n\n async requestZKProofVerification(_zkProof: ZKProofLike): Promise<InputProofBytesType> {\n throw new ConfigurationError(\"Not implemented in cleartext mode\");\n }\n\n async fetchFheEncryptionKeyBytes(): Promise<FheEncryptionKey | null> {\n return {\n publicKeyId: \"mock-public-key-id\",\n publicKey: new Uint8Array([32]),\n };\n }\n\n async getPublicParams(_bits: number): Promise<PublicParamsData | null> {\n return {\n publicParams: new Uint8Array([32]),\n publicParamsId: \"mock-public-params-id\",\n };\n }\n\n async getAclAddress(): Promise<Address> {\n return this.#config.aclContractAddress as Address;\n }\n\n terminate(): void {\n // No resources to release in cleartext mode.\n }\n\n /** Calls {@link terminate} (no-op in cleartext mode). */\n [Symbol.dispose](): void {\n this.terminate();\n }\n\n async #decryptHandles(\n normalizedEncryptedValues: EncryptedValue[],\n ): Promise<Readonly<Record<EncryptedValue, ClearValue>>> {\n const values = await Promise.all(\n normalizedEncryptedValues.map((encryptedValue) => this.#readPlaintext(encryptedValue)),\n );\n\n return Object.fromEntries(\n normalizedEncryptedValues.map((encryptedValue, index) => [\n encryptedValue,\n decodeClearValue(encryptedValue, values[index]!),\n ]),\n );\n }\n\n async #assertDecryptAuthorization(\n normalizedEncryptedValues: EncryptedValue[],\n actorAddress: Address,\n contractAddress: Address,\n actorLabel: \"User\" | \"Delegator\",\n operationLabel: \"user decrypt\" | \"delegated decrypt\",\n ): Promise<void> {\n if (actorAddress === contractAddress) {\n throw new DecryptionFailedError(\n `${actorLabel} address ${actorAddress} must not equal contract address for ${operationLabel}`,\n );\n }\n\n const results = await Promise.all(\n normalizedEncryptedValues.flatMap((encryptedValue) => [\n this.#persistAllowed(encryptedValue, actorAddress),\n this.#persistAllowed(encryptedValue, contractAddress),\n ]),\n );\n\n for (let i = 0; i < normalizedEncryptedValues.length; i++) {\n const actorAllowed = results[i * 2];\n const contractAllowed = results[i * 2 + 1];\n if (!actorAllowed) {\n throw new DecryptionFailedError(\n `${actorLabel} ${actorAddress} is not authorized for ${operationLabel} of encrypted value ${normalizedEncryptedValues[i]!}`,\n );\n }\n if (!contractAllowed) {\n throw new DecryptionFailedError(\n `Contract ${contractAddress} is not authorized for ${operationLabel} of encrypted value ${normalizedEncryptedValues[i]!}`,\n );\n }\n }\n }\n\n async #assertDelegation(\n encryptedValues: EncryptedValue[],\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n ): Promise<void> {\n const results = await Promise.all(\n encryptedValues.map((encryptedValue) =>\n this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, encryptedValue],\n }),\n ),\n );\n\n for (let i = 0; i < encryptedValues.length; i++) {\n if (!results[i]) {\n throw new DecryptionFailedError(\n `Encrypted value ${encryptedValues[i]!} is not delegated for user decryption`,\n );\n }\n }\n }\n\n async #persistAllowed(encryptedValue: EncryptedValue, account: Address): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"persistAllowed\",\n args: [encryptedValue, account],\n });\n }\n\n async #isAllowedForDecryption(encryptedValue: EncryptedValue): Promise<boolean> {\n return this.#client.readContract({\n address: this.#config.aclContractAddress as Address,\n abi: ACL_ABI,\n functionName: \"isAllowedForDecryption\",\n args: [encryptedValue],\n });\n }\n\n async #readPlaintext(encryptedValue: EncryptedValue): Promise<bigint> {\n return this.#client.readContract({\n address: this.#config.executorAddress as Address,\n abi: EXECUTOR_ABI,\n functionName: \"plaintexts\",\n args: [encryptedValue],\n });\n }\n}\n"],"mappings":"iXAUA,MAAM,GACJ,EACA,KACiC,CACjC,KAAM,oBACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEM,GACJ,EACA,KACyB,CACzB,KAAM,aACN,QAAS,IACT,QAAS,OAAO,CAAO,EACvB,mBACF,GAEa,EAA4B,CACvC,OAAQ,EACR,MAAO,CACL,uBAAwB,CACtB,CAAE,KAAM,YAAa,KAAM,WAAY,EACvC,CAAE,KAAM,cAAe,KAAM,SAAU,EACvC,CAAE,KAAM,kBAAmB,KAAM,SAAU,EAC3C,CAAE,KAAM,kBAAmB,KAAM,SAAU,EAC3C,CAAE,KAAM,YAAa,KAAM,OAAQ,CACrC,CACF,CACF,EAEa,EAAwB,CACnC,OAAQ,EACR,MAAO,CACL,0BAA2B,CACzB,CAAE,KAAM,YAAa,KAAM,WAAY,EACvC,CAAE,KAAM,kBAAmB,KAAM,OAAQ,EACzC,CAAE,KAAM,YAAa,KAAM,OAAQ,CACrC,CACF,CACF,EAEa,EAAsB,CACjC,OAAQ,EACR,MAAO,CACL,+BAAgC,CAC9B,CAAE,KAAM,YAAa,KAAM,OAAQ,EACnC,CAAE,KAAM,oBAAqB,KAAM,WAAY,EAC/C,CAAE,KAAM,iBAAkB,KAAM,SAAU,EAC1C,CAAE,KAAM,eAAgB,KAAM,SAAU,EACxC,CAAE,KAAM,YAAa,KAAM,OAAQ,CACrC,CACF,CACF,EAEa,EAAgC,CAC3C,OAAQ,EACR,MAAO,CACL,wCAAyC,CACvC,CAAE,KAAM,YAAa,KAAM,OAAQ,EACnC,CAAE,KAAM,oBAAqB,KAAM,WAAY,EAC/C,CAAE,KA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,IAC1C,GAAI,CAAC,EAAQ,GACX,MAAM,IAAI,EACR,mBAAmB,EAAgB,GAAI,sCACzC,CAGN,CAEA,KAAMM,GAAgB,EAAgC,EAAoC,CACxF,OAAO,KAAKP,GAAQ,aAAa,CAC/B,QAAS,KAAKC,GAAQ,mBACtB,IAAK,EACL,aAAc,iBACd,KAAM,CAAC,EAAgB,CAAO,CAChC,CAAC,CACH,CAEA,KAAMG,GAAwB,EAAkD,CAC9E,OAAO,KAAKJ,GAAQ,aAAa,CAC/B,QAAS,KAAKC,GAAQ,mBACtB,IAAK,EACL,aAAc,yBACd,KAAM,CAAC,CAAc,CACvB,CAAC,CACH,CAEA,KAAMI,GAAe,EAAiD,CACpE,OAAO,KAAKL,GAAQ,aAAa,CAC/B,QAAS,KAAKC,GAAQ,gBACtB,IAAK,EACL,aAAc,aACd,KAAM,CAAC,CAAc,CACvB,CAAC,CACH,CACF"}
@@ -1,2 +0,0 @@
1
- import{i as e,r as t,t as n}from"./relayer-D-nicEYJ.js";import{A as r,B as i,F as a,H as o,I as s,O as c,R as l,S as u,T as d,V as f,b as p,l as m,m as h,u as g,v as _,w as v,x as y}from"./wrappers-registry-BWWG0aze.js";import{n as b,t as x}from"./encryption-BGmINekJ.js";import{r as S}from"./error-W1N-FGwV.js";import{t as C}from"./assertions-CnPIS0VN.js";import{getAddress as w}from"viem";var T=class extends t{constructor(t,n){super(e.TransactionReverted,t,n),this.name=`TransactionRevertedError`}},E=class extends t{operation;signerChainId;providerChainId;constructor({operation:t,signerChainId:n,providerChainId:r},i){super(e.ChainMismatch,`Operation "${t}" requires signer and provider to be on the same chain, but signer is on chain ${n} and provider is on chain ${r}.`,i),this.name=`ChainMismatchError`,this.operation=t,this.signerChainId=n,this.providerChainId=r}},D=class extends t{requested;available;token;constructor(t,n,r){super(e.InsufficientConfidentialBalance,t,r),this.name=`InsufficientConfidentialBalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},O=class extends t{requested;available;token;constructor(t,n,r){super(e.InsufficientERC20Balance,t,r),this.name=`InsufficientERC20BalanceError`,this.requested=n.requested,this.available=n.available,this.token=n.token}},k=class extends t{constructor(t,n){super(e.BalanceCheckUnavailable,t,n),this.name=`BalanceCheckUnavailableError`}},A=class extends t{constructor(t,n){super(e.ERC20ReadFailed,t,n),this.name=`ERC20ReadFailedError`}};function j(e){return e instanceof o||e instanceof f||e instanceof n}const M=[{type:`function`,name:`allow`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowForDecryption`,inputs:[{name:`handlesList`,type:`bytes32[]`,internalType:`bytes32[]`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`allowTransient`,inputs:[{name:`ciphertext`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`cleanTransientStorage`,inputs:[],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`delegateForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`expirationDate`,type:`uint64`,internalType:`uint64`}],outputs:[],stateMutability:`nonpayable`},{type:`function`,name:`getUserDecryptionDelegationExpirationDate`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`uint64`,internalType:`uint64`}],stateMutability:`view`},{type:`function`,name:`isAccountDenied`,inputs:[{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isAllowedForDecryption`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`isHandleDelegatedForUserDecryption`,inputs:[{name:`delegator`,type:`address`,internalType:`address`},{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`},{name:`handle`,type:`bytes32`,internalType:`bytes32`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`multicall`,inputs:[{name:`data`,type:`bytes[]`,internalType:`bytes[]`}],outputs:[{name:`results`,type:`bytes[]`,internalType:`bytes[]`}],stateMutability:`payable`},{type:`function`,name:`persistAllowed`,inputs:[{name:`handle`,type:`bytes32`,internalType:`bytes32`},{name:`account`,type:`address`,internalType:`address`}],outputs:[{name:``,type:`bool`,internalType:`bool`}],stateMutability:`view`},{type:`function`,name:`revokeDelegationForUserDecryption`,inputs:[{name:`delegate`,type:`address`,internalType:`address`},{name:`contractAddress`,type:`address`,internalType:`address`}],outputs:[],stateMutability:`nonpayable`}];function N(e,t,n,r){return{address:e,abi:M,functionName:`delegateForUserDecryption`,args:[t,n,r]}}function P(e,t,n){return{address:e,abi:M,functionName:`revokeDelegationForUserDecryption`,args:[t,n]}}function F(e,t,n,r){return{address:e,abi:M,functionName:`getUserDecryptionDelegationExpirationDate`,args:[t,n,r]}}function I(e,t,n,r,i){return{address:e,abi:M,functionName:`isHandleDelegatedForUserDecryption`,args:[t,n,r,i]}}const L=2n**64n-1n;async function R(e,t,n){if(!t)throw new s(e);let r;try{r=t.requireWalletAccount(e)}catch(n){if(!(n instanceof l)||!t.refreshWalletAccount)throw n;await t.refreshWalletAccount(),r=t.requireWalletAccount(e)}let i=await n.getChainId();if(r.chainId!==i)throw new E({operation:e,signerChainId:r.chainId,providerChainId:i});return r}async function z(e,t,n){return(await R(e,t,n)).chainId}const B={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`,UnwrapSubmitted:`unwrap:submitted`,FinalizeUnwrapSubmitted:`finalizeUnwrap:submitted`,DelegationSubmitted:`delegation:submitted`,RevokeDelegationSubmitted:`revokeDelegation:submitted`,UnshieldPhase1Submitted:`unshield:phase1_submitted`,UnshieldPhase2Started:`unshield:phase2_started`,UnshieldPhase2Submitted:`unshield:phase2_submitted`},V={approveUnderlying:{submittedEvent:e=>({type:B.ApproveUnderlyingSubmitted,txHash:e,step:`approve`})},"approveUnderlying:reset":{submittedEvent:e=>({type:B.ApproveUnderlyingSubmitted,txHash:e,step:`reset`})},delegateDecryption:{submittedEvent:e=>({type:B.DelegationSubmitted,txHash:e})},finalizeUnwrap:{submittedEvent:e=>({type:B.FinalizeUnwrapSubmitted,txHash:e})},revokeDelegation:{submittedEvent:e=>({type:B.RevokeDelegationSubmitted,txHash:e})},setOperator:{submittedEvent:e=>({type:B.SetOperatorSubmitted,txHash:e})},"shield:transferAndCall":{submittedEvent:e=>({type:B.ShieldSubmitted,txHash:e,shieldPath:`transferAndCall`})},"shield:approveAndWrap":{submittedEvent:e=>({type:B.ShieldSubmitted,txHash:e,shieldPath:`approveAndWrap`})},transfer:{submittedEvent:e=>({type:B.TransferSubmitted,txHash:e})},transferFrom:{submittedEvent:e=>({type:B.TransferFromSubmitted,txHash:e})},unwrap:{submittedEvent:e=>({type:B.UnwrapSubmitted,txHash:e})},unwrapAll:{submittedEvent:e=>({type:B.UnwrapSubmitted,txHash:e})}};async function H(e,t=1/0){if(Number.isFinite(t)&&t<=0)throw Error(`maxConcurrency must be a positive number`);if(!Number.isFinite(t)||t>=e.length)return Promise.all(e.map(e=>e()));let n=Array.from({length:e.length}),r=0;async function i(){for(;r<e.length;){let t=r++;e[t]&&(n[t]=await e[t]())}}return await Promise.all(Array.from({length:t},i)),n}const U=`0x0000000000000000000000000000000000000000000000000000000000000000`;function W(e){return e===`0x0000000000000000000000000000000000000000000000000000000000000000`||e===`0x`}async function G(e){let{operation:n,signer:r,provider:i,config:o,emit:s,onSubmitted:c,logger:l}=e,u=V[n];try{let e=await r.writeContract(o);return s(u.submittedEvent(e)),a(`${n}: onSubmitted`,()=>c?.(e),l),{txHash:e,receipt:await i.waitForTransactionReceipt(e)}}catch(e){let r=e instanceof t?e:new T(`Transaction failed during ${n}`,{cause:e});throw s({type:B.TransactionError,operation:n,error:r}),r}}var K=class e{sdk;address;constructor(e,t){this.sdk=e,this.address=w(t)}#e(e){return i(this.sdk.signer,e)}async name(){return this.sdk.provider.readContract(p(this.address))}async symbol(){return this.sdk.provider.readContract(y(this.address))}async decimals(){return this.sdk.provider.readContract(_(this.address))}async isConfidential(){return this.sdk.provider.readContract(h(this.address,m))}async isWrapper(){return this.sdk.provider.readContract(h(this.address,g))}async balanceOf(e){let t=w(e),n=await this.readConfidentialBalanceOf(t),r=(await this.sdk.decryption.decryptValues([{encryptedValue:n,contractAddress:this.address}]))[n];if(r===void 0)throw new x(`Decryption returned no value for ${n}`);return C(r,`balanceOf: result[encryptedValue]`),r}async confidentialBalanceOf(e){return this.readConfidentialBalanceOf(w(e))}async decryptBalanceAs({delegatorAddress:e,accountAddress:t}){await z(`decryptBalanceAs`,this.sdk.signer,this.sdk.provider);let n=w(e),r=t?w(t):n,i=await this.readConfidentialBalanceOf(r);if(W(i))return 0n;let a=(await this.sdk.decryption.delegatedDecryptValues([{encryptedValue:i,contractAddress:this.address}],n,r))[i];if(a===void 0)throw new x(`Delegated decryption returned no value for ${i}`);return C(a,`decryptBalanceAs: result[encryptedValue]`),a}static async batchBalancesOf(n,r){let i=new Map,a=new Map;if(n.length===0)return{results:i,errors:a};let o=e.assertSameSdk(n);await z(`batchBalancesOf`,o.signer,o.provider),await o.permits.grantPermit(n.map(e=>e.address));let s=await H(n.map(e=>async()=>{try{return{status:`fulfilled`,value:await e.balanceOf(r)}}catch(e){return{status:`rejected`,reason:e}}}),5);for(let e=0;e<n.length;e++){let r=n[e].address,o=s[e];if(o.status===`fulfilled`)i.set(r,o.value);else{let e=o.reason;if(j(e))throw e;let n=e instanceof t?e:new x(S(e).message,{cause:e});a.set(r,n)}}if(a.size===n.length)throw a.values().next().value??new x(`All token balance decryptions failed`);return{results:i,errors:a}}static async batchDecryptBalancesAs(t,n){if(t.length===0)return new Map;let r=e.assertSameSdk(t),i=new Map,a=new Map,o=n.accountAddress?w(n.accountAddress):w(n.delegatorAddress),s=n.maxConcurrency??10;if(n.encryptedValues&&t.length!==n.encryptedValues.length)throw new x(`tokens.length (${t.length}) must equal encryptedValues.length (${n.encryptedValues.length})`);let c=n.encryptedValues??await e.readBalanceHandlesBatch(t,o,a,s),l=[];for(let[e,n]of t.entries()){let t=c[e];!t||a.has(n.address)||(W(t)?i.set(n.address,0n):l.push({token:n,encryptedValue:t}))}if(l.length>0){let e=await r.decryption.delegatedBatchDecryptValues({encryptedInputs:l.map(({token:e,encryptedValue:t})=>({encryptedValue:t,contractAddress:e.address})),delegatorAddress:n.delegatorAddress,accountAddress:n.accountAddress,maxConcurrency:s});for(let[t,n]of e.items.entries()){let e=l[t];if(!e)continue;if(n.error){a.set(e.token.address,n.error);continue}let r=n.value;if(r===void 0){a.set(e.token.address,new x(`Batch delegated decryption returned no value for ${n.encryptedValue} on token ${e.token.address}`));continue}C(r,`batchDecryptBalancesAs: result[encryptedValue]`),i.set(e.token.address,r)}}if(a.size===0)return i;if(n.onError){let e=[];for(let[t,r]of a)try{i.set(t,n.onError(r,t))}catch(n){e.push({address:t,error:S(n)})}if(e.length>0){let t=e.map(({address:e,error:t})=>`${e}: ${t.message}`).join(`; `);throw new x(`Batch delegated decryption onError callback failed for ${e.length} token(s): ${t}`,{cause:e[0]?.error})}return i}let u=Array.from(a.entries()),d=u.map(([e,t])=>`${e}: ${t.message}`).join(`; `);throw new x(`Batch delegated decryption failed for ${a.size} token(s): ${d}`,{cause:u[0]?.[1]})}static async readBalanceHandlesBatch(e,n,r,i){let a=await H(e.map(e=>async()=>{try{return{status:`fulfilled`,value:await e.readConfidentialBalanceOf(n)}}catch(e){return{status:`rejected`,reason:e}}}),i),o=[];for(let[n,i]of e.entries()){let e=a[n];if(e){if(e.status===`fulfilled`){o[n]=e.value;continue}if(j(e.reason))throw e.reason;r.set(i.address,e.reason instanceof t?e.reason:new x(S(e.reason).message,{cause:e.reason}))}}return o}async confidentialTransfer(e,t,n){this.#e(`confidentialTransfer`);let r=await R(`confidentialTransfer`,this.sdk.signer,this.sdk.provider),{skipBalanceCheck:i=!1,onEncryptComplete:o,onTransferSubmitted:s}=n??{},c=w(e);i||await this.assertConfidentialBalance(t);let{encryptedValues:l,inputProof:u}=await this.sdk.encrypt({values:[{value:t,type:`euint64`}],contractAddress:this.address,userAddress:w(r.address)});if(a(`transfer: onEncryptComplete`,()=>o?.(),this.sdk.logger),l.length===0)throw new b(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transfer`,config:v(this.address,c,l[0],u),onSubmitted:s})}async confidentialTransferFrom(e,t,n,r){this.#e(`confidentialTransferFrom`),await R(`confidentialTransferFrom`,this.sdk.signer,this.sdk.provider);let i=w(e),o=w(t),{encryptedValues:s,inputProof:c}=await this.sdk.encrypt({values:[{value:n,type:`euint64`}],contractAddress:this.address,userAddress:i});if(a(`transferFrom: onEncryptComplete`,()=>r?.onEncryptComplete?.(),this.sdk.logger),s.length===0)throw new b(`Encryption returned no encrypted values`);return this.submitTransaction({operation:`transferFrom`,config:d(this.address,i,o,s[0],c),onSubmitted:r?.onTransferSubmitted})}async setOperator(e,t){this.#e(`setOperator`),await z(`setOperator`,this.sdk.signer,this.sdk.provider);let n=w(e);return this.submitTransaction({operation:`setOperator`,config:r(this.address,n,t)})}async isOperator(e,t){return this.sdk.provider.readContract(c(this.address,w(e),w(t)))}async readConfidentialBalanceOf(e){return await this.sdk.provider.readContract(u(this.address,e))}async assertConfidentialBalance(e){if(e===0n)return;let n;try{let e=await R(`assertConfidentialBalance`,this.sdk.signer,this.sdk.provider);n=await this.balanceOf(w(e.address))}catch(e){throw e instanceof t?e:new k(`Balance validation failed (token: ${this.address})`,{cause:e})}if(n<e)throw new D(`Insufficient confidential balance: requested ${e}, available ${n} (token: ${this.address})`,{requested:e,available:n,token:this.address})}emit(e){this.sdk.emitEvent(e,this.address)}async submitTransaction(e){let{operation:t,config:n,onSubmitted:r}=e;return G({operation:t,signer:this.#e(t),provider:this.sdk.provider,config:n,emit:e=>this.emit(e),onSubmitted:r,logger:this.sdk.logger})}static assertSameSdk(e){let t=e[0].sdk;for(let r=1;r<e.length;r++)if(e[r].sdk!==t)throw new n(`All tokens in a batch operation must share the same ZamaSDK instance`);return t}};export{D as _,H as a,T as b,z as c,F as d,I as f,A as g,k as h,W as i,L as l,j as m,G as n,B as o,P as p,U as r,R as s,K as t,N as u,O as v,E as y};
2
- //# sourceMappingURL=token-TQ-VFHS4.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"token-TQ-VFHS4.js","names":["#requireSigner","submitSdkTransaction"],"sources":["../../src/errors/transaction.ts","../../src/errors/chain.ts","../../src/errors/balance.ts","../../src/errors/fatal-batch.ts","../../src/abi/acl.abi.ts","../../src/contracts/acl.ts","../../src/contracts/constants.ts","../../src/utils/alignment.ts","../../src/events/sdk-events.ts","../../src/utils/concurrency.ts","../../src/utils/handles.ts","../../src/utils/submit-transaction.ts","../../src/token/token.ts"],"sourcesContent":["import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** On-chain transaction reverted. */\nexport class TransactionRevertedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.TransactionReverted, message, options);\n this.name = \"TransactionRevertedError\";\n }\n}\n","import { ZamaError, ZamaErrorCode } from \"./base\";\n\n/**\n * Thrown when the signer and provider are connected to different chains at the\n * start of a write operation.\n *\n * Every write method runs a chain-alignment pre-flight check. If\n * `signer.getChainId()` and `provider.getChainId()` return different values,\n * this error is thrown before any RPC mutation is attempted.\n *\n * @example\n * ```ts\n * try {\n * await token.shield(1000n);\n * } catch (e) {\n * if (e instanceof ChainMismatchError) {\n * console.error(\n * `Signer is on chain ${e.signerChainId} but provider is on chain ${e.providerChainId}`,\n * );\n * }\n * }\n * ```\n */\nexport class ChainMismatchError extends ZamaError {\n readonly operation: string;\n readonly signerChainId: number;\n readonly providerChainId: number;\n\n constructor(\n {\n operation,\n signerChainId,\n providerChainId,\n }: { operation: string; signerChainId: number; providerChainId: number },\n options?: ErrorOptions,\n ) {\n super(\n ZamaErrorCode.ChainMismatch,\n `Operation \"${operation}\" requires signer and provider to be on the same chain, ` +\n `but signer is on chain ${signerChainId} and provider is on chain ${providerChainId}.`,\n options,\n );\n this.name = \"ChainMismatchError\";\n this.operation = operation;\n this.signerChainId = signerChainId;\n this.providerChainId = providerChainId;\n }\n}\n","import type { Address } from \"viem\";\nimport { ZamaError, ZamaErrorCode } from \"./base\";\n\n/** Structured details shared by balance-related errors. */\nexport interface BalanceErrorDetails {\n readonly requested: bigint;\n readonly available: bigint;\n readonly token: Address;\n}\n\n/** Confidential (cToken) balance is insufficient for the requested operation. */\nexport class InsufficientConfidentialBalanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The available balance at the time of the check. */\n readonly available: bigint;\n /** The token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientConfidentialBalance, message, options);\n this.name = \"InsufficientConfidentialBalanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** ERC-20 balance is insufficient for the requested shield amount. */\nexport class InsufficientERC20BalanceError extends ZamaError {\n /** The amount the caller requested. */\n readonly requested: bigint;\n /** The available balance at the time of the check. */\n readonly available: bigint;\n /** The ERC-20 token contract address. */\n readonly token: Address;\n\n constructor(message: string, details: BalanceErrorDetails, options?: ErrorOptions) {\n super(ZamaErrorCode.InsufficientERC20Balance, message, options);\n this.name = \"InsufficientERC20BalanceError\";\n this.requested = details.requested;\n this.available = details.available;\n this.token = details.token;\n }\n}\n\n/** Balance validation could not be performed (no cached credentials and decryption not possible). */\nexport class BalanceCheckUnavailableError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.BalanceCheckUnavailable, message, options);\n this.name = \"BalanceCheckUnavailableError\";\n }\n}\n\n/** A public ERC-20 read (e.g. balanceOf) failed due to a network or contract error. */\nexport class ERC20ReadFailedError extends ZamaError {\n constructor(message: string, options?: ErrorOptions) {\n super(ZamaErrorCode.ERC20ReadFailed, message, options);\n this.name = \"ERC20ReadFailedError\";\n }\n}\n","import { ConfigurationError } from \"./relayer\";\nimport { SigningRejectedError, SigningFailedError } from \"./signing\";\n\n/**\n * Returns `true` for errors that should abort an entire batch operation\n * rather than be recorded per-item — wallet signature rejected, signing\n * infrastructure broken, or SDK misconfigured. These are systemic failures\n * that won't recover within the same call.\n *\n * Callers iterating over a batch (e.g. per-token decrypt) should rethrow when\n * this predicate is true so the whole batch aborts, and record the error\n * per-item otherwise.\n */\nexport function isFatalBatchError(error: unknown): boolean {\n return (\n error instanceof SigningRejectedError ||\n error instanceof SigningFailedError ||\n error instanceof ConfigurationError\n );\n}\n","// DO NOT EDIT: generated by `pnpm abi:build` from\n// contracts/out/Impl.sol/IACL.json.\n// Regenerate after `pnpm contracts:build`; `pnpm abi:check` enforces this in CI.\nexport const aclAbi = [\n {\n type: \"function\",\n name: \"allow\",\n inputs: [\n {\n name: \"handle\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"account\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"allowForDecryption\",\n inputs: [\n {\n name: \"handlesList\",\n type: \"bytes32[]\",\n internalType: \"bytes32[]\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"allowTransient\",\n inputs: [\n {\n name: \"ciphertext\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"account\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"cleanTransientStorage\",\n inputs: [],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"delegateForUserDecryption\",\n inputs: [\n {\n name: \"delegate\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"contractAddress\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"expirationDate\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n {\n type: \"function\",\n name: \"getUserDecryptionDelegationExpirationDate\",\n inputs: [\n {\n name: \"delegator\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"delegate\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"contractAddress\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"uint64\",\n internalType: \"uint64\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAccountDenied\",\n inputs: [\n {\n name: \"account\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bool\",\n internalType: \"bool\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAllowed\",\n inputs: [\n {\n name: \"handle\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"account\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bool\",\n internalType: \"bool\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isAllowedForDecryption\",\n inputs: [\n {\n name: \"handle\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bool\",\n internalType: \"bool\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"isHandleDelegatedForUserDecryption\",\n inputs: [\n {\n name: \"delegator\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"delegate\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"contractAddress\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"handle\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bool\",\n internalType: \"bool\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"multicall\",\n inputs: [\n {\n name: \"data\",\n type: \"bytes[]\",\n internalType: \"bytes[]\",\n },\n ],\n outputs: [\n {\n name: \"results\",\n type: \"bytes[]\",\n internalType: \"bytes[]\",\n },\n ],\n stateMutability: \"payable\",\n },\n {\n type: \"function\",\n name: \"persistAllowed\",\n inputs: [\n {\n name: \"handle\",\n type: \"bytes32\",\n internalType: \"bytes32\",\n },\n {\n name: \"account\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [\n {\n name: \"\",\n type: \"bool\",\n internalType: \"bool\",\n },\n ],\n stateMutability: \"view\",\n },\n {\n type: \"function\",\n name: \"revokeDelegationForUserDecryption\",\n inputs: [\n {\n name: \"delegate\",\n type: \"address\",\n internalType: \"address\",\n },\n {\n name: \"contractAddress\",\n type: \"address\",\n internalType: \"address\",\n },\n ],\n outputs: [],\n stateMutability: \"nonpayable\",\n },\n] as const;\n","import type { Address } from \"viem\";\nimport { aclAbi } from \"../abi/acl.abi\";\n\n/**\n * Returns the contract config to delegate user decryption rights.\n *\n * @example\n * ```ts\n * const txHash = await signer.writeContract(\n * delegateForUserDecryptionContract(aclAddress, delegateAddress, contractAddress, expirationDate),\n * );\n * ```\n */\nexport function delegateForUserDecryptionContract(\n aclAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n expirationDate: bigint,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"delegateForUserDecryption\",\n args: [delegateAddress, contractAddress, expirationDate],\n } as const;\n}\n\n/**\n * Returns the contract config to revoke a user decryption delegation.\n *\n * @example\n * ```ts\n * const txHash = await signer.writeContract(\n * revokeDelegationContract(aclAddress, delegateAddress, contractAddress),\n * );\n * ```\n */\nexport function revokeDelegationContract(\n aclAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"revokeDelegationForUserDecryption\",\n args: [delegateAddress, contractAddress],\n } as const;\n}\n\n/**\n * Returns the contract config to read the delegation expiry date.\n *\n * @example\n * ```ts\n * const expiry = await provider.readContract(\n * getDelegationExpiryContract(aclAddress, delegatorAddress, delegateAddress, contractAddress),\n * );\n * ```\n */\nexport function getDelegationExpiryContract(\n aclAddress: Address,\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"getUserDecryptionDelegationExpirationDate\",\n args: [delegatorAddress, delegateAddress, contractAddress],\n } as const;\n}\n\n/**\n * Returns the contract config to check if a specific handle is delegated.\n *\n * @example\n * ```ts\n * const isDelegated = await provider.readContract(\n * isHandleDelegatedContract(aclAddress, delegatorAddress, delegateAddress, contractAddress, handle),\n * );\n * ```\n */\nexport function isHandleDelegatedContract(\n aclAddress: Address,\n delegatorAddress: Address,\n delegateAddress: Address,\n contractAddress: Address,\n handle: `0x${string}`,\n) {\n return {\n address: aclAddress,\n abi: aclAbi,\n functionName: \"isHandleDelegatedForUserDecryption\",\n args: [delegatorAddress, delegateAddress, contractAddress, handle],\n } as const;\n}\n","/** uint64 max — represents a permanent (no-expiry) delegation. */\nexport const MAX_UINT64 = 2n ** 64n - 1n;\n","import {\n ChainMismatchError,\n SignerNotConfiguredError,\n WalletAccountNotReadyError,\n} from \"../errors\";\nimport type { GenericProvider, GenericSigner, WalletAccount } from \"../types\";\n\n/**\n * Pre-flight guard for signer-required operations. Resolves the connected\n * wallet account (refreshing once if the signer reports it isn't ready) and\n * verifies the signer's chain matches the provider's.\n *\n * @internal\n */\nexport async function requireAlignedWalletAccount(\n operation: string,\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n): Promise<WalletAccount> {\n if (!signer) {\n throw new SignerNotConfiguredError(operation);\n }\n let account: WalletAccount;\n try {\n account = signer.requireWalletAccount(operation);\n } catch (error) {\n if (!(error instanceof WalletAccountNotReadyError) || !signer.refreshWalletAccount) {\n throw error;\n }\n await signer.refreshWalletAccount();\n account = signer.requireWalletAccount(operation);\n }\n const providerChainId = await provider.getChainId();\n if (account.chainId !== providerChainId) {\n throw new ChainMismatchError({\n operation,\n signerChainId: account.chainId,\n providerChainId,\n });\n }\n return account;\n}\n\n/**\n * Variant of {@link requireAlignedWalletAccount} that returns only the aligned\n * chain ID. Useful when a write path only needs to ensure signer/provider\n * coherence and doesn't otherwise consume the account.\n *\n * @internal\n */\nexport async function requireChainAlignment(\n operation: string,\n signer: GenericSigner | undefined,\n provider: GenericProvider,\n): Promise<number> {\n return (await requireAlignedWalletAccount(operation, signer, provider)).chainId;\n}\n","import type { Address, Hex } from \"viem\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/relayer-sdk.types\";\nimport type { ShieldPath } from \"../types/token\";\n\n/**\n * All SDK event keys, accessible as `ZamaSDKEvents.EncryptStart` etc.\n */\nexport const ZamaSDKEvents = {\n // FHE operations\n EncryptStart: \"encrypt:start\",\n EncryptEnd: \"encrypt:end\",\n EncryptError: \"encrypt:error\",\n DecryptStart: \"decrypt:start\",\n DecryptEnd: \"decrypt:end\",\n DecryptError: \"decrypt:error\",\n // Write operations\n TransactionError: \"transaction:error\",\n ShieldSubmitted: \"shield:submitted\",\n TransferSubmitted: \"transfer:submitted\",\n TransferFromSubmitted: \"transferFrom:submitted\",\n SetOperatorSubmitted: \"setOperator:submitted\",\n ApproveUnderlyingSubmitted: \"approveUnderlying:submitted\",\n UnwrapSubmitted: \"unwrap:submitted\",\n FinalizeUnwrapSubmitted: \"finalizeUnwrap:submitted\",\n // Delegation operations\n DelegationSubmitted: \"delegation:submitted\",\n RevokeDelegationSubmitted: \"revokeDelegation:submitted\",\n // Unshield orchestration\n UnshieldPhase1Submitted: \"unshield:phase1_submitted\",\n UnshieldPhase2Started: \"unshield:phase2_started\",\n UnshieldPhase2Submitted: \"unshield:phase2_submitted\",\n} as const;\n\n/** Union of all SDK event type strings. */\nexport type ZamaSDKEventType = (typeof ZamaSDKEvents)[keyof typeof ZamaSDKEvents];\n\n// -- Base fields present on every event --\n\nexport interface BaseEvent {\n tokenAddress?: Address;\n timestamp: number;\n /** Shared identifier linking related events in multi-phase operations (e.g. unshield). */\n operationId?: string;\n}\n\n// -- Per-event typed payloads --\n\nexport interface EncryptStartEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.EncryptStart;\n}\n\nexport interface EncryptEndEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.EncryptEnd;\n durationMs: number;\n}\n\nexport interface EncryptErrorEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.EncryptError;\n /** The error that caused the encryption to fail. */\n error: Error;\n durationMs: number;\n}\n\nexport interface DecryptStartEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.DecryptStart;\n /** Encrypted values being decrypted — correlate with matching DecryptEnd/DecryptError. */\n encryptedValues: EncryptedValue[];\n}\n\nexport interface DecryptEndEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.DecryptEnd;\n durationMs: number;\n /** Encrypted values that were decrypted. */\n encryptedValues: EncryptedValue[];\n /** Decrypted values keyed by encrypted value — use this to correlate events to specific entries. */\n result: Record<EncryptedValue, ClearValue>;\n}\n\nexport interface DecryptErrorEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.DecryptError;\n /** The error that caused the decryption to fail. */\n error: Error;\n durationMs: number;\n /** Encrypted values that were being decrypted when the error occurred. */\n encryptedValues: EncryptedValue[];\n}\n\nexport interface TransactionErrorEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.TransactionError;\n /** Which SDK operation failed. */\n operation: TransactionOperation;\n /** The error that caused the transaction to fail. */\n error: Error;\n}\n\nexport interface ShieldSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.ShieldSubmitted;\n txHash: Hex;\n /** Which execution path was used: single-tx `transferAndCall` or two-tx `approveAndWrap`. */\n shieldPath: ShieldPath;\n}\n\nexport interface TransferSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.TransferSubmitted;\n txHash: Hex;\n}\n\nexport interface TransferFromSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.TransferFromSubmitted;\n txHash: Hex;\n}\n\nexport interface SetOperatorSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.SetOperatorSubmitted;\n txHash: Hex;\n}\n\nexport interface ApproveUnderlyingSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.ApproveUnderlyingSubmitted;\n txHash: Hex;\n /** Which approval transaction was submitted. */\n step: \"reset\" | \"approve\";\n}\n\nexport interface UnwrapSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.UnwrapSubmitted;\n txHash: Hex;\n}\n\nexport interface FinalizeUnwrapSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.FinalizeUnwrapSubmitted;\n txHash: Hex;\n}\n\nexport interface DelegationSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.DelegationSubmitted;\n txHash: Hex;\n}\n\nexport interface RevokeDelegationSubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.RevokeDelegationSubmitted;\n txHash: Hex;\n}\n\nexport interface UnshieldPhase1SubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.UnshieldPhase1Submitted;\n txHash: Hex;\n}\n\nexport interface UnshieldPhase2StartedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.UnshieldPhase2Started;\n}\n\nexport interface UnshieldPhase2SubmittedEvent extends BaseEvent {\n type: typeof ZamaSDKEvents.UnshieldPhase2Submitted;\n txHash: Hex;\n}\n\n/**\n * Discriminated union of all SDK events.\n *\n * Decrypt events carry encrypted values and decrypted clear-text values so event\n * subscribers can correlate and bind them in UI layers. Events never carry\n * private keys, permit signatures, or ZK proofs.\n */\nexport type ZamaSDKEvent =\n | EncryptStartEvent\n | EncryptEndEvent\n | EncryptErrorEvent\n | DecryptStartEvent\n | DecryptEndEvent\n | DecryptErrorEvent\n | TransactionErrorEvent\n | ShieldSubmittedEvent\n | TransferSubmittedEvent\n | TransferFromSubmittedEvent\n | SetOperatorSubmittedEvent\n | ApproveUnderlyingSubmittedEvent\n | UnwrapSubmittedEvent\n | FinalizeUnwrapSubmittedEvent\n | DelegationSubmittedEvent\n | RevokeDelegationSubmittedEvent\n | UnshieldPhase1SubmittedEvent\n | UnshieldPhase2StartedEvent\n | UnshieldPhase2SubmittedEvent;\n\nexport type ZamaSDKEventListener = (event: ZamaSDKEvent) => void;\n\n/** Distributive Omit that preserves the discriminated union. */\nexport type ZamaSDKEventInput = ZamaSDKEvent extends infer E\n ? E extends ZamaSDKEvent\n ? Omit<E, \"timestamp\" | \"tokenAddress\">\n : never\n : never;\n\n/**\n * Single source of truth for each transaction operation's submitted-event payload.\n *\n * Adding a write op = adding one entry here. `TransactionOperation` is then\n * `keyof typeof transactionOperationMetadata`, so the dispatch table and the\n * operation union cannot drift.\n *\n * The `satisfies` check enforces that every entry produces a valid\n * {@link ZamaSDKEventInput}.\n */\nexport const transactionOperationMetadata = {\n approveUnderlying: {\n submittedEvent: (txHash: Hex) => ({\n type: ZamaSDKEvents.ApproveUnderlyingSubmitted,\n txHash,\n step: \"approve\" as const,\n }),\n },\n \"approveUnderlying:reset\": {\n submittedEvent: (txHash: Hex) => ({\n type: ZamaSDKEvents.ApproveUnderlyingSubmitted,\n txHash,\n step: \"reset\" as const,\n }),\n },\n delegateDecryption: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.DelegationSubmitted, txHash }),\n },\n finalizeUnwrap: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.FinalizeUnwrapSubmitted, txHash }),\n },\n revokeDelegation: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.RevokeDelegationSubmitted, txHash }),\n },\n setOperator: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.SetOperatorSubmitted, txHash }),\n },\n \"shield:transferAndCall\": {\n submittedEvent: (txHash: Hex) => ({\n type: ZamaSDKEvents.ShieldSubmitted,\n txHash,\n shieldPath: \"transferAndCall\" as const,\n }),\n },\n \"shield:approveAndWrap\": {\n submittedEvent: (txHash: Hex) => ({\n type: ZamaSDKEvents.ShieldSubmitted,\n txHash,\n shieldPath: \"approveAndWrap\" as const,\n }),\n },\n transfer: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.TransferSubmitted, txHash }),\n },\n transferFrom: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.TransferFromSubmitted, txHash }),\n },\n unwrap: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.UnwrapSubmitted, txHash }),\n },\n unwrapAll: {\n submittedEvent: (txHash: Hex) => ({ type: ZamaSDKEvents.UnwrapSubmitted, txHash }),\n },\n} satisfies Record<string, { submittedEvent: (txHash: Hex) => ZamaSDKEventInput }>;\n\n/**\n * SDK transaction operations that emit submitted/error lifecycle events.\n *\n * Operation strings encode the execution-path discriminator for flows that have\n * one (`shield:transferAndCall` vs. `shield:approveAndWrap`), routing both error\n * and success events on a single field — see {@link transactionOperationMetadata}.\n */\nexport type TransactionOperation = keyof typeof transactionOperationMetadata;\n","/**\n * Execute an array of async thunks with bounded concurrency.\n * Defaults to `Infinity` (equivalent to `Promise.all`).\n */\nexport async function pLimit<T>(\n fns: (() => Promise<T>)[],\n maxConcurrency = Infinity,\n): Promise<T[]> {\n if (Number.isFinite(maxConcurrency) && maxConcurrency <= 0) {\n throw new Error(\"maxConcurrency must be a positive number\");\n }\n if (!Number.isFinite(maxConcurrency) || maxConcurrency >= fns.length) {\n return Promise.all(fns.map((f) => f()));\n }\n\n const results: T[] = Array.from({ length: fns.length });\n let index = 0;\n\n async function worker() {\n while (index < fns.length) {\n const i = index++;\n if (fns[i]) {\n results[i] = await fns[i]();\n }\n }\n }\n\n await Promise.all(Array.from({ length: maxConcurrency }, worker));\n return results;\n}\n","export const ZERO_ENCRYPTED_VALUE =\n \"0x0000000000000000000000000000000000000000000000000000000000000000\" as const;\n\n/**\n * Check whether an encrypted value represents the zero value.\n */\nexport function isEncryptedValueZero(encryptedValue: string): boolean {\n return encryptedValue === ZERO_ENCRYPTED_VALUE || encryptedValue === \"0x\";\n}\n","import type { Hex } from \"viem\";\nimport { TransactionRevertedError, ZamaError } from \"../errors\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport { transactionOperationMetadata, ZamaSDKEvents } from \"../events/sdk-events\";\nimport type {\n GenericProvider,\n GenericSigner,\n TransactionResult,\n WriteContractConfig,\n} from \"../types\";\nimport type { GenericLogger } from \"../worker/worker.types\";\nimport { swallow } from \"./swallow\";\n\n/**\n * Shared write-transaction pipeline for SDK calls that submit a transaction.\n *\n * On success: writes the tx, emits the per-operation submitted event from\n * {@link transactionOperationMetadata}, fires `onSubmitted`, waits for the\n * receipt, and returns `{ txHash, receipt }`.\n *\n * On failure: emits a {@link ZamaSDKEvents.TransactionError} event with the\n * transaction-level error it will throw, then throws it. Existing `ZamaError`\n * instances are rethrown as-is; all other failures are wrapped in\n * `TransactionRevertedError` with the original error as `cause`.\n */\nexport async function submitTransaction(params: {\n operation: TransactionOperation;\n signer: GenericSigner;\n provider: GenericProvider;\n config: WriteContractConfig;\n emit: (input: ZamaSDKEventInput) => void;\n onSubmitted?: (txHash: Hex) => void;\n logger: GenericLogger;\n}): Promise<TransactionResult> {\n const { operation, signer, provider, config, emit, onSubmitted, logger } = params;\n const metadata = transactionOperationMetadata[operation];\n\n try {\n const txHash = await signer.writeContract(config);\n emit(metadata.submittedEvent(txHash));\n void swallow(`${operation}: onSubmitted`, () => onSubmitted?.(txHash), logger);\n const receipt = await provider.waitForTransactionReceipt(txHash);\n return { txHash, receipt };\n } catch (error) {\n const failure =\n error instanceof ZamaError\n ? error\n : new TransactionRevertedError(`Transaction failed during ${operation}`, {\n cause: error,\n });\n\n emit({\n type: ZamaSDKEvents.TransactionError,\n operation,\n error: failure,\n });\n throw failure;\n }\n}\n","import { type Address, getAddress, type Hex } from \"viem\";\nimport {\n confidentialBalanceOfContract,\n confidentialTransferContract,\n confidentialTransferFromContract,\n decimalsContract,\n ERC7984_INTERFACE_ID,\n ERC7984_WRAPPER_INTERFACE_ID,\n isOperatorContract,\n nameContract,\n setOperatorContract,\n supportsInterfaceContract,\n symbolContract,\n} from \"../contracts\";\nimport {\n BalanceCheckUnavailableError,\n ConfigurationError,\n DecryptionFailedError,\n EncryptionFailedError,\n InsufficientConfidentialBalanceError,\n isFatalBatchError,\n requireConfigured,\n ZamaError,\n} from \"../errors\";\nimport type { TransactionOperation, ZamaSDKEventInput } from \"../events/sdk-events\";\nimport type { ClearValue, EncryptedValue } from \"../relayer/relayer-sdk.types\";\nimport { toError } from \"../utils\";\nimport { requireAlignedWalletAccount, requireChainAlignment } from \"../utils/alignment\";\nimport { assertBigint } from \"../utils/assertions\";\nimport { pLimit } from \"../utils/concurrency\";\nimport { isEncryptedValueZero } from \"../utils/handles\";\nimport { submitTransaction as submitSdkTransaction } from \"../utils/submit-transaction\";\nimport { swallow } from \"../utils/swallow\";\nimport type {\n GenericSigner,\n TransactionResult,\n TransferCallbacks,\n TransferOptions,\n WriteContractConfig,\n} from \"../types\";\nimport type { ZamaSDK } from \"../zama-sdk\";\n\n/** Options for {@link Token.batchDecryptBalancesAs}. */\nexport interface BatchDecryptAsOptions {\n /** The address of the account that delegated decryption rights. */\n delegatorAddress: Address;\n /** Pre-fetched encrypted values. When omitted, they are fetched from the chain. */\n encryptedValues?: EncryptedValue[];\n /**\n * The account whose on-chain balance to read. Defaults to the delegator\n * address, which is the common case (the delegator grants permission to\n * decrypt their own balance). Only set this when the account differs\n * from the delegator.\n *\n * Matches the `account` parameter of `confidentialBalanceOf(account)` on-chain.\n */\n accountAddress?: Address;\n /** Maximum number of concurrent decrypt calls. Default: 10. */\n maxConcurrency?: number;\n /** Called when decryption fails for a single token. Return a fallback bigint. */\n onError?: (error: Error, address: Address) => bigint;\n}\n\n/** Result of {@link Token.batchBalancesOf}. */\nexport interface BatchBalancesResult {\n /** Successfully decrypted balances, keyed by token address. */\n results: Map<Address, bigint>;\n /** Per-token errors for tokens that failed to decrypt. */\n errors: Map<Address, ZamaError>;\n}\n\n/**\n * High-level interface for an ERC-7984 confidential token.\n * Hides FHE complexity (encryption, decryption, EIP-712 signing) behind\n * familiar ERC-20-like methods.\n *\n * For ERC-7984 wrappers (shield/unshield), use {@link WrappedToken} instead —\n * it extends `Token` with wrapper-specific operations.\n *\n * Decryption, credentials, caching, and event emission are handled by the\n * owning {@link ZamaSDK} — this class only exposes token-scoped helpers\n * that delegate to `sdk.decryption.decryptValues` and `sdk.permits.grantPermit`.\n */\nexport class Token {\n readonly sdk: ZamaSDK;\n readonly address: Address;\n\n constructor(sdk: ZamaSDK, address: Address) {\n this.sdk = sdk;\n this.address = getAddress(address);\n }\n\n /** Resolve `sdk.signer` or throw {@link SignerNotConfiguredError} tagged with `operation`. */\n #requireSigner(operation: string): GenericSigner {\n return requireConfigured(this.sdk.signer, operation);\n }\n\n // METADATA\n\n /** Read the token name from the contract. */\n async name(): Promise<string> {\n return this.sdk.provider.readContract(nameContract(this.address));\n }\n\n /** Read the token symbol from the contract. */\n async symbol(): Promise<string> {\n return this.sdk.provider.readContract(symbolContract(this.address));\n }\n\n /** Read the token decimals from the contract. */\n async decimals(): Promise<number> {\n return this.sdk.provider.readContract(decimalsContract(this.address));\n }\n\n // ERC-165 DISCOVERY\n\n /**\n * ERC-165 check for {@link ERC7984_INTERFACE_ID} support.\n *\n * @returns `true` if the contract implements the ERC-7984 confidential token interface.\n */\n async isConfidential(): Promise<boolean> {\n return this.sdk.provider.readContract(\n supportsInterfaceContract(this.address, ERC7984_INTERFACE_ID),\n );\n }\n\n /**\n * ERC-165 check for IERC7984ERC20Wrapper support.\n *\n * @returns `true` if the contract implements the ERC-7984 wrapper interface\n * ({@link ERC7984_WRAPPER_INTERFACE_ID}, `0x1f1c62b2`).\n */\n async isWrapper(): Promise<boolean> {\n return this.sdk.provider.readContract(\n supportsInterfaceContract(this.address, ERC7984_WRAPPER_INTERFACE_ID),\n );\n }\n\n // BALANCES\n\n /**\n * Decrypt and return the plaintext balance for the given owner.\n * Acquires FHE credentials via a wallet signature if none are cached.\n *\n * @param owner - Balance owner address.\n * @returns The decrypted plaintext balance as a bigint.\n * @throws if FHE decryption fails. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balance = await token.balanceOf(\"0xOwner\");\n * ```\n */\n async balanceOf(owner: Address): Promise<bigint> {\n const ownerAddress = getAddress(owner);\n const encryptedValue = await this.readConfidentialBalanceOf(ownerAddress);\n const result = await this.sdk.decryption.decryptValues([\n { encryptedValue, contractAddress: this.address },\n ]);\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(`Decryption returned no value for ${encryptedValue}`);\n }\n assertBigint(value, \"balanceOf: result[encryptedValue]\");\n return value;\n }\n\n /**\n * Return the raw encrypted balance without decrypting.\n *\n * @param owner - Balance owner address.\n * @returns The encrypted balance as a hex string.\n *\n * @example\n * ```ts\n * const encryptedValue = await token.confidentialBalanceOf(\"0xOwner\");\n * ```\n */\n async confidentialBalanceOf(owner: Address): Promise<EncryptedValue> {\n return this.readConfidentialBalanceOf(getAddress(owner));\n }\n\n /**\n * Decrypt the balance of a delegator using delegated decryption credentials.\n * The connected signer acts as the delegatee who has been granted permission\n * by the delegator to decrypt their balance.\n *\n * Clear values are cached in storage keyed by `(account, token, encryptedValue)`.\n * Because every on-chain balance change produces a new encrypted value,\n * stale cache entries are never served. Cache write failures are silently\n * ignored — they do not affect the returned value.\n *\n * @param delegatorAddress - The address of the account that delegated decryption rights.\n * @param accountAddress - The account whose on-chain balance to read. Defaults\n * to the delegator address.\n * @returns The decrypted plaintext balance as a bigint.\n * @throws if no active delegation exists. {@link DelegationNotFoundError}\n * @throws if the delegation has expired. {@link DelegationExpiredError}\n * @throws if delegated decryption fails. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balance = await token.decryptBalanceAs({\n * delegatorAddress: \"0xDelegator\",\n * });\n * ```\n */\n async decryptBalanceAs({\n delegatorAddress,\n accountAddress,\n }: {\n delegatorAddress: Address;\n accountAddress?: Address;\n }): Promise<bigint> {\n await requireChainAlignment(\"decryptBalanceAs\", this.sdk.signer, this.sdk.provider);\n const normalizedDelegator = getAddress(delegatorAddress);\n const normalizedAccount = accountAddress ? getAddress(accountAddress) : normalizedDelegator;\n\n const encryptedValue = await this.readConfidentialBalanceOf(normalizedAccount);\n if (isEncryptedValueZero(encryptedValue)) {\n return 0n;\n }\n\n const result = await this.sdk.decryption.delegatedDecryptValues(\n [{ encryptedValue, contractAddress: this.address }],\n normalizedDelegator,\n normalizedAccount,\n );\n\n const value = result[encryptedValue];\n if (value === undefined) {\n throw new DecryptionFailedError(\n `Delegated decryption returned no value for ${encryptedValue}`,\n );\n }\n assertBigint(value, \"decryptBalanceAs: result[encryptedValue]\");\n return value;\n }\n\n // BATCH STATICS\n\n /**\n * Decrypt confidential balances for multiple tokens in parallel, returning\n * successes and per-token errors separately. Pre-authorizes all token\n * addresses in a single wallet signature, then delegates each decrypt to\n * `sdk.decryption.decryptValues`.\n *\n * Tokens that fail to decrypt land in `errors` rather than aborting the\n * whole batch — caller decides how to surface them.\n *\n * @param tokens - Array of {@link Token} instances bound to the same SDK.\n * @param owner - Balance owner address.\n * @returns `{ results, errors }` partitioning the per-token outcomes.\n *\n * @example\n * ```ts\n * const { results, errors } = await Token.batchBalancesOf(tokens, owner);\n * ```\n */\n static async batchBalancesOf(tokens: Token[], owner: Address): Promise<BatchBalancesResult> {\n const results = new Map<Address, bigint>();\n const errors = new Map<Address, ZamaError>();\n if (tokens.length === 0) {\n return { results, errors };\n }\n\n const sdk = Token.assertSameSdk(tokens);\n // Fail fast on chain mismatch before prompting the wallet for a signature.\n await requireChainAlignment(\"batchBalancesOf\", sdk.signer, sdk.provider);\n // Pre-authorize the full token set in one wallet signature so subsequent\n // per-token decryptValues calls reuse the cached credentials.\n await sdk.permits.grantPermit(tokens.map((t) => t.address));\n\n const outcomes = await pLimit(\n tokens.map((t) => async () => {\n try {\n return {\n status: \"fulfilled\" as const,\n value: await t.balanceOf(owner),\n };\n } catch (reason) {\n return { status: \"rejected\" as const, reason };\n }\n }),\n 5,\n );\n\n for (let i = 0; i < tokens.length; i++) {\n const tokenAddress = tokens[i]!.address;\n const outcome = outcomes[i]!;\n if (outcome.status === \"fulfilled\") {\n results.set(tokenAddress, outcome.value);\n } else {\n const reason = outcome.reason;\n // Session-level failures (user rejected signature, SDK misconfigured)\n // apply to every token — surface them instead of collecting per-token.\n if (isFatalBatchError(reason)) {\n throw reason;\n }\n const error =\n reason instanceof ZamaError\n ? reason\n : new DecryptionFailedError(toError(reason).message, {\n cause: reason,\n });\n errors.set(tokenAddress, error);\n }\n }\n\n // Total failure: surface the first error so callers know nothing decrypted.\n if (errors.size === tokens.length) {\n const firstError = errors.values().next().value;\n throw firstError ?? new DecryptionFailedError(\"All token balance decryptions failed\");\n }\n\n return { results, errors };\n }\n\n /**\n * Batch decrypt confidential balances as a delegate across multiple tokens.\n * Mirrors {@link batchBalancesOf} but uses delegated credentials.\n *\n * **Error handling:** If a per-token decryption fails and no `onError` callback\n * is provided, errors are collected and thrown as an aggregated\n * `DecryptionFailedError`. When the relayer returns no value for an encrypted value,\n * a `DecryptionFailedError` is thrown for that token (never silently returns `0n`).\n * Pass `onError: () => 0n` to opt into the silent zero behavior.\n *\n * @param tokens - Array of Token instances to decrypt balances for.\n * @param options - Delegated decryption configuration.\n * @returns A Map from token address to decrypted balance.\n * @throws if no active delegation exists. {@link DelegationNotFoundError}\n * @throws if the delegation has expired. {@link DelegationExpiredError}\n * @throws if any decryption fails and no `onError` is provided. {@link DecryptionFailedError}\n *\n * @example\n * ```ts\n * const balances = await Token.batchDecryptBalancesAs(tokens, {\n * delegatorAddress: \"0xDelegator\",\n * onError: (err, addr) => { console.error(addr, err); return 0n; },\n * });\n * ```\n */\n static async batchDecryptBalancesAs(\n tokens: Token[],\n options: BatchDecryptAsOptions,\n ): Promise<Map<Address, bigint>> {\n if (tokens.length === 0) {\n return new Map();\n }\n\n const sdk = Token.assertSameSdk(tokens);\n const results = new Map<Address, bigint>();\n const errors = new Map<Address, ZamaError>();\n const normalizedAccount = options.accountAddress\n ? getAddress(options.accountAddress)\n : getAddress(options.delegatorAddress);\n const maxConcurrency = options.maxConcurrency ?? 10;\n if (options.encryptedValues && tokens.length !== options.encryptedValues.length) {\n throw new DecryptionFailedError(\n `tokens.length (${tokens.length}) must equal encryptedValues.length (${options.encryptedValues.length})`,\n );\n }\n const resolvedEncryptedValues =\n options.encryptedValues ??\n (await Token.readBalanceHandlesBatch(tokens, normalizedAccount, errors, maxConcurrency));\n\n const decryptRequests: Array<{ token: Token; encryptedValue: EncryptedValue }> = [];\n for (const [index, token] of tokens.entries()) {\n const encryptedValue = resolvedEncryptedValues[index];\n if (!encryptedValue || errors.has(token.address)) {\n continue;\n }\n if (isEncryptedValueZero(encryptedValue)) {\n // Zero balance → skip the relayer; no decryption needed.\n results.set(token.address, 0n);\n } else {\n decryptRequests.push({ token, encryptedValue });\n }\n }\n\n if (decryptRequests.length > 0) {\n const decrypted = await sdk.decryption.delegatedBatchDecryptValues({\n encryptedInputs: decryptRequests.map(({ token, encryptedValue }) => ({\n encryptedValue,\n contractAddress: token.address,\n })),\n delegatorAddress: options.delegatorAddress,\n accountAddress: options.accountAddress,\n maxConcurrency,\n });\n\n for (const [index, item] of decrypted.items.entries()) {\n const request = decryptRequests[index];\n if (!request) {\n continue;\n }\n if (item.error) {\n errors.set(request.token.address, item.error);\n continue;\n }\n const value = item.value;\n if (value === undefined) {\n errors.set(\n request.token.address,\n new DecryptionFailedError(\n `Batch delegated decryption returned no value for ${item.encryptedValue} on token ${request.token.address}`,\n ),\n );\n continue;\n }\n assertBigint(value, \"batchDecryptBalancesAs: result[encryptedValue]\");\n results.set(request.token.address, value);\n }\n }\n\n if (errors.size === 0) {\n return results;\n }\n\n if (options.onError) {\n const callbackErrors: Array<{ address: Address; error: Error }> = [];\n for (const [address, error] of errors) {\n try {\n results.set(address, options.onError(error, address));\n } catch (callbackError) {\n callbackErrors.push({ address, error: toError(callbackError) });\n }\n }\n if (callbackErrors.length > 0) {\n const message = callbackErrors\n .map(({ address, error }) => `${address}: ${error.message}`)\n .join(\"; \");\n throw new DecryptionFailedError(\n `Batch delegated decryption onError callback failed for ${callbackErrors.length} token(s): ${message}`,\n { cause: callbackErrors[0]?.error },\n );\n }\n return results;\n }\n\n const errorEntries = Array.from(errors.entries());\n const message = errorEntries.map(([addr, e]) => `${addr}: ${e.message}`).join(\"; \");\n throw new DecryptionFailedError(\n `Batch delegated decryption failed for ${errors.size} token(s): ${message}`,\n { cause: errorEntries[0]?.[1] },\n );\n }\n\n private static async readBalanceHandlesBatch(\n tokens: Token[],\n accountAddress: Address,\n errors: Map<Address, ZamaError>,\n maxConcurrency: number,\n ): Promise<Array<EncryptedValue | undefined>> {\n const outcomes = await pLimit(\n tokens.map((token) => async () => {\n try {\n return {\n status: \"fulfilled\" as const,\n value: await token.readConfidentialBalanceOf(accountAddress),\n };\n } catch (reason) {\n return { status: \"rejected\" as const, reason };\n }\n }),\n maxConcurrency,\n );\n\n const encryptedValues: Array<EncryptedValue | undefined> = [];\n for (const [index, token] of tokens.entries()) {\n const outcome = outcomes[index];\n if (!outcome) {\n continue;\n }\n if (outcome.status === \"fulfilled\") {\n encryptedValues[index] = outcome.value;\n continue;\n }\n if (isFatalBatchError(outcome.reason)) {\n throw outcome.reason;\n }\n errors.set(\n token.address,\n outcome.reason instanceof ZamaError\n ? outcome.reason\n : new DecryptionFailedError(toError(outcome.reason).message, {\n cause: outcome.reason,\n }),\n );\n }\n return encryptedValues;\n }\n\n // WRITE OPERATIONS\n\n /**\n * Confidential transfer. Encrypts the amount via FHE, then calls the contract.\n *\n * By default, the SDK validates the confidential balance before submitting.\n * If a cached plaintext balance exists it is used; otherwise, if credentials\n * are cached, it decrypts on the fly. Set `skipBalanceCheck: true` to bypass\n * this validation (e.g. for smart wallets).\n *\n * @param to - Recipient address.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @param options - Optional: `skipBalanceCheck` (default `false`).\n * @returns The transaction hash and mined receipt.\n * @throws if signer and provider are on different chains. {@link ChainMismatchError}\n * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}\n * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}\n * @throws if FHE encryption fails. {@link EncryptionFailedError}\n * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransfer(\"0xRecipient\", 1000n);\n * ```\n */\n async confidentialTransfer(\n to: Address,\n amount: bigint,\n options?: TransferOptions,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransfer\");\n const account = await requireAlignedWalletAccount(\n \"confidentialTransfer\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const { skipBalanceCheck = false, onEncryptComplete, onTransferSubmitted } = options ?? {};\n\n const normalizedTo = getAddress(to);\n\n if (!skipBalanceCheck) {\n await this.assertConfidentialBalance(amount);\n }\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: getAddress(account.address),\n });\n void swallow(\"transfer: onEncryptComplete\", () => onEncryptComplete?.(), this.sdk.logger);\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transfer\",\n config: confidentialTransferContract(\n this.address,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n ),\n onSubmitted: onTransferSubmitted,\n });\n }\n\n /**\n * Operator encrypted transfer on behalf of another address.\n * The caller must be an approved operator for `from`.\n *\n * @param from - The address to transfer from (caller must be an approved operator).\n * @param to - Recipient address.\n * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.confidentialTransferFrom(\"0xFrom\", \"0xTo\", 500n);\n * ```\n */\n async confidentialTransferFrom(\n from: Address,\n to: Address,\n amount: bigint,\n callbacks?: TransferCallbacks,\n ): Promise<TransactionResult> {\n this.#requireSigner(\"confidentialTransferFrom\");\n await requireAlignedWalletAccount(\n \"confidentialTransferFrom\",\n this.sdk.signer,\n this.sdk.provider,\n );\n const normalizedFrom = getAddress(from);\n const normalizedTo = getAddress(to);\n\n const { encryptedValues, inputProof } = await this.sdk.encrypt({\n values: [{ value: amount, type: \"euint64\" }],\n contractAddress: this.address,\n userAddress: normalizedFrom,\n });\n void swallow(\n \"transferFrom: onEncryptComplete\",\n () => callbacks?.onEncryptComplete?.(),\n this.sdk.logger,\n );\n\n if (encryptedValues.length === 0) {\n throw new EncryptionFailedError(\"Encryption returned no encrypted values\");\n }\n\n return this.submitTransaction({\n operation: \"transferFrom\",\n config: confidentialTransferFromContract(\n this.address,\n normalizedFrom,\n normalizedTo,\n encryptedValues[0]!,\n inputProof,\n ),\n onSubmitted: callbacks?.onTransferSubmitted,\n });\n }\n\n // OPERATOR APPROVAL\n\n /**\n * Set operator approval for the confidential token.\n * Defaults to 1 hour from now if `until` is not specified.\n *\n * @param operator - The address to set as an operator.\n * @param until - Optional Unix timestamp for approval expiry. Defaults to now + 1 hour.\n * @returns The transaction hash and mined receipt.\n *\n * @example\n * ```ts\n * const txHash = await token.setOperator(\"0xOperator\");\n * ```\n */\n async setOperator(operator: Address, until?: number): Promise<TransactionResult> {\n this.#requireSigner(\"setOperator\");\n await requireChainAlignment(\"setOperator\", this.sdk.signer, this.sdk.provider);\n const normalizedOperator = getAddress(operator);\n return this.submitTransaction({\n operation: \"setOperator\",\n config: setOperatorContract(this.address, normalizedOperator, until),\n });\n }\n\n /**\n * Check if a spender is an approved operator for a given holder.\n *\n * @param holder - The token holder address.\n * @param spender - The address to check operator approval for.\n * @returns `true` if the spender is an approved operator for the holder.\n *\n * @example\n * ```ts\n * if (await token.isOperator(\"0xHolder\", \"0xSpender\")) {\n * // spender can call transferFrom on behalf of holder\n * }\n * ```\n */\n async isOperator(holder: Address, spender: Address): Promise<boolean> {\n return this.sdk.provider.readContract(\n isOperatorContract(this.address, getAddress(holder), getAddress(spender)),\n );\n }\n\n // PROTECTED HELPERS\n\n /**\n * Read the on-chain encrypted balance for a given owner.\n *\n * @internal\n */\n protected async readConfidentialBalanceOf(owner: Address): Promise<EncryptedValue> {\n return await this.sdk.provider.readContract(confidentialBalanceOfContract(this.address, owner));\n }\n\n /**\n * Pre-flight check: decrypt the confidential balance and compare against the\n * requested amount. If credentials are cached the decrypt happens silently;\n * if not, throws {@link BalanceCheckUnavailableError} instead of triggering\n * a surprise EIP-712 popup.\n *\n * @internal\n */\n protected async assertConfidentialBalance(amount: bigint): Promise<void> {\n if (amount === 0n) {\n return;\n }\n\n let balance: bigint;\n try {\n const account = await requireAlignedWalletAccount(\n \"assertConfidentialBalance\",\n this.sdk.signer,\n this.sdk.provider,\n );\n balance = await this.balanceOf(getAddress(account.address));\n } catch (error) {\n if (error instanceof ZamaError) {\n throw error;\n }\n throw new BalanceCheckUnavailableError(`Balance validation failed (token: ${this.address})`, {\n cause: error,\n });\n }\n\n if (balance < amount) {\n throw new InsufficientConfidentialBalanceError(\n `Insufficient confidential balance: requested ${amount}, available ${balance} (token: ${this.address})`,\n { requested: amount, available: balance, token: this.address },\n );\n }\n }\n\n /**\n * Emit a token-scoped event through the owning {@link ZamaSDK} so that\n * subscribers see a unified stream.\n *\n * @internal\n */\n protected emit(input: ZamaSDKEventInput): void {\n this.sdk.emitEvent(input, this.address);\n }\n\n /**\n * Submit a token-scoped write transaction through the shared SDK transaction\n * pipeline. Callers keep pre-flight and operation-specific work local.\n *\n * @internal\n */\n protected async submitTransaction(params: {\n operation: TransactionOperation;\n config: WriteContractConfig;\n onSubmitted?: (txHash: Hex) => void;\n }): Promise<TransactionResult> {\n const { operation, config, onSubmitted } = params;\n return submitSdkTransaction({\n operation,\n signer: this.#requireSigner(operation),\n provider: this.sdk.provider,\n config,\n emit: (input) => this.emit(input),\n onSubmitted,\n logger: this.sdk.logger,\n });\n }\n\n /** Verify all tokens share the same SDK instance and return it. */\n private static assertSameSdk(tokens: Token[]): ZamaSDK {\n const sdk = tokens[0]!.sdk;\n for (let i = 1; i < tokens.length; i++) {\n if (tokens[i]!.sdk !== sdk) {\n throw new ConfigurationError(\n \"All tokens in a batch operation must share the same ZamaSDK instance\",\n );\n }\n }\n return sdk;\n }\n}\n\n/** @internal */\nexport type DecryptedHandlesMap = Map<EncryptedValue, ClearValue>;\n"],"mappings":"uYAGA,IAAa,EAAb,cAA8C,CAAU,CACtD,YAAY,EAAiB,EAAwB,CACnD,MAAM,EAAc,oBAAqB,EAAS,CAAO,EACzD,KAAK,KAAO,0BACd,CACF,ECea,EAAb,cAAwC,CAAU,CAChD,UACA,cACA,gBAEA,YACE,CACE,YACA,gBACA,mBAEF,EACA,CACA,MACE,EAAc,cACd,cAAc,EAAU,iFACI,EAAc,4BAA4B,EAAgB,GACtF,CACF,EACA,KAAK,KAAO,qBACZ,KAAK,UAAY,EACjB,KAAK,cAAgB,EACrB,KAAK,gBAAkB,CACzB,CACF,ECpCa,EAAb,cAA0D,CAAU,CAElE,UAEA,UAEA,MAEA,YAAY,EAAiB,EAA8B,EAAwB,CACjF,MAAM,EAAc,gCAAiC,EAAS,CAAO,EACrE,KAAK,KAAO,uCACZ,KAAK,UAAY,EAAQ,UACzB,KAAK,UAAY,EAAQ,UACzB,KAAK,MAAQ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,UACN,aAAc,SAChB,EACA,CACE,KAAM,iBACN,KAAM,SACN,aAAc,QAChB,CACF,EACA,QAAS,CAAC,EACV,gBAAiB,YACnB,EACA,CACE,KAAM,WACN,KAAM,4CACN,OAAQ,CACN,CACE,KAAM,YACN,KAAM,UACN,aAAc,SAChB,EACA,CACE,KAAM,WACN,KAAM,UACN,aAAc,SAChB,EACA,CACE,KAAM,kBACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,QAAS,CACP,CACE,KAAM,GACN,KAAM,SACN,aAAc,QAChB,CACF,EACA,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,kBACN,OAAQ,CACN,CACE,KAAM,UACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,QAAS,CACP,CACE,KAAM,GACN,KAAM,OACN,aAAc,MAChB,CACF,EACA,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,YACN,OAAQ,CACN,CACE,KAAM,SACN,KAAM,UACN,aAAc,SAChB,EACA,CACE,KAAM,UACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,QAAS,CACP,CACE,KAAM,GACN,KAAM,OACN,aAAc,MAChB,CACF,EACA,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,yBACN,OAAQ,CACN,CACE,KAAM,SACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,QAAS,CACP,CACE,KAAM,GACN,KAAM,OACN,aAAc,MAChB,CACF,EACA,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,qCACN,OAAQ,CACN,CACE,KAAM,YACN,KAAM,UACN,aAAc,SAChB,EACA,CACE,KAAM,WACN,KAAM,UACN,aAAc,SAChB,EACA,CACE,KAAM,kBACN,KAAM,UACN,aAAc,SAChB,EACA,CACE,KAAM,SACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,QAAS,CACP,CACE,KAAM,GACN,KAAM,OACN,aAAc,MAChB,CACF,EACA,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,YACN,OAAQ,CACN,CACE,KAAM,OACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,QAAS,CACP,CACE,KAAM,UACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,gBAAiB,SACnB,EACA,CACE,KAAM,WACN,KAAM,iBACN,OAAQ,CACN,CACE,KAAM,SACN,KAAM,UACN,aAAc,SAChB,EACA,CACE,KAAM,UACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,QAAS,CACP,CACE,KAAM,GACN,KAAM,OACN,aAAc,MAChB,CACF,EACA,gBAAiB,MACnB,EACA,CACE,KAAM,WACN,KAAM,oCACN,OAAQ,CACN,CACE,KAAM,WACN,KAAM,UACN,aAAc,SAChB,EACA,CACE,KAAM,kBACN,KAAM,UACN,aAAc,SAChB,CACF,EACA,QAAS,CAAC,EACV,gBAAiB,YACnB,CACF,EChQA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,MAAO,CACL,QAAS,EACT,IAAK,EACL,aAAc,4BACd,KAAM,CAAC,EAAiB,EAAiB,CAAc,CACzD,CACF,CAYA,SAAgB,EACd,EACA,EACA,EACA,CACA,MAAO,CACL,QAAS,EACT,IAAK,EACL,aAAc,oCACd,KAAM,CAAC,EAAiB,CAAe,CACzC,CACF,CAYA,SAAgB,EACd,EACA,EACA,EACA,EACA,CACA,MAAO,CACL,QAAS,EACT,IAAK,EACL,aAAc,4CACd,KAAM,CAAC,EAAkB,EAAiB,CAAe,CAC3D,CACF,CAYA,SAAgB,EACd,EACA,EACA,EACA,EACA,EACA,CACA,MAAO,CACL,QAAS,EACT,IAAK,EACL,aAAc,qCACd,KAAM,CAAC,EAAkB,EAAiB,EAAiB,CAAM,CACnE,CACF,CChGA,MAAa,EAAa,IAAM,IAAM,GCatC,eAAsB,EACpB,EACA,EACA,EACwB,CACxB,GAAI,CAAC,EACH,MAAM,IAAI,EAAyB,CAAS,EAE9C,IAAI,EACJ,GAAI,CACF,EAAU,EAAO,qBAAqB,CAAS,CACjD,OAAS,EAAO,CACd,GAAI,EA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