import axios from 'axios'; import { providers } from 'ethers'; // class to fetch gas station parameter // This class returns the gas in gwei export class GasStation { private maticGasStationUrl: string; private mumbaiGasStationUrl: string; private chainId: number; private provider: providers.Provider; constructor(provider: providers.Provider) { this.maticGasStationUrl = 'https://gasstation-mainnet.matic.network/v2'; this.mumbaiGasStationUrl = 'https://gasstation-mumbai.matic.today/v2'; this.provider = provider; } // fetch gas station parameters public async fetchGasStationParameters( chainId: number, ): Promise { let url: string | null = null; // select the gas station url based on the chain id if (chainId === 137) { url = this.maticGasStationUrl; } else if (this.chainId === 80001) { url = this.mumbaiGasStationUrl; } // if url is available in case of polygon based chains if (url) { const response = await axios({ method: 'get', url: url, }).then((response) => { return response.data; }); // gas parameters in gwei const gasStationParameters = new GasStationParameters( response.safeLow, response.standard, response.fast, ); return gasStationParameters; } else { // fetch the gas params from the current block return await this.fetchGasParamsFromBlock(); } } // get latest parameter in gwei private async fetchGasParamsFromBlock(): Promise { const block: providers.FeeData = await this.provider.getFeeData(); // convert block gas params from wei to gwei const gasParams: GasParam = { maxPriorityFee: block.maxPriorityFeePerGas?.div('1000000000').toNumber() || 0, maxFee: block.maxFeePerGas?.div('1000000000').toNumber() || 0, }; const gasStationParameters = new GasStationParameters( gasParams, gasParams, gasParams, ); return gasStationParameters; } } export interface GasParam { maxPriorityFee: number; maxFee: number; } // gas station parameters export class GasStationParameters { public safelow: GasParam; public standard: GasParam; public fast: GasParam; constructor(safelow: GasParam, standard: GasParam, fast: GasParam) { this.safelow = safelow; this.standard = standard; this.fast = fast; } }