DeFi Security Alliance

Verticals

Perpetual DEX Security: Liquidations, Funding, Oracles and ADL

A perpetual DEX security audit tests margin accounting, liquidation execution and who absorbs losses when normal settlement fails. Our snapshot resolved the margin rules for 177 Hyperliquid markets, including 34 with multiple tiers. Use that configuration inventory alongside a venue-specific loss model when commissioning the review.

Balance beam with weights tipping toward a row of falling dominoes above a blue safety net, illustrating liquidation risk in a perpetual DEX.

Key facts

Original measurement
34 of 177 included default-dex markets had multiple margin tiers; 143 had a single tier
Population boundary
233 metadata entries, with 56 explicit delistings excluded; builder-deployed dexes were not queried
Resolution completeness
No included margin table remained unresolved after applying documented implicit rules
Unknown fields
Optional isolation and margin-mode fields were absent for all 177 included entries
Loss allocation
Insurance and deleveraging order depends on the venue; profitable positions can be closed under ADL

Liquidation engine and partial liquidation math

A perpetual DEX security review follows an account from opening a position to settling its final liability. The implementation can reject unauthorized transfers and still let trading losses exceed recoverable collateral. Commission the review around that transition. Ask which balance changes first, which price values it and who can execute the next step when markets stop behaving normally.

Start with the account model. Distinguish deposited collateral from equity that includes unrealized profit and accrued funding. A liquidation eligibility check must use the same conventions as withdrawals, order placement and settlement. Otherwise an account can appear healthy to one function while another function releases the assets needed to cover its debt.

Hyperliquid's liquidation documentation describes order-book execution followed, under its specified conditions, by a backstop transfer. Cross and isolated positions have different transfer boundaries. Its partial liquidation rules also depend on position size and elapsed time. These are useful test dimensions, not rules to copy into another venue's specification.

Liquidation review cases and the evidence to request
CaseFailure to testRequired evidence
Partial fillCollateral or debt is updated for the requested amount instead of the filled amountReconciled balances after an incomplete execution
Margin tier crossingClosing part of a position applies the wrong maintenance deductionBoundary tests on both sides of each configured tier
Concurrent rescue depositA stale eligibility decision liquidates an account that has recoveredTransaction-order permutations using the actual execution model
Unfillable remainderA small residual position cannot be closed economicallyA documented terminal state for dust and remaining debt

Test the rescue path from the user side as well. An account owner may need to add collateral through a router while a keeper is attempting to liquidate the same account. Include authorization checks on the router and verify the credited asset amount after the transfer completes. If the collateral token takes a fee or changes balances independently, either demonstrate compatible accounting or state that the token behavior is unsupported. The test result should identify the assumption that makes the balance reconciliation valid.

Execution availability belongs in the scope. Replaying a profitable liquidation with unlimited liquidity proves little about a congested venue. Remove the best-priced liquidity, delay the keeper and repeat the eligibility calculation after each attempted fill. Record whether progress remains possible and whether the failure leaves a recoverable account or an unassigned liability.

Public findings help make that distinction concrete. Dedaub's Perpetual v2 collateral review described a deposit-on-behalf path that could fill another user's collateral slots and interfere with a rescue deposit. The report marked that finding dismissed. Use the scenario to ask about adversarial rescue paths; do not present it as a confirmed exploited vulnerability or an unresolved issue in a current deployment.

Our snapshot resolved margin rules for 177 markets

A liquidation engine audit needs its configuration population. Testing a representative asset can miss a tier boundary used elsewhere. We queried Hyperliquid's default perpetual market metadata and resolved the margin table attached to every included entry. The result separates markets with size-dependent leverage from those with a documented single-tier rule.

Method

Source
The public perpetual metadata endpoint, requested with type=meta and no alternative dex parameter.
Retrieved
. The saved result includes the request timestamp and complete response.
Population
233 universe entries. We excluded 56 entries explicitly marked isDelisted=true, leaving 177 in the analyzed denominator.
Resolution rule
Read the explicit table where present. For a table identifier below 50, apply the documented single tier whose maximum leverage equals that identifier.
Classification
Count resolved tiers, not vulnerability keywords. No manual finding classification is needed because the signal is a configuration field, not prose in an audit report.

Results

Default-dex margin metadata retrieved on
ObservationCountDenominatorScope implication
Multiple resolved tiers34177 included marketsSize-dependent boundaries need explicit tests
Single resolved tier143177 included marketsUse the documented implicit-table rule
Unresolved tier records0177 included marketsThe configuration inventory is complete for this response
Absent optional isolation flag177177 included marketsDo not infer isolation permissions from a missing field

The margin-tier specification explains why a missing explicit table is not necessarily missing data: lower identifiers encode the rule directly. A parser that joined only against the explicit table array would incorrectly call 143 records unresolved. That error would distort an audit inventory before any code review started.

Use this result to build the test manifest. Group markets by resolved table, retain the asset-to-table mapping and require tests at every distinct lower bound. Add a configuration-change check so an approved test manifest cannot silently outlive a governance or operator update.

Limits

  • Builder-deployed perpetual dexes were not queried.
  • Excluding an explicit delisting flag does not establish liquidity, executable depth or permission to open a position.
  • Optional onlyIsolated and marginMode fields were absent across the included population. They remain unknown in the dataset.
  • Configuration coverage cannot establish solvency or implementation correctness. We did not place orders or reproduce the venue's execution engine.

The reproducible script seo/research/perps-margin-survey.py and raw result seo/research/perps-margin-survey-2026-09-05.json are kept in the repository and are not published as site downloads.

Funding rate manipulation

Funding transfers value while a position stays open. A review must connect the sampled premium to the accumulated rate and then to the balance change. Test the boundaries separately: a correct formula can still consume an attacker-influenced input, and a reliable input can still be settled with the wrong sign or time unit.

Hyperliquid's funding specification distinguishes its rate calculation horizon from hourly payments. It also uses the oracle price to convert position size into payment notional and documents a different premium formula for builder-deployed markets. An auditor therefore needs the exact market family, not merely the name of the platform.

  1. Inventory attacker-influenced price samples and their executable depth.
  2. Trace the accumulator across an idle period, a position-size change and a settlement boundary. Preserve the timestamp sequence in the regression test.
  3. Reconcile debits and credits after applying documented rounding and any explicit protocol subsidy. Explain every residual instead of treating it as harmless dust.
  4. Repeat with a delayed update and an unavailable price source. Confirm which operations remain permitted while the rate is stale, including whether a user can reduce risk without increasing another account's liability. Record the expected failure response so a rejected transaction does not get mistaken for a successful settlement in an automated test.

A profitable manipulation model needs trading costs and exit liquidity. Moving a premium briefly is not enough to establish an extractable loss. Ask the reviewer to report the capital requirement, fees and settlement exposure assumed by the test, with a sensitivity case where the attacker cannot exit at the displayed mark.

Keep economic assumptions alongside the code findings. Our tokenomics audit scope guide explains how to separate an implemented rule from the behavior a model assumes. Funding-rate limits belong in both places when the implementation enforces them but their adequacy depends on liquidity and participant behavior.

Mark vs index price oracle design

The index is an external reference. The mark is the accounting price a venue chooses for positions. The executable close price is what available liquidity will actually pay. Treat these as separate fields in the threat model. A tight relationship during ordinary trading does not make them interchangeable during a gap.

Hyperliquid's mark-price documentation describes a combination of external prices and local book observations, including behavior when inputs are missing. Its oracle page adds exceptions for assets whose primary spot liquidity is local. That exception matters: counting venue names without checking the asset-specific source path can exaggerate independence.

Reference integrity
Check freshness, source eligibility and how unavailable inputs change the result. Correlated sources can repeat the same bad observation.
Accounting consistency
Follow the selected price into unrealized profit, margin checks and settlement. State which values are fixed within one operation.
Execution divergence
Measure the gap between the accounting price and a stressed close. The liquidation model needs this gap even when every oracle update is valid.
Recovery behavior
Specify how the system resumes after stale data. A fallback that accepts the first returning value without checking its context creates another boundary to test.

A price-source map should name the failure domain behind each input. Different API addresses can depend on the same exchange, publisher or network route. Ask the team to explain how the price calculation behaves when that shared dependency disappears, and keep the answer with the source configuration. Source count alone cannot establish independence.

Request a replay where the index updates while local depth disappears, followed by the opposite case where local trading continues but a reference source stops. For an off-chain matcher, include signed order expiry and cancellation behavior in the same sequence. The oracle manipulation analysis supplies the broader distinction between source validity and economically usable pricing.

Insurance fund sizing

An insurance-fund balance is meaningful only beside the liabilities it can absorb. Ask which asset the fund holds, which markets can draw from it and whether the code limits a draw per operation or period. Then model losses arriving together. Several positions that share a collateral asset can exhaust the same resource even if each market's isolated stress test passes.

There is no universal waterfall. The dYdX contract-loss explanation describes insurance support for liquidation execution and immediate deleveraging when an account becomes negative, without drawing on that fund at that stage. A diagram that always puts fund exhaustion before deleveraging would misstate that documented design.

Insurance questions that change the audit scope
QuestionArtifactFailure exposed
Which liabilities qualify?Asset and market eligibility mapA fund exists but cannot cover the affected liability
When can funds move?Executable draw conditionsLiquidity arrives after the insolvency transition
Who competes for reserves?Joint stress scenariosSeparate models spend the same reserve repeatedly
What if the fund asset falls?Collateral haircut assumptionsNominal reserves overstate realizable support

Do not confuse trading-loss support with exploit reimbursement. Drift's recovery update explicitly distinguishes an insurance fund for trading bankruptcies from its user recovery arrangements after an exploit. The contract and published terms determine the fund's purpose; the word insurance does not establish a general compensation promise.

Have the reviewer publish the stress assumptions and the failure threshold of the model. A reserve recommendation without those inputs cannot be retested when open interest, collateral composition or liquidation depth changes.

ADL waterfall and the October 2025 episode

ADL closes offsetting positions when the venue's applicable loss-handling rules require it. A profitable trader can therefore lose an expected position outcome without having breached their own maintenance requirement. Audit the selection rule and close price as loss allocation decisions, alongside the solvency condition they are intended to restore.

Hyperliquid's ADL documentation describes a ranking based on unrealized profit and leverage, with selected positions closed at the previous mark. Those details are venue-specific. The relevant invariant is not simply that accounting balances afterward: the implementation must also select and charge the counterparties its specification permits.

Loss allocation review across independent boundaries A price gap enters the eligibility check, then the venue's execution and backstop policy, then any permitted counterparty closure. Evidence beneath each stage changes from account state to available liquidity to selection and settlement records. EligibilityAccount stateVenue loss policyExecutable liquidityCounterparty closeAllocation record Insurance participation and stage order must come from the venue's specification.
Review boundaries, not a universal execution waterfall. A venue can enter its deleveraging path directly under its documented conditions.
Eligibility evidence
Balances, position state and the exact price observation establish why intervention became permissible.
Loss-policy evidence
Execution attempts and eligible backstop resources explain which branches were available.
Allocation evidence
Counterparty selection and settlement records show who absorbed the remaining loss.

Tarun Chitra's revised ADL study analyzes the Hyperliquid episode of . The author reports $2.1 billion of positions closed in 12 minutes. That is a study's notional-closure figure, not stolen funds and not a measurement we reproduced. The revision history records corrected empirical analysis, so retain the version when citing it.

The counterparty queue needs boundary tests of its own. Compare positions with equal ranking values, account equity approaching the division boundary and a position that changes size between selection and execution. Specify the tie rule and the point at which the selection snapshot becomes binding. If another transaction can change the inputs, the implementation needs a documented revalidation or atomic execution rule. Capture the selected account set so the result can be independently inspected.

Turn the case into a test request: replay the selected counterparties, compare their closes with the specified ranking and reconcile total loss allocation. Include accounts with no open positions where the specification promises protection. Restoring venue solvency does not establish that every trader retained their expected profit.

Scoping checklist for a perps audit

A perpetual futures DEX audit quote should identify the deployable system and the market configuration it covers. A contract-only review can be appropriate for a narrow change. It becomes misleading when its conclusion is presented as evidence about an unreviewed matcher, oracle operator or emergency process.

  1. Freeze the code revision and inventory the contracts, matching service, keeper logic and administrator-controlled parameters. Name excluded components in the signed scope.
  2. Deliver the account model with unit conventions. Include collateral conversion, funding settlement and the transitions that permit a withdrawal.
  3. Supply the complete market manifest and resolve inherited defaults. Attach tier-boundary tests rather than selecting a familiar asset as a proxy for every market.
  4. Define observable pass conditions for each failure scenario.
  5. Require reproducible findings and remediation checks against the release revision. Separate accepted economic assumptions from verified implementation behavior.
  6. Assign ownership for post-launch parameter changes and monitoring. A new market or changed margin table should trigger a documented review decision. Record who can accept that change, which test outputs they must inspect and where the configuration snapshot will be retained. This makes a later review traceable to the actual release rather than to an informal approval in a chat.

Compare that package with the scope and resolution fields in an audit report. Use the member directory to find relevant public work, then inspect an actual engagement through a profile such as Trail of Bits. A firm's presence in a directory is a starting point for checking evidence, not confirmation that a particular derivatives engine was reviewed.

The handoff is complete when another engineer can run the agreed liquidation and settlement cases from the supplied revision and explain every balance difference. Keep the expected output with the test. That gives the next parameter review something concrete to compare.

Frequently asked questions

Can an audit of an EVM vault cover the matching engine?

Only if the signed scope includes the matching engine and its interfaces. Ask which revision, service configuration and trust assumptions were reviewed. A vault finding cannot establish the behavior of an unexamined matcher.

What changes if a market is delisted during the engagement?

Preserve the original inventory and add the delisting transition to scope. Closing existing positions and settling residual liabilities can remain relevant after new positions are disabled. Document which release and configuration each finding concerns.

Can a confidential market-maker agreement be omitted from the public report?

The reviewer still needs any agreement that the liquidity model depends on. A public report can describe the dependency and its verification limit without exposing confidential commercial terms. Do not present assumed liquidity as observed executable depth.