What is gwei? Wei, gwei, ether and how Ethereum gas fees work

Covalent TeamUpdated 16 min read

Gwei is one billionth of an ether: 1 gwei = 10^-9 ETH = 10^9 wei. ETH units, EIP-1559 gas fees, live gas prices, cost estimates and a wallet's gas spend.

Gwei is a unit of ether (ETH): 1 gwei is 0.000000001 ETH (10-9 ETH), or 1,000,000,000 wei (109 wei). The name is short for giga-wei, a billion wei. Ethereum gas prices are quoted in gwei per unit of gas, so a transaction's fee is the gas it used times the price per gas: a plain ETH transfer uses 21,000 gas, and at 10 gwei per gas it costs 210,000 gwei, or 0.00021 ETH.

This guide covers the units of ETH, how gas fees are set since EIP-1559, a worked example, blob gas, code that converts between wei, gwei and ETH, and how to read current gas prices from an API, estimate what a transaction will cost, and add up how much gas an address has spent.

What gwei is

Ether has one base unit, the wei. Every amount on Ethereum (balances, the value of a transaction, gas prices) is an integer number of wei, and there are 1018 wei in one ether. Wei is named after Wei Dai, creator of b-money, per ethereum.org.

Wei is too small to read and ether too large for fees, so gas prices use the unit in between. "The base fee is 12 gwei" is easier to read than 12,000,000,000 wei or 0.000000012 ETH. Gwei is not a separate token: it is ether, counted in billionths.

Some libraries also call gwei a shannon or nanoether. The alias honours Claude Shannon; the word "gwei" itself just means giga-wei.

Wei, gwei and ether: the units of ETH

ethereum.org lists wei and gwei as the two denominations that matter besides ether:

Unit In wei In ether Used for
wei 1 0.000000000000000001 (10^-18) Every amount onchain, in contracts and RPC
gwei 1,000,000,000 (10^9) 0.000000001 (10^-9) Gas prices: base fee, priority fee, max fee
ether 1,000,000,000,000,000,000 (10^18) 1 Balances and transfers shown to people

So 1 ETH is 1,000,000,000 gwei, and 1 gwei is 1,000,000,000 wei. Libraries name the steps in between too: kwei (10^3 wei), mwei (10^6), szabo (10^12) and finney (10^15). You will rarely see them outside code.

How gas fees work on Ethereum

Gas measures the computation a transaction needs. Each EVM operation has a fixed gas cost, and every transaction starts with an intrinsic cost of 21,000 gas, which is all a plain ETH transfer uses. Token transfers, swaps and contract deployments use more. The ethereum.org gas page walks through how the cost adds up.

Since the London upgrade in August 2021, fees follow EIP-1559. A transaction sets three numbers, and the network sets a fourth:

Term Who sets it What it is
Gas limit You (your wallet) The most gas the transaction may use. If it runs out, the transaction fails and the whole limit is charged.
Base fee The network A price per gas every transaction in the block must pay. It is burned: destroyed, not paid to anyone.
Priority fee (tip) You maxPriorityFeePerGas: a price per gas on top of the base fee, paid to the validator.
Max fee You maxFeePerGas: the most you will pay per gas in total, base fee included.

The fee you pay is:

fee = gas used × (base fee + priority fee)

where the priority fee is your tip, capped so that base fee plus tip never exceeds your max fee. You pay for the gas the transaction actually used, not the gas limit. Your balance must still cover gas limit × max fee for the transaction to be valid.

The base fee moves with demand. Each block has a target of half the block gas limit; when a block uses more than the target, the next block's base fee rises, and when it uses less, it falls, by up to 12.5% per block (EIP-1559, ethereum.org). Because it is set by earlier blocks, the base fee for the next block is known in advance, and the tip is what you add to get included sooner when blocks are full.

Older "legacy" transactions with a single gasPrice still work: the base fee comes out of that price and the rest goes to the validator as the tip.

A worked example

These figures are illustrative, not current prices. You send an ERC-20 token transfer:

  • Gas limit 65,000, and the transfer uses 52,000 gas.
  • The block's base fee is 10 gwei. You offer a 1 gwei tip, with a max fee of 25 gwei.

Base fee plus tip is 11 gwei, under your 25 gwei max, so you pay 11 gwei per gas:

Item Gwei ETH
Balance needed: 65,000 × 25 gwei 1,625,000 0.001625
Fee paid: 52,000 × (10 + 1) gwei 572,000 0.000572
Of which burned: 52,000 × 10 gwei 520,000 0.00052
Of which tip to the validator: 52,000 × 1 gwei 52,000 0.000052

You need 0.001625 ETH available but pay 0.000572 ETH. At an illustrative ETH price of $3,000, the fee is 0.000572 × 3,000 = $1.716. Here is the same calculation in code, with integer wei throughout:

import { formatEther, formatGwei, parseGwei } from "viem"; // Illustrative figures, not current network prices.const gasLimit = 65_000n; // what the wallet allowsconst gasUsed = 52_000n; // what the transfer actually usedconst baseFee = parseGwei("10"); // set by the network, burnedconst maxPriorityFee = parseGwei("1"); // the tip you offerconst maxFee = parseGwei("25"); // the most you'll pay per gas const priorityFee = maxPriorityFee < maxFee - baseFee ? maxPriorityFee : maxFee - baseFee;const effectiveGasPrice = baseFee + priorityFee; console.log("balance needed:", formatEther(gasLimit * maxFee), "ETH"); // 0.001625console.log("fee paid:", formatEther(gasUsed * effectiveGasPrice), "ETH"); // 0.000572console.log("  burned:", formatEther(gasUsed * baseFee), "ETH"); // 0.00052console.log("  tip:   ", formatEther(gasUsed * priorityFee), "ETH"); // 0.000052console.log("price per gas:", formatGwei(effectiveGasPrice), "gwei"); // 11

Blob gas (EIP-4844)

Since the Dencun upgrade in March 2024, Ethereum has a second fee market. EIP-4844 added blob transactions, which carry large chunks of data ("blobs", 128 KB each) that layer 2 rollups use to post their transaction data to Ethereum cheaply.

  • Each blob costs 131,072 (217) units of blob gas, priced separately from ordinary gas.
  • The blob base fee has its own target and adjusts on its own, like the EIP-1559 base fee. A blob transaction sets maxFeePerBlobGas on top of the usual fee fields.
  • The blob fee is burned, and it is not refunded if the transaction fails.
  • Blobs are kept by consensus nodes for about 18 days, not forever, which is why they are cheaper than calldata.

The number of blobs a block can hold has gone up since, starting with EIP-7691 in the Pectra upgrade. Ordinary users rarely send blob transactions themselves; they pay for blob gas indirectly, through layer 2 fees.

How to convert wei, gwei and ETH

To convert by hand, move the decimal point: wei to gwei, divide by 109; gwei to ETH, divide by 109 again; wei to ETH, divide by 1018. So 21,000 gas at 100 gwei is 2,100,000 gwei, which is 0.0021 ETH.

In code, keep amounts as integer wei (BigInt in JavaScript) and convert only to show them. A JavaScript Number loses precision above 253, about 0.009 ETH in wei. viem has the conversions built in:

import { formatEther, formatGwei, parseEther, parseGwei } from "viem"; // Amounts on Ethereum are integers in wei. Keep them as BigInt and convert only for display.const wei = parseGwei("1"); // 1 gweiconsole.log(wei); // 1000000000nconsole.log(formatEther(wei)); // "0.000000001"console.log(parseEther("1")); // 1000000000000000000nconsole.log(formatGwei(parseEther("0.0021"))); // "2100000"console.log(formatGwei(12_345_678_901n)); // "12.345678901"

In ethers v6 the same calls are formatUnits(wei, "gwei"), parseUnits("1", "gwei"), formatEther and parseEther. With no library at all:

// The same conversions with no library: a unit is 10^9 (gwei) or 10^18 (ether) wei.function formatWei(wei, decimals) {    const base = 10n ** BigInt(decimals);    const sign = wei < 0n ? "-" : "";    const abs = wei < 0n ? -wei : wei;    const fraction = (abs % base).toString().padStart(decimals, "0").replace(/0+$/, "");    return `${sign}${abs / base}${fraction ? `.${fraction}` : ""}`;} function parseUnit(amount, decimals) {    const [whole, fraction = ""] = amount.split(".");    if (fraction.length > decimals) throw new Error(`${amount} has more than ${decimals} decimals`);    return BigInt(whole + fraction.padEnd(decimals, "0"));} const GWEI = 9;const ETHER = 18;console.log(formatWei(12_345_678_901n, GWEI)); // "12.345678901"console.log(formatWei(2_100_000_000_000_000n, ETHER)); // "0.0021"console.log(parseUnit("1.5", GWEI)); // 1500000000nconsole.log(parseUnit("0.05", ETHER)); // 50000000000000000n

Gas prices below 1 gwei are common, especially on layer 2s, so keep the decimals when you display them.

Get current gas prices from an API

Your node gives you the inputs through JSON-RPC: eth_gasPrice, eth_maxPriorityFeePerGas and eth_feeHistory, all in wei. They tell you the price per gas, not what a kind of transaction costs. A gas price API does that part for you: the Gas Price endpoint in the GoldRush Foundational API, GET /v1/{chainName}/event/{eventType}/gas_prices/, returns the price recently paid on one chain for one kind of transaction, and what that transaction costs in your currency.

eventType is one of three:

Event type Transactions it averages
nativetokens Plain transfers of the gas token, such as ETH
erc20 ERC-20 token transfers
uniswapv3 Uniswap V3 swaps

Add quote-currency to price the result in USD, EUR, GBP, JPY or one of the other currencies the reference lists. The response has:

  • base_fee: the latest block's base fee, in wei.
  • gas_quote_rate: the price of the chain's gas token in your quote currency.
  • updated_at: when the figures were computed.
  • items: one entry per recent interval. In a recorded response the three items cover the last 1, 3 and 5 minutes, named in interval. Each has:
    • gas_price: the average price per gas paid in that interval, in wei.
    • gas_spent: the average gas a transaction of that event type used. This is what makes it a cost estimate: a plain ETH transfer between wallets uses 21,000 gas, while token transfers and swaps vary with the contract.
    • gas_quote: the average execution fee in your quote currency.
    • other_fees: on rollups, the L1 data fee in your quote currency; empty on Ethereum itself.
    • total_gas_quote: the execution fee plus the L1 fee, with a formatted pretty_total_gas_quote such as "$22.66".

This fetches them for ETH transfers on Ethereum, converts wei to gwei and ETH, and prices a 21,000-gas transfer at each interval's price:

import { formatEther, formatGwei } from "viem"; const API = "https://api.covalenthq.com/v1";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; // Recent gas prices on one chain for one kind of transaction:// "nativetokens" (plain transfers), "erc20" (token transfers) or "uniswapv3" (swaps).async function getGasPrices(chain, eventType, currency = "USD") {    const url = `${API}/${chain}/event/${eventType}/gas_prices/?quote-currency=${currency}`;    const res = await fetch(url, { headers });    if (!res.ok) throw new Error(`${res.status} ${await res.text()}`);    const { data } = await res.json();    return data;} const data = await getGasPrices("eth-mainnet", "nativetokens");const GAS = 21_000n; // a plain ETH transfer uses exactly 21,000 gas console.log(`base fee: ${formatGwei(BigInt(data.base_fee))} gwei, ETH at $${data.gas_quote_rate}`);console.table(    data.items.map((item) => {        const gasPrice = BigInt(item.gas_price); // wei per unit of gas        const feeEth = formatEther(gasPrice * GAS);        return {            interval: item.interval,            gwei: formatGwei(gasPrice),            "transfer fee (ETH)": feeEth,            "transfer fee (USD)": (Number(feeEth) * data.gas_quote_rate).toFixed(4),            "average paid": item.pretty_total_gas_quote,        };    }));

You need a GoldRush API key: sign up for the free trial. It is billed in credits, at 1 per call. The figures are averages of what recent transactions paid; the floor for the next block is the base fee, which base_fee and your node both give you.

Estimate a transaction's cost

A fee estimate is the gas the transaction will use times the price per gas, converted from wei to ETH and then to your currency. Here is a recorded Gas Price API response for uniswapv3 swaps on Ethereum, taken on 23 February 2024 with quote-currency=USD (only the "Last 1 minute" item is shown):

{    "event_type": "uniswapv3",    "gas_quote_rate": 2945.376708984375,    "quote_currency": "USD",    "base_fee": "36643968777",    "items": [        {            "gas_price": "39101851588",            "gas_spent": "196739",            "gas_quote": 22.65836825300664,            "other_fees": { "l1_gas_quote": null },            "total_gas_quote": 22.65836825300664,            "pretty_total_gas_quote": "$22.66",            "interval": "Last 1 minute"        }    ]}
  1. Gas: an average swap used gas_spent = 196,739 gas. For your own transaction, use its gas estimate (eth_estimateGas) or, for a plain transfer, 21,000.
  2. Fee in wei: 196,739 × 39,101,851,588 wei (gas_price, about 39.1 gwei) = 7,692,859,179,571,532 wei.
  3. Fee in ETH: divide by 1018: 0.007692859 ETH.
  4. Fee in dollars: multiply by gas_quote_rate, the ETH price: 0.007692859 × 2,945.38 = $22.66, which is the response's own gas_quote.

The same steps in code, with integer wei until the last step:

import { formatEther, formatGwei } from "viem"; // One item and the gas_quote_rate from a recorded uniswapv3 response (eth-mainnet, 2024-02-23).const gasQuoteRate = 2945.376708984375;const item = { gas_price: "39101851588", gas_spent: "196739", gas_quote: 22.65836825300664, interval: "Last 1 minute" }; function estimateCost(gas, gasPriceWei, rate) {    const feeWei = gas * gasPriceWei; // step 2: gas x price per gas    const feeEth = formatEther(feeWei); // step 3: wei -> ETH    return { feeWei, feeEth, feeQuote: Number(feeEth) * rate }; // step 4: ETH -> your currency} const gasPrice = BigInt(item.gas_price);const swap = estimateCost(BigInt(item.gas_spent), gasPrice, gasQuoteRate);console.log(`${formatGwei(gasPrice)} gwei per gas`); // 39.101851588 gwei per gasconsole.log(swap.feeWei, `${swap.feeEth} ETH`, `$${swap.feeQuote.toFixed(2)}`); // 7692859179571532n 0.007692859179571532 ETH $22.66console.log(`API's gas_quote: $${item.gas_quote.toFixed(2)}`); // API's gas_quote: $22.66 const transfer = estimateCost(21_000n, gasPrice, gasQuoteRate); // a plain ETH transfer at the same priceconsole.log(`${transfer.feeEth} ETH`, `$${transfer.feeQuote.toFixed(2)}`); // 0.000821138883348 ETH $2.42

Two things to add before you show an estimate to a user. First, the price a transaction pays is the base fee at inclusion plus its tip, so a wallet sets the max fee with headroom over this average (see how gas fees work). Second, on rollups such as OP Stack chains the execution fee is only part of the cost: the transaction also pays an L1 data fee, which the API returns in other_fees and includes in total_gas_quote. On those chains, quote total_gas_quote, not gas_spent × gas_price alone.

How much gas has an address spent?

Only the sender of a transaction pays its fee. To add up what a wallet has spent on gas, count the transactions it sent (from_address is the wallet), not the ones it received. There are two ways to get the total with GoldRush.

One call per chain. The Wallet Transaction Summary endpoint (credits: 1 per call), with with-gas=true, returns a gas_summary for the address: total_sent_count (transactions it sent), total_fees_paid in wei, total_gas_quote in your quote currency, and average_gas_quote_per_tx. with-gas adds credits and can slow the response for very busy wallets; the reference page gives the figures.

import { formatEther } from "viem"; const API = "https://api.covalenthq.com/v1";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; async function gasSpent(chain: string, address: string) {    const url = `${API}/${chain}/address/${address}/transactions_summary/?with-gas=true&quote-currency=USD`;    const res = await fetch(url, { headers });    const body = await res.json();    if (!res.ok || body.error) throw new Error(`${res.status} ${body.error_message ?? ""}`);    const { gas_summary } = body.data.items[0];    return {        sent: gas_summary.total_sent_count as number,        eth: formatEther(BigInt(gas_summary.total_fees_paid)), // total_fees_paid is wei        usd: gas_summary.pretty_total_gas_quote as string,    };} console.log(await gasSpent("eth-mainnet", "0xdc2f48410033d18c5cce2c11135fd0d40fc19aaa"));

From the transactions, by month. To see when the gas went, read the address's history with the Transactions v3 endpoints (credits: 0.1 per item) and add up each sent transaction's fee. Every transaction carries fees_paid in wei and gas_quote, the same fee in your quote currency at the gas token's price on the day of the transaction, so the dollar total is what the gas cost at the time, not at today's price. Start from the newest page and follow links.prev back to the first:

import { formatEther } from "viem"; const API = "https://api.covalenthq.com/v1";const headers = { Authorization: `Bearer ${process.env.GOLDRUSH_API_KEY}` }; type Tx = { block_signed_at: string; from_address: string; fees_paid: string | null; gas_quote: number | null }; // links.prev is a full URL; set the options on every page, not just the first.async function getPage(pageUrl: string) {    const url = new URL(pageUrl);    url.searchParams.set("no-logs", "true"); // smaller response, lower cost per item    url.searchParams.set("quote-currency", "USD");    const res = await fetch(url, { headers });    const body = await res.json();    if (!res.ok || body.error) throw new Error(`${res.status} ${body.error_message ?? ""}`);    return body.data as { items: Tx[]; links?: { prev?: string | null } };} async function gasByMonth(chain: string, address: string) {    const months = new Map<string, { sent: number; wei: bigint; usd: number }>();    let page = await getPage(`${API}/${chain}/address/${address}/transactions_v3/`); // the newest page    while (true) {        for (const tx of page.items) {            if (tx.from_address.toLowerCase() !== address.toLowerCase()) continue; // the sender pays the fee            const month = tx.block_signed_at.slice(0, 7); // "YYYY-MM"            const m = months.get(month) ?? { sent: 0, wei: 0n, usd: 0 };            m.sent += 1;            m.wei += BigInt(tx.fees_paid ?? "0");            m.usd += tx.gas_quote ?? 0;            months.set(month, m);        }        if (!page.links?.prev) break;        page = await getPage(page.links.prev);    }    return [...months].sort(([a], [b]) => a.localeCompare(b));} let totalWei = 0n;let totalUsd = 0;for (const [month, m] of await gasByMonth("eth-mainnet", "0xdc2f48410033d18c5cce2c11135fd0d40fc19aaa")) {    console.log(month, m.sent, "sent", formatEther(m.wei), "ETH", `$${m.usd.toFixed(2)}`);    totalWei += m.wei;    totalUsd += m.usd;}console.log("total", formatEther(totalWei), "ETH", `$${totalUsd.toFixed(2)}`);

Each transaction is billed, so a long history costs more than the summary call; no-logs=true keeps each item cheaper. Paging, time windows and caching are covered in how to get transaction history for an address on Ethereum. For one transaction you already know, Get a transaction (credits: 0.1 per call) returns what it paid: gas_offered (the gas limit), gas_spent, gas_price and fees_paid in wei, and gas_quote in your currency.

If the total is higher than you'd like, the biggest saving is to move activity to a layer 2 rollup, where the same transfer or swap usually costs a fraction of what it does on Ethereum.

Frequently asked questions

How much is 1 gwei in ETH?

1 gwei is 0.000000001 ETH (10^-9 ETH), and 1,000,000,000 wei. To turn a gwei amount into ETH, divide it by 1,000,000,000: 2,100,000 gwei is 0.0021 ETH.

How many gwei are in 1 ETH?

One billion: 1 ETH is 1,000,000,000 gwei, which is 10^18 wei. To turn ETH into gwei, multiply by 1,000,000,000.

Is gwei a cryptocurrency?

No. Gwei is a unit of ether, the way a cent is a unit of the dollar. You can't buy or hold gwei as a separate token; any ETH balance can be counted in gwei or wei.

Why are gas prices quoted in gwei?

Because prices per unit of gas are tiny fractions of an ether. Quoting 12 gwei is easier to read and compare than 0.000000012 ETH or 12,000,000,000 wei. Onchain, the price is still stored as an integer number of wei.

What is a good gas price in gwei?

There is no fixed good number. Under EIP-1559 you must pay at least the current base fee, which changes every block with demand, plus a tip; wallets read the base fee and suggest a tip for you. A max fee well above the current base fee costs nothing extra, since you only pay the base fee plus your tip, and it keeps the transaction valid if the base fee rises before it is included.

Who gets the gas fee?

The base fee is burned, which removes that ETH from supply. Only the priority fee (tip) goes to the validator that includes the transaction. Blob fees from EIP-4844 transactions are burned too.

How do I get current gas prices from an API?

Call a gas price API such as GoldRush's Gas Price endpoint, /v1/{chain}/event/{eventType}/gas_prices/, with nativetokens, erc20 or uniswapv3 as the event type. It returns the latest base fee and, for recent intervals, the average gas price in wei, the average gas used and the cost in your quote currency. From a node, eth_gasPrice and eth_feeHistory give the price per gas only.

How do I see how much I've spent on gas?

Add up the fees of the transactions your address sent: received transactions cost you nothing. GoldRush's Wallet Transaction Summary endpoint with with-gas=true returns the total in one call per chain, in wei and in your currency; or sum fees_paid and gas_quote across your transaction history to see it by month. Block explorers show the fee of each transaction one by one.

Next steps

Get new guides by email

New tutorials and best practices for building with blockchain data, sent as they're published.