Web3 module to interact with the Ethereum blockchain and smart contracts.
67
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.
Returns the current gas price from the network.
getGasPrice(returnFormat?: DataFormat): Promise<Numbers>;Usage Example:
// Get current gas price
const gasPrice = await eth.getGasPrice();
console.log(`Current gas price: ${gasPrice} Wei`);
// Convert to Gwei for readability
import { fromWei } from "web3-utils";
const gasPriceGwei = fromWei(gasPrice, "gwei");
console.log(`Current gas price: ${gasPriceGwei} Gwei`);
// Use in legacy transaction
const transaction = {
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
value: "1000000000000000000",
gasPrice: gasPrice, // Use current gas price
gas: "21000"
};Returns the current max priority fee per gas (EIP-1559 tip).
getMaxPriorityFeePerGas(returnFormat?: DataFormat): Promise<Numbers>;Usage Example:
// Get suggested priority fee
const priorityFee = await eth.getMaxPriorityFeePerGas();
console.log(`Suggested priority fee: ${priorityFee} Wei`);
// Use in EIP-1559 transaction
const eip1559Transaction = {
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
value: "1000000000000000000",
maxPriorityFeePerGas: priorityFee,
maxFeePerGas: "30000000000", // Set max fee willing to pay
gas: "21000",
type: 2 // EIP-1559 transaction
};Returns comprehensive fee data including base fee and priority fee suggestions. This is an alias for calculateFeeData() with no parameters.
getFeeData(returnFormat?: DataFormat): Promise<FeeData>;Usage Example:
// Get complete fee data
const feeData = await eth.getFeeData();
console.log("Fee data:", {
gasPrice: feeData.gasPrice, // Legacy gas price
maxFeePerGas: feeData.maxFeePerGas, // EIP-1559 max fee
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas // EIP-1559 priority fee
});
// Use fee data in transaction
const receipt = await eth.sendTransaction({
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
value: "1000000000000000000",
maxFeePerGas: feeData.maxFeePerGas,
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
type: 2
});Calculates fee data with custom base fee and priority fee parameters.
calculateFeeData(baseFeePerGas?: Numbers, alternativeMaxPriorityFeePerGas?: Numbers): Promise<FeeData>;Usage Example:
// Calculate fees with custom base fee
const customBaseFee = "15000000000"; // 15 Gwei
const customFeeData = await eth.calculateFeeData(customBaseFee);
// Calculate fees with custom priority fee
const customPriorityFee = "2000000000"; // 2 Gwei
const feeDataWithTip = await eth.calculateFeeData(undefined, customPriorityFee);
// Use calculated fees
const transaction = {
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
to: "0x8ba1f109551bD432803012645Hac136c1c1b6c5E",
value: "1000000000000000000",
maxFeePerGas: feeDataWithTip.maxFeePerGas,
maxPriorityFeePerGas: feeDataWithTip.maxPriorityFeePerGas,
type: 2
};Retrieves historical fee data for analysis and fee estimation.
getFeeHistory(blockCount: Numbers, lastBlock: BlockNumberOrTag, rewardPercentiles?: Numbers[], returnFormat?: DataFormat): Promise<FeeHistoryOutput>;Parameters:
blockCount: Number of blocks to retrievelastBlock: Last block to include in historyrewardPercentiles: Array of percentiles (0-100) for priority fee analysisreturnFormat: Output format configurationUsage Example:
// Get fee history for last 100 blocks
const feeHistory = await eth.getFeeHistory(
100, // last 100 blocks
"latest", // up to latest block
[10, 25, 50, 75, 90] // percentiles for priority fees
);
console.log("Fee history:", {
oldestBlock: feeHistory.oldestBlock,
baseFeePerGas: feeHistory.baseFeePerGas,
reward: feeHistory.reward, // Priority fees at each percentile
gasUsedRatio: feeHistory.gasUsedRatio
});
// Analyze base fee trends
const baseFees = feeHistory.baseFeePerGas;
const avgBaseFee = baseFees.reduce((sum, fee, index) => {
if (index < baseFees.length - 1) { // Skip last element (next block's base fee)
return sum + Number(fee);
}
return sum;
}, 0) / (baseFees.length - 1);
console.log(`Average base fee: ${avgBaseFee} Wei`);
// Analyze priority fee trends (50th percentile)
const medianPriorityFees = feeHistory.reward.map(rewards => Number(rewards[2])); // 50th percentile
const avgPriorityFee = medianPriorityFees.reduce((sum, fee) => sum + fee, 0) / medianPriorityFees.length;
console.log(`Average priority fee (median): ${avgPriorityFee} Wei`);// Smart fee calculation based on network conditions
async function calculateOptimalFees(urgency: 'slow' | 'standard' | 'fast' = 'standard') {
const feeHistory = await eth.getFeeHistory(20, "latest", [10, 50, 90]);
const feeData = await eth.getFeeData();
// Get recent base fees and priority fees
const recentBaseFees = feeHistory.baseFeePerGas.slice(0, -1).map(Number);
const recentPriorityFees = feeHistory.reward.map(rewards => Number(rewards[1])); // 50th percentile
// Calculate average and trend
const avgBaseFee = recentBaseFees.reduce((a, b) => a + b) / recentBaseFees.length;
const isBaseFeeRising = recentBaseFees[recentBaseFees.length - 1] > recentBaseFees[0];
// Adjust priority fee based on urgency
const priorityMultipliers = { slow: 0.8, standard: 1.0, fast: 1.5 };
const suggestedPriorityFee = Number(feeData.maxPriorityFeePerGas) * priorityMultipliers[urgency];
// Calculate max fee with buffer for base fee volatility
const baseFeeBuffer = isBaseFeeRising ? 1.3 : 1.1;
const maxFeePerGas = Math.floor(avgBaseFee * baseFeeBuffer + suggestedPriorityFee);
return {
maxFeePerGas: maxFeePerGas.toString(),
maxPriorityFeePerGas: Math.floor(suggestedPriorityFee).toString(),
estimatedBaseFee: Math.floor(avgBaseFee).toString(),
baseFeeDirection: isBaseFeeRising ? 'rising' : 'stable/falling'
};
}
// Usage
const optimalFees = await calculateOptimalFees('fast');
console.log("Optimal fees for fast confirmation:", optimalFees);// Monitor fee changes in real-time
async function monitorFees() {
const subscription = await eth.subscribe("newHeads");
subscription.on("data", async (blockHeader) => {
try {
// Get fee data for new block
const feeData = await eth.getFeeData();
const block = await eth.getBlock(blockHeader.number);
console.log(`Block ${blockHeader.number}:`, {
baseFeePerGas: block.baseFeePerGas,
gasUsed: blockHeader.gasUsed,
gasLimit: blockHeader.gasLimit,
utilization: (Number(blockHeader.gasUsed) / Number(blockHeader.gasLimit) * 100).toFixed(2) + '%',
suggestedMaxFee: feeData.maxFeePerGas,
suggestedPriorityFee: feeData.maxPriorityFeePerGas
});
} catch (error) {
console.error("Error monitoring fees:", error);
}
});
return subscription;
}// Estimate total transaction costs
async function estimateTransactionCost(transaction: any, urgency: 'slow' | 'standard' | 'fast' = 'standard') {
// Get gas estimate
const gasEstimate = await eth.estimateGas(transaction);
// Get optimal fees
const fees = await calculateOptimalFees(urgency);
// Calculate costs
const maxCost = Number(gasEstimate) * Number(fees.maxFeePerGas);
const expectedCost = Number(gasEstimate) * (Number(fees.estimatedBaseFee) + Number(fees.maxPriorityFeePerGas));
return {
gasEstimate: gasEstimate.toString(),
maxFeePerGas: fees.maxFeePerGas,
maxPriorityFeePerGas: fees.maxPriorityFeePerGas,
maxCostWei: maxCost.toString(),
expectedCostWei: expectedCost.toString(),
maxCostEth: (maxCost / 1e18).toFixed(6),
expectedCostEth: (expectedCost / 1e18).toFixed(6)
};
}
// Usage
const costEstimate = await estimateTransactionCost({
from: "0x742d35Cc6634C0532925a3b8D7389Fc3C1b6c5E",
to: "0x1234567890123456789012345678901234567890",
data: "0xa9059cbb000000000000000000000000..." // token transfer
}, 'fast');
console.log("Transaction cost estimate:", costEstimate);Returns the current network hash rate (for compatible networks).
getHashRate(returnFormat?: DataFormat): Promise<Numbers>;Returns the current work for mining (for compatible networks).
getWork(): Promise<[HexString32Bytes, HexString32Bytes, HexString32Bytes]>;Submits mining work to the network (for compatible networks).
submitWork(nonce: HexString8Bytes, hash: HexString32Bytes, digest: HexString32Bytes): Promise<boolean>;interface FeeData {
gasPrice?: Numbers;
maxFeePerGas?: Numbers;
maxPriorityFeePerGas?: Numbers;
}
interface FeeHistoryOutput {
oldestBlock: Numbers;
baseFeePerGas: Numbers[];
reward: Numbers[][];
gasUsedRatio: Numbers[];
}
type Numbers = HexString | number | bigint;
type BlockNumberOrTag = Numbers | "latest" | "earliest" | "pending" | "safe" | "finalized";
interface DataFormat {
number: NumberFormat;
bytes: BytesFormat;
}
type NumberFormat = "NUMBER_HEX" | "NUMBER_NUMBER" | "NUMBER_BIGINT";
type BytesFormat = "BYTES_HEX" | "BYTES_UINT8ARRAY";Install with Tessl CLI
npx tessl i tessl/npm-web3-ethdocs
evals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10