Perpetuals and Funding-Rate Mechanics
Perpetual swap protocols (perps) let users take leveraged long or short positions on an asset without an expiry date. They are the third-largest DeFi category by TVL and are particularly bug-prone because they combine several non-trivial subsystems: an oracle, a margin engine, a funding-rate mechanism, a liquidation engine, and (depending on design) an AMM or order book.
High-Level Architecture Families
Virtual AMMs (vAMMs)
Pioneered by Perpetual Protocol V1, the vAMM has reserves that exist only on paper — there's no real liquidity in the AMM, just a constant-product invariant used as a price-discovery mechanism. Traders' P&L is settled in real collateral; the vAMM itself doesn't hold the underlying.
Largely deprecated due to inherent fragility. Still encountered in audits of legacy code or experimental forks.
Order-Book Perps
Centralized-style order book matching, settled on-chain. Examples: dYdX V3 (StarkEx-based), Vertex, Hyperliquid (its own L1), Aevo. Audit focus is usually on the matching engine off-chain and the on-chain settlement layer.
AMM-Based Perps with Real Liquidity
Examples: GMX V1/V2, Gains Network. LPs provide a pool of real assets; traders take positions against the pool; the pool earns fees and absorbs P&L. Often called "pool-vs-trader" or "house" models.
These models have a counterparty problem: when traders are net long and the asset goes up, the pool loses; LPs are exposed to traders' aggregate P&L.
Cross-Margin / Account-Based
Examples: dYdX V4, Drift, Synthetix Perps V3. Each user has a cross-margin account whose health depends on the net P&L and collateral across positions. More capital-efficient; more complex.
Mechanics That Almost Always Have Bugs
Funding Rate
Perpetuals need a mechanism to keep the perp price close to spot. Funding payments — paid periodically between longs and shorts, in proportion to the perp-spot price gap — provide the equilibrium force.
Variants:
- Premium-based: funding rate is a function of (perp price - spot price). Longs pay shorts when perp is above spot; vice versa.
- Open-interest-based: funding depends on the imbalance between long and short open interest.
- Hybrid: combinations of the above.
Common bugs:
- Funding accrual time mismatch. Funding is paid every N hours, but accrual is computed continuously. Misalignment lets users open positions just before a funding payment and close just after, capturing or avoiding the payment.
- Funding rate clipping. Protocols cap the funding rate to prevent runaway charges. If the cap is too aggressive, the perp price can drift far from spot, creating arbitrage opportunities against the protocol.
- Funding accumulator overflow. The cumulative funding accumulator grows over time; if its scale or sign is mishandled, positions opened long ago can have wrong P&L.
- Funding payable on closed positions. A position that was closed but not properly cleaned up can still be charged funding, draining collateral.
Margin and Liquidation Math
The protocol must continuously evaluate every position's health. This involves:
- Current value of collateral (from the oracle).
- Current value of position notional (from the oracle).
- Unrealized P&L.
- Funding already paid.
- Maintenance margin requirement.
Common bugs:
- Off-by-one in margin checks (using strict vs. non-strict inequalities; allowing positions exactly at the liquidation threshold).
- Stale P&L — computing health using a price observation that's older than the liquidator's observation.
- Wrong sign on P&L — long positions credited losses, etc. Sounds absurd; happens in practice.
- Mark price vs. index price confusion — the mark price (used for P&L) and the index price (used for funding) can differ; using the wrong one in the wrong calculation is a finding.
Liquidation Mechanics
When a position becomes underwater, it must be liquidated. Designs vary:
- Full liquidation: the entire position is closed at once. Simple, but can leave bad debt if the position is very large.
- Partial liquidation: a fraction of the position is closed; iterates until healthy. Complex, but limits realized P&L per liquidation.
- Auction-based: position is auctioned (Dutch or sealed-bid) to liquidators. Used by some protocols to ensure efficient liquidation in volatile markets.
- Auto-deleveraging (ADL): when the insurance fund is exhausted, profitable positions on the opposite side are forcibly closed. GMX-style.
Common bugs:
- Liquidation incentives misaligned — too low and positions stay underwater; too high and excess value transfers to liquidators.
- Liquidation order matters — when multiple positions are simultaneously liquidatable, the order can affect total losses to the protocol.
- Self-liquidation paths that don't check the same invariants as third-party liquidation.
- Liquidation of paused markets — markets paused for legitimate reasons (oracle failure, governance) shouldn't allow liquidation at stale prices.
Insurance Fund
The buffer between traders' P&L and LPs/depositors. When liquidations don't cover losses, the insurance fund absorbs them; when over-coverage happens, the fund grows.
Common bugs:
- Insurance fund draining via crafted liquidations. A liquidator can construct a scenario where the protocol pays out more than it should, transferring value from the insurance fund.
- Insurance fund accounting errors — additions/subtractions in the wrong order, with the wrong sign, or using stale values.
- Insurance fund used in non-insurance contexts — admin functions or governance actions that touch the fund without going through proper accounting.
ADL (Auto-Deleveraging)
When the insurance fund is exhausted, some protocols forcibly close winning positions on the opposite side at the bankruptcy price. This is fair in expectation but produces strong negative incentives for traders.
Audit considerations:
- ADL selection mechanism must be deterministic and resistant to manipulation. Ordering by profit, by leverage, or by composite scores all have different gaming properties.
- ADL triggering condition must be precise — triggering too eagerly punishes winners unnecessarily.
- Accounting after ADL — the closed positions' collateral must be returned correctly; their margin requirements removed; the corresponding counterparty positions adjusted.
Oracle for Perps
The single most important security input. The oracle determines:
- Mark price for P&L computation.
- Liquidation threshold checks.
- Funding rate calculation.
- ADL trigger conditions.
For perps, an oracle bug is usually catastrophic. The standard mitigations from §4.15.4 apply, with extra caution: perps' P&L is leveraged, so a 1% oracle error on a 10x position is a 10% loss.
Pool-vs-Trader Specific Bugs (GMX-style)
When LPs are the counterparty, the protocol must ensure LPs are not systematically losing to informed traders:
- Skewed open interest — when traders are heavily one-sided, the LP pool's risk is concentrated. Designs use OI caps, funding rate skew, or insurance funds to manage this.
- Borrow fees — traders pay a fee for borrowing the pool's liquidity to take leveraged positions. Misaligned borrow fees let traders capture the LP's edge.
- Trader-vs-pool zero-sum — over time, if traders are net profitable, the pool loses. Audit consideration: is the protocol's fee schedule sufficient to compensate LPs for this exposure?
GMX V1 famously had a "free trades" period (low fees, no spread, no funding) that ended up costing LPs substantially when sophisticated traders exploited the design. GMX V2 redesigned the fee model to address this. Audits of new perps in this family should specifically check the LP economics.
Audit Checklist for Perpetuals
- Oracle: source, freshness, deviation tolerance, manipulation resistance — same checks as for lending but more critical.
- Mark price and index price distinguished correctly throughout the codebase.
- Funding rate: accrual is continuous, payments are atomic, cap (if any) is sensible, sign is correct.
- Margin math: maintenance margin checked before any state change to a position; liquidation triggered at the right threshold.
- Liquidation: incentives align liquidators with protocol; partial vs. full liquidation handled consistently.
- Insurance fund: additions/subtractions accurate; can't be drained by crafted liquidations.
- ADL (if applicable): selection deterministic, triggering condition precise, accounting consistent.
- Pause/freeze paths: don't permit liquidation at stale prices; don't trap users' collateral.
- Self-liquidation paths: same checks as third-party liquidation.
- Re-entrancy: every position-modifying function reviewed; cross-function reentrancy considered.
- LP economics (if pool-vs-trader): is the fee schedule sufficient to compensate LPs for trader profitability?
- Withdrawal/exit paths: users can always exit (subject to maintenance margin); LPs can withdraw subject to liquidity constraints.
Perps audits are unusually expensive because the systems are large and the bug categories are subtle. Expect to spend more time on perps than on equivalent-TVL DEXs or lending markets, and expect specialist review.