Curve's StableSwapNG represents a significant evolution in decentralized exchange (DEX) design, specifically optimized for efficiently trading stable assets and tokens pegged to similar values. This next-generation protocol employs multidimensional invariant surfaces that enable three, four, and even higher-dimensional curves compared to traditional two-dimensional invariant curves used in platforms like Uniswap.
Core Components and Factory Structure
The StableSwapNG ecosystem begins with the pool factory contract (CurveStableSwapFactoryNG.vy), which serves as the deployment mechanism for two primary types of exchange pools: PlainPool and MetaPool. Additionally, the factory deploys special Gauge contracts that handle additional reward distributions.
The deployment functions deploy_plain_pool() and deploy_metapool() handle the creation of these pool types. Plain pools facilitate standard token exchanges, while meta pools enable trading with liquidity provider (LP) tokens from other pools. In meta pools, the first listed token is always an LP token from a "base" pool.
Common deployment parameters include:
- Token lists (up to eight different tokens)
- Decimal precision specifications
- Token types and rate oracles
- Exchange fees and amplification factors for the invariant curve
Token types within StableSwapNG can include regular ERC20 tokens, tokens with rate oracles (like wstETH), rebasing tokens (such as stETH), and ERC4626 vault shares. Each token type may require special handling mechanisms to ensure proper accounting and exchange functionality.
The _implementation_idx parameter deserves special attention as it enables upgradeable pool logic. The factory maintains registries of implementation contracts for PlainPool, MetaPool, Gauge, Math, and Views functionality, allowing for protocol improvements and bug fixes through governance processes.
Pool registration involves storing pool data in self.pool_data and adding token addresses to self.markets mapping. The mapping uses XOR operations on token addresses to generate unique keys that identify pools facilitating exchanges between any two tokens, regardless of their order in the pair.
Technical Implementation of Plain Pools
Plain pools in StableSwapNG handle straightforward token exchanges without wrapped tokens. The initialization process begins with setting the token list, amplification factor, and oracle time window configuration.
During initialization, an interesting optimization involves packing oracle addresses and method selectors into a single 256-bit value, reducing gas consumption. The system also handles ERC4626 tokens with underlying assets, requiring careful management of scale factors to ensure proper operations between ERC4626 tokens and their underlying assets.
Token transfers within pools are managed through two primary functions:
_transfer_in(): Modifies pool'sstored_balances[coin_idx]and includes both traditionaltransferFrom()logic and an "optimistic" transfer approachtransfer_out(): Directly executes token transfers to users while updating stored balances
The optimistic transfer variant cannot be used with rebasing tokens, as pool balances might change between transfer and exchange operations.
Exchange Mechanism and Process
The exchange process begins with either the exchange() or exchange_received() functions, differing primarily in their transfer methods. Both functions accept indices of tokens being exchanged and a _min_dy parameter that sets slippage limits by defining the minimum amount of output tokens required.
The core exchange logic occurs in the _exchange() function, which begins by fetching actual balances of various token types. The _balances() function handles rebasing tokens by querying actual balanceOf(self) instead of relying on stored balances. The _xp_mem() function then calculates actual reserve values by applying corresponding rates.
The mathematical heart of the exchange involves calculating _dy, which represents the resulting amount of output tokens. This calculation occurs in the __exchange() function, where the primary pool variable D represents the total number of tokens under normalized balances. The amplification parameter amp works with D and actual reserves to calculate target reserve amounts, ultimately determining how many tokens should be sent to the user.
To prevent rounding issues, the target dy value is reduced by one unit, protecting the pool from potential attacks exploiting favorable rounding for users. The calculated dy value then serves as the basis for dynamic fee calculations.
Dynamic Fee Structure
StableSwapNG implements a sophisticated dynamic fee system that deducts fees from output tokens, thereby enhancing pool balances and increasing LP token values. Fees are charged during imbalanced liquidity additions or removals, preventing users from effectively executing exchanges through liquidity operations instead of proper swaps.
The "ideal" token quantity calculation operates on the principle that if D increases by x%, each token balance should increase by the same percentage. The system determines target balances using this D increase and calculates fees based on the differences.
The dynamic fee coefficient depends on the current imbalance between two tokens i and j. Additionally, a special self.offpeg_fee_multiplier value can be set by pool governance when pools deviate significantly from their pegs, providing additional protection during market stress.
👉 Explore advanced trading strategies
Liquidity Management
The add_liquidity() function accepts specified amounts of all pool tokens and initially checks whether D hasn't decreased, ensuring proper pool mathematics. Liquidity providers receive LP tokens representing their share of the pool, with the minting amount calculated based on the proportional increase in pool value.
Removing liquidity follows a similar but reverse process, with the system calculating token amounts to return to users based on their LP token share and current pool balances. The protocol ensures that proportional liquidity removals don't incur fees, while imbalanced removals trigger dynamic fee applications.
Oracle Implementation and Price Stability
A critical parameter in StableSwapNG is _ma_exp_time, which defines the time window for the pool's moving average price oracle. Curve allows configuration of this parameter because different token sets require varying "reaction times" from price oracles.
More volatile assets need faster response times, making their oracles more vulnerable to price manipulation. Conversely, stable assets can accommodate larger time windows, making their price oracles more resistant to manipulation attempts. This flexible approach to oracle configuration represents a significant advancement in DEX design, balancing responsiveness with manipulation resistance.
Meta Pool Architecture
Meta pools represent a specialized pool type within StableSwapNG that enables trading with LP tokens from other pools. In these pools, the first listed token is always an LP token from a base pool, creating a layered liquidity structure that enhances capital efficiency across the ecosystem.
Meta pools inherit most functionality from plain pools but require additional handling for LP token interactions. The system must properly account for the underlying assets represented by LP tokens, creating a more complex but powerful liquidity architecture.
Upgradeability and Governance
Unlike some competing DEX implementations, StableSwapNG doesn't feature configurable exchange/liquidity hooks. The logic remains fixed, with only pool and Gauge implementations modifiable through governance processes. This approach balances flexibility with security, preventing potential attack vectors through arbitrary callback functions while still allowing protocol improvements.
The factory contract's ability to update implementation addresses for various components creates an upgradeable architecture that can evolve with the DeFi ecosystem while maintaining backward compatibility and security.
Frequently Asked Questions
What makes StableSwapNG different from traditional AMMs?
StableSwapNG uses multidimensional invariant surfaces that enable more efficient trading of stable assets. Unlike traditional two-dimensional curves, it supports higher-dimensional mathematics that better maintain pegs between similar-valued assets, reducing slippage and improving capital efficiency.
How does the dynamic fee system work?
Fees are calculated based on the imbalance between tokens in a trade. When pools are balanced near their pegs, fees remain low. As imbalances grow, fees increase dynamically to encourage arbitrageurs to restore balance while compensating LPs for increased risk.
Can StableSwapNG handle rebasing tokens?
Yes, the system includes special handling for rebasing tokens like stETH. Instead of relying solely on stored balances, it queries actual token balances before critical operations, ensuring proper accounting despite balance changes from rebasing events.
What is the purpose of the amplification parameter?
The amplification factor determines how closely the curve resembles either a constant sum or constant product formula. Higher values create flatter curves that maintain tighter pegs but might become less liquid during significant imbalances, while lower values create more curved surfaces that handle imbalances better but with more slippage.
How are oracle time windows selected?
Oracle configurations balance responsiveness against manipulation resistance. More volatile tokens use shorter time windows for quicker price updates, while stable tokens use longer windows that are more resistant to short-term manipulation attempts.
What advantages do meta pools provide?
Meta pools enable trading between LP tokens and other assets, creating layered liquidity structures. This allows capital to flow more efficiently between different pools and protocols while maintaining exposure to underlying assets through LP tokens.