0
# Event Watching & Subscriptions
1
2
Real-time event watching for accounts, chains, blocks, and contract events. Reactive programming support.
3
4
## Capabilities
5
6
### Watch Account Changes
7
8
Monitor account state changes in real-time.
9
10
```typescript { .api }
11
/**
12
* Watches for account changes
13
* @param config - Wagmi configuration
14
* @param parameters - Watch parameters
15
* @returns Unsubscribe function
16
*/
17
function watchAccount<config extends Config>(
18
config: config,
19
parameters: WatchAccountParameters<config>
20
): WatchAccountReturnType;
21
22
interface WatchAccountParameters<config extends Config> {
23
/** Callback when account changes */
24
onChange(account: GetAccountReturnType<config>): void;
25
}
26
27
type WatchAccountReturnType = () => void; // Unsubscribe function
28
```
29
30
**Usage Example:**
31
32
```typescript
33
import { watchAccount } from '@wagmi/core'
34
35
const unsubscribe = watchAccount(config, {
36
onChange(account) {
37
console.log('Account changed:', {
38
address: account.address,
39
isConnected: account.isConnected,
40
status: account.status,
41
})
42
43
if (account.isConnected) {
44
// User connected - update UI
45
updateWalletUI(account.address)
46
} else {
47
// User disconnected - clear UI
48
clearWalletUI()
49
}
50
},
51
})
52
53
// Cleanup when component unmounts
54
// unsubscribe()
55
```
56
57
### Watch Chain Changes
58
59
Monitor chain ID changes in real-time.
60
61
```typescript { .api }
62
/**
63
* Watches for chain ID changes
64
* @param config - Wagmi configuration
65
* @param parameters - Watch parameters
66
* @returns Unsubscribe function
67
*/
68
function watchChainId<config extends Config>(
69
config: config,
70
parameters: WatchChainIdParameters<config>
71
): WatchChainIdReturnType;
72
73
interface WatchChainIdParameters<config extends Config> {
74
/** Callback when chain ID changes */
75
onChange(chainId: GetChainIdReturnType<config>): void;
76
}
77
78
type WatchChainIdReturnType = () => void;
79
```
80
81
**Usage Example:**
82
83
```typescript
84
import { watchChainId } from '@wagmi/core'
85
86
const unsubscribe = watchChainId(config, {
87
onChange(chainId) {
88
const chain = config.chains.find(c => c.id === chainId)
89
console.log('Switched to chain:', {
90
id: chainId,
91
name: chain?.name,
92
})
93
94
// Update app state for new chain
95
handleChainChange(chainId)
96
},
97
})
98
```
99
100
### Watch Block Number
101
102
Monitor new blocks in real-time.
103
104
```typescript { .api }
105
/**
106
* Watches for new block numbers
107
* @param config - Wagmi configuration
108
* @param parameters - Watch parameters
109
* @returns Unsubscribe function
110
*/
111
function watchBlockNumber<config extends Config>(
112
config: config,
113
parameters: WatchBlockNumberParameters<config>
114
): WatchBlockNumberReturnType;
115
116
interface WatchBlockNumberParameters<config extends Config> {
117
/** Callback when new block */
118
onBlockNumber(blockNumber: bigint): void;
119
/** Callback for errors */
120
onError?(error: Error): void;
121
/** Chain ID to watch */
122
chainId?: config['chains'][number]['id'];
123
/** Enable polling mode */
124
poll?: boolean;
125
/** Polling interval in ms */
126
pollingInterval?: number;
127
}
128
129
type WatchBlockNumberReturnType = () => void;
130
```
131
132
**Usage Example:**
133
134
```typescript
135
import { watchBlockNumber } from '@wagmi/core'
136
137
const unsubscribe = watchBlockNumber(config, {
138
onBlockNumber(blockNumber) {
139
console.log('New block:', blockNumber.toString())
140
// Update block-dependent data
141
refreshBlockData(blockNumber)
142
},
143
onError(error) {
144
console.error('Block watching error:', error)
145
},
146
pollingInterval: 12000, // 12 seconds
147
})
148
```
149
150
### Watch Blocks
151
152
Monitor complete block data.
153
154
```typescript { .api }
155
/**
156
* Watches for new blocks
157
* @param config - Wagmi configuration
158
* @param parameters - Watch parameters
159
* @returns Unsubscribe function
160
*/
161
function watchBlocks<config extends Config>(
162
config: config,
163
parameters: WatchBlocksParameters<config>
164
): WatchBlocksReturnType;
165
166
interface WatchBlocksParameters<config extends Config> {
167
/** Callback when new block */
168
onBlock(block: Block): void;
169
/** Callback for errors */
170
onError?(error: Error): void;
171
/** Chain ID to watch */
172
chainId?: config['chains'][number]['id'];
173
/** Include transactions */
174
includeTransactions?: boolean;
175
/** Block tag to watch */
176
blockTag?: 'latest' | 'pending' | 'safe' | 'finalized';
177
/** Enable polling mode */
178
poll?: boolean;
179
/** Polling interval */
180
pollingInterval?: number;
181
}
182
183
type WatchBlocksReturnType = () => void;
184
185
interface Block {
186
hash: Hash;
187
number: bigint;
188
timestamp: bigint;
189
parentHash: Hash;
190
gasLimit: bigint;
191
gasUsed: bigint;
192
miner: Address;
193
transactions: Hash[] | Transaction[];
194
baseFeePerGas?: bigint;
195
}
196
```
197
198
### Watch Contract Events
199
200
Monitor smart contract events in real-time.
201
202
```typescript { .api }
203
/**
204
* Watches for contract events
205
* @param config - Wagmi configuration
206
* @param parameters - Watch parameters
207
* @returns Unsubscribe function
208
*/
209
function watchContractEvent<config extends Config>(
210
config: config,
211
parameters: WatchContractEventParameters<config>
212
): WatchContractEventReturnType;
213
214
interface WatchContractEventParameters<config extends Config> {
215
/** Contract address */
216
address: Address;
217
/** Contract ABI */
218
abi: Abi;
219
/** Event name to watch */
220
eventName?: string;
221
/** Event filter arguments */
222
args?: Record<string, any>;
223
/** Callback when event occurs */
224
onLogs(logs: Log[]): void;
225
/** Callback for errors */
226
onError?(error: Error): void;
227
/** Chain ID */
228
chainId?: config['chains'][number]['id'];
229
/** Start from block */
230
fromBlock?: bigint;
231
/** Enable polling */
232
poll?: boolean;
233
/** Polling interval */
234
pollingInterval?: number;
235
}
236
237
type WatchContractEventReturnType = () => void;
238
239
interface Log {
240
address: Address;
241
topics: readonly Hex[];
242
data: Hex;
243
blockNumber: bigint;
244
transactionHash: Hash;
245
transactionIndex: number;
246
blockHash: Hash;
247
logIndex: number;
248
removed: boolean;
249
}
250
```
251
252
**Usage Example:**
253
254
```typescript
255
import { watchContractEvent, decodeEventLog } from '@wagmi/core'
256
257
// Watch ERC-20 Transfer events
258
const unsubscribe = watchContractEvent(config, {
259
address: '0xA0b86a33E6411c0B7f8C4b5d3e1B9d3e8b4a4e6f',
260
abi: erc20Abi,
261
eventName: 'Transfer',
262
args: {
263
from: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e', // Filter by sender
264
},
265
onLogs(logs) {
266
logs.forEach(log => {
267
try {
268
const decoded = decodeEventLog({
269
abi: erc20Abi,
270
data: log.data,
271
topics: log.topics,
272
})
273
274
console.log('Transfer event:', {
275
from: decoded.args.from,
276
to: decoded.args.to,
277
value: decoded.args.value.toString(),
278
blockNumber: log.blockNumber.toString(),
279
transactionHash: log.transactionHash,
280
})
281
} catch (error) {
282
console.error('Failed to decode log:', error)
283
}
284
})
285
},
286
onError(error) {
287
console.error('Event watching error:', error)
288
},
289
})
290
291
// Watch all events from a contract
292
const unsubscribeAll = watchContractEvent(config, {
293
address: '0xContractAddress',
294
abi: contractAbi,
295
// No eventName = watch all events
296
onLogs(logs) {
297
console.log('Contract events:', logs.length)
298
},
299
})
300
```
301
302
### Watch Pending Transactions
303
304
Monitor pending transactions in the mempool.
305
306
```typescript { .api }
307
/**
308
* Watches for pending transactions
309
* @param config - Wagmi configuration
310
* @param parameters - Watch parameters
311
* @returns Unsubscribe function
312
*/
313
function watchPendingTransactions<config extends Config>(
314
config: config,
315
parameters: WatchPendingTransactionsParameters<config>
316
): WatchPendingTransactionsReturnType;
317
318
interface WatchPendingTransactionsParameters<config extends Config> {
319
/** Callback when new pending transactions */
320
onTransactions(hashes: Hash[]): void;
321
/** Callback for errors */
322
onError?(error: Error): void;
323
/** Chain ID to watch */
324
chainId?: config['chains'][number]['id'];
325
/** Enable polling */
326
poll?: boolean;
327
/** Polling interval */
328
pollingInterval?: number;
329
}
330
331
type WatchPendingTransactionsReturnType = () => void;
332
```
333
334
### Watch Connections
335
336
Monitor changes to wallet connections.
337
338
```typescript { .api }
339
/**
340
* Watches for changes to wallet connections
341
* @param config - Wagmi configuration
342
* @param parameters - Watch parameters
343
* @returns Unsubscribe function
344
*/
345
function watchConnections<config extends Config>(
346
config: config,
347
parameters: WatchConnectionsParameters
348
): WatchConnectionsReturnType;
349
350
interface WatchConnectionsParameters {
351
/** Callback when connections change */
352
onChange(
353
connections: GetConnectionsReturnType,
354
prevConnections: GetConnectionsReturnType
355
): void;
356
}
357
358
type WatchConnectionsReturnType = () => void;
359
```
360
361
### Watch Connectors
362
363
Monitor changes to available wallet connectors.
364
365
```typescript { .api }
366
/**
367
* Watches for changes to available connectors
368
* @param config - Wagmi configuration
369
* @param parameters - Watch parameters
370
* @returns Unsubscribe function
371
*/
372
function watchConnectors<config extends Config>(
373
config: config,
374
parameters: WatchConnectorsParameters<config>
375
): WatchConnectorsReturnType;
376
377
interface WatchConnectorsParameters<config extends Config> {
378
/** Callback when connectors change */
379
onChange(
380
connectors: GetConnectorsReturnType<config>,
381
prevConnectors: GetConnectorsReturnType<config>
382
): void;
383
}
384
385
type WatchConnectorsReturnType = () => void;
386
```
387
388
## Advanced Watching Patterns
389
390
### Combined Watchers
391
392
Example of using multiple watchers together:
393
394
```typescript
395
import {
396
watchAccount,
397
watchChainId,
398
watchBlockNumber,
399
watchContractEvent
400
} from '@wagmi/core'
401
402
class WalletManager {
403
private unsubscribers: (() => void)[] = []
404
405
start() {
406
// Watch account changes
407
this.unsubscribers.push(
408
watchAccount(config, {
409
onChange: (account) => {
410
this.handleAccountChange(account)
411
},
412
})
413
)
414
415
// Watch chain changes
416
this.unsubscribers.push(
417
watchChainId(config, {
418
onChange: (chainId) => {
419
this.handleChainChange(chainId)
420
},
421
})
422
)
423
424
// Watch new blocks
425
this.unsubscribers.push(
426
watchBlockNumber(config, {
427
onBlockNumber: (blockNumber) => {
428
this.handleNewBlock(blockNumber)
429
},
430
pollingInterval: 12000,
431
})
432
)
433
}
434
435
stop() {
436
// Cleanup all watchers
437
this.unsubscribers.forEach(unsubscribe => unsubscribe())
438
this.unsubscribers = []
439
}
440
441
private handleAccountChange(account: any) {
442
if (account.isConnected) {
443
console.log('User connected:', account.address)
444
this.startUserSpecificWatchers(account.address)
445
} else {
446
console.log('User disconnected')
447
this.stopUserSpecificWatchers()
448
}
449
}
450
451
private handleChainChange(chainId: number) {
452
console.log('Chain changed:', chainId)
453
// Restart chain-specific watchers
454
this.restartChainWatchers(chainId)
455
}
456
457
private handleNewBlock(blockNumber: bigint) {
458
console.log('New block:', blockNumber.toString())
459
// Update any block-dependent UI
460
}
461
462
private startUserSpecificWatchers(userAddress: Address) {
463
// Watch user's token transfers
464
this.unsubscribers.push(
465
watchContractEvent(config, {
466
address: '0xTokenAddress',
467
abi: erc20Abi,
468
eventName: 'Transfer',
469
args: {
470
to: userAddress, // Incoming transfers
471
},
472
onLogs: (logs) => {
473
console.log('Incoming token transfers:', logs.length)
474
},
475
})
476
)
477
}
478
479
private stopUserSpecificWatchers() {
480
// Implementation to stop user-specific watchers
481
}
482
483
private restartChainWatchers(chainId: number) {
484
// Implementation to restart chain-specific watchers
485
}
486
}
487
488
// Usage
489
const walletManager = new WalletManager()
490
walletManager.start()
491
492
// Later, cleanup
493
// walletManager.stop()
494
```
495
496
### React Hook Pattern
497
498
If using with React, here's a common pattern:
499
500
```typescript
501
import { useEffect, useState } from 'react'
502
import { watchAccount, watchChainId } from '@wagmi/core'
503
504
function useWagmiState() {
505
const [account, setAccount] = useState(null)
506
const [chainId, setChainId] = useState(null)
507
508
useEffect(() => {
509
const unsubscribeAccount = watchAccount(config, {
510
onChange: setAccount,
511
})
512
513
const unsubscribeChain = watchChainId(config, {
514
onChange: setChainId,
515
})
516
517
return () => {
518
unsubscribeAccount()
519
unsubscribeChain()
520
}
521
}, [])
522
523
return { account, chainId }
524
}
525
526
// Usage in component
527
function MyComponent() {
528
const { account, chainId } = useWagmiState()
529
530
return (
531
<div>
532
<div>Account: {account?.address}</div>
533
<div>Chain: {chainId}</div>
534
</div>
535
)
536
}
537
```
538
539
All watch functions return unsubscribe functions that should be called to clean up listeners and prevent memory leaks.