Blockchain infrastructure · 6 MIN READ
EIP-1559 fees: compute the effective gas price exactly and refuse to sign above a ceiling
Derive maxFeePerGas and maxPriorityFeePerGas with big.Int, predict the effective gas price for any base fee and enforce a fee ceiling before signing.
Since the London upgrade an Ethereum transaction no longer names one gas price. It carries two caps chosen by the sender, while the protocol sets a per-block base fee that is burned. The price actually paid is decided only when a block includes the transaction, so the code that builds it has to reason about the worst case. This lesson computes those numbers exactly and puts a ceiling in front of the signer that no fee oracle can raise.
blockchain · A MAP OF THE IDEA
- Observe base fee + tip
- Derive caps in wei
- Enforce fee ceiling
- Build type-2 tx unsigned
Useful when
- Exact integer arithmetic that agrees with go-ethereum's EffectiveGasTip.
- A policy ceiling bounds spend even when an oracle or node misbehaves.
Watch out
- A capped transaction can wait indefinitely while the base fee keeps rising.
- Blob gas has a separate fee market that this policy does not bound.
Implementation & operation cost: A small fee module with table tests and one reviewed ceiling per chain; the price is occasional delayed inclusion during fee spikes.
Two caps from the sender, one price from the protocol
A type-2 transaction, types.DynamicFeeTx in go-ethereum, carries GasTipCap (maxPriorityFeePerGas, the most the sender offers the block producer) and GasFeeCap (maxFeePerGas, the most it will pay per unit of gas in total). The block header carries BaseFee. A block can include the transaction only if maxFeePerGas is at least that base fee, and the price per gas is then min(maxFeePerGas, baseFee + maxPriorityFeePerGas). The base-fee part is burned; only the remainder reaches the producer. The base fee follows demand: geth's CalcBaseFee changes it by parentBaseFee * (gasUsed - target) / target / 8, so a completely full block raises it by 12.5 percent and an empty one lowers it by the same fraction. Every value here is an integer number of wei that can exceed 64 bits, which is why go-ethereum uses *big.Int throughout and why float64 has no place in the calculation; the exact-units lesson shows that failure for token amounts.
Compute the caps, check the policy, then build
The program takes an observed base fee of 30 gwei and a 2 gwei tip and derives a fee cap of twice the base fee plus the tip, the same headroom go-ethereum's bind/v2 transactor uses when no cap is given. It runs the policy check a signing service would own, builds an unsigned DynamicFeeTx for local chain 1337, and replays the inclusion formula at three possible base fees, cross-checking each result against go-ethereum's own Transaction.EffectiveGasTip.
package main
import (
"errors"
"fmt"
"math/big"
"strings"
"github.com/ethereum/go-ethereum/common"
"github.com/ethereum/go-ethereum/core/types"
"github.com/ethereum/go-ethereum/params"
)
// FeePolicy is owned by the signing service, not by the fee oracle.
type FeePolicy struct {
MaxFeePerGas *big.Int // highest maxFeePerGas the service will sign
MaxTotalFee *big.Int // highest gasLimit * maxFeePerGas, in wei
}
var errAbovePolicy = errors.New("refusing to sign")
func gwei(n int64) *big.Int {
return new(big.Int).Mul(big.NewInt(n), big.NewInt(params.GWei))
}
// formatGwei prints a non-negative wei amount as gwei without floating point.
func formatGwei(wei *big.Int) string {
q, r := new(big.Int).QuoRem(wei, big.NewInt(params.GWei), new(big.Int))
if r.Sign() == 0 {
return q.String() + " gwei"
}
frac := strings.TrimRight(fmt.Sprintf("%09d", r.Uint64()), "0")
return q.String() + "." + frac + " gwei"
}
// feeCapFor leaves room for the base fee to double before inclusion.
func feeCapFor(baseFee, tip *big.Int) *big.Int {
c := new(big.Int).Mul(baseFee, big.NewInt(2))
return c.Add(c, tip)
}
// effectivePrice is min(feeCap, baseFee+tipCap). Below baseFee it is not includable.
func effectivePrice(baseFee, tipCap, feeCap *big.Int) (*big.Int, error) {
if feeCap.Cmp(baseFee) < 0 {
return nil, errors.New("max fee below base fee")
}
p := new(big.Int).Add(baseFee, tipCap)
if p.Cmp(feeCap) > 0 {
p.Set(feeCap)
}
return p, nil
}
func checkPolicy(p FeePolicy, gas uint64, tipCap, feeCap *big.Int) error {
if tipCap.Sign() < 0 || feeCap.Sign() <= 0 || tipCap.Cmp(feeCap) > 0 {
return errors.New("need 0 <= max priority fee <= max fee")
}
if feeCap.Cmp(p.MaxFeePerGas) > 0 {
return fmt.Errorf("%w: max fee %s > limit %s", errAbovePolicy, formatGwei(feeCap), formatGwei(p.MaxFeePerGas))
}
worst := new(big.Int).Mul(new(big.Int).SetUint64(gas), feeCap)
if worst.Cmp(p.MaxTotalFee) > 0 {
return fmt.Errorf("%w: worst-case fee %s wei > limit %s wei", errAbovePolicy, worst, p.MaxTotalFee)
}
return nil
}
func main() {
policy := FeePolicy{MaxFeePerGas: gwei(100), MaxTotalFee: big.NewInt(3_000_000_000_000_000)}
const gasLimit = 21_000
baseFee, tip := gwei(30), gwei(2) // observed from the latest header and a tip oracle
feeCap := feeCapFor(baseFee, tip)
fmt.Println("max priority fee", formatGwei(tip)+", max fee", formatGwei(feeCap))
fmt.Println(checkPolicy(policy, gasLimit, tip, feeCapFor(gwei(120), tip)))
fmt.Println(checkPolicy(policy, 200_000, tip, feeCap))
if err := checkPolicy(policy, gasLimit, tip, feeCap); err != nil {
panic(err)
}
to := common.HexToAddress("0x00000000000000000000000000000000000000aa")
tx := types.NewTx(&types.DynamicFeeTx{
ChainID: big.NewInt(1337),
Nonce: 0,
GasTipCap: tip,
GasFeeCap: feeCap,
Gas: gasLimit,
To: &to,
Value: big.NewInt(10_000_000_000_000_000), // 0.01 ether in wei
})
fmt.Println("built unsigned type", tx.Type(), "tx for chain", tx.ChainId())
for _, b := range []*big.Int{gwei(30), big.NewInt(61_500_000_000), gwei(63)} {
price, err := effectivePrice(b, tip, feeCap)
gethTip, gethErr := tx.EffectiveGasTip(b)
if err != nil {
fmt.Printf("base %s: not includable (%v)\n", formatGwei(b), gethErr)
continue
}
ourTip := new(big.Int).Sub(price, b)
fmt.Printf("base %s: pays %s, producer tip %s, geth agrees: %t\n",
formatGwei(b), formatGwei(price), formatGwei(ourTip), ourTip.Cmp(gethTip) == 0)
}
fmt.Println("upfront balance check:", tx.Cost(), "wei")
}gwei multiplies by params.GWei (1e9) inside big.Int, and formatGwei divides with QuoRem so 61.5 gwei prints exactly. checkPolicy rejects a tip above the cap, a fee cap above 100 gwei and a worst case (gas limit * fee cap) above 0.003 ether: the oracle spike to a 120 gwei base fee yields a 242 gwei cap and is refused, and so is a 200000-gas call even at the normal cap. At base 30 the sender pays 32 gwei and the producer keeps 2. At 61.5 the cap binds, so the producer gets only 0.5. At 63 geth returns ErrGasFeeCapTooLow (fee cap less than base fee) and the transaction simply waits. tx.Cost() is gas * GasFeeCap + value, the balance a node demands up front, not the amount finally charged.
Take inputs from the node, but let the policy decide
In production the base fee comes from the latest header and the tip from the node's suggestion or from eth_feeHistory percentiles. Both are hints from an external dependency, so they are inputs to the policy rather than values the signer trusts. FeeHistory returns one more base fee than the number of blocks requested: the last entry is the node's projection for the next block, a better starting point than the latest header when blocks are full.
head, err := client.HeaderByNumber(ctx, nil) // latest
if err != nil {
return err
}
if head.BaseFee == nil {
return errors.New("no EIP-1559 base fee on this chain; use a legacy fee policy")
}
tip, err := client.SuggestGasTipCap(ctx) // eth_maxPriorityFeePerGas
if err != nil {
return err
}
hist, err := client.FeeHistory(ctx, 5, nil, []float64{50})
if err != nil {
return err
}
nextBase := hist.BaseFee[len(hist.BaseFee)-1] // the node's projection for the next block
feeCap := feeCapFor(nextBase, tip)
if err := checkPolicy(policy, gasLimit, tip, feeCap); err != nil {
return err // alert: the market moved beyond what this service may pay
}This fragment talks to a real node, so run it in your own native environment against an endpoint whose chain ID you have verified; it is not executed here. HeaderByNumber(ctx, nil) asks for the latest header, and BaseFee is nil before London, which deserves an explicit error instead of a nil-pointer panic. SuggestGasTipCap maps to eth_maxPriorityFeePerGas; the 50th-percentile rewards in hist.Reward are an alternative tip source. hist.BaseFee has blockCount+1 entries, the last one for the next block. Whatever the source, checkPolicy has the last word.
Ceilings, replacements and what is finally charged
Treat the fee ceiling as configuration with an owner, reviewed like any spending limit, and alert when the guard trips instead of raising it automatically. A transaction with 2x headroom can still wait if the base fee keeps climbing; that is the safe failure, because the alternative is paying whatever the market demands. When you do speed up a pending transaction, the replacement rules from the nonces lesson apply: geth's default pool accepts a same-nonce replacement only if both the fee cap and the tip rise by at least 10 percent, so bump both and pass the new values through the same policy. Reconcile budgets from the receipt, EffectiveGasPrice * GasUsed, not from the caps; unused gas and unused headroom are never charged. The gas limit is a separate guard: estimating it is a simulation against current state, and the worst-case fee multiplies it. Blob transactions add an independent fee market, maxFeePerBlobGas, that this policy does not bound.
Test the guard at its edges
The fee path needs no node to test. Table-test effectivePrice at base fees below, at and above the point where the cap binds, and assert agreement with EffectiveGasTip in each case so a library upgrade that changes the rules is noticed. Test the guard with a tip above the cap, a zero cap, a cap exactly at the limit (allowed) and one wei above it (refused), and a gas limit that pushes the worst case over the total ceiling. Add a regression test that oracle values are copied rather than aliased: big.Int methods mutate their receiver, so a helper that writes into a *big.Int taken from a header can silently change the next transaction's fees. types.NewTx copies its TxData, which protects the built transaction, but not the policy inputs you keep. In review, check that nothing between the policy check and the signer can change the fields.
TAKE THIS WITH YOU
Compute EIP-1559 fees in wei with big.Int: the price paid is min(maxFee, baseFee + tip), and a policy-owned ceiling on maxFee and on gasLimit * maxFee must reject a transaction before it is signed.
Check your understanding
What price per unit of gas does an included EIP-1559 transaction actually pay?
Go to the source
Progress stays in this browser. No account needed.