custom-gas-station.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. import {
  2. type CustomGasChainId,
  3. type TxSpeed,
  4. verifyValidOption,
  5. txSpeeds,
  6. customGasChainIds,
  7. } from "../utils.js";
  8. import type { Logger } from "pino";
  9. import { parseGwei } from "viem";
  10. type chainMethods = Record<CustomGasChainId, () => Promise<bigint | undefined>>;
  11. export class CustomGasStation {
  12. private chain: CustomGasChainId;
  13. private speed: TxSpeed;
  14. private chainMethods: chainMethods = {
  15. 137: this.fetchMaticMainnetGasPrice.bind(this),
  16. };
  17. private logger: Logger;
  18. constructor(logger: Logger, chain: number, speed: string) {
  19. this.logger = logger;
  20. this.speed = verifyValidOption(speed, txSpeeds);
  21. this.chain = verifyValidOption(chain, customGasChainIds);
  22. }
  23. async getCustomGasPrice() {
  24. return this.chainMethods[this.chain]();
  25. }
  26. private async fetchMaticMainnetGasPrice() {
  27. try {
  28. const res = await fetch("https://gasstation.polygon.technology/v2");
  29. // TODO: improve the typing specificity here
  30. const jsonRes = (await res.json()) as any;
  31. const gasPrice = jsonRes[this.speed].maxFee;
  32. return parseGwei(gasPrice.toFixed(2));
  33. } catch (err) {
  34. this.logger.error(
  35. err,
  36. "Failed to fetch gas price from Matic mainnet. Returning undefined",
  37. );
  38. return undefined;
  39. }
  40. }
  41. }
  42. export function getCustomGasStation(
  43. logger: Logger,
  44. customGasStation?: number,
  45. txSpeed?: string,
  46. ) {
  47. if (customGasStation && txSpeed) {
  48. return new CustomGasStation(logger, customGasStation, txSpeed);
  49. }
  50. return;
  51. }