On-Chain Derivatives Protocol Development

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1 servicesAll 1306 services
On-Chain Derivatives Protocol Development
Complex
from 2 weeks to 3 months
FAQ
Blockchain Development Services
Blockchain Development Stages
Latest works
  • image_website-b2b-advance_0.png
    B2B ADVANCE company website development
    1214
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    852
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_logo-advance_0.png
    B2B Advance company logo design
    561
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    823

Development of On-chain Derivatives Protocol

dYdX v3 processed hundreds of thousands of orders per day — but ran on StarkEx, a centralized off-chain engine. When the team moved to their own Cosmos chain in v4, they literally rewrote everything, because a "real" on-chain derivatives orderbook with perpetuals on EVM didn't exist in production-ready form. This is an honest indicator of task complexity: an on-chain derivatives protocol is not an overlay on AMM, it is a separate financial system with dozens of interconnected components.

Classification of on-chain derivatives

Before writing first line of code, need to precisely define instrument type. Contracts for different derivative classes have no common code except basic utilities.

Type Examples Key mechanic Complexity
Perpetual futures GMX, dYdX, Gains Funding rate, mark price, liquidation High
Options Lyra, Dopex, Premia Greeks, IV model, exercise Very high
Structured products Ribbon Finance Vault strategies, rolling Medium
Prediction markets Polymarket Binary settlement, oracle Medium
Synthetic assets Synthetix Debt pool, oracle debt, SNX staking High

Next we focus on perpetual futures — the most popular type, which clients order most often.

Perpetual futures: where real engineering problems live

Funding rate — the heart of perpetuals

Perpetual futures have no expiration. Instead of convergence to spot price through expiration date, perpetual maintains peg through funding rate — periodic payments between longs and shorts.

Standard formula: fundingRate = clamp(premium / fundingInterval, -maxRate, maxRate), where premium = (markPrice - indexPrice) / indexPrice.

The problem is mark price on illiquid markets is easily manipulable. GMX v1 used pure Chainlink price feed as mark price — this allowed attackers to open positions right before manipulated oracle updated price, and close after. GMX lost millions on this before position impact fee was introduced.

Solution we use: mark price = TWAP from last X minutes of trades on protocol itself (if volume sufficient) with fallback to median from three oracles (Chainlink, Pyth, Redstone). Manipulation becomes expensive: need to move both trading volume on protocol and multiple external oracles simultaneously.

Liquidation engine and partial liquidation

Classic approach — liquidation at health factor < 1 with immediate closure of entire position. Liquidator gets liquidation fee (usually 0.5–1%). Problem: on volatile market position can go deep underwater faster than liquidator can react. Result — bad debt, covered by insurance fund.

More advanced approach — partial liquidation: at warning threshold (e.g., margin ratio < 5%) position is partially forcefully reduced to restore margin ratio. Full liquidation only at complete margin exhaustion.

function liquidate(address trader, bytes32 marketId) external {
    Position storage pos = positions[trader][marketId];
    uint256 markPrice = getMarkPrice(marketId);
    
    int256 unrealizedPnl = _calcUnrealizedPnl(pos, markPrice);
    uint256 margin = uint256(int256(pos.collateral) + unrealizedPnl);
    uint256 maintenanceMargin = _getMaintenanceMargin(pos, markPrice);
    
    require(margin < maintenanceMargin, "Position healthy");
    
    // Partial liquidation if possible
    uint256 reduceAmount = _calcPartialLiquidationSize(pos, margin, maintenanceMargin);
    _reducePosition(trader, marketId, reduceAmount, markPrice);
    
    uint256 liquidationFee = reduceAmount * liquidationFeeRate / 1e18;
    _transferFee(msg.sender, liquidationFee);
}

Cross-margin vs isolated margin

Cross-margin: entire user balance — common margin for all positions. Position on ETH helps survive position on BTC on local drawdown. Risk — one losing position can liquidate entire account.

Isolated margin: each position isolated. Maximum loss on position limited to allocated margin. Safer for user, harder to implement: need per-position accounting in storage.

For most client protocols we implement isolated margin as default mode with optional cross-margin for advanced users.

Architecture: AMM vs Virtual AMM vs Orderbook

vAMM (virtual AMM) — Perpetual Protocol approach. No real liquidity, price determined by x*y=k formula on virtual reserves. Liquidity providers not needed for basic operation. Minus: high slippage on large positions, funding rate doesn't always reflect real market.

Global liquidity pool — GMX approach. LPs deposit basket of assets (GLP/GM), become counterparties for all traders. If traders average lose — LPs earn. Works well on stable markets, but LPs carry asymmetric risk: on massive profitable trader positions GLP loses value.

Hybrid orderbook + AMM — most complex, closest to CEX UX. Off-chain matching (via dedicated sequencer or off-chain orderbook) with on-chain settlement. Hyperliquid uses this architecture.

Oracle infrastructure

Derivatives protocol — most demanding oracle consumer in DeFi. Requirements:

  • Latency: Chainlink update every few blocks insufficient for active trading. Pyth Network provides sub-second updates via pull-oracle: data published off-chain, on-chain update initiated by user transaction with proof.
  • Multi-asset: each market needs separate price feed. Redstone provides flexible system with custom aggregators.
  • Manipulation resistance: for mark price need TWAP, for liquidation price — more current data.

We build three-level system: Pyth for trading execution, Chainlink TWAP for mark price calculation, proprietary on-chain TWAP as last line of defense.

Risks and mitigation measures

Insurance fund: mandatory component for any perpetual protocol. Filled from portion of trading fee (usually 10-20%). Covers bad debt when liquidation insufficient.

Position limits: maximum open interest per side (long/short) limits protocol maximum exposure. Proportional to insurance fund size.

Circuit breakers: when mark price deviation from index price exceeds threshold (e.g., 5%) — stop new positions until normalization. Protection from oracle manipulation.

Admin key security: protocol with GMX-level TVL ($500M+) requires multi-sig timelock (minimum 48 hours) on all parametric changes. Instant fee or liquidation threshold changes — red flag for any auditor.

Development stack

Contracts: Solidity 0.8.24 + Foundry for testing. Foundry fork-tests critical — test liquidation scenarios on real historical data (e.g., LUNA-crash in May 2022, FTX-collapse in November 2022). Static analysis: Slither + Halmos for symbolic execution of critical functions.

Off-chain components (funding rate calculation, keeper for liquidations) — Node.js + ethers.js with Flashbots bundle submission for prioritized liquidation execution.

Frontend: wagmi v2 + viem + TradingView Lightweight Charts for candlestick display.

Development process

Analytics and spec (1 week). Type of derivatives, trading pairs, liquidity model, oracle stack, fee economics.

Architectural design (1 week). Contract scheme, storage layout, component interfaces, economic model simulation.

Core development (4–8 weeks). Position management, margin system, liquidation engine, funding rate, oracle integrations.

Off-chain services (2–3 weeks). Keeper bots for liquidations, funding rate keeper, price feed aggregator.

Testing (2 weeks). Unit, fuzz, fork-tests. Stress scenario simulation.

External audit. Mandatory for derivatives protocol with real TVL. Recommend minimum two independent auditors.

Timeline estimates

MVP vAMM with one trading pair — 8–10 weeks. Full multi-market protocol with partial liquidation, insurance fund and keeper infrastructure — 4–6 months before audit. Post-audit fixes and deployment — another 4–8 weeks.