Explore how Perpetual DEXs are built and secured. Learn about their core architecture, smart contracts and key security mechanisms.

Decentralized Finance is transforming how derivatives trading works, and Perpetual Decentralized Exchanges are at the center of this change. These exchanges allow traders to open futures positions called perpetual contracts on assets like BTC, ETH, or even smaller tokens, all without expiration dates. Traders can use leverage to increase their exposure, and smart contracts automatically manage pricing, funding payments, and settlements.
As of October 2025, on-chain perpetuals have reached over $1.5 trillion in monthly trading volume, up 52% year-over-year, now making up 18% of the global derivatives market. This growth has been driven by the move away from centralized exchanges (CEXs) after regulatory crackdowns and past collapses like FTX. The rise of perpetuals isn’t just hype it’s built on solid mechanics like real-time mark-to-market settlements, dynamic funding rates that keep perp prices close to spot, and composability with other DeFi protocols such as lending markets and yield optimizers.
However, leverage comes with high risk. In 2025 alone, over $3.2 billion in losses have come from perp-related exploits, including oracle manipulation, flash loan attacks, and mass liquidations that destabilized entire ecosystems.
Perpetual futures, or perps, have their roots in traditional finance long before the crypto boom. The idea first appeared in 1993, when Nobel laureate Robert Shiller introduced the concept of continuous futures, contracts that never expire and continuously track an asset’s spot price. The main goal was to allow traders and investors to hedge their positions indefinitely, without needing to roll over expiring futures contracts.
The mechanism that makes this work is called the funding rate, a periodic payment between long and short traders that keeps the perpetual contract’s price close to the spot price. In simple terms:

If the perp price trades above the spot price, long traders pay shorts, and vice versa. This system ensures that prices don’t drift too far apart.
Although the concept existed for decades, it wasn’t implemented until crypto markets demanded 24/7 trading tools. In 2016, BitMEX launched the first crypto perpetual contract, XBTUSD which introduced:
Traders used Bitcoin as both the margin and settlement asset, with profits and losses updating continuously:

This innovation quickly became a cornerstone of the crypto derivatives market, with BitMEX handling over $1 trillion in annual volume by 2018. However, centralized risks, like the 2020 AML violations that led to regulatory fines, highlighted the system’s weaknesses.
Meanwhile, traditional finance (TradFi) caught up. In December 2017, CME Group launched Bitcoin futures, and by 2021, it introduced smaller “nano” perpetuals aimed at retail traders. Unlike BitMEX, CME’s contracts are cash-settled in USD, offer lower leverage (5–20x), and are regulated by the CFTC. Funding rates are calculated using time-weighted average prices (TWAPs) to prevent manipulation, and liquidations are managed through clearinghouse auctions.
As of 2025, U.S. regulated perpetual markets have grown over 300%, with CME’s ETH perpetuals seeing $60 billion in daily volume. Other platforms followed suit, Deribit combined options and perps, while Bakkt focused on institutional-grade custody.
Key mechanisms in traditional perpetual markets include:
| Aspect | BitMEX (Offshore) | CME (Regulated) |
|---|---|---|
| Leverage | Up to 100x | 5–20x |
| Settlement | Inverse (BTC) | Linear (USD) |
| Funding Frequency | 8 hours | 1 hour |
| Oversight | None | CFTC |
| Volume (Oct 2025) | $550B/month | $120B/month |
While traditional perps expanded access to leverage, they relied on centralized trust, custodians, clearinghouses, and intermediaries. Decentralized Finance (DeFi) flipped this model entirely, using smart contracts and on-chain oracles to automate everything transparently. The first major example was dYdX (2018), which brought BitMEX’s model on-chain, marking the start of the DeFi perpetual revolution, where code replaced intermediaries.
DeFi perpetual contracts borrow the core ideas from traditional finance but adapt them for the realities of blockchain systems. A perpetual contract (or perp) is an agreement between traders to buy or sell an asset in the future, but unlike normal futures, it never expires. Traders can go long (betting the price will rise) or short (betting it will fall). To protect against volatility, every position must be backed by collateral, usually between 100% and 200% of the trade’s value.
Initial Margin: The minimum collateral required to open a position.
Initial Margin = Position Value / Leverage
(For example, at 100x leverage, you only need 1% of the position’s value.)
Funding Payment: Periodic payments between long and short traders to keep the perpetual price close to the spot price.
Funding Payment} = Position Size x Funding Rate x Time Interval
These funding payments are typically settled every 1–8 hours.
In DeFi, smart contracts can’t directly access market prices, so they rely on oracles such as Chainlink or Pyth. These oracles deliver time-weighted average prices (TWAP) to prevent sudden manipulation through flash loans or short-term volatility spikes:

| Feature | TradFi Perps | DeFi Perps |
|---|---|---|
| Expiry | None | None |
| Leverage | 5–100x | 10–200x |
| Counterparty | Clearinghouse | Smart Contracts |
| Funding Mechanism | Premium-based | Imbalance-based |
| Settlement | Centralized | On-chain |
Perpetual DEXes combine off-chain order processing and on-chain smart contracts to deliver fast and trustless trading. Most run on Layer 2 networks like Arbitrum, Optimism, or Base to reduce fees and increase speed.
Two main models power these platforms:
In an Automated Market Maker (AMM) model, traders interact with a shared liquidity pool called GLP. Liquidity providers (LPs) deposit tokens into this pool, and traders open long or short positions against it. The AMM adjusts prices based on trade size and pool balance:

The larger the trade compared to the pool, the greater the slippage. Most systems cap this effect around 0.5% to protect users from excessive losses.
A Central Limit Order Book (CLOB) model works more like traditional exchanges. Traders place bids and asks, and a matching engine pairs them. The matching usually happens off-chain for speed, while settlements occur on-chain for transparency. Platforms like dYdX achieve near-millisecond trade speeds using Cosmos validators and optimized mempools.
All Perpetual DEXes rely on a few key systems:
Each step happens within a single blockchain transaction, ensuring that all actions—price validation, margin checks, and settlements—occur atomically and transparently.

Perpetual DEXes run on audited EVM smart contracts, often using OpenZeppelin’s UpgradableProxy for flexibility. Inspired by GMX on Arbitrum, they use modular contracts with ERC20 extensions and strict access controls like onlyKeeper for security.
Note: The following snippets are pseudocode examples and should not be used in production environments.
1// Defines a user's position in a market: tracks exposure, collateral, and timestamps for funding/liquidation checks
2struct Position {
3 uint256 size; // Nominal size in USD (notional value)
4 uint256 collateral; // User's deposited collateral (in USD equivalent)
5 uint256 avgEntryPrice; // Average entry price, weighted by size increases
6 bool isLong; // True for long, false for short positions
7 uint256 lastFundingTime; // Timestamp of last funding accrual to avoid overpayments
8 address collateralToken; // ERC20 token used as collateral (e.g., USDC)
9}
10// Global mapping: user address -> market address -> their active position
11mapping(address => mapping(address => Position)) public positions;Opening a Position, this function queues an increase order for keeper execution, validating margins upfront.
1function createIncreaseOrder(
2 address market, // Target market (e.g., BTC-USD)
3 bool isLong, // Position direction
4 uint256 size, // Desired notional size in USD
5 uint256 collateralAmount, // Amount of collateral to add
6 address collateralToken, // Token for collateral (must be approved)
7 uint256 acceptablePrice, // Max price tolerance for slippage
8 uint256 executionFee, // Gas/relayer fee
9 bytes calldata data // Optional data for pre-swap hooks (e.g., via 1inch)
10) external nonReentrant { // Prevents reentrancy during execution
11 // Fetch current mark price from oracle to validate
12 uint256 markPrice = getMarkPrice(market);
13 require(markPrice <= acceptablePrice, "Price above acceptable"); // Slippage guard
14
15 // Ensure sufficient collateral for leverage (e.g., MAX_LEVERAGE = 100)
16 uint256 minCollateral = (size * markPrice) / MAX_LEVERAGE + executionFee;
17 require(collateralAmount >= minCollateral, "Insufficient collateral");
18
19 // Pull collateral from user to this contract (acts as vault)
20 IERC20(collateralToken).transferFrom(msg.sender, address(this), collateralAmount);
21
22 // Queue order for off-chain keeper to execute (reduces gas for user)
23 increaseOrders[nonces[msg.sender]++] = IncreaseOrder({
24 market: market,
25 isLong: isLong,
26 sizeDelta: size, // Increment to position size
27 collateralDelta: collateralAmount,
28 price: markPrice,
29 collateralToken: collateralToken,
30 executionFee: executionFee
31 });
32
33 // Event for indexing/tracking by frontends and subgraphs
34 emit IncreaseOrderCreated(msg.sender, market, size, isLong);
35}Keepers later fulfill, merge into existing position or create new, updating open interest.
Closing a Position
1function createDecreaseOrder(
2 address market, // Market to reduce exposure in
3 uint256 sizeDelta, // Portion of size to close (partial OK)
4 uint256 collateralDelta, // Collateral to withdraw (up to available)
5 bool receiveInNative, // True for ETH unwrap, false for ERC20
6 address receiver, // Recipient (defaults to msg.sender)
7 uint256 acceptablePrice, // Min price for slippage on close
8 bytes calldata data // Callback data for post-swap
9) external nonReentrant {
10 // Load user's current position
11 Position storage pos = positions[msg.sender][market];
12 require(pos.size > 0, "No position"); // Sanity check
13
14 // Real-time PnL: Positive for profitable direction
15 uint256 markPrice = getMarkPrice(market);
16 int256 pnl = isLong ? int256(sizeDelta * (markPrice - pos.avgEntryPrice)) / pos.avgEntryPrice
17 : int256(sizeDelta * (pos.avgEntryPrice - markPrice)) / pos.avgEntryPrice;
18
19 require(markPrice <= acceptablePrice, "Price above acceptable"); // For shorts, adjust logic if needed
20
21 // Deduct trading fees (e.g., FEE_PPM = 50 for 0.05%)
22 uint256 fee = (sizeDelta * FEE_PPM) / 1e6;
23 uint256 netCollateral = uint256(int256(collateralDelta) + pnl) > fee ?
24 collateralDelta + uint256(pnl) - fee : 0; // Clamp to zero if underwater
25
26 // Shrink position state
27 pos.size -= sizeDelta;
28 pos.collateral -= collateralDelta;
29 if (pos.size == 0) delete positions[msg.sender][market]; // Clean up empty slots
30
31 // Payout to receiver (unwrap ETH if flagged)
32 if (netCollateral > 0) {
33 if (receiveInNative && collateralToken == WETH) {
34 WETH.withdraw(netCollateral); // Unwrap to ETH
35 payable(receiver).transfer(netCollateral);
36 } else {
37 IERC20(pos.collateralToken).transfer(receiver, netCollateral);
38 }
39 }
40
41 // Log for analytics and disputes
42 emit DecreaseOrderExecuted(msg.sender, market, sizeDelta, pnl, fee);
43}Funding.sol refreshes rates hourly, accruing to positions:
1function updateFunding(address market) external { // Callable by keepers/timers
2 // Snapshot open interest by side
3 uint256 longOI = openInterest[market][true];
4 uint256 shortOI = openInterest[market][false];
5 uint256 totalOI = longOI + shortOI;
6
7 // Compute skew: Positive if longs dominate
8 int256 imbalance = int256(longOI) - int256(shortOI);
9 uint256 fundingRate = totalOI > 0 ?
10 (uint256(imbalance) * MAX_FUNDING_RATE * 1e18) / totalOI : 0; // Scaled for precision
11
12 // Bound rate (e.g., MAX_FUNDING_RATE = 0.05% per hour)
13 fundingRates[market] = fundingRate > MAX_FUNDING_RATE ? MAX_FUNDING_RATE : fundingRate;
14
15 // Apply to open positions: Longs pay if positive rate
16 for (uint i = 0; i < positionsInMarket[market].length; i++) {
17 Position storage pos = positions[positionsInMarket[market][i].user][market];
18 if (pos.size > 0) {
19 int256 payment = int256(pos.size * fundingRate * (block.timestamp - pos.lastFundingTime)) / 1e18 / 3600;
20 if (pos.isLong) {
21 pos.collateral = pos.collateral > uint256(payment) ? pos.collateral - uint256(payment) : 0; // Clamp
22 } else {
23 pos.collateral += uint256(payment); // Shorts receive
24 }
25 pos.lastFundingTime = block.timestamp; // Reset timer
26 }
27 }
28
29 emit FundingUpdated(market, fundingRate, longOI, shortOI);
30}
31Liquidation.sol leans on oracles for impartiality:
1function liquidate(address user, address market) external nonReentrant { // Only keepers
2 // Snapshot position
3 Position memory pos = positions[user][market];
4 require(pos.size > 0, "No position");
5
6 uint256 oraclePrice = getOraclePrice(market); // Manipulation-resistant feed
7 uint256 liquidationPrice = calculateLiquidationPrice(pos, oraclePrice); // Based on maintenance margin
8
9 // Verify breach (e.g., 2.5% buffer over bankruptcy price)
10 uint256 bankruptcyPrice = pos.collateral * oraclePrice / pos.size;
11 require(oraclePrice <= liquidationPrice || oraclePrice >= liquidationPrice, "Not liquidatable"); // Dir-dependent
12
13 // Partial liq: Up to 50% to minimize impact
14 uint256 liqSize = pos.size > pos.size / 2 ? pos.size / 2 : pos.size;
15 uint256 bounty = (liqSize * LIQ_BOUNTY_PCT) / 100; // e.g., 5% incentive to keeper
16
17 // Compute liq PnL (may be negative)
18 int256 liqPnL = calculatePnL(pos, oraclePrice, liqSize);
19 uint256 remainingCollateral = pos.collateral + uint256(liqPnL) - bounty;
20
21 // Refund any surplus to user
22 if (remainingCollateral > 0) {
23 IERC20(pos.collateralToken).transfer(user, remainingCollateral);
24 }
25 // Keeper payout from protocol fees/insurance
26 payable(msg.sender).transfer(bounty); // Or token equivalent
27
28 // Prorate position reduction, update OI
29 pos.size -= liqSize;
30 pos.collateral -= (pos.collateral * liqSize / pos.size); // Proportional
31
32 // Route any profit to insurance fund
33 if (liqPnL > 0) insuranceFund += uint256(liqPnL);
34
35 emit LiquidationExecuted(user, market, liqSize, bounty);
36}
37For dYdX (Cosmos SDK), logic migrates off-chain, gRPC indexers pair orders, settling via Subaccount equity checks (equity = collateral + unrealizedPnL). Liquidations auction through state committees.
Liquidation Flow Diagram:

Below are the most notable real attack vectors identified in perpetual DEX protocols such as GMX, Perpetual Protocol, Drift, Mango, dYdX, and Hyperliquid.
Smart contracts form the backbone of every perpetual DEX. Even small errors in logic or math can lead to massive losses.
Real Attacks:
Even one bug can drain liquidity. Safeguard your Perpetual DEX from exploits and risks with QuillAudits’ expert DeFi audits.
Oracles are critical to determining position values and liquidation thresholds. Manipulating price feeds or exploiting update delays can directly result in false liquidations or unfair profit extraction.
Real Attacks:
Leverage amplifies the impact of economic imbalances. Attackers often use large positions or funding loops to distort market dynamics.
Real Attacks:
Validators and bots exploit transaction ordering, mempool visibility, and latency to extract profits from perpetual DEX traders.
Real Attacks:
Despite claims of decentralization, governance and upgrade paths can become centralized points of failure.
Real Attacks:

Hyperliquid is a Solana-based CLOB perpetual DEX optimized for high-frequency trading and low-latency execution. It supports 20–100x leverage across more than 80 markets and employs advanced machine learning algorithms to manage risk and funding rate imbalances. With a record-breaking monthly trading volume surpassing $300 billion, Hyperliquid currently leads the perpetual DEX ecosystem in both scale and throughput.
dYdX operates on a Cosmos app chain, leveraging a fully decentralized CLOB structure for institutional-grade trading. It offers up to 20x leverage across multiple perpetual markets and provides sub-20ms execution speeds with on-chain settlement. dYdX remains a top-tier derivatives venue with billions in monthly trading volume and around a billion dollars in open interest.
GMX uses an AMM model deployed on Arbitrum and Avalanche, enabling traders to take 10–50x leveraged positions against shared GLP liquidity pools. The platform features dynamic pricing and virtual reserves to simulate deep liquidity while maintaining strict open interest caps and robust risk management. GMX continues to be one of the most trusted AMM-based perpetual DEXes, processing billions in monthly volume.
Drift Protocol is a Solana-based AMM perpetual DEX offering 5–20x leverage on a wide range of markets. It uses oracle-driven pricing, just-in-time liquidity provisioning, and automated keeper systems for efficient liquidation handling. Drift combines strong performance with composability within the Solana ecosystem, maintaining a healthy balance between volume growth and capital efficiency.
Aevo is a CLOB-based perpetual exchange built on a custom Ethereum Layer 2 network. It specializes in trading emerging and pre-launch tokens, with up to 50x leverage. Aevo’s off-chain intent aggregation mechanism ensures high matching efficiency and low gas costs, positioning it as a preferred venue for advanced derivatives traders seeking speed and flexibility.
Gains Network operates a dynamic AMM model across Polygon and Arbitrum, offering 20–150x leverage across crypto, forex, and index markets. Its single-sided liquidity design enables efficient capital utilization while maintaining deep liquidity for traders. The protocol continues to expand its market coverage and remains a major player in leveraged DeFi trading.
Perpetual Protocol on Optimism utilizes a virtual AMM (vAMM) mechanism with an integrated insurance fund for liquidation stability. It supports up to 10x leverage across leading crypto assets and remains a benchmark for accessible, user-friendly perpetual trading. The platform’s focus on reliability and transparency makes it a long-standing fixture in the DeFi derivatives space.
Vertex is a CLOB-based perpetual DEX on Ethereum Layer 2 networks such as Arbitrum and Base. It unifies spot and derivatives trading under a shared margin system, allowing 10–50x leverage and efficient collateral management. Vertex offers a professional-grade trading experience with a focus on transparency, performance, and user control.
Perpetual DEXes represent the synthesis of financial theory and blockchain engineering, combining Shiller’s vision of continuous futures with DeFi’s ethos of transparency. Yet, as 2025’s exploits reveal, security is not a feature, it’s architecture. Building resilient perpetual DEXes demands an interdisciplinary approach, rigorous audits, formal methods, and robust oracle frameworks.
Contents

Get updates on our community, partners, events, and everything happening across the ecosystem — delivered straight to your inbox.
Subscribe Now!

Office 104/105 Level 1, Emaar Square, Building 4 Sheikh Mohammed Bin Rashid Boulevard Downtown Dubai, United Arab Emirates P.O box: 416654
Privacy PolicyAll Rights Reserved. © 2025. QuillAudits - LLC
Office 104/105 Level 1, Emaar Square, Building 4 Sheikh Mohammed Bin Rashid Boulevard Downtown Dubai, United Arab Emirates P.O box: 416654
hello@quillaudits.comAll Rights Reserved. © 2025. QuillAudits - LLC
Privacy Policy