consensus/misc: reduce allocations and improve comments in CalcBaseFee (#24958)
* consensus/misc: reduce allocations in CalcBaseFee * consensus/misc: add formulas of CalcBaseFee
This commit is contained in:
parent
6f075bf6af
commit
490c45c70f
@ -58,36 +58,36 @@ 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)
|
||||
}
|
||||
|
||||
var (
|
||||
num = new(big.Int)
|
||||
denom = new(big.Int)
|
||||
)
|
||||
|
||||
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,
|
||||
)
|
||||
// max(1, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)
|
||||
num.SetUint64(parent.GasUsed - parentGasTarget)
|
||||
num.Mul(num, parent.BaseFee)
|
||||
num.Div(num, denom.SetUint64(parentGasTarget))
|
||||
num.Div(num, denom.SetUint64(params.BaseFeeChangeDenominator))
|
||||
baseFeeDelta := math.BigMax(num, common.Big1)
|
||||
|
||||
return x.Add(parent.BaseFee, baseFeeDelta)
|
||||
return num.Add(parent.BaseFee, baseFeeDelta)
|
||||
} 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)
|
||||
// max(0, parentBaseFee * gasUsedDelta / parentGasTarget / baseFeeChangeDenominator)
|
||||
num.SetUint64(parentGasTarget - parent.GasUsed)
|
||||
num.Mul(num, parent.BaseFee)
|
||||
num.Div(num, denom.SetUint64(parentGasTarget))
|
||||
num.Div(num, denom.SetUint64(params.BaseFeeChangeDenominator))
|
||||
baseFee := num.Sub(parent.BaseFee, num)
|
||||
|
||||
return math.BigMax(
|
||||
x.Sub(parent.BaseFee, baseFeeDelta),
|
||||
common.Big0,
|
||||
)
|
||||
return math.BigMax(baseFee, common.Big0)
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user