Inside the GMX Exploit: How a Reentrancy Bug Led to a $42M Loss

GMX is one of the leading decentralized perpetual exchanges in DeFi, enabling users to trade leveraged positions directly on-chain across Arbitrum and Avalanche. In July 2025, GMX suffered a critical exploit that drained approximately $42 million from its V1 protocol, making it one of the most impactful DeFi hacks of the year.
This article provides a technical yet accessible breakdown of the GMX exploit: how the vulnerability worked, the attacker’s step-by-step strategy, the consequences for users and the protocol, also the broader lessons it offers for DeFi security.
GMX maintained two versions of its protocol. V1 was the original design, which used GLP (GMX Liquidity Provider) tokens to represent shares of a liquidity pool backing trader positions. V2, a later upgrade, introduced stricter risk controls and redesigned vault logic. Importantly, the exploit only affected V1.
What is Reentrancy?
Reentrancy is a class of smart contract vulnerability in which an external call allows an attacker to repeatedly re-enter a function before its initial execution is finished. This creates a situation where the contract state is manipulated in unexpected ways.
A classic analogy: imagine paying money from a wallet before updating the balance inside it. If someone can call the withdrawal function again midway, they could keep draining funds before the contract realizes the balance is empty.
The Vulnerability
In V1, GLP tokens represented shares of the protocol’s liquidity pool, and their value depended on Assets Under Management (AUM). AUM itself was influenced not only by deposits and withdrawals but also by the state of global short positions.
Two key design issues created the opening for exploitation:
- Reentrancy in Position Management: When opening a short via increasePosition, the protocol updated the global short size immediately but delayed updating the global short average price (tracked in ShortsTracker).
If a malicious contract re-entered during this gap, it could create positions against stale global averages.
- Immediate AUM Impact from Shorts: Because the global short size was increased instantly, AUM calculations were inflated right away. Since GLP Price = AUM ÷ Total GLP Supply, this boosted GLP valuations artificially.
By exploiting this sequence with Keeper execution and the timelock.enableLeverage mechanism, the attacker rapidly opened large short positions while average prices lagged, driving AUM and thus GLP value to distorted levels. They then redeemed GLP at these manipulated, inflated prices.
The Exploit Walkthrough
Step 1: Set up Funding the Attack
- The attacker funded their malicious contract with collateral (ETH or stablecoins).
- They deposited assets into GMX V1’s liquidity pool and received GLP tokens in return.
- On the surface, this looked like a normal liquidity provision.
Step 2: Keeper Execution & Reentrancy
A. Triggering the Keeper
The attacker submitted a reduce-order, which was later executed by GMX’s Keeper.
During execution, the Keeper enabled leverage via the Timelock.enableLeverage call
B. Refund & Fallback Trigger
- The Keeper refunded collateral (WETH → ETH) to the attacker’s contract.
- The ETH transfer triggered the contract’s fallback function, enabling reentrancy.
C. Opening Shorts During Reentrancy
Inside the fallback, the attacker reentered GMX and deposited 3,001 USDC.
They opened a 30x WBTC short using increasePosition.
Because this was a direct call, globalShortAveragePrices was not updated, leaving prices artificially low.
Step 3: Looping & Draining Value
Each loop: the attacker opened shorts → placed decrease orders → Keeper later executed them.
During execution, globalShortAveragePrices was updated, but only after manipulation had already occurred.
By repeating this cycle, the attacker pushed the global short average price for WBTC down by ~57x.
- Finally, the attacker redeemed GLP at this manipulated price, extracting $42M in assets.
Impact Analysis
The GMX V1 exploit had both immediate financial consequences and longer-term reputational implications for the protocol and users. The attacker successfully drained approximately $42 million in assets from the protocol. Losses included WETH, WBTC, and stablecoins extracted through manipulated GLP redemptions. The exploit impacted liquidity providers (GLP holders) directly, since GLP value is tied to the pool’s AUM. Their tokens were effectively diluted by the inflated redemption payouts.
Impact on Users
Traders: While open positions remained technically intact, the reduction in liquidity worsened slippage and risked destabilizing the trading environment.
Confidence Shock: Retail users who viewed GMX as a “blue-chip” DeFi protocol faced losses or, at best, saw the protocol’s perceived safety evaporate overnight.
GLP Holders: Suffered a reduction in the value of their tokens, as the pool was drained of assets.
Reputational Damage
Erosion of Trust: GMX had been regarded as one of the most battle-tested perpetual exchanges. The exploit exposed fundamental flaws in its V1 design.
Migration Pressure: The incident accelerated migration to GMX V2, which introduced stricter accounting, risk controls, and reentrancy protections.
DeFi Ecosystem Impact: The hack reinforced the narrative that even high-profile, widely audited protocols remain vulnerable, highlighting systemic risks in DeFi infrastructure.
Remediation and Lessons Learned
After the exploit, the GMX team moved quickly to contain the damage:
Disabled Vulnerable Contracts: GLP minting/redemption and position functions in V1 were frozen to prevent further abuse.
Migrated Users to V2: GMX V2, which already had redesigned vault logic and stricter risk controls, was promoted as the safer alternative. Liquidity incentives were shifted to accelerate migration.
Compensation & Communication: The team engaged with the community to clarify the scope of losses. While direct reimbursement was limited, affected users were prioritized in recovery discussions. GMX also worked with security partners to track attacker funds.
Audit Reviews: Postmortem analyses were carried out with external auditors to assess why the vulnerability was missed and to improve future coverage.
Best Practices Against Reentrancy
The exploit highlights how critical it is to defend against reentrancy in every external call path. Developers can follow these safeguards:
Checks-Effects-Interactions (CEI): Always update internal state before transferring tokens or calling external contracts.
Reentrancy Guards: Use mutex locks (e.g., OpenZeppelin’s non-reentrant modifier) to block reentrant calls.
Atomic Accounting: Ensure that critical financial calculations (e.g., AUM, supply, balances) are finalized before value transfers.
Minimal External Calls: Avoid calling untrusted contracts mid-function. If necessary, design with controlled hooks.
Invariant Testing: Run fuzzing and property-based tests to ensure system-wide invariants (e.g., total assets >= total claims) hold under adversarial input.
Advice for Developers and Auditors
Developers should design financial logic with an “attacker mindset.” Any state that can be observed or updated across multiple transactions should be assumed manipulable.
Auditors should explicitly trace for cross-function state dependencies (e.g., global averages, AUM updates) and model them under reentrant conditions.
Protocols should implement defense-in-depth: multiple overlapping safeguards (CEI, reentrancy guards, and circuit breakers) instead of relying on a single design pattern.
What this means for DeFi security
Composability ≠ atomic safety. DeFi prides itself on Lego-like contracts, but GMX V1 shows that cross-contract invariants (vault AUM ↔ shorts tracker ↔ GLP price) can break if they aren’t updated atomically in the same execution context.
Reentrancy is more than “withdraw() twice.” Modern exploit chain capability flips (e.g., enableLeverage), stateful accounting, and refund callbacks to create exploitable windows—even when obvious reentrancy guards exist on user-facing functions.
Global toggles are capability leaks. Any global “ON/OFF” execution flag (leverage enabled, emergency mode, fee holiday) becomes a high-value target if it can be flipped mid-call and observed during external calls.
Oracle-coupled accounting must commit atomically. If AUM or share price depends on price-derived PnL, all dependent fields must update together or not at all. Partial updates create a “phantom value” that can be redeemed.
Push payments to untrusted contracts are dangerous. ETH refunds or token transfers mid-critical path invite fallback-based reentrancy. Prefer pull patterns (users withdraw later) or constrained callbacks with allowlists and reentrancy domains.
Audits must test flows, not functions. Keeper/executor paths, scheduled orders, and cross-contract mutations need adversarial, stateful fuzzing—not just line-by-line reviews.
Runtime defenses matter. Circuit breakers for abnormal GLP price jumps, short-size deltas, or AUM spikes can halt drains even when logic has bugs.
Where similar bugs may hide
Tokenized vaults & yield aggregators that compute share price from AUM while allowing mid-call external interactions (refunds, strategy calls, hooks). If share/asset math isn’t 4626-like and atomic, redemption manipulation is possible.
Perpetuals and margin systems with separate “position size” and “average entry price” variables. If one updates instantly and the other lags (especially across contracts), PnL-dependent accounting can be gamed.
Order-book/keeper architectures that:
Temporarily elevate privileges (global leverage/fee toggles),
Perform push refunds in ETH/tokens mid-execution.
Accept user-provided callback recipients.
This trio recreates the GMX pattern.
AMMs with hooks/callbacks (e.g., swap hooks, onFlashLoan) that adjust fees, oracles, or reserves after calling out. If reserve/price updates aren’t CEI-aligned, attackers can reenter with stale reserves.
Cross-chain accounting (bridges, omnichain vaults) where local AUM/share supply is updated ahead of remote settlement. Timing gaps can be exploited to mint/redeem against inflated accounting.
Liquid staking/LSDFi wrappers that compute exchange rates from oracle-driven PnL. If rebase or exchange-rate updates lag deposits/withdrawals, the “who owns the gain/loss” boundary can be abused.
Any protocol using global execution toggles (pause/enable features) inside user flows instead of governance-only, time-delayed changes.
Practical takeaways for the ecosystem
Design: Remove global toggles from hot paths; scope capabilities to this order only. Batch all accounting updates into a single commit; abort on any failure—no partial state.
Engineering: Enforce checks–effects–interactions rigorously; adopt pull payments; apply non-reentrant on keeper/executor/refund paths; create a cross-contract reentrancy domain (mutex) for critical flows.
Testing: Write stateful fuzzers that simulate keeper execution, flashloans, callbacks, and MEV timing.
Operations: Deploy anomaly monitors for AUM/price deltas per block; auto-trigger circuit breakers that pause mint/redeem or keeper actions when thresholds breach.
Auditing: Treat economic invariants as first-class: Prove that no sequence of external calls can realize PnL or AUM before all dependent state commits.
Conclusion
The GMX V1 cross-contract reentrancy exploit was a reminder that even the most respected protocols in DeFi can harbor latent design flaws when accounting, execution, and external calls are not perfectly aligned. A single gap between state updates and refunds cascaded into a $42M loss, shaking trust in a “blue-chip” protocol and underscoring how unforgiving smart contract logic can be.
As DeFi evolves, so too will the attackers. Protocol builders, auditors, and researchers must assume adversaries will chain together subtle capability flips, stale state, and keeper/executor paths in ways that audits alone may not anticipate. The GMX exploit should serve as both a warning and a call to action: rigorous testing, adversarial modeling, and real-time anomaly detection are no longer optional.
The permissionless finance promises of Defi rests on the strength of its security. To protect users and preserve trust, the ecosystem must keep raising the bar, learning from each exploit, closing every gap, and treating security research as a continuous, collective responsibility.
Subscribe to my newsletter
Read articles from Adesola aka Draymond directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
