0
# Configuration & Setup
1
2
Core configuration system for initializing wagmi with chains, connectors, and transports. Essential for all wagmi applications.
3
4
## Capabilities
5
6
### Create Configuration
7
8
Creates the main wagmi configuration object that manages chains, connectors, and transports.
9
10
```typescript { .api }
11
/**
12
* Creates wagmi configuration with chains, connectors, and transports
13
* @param parameters - Configuration parameters
14
* @returns Configured wagmi instance
15
*/
16
function createConfig<
17
const chains extends readonly [Chain, ...Chain[]],
18
transports extends Record<chains[number]['id'], Transport>,
19
const connectorFns extends readonly CreateConnectorFn[]
20
>(
21
parameters: CreateConfigParameters<chains, transports, connectorFns>
22
): Config<chains, transports, connectorFns>;
23
24
interface CreateConfigParameters<chains, transports, connectorFns> {
25
/** Array of blockchain networks to support */
26
chains: chains;
27
/** Array of wallet connector functions */
28
connectors?: connectorFns;
29
/** Transport configuration for each chain */
30
transports: transports;
31
/** Storage for persisting wagmi state */
32
storage?: Storage;
33
/** Enable server-side rendering support */
34
ssr?: boolean;
35
/** Sync connected chain with connector's active chain */
36
syncConnectedChain?: boolean;
37
/** Enable multi-injected provider discovery (EIP-6963) */
38
multiInjectedProviderDiscovery?: boolean;
39
}
40
41
interface Config<chains, transports, connectorFns> {
42
chains: chains;
43
connectors: readonly Connector[];
44
transports: transports;
45
storage: Storage;
46
state: State;
47
subscribe: (listener: () => void) => () => void;
48
getClient: (parameters?: { chainId?: number }) => Client;
49
}
50
```
51
52
**Usage Example:**
53
54
```typescript
55
import { createConfig, http } from '@wagmi/core'
56
import { mainnet, sepolia, polygon } from '@wagmi/core/chains'
57
import { injected, metaMask, walletConnect } from '@wagmi/core/connectors'
58
59
const config = createConfig({
60
chains: [mainnet, sepolia, polygon],
61
connectors: [
62
injected(),
63
metaMask(),
64
walletConnect({ projectId: 'your-project-id' }),
65
],
66
transports: {
67
[mainnet.id]: http(),
68
[sepolia.id]: http('https://sepolia.infura.io/v3/your-key'),
69
[polygon.id]: http('https://polygon-rpc.com'),
70
},
71
ssr: true,
72
})
73
```
74
75
### Create Storage
76
77
Creates storage for persisting wagmi state across browser sessions.
78
79
```typescript { .api }
80
/**
81
* Creates storage for persisting wagmi state
82
* @param parameters - Storage configuration
83
* @returns Storage instance
84
*/
85
function createStorage(parameters?: CreateStorageParameters): Storage;
86
87
interface CreateStorageParameters {
88
/** Storage backend (defaults to localStorage) */
89
storage?: {
90
getItem(key: string): string | null;
91
setItem(key: string, value: string): void;
92
removeItem(key: string): void;
93
};
94
/** Storage key prefix */
95
key?: string;
96
/** Serialization functions */
97
serialize?: (value: any) => string;
98
deserialize?: (value: string) => any;
99
}
100
101
interface Storage {
102
getItem<T>(key: string, defaultValue?: T): T | null;
103
setItem<T>(key: string, value: T): void;
104
removeItem(key: string): void;
105
}
106
107
/** No-op storage implementation */
108
const noopStorage: Storage;
109
```
110
111
**Usage Example:**
112
113
```typescript
114
import { createStorage } from '@wagmi/core'
115
116
// Custom storage
117
const customStorage = createStorage({
118
storage: window.sessionStorage, // Use sessionStorage instead of localStorage
119
key: 'my-app-wagmi',
120
})
121
122
// Use in config
123
const config = createConfig({
124
// ... other config
125
storage: customStorage,
126
})
127
```
128
129
### Hydration
130
131
Hydrates wagmi config with initial state for server-side rendering support.
132
133
```typescript { .api }
134
/**
135
* Hydrates config with initial state for SSR
136
* @param config - Wagmi configuration
137
* @param initialState - Initial state to hydrate with
138
*/
139
function hydrate<config extends Config>(
140
config: config,
141
initialState: PartializedState
142
): void;
143
144
interface PartializedState {
145
chainId?: number;
146
connections?: Map<string, Connection>;
147
current?: string;
148
status?: 'connected' | 'connecting' | 'disconnected' | 'reconnecting';
149
}
150
```
151
152
**Usage Example:**
153
154
```typescript
155
import { createConfig, hydrate } from '@wagmi/core'
156
157
const config = createConfig({
158
// ... config
159
ssr: true,
160
})
161
162
// On client, hydrate with server state
163
if (typeof window !== 'undefined') {
164
hydrate(config, window.__WAGMI_STATE__)
165
}
166
```
167
168
### Connectors
169
170
Built-in wallet connectors for common connection methods.
171
172
```typescript { .api }
173
/**
174
* Injected wallet connector (MetaMask, browser wallets)
175
* @param parameters - Injected connector options
176
* @returns Connector function
177
*/
178
function injected(parameters?: InjectedParameters): CreateConnectorFn;
179
180
interface InjectedParameters {
181
/** Target specific injected wallets */
182
target?:
183
| 'metaMask'
184
| 'coinbaseWallet'
185
| 'trust'
186
| (() => { id: string; name: string; provider?: any });
187
/** Shimmed disconnect behavior */
188
shimDisconnect?: boolean;
189
}
190
191
/**
192
* Mock connector for testing
193
* @param parameters - Mock connector options
194
* @returns Connector function for testing
195
*/
196
function mock(parameters: MockParameters): CreateConnectorFn;
197
198
interface MockParameters {
199
/** Mock accounts */
200
accounts: readonly Address[];
201
/** Mock chain ID */
202
chainId?: number;
203
/** Mock features */
204
features?: {
205
connectError?: boolean;
206
reconnect?: boolean;
207
signMessageError?: boolean;
208
switchChainError?: boolean;
209
};
210
}
211
```
212
213
### Custom Connectors
214
215
Create custom wallet connectors for specialized connection methods.
216
217
```typescript { .api }
218
/**
219
* Creates a custom connector
220
* @param connectorFn - Connector implementation function
221
* @returns Custom connector function
222
*/
223
function createConnector<TProvider, TOptions = any>(
224
connectorFn: (config: CreateConnectorFn<TProvider, TOptions>) => Connector<TProvider>
225
): CreateConnectorFn<TProvider, TOptions>;
226
227
interface CreateConnectorFn<TProvider = any, TOptions = any> {
228
(options?: TOptions): (config: Config) => Connector<TProvider>;
229
}
230
231
interface Connector<TProvider = any> {
232
id: string;
233
name: string;
234
type: string;
235
icon?: string;
236
rdns?: string | readonly string[];
237
238
setup?(): Promise<void>;
239
connect(parameters?: { chainId?: number; isReconnecting?: boolean }): Promise<{
240
accounts: readonly Address[];
241
chainId: number;
242
}>;
243
disconnect(): Promise<void>;
244
getAccounts(): Promise<readonly Address[]>;
245
getChainId(): Promise<number>;
246
getProvider(): Promise<TProvider>;
247
isAuthorized(): Promise<boolean>;
248
switchChain?(parameters: { chainId: number }): Promise<Chain>;
249
250
onAccountsChanged?(accounts: string[]): void;
251
onChainChanged?(chainId: string | number): void;
252
onConnect?(connectInfo: { chainId: string | number }): void;
253
onDisconnect?(error?: { code: number; message: string }): void;
254
onMessage?(message: { type: string; data?: any }): void;
255
}
256
257
interface ConnectorEventMap {
258
change: {
259
accounts?: readonly Address[];
260
chainId?: number;
261
};
262
connect: {
263
accounts: readonly Address[];
264
chainId: number;
265
};
266
disconnect: void;
267
error: { error: Error };
268
message: { message: any };
269
}
270
```
271
272
**Usage Example:**
273
274
```typescript
275
import { createConnector } from '@wagmi/core'
276
277
// Custom WalletConnect-style connector example
278
const customWalletConnector = createConnector((config) => ({
279
id: 'custom-wallet',
280
name: 'Custom Wallet',
281
type: 'injected',
282
283
async connect() {
284
// Custom connection logic
285
const provider = await this.getProvider()
286
const accounts = await provider.request({ method: 'eth_requestAccounts' })
287
const chainId = await provider.request({ method: 'eth_chainId' })
288
289
return {
290
accounts: accounts,
291
chainId: parseInt(chainId, 16),
292
}
293
},
294
295
async getProvider() {
296
// Return custom provider
297
return window.customWallet
298
},
299
300
// ... other required methods
301
}))
302
303
const config = createConfig({
304
connectors: [customWalletConnector()],
305
// ... rest of config
306
})
307
```
308
309
### Transports
310
311
Transport layer configuration for blockchain communication.
312
313
```typescript { .api }
314
/**
315
* Fallback transport that tries multiple transports in order
316
* @param transports - Array of transports to try
317
* @param config - Fallback configuration
318
* @returns Fallback transport
319
*/
320
function fallback<TTransport extends Transport>(
321
transports: TTransport[],
322
config?: FallbackConfig
323
): FallbackTransport<TTransport>;
324
325
interface FallbackConfig {
326
/** Number of times to retry */
327
retryCount?: number;
328
/** Delay between retries in ms */
329
retryDelay?: number;
330
/** Rank transports by priority */
331
rank?: boolean;
332
}
333
334
/**
335
* Unstable connector transport (experimental)
336
* @param config - Connector transport configuration
337
* @returns Connector transport
338
*/
339
function unstable_connector(config: ConnectorTransportConfig): ConnectorTransport;
340
341
interface ConnectorTransportConfig {
342
/** Connector to use for transport */
343
connector: Connector;
344
}
345
346
// Re-exported from viem
347
function http(url?: string, config?: HttpTransportConfig): HttpTransport;
348
function webSocket(url: string, config?: WebSocketTransportConfig): WebSocketTransport;
349
function custom<TProvider>(provider: TProvider): CustomTransport;
350
```
351
352
## Utility Functions
353
354
```typescript { .api }
355
/**
356
* Cookie-based storage for SSR applications
357
*/
358
const cookieStorage: Storage;
359
360
/**
361
* Converts cookie to initial state for hydration
362
* @param cookie - Cookie string
363
* @returns Initial state
364
*/
365
function cookieToInitialState(cookie?: string): PartializedState | undefined;
366
367
/**
368
* Parses cookie string into key-value pairs
369
* @param cookie - Cookie string to parse
370
* @returns Parsed cookie object
371
*/
372
function parseCookie(cookie: string): Record<string, string>;
373
374
/**
375
* Extracts RPC URLs from transport configuration
376
* @param transports - Transport configuration
377
* @returns Map of chain IDs to RPC URLs
378
*/
379
function extractRpcUrls(transports: Record<number, Transport>): Record<number, string[]>;
380
381
/**
382
* Normalizes chain ID to number format
383
* @param chainId - Chain ID in various formats
384
* @returns Normalized chain ID as number
385
*/
386
function normalizeChainId(chainId: string | number | bigint): number;
387
```