diff --git a/consensus/misc/eip1559.go b/consensus/misc/eip1559.go index e18340b0f33ec..977538b7e09f4 100644 --- a/consensus/misc/eip1559.go +++ b/consensus/misc/eip1559.go @@ -58,36 +58,30 @@ func CalcBaseFee(config *params.ChainConfig, parent *types.Header) *big.Int { return new(big.Int).SetUint64(params.InitialBaseFee) } - var ( - parentGasTarget = parent.GasLimit / params.ElasticityMultiplier - parentGasTargetBig = new(big.Int).SetUint64(parentGasTarget) - baseFeeChangeDenominator = new(big.Int).SetUint64(params.BaseFeeChangeDenominator) - ) + parentGasTarget := parent.GasLimit / params.ElasticityMultiplier + // If the parent gasUsed is the same as the target, the baseFee remains unchanged. if parent.GasUsed == parentGasTarget { return new(big.Int).Set(parent.BaseFee) } + + parentGasTargetAdjusted := new(big.Int).SetUint64(parentGasTarget * params.BaseFeeChangeDenominator) + if parent.GasUsed > parentGasTarget { // If the parent block used more gas than its target, the baseFee should increase. - gasUsedDelta := new(big.Int).SetUint64(parent.GasUsed - parentGasTarget) - x := new(big.Int).Mul(parent.BaseFee, gasUsedDelta) - y := x.Div(x, parentGasTargetBig) - baseFeeDelta := math.BigMax( - x.Div(y, baseFeeChangeDenominator), - common.Big1, - ) + r := new(big.Int).SetUint64(parent.GasUsed - parentGasTarget) + r.Mul(r, parent.BaseFee) + r.Div(r, parentGasTargetAdjusted) + r.Add(parent.BaseFee, math.BigMax(r, common.Big1)) - return x.Add(parent.BaseFee, baseFeeDelta) + return r } else { // Otherwise if the parent block used less gas than its target, the baseFee should decrease. - gasUsedDelta := new(big.Int).SetUint64(parentGasTarget - parent.GasUsed) - x := new(big.Int).Mul(parent.BaseFee, gasUsedDelta) - y := x.Div(x, parentGasTargetBig) - baseFeeDelta := x.Div(y, baseFeeChangeDenominator) + r := new(big.Int).SetUint64(parentGasTarget - parent.GasUsed) + r.Mul(r, parent.BaseFee) + r.Div(r, parentGasTargetAdjusted) + r.Sub(parent.BaseFee, r) - return math.BigMax( - x.Sub(parent.BaseFee, baseFeeDelta), - common.Big0, - ) + return math.BigMax(r, common.Big0) } }