0
# Connection Management
1
2
Wallet connection, disconnection, and network switching functionality. Handles wallet lifecycle and chain management.
3
4
## Capabilities
5
6
### Connect to Wallet
7
8
Establishes connection to a wallet connector.
9
10
```typescript { .api }
11
/**
12
* Connects to a wallet connector
13
* @param config - Wagmi configuration
14
* @param parameters - Connection parameters
15
* @returns Connection result with accounts and chain ID
16
*/
17
function connect<config extends Config, connector extends Connector | CreateConnectorFn>(
18
config: config,
19
parameters: ConnectParameters<config, connector>
20
): Promise<ConnectReturnType<config>>;
21
22
interface ConnectParameters<config extends Config, connector extends Connector | CreateConnectorFn> {
23
/** Connector to connect with */
24
connector: connector | CreateConnectorFn;
25
/** Target chain ID to connect to */
26
chainId?: config['chains'][number]['id'];
27
}
28
29
interface ConnectReturnType<config extends Config> {
30
/** Connected accounts */
31
accounts: readonly [Address, ...Address[]];
32
/** Connected chain ID */
33
chainId: config['chains'][number]['id'];
34
}
35
36
type ConnectErrorType =
37
| BaseErrorType
38
| ConnectorAlreadyConnectedErrorType
39
| ResourceUnavailableRpcErrorType
40
| UserRejectedRequestErrorType;
41
```
42
43
**Usage Example:**
44
45
```typescript
46
import { connect } from '@wagmi/core'
47
import { injected } from '@wagmi/core/connectors'
48
49
try {
50
const result = await connect(config, {
51
connector: injected(),
52
chainId: mainnet.id, // Optional: specific chain
53
})
54
55
console.log('Connected accounts:', result.accounts)
56
console.log('Connected to chain:', result.chainId)
57
} catch (error) {
58
if (error.name === 'UserRejectedRequestError') {
59
console.log('User rejected connection')
60
}
61
}
62
```
63
64
### Disconnect from Wallet
65
66
Disconnects from the current wallet connector.
67
68
```typescript { .api }
69
/**
70
* Disconnects from current connector
71
* @param config - Wagmi configuration
72
* @param parameters - Disconnect parameters (optional)
73
* @returns Disconnect confirmation
74
*/
75
function disconnect(
76
config: Config,
77
parameters?: DisconnectParameters
78
): Promise<DisconnectReturnType>;
79
80
interface DisconnectParameters {
81
/** Specific connector to disconnect (optional) */
82
connector?: Connector;
83
}
84
85
interface DisconnectReturnType {
86
/** Success confirmation */
87
success: true;
88
}
89
90
type DisconnectErrorType = BaseErrorType;
91
```
92
93
**Usage Example:**
94
95
```typescript
96
import { disconnect } from '@wagmi/core'
97
98
try {
99
await disconnect(config)
100
console.log('Disconnected successfully')
101
} catch (error) {
102
console.error('Disconnect failed:', error)
103
}
104
```
105
106
### Reconnect to Previous Wallets
107
108
Attempts to reconnect to previously connected wallets.
109
110
```typescript { .api }
111
/**
112
* Reconnects to previous connectors from storage
113
* @param config - Wagmi configuration
114
* @param parameters - Reconnect parameters (optional)
115
* @returns Reconnection results
116
*/
117
function reconnect(
118
config: Config,
119
parameters?: ReconnectParameters
120
): Promise<ReconnectReturnType>;
121
122
interface ReconnectParameters {
123
/** Specific connectors to reconnect to */
124
connectors?: Connector[];
125
}
126
127
interface ReconnectReturnType {
128
/** Reconnected accounts */
129
accounts: readonly Address[];
130
/** Reconnected chain ID */
131
chainId: number;
132
}
133
134
type ReconnectErrorType = BaseErrorType;
135
```
136
137
**Usage Example:**
138
139
```typescript
140
import { reconnect } from '@wagmi/core'
141
142
// Typically called on app initialization
143
try {
144
const result = await reconnect(config)
145
if (result.accounts.length > 0) {
146
console.log('Reconnected to:', result.accounts)
147
}
148
} catch (error) {
149
console.log('No previous connection to restore')
150
}
151
```
152
153
### Switch Blockchain Network
154
155
Switches the connected wallet to a different blockchain network.
156
157
```typescript { .api }
158
/**
159
* Switches to a different blockchain network
160
* @param config - Wagmi configuration
161
* @param parameters - Switch chain parameters
162
* @returns Switch result with new chain info
163
*/
164
function switchChain<config extends Config>(
165
config: config,
166
parameters: SwitchChainParameters<config>
167
): Promise<SwitchChainReturnType<config>>;
168
169
interface SwitchChainParameters<config extends Config> {
170
/** Target chain ID to switch to */
171
chainId: config['chains'][number]['id'];
172
/** Specific connector to switch (optional) */
173
connector?: Connector;
174
}
175
176
interface SwitchChainReturnType<config extends Config> {
177
/** New chain ID */
178
chainId: config['chains'][number]['id'];
179
}
180
181
type SwitchChainErrorType =
182
| BaseErrorType
183
| SwitchChainNotSupportedErrorType
184
| UserRejectedRequestErrorType;
185
186
/** @deprecated Use switchChain instead */
187
const switchNetwork = switchChain;
188
```
189
190
**Usage Example:**
191
192
```typescript
193
import { switchChain } from '@wagmi/core'
194
import { polygon } from '@wagmi/core/chains'
195
196
try {
197
const result = await switchChain(config, {
198
chainId: polygon.id,
199
})
200
console.log('Switched to chain:', result.chainId)
201
} catch (error) {
202
if (error.name === 'SwitchChainNotSupportedError') {
203
console.log('Wallet does not support chain switching')
204
} else if (error.name === 'UserRejectedRequestError') {
205
console.log('User rejected chain switch')
206
}
207
}
208
```
209
210
### Switch Account
211
212
Switches to a different account within the connected wallet.
213
214
```typescript { .api }
215
/**
216
* Switches to a different account
217
* @param config - Wagmi configuration
218
* @param parameters - Switch account parameters
219
* @returns Switch result with new account info
220
*/
221
function switchAccount<config extends Config>(
222
config: config,
223
parameters: SwitchAccountParameters<config>
224
): Promise<SwitchAccountReturnType<config>>;
225
226
interface SwitchAccountParameters<config extends Config> {
227
/** Target account address */
228
account: Address;
229
/** Specific connector to switch account for (optional) */
230
connector?: Connector;
231
}
232
233
interface SwitchAccountReturnType<config extends Config> {
234
/** New active account */
235
account: Address;
236
/** Chain ID */
237
chainId: config['chains'][number]['id'];
238
}
239
240
type SwitchAccountErrorType =
241
| BaseErrorType
242
| ConnectorAccountNotFoundErrorType
243
| ConnectorNotConnectedErrorType;
244
```
245
246
**Usage Example:**
247
248
```typescript
249
import { switchAccount, getConnections } from '@wagmi/core'
250
251
// Get available accounts
252
const connections = getConnections(config)
253
const availableAccounts = connections[0]?.accounts || []
254
255
if (availableAccounts.length > 1) {
256
try {
257
const result = await switchAccount(config, {
258
account: availableAccounts[1], // Switch to second account
259
})
260
console.log('Switched to account:', result.account)
261
} catch (error) {
262
console.error('Account switch failed:', error)
263
}
264
}
265
```
266
267
## Connection State Management
268
269
### Watch Connection Changes
270
271
Monitor connection state changes in real-time.
272
273
```typescript { .api }
274
/**
275
* Watches for connection changes
276
* @param config - Wagmi configuration
277
* @param parameters - Watch parameters
278
* @returns Unsubscribe function
279
*/
280
function watchConnections<config extends Config>(
281
config: config,
282
parameters: WatchConnectionsParameters<config>
283
): WatchConnectionsReturnType;
284
285
interface WatchConnectionsParameters<config extends Config> {
286
/** Callback when connections change */
287
onChange(connections: GetConnectionsReturnType<config>): void;
288
}
289
290
type WatchConnectionsReturnType = () => void; // Unsubscribe function
291
292
/**
293
* Watches for connector changes
294
* @param config - Wagmi configuration
295
* @param parameters - Watch parameters
296
* @returns Unsubscribe function
297
*/
298
function watchConnectors<config extends Config>(
299
config: config,
300
parameters: WatchConnectorsParameters<config>
301
): WatchConnectorsReturnType;
302
303
interface WatchConnectorsParameters<config extends Config> {
304
/** Callback when connectors change */
305
onChange(connectors: GetConnectorsReturnType<config>): void;
306
}
307
308
type WatchConnectorsReturnType = () => void;
309
```
310
311
**Usage Example:**
312
313
```typescript
314
import { watchConnections, watchConnectors } from '@wagmi/core'
315
316
// Watch connection changes
317
const unsubscribeConnections = watchConnections(config, {
318
onChange(connections) {
319
console.log('Connection changed:', connections)
320
},
321
})
322
323
// Watch connector changes (useful for detecting new injected wallets)
324
const unsubscribeConnectors = watchConnectors(config, {
325
onChange(connectors) {
326
console.log('Available connectors:', connectors.map(c => c.name))
327
},
328
})
329
330
// Cleanup when component unmounts
331
// unsubscribeConnections()
332
// unsubscribeConnectors()
333
```
334
335
## Error Handling
336
337
Connection management functions can throw specific errors:
338
339
```typescript { .api }
340
class ConnectorAlreadyConnectedError extends BaseError {
341
name: 'ConnectorAlreadyConnectedError';
342
}
343
344
class ConnectorNotConnectedError extends BaseError {
345
name: 'ConnectorNotConnectedError';
346
}
347
348
class ConnectorNotFoundError extends BaseError {
349
name: 'ConnectorNotFoundError';
350
}
351
352
class ConnectorAccountNotFoundError extends BaseError {
353
name: 'ConnectorAccountNotFoundError';
354
}
355
356
class SwitchChainNotSupportedError extends BaseError {
357
name: 'SwitchChainNotSupportedError';
358
}
359
360
class UserRejectedRequestError extends BaseError {
361
name: 'UserRejectedRequestError';
362
}
363
```
364
365
Handle these errors appropriately to provide good user experience:
366
367
```typescript
368
try {
369
await connect(config, { connector: injected() })
370
} catch (error) {
371
switch (error.name) {
372
case 'ConnectorAlreadyConnectedError':
373
console.log('Already connected to this wallet')
374
break
375
case 'UserRejectedRequestError':
376
console.log('User cancelled connection')
377
break
378
case 'ResourceUnavailableRpcError':
379
console.log('RPC connection failed')
380
break
381
default:
382
console.error('Connection failed:', error)
383
}
384
}
385
```