Skip to content

Instantly share code, notes, and snippets.

@botdad
Created October 1, 2021 16:21
Show Gist options
  • Save botdad/1faa81b90f124379e1dc972a919a57a3 to your computer and use it in GitHub Desktop.
Save botdad/1faa81b90f124379e1dc972a919a57a3 to your computer and use it in GitHub Desktop.
EIP1559 gas math in TS
import { BigNumber } from 'ethers'
const BASE_FEE_MAX_CHANGE_DENOMINATOR = 8
export const getBaseFeeInNextBlock = (
currentBaseFeePerGas: BigNumber,
currentGasUsed: BigNumber,
currentGasLimit: BigNumber
): BigNumber => {
const currentGasTarget = currentGasLimit.div(2)
if (currentGasUsed.eq(currentGasTarget)) {
return currentBaseFeePerGas
} else if (currentGasUsed.gt(currentGasTarget)) {
const gasUsedDelta = currentGasUsed.sub(currentGasTarget)
const baseFeePerGasDelta = currentBaseFeePerGas
.mul(gasUsedDelta)
.div(currentGasTarget)
.div(BASE_FEE_MAX_CHANGE_DENOMINATOR)
return currentBaseFeePerGas.add(baseFeePerGasDelta)
} else {
const gasUsedDelta = currentGasTarget.sub(currentGasUsed)
const baseFeePerGasDelta = currentBaseFeePerGas
.mul(gasUsedDelta)
.div(currentGasTarget)
.div(BASE_FEE_MAX_CHANGE_DENOMINATOR)
return currentBaseFeePerGas.sub(baseFeePerGasDelta)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment