A decentralized perpetual swaps protocol allows users to trade leveraged futures contracts without a central intermediary. Unlike traditional futures, perpetuals have no expiry date and use a funding rate mechanism to keep their price tethered to the underlying asset's spot price. The core architectural challenge is replicating the efficiency and liquidity of centralized exchanges (CEXs) like Binance or Bybit within a trustless, on-chain environment. This requires a robust system for position management, price oracles, collateral and margin, and a mechanism to balance long and short interest.
How to Architect a Decentralized Perpetual Swaps Protocol
How to Architect a Decentralized Perpetual Swaps Protocol
A technical blueprint for building a decentralized perpetual futures protocol, covering core components, smart contract architecture, and key design decisions.
The foundation of the protocol is its smart contract system. You'll need several core contracts: a Vault to custody all user collateral, a Perpetual or Market contract to manage positions and P&L, a Price Oracle for secure price feeds, and an Order Book or Automated Market Maker (AMM) for trade execution. For maximum capital efficiency, many protocols like dYdX and GMX use a shared liquidity pool model where liquidity providers (LPs) earn fees from traders. The Vault must isolate risk by ensuring one trader's bad debt is socialized only among LPs, not other traders, using a carefully designed liquidation engine.
Accurate and manipulation-resistant price data is non-negotiable. You must integrate a decentralized oracle like Chainlink for main asset prices or build a robust time-weighted average price (TWAP) oracle using data from major DEXes. The funding rate is calculated periodically (e.g., every 8 hours) based on the difference between the perpetual's mark price (from the oracle) and its index price. This rate is paid from one side of the market to the other, incentivizing trades that bring the price back to peg. The formula is typically: Funding Rate = (Twap Premium / Index Price) / Funding Interval.
The liquidation engine is the protocol's risk manager. Each position has a maintenance margin threshold (e.g., 5%). If a position's margin ratio falls below this due to price movement, it becomes eligible for liquidation. Keepers (external bots) are incentivized by a liquidation fee to close these positions. The logic must handle partial liquidations and define a clear liquidation price formula. To prevent instant re-liquidations, a buffer is often added. Protocols must also guard against maximum loss scenarios to protect the shared pool.
Finally, consider the trade execution model. An order book offers familiar CEX-like precision but can be gas-intensive and require off-chain matching with on-chain settlement. An AMM-based model (like Perpetual Protocol v1's vAMM) uses virtual liquidity for zero slippage but relies entirely on oracle prices. A hybrid approach, such as an RFQ (Request-for-Quote) system or limit order book built on an L2, is common in modern designs. The choice dictates your scalability needs and whether you'll deploy on an L1 like Ethereum or an L2 like Arbitrum or Base for lower fees.
Prerequisites and Core Dependencies
Building a decentralized perpetual swaps protocol requires a robust technical foundation. This section covers the essential knowledge and core components you must understand before writing a single line of code.
A deep understanding of Ethereum Virtual Machine (EVM) fundamentals is non-negotiable. You must be proficient in Solidity for smart contract development, with a focus on gas optimization, security patterns, and upgradeability strategies. Familiarity with Hardhat or Foundry for development, testing, and deployment is essential. You should also understand core DeFi primitives like ERC-20 tokens, oracles, and the mechanics of Automated Market Makers (AMMs) from protocols like Uniswap V3, as perpetual protocols often build upon similar liquidity and pricing concepts.
The protocol's architecture relies on several critical dependencies. First, a price feed oracle is required to fetch accurate, low-latency market data for margin calculations and liquidation triggers. Chainlink is a common choice, but you may need a custom solution for exotic assets. Second, you need a mechanism for cross-margin accounting and position management, which involves tracking user equity, open positions, and unrealized P&L. Third, a funding rate mechanism must be implemented to balance long and short interest, typically using a time-weighted average price (TWAP) difference between the perpetual's mark price and the underlying spot index.
Liquidity provisioning is a core challenge. You must decide between an order book model (like dYdX v3) or an AMM-based pool model (like GMX). An order book offers better capital efficiency for large trades but requires sophisticated off-chain matching engines. An AMM model relies on liquidity pools where LPs act as the counterparty to all trades, simplifying on-chain execution but introducing impermanent loss and liquidity fragmentation risks. Your choice dictates the entire backend architecture for trade matching and price discovery.
Security considerations are paramount. You must implement robust liquidation engines that can withstand volatile market conditions and prevent protocol insolvency. This involves setting appropriate margin ratios, designing efficient liquidation incentives, and creating circuit breakers. Furthermore, the protocol must be resilient to oracle manipulation attacks, flash loan exploits, and economic attacks on the funding rate mechanism. Extensive testing, including fuzzing and formal verification for critical components, is a prerequisite for mainnet deployment.
Finally, you need to plan for the user interface and indexing layer. While not part of the core protocol, a functional front-end requires interaction with smart contracts via a library like ethers.js or viem. You will also need a subgraph (using The Graph) or a custom indexer to efficiently query open positions, trading history, and pool statistics off-chain, as these queries are prohibitively expensive to perform directly on-chain.
How to Architect a Decentralized Perpetual Swaps Protocol
A technical guide to designing the foundational components of a decentralized perpetual swaps protocol, covering the virtual AMM, funding rate mechanism, and risk management layers.
The core of a decentralized perpetual swaps protocol is a virtual automated market maker (vAMM). Unlike a traditional AMM that holds real assets, a vAMM is a purely mathematical pricing curve, such as the constant product formula x * y = k. It determines the price for the perpetual contract based on the virtual reserves of the long and short sides. This design decouples price discovery from actual liquidity, allowing for deep liquidity and high leverage with minimal capital. Trades are settled in a single collateral asset, typically a stablecoin, with profits and losses settled in real-time via the protocol's internal accounting system.
To keep the perpetual contract's price anchored to the spot market, protocols implement a funding rate mechanism. This is a periodic payment exchanged between long and short traders. When the perpetual price trades above the spot index price, longs pay funding to shorts, incentivizing selling pressure. When it trades below, shorts pay longs. The funding rate is typically calculated as Funding Rate = (Perp Price - Index Price) / Index Price * Time Factor. This creates a powerful economic force that encourages arbitrage and maintains price convergence without requiring direct spot asset settlement.
Risk management is enforced through a multi-layered system. The primary layer is the margin and liquidation engine. Each position must maintain a minimum margin ratio, calculated as (Collateral - Unrealized PNL) / Position Size. If this ratio falls below a maintenance threshold, the position becomes eligible for liquidation. Liquidators can close the position in exchange for a bounty, with the protocol's insurance fund covering any remaining bad debt. Advanced protocols implement circuit breakers, position size limits, and volatility-based margin requirements to mitigate systemic risk during extreme market events.
Oracle integration is critical for accurate pricing and liquidation. The protocol must securely fetch the spot index price from a decentralized oracle network like Chainlink or a custom medianizer of CEX prices. This index price feeds into the funding rate calculation and acts as the benchmark for liquidations. To prevent oracle manipulation attacks, protocols often use a time-weighted average price (TWAP) over a short window and implement a delay between price updates and their use in critical functions, allowing time for dispute or pausing mechanisms to activate.
The final architectural consideration is the collateral and settlement layer. Most protocols use a single collateral token (e.g., USDC) deposited into a smart contract vault. All profits, losses, funding payments, and fees are denominated and settled in this asset. This simplifies accounting and interoperability. When a user opens a position, they lock collateral; the protocol mints a virtual position token representing their exposure. The smart contract system must accurately track each user's balance, aggregate open interest, and manage the distribution of fees to liquidity providers and the protocol treasury.
Liquidity Model Comparison: vAMM vs. Order Book
A technical comparison of the two primary liquidity models for structuring a perpetual swaps protocol, focusing on implementation complexity, capital efficiency, and user experience.
| Feature / Metric | Virtual AMM (vAMM) | Central Limit Order Book (CLOB) |
|---|---|---|
Liquidity Source | Virtual liquidity pool | Real limit orders from LPs/traders |
Capital Efficiency | High (leverages virtual capital) | Low (requires locked collateral) |
Price Discovery | Oracle-based with funding rates | Order book matching |
Slippage Model | Bonding curve (e.g., x*y=k) | Order book depth |
Implementation Complexity | Medium (smart contract logic) | High (off-chain matching engine) |
Gas Cost for Opening | ~150k-200k gas | ~80k-120k gas (on-chain settlement) |
Typical Fee Structure | 0.05% - 0.1% taker fee | 0.02% - 0.05% maker/taker fees |
Example Protocols | Perpetual Protocol, GMX | dYdX (v3), Vertex Protocol |
How to Architect a Decentralized Perpetual Swaps Protocol
A guide to designing the core smart contract components for a decentralized perpetual futures protocol, covering key modules, security considerations, and gas optimization strategies.
A decentralized perpetual swaps protocol allows users to trade leveraged derivatives with no expiration date, using on-chain smart contracts as the settlement layer. Unlike centralized exchanges, the core architecture must be trust-minimized, composable, and resistant to manipulation. The primary system components include a vault for collateral management, an order book or automated market maker (AMM) for price discovery, a keeper network for position execution, and an oracle for secure price feeds. Protocols like GMX, dYdX, and Perpetual Protocol each implement variations of this architecture, balancing trade-offs between capital efficiency, latency, and decentralization.
The collateral vault is the foundational contract that holds all user deposits. It must securely account for each user's margin, handle multiple collateral assets (like WETH, USDC, wBTC), and calculate global debt pools. A critical design choice is between an isolated margin model, where each position's risk is contained, and a cross-margin model within a shared liquidity pool, which offers higher capital efficiency but introduces systemic risk. The vault also manages the protocol's solvency by liquidating undercollateralized positions, a function typically triggered by external keeper bots when the maintenance margin threshold is breached.
Price discovery and trade execution are handled by the exchange engine. Two dominant models exist: an off-chain order book with on-chain settlement (used by dYdX v3) and an on-chain virtual AMM (vAMM) like Perpetual Protocol's. The vAMM model uses a constant product formula x * y = k to determine prices without requiring counterparties, but relies entirely on oracle prices for mark-to-market. Alternatively, protocols may use a liquidity pool model (like GMX's GLP), where liquidity providers earn fees from traders' profits and losses, acting as the collective counterparty to all positions.
A secure and low-latency oracle is non-negotiable for perpetuals, as prices determine funding rates, profit/loss, and liquidation triggers. Most protocols use a decentralized oracle network like Chainlink, often with a price feed delay (e.g., a 2-minute TWAP) to prevent flash loan manipulation. The funding rate mechanism, which periodically pays longs or shorts to keep the perpetual contract price anchored to the spot price, is calculated and applied on-chain based on the difference between the mark price (from the oracle) and the index price.
The keeper network consists of permissionless bots that perform essential system upkeep. Keepers are incentivized by fees to: execute limit orders, trigger liquidations of risky positions, and update funding rates. The smart contracts must expose these functions with clear incentives and access conditions, often using a commit-reveal scheme or time priority to prevent front-running. Gas efficiency is paramount, as keeper operations are frequent; consider using EIP-712 for signed orders and aggregating state updates to minimize transactions.
Finally, risk management parameters must be immutable or governance-upgradable via a TimelockController. Key parameters include: initial and maintenance margin ratios, maximum leverage (e.g., 10x-50x), funding rate intervals, liquidation penalties, and oracle staleness thresholds. A well-architected protocol will compartmentalize these modules, use OpenZeppelin libraries for security, and undergo rigorous audits. The end goal is a system that is robust under high volatility, economically sustainable, and transparent for users and integrators.
Core Contract Functions and Events
A perpetual swaps protocol is defined by its smart contract logic. This section details the essential functions and events that govern trading, risk management, and system state.
Position Management Functions
These functions allow users to open, adjust, and close leveraged positions.
openPosition(): Accepts collateral, sets leverage, and creates a new long or short position. It validates margin requirements and updates the global open interest.addMargin()/removeMargin(): Lets a trader modify the collateral backing an existing position, affecting its liquidation price.closePosition(): Settles a position's P&L, returns remaining collateral to the user, and reduces the global open interest. Protocols like GMX and dYdX implement these with slight variations in fee structure and price oracle integration.
Liquidation Engine
Critical for maintaining protocol solvency, this function automatically closes underwater positions.
liquidatePosition(): Called by keepers when a position's health factor falls below the maintenance margin threshold. It calculates the bad debt, applies a liquidation penalty, and may use the position's collateral to cover losses. The design of this function (e.g., partial vs. full liquidation, penalty size) is a major differentiator for protocols like Perpetual Protocol and Synthetix.
Oracle and Pricing Functions
Secure price feeds are the backbone of any derivatives protocol. These functions manage data ingestion and validation.
updatePrice(): Typically a permissioned function called by oracles or keepers to submit new market data for an asset. Robust implementations use Pyth Network or Chainlink with multi-source aggregation and staleness checks.getMarkPrice()/getIndexPrice(): View functions that return the current price used for mark-to-market P&L and the underlying index price, respectively. The spread between them influences funding rates.
Funding Rate Mechanism
This function periodically reconcries longs and shorts to keep the perpetual contract price anchored to the spot price.
payFunding(): Called at regular intervals (e.g., hourly). It calculates the funding rate based on the premium of the mark price over the index price, then transfers payments from one side of the market to the other. The logic for rate calculation (e.g., time-weighted average premium) is defined here and is a key feature of protocols like ApeX Protocol.
Key Contract Events
Events are emitted for off-chain indexing and user interface updates. Essential events include:
PositionOpened(address indexed trader, uint256 positionId, bool isLong, uint256 size, uint256 collateral): Logs all new positions.PositionClosed(address indexed trader, uint256 positionId, uint256 pnl, bool isProfit): Records position settlement and P&L.PositionLiquidated(address indexed trader, uint256 positionId, address liquidator, uint256 liquidationFee): Emitted when a liquidation occurs, providing transparency into system health.
Risk and Parameter Configuration
Admin or governance functions that control protocol risk parameters.
setMaintenanceMarginRatio(): Adjusts the minimum collateral ratio before liquidation. A lower ratio allows higher leverage but increases systemic risk.setMaxOpenInterest(): Caps the total notional value of open positions for a specific market to manage concentrated risk.setLiquidationFeeRatio(): Sets the penalty paid to liquidators. These parameters are often managed via a timelock-controlled multisig or DAO vote in protocols like Gains Network.
Implementing the Position Lifecycle
A technical walkthrough of the core mechanisms—opening, managing, and closing positions—that define a decentralized perpetual swaps protocol.
The position lifecycle is the fundamental state machine of any perpetual swaps protocol. It governs a user's collateralized debt position from inception to termination, dictating the rules for margin, funding payments, and liquidation. Architecting this correctly is critical for protocol solvency and user experience. The lifecycle typically consists of three primary states: OPEN, ADJUSTED (where margin is added or removed), and CLOSED. A fourth, terminal state, LIQUIDATED, is triggered by an external keeper when a position's health falls below a safety threshold.
Opening a position begins with the openPosition function. A user specifies a size (notional value), collateral amount, and isLong flag. The protocol must validate this request against several parameters: the initialMarginRatio (IMR) to ensure sufficient collateral, the maxOpenInterest for the market to manage risk, and available liquidity. Upon validation, the protocol mints a virtual debt position and credits a virtual asset to the user. The user's account is debited the collateral, which is held in the protocol's vault. The Position struct is then recorded on-chain, storing the entry price, size, collateral, and cumulative funding rate snapshot.
Active positions are subject to funding payments, which periodically exchange a fee between longs and shorts to peg the perpetual contract's price to the underlying spot index. This is calculated off-chain by oracles and applied on-chain via a payFunding function. The protocol tracks a global cumulativeFundingRate for each market. When a user interacts with their position (adjusts, closes), the protocol settles the accrued funding payment by adjusting the position's realizedPnl and collateral balance. This mechanism ensures the contract price does not diverge significantly from the spot price without imposing an expiry date.
The most critical function for protocol safety is liquidatePosition. A position becomes eligible for liquidation when its margin ratio falls below the maintenanceMarginRatio (MMR), calculated as (collateral + unrealizedPnl) / (size). Keepers monitor positions and call this function to close the underwater position. The liquidation process involves closing the position at the current oracle price, applying a liquidationPenalty (a fee paid to the keeper from the remaining collateral), and returning any leftover collateral to the user. Robust liquidation logic, including partial liquidation and incentive mechanisms for keepers, is essential to prevent bad debt accumulation.
Finally, a user can voluntarily closePosition. This function calculates the final realizedPnl based on the exit oracle price versus the entry price, settles any remaining funding payments, and transfers the net collateral (initial collateral + realizedPnl - fees) back to the user. The position struct is then deleted, and the global open interest for that market is reduced. Properly architecting this flow requires careful handling of rounding, price slippage protection, and fee distribution (e.g., to protocol treasury and liquidity providers).
Implementing this lifecycle requires integrating with reliable price oracles like Chainlink or Pyth Network for mark prices, and designing a secure vault for collateral management. Audited reference implementations can be studied in protocols like GMX V1/V2, Synthetix Perps, and dYdX V3, each demonstrating different trade-offs in risk management, capital efficiency, and decentralization. The core challenge is balancing capital efficiency (low margin requirements) with systemic security (high enough ratios to withstand volatility).
Funding Rate Calculation and Settlement
A deep dive into the mechanism that anchors perpetual swap prices to their underlying spot markets, covering the mathematical models, on-chain implementation, and settlement logic.
Perpetual swaps, or perps, are derivative contracts that track an asset's price without an expiry date. Unlike futures, they do not settle at a future date. Instead, they use a funding rate mechanism to periodically exchange payments between long and short traders. This payment incentivizes traders to align the perpetual swap's price, known as the mark price, with the underlying asset's index price (a composite price from major spot exchanges). If the perpetual trades at a premium (mark > index), longs pay shorts. If it trades at a discount (mark < index), shorts pay longs. This creates a continuous economic force tethering the two prices.
The funding rate is calculated at regular intervals, typically every hour or eight hours. The core formula used by protocols like GMX and dYdX is: Funding Rate = (Premium / Index Price) * Funding Interval Factor. The premium is the difference between the mark and index prices. The Funding Interval Factor scales the rate to the chosen period (e.g., 1/8 for 8-hour funding). A positive result means longs pay; a negative result means shorts pay. This rate is then applied to a trader's position size to determine their payment or receipt. For example, with a 0.01% funding rate, a $10,000 long position would pay $1 to shorts.
Implementing this on-chain requires secure price oracles. The index price must be resilient to manipulation, often sourced from a decentralized oracle like Chainlink or a time-weighted average price (TWAP) from multiple DEXs. The mark price is typically the protocol's own time-weighted average mid-price from recent trades. The calculation and settlement logic is executed by a smart contract, often triggered by a keeper bot when the funding period elapses. The contract fetches the latest prices, computes the rate, and updates an internal accounting system to track each trader's accrued funding payments.
Settlement does not involve transferring collateral on every tick. Instead, protocols use an accrued funding model. The calculated funding rate is stored per market, and a trader's position has a lastFundingTimestamp. When a trader interacts with their position (e.g., adding/removing collateral, closing), the contract calculates the accrued funding since their last update: Accrued = Position Size * Funding Rate * Time Intervals. This amount is then settled by adjusting the trader's realized PnL or directly modifying their collateral balance. This gas-efficient method defers actual payment until interaction.
Advanced protocols incorporate a funding rate cap and smoothing mechanisms. A cap (e.g., ±0.75% per 8 hours) prevents extreme payments during volatile, illiquid markets. Smoothing, such as taking an average of the last few funding rates, reduces volatility in payments. Furthermore, the protocol's fee structure often takes a small cut of the funding payments as a protocol fee. When architecting, key decisions include the funding interval, oracle selection, cap parameters, and the settlement hook design to integrate seamlessly with your core trading and liquidation engine.
Essential Resources and Code References
These resources cover the core building blocks required to design a decentralized perpetual swaps protocol, from market mechanics and oracle design to smart contract security and liquidation flows.
Margin, Leverage, and Liquidation Logic
Perpetual swaps depend on isolated or cross-margin systems to manage trader leverage and protocol solvency. Liquidation logic must be deterministic, gas-efficient, and resistant to MEV.
Core components:
- Initial and maintenance margin calculations per position.
- Leverage caps based on asset volatility and liquidity.
- Liquidation price formulas derived from collateral, position size, and funding.
Design patterns used in production:
- Partial liquidations to reduce bad debt instead of closing full positions.
- Liquidation incentives paid to keepers or bots.
- Insurance funds to absorb losses during extreme volatility.
GMX, dYdX, and Vertex all use keeper-based liquidation systems rather than fully automatic contract execution.
When implementing this layer, simulate black swan scenarios using historical volatility spikes to test insolvency risk before deployment.
Liquidity Providers and Risk Management
Unlike spot AMMs, perpetual protocols expose LPs to trader PnL asymmetry. LP risk management determines long-term protocol sustainability.
Key mechanisms:
- Global PnL caps that limit trader profit relative to pool size.
- Dynamic funding rates to balance long and short open interest.
- Asset utilization limits to prevent overexposure to single markets.
Examples:
- GMX LPs take the opposite side of trader positions, earning fees but absorbing losses.
- Some newer designs split LP roles into passive liquidity and backstop insurance providers.
Risk dashboards should track:
- Open interest by asset
- Net protocol exposure
- LP unrealized PnL
Ignoring LP risk leads to liquidity flight, which directly degrades pricing and increases liquidation cascades.
How to Architect a Decentralized Perpetual Swaps Protocol
Building a decentralized perpetual swaps protocol requires a security-first architecture that mitigates counterparty, market, and systemic risks inherent to leveraged trading.
The core risk in a perpetual swaps protocol is counterparty risk, which is managed by the clearing mechanism. Unlike centralized exchanges that act as counterparty, decentralized protocols must create a trustless system where the protocol itself or a pool of liquidity backstops all positions. This is typically achieved through a global insurance fund and a vault system that holds collateral. When a position is liquidated at a loss, the loss is first covered by the trader's remaining margin, then by the insurance fund, and finally, in extreme cases, by a mechanism like auto-deleveraging (ADL) or socialized loss among profitable traders. Protocols like dYdX v3 and GMX implement variations of this layered loss absorption model.
Market risk is primarily addressed through the oracle design and liquidation engine. Price feeds must be robust against manipulation; using a decentralized oracle network like Chainlink with multiple data sources and heartbeat updates is standard. The liquidation engine must be permissionless and efficient. It should calculate a position's health based on the formula: Health Factor = (Collateral Value) / (Position Notional * Maintenance Margin Ratio). When this factor falls below 1, the position becomes eligible for liquidation. The engine must account for slippage during liquidation and ensure liquidators are sufficiently incentivized with a bounty, typically 5-10% of the position size, to maintain system solvency.
Systemic risks include smart contract vulnerabilities and economic attacks. The protocol's smart contracts, especially the core Perpetual contract handling positions and the Liquidation contract, must undergo rigorous audits and formal verification. Use established libraries like OpenZeppelin and implement circuit breakers that can pause trading or liquidations during extreme volatility. Economic attacks like funding rate manipulation must be mitigated. Funding payments, which tether the perpetual contract price to the spot price, should be calculated over a time-weighted average price (TWAP) and have caps to prevent predatory trading. Furthermore, the protocol must guard against flash loan attacks by ensuring critical state changes (like oracle updates) are not performed in the same transaction as large trades.
Liquidity risk is another critical factor. A protocol needs deep liquidity to ensure traders can enter and exit positions with minimal slippage. Architectures differ: Order Book models (dYdX on StarkEx) rely on market makers, while Automated Market Maker (AMM) pools (GMX's GLP) use a shared liquidity pool from LPs. The AMM model introduces impermanent loss risk for LPs, which is compensated via trading fees and esoteric rewards. The protocol must carefully design its fee structure (opening/closing fees, borrowing fees for leverage) and tokenomics to sustainably incentivize liquidity provision, ensuring the system remains solvent during high volatility and mass liquidations.
Finally, operational security is paramount. Implement multi-signature wallets or a decentralized autonomous organization (DAO) for administering protocol parameters like fee rates, margin requirements, and oracle configurations. Use timelocks for all privileged functions to give the community time to react to malicious proposals. Maintain comprehensive event logging and off-chain monitoring for unusual activity. A well-architected protocol is not just a set of contracts but a resilient economic system with layered defenses, transparent governance, and mechanisms that align the incentives of traders, liquidity providers, and liquidators to ensure long-term stability.
Frequently Asked Questions on Protocol Architecture
Common technical questions and architectural decisions for developers building perpetual swaps protocols.
Decentralized perpetuals (perp) protocols operate on-chain with non-custodial settlement, meaning users retain control of their assets via smart contracts, unlike centralized exchanges (CEXs) which hold custody. The core architectural differences are:
- Price Feeds: DEX perps rely on decentralized oracles (e.g., Chainlink, Pyth Network) for mark price, while CEXs use their internal order book.
- Liquidity: DEX perps use Automated Market Makers (AMMs) or virtual AMMs (vAMMs) funded by liquidity providers, whereas CEXs match orders directly.
- Counterparty Risk: In a DEX, the protocol's smart contract is the counterparty, eliminating broker risk but introducing smart contract risk.
- Funding Rate Mechanism: Both use funding payments to peg perpetual prices to the spot, but DEX calculations are transparent and executed on-chain.