0
# Advanced Features
1
2
Advanced functionality including proof generation, SSR hydration, context management, and error handling. This module covers specialized wagmi features for complex applications and edge cases.
3
4
## Capabilities
5
6
### useProof
7
8
Hook to get account proof data for cryptographic verification and state proofs.
9
10
```typescript { .api }
11
/**
12
* Hook to get account proof
13
* @param parameters - Account proof query parameters
14
* @returns Account proof data with storage proofs
15
*/
16
function useProof<config = Config, selectData = UseProofReturnType>(
17
parameters: UseProofParameters<config, selectData>
18
): UseProofReturnType<selectData>;
19
20
interface UseProofParameters<config = Config, selectData = UseProofReturnType> {
21
/** Address to generate proof for */
22
address: Address;
23
/** Storage keys to include in proof */
24
storageKeys: Hex[];
25
/** Block number to generate proof at */
26
blockNumber?: bigint;
27
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
28
/** Chain to use */
29
chainId?: config['chains'][number]['id'];
30
config?: Config | config;
31
query?: {
32
enabled?: boolean;
33
staleTime?: number;
34
gcTime?: number;
35
select?: (data: UseProofReturnType) => selectData;
36
};
37
}
38
39
interface UseProofReturnType {
40
/** Account address */
41
address: Address;
42
/** Account nonce */
43
nonce: Hex;
44
/** Account balance */
45
balance: Hex;
46
/** Code hash */
47
codeHash: Hex;
48
/** Storage hash */
49
storageHash: Hex;
50
/** Account proof */
51
accountProof: Hex[];
52
/** Storage proofs */
53
storageProof: StorageProof[];
54
}
55
56
interface StorageProof {
57
/** Storage key */
58
key: Hex;
59
/** Storage value */
60
value: Hex;
61
/** Storage proof */
62
proof: Hex[];
63
}
64
```
65
66
**Usage Example:**
67
68
```typescript
69
import { useProof } from "wagmi";
70
71
function AccountProofGenerator() {
72
const { data: proof, isLoading } = useProof({
73
address: '0x742d35Cc6634C0532925a3b8D',
74
storageKeys: [
75
'0x0000000000000000000000000000000000000000000000000000000000000000',
76
],
77
});
78
79
if (isLoading) return <div>Generating proof...</div>;
80
81
return (
82
<div>
83
<h3>Account Proof</h3>
84
<p>Address: {proof?.address}</p>
85
<p>Nonce: {proof?.nonce}</p>
86
<p>Balance: {proof?.balance}</p>
87
<p>Storage Proofs: {proof?.storageProof.length}</p>
88
<details>
89
<summary>Account Proof ({proof?.accountProof.length} items)</summary>
90
{proof?.accountProof.map((item, i) => (
91
<p key={i} style={{ fontSize: '0.8em', wordBreak: 'break-all' }}>
92
{item}
93
</p>
94
))}
95
</details>
96
</div>
97
);
98
}
99
```
100
101
## Context and Provider System
102
103
### WagmiProvider
104
105
Main provider component that configures wagmi for your application.
106
107
```typescript { .api }
108
/**
109
* Main provider component for wagmi configuration
110
* @param props - Provider configuration
111
* @returns React provider component
112
*/
113
function WagmiProvider(props: WagmiProviderProps): JSX.Element;
114
115
interface WagmiProviderProps {
116
/** Wagmi configuration object */
117
config: ResolvedRegister['config'];
118
/** Initial state for SSR/hydration */
119
initialState?: State;
120
/** Whether to reconnect on mount (default: true) */
121
reconnectOnMount?: boolean;
122
/** React children */
123
children: React.ReactNode;
124
}
125
126
interface ResolvedRegister {
127
config: Config;
128
}
129
130
interface Config {
131
/** Configured chains */
132
chains: readonly Chain[];
133
/** Available connectors */
134
connectors: Connector[];
135
/** Transport configuration */
136
transports: Record<number, Transport>;
137
/** Internal state */
138
state: State;
139
/** Storage implementation */
140
storage?: Storage;
141
/** SSR mode */
142
ssr?: boolean;
143
/** Sync connected chain */
144
syncConnectedChain?: boolean;
145
/** Multi-injected provider discovery */
146
multiInjectedProviderDiscovery?: boolean;
147
}
148
```
149
150
### WagmiContext
151
152
React context for accessing wagmi configuration and state.
153
154
```typescript { .api }
155
/**
156
* React context for wagmi configuration access
157
*/
158
const WagmiContext: React.Context<Config | undefined>;
159
160
/**
161
* Hook to access wagmi context
162
* @returns Wagmi configuration
163
* @throws WagmiProviderNotFoundError if used outside provider
164
*/
165
function useConfig(): Config;
166
```
167
168
### Hydrate
169
170
Component for handling SSR hydration with wagmi state.
171
172
```typescript { .api }
173
/**
174
* Component for SSR hydration support
175
* @param props - Hydration configuration
176
* @returns React component for hydration
177
*/
178
function Hydrate(props: HydrateProps): JSX.Element;
179
180
interface HydrateProps {
181
/** Wagmi configuration */
182
config: ResolvedRegister['config'];
183
/** Initial state for hydration */
184
initialState?: State;
185
/** Whether to reconnect on mount */
186
reconnectOnMount?: boolean;
187
/** React children */
188
children: React.ReactNode;
189
}
190
```
191
192
**Usage Example:**
193
194
```typescript
195
import { Hydrate, WagmiProvider } from "wagmi";
196
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
197
198
// Server-side
199
function getInitialState() {
200
// Return serialized wagmi state from server
201
return {
202
chainId: 1,
203
connections: new Map(),
204
current: undefined,
205
status: 'disconnected' as const,
206
};
207
}
208
209
// Client-side
210
function App({ initialState }: { initialState?: State }) {
211
const queryClient = new QueryClient();
212
213
return (
214
<WagmiProvider config={config}>
215
<QueryClientProvider client={queryClient}>
216
<Hydrate initialState={initialState}>
217
<MyApp />
218
</Hydrate>
219
</QueryClientProvider>
220
</WagmiProvider>
221
);
222
}
223
```
224
225
## Error Handling
226
227
### WagmiProviderNotFoundError
228
229
Error thrown when wagmi hooks are used outside of WagmiProvider context.
230
231
```typescript { .api }
232
/**
233
* Error thrown when WagmiProvider context is not found
234
*/
235
class WagmiProviderNotFoundError extends BaseError {
236
name: 'WagmiProviderNotFoundError';
237
constructor();
238
}
239
240
/**
241
* Type for WagmiProviderNotFoundError
242
*/
243
type WagmiProviderNotFoundErrorType = WagmiProviderNotFoundError;
244
```
245
246
### BaseError
247
248
Base error class for all wagmi React errors.
249
250
```typescript { .api }
251
/**
252
* Base error class for wagmi React errors
253
*/
254
class BaseError extends Error {
255
name: 'BaseError';
256
constructor(shortMessage: string, args?: BaseErrorParameters);
257
}
258
259
interface BaseErrorParameters {
260
cause?: unknown;
261
details?: string;
262
docsPath?: string;
263
metaMessages?: string[];
264
}
265
266
/**
267
* Type for BaseError
268
*/
269
type BaseErrorType = BaseError;
270
```
271
272
**Error Handling Example:**
273
274
```typescript
275
import { useAccount, WagmiProviderNotFoundError } from "wagmi";
276
277
function ErrorBoundaryComponent() {
278
try {
279
const { address } = useAccount();
280
return <div>Address: {address}</div>;
281
} catch (error) {
282
if (error instanceof WagmiProviderNotFoundError) {
283
return (
284
<div>
285
Error: Wagmi hooks must be used within WagmiProvider.
286
Please wrap your component with WagmiProvider.
287
</div>
288
);
289
}
290
throw error; // Re-throw other errors
291
}
292
}
293
```
294
295
## Advanced Client Management
296
297
### useConnectorClient
298
299
Hook to get the connector's client instance for direct interaction.
300
301
```typescript { .api }
302
/**
303
* Hook to get connector's client
304
* @param parameters - Connector client parameters
305
* @returns Connector client instance
306
*/
307
function useConnectorClient<config = Config>(
308
parameters?: UseConnectorClientParameters<config>
309
): UseConnectorClientReturnType<config>;
310
311
interface UseConnectorClientParameters<config = Config> {
312
/** Specific connector to get client for */
313
connector?: Connector;
314
/** Chain ID for the client */
315
chainId?: config['chains'][number]['id'];
316
config?: Config | config;
317
query?: {
318
enabled?: boolean;
319
staleTime?: number;
320
gcTime?: number;
321
};
322
}
323
324
type UseConnectorClientReturnType<config = Config> = {
325
data?: ConnectorClient;
326
error: Error | null;
327
isError: boolean;
328
isLoading: boolean;
329
isSuccess: boolean;
330
status: 'error' | 'loading' | 'success';
331
};
332
333
interface ConnectorClient {
334
/** Client instance */
335
client: Client;
336
/** Transport configuration */
337
transport: Transport;
338
/** Account information */
339
account?: Account;
340
/** Chain information */
341
chain?: Chain;
342
}
343
```
344
345
### useWalletClient
346
347
Hook to get a wallet client for signing operations.
348
349
```typescript { .api }
350
/**
351
* Hook to get wallet client for signing
352
* @param parameters - Wallet client parameters
353
* @returns Wallet client instance
354
*/
355
function useWalletClient<config = Config, selectData = UseWalletClientReturnType>(
356
parameters?: UseWalletClientParameters<config, selectData>
357
): UseWalletClientReturnType<selectData>;
358
359
interface UseWalletClientParameters<config = Config, selectData = UseWalletClientReturnType> {
360
/** Account to get wallet client for */
361
account?: Address;
362
/** Chain ID */
363
chainId?: config['chains'][number]['id'];
364
config?: Config | config;
365
query?: {
366
enabled?: boolean;
367
staleTime?: number;
368
gcTime?: number;
369
select?: (data: UseWalletClientReturnType) => selectData;
370
};
371
}
372
373
type UseWalletClientReturnType = WalletClient | undefined;
374
375
interface WalletClient extends Client {
376
/** Account for wallet operations */
377
account: Account;
378
/** Request permissions */
379
requestPermissions?: (permissions: Permission[]) => Promise<Permission[]>;
380
/** Get permissions */
381
getPermissions?: () => Promise<Permission[]>;
382
/** Switch chain */
383
switchChain?: (args: { id: number }) => Promise<void>;
384
/** Watch asset */
385
watchAsset?: (asset: WatchAssetParams) => Promise<boolean>;
386
}
387
```
388
389
## Configuration Utilities
390
391
### createConfig
392
393
Function to create wagmi configuration with type safety.
394
395
```typescript { .api }
396
/**
397
* Create wagmi configuration
398
* @param parameters - Configuration parameters
399
* @returns Configured wagmi config
400
*/
401
function createConfig(parameters: CreateConfigParameters): Config;
402
403
interface CreateConfigParameters {
404
/** Supported chains */
405
chains: readonly [Chain, ...Chain[]];
406
/** Available connectors */
407
connectors?: Connector[];
408
/** Transport configuration per chain */
409
transports: Record<number, Transport>;
410
/** Storage implementation */
411
storage?: Storage;
412
/** SSR support */
413
ssr?: boolean;
414
/** Sync connected chain */
415
syncConnectedChain?: boolean;
416
/** Enable multi-injected provider discovery */
417
multiInjectedProviderDiscovery?: boolean;
418
}
419
```
420
421
### Storage Management
422
423
```typescript { .api }
424
/**
425
* Storage interface for wagmi state persistence
426
*/
427
interface Storage {
428
getItem: (key: string) => string | null | Promise<string | null>;
429
setItem: (key: string, value: string) => void | Promise<void>;
430
removeItem: (key: string) => void | Promise<void>;
431
}
432
433
/**
434
* Create custom storage implementation
435
* @param parameters - Storage parameters
436
* @returns Storage implementation
437
*/
438
function createStorage(parameters: CreateStorageParameters): Storage;
439
440
interface CreateStorageParameters {
441
/** Storage key prefix */
442
key?: string;
443
/** Storage implementation */
444
storage: Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>;
445
/** Serialization functions */
446
serialize?: (value: unknown) => string;
447
deserialize?: (value: string) => unknown;
448
}
449
450
/**
451
* No-op storage (doesn't persist anything)
452
*/
453
const noopStorage: Storage;
454
455
/**
456
* Cookie-based storage for SSR
457
*/
458
const cookieStorage: Storage;
459
```
460
461
## Advanced Patterns
462
463
### Custom Hook with Error Boundary
464
465
```typescript
466
import { useAccount, BaseError } from "wagmi";
467
import { useErrorBoundary } from "react-error-boundary";
468
469
function useAccountWithErrorHandling() {
470
const { showBoundary } = useErrorBoundary();
471
472
try {
473
return useAccount();
474
} catch (error) {
475
if (error instanceof BaseError) {
476
showBoundary(error);
477
}
478
throw error;
479
}
480
}
481
```
482
483
### SSR Helper Functions
484
485
```typescript
486
import { cookieToInitialState, parseCookie } from "wagmi";
487
488
// Server-side state extraction
489
function getServerSideWagmiState(cookieHeader?: string) {
490
if (!cookieHeader) return undefined;
491
492
const cookie = parseCookie(cookieHeader, 'wagmi.store');
493
return cookieToInitialState(config, cookie);
494
}
495
496
// Next.js example
497
export async function getServerSideProps(context: GetServerSidePropsContext) {
498
return {
499
props: {
500
initialWagmiState: getServerSideWagmiState(context.req.headers.cookie),
501
},
502
};
503
}
504
```
505
506
## Common Types
507
508
```typescript { .api }
509
type Address = `0x${string}`;
510
type Hash = `0x${string}`;
511
type Hex = `0x${string}`;
512
513
interface State {
514
chainId: number;
515
connections: Map<string, Connection>;
516
current?: string;
517
status: 'connecting' | 'connected' | 'disconnected' | 'reconnecting';
518
}
519
520
interface Connection {
521
accounts: readonly Address[];
522
chainId: number;
523
connector: Connector;
524
}
525
526
interface Chain {
527
id: number;
528
name: string;
529
network: string;
530
nativeCurrency: {
531
name: string;
532
symbol: string;
533
decimals: number;
534
};
535
rpcUrls: {
536
default: { http: readonly string[] };
537
public: { http: readonly string[] };
538
};
539
blockExplorers?: {
540
default: { name: string; url: string };
541
};
542
}
543
544
interface Connector {
545
id: string;
546
name: string;
547
type: string;
548
icon?: string;
549
ready?: boolean;
550
}
551
552
interface Transport {
553
key: string;
554
name: string;
555
request: (request: { method: string; params?: any[] }) => Promise<any>;
556
type: string;
557
}
558
559
interface Account {
560
address: Address;
561
type: 'json-rpc' | 'local' | 'privateKey';
562
}
563
564
interface Permission {
565
caveats: Caveat[];
566
date: number;
567
id: string;
568
invoker: string;
569
parentCapability: string;
570
}
571
572
interface Caveat {
573
type: string;
574
value: unknown;
575
}
576
577
interface WatchAssetParams {
578
type: 'ERC20';
579
options: {
580
address: Address;
581
symbol?: string;
582
decimals?: number;
583
image?: string;
584
};
585
}
586
```