Created
October 1, 2021 16:21
-
-
Save botdad/1faa81b90f124379e1dc972a919a57a3 to your computer and use it in GitHub Desktop.
EIP1559 gas math in TS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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