You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Web3.js获取以太坊交易过程中的Gasprice

在Web3.js中获取以太坊交易的Gas价格

一、发送交易前获取建议Gas价格

你可以用Web3.eth.getGasPrice()方法获取当前网络的建议Gas价格(单位为wei),这个值是当前网络交易的中位数Gas价格,可作为交易时的参考,也能手动指定到交易参数里。修改你的代码如下:

const paymentAddress='xxxxxxxxxxxxxxxxxxxx'

// 先获取建议Gas价格
Web3.eth.getGasPrice()
  .then(gasPrice => {
    console.log("当前建议Gas价格(wei):", gasPrice);
    // 发送交易时可手动指定gasPrice,不指定的话Web3会自动使用网络建议值
    return Web3.eth.sendTransaction({
      to: paymentAddress,
      value: XXXXXXXXX,
      gasPrice: gasPrice // 可选参数
    });
  })
  .then(transactionReceipt => {
    console.log("交易成功,交易哈希:", transactionReceipt.transactionHash);
    // 交易上链后,从收据里拿实际使用的Gas价格
    console.log("交易实际使用的Gas价格(wei):", transactionReceipt.effectiveGasPrice);
  })
  .catch(err => {
    console.log("交易错误:", err);
  });

二、查询已上链交易的实际Gas价格

如果交易已经完成上链,你可以通过交易哈希调用Web3.eth.getTransactionReceipt()获取交易收据,其中的effectiveGasPrice字段就是该交易实际支付的Gas价格(EIP-1559网络下包含基础费和优先级小费):

const txHash = "你的交易哈希值";
Web3.eth.getTransactionReceipt(txHash)
  .then(receipt => {
    console.log("交易实际Gas价格(wei):", receipt.effectiveGasPrice);
    // 转换成gwei更直观
    console.log("交易实际Gas价格(gwei):", Web3.utils.fromWei(receipt.effectiveGasPrice, 'gwei'));
  })
  .catch(err => {
    console.log("查询失败:", err);
  });

注意:EIP-1559启用的网络(如以太坊主网)中,若你不手动指定gasPrice,Web3.js会自动处理基础费和小费,此时交易收据里的effectiveGasPrice就是最终实际支付的总Gas价格。

内容的提问来源于stack exchange,提问作者Abhishek

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 02:31:11