在 1.21 中,如何估算 EIP-1559 的 maxFeePerGas 避免 stuck tx
解读
国内主流链(BSC、Polygon、Arbitrum、OP 等)都已兼容 EIP-1559,但各链的 baseFee 波动区间、区块容量弹性系数与以太坊主网并不一致。面试官问“1.21” 并不是让你背版本号,而是考察两点:
- 你是否理解 Go 1.21 在 ethclient、types.DynamicFeeTx、header.BaseFee 等接口上的最新行为;
- 你是否能在代码里实时估算 maxFeePerGas,既不让交易卡住,也不白白多付 gas。
一句话:用 Go 1.21 写一段能在国内节点网络抖动、出块时间不稳定的场景下不卡单、不超付的 maxFeePerGas 估算逻辑。
知识点
- EIP-1559 费用公式:
effectiveGasPrice = min(maxFeePerGas, maxPriorityFeePerGas + baseFee)
交易被打包的条件是 effectiveGasPrice ≥ baseFee。 - Go 1.21 的
types.DynamicFeeTx字段含义:GasFeeCap即 maxFeePerGasGasTipCap即 maxPriorityFeePerGas
二者必须同时设置,不能再用传统的 GasPrice 字段。
- 国内节点普遍对未上链交易缓存 3~5 min,若 maxFeePerGas < 未来 baseFee,交易即“卡住”,不会自动退回。
- 估算策略:
a. 取最近 20 个区块的 baseFee 滑动最大值作为安全边际;
b. 用指数加权移动平均(EWMA)预测下一区块 baseFee;
c. 给出一个动态上浮系数 k(1.15~1.25),抵消突发拥堵;
d. maxPriorityFeePerGas 按当前 pending 区块的 55% percentile 取,既保证排序,又避免“内卷”。 - Go 实现细节:
- 用
ethclient.BlockByNumber(ctx, nil)取最新头,拿到header.BaseFee(*big.Int,单位为 wei); - 用
ethclient.PendingHeader或txpool_content拿到 pending 池的 tip 分布; - 全部计算在 wei 维度完成,最后统一转回
big.Int,防止精度截断; - 用
sync.Pool复用big.Int对象,降低高并发场景下的 GC 压力。
- 用
答案
package main
import (
"context"
"log"
"math/big"
"time"
"github.com/ethereum/go-ethereum/ethclient"
"github.com/ethereum/go-ethereum/rpc"
)
const (
// 国内节点建议 20 块窗口
blockWindow = 20
// 安全边际 1.2 倍
safetyFactor = 1200
// 分母 1000
factorDenom = 1000
)
// EstimateMaxFeePerGas 返回下一笔交易推荐的 maxFeePerGas 与 maxPriorityFeePerGas(单位: wei)
func EstimateMaxFeePerGas(rawRPC string) (*big.Int, *big.Int, error) {
rc, err := rpc.Dial(rawRPC)
if err != nil {
return nil, nil, err
}
client := ethclient.NewClient(rc)
defer client.Close()
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// 1. 拉取最新区块号
header, err := client.HeaderByNumber(ctx, nil)
if err != nil {
return nil, nil, err
}
current := header.Number.Uint64()
// 2. 收集最近 blockWindow 的 baseFee
var baseFees []*big.Int
for i := uint64(0); i < blockWindow; i++ {
h, err := client.HeaderByNumber(ctx, big.NewInt(int64(current-i)))
if err != nil {
continue
}
if h.BaseFee != nil {
baseFees = append(baseFees, new(big.Int).Set(h.BaseFee))
}
}
if len(baseFees) == 0 {
return nil, nil, fmt.Errorf("no baseFee data")
}
// 3. 取滑动最大值
maxBase := new(big.Int).Set(baseFees[0])
for _, v := range baseFees {
if v.Cmp(maxBase) > 0 {
maxBase.Set(v)
}
}
// 4. 预测下一区块 baseFee = maxBase * safetyFactor / factorDenom
nextBase := new(big.Int).Mul(maxBase, big.NewInt(safetyFactor))
nextBase.Div(nextBase, big.NewInt(factorDenom))
// 5. 取 pending 池 tip 55 分位
tips, err := client.PendingTransactionTips(ctx) // 伪代码,实际可遍历 txpool_content
if err != nil || len(tips) == 0 {
// 降级策略
tip = big.NewInt(2e9) // 2 Gwei
} else {
sort.Sort(bigIntArray(tips))
idx := len(tips) * 55 / 100
tip = new(big.Int).Set(tips[idx])
}
// 6. 组装结果
maxFeePerGas := new(big.Int).Add(nextBase, tip)
return maxFeePerGas, tip, nil
}
调用示例:
maxFee, maxTip, _ := EstimateMaxFeePerGas("https://bsc-mainnet.nodereal.io/v1/your-key")
tx := types.NewTx(&types.DynamicFeeTx{
ChainID: big.NewInt(56),
Nonce: nonce,
GasFeeCap: maxFee,
GasTipCap: maxTip,
Gas: 21000,
To: &to,
Value: value,
Data: nil,
})
关键点
- 全部计算在
big.Int内完成,防止溢出; - 用滑动最大 baseFee + 1.2 倍系数,国内链瞬时拥堵也能过;
- 优先读 pending 池,节点不给 txpool_content 接口时立即降级,保证鲁棒性;
- 返回的 maxFeePerGas 已包含 tip,直接塞进 GasFeeCap 即可,无需再手动相加。
拓展思考
- 多链适配:BSC 的 baseFee 上限 30 gwei、Polygon 弹性系数 8/2,与以太坊 12.5% 不同,上浮系数 k 需可配置,建议用
map[chainID]float64注入。 - 实时热刷新:把估算逻辑包装成
gasprice.Service,每 3 秒异步缓存一次,业务层直接读缓存,避免并发请求把节点打满。 - 交易替换(Replace-by-Fee):若发现 10 秒未上链,可复用 nonce 重新估算,仅提高 10% 的 maxFeePerGas,防止“过度竞价”。
- Go 1.21 的 atomic.Int64 比 big.Int 更快,可把 gwei 级数据放大 9 位转 int64,在高频场景下减少 30% CPU。
- 合规与审计:国内钱包上架应用商店需提供链上手续费计算说明,把本段代码输出打印成日志,方便监管抽查。