@zama-fhe/sdk 3.3.0 → 3.3.1-alpha.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/README.md +0 -2
  2. package/dist/cjs/base-signer.cjs +1 -1
  3. package/dist/cjs/base-signer.cjs.map +1 -1
  4. package/dist/cjs/chains.cjs +1 -1
  5. package/dist/cjs/chains.cjs.map +1 -1
  6. package/dist/cjs/cleartext/index.cjs +1 -1
  7. package/dist/cjs/cleartext.cjs +2 -0
  8. package/dist/cjs/cleartext.cjs.map +1 -0
  9. package/dist/cjs/ethers/index.cjs.map +1 -1
  10. package/dist/cjs/fhevm-relayer.cjs +2 -0
  11. package/dist/cjs/fhevm-relayer.cjs.map +1 -0
  12. package/dist/cjs/index.cjs +1 -1
  13. package/dist/cjs/index.cjs.map +1 -1
  14. package/dist/cjs/node/index.cjs +2 -0
  15. package/dist/cjs/node/index.cjs.map +1 -0
  16. package/dist/cjs/query/index.cjs +1 -1
  17. package/dist/cjs/query/index.cjs.map +1 -1
  18. package/dist/cjs/relayer.cjs +1 -1
  19. package/dist/cjs/relayer.cjs.map +1 -1
  20. package/dist/cjs/token.cjs +1 -1
  21. package/dist/cjs/token.cjs.map +1 -1
  22. package/dist/cjs/viem/index.cjs +1 -1
  23. package/dist/cjs/viem/index.cjs.map +1 -1
  24. package/dist/cjs/web/index.cjs +1 -590
  25. package/dist/cjs/web/index.cjs.map +1 -1
  26. package/dist/cjs/wrappers-registry.cjs.map +1 -1
  27. package/dist/esm/base-signer-CI-FYai2.js +2 -0
  28. package/dist/esm/base-signer-CI-FYai2.js.map +1 -0
  29. package/dist/esm/{base-signer-C3Wc5oi9.d.ts → base-signer-Q2EJECrc.d.ts} +2 -2
  30. package/dist/esm/chains/index.d.ts +2 -3
  31. package/dist/esm/chains/index.js +1 -1
  32. package/dist/esm/chains-CLv9HEJ_.js +2 -0
  33. package/dist/esm/chains-CLv9HEJ_.js.map +1 -0
  34. package/dist/esm/cleartext/index.d.ts +3 -2
  35. package/dist/esm/cleartext/index.js +1 -1
  36. package/dist/esm/cleartext-BfXTVQu-.js +2 -0
  37. package/dist/esm/cleartext-BfXTVQu-.js.map +1 -0
  38. package/dist/esm/cleartext-U6sPs_Kd.d.ts +19 -0
  39. package/dist/esm/ethers/index.d.ts +4 -5
  40. package/dist/esm/ethers/index.js +1 -1
  41. package/dist/esm/ethers/index.js.map +1 -1
  42. package/dist/esm/fhevm-relayer-B-lEKfPQ.js +2 -0
  43. package/dist/esm/fhevm-relayer-B-lEKfPQ.js.map +1 -0
  44. package/dist/esm/index-BnIp_-Ak.d.ts +328 -0
  45. package/dist/esm/{index-CYBH0nyo.d.ts → index-D66eC3G7.d.ts} +60 -13
  46. package/dist/esm/index.d.ts +8 -11
  47. package/dist/esm/index.js +1 -1
  48. package/dist/esm/index.js.map +1 -1
  49. package/dist/esm/node/index.d.ts +5 -194
  50. package/dist/esm/node/index.js +1 -1
  51. package/dist/esm/node/index.js.map +1 -1
  52. package/dist/esm/query/index.d.ts +3 -380
  53. package/dist/esm/query/index.js +1 -1
  54. package/dist/esm/query/index.js.map +1 -1
  55. package/dist/esm/relayer-BYq9bLh8.js +2 -0
  56. package/dist/esm/relayer-BYq9bLh8.js.map +1 -0
  57. package/dist/esm/token-CmHTAAWW.js +2 -0
  58. package/dist/esm/token-CmHTAAWW.js.map +1 -0
  59. package/dist/esm/{types-piBsdTIP.d.ts → types-Bov8XY36.d.ts} +3 -3
  60. package/dist/esm/{types-OHIaPwCy.d.ts → types-BpvL50qX.d.ts} +3 -3
  61. package/dist/esm/types-C-WTLcHZ.d.ts +988 -0
  62. package/dist/esm/viem/index.d.ts +4 -5
  63. package/dist/esm/viem/index.js +1 -1
  64. package/dist/esm/viem/index.js.map +1 -1
  65. package/dist/esm/web/index.d.ts +6 -9
  66. package/dist/esm/web/index.js +1 -590
  67. package/dist/esm/web/index.js.map +1 -1
  68. package/dist/esm/{wrappers-registry-C1oK8Bi6.js → wrappers-registry-xZWzyAi4.js} +2 -2
  69. package/dist/esm/wrappers-registry-xZWzyAi4.js.map +1 -0
  70. package/dist/esm/{index-C1Mtc8Rw.d.ts → zama-sdk-q4_qt64Q.d.ts} +1471 -1102
  71. package/package.json +6 -2
  72. package/dist/cjs/assertions.cjs +0 -2
  73. package/dist/cjs/assertions.cjs.map +0 -1
  74. package/dist/cjs/encryption.cjs +0 -2
  75. package/dist/cjs/encryption.cjs.map +0 -1
  76. package/dist/cjs/relayer-cleartext.cjs +0 -2
  77. package/dist/cjs/relayer-cleartext.cjs.map +0 -1
  78. package/dist/cjs/relayer-sdk.worker.js +0 -589
  79. package/dist/cjs/timeout.cjs +0 -2
  80. package/dist/cjs/timeout.cjs.map +0 -1
  81. package/dist/cjs/validation.cjs +0 -2
  82. package/dist/cjs/validation.cjs.map +0 -1
  83. package/dist/esm/assertions-zYseN5Xz.js +0 -2
  84. package/dist/esm/assertions-zYseN5Xz.js.map +0 -1
  85. package/dist/esm/base-signer-DjytqPkd.js +0 -2
  86. package/dist/esm/base-signer-DjytqPkd.js.map +0 -1
  87. package/dist/esm/chains-CXcO1DBP.js +0 -2
  88. package/dist/esm/chains-CXcO1DBP.js.map +0 -1
  89. package/dist/esm/cleartext-DAkOTlrE.d.ts +0 -19
  90. package/dist/esm/cleartext-rTWFctyd.js +0 -2
  91. package/dist/esm/cleartext-rTWFctyd.js.map +0 -1
  92. package/dist/esm/encryption-x4Z_Icqk.js +0 -2
  93. package/dist/esm/encryption-x4Z_Icqk.js.map +0 -1
  94. package/dist/esm/hex-A72GrTf9.js +0 -2
  95. package/dist/esm/hex-A72GrTf9.js.map +0 -1
  96. package/dist/esm/indexeddb-storage-Mi-fCWN3.js +0 -2
  97. package/dist/esm/indexeddb-storage-Mi-fCWN3.js.map +0 -1
  98. package/dist/esm/memory-storage-fp9RY5BQ.js +0 -2
  99. package/dist/esm/memory-storage-fp9RY5BQ.js.map +0 -1
  100. package/dist/esm/node/relayer-sdk.node-worker.d.ts +0 -1
  101. package/dist/esm/node/relayer-sdk.node-worker.js +0 -2
  102. package/dist/esm/node/relayer-sdk.node-worker.js.map +0 -1
  103. package/dist/esm/relayer-cleartext-Bp6jtxDd.js +0 -2
  104. package/dist/esm/relayer-cleartext-Bp6jtxDd.js.map +0 -1
  105. package/dist/esm/relayer-cleartext-CSeMlmGO.d.ts +0 -844
  106. package/dist/esm/relayer-eavK5bfZ.js +0 -2
  107. package/dist/esm/relayer-eavK5bfZ.js.map +0 -1
  108. package/dist/esm/relayer-sdk.worker.js +0 -589
  109. package/dist/esm/timeout-CNVfiaJD.js +0 -2
  110. package/dist/esm/timeout-CNVfiaJD.js.map +0 -1
  111. package/dist/esm/token-Bt33g0zQ.js +0 -2
  112. package/dist/esm/token-Bt33g0zQ.js.map +0 -1
  113. package/dist/esm/types-BgczXqW2.d.ts +0 -49
  114. package/dist/esm/types-Gn5MeDsr.d.ts +0 -669
  115. package/dist/esm/validation-DLszOweh.js +0 -2
  116. package/dist/esm/validation-DLszOweh.js.map +0 -1
  117. package/dist/esm/worker.base-client-BVnT4yJa.js +0 -2
  118. package/dist/esm/worker.base-client-BVnT4yJa.js.map +0 -1
  119. package/dist/esm/wrappers-registry-C1oK8Bi6.js.map +0 -1
@@ -1,9 +1,7 @@
1
- import { n as FheChain } from "./types-BgczXqW2.js";
2
- import { E as ShieldOptions, F as GenericSigner, H as TransactionResult, I as WalletAccount, M as UnshieldCallbacks, N as GenericStorage, O as TransferOptions, P as GenericProvider, R as WalletAccountListener, Y as WriteContractConfig, a as StoredTransportKeyPairWithPermits, d as EncryptParams, f as EncryptResult, g as PublicDecryptResult, j as TransferCallbacks, k as UnshieldOptions, p as EncryptedValue, pt as GenericLogger, s as ClearValue } from "./relayer-cleartext-CSeMlmGO.js";
3
- import { E as TransactionOperation, P as ZamaSDKEventInput, a as ZamaConfig, n as RelayerConfig, s as ZamaConfigGeneric, u as RelayerDispatcher } from "./types-Gn5MeDsr.js";
1
+ import { u as FheChain } from "./index-D66eC3G7.js";
2
+ import { $ as TransferOptions, Bt as EncryptedValue, C as ChainRouter, Ht as FhevmRelayerOptions, K as ZamaSDKEventInput, Mt as TransactionResult, Nt as ClearValue, Pt as DecryptPublicValuesResult, R as TransactionOperation, Rt as EncryptParams, Ut as FhevmRelayerSDK, Z as ShieldOptions, c as GenericStorage, d as WalletAccount, et as UnshieldOptions, i as ZamaConfig, l as GenericProvider, n as RelayerConfig, nt as TransferCallbacks, o as ZamaConfigGeneric, p as WalletAccountListener, rt as UnshieldCallbacks, s as GenericLogger, u as GenericSigner, x as WriteContractConfig, zt as EncryptResult } from "./types-C-WTLcHZ.js";
4
3
  import { Address, Hex } from "viem";
5
4
  import { z } from "zod/mini";
6
- import { UserDecryptResults } from "@zama-fhe/relayer-sdk/bundle";
7
5
  import { MutationFunctionContext, QueryKey, QueryObserverOptions, skipToken } from "@tanstack/query-core";
8
6
 
9
7
  //#region src/config/create.d.ts
@@ -39,7 +37,7 @@ declare function resolveStorage(storage?: GenericStorage | undefined, permitStor
39
37
  };
40
38
  interface ResolvedChainRelayer {
41
39
  chain: FheChain;
42
- relayer: RelayerConfig;
40
+ relayerConfig: RelayerConfig;
43
41
  }
44
42
  declare function resolveChainRelayers(chains: readonly FheChain[], relayers: Readonly<Record<number, RelayerConfig>>): Map<number, ResolvedChainRelayer>;
45
43
  //#endregion
@@ -18458,6 +18456,34 @@ declare function isConfidentialTokenValidContract(registry: Address, confidentia
18458
18456
  readonly args: readonly [`0x${string}`];
18459
18457
  };
18460
18458
  //#endregion
18459
+ //#region src/query/utils.d.ts
18460
+ type StrippedQueryOptionKeys = "gcTime" | "staleTime" | "enabled" | "select" | "refetchInterval" | "refetchOnMount" | "refetchOnWindowFocus" | "refetchOnReconnect" | "retry" | "retryDelay" | "retryOnMount" | "queryFn" | "queryKey" | "queryKeyHashFn" | "initialData" | "initialDataUpdatedAt" | "placeholderData" | "structuralSharing" | "throwOnError" | "meta" | "query" | "pollingInterval";
18461
+ /**
18462
+ * Remove TanStack behavioral options from a query config object so only domain
18463
+ * parameters remain for the lower-level factory.
18464
+ *
18465
+ * @example
18466
+ * ```ts
18467
+ * const params = filterQueryOptions({
18468
+ * query: { enabled: false },
18469
+ * gcTime: 60_000,
18470
+ * owner: "0xabc",
18471
+ * });
18472
+ * // => { owner: "0xabc" }
18473
+ * ```
18474
+ */
18475
+ declare function filterQueryOptions<TOptions extends Record<string, unknown>>(options: TOptions): Omit<TOptions, StrippedQueryOptionKeys>;
18476
+ /**
18477
+ * Stable hash function for query keys.
18478
+ * Sorts object keys recursively and converts bigint values to strings.
18479
+ *
18480
+ * @remarks
18481
+ * bigint values are serialized as decimal strings, so `42n` and `"42"` hash to
18482
+ * the same token when they occupy the same position. This collision is accepted
18483
+ * by design for the current query-key conventions in this package.
18484
+ */
18485
+ declare function hashFn(queryKey: readonly unknown[]): string;
18486
+ //#endregion
18461
18487
  //#region src/query/factory-types.d.ts
18462
18488
  type RequiredBy<T, K extends keyof T> = Omit<T, K> & Required<Pick<T, K>>;
18463
18489
  type QueryFactoryOptions<TQueryFnData = unknown, TError = Error, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> = Omit<RequiredBy<QueryObserverOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>, "queryKey">, "queryFn" | "queryHash" | "queryKeyHashFn" | "throwOnError"> & {
@@ -18469,6 +18495,11 @@ interface MutationFactoryOptions<TMutationKey extends readonly unknown[], TVaria
18469
18495
  onSuccess?: (data: TData, variables: TVariables, onMutateResult: TOnMutateResult, context: MutationFunctionContext) => void;
18470
18496
  }
18471
18497
  //#endregion
18498
+ //#region src/query/signer-query-context.d.ts
18499
+ interface SignerQueryContext {
18500
+ walletAccount?: WalletAccount;
18501
+ }
18502
+ //#endregion
18472
18503
  //#region src/query/query-keys.d.ts
18473
18504
  /**
18474
18505
  * Canonical query-key namespace for `@zama-fhe/sdk/query`.
@@ -18672,112 +18703,393 @@ declare const zamaQueryKeys: {
18672
18703
  };
18673
18704
  };
18674
18705
  //#endregion
18675
- //#region src/query/signer-query-context.d.ts
18676
- interface SignerQueryContext {
18677
- walletAccount?: WalletAccount;
18706
+ //#region src/query/invalidation.d.ts
18707
+ interface QueryLike {
18708
+ queryKey: readonly unknown[];
18709
+ }
18710
+ interface QueryFilterLike {
18711
+ queryKey?: readonly unknown[];
18712
+ predicate?: (query: QueryLike) => boolean;
18678
18713
  }
18714
+ interface QueryClientLike {
18715
+ invalidateQueries(filters: QueryFilterLike): void | Promise<void>;
18716
+ removeQueries(filters: QueryFilterLike): void;
18717
+ }
18718
+ declare function invalidateAfterUnwrap(queryClient: QueryClientLike, tokenAddress: Address): void;
18719
+ declare function invalidateBalanceQueries(queryClient: QueryClientLike, tokenAddress: Address): void;
18720
+ declare function invalidateAfterShield(queryClient: QueryClientLike, tokenAddress: Address): void;
18721
+ declare function invalidateAfterUnshield(queryClient: QueryClientLike, tokenAddress: Address): void;
18722
+ declare function invalidateAfterUnshieldSettled(queryClient: QueryClientLike, tokenAddress: Address): void;
18723
+ declare function invalidateAfterTransfer(queryClient: QueryClientLike, tokenAddress: Address): void;
18724
+ declare function invalidateAfterApproveUnderlying(queryClient: QueryClientLike, tokenAddress: Address): void;
18725
+ declare function invalidateAfterSetOperator(queryClient: QueryClientLike, tokenAddress: Address): void;
18726
+ declare function invalidateWagmiBalanceQueries(queryClient: QueryClientLike): void;
18727
+ declare function invalidateWalletLifecycleQueries(queryClient: QueryClientLike): void;
18679
18728
  //#endregion
18680
- //#region src/query/user-decrypt.d.ts
18681
- interface EncryptedInput {
18682
- encryptedValue: EncryptedValue;
18683
- contractAddress: Address;
18729
+ //#region src/query/token-metadata.d.ts
18730
+ /** ERC-20 token metadata returned by {@link tokenMetadataQueryOptions}. */
18731
+ interface TokenMetadata {
18732
+ name: string;
18733
+ symbol: string;
18734
+ decimals: number;
18684
18735
  }
18685
- /** Alias for {@link UserDecryptResults}. */
18686
- type DecryptResult = UserDecryptResults;
18687
- declare function decryptValuesQueryOptions(sdk: ZamaSDK, encryptedInputs: EncryptedInput[], signerContext?: SignerQueryContext): QueryFactoryOptions<DecryptResult, Error, DecryptResult, ReturnType<typeof zamaQueryKeys.decryption.encryptedInputs>>;
18736
+ interface TokenMetadataQueryConfig {
18737
+ query?: Record<string, unknown>;
18738
+ }
18739
+ declare function tokenMetadataQueryOptions(sdk: ZamaSDK, tokenAddress: Address, config?: TokenMetadataQueryConfig): QueryFactoryOptions<TokenMetadata, Error, TokenMetadata, ReturnType<typeof zamaQueryKeys.tokenMetadata.token>>;
18688
18740
  //#endregion
18689
- //#region src/credentials/credential-service.d.ts
18690
- /** Configuration for {@link CredentialService}. TTLs are pre-validated by the caller. */
18691
- interface CredentialServiceConfig {
18692
- relayer: RelayerDispatcher;
18693
- signer: GenericSigner;
18694
- /** Transport key pair lifetime in seconds. Pre-validated. */
18695
- transportKeyPairTTL: number;
18696
- /** Permit lifetime in days. Pre-validated. */
18697
- permitTTL: number;
18698
- /** Backing storage for transport key pairs (and permits if `permitStorage` is omitted). */
18699
- storage: GenericStorage;
18700
- /** Optional dedicated storage for permits; defaults to `storage`. */
18701
- permitStorage?: GenericStorage;
18702
- /** SDK-wide logger for credential-path diagnostics. */
18703
- logger: GenericLogger;
18741
+ //#region src/query/is-confidential.d.ts
18742
+ interface IsConfidentialQueryConfig {
18743
+ query?: Record<string, unknown>;
18744
+ }
18745
+ declare function isConfidentialQueryOptions(sdk: ZamaSDK, tokenAddress: Address, config?: IsConfidentialQueryConfig): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.isConfidential.token>>;
18746
+ declare function isWrapperQueryOptions(sdk: ZamaSDK, tokenAddress: Address, config?: IsConfidentialQueryConfig): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.isWrapper.token>>;
18747
+ //#endregion
18748
+ //#region src/query/total-supply.d.ts
18749
+ interface TotalSupplyQueryConfig {
18750
+ query?: Record<string, unknown>;
18704
18751
  }
18752
+ declare function totalSupplyQueryOptions(sdk: ZamaSDK, tokenAddress: Address, config?: TotalSupplyQueryConfig): QueryFactoryOptions<bigint, Error, bigint, ReturnType<typeof zamaQueryKeys.totalSupply.token>>;
18753
+ //#endregion
18754
+ //#region src/schemas/primitives.d.ts
18755
+ declare const checksummedTag: unique symbol;
18756
+ /** An EVM address that has been put through `getAddress` (EIP-55 checksum form). */
18757
+ type ChecksummedAddress = Address & {
18758
+ readonly [checksummedTag]: true;
18759
+ };
18760
+ //#endregion
18761
+ //#region src/credentials/schemas.d.ts
18762
+ declare const StoredTransportKeyPairSchema: z.ZodMiniObject<{
18763
+ publicKey: z.ZodMiniCustom<`0x${string}`, `0x${string}`>;
18764
+ privateKey: z.ZodMiniCustom<`0x${string}`, `0x${string}`>;
18765
+ createdAt: z.ZodMiniNumberFormat;
18766
+ expiresAt: z.ZodMiniNumberFormat;
18767
+ }, z.core.$strip>;
18768
+ declare const PermissionSchema: z.ZodMiniObject<{
18769
+ keypairPublicKey: z.ZodMiniCustom<`0x${string}`, `0x${string}`>;
18770
+ contractAddresses: z.ZodMiniArray<z.ZodMiniPipe<z.ZodMiniCustom<`0x${string}`, `0x${string}`>, z.ZodMiniTransform<ChecksummedAddress, `0x${string}`>>>;
18771
+ serializedPermit: z.ZodMiniObject<{
18772
+ version: z.ZodMiniNumberFormat;
18773
+ eip712: z.ZodMiniObject<{
18774
+ domain: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
18775
+ primaryType: z.ZodMiniOptional<z.ZodMiniString<string>>;
18776
+ types: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniArray<z.ZodMiniObject<{
18777
+ name: z.ZodMiniString<string>;
18778
+ type: z.ZodMiniString<string>;
18779
+ }, z.core.$strip>>>;
18780
+ message: z.ZodMiniRecord<z.ZodMiniString<string>, z.ZodMiniUnknown>;
18781
+ }, z.core.$strip>;
18782
+ signature: z.ZodMiniCustom<`0x${string}`, `0x${string}`>;
18783
+ signerAddress: z.ZodMiniPipe<z.ZodMiniCustom<`0x${string}`, `0x${string}`>, z.ZodMiniTransform<ChecksummedAddress, `0x${string}`>>;
18784
+ }, z.core.$strip>;
18785
+ startTimestamp: z.ZodMiniNumberFormat;
18786
+ durationDays: z.ZodMiniNumberFormat;
18787
+ }, z.core.$strip>;
18788
+ //#endregion
18789
+ //#region src/credentials/types.d.ts
18705
18790
  /**
18706
- * Single facade coordinating the keypair vault and the permission store.
18791
+ * Serialized transport key pair ML-KEM public + private key as hex, the shape
18792
+ * we persist and hand to the decrypt path. Mirrors `@fhevm/sdk`'s
18793
+ * `serializeTransportKeyPair` output; the private half is plaintext, so treat it
18794
+ * as sensitive.
18795
+ */
18796
+ interface SerializedTransportKeyPair {
18797
+ publicKey: Hex;
18798
+ privateKey: Hex;
18799
+ }
18800
+ /** Persisted transport key pair entry with a bounded lifetime. */
18801
+ type StoredTransportKeyPair = z.infer<typeof StoredTransportKeyPairSchema>;
18802
+ /**
18803
+ * A signed EIP-712 permit binding a signer (and optional delegator) to a set of
18804
+ * contract addresses for a bounded time window. Wraps the serialized `@fhevm/sdk`
18805
+ * permit ({@link SerializedPermit}) alongside the scope/coverage metadata the
18806
+ * permission store indexes on.
18807
+ */
18808
+ type Permission = z.infer<typeof PermissionSchema>;
18809
+ /**
18810
+ * Credentials resolved for a decrypt operation: the transport key pair plus the
18811
+ * permits covering the requested contracts. A live, in-memory bundle — not a
18812
+ * storage record. {@link resolvePermit} extracts one {@link ResolvedPermit} from
18813
+ * it per contract.
18814
+ */
18815
+ interface SerializedTransportKeyPairWithPermissions {
18816
+ readonly keypair: SerializedTransportKeyPair;
18817
+ readonly permissions: readonly Permission[];
18818
+ }
18819
+ //#endregion
18820
+ //#region src/wrappers-registry.d.ts
18821
+ /**
18822
+ * Default wrappers registry addresses for known chains.
18823
+ * Only includes chains where a registry is deployed (excludes Hardhat).
18707
18824
  *
18708
- * `CredentialService` is the only credentials object held by `ZamaSDK`. It accepts identity
18709
- * transitions via `handleWalletAccountChange`.
18825
+ * @deprecated Read `registryAddress` from the chain presets instead (e.g.
18826
+ * `sepolia.registryAddress`). Will be removed in the next major version.
18710
18827
  */
18711
- declare class CredentialService {
18828
+ declare const DefaultRegistryAddresses: Record<number, Address>;
18829
+ /** Configuration for {@link WrappersRegistry}. */
18830
+ interface WrappersRegistryConfig {
18831
+ /** Read-only chain provider used for every registry lookup. */
18832
+ provider: GenericProvider;
18833
+ /**
18834
+ * Per-chain registry address overrides, merged on top of
18835
+ * {@link DefaultRegistryAddresses}. Use this to supply a registry
18836
+ * address for custom or local chains (e.g. Hardhat).
18837
+ *
18838
+ * @example
18839
+ * ```ts
18840
+ * new WrappersRegistry({
18841
+ * provider,
18842
+ * registryAddresses: { [31337]: "0xYourHardhatRegistry" },
18843
+ * });
18844
+ * ```
18845
+ */
18846
+ registryAddresses?: Record<number, Address>;
18847
+ /**
18848
+ * How long cached registry results remain valid, in seconds.
18849
+ * Default: `86400` (24 hours).
18850
+ */
18851
+ registryTTL?: number;
18852
+ }
18853
+ /** Options for {@link WrappersRegistry.listPairs}. */
18854
+ interface ListPairsOptions {
18855
+ /** Page number (1-indexed). Default: `1`. */
18856
+ page?: number;
18857
+ /** Number of items per page. Default: `100`. */
18858
+ pageSize?: number;
18859
+ /**
18860
+ * When `true`, fetches on-chain metadata (name, symbol, decimals) for both
18861
+ * the ERC-20 and confidential token, plus totalSupply for the ERC-20.
18862
+ * Default: `false`.
18863
+ */
18864
+ metadata?: boolean;
18865
+ }
18866
+ /**
18867
+ * High-level interface for the on-chain token wrappers registry.
18868
+ *
18869
+ * Uses the configured {@link GenericProvider} to resolve the correct registry
18870
+ * contract address for the current chain and exposes typed read helpers for
18871
+ * every registry query. Results are cached in memory with a configurable TTL
18872
+ * (default 24 hours).
18873
+ *
18874
+ * @example
18875
+ * ```ts
18876
+ * const registry = new WrappersRegistry({ provider });
18877
+ *
18878
+ * // Paginated listing
18879
+ * const page1 = await registry.listPairs({ page: 1, pageSize: 20 });
18880
+ *
18881
+ * // Structured lookups
18882
+ * const result = await registry.getConfidentialToken(erc20Address);
18883
+ * if (result) console.log(result.confidentialTokenAddress);
18884
+ *
18885
+ * // Force refresh
18886
+ * registry.refresh();
18887
+ * ```
18888
+ */
18889
+ declare class WrappersRegistry {
18712
18890
  #private;
18713
- constructor(config: CredentialServiceConfig);
18891
+ readonly provider: GenericProvider;
18892
+ constructor(config: WrappersRegistryConfig);
18714
18893
  /**
18715
- * Resolve a keypair and permissions covering `contracts`, minimizing wallet
18716
- * prompts by reusing or widening existing permits where possible. Empty
18717
- * `contracts` warms the keypair without prompting.
18894
+ * Synchronous lookup of the registry address for a given chain ID.
18895
+ * Returns `undefined` if no address is configured for that chain.
18896
+ */
18897
+ getAddress(chainId: number): Address | undefined;
18898
+ /**
18899
+ * Force-invalidate the in-memory cache. The next call to any read method
18900
+ * will fetch fresh data from the chain.
18901
+ */
18902
+ refresh(): void;
18903
+ /**
18904
+ * The cache TTL in milliseconds.
18905
+ * Exposed so query option factories can set a matching `staleTime`.
18906
+ */
18907
+ get ttlMs(): number;
18908
+ /**
18909
+ * Resolve the registry contract address for the current chain.
18718
18910
  *
18719
- * @returns The resolved keypair and permits covering the requested contracts.
18720
- * @throws if the user rejects a wallet signature prompt. {@link SigningRejectedError}
18721
- * @throws if signing fails for any other reason. {@link SigningFailedError}
18911
+ * Priority: `registryAddresses[chainId]` \> built-in default.
18912
+ *
18913
+ * @returns The registry contract address for the connected chain.
18914
+ * @throws if no address is configured for the chain. {@link ConfigurationError}
18722
18915
  */
18723
- grantPermit(contracts: readonly Address[], delegator?: Address): Promise<StoredTransportKeyPairWithPermits>;
18916
+ getRegistryAddress(): Promise<Address>;
18724
18917
  /**
18725
- * Pure store lookup: are stored permits sufficient to cover `contracts`? No wallet prompt.
18918
+ * List token wrapper pairs with page-based pagination.
18726
18919
  *
18727
- * @returns `true` if cached permits cover all requested contracts (vacuously
18728
- * true for an empty list); `false` if no keypair exists or coverage is
18729
- * incomplete.
18920
+ * Internally maps to `getTokenConfidentialTokenPairsSlice` on-chain.
18921
+ *
18922
+ * @param options - Pagination and enrichment options.
18923
+ * @returns A {@link PaginatedResult} of pairs.
18924
+ *
18925
+ * @example
18926
+ * ```ts
18927
+ * const result = await registry.listPairs({ page: 1, pageSize: 20 });
18928
+ * console.log(`${result.total} pairs, showing page ${result.page}`);
18929
+ *
18930
+ * // With on-chain metadata
18931
+ * const withMeta = await registry.listPairs({ metadata: true, pageSize: 10 });
18932
+ * for (const pair of withMeta.items) {
18933
+ * console.log(pair.underlying.symbol, "→", pair.confidential.symbol);
18934
+ * }
18935
+ * ```
18730
18936
  */
18731
- hasPermit(contracts: readonly Address[], delegator?: Address): Promise<boolean>;
18937
+ listPairs(options: ListPairsOptions & {
18938
+ metadata: true;
18939
+ }): Promise<PaginatedResult<TokenWrapperPairWithMetadata>>;
18940
+ listPairs(options?: ListPairsOptions): Promise<PaginatedResult<TokenWrapperPair>>;
18732
18941
  /**
18733
- * Wipe FHE permits for the current signer.
18942
+ * Look up the confidential token for a given plain ERC-20 address.
18734
18943
  *
18735
- * - With no argument: every permit referencing this signer is removed across
18736
- * all chains and delegators. The keypair survives use
18737
- * {@link clearCredentials} to also wipe the keypair.
18738
- * - With a contract list: every signed permit in the direct-decrypt scope
18739
- * (current chain) whose immutable payload touches any listed address is
18740
- * removed. Delegated permits are not touched in this mode.
18944
+ * @param tokenAddress - The plain ERC-20 token address.
18945
+ * @returns The lookup result, or `null` if the token has never been registered.
18946
+ * **Note:** revoked tokens (registered then invalidated) return a non-null result
18947
+ * with `isValid: false`. Check `result.isValid` explicitly rather than using
18948
+ * `if (result)` to guard against processing revoked tokens.
18741
18949
  *
18742
- * @throws if reading the signer address fails. {@link SigningFailedError}
18950
+ * @example
18951
+ * ```ts
18952
+ * const result = await registry.getConfidentialToken(usdcAddress);
18953
+ * if (result?.isValid) {
18954
+ * console.log(result.confidentialTokenAddress);
18955
+ * }
18956
+ * ```
18743
18957
  */
18744
- revokePermits(contracts?: readonly Address[]): Promise<void>;
18958
+ getConfidentialToken(tokenAddress: Address): Promise<{
18959
+ confidentialTokenAddress: Address;
18960
+ isValid: boolean;
18961
+ } | null>;
18745
18962
  /**
18746
- * Wipe the keypair for the current signer and cascade-delete every
18747
- * permission referencing it across all chains and delegators.
18963
+ * Reverse lookup find the plain ERC-20 for a given confidential token.
18748
18964
  *
18749
- * @throws if reading the signer address fails. {@link SigningFailedError}
18965
+ * @param confidentialTokenAddress - The confidential token address.
18966
+ * @returns The lookup result, or `null` if no pair is registered.
18967
+ *
18968
+ * @example
18969
+ * ```ts
18970
+ * const result = await registry.getUnderlyingToken(cUsdcAddress);
18971
+ * if (result) {
18972
+ * console.log(result.tokenAddress, result.isValid);
18973
+ * }
18974
+ * ```
18750
18975
  */
18751
- clearCredentials(): Promise<void>;
18976
+ getUnderlyingToken(confidentialTokenAddress: Address): Promise<{
18977
+ tokenAddress: Address;
18978
+ isValid: boolean;
18979
+ } | null>;
18752
18980
  /**
18753
- * Warm the signer transport key pair cache for a known address.
18981
+ * Fetch all token wrapper pairs from the registry.
18754
18982
  *
18755
- * Best-effort prefetch primitive: correctness still comes from `grantPermit`,
18756
- * which lazily creates the transport key pair when needed. Errors (storage failure,
18757
- * relayer 4xx, missing Worker in SSR) are **not** swallowed here — the caller
18758
- * decides whether to log, ignore, or surface them.
18983
+ * @returns All registered `TokenWrapperPair` entries.
18759
18984
  */
18760
- warmTransportKeyPair(address: Address): Promise<void>;
18985
+ getTokenPairs(): Promise<readonly TokenWrapperPair[]>;
18761
18986
  /**
18762
- * Apply a wallet account transition.
18987
+ * Get the total number of token wrapper pairs.
18763
18988
  *
18764
- * Address change clears persisted credentials for the previous account.
18765
- * Chain-only changes keep credentials intact because permits are chain-scoped
18766
- * already and stale decrypt plaintext is cleared by `ZamaSDK`.
18989
+ * @returns The count as a bigint.
18767
18990
  */
18768
- handleWalletAccountChange(prev?: {
18769
- address: Address;
18770
- }, next?: {
18771
- address: Address;
18772
- }): Promise<void>;
18773
- }
18774
- //#endregion
18775
- //#region src/errors/base.d.ts
18776
- /**
18777
- * Typed error codes thrown by the SDK.
18778
- * Use `error.code` or `instanceof` to programmatically handle specific failure modes.
18779
- *
18780
- * @example
18991
+ getTokenPairsLength(): Promise<bigint>;
18992
+ /**
18993
+ * Fetch a range of token wrapper pairs (paginated by index).
18994
+ *
18995
+ * @param fromIndex - Start index (inclusive).
18996
+ * @param toIndex - End index (exclusive).
18997
+ * @returns The slice of `TokenWrapperPair` entries.
18998
+ */
18999
+ getTokenPairsSlice(fromIndex: bigint, toIndex: bigint): Promise<readonly TokenWrapperPair[]>;
19000
+ /**
19001
+ * Fetch a single token wrapper pair by index.
19002
+ *
19003
+ * @param index - Zero-based pair index.
19004
+ * @returns The `TokenWrapperPair` at that index.
19005
+ */
19006
+ getTokenPair(index: bigint): Promise<TokenWrapperPair>;
19007
+ /**
19008
+ * Look up the confidential token address for a given plain ERC-20 token.
19009
+ *
19010
+ * @param tokenAddress - The plain ERC-20 token address.
19011
+ * @returns A tuple `[isValid, confidentialTokenAddress]`. `isValid` is `true` only for a
19012
+ * registered, non-revoked wrapper. The address is the zero address when no pair is registered.
19013
+ * A non-zero address with `isValid=false` means the wrapper was registered but later revoked.
19014
+ */
19015
+ getConfidentialTokenAddress(tokenAddress: Address): Promise<readonly [boolean, Address]>;
19016
+ /**
19017
+ * Reverse lookup — find the plain ERC-20 for a given confidential token.
19018
+ *
19019
+ * @param confidentialTokenAddress - The confidential token address.
19020
+ * @returns A tuple `[isValid, tokenAddress]`. `isValid` is `true` only for a registered,
19021
+ * non-revoked wrapper. The address is the zero address when no pair is registered.
19022
+ * A non-zero address with `isValid=false` means the wrapper was registered but later revoked.
19023
+ */
19024
+ getTokenAddress(confidentialTokenAddress: Address): Promise<readonly [boolean, Address]>;
19025
+ /**
19026
+ * Check whether a confidential token is registered and valid.
19027
+ *
19028
+ * @param confidentialTokenAddress - The confidential token address to check.
19029
+ * @returns `true` if the token is a known valid wrapper in the registry.
19030
+ */
19031
+ isConfidentialTokenValid(confidentialTokenAddress: Address): Promise<boolean>;
19032
+ }
19033
+ //#endregion
19034
+ //#region src/query/wrapper-discovery.d.ts
19035
+ interface WrapperDiscoveryQueryConfig {
19036
+ /**
19037
+ * Address of any confidential token you control.
19038
+ * Used to scope the query cache key and to gate whether the query
19039
+ * is enabled — it does not affect which wrapper the registry returns.
19040
+ */
19041
+ tokenAddress?: Address;
19042
+ /**
19043
+ * The ERC-20 token address to discover the confidential wrapper for.
19044
+ * The registry is resolved automatically from chain config.
19045
+ */
19046
+ erc20Address?: Address;
19047
+ /**
19048
+ * The resolved registry contract address for the current chain.
19049
+ * Included in the query key so that switching chains invalidates
19050
+ * stale cached results. Pass `undefined` when the chain ID is not
19051
+ * yet known — the query will be disabled.
19052
+ */
19053
+ registryAddress?: Address;
19054
+ query?: Record<string, unknown>;
19055
+ }
19056
+ declare function wrapperDiscoveryQueryOptions(registry: WrappersRegistry, config: WrapperDiscoveryQueryConfig): QueryFactoryOptions<Address | null, Error, Address | null, ReturnType<typeof zamaQueryKeys.wrapperDiscovery.token>>;
19057
+ //#endregion
19058
+ //#region src/query/underlying-allowance.d.ts
19059
+ interface UnderlyingAllowanceQueryConfig {
19060
+ owner?: Address;
19061
+ query?: Record<string, unknown>;
19062
+ }
19063
+ declare function underlyingAllowanceQueryOptions(sdk: ZamaSDK, tokenAddress: Address, config: UnderlyingAllowanceQueryConfig): QueryFactoryOptions<bigint, Error, bigint, ReturnType<typeof zamaQueryKeys.underlyingAllowance.scope>>;
19064
+ //#endregion
19065
+ //#region src/query/pending-unshield.d.ts
19066
+ interface PendingUnshieldQueryConfig {
19067
+ query?: Record<string, unknown>;
19068
+ }
19069
+ /**
19070
+ * Query options for reading the unwrap tx hash of an unshield that was
19071
+ * interrupted between its two phases (returns `null` if none is pending).
19072
+ *
19073
+ * Backed by {@link ZamaSDK} storage via `WrappedToken.getPendingUnshield()`.
19074
+ * `staleTime: 0` so the value reflects storage on mount; the unshield/unwrap
19075
+ * mutations also invalidate this key on success.
19076
+ */
19077
+ declare function pendingUnshieldQueryOptions(sdk: ZamaSDK, tokenAddress: Address, config?: PendingUnshieldQueryConfig): QueryFactoryOptions<Hex | null, Error, Hex | null, ReturnType<typeof zamaQueryKeys.pendingUnshield.token>>;
19078
+ //#endregion
19079
+ //#region src/query/confidential-is-operator.d.ts
19080
+ interface ConfidentialIsOperatorQueryConfig {
19081
+ holder?: Address;
19082
+ spender?: Address;
19083
+ query?: Record<string, unknown>;
19084
+ }
19085
+ declare function confidentialIsOperatorQueryOptions(sdk: ZamaSDK, tokenAddress: Address | undefined, config: ConfidentialIsOperatorQueryConfig): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.confidentialIsOperator.scope>>;
19086
+ //#endregion
19087
+ //#region src/errors/base.d.ts
19088
+ /**
19089
+ * Typed error codes thrown by the SDK.
19090
+ * Use `error.code` or `instanceof` to programmatically handle specific failure modes.
19091
+ *
19092
+ * @example
18781
19093
  * ```ts
18782
19094
  * try {
18783
19095
  * await token.confidentialTransfer("0xTo", 100n);
@@ -18799,9 +19111,7 @@ declare const ZamaErrorCode: {
18799
19111
  readonly NoCiphertext: "NO_CIPHERTEXT"; /** Relayer HTTP request failed. */
18800
19112
  readonly RelayerRequestFailed: "RELAYER_REQUEST_FAILED"; /** The configured signer/account is not entitled (ACL) to decrypt this encrypted value. Don't retry — wait for a grant. */
18801
19113
  readonly NotEntitled: "NOT_ENTITLED"; /** The consumer's RPC provider rate-limited an on-chain read (e.g. HTTP 429 / JSON-RPC -32005). Retryable. */
18802
- readonly RpcRateLimited: "RPC_RATE_LIMITED"; /** A worker operation exceeded its configured timeout; the worker is recycled by default. Retryable. */
18803
- readonly OperationTimeout: "OPERATION_TIMEOUT"; /** An in-flight worker operation was aborted as collateral of another operation's timeout recycle. Retryable. */
18804
- readonly WorkerRecycled: "WORKER_RECYCLED"; /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */
19114
+ readonly RpcRateLimited: "RPC_RATE_LIMITED"; /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */
18805
19115
  readonly Configuration: "CONFIGURATION"; /** Delegation cannot target self (delegate === msg.sender). */
18806
19116
  readonly DelegationSelfNotAllowed: "DELEGATION_SELF_NOT_ALLOWED"; /** Only one delegate/revoke per (delegator, delegate, contract) per block. */
18807
19117
  readonly DelegationCooldown: "DELEGATION_COOLDOWN"; /** No active delegation found for this (delegator, delegate, contract) tuple. */
@@ -19010,11 +19320,14 @@ declare class RelayerRequestFailedError extends ZamaError {
19010
19320
  readonly retryAfter: number | undefined;
19011
19321
  /**
19012
19322
  * Whether the request may be safely retried. `true` for relayer back-pressure
19013
- * (HTTP 429); pair with {@link retryAfter} for the server's suggested delay.
19323
+ * (HTTP 429) pair with {@link retryAfter} for the server's suggested delay
19324
+ * and for a relayer timeout (which carries no status but is safe to retry, via
19325
+ * the `retryable` option). `false` for terminal failures (e.g. a 4xx/5xx).
19014
19326
  */
19015
19327
  readonly retryable: boolean;
19016
19328
  constructor(message: string, statusCode?: number, options?: ErrorOptions & {
19017
19329
  retryAfter?: number;
19330
+ retryable?: boolean;
19018
19331
  });
19019
19332
  }
19020
19333
  /** SDK configuration is invalid (e.g. forbidden chain ID, unsupported type). */
@@ -19144,79 +19457,6 @@ declare class TransactionRevertedError extends ZamaError {
19144
19457
  constructor(message: string, options?: ErrorOptions);
19145
19458
  }
19146
19459
  //#endregion
19147
- //#region src/errors/timeout.d.ts
19148
- /**
19149
- * A worker operation (encrypt / decrypt / EIP-712 / key fetch) did not complete
19150
- * within its configured timeout — typically a stuck relayer or WASM call. On the
19151
- * Node pool the SDK **recycles the affected worker** (terminating the hung
19152
- * thread) so it self-heals; the operation itself is **retryable**.
19153
- *
19154
- * Configure the bound (seconds) via `node({ operationTimeout })`. Distinct from a
19155
- * decryption/entitlement failure — a timeout is an infrastructure/latency
19156
- * condition, so it no longer collapses into {@link DecryptionFailedError}.
19157
- *
19158
- * @example
19159
- * ```ts
19160
- * try {
19161
- * await sdk.decryption.decryptValues([{ encryptedValue, contractAddress }]);
19162
- * } catch (e) {
19163
- * if (e instanceof WorkerTimeoutError) {
19164
- * // retry (the worker was recycled); consider raising operationTimeout
19165
- * }
19166
- * }
19167
- * ```
19168
- */
19169
- declare class WorkerTimeoutError extends ZamaError {
19170
- /**
19171
- * The worker operation that timed out. This is the internal worker op code
19172
- * (e.g. `USER_DECRYPT`, `ENCRYPT`), not the public SDK method name.
19173
- */
19174
- readonly operation: string;
19175
- /** The configured timeout that was exceeded, in **seconds** (the SDK's duration unit). */
19176
- readonly timeout: number;
19177
- /** Wall-clock time the operation ran before being abandoned, in **seconds** (may be fractional). */
19178
- readonly elapsed: number;
19179
- /** Label of the worker that stalled, when known (e.g. `node-worker-2`). */
19180
- readonly worker: string | undefined;
19181
- constructor(args: {
19182
- operation: string;
19183
- timeout: number;
19184
- elapsed: number;
19185
- worker?: string;
19186
- }, options?: ErrorOptions);
19187
- }
19188
- /**
19189
- * An in-flight worker operation was aborted as **collateral** when its worker was
19190
- * recycled — the worker was torn down to recover from *another* operation's
19191
- * timeout (Node pool self-healing), not because this operation itself timed out.
19192
- *
19193
- * The operation never reached a verdict, so it is **retryable**: the next call
19194
- * lazily re-inits a fresh worker. It is intentionally distinct from
19195
- * {@link WorkerTimeoutError} (this op did not exceed its own bound) and from
19196
- * {@link DecryptionFailedError} (nothing actually failed to decrypt) — so a
19197
- * consumer can retry it instead of surfacing a terminal failure.
19198
- *
19199
- * @example
19200
- * ```ts
19201
- * matchZamaError(error, {
19202
- * WORKER_RECYCLED: () => retry(), // transient: the worker was replaced
19203
- * });
19204
- * ```
19205
- */
19206
- declare class WorkerRecycledError extends ZamaError {
19207
- /**
19208
- * The worker operation that was aborted. This is the internal worker op code
19209
- * (e.g. `USER_DECRYPT`, `ENCRYPT`), not the public SDK method name.
19210
- */
19211
- readonly operation: string;
19212
- /** Label of the recycled worker, when known (e.g. `node-worker-2`). */
19213
- readonly worker: string | undefined;
19214
- constructor(args: {
19215
- operation: string;
19216
- worker?: string;
19217
- }, options?: ErrorOptions);
19218
- }
19219
- //#endregion
19220
19460
  //#region src/errors/match.d.ts
19221
19461
  /**
19222
19462
  * Identity type that fails to instantiate unless `T` maps every code to a `ZamaError`.
@@ -19242,8 +19482,6 @@ type ErrorForCode = Complete<{
19242
19482
  [ZamaErrorCode.RelayerRequestFailed]: RelayerRequestFailedError;
19243
19483
  [ZamaErrorCode.NotEntitled]: NotEntitledError;
19244
19484
  [ZamaErrorCode.RpcRateLimited]: RpcRateLimitError;
19245
- [ZamaErrorCode.OperationTimeout]: WorkerTimeoutError;
19246
- [ZamaErrorCode.WorkerRecycled]: WorkerRecycledError;
19247
19485
  [ZamaErrorCode.Configuration]: ConfigurationError;
19248
19486
  [ZamaErrorCode.DelegationSelfNotAllowed]: DelegationSelfNotAllowedError;
19249
19487
  [ZamaErrorCode.DelegationCooldown]: DelegationCooldownError;
@@ -19284,1198 +19522,1325 @@ declare function matchZamaError<R>(error: unknown, handlers: { [K in ZamaErrorCo
19284
19522
  _?: (error: unknown) => R;
19285
19523
  }): R | undefined;
19286
19524
  //#endregion
19287
- //#region src/services/caching-service.d.ts
19288
- /**
19289
- * Storage-backed cache for decrypted FHE plaintext values.
19290
- *
19291
- * Each entry is keyed by `(requester, contractAddress, handle)` so different
19292
- * signers cannot read each other's cached decryptions.
19293
- */
19294
- declare class CachingService {
19295
- #private;
19296
- constructor(storage: GenericStorage, logger: GenericLogger);
19297
- get(requester: Address, contractAddress: Address, encryptedValue: EncryptedValue): Promise<ClearValue | null>;
19298
- set(requester: Address, contractAddress: Address, encryptedValue: EncryptedValue, value: ClearValue): Promise<void>;
19299
- delete(requester: Address, contractAddress: Address, encryptedValue: EncryptedValue): Promise<void>;
19300
- clearForRequester(requester: Address): Promise<void>;
19301
- clearAll(): Promise<void>;
19302
- }
19303
- //#endregion
19304
- //#region src/services/delegation-service.d.ts
19305
- declare class DelegationService {
19306
- #private;
19307
- constructor({
19308
- provider,
19309
- relayer,
19310
- emitEvent,
19311
- logger
19312
- }: {
19313
- provider: GenericProvider;
19314
- relayer: RelayerDispatcher;
19315
- logger: GenericLogger;
19316
- emitEvent?: (input: ZamaSDKEventInput, tokenAddress?: Address) => void;
19317
- });
19318
- delegateDecryption(signer: GenericSigner, {
19319
- contractAddress,
19320
- delegateAddress,
19321
- delegatorAddress,
19322
- expirationDate
19323
- }: {
19324
- contractAddress: Address;
19325
- delegateAddress: Address;
19326
- delegatorAddress: Address;
19327
- expirationDate?: Date;
19328
- }): Promise<TransactionResult>;
19329
- revokeDelegation(signer: GenericSigner, {
19330
- contractAddress,
19331
- delegateAddress,
19332
- delegatorAddress
19333
- }: {
19334
- contractAddress: Address;
19335
- delegateAddress: Address;
19336
- delegatorAddress: Address;
19337
- }): Promise<TransactionResult>;
19338
- isDelegated(params: {
19339
- contractAddress: Address;
19340
- delegatorAddress: Address;
19341
- delegateAddress: Address;
19342
- }): Promise<boolean>;
19343
- getDelegationExpiry({
19344
- contractAddress,
19345
- delegatorAddress,
19346
- delegateAddress
19347
- }: {
19348
- contractAddress: Address;
19349
- delegatorAddress: Address;
19350
- delegateAddress: Address;
19351
- }): Promise<bigint>;
19352
- findInactiveDelegations(contractAddresses: readonly Address[], delegatorAddress: Address, delegateAddress: Address): Promise<Map<Address, DelegationNotFoundError | DelegationExpiredError>>;
19353
- assertDelegationActive(contractAddress: Address, delegatorAddress: Address, delegateAddress: Address): Promise<void>;
19354
- }
19355
- //#endregion
19356
- //#region src/services/decryption-service.d.ts
19357
- /** Options shared by the delegated-decrypt entry points. */
19358
- interface DelegatedDecryptOptions {
19525
+ //#region src/token/token.d.ts
19526
+ /** Options for {@link Token.batchDecryptBalancesAs}. */
19527
+ interface BatchDecryptAsOptions {
19528
+ /** The address of the account that delegated decryption rights. */
19529
+ delegatorAddress: Address;
19530
+ /** Pre-fetched encrypted values. When omitted, they are fetched from the chain. */
19531
+ encryptedValues?: EncryptedValue[];
19359
19532
  /**
19360
- * Ride out the gateway propagation window: when a just-granted delegation
19361
- * has not yet synced, the delegated decrypt is retried (bounded, ~30s) until
19362
- * it lands instead of throwing {@link DelegationNotPropagatedError}. Defaults
19363
- * to `true`. Pass `false` to fail fast on the first not-propagated response.
19533
+ * The account whose on-chain balance to read. Defaults to the delegator
19534
+ * address, which is the common case (the delegator grants permission to
19535
+ * decrypt their own balance). Only set this when the account differs
19536
+ * from the delegator.
19537
+ *
19538
+ * Matches the `account` parameter of `confidentialBalanceOf(account)` on-chain.
19364
19539
  */
19365
- waitForPropagation?: boolean;
19366
- }
19367
- interface BatchDecryptItem {
19368
- encryptedValue: EncryptedValue;
19369
- contractAddress: Address;
19370
- value?: ClearValue;
19371
- error?: ZamaError;
19372
- }
19373
- interface BatchDecryptResult {
19374
- items: BatchDecryptItem[];
19540
+ accountAddress?: Address;
19541
+ /** Maximum number of concurrent decrypt calls. Default: 10. */
19542
+ maxConcurrency?: number;
19543
+ /** Called when decryption fails for a single token. Return a fallback bigint. */
19544
+ onError?: (error: Error, address: Address) => bigint;
19375
19545
  }
19376
- declare class DecryptionService {
19377
- #private;
19378
- constructor({
19379
- cache,
19380
- credentialService,
19381
- delegationService,
19382
- relayer,
19383
- emitEvent
19384
- }: {
19385
- cache: CachingService;
19386
- credentialService: CredentialService;
19387
- delegationService: DelegationService;
19388
- relayer: RelayerDispatcher;
19389
- emitEvent: (input: ZamaSDKEventInput) => void;
19390
- });
19391
- userDecrypt(handles: EncryptedInput[], signerAddress: Address): Promise<Record<EncryptedValue, ClearValue>>;
19392
- delegatedUserDecrypt(encryptedValues: EncryptedInput[], delegatorAddress: Address, delegateAddress: Address, accountAddress: Address, options?: DelegatedDecryptOptions): Promise<Record<EncryptedValue, ClearValue>>;
19393
- delegatedBatchDecryptHandlesAs({
19394
- encryptedInputs,
19395
- delegatorAddress,
19396
- delegateAddress,
19397
- accountAddress,
19398
- maxConcurrency,
19399
- waitForPropagation
19400
- }: {
19401
- encryptedInputs: EncryptedInput[];
19402
- delegatorAddress: Address;
19403
- delegateAddress: Address;
19404
- accountAddress: Address;
19405
- maxConcurrency?: number;
19406
- waitForPropagation?: boolean;
19407
- }): Promise<BatchDecryptResult>;
19546
+ /** Result of {@link Token.batchBalancesOf}. */
19547
+ interface BatchBalancesResult {
19548
+ /** Successfully decrypted balances, keyed by token address. */
19549
+ results: Map<Address, bigint>;
19550
+ /** Per-token errors for tokens that failed to decrypt. */
19551
+ errors: Map<Address, ZamaError>;
19408
19552
  }
19409
- //#endregion
19410
- //#region src/namespaces/decryption.d.ts
19411
19553
  /**
19412
- * Public namespace for FHE decryption the canonical way to decrypt.
19413
- *
19414
- * Exposed as `sdk.decryption`. Prefer these methods over the low-level
19415
- * `sdk.relayer.userDecrypt` / `delegatedUserDecrypt` / `publicDecrypt`: they
19416
- * assemble the credential bundle (transport key pair, EIP-712 permit) for you,
19417
- * cache results, and wrap relayer errors. Reach for `sdk.relayer.*` only when
19418
- * you must control credential assembly by hand.
19554
+ * High-level interface for an ERC-7984 confidential token.
19555
+ * Hides FHE complexity (encryption, decryption, EIP-712 signing) behind
19556
+ * familiar ERC-20-like methods.
19419
19557
  *
19420
- * Owns the SDK-level guards (signer requirement on
19421
- * `decryptValues` and `delegatedDecryptValues`, empty-array
19422
- * short-circuit on `decryptPublicValues`, relayer error wrapping) and delegates the
19423
- * actual work to the internal {@link DecryptionService} or the relayer directly for
19424
- * `decryptPublicValues`.
19558
+ * For ERC-7984 wrappers (shield/unshield), use {@link WrappedToken} instead —
19559
+ * it extends `Token` with wrapper-specific operations.
19425
19560
  *
19426
- * **Mixed signer requirement:** `decryptValues` and
19427
- * `delegatedDecryptValues` need a configured signer; `decryptPublicValues`
19428
- * does not. Each method documents its requirement in its JSDoc.
19561
+ * Decryption, credentials, caching, and event emission are handled by the
19562
+ * owning {@link ZamaSDK} this class only exposes token-scoped helpers
19563
+ * that delegate to `sdk.decryption.decryptValues` and `sdk.permits.grantPermit`.
19429
19564
  */
19430
- declare class Decryption {
19565
+ declare class Token {
19431
19566
  #private;
19432
- /** @internal */
19433
- constructor(opts: {
19434
- signer: GenericSigner | undefined;
19435
- provider: GenericProvider;
19436
- relayer: RelayerDispatcher;
19437
- decryptionService: DecryptionService | undefined;
19438
- });
19567
+ readonly sdk: ZamaSDK;
19568
+ readonly address: Address;
19569
+ constructor(sdk: ZamaSDK, address: Address);
19570
+ /** Read the token name from the contract. */
19571
+ name(): Promise<string>;
19572
+ /** Read the token symbol from the contract. */
19573
+ symbol(): Promise<string>;
19574
+ /** Read the token decimals from the contract. */
19575
+ decimals(): Promise<number>;
19439
19576
  /**
19440
- * Decrypt one or more FHE encrypted values. Results are cached — repeated calls
19441
- * for the same encrypted value skip the relayer round-trip.
19442
- *
19443
- * Zero encrypted values are mapped to `0n` without hitting the relayer.
19444
- * Events (`DecryptStart/End/Error`) are emitted uniformly.
19445
- * Relayer errors are wrapped into typed SDK errors.
19446
- *
19447
- * @param encryptedInput - Encrypted values to decrypt, each paired with its contract address.
19448
- * @returns A record mapping each encrypted value to its decrypted clear-text value.
19449
- * @throws if no signer is configured. {@link SignerNotConfiguredError}
19450
- * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19577
+ * ERC-165 check for {@link ERC7984_INTERFACE_ID} support.
19451
19578
  *
19452
- * @example
19453
- * ```ts
19454
- * const values = await sdk.decryption.decryptValues([
19455
- * { encryptedValue: balance, contractAddress: cUSDT },
19456
- * ]);
19457
- * console.log(values[balance]); // 1000n
19458
- * ```
19579
+ * @returns `true` if the contract implements the ERC-7984 confidential token interface.
19459
19580
  */
19460
- decryptValues(encryptedInput: EncryptedInput[]): Promise<Record<EncryptedValue, ClearValue>>;
19581
+ isConfidential(): Promise<boolean>;
19461
19582
  /**
19462
- * Decrypt one or more FHE encrypted values using delegated credentials.
19583
+ * ERC-165 check for IERC7984ERC20Wrapper support.
19463
19584
  *
19464
- * Mirrors {@link decryptValues} with delegated credentials same caching and
19465
- * zero-value short-circuit. Before reading from cache or calling the relayer,
19466
- * every non-zero encrypted value's contract must have an active delegation from the
19467
- * delegator to the connected signer; missing or expired delegations fail fast.
19585
+ * @returns `true` if the contract implements the ERC-7984 wrapper interface
19586
+ * ({@link ERC7984_WRAPPER_INTERFACE_ID}, `0x1f1c62b2`).
19587
+ */
19588
+ isWrapper(): Promise<boolean>;
19589
+ /**
19590
+ * Decrypt and return the plaintext balance for the given owner.
19591
+ * Acquires FHE credentials via a wallet signature if none are cached.
19468
19592
  *
19469
- * @param encryptedInputs - FHE encrypted values paired with their contract addresses.
19470
- * @param delegatorAddress - The address that granted delegation rights.
19471
- * @param accountAddress - Address used as the cache key's "requester"
19472
- * dimension. Defaults to `delegatorAddress`. Pass the actual account address
19473
- * when decrypting on behalf of someone whose balance is stored under a
19474
- * different address (e.g. `decryptBalanceAs` with an explicit `accountAddress`).
19475
- * @param options - Delegated-decrypt options. By default the call rides out the
19476
- * gateway propagation window ({@link DelegatedDecryptOptions.waitForPropagation});
19477
- * pass `{ waitForPropagation: false }` to fail fast instead.
19478
- * @returns Map of encrypted value → clear-text value.
19593
+ * @param owner - Balance owner address.
19594
+ * @returns The decrypted plaintext balance as a bigint.
19595
+ * @throws if FHE decryption fails. {@link DecryptionFailedError}
19479
19596
  *
19480
19597
  * @example
19481
19598
  * ```ts
19482
- * const values = await sdk.decryption.delegatedDecryptValues([
19483
- * { encryptedValue: balance, contractAddress: tokenAddr },
19484
- * ], delegatorAddr);
19485
- * console.log(values[balance]); // 1000n
19599
+ * const balance = await token.balanceOf("0xOwner");
19486
19600
  * ```
19487
19601
  */
19488
- delegatedDecryptValues(encryptedInputs: EncryptedInput[], delegatorAddress: Address, accountAddress?: Address, options?: DelegatedDecryptOptions): Promise<Record<EncryptedValue, ClearValue>>;
19602
+ balanceOf(owner: Address): Promise<bigint>;
19489
19603
  /**
19490
- * Publicly decrypt one or more FHE encrypted values.
19491
- *
19492
- * Signer-independent: works without a configured signer.
19493
- * Returns the decryption proof alongside the clear-text values so callers
19494
- * can submit on-chain finalization transactions (e.g. `finalizeUnwrap`).
19604
+ * Return the raw encrypted balance without decrypting.
19495
19605
  *
19496
- * @param encryptedValues - FHE encrypted values to decrypt publicly.
19497
- * @returns Clear-text values, ABI-encoded values, and the decryption proof.
19606
+ * @param owner - Balance owner address.
19607
+ * @returns The encrypted balance as a hex string.
19498
19608
  *
19499
19609
  * @example
19500
19610
  * ```ts
19501
- * const { clearValues, decryptionProof, abiEncodedClearValues } =
19502
- * await sdk.decryption.decryptPublicValues([encryptedValue]);
19611
+ * const encryptedValue = await token.confidentialBalanceOf("0xOwner");
19503
19612
  * ```
19504
19613
  */
19505
- decryptPublicValues(encryptedValues: EncryptedValue[]): Promise<PublicDecryptResult>;
19614
+ confidentialBalanceOf(owner: Address): Promise<EncryptedValue>;
19506
19615
  /**
19507
- * Batch-decrypt delegated encrypted values with per-entry error isolation.
19616
+ * Decrypt the balance of a delegator using delegated decryption credentials.
19617
+ * The connected signer acts as the delegatee who has been granted permission
19618
+ * by the delegator to decrypt their balance.
19508
19619
  *
19509
- * Attempts a single batch request first. If the batch fails with a non-fatal
19510
- * error (e.g. one entry is invalid), falls back to per-entry decryption so
19511
- * healthy entries still resolve. Each item in the result carries either a
19512
- * decrypted value or an error callers decide how to surface partial failures.
19620
+ * Clear values are cached in storage keyed by `(account, token, encryptedValue)`.
19621
+ * Because every on-chain balance change produces a new encrypted value,
19622
+ * stale cache entries are never served. Cache write failures are silently
19623
+ * ignoredthey do not affect the returned value.
19513
19624
  *
19514
- * @param encryptedInputs - FHE encrypted values paired with their contract addresses.
19515
- * @param delegatorAddress - The address that granted delegation rights.
19516
- * @param accountAddress - The account on whose behalf decryption is performed. Defaults to `delegatorAddress`.
19517
- * @param maxConcurrency - Maximum parallel decrypt calls during per-entry fallback.
19518
- * @param waitForPropagation - Ride out the gateway propagation window on the
19519
- * initial batch attempt (default `true`). See {@link DelegatedDecryptOptions.waitForPropagation}.
19520
- * @returns Per-entry results, each with a value or an error.
19521
- * @throws if no signer is configured. {@link SignerNotConfiguredError}
19522
- * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19625
+ * @param delegatorAddress - The address of the account that delegated decryption rights.
19626
+ * @param accountAddress - The account whose on-chain balance to read. Defaults
19627
+ * to the delegator address.
19628
+ * @returns The decrypted plaintext balance as a bigint.
19629
+ * @throws if no active delegation exists. {@link DelegationNotFoundError}
19630
+ * @throws if the delegation has expired. {@link DelegationExpiredError}
19631
+ * @throws if delegated decryption fails. {@link DecryptionFailedError}
19523
19632
  *
19524
19633
  * @example
19525
19634
  * ```ts
19526
- * const result = await sdk.decryption.delegatedBatchDecryptValues({
19527
- * encryptedInputs: [
19528
- * { encryptedValue: encryptedValue1, contractAddress: tokenA },
19529
- * { encryptedValue: encryptedValue2, contractAddress: tokenB },
19530
- * ],
19635
+ * const balance = await token.decryptBalanceAs({
19531
19636
  * delegatorAddress: "0xDelegator",
19532
- * maxConcurrency: 5,
19533
19637
  * });
19534
- * for (const item of result.items) {
19535
- * if (item.error) console.error(item.encryptedValue, item.error);
19536
- * else console.log(item.encryptedValue, item.value);
19537
- * }
19538
19638
  * ```
19539
19639
  */
19540
- delegatedBatchDecryptValues({
19541
- encryptedInputs,
19640
+ decryptBalanceAs({
19542
19641
  delegatorAddress,
19543
- accountAddress,
19544
- maxConcurrency,
19545
- waitForPropagation
19642
+ accountAddress
19546
19643
  }: {
19547
- encryptedInputs: EncryptedInput[];
19548
19644
  delegatorAddress: Address;
19549
19645
  accountAddress?: Address;
19550
- maxConcurrency?: number;
19551
- } & DelegatedDecryptOptions): Promise<BatchDecryptResult>;
19552
- }
19553
- //#endregion
19554
- //#region src/namespaces/delegations.d.ts
19555
- /**
19556
- * Public namespace for on-chain decryption-delegation management.
19557
- *
19558
- * Exposed as `sdk.delegations`. Owns the SDK-level guards (signer requirement, chain
19559
- * alignment, delegator address resolution from the wallet account) and delegates the
19560
- * actual work to the internal {@link DelegationService}.
19561
- *
19562
- * Delegation operations write to the host chain ACL; after a delegation is mined,
19563
- * the gateway syncs the ACL state via cross-chain event propagation — usually
19564
- * within ~10 blocks (a few seconds). Delegated decryption rides out that window
19565
- * with a bounded internal retry, so callers can decrypt right after granting.
19566
- */
19567
- declare class Delegations {
19568
- #private;
19569
- /** @internal */
19570
- constructor(opts: {
19571
- signer: GenericSigner | undefined;
19572
- provider: GenericProvider;
19573
- delegationService: DelegationService;
19574
- });
19646
+ }): Promise<bigint>;
19575
19647
  /**
19576
- * Delegate decryption rights for a confidential contract to another address.
19577
- * Calls `ACL.delegateForUserDecryption()` on-chain.
19648
+ * Decrypt confidential balances for multiple tokens in parallel, returning
19649
+ * successes and per-token errors separately. Pre-authorizes all token
19650
+ * addresses in a single wallet signature, then delegates each decrypt to
19651
+ * `sdk.decryption.decryptValues`.
19578
19652
  *
19579
- * The delegation is recorded on L1 immediately, but the gateway must sync the
19580
- * ACL state via cross-chain event propagation usually within ~10 blocks (a
19581
- * few seconds). You do not need to wait: delegated decryption rides out that
19582
- * window with a bounded internal retry, so you can decrypt right after this
19583
- * resolves.
19653
+ * Tokens that fail to decrypt land in `errors` rather than aborting the
19654
+ * whole batch caller decides how to surface them.
19584
19655
  *
19585
- * @param contractAddress - The confidential contract address to delegate on.
19586
- * @param delegateAddress - Address to delegate decryption rights to.
19587
- * @param expirationDate - Optional expiration date (defaults to permanent delegation via `uint64.max`).
19588
- * @returns The transaction hash and mined receipt.
19589
- * @throws if no signer is configured. {@link SignerNotConfiguredError}
19590
- * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19591
- * @throws if `expirationDate` is less than 1 hour in the future. {@link DelegationExpirationTooSoonError}
19592
- * @throws if the delegate equals the connected wallet. {@link DelegationSelfNotAllowedError}
19593
- * @throws if the delegate equals the contract address. {@link DelegationDelegateEqualsContractError}
19594
- * @throws if the new expiry equals the current one. {@link DelegationExpiryUnchangedError}
19595
- * @throws if the delegation transaction reverts. {@link TransactionRevertedError}
19656
+ * @param tokens - Array of {@link Token} instances bound to the same SDK.
19657
+ * @param owner - Balance owner address.
19658
+ * @returns `{ results, errors }` partitioning the per-token outcomes.
19659
+ *
19660
+ * @example
19661
+ * ```ts
19662
+ * const { results, errors } = await Token.batchBalancesOf(tokens, owner);
19663
+ * ```
19596
19664
  */
19597
- delegateDecryption({
19598
- contractAddress,
19599
- delegateAddress,
19600
- expirationDate
19601
- }: {
19602
- contractAddress: Address;
19603
- delegateAddress: Address;
19604
- expirationDate?: Date;
19605
- }): Promise<TransactionResult>;
19665
+ static batchBalancesOf(tokens: Token[], owner: Address): Promise<BatchBalancesResult>;
19606
19666
  /**
19607
- * Revoke decryption delegation for a confidential contract.
19608
- * Calls `ACL.revokeDelegationForUserDecryption()` on-chain.
19667
+ * Batch decrypt confidential balances as a delegate across multiple tokens.
19668
+ * Mirrors {@link batchBalancesOf} but uses delegated credentials.
19609
19669
  *
19610
- * @param contractAddress - The confidential contract address to revoke delegation on.
19611
- * @param delegateAddress - Address to revoke delegation from.
19612
- * @returns The transaction hash and mined receipt.
19613
- * @throws if no signer is configured. {@link SignerNotConfiguredError}
19614
- * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19615
- * @throws if no delegation exists for this (delegator, delegate, contract) tuple. {@link DelegationNotFoundError}
19616
- * @throws if the revocation transaction reverts. {@link TransactionRevertedError}
19670
+ * **Error handling:** If a per-token decryption fails and no `onError` callback
19671
+ * is provided, errors are collected and thrown as an aggregated
19672
+ * `DecryptionFailedError`. When the relayer returns no value for an encrypted value,
19673
+ * a `DecryptionFailedError` is thrown for that token (never silently returns `0n`).
19674
+ * Pass `onError: () => 0n` to opt into the silent zero behavior.
19675
+ *
19676
+ * @param tokens - Array of Token instances to decrypt balances for.
19677
+ * @param options - Delegated decryption configuration.
19678
+ * @returns A Map from token address to decrypted balance.
19679
+ * @throws if no active delegation exists. {@link DelegationNotFoundError}
19680
+ * @throws if the delegation has expired. {@link DelegationExpiredError}
19681
+ * @throws if any decryption fails and no `onError` is provided. {@link DecryptionFailedError}
19682
+ *
19683
+ * @example
19684
+ * ```ts
19685
+ * const balances = await Token.batchDecryptBalancesAs(tokens, {
19686
+ * delegatorAddress: "0xDelegator",
19687
+ * onError: (err, addr) => { console.error(addr, err); return 0n; },
19688
+ * });
19689
+ * ```
19617
19690
  */
19618
- revokeDelegation({
19619
- contractAddress,
19620
- delegateAddress
19621
- }: {
19622
- contractAddress: Address;
19623
- delegateAddress: Address;
19624
- }): Promise<TransactionResult>;
19691
+ static batchDecryptBalancesAs(tokens: Token[], options: BatchDecryptAsOptions): Promise<Map<Address, bigint>>;
19692
+ private static readBalanceHandlesBatch;
19625
19693
  /**
19626
- * Check whether a delegation is active for the given contract address.
19694
+ * Confidential transfer. Encrypts the amount via FHE, then calls the contract.
19627
19695
  *
19628
- * Signer-independent: works without a configured signer.
19696
+ * By default, the SDK validates the confidential balance before submitting.
19697
+ * If a cached plaintext balance exists it is used; otherwise, if credentials
19698
+ * are cached, it decrypts on the fly. Set `skipBalanceCheck: true` to bypass
19699
+ * this validation (e.g. for smart wallets).
19629
19700
  *
19630
- * @param contractAddress - The confidential contract address.
19631
- * @param delegatorAddress - The address that granted the delegation.
19632
- * @param delegateAddress - The address that received delegation rights.
19633
- * @returns `true` if the delegation exists and has not expired.
19701
+ * @param to - Recipient address.
19702
+ * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).
19703
+ * @param options - Optional: `skipBalanceCheck` (default `false`).
19704
+ * @returns The transaction hash and mined receipt.
19705
+ * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19706
+ * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}
19707
+ * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}
19708
+ * @throws if FHE encryption fails. {@link EncryptionFailedError}
19709
+ * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}
19710
+ *
19711
+ * @example
19712
+ * ```ts
19713
+ * const txHash = await token.confidentialTransfer("0xRecipient", 1000n);
19714
+ * ```
19634
19715
  */
19635
- isActive(params: {
19636
- contractAddress: Address;
19637
- delegatorAddress: Address;
19638
- delegateAddress: Address;
19639
- }): Promise<boolean>;
19716
+ confidentialTransfer(to: Address, amount: bigint, options?: TransferOptions): Promise<TransactionResult>;
19640
19717
  /**
19641
- * Get the expiration timestamp of a delegation for the given contract.
19718
+ * Operator encrypted transfer on behalf of another address.
19719
+ * The caller must be an approved operator for `from`.
19642
19720
  *
19643
- * Signer-independent: works without a configured signer.
19721
+ * @param from - The address to transfer from (caller must be an approved operator).
19722
+ * @param to - Recipient address.
19723
+ * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).
19724
+ * @returns The transaction hash and mined receipt.
19644
19725
  *
19645
- * @param contractAddress - The confidential contract address.
19646
- * @param delegatorAddress - The address that granted the delegation.
19647
- * @param delegateAddress - The address that received delegation rights.
19648
- * @returns Unix timestamp as bigint. `0n` = no delegation. `2^64 - 1` = permanent.
19726
+ * @example
19727
+ * ```ts
19728
+ * const txHash = await token.confidentialTransferFrom("0xFrom", "0xTo", 500n);
19729
+ * ```
19649
19730
  */
19650
- getExpiry(params: {
19651
- contractAddress: Address;
19652
- delegatorAddress: Address;
19653
- delegateAddress: Address;
19654
- }): Promise<bigint>;
19655
- }
19656
- //#endregion
19657
- //#region src/namespaces/permits.d.ts
19658
- /**
19659
- * Public namespace for permit and transport-key-pair management.
19660
- *
19661
- * Exposed as `sdk.permits`. Owns the SDK-level guards (chain alignment, empty-array
19662
- * short-circuit, decrypt-cache invalidation) and delegates the actual work to the
19663
- * internal {@link CredentialService}.
19664
- *
19665
- * The namespace is named `permits` because the user-facing concept is the signed-permit
19666
- * store. The transport key pair is invisible plumbing — there is no `getTransportKeyPair()`
19667
- * surfaced; the key pair exists to sign permits and is created automatically when needed.
19668
- * {@link clear} wipes both the permit store and the transport key pair (permits
19669
- * cascade-delete with the key pair).
19670
- */
19671
- declare class Permits {
19672
- #private;
19673
- /** @internal */
19674
- constructor(opts: {
19675
- signer: GenericSigner | undefined;
19676
- provider: GenericProvider;
19677
- cachingService: CachingService;
19678
- credentialService: CredentialService | undefined;
19679
- logger: GenericLogger;
19680
- });
19731
+ confidentialTransferFrom(from: Address, to: Address, amount: bigint, callbacks?: TransferCallbacks): Promise<TransactionResult>;
19681
19732
  /**
19682
- * Sign and store an EIP-712 permit authorising direct decryption for the
19683
- * given contract addresses.
19733
+ * ERC-7984 `confidentialTransferAndCall`: encrypted transfer that also invokes
19734
+ * the recipient's receiver hook (`onConfidentialTransferReceived`) in a single
19735
+ * transaction. The caller crafts the opaque `data` payload — the SDK does not
19736
+ * encode, validate, or interpret it.
19684
19737
  *
19685
- * Idempotent: if a permit covering the requested set already exists, no
19686
- * wallet prompt occurs. Otherwise the SDK chunks the uncovered subset into
19687
- * groups of ≤10 contracts and prompts once per chunk; partial mid-flight
19688
- * rejection is preserved (already-signed chunks are persisted before the
19689
- * next prompt).
19738
+ * Balance validation follows the same rules as {@link Token.confidentialTransfer}.
19690
19739
  *
19691
- * @param contracts - Contract addresses to authorize.
19692
- */
19693
- grantPermit(contracts: Address[]): Promise<void>;
19694
- /**
19695
- * Sign and store an EIP-712 delegation permit authorising decryption on
19696
- * behalf of `delegator`. Same idempotence/chunking semantics as {@link grantPermit}.
19740
+ * @param to - Recipient address. Must implement the ERC-7984 receiver hook.
19741
+ * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).
19742
+ * @param data - Opaque bytes forwarded to the recipient's receiver hook.
19743
+ * @param options - Optional: `skipBalanceCheck` (default `false`).
19744
+ * @returns The transaction hash and mined receipt.
19697
19745
  *
19698
- * @param delegator - The address that delegated decryption rights to the connected signer.
19699
- * @param contracts - Contract addresses to authorize.
19746
+ * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19747
+ * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}
19748
+ * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}
19749
+ * @throws if FHE encryption fails. {@link EncryptionFailedError}
19750
+ * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}
19751
+ *
19752
+ * @example
19753
+ * ```ts
19754
+ * const txHash = await token.confidentialTransferAndCall(
19755
+ * "0xRecipient",
19756
+ * 1000n,
19757
+ * "0xabcd", // caller-encoded payload forwarded to the receiver hook
19758
+ * );
19759
+ * ```
19700
19760
  */
19701
- grantDelegationPermit(delegator: Address, contracts: Address[]): Promise<void>;
19761
+ confidentialTransferAndCall(to: Address, amount: bigint, data: Hex, options?: TransferOptions): Promise<TransactionResult>;
19702
19762
  /**
19703
- * Pure store lookup: is there a permit covering `contracts`?
19704
- * No wallet prompt, no transport key pair generation. Returns `false` when no signer
19705
- * is configured.
19763
+ * ERC-7984 `confidentialTransferFromAndCall`: operator-initiated encrypted
19764
+ * transfer that also invokes the recipient's receiver hook in a single
19765
+ * transaction. The caller must be an approved operator for `from` and crafts
19766
+ * the opaque `data` payload — the SDK does not encode or interpret it.
19767
+ *
19768
+ * @param from - The address to transfer from (caller must be an approved operator).
19769
+ * @param to - Recipient address. Must implement the ERC-7984 receiver hook.
19770
+ * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).
19771
+ * @param data - Opaque bytes forwarded to the recipient's receiver hook.
19772
+ * @param callbacks - Optional progress callbacks.
19773
+ * @returns The transaction hash and mined receipt.
19774
+ *
19775
+ * @example
19776
+ * ```ts
19777
+ * const txHash = await token.confidentialTransferFromAndCall(
19778
+ * "0xFrom",
19779
+ * "0xRecipient",
19780
+ * 500n,
19781
+ * "0xabcd",
19782
+ * );
19783
+ * ```
19706
19784
  */
19707
- hasPermit(contracts: Address[]): Promise<boolean>;
19785
+ confidentialTransferFromAndCall(from: Address, to: Address, amount: bigint, data: Hex, callbacks?: TransferCallbacks): Promise<TransactionResult>;
19708
19786
  /**
19709
- * Pure store lookup for a delegation permit. See {@link hasPermit}.
19787
+ * Set operator approval for the confidential token.
19788
+ * Defaults to 1 hour from now if `until` is not specified.
19710
19789
  *
19711
- * @param delegator - The address that delegated decryption rights to the connected signer.
19712
- * @param contracts - Contract addresses to check.
19713
- * @returns `true` if cached delegation permits cover all requested contracts.
19790
+ * @param operator - The address to set as an operator.
19791
+ * @param until - Optional Unix timestamp for approval expiry. Defaults to now + 1 hour.
19792
+ * @returns The transaction hash and mined receipt.
19793
+ *
19794
+ * @example
19795
+ * ```ts
19796
+ * const txHash = await token.setOperator("0xOperator");
19797
+ * ```
19714
19798
  */
19715
- hasDelegationPermit(delegator: Address, contracts: Address[]): Promise<boolean>;
19799
+ setOperator(operator: Address, until?: number): Promise<TransactionResult>;
19716
19800
  /**
19717
- * Best-effort transport-key-pair prefetch for the connected signer.
19801
+ * Check if a spender is an approved operator for a given holder.
19718
19802
  *
19719
- * Optional latency optimization: decrypt and permit flows remain correct
19720
- * without it because they lazily create the transport key pair when needed.
19803
+ * @param holder - The token holder address.
19804
+ * @param spender - The address to check operator approval for.
19805
+ * @returns `true` if the spender is an approved operator for the holder.
19721
19806
  *
19722
- * Silent no-op when no signer is configured or no wallet account is
19723
- * available. The transport key pair is generated through the relayer dispatcher's
19724
- * currently active chain see {@link LifecycleService}, which calls
19725
- * `switchChain` before fanning the wallet-account change out to listeners,
19726
- * so any downstream caller (including React adapters) observes the
19727
- * dispatcher on the wallet chain by the time it invokes warmup.
19807
+ * @example
19808
+ * ```ts
19809
+ * if (await token.isOperator("0xHolder", "0xSpender")) {
19810
+ * // spender can call transferFrom on behalf of holder
19811
+ * }
19812
+ * ```
19728
19813
  */
19729
- warmTransportKeyPair(): Promise<void>;
19814
+ isOperator(holder: Address, spender: Address): Promise<boolean>;
19730
19815
  /**
19731
- * Wipe FHE permits for the current signer.
19816
+ * Read the on-chain encrypted balance for a given owner.
19732
19817
  *
19733
- * - With no argument: every permit referencing this signer is removed across
19734
- * all chains and delegators. The transport key pair survives — use {@link clear} to
19735
- * also wipe the transport key pair.
19736
- * - With a contract list: every signed permit in the direct-decrypt scope
19737
- * (current chain) whose immutable payload touches any listed address is
19738
- * removed. Delegation permits are not touched in this mode.
19818
+ * @internal
19819
+ */
19820
+ protected readConfidentialBalanceOf(owner: Address): Promise<EncryptedValue>;
19821
+ /**
19822
+ * Pre-flight check: decrypt the confidential balance and compare against the
19823
+ * requested amount. If credentials are cached the decrypt happens silently;
19824
+ * if not, throws {@link BalanceCheckUnavailableError} instead of triggering
19825
+ * a surprise EIP-712 popup.
19739
19826
  *
19740
- * @throws if no signer is configured. {@link SignerNotConfiguredError}
19827
+ * @internal
19741
19828
  */
19742
- revokePermits(contracts?: Address[]): Promise<void>;
19829
+ protected assertConfidentialBalance(amount: bigint): Promise<void>;
19743
19830
  /**
19744
- * Wipe the transport key pair for the current signer and cascade-delete every permit
19745
- * (across chains and delegators) referencing it.
19831
+ * Emit a token-scoped event through the owning {@link ZamaSDK} so that
19832
+ * subscribers see a unified stream.
19746
19833
  *
19747
- * @throws if no signer is configured. {@link SignerNotConfiguredError}
19834
+ * @internal
19748
19835
  */
19749
- clear(): Promise<void>;
19750
- }
19751
- //#endregion
19752
- //#region src/token/token.d.ts
19753
- /** Options for {@link Token.batchDecryptBalancesAs}. */
19754
- interface BatchDecryptAsOptions {
19755
- /** The address of the account that delegated decryption rights. */
19756
- delegatorAddress: Address;
19757
- /** Pre-fetched encrypted values. When omitted, they are fetched from the chain. */
19758
- encryptedValues?: EncryptedValue[];
19836
+ protected emit(input: ZamaSDKEventInput): void;
19759
19837
  /**
19760
- * The account whose on-chain balance to read. Defaults to the delegator
19761
- * address, which is the common case (the delegator grants permission to
19762
- * decrypt their own balance). Only set this when the account differs
19763
- * from the delegator.
19838
+ * Submit a token-scoped write transaction through the shared SDK transaction
19839
+ * pipeline. Callers keep pre-flight and operation-specific work local.
19764
19840
  *
19765
- * Matches the `account` parameter of `confidentialBalanceOf(account)` on-chain.
19841
+ * @internal
19766
19842
  */
19767
- accountAddress?: Address;
19768
- /** Maximum number of concurrent decrypt calls. Default: 10. */
19769
- maxConcurrency?: number;
19770
- /** Called when decryption fails for a single token. Return a fallback bigint. */
19771
- onError?: (error: Error, address: Address) => bigint;
19772
- }
19773
- /** Result of {@link Token.batchBalancesOf}. */
19774
- interface BatchBalancesResult {
19775
- /** Successfully decrypted balances, keyed by token address. */
19776
- results: Map<Address, bigint>;
19777
- /** Per-token errors for tokens that failed to decrypt. */
19778
- errors: Map<Address, ZamaError>;
19843
+ protected submitTransaction(params: {
19844
+ operation: TransactionOperation;
19845
+ config: WriteContractConfig;
19846
+ onSubmitted?: (txHash: Hex) => void;
19847
+ }): Promise<TransactionResult>;
19848
+ /** Verify all tokens share the same SDK instance and return it. */
19849
+ private static assertSameSdk;
19779
19850
  }
19851
+ //#endregion
19852
+ //#region src/token/wrapped-token.d.ts
19780
19853
  /**
19781
- * High-level interface for an ERC-7984 confidential token.
19782
- * Hides FHE complexity (encryption, decryption, EIP-712 signing) behind
19783
- * familiar ERC-20-like methods.
19854
+ * Confidential ERC-20 wrapper (ERC-7984 ERC20Wrapper).
19784
19855
  *
19785
- * For ERC-7984 wrappers (shield/unshield), use {@link WrappedToken} instead
19786
- * it extends `Token` with wrapper-specific operations.
19856
+ * Extends {@link Token} with wrapper-specific operations:
19857
+ * - `shield` / `unshield` convert between the underlying ERC-20 and confidential balance
19858
+ * - `unwrap` / `unwrapAll` / `finalizeUnwrap` — low-level two-phase primitives
19859
+ * - `underlying` / `allowance` — wrapper reads
19787
19860
  *
19788
- * Decryption, credentials, caching, and event emission are handled by the
19789
- * owning {@link ZamaSDK} — this class only exposes token-scoped helpers
19790
- * that delegate to `sdk.decryption.decryptValues` and `sdk.permits.grantPermit`.
19861
+ * `WrappedToken.address` is the wrapper contract address itself the wrapper
19862
+ * IS the confidential token.
19791
19863
  */
19792
- declare class Token {
19864
+ declare class WrappedToken extends Token {
19793
19865
  #private;
19794
- readonly sdk: ZamaSDK;
19795
- readonly address: Address;
19796
- constructor(sdk: ZamaSDK, address: Address);
19797
- /** Read the token name from the contract. */
19798
- name(): Promise<string>;
19799
- /** Read the token symbol from the contract. */
19800
- symbol(): Promise<string>;
19801
- /** Read the token decimals from the contract. */
19802
- decimals(): Promise<number>;
19803
19866
  /**
19804
- * ERC-165 check for {@link ERC7984_INTERFACE_ID} support.
19867
+ * Read the underlying ERC-20 token address from the wrapper contract.
19805
19868
  *
19806
- * @returns `true` if the contract implements the ERC-7984 confidential token interface.
19869
+ * @returns The underlying ERC-20 token address.
19807
19870
  */
19808
- isConfidential(): Promise<boolean>;
19871
+ underlying(): Promise<Address>;
19809
19872
  /**
19810
- * ERC-165 check for IERC7984ERC20Wrapper support.
19811
- *
19812
- * @returns `true` if the contract implements the ERC-7984 wrapper interface
19813
- * ({@link ERC7984_WRAPPER_INTERFACE_ID}, `0x1f1c62b2`).
19873
+ * Check whether the underlying ERC-20 supports ERC-1363 (payable token).
19874
+ * Result is cached per WrappedToken instance (negative results included):
19875
+ * once we know an underlying does not support ERC-1363, subsequent shields
19876
+ * go straight to the `approve` + `wrap` path without re-probing.
19814
19877
  */
19815
- isWrapper(): Promise<boolean>;
19878
+ isPayable(): Promise<boolean>;
19816
19879
  /**
19817
- * Decrypt and return the plaintext balance for the given owner.
19818
- * Acquires FHE credentials via a wallet signature if none are cached.
19819
- *
19820
- * @param owner - Balance owner address.
19821
- * @returns The decrypted plaintext balance as a bigint.
19822
- * @throws if FHE decryption fails. {@link DecryptionFailedError}
19880
+ * Read the ERC-20 allowance granted by `owner` to this wrapper for the
19881
+ * underlying token.
19823
19882
  *
19824
- * @example
19825
- * ```ts
19826
- * const balance = await token.balanceOf("0xOwner");
19827
- * ```
19883
+ * @param owner - The owner address whose allowance to read.
19884
+ * @returns The current allowance as a bigint.
19828
19885
  */
19829
- balanceOf(owner: Address): Promise<bigint>;
19886
+ allowance(owner: Address): Promise<bigint>;
19830
19887
  /**
19831
- * Return the raw encrypted balance without decrypting.
19888
+ * Shield public ERC-20 tokens into confidential tokens.
19832
19889
  *
19833
- * @param owner - Balance owner address.
19834
- * @returns The encrypted balance as a hex string.
19890
+ * The execution path is decided automatically by ERC-165 introspection on
19891
+ * the underlying ERC-20:
19892
+ * - **`transferAndCall`** (single tx): when the underlying supports
19893
+ * ERC-1363, no approval is required — the wrapper's `onTransferReceived`
19894
+ * callback mints confidential tokens directly. `approvalStrategy` is
19895
+ * **ignored** on this path. See {@link ShieldPath}.
19896
+ * - **`approveAndWrap`** (two-tx fallback): otherwise, an `approve` is
19897
+ * followed by a `wrap`. Approval is controlled by `approvalStrategy`
19898
+ * (`"exact"` by default, `"max"` for unlimited, `"skip"` to opt out).
19899
+ *
19900
+ * The ERC-20 balance is validated before submitting (public read, no
19901
+ * signing required) so the call works for all wallet types, including
19902
+ * smart wallets.
19903
+ *
19904
+ * @param amount - The plaintext amount to shield.
19905
+ * @param options - Optional: `approvalStrategy`, `to`, callbacks.
19906
+ * @returns The transaction hash and mined receipt.
19907
+ * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19908
+ * @throws if the ERC-20 balance is less than `amount`. {@link InsufficientERC20BalanceError}
19909
+ * @throws if the ERC-20 approval or shield transaction reverts. {@link TransactionRevertedError}
19835
19910
  *
19836
19911
  * @example
19837
19912
  * ```ts
19838
- * const encryptedValue = await token.confidentialBalanceOf("0xOwner");
19913
+ * const txHash = await wrappedToken.shield(1000n);
19839
19914
  * ```
19840
19915
  */
19841
- confidentialBalanceOf(owner: Address): Promise<EncryptedValue>;
19916
+ shield(amount: bigint, options?: ShieldOptions): Promise<TransactionResult>;
19842
19917
  /**
19843
- * Decrypt the balance of a delegator using delegated decryption credentials.
19844
- * The connected signer acts as the delegatee who has been granted permission
19845
- * by the delegator to decrypt their balance.
19846
- *
19847
- * Clear values are cached in storage keyed by `(account, token, encryptedValue)`.
19848
- * Because every on-chain balance change produces a new encrypted value,
19849
- * stale cache entries are never served. Cache write failures are silently
19850
- * ignored — they do not affect the returned value.
19918
+ * Approve this wrapper contract to spend the underlying ERC-20.
19919
+ * Defaults to max uint256. Resets to zero first if there's an existing
19920
+ * non-zero allowance (required by tokens like USDT).
19851
19921
  *
19852
- * @param delegatorAddress - The address of the account that delegated decryption rights.
19853
- * @param accountAddress - The account whose on-chain balance to read. Defaults
19854
- * to the delegator address.
19855
- * @returns The decrypted plaintext balance as a bigint.
19856
- * @throws if no active delegation exists. {@link DelegationNotFoundError}
19857
- * @throws if the delegation has expired. {@link DelegationExpiredError}
19858
- * @throws if delegated decryption fails. {@link DecryptionFailedError}
19922
+ * @param amount - Optional approval amount. Defaults to max uint256.
19923
+ * @returns The transaction hash and mined receipt.
19859
19924
  *
19860
19925
  * @example
19861
19926
  * ```ts
19862
- * const balance = await token.decryptBalanceAs({
19863
- * delegatorAddress: "0xDelegator",
19864
- * });
19927
+ * await wrappedToken.approveUnderlying(); // max approval
19928
+ * await wrappedToken.approveUnderlying(1000n); // exact amount
19865
19929
  * ```
19866
19930
  */
19867
- decryptBalanceAs({
19868
- delegatorAddress,
19869
- accountAddress
19870
- }: {
19871
- delegatorAddress: Address;
19872
- accountAddress?: Address;
19873
- }): Promise<bigint>;
19931
+ approveUnderlying(amount?: bigint): Promise<TransactionResult>;
19874
19932
  /**
19875
- * Decrypt confidential balances for multiple tokens in parallel, returning
19876
- * successes and per-token errors separately. Pre-authorizes all token
19877
- * addresses in a single wallet signature, then delegates each decrypt to
19878
- * `sdk.decryption.decryptValues`.
19933
+ * Unshield a specific amount and finalize in one call.
19934
+ * Orchestrates: unshield wait for receipt parse event → finalize.
19879
19935
  *
19880
- * Tokens that fail to decrypt land in `errors` rather than aborting the
19881
- * whole batch caller decides how to surface them.
19936
+ * By default, the SDK validates the confidential balance before submitting.
19937
+ * Set `skipBalanceCheck: true` to bypass this validation (e.g. for smart wallets).
19882
19938
  *
19883
- * @param tokens - Array of {@link Token} instances bound to the same SDK.
19884
- * @param owner - Balance owner address.
19885
- * @returns `{ results, errors }` partitioning the per-token outcomes.
19939
+ * @param amount - The plaintext amount to unshield.
19940
+ * @param options - Optional: `skipBalanceCheck` (default `false`), callbacks.
19941
+ * @returns The finalize transaction hash and mined receipt.
19886
19942
  *
19887
19943
  * @example
19888
19944
  * ```ts
19889
- * const { results, errors } = await Token.batchBalancesOf(tokens, owner);
19945
+ * const txHash = await wrappedToken.unshield(500n);
19890
19946
  * ```
19891
19947
  */
19892
- static batchBalancesOf(tokens: Token[], owner: Address): Promise<BatchBalancesResult>;
19948
+ unshield(amount: bigint, options?: UnshieldOptions): Promise<TransactionResult>;
19893
19949
  /**
19894
- * Batch decrypt confidential balances as a delegate across multiple tokens.
19895
- * Mirrors {@link batchBalancesOf} but uses delegated credentials.
19896
- *
19897
- * **Error handling:** If a per-token decryption fails and no `onError` callback
19898
- * is provided, errors are collected and thrown as an aggregated
19899
- * `DecryptionFailedError`. When the relayer returns no value for an encrypted value,
19900
- * a `DecryptionFailedError` is thrown for that token (never silently returns `0n`).
19901
- * Pass `onError: () => 0n` to opt into the silent zero behavior.
19950
+ * Unshield the entire balance and finalize in one call.
19951
+ * Orchestrates: unshieldAll wait for receipt → parse event → finalize.
19902
19952
  *
19903
- * @param tokens - Array of Token instances to decrypt balances for.
19904
- * @param options - Delegated decryption configuration.
19905
- * @returns A Map from token address to decrypted balance.
19906
- * @throws if no active delegation exists. {@link DelegationNotFoundError}
19907
- * @throws if the delegation has expired. {@link DelegationExpiredError}
19908
- * @throws if any decryption fails and no `onError` is provided. {@link DecryptionFailedError}
19953
+ * @param callbacks - Optional progress callbacks for each phase.
19954
+ * @returns The finalize transaction hash and mined receipt.
19955
+ * @throws if the balance is zero. {@link DecryptionFailedError}
19909
19956
  *
19910
19957
  * @example
19911
19958
  * ```ts
19912
- * const balances = await Token.batchDecryptBalancesAs(tokens, {
19913
- * delegatorAddress: "0xDelegator",
19914
- * onError: (err, addr) => { console.error(addr, err); return 0n; },
19915
- * });
19959
+ * const txHash = await wrappedToken.unshieldAll();
19916
19960
  * ```
19917
19961
  */
19918
- static batchDecryptBalancesAs(tokens: Token[], options: BatchDecryptAsOptions): Promise<Map<Address, bigint>>;
19919
- private static readBalanceHandlesBatch;
19962
+ unshieldAll(callbacks?: UnshieldCallbacks): Promise<TransactionResult>;
19920
19963
  /**
19921
- * Confidential transfer. Encrypts the amount via FHE, then calls the contract.
19922
- *
19923
- * By default, the SDK validates the confidential balance before submitting.
19924
- * If a cached plaintext balance exists it is used; otherwise, if credentials
19925
- * are cached, it decrypts on the fly. Set `skipBalanceCheck: true` to bypass
19926
- * this validation (e.g. for smart wallets).
19964
+ * Resume an in-progress unshield from an existing unwrap tx hash.
19965
+ * Useful when the user already submitted the unwrap but the finalize step
19966
+ * was interrupted (e.g. page reload, network error).
19927
19967
  *
19928
- * @param to - Recipient address.
19929
- * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).
19930
- * @param options - Optional: `skipBalanceCheck` (default `false`).
19931
- * @returns The transaction hash and mined receipt.
19932
- * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19933
- * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}
19934
- * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}
19935
- * @throws if FHE encryption fails. {@link EncryptionFailedError}
19936
- * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}
19968
+ * @param unwrapTxHash - The transaction hash of the previously submitted unwrap.
19969
+ * @param callbacks - Optional progress callbacks.
19970
+ * @returns The finalize transaction hash and mined receipt.
19937
19971
  *
19938
19972
  * @example
19939
19973
  * ```ts
19940
- * const txHash = await token.confidentialTransfer("0xRecipient", 1000n);
19974
+ * const txHash = await wrappedToken.resumeUnshield(previousUnwrapTxHash);
19941
19975
  * ```
19942
19976
  */
19943
- confidentialTransfer(to: Address, amount: bigint, options?: TransferOptions): Promise<TransactionResult>;
19977
+ resumeUnshield(unwrapTxHash: Hex, callbacks?: UnshieldCallbacks): Promise<TransactionResult>;
19944
19978
  /**
19945
- * Operator encrypted transfer on behalf of another address.
19946
- * The caller must be an approved operator for `from`.
19979
+ * Return the unwrap tx hash of an unshield that was interrupted between its
19980
+ * two phases, or `null` if none is pending for this wrapper.
19947
19981
  *
19948
- * @param from - The address to transfer from (caller must be an approved operator).
19949
- * @param to - Recipient address.
19950
- * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).
19951
- * @returns The transaction hash and mined receipt.
19982
+ * The SDK persists this automatically when {@link unshield}/{@link unshieldAll}
19983
+ * submit phase 1, and clears it once phase 2 finalizes. Use the returned hash
19984
+ * to surface a "resume" affordance, then pass it to {@link resumeUnshield}.
19985
+ * Resuming is intentionally caller-driven auto-resuming on load would fire a
19986
+ * wallet transaction unprompted.
19987
+ *
19988
+ * @returns The pending unwrap tx hash, or `null`.
19952
19989
  *
19953
19990
  * @example
19954
19991
  * ```ts
19955
- * const txHash = await token.confidentialTransferFrom("0xFrom", "0xTo", 500n);
19992
+ * const unwrapTxHash = await wrappedToken.getPendingUnshield();
19993
+ * if (unwrapTxHash) await wrappedToken.resumeUnshield(unwrapTxHash);
19956
19994
  * ```
19957
19995
  */
19958
- confidentialTransferFrom(from: Address, to: Address, amount: bigint, callbacks?: TransferCallbacks): Promise<TransactionResult>;
19996
+ getPendingUnshield(): Promise<Hex | null>;
19959
19997
  /**
19960
- * ERC-7984 `confidentialTransferAndCall`: encrypted transfer that also invokes
19961
- * the recipient's receiver hook (`onConfidentialTransferReceived`) in a single
19962
- * transaction. The caller crafts the opaque `data` payload — the SDK does not
19963
- * encode, validate, or interpret it.
19964
- *
19965
- * Balance validation follows the same rules as {@link Token.confidentialTransfer}.
19998
+ * Request an unwrap for a specific amount. Encrypts the amount first.
19999
+ * Call {@link finalizeUnwrap} after the request is processed on-chain.
19966
20000
  *
19967
- * @param to - Recipient address. Must implement the ERC-7984 receiver hook.
19968
- * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).
19969
- * @param data - Opaque bytes forwarded to the recipient's receiver hook.
19970
- * @param options - Optional: `skipBalanceCheck` (default `false`).
20001
+ * @param amount - The plaintext amount to unwrap (encrypted automatically).
19971
20002
  * @returns The transaction hash and mined receipt.
19972
20003
  *
19973
- * @throws if signer and provider are on different chains. {@link ChainMismatchError}
19974
- * @throws if the balance is less than `amount`. {@link InsufficientConfidentialBalanceError}
19975
- * @throws if balance validation requires decryption that is not possible. {@link BalanceCheckUnavailableError}
19976
- * @throws if FHE encryption fails. {@link EncryptionFailedError}
19977
- * @throws if the on-chain transfer reverts. {@link TransactionRevertedError}
19978
- *
19979
20004
  * @example
19980
20005
  * ```ts
19981
- * const txHash = await token.confidentialTransferAndCall(
19982
- * "0xRecipient",
19983
- * 1000n,
19984
- * "0xabcd", // caller-encoded payload forwarded to the receiver hook
19985
- * );
20006
+ * const txHash = await wrappedToken.unwrap(500n);
19986
20007
  * ```
19987
20008
  */
19988
- confidentialTransferAndCall(to: Address, amount: bigint, data: Hex, options?: TransferOptions): Promise<TransactionResult>;
20009
+ unwrap(amount: bigint): Promise<TransactionResult>;
19989
20010
  /**
19990
- * ERC-7984 `confidentialTransferFromAndCall`: operator-initiated encrypted
19991
- * transfer that also invokes the recipient's receiver hook in a single
19992
- * transaction. The caller must be an approved operator for `from` and crafts
19993
- * the opaque `data` payload — the SDK does not encode or interpret it.
20011
+ * Request an unwrap for the entire confidential balance.
20012
+ * Uses the on-chain encrypted balance directly (no encryption needed).
20013
+ * Throws if the balance is zero.
19994
20014
  *
19995
- * @param from - The address to transfer from (caller must be an approved operator).
19996
- * @param to - Recipient address. Must implement the ERC-7984 receiver hook.
19997
- * @param amount - Plaintext amount to transfer (encrypted automatically via FHE).
19998
- * @param data - Opaque bytes forwarded to the recipient's receiver hook.
19999
- * @param callbacks - Optional progress callbacks.
20000
20015
  * @returns The transaction hash and mined receipt.
20016
+ * @throws if the balance is zero. {@link DecryptionFailedError}
20001
20017
  *
20002
20018
  * @example
20003
20019
  * ```ts
20004
- * const txHash = await token.confidentialTransferFromAndCall(
20005
- * "0xFrom",
20006
- * "0xRecipient",
20007
- * 500n,
20008
- * "0xabcd",
20009
- * );
20020
+ * const txHash = await wrappedToken.unwrapAll();
20010
20021
  * ```
20011
20022
  */
20012
- confidentialTransferFromAndCall(from: Address, to: Address, amount: bigint, data: Hex, callbacks?: TransferCallbacks): Promise<TransactionResult>;
20023
+ unwrapAll(): Promise<TransactionResult>;
20013
20024
  /**
20014
- * Set operator approval for the confidential token.
20015
- * Defaults to 1 hour from now if `until` is not specified.
20025
+ * Complete an unwrap by providing the public decryption proof.
20026
+ * Call this after an unshield request has been processed on-chain.
20016
20027
  *
20017
- * @param operator - The address to set as an operator.
20018
- * @param until - Optional Unix timestamp for approval expiry. Defaults to now + 1 hour.
20028
+ * @param unwrapRequestId - `unwrapRequestId` from the `UnwrapRequested` event.
20019
20029
  * @returns The transaction hash and mined receipt.
20020
20030
  *
20021
20031
  * @example
20022
20032
  * ```ts
20023
- * const txHash = await token.setOperator("0xOperator");
20033
+ * const event = findUnwrapRequested(receipt.logs);
20034
+ * const txHash = await wrappedToken.finalizeUnwrap(event.unwrapRequestId);
20024
20035
  * ```
20025
20036
  */
20026
- setOperator(operator: Address, until?: number): Promise<TransactionResult>;
20027
- /**
20028
- * Check if a spender is an approved operator for a given holder.
20029
- *
20030
- * @param holder - The token holder address.
20031
- * @param spender - The address to check operator approval for.
20032
- * @returns `true` if the spender is an approved operator for the holder.
20033
- *
20034
- * @example
20035
- * ```ts
20036
- * if (await token.isOperator("0xHolder", "0xSpender")) {
20037
- * // spender can call transferFrom on behalf of holder
20038
- * }
20039
- * ```
20040
- */
20041
- isOperator(holder: Address, spender: Address): Promise<boolean>;
20042
- /**
20043
- * Read the on-chain encrypted balance for a given owner.
20044
- *
20045
- * @internal
20046
- */
20047
- protected readConfidentialBalanceOf(owner: Address): Promise<EncryptedValue>;
20037
+ finalizeUnwrap(unwrapRequestId: EncryptedValue): Promise<TransactionResult>;
20038
+ }
20039
+ //#endregion
20040
+ //#region src/query/confidential-balance.d.ts
20041
+ interface ConfidentialBalanceQueryConfig {
20042
+ tokenAddress: Address;
20043
+ account?: Address;
20044
+ query?: Record<string, unknown>;
20045
+ }
20046
+ /** Query options for a single confidential token balance. Auto-gated on `account`. */
20047
+ declare function confidentialBalanceQueryOptions(token: Token, config: ConfidentialBalanceQueryConfig, signerContext?: SignerQueryContext): QueryFactoryOptions<bigint, Error, bigint, ReturnType<typeof zamaQueryKeys.confidentialBalance.owner>>;
20048
+ //#endregion
20049
+ //#region src/query/confidential-balances.d.ts
20050
+ interface ConfidentialBalancesQueryConfig {
20051
+ account?: Address;
20052
+ query?: Record<string, unknown>;
20053
+ }
20054
+ declare function confidentialBalancesQueryOptions(tokens: Token[], config?: ConfidentialBalancesQueryConfig, signerContext?: SignerQueryContext): QueryFactoryOptions<BatchBalancesResult, Error, BatchBalancesResult, ReturnType<typeof zamaQueryKeys.confidentialBalances.tokens>>;
20055
+ //#endregion
20056
+ //#region src/query/wrappers-registry.d.ts
20057
+ interface WrappersRegistryQueryConfig {
20058
+ registryAddress: Address | undefined;
20059
+ query?: Record<string, unknown>;
20060
+ }
20061
+ declare function tokenPairsQueryOptions(sdk: ZamaSDK, config: WrappersRegistryQueryConfig): QueryFactoryOptions<readonly TokenWrapperPair[], Error, readonly TokenWrapperPair[], ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairs>>;
20062
+ interface ConfidentialTokenAddressQueryConfig extends WrappersRegistryQueryConfig {
20063
+ tokenAddress?: Address;
20064
+ }
20065
+ declare function confidentialTokenAddressQueryOptions(sdk: ZamaSDK, config: ConfidentialTokenAddressQueryConfig): QueryFactoryOptions<readonly [boolean, Address], Error, readonly [boolean, Address], ReturnType<typeof zamaQueryKeys.wrappersRegistry.confidentialTokenAddress>>;
20066
+ interface TokenAddressQueryConfig extends WrappersRegistryQueryConfig {
20067
+ confidentialTokenAddress?: Address;
20068
+ }
20069
+ declare function tokenAddressQueryOptions(sdk: ZamaSDK, config: TokenAddressQueryConfig): QueryFactoryOptions<readonly [boolean, Address], Error, readonly [boolean, Address], ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenAddress>>;
20070
+ declare function tokenPairsLengthQueryOptions(sdk: ZamaSDK, config: WrappersRegistryQueryConfig): QueryFactoryOptions<bigint, Error, bigint, ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairsLength>>;
20071
+ interface TokenPairsSliceQueryConfig extends WrappersRegistryQueryConfig {
20072
+ fromIndex?: bigint;
20073
+ toIndex?: bigint;
20074
+ }
20075
+ declare function tokenPairsSliceQueryOptions(sdk: ZamaSDK, config: TokenPairsSliceQueryConfig): QueryFactoryOptions<readonly TokenWrapperPair[], Error, readonly TokenWrapperPair[], ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPairsSlice>>;
20076
+ interface TokenPairQueryConfig extends WrappersRegistryQueryConfig {
20077
+ index?: bigint;
20078
+ }
20079
+ declare function tokenPairQueryOptions(sdk: ZamaSDK, config: TokenPairQueryConfig): QueryFactoryOptions<TokenWrapperPair, Error, TokenWrapperPair, ReturnType<typeof zamaQueryKeys.wrappersRegistry.tokenPair>>;
20080
+ interface IsConfidentialTokenValidQueryConfig extends WrappersRegistryQueryConfig {
20081
+ confidentialTokenAddress?: Address;
20082
+ }
20083
+ declare function isConfidentialTokenValidQueryOptions(sdk: ZamaSDK, config: IsConfidentialTokenValidQueryConfig): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.wrappersRegistry.isConfidentialTokenValid>>;
20084
+ interface ListPairsQueryConfig {
20048
20085
  /**
20049
- * Pre-flight check: decrypt the confidential balance and compare against the
20050
- * requested amount. If credentials are cached the decrypt happens silently;
20051
- * if not, throws {@link BalanceCheckUnavailableError} instead of triggering
20052
- * a surprise EIP-712 popup.
20053
- *
20054
- * @internal
20086
+ * The registry address for this chain used as a query key discriminator.
20087
+ * The registry instance already knows how to resolve the address for the
20088
+ * current chain; this field just keeps the TanStack Query cache isolated
20089
+ * per registry contract.
20055
20090
  */
20056
- protected assertConfidentialBalance(amount: bigint): Promise<void>;
20091
+ registryAddress: Address | undefined;
20092
+ page?: number;
20093
+ pageSize?: number;
20094
+ metadata?: boolean;
20095
+ query?: Record<string, unknown>;
20096
+ }
20097
+ /**
20098
+ * Query options for paginated listing of token wrapper pairs.
20099
+ *
20100
+ * Accepts a {@link WrappersRegistry} instance rather than a raw provider so that the
20101
+ * class-level TTL cache is shared across multiple `queryFn` executions. Pass
20102
+ * `sdk.registry` (the ZamaSDK lazy singleton) to ensure a single shared cache.
20103
+ */
20104
+ declare function listPairsQueryOptions(registry: WrappersRegistry, config: ListPairsQueryConfig): QueryFactoryOptions<PaginatedResult<TokenWrapperPair | TokenWrapperPairWithMetadata>, Error, PaginatedResult<TokenWrapperPair | TokenWrapperPairWithMetadata>, ReturnType<typeof zamaQueryKeys.wrappersRegistry.listPairs>>;
20105
+ //#endregion
20106
+ //#region src/query/shield.d.ts
20107
+ /** Variables for {@link shieldMutationOptions}. */
20108
+ interface ShieldParams extends ShieldOptions {
20109
+ amount: bigint;
20110
+ }
20111
+ declare function shieldMutationOptions(token: WrappedToken): MutationFactoryOptions<readonly ["zama.shield", Address], ShieldParams, TransactionResult>;
20112
+ //#endregion
20113
+ //#region src/query/transfer.d.ts
20114
+ /** Variables for {@link confidentialTransferMutationOptions}. */
20115
+ interface ConfidentialTransferParams extends TransferOptions {
20116
+ to: Address;
20117
+ amount: bigint;
20118
+ }
20119
+ declare function confidentialTransferMutationOptions(token: Token): MutationFactoryOptions<readonly ["zama.confidentialTransfer", Address], ConfidentialTransferParams, TransactionResult>;
20120
+ //#endregion
20121
+ //#region src/query/transfer-and-call.d.ts
20122
+ /** Variables for {@link confidentialTransferAndCallMutationOptions}. */
20123
+ interface ConfidentialTransferAndCallParams extends TransferOptions {
20124
+ to: Address;
20125
+ amount: bigint;
20126
+ /** Opaque bytes forwarded to the recipient's ERC-7984 receiver hook. */
20127
+ data: Hex;
20128
+ }
20129
+ declare function confidentialTransferAndCallMutationOptions(token: Token): MutationFactoryOptions<readonly ["zama.confidentialTransferAndCall", Address], ConfidentialTransferAndCallParams, TransactionResult>;
20130
+ //#endregion
20131
+ //#region src/query/transfer-from.d.ts
20132
+ /** Variables for {@link confidentialTransferFromMutationOptions}. */
20133
+ interface ConfidentialTransferFromParams {
20134
+ from: Address;
20135
+ to: Address;
20136
+ amount: bigint;
20137
+ /** Optional progress callbacks for the multi-step transfer flow. */
20138
+ callbacks?: TransferCallbacks;
20139
+ }
20140
+ declare function confidentialTransferFromMutationOptions(token: Token): MutationFactoryOptions<readonly ["zama.confidentialTransferFrom", Address], ConfidentialTransferFromParams, TransactionResult>;
20141
+ //#endregion
20142
+ //#region src/query/transfer-from-and-call.d.ts
20143
+ /** Variables for {@link confidentialTransferFromAndCallMutationOptions}. */
20144
+ interface ConfidentialTransferFromAndCallParams {
20145
+ from: Address;
20146
+ to: Address;
20147
+ amount: bigint;
20148
+ /** Opaque bytes forwarded to the recipient's ERC-7984 receiver hook. */
20149
+ data: Hex;
20150
+ /** Optional progress callbacks for the multi-step transfer flow. */
20151
+ callbacks?: TransferCallbacks;
20152
+ }
20153
+ declare function confidentialTransferFromAndCallMutationOptions(token: Token): MutationFactoryOptions<readonly ["zama.confidentialTransferFromAndCall", Address], ConfidentialTransferFromAndCallParams, TransactionResult>;
20154
+ //#endregion
20155
+ //#region src/query/set-operator.d.ts
20156
+ /** Variables for {@link confidentialSetOperatorMutationOptions}. */
20157
+ interface ConfidentialSetOperatorParams {
20158
+ operator: Address;
20159
+ until?: number;
20160
+ }
20161
+ declare function confidentialSetOperatorMutationOptions(token: Token): MutationFactoryOptions<readonly ["zama.confidentialSetOperator", Address], ConfidentialSetOperatorParams, TransactionResult>;
20162
+ //#endregion
20163
+ //#region src/query/approve-underlying.d.ts
20164
+ /** Variables for {@link approveUnderlyingMutationOptions}. */
20165
+ interface ApproveUnderlyingParams {
20166
+ amount?: bigint;
20167
+ }
20168
+ declare function approveUnderlyingMutationOptions(token: WrappedToken): MutationFactoryOptions<readonly ["zama.approveUnderlying", Address], ApproveUnderlyingParams, TransactionResult>;
20169
+ //#endregion
20170
+ //#region src/query/unshield.d.ts
20171
+ /** Variables for {@link unshieldMutationOptions}. */
20172
+ interface UnshieldParams extends UnshieldOptions {
20173
+ amount: bigint;
20174
+ }
20175
+ declare function unshieldMutationOptions(token: WrappedToken): MutationFactoryOptions<readonly ["zama.unshield", Address], UnshieldParams, TransactionResult>;
20176
+ //#endregion
20177
+ //#region src/query/unshield-all.d.ts
20178
+ /** Variables for {@link unshieldAllMutationOptions}. */
20179
+ interface UnshieldAllParams extends UnshieldCallbacks {}
20180
+ declare function unshieldAllMutationOptions(token: WrappedToken): MutationFactoryOptions<readonly ["zama.unshieldAll", Address], UnshieldAllParams | void, TransactionResult>;
20181
+ //#endregion
20182
+ //#region src/query/resume-unshield.d.ts
20183
+ /** Variables for {@link resumeUnshieldMutationOptions}. */
20184
+ interface ResumeUnshieldParams extends UnshieldCallbacks {
20185
+ unwrapTxHash: Hex;
20186
+ }
20187
+ declare function resumeUnshieldMutationOptions(token: WrappedToken): MutationFactoryOptions<readonly ["zama.resumeUnshield", Address], ResumeUnshieldParams, TransactionResult>;
20188
+ //#endregion
20189
+ //#region src/query/unwrap.d.ts
20190
+ /** Variables for {@link unwrapMutationOptions}. */
20191
+ interface UnwrapParams {
20192
+ amount: bigint;
20193
+ }
20194
+ declare function unwrapMutationOptions(token: WrappedToken): MutationFactoryOptions<readonly ["zama.unwrap", Address], UnwrapParams, TransactionResult>;
20195
+ //#endregion
20196
+ //#region src/query/unwrap-all.d.ts
20197
+ declare function unwrapAllMutationOptions(token: WrappedToken): MutationFactoryOptions<readonly ["zama.unwrapAll", Address], void, TransactionResult>;
20198
+ //#endregion
20199
+ //#region src/query/finalize-unwrap.d.ts
20200
+ /** Variables for {@link finalizeUnwrapMutationOptions}. */
20201
+ type FinalizeUnwrapParams = {
20202
+ /** Identifier from an `UnwrapRequested` event. */unwrapRequestId: EncryptedValue;
20203
+ };
20204
+ declare function finalizeUnwrapMutationOptions(token: WrappedToken): MutationFactoryOptions<readonly ["zama.finalizeUnwrap", Address], FinalizeUnwrapParams, TransactionResult>;
20205
+ //#endregion
20206
+ //#region src/query/encrypt.d.ts
20207
+ declare function encryptMutationOptions(sdk: ZamaSDK): MutationFactoryOptions<readonly ["zama.encrypt"], EncryptParams, EncryptResult>;
20208
+ //#endregion
20209
+ //#region src/query/user-decrypt.d.ts
20210
+ interface EncryptedInput {
20211
+ encryptedValue: EncryptedValue;
20212
+ contractAddress: Address;
20213
+ }
20214
+ /** Decrypted clear values keyed by encrypted handle. */
20215
+ type DecryptResult = Readonly<Record<EncryptedValue, ClearValue>>;
20216
+ declare function decryptValuesQueryOptions(sdk: ZamaSDK, encryptedInputs: EncryptedInput[], signerContext?: SignerQueryContext): QueryFactoryOptions<DecryptResult, Error, DecryptResult, ReturnType<typeof zamaQueryKeys.decryption.encryptedInputs>>;
20217
+ //#endregion
20218
+ //#region src/query/delegated-decrypt.d.ts
20219
+ interface DelegatedDecryptValuesMutationParams {
20220
+ encryptedInputs: EncryptedInput[];
20221
+ delegatorAddress: Address;
20222
+ }
20223
+ declare function delegatedDecryptValuesMutationOptions(sdk: ZamaSDK): MutationFactoryOptions<readonly ["zama.delegatedDecryptValues"], DelegatedDecryptValuesMutationParams, Readonly<Record<EncryptedValue, ClearValue>>>;
20224
+ //#endregion
20225
+ //#region src/query/public-decrypt.d.ts
20226
+ declare function decryptPublicValuesMutationOptions(sdk: ZamaSDK): MutationFactoryOptions<readonly ["zama.decryptPublicValues"], EncryptedValue[], DecryptPublicValuesResult>;
20227
+ //#endregion
20228
+ //#region src/query/grant-permit.d.ts
20229
+ declare function grantPermitMutationOptions(sdk: ZamaSDK): MutationFactoryOptions<readonly ["zama.grantPermit"], Address[], void>;
20230
+ //#endregion
20231
+ //#region src/query/has-permit.d.ts
20232
+ interface HasPermitQueryConfig {
20233
+ /** Contract addresses to check credentials against. */
20234
+ contractAddresses: Address[];
20057
20235
  /**
20058
- * Emit a token-scoped event through the owning {@link ZamaSDK} so that
20059
- * subscribers see a unified stream.
20060
- *
20061
- * @internal
20236
+ * Standard TanStack query options. `hasPermit` intentionally overrides cache
20237
+ * timing because permit state is wallet-local, not server state: every fetch
20238
+ * should read the SDK credential service directly.
20062
20239
  */
20063
- protected emit(input: ZamaSDKEventInput): void;
20064
- /**
20065
- * Submit a token-scoped write transaction through the shared SDK transaction
20066
- * pipeline. Callers keep pre-flight and operation-specific work local.
20067
- *
20068
- * @internal
20069
- */
20070
- protected submitTransaction(params: {
20071
- operation: TransactionOperation;
20072
- config: WriteContractConfig;
20073
- onSubmitted?: (txHash: Hex) => void;
20074
- }): Promise<TransactionResult>;
20075
- /** Verify all tokens share the same SDK instance and return it. */
20076
- private static assertSameSdk;
20240
+ query?: Record<string, unknown>;
20077
20241
  }
20242
+ declare function hasPermitQueryOptions(sdk: ZamaSDK, config: HasPermitQueryConfig, signerContext?: SignerQueryContext): QueryFactoryOptions<boolean, Error, boolean, ReturnType<typeof zamaQueryKeys.hasPermit.scope>>;
20078
20243
  //#endregion
20079
- //#region src/token/wrapped-token.d.ts
20244
+ //#region src/query/revoke-permits.d.ts
20245
+ /** TanStack Query mutation factory for {@link Permits.revokePermits}. */
20246
+ declare function revokePermitsMutationOptions(sdk: ZamaSDK): MutationFactoryOptions<readonly ["zama.revokePermits"], Address[] | void, void>;
20247
+ //#endregion
20248
+ //#region src/query/clear-credentials.d.ts
20249
+ /** TanStack Query mutation factory for {@link Permits.clear}. */
20250
+ declare function clearCredentialsMutationOptions(sdk: ZamaSDK): MutationFactoryOptions<readonly ["zama.clearCredentials"], void, void>;
20251
+ //#endregion
20252
+ //#region src/query/delegate-decryption.d.ts
20253
+ /** Variables for {@link delegateDecryptionMutationOptions}. */
20254
+ interface DelegateDecryptionParams {
20255
+ delegateAddress: Address;
20256
+ expirationDate?: Date;
20257
+ }
20258
+ declare function delegateDecryptionMutationOptions(sdk: ZamaSDK, contractAddress: Address): MutationFactoryOptions<readonly ["zama.delegateDecryption", Address], DelegateDecryptionParams, TransactionResult>;
20259
+ //#endregion
20260
+ //#region src/query/decrypt-balance-as.d.ts
20261
+ /** Variables for {@link decryptBalanceAsMutationOptions}. */
20262
+ interface DecryptBalanceAsParams {
20263
+ delegatorAddress: Address;
20264
+ accountAddress?: Address;
20265
+ }
20266
+ declare function decryptBalanceAsMutationOptions(token: Token): MutationFactoryOptions<readonly ["zama.decryptBalanceAs", Address], DecryptBalanceAsParams, bigint>;
20267
+ //#endregion
20268
+ //#region src/query/batch-decrypt-balances-as.d.ts
20269
+ /** Variables for {@link batchDecryptBalancesAsMutationOptions}. */
20270
+ type BatchDecryptBalancesAsParams = BatchDecryptAsOptions;
20271
+ declare function batchDecryptBalancesAsMutationOptions(tokens: Token[]): MutationFactoryOptions<readonly ["zama.batchDecryptBalancesAs", ...Address[]], BatchDecryptBalancesAsParams, Map<Address, bigint>>;
20272
+ //#endregion
20273
+ //#region src/query/revoke-delegation.d.ts
20274
+ /** Variables for {@link revokeDelegationMutationOptions}. */
20275
+ interface RevokeDelegationParams {
20276
+ delegateAddress: Address;
20277
+ }
20278
+ declare function revokeDelegationMutationOptions(sdk: ZamaSDK, contractAddress: Address): MutationFactoryOptions<readonly ["zama.revokeDelegation", Address], RevokeDelegationParams, TransactionResult>;
20279
+ //#endregion
20280
+ //#region src/query/delegation-status.d.ts
20281
+ interface DelegationStatusData {
20282
+ isActive: boolean;
20283
+ expiryTimestamp: bigint;
20284
+ }
20285
+ interface DelegationStatusQueryConfig {
20286
+ contractAddress: Address | undefined;
20287
+ delegatorAddress?: Address;
20288
+ delegateAddress?: Address;
20289
+ query?: Record<string, unknown>;
20290
+ }
20291
+ declare function delegationStatusQueryOptions(sdk: ZamaSDK, config: DelegationStatusQueryConfig): QueryFactoryOptions<DelegationStatusData, Error, DelegationStatusData, ReturnType<typeof zamaQueryKeys.delegationStatus.scope>>;
20292
+ //#endregion
20293
+ //#region src/credentials/credential-service.d.ts
20294
+ /** Configuration for {@link CredentialService}. TTLs are pre-validated by the caller. */
20295
+ interface CredentialServiceConfig {
20296
+ router: ChainRouter;
20297
+ signer: GenericSigner;
20298
+ /** Transport key pair lifetime in seconds. Pre-validated. */
20299
+ transportKeyPairTTL: number;
20300
+ /** Permit lifetime in days. Pre-validated. */
20301
+ permitTTL: number;
20302
+ /** Backing storage for transport key pairs (and permits if `permitStorage` is omitted). */
20303
+ storage: GenericStorage;
20304
+ /** Optional dedicated storage for permits; defaults to `storage`. */
20305
+ permitStorage?: GenericStorage;
20306
+ /** SDK-wide logger for credential-path diagnostics. */
20307
+ logger: GenericLogger;
20308
+ }
20080
20309
  /**
20081
- * Confidential ERC-20 wrapper (ERC-7984 ERC20Wrapper).
20082
- *
20083
- * Extends {@link Token} with wrapper-specific operations:
20084
- * - `shield` / `unshield` — convert between the underlying ERC-20 and confidential balance
20085
- * - `unwrap` / `unwrapAll` / `finalizeUnwrap` — low-level two-phase primitives
20086
- * - `underlying` / `allowance` — wrapper reads
20310
+ * Single facade coordinating the keypair vault and the permission store.
20087
20311
  *
20088
- * `WrappedToken.address` is the wrapper contract address itself the wrapper
20089
- * IS the confidential token.
20312
+ * `CredentialService` is the only credentials object held by `ZamaSDK`. It accepts identity
20313
+ * transitions via `handleWalletAccountChange`.
20090
20314
  */
20091
- declare class WrappedToken extends Token {
20315
+ declare class CredentialService {
20092
20316
  #private;
20317
+ constructor(config: CredentialServiceConfig);
20093
20318
  /**
20094
- * Read the underlying ERC-20 token address from the wrapper contract.
20319
+ * Resolve a keypair and permissions covering `contracts`, minimizing wallet
20320
+ * prompts by reusing or widening existing permits where possible. Empty
20321
+ * `contracts` warms the keypair without prompting.
20095
20322
  *
20096
- * @returns The underlying ERC-20 token address.
20323
+ * @returns The resolved keypair and permits covering the requested contracts.
20324
+ * @throws if the user rejects a wallet signature prompt. {@link SigningRejectedError}
20325
+ * @throws if signing fails for any other reason. {@link SigningFailedError}
20097
20326
  */
20098
- underlying(): Promise<Address>;
20327
+ grantPermit(contracts: readonly Address[], delegator?: Address): Promise<SerializedTransportKeyPairWithPermissions>;
20099
20328
  /**
20100
- * Check whether the underlying ERC-20 supports ERC-1363 (payable token).
20101
- * Result is cached per WrappedToken instance (negative results included):
20102
- * once we know an underlying does not support ERC-1363, subsequent shields
20103
- * go straight to the `approve` + `wrap` path without re-probing.
20104
- */
20105
- isPayable(): Promise<boolean>;
20106
- /**
20107
- * Read the ERC-20 allowance granted by `owner` to this wrapper for the
20108
- * underlying token.
20329
+ * Pure store lookup: are stored permits sufficient to cover `contracts`? No wallet prompt.
20109
20330
  *
20110
- * @param owner - The owner address whose allowance to read.
20111
- * @returns The current allowance as a bigint.
20331
+ * @returns `true` if cached permits cover all requested contracts (vacuously
20332
+ * true for an empty list); `false` if no keypair exists or coverage is
20333
+ * incomplete.
20112
20334
  */
20113
- allowance(owner: Address): Promise<bigint>;
20335
+ hasPermit(contracts: readonly Address[], delegator?: Address): Promise<boolean>;
20114
20336
  /**
20115
- * Shield public ERC-20 tokens into confidential tokens.
20116
- *
20117
- * The execution path is decided automatically by ERC-165 introspection on
20118
- * the underlying ERC-20:
20119
- * - **`transferAndCall`** (single tx): when the underlying supports
20120
- * ERC-1363, no approval is required — the wrapper's `onTransferReceived`
20121
- * callback mints confidential tokens directly. `approvalStrategy` is
20122
- * **ignored** on this path. See {@link ShieldPath}.
20123
- * - **`approveAndWrap`** (two-tx fallback): otherwise, an `approve` is
20124
- * followed by a `wrap`. Approval is controlled by `approvalStrategy`
20125
- * (`"exact"` by default, `"max"` for unlimited, `"skip"` to opt out).
20126
- *
20127
- * The ERC-20 balance is validated before submitting (public read, no
20128
- * signing required) so the call works for all wallet types, including
20129
- * smart wallets.
20337
+ * Wipe FHE permits for the current signer.
20130
20338
  *
20131
- * @param amount - The plaintext amount to shield.
20132
- * @param options - Optional: `approvalStrategy`, `to`, callbacks.
20133
- * @returns The transaction hash and mined receipt.
20134
- * @throws if signer and provider are on different chains. {@link ChainMismatchError}
20135
- * @throws if the ERC-20 balance is less than `amount`. {@link InsufficientERC20BalanceError}
20136
- * @throws if the ERC-20 approval or shield transaction reverts. {@link TransactionRevertedError}
20339
+ * - With no argument: every permit referencing this signer is removed across
20340
+ * all chains and delegators. The keypair survives — use
20341
+ * {@link clearCredentials} to also wipe the keypair.
20342
+ * - With a contract list: every signed permit in the direct-decrypt scope
20343
+ * (current chain) whose immutable payload touches any listed address is
20344
+ * removed. Delegated permits are not touched in this mode.
20137
20345
  *
20138
- * @example
20139
- * ```ts
20140
- * const txHash = await wrappedToken.shield(1000n);
20141
- * ```
20346
+ * @throws if reading the signer address fails. {@link SigningFailedError}
20142
20347
  */
20143
- shield(amount: bigint, options?: ShieldOptions): Promise<TransactionResult>;
20348
+ revokePermits(contracts?: readonly Address[]): Promise<void>;
20144
20349
  /**
20145
- * Approve this wrapper contract to spend the underlying ERC-20.
20146
- * Defaults to max uint256. Resets to zero first if there's an existing
20147
- * non-zero allowance (required by tokens like USDT).
20148
- *
20149
- * @param amount - Optional approval amount. Defaults to max uint256.
20150
- * @returns The transaction hash and mined receipt.
20350
+ * Wipe the keypair for the current signer and cascade-delete every
20351
+ * permission referencing it across all chains and delegators.
20151
20352
  *
20152
- * @example
20153
- * ```ts
20154
- * await wrappedToken.approveUnderlying(); // max approval
20155
- * await wrappedToken.approveUnderlying(1000n); // exact amount
20156
- * ```
20353
+ * @throws if reading the signer address fails. {@link SigningFailedError}
20157
20354
  */
20158
- approveUnderlying(amount?: bigint): Promise<TransactionResult>;
20355
+ clearCredentials(): Promise<void>;
20159
20356
  /**
20160
- * Unshield a specific amount and finalize in one call.
20161
- * Orchestrates: unshield → wait for receipt → parse event → finalize.
20162
- *
20163
- * By default, the SDK validates the confidential balance before submitting.
20164
- * Set `skipBalanceCheck: true` to bypass this validation (e.g. for smart wallets).
20357
+ * Warm the signer transport key pair cache for a known address.
20165
20358
  *
20166
- * @param amount - The plaintext amount to unshield.
20167
- * @param options - Optional: `skipBalanceCheck` (default `false`), callbacks.
20168
- * @returns The finalize transaction hash and mined receipt.
20359
+ * Best-effort prefetch primitive: correctness still comes from `grantPermit`,
20360
+ * which lazily creates the transport key pair when needed. Errors (storage failure,
20361
+ * relayer 4xx, missing Worker in SSR) are **not** swallowed here — the caller
20362
+ * decides whether to log, ignore, or surface them.
20363
+ */
20364
+ warmTransportKeyPair(address: Address): Promise<void>;
20365
+ /**
20366
+ * Apply a wallet account transition.
20169
20367
  *
20170
- * @example
20171
- * ```ts
20172
- * const txHash = await wrappedToken.unshield(500n);
20173
- * ```
20368
+ * Address change clears persisted credentials for the previous account.
20369
+ * Chain-only changes keep credentials intact because permits are chain-scoped
20370
+ * already and stale decrypt plaintext is cleared by `ZamaSDK`.
20174
20371
  */
20175
- unshield(amount: bigint, options?: UnshieldOptions): Promise<TransactionResult>;
20372
+ handleWalletAccountChange(prev?: {
20373
+ address: Address;
20374
+ }, next?: {
20375
+ address: Address;
20376
+ }): Promise<void>;
20377
+ }
20378
+ //#endregion
20379
+ //#region src/services/caching-service.d.ts
20380
+ /**
20381
+ * Storage-backed cache for decrypted FHE plaintext values.
20382
+ *
20383
+ * Each entry is keyed by `(requester, contractAddress, handle)` so different
20384
+ * signers cannot read each other's cached decryptions.
20385
+ */
20386
+ declare class CachingService {
20387
+ #private;
20388
+ constructor(storage: GenericStorage, logger: GenericLogger);
20389
+ get(requester: Address, contractAddress: Address, encryptedValue: EncryptedValue): Promise<ClearValue | null>;
20390
+ set(requester: Address, contractAddress: Address, encryptedValue: EncryptedValue, value: ClearValue): Promise<void>;
20391
+ delete(requester: Address, contractAddress: Address, encryptedValue: EncryptedValue): Promise<void>;
20392
+ clearForRequester(requester: Address): Promise<void>;
20393
+ clearAll(): Promise<void>;
20394
+ }
20395
+ //#endregion
20396
+ //#region src/services/delegation-service.d.ts
20397
+ declare class DelegationService {
20398
+ #private;
20399
+ constructor({
20400
+ provider,
20401
+ router,
20402
+ emitEvent,
20403
+ logger
20404
+ }: {
20405
+ provider: GenericProvider;
20406
+ router: ChainRouter;
20407
+ logger: GenericLogger;
20408
+ emitEvent?: (input: ZamaSDKEventInput, tokenAddress?: Address) => void;
20409
+ });
20410
+ delegateDecryption(signer: GenericSigner, {
20411
+ contractAddress,
20412
+ delegateAddress,
20413
+ delegatorAddress,
20414
+ expirationDate
20415
+ }: {
20416
+ contractAddress: Address;
20417
+ delegateAddress: Address;
20418
+ delegatorAddress: Address;
20419
+ expirationDate?: Date;
20420
+ }): Promise<TransactionResult>;
20421
+ revokeDelegation(signer: GenericSigner, {
20422
+ contractAddress,
20423
+ delegateAddress,
20424
+ delegatorAddress
20425
+ }: {
20426
+ contractAddress: Address;
20427
+ delegateAddress: Address;
20428
+ delegatorAddress: Address;
20429
+ }): Promise<TransactionResult>;
20430
+ isDelegated(params: {
20431
+ contractAddress: Address;
20432
+ delegatorAddress: Address;
20433
+ delegateAddress: Address;
20434
+ }): Promise<boolean>;
20435
+ getDelegationExpiry({
20436
+ contractAddress,
20437
+ delegatorAddress,
20438
+ delegateAddress
20439
+ }: {
20440
+ contractAddress: Address;
20441
+ delegatorAddress: Address;
20442
+ delegateAddress: Address;
20443
+ }): Promise<bigint>;
20444
+ findInactiveDelegations(contractAddresses: readonly Address[], delegatorAddress: Address, delegateAddress: Address): Promise<Map<Address, DelegationNotFoundError | DelegationExpiredError>>;
20445
+ assertDelegationActive(contractAddress: Address, delegatorAddress: Address, delegateAddress: Address): Promise<void>;
20446
+ }
20447
+ //#endregion
20448
+ //#region src/services/decryption-service.d.ts
20449
+ /** Options shared by the delegated-decrypt entry points. */
20450
+ interface DelegatedDecryptOptions {
20451
+ /**
20452
+ * Ride out the gateway propagation window: when a just-granted delegation
20453
+ * has not yet synced, the delegated decrypt is retried (bounded, ~30s) until
20454
+ * it lands instead of throwing {@link DelegationNotPropagatedError}. Defaults
20455
+ * to `true`. Pass `false` to fail fast on the first not-propagated response.
20456
+ */
20457
+ waitForPropagation?: boolean;
20458
+ }
20459
+ interface BatchDecryptItem {
20460
+ encryptedValue: EncryptedValue;
20461
+ contractAddress: Address;
20462
+ value?: ClearValue;
20463
+ error?: ZamaError;
20464
+ }
20465
+ interface BatchDecryptResult {
20466
+ items: BatchDecryptItem[];
20467
+ }
20468
+ declare class DecryptionService {
20469
+ #private;
20470
+ constructor({
20471
+ cache,
20472
+ credentialService,
20473
+ delegationService,
20474
+ router,
20475
+ emitEvent
20476
+ }: {
20477
+ cache: CachingService;
20478
+ credentialService: CredentialService;
20479
+ delegationService: DelegationService;
20480
+ router: ChainRouter;
20481
+ emitEvent: (input: ZamaSDKEventInput) => void;
20482
+ });
20483
+ decryptValues(handles: EncryptedInput[], signerAddress: Address, opts?: Pick<FhevmRelayerOptions, "signal" | "timeout">): Promise<Record<EncryptedValue, ClearValue>>;
20484
+ delegatedDecryptValues(encryptedInputs: EncryptedInput[], delegatorAddress: Address, delegateAddress: Address, accountAddress: Address, opts?: DelegatedDecryptOptions): Promise<Record<EncryptedValue, ClearValue>>;
20485
+ delegatedBatchDecryptHandlesAs({
20486
+ encryptedInputs,
20487
+ delegatorAddress,
20488
+ delegateAddress,
20489
+ accountAddress,
20490
+ maxConcurrency,
20491
+ waitForPropagation
20492
+ }: {
20493
+ encryptedInputs: EncryptedInput[];
20494
+ delegatorAddress: Address;
20495
+ delegateAddress: Address;
20496
+ accountAddress: Address;
20497
+ maxConcurrency?: number;
20498
+ waitForPropagation?: boolean;
20499
+ }): Promise<BatchDecryptResult>;
20500
+ }
20501
+ //#endregion
20502
+ //#region src/namespaces/decryption.d.ts
20503
+ /**
20504
+ * Public namespace for FHE decryption — the canonical way to decrypt.
20505
+ *
20506
+ * Exposed as `sdk.decryption`. Prefer these methods over the low-level
20507
+ * `sdk.relayer.decryptValues` / `decryptPublicValues`: they
20508
+ * assemble the credential bundle (transport key pair, EIP-712 permit) for you,
20509
+ * cache results, and wrap relayer errors. Reach for `sdk.relayer.*` only when
20510
+ * you must control credential assembly by hand.
20511
+ *
20512
+ * Owns the SDK-level guards (signer requirement on
20513
+ * `decryptValues` and `delegatedDecryptValues`, empty-array
20514
+ * short-circuit on `decryptPublicValues`, relayer error wrapping) and delegates the
20515
+ * actual work to the internal {@link DecryptionService} or the relayer directly for
20516
+ * `decryptPublicValues`.
20517
+ *
20518
+ * **Mixed signer requirement:** `decryptValues` and
20519
+ * `delegatedDecryptValues` need a configured signer; `decryptPublicValues`
20520
+ * does not. Each method documents its requirement in its JSDoc.
20521
+ */
20522
+ declare class Decryption {
20523
+ #private;
20524
+ /** @internal */
20525
+ constructor(opts: {
20526
+ signer: GenericSigner | undefined;
20527
+ provider: GenericProvider;
20528
+ router: ChainRouter;
20529
+ decryptionService: DecryptionService | undefined;
20530
+ });
20176
20531
  /**
20177
- * Unshield the entire balance and finalize in one call.
20178
- * Orchestrates: unshieldAll wait for receipt parse event → finalize.
20179
- *
20180
- * @param callbacks - Optional progress callbacks for each phase.
20181
- * @returns The finalize transaction hash and mined receipt.
20182
- * @throws if the balance is zero. {@link DecryptionFailedError}
20532
+ * Decrypt one or more FHE encrypted values. Results are cached — repeated calls
20533
+ * for the same encrypted value skip the relayer round-trip.
20183
20534
  *
20184
- * @example
20185
- * ```ts
20186
- * const txHash = await wrappedToken.unshieldAll();
20187
- * ```
20188
- */
20189
- unshieldAll(callbacks?: UnshieldCallbacks): Promise<TransactionResult>;
20190
- /**
20191
- * Resume an in-progress unshield from an existing unwrap tx hash.
20192
- * Useful when the user already submitted the unwrap but the finalize step
20193
- * was interrupted (e.g. page reload, network error).
20535
+ * Zero encrypted values are mapped to `0n` without hitting the relayer.
20536
+ * Events (`DecryptStart/End/Error`) are emitted uniformly.
20537
+ * Relayer errors are wrapped into typed SDK errors.
20194
20538
  *
20195
- * @param unwrapTxHash - The transaction hash of the previously submitted unwrap.
20196
- * @param callbacks - Optional progress callbacks.
20197
- * @returns The finalize transaction hash and mined receipt.
20539
+ * @param encryptedInput - Encrypted values to decrypt, each paired with its contract address.
20540
+ * @param options - Per-call `signal` and `timeout` forwarded to the relayer round-trip.
20541
+ * @returns A record mapping each encrypted value to its decrypted clear-text value.
20542
+ * @throws if no signer is configured. {@link SignerNotConfiguredError}
20543
+ * @throws if signer and provider are on different chains. {@link ChainMismatchError}
20198
20544
  *
20199
20545
  * @example
20200
20546
  * ```ts
20201
- * const txHash = await wrappedToken.resumeUnshield(previousUnwrapTxHash);
20547
+ * const values = await sdk.decryption.decryptValues([
20548
+ * { encryptedValue: balance, contractAddress: cUSDT },
20549
+ * ]);
20550
+ * console.log(values[balance]); // 1000n
20202
20551
  * ```
20203
20552
  */
20204
- resumeUnshield(unwrapTxHash: Hex, callbacks?: UnshieldCallbacks): Promise<TransactionResult>;
20553
+ decryptValues(encryptedInput: EncryptedInput[], options?: Pick<FhevmRelayerOptions, "signal" | "timeout">): Promise<Record<EncryptedValue, ClearValue>>;
20205
20554
  /**
20206
- * Return the unwrap tx hash of an unshield that was interrupted between its
20207
- * two phases, or `null` if none is pending for this wrapper.
20555
+ * Decrypt one or more FHE encrypted values using delegated credentials.
20208
20556
  *
20209
- * The SDK persists this automatically when {@link unshield}/{@link unshieldAll}
20210
- * submit phase 1, and clears it once phase 2 finalizes. Use the returned hash
20211
- * to surface a "resume" affordance, then pass it to {@link resumeUnshield}.
20212
- * Resuming is intentionally caller-driven auto-resuming on load would fire a
20213
- * wallet transaction unprompted.
20557
+ * Mirrors {@link decryptValues} with delegated credentials same caching and
20558
+ * zero-value short-circuit. Before reading from cache or calling the relayer,
20559
+ * every non-zero encrypted value's contract must have an active delegation from the
20560
+ * delegator to the connected signer; missing or expired delegations fail fast.
20214
20561
  *
20215
- * @returns The pending unwrap tx hash, or `null`.
20562
+ * @param encryptedInputs - FHE encrypted values paired with their contract addresses.
20563
+ * @param delegatorAddress - The address that granted delegation rights.
20564
+ * @param accountAddress - Address used as the cache key's "requester"
20565
+ * dimension. Defaults to `delegatorAddress`. Pass the actual account address
20566
+ * when decrypting on behalf of someone whose balance is stored under a
20567
+ * different address (e.g. `decryptBalanceAs` with an explicit `accountAddress`).
20568
+ * @param options - Delegated-decrypt options. By default the call rides out the
20569
+ * gateway propagation window ({@link DelegatedDecryptOptions.waitForPropagation});
20570
+ * pass `{ waitForPropagation: false }` to fail fast instead.
20571
+ * @returns Map of encrypted value → clear-text value.
20216
20572
  *
20217
20573
  * @example
20218
20574
  * ```ts
20219
- * const unwrapTxHash = await wrappedToken.getPendingUnshield();
20220
- * if (unwrapTxHash) await wrappedToken.resumeUnshield(unwrapTxHash);
20575
+ * const values = await sdk.decryption.delegatedDecryptValues([
20576
+ * { encryptedValue: balance, contractAddress: tokenAddr },
20577
+ * ], delegatorAddr);
20578
+ * console.log(values[balance]); // 1000n
20221
20579
  * ```
20222
20580
  */
20223
- getPendingUnshield(): Promise<Hex | null>;
20581
+ delegatedDecryptValues(encryptedInputs: EncryptedInput[], delegatorAddress: Address, accountAddress?: Address, options?: DelegatedDecryptOptions): Promise<Record<EncryptedValue, ClearValue>>;
20224
20582
  /**
20225
- * Request an unwrap for a specific amount. Encrypts the amount first.
20226
- * Call {@link finalizeUnwrap} after the request is processed on-chain.
20227
- *
20228
- * @param amount - The plaintext amount to unwrap (encrypted automatically).
20229
- * @returns The transaction hash and mined receipt.
20583
+ * Publicly decrypt one or more FHE encrypted values.
20230
20584
  *
20231
- * @example
20232
- * ```ts
20233
- * const txHash = await wrappedToken.unwrap(500n);
20234
- * ```
20235
- */
20236
- unwrap(amount: bigint): Promise<TransactionResult>;
20237
- /**
20238
- * Request an unwrap for the entire confidential balance.
20239
- * Uses the on-chain encrypted balance directly (no encryption needed).
20240
- * Throws if the balance is zero.
20585
+ * Signer-independent: works without a configured signer.
20586
+ * Returns the decryption proof alongside the clear-text values so callers
20587
+ * can submit on-chain finalization transactions (e.g. `finalizeUnwrap`).
20241
20588
  *
20242
- * @returns The transaction hash and mined receipt.
20243
- * @throws if the balance is zero. {@link DecryptionFailedError}
20589
+ * @param encryptedValues - FHE encrypted values to decrypt publicly.
20590
+ * @param options - Per-call `signal` and `timeout` forwarded to the relayer round-trip.
20591
+ * @returns Clear-text values, ABI-encoded values, and the decryption proof.
20244
20592
  *
20245
20593
  * @example
20246
20594
  * ```ts
20247
- * const txHash = await wrappedToken.unwrapAll();
20595
+ * const { clearValues, decryptionProof, abiEncodedClearValues } =
20596
+ * await sdk.decryption.decryptPublicValues([encryptedValue]);
20248
20597
  * ```
20249
20598
  */
20250
- unwrapAll(): Promise<TransactionResult>;
20599
+ decryptPublicValues(encryptedValues: EncryptedValue[], options?: Pick<FhevmRelayerOptions, "signal" | "timeout">): Promise<DecryptPublicValuesResult>;
20251
20600
  /**
20252
- * Complete an unwrap by providing the public decryption proof.
20253
- * Call this after an unshield request has been processed on-chain.
20601
+ * Batch-decrypt delegated encrypted values with per-entry error isolation.
20254
20602
  *
20255
- * @param unwrapRequestId - `unwrapRequestId` from the `UnwrapRequested` event.
20256
- * @returns The transaction hash and mined receipt.
20603
+ * Attempts a single batch request first. If the batch fails with a non-fatal
20604
+ * error (e.g. one entry is invalid), falls back to per-entry decryption so
20605
+ * healthy entries still resolve. Each item in the result carries either a
20606
+ * decrypted value or an error — callers decide how to surface partial failures.
20257
20607
  *
20258
- * @example
20259
- * ```ts
20260
- * const event = findUnwrapRequested(receipt.logs);
20261
- * const txHash = await wrappedToken.finalizeUnwrap(event.unwrapRequestId);
20262
- * ```
20263
- */
20264
- finalizeUnwrap(unwrapRequestId: EncryptedValue): Promise<TransactionResult>;
20265
- }
20266
- //#endregion
20267
- //#region src/wrappers-registry.d.ts
20268
- /**
20269
- * Default wrappers registry addresses for known chains.
20270
- * Only includes chains where a registry is deployed (excludes Hardhat).
20271
- *
20272
- * @deprecated Read `registryAddress` from the chain presets instead (e.g.
20273
- * `sepolia.registryAddress`). Will be removed in the next major version.
20274
- */
20275
- declare const DefaultRegistryAddresses: Record<number, Address>;
20276
- /** Configuration for {@link WrappersRegistry}. */
20277
- interface WrappersRegistryConfig {
20278
- /** Read-only chain provider used for every registry lookup. */
20279
- provider: GenericProvider;
20280
- /**
20281
- * Per-chain registry address overrides, merged on top of
20282
- * {@link DefaultRegistryAddresses}. Use this to supply a registry
20283
- * address for custom or local chains (e.g. Hardhat).
20608
+ * @param encryptedInputs - FHE encrypted values paired with their contract addresses.
20609
+ * @param delegatorAddress - The address that granted delegation rights.
20610
+ * @param accountAddress - The account on whose behalf decryption is performed. Defaults to `delegatorAddress`.
20611
+ * @param maxConcurrency - Maximum parallel decrypt calls during per-entry fallback.
20612
+ * @param waitForPropagation - Ride out the gateway propagation window on the
20613
+ * initial batch attempt (default `true`). See {@link DelegatedDecryptOptions.waitForPropagation}.
20614
+ * @returns Per-entry results, each with a value or an error.
20615
+ * @throws if no signer is configured. {@link SignerNotConfiguredError}
20616
+ * @throws if signer and provider are on different chains. {@link ChainMismatchError}
20284
20617
  *
20285
20618
  * @example
20286
20619
  * ```ts
20287
- * new WrappersRegistry({
20288
- * provider,
20289
- * registryAddresses: { [31337]: "0xYourHardhatRegistry" },
20620
+ * const result = await sdk.decryption.delegatedBatchDecryptValues({
20621
+ * encryptedInputs: [
20622
+ * { encryptedValue: encryptedValue1, contractAddress: tokenA },
20623
+ * { encryptedValue: encryptedValue2, contractAddress: tokenB },
20624
+ * ],
20625
+ * delegatorAddress: "0xDelegator",
20626
+ * maxConcurrency: 5,
20290
20627
  * });
20628
+ * for (const item of result.items) {
20629
+ * if (item.error) console.error(item.encryptedValue, item.error);
20630
+ * else console.log(item.encryptedValue, item.value);
20631
+ * }
20291
20632
  * ```
20292
20633
  */
20293
- registryAddresses?: Record<number, Address>;
20294
- /**
20295
- * How long cached registry results remain valid, in seconds.
20296
- * Default: `86400` (24 hours).
20297
- */
20298
- registryTTL?: number;
20299
- }
20300
- /** Options for {@link WrappersRegistry.listPairs}. */
20301
- interface ListPairsOptions {
20302
- /** Page number (1-indexed). Default: `1`. */
20303
- page?: number;
20304
- /** Number of items per page. Default: `100`. */
20305
- pageSize?: number;
20306
- /**
20307
- * When `true`, fetches on-chain metadata (name, symbol, decimals) for both
20308
- * the ERC-20 and confidential token, plus totalSupply for the ERC-20.
20309
- * Default: `false`.
20310
- */
20311
- metadata?: boolean;
20634
+ delegatedBatchDecryptValues({
20635
+ encryptedInputs,
20636
+ delegatorAddress,
20637
+ accountAddress,
20638
+ maxConcurrency,
20639
+ waitForPropagation
20640
+ }: {
20641
+ encryptedInputs: EncryptedInput[];
20642
+ delegatorAddress: Address;
20643
+ accountAddress?: Address;
20644
+ maxConcurrency?: number;
20645
+ } & DelegatedDecryptOptions): Promise<BatchDecryptResult>;
20312
20646
  }
20313
- /**
20314
- * High-level interface for the on-chain token wrappers registry.
20315
- *
20316
- * Uses the configured {@link GenericProvider} to resolve the correct registry
20317
- * contract address for the current chain and exposes typed read helpers for
20318
- * every registry query. Results are cached in memory with a configurable TTL
20319
- * (default 24 hours).
20320
- *
20321
- * @example
20322
- * ```ts
20323
- * const registry = new WrappersRegistry({ provider });
20324
- *
20325
- * // Paginated listing
20326
- * const page1 = await registry.listPairs({ page: 1, pageSize: 20 });
20327
- *
20328
- * // Structured lookups
20329
- * const result = await registry.getConfidentialToken(erc20Address);
20330
- * if (result) console.log(result.confidentialTokenAddress);
20331
- *
20332
- * // Force refresh
20333
- * registry.refresh();
20334
- * ```
20335
- */
20336
- declare class WrappersRegistry {
20337
- #private;
20338
- readonly provider: GenericProvider;
20339
- constructor(config: WrappersRegistryConfig);
20340
- /**
20341
- * Synchronous lookup of the registry address for a given chain ID.
20342
- * Returns `undefined` if no address is configured for that chain.
20343
- */
20344
- getAddress(chainId: number): Address | undefined;
20345
- /**
20346
- * Force-invalidate the in-memory cache. The next call to any read method
20347
- * will fetch fresh data from the chain.
20348
- */
20349
- refresh(): void;
20350
- /**
20351
- * The cache TTL in milliseconds.
20352
- * Exposed so query option factories can set a matching `staleTime`.
20353
- */
20354
- get ttlMs(): number;
20647
+ //#endregion
20648
+ //#region src/namespaces/delegations.d.ts
20649
+ /**
20650
+ * Public namespace for on-chain decryption-delegation management.
20651
+ *
20652
+ * Exposed as `sdk.delegations`. Owns the SDK-level guards (signer requirement, chain
20653
+ * alignment, delegator address resolution from the wallet account) and delegates the
20654
+ * actual work to the internal {@link DelegationService}.
20655
+ *
20656
+ * Delegation operations write to the host chain ACL; after a delegation is mined,
20657
+ * the gateway syncs the ACL state via cross-chain event propagation — usually
20658
+ * within ~10 blocks (a few seconds). Delegated decryption rides out that window
20659
+ * with a bounded internal retry, so callers can decrypt right after granting.
20660
+ */
20661
+ declare class Delegations {
20662
+ #private;
20663
+ /** @internal */
20664
+ constructor(opts: {
20665
+ signer: GenericSigner | undefined;
20666
+ provider: GenericProvider;
20667
+ delegationService: DelegationService;
20668
+ });
20355
20669
  /**
20356
- * Resolve the registry contract address for the current chain.
20670
+ * Delegate decryption rights for a confidential contract to another address.
20671
+ * Calls `ACL.delegateForUserDecryption()` on-chain.
20357
20672
  *
20358
- * Priority: `registryAddresses[chainId]` \> built-in default.
20673
+ * The delegation is recorded on L1 immediately, but the gateway must sync the
20674
+ * ACL state via cross-chain event propagation — usually within ~10 blocks (a
20675
+ * few seconds). You do not need to wait: delegated decryption rides out that
20676
+ * window with a bounded internal retry, so you can decrypt right after this
20677
+ * resolves.
20359
20678
  *
20360
- * @returns The registry contract address for the connected chain.
20361
- * @throws if no address is configured for the chain. {@link ConfigurationError}
20679
+ * @param contractAddress - The confidential contract address to delegate on.
20680
+ * @param delegateAddress - Address to delegate decryption rights to.
20681
+ * @param expirationDate - Optional expiration date (defaults to permanent delegation via `uint64.max`).
20682
+ * @returns The transaction hash and mined receipt.
20683
+ * @throws if no signer is configured. {@link SignerNotConfiguredError}
20684
+ * @throws if signer and provider are on different chains. {@link ChainMismatchError}
20685
+ * @throws if `expirationDate` is less than 1 hour in the future. {@link DelegationExpirationTooSoonError}
20686
+ * @throws if the delegate equals the connected wallet. {@link DelegationSelfNotAllowedError}
20687
+ * @throws if the delegate equals the contract address. {@link DelegationDelegateEqualsContractError}
20688
+ * @throws if the new expiry equals the current one. {@link DelegationExpiryUnchangedError}
20689
+ * @throws if the delegation transaction reverts. {@link TransactionRevertedError}
20362
20690
  */
20363
- getRegistryAddress(): Promise<Address>;
20691
+ delegateDecryption({
20692
+ contractAddress,
20693
+ delegateAddress,
20694
+ expirationDate
20695
+ }: {
20696
+ contractAddress: Address;
20697
+ delegateAddress: Address;
20698
+ expirationDate?: Date;
20699
+ }): Promise<TransactionResult>;
20364
20700
  /**
20365
- * List token wrapper pairs with page-based pagination.
20366
- *
20367
- * Internally maps to `getTokenConfidentialTokenPairsSlice` on-chain.
20368
- *
20369
- * @param options - Pagination and enrichment options.
20370
- * @returns A {@link PaginatedResult} of pairs.
20371
- *
20372
- * @example
20373
- * ```ts
20374
- * const result = await registry.listPairs({ page: 1, pageSize: 20 });
20375
- * console.log(`${result.total} pairs, showing page ${result.page}`);
20701
+ * Revoke decryption delegation for a confidential contract.
20702
+ * Calls `ACL.revokeDelegationForUserDecryption()` on-chain.
20376
20703
  *
20377
- * // With on-chain metadata
20378
- * const withMeta = await registry.listPairs({ metadata: true, pageSize: 10 });
20379
- * for (const pair of withMeta.items) {
20380
- * console.log(pair.underlying.symbol, "→", pair.confidential.symbol);
20381
- * }
20382
- * ```
20704
+ * @param contractAddress - The confidential contract address to revoke delegation on.
20705
+ * @param delegateAddress - Address to revoke delegation from.
20706
+ * @returns The transaction hash and mined receipt.
20707
+ * @throws if no signer is configured. {@link SignerNotConfiguredError}
20708
+ * @throws if signer and provider are on different chains. {@link ChainMismatchError}
20709
+ * @throws if no delegation exists for this (delegator, delegate, contract) tuple. {@link DelegationNotFoundError}
20710
+ * @throws if the revocation transaction reverts. {@link TransactionRevertedError}
20383
20711
  */
20384
- listPairs(options: ListPairsOptions & {
20385
- metadata: true;
20386
- }): Promise<PaginatedResult<TokenWrapperPairWithMetadata>>;
20387
- listPairs(options?: ListPairsOptions): Promise<PaginatedResult<TokenWrapperPair>>;
20712
+ revokeDelegation({
20713
+ contractAddress,
20714
+ delegateAddress
20715
+ }: {
20716
+ contractAddress: Address;
20717
+ delegateAddress: Address;
20718
+ }): Promise<TransactionResult>;
20388
20719
  /**
20389
- * Look up the confidential token for a given plain ERC-20 address.
20720
+ * Check whether a delegation is active for the given contract address.
20390
20721
  *
20391
- * @param tokenAddress - The plain ERC-20 token address.
20392
- * @returns The lookup result, or `null` if the token has never been registered.
20393
- * **Note:** revoked tokens (registered then invalidated) return a non-null result
20394
- * with `isValid: false`. Check `result.isValid` explicitly rather than using
20395
- * `if (result)` to guard against processing revoked tokens.
20722
+ * Signer-independent: works without a configured signer.
20396
20723
  *
20397
- * @example
20398
- * ```ts
20399
- * const result = await registry.getConfidentialToken(usdcAddress);
20400
- * if (result?.isValid) {
20401
- * console.log(result.confidentialTokenAddress);
20402
- * }
20403
- * ```
20724
+ * @param contractAddress - The confidential contract address.
20725
+ * @param delegatorAddress - The address that granted the delegation.
20726
+ * @param delegateAddress - The address that received delegation rights.
20727
+ * @returns `true` if the delegation exists and has not expired.
20404
20728
  */
20405
- getConfidentialToken(tokenAddress: Address): Promise<{
20406
- confidentialTokenAddress: Address;
20407
- isValid: boolean;
20408
- } | null>;
20729
+ isActive(params: {
20730
+ contractAddress: Address;
20731
+ delegatorAddress: Address;
20732
+ delegateAddress: Address;
20733
+ }): Promise<boolean>;
20409
20734
  /**
20410
- * Reverse lookup find the plain ERC-20 for a given confidential token.
20735
+ * Get the expiration timestamp of a delegation for the given contract.
20411
20736
  *
20412
- * @param confidentialTokenAddress - The confidential token address.
20413
- * @returns The lookup result, or `null` if no pair is registered.
20737
+ * Signer-independent: works without a configured signer.
20414
20738
  *
20415
- * @example
20416
- * ```ts
20417
- * const result = await registry.getUnderlyingToken(cUsdcAddress);
20418
- * if (result) {
20419
- * console.log(result.tokenAddress, result.isValid);
20420
- * }
20421
- * ```
20739
+ * @param contractAddress - The confidential contract address.
20740
+ * @param delegatorAddress - The address that granted the delegation.
20741
+ * @param delegateAddress - The address that received delegation rights.
20742
+ * @returns Unix timestamp as bigint. `0n` = no delegation. `2^64 - 1` = permanent.
20422
20743
  */
20423
- getUnderlyingToken(confidentialTokenAddress: Address): Promise<{
20424
- tokenAddress: Address;
20425
- isValid: boolean;
20426
- } | null>;
20744
+ getExpiry(params: {
20745
+ contractAddress: Address;
20746
+ delegatorAddress: Address;
20747
+ delegateAddress: Address;
20748
+ }): Promise<bigint>;
20749
+ }
20750
+ //#endregion
20751
+ //#region src/namespaces/permits.d.ts
20752
+ /**
20753
+ * Public namespace for permit and transport-key-pair management.
20754
+ *
20755
+ * Exposed as `sdk.permits`. Owns the SDK-level guards (chain alignment, empty-array
20756
+ * short-circuit, decrypt-cache invalidation) and delegates the actual work to the
20757
+ * internal {@link CredentialService}.
20758
+ *
20759
+ * The namespace is named `permits` because the user-facing concept is the signed-permit
20760
+ * store. The transport key pair is invisible plumbing — there is no `getTransportKeyPair()`
20761
+ * surfaced; the key pair exists to sign permits and is created automatically when needed.
20762
+ * {@link clear} wipes both the permit store and the transport key pair (permits
20763
+ * cascade-delete with the key pair).
20764
+ */
20765
+ declare class Permits {
20766
+ #private;
20767
+ /** @internal */
20768
+ constructor(opts: {
20769
+ signer: GenericSigner | undefined;
20770
+ provider: GenericProvider;
20771
+ cachingService: CachingService;
20772
+ credentialService: CredentialService | undefined;
20773
+ logger: GenericLogger;
20774
+ });
20427
20775
  /**
20428
- * Fetch all token wrapper pairs from the registry.
20776
+ * Sign and store an EIP-712 permit authorising direct decryption for the
20777
+ * given contract addresses.
20429
20778
  *
20430
- * @returns All registered `TokenWrapperPair` entries.
20779
+ * Idempotent: if a permit covering the requested set already exists, no
20780
+ * wallet prompt occurs. Otherwise the SDK chunks the uncovered subset into
20781
+ * groups of ≤10 contracts and prompts once per chunk; partial mid-flight
20782
+ * rejection is preserved (already-signed chunks are persisted before the
20783
+ * next prompt).
20784
+ *
20785
+ * @param contracts - Contract addresses to authorize.
20431
20786
  */
20432
- getTokenPairs(): Promise<readonly TokenWrapperPair[]>;
20787
+ grantPermit(contracts: Address[]): Promise<void>;
20433
20788
  /**
20434
- * Get the total number of token wrapper pairs.
20789
+ * Sign and store an EIP-712 delegation permit authorising decryption on
20790
+ * behalf of `delegator`. Same idempotence/chunking semantics as {@link grantPermit}.
20435
20791
  *
20436
- * @returns The count as a bigint.
20792
+ * @param delegator - The address that delegated decryption rights to the connected signer.
20793
+ * @param contracts - Contract addresses to authorize.
20437
20794
  */
20438
- getTokenPairsLength(): Promise<bigint>;
20795
+ grantDelegationPermit(delegator: Address, contracts: Address[]): Promise<void>;
20439
20796
  /**
20440
- * Fetch a range of token wrapper pairs (paginated by index).
20441
- *
20442
- * @param fromIndex - Start index (inclusive).
20443
- * @param toIndex - End index (exclusive).
20444
- * @returns The slice of `TokenWrapperPair` entries.
20797
+ * Pure store lookup: is there a permit covering `contracts`?
20798
+ * No wallet prompt, no transport key pair generation. Returns `false` when no signer
20799
+ * is configured.
20445
20800
  */
20446
- getTokenPairsSlice(fromIndex: bigint, toIndex: bigint): Promise<readonly TokenWrapperPair[]>;
20801
+ hasPermit(contracts: Address[]): Promise<boolean>;
20447
20802
  /**
20448
- * Fetch a single token wrapper pair by index.
20803
+ * Pure store lookup for a delegation permit. See {@link hasPermit}.
20449
20804
  *
20450
- * @param index - Zero-based pair index.
20451
- * @returns The `TokenWrapperPair` at that index.
20805
+ * @param delegator - The address that delegated decryption rights to the connected signer.
20806
+ * @param contracts - Contract addresses to check.
20807
+ * @returns `true` if cached delegation permits cover all requested contracts.
20452
20808
  */
20453
- getTokenPair(index: bigint): Promise<TokenWrapperPair>;
20809
+ hasDelegationPermit(delegator: Address, contracts: Address[]): Promise<boolean>;
20454
20810
  /**
20455
- * Look up the confidential token address for a given plain ERC-20 token.
20811
+ * Best-effort transport-key-pair prefetch for the connected signer.
20456
20812
  *
20457
- * @param tokenAddress - The plain ERC-20 token address.
20458
- * @returns A tuple `[isValid, confidentialTokenAddress]`. `isValid` is `true` only for a
20459
- * registered, non-revoked wrapper. The address is the zero address when no pair is registered.
20460
- * A non-zero address with `isValid=false` means the wrapper was registered but later revoked.
20813
+ * Optional latency optimization: decrypt and permit flows remain correct
20814
+ * without it because they lazily create the transport key pair when needed.
20815
+ *
20816
+ * Silent no-op when no signer is configured or no wallet account is
20817
+ * available. The transport key pair is generated through the relayer dispatcher's
20818
+ * currently active chain — see {@link LifecycleService}, which calls
20819
+ * `switchChain` before fanning the wallet-account change out to listeners,
20820
+ * so any downstream caller (including React adapters) observes the
20821
+ * dispatcher on the wallet chain by the time it invokes warmup.
20461
20822
  */
20462
- getConfidentialTokenAddress(tokenAddress: Address): Promise<readonly [boolean, Address]>;
20823
+ warmTransportKeyPair(): Promise<void>;
20463
20824
  /**
20464
- * Reverse lookup find the plain ERC-20 for a given confidential token.
20825
+ * Wipe FHE permits for the current signer.
20465
20826
  *
20466
- * @param confidentialTokenAddress - The confidential token address.
20467
- * @returns A tuple `[isValid, tokenAddress]`. `isValid` is `true` only for a registered,
20468
- * non-revoked wrapper. The address is the zero address when no pair is registered.
20469
- * A non-zero address with `isValid=false` means the wrapper was registered but later revoked.
20827
+ * - With no argument: every permit referencing this signer is removed across
20828
+ * all chains and delegators. The transport key pair survives use {@link clear} to
20829
+ * also wipe the transport key pair.
20830
+ * - With a contract list: every signed permit in the direct-decrypt scope
20831
+ * (current chain) whose immutable payload touches any listed address is
20832
+ * removed. Delegation permits are not touched in this mode.
20833
+ *
20834
+ * @throws if no signer is configured. {@link SignerNotConfiguredError}
20470
20835
  */
20471
- getTokenAddress(confidentialTokenAddress: Address): Promise<readonly [boolean, Address]>;
20836
+ revokePermits(contracts?: Address[]): Promise<void>;
20472
20837
  /**
20473
- * Check whether a confidential token is registered and valid.
20838
+ * Wipe the transport key pair for the current signer and cascade-delete every permit
20839
+ * (across chains and delegators) referencing it.
20474
20840
  *
20475
- * @param confidentialTokenAddress - The confidential token address to check.
20476
- * @returns `true` if the token is a known valid wrapper in the registry.
20841
+ * @throws if no signer is configured. {@link SignerNotConfiguredError}
20477
20842
  */
20478
- isConfidentialTokenValid(confidentialTokenAddress: Address): Promise<boolean>;
20843
+ clear(): Promise<void>;
20479
20844
  }
20480
20845
  //#endregion
20481
20846
  //#region src/zama-sdk.d.ts
@@ -20489,8 +20854,6 @@ declare class WrappersRegistry {
20489
20854
  */
20490
20855
  declare class ZamaSDK {
20491
20856
  #private;
20492
- /** @internal */
20493
- readonly relayer: RelayerDispatcher;
20494
20857
  readonly provider: GenericProvider;
20495
20858
  readonly signer: GenericSigner | undefined;
20496
20859
  readonly storage: GenericStorage;
@@ -20525,6 +20888,12 @@ declare class ZamaSDK {
20525
20888
  * @internal
20526
20889
  */
20527
20890
  get logger(): GenericLogger;
20891
+ /**
20892
+ * The single-chain relayer backend for the **currently active** chain.
20893
+ *
20894
+ * @internal
20895
+ */
20896
+ get relayer(): FhevmRelayerSDK;
20528
20897
  /**
20529
20898
  * Emit a structured SDK event into the unified SDK event stream.
20530
20899
  *
@@ -20573,7 +20942,7 @@ declare class ZamaSDK {
20573
20942
  * });
20574
20943
  * ```
20575
20944
  */
20576
- encrypt(params: EncryptParams): Promise<EncryptResult>;
20945
+ encrypt(params: EncryptParams, options?: Pick<FhevmRelayerOptions, "signal" | "timeout">): Promise<EncryptResult>;
20577
20946
  /**
20578
20947
  * Create a high-level ERC-20-style interface for an ERC-7984 confidential token.
20579
20948
  * Supports balance queries, transfers, operator approvals, and decryption.
@@ -20632,5 +21001,5 @@ declare class ZamaSDK {
20632
21001
  [Symbol.dispose](): void;
20633
21002
  }
20634
21003
  //#endregion
20635
- export { DecryptResult as $, BalanceCheckUnavailableError as A, decimalsContract as At, DelegationDelegateEqualsContractError as B, rateContract as Bt, SignerRequiredError as C, ERC7984_WRAPPER_INTERFACE_ID as Ct, NotEntitledError as D, allowanceContract as Dt, RpcRateLimitError as E, supportsInterfaceContract as Et, DecryptionFailedError as F, confidentialTransferContract as Ft, DelegationNotPropagatedError as G, wrapContract as Gt, DelegationExpiredError as H, underlyingContract as Ht, EncryptionFailedError as I, confidentialTransferFromContract as It, NoCiphertextError as J, resolveStorage as Jt, DelegationSelfNotAllowedError as K, ResolvedChainRelayer as Kt, AclPausedError as L, finalizeUnwrapContract as Lt, ERC20ReadFailedError as M, symbolContract as Mt, InsufficientConfidentialBalanceError as N, confidentialBalanceOfContract as Nt, ConfigurationError as O, approveContract as Ot, InsufficientERC20BalanceError as P, confidentialTotalSupplyContract as Pt, ZamaErrorCode as Q, DelegationContractIsSelfError as R, inferredTotalSupplyContract as Rt, SignerNotConfiguredError as S, ERC7984_INTERFACE_ID as St, WalletNotConnectedError as T, isConfidentialWrapperContract as Tt, DelegationExpiryUnchangedError as U, unwrapContract as Ut, DelegationExpirationTooSoonError as V, setOperatorContract as Vt, DelegationNotFoundError as W, unwrapFromBalanceContract as Wt, ChainMismatchError as X, TransportKeyPairExpiredError as Y, createConfig as Yt, ZamaError as Z, WorkerRecycledError as _, getDelegationExpiryContract as _t, WrappersRegistryConfig as a, QueryFactoryOptions as at, SigningFailedError as b, transferAndCallContract as bt, BatchDecryptAsOptions as c, TokenWrapperPairWithMetadata as ct, Delegations as d, getTokenPairContract as dt, EncryptedInput as et, Decryption as f, getTokenPairsContract as ft, matchZamaError as g, delegateForUserDecryptionContract as gt, DelegatedDecryptOptions as h, isConfidentialTokenValidContract as ht, WrappersRegistry as i, MutationFactoryOptions as it, BalanceErrorDetails as j, nameContract as jt, RelayerRequestFailedError as k, balanceOfContract as kt, Token as l, getConfidentialTokenAddressContract as lt, BatchDecryptResult as m, getTokenPairsSliceContract as mt, DefaultRegistryAddresses as n, SignerQueryContext as nt, WrappedToken as o, PaginatedResult as ot, BatchDecryptItem as p, getTokenPairsLengthContract as pt, InvalidTransportKeyPairError as q, resolveChainRelayers as qt, ListPairsOptions as r, zamaQueryKeys as rt, BatchBalancesResult as s, TokenWrapperPair as st, ZamaSDK as t, decryptValuesQueryOptions as tt, Permits as u, getTokenAddressContract as ut, WorkerTimeoutError as v, isHandleDelegatedContract as vt, WalletAccountNotReadyError as w, isConfidentialTokenContract as wt, SigningRejectedError as x, ERC1363_INTERFACE_ID as xt, TransactionRevertedError as y, revokeDelegationContract as yt, DelegationCooldownError as z, isOperatorContract as zt };
20636
- //# sourceMappingURL=index-C1Mtc8Rw.d.ts.map
21004
+ export { confidentialTransferMutationOptions as $, getTokenAddressContract as $n, DelegationSelfNotAllowedError as $t, encryptMutationOptions as A, QueryFilterLike as An, setOperatorContract as Ar, SignerRequiredError as At, UnshieldParams as B, invalidateWagmiBalanceQueries as Bn, InsufficientConfidentialBalanceError as Bt, grantPermitMutationOptions as C, IsConfidentialQueryConfig as Cn, confidentialTotalSupplyContract as Cr, BatchDecryptAsOptions as Ct, DecryptResult as D, TokenMetadataQueryConfig as Dn, inferredTotalSupplyContract as Dr, SigningFailedError as Dt, delegatedDecryptValuesMutationOptions as E, TokenMetadata as En, finalizeUnwrapContract as Er, TransactionRevertedError as Et, unwrapMutationOptions as F, invalidateAfterTransfer as Fn, ResolvedChainRelayer as Fr, ConfigurationError as Ft, confidentialSetOperatorMutationOptions as G, QueryFactoryOptions as Gn, DelegationContractIsSelfError as Gt, ApproveUnderlyingParams as H, zamaQueryKeys as Hn, DecryptionFailedError as Ht, ResumeUnshieldParams as I, invalidateAfterUnshield as In, resolveChainRelayers as Ir, RelayerRequestFailedError as It, ConfidentialTransferFromParams as J, hashFn as Jn, DelegationExpirationTooSoonError as Jt, ConfidentialTransferFromAndCallParams as K, StrippedQueryOptionKeys as Kn, DelegationCooldownError as Kt, resumeUnshieldMutationOptions as L, invalidateAfterUnshieldSettled as Ln, resolveStorage as Lr, BalanceCheckUnavailableError as Lt, finalizeUnwrapMutationOptions as M, invalidateAfterApproveUnderlying as Mn, unwrapContract as Mr, WalletNotConnectedError as Mt, unwrapAllMutationOptions as N, invalidateAfterSetOperator as Nn, unwrapFromBalanceContract as Nr, RpcRateLimitError as Nt, EncryptedInput as O, tokenMetadataQueryOptions as On, isOperatorContract as Or, SigningRejectedError as Ot, UnwrapParams as P, invalidateAfterShield as Pn, wrapContract as Pr, NotEntitledError as Pt, ConfidentialTransferParams as Q, getConfidentialTokenAddressContract as Qn, DelegationNotPropagatedError as Qt, UnshieldAllParams as R, invalidateAfterUnwrap as Rn, createConfig as Rr, BalanceErrorDetails as Rt, hasPermitQueryOptions as S, totalSupplyQueryOptions as Sn, confidentialBalanceOfContract as Sr, BatchBalancesResult as St, DelegatedDecryptValuesMutationParams as T, isWrapperQueryOptions as Tn, confidentialTransferFromContract as Tr, matchZamaError as Tt, approveUnderlyingMutationOptions as U, SignerQueryContext as Un, EncryptionFailedError as Ut, unshieldMutationOptions as V, invalidateWalletLifecycleQueries as Vn, InsufficientERC20BalanceError as Vt, ConfidentialSetOperatorParams as W, MutationFactoryOptions as Wn, AclPausedError as Wt, ConfidentialTransferAndCallParams as X, TokenWrapperPair as Xn, DelegationExpiryUnchangedError as Xt, confidentialTransferFromMutationOptions as Y, PaginatedResult as Yn, DelegationExpiredError as Yt, confidentialTransferAndCallMutationOptions as Z, TokenWrapperPairWithMetadata as Zn, DelegationNotFoundError as Zt, DelegateDecryptionParams as _, WrappersRegistryConfig as _n, approveContract as _r, ConfidentialBalancesQueryConfig as _t, BatchDecryptItem as a, ZamaErrorCode as an, delegateForUserDecryptionContract as ar, TokenAddressQueryConfig as at, revokePermitsMutationOptions as b, StoredTransportKeyPair as bn, nameContract as br, confidentialBalanceQueryOptions as bt, DelegationStatusData as c, PendingUnshieldQueryConfig as cn, revokeDelegationContract as cr, WrappersRegistryQueryConfig as ct, RevokeDelegationParams as d, underlyingAllowanceQueryOptions as dn, ERC7984_INTERFACE_ID as dr, listPairsQueryOptions as dt, InvalidTransportKeyPairError as en, getTokenPairContract as er, ShieldParams as et, revokeDelegationMutationOptions as f, WrapperDiscoveryQueryConfig as fn, ERC7984_WRAPPER_INTERFACE_ID as fr, tokenAddressQueryOptions as ft, decryptBalanceAsMutationOptions as g, WrappersRegistry as gn, allowanceContract as gr, tokenPairsSliceQueryOptions as gt, DecryptBalanceAsParams as h, ListPairsOptions as hn, supportsInterfaceContract as hr, tokenPairsQueryOptions as ht, Decryption as i, ZamaError as in, isConfidentialTokenValidContract as ir, ListPairsQueryConfig as it, FinalizeUnwrapParams as j, QueryLike as jn, underlyingContract as jr, WalletAccountNotReadyError as jt, decryptValuesQueryOptions as k, QueryClientLike as kn, rateContract as kr, SignerNotConfiguredError as kt, DelegationStatusQueryConfig as l, pendingUnshieldQueryOptions as ln, transferAndCallContract as lr, confidentialTokenAddressQueryOptions as lt, batchDecryptBalancesAsMutationOptions as m, DefaultRegistryAddresses as mn, isConfidentialWrapperContract as mr, tokenPairsLengthQueryOptions as mt, Permits as n, TransportKeyPairExpiredError as nn, getTokenPairsLengthContract as nr, ConfidentialTokenAddressQueryConfig as nt, BatchDecryptResult as o, ConfidentialIsOperatorQueryConfig as on, getDelegationExpiryContract as or, TokenPairQueryConfig as ot, BatchDecryptBalancesAsParams as p, wrapperDiscoveryQueryOptions as pn, isConfidentialTokenContract as pr, tokenPairQueryOptions as pt, confidentialTransferFromAndCallMutationOptions as q, filterQueryOptions as qn, DelegationDelegateEqualsContractError as qt, Delegations as r, ChainMismatchError as rn, getTokenPairsSliceContract as rr, IsConfidentialTokenValidQueryConfig as rt, DelegatedDecryptOptions as s, confidentialIsOperatorQueryOptions as sn, isHandleDelegatedContract as sr, TokenPairsSliceQueryConfig as st, ZamaSDK as t, NoCiphertextError as tn, getTokenPairsContract as tr, shieldMutationOptions as tt, delegationStatusQueryOptions as u, UnderlyingAllowanceQueryConfig as un, ERC1363_INTERFACE_ID as ur, isConfidentialTokenValidQueryOptions as ut, delegateDecryptionMutationOptions as v, Permission as vn, balanceOfContract as vr, confidentialBalancesQueryOptions as vt, decryptPublicValuesMutationOptions as w, isConfidentialQueryOptions as wn, confidentialTransferContract as wr, Token as wt, HasPermitQueryConfig as x, TotalSupplyQueryConfig as xn, symbolContract as xr, WrappedToken as xt, clearCredentialsMutationOptions as y, SerializedTransportKeyPair as yn, decimalsContract as yr, ConfidentialBalanceQueryConfig as yt, unshieldAllMutationOptions as z, invalidateBalanceQueries as zn, ERC20ReadFailedError as zt };
21005
+ //# sourceMappingURL=zama-sdk-q4_qt64Q.d.ts.map