0
# Smart Contracts
1
2
Contract interaction hooks for reading from and writing to smart contracts with full type safety. This module provides comprehensive functionality for all contract operations including reads, writes, simulation, deployment, and event watching.
3
4
## Capabilities
5
6
### useReadContract
7
8
Hook to read data from a smart contract function with automatic caching and revalidation.
9
10
```typescript { .api }
11
/**
12
* Hook to read from a contract
13
* @param parameters - Contract read parameters with ABI and function details
14
* @returns Contract read result with query state
15
*/
16
function useReadContract<config = Config, selectData = UseReadContractReturnType>(
17
parameters: UseReadContractParameters<config, selectData>
18
): UseReadContractReturnType<selectData>;
19
20
interface UseReadContractParameters<config = Config, selectData = UseReadContractReturnType> {
21
/** Contract ABI */
22
abi: Abi;
23
/** Contract address */
24
address: Address;
25
/** Function name to call */
26
functionName: string;
27
/** Function arguments */
28
args?: readonly unknown[];
29
/** Account to call from */
30
account?: Address;
31
/** Block number to read at */
32
blockNumber?: bigint;
33
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
34
/** Chain to use */
35
chainId?: config['chains'][number]['id'];
36
config?: Config | config;
37
query?: {
38
enabled?: boolean;
39
staleTime?: number;
40
gcTime?: number;
41
refetchInterval?: number;
42
select?: (data: UseReadContractReturnType) => selectData;
43
};
44
}
45
46
type UseReadContractReturnType = unknown;
47
```
48
49
**Usage Example:**
50
51
```typescript
52
import { useReadContract } from "wagmi";
53
import { erc20Abi } from "viem";
54
55
function TokenInfo() {
56
const { data: name } = useReadContract({
57
abi: erc20Abi,
58
address: '0x6B175474E89094C44Da98b954EedeAC495271d0F', // DAI
59
functionName: 'name',
60
});
61
62
const { data: balance } = useReadContract({
63
abi: erc20Abi,
64
address: '0x6B175474E89094C44Da98b954EedeAC495271d0F',
65
functionName: 'balanceOf',
66
args: ['0x742d35Cc6634C0532925a3b8D'],
67
});
68
69
return (
70
<div>
71
<p>Token: {name}</p>
72
<p>Balance: {balance?.toString()}</p>
73
</div>
74
);
75
}
76
```
77
78
### useWriteContract
79
80
Hook to write to a smart contract function with transaction lifecycle management.
81
82
```typescript { .api }
83
/**
84
* Hook to write to a contract
85
* @param parameters - Contract write configuration with mutation callbacks
86
* @returns Contract write mutation with transaction state
87
*/
88
function useWriteContract<config = Config, context = unknown>(
89
parameters?: UseWriteContractParameters<config, context>
90
): UseWriteContractReturnType<config, context>;
91
92
interface UseWriteContractParameters<config = Config, context = unknown> {
93
config?: Config | config;
94
mutation?: {
95
onMutate?: (variables: WriteContractVariables) => Promise<context> | context;
96
onError?: (error: WriteContractErrorType, variables: WriteContractVariables, context?: context) => Promise<void> | void;
97
onSuccess?: (data: WriteContractData, variables: WriteContractVariables, context?: context) => Promise<void> | void;
98
onSettled?: (data?: WriteContractData, error?: WriteContractErrorType, variables?: WriteContractVariables, context?: context) => Promise<void> | void;
99
};
100
}
101
102
interface UseWriteContractReturnType<config = Config, context = unknown> {
103
/** Write to contract */
104
writeContract: (variables: WriteContractVariables, options?: WriteContractMutateOptions) => void;
105
/** Async version of writeContract */
106
writeContractAsync: (variables: WriteContractVariables, options?: WriteContractMutateAsyncOptions) => Promise<WriteContractData>;
107
/** Transaction data */
108
data?: WriteContractData;
109
/** Write error */
110
error: WriteContractErrorType | null;
111
/** Write status flags */
112
isError: boolean;
113
isIdle: boolean;
114
isPending: boolean;
115
isSuccess: boolean;
116
/** Reset write state */
117
reset: () => void;
118
/** Current status */
119
status: 'error' | 'idle' | 'pending' | 'success';
120
/** Additional variables */
121
variables?: WriteContractVariables;
122
}
123
124
interface WriteContractVariables {
125
/** Contract ABI */
126
abi: Abi;
127
/** Contract address */
128
address: Address;
129
/** Function name to call */
130
functionName: string;
131
/** Function arguments */
132
args?: readonly unknown[];
133
/** Account to write from */
134
account?: Address;
135
/** Chain to use */
136
chainId?: number;
137
/** Gas limit */
138
gas?: bigint;
139
/** Gas price */
140
gasPrice?: bigint;
141
/** Max fee per gas (EIP-1559) */
142
maxFeePerGas?: bigint;
143
/** Max priority fee per gas (EIP-1559) */
144
maxPriorityFeePerGas?: bigint;
145
/** Nonce */
146
nonce?: number;
147
/** Value to send with transaction */
148
value?: bigint;
149
}
150
151
type WriteContractData = Hash;
152
```
153
154
**Usage Example:**
155
156
```typescript
157
import { useWriteContract, useWaitForTransactionReceipt } from "wagmi";
158
import { erc20Abi } from "viem";
159
160
function TransferTokens() {
161
const { writeContract, data: hash, isPending } = useWriteContract();
162
163
const { isLoading: isConfirming, isSuccess: isConfirmed } =
164
useWaitForTransactionReceipt({
165
hash,
166
});
167
168
const handleTransfer = () => {
169
writeContract({
170
abi: erc20Abi,
171
address: '0x6B175474E89094C44Da98b954EedeAC495271d0F',
172
functionName: 'transfer',
173
args: ['0x742d35Cc6634C0532925a3b8D', 1000000000000000000n], // 1 token
174
});
175
};
176
177
return (
178
<div>
179
<button onClick={handleTransfer} disabled={isPending || isConfirming}>
180
{isPending ? 'Preparing...' : isConfirming ? 'Confirming...' : 'Transfer'}
181
</button>
182
{isConfirmed && <div>Transfer successful!</div>}
183
</div>
184
);
185
}
186
```
187
188
### useSimulateContract
189
190
Hook to simulate a contract call before executing it to prevent failed transactions.
191
192
```typescript { .api }
193
/**
194
* Hook to simulate contract call
195
* @param parameters - Contract simulation parameters
196
* @returns Simulation result with gas estimates and return data
197
*/
198
function useSimulateContract<config = Config, selectData = UseSimulateContractReturnType>(
199
parameters: UseSimulateContractParameters<config, selectData>
200
): UseSimulateContractReturnType<selectData>;
201
202
interface UseSimulateContractParameters<config = Config, selectData = UseSimulateContractReturnType> {
203
/** Contract ABI */
204
abi: Abi;
205
/** Contract address */
206
address: Address;
207
/** Function name to call */
208
functionName: string;
209
/** Function arguments */
210
args?: readonly unknown[];
211
/** Account to simulate from */
212
account?: Address;
213
/** Block number to simulate at */
214
blockNumber?: bigint;
215
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
216
/** Chain to use */
217
chainId?: config['chains'][number]['id'];
218
/** Gas limit for simulation */
219
gas?: bigint;
220
/** Gas price */
221
gasPrice?: bigint;
222
/** Max fee per gas */
223
maxFeePerGas?: bigint;
224
/** Max priority fee per gas */
225
maxPriorityFeePerGas?: bigint;
226
/** Nonce */
227
nonce?: number;
228
/** Value to send */
229
value?: bigint;
230
config?: Config | config;
231
query?: {
232
enabled?: boolean;
233
staleTime?: number;
234
select?: (data: UseSimulateContractReturnType) => selectData;
235
};
236
}
237
238
interface UseSimulateContractReturnType {
239
/** Simulation result */
240
result: unknown;
241
/** Request data that can be used with useWriteContract */
242
request: {
243
abi: Abi;
244
address: Address;
245
functionName: string;
246
args?: readonly unknown[];
247
account?: Address;
248
chainId?: number;
249
gas?: bigint;
250
gasPrice?: bigint;
251
maxFeePerGas?: bigint;
252
maxPriorityFeePerGas?: bigint;
253
nonce?: number;
254
value?: bigint;
255
};
256
}
257
```
258
259
### useReadContracts
260
261
Hook to read from multiple contracts in a single request for optimal performance.
262
263
```typescript { .api }
264
/**
265
* Hook to read from multiple contracts
266
* @param parameters - Multiple contract read parameters
267
* @returns Array of contract read results
268
*/
269
function useReadContracts<config = Config, selectData = UseReadContractsReturnType>(
270
parameters: UseReadContractsParameters<config, selectData>
271
): UseReadContractsReturnType<selectData>;
272
273
interface UseReadContractsParameters<config = Config, selectData = UseReadContractsReturnType> {
274
/** Array of contract calls */
275
contracts: readonly ContractCall[];
276
/** Block number to read at */
277
blockNumber?: bigint;
278
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
279
/** Chain to use */
280
chainId?: config['chains'][number]['id'];
281
config?: Config | config;
282
query?: {
283
enabled?: boolean;
284
staleTime?: number;
285
select?: (data: UseReadContractsReturnType) => selectData;
286
};
287
}
288
289
interface ContractCall {
290
abi: Abi;
291
address: Address;
292
functionName: string;
293
args?: readonly unknown[];
294
}
295
296
type UseReadContractsReturnType = {
297
error?: Error;
298
result?: unknown;
299
status: 'failure' | 'success';
300
}[];
301
```
302
303
### useInfiniteReadContracts
304
305
Hook for paginated contract reads with infinite scroll support.
306
307
```typescript { .api }
308
/**
309
* Hook to read contracts with pagination
310
* @param parameters - Infinite contract read parameters
311
* @returns Paginated contract read results with fetch functions
312
*/
313
function useInfiniteReadContracts<config = Config, selectData = UseInfiniteContractReadsReturnType>(
314
parameters: UseInfiniteContractReadsParameters<config, selectData>
315
): UseInfiniteContractReadsReturnType<selectData>;
316
317
interface UseInfiniteContractReadsParameters<config = Config, selectData = UseInfiniteContractReadsReturnType> {
318
/** Function to generate contract calls for each page */
319
contracts: (pageParam: unknown) => readonly ContractCall[];
320
/** Block number to read at */
321
blockNumber?: bigint;
322
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
323
/** Chain to use */
324
chainId?: config['chains'][number]['id'];
325
config?: Config | config;
326
query?: {
327
enabled?: boolean;
328
staleTime?: number;
329
getNextPageParam?: (lastPage: unknown[], allPages: unknown[][]) => unknown;
330
select?: (data: UseInfiniteContractReadsReturnType) => selectData;
331
};
332
}
333
334
interface UseInfiniteContractReadsReturnType<selectData = unknown> {
335
data?: {
336
pages: unknown[][];
337
pageParams: unknown[];
338
};
339
error: Error | null;
340
fetchNextPage: () => void;
341
hasNextPage?: boolean;
342
isFetching: boolean;
343
isFetchingNextPage: boolean;
344
isLoading: boolean;
345
isError: boolean;
346
}
347
```
348
349
### useDeployContract
350
351
Hook to deploy a new smart contract with transaction tracking.
352
353
```typescript { .api }
354
/**
355
* Hook to deploy a contract
356
* @param parameters - Contract deployment configuration
357
* @returns Deploy contract mutation with transaction state
358
*/
359
function useDeployContract<config = Config, context = unknown>(
360
parameters?: UseDeployContractParameters<config, context>
361
): UseDeployContractReturnType<config, context>;
362
363
interface UseDeployContractParameters<config = Config, context = unknown> {
364
config?: Config | config;
365
mutation?: {
366
onMutate?: (variables: DeployContractVariables) => Promise<context> | context;
367
onError?: (error: DeployContractErrorType, variables: DeployContractVariables, context?: context) => Promise<void> | void;
368
onSuccess?: (data: DeployContractData, variables: DeployContractVariables, context?: context) => Promise<void> | void;
369
onSettled?: (data?: DeployContractData, error?: DeployContractErrorType, variables?: DeployContractVariables, context?: context) => Promise<void> | void;
370
};
371
}
372
373
interface UseDeployContractReturnType<config = Config, context = unknown> {
374
/** Deploy contract */
375
deployContract: (variables: DeployContractVariables, options?: DeployContractMutateOptions) => void;
376
/** Async version of deployContract */
377
deployContractAsync: (variables: DeployContractVariables, options?: DeployContractMutateAsyncOptions) => Promise<DeployContractData>;
378
/** Deploy transaction data */
379
data?: DeployContractData;
380
/** Deploy error */
381
error: DeployContractErrorType | null;
382
/** Deploy status flags */
383
isError: boolean;
384
isIdle: boolean;
385
isPending: boolean;
386
isSuccess: boolean;
387
/** Reset deploy state */
388
reset: () => void;
389
/** Current status */
390
status: 'error' | 'idle' | 'pending' | 'success';
391
/** Additional variables */
392
variables?: DeployContractVariables;
393
}
394
395
interface DeployContractVariables {
396
/** Contract ABI */
397
abi: Abi;
398
/** Contract bytecode */
399
bytecode: Hex;
400
/** Constructor arguments */
401
args?: readonly unknown[];
402
/** Account to deploy from */
403
account?: Address;
404
/** Chain to deploy to */
405
chainId?: number;
406
/** Gas limit */
407
gas?: bigint;
408
/** Gas price */
409
gasPrice?: bigint;
410
/** Max fee per gas */
411
maxFeePerGas?: bigint;
412
/** Max priority fee per gas */
413
maxPriorityFeePerGas?: bigint;
414
/** Nonce */
415
nonce?: number;
416
/** Value to send with deployment */
417
value?: bigint;
418
}
419
420
type DeployContractData = Hash;
421
```
422
423
### useWatchContractEvent
424
425
Hook to watch for specific contract events in real-time.
426
427
```typescript { .api }
428
/**
429
* Hook to watch contract events
430
* @param parameters - Event watching parameters
431
* @returns Event watcher that triggers on new events
432
*/
433
function useWatchContractEvent<config = Config>(
434
parameters: UseWatchContractEventParameters<config>
435
): UseWatchContractEventReturnType;
436
437
interface UseWatchContractEventParameters<config = Config> {
438
/** Contract ABI */
439
abi: Abi;
440
/** Contract address */
441
address: Address;
442
/** Event name to watch */
443
eventName: string;
444
/** Event parameter filters */
445
args?: Record<string, unknown>;
446
/** Batch event handling */
447
batch?: boolean;
448
/** Chain to watch */
449
chainId?: config['chains'][number]['id'];
450
config?: Config | config;
451
/** Event handler callback */
452
onLogs: (logs: Log[]) => void;
453
/** Polling interval in milliseconds */
454
pollingInterval?: number;
455
/** Whether to fetch past events */
456
strict?: boolean;
457
}
458
459
type UseWatchContractEventReturnType = void;
460
461
interface Log {
462
/** Event address */
463
address: Address;
464
/** Topics (indexed parameters) */
465
topics: Hash[];
466
/** Event data */
467
data: Hex;
468
/** Block hash */
469
blockHash: Hash;
470
/** Block number */
471
blockNumber: bigint;
472
/** Transaction hash */
473
transactionHash: Hash;
474
/** Transaction index */
475
transactionIndex: number;
476
/** Log index */
477
logIndex: number;
478
/** Whether log was removed */
479
removed: boolean;
480
}
481
```
482
483
**Usage Example:**
484
485
```typescript
486
import { useWatchContractEvent } from "wagmi";
487
import { erc20Abi } from "viem";
488
489
function TransferWatcher() {
490
useWatchContractEvent({
491
abi: erc20Abi,
492
address: '0x6B175474E89094C44Da98b954EedeAC495271d0F',
493
eventName: 'Transfer',
494
args: {
495
from: '0x742d35Cc6634C0532925a3b8D', // Watch transfers from specific address
496
},
497
onLogs(logs) {
498
console.log('New transfers!', logs);
499
},
500
});
501
502
return <div>Watching for transfers...</div>;
503
}
504
```
505
506
## Common Types
507
508
```typescript { .api }
509
type Abi = readonly AbiItem[];
510
511
interface AbiItem {
512
type: 'function' | 'event' | 'error' | 'constructor' | 'fallback' | 'receive';
513
name?: string;
514
inputs?: AbiParameter[];
515
outputs?: AbiParameter[];
516
stateMutability?: 'pure' | 'view' | 'nonpayable' | 'payable';
517
anonymous?: boolean;
518
}
519
520
interface AbiParameter {
521
name: string;
522
type: string;
523
components?: AbiParameter[];
524
indexed?: boolean;
525
}
526
527
type Address = `0x${string}`;
528
type Hash = `0x${string}`;
529
type Hex = `0x${string}`;
530
531
interface ContractCall {
532
abi: Abi;
533
address: Address;
534
functionName: string;
535
args?: readonly unknown[];
536
}
537
538
interface WriteContractMutateOptions {
539
onError?: (error: Error, variables: WriteContractVariables, context?: unknown) => void;
540
onSuccess?: (data: Hash, variables: WriteContractVariables, context?: unknown) => void;
541
onSettled?: (data?: Hash, error?: Error, variables?: WriteContractVariables, context?: unknown) => void;
542
}
543
544
interface WriteContractMutateAsyncOptions {
545
onError?: (error: Error, variables: WriteContractVariables, context?: unknown) => void;
546
onSuccess?: (data: Hash, variables: WriteContractVariables, context?: unknown) => void;
547
onSettled?: (data?: Hash, error?: Error, variables?: WriteContractVariables, context?: unknown) => void;
548
}
549
```