get_average_gas_prices

Function

def get_average_gas_prices(average='median', tx_amount=100, attempts=18):
    if not (latest_block := get_block('latest', False, attempts)):
        return {}
    else:
        latest_block = latest_block['number']
    gas_limit = []
    gas_prices = []
    for block_number in range(latest_block, latest_block - tx_amount, -1):
        if not (block := get_block(block_number, True)):
            return {}
        for _tx in block['transactions']:
            gas_limit.append(_tx['gas'])
            gas_prices.append(_tx['gasPrice'])
        if len(gas_prices) >= tx_amount:
            break
    match average:
        case 'mean':
            average_gas_limit = mean(gas_limit[:tx_amount])
            average_gas_price = mean(gas_prices[:tx_amount])
        case 'median':
            average_gas_limit = median(gas_limit[:tx_amount])
            average_gas_price = median(gas_prices[:tx_amount])
        case 'mode':
            average_gas_limit = mode(gas_limit[:tx_amount])
            average_gas_price = mode(gas_prices[:tx_amount])
        case _:
            raise Exception('Invalid average type')
    return {
        "gas_limit": average_gas_limit,
        "gas_price": average_gas_price
    }

Description

  • Get the latest block number

  • Loop each block starting from latest

  • Sample the gas/price for at least 1 transaction

  • Loop until transaction amount is satisfied

  • Calculate the average gas prices

  • Return a dictionary with gas_limit and gas_price averages