@zama-fhe/react-sdk 3.0.0-alpha.3 → 3.0.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,929 +1,135 @@
1
1
  # @zama-fhe/react-sdk
2
2
 
3
- React hooks for confidential contract operations, built on [React Query](https://tanstack.com/query). Provides declarative, declarative hooks for session authorization, balances, confidential transfers, shielding, unshielding, and decryption — so you never deal with raw FHE operations in your components.
3
+ React bindings for the Zama SDK. Use this package to wire confidential smart contract operations into a React app through `ZamaProvider` and hooks for authorization, encryption, balances, transfers, shielding, unshielding, approvals, and delegation.
4
4
 
5
5
  ## Installation
6
6
 
7
+ Install the React package, the core SDK, and React Query:
8
+
7
9
  ```bash
8
- pnpm add @zama-fhe/react-sdk @tanstack/react-query
10
+ pnpm add @zama-fhe/react-sdk @zama-fhe/sdk @tanstack/react-query
9
11
  # or
10
- npm install @zama-fhe/react-sdk @tanstack/react-query
12
+ npm install @zama-fhe/react-sdk @zama-fhe/sdk @tanstack/react-query
11
13
  # or
12
- yarn add @zama-fhe/react-sdk @tanstack/react-query
14
+ yarn add @zama-fhe/react-sdk @zama-fhe/sdk @tanstack/react-query
13
15
  ```
14
16
 
15
- `@zama-fhe/sdk` is included as a direct dependency no need to install it separately.
16
-
17
- ### Peer dependencies
17
+ If you follow the viem example below, add `viem` too:
18
18
 
19
- | Package | Version | Required? |
20
- | ----------------------- | ------- | --------------------------------------------- |
21
- | `react` | >= 18 | Yes |
22
- | `@tanstack/react-query` | >= 5 | Yes |
23
- | `viem` | >= 2 | Optional — for `/viem` and `/wagmi` sub-paths |
24
- | `ethers` | >= 6 | Optional — for `/ethers` sub-path |
25
- | `wagmi` | >= 2 | Optional — for `/wagmi` sub-path |
19
+ ```bash
20
+ pnpm add viem
21
+ # or
22
+ npm install viem
23
+ # or
24
+ yarn add viem
25
+ ```
26
26
 
27
- ## Quick Start
27
+ `react` >= 18 is required. If you already build a `ZamaConfig` with the core SDK, pass it directly to `ZamaProvider`.
28
28
 
29
- ### With wagmi
29
+ ## Minimal React example
30
30
 
31
31
  ```tsx
32
- import { WagmiProvider, createConfig, http } from "wagmi";
33
- import { mainnet, sepolia } from "wagmi/chains";
32
+ import type { ReactNode } from "react";
34
33
  import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
35
- import { ZamaProvider, RelayerWeb, indexedDBStorage } from "@zama-fhe/react-sdk";
36
- import { WagmiSigner } from "@zama-fhe/react-sdk/wagmi";
34
+ import { ZamaProvider, useAllow, useConfidentialBalance, useIsAllowed } from "@zama-fhe/react-sdk";
35
+ import { createConfig } from "@zama-fhe/sdk/viem";
36
+ import { web } from "@zama-fhe/sdk/web";
37
+ import { sepolia as sepoliaFhe, type FheChain } from "@zama-fhe/sdk/chains";
38
+ import { createPublicClient, createWalletClient, custom, http, type Address } from "viem";
39
+ import { sepolia } from "viem/chains";
40
+
41
+ const tokenAddress = "0xYourConfidentialToken" as Address;
42
+ const rpcUrl = "https://sepolia.infura.io/v3/YOUR_KEY";
43
+ const publicClient = createPublicClient({
44
+ chain: sepolia,
45
+ transport: http(rpcUrl),
46
+ });
37
47
 
38
- const wagmiConfig = createConfig({
39
- chains: [mainnet, sepolia],
40
- transports: {
41
- [mainnet.id]: http("https://mainnet.infura.io/v3/YOUR_KEY"),
42
- [sepolia.id]: http("https://sepolia.infura.io/v3/YOUR_KEY"),
43
- },
48
+ const walletClient = createWalletClient({
49
+ chain: sepolia,
50
+ transport: custom(window.ethereum!),
44
51
  });
45
52
 
46
- const signer = new WagmiSigner({ config: wagmiConfig });
53
+ const chain = {
54
+ ...sepoliaFhe,
55
+ network: rpcUrl,
56
+ relayerUrl: "https://your-app.com/api/relayer/11155111",
57
+ } as const satisfies FheChain;
47
58
 
48
- const relayer = new RelayerWeb({
49
- getChainId: () => signer.getChainId(),
50
- transports: {
51
- [mainnet.id]: {
52
- relayerUrl: "https://your-app.com/api/relayer/1",
53
- network: "https://mainnet.infura.io/v3/YOUR_KEY",
54
- },
55
- [sepolia.id]: {
56
- relayerUrl: "https://your-app.com/api/relayer/11155111",
57
- network: "https://sepolia.infura.io/v3/YOUR_KEY",
58
- },
59
- },
59
+ const queryClient = new QueryClient();
60
+ const zamaConfig = createConfig({
61
+ chains: [chain],
62
+ publicClient,
63
+ walletClient,
64
+ relayers: { [chain.id]: web() },
60
65
  });
61
66
 
62
- const queryClient = new QueryClient();
67
+ function AuthGate({
68
+ contractAddresses,
69
+ children,
70
+ }: {
71
+ contractAddresses: Address[];
72
+ children: ReactNode;
73
+ }) {
74
+ const { data: isAllowed, isLoading: isChecking } = useIsAllowed({ contractAddresses });
75
+ const { mutateAsync: allow, isPending: isAuthorizing } = useAllow();
76
+
77
+ if (isChecking) return <p>Checking authorization...</p>;
78
+ if (isAllowed) return <>{children}</>;
63
79
 
64
- function App() {
65
80
  return (
66
- <WagmiProvider config={wagmiConfig}>
67
- <QueryClientProvider client={queryClient}>
68
- <ZamaProvider relayer={relayer} signer={signer} storage={indexedDBStorage}>
69
- <TokenBalance />
70
- </ZamaProvider>
71
- </QueryClientProvider>
72
- </WagmiProvider>
81
+ <button onClick={() => void allow(contractAddresses)} disabled={isAuthorizing}>
82
+ {isAuthorizing ? "Signing..." : "Authorize decryption"}
83
+ </button>
73
84
  );
74
85
  }
75
86
 
76
- function TokenBalance() {
77
- const { data: balance, isLoading } = useConfidentialBalance({ tokenAddress: "0xTokenAddress" });
87
+ function Balance() {
88
+ const { data: balance, isLoading } = useConfidentialBalance({
89
+ tokenAddress,
90
+ });
78
91
 
79
- if (isLoading) return <p>Decrypting balance...</p>;
92
+ if (isLoading) return <p>Decrypting...</p>;
80
93
  return <p>Balance: {balance?.toString()}</p>;
81
94
  }
82
- ```
83
-
84
- ### With a custom signer
85
-
86
- ```tsx
87
- import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
88
- import { mainnet, sepolia } from "wagmi/chains"; // or define your own chain IDs
89
- import {
90
- ZamaProvider,
91
- RelayerWeb,
92
- useConfidentialBalance,
93
- useConfidentialTransfer,
94
- memoryStorage,
95
- } from "@zama-fhe/react-sdk";
96
95
 
97
- const relayer = new RelayerWeb({
98
- getChainId: () => yourCustomSigner.getChainId(),
99
- transports: {
100
- [mainnet.id]: {
101
- relayerUrl: "https://your-app.com/api/relayer/1",
102
- network: "https://mainnet.infura.io/v3/YOUR_KEY",
103
- },
104
- [sepolia.id]: {
105
- relayerUrl: "https://your-app.com/api/relayer/11155111",
106
- network: "https://sepolia.infura.io/v3/YOUR_KEY",
107
- },
108
- },
109
- });
110
-
111
- const queryClient = new QueryClient();
112
-
113
- function App() {
96
+ export function App() {
114
97
  return (
115
98
  <QueryClientProvider client={queryClient}>
116
- <ZamaProvider relayer={relayer} signer={yourCustomSigner} storage={memoryStorage}>
117
- <TransferForm />
99
+ <ZamaProvider config={zamaConfig}>
100
+ <AuthGate contractAddresses={[tokenAddress]}>
101
+ <Balance />
102
+ </AuthGate>
118
103
  </ZamaProvider>
119
104
  </QueryClientProvider>
120
105
  );
121
106
  }
122
-
123
- function TransferForm() {
124
- const { data: balance } = useConfidentialBalance({ tokenAddress: "0xTokenAddress" });
125
- const { mutateAsync: transfer, isPending } = useConfidentialTransfer({
126
- tokenAddress: "0xTokenAddress",
127
- });
128
-
129
- const handleTransfer = async () => {
130
- const txHash = await transfer({ to: "0xRecipient", amount: 100n });
131
- console.log("Transfer tx:", txHash);
132
- };
133
-
134
- return (
135
- <div>
136
- <p>Balance: {balance?.toString()}</p>
137
- <button onClick={handleTransfer} disabled={isPending}>
138
- {isPending ? "Transferring..." : "Send 100 tokens"}
139
- </button>
140
- </div>
141
- );
142
- }
143
- ```
144
-
145
- ## Provider Setup
146
-
147
- All setups use `ZamaProvider`. Create a signer with the adapter for your library, then pass it directly.
148
-
149
- ```tsx
150
- import { ZamaProvider } from "@zama-fhe/react-sdk";
151
-
152
- <ZamaProvider
153
- relayer={relayer} // RelayerSDK (RelayerWeb or RelayerNode instance)
154
- signer={signer} // GenericSigner (WagmiSigner, ViemSigner, EthersSigner, or custom)
155
- storage={storage} // GenericStorage
156
- sessionStorage={sessionStorage} // Optional. Session storage for wallet signatures. Default: in-memory (lost on reload).
157
- keypairTTL={2592000} // Optional. Seconds the ML-KEM keypair remains valid. Default: 2592000 (30 days).
158
- sessionTTL={2592000} // Optional. Seconds the session signature remains valid. Default: 2592000 (30 days). 0 = re-sign every operation.
159
- onEvent={(event) => console.debug(event)} // Optional. Structured event listener for debugging.
160
- >
161
- {children}
162
- </ZamaProvider>;
163
- ```
164
-
165
- ## Which Hooks Should I Use?
166
-
167
- The React SDK exports hooks from two layers. **Pick one layer per operation — never mix them.**
168
-
169
- **Use the main import** (`@zama-fhe/react-sdk`) when you have a `ZamaProvider` in your component tree. These hooks handle FHE encryption, cache invalidation, and error wrapping automatically:
170
-
171
- ```tsx
172
- import { useShield, useConfidentialTransfer } from "@zama-fhe/react-sdk";
173
-
174
- const { mutateAsync: shield } = useShield({ tokenAddress });
175
- await shield({ amount: 1000n }); // encryption + approval handled for you
176
- ```
177
-
178
- ```tsx
179
- import { ViemSigner } from "@zama-fhe/sdk/viem";
180
- import { EthersSigner } from "@zama-fhe/sdk/ethers";
181
- ```
182
-
183
- The `WagmiSigner` is the only adapter in the react-sdk since wagmi is React-specific:
184
-
185
- ```tsx
186
- import { WagmiSigner } from "@zama-fhe/react-sdk/wagmi";
187
- ```
188
-
189
- ## Hooks Reference
190
-
191
- All hooks require a `ZamaProvider` (or one of its variants) in the component tree.
192
-
193
- ### SDK Access
194
-
195
- #### `useZamaSDK`
196
-
197
- Returns the `ZamaSDK` instance from context. Use this when you need direct access to the SDK (e.g. for low-level relayer operations).
198
-
199
- ```ts
200
- function useZamaSDK(): ZamaSDK;
201
- ```
202
-
203
- #### `useToken`
204
-
205
- Returns a `Token` instance for a given token address. The encrypted ERC-20 contract IS the wrapper, so `wrapperAddress` defaults to `tokenAddress`. Pass it only if they differ. Memoized — same config returns the same instance.
206
-
207
- ```ts
208
- function useToken(config: { tokenAddress: Address; wrapperAddress?: Address }): Token;
209
- ```
210
-
211
- #### `useReadonlyToken`
212
-
213
- Returns a `ReadonlyToken` instance for a given token address (no wrapper needed). Memoized.
214
-
215
- ```ts
216
- function useReadonlyToken(tokenAddress: Address): ReadonlyToken;
217
- ```
218
-
219
- ### Balance Hooks
220
-
221
- #### `useConfidentialBalance`
222
-
223
- Single-token balance with automatic decryption. Calls `token.balanceOf(owner)` which reads the on-chain handle and decrypts via the SDK. Cached values are returned instantly — the relayer is only hit when the handle changes. Pass `refetchInterval` to poll for updates.
224
-
225
- ```ts
226
- function useConfidentialBalance(
227
- config: UseConfidentialBalanceConfig,
228
- options?: UseConfidentialBalanceOptions,
229
- ): UseQueryResult<bigint, Error>;
230
-
231
- interface UseConfidentialBalanceConfig {
232
- tokenAddress: Address;
233
- }
234
- ```
235
-
236
- Options extend `UseQueryOptions`.
237
-
238
- ```tsx
239
- const {
240
- data: balance,
241
- isLoading,
242
- error,
243
- } = useConfidentialBalance(
244
- {
245
- tokenAddress: "0xTokenAddress",
246
- },
247
- { refetchInterval: 5_000 },
248
- );
249
- ```
250
-
251
- #### `useConfidentialBalances`
252
-
253
- Multi-token batch balance. Calls `ReadonlyToken.batchBalancesOf()` which decrypts each token's balance via the SDK. Cached values are returned instantly — the relayer is only hit for changed handles. Returns partial results when some tokens fail.
254
-
255
- ```ts
256
- function useConfidentialBalances(
257
- config: UseConfidentialBalancesConfig,
258
- options?: UseConfidentialBalancesOptions,
259
- ): UseQueryResult<BatchBalancesResult, Error>;
260
-
261
- interface UseConfidentialBalancesConfig {
262
- tokenAddresses: Address[];
263
- }
264
-
265
- interface BatchBalancesResult {
266
- results: Map<Address, bigint>;
267
- errors: Map<Address, ZamaError>;
268
- }
269
- ```
270
-
271
- ```tsx
272
- const { data } = useConfidentialBalances({
273
- tokenAddresses: ["0xTokenA", "0xTokenB", "0xTokenC"],
274
- });
275
-
276
- const tokenABalance = data?.results.get("0xTokenA");
277
- if (data && data.errors.size > 0) {
278
- // some tokens failed — check data.errors
279
- }
280
- ```
281
-
282
- ### Authorization
283
-
284
- #### `useAllow`
285
-
286
- Pre-authorize FHE decrypt credentials for a list of contract addresses with a single wallet signature. Call this early (e.g. after wallet connect) so that subsequent decrypt operations reuse cached credentials without prompting the wallet again.
287
-
288
- ```ts
289
- function useAllow(): UseMutationResult<void, Error, Address[]>;
290
- ```
291
-
292
- ```tsx
293
- const { mutateAsync: allow, isPending } = useAllow();
294
-
295
- // Pre-authorize all known contracts up front
296
- await allow(allContractAddresses);
297
-
298
- // Individual balance decrypts now reuse cached credentials
299
- const { data: balance } = useConfidentialBalance({ tokenAddress: "0xTokenA" });
300
- ```
301
-
302
- #### `useIsAllowed`
303
-
304
- Check whether a session signature is cached, valid, and scoped to the contract addresses you want to decrypt. Returns `true` if decrypt operations can proceed without a wallet prompt. Use this to conditionally enable UI elements (e.g. a "Reveal Balances" button).
305
-
306
- ```ts
307
- function useIsAllowed(config: {
308
- contractAddresses: [Address, ...Address[]];
309
- }): UseQueryResult<boolean, Error>;
310
- ```
311
-
312
- ```tsx
313
- const { data: allowed } = useIsAllowed({
314
- contractAddresses: ["0xTokenA"],
315
- });
316
-
317
- <button disabled={!allowed}>Reveal Balance</button>;
318
- ```
319
-
320
- Automatically invalidated when `useAllow` or `useRevoke` succeed.
321
-
322
- #### `useRevoke`
323
-
324
- Revoke decrypt authorization for specific contract addresses. Stored credentials remain intact, but the next decrypt operation will require a fresh wallet signature.
325
-
326
- ```ts
327
- function useRevoke(): UseMutationResult<void, Error, Address[]>;
328
- ```
329
-
330
- ```tsx
331
- const { mutate: revoke } = useRevoke();
332
-
333
- // Revoke — addresses are included in the credentials:revoked event
334
- revoke(["0xContractA", "0xContractB"]);
335
- ```
336
-
337
- ### Transfer Hooks
338
-
339
- #### `useConfidentialTransfer`
340
-
341
- Encrypted transfer. Encrypts the amount and calls the contract. Automatically invalidates balance caches on success.
342
-
343
- ```ts
344
- function useConfidentialTransfer(
345
- config: UseZamaConfig,
346
- options?: UseMutationOptions<Address, Error, ConfidentialTransferParams>,
347
- ): UseMutationResult<Address, Error, ConfidentialTransferParams>;
348
-
349
- interface ConfidentialTransferParams {
350
- to: Address;
351
- amount: bigint;
352
- }
353
- ```
354
-
355
- ```tsx
356
- const { mutateAsync: transfer, isPending } = useConfidentialTransfer({
357
- tokenAddress: "0xTokenAddress",
358
- });
359
-
360
- const txHash = await transfer({ to: "0xRecipient", amount: 1000n });
361
- ```
362
-
363
- #### `useConfidentialTransferFrom`
364
-
365
- Operator transfer on behalf of another address.
366
-
367
- ```ts
368
- function useConfidentialTransferFrom(
369
- config: UseZamaConfig,
370
- options?: UseMutationOptions<Address, Error, ConfidentialTransferFromParams>,
371
- ): UseMutationResult<Address, Error, ConfidentialTransferFromParams>;
372
-
373
- interface ConfidentialTransferFromParams {
374
- from: Address;
375
- to: Address;
376
- amount: bigint;
377
- }
378
- ```
379
-
380
- ### Shield Hooks
381
-
382
- #### `useShield`
383
-
384
- Shield public ERC-20 tokens into confidential tokens. Handles ERC-20 approval automatically.
385
-
386
- ```ts
387
- function useShield(
388
- config: UseZamaConfig,
389
- options?: UseMutationOptions<Address, Error, ShieldParams>,
390
- ): UseMutationResult<Address, Error, ShieldParams>;
391
-
392
- interface ShieldParams {
393
- amount: bigint;
394
- approvalStrategy?: "max" | "exact" | "skip"; // default: "exact"
395
- }
396
- ```
397
-
398
- ```tsx
399
- const { mutateAsync: shield } = useShield({ tokenAddress: "0xTokenAddress" });
400
-
401
- // Shield 1000 tokens with exact approval (default)
402
- await shield({ amount: 1000n });
403
-
404
- // Shield with max approval
405
- await shield({ amount: 1000n, approvalStrategy: "max" });
406
- ```
407
-
408
- ### Unshield Hooks (Combined)
409
-
410
- These hooks orchestrate the full unshield flow in a single call: unwrap → wait for receipt → parse event → finalizeUnwrap. Use these for the simplest integration.
411
-
412
- #### `useUnshield`
413
-
414
- Unshield a specific amount. Handles the entire unwrap + finalize flow. Supports optional progress callbacks to track each step.
415
-
416
- ```ts
417
- function useUnshield(
418
- config: UseZamaConfig,
419
- options?: UseMutationOptions<Address, Error, UnshieldParams>,
420
- ): UseMutationResult<Address, Error, UnshieldParams>;
421
-
422
- interface UnshieldParams extends UnshieldCallbacks {
423
- amount: bigint;
424
- skipBalanceCheck?: boolean;
425
- }
426
- ```
427
-
428
- ```tsx
429
- const { mutateAsync: unshield, isPending } = useUnshield({
430
- tokenAddress: "0xTokenAddress",
431
- });
432
-
433
- const finalizeTxHash = await unshield({
434
- amount: 500n,
435
- onUnwrapSubmitted: (txHash) => console.log("Unwrap tx:", txHash),
436
- onFinalizing: () => console.log("Finalizing..."),
437
- onFinalizeSubmitted: (txHash) => console.log("Finalize tx:", txHash),
438
- });
439
- ```
440
-
441
- #### `useUnshieldAll`
442
-
443
- Unshield the entire balance. Handles the entire unwrap + finalize flow. Supports optional progress callbacks.
444
-
445
- ```ts
446
- function useUnshieldAll(
447
- config: UseZamaConfig,
448
- options?: UseMutationOptions<Address, Error, UnshieldAllParams | void>,
449
- ): UseMutationResult<Address, Error, UnshieldAllParams | void>;
450
-
451
- interface UnshieldAllParams extends UnshieldCallbacks {}
452
- ```
453
-
454
- ```tsx
455
- const { mutateAsync: unshieldAll } = useUnshieldAll({
456
- tokenAddress: "0xTokenAddress",
457
- });
458
-
459
- const finalizeTxHash = await unshieldAll();
460
- ```
461
-
462
- #### `useResumeUnshield`
463
-
464
- Resume an interrupted unshield from a saved unwrap tx hash. Useful when the user submitted the unwrap but the finalize step was interrupted (e.g. page reload, network error). Pair with the `savePendingUnshield`/`loadPendingUnshield`/`clearPendingUnshield` utilities for persistence.
465
-
466
- ```ts
467
- function useResumeUnshield(
468
- config: UseZamaConfig,
469
- options?: UseMutationOptions<Address, Error, ResumeUnshieldParams>,
470
- ): UseMutationResult<Address, Error, ResumeUnshieldParams>;
471
-
472
- interface ResumeUnshieldParams extends UnshieldCallbacks {
473
- unwrapTxHash: Hex;
474
- }
475
- ```
476
-
477
- ```tsx
478
- import { loadPendingUnshield, clearPendingUnshield } from "@zama-fhe/react-sdk";
479
-
480
- const { mutateAsync: resumeUnshield } = useResumeUnshield({
481
- tokenAddress: "0xTokenAddress",
482
- });
483
-
484
- // On mount, check for interrupted unshields
485
- const pending = await loadPendingUnshield(storage, wrapperAddress);
486
- if (pending) {
487
- await resumeUnshield({ unwrapTxHash: pending });
488
- await clearPendingUnshield(storage, wrapperAddress);
489
- }
490
- ```
491
-
492
- #### Pending Unshield Persistence
493
-
494
- Save the unwrap tx hash before finalization so interrupted unshields can be resumed after page reloads:
495
-
496
- ```ts
497
- import {
498
- savePendingUnshield,
499
- loadPendingUnshield,
500
- clearPendingUnshield,
501
- } from "@zama-fhe/react-sdk";
502
-
503
- // Save before the finalize step
504
- await savePendingUnshield(storage, wrapperAddress, unwrapTxHash);
505
-
506
- // Load on next visit
507
- const pending = await loadPendingUnshield(storage, wrapperAddress);
508
-
509
- // Clear after successful finalization
510
- await clearPendingUnshield(storage, wrapperAddress);
511
- ```
512
-
513
- ### Unwrap Hooks (Low-Level)
514
-
515
- These hooks expose the individual unwrap steps. Use them when you need fine-grained control over the flow.
516
-
517
- #### `useUnwrap`
518
-
519
- Request unwrap for a specific amount (requires manual finalization via `useFinalizeUnwrap`).
520
-
521
- ```ts
522
- function useUnwrap(
523
- config: UseZamaConfig,
524
- options?: UseMutationOptions<Address, Error, UnwrapParams>,
525
- ): UseMutationResult<Address, Error, UnwrapParams>;
526
-
527
- interface UnwrapParams {
528
- amount: bigint;
529
- }
530
- ```
531
-
532
- #### `useUnwrapAll`
533
-
534
- Request unwrap for the entire balance (requires manual finalization).
535
-
536
- ```ts
537
- function useUnwrapAll(
538
- config: UseZamaConfig,
539
- options?: UseMutationOptions<Address, Error, void>,
540
- ): UseMutationResult<Address, Error, void>;
541
- ```
542
-
543
- #### `useFinalizeUnwrap`
544
-
545
- Complete an unwrap by providing the decryption proof.
546
-
547
- ```ts
548
- function useFinalizeUnwrap(
549
- config: UseZamaConfig,
550
- options?: UseMutationOptions<Address, Error, FinalizeUnwrapParams>,
551
- ): UseMutationResult<Address, Error, FinalizeUnwrapParams>;
552
-
553
- interface FinalizeUnwrapParams {
554
- burnAmountHandle: Address;
555
- }
556
107
  ```
557
108
 
558
- ### Delegation Hooks
559
-
560
- #### `useDelegateDecryption`
561
-
562
- Grant decryption delegation to another address via the on-chain ACL. ACL address is resolved automatically from the relayer transport config.
563
-
564
- ```ts
565
- function useDelegateDecryption(
566
- config: UseZamaConfig,
567
- options?: UseMutationOptions<TransactionResult, Error, DelegateDecryptionParams>,
568
- ): UseMutationResult<TransactionResult, Error, DelegateDecryptionParams>;
569
-
570
- interface DelegateDecryptionParams {
571
- delegateAddress: Address;
572
- expirationDate?: Date;
573
- }
574
- ```
575
-
576
- ```tsx
577
- const { mutateAsync: delegate, isPending } = useDelegateDecryption({
578
- tokenAddress: "0xToken",
579
- });
580
-
581
- // Permanent delegation
582
- await delegate({ delegateAddress: "0xDelegate" });
583
-
584
- // With expiration
585
- await delegate({
586
- delegateAddress: "0xDelegate",
587
- expirationDate: new Date("2025-12-31"),
588
- });
589
- ```
590
-
591
- #### `useDecryptBalanceAs`
592
-
593
- Decrypt another user's balance as a delegate. Uses the delegated EIP-712 flow — the connected wallet signs as the delegate, and the relayer verifies the on-chain delegation.
594
-
595
- ```ts
596
- function useDecryptBalanceAs(
597
- tokenAddress: Address,
598
- options?: UseMutationOptions<bigint, Error, DecryptBalanceAsParams>,
599
- ): UseMutationResult<bigint, Error, DecryptBalanceAsParams>;
600
-
601
- interface DecryptBalanceAsParams {
602
- delegatorAddress: Address;
603
- owner?: Address;
604
- }
605
- ```
606
-
607
- ```tsx
608
- const { mutateAsync: decryptAs, data: balance } = useDecryptBalanceAs("0xToken");
609
-
610
- // Decrypt the delegator's balance
611
- const result = await decryptAs({ delegatorAddress: "0xDelegator" });
612
- // result => bigint
613
- ```
614
-
615
- ### Approval Hooks
616
-
617
- #### `useConfidentialApprove`
618
-
619
- Set operator approval for the confidential token.
620
-
621
- ```ts
622
- function useConfidentialApprove(
623
- config: UseZamaConfig,
624
- options?: UseMutationOptions<Address, Error, ConfidentialApproveParams>,
625
- ): UseMutationResult<Address, Error, ConfidentialApproveParams>;
626
-
627
- interface ConfidentialApproveParams {
628
- spender: Address;
629
- until?: number; // Unix timestamp, defaults to now + 1 hour
630
- }
631
- ```
632
-
633
- #### `useConfidentialIsApproved`
634
-
635
- Check if a spender is an approved operator. Enabled only when `spender` is defined.
636
-
637
- ```ts
638
- function useConfidentialIsApproved(
639
- config: UseZamaConfig,
640
- spender: Address | undefined,
641
- options?: Omit<UseQueryOptions<boolean, Error>, "queryKey" | "queryFn">,
642
- ): UseQueryResult<boolean, Error>;
643
- ```
644
-
645
- #### `useUnderlyingAllowance`
646
-
647
- Read the underlying ERC-20 allowance granted to the wrapper.
648
-
649
- ```ts
650
- function useUnderlyingAllowance(
651
- config: UseUnderlyingAllowanceConfig,
652
- options?: Omit<UseQueryOptions<bigint, Error>, "queryKey" | "queryFn">,
653
- ): UseQueryResult<bigint, Error>;
654
-
655
- interface UseUnderlyingAllowanceConfig {
656
- tokenAddress: Address;
657
- wrapperAddress: Address;
658
- }
659
- ```
660
-
661
- ### Discovery & Metadata
662
-
663
- #### `useWrapperDiscovery`
664
-
665
- Find the wrapper contract for a given token via the on-chain registry. Enabled only when `erc20Address` is defined. Results are cached indefinitely (`staleTime: Infinity`).
666
-
667
- ```ts
668
- function useWrapperDiscovery(
669
- config: UseWrapperDiscoveryConfig,
670
- options?: Omit<UseQueryOptions<Address | null, Error>, "queryKey" | "queryFn">,
671
- ): UseQueryResult<Address | null, Error>;
672
-
673
- interface UseWrapperDiscoveryConfig {
674
- tokenAddress: Address;
675
- erc20Address: Address | undefined;
676
- }
677
- ```
678
-
679
- #### `useTokenMetadata`
680
-
681
- Fetch token name, symbol, and decimals in parallel. Cached indefinitely.
682
-
683
- ```ts
684
- function useTokenMetadata(
685
- tokenAddress: Address,
686
- options?: Omit<UseQueryOptions<TokenMetadata, Error>, "queryKey" | "queryFn">,
687
- ): UseQueryResult<TokenMetadata, Error>;
688
-
689
- interface TokenMetadata {
690
- name: string;
691
- symbol: string;
692
- decimals: number;
693
- }
694
- ```
695
-
696
- ```tsx
697
- const { data: meta } = useTokenMetadata("0xTokenAddress");
698
- // meta?.name, meta?.symbol, meta?.decimals
699
- ```
700
-
701
- ### Low-Level FHE Hooks
702
-
703
- These hooks are for **custom FHE contracts** (non-token contracts that use encrypted types directly). For confidential ERC-20 tokens, use the high-level token hooks above instead. For detailed usage examples, see the [Encrypt & Decrypt guide](../../docs/gitbook/src/guides/encrypt-decrypt.md).
704
-
705
- #### Encryption
706
-
707
- ```tsx
708
- const encrypt = useEncrypt();
709
-
710
- const { handles, inputProof } = await encrypt.mutateAsync({
711
- values: [{ value: 1000n, type: "euint64" }],
712
- contractAddress: "0xYourContract",
713
- userAddress,
714
- });
715
-
716
- // Pass handles and inputProof to your contract call
717
- ```
718
-
719
- #### Decryption (`useUserDecrypt`)
720
-
721
- `useUserDecrypt` is a TanStack Query hook that manages the full decrypt orchestration — keypair generation, EIP-712, wallet signature — and reuses cached credentials when available, avoiding redundant wallet prompts. It is **disabled by default**; pass `enabled: true` to fire the query.
722
-
723
- ```tsx
724
- const { data, isPending, isSuccess } = useUserDecrypt(
725
- {
726
- handles: [
727
- { handle: "0xabc...", contractAddress: "0xTokenA" },
728
- { handle: "0xdef...", contractAddress: "0xTokenB" },
729
- ],
730
- },
731
- { enabled: shouldDecrypt },
732
- );
733
- // data: { "0xabc...": 500n, "0xdef...": 1000n }
734
- ```
735
-
736
- #### All Encryption & Decryption Hooks
737
-
738
- | Hook | Input | Output | Description |
739
- | --------------------------- | ---------------------------- | ------------------------ | ---------------------------------------------------------------------------- |
740
- | `useEncrypt()` | `EncryptParams` | `EncryptResult` | Encrypt values for smart contract calls. |
741
- | `useUserDecrypt()` | `UserDecryptQueryConfig` | `DecryptResult` | User decryption query with TanStack Query semantics. Results cached. |
742
- | `usePublicDecrypt()` | `string[]` (handles) | `PublicDecryptResult` | Public decryption (no authorization needed). Populates the decryption cache. |
743
- | `useDelegatedUserDecrypt()` | `DelegatedUserDecryptParams` | `Record<string, bigint>` | Decrypt via delegation. |
744
-
745
- #### Key Management
746
-
747
- | Hook | Input | Output | Description |
748
- | --------------------------------------- | ---------------------------------------- | ----------------------------------- | ---------------------------------------------------- |
749
- | `useGenerateKeypair()` | `void` | `FHEKeypair` | Generate an FHE keypair. |
750
- | `useCreateEIP712()` | `CreateEIP712Params` | `EIP712TypedData` | Create EIP-712 typed data for decrypt authorization. |
751
- | `useCreateDelegatedUserDecryptEIP712()` | `CreateDelegatedUserDecryptEIP712Params` | `KmsDelegatedUserDecryptEIP712Type` | Create EIP-712 for delegated decryption. |
752
- | `useRequestZKProofVerification()` | `ZKProofLike` | `InputProofBytesType` | Submit a ZK proof for verification. |
753
-
754
- #### Network
755
-
756
- | Hook | Input | Output | Description |
757
- | ------------------- | --------------- | ------------------------------------------ | ------------------------------------- |
758
- | `usePublicKey()` | `void` | `{ publicKeyId, publicKey } \| null` | Get the TFHE compact public key. |
759
- | `usePublicParams()` | `number` (bits) | `{ publicParams, publicParamsId } \| null` | Get public parameters for encryption. |
760
-
761
- ## Query Keys
762
-
763
- Use `zamaQueryKeys` for manual cache management (invalidation, prefetching, removal).
764
-
765
- ```ts
766
- import { zamaQueryKeys, decryptionKeys } from "@zama-fhe/react-sdk";
767
- ```
768
-
769
- | Factory | Keys | Description |
770
- | ------------------------------------ | ------------------------------------------------------------ | ----------------------------------- |
771
- | `zamaQueryKeys.confidentialBalance` | `.all`, `.token(address)`, `.owner(address, owner)` | Single-token decrypted balance. |
772
- | `zamaQueryKeys.confidentialBalances` | `.all`, `.tokens(addresses, owner)` | Multi-token batch balances. |
773
- | `zamaQueryKeys.isAllowed` | `.all` | Session signature status. |
774
- | `zamaQueryKeys.underlyingAllowance` | `.all`, `.token(address)`, `.scope(address, owner, wrapper)` | Underlying ERC-20 allowance. |
775
- | `decryptionKeys` | `.value(handle)` | Individual decrypted handle values. |
776
-
777
- ```tsx
778
- import { useQueryClient } from "@tanstack/react-query";
779
- import { zamaQueryKeys } from "@zama-fhe/react-sdk";
780
-
781
- const queryClient = useQueryClient();
782
-
783
- // Invalidate all balances
784
- queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalance.all });
785
-
786
- // Invalidate a specific token's balance
787
- queryClient.invalidateQueries({
788
- queryKey: zamaQueryKeys.confidentialBalance.token("0xTokenAddress"),
789
- });
790
- ```
791
-
792
- ## Wagmi Signer Adapter
793
-
794
- ```ts
795
- import { WagmiSigner } from "@zama-fhe/react-sdk/wagmi";
796
-
797
- const signer = new WagmiSigner({ config: wagmiConfig });
798
- ```
799
-
800
- ## Signer Adapters
801
-
802
- Signer adapters are provided by the core SDK package:
803
-
804
- ```ts
805
- import { ViemSigner } from "@zama-fhe/sdk/viem";
806
- import { EthersSigner } from "@zama-fhe/sdk/ethers";
807
- ```
808
-
809
- ## Wallet Integration Guide
810
-
811
- ### SSR / Next.js
812
-
813
- All components using SDK hooks must be client components. Add `"use client"` at the top of files that import from `@zama-fhe/react-sdk`. FHE operations (encryption, decryption) run in a Web Worker and require browser APIs — they cannot execute on the server.
814
-
815
- ```tsx
816
- "use client";
817
-
818
- import { useConfidentialBalance } from "@zama-fhe/react-sdk";
819
- ```
820
-
821
- Place `ZamaProvider` inside your client-only layout. Do **not** create the relayer or signer at the module level in a server component — wrap them in a client component or use lazy initialization.
822
-
823
- ### FHE Credentials Lifecycle
824
-
825
- FHE decrypt credentials are generated once per wallet + contract set and cached in the storage backend you provide (e.g. `IndexedDBStorage`). The wallet signature is kept **in memory only** — never persisted to disk. The lifecycle:
826
-
827
- 1. **First decrypt** — SDK generates an FHE keypair, creates EIP-712 typed data, and prompts the wallet to sign. The encrypted credential is stored; the signature is cached in memory.
828
- 2. **Same session** — Cached credentials and session signature are reused silently (no wallet prompt).
829
- 3. **Page reload** — Encrypted credentials are loaded from storage; the wallet is prompted once to re-sign for the session.
830
- 4. **Expiry** — Credentials expire based on `keypairTTL` (default: 2592000s = 30 days). After expiry, the next decrypt regenerates and re-prompts.
831
- 5. **Pre-authorization** — Call `useAllow(contractAddresses)` early to batch-authorize all contracts in one wallet prompt, avoiding repeated popups.
832
- 6. **Check status** — Use `useIsAllowed({ contractAddresses })` to conditionally enable UI elements (e.g. disable "Reveal" until allowed).
833
- 7. **Disconnect** — Call `useRevoke(contractAddresses)` or `await credentials.revoke()` to clear the session signature from memory.
834
-
835
- ### Web Extension Support
836
-
837
- By default, wallet signatures are stored in memory and lost on page reload (or service worker restart). For MV3 web extensions, use the built-in `chromeSessionStorage` singleton so signatures survive service worker restarts and are shared across popup, background, and content script contexts:
838
-
839
- ```tsx
840
- import { chromeSessionStorage } from "@zama-fhe/react-sdk";
841
-
842
- <ZamaProvider
843
- relayer={relayer}
844
- signer={signer}
845
- storage={indexedDBStorage}
846
- sessionStorage={chromeSessionStorage}
847
- >
848
- <App />
849
- </ZamaProvider>;
850
- ```
851
-
852
- This keeps the encrypted credentials in IndexedDB (persistent) while the unlock signature lives in `chrome.storage.session` (ephemeral, cleared when the browser closes).
853
-
854
- ### Error-to-User-Message Mapping
855
-
856
- Map SDK errors to user-friendly messages in your UI:
857
-
858
- ```tsx
859
- import {
860
- SigningRejectedError,
861
- EncryptionFailedError,
862
- DecryptionFailedError,
863
- TransactionRevertedError,
864
- ApprovalFailedError,
865
- } from "@zama-fhe/react-sdk";
866
-
867
- function getUserMessage(error: Error): string {
868
- if (error instanceof SigningRejectedError)
869
- return "Transaction cancelled — please approve in your wallet.";
870
- if (error instanceof EncryptionFailedError) return "Encryption failed — please try again.";
871
- if (error instanceof DecryptionFailedError) return "Decryption failed — please try again.";
872
- if (error instanceof ApprovalFailedError) return "Token approval failed — please try again.";
873
- if (error instanceof TransactionRevertedError)
874
- return "Transaction failed on-chain — check your balance.";
875
- return "An unexpected error occurred.";
876
- }
877
- ```
878
-
879
- Or use `matchZamaError` for a more concise pattern:
880
-
881
- ```tsx
882
- import { matchZamaError } from "@zama-fhe/react-sdk";
883
-
884
- const message = matchZamaError(error, {
885
- SIGNING_REJECTED: () => "Transaction cancelled — please approve in your wallet.",
886
- ENCRYPTION_FAILED: () => "Encryption failed — please try again.",
887
- DECRYPTION_FAILED: () => "Decryption failed — please try again.",
888
- APPROVAL_FAILED: () => "Token approval failed — please try again.",
889
- TRANSACTION_REVERTED: () => "Transaction failed on-chain — check your balance.",
890
- _: () => "An unexpected error occurred.",
891
- });
892
- ```
893
-
894
- ### Balance Caching and Refresh
895
-
896
- Balance queries call `token.balanceOf(owner)`, which reads the encrypted handle on-chain and decrypts via `sdk.userDecrypt`. The SDK's `DecryptCache` returns previously decrypted values instantly when the handle hasn't changed — the expensive relayer round-trip only runs when the balance actually changes. Pass `refetchInterval` to poll for on-chain updates.
897
-
898
- Mutation hooks (`useConfidentialTransfer`, `useShield`, `useUnshield`, etc.) automatically invalidate the relevant caches on success, so the UI updates immediately after user actions.
899
-
900
- To force a refresh:
901
-
902
- ```tsx
903
- const queryClient = useQueryClient();
904
- queryClient.invalidateQueries({ queryKey: zamaQueryKeys.confidentialBalance.all });
905
- ```
906
-
907
- ## Re-exports from Core SDK
908
-
909
- All public exports from `@zama-fhe/sdk` are re-exported from the main entry point. You never need to import from the core package directly.
910
-
911
- **Classes:** `RelayerWeb`, `ZamaSDK`, `Token`, `ReadonlyToken`, `MemoryStorage`, `memoryStorage`, `IndexedDBStorage`, `indexedDBStorage`, `CredentialsManager`.
912
-
913
- **Network configs:** `SepoliaConfig`, `MainnetConfig`, `HardhatConfig`.
914
-
915
- **Pending unshield:** `savePendingUnshield`, `loadPendingUnshield`, `clearPendingUnshield`.
109
+ This keeps `Balance` from mounting until the contract is authorized, so the first decrypt happens after an explicit user action instead of an unsolicited wallet popup.
916
110
 
917
- **Types:** `Address`, `ZamaSDKConfig`, `ReadonlyTokenConfig`, `NetworkType`, `RelayerSDK`, `RelayerSDKStatus`, `EncryptResult`, `EncryptParams`, `UserDecryptParams`, `PublicDecryptResult`, `KeypairType`, `EIP712TypedData`, `DelegatedUserDecryptParams`, `KmsDelegatedUserDecryptEIP712Type`, `ZKProofLike`, `InputProofBytesType`, `StoredCredentials`, `GenericSigner`, `GenericStorage`, `TransactionReceipt`, `TransactionResult`, `UnshieldCallbacks`.
111
+ If you need a wagmi-based setup or another integration pattern, start from the [Quick start](https://github.com/zama-ai/sdk/blob/main/docs/gitbook/src/tutorials/quick-start.md) and the [Guides](https://github.com/zama-ai/sdk/blob/main/docs/gitbook/src/guides/README.md).
918
112
 
919
- **Errors:** `ZamaError`, `ZamaErrorCode`, `SigningRejectedError`, `SigningFailedError`, `EncryptionFailedError`, `DecryptionFailedError`, `ApprovalFailedError`, `TransactionRevertedError`, `InvalidKeypairError`, `NoCiphertextError`, `RelayerRequestFailedError`, `matchZamaError`.
113
+ ## Using the provider and hooks
920
114
 
921
- **Constants:** `ZERO_HANDLE`, `ERC7984_INTERFACE_ID`, `ERC7984_WRAPPER_INTERFACE_ID`.
115
+ - `ZamaProvider` accepts a prebuilt `ZamaConfig`, so you can pair the React hooks with viem, ethers, or another signer setup from the core SDK.
116
+ - For wagmi-based apps, follow the Quick start and guides for the current recommended setup.
117
+ - Hooks from `@zama-fhe/react-sdk` handle confidential operations, cached decryption, and query invalidation for you.
118
+ - Lower-level SDK utilities, adapters, and token classes still come from `@zama-fhe/sdk`.
922
119
 
923
- **ABIs:** `ERC20_ABI`, `ERC20_METADATA_ABI`, `DEPLOYMENT_COORDINATOR_ABI`, `ERC165_ABI`, `ENCRYPTION_ABI`, `TRANSFER_BATCHER_ABI`, `WRAPPER_ABI`, `BATCH_SWAP_ABI`.
120
+ ## Common hooks
924
121
 
925
- **Events:** `RawLog`, `ConfidentialTransferEvent`, `WrappedEvent`, `UnwrapRequestedEvent`, `UnwrappedFinalizedEvent`, `UnwrappedStartedEvent`, `OnChainEvent`, `Topics`, `TOKEN_TOPICS`.
122
+ - `useIsAllowed` and `useAllow` let you gate decrypt flows behind an explicit user action.
123
+ - `useConfidentialBalance` reads and decrypts one token balance.
124
+ - `useConfidentialTransfer` sends a confidential transfer and invalidates affected queries.
125
+ - `useShield` converts public ERC-20 balances into confidential balances.
126
+ - `useUnshield` moves confidential balances back to public ERC-20 balances.
127
+ - `useDelegateDecryption` grants another account permission to decrypt a balance.
926
128
 
927
- **Event decoders:** `decodeConfidentialTransfer`, `decodeWrapped`, `decodeUnwrapRequested`, `decodeUnwrappedFinalized`, `decodeUnwrappedStarted`, `decodeOnChainEvent`, `decodeOnChainEvents`, `findUnwrapRequested`, `findWrapped`.
129
+ ## Documentation
928
130
 
929
- **Contract call builders:** `confidentialBalanceOfContract`, `confidentialTransferContract`, `confidentialTransferFromContract`, `isOperatorContract`, `unwrapContract`, `unwrapFromBalanceContract`, `finalizeUnwrapContract`, `setOperatorContract`, `underlyingContract`, `inferredTotalSupplyContract`, `wrapContract`, `supportsInterfaceContract`, `isConfidentialTokenContract`, `isConfidentialWrapperContract`, `nameContract`, `symbolContract`, `decimalsContract`, `allowanceContract`, `approveContract`, `confidentialTotalSupplyContract`, `totalSupplyContract`, `rateContract`.
131
+ - [Official documentation](https://docs.zama.org/protocol) is the best starting point for the hosted SDK docs.
132
+ - [Quick start](https://github.com/zama-ai/sdk/blob/main/docs/gitbook/src/tutorials/quick-start.md) shows the full React setup from install to first transfer.
133
+ - [React reference](https://github.com/zama-ai/sdk/blob/main/docs/gitbook/src/reference/react/README.md) documents all hooks, provider components, and query helpers.
134
+ - [Guides](https://github.com/zama-ai/sdk/blob/main/docs/gitbook/src/guides/README.md) cover focused topics such as authentication, SSR, browser extensions, balances, and transfers.
135
+ - [Core SDK reference](https://github.com/zama-ai/sdk/blob/main/docs/gitbook/src/reference/sdk/README.md) documents lower-level SDK classes, adapters, and utilities.