0
# Gas & Fee Estimation
1
2
Gas price monitoring and transaction fee estimation with support for EIP-1559 fee markets. This module provides comprehensive gas and fee estimation functionality for optimal transaction pricing and network cost management.
3
4
## Capabilities
5
6
### useEstimateGas
7
8
Hook to estimate gas required for a transaction before sending it.
9
10
```typescript { .api }
11
/**
12
* Hook to estimate gas for transaction
13
* @param parameters - Gas estimation parameters
14
* @returns Estimated gas amount required for the transaction
15
*/
16
function useEstimateGas<config = Config, selectData = UseEstimateGasReturnType>(
17
parameters: UseEstimateGasParameters<config, selectData>
18
): UseEstimateGasReturnType<selectData>;
19
20
interface UseEstimateGasParameters<config = Config, selectData = UseEstimateGasReturnType> {
21
/** Recipient address */
22
to: Address;
23
/** Transaction value */
24
value?: bigint;
25
/** Transaction data */
26
data?: Hex;
27
/** Account to estimate from */
28
account?: Address;
29
/** Block number to estimate at */
30
blockNumber?: bigint;
31
blockTag?: 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
32
/** Chain to use */
33
chainId?: config['chains'][number]['id'];
34
/** Gas price for estimation */
35
gasPrice?: bigint;
36
/** Max fee per gas */
37
maxFeePerGas?: bigint;
38
/** Max priority fee per gas */
39
maxPriorityFeePerGas?: bigint;
40
/** Nonce */
41
nonce?: number;
42
config?: Config | config;
43
query?: {
44
enabled?: boolean;
45
staleTime?: number;
46
gcTime?: number;
47
select?: (data: UseEstimateGasReturnType) => selectData;
48
};
49
}
50
51
type UseEstimateGasReturnType = bigint;
52
```
53
54
**Usage Example:**
55
56
```typescript
57
import { useEstimateGas, useSendTransaction } from "wagmi";
58
import { parseEther, formatGwei } from "viem";
59
60
function GasEstimationExample() {
61
const transactionParams = {
62
to: '0x742d35Cc6634C0532925a3b8D' as const,
63
value: parseEther('0.1'),
64
};
65
66
const { data: gasEstimate, isLoading } = useEstimateGas(transactionParams);
67
const { sendTransaction } = useSendTransaction();
68
69
const handleSend = () => {
70
sendTransaction({
71
...transactionParams,
72
gas: gasEstimate, // Use estimated gas
73
});
74
};
75
76
return (
77
<div>
78
{isLoading ? (
79
<p>Estimating gas...</p>
80
) : (
81
<div>
82
<p>Estimated gas: {gasEstimate?.toString()}</p>
83
<button onClick={handleSend}>Send with estimated gas</button>
84
</div>
85
)}
86
</div>
87
);
88
}
89
```
90
91
### useGasPrice
92
93
Hook to get current network gas price for legacy transactions.
94
95
```typescript { .api }
96
/**
97
* Hook to get current gas price
98
* @param parameters - Gas price query parameters
99
* @returns Current network gas price in wei
100
*/
101
function useGasPrice<config = Config, selectData = UseGasPriceReturnType>(
102
parameters?: UseGasPriceParameters<config, selectData>
103
): UseGasPriceReturnType<selectData>;
104
105
interface UseGasPriceParameters<config = Config, selectData = UseGasPriceReturnType> {
106
/** Chain to get gas price for */
107
chainId?: config['chains'][number]['id'];
108
config?: Config | config;
109
query?: {
110
enabled?: boolean;
111
staleTime?: number;
112
gcTime?: number;
113
refetchInterval?: number;
114
select?: (data: UseGasPriceReturnType) => selectData;
115
};
116
}
117
118
type UseGasPriceReturnType = bigint;
119
```
120
121
### useEstimateFeesPerGas
122
123
Hook to estimate fees per gas for EIP-1559 transactions (replaces legacy gas price).
124
125
```typescript { .api }
126
/**
127
* Hook to estimate fees per gas (replaces useFeeData)
128
* @param parameters - Fee estimation parameters
129
* @returns Fee estimates for EIP-1559 transactions
130
*/
131
function useEstimateFeesPerGas<config = Config, selectData = UseEstimateFeesPerGasReturnType>(
132
parameters?: UseEstimateFeesPerGasParameters<config, selectData>
133
): UseEstimateFeesPerGasReturnType<selectData>;
134
135
interface UseEstimateFeesPerGasParameters<config = Config, selectData = UseEstimateFeesPerGasReturnType> {
136
/** Fee multiplier for priority adjustment */
137
formatUnits?: 'wei' | 'gwei';
138
/** Transaction type hint */
139
type?: 'legacy' | 'eip1559';
140
/** Chain to estimate fees for */
141
chainId?: config['chains'][number]['id'];
142
config?: Config | config;
143
query?: {
144
enabled?: boolean;
145
staleTime?: number;
146
gcTime?: number;
147
refetchInterval?: number;
148
select?: (data: UseEstimateFeesPerGasReturnType) => selectData;
149
};
150
}
151
152
interface UseEstimateFeesPerGasReturnType {
153
/** Legacy gas price */
154
gasPrice?: bigint;
155
/** Max fee per gas (EIP-1559) */
156
maxFeePerGas?: bigint;
157
/** Max priority fee per gas (EIP-1559) */
158
maxPriorityFeePerGas?: bigint;
159
}
160
```
161
162
**Usage Example:**
163
164
```typescript
165
import { useEstimateFeesPerGas } from "wagmi";
166
import { formatGwei } from "viem";
167
168
function FeeEstimation() {
169
const { data: feeData, isLoading } = useEstimateFeesPerGas();
170
171
if (isLoading) return <div>Loading fee estimates...</div>;
172
173
return (
174
<div>
175
<h3>Current Fee Estimates</h3>
176
{feeData?.gasPrice && (
177
<p>Gas Price: {formatGwei(feeData.gasPrice)} gwei</p>
178
)}
179
{feeData?.maxFeePerGas && (
180
<p>Max Fee: {formatGwei(feeData.maxFeePerGas)} gwei</p>
181
)}
182
{feeData?.maxPriorityFeePerGas && (
183
<p>Max Priority Fee: {formatGwei(feeData.maxPriorityFeePerGas)} gwei</p>
184
)}
185
</div>
186
);
187
}
188
```
189
190
### useEstimateMaxPriorityFeePerGas
191
192
Hook to estimate the maximum priority fee per gas for EIP-1559 transactions.
193
194
```typescript { .api }
195
/**
196
* Hook to estimate max priority fee per gas
197
* @param parameters - Max priority fee estimation parameters
198
* @returns Estimated maximum priority fee per gas
199
*/
200
function useEstimateMaxPriorityFeePerGas<config = Config, selectData = UseEstimateMaxPriorityFeePerGasReturnType>(
201
parameters?: UseEstimateMaxPriorityFeePerGasParameters<config, selectData>
202
): UseEstimateMaxPriorityFeePerGasReturnType<selectData>;
203
204
interface UseEstimateMaxPriorityFeePerGasParameters<config = Config, selectData = UseEstimateMaxPriorityFeePerGasReturnType> {
205
/** Chain to estimate for */
206
chainId?: config['chains'][number]['id'];
207
config?: Config | config;
208
query?: {
209
enabled?: boolean;
210
staleTime?: number;
211
gcTime?: number;
212
refetchInterval?: number;
213
select?: (data: UseEstimateMaxPriorityFeePerGasReturnType) => selectData;
214
};
215
}
216
217
type UseEstimateMaxPriorityFeePerGasReturnType = bigint;
218
```
219
220
### useFeeHistory
221
222
Hook to get historical fee data for analysis and prediction.
223
224
```typescript { .api }
225
/**
226
* Hook to get fee history
227
* @param parameters - Fee history query parameters
228
* @returns Historical fee data for the specified block range
229
*/
230
function useFeeHistory<config = Config, selectData = UseFeeHistoryReturnType>(
231
parameters: UseFeeHistoryParameters<config, selectData>
232
): UseFeeHistoryReturnType<selectData>;
233
234
interface UseFeeHistoryParameters<config = Config, selectData = UseFeeHistoryReturnType> {
235
/** Number of blocks to fetch history for */
236
blockCount: number;
237
/** Newest block number or tag */
238
newestBlock?: bigint | 'latest' | 'earliest' | 'pending' | 'safe' | 'finalized';
239
/** Reward percentiles to calculate */
240
rewardPercentiles?: number[];
241
/** Chain to get history for */
242
chainId?: config['chains'][number]['id'];
243
config?: Config | config;
244
query?: {
245
enabled?: boolean;
246
staleTime?: number;
247
gcTime?: number;
248
select?: (data: UseFeeHistoryReturnType) => selectData;
249
};
250
}
251
252
interface UseFeeHistoryReturnType {
253
/** Base fee per gas for each block */
254
baseFeePerGas: bigint[];
255
/** Gas used ratio for each block */
256
gasUsedRatio: number[];
257
/** Oldest block number in the range */
258
oldestBlock: bigint;
259
/** Reward percentiles for each block */
260
reward?: bigint[][];
261
}
262
```
263
264
**Usage Example:**
265
266
```typescript
267
import { useFeeHistory } from "wagmi";
268
import { formatGwei } from "viem";
269
270
function FeeAnalytics() {
271
const { data: feeHistory, isLoading } = useFeeHistory({
272
blockCount: 10, // Last 10 blocks
273
rewardPercentiles: [25, 50, 75], // 25th, 50th, 75th percentiles
274
});
275
276
if (isLoading) return <div>Loading fee history...</div>;
277
278
const avgBaseFee = feeHistory?.baseFeePerGas.reduce((sum, fee) => sum + fee, 0n)
279
/ BigInt(feeHistory?.baseFeePerGas.length || 1);
280
281
return (
282
<div>
283
<h3>Fee Analytics</h3>
284
<p>Average Base Fee: {formatGwei(avgBaseFee || 0n)} gwei</p>
285
<p>Latest Block: {feeHistory?.oldestBlock.toString()}</p>
286
287
<h4>Recent Base Fees</h4>
288
{feeHistory?.baseFeePerGas.map((fee, i) => (
289
<div key={i}>
290
Block {(feeHistory.oldestBlock + BigInt(i)).toString()}: {formatGwei(fee)} gwei
291
</div>
292
))}
293
</div>
294
);
295
}
296
```
297
298
## Advanced Fee Management
299
300
### Dynamic Fee Calculator
301
302
```typescript
303
import {
304
useEstimateFeesPerGas,
305
useFeeHistory,
306
useEstimateGas
307
} from "wagmi";
308
import { formatGwei, parseGwei } from "viem";
309
310
interface FeeSpeed {
311
name: string;
312
multiplier: number;
313
description: string;
314
}
315
316
const FEE_SPEEDS: FeeSpeed[] = [
317
{ name: 'Slow', multiplier: 0.9, description: '~5 min' },
318
{ name: 'Standard', multiplier: 1.0, description: '~2 min' },
319
{ name: 'Fast', multiplier: 1.1, description: '~30 sec' },
320
{ name: 'Urgent', multiplier: 1.25, description: '~15 sec' },
321
];
322
323
function DynamicFeeCalculator({
324
transactionParams
325
}: {
326
transactionParams: { to: Address; value?: bigint; data?: Hex }
327
}) {
328
const { data: currentFees } = useEstimateFeesPerGas();
329
const { data: gasEstimate } = useEstimateGas(transactionParams);
330
331
const { data: feeHistory } = useFeeHistory({
332
blockCount: 5,
333
rewardPercentiles: [10, 50, 90],
334
});
335
336
const calculateFeeOptions = () => {
337
if (!currentFees?.maxFeePerGas || !currentFees?.maxPriorityFeePerGas) {
338
return [];
339
}
340
341
return FEE_SPEEDS.map(speed => {
342
const maxPriorityFee = currentFees.maxPriorityFeePerGas! * BigInt(Math.floor(speed.multiplier * 100)) / 100n;
343
const maxFee = currentFees.maxFeePerGas! * BigInt(Math.floor(speed.multiplier * 100)) / 100n;
344
345
const estimatedCost = gasEstimate ? (gasEstimate * maxFee) : 0n;
346
347
return {
348
...speed,
349
maxFeePerGas: maxFee,
350
maxPriorityFeePerGas: maxPriorityFee,
351
estimatedCost,
352
};
353
});
354
};
355
356
const feeOptions = calculateFeeOptions();
357
358
return (
359
<div>
360
<h3>Transaction Fee Options</h3>
361
{feeOptions.map((option, i) => (
362
<div key={i} className="fee-option">
363
<h4>{option.name} ({option.description})</h4>
364
<p>Max Fee: {formatGwei(option.maxFeePerGas)} gwei</p>
365
<p>Priority Fee: {formatGwei(option.maxPriorityFeePerGas)} gwei</p>
366
{option.estimatedCost > 0n && (
367
<p>Est. Cost: {formatEther(option.estimatedCost)} ETH</p>
368
)}
369
</div>
370
))}
371
</div>
372
);
373
}
374
```
375
376
### Fee Monitoring Component
377
378
```typescript
379
import { useEstimateFeesPerGas, useGasPrice } from "wagmi";
380
import { formatGwei } from "viem";
381
import { useEffect, useState } from "react";
382
383
function FeeMonitor() {
384
const [feeHistory, setFeeHistory] = useState<bigint[]>([]);
385
386
const { data: currentFees } = useEstimateFeesPerGas({
387
query: { refetchInterval: 10000 } // Update every 10 seconds
388
});
389
390
const { data: gasPrice } = useGasPrice({
391
query: { refetchInterval: 10000 }
392
});
393
394
useEffect(() => {
395
if (currentFees?.maxFeePerGas) {
396
setFeeHistory(prev => [...prev.slice(-19), currentFees.maxFeePerGas!]);
397
}
398
}, [currentFees]);
399
400
const avgFee = feeHistory.length > 0
401
? feeHistory.reduce((sum, fee) => sum + fee, 0n) / BigInt(feeHistory.length)
402
: 0n;
403
404
const minFee = feeHistory.length > 0 ? feeHistory.reduce((min, fee) => fee < min ? fee : min) : 0n;
405
const maxFee = feeHistory.length > 0 ? feeHistory.reduce((max, fee) => fee > max ? fee : max) : 0n;
406
407
return (
408
<div className="fee-monitor">
409
<h3>Network Fee Monitor</h3>
410
411
<div className="current-fees">
412
<h4>Current Fees</h4>
413
{gasPrice && <p>Gas Price: {formatGwei(gasPrice)} gwei</p>}
414
{currentFees?.maxFeePerGas && (
415
<p>Max Fee: {formatGwei(currentFees.maxFeePerGas)} gwei</p>
416
)}
417
{currentFees?.maxPriorityFeePerGas && (
418
<p>Priority Fee: {formatGwei(currentFees.maxPriorityFeePerGas)} gwei</p>
419
)}
420
</div>
421
422
{feeHistory.length > 0 && (
423
<div className="fee-stats">
424
<h4>Fee Statistics (Last {feeHistory.length} updates)</h4>
425
<p>Average: {formatGwei(avgFee)} gwei</p>
426
<p>Min: {formatGwei(minFee)} gwei</p>
427
<p>Max: {formatGwei(maxFee)} gwei</p>
428
</div>
429
)}
430
</div>
431
);
432
}
433
```
434
435
## Common Types
436
437
```typescript { .api }
438
type Address = `0x${string}`;
439
type Hex = `0x${string}`;
440
441
interface GasEstimate {
442
/** Estimated gas units */
443
gas: bigint;
444
/** Estimated cost in wei */
445
cost: bigint;
446
}
447
448
interface FeeData {
449
/** Legacy gas price */
450
gasPrice?: bigint;
451
/** EIP-1559 max fee per gas */
452
maxFeePerGas?: bigint;
453
/** EIP-1559 max priority fee per gas */
454
maxPriorityFeePerGas?: bigint;
455
/** Last base fee per gas */
456
lastBaseFeePerGas?: bigint;
457
}
458
459
interface FeeSuggestion {
460
/** Suggested priority fee */
461
maxPriorityFeePerGas: bigint;
462
/** Suggested max fee */
463
maxFeePerGas: bigint;
464
/** Expected confirmation time */
465
estimatedTime: string;
466
/** Confidence level */
467
confidence: 'low' | 'medium' | 'high';
468
}
469
```