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

Web3.js获取baseFeePerGas返回0x7,如何转为数值类型?

问题原因与解决方案

原因分析

你遇到的是Web3.js版本差异导致的返回格式问题:

  • 旧版本(如v0.x系列)的getBlock方法默认会将数值型字段(包括baseFeePerGas)以十六进制字符串形式返回;
  • 官方文档描述的Number类型返回,是针对Web3.js v1.x及以上版本的行为,这类新版本会自动将十六进制数值转换为JavaScript Number或BN(BigNumber)类型。

另外注意你的代码里虽然引入了ethers,但实际调用的是window.web3,所以生效逻辑由Web3.js决定,和ethers无关。

解决方法

方法1:手动转换十六进制为数值

用Web3.js内置工具方法直接转换:

function getBlock() {
  return window.web3.eth.getBlock('latest')
    .then(data => {
      // 转换为Number类型
      data.baseFeePerGas = web3.utils.hexToNumber(data.baseFeePerGas);
      // 如果数值超过JS安全整数范围(大于2^53-1),建议用BN类型避免精度丢失
      // data.baseFeePerGas = web3.utils.toBN(data.baseFeePerGas);
      console.log(data);
      return data;
    })
    .catch(err => console.error(err)); // 建议保留错误捕获逻辑定位问题
}

方法2:升级Web3.js到最新版本

升级到v1.x或更高版本后,getBlock返回的baseFeePerGas会自动转为BN类型(大数值场景更安全),你可以直接调用其方法转换为需要的类型:

// 升级后示例
window.web3.eth.getBlock('latest').then(data => {
  console.log(data.baseFeePerGas.toNumber()); // 转为Number
  console.log(data.baseFeePerGas.toString()); // 转为字符串
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 13:15:28