Scholarpeak

Gas Methods

Understand and estimate transaction costs on Ethereum.

What is Gas?

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

eth_gasPrice

Get the current network gas price

Returns the current average gas price in Wei. Gas price fluctuates based on network demand.

typescript
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;
}

eth_estimateGas

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.

typescript
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);
  }
}

Common Gas Costs

Send ETH21,000 gas
Send Token65,000 gas
Swap on DEX100,000 - 500,000 gas
Mint NFT200,000 - 1,000,000 gas

Key Takeaways

  • ✓ Gas price is measured in Wei, often displayed in GWei
  • ✓ Always estimate gas before sending transactions
  • ✓ Gas price fluctuates with network demand
  • ✓ Sending ETH is the cheapest operation (~21,000 gas)
  • ✓ Smart contract calls can use much more gas