Skip to content

Commit

Permalink
misc: reduce allocations in CalcBaseFee
Browse files Browse the repository at this point in the history
  • Loading branch information
Jeiwan committed May 26, 2022
1 parent d575a2d commit fa2c19a
Showing 1 changed file with 15 additions and 21 deletions.
36 changes: 15 additions & 21 deletions consensus/misc/eip1559.go
Expand Up @@ -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)
}
}

0 comments on commit fa2c19a

Please sign in to comment.