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 (prices are stored with 12 decimal places) |
|
GMX USD amount precision (USD values use 30 decimal places) |
|
Common GMX event names for reference |
|
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 GMX error reason from reasonBytes. |
|
Decode a single GMX EventLog from a transaction log entry. |
|
Decode all GMX events from a transaction receipt. |
|
Extract order execution result from a keeper transaction receipt. |
|
Extract order key from OrderCreated or OrderExecuted event in receipt. |
|
Find all events with a specific name from a transaction receipt. |
|
Compute the keccak256 hash of an event name. |
Classes
Parsed GMX event data from EventLogData structure. |
|
Result of GMX order execution. |
|
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.
- 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:
objectParsed 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.
- msg_sender: Optional[eth_typing.evm.HexAddress]
The message sender (usually a GMX contract)
- 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
- get_address(key, default=None)
Get an address item by key.
- Parameters
key (str) –
default (Optional[eth_typing.evm.HexAddress]) –
- Return type
- get_uint(key, default=None)
Get a uint item by key.
- get_int(key, default=None)
Get an int item by key.
- get_bool(key, default=None)
Get a bool item by key.
- get_bytes32(key, default=None)
Get a bytes32 item by key.
- get_bytes(key, default=None)
Get a bytes item by key.
- get_string(key, default=None)
Get a string item by key.
- __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
event_name (str) –
msg_sender (Optional[eth_typing.evm.HexAddress]) –
topic1 (bytes | None) –
topic2 (bytes | None) –
address_items (dict[str, eth_typing.evm.HexAddress]) –
address_array_items (dict[str, list[eth_typing.evm.HexAddress]]) –
- Return type
None
- class OrderFees
Bases:
objectFees from GMX order execution.
All fee values are in token amounts (not USD).
- class OrderExecutionResult
Bases:
objectResult of GMX order execution.
This dataclass aggregates information from order execution events (OrderExecuted, OrderFrozen, OrderCancelled) and position events (PositionIncrease, PositionDecrease).
- status: Literal['executed', 'frozen', 'cancelled']
Execution status
- account: Optional[eth_typing.evm.HexAddress]
Account address that owns the order
- fees: eth_defi.gmx.events.OrderFees | None
Execution fees
- __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
order_key (bytes) –
status (Literal['executed', 'frozen', 'cancelled']) –
account (Optional[eth_typing.evm.HexAddress]) –
execution_price (int | None) –
size_delta_usd (int | None) –
size_delta_in_tokens (int | None) –
collateral_delta (int | None) –
pnl_usd (int | None) –
price_impact_usd (int | None) –
fees (eth_defi.gmx.events.OrderFees | None) –
reason (str | None) –
reason_bytes (bytes | None) –
decoded_error (str | None) –
position_key (bytes | None) –
is_long (bool | None) –
- 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
- 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
- find_events_by_name(web3, receipt, event_name)
Find all events with a specific name from a transaction receipt.
- Parameters
- Yields
Matching GMXEventData events
- Return type
- 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.
- 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
- Returns
OrderExecutionResult or None if no order events found
- Return type
- 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