2

Have a code where gas price data provided via gasstation api. Now it works on polygon. Wanted to start this on Arbitrum and Optimism, but can't find any api with gas price. As i understand, the gas on Arbitrum and Optimism has 2 parts, l1 and l2. If anyone knows how to solve this, please help

import got from "got"
import { BigNumber, ethers } from "ethers";
import { CurrencyAmount } from "@uniswap/sdk-core";
import { Pool } from "@uniswap/v3-sdk";
import { WETH_ADDRESS } from "./constants";

interface GasPriceData {
fast:{
maxPriorityFee: number;
maxFee: number;
}
 }

export async function getmaxFeePerGas(): Promise<BigNumber> {
const gasPriceData: GasPriceData = await got("https://gasstation-mainnet.matic.network/v2").json();
return ethers.utils.parseUnits(gasPriceData.fast.maxFee.toFixed(9).toString(), 9);
 }

export async function getmaxPriorityFee(): Promise<BigNumber> {
const gasPriceData: GasPriceData = await got("https://gasstation-mainnet.matic.network/v2").json();
return ethers.utils.parseUnits(gasPriceData.fast.maxPriorityFee.toFixed(9).toString(), 9);
}
Dajeir
  • 51
  • 1

1 Answers1

0

While this solution will not give you the exact same data as the APIs you are currently using, Ethers has built-in gas fee functionality.

const provider = new ethers.providers.JsonRpcProvider($RPC_ENDPOINT);
const feeData = await provider.getFeeData();

This will return an object that looks something like this:

{
  lastBaseFeePerGas: BigNumber { _hex: '0x047c5067ef', _isBigNumber: true },
  maxFeePerGas: BigNumber { _hex: '0x095208fede', _isBigNumber: true },
  maxPriorityFeePerGas: BigNumber { _hex: '0x59682f00', _isBigNumber: true },
  gasPrice: BigNumber { _hex: '0x0488a084b7', _isBigNumber: true }
}

Worth noting that the data returned will vary for different chains, especially L2s. For Optimism, you need to account for both the L1 and L2 gas fees. The gasPrice returned by Ethers will only cover the L2 portion of the fees for the transaction. The L1 fee must be fetched from Optimism's gas price oracle. Optimism's docs have a more detailed explanation.