从以太坊交易回执核算 EIP-1559 手续费

星期日, 9月 7, 2025 | 4分钟阅读 | 更新于 星期日, 9月 7, 2025

@

《以太坊 交易类型》 里列出了 0x02 交易的两个费率字段。发送方给出 maxFeePerGas 和 maxPriorityFeePerGas,区块决定实际基础费,回执记录实际费率与 Gas 用量。对账时需要把这三个来源拼起来,才能分清扣款的去向。

实验环境 Go 1.25.1,示例用标准库。采集实际主网数据使用 Foundry v1.3.2 的 Cast、Bash 5.2.0 和 jq 1.7.1。 Go 发行记录 · Foundry v1.3.2

一、从一组具体数字开始

设 Gas 上限为 50000,实际使用 21000。交易允许每 Gas 最多付 50 gwei,小费上限为 3 gwei。入块时基础费为 48 gwei。能给的小费还剩 2 gwei,所以有效费率是 50 gwei。假如同一笔交易进入基础费为 29 gwei 的区块,有效费率会是 32 gwei。

实际小费率 = min(小费上限, 总费率上限 - 区块基础费率)
实际费率   = 区块基础费率 + 实际小费率
执行费用   = 实际费率 × gasUsed
基础费销毁 = 区块基础费率 × gasUsed
小费       = 实际小费率 × gasUsed

第一组数字算出的执行费用为 0.00105 ETH,基础费销毁为 0.001008 ETH,小费为 0.000042 ETH。Gas 上限约束交易可用的 Gas,也用于计算发送前的余额需求。最终结算看 gasUsed。成功和回滚都消耗 Gas。回执的 cumulativeGasUsed 是同一区块中的累计用量,单笔对账应取 gasUsed。 EIP-1559 · 交易回执字段

二、用整数复算并校验回执

保存为 fees.go。输入费率都用 wei,乘法全程使用 big.Int。示例只接 0x02 交易的执行费用。Blob 交易还会有额外的 Blob Gas 费用。

package fees

import (
    "fmt"
    "math/big"
)

type Fee struct {
    Total  *big.Int
    Burned *big.Int
    Tip    *big.Int
}

func Reconcile(base, max, priority, effective *big.Int, gasUsed uint64) (Fee, error) {
    for _, rate := range []*big.Int{base, max, priority, effective} {
        if rate == nil || rate.Sign() < 0 {
            return Fee{}, fmt.Errorf("missing or negative gas price")
        }
    }
    if priority.Cmp(max) > 0 || base.Cmp(max) > 0 {
        return Fee{}, fmt.Errorf("inconsistent transaction fee caps")
    }

    tipRate := new(big.Int).Sub(max, base)
    if tipRate.Cmp(priority) > 0 {
        tipRate.Set(priority)
    }
    rate := new(big.Int).Add(base, tipRate)
    if rate.Cmp(effective) != 0 {
        return Fee{}, fmt.Errorf("effective gas price: receipt=%s computed=%s", effective, rate)
    }

    used := new(big.Int).SetUint64(gasUsed)
    return Fee{
        Total:  new(big.Int).Mul(rate, used),
        Burned: new(big.Int).Mul(base, used),
        Tip:    new(big.Int).Mul(tipRate, used),
    }, nil
}

将下面保存为 fees_test.go,执行 GOTOOLCHAIN=go1.25.1 go mod init fee-lab 和 GOTOOLCHAIN=go1.25.1 go test。测试里的第一和第二个输入分别覆盖手续费上限夹住小费、以及小费按出价结算。

package fees

import (
    "math/big"
    "testing"
)

func TestReconcile(t *testing.T) {
    gwei := func(v int64) *big.Int { return big.NewInt(v * 1_000_000_000) }
    for _, test := range []struct {
        base, effective, tip int64
        wantError           bool
    }{
        {48, 50, 2, false},
        {29, 32, 3, false},
        {48, 51, 0, true},
        {51, 51, 0, true},
    } {
        fee, err := Reconcile(gwei(test.base), gwei(50), gwei(3), gwei(test.effective), 21_000)
        if (err != nil) != test.wantError {
            t.Fatalf("base %d: %v", test.base, err)
        }
        if err != nil {
            continue
        }
        want := gwei(test.tip * 21_000)
        if fee.Tip.Cmp(want) != 0 {
            t.Fatalf("tip=%s want %s", fee.Tip, want)
        }
        if new(big.Int).Add(fee.Burned, fee.Tip).Cmp(fee.Total) != 0 {
            t.Fatal("burn and tip do not add up")
        }
    }
}

三、检查交易、回执和区块是否匹配

选一笔已经确定入块的 0x02 交易。先取回执,再用其中的区块哈希读区块头。这样计算用的基础费能和这份回执对上。

cast rpc --rpc-url "$EXEC_RPC" eth_getTransactionByHash "$TX" > tx.json
cast rpc --rpc-url "$EXEC_RPC" eth_getTransactionReceipt "$TX" > receipt.json
block_hash=$(jq -er .blockHash receipt.json)
cast rpc --rpc-url "$EXEC_RPC" eth_getBlockByHash "$block_hash" false > block.json

jq '{type,hash,blockHash,maxFeePerGas,maxPriorityFeePerGas}' tx.json
jq '{type,transactionHash,blockHash,gasUsed,effectiveGasPrice,status}' receipt.json
jq '{hash,baseFeePerGas}' block.json

把上述十六进制数量解析成整数,再传给 Reconcile。如果交易尚未入块,回执可以返回 null,这时只能记录预计值。结算服务在入账前要核对交易哈希和各响应的区块哈希,并按链的确认策略检查该区块。收到重组后的新回执,费用应以新的入块结果计算。

四、从父区块推算基础费

对账时已知的是当前块的 baseFeePerGas。如果还要估算下一块,就从当前块的 gasUsed 和 gasLimit 出发。对 London 之后的普通区块,目标 Gas 用量是该块 Gas 上限除以二。用量高于目标时按比例增加,低于时按比例减少。两次除法都向下取整,向上调整最少加 1 wei。区块等于目标用量时,基础费保持不变。 EIP-1559 的基础费公式

假设父区块的 gasLimit 为 3000 万,目标为 1500 万,基础费为 40 gwei。

父区块 gasUsed变化下一块基础费
3000 万+5 gwei45 gwei
2250 万+2.5 gwei42.5 gwei
1500 万040 gwei
0-5 gwei35 gwei

拿其中 2250 万这一行为例,40 gwei × (2250 万 - 1500 万) ÷ 1500 万 ÷ 8 得到 2.5 gwei。若当前交易的费率上限为 42 gwei,下一块的基础费已经高于上限,后续打包还要等到基础费下降或发送方替换交易。若上限为 44 gwei、小费上限为 3 gwei,进入该块时只能留下 1.5 gwei 的小费。

可以用上一节的 Cast 查询一个块,并用其 parentHash 查父块。记录两个区块各自的基础费,然后用父块的两项 Gas 数据复算子块,把所有值保持为整数 wei。在已经打包的交易记录里,同时保存回执的 gasUsed、有效费率和区块哈希。若换到另一分叉,即使交易哈希没变,实际基础费和执行用量仍要根据新回执重新核对。

© 2026 我的博客

🌱 Powered by Hugo with theme Dream.