Understand and estimate transaction costs on Ethereum.
Gas is the unit of computational effort required to execute transactions and smart contracts on Ethereum. Every operation costs a certain amount of gas, and users pay for this gas in ETH.
Gas Price = Gas Units × Gas Price Per Unit
For example: Sending ETH uses ~21,000 gas. If gas price is 50 GWei, the cost is 21,000 × 50 GWei = 0.00105 ETH
Get the current network gas price
Returns the current average gas price in Wei. Gas price fluctuates based on network demand.
async function getCurrentGasPrice() {
const gasPriceWei = await window.ethereum.request({
method: 'eth_gasPrice'
});
// Convert Wei to GWei (1 GWei = 1e9 Wei)
const gasPriceGWei = Number(BigInt(gasPriceWei)) / 1e9;
console.log('Gas price:', gasPriceGWei, 'GWei');
return gasPriceGWei;
}Estimate how much gas a transaction will use
Simulates a transaction execution and returns the estimated gas units needed. This prevents out-of-gas errors.
async function calculateTransactionCost(toAddress, amountETH) {
try {
const accounts = await window.ethereum.request({
method: 'eth_requestAccounts'
});
const amountWei = '0x' + BigInt(Math.round(amountETH * 1e18)).toString(16);
// Get gas price
const gasPriceWei = await window.ethereum.request({
method: 'eth_gasPrice'
});
const gasPriceGWei = Number(BigInt(gasPriceWei)) / 1e9;
// Estimate gas
const estimatedGas = await window.ethereum.request({
method: 'eth_estimateGas',
params: [{
from: accounts[0],
to: toAddress,
value: amountWei
}]
});
const gasUnits = Number(BigInt(estimatedGas));
// Calculate total cost
const totalCostWei = BigInt(gasPriceWei) * BigInt(gasUnits);
const totalCostETH = Number(totalCostWei) / 1e18;
console.log(`Gas units: ${gasUnits}`);
console.log(`Gas price: ${gasPriceGWei} GWei`);
console.log(`Transaction cost: ${totalCostETH} ETH`);
console.log(`Total cost (including amount): ${Number(amountWei) / 1e18 + totalCostETH} ETH`);
return { gasUnits, gasPriceGWei, totalCostETH };
} catch (error) {
console.error('Error:', error);
}
}