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

如何用ethers.js计算ETH转账的预估交易手续费(ETH单位)

计算ETH钱包转账的预估手续费(ETH单位)

要计算预估交易手续费,核心逻辑是手续费 = gas用量 × gas单价,再将wei单位转换为ETH即可。以下结合你已获取的参数,分两种交易类型说明:

一、基础前提

  • 普通ETH钱包转账的默认gas用量(gasLimit)为21000(无合约交互场景);如果是调用合约等复杂交易,建议用provider.estimateGas()获取精准的gas消耗值。
  • 通过getFeeData()获取的gasPrice、maxFeePerGas等参数均为wei单位,最终需要用ethers.utils.formatEther()转换为ETH单位。

二、Legacy交易(非EIP-1559)

Legacy交易采用固定gasPrice作为gas单价,预估手续费计算方式:

// 普通转账默认gasLimit
const gasLimit = 21000;
// 计算wei手续费后转成ETH
const legacyFeeETH = ethers.utils.formatEther(gasPrice.mul(gasLimit));

三、EIP-1559交易(当前主流)

EIP-1559交易的手续费由网络基础费(baseFeePerGas,网络自动调整)+ 矿工小费(maxPriorityFeePerGas)组成,maxFeePerGas是用户设置的手续费上限(实际支付不会超过该值)。

1. 正常情况预估(基于当前网络基础费)

// 计算当前基础费+小费的总单价,再乘以gasLimit转成ETH
const normal1559FeeETH = ethers.utils.formatEther(
  baseFeePerGas.add(maxPriorityFeePerGas).mul(gasLimit)
);

2. 最坏情况预估(触发手续费上限)

若网络拥堵导致基础费飙升,实际支付的手续费最高不会超过maxFeePerGas,最坏情况的预估方式:

const max1559FeeETH = ethers.utils.formatEther(maxFeePerGas.mul(gasLimit));

完整代码示例

const provider = new ethers.providers.JsonRpcProvider('rpc_url');
const {
  gasPrice, maxFeePerGas, maxPriorityFeePerGas, baseFeePerGas
} = await provider.getFeeData();

// 可选:用estimateGas获取精准gas用量(适合复杂交易)
const gasLimit = await provider.estimateGas({
  from: '你的钱包地址',
  to: '收款钱包地址',
  value: ethers.utils.parseEther('0.01') // 转账金额按需修改
});
// 普通转账可直接用固定值:const gasLimit = 21000;

// 计算各类型预估手续费
const legacyFeeETH = ethers.utils.formatEther(gasPrice.mul(gasLimit));
const normal1559FeeETH = ethers.utils.formatEther(baseFeePerGas.add(maxPriorityFeePerGas).mul(gasLimit));
const max1559FeeETH = ethers.utils.formatEther(maxFeePerGas.mul(gasLimit));

// 在UI中展示示例
console.log(`Legacy预估手续费:${legacyFeeETH} ETH`);
console.log(`EIP-1559正常预估手续费:${normal1559FeeETH} ETH`);
console.log(`EIP-1559最高预估手续费:${max1559FeeETH} ETH`);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:30:39