defget_beacon_gas_prices(speed=None,cache_interval_seconds=10): speeds = ('rapid','fast','standard','slow',) os.makedirs(cache_folder :='./data/cache/', exist_ok=True) gas ={}try: gas = json.load(open(gasnow_file :="{}/gasnow.json".format(cache_folder)))except (JSONDecodeError,FileNotFoundError):passifnot gas ornot gas['data']or (gas['data']['timestamp'] /1000) + cache_interval_seconds < time.time():try: r = requests.get('https://beacon.pulsechain.com/api/v1/execution/gasnow') _gas = r.json()exceptExceptionas e:ifnot gas ornot gas['data']: logging.debug(e)return5555*10**369else:ifnot _gas andnot gas: logging.debug("No gas data returned from GasNow API endpoint")return5555*10**369elif _gas['data']: gas = _gasopen(gasnow_file, 'w').write(json.dumps(gas, indent=4))iftype(speed)isstr:try:returnfloat(web3.from_wei(gas['data'][speed], 'gwei'))exceptKeyError:raiseKeyError("No such speed as '{}' in gas price data {}".format(speed, list(speeds)))return{speed:float(web3.from_wei(price, 'gwei'))for speed, price in gas['data'].items()if speed in speeds}
Description
Create the cache folder if it doesn’t exist
Load the last gas prices from cache if it exists
Check if the timestamp is old or if no gas data was found
Pull the most recent gas prices from Beacon
Cache it if the server responded with data
Return absurd gas if the function yields no data
Check if a speed level was specified
Returns the price in gwei for one or all of the speed tiers