0
# Transaction Management
1
2
Transaction sending, estimation, waiting, and monitoring. Complete transaction lifecycle management.
3
4
## Capabilities
5
6
### Send Transaction
7
8
Sends a transaction to the blockchain.
9
10
```typescript { .api }
11
/**
12
* Sends a transaction to the blockchain
13
* @param config - Wagmi configuration
14
* @param parameters - Transaction parameters
15
* @returns Transaction hash
16
*/
17
function sendTransaction<config extends Config>(
18
config: config,
19
parameters: SendTransactionParameters<config>
20
): Promise<SendTransactionReturnType>;
21
22
interface SendTransactionParameters<config extends Config> {
23
/** Account to send from (optional, uses connected account) */
24
account?: Address;
25
/** Target address */
26
to?: Address;
27
/** Transaction data */
28
data?: Hex;
29
/** Gas limit */
30
gas?: bigint;
31
/** Gas price (legacy transactions) */
32
gasPrice?: bigint;
33
/** Max fee per gas (EIP-1559) */
34
maxFeePerGas?: bigint;
35
/** Max priority fee per gas (EIP-1559) */
36
maxPriorityFeePerGas?: bigint;
37
/** Nonce */
38
nonce?: number;
39
/** Value to send in wei */
40
value?: bigint;
41
/** Chain ID to send on */
42
chainId?: config['chains'][number]['id'];
43
}
44
45
type SendTransactionReturnType = Hash; // Transaction hash
46
47
type SendTransactionErrorType =
48
| BaseErrorType
49
| UserRejectedRequestErrorType
50
| InsufficientFundsErrorType;
51
```
52
53
**Usage Example:**
54
55
```typescript
56
import { sendTransaction, parseEther } from '@wagmi/core'
57
58
// Send ETH transfer
59
const hash = await sendTransaction(config, {
60
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
61
value: parseEther('0.1'), // 0.1 ETH
62
})
63
console.log('Transaction hash:', hash)
64
65
// Send transaction with custom gas
66
const customGasHash = await sendTransaction(config, {
67
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
68
value: parseEther('0.05'),
69
gas: 21000n,
70
maxFeePerGas: parseGwei('20'),
71
maxPriorityFeePerGas: parseGwei('2'),
72
})
73
74
// Send contract interaction data
75
const contractCallHash = await sendTransaction(config, {
76
to: '0xContractAddress',
77
data: '0x1234567890abcdef...', // Encoded function call
78
gas: 100000n,
79
})
80
```
81
82
### Estimate Gas
83
84
Estimates gas required for a transaction.
85
86
```typescript { .api }
87
/**
88
* Estimates gas for a transaction
89
* @param config - Wagmi configuration
90
* @param parameters - Gas estimation parameters
91
* @returns Estimated gas amount
92
*/
93
function estimateGas<config extends Config>(
94
config: config,
95
parameters: EstimateGasParameters<config>
96
): Promise<EstimateGasReturnType>;
97
98
interface EstimateGasParameters<config extends Config> {
99
/** Account to estimate from */
100
account?: Address;
101
/** Target address */
102
to?: Address;
103
/** Transaction data */
104
data?: Hex;
105
/** Gas price */
106
gasPrice?: bigint;
107
/** Max fee per gas */
108
maxFeePerGas?: bigint;
109
/** Max priority fee per gas */
110
maxPriorityFeePerGas?: bigint;
111
/** Nonce */
112
nonce?: number;
113
/** Value to send */
114
value?: bigint;
115
/** Chain ID to estimate on */
116
chainId?: config['chains'][number]['id'];
117
/** Block number to estimate at */
118
blockNumber?: bigint;
119
/** Block tag */
120
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
121
}
122
123
type EstimateGasReturnType = bigint;
124
125
type EstimateGasErrorType = BaseErrorType | EstimationErrorType;
126
```
127
128
**Usage Example:**
129
130
```typescript
131
import { estimateGas, parseEther } from '@wagmi/core'
132
133
// Estimate gas for ETH transfer
134
const gasEstimate = await estimateGas(config, {
135
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
136
value: parseEther('0.1'),
137
})
138
console.log('Estimated gas:', gasEstimate.toString())
139
140
// Estimate gas for contract call
141
const contractGasEstimate = await estimateGas(config, {
142
to: '0xContractAddress',
143
data: '0x1234567890abcdef...', // Encoded function call
144
})
145
console.log('Contract call gas estimate:', contractGasEstimate.toString())
146
147
// Use estimate in actual transaction
148
const hash = await sendTransaction(config, {
149
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
150
value: parseEther('0.1'),
151
gas: gasEstimate + 10000n, // Add buffer
152
})
153
```
154
155
### Prepare Transaction Request
156
157
Prepares a transaction request with gas estimation and fee calculation.
158
159
```typescript { .api }
160
/**
161
* Prepares transaction request with gas estimation
162
* @param config - Wagmi configuration
163
* @param parameters - Transaction preparation parameters
164
* @returns Prepared transaction request
165
*/
166
function prepareTransactionRequest<config extends Config>(
167
config: config,
168
parameters: PrepareTransactionRequestParameters<config>
169
): Promise<PrepareTransactionRequestReturnType>;
170
171
interface PrepareTransactionRequestParameters<config extends Config> {
172
/** Account to send from */
173
account?: Address;
174
/** Target address */
175
to?: Address;
176
/** Transaction data */
177
data?: Hex;
178
/** Gas limit (optional, will estimate if not provided) */
179
gas?: bigint;
180
/** Gas price (legacy) */
181
gasPrice?: bigint;
182
/** Max fee per gas (EIP-1559) */
183
maxFeePerGas?: bigint;
184
/** Max priority fee per gas (EIP-1559) */
185
maxPriorityFeePerGas?: bigint;
186
/** Nonce (optional, will fetch if not provided) */
187
nonce?: number;
188
/** Value to send */
189
value?: bigint;
190
/** Chain ID */
191
chainId?: config['chains'][number]['id'];
192
}
193
194
interface PrepareTransactionRequestReturnType {
195
/** Account sending transaction */
196
account: Address;
197
/** Target address */
198
to?: Address;
199
/** Transaction data */
200
data?: Hex;
201
/** Gas limit */
202
gas: bigint;
203
/** Gas price (legacy) */
204
gasPrice?: bigint;
205
/** Max fee per gas (EIP-1559) */
206
maxFeePerGas?: bigint;
207
/** Max priority fee per gas (EIP-1559) */
208
maxPriorityFeePerGas?: bigint;
209
/** Nonce */
210
nonce: number;
211
/** Value to send */
212
value?: bigint;
213
/** Chain ID */
214
chainId: number;
215
/** Transaction type */
216
type: 'legacy' | 'eip2930' | 'eip1559';
217
}
218
219
type PrepareTransactionRequestErrorType =
220
| BaseErrorType
221
| EstimationErrorType;
222
```
223
224
**Usage Example:**
225
226
```typescript
227
import { prepareTransactionRequest, sendTransaction } from '@wagmi/core'
228
229
// Prepare transaction with automatic gas estimation
230
const prepared = await prepareTransactionRequest(config, {
231
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
232
value: parseEther('0.1'),
233
})
234
235
console.log('Prepared transaction:', {
236
gas: prepared.gas.toString(),
237
maxFeePerGas: prepared.maxFeePerGas?.toString(),
238
nonce: prepared.nonce,
239
type: prepared.type,
240
})
241
242
// Send the prepared transaction
243
const hash = await sendTransaction(config, prepared)
244
console.log('Transaction sent:', hash)
245
```
246
247
### Wait for Transaction Receipt
248
249
Waits for a transaction to be mined and returns the receipt.
250
251
```typescript { .api }
252
/**
253
* Waits for transaction to be mined
254
* @param config - Wagmi configuration
255
* @param parameters - Wait parameters
256
* @returns Transaction receipt
257
*/
258
function waitForTransactionReceipt<config extends Config>(
259
config: config,
260
parameters: WaitForTransactionReceiptParameters<config>
261
): Promise<WaitForTransactionReceiptReturnType>;
262
263
interface WaitForTransactionReceiptParameters<config extends Config> {
264
/** Transaction hash to wait for */
265
hash: Hash;
266
/** Number of confirmations to wait for */
267
confirmations?: number;
268
/** Polling interval in milliseconds */
269
pollingInterval?: number;
270
/** Timeout in milliseconds */
271
timeout?: number;
272
/** Chain ID */
273
chainId?: config['chains'][number]['id'];
274
}
275
276
interface WaitForTransactionReceiptReturnType {
277
/** Transaction hash */
278
transactionHash: Hash;
279
/** Block hash */
280
blockHash: Hash;
281
/** Block number */
282
blockNumber: bigint;
283
/** Transaction index in block */
284
transactionIndex: number;
285
/** From address */
286
from: Address;
287
/** To address */
288
to?: Address;
289
/** Gas used */
290
gasUsed: bigint;
291
/** Effective gas price */
292
effectiveGasPrice: bigint;
293
/** Transaction status */
294
status: 'success' | 'reverted';
295
/** Event logs */
296
logs: Log[];
297
/** Contract address (if deployment) */
298
contractAddress?: Address;
299
/** Cumulative gas used in block */
300
cumulativeGasUsed: bigint;
301
/** Transaction type */
302
type: 'legacy' | 'eip2930' | 'eip1559';
303
}
304
305
type WaitForTransactionReceiptErrorType =
306
| BaseErrorType
307
| TransactionReceiptNotFoundErrorType
308
| TransactionNotFoundErrorType
309
| WaitForTransactionReceiptTimeoutErrorType;
310
311
/** @deprecated Use waitForTransactionReceipt instead */
312
const waitForTransaction = waitForTransactionReceipt;
313
```
314
315
**Usage Example:**
316
317
```typescript
318
import { sendTransaction, waitForTransactionReceipt } from '@wagmi/core'
319
320
// Send transaction and wait for confirmation
321
const hash = await sendTransaction(config, {
322
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
323
value: parseEther('0.1'),
324
})
325
326
console.log('Transaction sent:', hash)
327
328
// Wait for transaction to be mined
329
const receipt = await waitForTransactionReceipt(config, {
330
hash,
331
confirmations: 1, // Wait for 1 confirmation
332
})
333
334
console.log('Transaction confirmed:', {
335
blockNumber: receipt.blockNumber.toString(),
336
gasUsed: receipt.gasUsed.toString(),
337
status: receipt.status,
338
})
339
340
// Check if transaction succeeded
341
if (receipt.status === 'success') {
342
console.log('Transaction successful!')
343
console.log('Logs:', receipt.logs.length)
344
} else {
345
console.log('Transaction failed/reverted')
346
}
347
```
348
349
### Batch Calls (EIP-5792)
350
351
Send multiple operations in a single batch transaction.
352
353
```typescript { .api }
354
/**
355
* Sends batch of calls (EIP-5792)
356
* @param config - Wagmi configuration
357
* @param parameters - Batch calls parameters
358
* @returns Batch call identifier
359
*/
360
function sendCalls<config extends Config>(
361
config: config,
362
parameters: SendCallsParameters<config>
363
): Promise<SendCallsReturnType>;
364
365
interface SendCallsParameters<config extends Config> {
366
/** Array of calls to execute */
367
calls: readonly {
368
/** Target contract address */
369
to?: Address;
370
/** Call data */
371
data?: Hex;
372
/** Value to send with call */
373
value?: bigint;
374
}[];
375
/** Chain ID to execute on */
376
chainId?: config['chains'][number]['id'];
377
/** Capabilities for the batch */
378
capabilities?: {
379
/** Paymaster service configuration */
380
paymasterService?: {
381
url: string;
382
};
383
/** Auxiliary funds configuration */
384
auxiliaryFunds?: {
385
supported: boolean;
386
};
387
};
388
}
389
390
type SendCallsReturnType = string; // Batch identifier
391
392
type SendCallsErrorType =
393
| BaseErrorType
394
| UserRejectedRequestErrorType;
395
396
/**
397
* Gets status of batch calls
398
* @param config - Wagmi configuration
399
* @param parameters - Status query parameters
400
* @returns Batch status information
401
*/
402
function getCallsStatus<config extends Config>(
403
config: config,
404
parameters: GetCallsStatusParameters<config>
405
): Promise<GetCallsStatusReturnType>;
406
407
interface GetCallsStatusParameters<config extends Config> {
408
/** Batch identifier */
409
id: string;
410
/** Chain ID */
411
chainId?: config['chains'][number]['id'];
412
}
413
414
interface GetCallsStatusReturnType {
415
/** Batch status */
416
status: 'PENDING' | 'CONFIRMED';
417
/** Transaction receipts (if confirmed) */
418
receipts?: TransactionReceipt[];
419
}
420
421
/**
422
* Waits for batch calls to complete
423
* @param config - Wagmi configuration
424
* @param parameters - Wait parameters
425
* @returns Final batch status
426
*/
427
function waitForCallsStatus<config extends Config>(
428
config: config,
429
parameters: WaitForCallsStatusParameters<config>
430
): Promise<WaitForCallsStatusReturnType>;
431
432
interface WaitForCallsStatusParameters<config extends Config> {
433
/** Batch identifier */
434
id: string;
435
/** Chain ID */
436
chainId?: config['chains'][number]['id'];
437
/** Polling interval */
438
pollingInterval?: number;
439
/** Timeout */
440
timeout?: number;
441
}
442
443
type WaitForCallsStatusReturnType = GetCallsStatusReturnType;
444
445
/**
446
* Shows status UI for batch calls
447
* @param config - Wagmi configuration
448
* @param parameters - Show status parameters
449
* @returns Status display result
450
*/
451
function showCallsStatus<config extends Config>(
452
config: config,
453
parameters: ShowCallsStatusParameters<config>
454
): Promise<ShowCallsStatusReturnType>;
455
456
interface ShowCallsStatusParameters<config extends Config> {
457
/** Batch identifier */
458
id: string;
459
/** Chain ID */
460
chainId?: config['chains'][number]['id'];
461
}
462
463
type ShowCallsStatusReturnType = null;
464
```
465
466
**Usage Example:**
467
468
```typescript
469
import {
470
sendCalls,
471
waitForCallsStatus,
472
getCallsStatus,
473
showCallsStatus
474
} from '@wagmi/core'
475
476
// Send batch of ERC-20 transfers
477
const batchId = await sendCalls(config, {
478
calls: [
479
{
480
to: '0xTokenA',
481
data: encodeFunctionData({
482
abi: erc20Abi,
483
functionName: 'transfer',
484
args: ['0xRecipient1', 1000000n],
485
}),
486
},
487
{
488
to: '0xTokenB',
489
data: encodeFunctionData({
490
abi: erc20Abi,
491
functionName: 'transfer',
492
args: ['0xRecipient2', 2000000n],
493
}),
494
},
495
],
496
})
497
498
console.log('Batch sent:', batchId)
499
500
// Wait for batch to complete
501
const finalStatus = await waitForCallsStatus(config, {
502
id: batchId,
503
})
504
505
if (finalStatus.status === 'CONFIRMED') {
506
console.log('Batch confirmed!')
507
console.log('Receipts:', finalStatus.receipts?.length)
508
}
509
510
// Or check status manually
511
const status = await getCallsStatus(config, { id: batchId })
512
console.log('Current status:', status.status)
513
514
// Show status in wallet UI
515
await showCallsStatus(config, { id: batchId })
516
```
517
518
## Transaction Utilities
519
520
### Transaction Monitoring
521
522
Monitor pending and confirmed transactions.
523
524
```typescript { .api }
525
/**
526
* Watches for pending transactions
527
* @param config - Wagmi configuration
528
* @param parameters - Watch parameters
529
* @returns Unsubscribe function
530
*/
531
function watchPendingTransactions<config extends Config>(
532
config: config,
533
parameters: WatchPendingTransactionsParameters<config>
534
): WatchPendingTransactionsReturnType;
535
536
interface WatchPendingTransactionsParameters<config extends Config> {
537
/** Callback when new pending transaction detected */
538
onTransactions(transactions: Hash[]): void;
539
/** Callback for errors */
540
onError?(error: Error): void;
541
/** Chain ID to watch */
542
chainId?: config['chains'][number]['id'];
543
/** Polling interval */
544
poll?: boolean;
545
/** Polling interval in ms */
546
pollingInterval?: number;
547
}
548
549
type WatchPendingTransactionsReturnType = () => void; // Unsubscribe function
550
```
551
552
**Usage Example:**
553
554
```typescript
555
import { watchPendingTransactions } from '@wagmi/core'
556
557
// Watch for pending transactions
558
const unsubscribe = watchPendingTransactions(config, {
559
onTransactions(hashes) {
560
console.log('New pending transactions:', hashes)
561
// Process pending transactions
562
hashes.forEach(hash => {
563
console.log('Pending tx:', hash)
564
})
565
},
566
onError(error) {
567
console.error('Watch error:', error)
568
},
569
pollingInterval: 1000, // Check every second
570
})
571
572
// Stop watching
573
// unsubscribe()
574
```
575
576
### Complete Transaction Flow Example
577
578
Here's a complete example showing the full transaction lifecycle:
579
580
```typescript
581
import {
582
estimateGas,
583
prepareTransactionRequest,
584
sendTransaction,
585
waitForTransactionReceipt,
586
parseEther,
587
parseGwei
588
} from '@wagmi/core'
589
590
async function sendTransactionWithFullFlow() {
591
try {
592
// 1. Estimate gas first
593
const gasEstimate = await estimateGas(config, {
594
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
595
value: parseEther('0.1'),
596
})
597
console.log('Gas estimate:', gasEstimate.toString())
598
599
// 2. Prepare transaction with custom parameters
600
const prepared = await prepareTransactionRequest(config, {
601
to: '0x742d35Cc6601C2F3Ac5e5c7A9d16e4e6Be4e6e9e',
602
value: parseEther('0.1'),
603
gas: gasEstimate + 5000n, // Add buffer
604
maxFeePerGas: parseGwei('20'),
605
maxPriorityFeePerGas: parseGwei('2'),
606
})
607
console.log('Prepared transaction:', prepared)
608
609
// 3. Send transaction
610
const hash = await sendTransaction(config, prepared)
611
console.log('Transaction sent:', hash)
612
613
// 4. Wait for confirmation
614
const receipt = await waitForTransactionReceipt(config, {
615
hash,
616
confirmations: 2, // Wait for 2 confirmations
617
timeout: 60000, // 1 minute timeout
618
})
619
620
// 5. Handle result
621
if (receipt.status === 'success') {
622
console.log('✅ Transaction successful!')
623
console.log('Block:', receipt.blockNumber.toString())
624
console.log('Gas used:', receipt.gasUsed.toString())
625
console.log('Effective gas price:', receipt.effectiveGasPrice.toString())
626
} else {
627
console.log('❌ Transaction failed')
628
}
629
630
return receipt
631
632
} catch (error) {
633
console.error('Transaction failed:', error)
634
635
// Handle specific errors
636
if (error.name === 'UserRejectedRequestError') {
637
console.log('User cancelled transaction')
638
} else if (error.name === 'InsufficientFundsError') {
639
console.log('Insufficient funds for transaction')
640
} else if (error.name === 'EstimationError') {
641
console.log('Gas estimation failed')
642
}
643
644
throw error
645
}
646
}
647
648
// Usage
649
sendTransactionWithFullFlow()
650
.then(receipt => console.log('Final receipt:', receipt))
651
.catch(error => console.error('Flow failed:', error))
652
```