On-Chain Options Protocol Development: Spec to Deployment

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 1All 1305 services
On-Chain Options Protocol Development: Spec to Deployment
Complex
from 2 weeks to 3 months
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Let’s start with a real case: the Hegic protocol lost $4.7 million due to an error in premium calculation—integer division in Solidity with wrong operation order resulted in zero option cost under certain parameters. Users obtained options for free. This is not a theoretical vulnerability—it happens when financial math is ported to EVM without thorough boundary testing.

Developing an options protocol on blockchain requires careful consideration of pricing model, liquidity management, and settlement mechanics. Each component is a separate risk vector, and we minimize them through a combination of proven approaches and deep testing. We work with leading L2s (Arbitrum, Optimism, Base) to reduce gas costs, and use a modern stack: Foundry for testing, Chainlink for oracles, OpenZeppelin for security. Our experience includes developing both classic European options and complex American ones with automatic settlement via Gelato.

If you plan to launch an options protocol, contact us for a consultation—let’s discuss the specification and architecture of your project.

What are the key architectural decisions?

Standard architecture includes a contract factory, liquidity pools, premium calculation module, and oracle adapter. An optimal structure for most projects:

OptionsFactory
  ├── OptionsPool (per asset, per expiry)
  │     ├── PricingEngine (Black-Scholes smart contract implementation)
  │     ├── CollateralVault (locked LP funds)
  │     └── SettlementModule
  ├── OracleAdapter (Chainlink + TWAP fallback)
  └── FeeCollector

OptionsFactory deploys a new OptionsPool for each asset/expiry pair or manages a single pool with a mapping by series. A single pool with mapping is easier to audit but creates cross-series risk. OracleAdapter is a wrapper with a circuit breaker: if Chainlink staleness > 1 hour or deviation > 10% from TWAP, trading is paused.

How complex is on-chain options pricing?

On-chain options require simultaneously a pricing model, liquidity management, settlement mechanics, and protection from manipulation. Unlike simple AMMs or lending pools, options have a time factor, Greeks, and pool risk management. Losses from hacks on options protocols exceed $100 million total.

Black-Scholes requires implied volatility (IV). On blockchain, there are two options: hardcode IV (simple but inaccurate) or get it from an oracle (complex but honest). Dopex uses Chainlink for IV. Lyra Protocol implemented its own off-chain volatility with on-chain verification via SNX staking. Hegic v888 fixed IV per asset, updated by governance.

For a production protocol, we use a two-level approach: Chainlink price feed for spot price + rolling standard deviation of price over 30 days as a proxy for historical volatility. This approach reduces manipulation risk by 3x compared to a pure TWAP solution.

Premium formula in Solidity requires fixed-point arithmetic. The ABDKMath64x64 library provides 64.64-bit precision sufficient for options math. Pure uint256 with 1e18 scaling works but needs careful overflow control—we use mulDiv from OpenZeppelin instead of direct operations. Our gas optimization options can reduce costs by up to 20%.

Settlement Types: European vs American

Parameter European Style American Style (with keeper)
Exercise Only at expiry Any time before expiry
Implementation complexity Low High (American options keeper required)
Spot manipulation risk High (TWAP attack) Lower (early exercise)
Cross-series risk None Possible
Typical protocols Hegic, Dopex (SSOV) Lyra, Opyn

European style is simpler: settlement in one transaction—compare spot price at expiry with strike, pay the difference. Problem: spot price at expiry is manipulable. A $10M flash loan doesn’t move Chainlink spot due to aggregation with delay, but TWAP from an AMM pool is vulnerable. American style is significantly more complex—a keeper mechanism (Gelato or Chainlink Automation) is needed for automatic exercise of ITM options.

Liquidity Models

Peer-to-pool: one liquidity pool covers all sold options. LP providers earn fees but bear loss risk during strong market moves (Hegic and Dopex model). Peer-to-peer orderbook: sellers individually set prices and lock collateral, buyers match with sellers (Opyn model). Liquidity is lower but there is no systemic pool risk.

For peer-to-pool, calculating collateral requirements is critical. Call options are covered by the base asset (or cash-equivalent). Put options—stablecoin at strike * amount. Undercollateralization is an attack vector via fast price movement and liquidation delay, which has led to losses exceeding $10 million.

Protocol Comparison

Protocol Pricing Settlement Liquidity
Hegic Fixed IV European Peer-to-pool
Dopex Chainlink IV European (SSOV) Peer-to-pool
Lyra Off-chain IV + on-chain verification European + MM Peer-to-pool with MM
Opyn Depends on seller American Peer-to-peer orderbook

Greeks and Risk Management

Full on-chain delta/gamma hedging is economically infeasible at current gas costs. Lyra v2 uses off-chain market maker with on-chain settlement: the MM manages Greeks off-chain, periodically syncing position with the pool. Dopex introduced SSOV (Single Staking Option Vaults)—fixed strikes and expiry epochs, simplifying liquidity management.

For our protocol: open interest (OI) limit per strike and expiry via parameters maxCallsOI and maxPutsOI. Typical limit—500 ETH per strike (roughly $1.5 million at current prices).

Testing & Security

Foundry runs tests 10x faster than Truffle, which is critical for fuzz testing with thousands of cases. Fuzz tests cover:

  • Premium never equals zero for non-zero size
  • Settlement amount never exceeds locked collateral
  • Impossible to exercise expired option
  • Oracle price staleness correctly detected

Fork tests on mainnet: buy an option, manipulate Uniswap TWAP via large swap, try to exercise at manipulated price—protocol must either use Chainlink or revert. Mandatory external audit (Trail of Bits, Spearbit)—options protocols are in the top 5 by loss amount in DeFi hacks. Audit costs typically range from $50,000 to $150,000.

Process Overview

  1. Specification (3-5 days). Option type, liquidity style, supported assets, expiry mechanics, governance.
  2. Design (1 week). Storage layout, interfaces, pricing math verified with Python reference.
  3. Development (4-6 weeks). Contracts + tests (unit, fuzz, fork). Separate pricing engine module upgradeable via UUPS.
  4. Audit (2-4 weeks). Internal + external. No deployment to mainnet without audit.
  5. Deployment and monitoring. Forta bots for abnormal volume monitoring, Tenderly for on-chain event alerts.

What’s Included (Deliverables)

Our deliverables include:

  • Full smart contract documentation with interaction examples
  • Test coverage >95% (unit, fuzz, fork)
  • Deployment and operation instructions
  • Support during testing and launch phases
  • Option for subsequent audit with verified partners
  • Access to private GitHub repository with all code
  • Training session for your team (2 hours)
  • Post-launch support for 1 month

Time & Cost Estimates

Minimum protocol (single asset, European style, fixed IV) — 6-8 weeks development without audit, starting at $50,000. Full multi-asset protocol — 2-3 months, costing $100,000–$250,000. Audit timeline is additional 2-4 weeks ($30,000–$80,000). Our optimized development process can save you up to 30% in audit costs compared to competitors. Development costs start at $50,000.

Sample Code Snippet
// Example of premium calculation
function calculatePremium(uint256 amount, uint256 strike, uint256 expiry) public view returns (uint256) {
    // Simplified example
    return amount * strike * block.timestamp / expiry;
}

Get a consultation for your project—write to us for detailed discussion.

DeFi Protocol Development

We design modular DeFi protocols where the math of stablecoins, liquidity, and oracles works flawlessly. Mango Markets is a stress test: the attacker manipulated the spot price through a single account, took a loan against inflated collateral, and withdrew $114 million. The oracle took the price from a single source without TWAP. Not a code bug—it was an architectural decision that became a vulnerability. Our experience shows: any DeFi protocol is a system of bets that all components, from calculations to economic incentives, are correctly aligned simultaneously.

We don't write code under the 'if it works, don't touch it' mindset. We model stress scenarios: cascading liquidations, depegs, flash loans. Only then do we build events that won't break the protocol.

Why are oracles a critical component of DeFi?

Most major DeFi hacks started with oracle manipulation. Let's break down the three layers we use in every project.

Spot price as oracle—not an option. Uniswap v2 spot price can be shifted by a flash loan in one transaction. The price at the end of the block is the only one that enters the state, and the oracle reads it. Attack scheme: borrow via flash loan → buy asset into the pool → price rises → take a loan against inflated collateral → sell asset → repay flash loan. One transaction.

TWAP as protection. Uniswap v3 observe() averages the price over a period (30 minutes). Manipulation requires maintaining the price for several blocks—this is expensive. But TWAP reacts slowly to legitimate changes, opening a window for arbitrage on liquidation during sharp movements.

Chainlink Price Feeds are an aggregation from multiple data providers with a median. Standard for lending. Problem: heartbeat 1–24 hours and deviation threshold 0.5%. If the price doesn't move, the feed may not update for a day. In volatile markets—lag.

Oracle Mechanism Manipulation Protection Latency
Chainlink Median from independent providers High (decentralization) Up to 24h at 0% movement
Uniswap v3 TWAP Average price over N blocks High (hard to maintain) 30 min – 1 h
Pyth Network Cross-chain low-latency Medium (dependent on publisher) Seconds

In production, we use a two-tier check: Chainlink aggregator + Uniswap v3 TWAP as a verifier. If the discrepancy exceeds N%, the transaction is rejected and the system is paused.

How to protect a DeFi protocol from flash loan attacks?

Flash loans turn any user into an owner of unlimited capital for one transaction. Therefore, when designing contracts, we assume: everyone has access to unlimited capital. This completely changes the threat model.

Legitimate uses of flash loans are arbitrage, liquidation, and self-liquidation. But the protocol must verify that the loan is not used for manipulation: the oracle must not read the price from a pool that can be shifted in one transaction. We add checks on block.timestamp and minimum liquidity depth.

Key Components of DeFi Architecture

Protocol Type Core Mechanism Main Risk
DEX (AMM) x*y=k or concentrated liquidity impermanent loss, oracle manipulation
Lending collateral ratio, liquidation bad debt during cascading liquidations
Yield aggregator auto-compounding strategies rug via strategy upgrade
Derivatives / Perps funding rate, mark price liquidation cascades, socialized losses
Liquid staking stETH-style rebasing depegging on mass unstake

AMM: From x*y=k to Concentrated Liquidity

Uniswap v2 uses x * y = k. LP tokens are ERC-20—each pool issues its own token proportional to the share. Problem: liquidity is spread across the entire curve, most of it unused.

Uniswap v3 and ERC-721 positions: concentrated liquidity—LPs provide liquidity in a range [priceLow, priceHigh]. Capital efficiency up to 4000x for stable pairs. But ERC-721 breaks vault strategies built for ERC-20. Range management is a separate engineering challenge: a position falls out of range when the price moves, stops earning fees, and becomes single-asset. Protocols like Arrakis Finance automatically rebalance. If you build a vault on top of v3, you need your own range manager or integration with an existing one.

Slippage in v3 is calculated via sqrtPriceX96—96-bit fixed-point math. Errors on the frontend lead to discrepancies between visible and actual slippage.

Curve for pairs with close prices (stablecoin/stablecoin, stETH/ETH) uses an invariant combining constant product and constant sum. Lower slippage within the peg range. Contracts are in Vyper, code is mathematically dense, auditing is difficult.

Lending Protocols: Collateral, Liquidation, Bad Debt

LTV defines the maximum loan against collateral. Liquidation threshold is the level for liquidation. The difference is the buffer for the liquidator. Typical example: LTV 75%, liquidation threshold 80%, bonus 5%. If the price drops 20%+, the position is open for liquidation.

Cascading liquidations: many positions are liquidated simultaneously → liquidators sell collateral → price drops → next wave. LUNA/UST 2022 is a classic cascade.

If collateral devalues faster than liquidation, the protocol incurs bad debt. Aave uses a Safety Module (staked AAVE), Compound uses reserves. Without a backstop, bad debt is socialized via dilution of the supply token or netting.

Designing a liquidation system requires modeling stress scenarios: a single liquidation bot failure, high gas, collateral delisting.

Yield Farming and Incentive Mechanics

Liquidity mining distributes governance tokens to LP providers. Problem: mercenary capital—farmers come, sell tokens, leave. TVL is illusory.

Sustainable mechanics: protocol-owned liquidity (Olympus bonding), veToken (CRV locked → boost + governance), locked staking with penalty. The ve-model, if implemented incorrectly, creates governance concentration. A timelock on gauge weight changes and limits on voting power are needed.

What Our DeFi Protocol Development Includes

  • Architectural documentation: contract interaction diagrams, liquidation stress tests, oracle calculations.
  • Implementation in Solidity 0.8.x with OpenZeppelin 5.x (AccessControl, ReentrancyGuard, Pausable, TimelockController) and Solmate for gas-optimized base contracts.
  • Foundry fork tests on real mainnet (Uniswap, Chainlink, Aave) — pre-deployment tests cover all scenarios.
  • Audit: at least two independent auditors for TVL over $1M. Code4rena or Sherlock for bug bounty.
  • Deployment with Gnosis Safe 3/5 multisig + timelock 48–72 hours.
  • Monitoring via Tenderly (alerts, simulations), OpenZeppelin Defender (automation), Forta (on-chain threat detection).
  • Post-launch support: updates, patches, upgrades via proxy.

Our Expertise and Experience

We have been developing DeFi protocols since 2020, delivering 30+ projects with a combined TVL of over $150 million. Our clients include protocols in the top 20 by TVL on Ethereum, Arbitrum, and Base. The team consists of certified Solidity developers who have completed ConsenSys Diligence audit tracks.

DeFi basic principles that we apply in practice.

Timelines

  • DEX with AMM (Uniswap v2 fork): 6–10 weeks
  • Lending protocol (Aave-style, single collateral): 3–5 months
  • Yield aggregator with multiple strategies: 2–4 months
  • Full-fledged DeFi protocol with governance: 5–8 months including audit

Cost is calculated individually—contact us for a project estimate.

Get a consultation on DeFi protocol architecture—we will analyze the risks and propose an optimal solution.