added better error handling for gasnow cache

This commit is contained in:
Alexander 2024-07-13 07:22:50 -04:00
parent 4bf1099d70
commit dfdd849fc6

View file

@ -5,6 +5,7 @@ import os
import random import random
import sys import sys
import time import time
from json import JSONDecodeError
from logging.handlers import TimedRotatingFileHandler from logging.handlers import TimedRotatingFileHandler
from statistics import median, mean, mode from statistics import median, mean, mode
@ -366,8 +367,10 @@ def get_beacon_gas_prices(speed=None, cache_interval_seconds=10):
speeds = ('rapid', 'fast', 'standard', 'slow',) speeds = ('rapid', 'fast', 'standard', 'slow',)
os.makedirs(cache_folder := './data/cache/', exist_ok=True) os.makedirs(cache_folder := './data/cache/', exist_ok=True)
gas = {} gas = {}
if os.path.isfile(gasnow_file := "{}/gasnow.json".format(cache_folder)): try:
gas = json.load(open(gasnow_file)) gas = json.load(open(gasnow_file := "{}/gasnow.json".format(cache_folder)))
except (JSONDecodeError, FileNotFoundError):
pass
if not gas or not gas['data'] or (gas['data']['timestamp'] / 1000) + cache_interval_seconds < time.time(): if not gas or not gas['data'] or (gas['data']['timestamp'] / 1000) + cache_interval_seconds < time.time():
try: try:
r = requests.get('https://beacon.pulsechain.com/api/v1/execution/gasnow') r = requests.get('https://beacon.pulsechain.com/api/v1/execution/gasnow')
@ -382,7 +385,7 @@ def get_beacon_gas_prices(speed=None, cache_interval_seconds=10):
return 5555 * 10 ** 369 return 5555 * 10 ** 369
elif _gas['data']: elif _gas['data']:
gas = _gas gas = _gas
open('./data/cache/gasnow.json', 'w').write(json.dumps(gas, indent=4)) open(gasnow_file, 'w').write(json.dumps(gas, indent=4))
if type(speed) is str: if type(speed) is str:
try: try:
return float(web3.from_wei(gas['data'][speed], 'gwei')) return float(web3.from_wei(gas['data'][speed], 'gwei'))