Fetching Gas Prices Script
This script handles the process of fetching gas prices for hedger transactions from different sources, checks for errors, and ensures the gas price does not exceed a specified upper bound.
Full Script:
__get_gas_from_metaswap
Function Definition and Parameters:
This function is designed to retrieve gas price information from the Metamask Gas API. It takes two parameters:
priority
: The priority level of the transaction, which will determine the gas fee structure to use (low, medium, high).gas_upper_bound
: The maximum allowable gas price for the transaction.
Gas Provider URL:
Constructs the URL to fetch gas price information from the Metamask Gas API for the specific blockchain network identified by self.chain_id
.
Initialize Response:
Initializes the variable resp
to None
. This will later be used to store the response from the API request.
Fetching and Processing Data:
Attempts to send a GET request to the gas_provider
URL with a specified timeout (RequestTimeout
). The response from this request is stored in resp
,then converts the response from the API into JSON format, which allows for easy access to the data fields within the response.
Extract Gas Fees:
Extracts the suggested maximum fee per gas unit (suggestedMaxFeePerGas) and the suggested maximum priority fee per gas unit (Decimal) from the JSON response, converting these values to Decimal.
Log Span Label:
Logs the extracted gas fee information using apm.span_label for monitoring purposes. This includes the maximum fee per gas, the maximum priority fee per gas, and the URL of the gas price provider.
Check Upper Bound:
Checks if the max_fee_per_gas
exceeds the specified gas_upper_bound
. If it does, raises an OutOfRangeTransactionFee
exception with a descriptive message.
Prepare Gas Parameters:
If the gas fee is within the acceptable range, this prepares a dictionary gas_params containing the gas fee values converted to Wei (a smaller unit of Ether) using Web3.to_wei, then returns the gas_params dictionary.
Exception Handling:
Handles potential exceptions that might occur during the process:
RequestException
: General exception for request issues.JSONDecodeError
: Issue decoding the JSON response.KeyError
: If the expected keys are not present in the JSON response.
If an exception occurs, logs the error (unless in development environment DevEnv) and raises a FailedToGetGasPrice exception with an appropriate message.
__get_gas_from_rpc
Function Definition and Parameters:
This function is a private method to get gas prices from an RPC provider. It takes priority and gas_upper_bound as parameters.
Initialize Gas Price:
Initializes the gas price variable to None.
Loop Through Providers:
Iterates through available RPC providers to fetch the gas price. If it fails for a provider, logs the error and continues to the next one. Also logs the gas fees and provider URL for tracing purposes with apm.span_label
Check Gas Price:
If a gas price was retrieved, the function checks whether this price divided by 1e9 (to convert from wei to GWei) exceeds the gas_upper_bound
. If it does, it raises an exception for exceeding the specified gas price limit.
Return Gas Parameters:
Finally, the function returns a dictionary with a single key-value pair. The key is gasPrice, and the value is the fetched gas_price adjusted by a priority multiplier. This multiplier adjusts the gas price based on the transaction priority, allowing for some dynamic control over how much to pay per transaction.
__get_gas_price
Function Definition and Parameters:
This function fetches the gas price based on the specified gas_upper_bound and priority.
Initialize Gas Parameters:
Initializes an empty dictionary gas_params
to store the gas price parameters.
Conditional Check for Test BNB Network
Checks if the chain_id
is 97, which corresponds to the Test BNB Network. If true, it sets the gasPrice to 10.1 GWei (converted to Wei) directly in the gas_params dictionary.
Conditional Check for Development Environment or Specific Chains
If the code is running in a development environment (DevEnv) or if the chain_id
is in the ChainIdsWithGasFromRPC
list, it fetches the gas price from RPC providers by calling the __get_gas_from_rpc
method with the specified priority and gas_upper_bound
.
Attempt to Get Gas Price from Metamask Swap API
If the previous conditions are not met, it attempts to fetch the gas price from MetaSwap using the __get_gas_from_metaswap
method. If this attempt fails and raises a FailedToGetGasPrice
exception, it falls back to fetching the gas price from RPC providers using the __get_gas_from_rpc
method.
Logging the Gas Parameters
Logs the gas price parameters using for monitoring purposes. The **gas_params syntax unpacks the dictionary so that each key-value pair in gas_params is passed as a separate keyword argument.
Returning the Gas Parameters
Returns the gas_params dictionary to the caller.
Summary:
The _get_gas_price
function is designed to determine and return the appropriate gas price parameters for a transaction. It first checks if the network is the Test BNB Network, in which case it directly sets the gas price. If the environment is a development environment or the chain ID is in a specific list, it fetches the gas price from RPC providers. Otherwise, it tries to fetch the gas price from MetaSwap and falls back to RPC providers if that fails.
Last updated