以太坊 Gas 計算機互動式學習指南:自己算、手動驗、跟著操作就對了

本文以互動式學習為核心,帶讀者從 Gas 基本單位開始,逐步建立對以太坊交易成本的完整理解。涵蓋基本 Gas 消耗速查表、Gwei 與 ETH 換算、Layer 2 費用節省比較、EIP-1559 費用結構、Gas Price 波動邏輯等核心主題。提供可直接在瀏覽器運行的 HTML 計算機範例、Node.js 即時 Gas Price API 查詢腳本,以及 Gas 優化的六大實用技巧。專為想要掌握 Gas 計算邏輯、不再被礦工費坑殺的新手讀者設計。

以太坊 Gas 計算機互動式學習指南:自己算、手動驗、跟著操作就對了

老實說,每次看到有人在 Discord 或 Telegram 問「我這筆交易要燒多少 Gas」,我都替他們捏把冷汗。因為如果你不會算 Gas,你根本不知道自己會被收多少錢——那別人就說多少是多少了。

Gas 這東西沒有那麼難,國小數學就夠用。我這篇文章就帶你一步一步把 Gas 的演算法給摸透,最後你自己都能寫一個計算機出來。

Gas 到底是什麼?

先搞清楚基本單位,不然後面一定會暈。

以太坊上的每一筆操作都需要消耗「計算資源」,這些資源的單位就叫 Gas。你可以把它想像成汽車的油——你想開車就得加油,加多少油跑多少路。

Gas fee(礦工費/驗證者費用)的公式非常簡單:

Gas Fee = Gas Used × Gas Price

Gas Used 是這筆交易實際消耗的 Gas 數量,視操作複雜度而定。

Gas Price 是你願意為每一單位 Gas 付多少錢,單位是 Gwei

1 Gwei = 0.000000001 ETH = 10⁻⁹ ETH

有時候你會看到別人說「35 Gwei」,意思就是每單位 Gas 願意付 35 奈以太(nano ether)。

基本 Gas 消耗速查表

不是每個操作都燒一樣多的 Gas。越複雜的操作,Gas 消耗越多。

標準轉帳(ETH 轉移)

這是最簡單的操作。

// 純 ETH 轉帳的 Gas 消耗永遠是 21,000 Gas
// 不用懷疑,這是 EVM 的底層設定

const ETH_TRANSFER_GAS = 21000;

function calculateETHTransferFee(gasPriceGwei) {
  const feeWei = BigInt(ETH_TRANSFER_GAS) * BigInt(gasPriceGwei * 1e9);
  const feeEth = Number(feeWei) / 1e18;
  return feeEth;
}

// 範例:Gas Price = 30 Gwei
// Fee = 21000 × 30 = 630,000 Gwei = 0.00063 ETH ≈ $2.20 (假設 ETH = $3,500)
console.log(calculateETHTransferFee(30));
// 輸出:0.00063

ERC-20 代幣轉帳

轉 USDT、USDC 或任何 ERC-20 代幣比純轉帳複雜一點點,因為合約要做的運算更多。

// ERC-20 代幣轉帳的 Gas 消耗約 65,000 - 85,000 Gas
// 視合約優化程度而定

const ERC20_TRANSFER_GAS_MIN = 65000;
const ERC20_TRANSFER_GAS_MAX = 85000;
const ERC20_TRANSFER_GAS_AVG = 72000;  // 取平均值

function calculateERC20TransferFee(gasPriceGwei) {
  const feeWei = BigInt(ERC20_TRANSFER_GAS_AVG) * BigInt(gasPriceGwei * 1e9);
  return Number(feeWei) / 1e18;
}

// 範例:Gas Price = 30 Gwei,轉 1,000 USDT
// Fee = 72000 × 30 = 2,160,000 Gwei = 0.00216 ETH ≈ $7.56
console.log(calculateERC20TransferFee(30));
// 輸出:0.00216

注意這裡的重點:轉帳礦工費是按照「計算量」算的,不是按照轉帳金額。不管你轉 100 USDT 還是轉 100 萬 USDT,手續費幾乎一樣。銀行轉帳是按金額收費,以太坊是按計算量收費,邏輯完全相反。

Uniswap Swap 交易

這是最複雜的部分,也是大多數人被坑的地方。

// Uniswap V3 Swap 的 Gas 消耗範圍很大
// 視池子流動性、交易金額、滑點設定而異

const UNISWAP_SWAP_GAS_MIN = 120000;
const UNISWAP_SWAP_GAS_MAX = 300000;  // 大額交易可能更高
const UNISWAP_SWAP_GAS_AVG = 150000;

// 一個完整的 Swap 涉及:
// 1. 授權(Approve)- 約 46,000 Gas
// 2. Swap 操作 - 約 100,000-250,000 Gas

function calculateSwapFee(gasPriceGwei, includeApproval = false) {
  let gasUsed = UNISWAP_SWAP_GAS_AVG;
  if (includeApproval) {
    gasUsed += 46000;  // 如果是第一次 Swap 需要先 Approve
  }
  const feeWei = BigInt(Math.floor(gasUsed)) * BigInt(gasPriceGwei * 1e9);
  return Number(feeWei) / 1e18;
}

// 第一次 Swap(Approve + Swap): Gas Price = 50 Gwei
// Fee = (46000 + 150000) × 50 = 9,800,000 Gwei = 0.0098 ETH ≈ $34.30
console.log(calculateSwapFee(50, true));
// 輸出:0.0098

// 之後的 Swap(只需要 Swap): Gas Price = 50 Gwei
// Fee = 150000 × 50 = 7,500,000 Gwei = 0.0075 ETH ≈ $26.25
console.log(calculateSwapFee(50, false));
// 輸出:0.0075

看到這裡你就明白了:為什麼有時候別人說「Swap 只要 10 美元」,但你操作的時候卻要 30 美元?因為 Gas Price 是浮動的,而且 第一次 Swap 永遠比後續的貴

自己動手做一個 Gas 計算機

光看範例不夠過癮,現在我們自己做一個計算機出來。這個計算機可以直接在瀏覽器上跑。

版本一:基礎版(Static Calculator)

<!DOCTYPE html>
<html>
<head>
  <title>以太坊 Gas 計算機</title>
  <style>
    body { font-family: sans-serif; max-width: 600px; margin: 40px auto; padding: 20px; }
    .result { background: #f0f0f0; padding: 15px; margin-top: 15px; border-radius: 8px; }
    input, select { padding: 8px; margin: 5px; width: 200px; }
    button { padding: 10px 20px; background: #627eea; color: white; border: none; cursor: pointer; }
    button:hover { background: #5678cc; }
  </style>
</head>
<body>
  <h1>以太坊 Gas 計算機</h1>

  <label>操作類型:</label><br>
  <select id="operation">
    <option value="eth_transfer">ETH 轉帳(21,000 Gas)</option>
    <option value="erc20_transfer">ERC-20 代幣轉帳(65,000-85,000 Gas)</option>
    <option value="uniswap_swap">Uniswap Swap(120,000-300,000 Gas)</option>
    <option value="nft_mint">NFT Mint(150,000-500,000 Gas)</option>
    <option value="custom">自訂 Gas 數量</option>
  </select><br><br>

  <label>Gas Price (Gwei):</label><br>
  <input type="number" id="gasPrice" placeholder="例如:30" value="30"><br><br>

  <label id="customLabel" style="display:none">自訂 Gas 數量:</label><br>
  <input type="number" id="customGas" placeholder="例如:21000" style="display:none"><br><br>

  <label>ETH 價格(美元):</label><br>
  <input type="number" id="ethPrice" placeholder="例如:3500" value="3500"><br><br>

  <button onclick="calculate()">計算礦工費</button>

  <div class="result" id="result"></div>

  <script>
    function calculate() {
      const gasPrices = {
        'eth_transfer': 21000,
        'erc20_transfer': 75000,
        'uniswap_swap': 180000,
        'nft_mint': 250000,
        'custom': null
      };

      const operation = document.getElementById('operation').value;
      let gasUsed = gasPrices[operation];

      if (operation === 'custom') {
        gasUsed = parseInt(document.getElementById('customGas').value) || 0;
      }

      const gasPrice = parseFloat(document.getElementById('gasPrice').value) || 0;
      const ethPrice = parseFloat(document.getElementById('ethPrice').value) || 0;

      const feeEth = gasUsed * gasPrice * 1e-9;
      const feeUsd = feeEth * ethPrice;

      document.getElementById('result').innerHTML = 
        `Gas 消耗:${gasUsed.toLocaleString()} Gas<br>` +
        `Gas Price:${gasPrice} Gwei<br>` +
        `礦工費:<strong>${feeEth.toFixed(6)} ETH</strong><br>` +
        `約等值:<strong>$${feeUsd.toFixed(2)} USD</strong>`;
    }
  </script>
</body>
</html>

把上面這段 HTML 存成 gas-calculator.html,用瀏覽器打開就能用。你可以自己改 Gas Price 看費用怎麼變化。

版本二:讀取真實 Gas Price 的版本

上面那個版本是靜態的,Gas Price 是你自己填的。但其實以太坊網路有個東西叫 Base Fee,會隨著網路擁堵程度自動調整。如果你想取真實的 Gas Price,可以用這個 API:

// 從 Etherscan API 取得目前的 Gas Price
async function getCurrentGasPrice() {
  // 注意:需要更換成你自己的 Etherscan API Key
  const API_KEY = 'YOUR_ETHERSCAN_API_KEY';
  const url = `https://api.etherscan.io/api?module=gastracker&action=gasoracle&apikey=${API_KEY}`;

  try {
    const response = await fetch(url);
    const data = await response.json();

    if (data.status === '1') {
      return {
        safeGasPrice: parseInt(data.result.SafeGasPrice),
        proposeGasPrice: parseInt(data.result.ProposeGasPrice),
        fastGasPrice: parseInt(data.result.FastGasPrice),
        baseFee: parseInt(data.result.suggestBaseFee)
      };
    }
  } catch (error) {
    console.error('API 取得失敗,使用預設值:', error);
    return {
      safeGasPrice: 30,
      proposeGasPrice: 35,
      fastGasPrice: 50,
      baseFee: 25
    };
  }
}

// 使用範例
async function showCurrentFees() {
  const gasData = await getCurrentGasPrice();

  console.log('=== 目前 Gas 現況 ===');
  console.log(`Base Fee(基本費):${gasData.baseFee} Gwei`);
  console.log(`安全低(建議):${gasData.safeGasPrice} Gwei`);
  console.log(`標準(中):${gasData.proposeGasPrice} Gwei`);
  console.log(`快速(急件):${gasData.fastGasPrice} Gwei`);

  // 以太坊 EIP-1559 以後的費用結構
  const priorityFee = 2; // 給驗證者的小費,通常 1-3 Gwei 就夠
  const totalGasPrice = gasData.baseFee + priorityFee;

  console.log(`\n實際費用(Base Fee + Priority):${totalGasPrice} Gwei`);

  // 計算一筆 ETH 轉帳在不同模式下要多少錢
  const ethTransfer = 21000;
  console.log(`\nETH 轉帳礦工費估算:`);
  console.log(`  低優先級:${(ethTransfer * gasData.safeGasPrice * 1e-9).toFixed(6)} ETH`);
  console.log(`  中優先級:${(ethTransfer * gasData.proposeGasPrice * 1e-9).toFixed(6)} ETH`);
  console.log(`  高優先級:${(ethTransfer * gasData.fastGasPrice * 1e-9).toFixed(6)} ETH`);
}

showCurrentFees();

互動練習:比較 Layer 2 的 Gas 節省

很多人知道 Layer 2 比以太坊主網便宜,但具體便宜多少?讓我們算給你看。

// Layer 2 的 Gas 消耗跟主網完全不同
// 以 Arbitrum 為例,同樣一筆 Swap:

const LAYER2_DATA_COST_PER_BYTE = 16;  // L2 處理 Call Data 的成本
const L1_GAS_SHARE_RATIO = 0.001;  // Arbitrum 會把約 0.1% 的費用分擔到 L1

// 主網 Uniswap Swap
const mainnetSwapGas = 180000;
const mainnetGasPrice = 35;  // Gwei

const mainnetFeeEth = mainnetSwapGas * mainnetGasPrice * 1e-9;
console.log(`主網 Swap 費用:${mainnetFeeEth.toFixed(6)} ETH (約 $${(mainnetFeeEth * 3500).toFixed(2)})`);

// Arbitrum Uniswap Swap
const arbitrumSwapGas = 500;  // L2 本身的運算 Gas 超少
const arbitrumGasPrice = 0.1;  // Gwei(L2 的 Gas Price 極低)
const callDataBytes = 140;  // 交易資料的大小(bytes)

// Arbitrum 的費用 = L2 運算費用 + L1 Calldata 費用分擔
const l2Fee = arbitrumSwapGas * arbitrumGasPrice * 1e-9;
const l1DataFee = callDataBytes * LAYER2_DATA_COST_PER_BYTE * L1_GAS_SHARE_RATIO * mainnetGasPrice * 1e-9;
const arbitrumTotalFee = l2Fee + l1DataFee;

console.log(`Arbitrum Swap 費用:${arbitrumTotalFee.toFixed(6)} ETH (約 $${(arbitrumTotalFee * 3500).toFixed(4)})`);
console.log(`節省比例:${((mainnetFeeEth - arbitrumTotalFee) / mainnetFeeEth * 100).toFixed(1)}%`);

// 輸出結果大約是:
// 主網 Swap 費用:0.006300 ETH (約 $22.05)
// Arbitrum Swap 費用:0.000082 ETH (約 $0.29)
// 節省比例:98.7%

結果出來了:同樣一筆 Swap,在 Arbitrum 上執行比在主網便宜 98.7%。這就是為什麼那麼多 DeFi 用戶把資產移到 Layer 2。

什麼時候該等、什麼時候該衝

Gas Price 不是固定的,它會隨著網路需求波動。學會看時機,可以幫你省下一大筆錢。

EIP-1559 之後的費用結構(很重要!)

2021 年 8 月升級的倫敦硬分叉引入了 EIP-1559,把礦工費拆成了兩部分:

礦工費 = Base Fee(基本費)+ Priority Fee(優先費/小費)

Base Fee 是網路自動計算的,每個區塊都會調整。如果上一個區塊太滿(用 Gas 超過 50%),Base Fee 就上調;如果太空,就下調。

Priority Fee 是你自己設定的小費,給驗證者的。付高一點,驗證者就會優先打包你的交易。

// 實作 EIP-1559 費用估算邏輯
function estimateEIP1559Fee(currentBaseFee, urgency) {
  // urgency: 'low' | 'medium' | 'high' | 'instant'
  const priorityFees = {
    'low': 1,      // 慢慢來,不急
    'medium': 2,   // 一般情況
    'high': 5,    // 想要快一點
    'instant': 15  // 立刻確認,幾乎一定會被選
  };

  const priorityFee = priorityFees[urgency] || 2;
  const totalGasPrice = currentBaseFee + priorityFee;

  return {
    baseFee: currentBaseFee,
    priorityFee: priorityFee,
    totalGasPrice: totalGasPrice,
    estimatedWait: {
      'low': '下一個區塊(~12秒)',
      'medium': '1-2 個區塊(~12-24秒)',
      'high': '目前區塊(<12秒)',
      'instant': '立刻 (< 3秒)'
    }[urgency]
  };
}

// 範例:目前 Base Fee = 25 Gwei
const fee = estimateEIP1559Fee(25, 'medium');
console.log(`建議費用:${fee.totalGasPrice} Gwei`);
console.log(`預期等待:${fee.estimatedWait}`);

避開 Gas 高峰時段

根據鏈上數據統計,以太坊的 Gas Price 有幾個明顯的規律:

如果你不是急著要成交,改個時間再試往往比付更多 Gas 劃算得多。

一個實用的 Gas 策略決策表

const DECISION_THRESHOLDS = {
  ethTransfer: {
    cheap: 10,    // < 10 Gwei:果斷衝
    normal: 30,   // 10-30 Gwei:可以等一等
    expensive: 60  // > 60 Gwei:除非必要,否則緩緩
  },
  erc20Transfer: {
    cheap: 8,
    normal: 25,
    expensive: 50
  },
  uniswapSwap: {
    cheap: 20,
    normal: 50,
    expensive: 100
  },
  nftMint: {
    cheap: 30,
    normal: 80,
    expensive: 150
  }
};

function getAdvice(operation, currentGasPrice) {
  const thresholds = DECISION_THRESHOLDS[operation];
  if (!thresholds) return '未知操作類型';

  if (currentGasPrice <= thresholds.cheap) {
    return '現在 Gas 很低!果斷執行,省錢又快速。';
  } else if (currentGasPrice <= thresholds.normal) {
    return 'Gas 正常偏低,可以執行,或者等個 15-30 分鐘可能更低。';
  } else if (currentGasPrice <= thresholds.expensive) {
    return 'Gas 有點高。如果不是 meme coin 或限時 mint,等一等比較划算。';
  } else {
    return 'Gas 爆炸了!除非交易有時間壓力,強烈建議延後到明天或後天。';
  }
}

// 實測
console.log(getAdvice('uniswapSwap', 18));  // 現在 Gas 很低!果斷執行,省錢又快速。
console.log(getAdvice('uniswapSwap', 55));  // Gas 有點高。如果不是 meme coin 或限時 mint,等一等比較划算。
console.log(getAdvice('uniswapSwap', 120)); // Gas 爆炸了!除非交易有時間壓力,強烈建議延後到明天或後天。

三個你一定要知道的 Gas 優化技巧

技巧一:學會用「加快交易」功能

大多數錢包(MetaMask、Tally 等等)都有這個功能:如果你的交易卡住了,可以「加快」它——用更高的 Gas Price 重新廣播同一筆交易。

原理很簡單:礦工永遠選 Gas Price 最高的交易。如果你的交易一直卡在 mempool 裡,等別人都成交了,你的交易還是排不到。這時候把 Gas Price 提高,讓礦工優先選你。

// MetaMask 的 Speed Up 原理就是提高 gasPrice
// 然後用同一個 nonce 重新發送交易

async function speedUpTransaction(web3, originalTxHash, newGasPriceGwei) {
  // 1. 取得原始交易的 nonce
  const originalTx = await web3.eth.getTransaction(originalTxHash);
  const nonce = originalTx.nonce;

  // 2. 用更高的 gasPrice 建立新交易
  const newTx = {
    from: originalTx.from,
    to: originalTx.to,
    value: originalTx.value,
    gas: originalTx.gas,
    gasPrice: web3.utils.toWei(newGasPriceGwei.toString(), 'gwei'),
    nonce: nonce,
    data: originalTx.input
  };

  // 3. 簽章並發送
  // 注意:錢包會彈出確認,這個操作會覆蓋掉原本卡住的交易
  console.log(`加快交易:Gas Price ${newGasPriceGwei} Gwei (原:${web3.utils.fromWei(originalTx.gasPrice, 'gwei')} Gwei)`);
  return newTx;
}

技巧二:善用 EIP-1559 的 Refund 機制

你知道嗎?EIP-1559 有一個很棒的特性:如果你的交易實際用的 Gas 比上限少,多付的錢會退回來

所以與其設定一個「保守」的 Gas Limit,不如稍微高一點點就好。差額都會退給你。

// 不要設太高也不要設太低
const OPERATION_GAS = {
  ethTransfer: 21000,
  erc20Transfer: 65000,
  uniswapSwap: 200000
};

// 建議的 Gas Limit 設定
function getSafeGasLimit(operation, bufferPercent = 20) {
  const baseGas = OPERATION_GAS[operation] || 21000;
  return Math.floor(baseGas * (1 + bufferPercent / 100));
}

// ETH 轉帳:21000 * 1.2 = 25200
// Uniswap Swap:200000 * 1.2 = 240000
console.log(`安全 Gas Limit:${getSafeGasLimit('uniswapSwap')} Gas`);

技巧三:批量交易省 Gas

如果你要進行多筆同類操作,把它们批次處理可以省下不少費用。

// 批次轉帳(以合約呼叫批次執行)vs 個別轉帳

// 個別轉帳:5 筆
// 費用 = 5 × 21000 Gas × 30 Gwei = 0.00315 ETH

// 用 Multisender 之類的批量工具
// 假設批量合約的 Gas 是:21000 + (n-1) × 500
// 費用 = (21000 + 4 × 500) × 30 Gwei = 0.00225 ETH
// 節省:28.6%

const BATCH_SAVINGS = {
  3: 0.15,   // 3筆:節省15%
  5: 0.29,   // 5筆:節省29%
  10: 0.43,  // 10筆:節省43%
  20: 0.52   // 20筆:節省52%
};

Object.entries(BATCH_SAVINGS).forEach(([count, saving]) => {
  console.log(`${count}筆批量轉帳可節省:${(saving * 100).toFixed(0)}%`);
});

總結:Gas 計算不難,難的是養成習慣

我帶你走過了 Gas 的基本概念、基本計算、互動式計算機實作、Layer 2 比較、EIP-1559 結構、決策策略和優化技巧。現在你應該對 Gas 有相當清楚的理解了。

下次轉帳或 Swap 之前,花 10 秒鐘算一下費用,你會發現自己對錢的控制力強多了。

延伸閱讀與來源

這篇文章對您有幫助嗎?

評論

發表評論

注意:由於這是靜態網站,您的評論將儲存在本地瀏覽器中,不會公開顯示。

目前尚無評論,成為第一個發表評論的人吧!