Skip to content

Commit 490c45c

Browse files
authored
consensus/misc: reduce allocations and improve comments in CalcBaseFee (ethereum#24958)
* consensus/misc: reduce allocations in CalcBaseFee * consensus/misc: add formulas of CalcBaseFee
1 parent 6f075bf commit 490c45c

File tree

1 file changed

+21
-21
lines changed

1 file changed

+21
-21
lines changed

consensus/misc/eip1559.go

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -58,36 +58,36 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header) *big.Int {
5858
return new(big.Int).SetUint64(params.InitialBaseFee)
5959
}
6060

61-
var (
62-
parentGasTarget = parent.GasLimit / params.ElasticityMultiplier
63-
parentGasTargetBig = new(big.Int).SetUint64(parentGasTarget)
64-
baseFeeChangeDenominator = new(big.Int).SetUint64(params.BaseFeeChangeDenominator)
65-
)
61+
parentGasTarget := parent.GasLimit / params.ElasticityMultiplier
6662
// If the parent gasUsed is the same as the target, the baseFee remains unchanged.
6763
if parent.GasUsed == parentGasTarget {
6864
return new(big.Int).Set(parent.BaseFee)
6965
}
66+
67+
var (
68+
num = new(big.Int)
69+
denom = new(big.Int)
70+
)
71+
7072
if parent.GasUsed > parentGasTarget {
7173
// If the parent block used more gas than its target, the baseFee should increase.
72-
gasUsedDelta := new(big.Int).SetUint64(parent.GasUsed - parentGasTarget)
73-
x := new(big.Int).Mul(parent.BaseFee, gasUsedDelta)
74-
y := x.Div(x, parentGasTargetBig)
75-
baseFeeDelta := math.BigMax(
76-
x.Div(y, baseFeeChangeDenominator),
77-
common.Big1,
78-
)
74+
// max(1, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)
75+
num.SetUint64(parent.GasUsed - parentGasTarget)
76+
num.Mul(num, parent.BaseFee)
77+
num.Div(num, denom.SetUint64(parentGasTarget))
78+
num.Div(num, denom.SetUint64(params.BaseFeeChangeDenominator))
79+
baseFeeDelta := math.BigMax(num, common.Big1)
7980

80-
return x.Add(parent.BaseFee, baseFeeDelta)
81+
return num.Add(parent.BaseFee, baseFeeDelta)
8182
} else {
8283
// Otherwise if the parent block used less gas than its target, the baseFee should decrease.
83-
gasUsedDelta := new(big.Int).SetUint64(parentGasTarget - parent.GasUsed)
84-
x := new(big.Int).Mul(parent.BaseFee, gasUsedDelta)
85-
y := x.Div(x, parentGasTargetBig)
86-
baseFeeDelta := x.Div(y, baseFeeChangeDenominator)
84+
// max(0, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)
85+
num.SetUint64(parentGasTarget - parent.GasUsed)
86+
num.Mul(num, parent.BaseFee)
87+
num.Div(num, denom.SetUint64(parentGasTarget))
88+
num.Div(num, denom.SetUint64(params.BaseFeeChangeDenominator))
89+
baseFee := num.Sub(parent.BaseFee, num)
8790

88-
return math.BigMax(
89-
x.Sub(parent.BaseFee, baseFeeDelta),
90-
common.Big0,
91-
)
91+
return math.BigMax(baseFee, common.Big0)
9292
}
9393
}

0 commit comments

Comments
 (0)