ScaleBit

Oct 12, 2023

Musing on Secure Option Protocols, Vulnerabilities, Architecture, and Evolution in DeFi

This technical research report was authored by Norman from the ScaleBit Research Group

Introduction

OP

In the ever-evolving landscape of decentralized finance (DeFi), options trading has emerged as a sophisticated and vital instrument for risk management and investment strategies. The significance of crypto options is underscored by theTotalValue Locked (TVL) across various platforms, with Dopex holding \$19.55 million, Lyra at \$16.42 million, and other emerging platforms contributing to a diverse and growing field. [1]

Facilitated by decentralized protocols, crypto options offer flexibility, accessibility, and unique features. As a security researcher at ScaleBit, I will guide you through these innovations, emphasizing the security aspects that are paramount in this space. We’ll explore what DeFi options are and delve into protocols like Opyn, Ribbon Finance, Lyra, and more. These platforms are pioneering new paths in DeFi, Introducing Orderbooks, AMMs, structured products and AMM powered types to DeFi landscape. After that, we will focus on the security considerations, vulnerabilities, and best practices that are essential for understanding this burgeoning field.

What are the options?

An option is a financial tool linked to the value of underlying securities such as indexes, stocks, and exchange-traded funds (ETFs). It allows the buyer to buy or sell the underlying asset based on the type of contract they hold. Unlike futures, the holder is not obligated to buy or sell the asset if they choose not to. The strike price is the price stated on an option. Online or retail brokers are usually involved in the buying and selling of options. [2]

Types of Options

OP

The purchaser of a Call Option has the option to acquire the underlying asset, whereas a Put Option gives the purchaser the right to dispose of the underlying asset.

The exercise terms for options are not all the same:

  • European options can only be exercised or settled on the expiration date.
  • American options can be exercised at any point before expiration.
  • Bermudian options can be exercised on specific pre-expiration dates.

Additionally, it is important to understand how options are settled. Asset-settled options deliver or exchange the underlying asset upon expiration, while cash-settled options use cash or stablecoins. [3]

The premium amount for an option is determined by the probability of it being beneficial for the buyer, which is affected by the strike price and current asset price. A greater probability results in a higher premium, while a lower probability leads to a lower premium. [3]

For instance, purchasing a call option with a \$26000 strike price for BTC when it is valued at \$28000 for a week would have a high premium due to the low possibility of ETH falling below \$26000.

How DeFi options work

The demand for DeFi Options is high, but DeFi is still a relatively small player in comparison to centralized counterparties like Deribit, OKEx, etc. As a result, options trading is limited due to a lack of liquidity and active users. Nevertheless, we cannot ignore the transparency and innovation they brought to the market. Therefore, let’s categorize those protocols and delve into how their token economics work.

Types of DeFi Options Protocols

According to Three Sigma, there are 4 types of option protocols: Orderbooks, AMMs, Structured Products, and AMM Powered. [3]

OP

Orderbooks

Marketplaces known as Orderbooks allow buyers and sellers to place orders for buying or selling assets. These orders are publicly recorded in an “order book” that displays the prices at which buyers are willing to purchase and sellers are willing to sell. When a buyer and seller agree on a price, the exchange executes the trade and removes the corresponding orders from the order book.

There are two types of DeFi order book options protocols: Infrastructure and Fully-Fledged options DEXs.

Regarding infrastructure order book option protocols, market makers and decentralized options vaults (DOV) such as Ribbon utilize these protocols to price and sell options generated on the infrastructure layer. The purpose of these protocols is to facilitate the activities of options underwriters.

Fully-fledged options DEXs offer a trading platform for pre-existing and priced options contracts. This enables Market Makers and other traders to directly trade options by matching orders at specific prices, without requiring an underlying infrastructure protocol.

One of the option protocols that utilize order books is Opyn.

Opyn offers a product called “Squeeth” (Squared ETH) that allows for long positions without the fear of liquidation. Under this system, longs are charged a fee to keep their positions open, while shorts receive funding from longs but must maintain a collateral ratio to prevent liquidation.

OP

However, constantly checking these orders on-chain can lead to scalability and latency issues, making on-chain order books slow and expensive given the current state of blockchain technology. It can be partly solved by bringing the order book off-chain, but that will lead to a centralized problem which concerns the users.

AMMs

AMMs utilize algorithms to enable users to purchase or sell assets without specifying a particular price. The algorithm determines the price based on supply and demand, and transactions are carried out at the most favorable price.

From the perspective of the LP, AMMs can be classified into two groups based on their functions. The first group comprises AMMs that enable users to purchase options (long) solely from the AMM. The second group comprises AMMs that mitigate their risk exposure or reinvest their collateral to enhance returns.

Dopex is a first-waved AMM option protocol that provides vaults for Single-Staking Option (SSOV) enabling users to gain yield by locking up tokens for a specific duration.

OP

Farming rewards and premiums together contribute to the yield earned, while option writers receive rDPX tokens as compensation proportional to the losses incurred from writing options, in order to reduce risk.

Structured Products

Structured products offer personalized investment strategies that can potentially yield higher returns while minimizing risk. In the context of DeFi options, structured products utilize options to automate investment strategies, typically involving option selling. This enables investors to deposit funds and have their investment strategy executed automatically, eliminating the need for intermediaries or manual intervention.

Two popular strategies used in options trading are Covered Calls and Put Selling.

Covered Calls involve an investor holding a long position in an asset and simultaneously selling call options on that asset to generate extra income from option premiums. On the other hand, Put Selling involves an investor selling put options without shorting the underlying asset to generate income from option premiums and possibly acquire the underlying asset at a lower price.

Due to its yield narrative and token incentives, Ribbon has been able to attract a significant number of users and a respectable amount of capital, making it one of the most prosperous options products. It was also the first protocol to systematically sell options.

OP

At present, Ribbon has two types of vaults available: Theta vaults and Delta vaults.

Theta vaults utilize Opyn’s Gamma Protocol to mint oTokens, which are then auctioned through Gnosis Batch Auctions as part of an automated options selling strategy. This strategy involves writing and auctioning out-of-the-money options to collect premiums. In contrast, Delta vaults offer a way to hedge long positions by using a portion of the deposited funds to purchase options from Theta vault auctions. If these options expire in the money, profits can be claimed.

AMM Powered

According to Three Sigma, some protocols that utilize AMMs should be classified as a type of option AMM. The rationale behind this is that AMMs often face challenges in acquiring and retaining adequate liquidity, and it would be more beneficial for the ecosystem to use an existing DEX such as Uniswap, which already has sufficient liquidity. AMMs can function as a liquidity layer, with the initial building block being the DEX AMM, but additional building blocks such as options or volatility DEXs with comparable payout structures to options can be constructed on top of it.

Gammaswap is one of the most prominent AMM-powered option protocols.

Through Gammaswap, AMM LPs can protect themselves against impermanent loss by taking advantage of shorting volatility and earning trading fees. Meanwhile, those who choose to go long on volatility will have to pay a premium to the short side.

OP

How to design a safe option protocol

We have introduced the types and categories of DeFi option protocols and some examples. Now we will explore how to design and develop a safe option protocol from the architecture layer.

Orderbooks

When it comes to the infrastructure option protocols, it’s wise to take some time to explore if setting up and interacting with those option contracts will cause problems.

For example, in Opyn, anyone can open a repo (vault) and it will allow users to offer collateral and receive oTokens in exchange.

If this repo is transferable, it might get into a race condition. It is possible for a malicious previous owner to carry out a front-running transaction that results in the repo being in a less secure collateralization status. This could be achieved by creating more oTokens and removing collateral, which could ultimately harm the current owner. [5]

/**
    * @notice allows the owner to transfer ownership of their repo to someone else
    * @param repoIndex Index of the repo to be transferred
    * @param newOwner address of the new owner
    */
   function transferRepoOwnership(uint256 repoIndex, address payable newOwner) public {
       require(repos[repoIndex].owner == msg.sender, "Cannot transferRepoOwnership as non owner");
       repos[repoIndex].owner = newOwner;
       emit TransferRepoOwnership(repoIndex, msg.sender, newOwner);
   }

In Opyn’s case, this function is removed to protect the new owner’s interests.

Typically, those protocols also involve the liquidation process to help the protocol stay healthy. However inappropriate liquidation design will push the protocol into insolvency instead.

In Opyn, oToken is an ERC20-compliant token called oToken as well as the functions for options. And users can issue OTokens in an over-collateralization way. If the collateral drops to certain values, the protocol will become insolvent due to the liquidation process. Additionally, since the collateralization ratio is low, more liquidation events can occur, which will exacerbate the protocol’s insolvency. [5]

Vc1 < Vc/collateralizationRatio + Lo (liquidationIncentive + liquidationFee)

OP

This can be solved by either implementing an offline observation mechanism or a liquidation bot.

For the fully-fledged protocols, the potential problem of DOS should be considered. For instance, in Ribbon Finance, the keeper executes most of the user actions. In this case, a malicious user can deploy a DOS attack by sending thousands of requests to the application and crashing the system. [6]

Therefore, order book protocols should consider throttling and low funds detection to prevent DOS attacks, especially since there is a special role in handling user transactions.

AMMs

For AMM (Automated Market Maker) types of option protocols, it’s important to check if it does properly check against expiry, option type, and other fields related to its business logic.

For example, Hegic, a second-wave AMM option protocol, had several bugs during its audits.

The most critical one is that it does not check optionType, and that allows malicious users to create invalid options and drain the pool rewards.

Another obvious bug is that Hegic did not update its dailyReward, so that anyone can just bypass the limit. [7]

function getReward(uint optionId) external {
   uint amount = rewardAmount(optionId);
   uint today = block.timestamp / 1 days;
   (, address holder, , , , , , ) = hegicOptions.options(optionId);
   require(!rewardedOptions[optionId], "The option was rewarded");
   require(
       amount.add(dailyReward[today]) < MAX_DAILY_REWARD,
       "Exceeds daily limits"
   );
   rewardedOptions[optionId] = true;
   hegic.safeTransfer(holder, amount);
}

Similar issues like uninitialized strike is allowed to be used in Lyra’s audit report stresses this commonality.

Thus, checking the insistence of business logic like rewarding, distributing, and exercising is crucial in AMM types of option protocols.

Structured Products

The core functionality of structured product option protocols is to design the vaults with automated strategies, therefore, it is crucial to make sure users won’t lose money interacting with vaults. Efforts should be made to check the compatibility among functions, the fee calculations, and more.

In Ribbon Finance’s audit report, there is a critical issue related to function compatibility. In the design of Ribbon Finance, users will deposit assets into a vault, and those assets are set to pending until the next round of the vault. And for those assets, they should not be calculated with reward distribution or penalties. However, the variable vaultState.totalPending only increases and never decreases even user uses the instant withdraw function. Due to this, a lot of arithmetic calculations will go wrong and eventually revert, making this protocol halt. [9]

In a nutshell, it’d be wise to check again how the vaults and strategies are implemented and whether users’ funds are safe under any condition.

AMM-powered

For AMM-powered option protocol, handling LP positions should be taken with extra care.

Let’s take GammaSwap for example, the _depositNoPull() function will always revert with ZeroAmount() error due to a misconstruction. In the design of the deposits, users can deposit assets and some tokens are minted to the dev to collect the protocol fees, however, for the very first deposit there are not any tokens yet, and the devShares are therefore zero. And that will always revert the deposit function.

Thus, when designing the AMM-powered option protocol, always be cautious about the intersection between AMM and options, and that’s where the bugs hide.

Conclusion

Decentralized options protocols enable sophisticated financial strategies without centralized intermediaries. Order book has a constant need to scan the orders on chain, which brings scalability and latency issues. Thus, they are mainly uses as the base layer for structured products. AMM, on the other hand, faces issues like inventory risk. Structured products introduced the automated strategies but users will need to decide on which to use under different market conditions. And lastly, AMM-powered options protocols’ future seem bright, but it depends on if they can attract users to deposit assets in their pools rather than traditional AMMs.

As we’ve explored, these innovations come with security risks if not properly architected. By reviewing real-world protocol audits and vulnerabilities, we’ve uncovered common pitfalls and best practices for creating safe and resilient options primitives. While the DeFi options landscape will continue evolving, foundational knowledge of secure design empowers developers to avoid past mistakes. As decentralized options grow in adoption, security and transparency must remain top priorities. By keeping users’ funds and interests protected, we can unlock the full possibilities of decentralized options in a sustainable way.

Reference

[1] https://defillama.com/protocols/options

[2] https://www.investopedia.com/terms/o/option.asp

[3] https://threesigma.xyz/blog/defi-options-landscape

[4] https://www.fe.training/free-resources/financial-markets/options/

[5] https://blog.openzeppelin.com/opyn-contracts-audit

[6] https://github.com/ribbon-finance/aevo-audit/blob/master/Ribbon-report.pdf

[7] https://github.com/hegic/contracts/blob/main/packages/herge/docs/PeckShield-Audit-Report-Hegic-Herge-Protocol-Upgrade-v1.0.pdf

[8] https://github.com/sherlock-protocol/sherlock-reports/blob/main/audits/2022.06.27 - Final - Lyra Audit Report.pdf

[9] https://blog.openzeppelin.com/ribbon-finance-audit

[10] https://github.com/HalbornSecurity/PublicReports/blob/master/Solidity Smart Contract
Audits/GammaSwap_Labs_Core_Strategies_and_Periphery_Smart_Contract_Security_Audit_Report_Halborn_Final.pdf

About ScaleBit

ScaleBit is a blockchain security team that provides security solutions for Mass Adoption of Web3. With expertise in scaling technologies like blockchain interoperability and zero-knowledge proofs, we provide meticulous and cutting-edge security audits for blockchain applications. The team comprises security professionals with extensive experience in both academia and enterprise. Our mission is to provide security solutions for Web3 Mass Adoption and make security accessible for all.

OLDER > < NEWER