Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
Free 30-min Web3 Consultation
Book Consultation
Smart Contract Security Audits
View Audit Services
Custom DeFi Protocol Development
Explore DeFi
Full-Stack Web3 dApp Development
View App Services
LABS
Glossary

StableSwap Invariant Attack

A StableSwap invariant attack is an exploit that manipulates the specialized bonding curve of an AMM, like Curve Finance, to drain liquidity from stablecoin pools.
Chainscore © 2026
definition
SECURITY VULNERABILITY

What is a StableSwap Invariant Attack?

An exploit targeting the mathematical formula governing liquidity in automated market makers designed for stablecoins.

A StableSwap invariant attack is a type of financial exploit that manipulates the bonding curve of an automated market maker (AMM) to drain liquidity pools, specifically targeting the specialized constant product and constant sum formulas used by protocols like Curve Finance. The attack exploits the precise mathematical relationship, or invariant, that balances asset prices within a pool. By executing a series of large, imbalanced trades, an attacker can temporarily push the pool's reserves far from their equilibrium peg, creating a massive arbitrage opportunity that is then captured by the attacker themselves, often using a flash loan, to extract value at the expense of other liquidity providers.

The core vulnerability lies in the amplification coefficient (A) parameter used in StableSwap invariant formulas such as StableSwap and Curve v1. This coefficient is designed to create a "flatter" curve within a narrow price range around the peg (e.g., $0.99 to $1.01 for stablecoins), providing extremely low slippage for normal trades. However, if an attacker can force the pool's composition beyond this optimized "flat" region, the curve's behavior reverts sharply to a standard constant product curve (like Uniswap's x * y = k), resulting in catastrophic price impact. The attacker's profit is the difference between the artificially depressed price they create and the actual market price.

A canonical example is the March 2023 attack on the pETH-ETH pool on Curve Finance. The attacker used a flash loan to deposit a massive amount of one asset (pETH), drastically skewing the pool's balance. This pushed the invariant calculation into the high-slippage zone of the curve, making the other asset (ETH) artificially cheap within the pool. The attacker then swapped a small amount to buy this undervalued ETH, before repaying the flash loan and keeping the profit, which amounted to millions of dollars. The attack was possible due to a vulnerability in the pool's price oracle, which failed to accurately reflect pETH's true market value, allowing the invariant to be gamed.

To mitigate such attacks, modern AMM designs have implemented several safeguards. Curve v2 introduced the internal price repeg mechanism and a dynamic A parameter that adjusts based on pool balance, making it harder to push the pool into imbalanced states. Other defenses include oracle-based guards that reject trades if the implied price deviates too far from a trusted external oracle, circuit breakers that halt trading during extreme volatility, and more robust liquidity provider fee structures that increase during periods of imbalance to penalize manipulative trades. Understanding the invariant's mathematical properties is crucial for both protocol designers and liquidity providers assessing risk.

key-features
MECHANICAL BREAKDOWN

Key Features of the Attack

The StableSwap Invariant Attack exploits the mathematical assumptions of a specific AMM bonding curve, allowing an attacker to drain liquidity by manipulating the pool's internal price.

01

Exploiting the Invariant Curve

The attack targets the StableSwap invariant, a hybrid function designed for stablecoin pairs that approximates a constant sum (low slippage) near the peg but behaves like a constant product (Uniswap v2) far from it. The attacker identifies a flaw where large, imbalanced trades can be executed with minimal slippage due to miscalculated fees or rounding errors within the curve's implementation, enabling arbitrage-free extraction of value.

02

The Donation Vector

A critical precursor step involves donating a large amount of a single token to the liquidity pool. This artificially skews the pool's reserves, dramatically altering the effective exchange rate for subsequent swaps. The donation manipulates the pool's internal state so that a follow-up trade in the opposite direction yields a disproportionately large output, effectively returning the donated tokens plus a significant portion of the pool's other assets.

03

Price Manipulation & Slippage

The attack does not rely on external oracle price feeds. Instead, it manipulates the pool's internal spot price by exploiting the invariant's mathematical properties. The manipulated state causes the AMM to misprice assets, allowing the attacker to swap tokens at a highly favorable rate with abnormally low slippage, contrary to the curve's intended behavior for such an imbalanced trade.

04

Flash Loan Dependency

These attacks are typically executed within a single transaction using flash loans. The attacker borrows millions in capital to fund the initial donation and large swap, repaying the loan at the end of the transaction. This requires zero upfront capital and makes the attack economically feasible, as seen in incidents like the Curve Finance exploit of July 2023.

05

Vulnerable Pool Conditions

Not all StableSwap pools are vulnerable. The exploit requires specific conditions:

  • An implementation bug in the invariant's fee calculation or precision handling.
  • Use of a vulnerable Vyper compiler version (as in the 2023 Curve incident).
  • A pool with significant liquidity to make the attack profitable after flash loan fees.
  • Low network congestion to ensure transaction atomicity.
06

Post-Attack Arbitrage

After the attack drains value, the pool is left in a severely imbalanced state. This creates a massive arbitrage opportunity for other bots to rebalance the pool back to the market price, profiting from the discrepancy. This secondary activity can partially recover some losses for LPs but also adds complexity to the post-mortem analysis of fund flows.

how-it-works
SECURITY

How a StableSwap Invariant Attack Works

A technical breakdown of the exploit vector that targets the mathematical core of automated market makers designed for stable assets.

A StableSwap invariant attack is a sophisticated exploit that manipulates the pricing formula of a Constant Function Market Maker (CFMM) to drain liquidity by forcing the pool into an imbalanced state where the invariant no longer holds. Unlike simple price oracle manipulation, this attack directly targets the invariant equation—the mathematical rule that defines the relationship between the reserves of assets in a pool, such as the StableSwap invariant or Curve Finance's StableSwap model. The attacker typically uses a flash loan to execute a series of large, precisely calculated swaps that push the pool's reserves to an extreme imbalance, creating a temporary but exploitable discrepancy between the pool's internal pricing and the external market price.

The attack capitalizes on the specific design of StableSwap AMMs, which use a combined invariant that blends a constant-product curve (like Uniswap's x*y=k) with a constant-sum curve to enable low slippage for pegged assets. When reserves become highly imbalanced, the invariant's behavior can shift, allowing an attacker to swap assets at a more favorable rate than the true value. The core vulnerability often lies in the amplification coefficient (A) parameter, which controls this blending. By manipulating reserves to a point where the effective A changes the curve's shape dramatically, the attacker can "break" the intended pricing mechanism, enabling them to withdraw more value than they deposited in a final arbitrage step.

A canonical example is the attack on Curve Finance pools in July 2023, where vulnerabilities in the Vyper compiler led to reentrancy, which attackers used to perform the precise multi-swap sequences required for an invariant attack. The exploit followed a pattern: borrow assets via flash loan, skew the pool's balance through reentrant deposits and swaps, and then execute an arbitrage trade that profits from the artificially created price dislocation. This highlights that while the attack targets the invariant's math, it often requires an additional vulnerability, such as reentrancy or a flawed oracle, to initiate the manipulative transactions.

Preventing StableSwap invariant attacks requires robust protocol design, including thorough auditing of the invariant implementation and the smart contract code that interacts with it. Key mitigation strategies involve implementing reentrancy guards, using internal oracles or time-weighted average prices (TWAPs) to limit large price deviations within a single block, and carefully designing emergency circuit breakers that halt trading if reserve ratios move beyond safe parameters. Furthermore, continuous monitoring of pool imbalances and the A parameter's effective state can provide early warning signs of potential manipulation attempts.

For developers and liquidity providers, understanding this attack vector is crucial for assessing risks in DeFi yield strategies. It underscores that the complex mathematics enabling efficient stablecoin trading can also introduce unique attack surfaces. Security ultimately depends on the integrity of the invariant's code, the safeguards around its execution environment, and the economic assumptions about how deep and balanced liquidity must remain for the model to function as intended.

visual-explainer
STABLESWAP INVARIANT ATTACK

Visualizing the Attack Vector

A conceptual breakdown of how an attacker can exploit the mathematical properties of a StableSwap invariant to drain liquidity from a decentralized exchange pool.

A StableSwap invariant attack is a sophisticated exploit targeting the bonding curves of automated market makers (AMMs) like Curve Finance, where the attacker manipulates the pool's internal price oracle to drain funds. The core vulnerability lies in the pool's reliance on its own spot price for the invariant calculation, creating a feedback loop. By executing a large, imbalanced trade, the attacker can temporarily skew the oracle price, tricking the invariant into believing the pool is heavily imbalanced when it is not, thereby allowing the withdrawal of excess value.

The attack unfolds in a multi-step process. First, the attacker borrows a massive amount of one asset in the pool (e.g., a stablecoin) via flash loans. They then deposit this borrowed capital into the targeted liquidity pool, significantly altering the token ratios. This large deposit distorts the pool's internal oracle price for that asset. Crucially, the StableSwap invariant—designed to maintain a "flat" region for stable asset pairs—interprets this artificial imbalance as a legitimate state, miscalculating the true value of liquidity.

With the oracle manipulated, the attacker executes the critical step: withdrawing their liquidity. Because the invariant's calculations are now based on incorrect prices, the withdrawal formula returns more value than the attacker deposited. They receive a disproportionate amount of the other asset in the pool (e.g., a different stablecoin), effectively extracting value from the pool's reserves. Finally, the attacker repays the flash loan with a portion of the profit, leaving the liquidity pool with a permanent loss and an actual imbalance that harms remaining liquidity providers.

This attack vector is distinct from simple arbitrage and highlights the risks of oracle manipulation within a system's core pricing mechanism. It exploits the very feature—a low-slippage curve for like-valued assets—that makes StableSwap pools efficient. Defensive measures include using time-weighted average price (TWAP) oracles, implementing deposit/withdrawal limits, and conducting rigorous audits of the invariant's response to extreme, single-block transactions.

examples
STABLESWAP INVARIANT ATTACK

Historical Examples and Incidents

These incidents demonstrate the practical risks of vulnerabilities in the StableSwap invariant formula, where attackers exploited mathematical flaws to drain liquidity pools.

02

MIM-UST 3Pool Attack (October 2021)

An attacker exploited the peg stability mechanism of the MIM-UST 3Pool on Curve. By taking a flash loan to skew the pool's balance, they manipulated the StableSwap invariant to mint an excessive amount of MIM (Magic Internet Money) at an incorrect price. The attack netted the exploiter over $130M, demonstrating how invariant-based pricing can be gamed when one asset significantly deviates from its peg.

03

Ellipsis Finance Post-Launch Exploit (March 2021)

Shortly after launch, Ellipsis Finance (a Curve fork on BSC) suffered an exploit due to an incorrect implementation of the StableSwap invariant. A flaw in the deposit function allowed an attacker to mint an inflated number of LP tokens for a minimal deposit, enabling them to drain approximately $200k from the BUSD-USDT-USDC pool. This incident underscored the dangers of forking complex financial protocols without rigorous security audits.

04

Saddle Finance Frontend Attack (January 2022)

While not a direct attack on the invariant's math, this incident targeted Saddle Finance's frontend, which implemented the StableSwap model. Attackers compromised the DNS to redirect users to a malicious site, stealing wallet approvals. Although the smart contracts remained secure, it highlighted that the security of an AMM extends beyond its core invariant formula to its entire operational stack.

05

Theoretical Vulnerability: Oracle Manipulation

A persistent theoretical risk for StableSwap pools is oracle manipulation. If a pool's invariant relies on an external price feed for a pegged asset, an attacker could:

  • Manipulate the oracle price on a DEX.
  • Cause the StableSwap pool to misprice assets relative to the manipulated oracle.
  • Arbitrage the pool to extract value, exploiting the discrepancy between the invariant's internal calculation and the corrupted external data.
06

Key Mitigation: The 'p' Parameter & Audits

Post-incident analyses consistently point to parameter tuning and comprehensive audits as critical defenses. The amplification coefficient (A or p parameter) must be carefully set to balance capital efficiency with resistance to manipulation. Major protocols now employ:

  • Formal verification of invariant mathematics.
  • Time-weighted average price (TWAP) oracles for peg references.
  • Emergency DAO controls to pause pools during detected anomalies.
security-considerations
STABLESWAP INVARIANT ATTACK

Security Considerations and Mitigations

StableSwap invariant attacks exploit the mathematical bonding curve of concentrated liquidity AMMs to manipulate prices and extract value. This section details the attack vector and established defensive strategies.

01

The Attack Vector: Curve's Invariant

The attack targets the StableSwap invariant, the core formula governing liquidity in pools like Curve Finance. Unlike a constant product AMM (x*y=k), StableSwap uses a hybrid function that approximates a constant sum (x+y=k) when assets are near peg, enabling low slippage. Attackers exploit this by performing large, imbalanced swaps that push the pool far from equilibrium, temporarily breaking the 'stable' region and causing the invariant to behave more like a volatile constant product curve. This creates massive, artificial price impact that can be arbitraged for profit, draining value from the pool's liquidity providers.

02

Oracle Manipulation & Price Impact

A successful attack hinges on manipulating the pool's internal price oracle. StableSwap pools use a time-weighted average price (TWAP) oracle for rebalancing and fee adjustments. By executing a large, imbalanced swap, the attacker creates a severe, short-term price dislocation. If the pool's oracle has a short lookback period or low granularity, this manipulated price can be used to trigger unfavorable rebalancing or be read by external protocols (e.g., lending markets) that rely on it, leading to cascading liquidations or faulty valuations that the attacker profits from.

03

Primary Mitigation: Amplification Coefficient

The key parameter for defense is the pool's amplification coefficient (A). This value controls how 'flat' the bonding curve is within the peg range. A higher A creates a wider, flatter region (more like a constant sum), making it exponentially more expensive to move the price. Mitigations involve:

  • Setting A appropriately high for the asset pair's expected volatility.
  • Dynamic A adjustments via governance to respond to market conditions.
  • Oracle hardening using longer TWAP windows (e.g., 2 hours on Curve v2) to smooth out short-term manipulation attempts.
04

Liquidity Depth & Pool Composition

Attack feasibility is directly tied to liquidity depth and asset correlation. Mitigations include:

  • Requiring massive TVL: A deep pool makes the cost of price manipulation prohibitively high.
  • Curating asset pairs: Pools should contain only assets with proven, high correlation (e.g., USDC/DAI/USDT). Including a volatile, low-liquidity asset dramatically increases risk.
  • Monitoring imbalance: Protocols monitor the pool's token balances; large, sustained imbalances can trigger alerts or temporary fee increases to deter attacks.
05

Fee Structures as a Deterrent

Adaptive fee models are a critical line of defense. When a pool detects conditions ripe for an invariant attack (e.g., rapid price deviation), it can activate dynamic fees. For example:

  • Curve v2's 'Profit' Algorithm: Automatically increases the swap fee when the internal oracle price deviates from the external market price, capturing arbitrage profit for LPs instead of the attacker.
  • Asymmetric Fees: Charging higher fees on the imbalanced side of a trade. This directly increases the attacker's cost, making the exploit economically unviable.
06

Related Vulnerability: Read-Only Reentrancy

StableSwap pools can be indirectly attacked via read-only reentrancy. This occurs when an external contract (e.g., a lending market) reads the manipulated price from the pool's oracle during a state-changing call to the pool itself. While the pool's state may be secure, the corrupted price read can cause faulty logic in the external protocol. Mitigation requires protocols to implement the Checks-Effects-Interactions pattern and use non-reentrant modifiers on functions that make external calls which could query the vulnerable pool state.

EXPLOIT COMPARISON

StableSwap Invariant Attack vs. Other AMM Exploits

A comparison of the StableSwap Invariant Attack's mechanism and impact against other common Automated Market Maker (AMM) vulnerabilities.

Feature / MetricStableSwap Invariant AttackFlash Loan AttackOracle ManipulationReentrancy Attack

Primary Attack Vector

Mathematical precision error in invariant calculation

Borrowing uncollateralized capital within a single transaction

Feeding false price data to an on-chain oracle

Recursive callback into a vulnerable contract before state update

Core Vulnerability

Rounding errors and amplification parameter exploitation

Lack of atomic transaction isolation for borrowed funds

Reliance on manipulable or insufficiently decentralized price feeds

Violation of the Checks-Effects-Interactions pattern

Typical Impact

Draining liquidity pools of stable assets

Large, rapid arbitrage or market manipulation

Forced liquidations or incorrect pricing for derivatives

Direct theft of user funds from a contract

Attack Scale (Typical Loss)

$1M - $100M+

$10K - $100M+

$1M - $100M+

$10K - $100M+

Preventive Measure

Secure invariant math with high precision, circuit breakers

Transaction-level isolation, fee adjustments

Decentralized oracles, time-weighted average prices (TWAP)

Reentrancy guards, proper state management

Requires External Capital?

Targets Specific AMM Design?

Complexity of Execution

High (requires deep math understanding)

Medium (requires complex transaction bundling)

Medium to High (requires price feed influence)

Low (exploits well-known pattern)

STABLESWAP

Common Misconceptions

Clarifying persistent misunderstandings about the StableSwap invariant, its security model, and the nature of attacks on concentrated liquidity pools.

A StableSwap invariant attack is a misnomer; it refers not to a direct exploit of the StableSwap invariant formula itself, but to a sophisticated manipulation of concentrated liquidity pools (like those in Uniswap V3) that mimic stable assets. The attack exploits the pool's oracle price and the concentrated nature of liquidity to drain funds. The attacker manipulates the price far outside the normal trading range, causing the pool's internal oracle to report a wildly inaccurate price. They then execute a large, imbalanced swap that capitalizes on this manipulated price and the minimal liquidity available at the new tick, extracting value before the price can correct.

Key mechanics involve:

  1. Price Manipulation: Using a flash loan to move the pool's price to a distant tick where liquidity is thin.
  2. Oracle Exploit: The manipulated price is stored by the pool's oracle.
  3. Value Extraction: A subsequent swap uses the faulty oracle price as a reference, allowing the attacker to trade as if the asset is still at its original, stable value, while the pool's actual reserves are severely depleted.
STABLESWAP INVARIANT

Frequently Asked Questions (FAQ)

Essential questions and answers about the StableSwap invariant attack, a critical vulnerability affecting automated market makers (AMMs) with concentrated liquidity.

A StableSwap invariant attack is a sophisticated exploit where an attacker manipulates the price of a concentrated liquidity pool to drain its reserves by forcing the pool's invariant calculation to fail or produce an incorrect exchange rate. This attack specifically targets the mathematical formula (the invariant) that AMMs like Curve Finance use to maintain a stable price for pegged assets, exploiting rounding errors or precision loss in the contract's logic to extract value.

Key Mechanism:

  • The attacker executes a series of large, imbalanced swaps that push the pool's price far from its intended peg.
  • This extreme price movement can cause the invariant calculation to overflow, underflow, or encounter a division-by-zero error due to the specific implementation of the bonding curve.
  • By carefully crafting the transaction sequence, the attacker can then perform a "donation" or a follow-up swap that is mispriced by the compromised invariant, allowing them to withdraw more assets than they deposited.
ENQUIRY

Get In Touch
today.

Our experts will offer a free quote and a 30min call to discuss your project.

NDA Protected
24h Response
Directly to Engineering Team
10+
Protocols Shipped
$20M+
TVL Overall
NDA Protected Directly to Engineering Team
StableSwap Invariant Attack: Definition & Exploit | ChainScore Glossary