gmx.gas_monitor

Documentation for eth_defi.gmx.gas_monitor Python module.

GMX Gas Monitoring Module.

This module provides comprehensive gas monitoring for GMX trading operations, including: - Balance monitoring with configurable warning and critical thresholds - Gas estimation with safety buffers - USD cost calculation using GMX oracle prices - Graceful failure handling for out-of-gas scenarios

Example usage:

from eth_defi.gmx.gas_monitor import GasMonitorConfig, GMXGasMonitor

# Configure thresholds
config = GasMonitorConfig(
    warning_threshold_usd=10.0,
    critical_threshold_usd=2.0,
    raise_on_critical=False,
)

# Create monitor
monitor = GMXGasMonitor(web3, chain="arbitrum", config=config)

# Check balance
result = monitor.check_gas_balance(wallet_address)
if result.status == "critical":
    print(f"Critical: {result.message}")

Functions

create_gas_monitor_config_from_env()

Create GasMonitorConfig from environment variables.

Classes

GMXGasMonitor

Gas monitoring for GMX trading operations.

GasCheckResult

Result of a gas balance check.

GasEstimate

Gas estimation result with cost breakdown.

GasMonitorConfig

Configuration for gas monitoring.

TradeExecutionResult

Result of a trade execution attempt.

Exceptions

InsufficientGasError

Raised when gas balance is critically low and raise_on_critical is True.

class GasMonitorConfig

Bases: object

Configuration for gas monitoring.

Parameters
  • warning_threshold_usd – Balance threshold (USD) below which a warning is logged

  • critical_threshold_usd – Balance threshold (USD) below which trades may be rejected

  • enabled – Whether gas monitoring is active

  • raise_on_critical – If True, raise exception on critical; if False, return failed result

  • gas_estimate_buffer – Multiplier applied to gas estimates (e.g., 1.2 = 20% buffer)

__init__(warning_threshold_usd=1.0, critical_threshold_usd=0.5, enabled=True, raise_on_critical=False, gas_estimate_buffer=1.2)
Parameters
  • warning_threshold_usd (float) –

  • critical_threshold_usd (float) –

  • enabled (bool) –

  • raise_on_critical (bool) –

  • gas_estimate_buffer (float) –

Return type

None

class GasCheckResult

Bases: object

Result of a gas balance check.

Parameters
  • passed – Whether the balance is sufficient for trading

  • native_balance_wei – Raw balance in wei

  • native_balance – Balance in native token units (ETH/AVAX)

  • native_price_usd – Current price of native token in USD (None if unavailable)

  • balance_usd – Balance value in USD (None if price unavailable)

  • status – Status level - ‘ok’, ‘warning’, or ‘critical’

  • message – Human-readable status message

__init__(passed, native_balance_wei, native_balance, native_price_usd, balance_usd, status, message)
Parameters
Return type

None

class GasEstimate

Bases: object

Gas estimation result with cost breakdown.

Parameters
  • raw_gas_limit – Raw estimate from web3.eth.estimate_gas()

  • gas_limit – Final estimate after buffer applied

  • safety_buffer – Buffer multiplier that was applied (e.g., 1.2)

  • gas_price_wei – Current gas price in wei

  • estimated_cost_wei – Estimated total cost in wei

  • estimated_cost_native – Estimated cost in native token units

  • native_price_usd – Current price of native token in USD (None if unavailable)

  • estimated_cost_usd – Estimated cost in USD (None if price unavailable)

__init__(raw_gas_limit, gas_limit, safety_buffer, gas_price_wei, estimated_cost_wei, estimated_cost_native, native_price_usd, estimated_cost_usd)
Parameters
  • raw_gas_limit (int) –

  • gas_limit (int) –

  • safety_buffer (float) –

  • gas_price_wei (int) –

  • estimated_cost_wei (int) –

  • estimated_cost_native (decimal.Decimal) –

  • native_price_usd (float | None) –

  • estimated_cost_usd (float | None) –

Return type

None

class TradeExecutionResult

Bases: object

Result of a trade execution attempt.

Provides comprehensive information about trade outcome, including success/failure status, gas costs, and any error information. This allows graceful handling of failures without crashing.

Parameters
  • success – Whether the trade was executed successfully

  • status – Status code - ‘executed’, ‘failed’, or ‘rejected’

  • reason – Failure reason if not successful - ‘out_of_gas’, ‘reverted’, ‘critical_balance’, etc.

  • tx_hash – Transaction hash if submitted (None if rejected before submission)

  • receipt – Transaction receipt if confirmed (None otherwise)

  • order_result – The original OrderResult that was attempted

  • gas_check – Pre-trade gas balance check result

  • gas_used – Actual gas used (from receipt, None if not executed)

  • gas_cost_native – Actual gas cost in native token (None if not executed)

  • gas_cost_usd – Actual gas cost in USD (None if not executed or price unavailable)

  • error_message – Detailed error message if failed

__init__(success, status, reason, tx_hash, receipt, order_result, gas_check, gas_used, gas_cost_native, gas_cost_usd, error_message)
Parameters
Return type

None

exception InsufficientGasError

Bases: Exception

Raised when gas balance is critically low and raise_on_critical is True.

Initialise with message and gas check result.

Parameters
  • message – Error message

  • gas_check – The gas check result that triggered the error

__init__(message, gas_check)

Initialise with message and gas check result.

Parameters
__new__(**kwargs)
add_note()

Exception.add_note(note) – add a note to the exception

with_traceback()

Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.

class GMXGasMonitor

Bases: object

Gas monitoring for GMX trading operations.

Provides balance checking, gas estimation, and logging for GMX trades. Integrates with GMX oracle for USD price calculations.

Parameters
  • web3 – Web3 instance connected to the blockchain

  • chain – Chain name (‘arbitrum’, ‘avalanche’, ‘arbitrum_sepolia’)

  • config – Optional gas monitor configuration

Initialise the gas monitor.

Parameters
  • web3 – Web3 instance connected to the blockchain

  • chain – Chain name (e.g., ‘arbitrum’, ‘avalanche’)

  • config – Gas monitoring configuration (uses defaults if None)

__init__(web3, chain, config=None)

Initialise the gas monitor.

Parameters
  • web3 (web3.main.Web3) – Web3 instance connected to the blockchain

  • chain (str) – Chain name (e.g., ‘arbitrum’, ‘avalanche’)

  • config (eth_defi.gmx.gas_monitor.GasMonitorConfig | None) – Gas monitoring configuration (uses defaults if None)

property oracle_prices

Lazy-load oracle prices client.

get_native_token_price_usd()

Fetch the native token (ETH/AVAX) price from GMX oracle.

Returns

Price in USD, or None if unavailable

Return type

float | None

check_gas_balance(wallet_address)

Check wallet gas balance against configured thresholds.

Parameters

wallet_address (Union[eth_typing.evm.HexAddress, str]) – Address to check balance for

Returns

GasCheckResult with status and balance information

Return type

eth_defi.gmx.gas_monitor.GasCheckResult

estimate_transaction_gas(tx, from_addr)

Estimate gas for a transaction with safety buffer.

Parameters
Returns

GasEstimate with raw and buffered values

Return type

eth_defi.gmx.gas_monitor.GasEstimate

log_gas_estimate(estimate, operation)

Log gas estimate details for an operation.

Parameters
Return type

None

log_gas_usage(receipt, native_price_usd, operation, estimated_gas=None)

Log actual gas used after transaction confirmation.

Parameters
  • receipt (dict) – Transaction receipt

  • native_price_usd (float | None) – Current native token price in USD

  • operation (str) – Description of the operation

  • estimated_gas (int | None) – Original gas estimate for efficiency calculation

Returns

Tuple of (gas_cost_native, gas_cost_usd)

Return type

tuple[decimal.Decimal, float | None]

log_gas_check_warning(gas_check)

Log a warning for low gas balance.

Parameters

gas_check (eth_defi.gmx.gas_monitor.GasCheckResult) – The gas check result to log

Return type

None

create_gas_monitor_config_from_env()

Create GasMonitorConfig from environment variables.

Environment variables: - GMX_GAS_WARNING_THRESHOLD_USD: Warning threshold in USD (default: 10.0) - GMX_GAS_CRITICAL_THRESHOLD_USD: Critical threshold in USD (default: 2.0) - GMX_GAS_MONITOR_ENABLED: Whether monitoring is enabled (default: true) - GMX_GAS_ESTIMATE_BUFFER: Gas estimate buffer multiplier (default: 1.2) - GMX_GAS_RAISE_ON_CRITICAL: Whether to raise on critical (default: true)

Returns

Configured GasMonitorConfig instance

Return type

eth_defi.gmx.gas_monitor.GasMonitorConfig