gmx.events

Documentation for eth_defi.gmx.events Python module.

GMX event log decoding and parsing.

This module provides utilities for decoding GMX protocol events from transaction receipts. GMX emits all events through a centralised EventEmitter contract using EventLog, EventLog1, and EventLog2 event types.

Key features:

  • Decode complex EventLogData structure from transaction logs

  • Extract order execution results (success/failure/frozen)

  • Parse position increase/decrease events with execution prices, PnL, and fees

  • Decode error reasons from failed orders

Example usage:

from web3 import Web3
from eth_defi.gmx.events import (
    decode_gmx_events,
    extract_order_execution_result,
)

# Get transaction receipt
receipt = web3.eth.get_transaction_receipt(tx_hash)

# Decode all GMX events from receipt
events = list(decode_gmx_events(web3, receipt))

# Extract order execution result
result = extract_order_execution_result(web3, receipt)
if result:
    print(f"Order status: {result.status}")
    print(f"Execution price: {result.execution_price}")

For more information on GMX events, see: https://docs.gmx.io/docs/api/contracts#event-monitoring

Module Attributes

GMX_PRICE_PRECISION

GMX price precision (prices are stored with 12 decimal places)

GMX_USD_PRECISION

GMX USD amount precision (USD values use 30 decimal places)

GMX_EVENT_NAMES

Common GMX event names for reference

GMX_ERROR_SELECTORS

GMX error selectors (computed from keccak256("ErrorName(types...)")[:4]) Maps 4-byte selector hex string to (error_name, parameter_types) tuple See: https://github.com/gmx-io/gmx-synthetics/blob/main/contracts/error/Errors.sol

Functions

decode_error_reason(reason_bytes)

Decode GMX error reason from reasonBytes.

decode_gmx_event(web3, log)

Decode a single GMX EventLog from a transaction log entry.

decode_gmx_events(web3, receipt)

Decode all GMX events from a transaction receipt.

extract_order_execution_result(web3, receipt)

Extract order execution result from a keeper transaction receipt.

extract_order_key_from_receipt(web3, receipt)

Extract order key from OrderCreated or OrderExecuted event in receipt.

find_events_by_name(web3, receipt, event_name)

Find all events with a specific name from a transaction receipt.

get_event_name_hash(event_name)

Compute the keccak256 hash of an event name.

Classes

GMXEventData

Parsed GMX event data from EventLogData structure.

OrderExecutionResult

Result of GMX order execution.

OrderFees

Fees from GMX order execution.

get_event_name_hash(event_name)

Compute the keccak256 hash of an event name.

GMX uses the hash of event name strings as topic[1] in EventLog events for efficient filtering.

Parameters

event_name (str) – The event name (e.g., “OrderCreated”, “OrderExecuted”)

Returns

The keccak256 hash as hex string without 0x prefix

Return type

str

GMX_PRICE_PRECISION = 1000000000000

GMX price precision (prices are stored with 12 decimal places)

GMX_USD_PRECISION = 1000000000000000000000000000000

GMX USD amount precision (USD values use 30 decimal places)

GMX_EVENT_NAMES = {'DepositCreated', 'DepositExecuted', 'OrderCancelled', 'OrderCreated', 'OrderExecuted', 'OrderFrozen', 'OrderUpdated', 'PositionDecrease', 'PositionIncrease', 'WithdrawalCreated', 'WithdrawalExecuted'}

Common GMX event names for reference

class GMXEventData

Bases: object

Parsed GMX event data from EventLogData structure.

GMX events contain structured data in the following categories:

  • Address items: Contract addresses (account, market, tokens)

  • Uint items: Unsigned integers (sizes, prices, fees)

  • Int items: Signed integers (PnL, price impact)

  • Bool items: Boolean flags (isLong, etc.)

  • Bytes32 items: Order/position keys

  • Bytes items: Raw byte data (error reasons)

  • String items: String data (reasons)

Each category has both single items and array items.

event_name: str

The event name (e.g., “OrderCreated”, “OrderExecuted”)

msg_sender: Optional[eth_typing.evm.HexAddress]

The message sender (usually a GMX contract)

topic1: bytes | None

Topic1 from EventLog1/EventLog2 (often order key)

topic2: bytes | None

Topic2 from EventLog2 (often account address as bytes32)

address_items: dict[str, eth_typing.evm.HexAddress]

Single address values keyed by name

address_array_items: dict[str, list[eth_typing.evm.HexAddress]]

Array address values keyed by name

uint_items: dict[str, int]

Single uint256 values keyed by name

uint_array_items: dict[str, list[int]]

Array uint256 values keyed by name

int_items: dict[str, int]

Single int256 values keyed by name

int_array_items: dict[str, list[int]]

Array int256 values keyed by name

bool_items: dict[str, bool]

Single bool values keyed by name

bool_array_items: dict[str, list[bool]]

Array bool values keyed by name

bytes32_items: dict[str, bytes]

Single bytes32 values keyed by name

bytes32_array_items: dict[str, list[bytes]]

Array bytes32 values keyed by name

bytes_items: dict[str, bytes]

Single bytes values keyed by name

bytes_array_items: dict[str, list[bytes]]

Array bytes values keyed by name

string_items: dict[str, str]

Single string values keyed by name

string_array_items: dict[str, list[str]]

Array string values keyed by name

get_address(key, default=None)

Get an address item by key.

Parameters
Return type

Optional[eth_typing.evm.HexAddress]

get_uint(key, default=None)

Get a uint item by key.

Parameters
  • key (str) –

  • default (int | None) –

Return type

int | None

get_int(key, default=None)

Get an int item by key.

Parameters
  • key (str) –

  • default (int | None) –

Return type

int | None

get_bool(key, default=None)

Get a bool item by key.

Parameters
  • key (str) –

  • default (bool | None) –

Return type

bool | None

get_bytes32(key, default=None)

Get a bytes32 item by key.

Parameters
  • key (str) –

  • default (bytes | None) –

Return type

bytes | None

get_bytes(key, default=None)

Get a bytes item by key.

Parameters
  • key (str) –

  • default (bytes | None) –

Return type

bytes | None

get_string(key, default=None)

Get a string item by key.

Parameters
  • key (str) –

  • default (str | None) –

Return type

str | None

__init__(event_name, msg_sender=None, topic1=None, topic2=None, address_items=<factory>, address_array_items=<factory>, uint_items=<factory>, uint_array_items=<factory>, int_items=<factory>, int_array_items=<factory>, bool_items=<factory>, bool_array_items=<factory>, bytes32_items=<factory>, bytes32_array_items=<factory>, bytes_items=<factory>, bytes_array_items=<factory>, string_items=<factory>, string_array_items=<factory>)
Parameters
Return type

None

class OrderFees

Bases: object

Fees from GMX order execution.

All fee values are in token amounts (not USD).

position_fee: int

Position fee amount

borrowing_fee: int

Borrowing fee amount

funding_fee: int

Funding fee amount

liquidation_fee: int

Liquidation fee amount (if applicable)

__init__(position_fee=0, borrowing_fee=0, funding_fee=0, liquidation_fee=0)
Parameters
  • position_fee (int) –

  • borrowing_fee (int) –

  • funding_fee (int) –

  • liquidation_fee (int) –

Return type

None

class OrderExecutionResult

Bases: object

Result of GMX order execution.

This dataclass aggregates information from order execution events (OrderExecuted, OrderFrozen, OrderCancelled) and position events (PositionIncrease, PositionDecrease).

order_key: bytes

The order key (32-byte identifier)

status: Literal['executed', 'frozen', 'cancelled']

Execution status

account: Optional[eth_typing.evm.HexAddress]

Account address that owns the order

execution_price: int | None

Execution price (30 decimal precision)

size_delta_usd: int | None

Size delta in USD (30 decimal precision)

size_delta_in_tokens: int | None

Size delta in tokens

collateral_delta: int | None

Collateral delta amount (can be negative for decreases)

pnl_usd: int | None

Realised PnL in USD (30 decimal precision, for decrease orders)

price_impact_usd: int | None

Price impact in USD (30 decimal precision)

fees: eth_defi.gmx.events.OrderFees | None

Execution fees

reason: str | None

Error reason string (for frozen/cancelled orders)

reason_bytes: bytes | None

Raw error reason bytes (for frozen/cancelled orders)

decoded_error: str | None

Decoded error message from reason_bytes

position_key: bytes | None

Position key (if position was modified)

is_long: bool | None

Whether the position is long

__init__(order_key, status, account=None, execution_price=None, size_delta_usd=None, size_delta_in_tokens=None, collateral_delta=None, pnl_usd=None, price_impact_usd=None, fees=None, reason=None, reason_bytes=None, decoded_error=None, position_key=None, is_long=None)
Parameters
Return type

None

decode_gmx_event(web3, log)

Decode a single GMX EventLog from a transaction log entry.

This function handles EventLog, EventLog1, and EventLog2 events emitted by the GMX EventEmitter contract.

Parameters
  • web3 (web3.main.Web3) – Web3 instance

  • log (dict) – A single log entry from transaction receipt

Returns

Parsed GMXEventData or None if not a GMX event

Return type

eth_defi.gmx.events.GMXEventData | None

decode_gmx_events(web3, receipt)

Decode all GMX events from a transaction receipt.

Parameters
  • web3 (web3.main.Web3) – Web3 instance

  • receipt (dict) – Transaction receipt dictionary

Yields

Parsed GMXEventData for each GMX event found

Return type

Iterator[eth_defi.gmx.events.GMXEventData]

find_events_by_name(web3, receipt, event_name)

Find all events with a specific name from a transaction receipt.

Parameters
  • web3 (web3.main.Web3) – Web3 instance

  • receipt (dict) – Transaction receipt dictionary

  • event_name (str) – The event name to filter for (e.g., “OrderExecuted”)

Yields

Matching GMXEventData events

Return type

Iterator[eth_defi.gmx.events.GMXEventData]

GMX_ERROR_SELECTORS: dict[str, tuple[str, list[str]]] = {'0481a15a': ('InvalidOrderPrices', ['uint256', 'uint256', 'uint256', 'uint256']), '08c379a0': ('Error', ['string']), '10811ceb': ('InvalidPositionMarket', []), '109ef850': ('MaxLongExceeded', ['uint256', 'uint256']), '12110872': ('LiquidatablePosition', ['string', 'int256', 'int256', 'int256']), '169f0412': ('MaxPoolUsdForDepositExceeded', ['uint256', 'uint256']), '2159b161': ('InsufficientCollateralUsd', ['int256']), '23090a31': ('InsufficientPoolAmount', ['uint256', 'uint256']), '29ff3fc8': ('MaxPoolAmountExceeded', ['uint256', 'uint256']), '2b6e7c3f': ('MaxPriceAgeExceeded', ['uint256', 'uint256']), '2bf127cf': ('MaxOpenInterestExceeded', ['uint256', 'uint256']), '30779725': ('EmptyOrder', []), '315276c9': ('InsufficientReserve', ['uint256', 'uint256']), '3784f834': ('UnsupportedOrderType', ['uint256']), '3a61a4a9': ('UnableToWithdrawCollateral', ['int256']), '416f9306': ('InsufficientExecutionGas', ['uint256', 'uint256', 'uint256']), '426cfff0': ('PositionNotFound', ['bytes32']), '42c0bc84': ('MinLongTokens', ['uint256', 'uint256']), '4dfbbff3': ('EmptyPosition', []), '59485ed9': ('OrderNotFound', ['bytes32']), '5ba53cd3': ('MaxShortExceeded', ['uint256', 'uint256']), '6514b64e': ('InvalidFeedPrice', ['address', 'int256']), '677abf1c': ('OracleTimestampsAreSmallerThanRequired', ['uint256', 'uint256']), '6ce23460': ('MinMarketTokens', ['uint256', 'uint256']), '730d44b1': ('OrderAlreadyFrozen', []), '74cc815b': ('InsufficientCollateralAmount', ['uint256', 'int256']), '75885d69': ('SwapPriceImpactExceedsAmountIn', ['uint256', 'int256']), '78cd7e7a': ('InsufficientWntAmountForExecutionFee', ['uint256', 'uint256']), '794a604a': ('MaxAutoCancelOrdersExceeded', ['uint256', 'uint256']), '85efb31a': ('MinPositionSize', ['uint256', 'uint256']), '8c617982': ('InsufficientReserveForOpenInterest', ['uint256', 'uint256']), '919dd98a': ('PositionShouldNotBeLiquidated', ['string', 'int256', 'int256', 'int256']), '9319d603': ('OrderValidFromTimeNotReached', ['uint256', 'uint256']), '9c693e4e': ('InvalidCollateralTokenForMarket', ['address', 'address']), '9fbe2cbc': ('InvalidDecreaseOrderSize', ['uint256', 'uint256']), 'a196af45': ('MinShortTokens', ['uint256', 'uint256']), 'a7aebadc': ('InsufficientSwapOutputAmount', ['uint256', 'uint256']), 'a942ab62': ('MaxCollateralSumExceeded', ['uint256', 'uint256']), 'ac504dbb': ('InsufficientExecutionFee', ['uint256', 'uint256']), 'b4a196af': ('MinShortTokens', ['uint256', 'uint256']), 'be2cbc10': ('InvalidDecreaseOrderSize', ['uint256', 'uint256']), 'bff65b3f': ('InvalidPositionSizeValues', ['uint256', 'uint256']), 'c78b78fa': ('DuplicatedMarketInSwapPath', ['address']), 'cc32db99': ('NegativeExecutionPrice', ['int256', 'uint256', 'uint256', 'int256', 'uint256']), 'cd64a025': ('EmptyPrimaryPrice', ['address']), 'd28d3eb5': ('InsufficientOutputAmount', ['uint256', 'uint256']), 'e09ad0e9': ('OrderNotFulfillableAtAcceptablePrice', ['uint256', 'uint256']), 'e234604a': ('MinMarketTokens', ['uint256', 'uint256']), 'f0641c92': ('PriceImpactLargerThanOrderSize', ['int256', 'uint256']), 'f4253177': ('EmptySizeDeltaInTokens', []), 'f442c0bc': ('MinLongTokens', ['uint256', 'uint256']), 'f817118e': ('InvalidTokenIn', ['address', 'address']), 'f8c937db': ('DisabledMarket', ['address']), 'feddc084': ('InvalidKeeperForFrozenOrder', ['address'])}

GMX error selectors (computed from keccak256(“ErrorName(types…)”)[:4]) Maps 4-byte selector hex string to (error_name, parameter_types) tuple See: https://github.com/gmx-io/gmx-synthetics/blob/main/contracts/error/Errors.sol

decode_error_reason(reason_bytes)

Decode GMX error reason from reasonBytes.

GMX uses custom error selectors. This function attempts to decode common error types and their parameters.

Parameters

reason_bytes (bytes) – The raw reasonBytes from OrderFrozen/OrderCancelled events

Returns

Decoded error message with parameters, or None if cannot decode

Return type

str | None

extract_order_execution_result(web3, receipt, order_key=None)

Extract order execution result from a keeper transaction receipt.

This function looks for OrderExecuted, OrderFrozen, or OrderCancelled events and extracts the relevant execution data. For successful orders, it also extracts PositionIncrease/PositionDecrease data.

Parameters
  • web3 (web3.main.Web3) – Web3 instance

  • receipt (dict) – Transaction receipt from keeper execution

  • order_key (bytes | None) – Optional order key to filter for. If not provided, returns the first order event found.

Returns

OrderExecutionResult or None if no order events found

Return type

eth_defi.gmx.events.OrderExecutionResult | None

extract_order_key_from_receipt(web3, receipt)

Extract order key from OrderCreated or OrderExecuted event in receipt.

This function handles both GMX order execution models:

  • Two-phase orders (limit orders): Look for OrderCreated event, order is pending until keeper executes it in a separate transaction.

  • Single-phase orders (market orders): Look for OrderExecuted event, order is created and executed atomically in the same transaction.

Parameters
  • web3 (web3.main.Web3) – Web3 instance

  • receipt (dict) – Transaction receipt from order creation/execution

Returns

The 32-byte order key

Raises

ValueError – If no OrderCreated or OrderExecuted event found in receipt

Return type

bytes