# DeFi Options

**DeFi Options** is an open source decentralized options trading platform targeted at Layer 1 and Layer 2 chains allowing users to buy, sell and write cash settable european call/put option tokens.

Our flexible structure allows traders to access or spin up their own on-chain peer-to-pool options trading liquidity pool where they control the rules (i.e set traded underlying assets, select price oracles, define pricing models, determine trading spreads, adjust permissions for traders and LPs, etc).

![frontend app](/files/4hfJBE60L7luNOpCsd7n)

## Mission

To provide an attractive, dynamic environment for both options traders and options writers for trading not only crypto options, but also foreign exchange options, commodity options and more.‌

## Vision

Our protocol was built with scalability and flexibility in mind and will be able to support all Ethereum / EVM-compatible chains while bringing a more capital efficient collateral allocation model and a more diversified options offer to DeFi.

We believe options writers should be rewarded for absorbing the risk of issuing options. We also believe options buyers should have access to fair prices. And it has been with these beliefs in mind that we've designed the **DeFi Options** protocol.

We invite you to visit our [GitHub page](https://github.com/DeFiOptions) for reviewing our source code, and to join our [Discord Server](https://discord.gg/WCeKgHNz3z) for keeping up with the protocol's latest developments.


# Security

## Audit

Find the DeFi Options protocol [PeckShield](https://peckshield.com/en) audit report here:

{% embed url="<https://github.com/DeFiOptions/DeFiOptions-core/blob/master/audits/PeckShield-Audit-Report-DeFiOptions-v1.0.pdf>" %}


# Disclaimer

**Defi Options** is a proof-of-concept open source software project target for testnets and not intended for use in live environments where financial values are involved. As an open source project our code is provided to the general public under the [GPL-3.0 License](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/LICENSE) without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

We strongly advise you to seek legal counseling for all relevant jurisdictions before planning to deploy DeFi Options to a live environment to ensure all required regulations are being met. Use it at your own risk.


# Overview

The **Defi Options** exchange enables trading of long and short positions for cash settable call and put [european style options](https://en.wikipedia.org/wiki/Option_style#American_and_European_options).

It's been implemented as a collection of smart contracts written in the [solidity](https://en.wikipedia.org/wiki/Solidity) programming language. The diagram below gives a glimpse on how traders interact with the exchange, and how components interact with one another.

![](/files/-MXj1R3Jstn3jA7IPvcX)

### Options Exchange

The exchange accepts stablecoin deposits as collateral for writing tokenized (ERC20) options, and a dynamic approach has been implemented for ensuring collateral in a more capital efficient way, making use of favorable writer's open option positions for decreasing total required balance provided as collateral.

### Price Feeds

Decentralized price feeds provide the exchange on-chain underlying price and volatility updates, which is crucial for properly calculating options intrinsic values, collateral requirements, and performing settlements.

### Settlement

Because options are tokenized they can be freely traded/transferred between any two parties. Upon maturity each option contract is liquidated and cash settled by the credit provider contract, becoming open for redemption by token holders. In case any option writer happens to be short on funds during settlement the credit provider will register a debt and cover payment obligations, essentially performing a lending operation.

### Debt Management

Registered debt will accrue interest until it's repaid by the borrower. Payment occurs either implicitly when any of the borrower's open option positions matures and is cash settled (pending debt will be discounted from profits) or explicitly if the borrower makes a new stablecoin deposit in the exchange.

### Credit Tokens

Exchange's balances not allocated as collateral can be withdrawn by respective owners in the form of stablecoins. If there aren't enough stablecoins available at the moment of the request due to operational reasons the solicitant will receive ERC20 credit tokens issued by the credit provider instead. These credit tokens are a promise of future payment, serving as a proxy for stablecoins since they can be redeemed for stablecoins at a 1:1 value conversion ratio, and are essential for keeping the exchange afloat during episodes of high withdrawal demand.

Holders of credit tokens can request to withdraw (and burn) their balance for stablecoins as long as there are sufficient funds available in the exchange to process the operation, otherwise the withdraw request will be FIFO-queued while the exchange gathers funds, accruing interest until it's finally processed to compensate for the delay.


# Roles

More than simply a decentralized exchange, **Defi Options** is an environment where four main types of participants 👥 play a role:

* Traders
* Liquidity Providers
* Validators
* Token Holders

Each of these roles has specifics interests and motivations for interacting with **Defi Options**, as we'll see in the next pages.


# Traders

Traders 📈 buy and sell options, and they do it for a myriad of reasons, among them:

* **Limit losses:** Hedging the risk exposure of their portfolio against sudden price changes
* **Exposure:** Gaining exposure to markets they wouldn't have access to otherwise (ex: commodities market)
* **Leverage:** Because options are much cheaper to purchase in comparison to the underlying asset, you can purchase more and get more upside potential
* **Strategies:** Options allow us the flexibility to come up with many strategies that both limit risk and maximize return.

In doing so traders are usually concerned with meeting two conditions:

1. Efficient prices: so that they can rest assure they're not overpaying for an option, or selling it underpriced.
2. High liquidity: so that they enter / exit options positions without hassle.

Our liquidity pool has been designed to provide just that, efficient prices and high liquidity, which we believe will incentivize traders into adopting our exchange.

Even though traders can interact with the **Defi Options** exchange directly for making deposits, providing collateral, writing tokenized options and managing their options portfolio, buying and selling of options will happen from trader to trader, or through a liquidity pool. That's because the options exchange is only responsible for providing an environment for trading options, but not for pricing them, nor providing liquidity.


# Liquidity Providers

Liquidity providers 💰 participate by providing funds (stablecoins) to the liquidity pool. When they do that they receive pool tokens in return following a “post-money” valuation strategy, i.e., proportionally to their contribution to the total amount of capital allocated in the pool including the expected value of open option positions held by the pool (this allows new liquidity providers to enter the pool at any time without harm to pre-existent providers).

Funds are locked in the pool until it reaches its pre-defined liquidation date, whereupon the pool ceases operations and accumulated capital is distributed to liquidity providers proportionally to their participation in the total supply of pool tokens.

A single **Defi Options** liquidity pool instance is able to trade a wide range of options of different maturities, strike prices, and even underlying assets, thus reducing the pool's returns overall volatility due to diversification. We believe this feature will appeal to liquidity providers that are seeking exposure to options in a more controlled way.


# Validators

The options exchange requires some maintenance tasks to be executed periodically for proper operation, and validators 🕵️‍♀️ are incentivized to execute these tasks. Here is a short list of them:

* Deploying new option token contracts
* Liquidating expired option token contracts
* Calling prefetch functions for updating contracts preprocessed parameters values (ex: daily price volatilities) to reduce traders gas usage
* Monitoring collateral requirements for performing early liquidation of undercollateralized options writers open positions

Upon successfully executing one or more of these tasks a validator will be rewarded with **Defi Options** governance tokens, which he/she could exchange for their monetary value, or accumulated for having a say in the governance process.


# Token Holders

Token Holders 🥮 collectively constitute the DAO (decentralized autonomous organization) that oversees the **Defi Options** protocol.

Through a proposal voting process they can change the parameters that govern the options exchange operations, such as:

* Credit / Debt interest rates
* The exchange's payment processing fee
* The stablecoins accepted by the exchange
* Registered underlying price feeds (against which options are written)
* Collateral model parameters (ex: volatility period, multipliers, etc)

Besides that token holders can also submit proposals for using the exchange's excess capital, for instance for being used as additional collateral for covering loans from defaulting debtors, for being invested in the protocol's continuing development, or simply for being distributed among token holders themselves.


# Liquidity Pool

One could say that achieving efficient pricing is among the biggest challenges for implementing a successful liquidity pool. Typically the price of an asset varies according to supply and demand pressures. If there’s too much supply prices will drop, since sellers will compete against each other for offering the most competitive price. Likewise if demand is up to the roof prices will rise, since buyers will fight amongst themselves to offer the best price for purchasing an asset.

Several models have been proposed and are being used in DeFi to address this challenge. [Uniswap](https://en.wikipedia.org/wiki/Uniswap) liquidity pools famously use the constant product formula to automatically adjust cryptocurrencies exchange prices upon each processed transaction. In this case market participants are resposible for driving exchange rates up/down by taking advantage of short-lived arbitrage opportunities that appear when prices distantiate from their ideal values.

Nonetheless a supply/demand based pricing model, such as Uniswap’s, may be unfit for pricing options, since an option price is not entirely the result of supply and demand pressures, but rather directly dependent on its underlying’s price. This observation motivated **Defi Options** to propose a linear interpolation based liquidity pool model:

![](/files/-MXtOUfgMkT-7w4eGixN)

On one side of the table we have options traders that interact with the pool by either buying options from it or selling options to it. The pool first calculates the target price for an option based on its internal pricing parameters (more on that latter) and then applies a fixed spread on top of it for deriving the buy price above the target price, and sell price below the target price. This spread can be freely defined by the pool operator and should be high enough for ensuring the pool is profitable, but not too high as to demotivate traders.

On the other side of the table we have liquidity providers. They interact with the pool by depositing funds into it which are used to both **i)** allocate collateral for writing new option tokens for selling to traders and **ii)** allocate a reserve of capital for buying option tokens from traders.

**PS**: Notice that, even though the protocol provides the linear interpolation based pool implementation, the options exchange is completely independent / decoupled from liquidity pools. This brings up many possibilities such as the emergence of new liquidity pool designs from the community for addressing specific market requirements.


# Pool Deposits

Liquidity providers receive pool tokens in return for depositing compatible stablecoin tokens into the pool following a “post-money” valuation strategy, i.e., proportionally to their contribution to the total amount of capital allocated in the pool including the expected value of open option positions. This allows new liquidity providers to enter the pool at any time without harm to pre-existent providers.

Funds are locked in the pool until it reaches the pre-defined liquidation date, whereupon the pool ceases operations and profits are distributed to liquidity providers proportionally to their participation in the total supply of pool tokens.

Even so, since the pool is tokenized, liquidity providers are free to trade their pool tokens in the open market in case they need to recover their funds earlier.


# Pricing Model

The pool holds a pricing parameters data structure for each tradable option which contains a discretized pricing curve calculated off-chain based on a traditional option pricing model (ex: Monte Carlo) that’s “uploaded” to the pool storage. The pool pricing function receives the underlying price (fetched from the underlying price feed) and the current timestamp as inputs, then it interpolates the discrete curve to obtain the desired option’s target price. That’s it, simple math.

The pricing curve is defined by two timestamps ("t0" and "t1") and two arrays ("x" and "y"). Let's take a look at an example:

```
 // underlying price points (US$)
x = [1350, 1400, 1450, 1500, 1550, 1600, 1650];

y = [
     // option price points for "t0" (US$)
    27, 42, 62, 87, 118, 152, 191,
    
    // option price points for "t1" (US$)
    22, 36, 56, 81, 111, 146, 185
];
```

This example snippet defines price points for a hypothetical ETH call option with strike price of US$ 1.500 and an interpolation period starting at 7 days to maturity ("t0") and ending at 6 days to maturity ("t1"), resulting in the pricing surface plotted below:

![](/files/-MXtNZQmGYN298IVXhwo)

By following this approach the more heavy math is performed off-chain, since it would be unfeasible/too damn expensive to run a Monte Carlo simulation or any other option pricing method on ethereum, and actually a waste of capital, as interpolating a preprocessed discretized curve achieves similar end results with much less on-chain computational effort.


# Clearing System

Clearing denotes all activities from the time an option is written until it is settled. This process turns the promise of payment of an option's intrinsic value into the actual movement of funds from one account to another, considering the option expires in the money.

Options are inherently risky [⚠️](https://emojipedia.org/warning/) and in the case of european style options writers are faced with a financial obligation towards options holders upon maturity of the option, proportional to the option intrinsic value and volume written.

Hence the exchange is required to implement a set of risk management rules for ensuring that writers will, in the large majority of cases, fulfill their financial obligations.

The options exchange collateral allocation model and its liquidation process are presented in the next sections. They've been designed to protect options holders against the risk of options writers defaulting their payment obligations, but at the same time with capital efficiency in mind as to allow writers a more flexible environment.


# Collateral Allocation

The options exchange requires options writers to provide collateral for writing options, for making sure writers will be able to cover financial obligations once options mature, and not simply default on payments.

All open positions owned by an address (written or held) are taken into account for allocating collateral regardless of the underlying, option type and maturity, according to the following formula implemented in solidity code:

![](/files/-MXtAyxUBPK7FG0q52cJ)

A short position "i" increases required collateral proportionally to the written volume taking into account the period adjusted on-chain historical underlying price volatility and the option intrinsic value ("υ"). A long position "j" decreases required collateral proportionally to the held volume taking into account the option intrinsic value alone. The k-upper constant plays a role in the liquidation process and serves as an additional security factor protecting against the inherent uncertainty of the underlying price volatility (i.e. the volatility-of-volatility risk).


# Liquidation Process

Options can be liquidated either individually due to a writer not meeting collateral requirements for covering his open positions, or collectively at the option token contract level upon maturity.

In the first case, when a writer doesn't meet the collateral requirements for covering his open positions, any of his positions will be susceptible to early liquidation for reducing liabilities until the writer starts meeting collateral requirements again.

The effective volume susceptible to early liquidation is calculated using the minimum required volume for the writer to start meeting the collateral requirements again:

![](/files/-MXtDx5cCa9MI2_5JUue)

Here two constants are employed, k-upper and k-lower, whose difference enables the clearance of the collateral deficit in a simple manner. Once the liquidation volume is found, the liquidation value is calculated as:

![](/files/-MXtEADeQdDoNBeQJy-y)

Funds from early liquidation are transferred to the respective option token contract and held until maturity.

Now in the second scenario, when the option token contract matures, all still active written options are liquidated, cash settled by the credit provider contract and the accumulated capital becomes available for redemption among option holders proportionally to their share of the total token supply. In case any option writer happens to be short on funds during settlement the credit provider will register a debt and cover payment obligations, essentially performing a lending operation.


# Governance

**Defi Options** is being built to function as a DAO, i.e., a decentralized autonomous organization.

Protocol settings are embedded into the smart contracts and can be managed by governance token holders, which can submit proposals for updating these settings values.

Once submitted proposals go through a voting cycle. If the majority of participants vote in favor of the proposal it gets executed and changes are applied to the protocol. Otherwise, if the proposal doesn't get enough votes for approval, it's marked as rejected resulting in no change to the protocol.


# Protocol Settings

Below is a short list of protocol settings that are managed by the governance process:

| Setting             | Description                                                                                                             |
| ------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| minShareForProposal | Minimum share of the total governance tokens supply for being able to submit a proposal                                 |
| debtInterestRate    | Interest rate charged to outstanding debts by the "CreditProvider" contract                                             |
| creditInterestRate  | Interest rate applied to credit tokens balances                                                                         |
| processingFee       | Options cash settling fee charged by the "CreditProvider" contract                                                      |
| volatilityPeriod    | Period in days for calculating the onchain volatility of underlying assets, required in the collateral allocation model |

The list of accepted stablecoins is also stored in the protocol settings contract along with each stablecoin conversion parameters, for converting values to the protocol's decimals base ("18" decimals).


# Proposal Voting

A proposal is defined as a (verified) smart contract that follows a specific template provided by **Defi Options**. Token holders that meet a minimum share of the total supply of governance tokens are allowed to submit proposals for voting [🗳️](https://emojipedia.org/ballot-box-with-ballot/) by the DAO.

The voting phase will be open for a specific period of time, after which the proposal is marked either as approved or rejected, depending on the amount of "yea" or "nay" votes it's received.

If approved, the proposal will be granted "administrative" privileges for calling functions for updating the protocol's settings. This approach allows for a flexible governance model.

If rejected the proposal is simply ignored, and won't be executed nor be granted any privilege that would allow it to modify protocol's settings.


# DOD Token

DOD Contract Address on **Ethereum**: [0xfc7e3cfa47fbf90310ec203f46fee1af2771548c](https://etherscan.io/token/0xfc7e3cfa47fbf90310ec203f46fee1af2771548c?a=0x6950429826459dc2b8c3fcc1a07b6fb6eca192b9)

DOD Contract Address on **Polygon (Matic)**: [0x7e6663d14f058880fad199bcb745a81c46407809](https://polygonscan.com/token/0x7e6663d14f058880fad199bcb745a81c46407809?a=0xEea5B2889BF36695d45bFD2071c2499065831B0A)

## Token Utility

### Governance

DOD Token is a [#governance](#governance "mention") token that gives it's owners right to influence [Protocol Settings](/protocol/governance/protocol-settings) via [Proposal Voting](/protocol/governance/proposal-voting). Please refer to [Token Holders](/protocol/roles/token-holders) for details.

### Contributor Rewards

[Contributors](/community/contributors) can earn DOD for bringing value to the community.

### Community Rewards

🛠  - We are preparing several reward programs to incentivise early protocol usage, liquidity, security and staking.

{% hint style="warning" %}
DeFi Options DAO (DOD) tokens are utility tokens targeted solely at creating a community of supporters of the protocol. They don't hold any monetary value, nor can they be characterised as investment, shares or securities of any type. Owning DOD tokens doesn't entitle you any rights or guarantees of any kind. If you've swapped any other token or crypto to acquire DOD tokens be advised that you WON'T be refunded under any circumstances. Acquire DOD tokens at your own discretion. You are waiving your rights and agreeing to these terms and conditions if you decide to go further and become a holder of DOD tokens. If you are uncertain as to anything in this informative website or you are not prepared to lose all tokens or crypto that you swap for acquiring DOD tokens, we strongly urge you not to acquire any DOD tokens, not to engage with DOD.
{% endhint %}

## Token Economics

Total Supply: 100,000,000 DOD

Seed Sale Allocation: 5,000,000 DOD

Seed Sale Rate ≈ $0.015 / DOD

Seed Sale Total Raise: $75.000 (Used for [Security](/security#audit))

Seed Sale Vesting period: 25% released form day 1, 75% unlocked after 100 days

![](/files/IWMuXev74uV92szAed8y)


# Contributors

{% embed url="<https://www.loom.com/share/4ac0df18ab564d53815384e35b62ab3e?t=0>" %}

Bellow you can find proposed framework & process for token allocation that makes sure we value contributors that are important for the long-term success. Since the DAO consists of a big group of individuals with different subjective experiences of what is valuable & fair this is our attempt of making the reward allocation process transparent & decentralised while providing **ability to get involved regardless of your background, skill level, and availability**.

## 1. For Everyone: Rewarded Engagement in Discord and Forum

We are using [SourceCred](https://sourcecred.io/) - technology that makes it easy to track and reward engagement. Based on your participation and other's reaction to it, we will measure your credibility (Cred).

In short, we are tracking and rewarding:

* Messages sent
* Reactions sent & received
* Sending and receiving props
* Mentioning and being mentioned by

Please complete the [onboarding](https://shinedao.finance/onboarding/) at ShineDAO to start earning rewards automatically.

As seen in the [\[Proposal\] SourceCred Integration & Rewards Distribution](https://snapshot.org/#/defioptionsdao.eth/proposal/QmZFsejaToqzJyQknkVk9aHv74Uo68kfp1tEgTrXvEMv5w), we will start by distributing 10,000 DOD weekly.

## 2. For New or Passive Content Creators: Decentralised Content Creation Process

For **new** or **passive** content creators: You will get the opportunity to contribute with full creative freedom. The process bellow will prevent spreading information that is false or not aligned with the rest of the community. Please find useful resources for content in [Marketing Material](/community/marketing-material).

{% embed url="<https://forum.shinedao.finance/t/decentralized-content-creation/41>" %}

## 3. For Early Contributors in Our Guilds: 4% of Total DOD Supply

[Coordinape](https://coordinape.com/) is a tool to do just that allows us to reward each-other retroactively in decentralised way. Wanna participate?

1. Check out the activities happening in our Notion
2. See if you can help with any of existing **Initiative🧑‍🚀**  or create your own initiative! (please talk to points of contact)
3. If you pass the trial, you will be invited to the guild and ready to benefit from early contributor allocation

{% embed url="<https://oasis-firefly-683.notion.site/DeFi-Options-DAO-ef46b38ed2f14eb6b37f8a23a808d204>" %}

## 4. Contributing to Core Development

Simply [shoot a message](mailto:defi-options@protonmail.com?subject=DeFiOptions%20%7C%20Interested%20Contributor) describing how do you wish to contribute so we can arrange a plan accordingly.


# Marketing Material

## Logo

![](/files/u2vq4c4dq0Z5pORSqtBJ)

## **Colours**

![](/files/W0GvZIyK8pCUGgBOWI0X)

## Styleguide

{% embed url="<https://www.figma.com/file/AFWN8qL29z8upMw8FcadR8?node-id=244%3A9855>" %}

## Process

{% embed url="<https://forum.shinedao.finance/t/decentralized-content-creation/41>" %}


# Resources

Here are some resources to learn more about options:

{% embed url="<https://optionalpha.com/courses/options-basics>" %}

{% embed url="<https://www.khanacademy.org/economics-finance-domain/core-finance/derivative-securities>" %}

{% embed url="<https://www.investopedia.com/options-basics-tutorial-4583012>" %}

If you have any questions or suggestions, we'd love to hear from you in our [Discord Server](https://discord.gg/WCeKgHNz3z).


# Risk Factors

In this section we're going to take a look at the different types of risk that play a role in the context of an options trading environment, be it in traditional finance or in decentralized finance:

* [Options](/knowledge-base/risk-factors/options)
* [Liquidity Pool](/knowledge-base/risk-factors/liquidity-pool)

It's paramount that you have a clear understanding of the risk factors before interacting with such an environment. It's not recommended to take part in any activity related to options trading unattended or without proper knowledge of the risks involved.

**You shouldn't in any circumstance entrust, deposit, trade or allocate more funds than you're willing to lose completely when dealing with options.**

This content is for informational purposes only, you should not construe any such information or other material as legal, tax, investment, financial, or other advice. Nothing contained in this Site constitutes a solicitation, recommendation, endorsement, or offer to buy or sell any financial instrument or crypto.


# Options

Options carry different risks depending on their type (Call/Put) and how they're traded (held/writen). Let's take a look at the different risk profiles for each possible operation:

**Call holders**: If you buy a call, you are buying the right to purchase the stock at a specific price. The upside potential is unlimited, and the downside potential is the premium that you spent. You want the price to go up a lot so that you can buy it at a lower price.

**Put holders**: If you buy a put, you are buying the right to sell a stock at a specific price. The upside potential is the difference between the share prices (suppose you buy the right to sell at $5 per share and it drops to $3 per share). The downside potential is the premium that you spent. You want the price to go down a lot so you can sell it at a higher price.

**Call writers**: If you sell a call, you are selling the right to purchase to someone else. The upside potential is the premium for the option; the downside potential is unlimited. You want the price to stay about the same (or even drop a little) so that whoever buys your call doesn’t exercise the option and force you to sell.

**Put writers**: If you sell a put, you are selling the right to sell to someone else. The upside potential is the premium for the option, the downside potential is the amount the stock is worth. You want the price to stay above the strike price so that the buyer doesn’t force you to sell at a higher price than the stock is worth.

To simplify further, if you buy an option, your downside potential is the premium that you spent on the option. **If you sell a call there is unlimited downside potential; if you sell a put, the downside potential is limited to the value of the underlying asset**.

Reference:

* [Is it Risky to Invest in Options? (Investopedia)](https://www.investopedia.com/articles/investing/122815/it-risky-invest-options.asp)


# Liquidity Pool

Becoming a liquidity provider by depositing funds in a liquidity pool that writes and sells options is **exceptionally risky**, and you shouldn't in any circumstance deposit more funds in a pool than you're willing to lose completely.

As we've seen in the Risk Factors [Options](/knowledge-base/risk-factors/options) page, call/put writers take the highest amounts of risk in the context of options trading, and in a sense the pool acts as a crowdfunded options writer agent. Liquidity providers then are exposed to the same risk profile as the liquidity pool, proportional to their stake in the pool.

In addition to the aforementioned risks of trading options liquidity providers are also subject to risks related to:

* **Pricing Model Performance**: The pool prices options according to a specific pricing model, determined by the pool operator. If the pricing model prices options too cheap then the liquidity pool will, on average, lose money.
* **Smart Contract Vulnerabilities**: The liquidity pool smart contract is decoupled from the options exchange. It has been audited by PeckShield, along with all other protocol contracts. Nonetheless it's particularly complex and hasn't been battle tested yet, so interact with it with caution.


# Making a deposit

In order to make a deposit first approve a compatible stablecoin allowance for the exchange on the amount you wish to deposit, then call the exchange's `depositTokens` function:

```
ERC20 stablecoin = ERC20(0x123...);
OptionsExchange exchange = OptionsExchange(0xABC...);

address to = 0x456...;
uint value = 100e18;
stablecoin.approve(address(exchange), value);
exchange.depositTokens(to, address(stablecoin), value);
```

*Obs: An* [*EIP-2612 compatible*](https://eips.ethereum.org/EIPS/eip-2612) *`depositTokens` function is also provided for deposit functions in a single transaction.*

After the operation completes check total exchange balance for an address using the `balanceOf` function:

```
address owner = 0x456...;
uint balance = exchange.balanceOf(owner);
```

Balance is returned in dollars considering 18 decimal places.

In case you wish to withdraw funds (ex: profits from an operation) call the `withdrawTokens` function:

```
uint value = 50e18;
exchange.withdrawTokens(value);
```

The function will transfer stablecoin tokens to the `msg.sender` for the requested amount, provided that the caller has enough unallocated balance. Since the exchange accepts multiple stablecoins the withdrawer should expect to receive any of these tokens.

*Obs: If there aren't enough stablecoins available in the exchange the solicitant will receive ERC20 credit tokens issued by the credit provider contract which can later be redeemed for stablecoins at a 1:1 value conversion ratio.*

<br>


# Writing options

Before writing an option calculate the amount of collateral needed by calling the `calcCollateral` function providing the option parameters:

```
address eth_usd_feed = address(0x987...);
uint volumeBase = 1e18;
uint strikePrice = 1300e18;
uint maturity = now + 30 days;

uint collateral = exchange.calcCollateral(
    eth_usd_feed, 
    10 * volumeBase, 
    OptionsExchange.OptionType.CALL, 
    strikePrice, 
    maturity
);
```

The snippet above calculates the collateral needed for writing ten ETH call options at the strike price of US$ 1300 per ETH maturing in 30 days from the current date.

After checking that the writer has enough unallocated balance to provide as collateral, proceed to write options by calling the `writeOptions` function:

```
address holder = 0xDEF...;

address tkAddr = exchange.writeOptions(
    eth_usd_feed, 
    10 * volumeBase, 
    OptionsExchange.OptionType.CALL, 
    strikePrice, 
    maturity,
    holder
);
```

Options are issued as ERC20 tokens and sent to the specified `holder` address. The `writeOptions` function returns the option token contract address for convenience:

```
ERC20 token = ERC20(tkAddr);
uint balance = token.balanceOf(holder); // equal to written volume

address to = 0x567...;
token.transfer(to, 5 * volumeBase); // considering 'msg.sender == owner'
```

Options are aggregated by their underlying, strike price and maturity, each of which will resolve to a specific ERC20 token contract address. Take advantage of already existent option token contracts when writing options for increased liquidity.

The `calcIntrinsicValue` allows callers to check the updated intrinsict value for an option, specified by its token contract address `tkAddr`:

```
uint iv = exchange.calcIntrinsicValue(tkAddr);
```

Suppose the ETH price has gone up to US$ 1400, and considering that the strike price was set to US$ 1300, then the intrinsic value returned would be `100e18`, i.e., US$ 100. Multiply this value by the held volume to obtain the position's aggregated intrinsic value.


# Collateral allocation

All open positions owned by an address (written or held) are taken into account for allocating collateral regardless of the underlying, option type and maturity, according to the following formula implemented in solidity code:

![](/files/-MXtAyxUBPK7FG0q52cJ)

A short position "i" increases required collateral proportionally to the written volume taking into account the period adjusted on-chain historical underlying price volatility and the option intrinsic value ("υ"). A long position "j" decreases required collateral proportionally to the held volume taking into account the option intrinsic value alone. The kupper constant plays a role in the liquidation process and serves as an additional security factor protecting against the inherent uncertainty of the underlying price volatility (i.e. the volatility-of-volatility risk).

Call the `calcCollateral` function to perform this calculation and obtain the collateral requirements for a specific address:

```
uint collateral = exchange.calcCollateral(owner);
```

The difference between the address balance and its collateral requirements is the address surplus. The `calcSurplus` function is conveniently provided to perform this calculation:

```
uint surplus = exchange.calcSurplus(owner);
```

The surplus effectively represents the amount of funds available for writing new options and for covering required collateral variations due to underlying price jumps. If it returns zero it means that the specified address is lacking enough collateral and at risk of having its positions liquidated.


# Liquidating positions

Options can be liquidated either individually due to a writer not meeting collateral requirements for covering his open positions, or collectively at the option token contract level upon maturity.

In the first case, when a writer doesn't meet the collateral requirements for covering his open positions, any of his positions will be susceptible to liquidation for reducing liabilities until the writer starts meeting collateral requirements again.

To liquidate a specific writer option in this situation call the `liquidateOptions` function providing both the option token contract address and the writer address:

```
uint value = exchange.liquidateOptions(tkAddr, owner);
```

The function returns the value resulting from liquidating the position (either partially or fully), which is transferred to the respective option token contract and held until maturity, whereupon the contract is fully liquidated and profits are distributed to option holders proportionally to their share of the total supply.

The effective volume liquidated by this function call is calculated using the minimum required volume for the writer to start meeting the collateral requirements again:

![](/files/-MXtDx5cCa9MI2_5JUue)

Here two constants are employed, kupper and klower, whose difference enables the clearance of the collateral deficit in a simple manner. Once the liquidation volume is found, the liquidation value is calculated as:

![](/files/-MXtEADeQdDoNBeQJy-y)

Now in the second case, when the option matures, all option token contract written positions can be liquidated for their intrinsic value. The exchange offers a function overload that accpets an array of options writers addresses for liquidating their positions in a more gas usage efficient way:

```
address[] memory owners = new address[](length);
// initialize array (...)
exchange.liquidateOptions(tkAddr, owners);
```

Liquidated options are cash settled by the credit provider contract and the accumulated capital becomes available for redemption among option holders proportionally to their share of the total token supply:

```
OptionToken optionToken = OptionToken(tkAddr);
optionToken.redeem(holder);
```

In case any option writer happens to be short on funds during settlement the credit provider will register a debt and cover payment obligations, essentially performing a lending operation.


# Burning options

he exchange keeps track of all option writers and holders. Option writers are addresses that create option tokens. Option holders in turn are addresses to whom option tokens are transferred to. On calling the `writeOptions` exchange function an address becomes both writer and holder of the newly issued option tokens, until it decides to transfer them to a third-party.

In order to burn options, for instance to close a position before maturity and release allocated collateral, writers can call the `burn` function from the option token contract:

```
OptionToken token = OptionToken(tokenAddress);
uint amount = 5 * volumeBase;
token.burn(amount);
```

The calling address must be both writer and holder of the specified volume of options that are to be burned, otherwise the function will revert. If the calling address happens to be short biased (written volume > held volume) it will have to purchase option tokens in the market up to the volume it wishes to burn.

#### Underlying feeds

Both the `calcCollateral` and the `writeOptions` exchange functions receive the address of the option underlying price feed contract as a parameter. The feed contract implements the following interface:

```
interface UnderlyingFeed {

    function symbol() external view returns (string memory);

    function getLatestPrice() external view returns (uint timestamp, int price);

    function getPrice(uint position) external view returns (uint timestamp, int price);

    function getDailyVolatility(uint timespan) external view returns (uint vol);

    function calcLowerVolatility(uint vol) external view returns (uint lowerVol);

    function calcUpperVolatility(uint vol) external view returns (uint upperVol);
}
```

The exchange depends on these functions to calculate options intrinsic value, collateral requirements and to liquidate positions.

* The `symbol` function is used to create option token contracts identifiers, such as `ETH/USD-EC-13e20-1611964800` which represents an ETH european call option with strike price US$ 1300 and maturity at timestamp `1611964800`.
* The `getLatestPrice` function retrieves the latest quote for the option underlying, for calculating its intrinsic value.
* The `getPrice` function on the other hand retrieves the first price for the underlying registered in the blockchain after a specific timestamp position, and is used to liquidate the option token contract at maturity.
* The `getDailyVolatility` function is used to calculate collateral requirements as described in the [collateral allocation](https://github.com/DeFiOptions/DeFiOptions-core#collateral-allocation) section.
* The `calcLowerVolatility` and `calcUpperVolatility` apply, respectively, the klower and kupper constants to the volatility passed as a parameter, also used for calculating collateral requirements, and for liquidating positions as well.

This repository provides a [Chainlink](https://chain.link/) based implementation of the `UnderlyingFeed` interface which allows any Chainlink USD fiat paired currency (ex: ETH, BTC, LINK, EUR) to be used as underlying for issuing options:

* [contracts/feeds/ChainlinkFeed.sol](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/feeds/ChainlinkFeed.sol)

Notice that this implementation provides prefetching functions (`prefetchSample`, `prefetchDailyPrice` and `prefetchDailyVolatility`) which should be called periodically and are used to lock-in underlying prices for liquidation and to optimize gas usage while performing volatility calculations.


# Credit tokens

A [credit token](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/finance/CreditToken.sol) can be viewed as a proxy for any of the exchange's compatible stablecoin tokens, since it can be redeemed for the stablecoin at a 1:1 value conversion ratio. In this sense the credit token is also a stablecoin, one with less liquidity nonetheless.

Credit tokens are issued when there aren't enough stablecoin tokens available in the exchange to cover a withdraw operation. Holders of credit tokens receive interest on their balance (hourly accrued) to compensate for the time they have to wait to finally redeem (burn) these credit tokens for stablecoins once the exchange ensures funds again. To redeem credit tokens call the `requestWithdraw` function, and expect to receive the requested value in any of the exchange's compatible stablecoin tokens:

```
CreditToken ct = CreditToken(0xABC...);
ct.requestWithdraw(value);
```

In case there aren't sufficient stablecoin tokens available to fulfil the request it'll be FIFO-queued for processing when the exchange ensures enough funds.

The exchange will ensure funds for burning credit tokens when debtors repay their debts (for instance when an option token contract is liquidated and the debtor receives profits, which are instantly discounted for pending debts before becoming available to the debtor) or through options settlement processing fees, which by default are not charged, but can be configured upon demand.


# Linear liquidity pool

This project provides a liquidity pool implementation that uses linear interpolation for calculating buy/sell option prices. The diagram below illustrates how the linear interpolation liquidity pool fits in the options exchange trading environment, how market agents interact with it, and provides some context on the pool pricing model:

![](/files/-MXtOUfgMkT-7w4eGixN)

The pool holds a pricing parameters data structure for each tradable option which contains a discretized pricing curve calculated off-chain based on a traditional option pricing model (ex: Monte Carlo) that’s “uploaded” to the pool storage. The pool pricing function receives the underlying price (fetched from the underlying price feed) and the current timestamp as inputs, then it interpolates the discrete curve to obtain the desired option’s target price.

A fixed spread is applied on top of the option’s target price for deriving its buy price above the target price, and sell price below the target price. This spread can be freely defined by the pool operator and should be high enough for ensuring the pool is profitable, but not too high as to demotivate traders.

### **Pool interface**

The following [liquidity pool interface](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/interfaces/ILiquidityPool.sol) functions are provided for those willing to interact with the options exchange environment:

```
interface ILiquidityPool {

    function depositTokens(address to, address token, uint value) external;

    function listSymbols() external view returns (string memory);

    function queryBuy(string calldata optSymbol) external view returns (uint price, uint volume);

    function querySell(string calldata optSymbol) external view returns (uint price, uint volume);

    function buy(string calldata optSymbol, uint price, uint volume, address token)
        external
        returns (address addr);

    function sell(string calldata optSymbol, uint price, uint volume) external;
}
```

*Obs:* [*EIP-2612 compatible*](https://eips.ethereum.org/EIPS/eip-2612) *`buy` and `sell` functions are also provided for trading options in a single transaction.*

Liquidity providers can call the `depositTokens` function for depositing compatible stablecoin tokens into the pool and receive pool tokens in return following a “post-money” valuation strategy, i.e., proportionally to their contribution to the total amount of capital allocated in the pool including the expected value of open option positions. This allows new liquidity providers to enter the pool at any time without harm to pre-existent providers.

Funds are locked in the pool until it reaches the pre-defined liquidation date, whereupon the pool ceases operations and profits are distributed to liquidity providers proportionally to their participation in the total supply of pool tokens.

The `listSymbols` function should be called to obtain the list of tradable options in the pool and returns a string containing all active option symbols, one per line. Symbols are encoded as follows:

* `[underlying symbol]/[base currency]-[type code]-[strike price]-[maturity]`

Where:

* The type code will be “EC” for European Call or “EP” for European Put.
* Strike price is provided in the base currency using a “1e18” decimal base. For instance, considering the USD base currency, 175e19 is equivalent to 1750e18 which in turn converts to 1750 USD.
* Maturity is provided as a Unix timestamp from epoch. For instance, 161784e4 is equivalent to 1617840000 which in turn converts to “GMT: Thursday, 8 April 2021 00:00:00”.

### **Buying from the pool**

Traders should first call the `queryBuy` function which receives an option symbol and returns both the spread-adjusted “buy” price and available volume for purchase from the pool, and then call the `buy` function specifying the option symbol, queried “buy” price, desired volume for purchase and the address of the stablecoin used as payment:

```
(uint buyPrice,) = pool.queryBuy(symbol);
uint volume = 1 * volumeBase;
stablecoin.approve(address(pool), price * volume / volumeBase);
pool.buy(symbol, price, volume, address(stablecoin));
```

### **Selling to the pool**

Likewise traders should first call the `querySell` function which receives an option symbol and returns both the spread-adjusted “sell” price and available volume the pool is able to purchase, and then call the `sell` function specifying the option symbol, queried “sell” price and the pre-approved option token transfer volume being sold:

```
(uint sellPrice,) = pool.querySell(symbol);
uint volume = 1 * volumeBase;

OptionToken token OptionToken(exchange.resolveToken(symbol));
token.approve(address(pool), price * volume / volumeBase);
pool.sell(symbol, price, volume);
```

Upon a successful transaction payment for the transferred option tokens is provided in the form of balance transferred from the pool account to the `msg.sender` account within the options exchange.


# Addresses

### Polygon

DeFi Options has been deployed to Polygon mainnet. Find the verified contracts addresses in the table below:

| Contract                                                                                                                     | Address                                                                                                                  |
| ---------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------ |
| [OptionsExchange](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/finance/OptionsExchange.sol)         | [0x69b38e5cd783cbeeb06e11b4ad29a95af14dbcc9](https://polygonscan.com/address/0x69b38e5cd783cbeeb06e11b4ad29a95af14dbcc9) |
| [CreditToken](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/finance/CreditToken.sol)                 | [0x045f70e2e63907000c0ff511862c936fc0857979](https://polygonscan.com/address/0x045f70e2e63907000c0ff511862c936fc0857979) |
| [Linear Liquidity Pool](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/pools/LinearLiquidityPool.sol) | [0xa8353943cd1b9572d46ff927c8cfe89ba0b06b19](https://polygonscan.com/address/0xa8353943cd1b9572d46ff927c8cfe89ba0b06b19) |
| [ETH/USD feed](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/interfaces/UnderlyingFeed.sol)          | [0xc6538cec5ca383217efe2c10b447d8d48453874a](https://polygonscan.com/address/0xc6538cec5ca383217efe2c10b447d8d48453874a) |
| [BTC/USD feed](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/interfaces/UnderlyingFeed.sol)          | [0x2205c21d04adc4a9d6a5f55e76aec39010bb5e72](https://polygonscan.com/address/0x2205c21d04adc4a9d6a5f55e76aec39010bb5e72) |
| [MATIC/USD feed](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/interfaces/UnderlyingFeed.sol)        | [0x822a5D26a5A8F881BF4C515E51cF00fC063C6C3C](https://polygonscan.com/address/0x822a5D26a5A8F881BF4C515E51cF00fC063C6C3C) |
| [SOL/USD feed](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/interfaces/UnderlyingFeed.sol)          | [0x2863E94bEBa09F53888887F9d647bd406a593b43](https://polygonscan.com/address/0x2863E94bEBa09F53888887F9d647bd406a593b43) |

### Kovan

DeFi Options is available on kovan testnet for testing. Contract addresses are provided in the table below:

| Contract                                                                                                                     | Address                                                                                                                     |
| ---------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------- |
| [OptionsExchange](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/finance/OptionsExchange.sol)         | [0x1233a9d9a02eef1bc24675332684d4bfdd866f8a](https://kovan.etherscan.io/address/0x1233a9d9a02eef1bc24675332684d4bfdd866f8a) |
| [CreditToken](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/finance/CreditToken.sol)                 | [0xae7512c5d996b12830a282eeb9eecb4cf01207d2](https://kovan.etherscan.io/address/0xae7512c5d996b12830a282eeb9eecb4cf01207d2) |
| [Linear Liquidity Pool](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/pools/LinearLiquidityPool.sol) | [0xb0be2a679632f028edb4a3e29bb82ac6ed6d84d9](https://kovan.etherscan.io/address/0xb0be2a679632f028edb4a3e29bb82ac6ed6d84d9) |
| [ETH/USD feed](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/interfaces/UnderlyingFeed.sol)          | [0xF6DF43F27d51289703C2A93289D53C4D5AC79b7d](https://kovan.etherscan.io/address/0xF6DF43F27d51289703C2A93289D53C4D5AC79b7d) |
| [BTC/USD feed](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/contracts/interfaces/UnderlyingFeed.sol)          | [0x261E05174813A0a6dafE208830410768b709E6ca](https://kovan.etherscan.io/address/0x261E05174813A0a6dafE208830410768b709E6ca) |
| [Fakecoin](https://github.com/DeFiOptions/DeFiOptions-core/blob/master/test/common/mock/ERC20Mock.sol)                       | [0xB51E93aA4B4B411A36De9343128299B483DBA133](https://kovan.etherscan.io/address/0xB51E93aA4B4B411A36De9343128299B483DBA133) |

A freely issuable ERC20 fake stablecoin ("fakecoin") is provided for convenience. Simply issue fakecoin tokens for an address you own to be able to interact with the exchange for depositing funds, writing options and evaluate its functionality:

```
ERC20Mock fakecoin = ERC20Mock(0xdd8...);
address to = 0xABC
uint value = 1500e18;
fakecoin.issue(to, value);
```


