When we undertook the development of the first perpetual protocol for a client, we immediately faced the challenge of designing a manipulation-resistant liquidation system. The standard mechanism of fully closing a position when the health factor drops below 1 on highly volatile markets generated bad debt of 3.8% of volume. During an internal hackathon, we rewrote the core liquidation engine four times before finding a working configuration: partial liquidation plus dynamic fee. This honestly indicates the complexity of the task: developing an on-chain derivatives protocol is not an overlay on an AMM but a separate financial system with dozens of interconnected components. Our team has over 5 years of experience in DeFi and has implemented more than 10 protocols with a cumulative TVL of over $180M. We guarantee code quality and passing external audits. Thanks to gas optimization, our clients save up to $150,000 annually in transaction costs. Development of an MVP starts at $50,000, and full audit-ready protocols range from $200,000 to $500,000 depending on complexity. Additionally, we have reduced deployment costs by 20% through efficient library linking, saving clients an average of $12,000 on mainnet. In one protocol, we reduced bad debt from 3.8% to 1.2% through partial liquidation.
What Types of Derivatives Can Be Implemented On-Chain?
We develop perpetual futures, options (including European and exotic), structured products (vault strategies), and synthetic assets. Each type requires unique contract logic—from funding rates to option exercise. The cost for an MVP starts at $50,000, and a full protocol ranges from $200,000 to $500,000.
How Do We Ensure Manipulation Resistance and Oracle Security?
Manipulation resistance is critical for any on-chain derivatives exchange. We implement multiple layers: a three-tier oracle system, dynamic fees, and circuit breakers. For example, our mark price uses a 1-hour TWAP of Chainlink data, while execution uses Pyth's sub-second feed. This makes manipulation costly—attackers would need to influence both feeds and the protocol's own volume. We also enforce position limits proportional to the insurance fund, which should be at least 1% of TVL. In our $180M protocol, the insurance fund started at $1.8M and grew through fee allocation.
A derivatives protocol is the most demanding consumer of oracles in DeFi. Requirements:
- Latency: Chainlink updates every few blocks are insufficient for active trading. Pyth Network provides sub-second updates via a pull oracle: data is published off-chain, on-chain update is initiated by the user in a transaction with proof.
- Multi-asset: each market needs a separate price feed. Redstone provides a flexible system with custom aggregators.
- Manipulation resistance: for mark price we need TWAP, for liquidation price—more current data.
We build a three-tier system: Pyth for trade execution, Chainlink TWAP for mark price calculation, our own on-chain TWAP as the last line of defense. Setup steps:
- Integrate Pyth pull oracle for each trading pair—updates every 400ms.
- Configure Chainlink TWAP feed (1-hour period) for mark price calculation.
- Deploy a backup on-chain TWAP based on the last 100 blocks.
- Conduct manipulation simulation: open a $1M position and try to move the price—the system should resist.
Derivative Types and Liquidity Models
Before writing a single line of code, you need to precisely define the type of instrument. Contracts for different derivative classes share no common code except basic utilities.
| Type | Examples | Key Mechanism | 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 |
We will focus on perpetual futures, the most sought-after type. Liquidity is the key success factor for any derivatives exchange. We offer several models: vAMM for quick launch (requires minimal capital, but has high slippage—up to 2% on $500k positions), liquidity pool with LP incentives (initial TVL from $2M, average LP yield 15-20% annually), or a hybrid orderbook for institutional volumes. The choice depends on target audience and trading volumes. Typically, a vAMM is sufficient to start, with a switch to a pool upon reaching $10M daily volume. We've seen protocols with $50M TVL reduce slippage to 0.1% using our optimized pool design. For options creation blockchain, we implement on-chain options creation on blockchain using standardized ERC-20 wrappers.
Detailed Infrastructure Costs
Running a full derivatives protocol requires off-chain keepers and price feed infrastructure. Estimated monthly costs: $800 for keeper VPS nodes, $1,200 for Pyth data feeds, and $400 for Chainlink subscription. These costs are included in our support packages.
Liquidation Engine and Risk Management
Funding Rate – The Heart of Perpetuals
Perpetual futures on Wikipedia have no expiration. Instead of converging to spot price via an expiration date, perpetuals maintain peg through a funding rate—periodic payments between longs and shorts.
The standard formula: fundingRate = clamp(premium / fundingInterval, -maxRate, maxRate), where premium = (markPrice - indexPrice) / indexPrice.
The problem is that the mark price on illiquid markets is easily manipulable. GMX v1 used a pure Chainlink price feed as the mark price—this allowed attackers to open positions right before a manipulated oracle update and close after. GMX lost several million dollars on this until introducing a position impact fee.
The solution we use: mark price = TWAP over the last X minutes of trading on the protocol itself (if volume is sufficient) with a fallback to the median of three oracles (Chainlink, Pyth, Redstone). Manipulation becomes expensive: you need to move both the trading volume on the protocol and several external oracles simultaneously.
Liquidation Engine and Partial Liquidation
The classic approach—liquidation when health factor < 1 with immediate closure of the entire position. The liquidator receives a liquidation fee (typically 0.5–1%). Problem: in a volatile market, a position can go deeply negative faster than the liquidator can react. Result—bad debt covered by the insurance fund. An average liquidation costs about 2000 gas, which at a gas price of 50 gwei is about $0.02, but during high volatility liquidators pay a premium up to $0.5.
A more advanced approach—partial liquidation: when the warning threshold is reached (e.g., margin ratio < 5%), the position is partially reduced until the margin ratio is restored. Full liquidation only when margin is completely exhausted.
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: the entire user balance is common margin for all positions. An ETH position helps an BTC position survive a local drop. Risk—one losing position can liquidate the whole account.
Isolated margin: each position is isolated. Maximum loss is limited to the allocated margin. Safer for the user, more complex to implement: requires per-position accounting in storage.
For most client protocols, we implement isolated margin as the default mode with optional cross-margin for advanced users.
Risks and Mitigation Measures
Insurance fund: a mandatory component for any perpetual protocol. Funded from a portion of trading fees (usually 10-20%). Covers bad debt from insufficient liquidation. With TVL of $180M, we recommend a target fund size of $1.8M.
Position limits: maximum open interest per side (long/short) limits protocol exposure. Proportional to the insurance fund size.
Circuit breakers: if the mark price deviates from the index price by more than 5%—halt new positions until normalization. Protection against oracle manipulation.
Admin key security: a protocol with TVL > $500M requires a multi-sig timelock (at least 48 hours) on all parameter changes. Instant changes of fees or liquidation thresholds are a red flag for any auditor.
Development Process and Deliverables
Architecture: vAMM vs Global Liquidity Pool vs Hybrid Orderbook
vAMM (virtual AMM)—the approach of Perpetual Protocol. No real liquidity, price determined by the formula x*y=k on virtual reserves. Liquidity providers are not needed for basic operation. Downside: high slippage on large positions (up to 2% for a $500k position), funding rate does not always reflect the real market.
Global liquidity pool—the approach of GMX. LPs deposit a basket of assets (GLP/GM) and become counterparties to all traders. If traders lose on average—LPs profit (average yield 15-20% annually). Works well on stable markets, but LPs bear asymmetric risk: during mass profitable positions, GLP loses value.
Hybrid orderbook + AMM—the most complex, closest to CEX UX. Off-chain matching (via a dedicated sequencer or off-chain orderbook) with on-chain settlement. This architecture is used by Hyperliquid.
Development Stack
Contracts: Solidity 0.8.24 + Foundry for testing. Foundry fork tests are critical—we test liquidation scenarios against historical data (LUNA crash, FTX collapse). 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 priority execution of liquidations. A typical liquidation takes about 2000 gas.
Frontend: wagmi v2 + viem + TradingView Lightweight Charts for candlestick display. We support up to 50,000 concurrent connections.
Process Workflow
| Stage | Duration | Description |
|---|---|---|
| Analytics and spec | 1 week | Type of derivatives, trading pairs, liquidity model, oracle stack, fee economics |
| Architecture design | 1 week | Contract scheme, storage layout, 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. Simulation of stress scenarios |
| External audit | 2–4 weeks | Mandatory for a derivatives protocol with real TVL. At least two independent auditors |
Deliverables of Turnkey Derivatives Protocol Development
- Development of core smart contracts (Solidity, Foundry) with full ownership transfer
- Off-chain services (Node.js, ethers.js) with source code and deployment scripts
- Oracle integration (Pyth, Chainlink, Redstone) with configuration documentation
- Comprehensive testing (unit, fuzz, fork) including stress tests and manipulation simulations
- Preparation for external audit and support during audit fixes
- Architectural, API, and deployment documentation
- Training for the client's team (workshop + written materials)
- Admin panel and monitoring dashboard access
- Post-deployment support for 3 months (bug fixes, gas optimization, minor upgrades)
Timeline Estimates
MVP vAMM with one trading pair—8–10 weeks. A 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. We offer project assessment and free consultation on choosing the liquidity model and development stack.
Before deployment, it is recommended to check: reentrancy guard in all margin-changing functions, liquidation testing under extreme price movements (e.g., -50% over 1 block), correct funding rate calculation at zero volume, formal verification of critical functions (Halmos), access control audit in admin functions, and stress testing of gas limits during mass liquidations.
Our team is ready to discuss your project. We specialize in DeFi derivatives exchange development, margin trading DeFi, smart contracts derivatives, options creation blockchain, AMM derivatives development, smart contract audit derivatives, gas optimization derivatives, and Chainlink Pyth integration. With our services, we ensure efficient and robust protocols. We also provide perpetual futures development as part of our standard package.







