0
# Gas & Fee Management
1
2
The gas and fee management functionality provides comprehensive tools for gas price discovery, fee market analysis, EIP-1559 transaction fee calculation, and fee history tracking.
3
4
## Gas Price Discovery
5
6
### getGasPrice
7
8
Returns the current gas price from the network.
9
10
```typescript { .api }
11
getGasPrice(returnFormat?: DataFormat): Promise<Numbers>;
12
```
13
14
**Usage Example:**
15
```typescript
16
// Get current gas price
17
const gasPrice = await eth.getGasPrice();
18
console.log(`Current gas price: ${gasPrice} Wei`);
19
20
// Convert to Gwei for readability
21
import { fromWei } from "web3-utils";
22
const gasPriceGwei = fromWei(gasPrice, "gwei");
23
console.log(`Current gas price: ${gasPriceGwei} Gwei`);
24
25
// Use in legacy transaction
26
const transaction = {
27
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
28
to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
29
value: "1000000000000000000",
30
gasPrice: gasPrice, // Use current gas price
31
gas: "21000"
32
};
33
```
34
35
### getMaxPriorityFeePerGas
36
37
Returns the current max priority fee per gas (EIP-1559 tip).
38
39
```typescript { .api }
40
getMaxPriorityFeePerGas(returnFormat?: DataFormat): Promise<Numbers>;
41
```
42
43
**Usage Example:**
44
```typescript
45
// Get suggested priority fee
46
const priorityFee = await eth.getMaxPriorityFeePerGas();
47
console.log(`Suggested priority fee: ${priorityFee} Wei`);
48
49
// Use in EIP-1559 transaction
50
const eip1559Transaction = {
51
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
52
to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
53
value: "1000000000000000000",
54
maxPriorityFeePerGas: priorityFee,
55
maxFeePerGas: "30000000000", // Set max fee willing to pay
56
gas: "21000",
57
type: 2 // EIP-1559 transaction
58
};
59
```
60
61
## EIP-1559 Fee Management
62
63
### getFeeData
64
65
Returns comprehensive fee data including base fee and priority fee suggestions. This is an alias for `calculateFeeData()` with no parameters.
66
67
```typescript { .api }
68
getFeeData(returnFormat?: DataFormat): Promise<FeeData>;
69
```
70
71
**Usage Example:**
72
```typescript
73
// Get complete fee data
74
const feeData = await eth.getFeeData();
75
console.log("Fee data:", {
76
gasPrice: feeData.gasPrice, // Legacy gas price
77
maxFeePerGas: feeData.maxFeePerGas, // EIP-1559 max fee
78
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas // EIP-1559 priority fee
79
});
80
81
// Use fee data in transaction
82
const receipt = await eth.sendTransaction({
83
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
84
to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
85
value: "1000000000000000000",
86
maxFeePerGas: feeData.maxFeePerGas,
87
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
88
type: 2
89
});
90
```
91
92
### calculateFeeData
93
94
Calculates fee data with custom base fee and priority fee parameters.
95
96
```typescript { .api }
97
calculateFeeData(baseFeePerGas?: Numbers, alternativeMaxPriorityFeePerGas?: Numbers): Promise<FeeData>;
98
```
99
100
**Usage Example:**
101
```typescript
102
// Calculate fees with custom base fee
103
const customBaseFee = "15000000000"; // 15 Gwei
104
const customFeeData = await eth.calculateFeeData(customBaseFee);
105
106
// Calculate fees with custom priority fee
107
const customPriorityFee = "2000000000"; // 2 Gwei
108
const feeDataWithTip = await eth.calculateFeeData(undefined, customPriorityFee);
109
110
// Use calculated fees
111
const transaction = {
112
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
113
to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
114
value: "1000000000000000000",
115
maxFeePerGas: feeDataWithTip.maxFeePerGas,
116
maxPriorityFeePerGas: feeDataWithTip.maxPriorityFeePerGas,
117
type: 2
118
};
119
```
120
121
## Fee History Analysis
122
123
### getFeeHistory
124
125
Retrieves historical fee data for analysis and fee estimation.
126
127
```typescript { .api }
128
getFeeHistory(blockCount: Numbers, lastBlock: BlockNumberOrTag, rewardPercentiles?: Numbers[], returnFormat?: DataFormat): Promise<FeeHistoryOutput>;
129
```
130
131
**Parameters:**
132
- `blockCount`: Number of blocks to retrieve
133
- `lastBlock`: Last block to include in history
134
- `rewardPercentiles`: Array of percentiles (0-100) for priority fee analysis
135
- `returnFormat`: Output format configuration
136
137
**Usage Example:**
138
```typescript
139
// Get fee history for last 100 blocks
140
const feeHistory = await eth.getFeeHistory(
141
100, // last 100 blocks
142
"latest", // up to latest block
143
[10, 25, 50, 75, 90] // percentiles for priority fees
144
);
145
146
console.log("Fee history:", {
147
oldestBlock: feeHistory.oldestBlock,
148
baseFeePerGas: feeHistory.baseFeePerGas,
149
reward: feeHistory.reward, // Priority fees at each percentile
150
gasUsedRatio: feeHistory.gasUsedRatio
151
});
152
153
// Analyze base fee trends
154
const baseFees = feeHistory.baseFeePerGas;
155
const avgBaseFee = baseFees.reduce((sum, fee, index) => {
156
if (index < baseFees.length - 1) { // Skip last element (next block's base fee)
157
return sum + Number(fee);
158
}
159
return sum;
160
}, 0) / (baseFees.length - 1);
161
162
console.log(`Average base fee: ${avgBaseFee} Wei`);
163
164
// Analyze priority fee trends (50th percentile)
165
const medianPriorityFees = feeHistory.reward.map(rewards => Number(rewards[2])); // 50th percentile
166
const avgPriorityFee = medianPriorityFees.reduce((sum, fee) => sum + fee, 0) / medianPriorityFees.length;
167
168
console.log(`Average priority fee (median): ${avgPriorityFee} Wei`);
169
```
170
171
## Advanced Fee Strategies
172
173
### Dynamic Fee Calculation
174
175
```typescript
176
// Smart fee calculation based on network conditions
177
async function calculateOptimalFees(urgency: 'slow' | 'standard' | 'fast' = 'standard') {
178
const feeHistory = await eth.getFeeHistory(20, "latest", [10, 50, 90]);
179
const feeData = await eth.getFeeData();
180
181
// Get recent base fees and priority fees
182
const recentBaseFees = feeHistory.baseFeePerGas.slice(0, -1).map(Number);
183
const recentPriorityFees = feeHistory.reward.map(rewards => Number(rewards[1])); // 50th percentile
184
185
// Calculate average and trend
186
const avgBaseFee = recentBaseFees.reduce((a, b) => a + b) / recentBaseFees.length;
187
const isBaseFeeRising = recentBaseFees[recentBaseFees.length - 1] > recentBaseFees[0];
188
189
// Adjust priority fee based on urgency
190
const priorityMultipliers = { slow: 0.8, standard: 1.0, fast: 1.5 };
191
const suggestedPriorityFee = Number(feeData.maxPriorityFeePerGas) * priorityMultipliers[urgency];
192
193
// Calculate max fee with buffer for base fee volatility
194
const baseFeeBuffer = isBaseFeeRising ? 1.3 : 1.1;
195
const maxFeePerGas = Math.floor(avgBaseFee * baseFeeBuffer + suggestedPriorityFee);
196
197
return {
198
maxFeePerGas: maxFeePerGas.toString(),
199
maxPriorityFeePerGas: Math.floor(suggestedPriorityFee).toString(),
200
estimatedBaseFee: Math.floor(avgBaseFee).toString(),
201
baseFeeDirection: isBaseFeeRising ? 'rising' : 'stable/falling'
202
};
203
}
204
205
// Usage
206
const optimalFees = await calculateOptimalFees('fast');
207
console.log("Optimal fees for fast confirmation:", optimalFees);
208
```
209
210
### Fee Monitoring
211
212
```typescript
213
// Monitor fee changes in real-time
214
async function monitorFees() {
215
const subscription = await eth.subscribe("newHeads");
216
217
subscription.on("data", async (blockHeader) => {
218
try {
219
// Get fee data for new block
220
const feeData = await eth.getFeeData();
221
const block = await eth.getBlock(blockHeader.number);
222
223
console.log(`Block ${blockHeader.number}:`, {
224
baseFeePerGas: block.baseFeePerGas,
225
gasUsed: blockHeader.gasUsed,
226
gasLimit: blockHeader.gasLimit,
227
utilization: (Number(blockHeader.gasUsed) / Number(blockHeader.gasLimit) * 100).toFixed(2) + '%',
228
suggestedMaxFee: feeData.maxFeePerGas,
229
suggestedPriorityFee: feeData.maxPriorityFeePerGas
230
});
231
} catch (error) {
232
console.error("Error monitoring fees:", error);
233
}
234
});
235
236
return subscription;
237
}
238
```
239
240
### Transaction Cost Estimation
241
242
```typescript
243
// Estimate total transaction costs
244
async function estimateTransactionCost(transaction: any, urgency: 'slow' | 'standard' | 'fast' = 'standard') {
245
// Get gas estimate
246
const gasEstimate = await eth.estimateGas(transaction);
247
248
// Get optimal fees
249
const fees = await calculateOptimalFees(urgency);
250
251
// Calculate costs
252
const maxCost = Number(gasEstimate) * Number(fees.maxFeePerGas);
253
const expectedCost = Number(gasEstimate) * (Number(fees.estimatedBaseFee) + Number(fees.maxPriorityFeePerGas));
254
255
return {
256
gasEstimate: gasEstimate.toString(),
257
maxFeePerGas: fees.maxFeePerGas,
258
maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
259
maxCostWei: maxCost.toString(),
260
expectedCostWei: expectedCost.toString(),
261
maxCostEth: (maxCost / 1e18).toFixed(6),
262
expectedCostEth: (expectedCost / 1e18).toFixed(6)
263
};
264
}
265
266
// Usage
267
const costEstimate = await estimateTransactionCost({
268
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
269
to: "0x1234567890123456789012345678901234567890",
270
data: "0xa9059cbb000000000000000000000000..." // token transfer
271
}, 'fast');
272
273
console.log("Transaction cost estimate:", costEstimate);
274
```
275
276
## Mining and Network Information
277
278
### getHashRate
279
280
Returns the current network hash rate (for compatible networks).
281
282
```typescript { .api }
283
getHashRate(returnFormat?: DataFormat): Promise<Numbers>;
284
```
285
286
### getWork
287
288
Returns the current work for mining (for compatible networks).
289
290
```typescript { .api }
291
getWork(): Promise<[HexString32Bytes, HexString32Bytes, HexString32Bytes]>;
292
```
293
294
### submitWork
295
296
Submits mining work to the network (for compatible networks).
297
298
```typescript { .api }
299
submitWork(nonce: HexString8Bytes, hash: HexString32Bytes, digest: HexString32Bytes): Promise<boolean>;
300
```
301
302
## Core Types
303
304
```typescript { .api }
305
interface FeeData {
306
gasPrice?: Numbers;
307
maxFeePerGas?: Numbers;
308
maxPriorityFeePerGas?: Numbers;
309
}
310
311
interface FeeHistoryOutput {
312
oldestBlock: Numbers;
313
baseFeePerGas: Numbers[];
314
reward: Numbers[][];
315
gasUsedRatio: Numbers[];
316
}
317
318
type Numbers = HexString | number | bigint;
319
type BlockNumberOrTag = Numbers | "latest" | "earliest" | "pending" | "safe" | "finalized";
320
321
interface DataFormat {
322
number: NumberFormat;
323
bytes: BytesFormat;
324
}
325
326
type NumberFormat = "NUMBER_HEX" | "NUMBER_NUMBER" | "NUMBER_BIGINT";
327
type BytesFormat = "BYTES_HEX" | "BYTES_UINT8ARRAY";
328
```