Estimate Transaction Gas with Ethers.js and EIP-1559

Rob
CoinsBench
Published in
4 min readJan 2, 2023

--

👉 Demo code — https://github.com/neznein9/gas-estimation

EIP-1559 has arrived, starting with Ethereum’s London Fork, and continuing out to Layer 2s and other EVM compatible blockchains in the last year. These new transactions set the price of gas differently than we’ve done it in the past, and we need to update our code in order to make sure our users, oracles, and other web3 integrations can (over)pay for priority when necessary.

StableDiff, you doin okay?

In the old days, we could either mock up a transaction and ask the RPC provider to estimate the gas, or else we requested the feeData directly. either of which gave us a current gasPrice on the blockchain.

To switch over to EIP-1559, we’ll throw away the gasPrice parameter and replace it with the following three variables:

Base Fee

A rolling fee that the blockchain raises and lowers to optimize transaction throughput on the network.

Max Priority Fee Per Gas

A gratuity directly from the user to the miner. 💰 ➡ 🚀

Max Fee Per Gas

An upper limit of the previous two added together — the transaction cannot exceed this gas cost.

First Technique: Gas Station

Of the three variables above, the baseFee depends on current blockchain conditions (e.g. gas wars), and the maxPriorityFee is set by the user or dev. From these two values we can calculate the maxFeePerGas, and we’ll have everything required to send a transaction.

We’ll need a gas station. These APIs come in all shapes and sizes, but the easiest to consume are plain REST endpoints. Here are a couple I use:

--

--

Leader of software engineers. Crypto enthusiast. Amateur bicycler.