如何使用estimateGas()预估交易成本,并在用户确认前显示Gas费用?

解读

面试官真正想考察的是“在真实业务场景下,如何既准确又友好地把链上成本提前告诉用户”。
国内主流应用(交易所、钱包、NFT 平台)普遍要求:

  1. 不能等用户签名后才报错“out of gas”;
  2. 必须折算成人民币,且误差不超过 5%;
  3. 要兼容 MetaMask、WalletConnect、OKX、imToken 等多端;
  4. 在 1~2 秒内给出结果,不能卡 UI。

因此,回答要覆盖:

  • 如何调用 estimateGas() 拿到“gasLimit”
  • 如何拿到“gasPrice / maxFee / maxPriorityFee”
  • 如何把 gasLimit × 单价 转成“元”并展示
  • 如何防止低估、如何降级
  • 如何在前端代码里落地(Vue/React 小片段即可)

知识点

  1. estimateGas() 本质:本地节点执行一次 tx,返回 gasUsed,不含签名、不上链。
  2. 返回值是“gasLimit”预估值,实际消耗 ≤ 该值;复杂逻辑(如 ERC20 转账+回调)需再乘 1.2~1.3 安全系數。
  3. 国内节点服务商:Alibaba Cloud BaaS、BSN 文昌链、NodeReal、Ankr、Infura+VPN。
  4. EIP-1559 字段:maxFeePerGas、maxPriorityFeePerGas;Legacy 字段:gasPrice。
  5. 获取实时 gas 价格:
    • eth_gasPrice(兼容最好)
    • eth_maxPriorityFeePerGas + eth_baseFee(1559)
    • 第三方:GasNow 镜像站、OKLink OpenAPI、etherscan-cn API。
  6. 人民币折算:先取 Binance-CN 或 OKX 场外 USDT/CNY 中间价,再用链上 WETH/USDT 或 ETH/USDT 价格,两步乘法。
  7. 精度处理:BigNumber 只能用 ethers.BigNumber 或 bignumber.js,禁止 parseFloat。
  8. 安全降级:estimateGas 失败 → 用同类历史交易 gasLimit 的 95 分位值;仍失败 → 提示“链上拥堵,请稍后再试”。
  9. 合规提示:界面必须写“预估费用,实际以链上为准”,防止消费争议。

答案

以下示例基于 ethers v5 + React,业务场景:用户点击“立即铸造”NFT,前端需先弹窗展示“预计 3.12 元”。

  1. 准备工具函数
import { ethers } from 'ethers';
import axios from 'axios';

// 获取 CN¥/ETH 汇率:两步法,先 USDT/CNY,再 ETH/USDT
async function getCnyPerEth(): Promise<number> {
  const { data: usdtCny } = await axios.get('https://www.okx.com/api/v5/market/ticker?instId=USDT-CNY');
  const { data: ethUsdt } = await axios.get('https://www.okx.com/api/v5/market/ticker?instId=ETH-USDT');
  return parseFloat(usdtCny.data[0].last) * parseFloat(ethUsdt.data[0].last);
}

// 通用安全乘法
function mul18(x: string, y: string): string {
  return ethers.BigNumber.from(x).mul(y).div(ethers.utils.parseEther('1')).toString();
}
  1. 预估 gasLimit
async function estimateGasLimit(
  signer: ethers.providers.JsonRpcSigner,
  txReq: ethers.providers.TransactionRequest
): Promise<ethers.BigNumber> {
  try {
    const gas = await signer.estimateGas(txReq);
    // 复杂业务加 20% 缓冲
    return gas.mul(120).div(100);
  } catch (e) {
    // 降级:读历史 95 分位
    return ethers.BigNumber.from('150000');
  }
}
  1. 获取 gasPrice(兼容 1559 与 Legacy)
async function getGasPrice(provider: ethers.providers.JsonRpcProvider):
  Promise<{ gasPrice?: ethers.BigNumber; maxFee?: ethers.BigNumber; maxPriority?: ethers.BigNumber }> {
  const block = await provider.getBlock('latest');
  if (block.baseFeePerGas) {
    const maxPriority = await provider.send('eth_maxPriorityFeePerGas', []);
    const base = block.baseFeePerGas.mul(110).div(100); // 多给 10%
    return {
      maxFee: base.add(maxPriority),
      maxPriority: ethers.BigNumber.from(maxPriority),
    };
  } else {
    return { gasPrice: await provider.getGasPrice() };
  }
}
  1. 计算人民币费用并弹窗
async function showGasFee(
  signer: ethers.providers.JsonRpcSigner,
  txReq: ethers.providers.TransactionRequest
) {
  const provider = signer.provider;
  const [gasLimit, gasPriceObj, cnyPerEth] = await Promise.all([
    estimateGasLimit(signer, txReq),
    getGasPrice(provider),
    getCnyPerEth(),
  ]);

  let gasCostWei: ethers.BigNumber;
  if (gasPriceObj.gasPrice) {
    gasCostWei = gasLimit.mul(gasPriceObj.gasPrice);
  } else {
    gasCostWei = gasLimit.mul(gasPriceObj.maxFee!);
  }

  const gasCostEth = ethers.utils.formatEther(gasCostWei);
  const gasCostCny = (parseFloat(gasCostEth) * cnyPerEth).toFixed(2);

  const confirm = window.confirm(`预计矿工费:${gasCostCny} 元\n实际费用以链上为准,是否继续?`);
  if (!confirm) throw new Error('用户取消');

  // 真正发送交易时把 buffer 后的 gasLimit 写回
  return { ...txReq, gasLimit, ...gasPriceObj };
}
  1. 调用端
const txReq = await showGasFee(signer, {
  to: nftContract.address,
  data: nftContract.interface.encodeFunctionData('mint', [quantity]),
});
const tx = await signer.sendTransaction(txReq);
await tx.wait();

关键点:

  • 所有数值用 BigNumber,防止精度溢出;
  • 1~2 秒内完成,Promise.all 并行;
  • 失败降级到 150k gas,用户仍可手动加速;
  • 界面展示“≈3.12 元”,含免责声明。

拓展思考

  1. 批量预估:若一次 100 条 claim,可用 multicall 聚合 estimateGas,减少 99% RPC 往返。
  2. L2 差异:Arbitrum 需额外调用 NodeInterface.estimateRetryableTicket,Optimism 把 L1Fee 算进总成本,否则用户会少付。
  3. 动态更新:gasPrice 每 5 秒变一次,可用 SWR 或 React-Query 做后台轮询,弹窗内实时刷新。
  4. 合约可优化:提前在合约里暴露 estimateMintGas() 视图函数,把循环次数、存储写入量化,返回理论值,前端直接乘单价,省去一次 estimateGas 调用。
  5. 合规存档:把预估 gasLimit、gasPrice、CNY 汇率、时间戳一并埋点,用户投诉时可出具日志,满足国内网信办“链上服务日志留存 6 个月”要求。