Firstly, I'd like to say that the third top answer and second top answer are correct but vague. The top answer also implicitly relies on the use of a Contract and a DefaultProvider which is not ideal because a custom provider is much more practical, and you don't always have a Contract to rely on for estimating gas. I had some difficulty with the migration so I am going to share a working example here for everyone.
If you're using TypeScript, the import should look like this:
import { ethers } from "ethers";
To create a provider, you can use the following line:
const provider = new ethers.JsonRpcProvider("some_provider_url");
As the other answers suggested, you can use provider#getFeeData():
const feeData = await provider.getFeeData();
I also had issues processing the output, but instead of using ethers.utils.formatUnits, we now use ethers.formatUnits:
// These are not in a very useful format
let gasPrice = feeData.gasPrice;
let maxFeePerGas = feeData.maxFeePerGas;
let maxPriorityFeePerGas = feeData.maxPriorityFeePerGas;
// Convert the gas price from Wei to Gwei or Ether for better readability
const gasPriceInEth = ethers.formatUnits(gasPrice, 'ether');
const gasPriceInGwei = ethers.formatUnits(gasPrice, 'gwei');
const gasPriceInWei = ethers.formatUnits(gasPrice, 'wei');
Should be more than enough to help anyone else with migration issues as well.
estimateGasmethod but that returns the "units of gas that would be required". In order to arrive at the transaction fee, don't I need both units of gas AND the gas price? https://ethereum.stackexchange.com/questions/19665/how-to-calculate-transaction-fee – Sam Richards Jun 02 '21 at 21:58getGasPricefunction. – Paul Razvan Berg Jun 03 '21 at 09:43ERC20: transfer from the zero address. When you create the erc20 variable you will need a signer, also the signer must have at least the amount you want to send as balance. If you want to use the default provider, you have to override thefromattribute. – gabkov Feb 17 '23 at 14:13