# What are gas fees
Gas fees are transaction costs paid on blockchain networks like Ethereum to compensate validators or miners for processing and securing operations. They ensure network efficiency by prioritizing higher-paying transactions during congestion.
## How it works
1. **Computational Cost:** is the amount of computing resources required to execute a task or process in a computer system.
2. **Security:** security refers to the measures put in place to protect transactions and data from unauthorized access, fraud, tampering, or attacks while.
3. **Reward:** is the incentive given to those who process and maintain transactions in the system.
4. **Gas Limit:** The maximum amount of computational effort you're willing to spend.
5. **Gas Price:** The cost per unit of gas (often in gwei, a fraction of the native coin).
***The Formula:***
Total Gas Fee = Units of Gas Used x (Base fee + Priority fee)
**1. Units of Gas Used:** The total amount of computational "work" the transaction required (e.g., a simple transfer typically uses 21,000 units).
**2. Base Fee:** The minimum price per unit of gas required to be included in a block, set by the network and automatically "burned" (removed from circulation).
**3. Priority Fee (Tip):** An optional additional fee paid directly to validators to incentivize them to prioritize your transaction.
Example Calculation:If you send a standard transaction (21,000 units) with a base fee of 50 gwei and a tip of 10 gwei:
21,000 X (50+10) = 1,260,000 gwe.
Convert to ETH: 1,260,000/1,000,000,000 = 0.00126 ETH
```
const { ethers } = require("ethers");
async function getRealTimeGasEstimate(rpcUrl) {
const provider = new ethers.JsonRpcProvider(rpcUrl);
try {
const feeData = await provider.getFeeData();
const latestBlock = await provider.getBlock("latest");
const baseFee = latestBlock.baseFeePerGas;
const standardTransferGas = 21000n;
const priorityFee = feeData.maxPriorityFeePerGas;
const estimatedGasPrice = baseFee + priorityFee;
const totalFeeWei = standardTransferGas * estimatedGasPrice;
return {
baseFeeGwei: ethers.formatUnits(baseFee, "gwei"),
priorityFeeGwei: ethers.formatUnits(priorityFee, "gwei"),
totalEstimateEth: ethers.formatEther(totalFeeWei),
totalEstimateUsd: null
};
} catch (error) {
console.error("Error fetching gas data:", error);
}
}
```
`const { ethers } = require("ethers");`
Imports the ethers.js library
`async function getRealTimeGasEstimate(rpcUrl) {`
1. async → the function uses await inside
2. rpcUrl → URL of an Ethereum node Example:
`const provider = new ethers.JsonRpcProvider(rpcUrl);`
Creates a provider:
1. Reads blockchain data
2. Talks to Ethereum nodes via JSON-RPC
3. Does not need a wallet or private key
Think of it like:
“I just want to read blockchain data, not sign transactions.”
`try {`
Ensures your app doesn’t crash if:
1. RPC is down
2. Network errors occur
3. Invalid data is returned
`const feeData = await provider.getFeeData();`
What this returns
feeData contains:
```
{
gasPrice,
maxFeePerGas,
maxPriorityFeePerGas
}
```
Ethereum uses EIP-1559, meaning:
I. Gas is not a single number anymore
II. Fees are split into:
1. Base Fee → burned
2. Priority Fee (Tip) → paid to validators
`const latestBlock = await provider.getBlock("latest");`
1. Fetches the most recent block on Ethereum
2. This block contains real-time network info
`const baseFee = latestBlock.baseFeePerGas;`
I. baseFeePerGas:
1. Set by the network
2. Changes block-by-block
3. Is burned, not paid to validators
`const standardTransferGas = 21000n;`
I. A simple ETH transfer always costs 21,000 gas
II. The n means BigInt, required for large numbers in JS
```
const priorityFee =
feeData.maxPriorityFeePerGas || ethers.parseUnits("1.5", "gwei");
```
I. This is the validator incentive
II. Higher tip = faster inclusion
`const estimatedGasPrice = baseFee + priorityFee;`
Formula (EIP-1559)
`Total Gas Price = Base Fee + Priority Fee`
This is what you effectively pay per gas unit
`const totalFeeWei = standardTransferGas * estimatedGasPrice;`
Translation
Total Fee = Gas Units × Gas Price
Example:
21,000 × (30 gwei) = total cost
Stored in Wei.
```
return {
baseFeeGwei: ethers.formatUnits(baseFee, "gwei"),
priorityFeeGwei: ethers.formatUnits(priorityFee, "gwei"),
totalEstimateEth: ethers.formatEther(totalFeeWei),
totalEstimateUsd: null
};
```
I. formatUnits(value, "gwei")
II. formatEther(value) → converts Wei → ETH
`totalEstimateUsd: null`
Why?
I. ETH → USD requires:
1. Price feed (Chainlink, CoinGecko, etc.)
2. Not available on-chain directly
```
} catch (error) {
console.error("Error fetching gas data:", error);
}
```
I. Prevents silent failures
II. Helps debug RPC issues