# Divergence Protocol

How are your perps when the markets are calm? Returning 1%, 3%, 5%, on top of funding fees and liquidation risks? With [digital options](/overview/protocol-basics/digital-options), a trader enjoys freedom of expression, choosing a return up to 99x, no matter the market.

### Introduction to Divergence v1

Divergence v1 is an innovative [automated market maker](https://chain.link/education-hub/what-is-an-automated-market-maker-amm) (AMM) evolved from Uniswap V3. It presents unprecedented capital efficiency for DeFi options. Its permissionless, peer-to-peer smart contract infrastructure enables [digital options](/overview/protocol-basics/digital-options) to be tokenized, swapped, and settled on [Ethereum](https://ethereum.org/) and EVM-compatible chains. &#x20;

* **Open, Permissionless System**: It ensures equal opportunities for anyone to:
  * Create a digital options market of a custom underlying, strike, expiry, and collateral
  * Swap for digital calls or puts
  * Provide liquidity to sell digital calls or puts passively and earn premiums plus fees
  * Settle options using the price feeds from decentralized oracle networks such as [Pyth](https://docs.pyth.network/price-feeds/use-real-time-data)
* **Capital Efficiency**: The design leverages Uniswap V3 concepts, offering a full suite of DeFi options trading functionalities entirely on-chain. No over-collateralization. No Lockups. Every buyers and sellers decide their own option prices.

### Why Digital Options?

Options are DeFi's next frontier. Current markets focus on a handful of major assets such as BTC and ETH. Many centralized and hybrid solutions gate-keep derivatives markets, neglecting a wide array of long-tail assets and their potential to be leveraged.&#x20;

Digital options are ideal for leverage trading and hedging volatile assets. Divergence v1 empowers DeFi native assets typically bypassed by perpetual swaps. Any ERC20 fungible assets can be used as options collateral and/or underlying. Unlike [standard options](https://www.investopedia.com/terms/o/option.asp), the risk and reward of digital options is known before a trade:

* **No Liquidation Risk**: No stress about wick candles! All options are fully-backed, preventing liquidations during extreme market fluctuations.
* **Non-linear Return**: Pay a fraction, and earn a fixed 1 collateral when a digital option expires profitably. The % rate of return can far exceed the % price difference of the underlying asset.
* **Up to 99x Leverage**: An option costing as little as 0.01 $DIVERs returns 1 - 0.01 = 0.99 $DIVERs, achieving maximum leverage. The return is always 1 - premium, quoted in collateral units.

### Divergence v1's Protocol Design

The Divergence v1 protocol is designed to cut out the CeFi intermediaries.&#x20;

It differs from a central limit order book, where buy and sell orders are organized by price levels and are matched with specific orders left by others. In the Divergence v1 Automated Market Maker (AMM), options trading occurs directly with a liquidity pool, which serves as an options market with selected specifications. At each price level, users buys options from aggregated liquidity positions. This order is then redistributed to sellers on a *pro-rata* basis.

A Divergence option pool handles three assets: calls, puts, and an [ERC-20 token](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) that collateralizes and quotes the options. The calls and puts are minted as<img src="/files/KICz5vyFPAdeSYRkSpjw" alt="" data-size="line">Spear and <img src="/files/EeXCAlrfMMmuGv4ObKLb" alt="" data-size="line">Shield tokens, respectively. And the collateral token can differ from the underlying, allowing for synthetic exposures.

In the Divergence v1 AMM, options are fully collateralized before they are tokenized, swapped, and settled. Call and put options are valued relative to each other. [Their relative prices change when collaterals are swapped for either calls or puts](/overview/protocol-basics/triangular-swaps), and a new market rate for both options is found.

Using a web3 wallet, anyone can manage individual options exposures. They can long or short options anytime before expiry. Unlike [standard options](https://www.investopedia.com/terms/v/vanillaoption.asp), digital options have limited risk. Protocol participants can decide their maximum gain or loss before a trade.

The protocol's interface is one of the ways one can interact with the protocol. Before using the interface, please confirm the acceptance of the [Terms of Service](/legal/terms-of-service) and [Risk Disclosure](/legal/risk-disclosure).&#x20;


# Protocol Basics

Get started with foundational concepts of Divergence v1.

In a European [digital options](/overview/protocol-basics/digital-options#what-are-digital-options) transaction, the buyer pays a premium and obtains the **right** to receive a fixed $1 payout. This right is tokenized and exercisable at options' maturity. The seller receives the premium and assumes the **obligation** to pay $1.&#x20;

In a Divergence v1 pool, one pays premiums to market buy options. Before a swap, there must be liquidity for a price range. The liquidity providers (LPs) are passive sellers of options. The liquidity they provide ensures that options can be paid off upon settlement. LPs collect fees for transactions within their liquidity range. The premiums they receive are kept in the pool and reserved for settlement.&#x20;

Before options expire, one can also provide previously purchased calls or puts as liquidity to close long exposures, or buy puts or calls to hedge and offset long exposures.

At settlement, anyone can call the smart contracts to retrieve a settlement price from [Pyth](https://docs.pyth.network/price-feeds/use-real-time-data). If the underlying price is above or equal to the strike price, the call options are in-the-money. Call token holders can exercise their rights to receive one collateral per option.  LPs have the seller obligation to pay for their open shorts in calls. Otherwise, the put options are in-the-money, and put holders can claim one collateral per option.  LPs have the seller obligation to pay for their open shorts in puts.

For broader discussions about digital options as a financial derivative, and the core swap and liquidity functionalities of Divergence v1, visit the following pages:

<table data-view="cards"><thead><tr><th align="center"></th><th data-hidden></th><th data-hidden></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td align="center"><strong>Digital Options</strong></td><td></td><td></td><td><a href="/pages/V3otewC7NPlPpWaO4aBf">/pages/V3otewC7NPlPpWaO4aBf</a></td><td><a href="/files/q7Lw7vZCrrydAdJqAUOu">/files/q7Lw7vZCrrydAdJqAUOu</a></td></tr><tr><td align="center"><strong>Triangular Swaps</strong></td><td></td><td></td><td><a href="/pages/oSDjoctcy4YkChbh19Ai">/pages/oSDjoctcy4YkChbh19Ai</a></td><td><a href="/files/r54Yx40WzrH7ZuwBogjj">/files/r54Yx40WzrH7ZuwBogjj</a></td></tr><tr><td align="center"><strong>Convertible Liquidity</strong></td><td></td><td></td><td><a href="/pages/xrJPblwUj44CL6FgA3EO">/pages/xrJPblwUj44CL6FgA3EO</a></td><td><a href="/files/8WVmul54S7E6SgnqRyCy">/files/8WVmul54S7E6SgnqRyCy</a></td></tr></tbody></table>

For those who are looking for a quick reference on options trading, view the one-page summary of [options specs](/overview/protocol-basics/options-specs) and the curated playlists in our [youtube channel](https://www.youtube.com/@DivergenceProtocol). To dive deeper, please refer to the [whitepaper](https://www.divergence-protocol.com/diver_v1AMM_paper.pdf) and the [technical documentation of Divergence v1 smart contracts](/technical-reference/smart-contract-architecture). For some of the fundamental math concepts of the protocol, check out this [Uniswap v3 primer](https://blog.uniswap.org/uniswap-v3-math-primer).&#x20;


# Digital Options

Digital options, also known as binary or bet options, offer a predetermined risk and reward for the holder. Digital calls and puts are minted as Spear and Shield tokens, respectively.

> ***`The Game is a win-or-lose battle,`*** \
> &#x20;   ***`where bullas and beras combat with`*** \
> &#x20;   ***`Spears and Shields,`*** \
> &#x20;   ***`for prizes claimable at expiry.`***  \
> &#x20;                                    ***`-- anon`***:diving\_mask:

Divergence v1 offers European-style digital options, each backed by an ERC-20 token collateral. They are exercised at expiry, paying a fixed amount or nothing at all.&#x20;

## What are Digital Options?

<table data-card-size="large" data-view="cards"><thead><tr><th align="center"></th><th></th><th data-hidden></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td align="center"><strong>Digital Call</strong></td><td><ul><li>Premium costs less than 1 collateral</li><li>Buyer has the right to claim 1 collateral, if the underlying price <em><strong>settles at or above</strong></em> the strike. </li><li>Otherwise, it expires worthless.</li></ul></td><td></td><td><a href="/files/rKeMMM5X2Q0OkGh5a6do">/files/rKeMMM5X2Q0OkGh5a6do</a></td></tr><tr><td align="center"><strong>Digital Put</strong></td><td><ul><li>Premium costs less than 1 collateral</li><li>Buyer has the right to claim 1 collateral, if the underlying price <strong>settle</strong><em><strong>s below</strong></em> the strike. </li><li>Otherwise, it expires worthless. </li></ul></td><td></td><td><a href="/files/SIZVXZEtxKSPmdhzNOar">/files/SIZVXZEtxKSPmdhzNOar</a></td></tr></tbody></table>

## How Much Does it Cost to Long or Short a Digital Option?

<table><thead><tr><th width="194">Position</th><th width="130">Call</th><th>Put</th></tr></thead><tbody><tr><td>Long</td><td>Premium</td><td>Premium</td></tr><tr><td>Short</td><td>1 - Premium</td><td>1 - Premium</td></tr></tbody></table>

## Risk & Reward for a Digital Option

<table><thead><tr><th width="194">Settlement</th><th width="130">Long Call</th><th width="133">Short Call</th><th width="124">Long Put</th><th>Short Put</th></tr></thead><tbody><tr><td>Price ≥ Strike</td><td>Gain 1 - Premium</td><td>Lose 1 - Premium</td><td>Lose Premium</td><td><p>Gain</p><p>Premium</p></td></tr><tr><td>Price &#x3C; Strike</td><td>Lose Premium</td><td>Gain Premium</td><td>Gain 1 - Premium</td><td><p>Lose 1 - </p><p>Premium</p></td></tr></tbody></table>

## How to trade Digital Options?

When using Divergence v1 smart contracts, one can come across:

* &#x20;:crossed\_swords: ***`Battle`*** an AMM pool for digital options
* &#x20;:stadium: ***`Arena`*** deployer and admin of *`Battle`*&#x20;
* <img src="/files/KICz5vyFPAdeSYRkSpjw" alt="" data-size="line">***`Spear`*** a European digital call option token &#x20;
* <img src="/files/EeXCAlrfMMmuGv4ObKLb" alt="" data-size="line">***`Shield`*** a European digital put option token

Each Battle mints Spear and Shield,  ERC-20-compliant options tokens of a specific underlying, strike price, collateral, and expiry. A Battle's contract address is not re-used after expiry. A new Battle can be created for the following expiry. &#x20;

{% hint style="info" %}
*Suppose a digital call costs 0.01 DAI. Its underlying is ETHUSD, and its strike is $2,000. If ETH settles above or equal $2,000, the option pays 1 DAI. Otherwise, it expires worthless. The buyer of this call earns 1 - 0.01 = 0.99 DAI less fees, i.e., a 99x return.*
{% endhint %}

The v1 interface is one of the many ways one may interact with the protocol. The following pages provide concise, step-by-step guides on how to trade digital options:

<table data-card-size="large" data-view="cards"><thead><tr><th></th><th data-hidden></th><th data-hidden></th><th data-hidden data-card-target data-type="content-ref"></th><th data-hidden data-card-cover data-type="files"></th></tr></thead><tbody><tr><td><strong>Long Options</strong></td><td></td><td></td><td><a href="/pages/Wf45vJfNZC1ZljAMK8kO">/pages/Wf45vJfNZC1ZljAMK8kO</a></td><td><a href="/files/RCcpOE5vBWM7LojImj9l">/files/RCcpOE5vBWM7LojImj9l</a></td></tr><tr><td><strong>Short Options</strong></td><td></td><td></td><td><a href="/pages/Nj4SkmXAgndya2pDpSYC">/pages/Nj4SkmXAgndya2pDpSYC</a></td><td><a href="/files/flz9GibEl9ueqV3AiZNS">/files/flz9GibEl9ueqV3AiZNS</a></td></tr></tbody></table>

## How to Price Digital Options?

Simply put, each and every individual user of the protocol decides the price, as they buy and sell tokenized digital options. The protocol does not use a theoretical pricing model to arbitrarily set option prices. **The price for an option is simply the amount of collateral paid divided by the number of options received**. [This model-free approach](/overview/protocol-basics/triangular-swaps) enables real-time price discovery:

* There's not a one-size-fits-all theoretical price model that works at all times.&#x20;
* Commonly used pricing models typically require discretionary inputs and real-time adjustments. The costs of these adjustments need not be imposed on all participants. Instead, the calculations can be done off-chain by individuals, before a transaction.&#x20;

Spear and Shield tokens are priced between 0.01 and 0.99 collateral units. Their prices suggest market expectations about the direction of the underlying price.&#x20;

{% hint style="info" %}
*Suppose you pay 40 USDC to long 100 Spear. You spend 40/100 = 0.4 USDC for a spear. You are estimating a 40% chance that the underlying will settle above the strike price.*
{% endhint %}

For more theoretical and practical guides to digital options pricing, see the [reference](/overview/protocol-basics/references) section.&#x20;

## What is Put-Call Parity?

A crucial underpinning of Divergence v1's design is **the price parity of digital options:**

$$
Digital Call Price + Digital Put Price = 1
$$

In other words, at maturity, the probability of a call being profitable and the probability of a put being profitable add up to 100%.  One can expect the payoff for a long or short digital option to be:

![A Long Spear is a Short Shield. | A Long Shield is a Short Spear. ](/files/GghoPGMq9oWj9ZI28zs0)

* **Long Digital Call = Short Digital Put**&#x20;

{% hint style="info" %}
*Suppose Spear/Shield trades at .40/.60.*

* *A trader who longs a Spear at .40 expects to receive a 1.0 payout, which includes the initial investment of .40 plus .60 profit* *if the underlying settles at or above the strike.*&#x20;

* *A trader who shorts a Shield at .60 expects to keep the collected premium as profit under the same condition.*&#x20;
  {% endhint %}

* **Long Digital Put = Short Digital call**

{% hint style="info" %}
*Suppose Spear/Shield trades at .40/.60.*&#x20;

* *A trader who longs a Shield at .60 expects to receive a 1.0 payout, which includes the initial investment of .60 plus .40 profit if the underlying settles below the strike.*&#x20;
* *A trader who shorts a Spear at .40 expects to keep the collected premium as profit under the same condition.*
  {% endhint %}

{% embed url="<https://youtu.be/ngLl54mY8D0>" %}
Put-Call Parity Explained
{% endembed %}

## Why Digital Options?

Digital options can be used to replicate the payoff structure of any financial asset. They are useful as a hedge against sudden, large price movements in illiquid underlying assets.&#x20;

{% embed url="<https://www.youtube.com/watch?t=1s&v=B0N35uDgKMo>" %}
**Binary Calls Explained**
{% endembed %}

{% embed url="<https://www.youtube.com/watch?v=XCrwqzAC4XQ>" %}
**Binary Puts Explained**
{% endembed %}

## Cash-or-Nothing, Asset-or-Nothing or ???

<img src="/files/KICz5vyFPAdeSYRkSpjw" alt="" data-size="line">Spears and <img src="/files/EeXCAlrfMMmuGv4ObKLb" alt="" data-size="line">Shields can be considered as: &#x20;

* **Cash-or-Nothing** when pool collateral is a **stablecoin;**
* **Asset-or-nothing** when the **underlying asset** is used as collateral;&#x20;

In some cases, a pool may be funded with a collateral asset that is different from the underlying asset, and in this case, the payout is a **correlated or uncorrelated asset.**

{% embed url="<https://www.youtube.com/watch?v=W-CxXh1JQyE>" %}
**Asset-or-Nothing & Cash-or-Nothing Calls Explained**
{% endembed %}

{% embed url="<https://www.youtube.com/watch?t=2s&v=y4IhQmt-fR0>" %}
**Asset-or-Nothing & Cash-or-Nothing Puts Explained**
{% endembed %}

## Composability of Digital Options

Digital options are the basic components of many structured products. One can use a basket of digital options, or combine digital options with other financial products to compose defined risk strategies. They can be a versatile, powerful tool for [hedging a DeFi portfolio](https://medium.com/divergence-protocol/how-to-hedge-your-defi-portfolio-using-options-on-divergence-1dafe6afba9f).

Digital Options are also [the building blocks of standard options](https://en.wikipedia.org/wiki/Black%E2%80%93Scholes_model#Cash-or-nothing_call).  As noted in above video explainers, Asset-or-Nothing and Cash-or-Nothing options can replicate vanilla options:&#x20;

* **Standard European call = Asset-or-Nothing call - Cash-or-Nothing call** \
  *where the cash-or-nothing call payoff equals the strike value*
* **Standard European put = Cash-or-Nothing put - Asset-or Nothing put**&#x20;

  *where the cash-or-nothing put payoff equals the strike value*

Therefore they also present opportunities to arbitrage or hedge against standard options available in DeFi and beyond.:diving\_mask:


# Triangular Swaps

At Divergence v1, one swaps collateral tokens for calls or puts. A virtual curve is used to triangulate the relative value of calls, puts and collaterals as follows:

<figure><img src="/files/WnRWwqFMFFJyyzJFvO4o" alt=""><figcaption><p>Swapping Options Premiums for a Payoff Expected at Settlement </p></figcaption></figure>

A Divergence v1 pool handles three assets: a call, a put, and a collateral token. **Using the virtual curve, one swaps an amount of options premiums for a certain payout expected at settlement**. The buyer obtains the right to receive this expected payout, represented by the options tokens.&#x20;

The virtual curve tracks the squared root of the [cross rate](https://www.investopedia.com/terms/c/crossrate.asp) between call and put options. This cross rate is the relative value of puts quoted by calls. The [put-call parity](/overview/protocol-basics/digital-options#what-is-put-call-parity) is used to compute the value of calls and puts quoted by collateral.

{% hint style="info" %}
The current price of a call is 0.40 collateral.  Per put-call parity, the price of a put must be 1 - 0.40 = 0.60 collateral.  Therefore, the current sqrtPrice tracked by the virtual curve is sqrt(put price/call price) = sqrt(0.60/0.40).&#x20;
{% endhint %}

When one swaps collaterals for calls, the call price rises. The put price must fall because of put-call parity. So, the cross rate of calls and puts drops. Conversely, the put price increases because of a put purchase. The call price declines accordingly, raising the cross rate.&#x20;

{% hint style="info" %}
The price of a call is 0.40 collateral, and the current sqrtPrice is sqrt(0.60/0.40).  A buyer swaps for calls, and the call price rises to 0.45 collateral. Per put-call parity, the new put price must be 1-0.45 = 0.55 collateral. The sqrtPrice declines to sqrt(0.55/0.45).
{% endhint %}

{% hint style="info" %}
The price of a put is 0.60 collateral, and the current sqrtPrice is sqrt(0.60/0.40).  A buyer swaps for puts, and the put price rises to 0.70 collateral. Per put-call parity, the new call price must be 1-0.70 = 0.30 collateral. The sqrtPrice rises to sqrt(0.70/0.30).
{% endhint %}

**One can receive the same amount of call or put tokens when a liquidity range is crossed entirely from above, or below.** This liquidity range has to observe put-call parity:

> Premiums for Calls + Premiums for Puts = Payoff for Calls (Puts)&#x20;

It must be noted that premiums for calls (puts) can serve as *expected returns* for puts (calls) sold in the same liquidity range. If this put-call parity is broken, it generates [triangular arbitrage](https://www.investopedia.com/terms/t/triangulararbitrage.asp) within a pool. So, the pool has to triangulate the transactions as such:

:digit\_one: receives a collateral value of calls (or puts) as options premium

:digit\_two: combines with a collateral value of puts (or calls) and reserves the payout for settlement

:digit\_three: mints call (or put) tokens for the buyer

This triangulation process ensures that, for the same liquidity rang&#x65;**, a long call and a long put can settle each other, regardless of the outcome**.

{% hint style="info" %}
Alice buys a call and Bob buys a put. At settlement, one pockets 1 DAI, retrieving paid premium plus return. And the other loses the premium. If the underlying price settles below the strike price, Alice’s premium ends up with Bob. Otherwise, Bob’s premium goes to Alice.
{% endhint %}

<figure><img src="/files/53KzYyBnsyZjsKvSAgfY" alt=""><figcaption></figcaption></figure>


# Convertible Liquidity

Liquidity providers sell calls and puts within custom price ranges. They can either naked short calls or puts, or sell previously bought calls or puts.

<figure><img src="/files/My9lgoL7nTlZdHUZfR33" alt=""><figcaption><p>How Liquidity Provision Works on Divergence v1</p></figcaption></figure>

In a Divergence v1 pool, liquidity providers can **concentrate** their liquidity within price intervals where they anticipate buying interest. An LP can have many individualized liquidity positions per pool. For each liquidity position, a non-fungible token is minted.&#x20;

The price curve of Divergence v1 is segmented with ticks, using [concentrated liquidity](https://docs.uniswap.org/concepts/protocol/concentrated-liquidity) functions of Uniswap v3. The key difference is that **v1 pools track the relative price between calls and puts**. Calls or puts have a price range of \[0.01, 0.99], and their relative price is between \[0.01/0.99, 0.99/0.01]. Within this price range, LPs can choose lower and upper price bounds when initiating a liquidity position. Both calls and puts can be sold from a position.&#x20;

{% hint style="info" %}
Suppose the current call price is 0.28. Liquidity provider Alice selects a price range of \[0.30, 0.40] to short calls. This implies that her position has a put price range of \[1-0.40, 1-0.30], or \[0.60, 0.70].  The position boundaries are initiated at ticks near a put/call price range of \[0.60/0.40, 0.70/0.30].\
\
After the call price rises to 0.40, Alice's position is fully crossed. The current put price is 1-0.40 = 0.60. If the next trader buys puts, the price will cross back Alice's position. &#x20;
{% endhint %}

LPs earn premiums and transaction fees from selling options. Liquidity is active when the price moves within a range. Premiums are recorded and allocated proportionally to active liquidity, just like [transaction fees](/overview/protocol-basics/fees#swap-fees). Once the price exits a liquidity range, liquidity is deactivated and no longer earns premiums and fees. When [removing liquidity](/user-guide/short-options/finalize-shorts),  LPs finalize their short interest and discontinue option market making. They can collect premiums and fees by either [squaring off their open shorts](/user-guide/short-options/close-shorts), or [settling positions](/user-guide/short-options/expiry-withdrawal) at expiry. Using just one asset as seed collateral, a liquidity position avoids [impermanent loss](https://support.uniswap.org/hc/en-us/articles/20904453751693-What-is-Impermanent-Loss) due to changing asset ratios.

## Impermanent Optionality

A liquidity position can have **unlimited gross shorts in both calls and puts** within its price range. For the same price interval, a short call and a short put settle each other, regardless of the outcome. This enables **auto-risk reduction** for a liquidity position. An LP has seller obligations only for **net shorts in either calls or puts**.  **This short exposure is not permanent until liquidity is removed.**

{% hint style="info" %}
Chad provides liquidity for a single call option. Alice buys a call, fully crossing his position. Then Bob buys a put, undoing Chad's short call exposure. Alice buys another call and Bob buys another put. They trade back and forth until Alice ends up with 1 million calls and Bob has 1 million puts.\
&#x20;\
If the underlying price settles below the strike, Alice’s premium ends up with Bob, who receives 1 million collateral. Otherwise, Bob’s premium goes to Alice, who gets 1 million collateral. Chad has no options exposure. He collects fees for all the trades within his liquidity range.
{% endhint %}

The chosen price bounds enable a position to either **sell more calls than puts** **or** **sell more puts than calls**. When the price exits the range, a position stops selling options, capping the amount of *net* shorts it accumulates. After offsetting call and put sales, **a liquidity position accumulates a predefined amount of&#x20;*****net*****&#x20;shorts in calls or puts**. This ensures that a position’s seed liquidity can pay off the accumulated net shorts, in case they expire profitably. Therefore the maximum loss LPs can expect is **restricted to the seed liquidity amounts**.

{% hint style="info" %}
Suppose Alice buys 1 million calls, and Bob gets 999,999 puts in the above scenario. LP Chad's short exposure maxes out at 1,000,000 - 999,999 = 1 call.&#x20;
{% endhint %}

## Liquidity Types

A liquidity position can be minted using **either collateral or prior-purchased options**. LPs can passively **convert** different types of liquidity to take on or off options risk. It is important to note that a position's options exposure is not final until its [liquidity is removed](/user-guide/short-options/finalize-shorts). &#x20;

* **Liquidity Positions Minted with Collateral**

> - *Similar to limit-sell orders to naked short calls or puts.*&#x20;
> - *An alternative to market buying digital calls or puts, according to* [the put-call parity](/overview/protocol-basics/digital-options#what-is-put-call-parity)
>   * *If one is bullish, shorting a put is an alternative to buying a call.* &#x20;
>   * *If one is bearish, a short call works similarly as a long put.*
> - *If the price crosses back a position, the LP's open shorts in calls or puts are neutralized.*

* **Liquidity positions** **Minted with Either Call or Put Options**&#x20;

> - *Similar to limit-close orders for existing longs.*&#x20;
> - *When a position is seeded with calls (puts), its net shorts in calls (puts) neutralize the long.*
> - *Act like one seeded with collateral when the price crosses back. The premium proceeds are effectively used as liquidity to sell more options, which reverses the close order.*

### Seed Deposit

When a position is minted using collateral, the required seed deposit is **the expected gain for the largest net shorts in calls or puts it can have**.  For a liquidity position intended to sell 1 call (or 1 put) at the price of N collateral (0.01≤ N ≤ 0.99), the required collateral deposit is 1 - N.&#x20;

{% hint style="info" %}
Suppose Chad wants to sell 1 call at the effective price of 0.7 DAI. The required collateral deposit is 1 - 0.7 = 0.3 DAI. For the same liquidity range, 1 put is priced at 0.3 DAI. If he wishes to sell a put, 1-0.3 = 0.7 DAI of seed liquidity is required.
{% endhint %}

When seeding prior-purchased options to close longs, calls or puts must be provided to a liquidity range above the current call (or put) price.&#x20;

### Reserved for Settlement&#x20;

Before expiry, liquidity can be withdrawn to close short exposure, while collaterals must be reserved in the pool as an obligation to cover profitable options upon expiration. These reserved collaterals correspond to the larger short interest, whether on calls or puts. Once collateral is reserved for settlement, any unused liquidity, including both collateral and options, is returned.

$$
C\_{obligation} = Max (Short Interest on Call, Short Interest on Put)
$$

Where the open shorts in options are zero unless the sold amounts are larger than seeded&#x20;

* Short Interest on Call = calls sold - calls seeded
* Short Interest on Put = puts sold - puts seeded

Examples:

{% hint style="info" %}
A liquidity position is minted using 10 calls. It sold 6 calls and 3 puts. \
\
The position has 0 short interest on call, as the calls sold are less than the calls seeded. However, it has 3 short interest on put.  So, the pool reserves 3 collateral and returns 10-6=4 calls, when liquidity is removed. \
\
After settlement, if puts expire worthless, 3 collateral can be withdrawn by the LP. The returned 4 calls can be exercised for 4 collateral in payoff. If the puts expire in the money, the reserved 3 collateral goes to the put holders.
{% endhint %}

{% hint style="info" %}
A liquidity position is minted using 10 collateral. It sold 5 calls and 3 puts. <br>

The position has 5 short interest on call and 3 short interest on put. So, the pool reserves 5 collateral (which would include the collected option premiums) upon liquidity removal. \
\
If the calls expire worthless, the LP can withdraw 2 collateral from the expired net shorts. Otherwise, the full reserved amount is paid to the call holders.&#x20;
{% endhint %}


# Options Specs

<table data-full-width="false"><thead><tr><th width="267.7311071292405">Terms</th><th>Specifications</th></tr></thead><tbody><tr><td><mark style="color:green;"><strong>Underlying</strong></mark></td><td>Prices, rates, and events from a decentralized oracle can be accepted as underlying. In the initial phase the underlying whitelist includes: BTCUSD, ETHUSD</td></tr><tr><td><mark style="color:green;"><strong>Strike Price</strong></mark></td><td>To avoid the “too-many-strikes” problem, inputs are rounded to two significant figures with precision up to 8 decimals. Examples:  1) a five-figure BTC price (27001.50) will round to the fourth figure (27000);  2) a four-figure ETH price (1799.50) will round to the third (1700);  3) a doge price (if supported at 0.071535) will round to (0.071)</td></tr><tr><td><mark style="color:green;"><strong>Trading hours</strong></mark></td><td>24/7</td></tr><tr><td><mark style="color:green;"><strong>Expiry</strong></mark></td><td>The contract supports the creation of pools with settlement at UTC 8:00. Daily, weekly, and monthly expiry selections are offered in the app interface for ease of interaction. Weekly and monthly expiries occur on UTC 8:00 on Fridays. Settlement at alternative times is possible.</td></tr><tr><td><mark style="color:green;"><strong>Collateral</strong></mark> </td><td>Initially, a whitelist of ERC-20 tokens is supported as quote assets for digital options. This whitelist can expand as demanded by the community. Such a whitelist is necessary for this stage to detect any unforeseen issues and concentrate liquidity. It can be removed via admin functions of the smart contract. Collateral tokens of 18 decimals are supported by default. Those with other decimal places, while may be supported, are not recommended for use as collateral due to possible loss of computational precision.<br><br>The initial whitelist includes WETH, USDT, DIVER, and <a href="/pages/x2dGKrQM4KSnkruSinbB">Ditanic test coins</a>.</td></tr><tr><td><mark style="color:green;"><strong>Quotation</strong></mark> </td><td>Options are quoted per unit of collateral, with a minimum price of 0.01 collateral and a maximum of 0.99 collateral.  e.g., An options pool created using USDT will trade options from 0.01 to 0.99 USDT.</td></tr><tr><td><mark style="color:green;"><strong>Settlement</strong></mark> </td><td>Options tokens are exercised at expiry. Depending on the collateral in use, options are cash-settled when a stablecoin is used as collateral or physically settled when an asset token such as WETH is used as collateral. <br><br>A fixed payout of 1 collateral unit is claimable per each in-the-money option. A call (Spear token) is in-the-money when the underlying price settles above or equal to the strike price; otherwise, a put (Shield token) is in-the-money.<br><br>A liquidity position will pay out 1 collateral for each shorted in-the-money option. For each out-of-money option, liquidity providers can reclaim 1 reserved collateral.</td></tr><tr><td><mark style="color:green;"><strong>Settlement Price</strong></mark></td><td>Underlying price feed via heartbeat updates provided by Pyth. For more information, visit <a href="https://docs.pyth.network/price-feeds/use-real-time-data">here</a>.</td></tr><tr><td><mark style="color:green;"><strong>Seed Deposit</strong></mark></td><td>For a liquidity position intended to sell 1 call (or 1 put) at the price of N collateral (0.01≤ N ≤ 0.99), the required collateral deposit is 1 - N. One can also seed 1 call (or 1 put) to a liquidity range above the current call (or put) price, to <a href="/pages/C9NK0DfZjzVh1O7QJbOX">limit close this long exposure</a>.</td></tr><tr><td><mark style="color:green;"><strong>Reserved for Settlement</strong></mark></td><td>Anytime prior to expiry, liquidity can be removed from a position to finalize options exposure. A liquidity position can passively short both calls and puts, and collaterals must be reserved to pay off sold options, in case they expire profitably. The collaterals reserved for settlement equate to the larger short interest, be it on calls or puts; however, a liquidity provider's exposure is only limited to his net shorts in calls or puts, after offsetting call sales and put sales. </td></tr><tr><td><mark style="color:green;"><strong>Position Limit</strong></mark></td><td>None</td></tr><tr><td><mark style="color:green;"><strong>Minimum Size</strong></mark></td><td>None. (Each transaction costs gas, however)</td></tr><tr><td><mark style="color:green;"><strong>Fees</strong></mark></td><td>Pools are set to a default transaction fee of 0.3% per notional. ie, for each option token sold, a flat fee of 0.003 collateral is applicable. An exercise fee of 0.15% is applied when a holder of an in-the-money option claims payoff at settlement. For more information, please refer to <a href="/pages/lGICQlNAAZJm6aG4gPn4">Fees</a>. </td></tr></tbody></table>


# Fees

Divergence v1 introduces highly customizable options pools. Each has its own underlying, collateral, expiry, and strike price. Once options expire, a pool's address cannot be reused to deploy a new pool. It is impractical to enable different fees for each pool, due to the issue of liquidity fragmentation. Therefore, fees are configured based on the underlying asset.&#x20;

It is expected that traders and liquidity providers favor certain fee levels for options with common underlying assets. Option pools with rarer underlying will naturally prefer a higher fee, to counterbalance market-making risks.

### Transaction Fee <a href="#swap-fees" id="swap-fees"></a>

Transaction fees are proportionally divided among active liquidity at the time of a trade. If the option price leaves a position's range, that liquidity no longer earns fees. If the options price reenters the range, the liquidity starts earning fees again. Liquidity providers collect fees separately from the pool.

Pools have a default transaction fee of 0.3% per notional. That means, for each option token sold, a transaction fee of 0.003 collateral units applies. More fee rates of up to 1% may be added in the future per on-chain governance.&#x20;

### Exercise Fee <a href="#swap-fees" id="swap-fees"></a>

After settlement, those options that expire profitably can be exercised for 1 collateral each. An exercise fee of 0.15% applies when option holders claim payoffs. This fee rate does not apply to liquidity providers, who can keep their received premiums from out-of-money options.&#x20;

### Protocol Fee <a href="#swap-fees" id="swap-fees"></a>

The protocol collects 30% of the transaction fee, as well as the exercise fee. The protocol governance has flexibility in changing the fraction of fees that go to the protocol.


# Glossary

## Battle

An option pool of a specific term. It is the core smart contract that interacts with user accounts. Users can call functions within the contract to long options, add and withdraw liquidity, and settle positions.&#x20;

## Collateral

Liquidity providers deposit collateral to ensure they can cover short options positions in the event of option exercises at expiration.&#x20;

## Liquidity Provider

A liquidity provider is someone that sells (goes short on) options. Liquidity providers are compensated with transaction fees and premiums. &#x20;

## Defined Risk Positions

Defined risk positions offer a maximum profit and loss potential, while undefined risk positions can theoretically generate unlimited profit and loss. Digital options, by nature, are defined risk instruments that provide traders and liquidity providers with predetermined returns and risks.

### In Range / Out of Range

If option price is within the price boundaries set by liquidity providers, the position is said to be in range and will earn tx fees and premiums. As the option price rises or falls, it may move outside the price boundaries. When the price goes beyond a position's lower or upper boundary, the position becomes out of range and no longer earns transaction fees or premiums.

### Moneyness

Moneyness refers to the relative position of the current price of an underlying in relation to the strike price of the option. If the option would have positive value if it were to expire today, it is said to be "in the money" (ITM); if it would be worthless if expiring with the underlying at its current price, it is said to be "out of the money" (OTM); and if the current underlying price and strike price are very close, it is said to be "at the money" (ATM).

## Long Position

Refers to options bought by traders with the expectation that they will rise in value.

## Short Position&#x20;

A liquidity provider creates a short position. They must select the lower and upper option sale prices, which represent the boundaries of the position.

## Option Price

The price for digital options quoted in collateral units. At any given time, the call option price and the put option price shall always add up to one collateral unit.&#x20;

### Premium

Premium refers to the price paid by traders to liquidity providers for a digital call option or digital put option. It is the income received by liquidity providers for selling these options.

## Option Tokens

Spears and Shields are tokenized digital call options and digital put options. They're minted as fungible tokens by the smart contract.&#x20;

### Spear

A European-style digital call option, with the right to receive one collateral when the settlement price of the underlying exceeds the strike price, otherwise, it expires worthless.

### Shield

A European-style digital put option, with the right to receive one collateral when the price of the underlying asset settles below the strike price, otherwise, it expires worthless.

## Open Interest

The total number of options positions that are opened and have not been exercised.&#x20;

## Oracle

A third-party service or software that collects and updates the underlying asset prices used for settling options. The oracle receives asset prices during specified time slots and supplies them to smart contracts that use them to determine the settlement price of options.

## Virtual Curve

A bonding curve that determines the price of options and facilitates the sale of those options.

### Tick

The boundaries between discrete areas in price space. Ticks are spaced such that an increase or decrease of 1 tick represents a % increase or decrease in the option price. &#x20;

### Range&#x20;

Any interval between two price ticks of any distance.&#x20;

## Sales Volume

The gross number of call options and put options that a short position has sold. &#x20;

## (Net) Short Exposure

The net short status of an LP's open short position, after offsetting calls and puts that are sold.&#x20;

## Settlement Value

After expiration, the option seller (liquidity provider) will be assigned the obligation to payout one collateral unit for each option token he sold that expires in the money.&#x20;


# References

Digital options are not a novel concept. They have been thoroughly explored in decades of studies on financial derivatives. Here are a few insightful ones:

## [Unscrambling the binary code](https://www.academia.edu/16585778/Unscrambling_the_binary_code) <a href="#swp-tcr--title" id="swp-tcr--title"></a>

Mark Rubinstein, Eric Reiner, 1991, Risk Magazine

> The pay-offs of binary options tend to be switched completely one way or the other depending on whether the underlying asset price satisfies some condition. This article considers a wide variety of binaries, first those with path-independent pay-off s and then the more complex barrier binaries with path-dependent pay-offs.

## [An introduction to quantitative finance](https://global.oup.com/academic/product/an-introduction-to-quantitative-finance-9780199666591?cc=us\&lang=en&)

Stephen Blyth, 2013, Oxford University Press

{% embed url="<https://www.youtube.com/watch?v=eG_aRPy1KVE>" %}

## [Dynamic Hedging: Managing Vanilla and Exotic Options](https://www.wiley.com/en-us/Dynamic+Hedging%3A+Managing+Vanilla+and+Exotic+Options-p-9780471152804)

Nassim Nicholas Taleb, 1997, John Wiley & Sons

> Binary options are perhaps the best training ground for a trader as they can teach more about advanced book management. At the heart of most exotic structure and every bet resides a binary.

## Other relevant books for reference:

#### **Options, Futures, and Other Derivatives** by John Hull

*The textbook.*

**Option Volatility & Pricing: Advanced Trading Strategies and Techniques** by Sheldon Natenberg

*Written by a trader for traders. A clear and easy-to-understand overview of key concepts without excessive focus on moon math.*&#x20;

**Volatility Trading** by Euan Sinclair

*A fine book that delves into the various nuances of options trading, with extensive discussions on quantitative models for measuring volatility.*

**The Complete Guide to Option Pricing Formulas** by Espen Gaarder Haug

*A great reference for options pricing formulas that comes along with ready-to-use spreadsheets.*

{% hint style="info" %}
*Divergence is not affiliated with any of these authors, and does not bear responsibility for any error, omission, or defect that may be included in such content. Not financial advice.*
{% endhint %}


# 📈Long Options

Select a collateral, swap for Spear tokens as calls, or Shield tokens as puts, and chill 😎

{% hint style="success" %}
If you are new to the Divergence Protocol, it is advised to start with the [protocol basics](/overview/protocol-basics).
{% endhint %}

Longing digital options is akin to market buying options in a traditional order book. Instead of matching with specific orders one after another, the swaps execute against a passive pool of liquidity. Liquidity providers earn fees proportional to their committed capital. **The protocol's swap functionalities are long-only. Collateral tokens are swapped for options tokens, not the reverse.**&#x20;

Before expiry, traders can [close their longs](/user-guide/long-options/close-longs) by providing the options they've bought as liquidity to a price range, similar to limit sell orders in a order book. Alternatively, to hedge a number of long calls (puts), one can buy the same amount of puts (calls), or provide collateral liquidity to [open shorts](/user-guide/short-options/open-shorts).&#x20;

After expiry, if the options are in-the-money, they can be [exercised](/user-guide/long-options/exercise-options) for 1 collateral token each. The following provide step-by-step guides about using the protocol interface to complete the above steps:

<img src="/files/GqXN6gVfvFPfTkN53AGO" alt="" class="gitbook-drawing">


# 🔥Open Longs

### 🦍Market Buy

<figure><img src="/files/yFGrbf35B49DCNyDZxrs" alt=""><figcaption></figcaption></figure>

Select the desired parameters - underlying, collateral, expiration and browse available strikes.

1. Switch the "BUY/SELL" status to "BUY".&#x20;
2. Select "CALL"📈 or "PUT"📉 to go long.&#x20;
3. Enter the amount of collateral you'll spend to long options.&#x20;
4. Complete the trade!&#x20;

### 👀View Long Positions

Your long positions will be visible in "Positions". &#x20;

<figure><img src="/files/GTAJKiGsiymPL8IuQ7pd" alt=""><figcaption></figcaption></figure>

You may choose to either [exercise](/user-guide/short-options/expiry-withdrawal#exercise-option-positions) your option holdings at expiry if it expires in-the-money🤑; or [close your long positions](/user-guide/long-options/close-longs) earlier by providing the options as liquidity to sell.&#x20;


# 🌊Close Longs

To close or hedge your longs in either spears or shields, you can either:&#x20;

<table data-full-width="false"><thead><tr><th width="373">Sell Passively at Custom Prices</th><th>Buy Actively for Immediate Execution</th></tr></thead><tbody><tr><td><ul><li>Use prior-purchased options as liquidity to sell options; Or supply collateral as liquidity to open off-setting shorts.</li><li>Remove liquidity to finalize positions.</li><li>If supplying collateral liquidity, use your options tokens to <a href="/pages/3TSgwXLj8mZXpN3vVxyj">redeem collateral before expiry</a>. Or <a href="/pages/i9JLdwX6bnoM0gazBCSF">claim back reserves after expiry</a> after settlement. </li></ul></td><td><ul><li>Long the same amount of Shields (puts) to hedge your long Spears (calls). </li><li>Long the same amount of Spears (calls) to hedge your long Shields (puts). </li><li>See digital option <a href="/pages/V3otewC7NPlPpWaO4aBf#what-is-put-call-parity">put-call parity</a>. </li></ul></td></tr></tbody></table>

The following provides a tutorial for the first option:&#x20;

### ➕Provide Sell Liquidity with Prior-Purchased Options

<figure><img src="/files/8uD0I2Ylp4pWrfq1eO1a" alt=""><figcaption></figcaption></figure>

1. Go to Dashboard - Positions, and click the "Earn" button on the right.&#x20;
2. Select the price ranges at which you would like to provide liquidity and sell your options.&#x20;
3. Enter the number of options you wish to sell.&#x20;
4. Complete the transaction.

### 👁‍🗨View Open Orders

Once you have provided sell liquidity using prior-purchased options, you can see it in your "Dashboard-Open Orders" section. You can also view the details of your position, including the number of longs in calls (puts) you have closed, by clicking on the position.&#x20;

<figure><img src="/files/gO9VMIZ3JnWYOtkbvbcz" alt=""><figcaption></figcaption></figure>

The following key details of your open order will be available for you:&#x20;

* **Status:** the number of longs you have closed and additional shorts you have opened (if any) .
* **Deposit:** The number of calls (puts) you deposited to sell.
* **Fees:** Total amount of transaction fees you have earned.
* **Premium:** The amount of proceeds you received for selling the options.
* **Sales Volume:** The gross number of calls and puts you have sold.&#x20;
* **Withdrawable:** the amount of collaterals withdrawable upon liquidity removal. &#x20;

***Note: Your long closure is not final until you remove liquidity.** You must monitor your position and remove liquidity promptly once your seeded calls (puts) are sold out. Otherwise, if later the price traces back, your premiums would be used as liquidity (collaterals) to short additional puts (calls), which in turn neutralizes your long closure.*&#x20;


# 👨‍🌾Exercise Options

At expiration, option pools can be settled according to price feeds provided by oracles. Traders can exercise their held-to-maturity options and claim the payout individually, if any.&#x20;

### 💰Exercise Option Positions

If your outstanding longs expire in-the-money🤑, you'll be able to receive one collateral unit per option token from the options pool. Otherwise, your longs expire worthless💀.&#x20;

<figure><img src="/files/XOjSvRgHvRIcmsEDCQk9" alt=""><figcaption></figcaption></figure>


# 📉Short Options

Liquidity providers are options sellers. They passively sell calls or puts at custom prices. In a pool, multiple liquidity positions can be minted, each as an NFT.

{% hint style="success" %}
If you are new to the Divergence Protocol, it is advised to start with the [protocol basics](/overview/protocol-basics).
{% endhint %}

In fact, a liquidity provider is a fee-earning passive trader, according to [the put-call parity](/overview/protocol-basics/digital-options#what-is-put-call-parity). If one is bullish, an alternative to buying a call is to short a put. Conversely, when one is bearish, a short call works similarly to a long put.&#x20;

Unlike a traditional limit short order, a liquidity position on Divergence v1 is minted for the purpose of facilitating swaps. The pool contract is not able to stop a position from being crossed until its liquidity provider signs a transaction to [remove liquidity](/user-guide/short-options/finalize-shorts). **As the price moves back and forth in its price range, a short position can sell both calls and puts.**&#x20;

{% hint style="info" %}
A liquidity position is intended to sell calls between \[0.30, 0.80]. Once the current price enters its range, it can also sell puts between \[1 - 0.80, 1 - 0.30], or \[0.20, 0.70].&#x20;
{% endhint %}

An option pool's open interests are settled in this logical order:

:digit\_one:A long call and a long put settle each other, regardless of the outcome.

:digit\_two:Any remaining longs in calls or puts in the pool are then squared with the LPs.

**LP's exposure equals the position's net shorts in either calls or puts**. The seed liquidity amount and the selected price range determine whether the LP will sell more calls than puts (short on call) or vice versa (short on put), and the maximum net amount of options a position can short.

When removing liquidity, the smart contracts compute a finalized amount of net shorts in calls or puts owed to a position. After reserving collateral for settlement, unused liquidity is returned.&#x20;

An LP can [close a position](/user-guide/short-options/close-shorts) before expiry, by burning the amount of options net shorted. If not already owned, these options tokens can be market [bought](/user-guide/long-options/open-longs), the same as how [short covering](https://www.investopedia.com/terms/s/shortcovering.asp) typically works.&#x20;

{% hint style="info" %}
Suppose a liquidity position is minted with collateral. After removing liquidity, it sells 3 calls and 5 puts. The LP is said to have net shorted 5-3=2 puts.  Its LP needs to send 2 shield tokens (as puts) to the contract to redeem 2 collateral. <br>

The position's PNL = 2 \* ( effective price for open shorts - buyback price)
{% endhint %}

After the expiry, anyone can call the contract to settle the options. If the calls (or puts) settle out of money, their open shorts become profitable. One collateral can be withdrawn for each.

{% hint style="info" %}
A position sells 3 calls and 5 puts at expiry. The LP is said to have net shorted 5-3=2 puts. If puts expire out-of-money, its LP can settle the position and withdraw 2 collateral. If the puts expire profitably, however, the collateral reserved for settlement goes to the put holders. No collateral can be withdrawn by the LP.
{% endhint %}

The following provide step-by-step guides about using the protocol interface to:

<img src="/files/ZF9BNC77XQaAnyntECXr" alt="" class="gitbook-drawing">


# 💧Open Shorts

To open a naked short position on either calls (spear tokens) or puts (shield tokens), liquidity providers must deposit collaterals to the option pool. Later, the deposited collaterals will be utilized and reserved for settlement when option tokens are sold to traders. Liquidity positions can sell both calls and puts while liquidity is active. As premiums from selling a call can settle a put, and vice versa, an LP's short exposure is only limited to **net shorts in either calls or puts**:&#x20;

<table><thead><tr><th width="380">Short Calls</th><th>Short Puts</th></tr></thead><tbody><tr><td><ul><li><em>Select a price range for <strong>calls</strong>.</em></li><li><em>The lower price bound has to be higher than the current price of <strong>calls</strong>.</em></li><li><em>This position <strong>sells more calls than puts</strong></em></li><li>Exposure is limited to <strong>net shorts in calls</strong></li></ul></td><td><ul><li><em>Selects a price range for <strong>puts</strong></em></li><li><em>The lower price bound has to be higher than the current price of <strong>puts</strong>.</em> </li><li><em>This position <strong>sells more puts than calls</strong></em></li><li>Exposure is limited to <strong>net shorts in puts</strong></li></ul></td></tr></tbody></table>

### ➕ Provide Sell Liquidity with Collaterals

<figure><img src="/files/CucgptQKFSuvKfmqc6kY" alt=""><figcaption></figcaption></figure>

Specify your desired option terms - underlying, collateral, expiration and browse available strikes.&#x20;

1. Switch the "BUY/SELL" status to "SELL".&#x20;
2. Select "CALL"📈 or "PUT"📉 to go short.&#x20;
3. If you didn't find pools with desired strikes, you can create a new option pool below. &#x20;
4. Select the price ranges at which you would like to short options.&#x20;
5. Enter the amount of collaterals you wish to deposit to the naked short position.
6. Complete the transaction.

###

### 👁‍🗨View Open Orders

Once you have provided sell liquidity using collaterals, you will see it in your "Dashboard-Open Orders" section. You can also view the details of your order, including the number of options you have sold.

<figure><img src="/files/VtEkUB5gxYlshpixr76O" alt=""><figcaption></figcaption></figure>

The following key details of your open order will be available for you:&#x20;

* **Status:** The short status after netting calls and puts that are sold. Learn [here](/overview/protocol-basics/digital-options#what-is-put-call-parity).&#x20;
* **Deposit:** The amount of collaterals initially committed to the position.&#x20;
* **Fees:** Total amount of transaction fees you have earned.
* **Premium:** The amount of proceeds you received for selling the options.
* **Sales Volume:** The gross number of calls and puts you have sold.&#x20;
* **Withdrawable:** the amount of collaterals withdrawable upon liquidity removal.&#x20;


# 🔚Finalize Shorts

Liquidity providers can remove liquidity prior to expiry to finalize their short exposure. When removing liquidity, the smart contracts compute a finalized amount of net shorts in calls or puts owed to a position. After reserving collateral for settlement, unused collaterals are returned.&#x20;

### ➖Finalize Short Exposure

<figure><img src="/files/fFZ0gBNkGGOXbNj5fZ3j" alt=""><figcaption></figcaption></figure>

By clicking "withdraw", your order will finalize, and you will then receive the collaterals not reserved for settlement, details as follows:&#x20;

$$
YouCanReceive=Deposit + Premium + Fees - Reserved for Settlement
$$

* **Deposit:** The amount of collaterals initially committed to the position, if any.&#x20;
* **Fees:** The transaction fees you have accumulated.&#x20;
* **Premium:** The premiums for your outstanding short positions.
* **Reserved for Settlement:** Collaterals [reserved](/overview/protocol-basics/convertible-liquidity#reserved-for-settlement) for sold options, in case expire profitably.

Following liquidity removal, your finalized short exposure will be visible under "dashboard-position." Here, you can view the value of the short position.&#x20;

<figure><img src="/files/u35TD3N9pmO2ZZCMXBiq" alt=""><figcaption></figcaption></figure>

**Note:** Besides, If sell liquidity is seeded with prior-purchased options, **any options holdings that remain unsold at the time of withdrawal will also be returned.** You can hold till expiry or choose to sell again.&#x20;


# 📥Close Shorts

Upon removing liquidity, a liquidity position's exposure to options is locked in. Subsequently, users have the choice to either wait until expiry to [withdraw](/user-guide/short-options/expiry-withdrawal) collaterals reserved for settlement—assuming the sold options expire worthless—or to immediately close by burning the corresponding quantity of option tokens that were shorted.&#x20;

### ➖ Close Shorts

By burning an equivalent number of options they have shorted, users can directly close their short positions without having to wait until expiry. If not already owned, options tokens can be market [bought](/user-guide/long-options/open-longs), the same as how [short covering](https://www.investopedia.com/terms/s/shortcovering.asp) typically works.&#x20;

<figure><img src="/files/jZTGdajGXKS8dkx29QiT" alt=""><figcaption></figcaption></figure>

Closing the short position will release an equivalent amount of collaterals as that of the options burnt. Additionally, the [position's profit and loss (PNL) ](/user-guide/short-options)can be determined by calculating the difference between the premiums received from selling the options and the cost incurred from buying them back.


# ⏰Expiry Withdrawal

Following the expiration date, option pools can be settled by anyone through the oracle contract. If the calls (or puts) sold settle out of the money, your position turns profitable; otherwise, it incurs a loss.

### 💸Settle Short Position

Navigate to 'Dashboard-Position' to locate your short position. If the shorts expire out-of-the-money, you are in profit and one collateral can be withdrawn for each option token shorted. If not, you'll incur a loss, and your position will expire worthless.

### 💸Settle Liquidity Position

Navigate to 'Dashboard-Open Order' to locate your unfinalized liquidity position. The amount of collaterals you can claim from this position is determined by the following factors:

$$
YouCanReceive = Collateral Deposit + Fees + Premium - Settlement Value
$$

* **Deposit:** The amount of collaterals initially committed to the position, if any.
* **Fees:** Total amount of transaction fees you have earned.
* **Premium:** The amount of proceeds you received for selling the options.
* **Settlement Value:** Collateral payout to holders of options that expire profitably.

***Note: If the position is seeded with prior-purchased options,*****&#x20;any options holdings that remain unsold at the time of settlement will also be returned.** You will need to [exercise](/user-guide/long-options/exercise-options) them yourself.&#x20;


# 🍸Dive Bar

Experimental prediction markets for those who would like to take a stand.

{% hint style="info" %}
The Dive Bar uses the protocol's [smart contract architecture](/technical-reference/smart-contract-architecture), with custom oracle contracts retrieving off-chain data feeds. These markets are introduced as pilots, and are created for those brave enough for a dive. With sufficient community interest,  and the support of third-party oracle networks, they can be integrated as staples of options offerings. Interested community members can [request](mailto:contact@divergence-protocol.com) new prediction markets to be added to the Dive Bar. &#x20;
{% endhint %}

<figure><img src="/files/QJ8dCbdt7uLintadMqjH" alt=""><figcaption></figcaption></figure>

The prediction markets primarily adhere to the [options specs](/overview/protocol-basics/options-specs), with a few distinctions:

* The markets trade on the outcomes of unknown future events. They can also be configured to trade on prices of assets, including those that are not yet publicly offered.
* Each market uses one ERC20 collateral token to long and short <mark style="color:green;">YES</mark> or <mark style="color:red;">NO</mark> event outcomes
* <img src="/files/KICz5vyFPAdeSYRkSpjw" alt="" data-size="line">Spear tokens settles profitably when the event outcome is  '<mark style="color:green;">YES</mark>'.
* <img src="/files/EeXCAlrfMMmuGv4ObKLb" alt="" data-size="line">Shield tokens settles profitably when the event outcome is '<mark style="color:red;">NO</mark>'.
* The interface is designed with some similarity to orderbooks, with each liquidity position (aka sell orders) set to a minimum interval of 30 ticks.
* As is the case with [shorting options](/user-guide/short-options),  liquidity positions must be finalized under "Open Orders", before the shorts in <mark style="color:green;">YES</mark> or <mark style="color:red;">NO</mark>  can be [closed](/user-guide/short-options/close-shorts).  To close shorts, simply click "Close", approve and confirm sending the pool the prompted amount of <mark style="color:green;">YES</mark> or <mark style="color:red;">NO</mark> from holdings, and receive the reserved collateral. Note that the open shorts can only be closed in full. &#x20;

<figure><img src="/files/PjaiwYLa96TEWZE5AwMA" alt=""><figcaption><p>After finalizing a liquidity position under "Open Orders", go to "Positions" to close it. </p></figcaption></figure>

* Markets expire at custom timestamps specified as a pool's `BattleKey`. An hour after settlement,  winning long <mark style="color:green;">YES</mark> or <mark style="color:red;">NO</mark> positions can exercise for profit.  Liquidity providers who have opened shorts in losing  <mark style="color:green;">YES</mark> or <mark style="color:red;">NO</mark> positions can reclaim reserved collateral, keeping the premiums as profit.
* To [close longs](/user-guide/long-options/close-longs) in <mark style="color:green;">YES</mark> or <mark style="color:red;">NO</mark>,  click "Earn", select a limit price to sell your holdings and confirm adding liquidity. Don't forget to finalize these in "Open Orders" to withdraw your sale proceeds! &#x20;
* Alternative [fee](/overview/protocol-basics/fees) structures for the markets can be enabled.
* Last but not least, **these markets enable everyone to voice their opinions**. Click on the "Yes" or "No" button and share your views on X 🤿\_🤿

<figure><img src="/files/AzjNAHSowfJRuENKsN7a" alt=""><figcaption><p>You've got it. Just say it.</p></figcaption></figure>


# Smart Contract Architecture

The Divergence smart contracts system includes core contracts and periphery contracts. Below are a brief overview of the contract functionalities:

***

### Core

The core contract functionalities provide the foundation for options market creation, automatic market-making and peer-to-pool interactions.

#### [Arena](/technical-reference/core/arena)

Deploys pools, i.e. Battles, for options tokens of specific underlying, collateral, fees and other deployment parameters.

#### [Battle](/technical-reference/core/battle)

Each options AMM pool is contained in a Battle contract. Battle contracts contain the core functionalities including minting and burning liquidity, trading options tokens, settling pools and claiming proceeds. The onlyManager functions are called via the Manager contract in the Periphery contracts.

#### [Oracle](/technical-reference/core/oracle)

Collects and updates underlying asset prices used for settling options. It retrieves asset prices and supplies them to all contracts that use them.

#### [sToken](/technical-reference/core/stoken)

Implements digital call and put options as Spear and Shield tokens.

***

### Periphery

Periphery contracts contain methods of interacting with core contracts. Periphery interfaces are the main handler of external calls.

#### [Manager](/technical-reference/periphery/manager)

Mints LP liquidity positions as non-fungible tokens. Handles the logic of adding and withdrawing liquidity. Provides functionalities that enable LPs to redeem or withdraw obligatory collateral reserves for settlement. It also facilitates trade functionalities.


# Deployment addresses

For our v1 deployment on Arbitrum One:

BattleImpl: 0xB9A1B8dF279E20Ff7dC7A32EE15d3eF2d5E45F62 &#x20;

OracleCustom: 0x1aBAE7617f6Ae462412788E5031dA3646F188607&#x20;

Oracle: 0x07C8C1e84C3814bfE2870Dfed24635Ef715aCB7c&#x20;

Arena: 0xA0D812cAe2376b90951192319477eF5Fe3Ac56D5&#x20;

Manager: 0x55A14661d94C2cE307Ab918bb9564545282C2454&#x20;

Quoter: 0x2791386ecE62d8Ec3D3b223871be192c6BD5D5D5


# Core


# Arena

Deploys battles, aka options pools. Sets pool underlying, collateral, fees, expiries and other deployment parameters.

## setFeeForUnderlying

Assigns a fee ratio to pools created for a specific underlying asset. Can only be set by the owner.

```javascript
function setFeeForUnderlying(string calldata underlying, Fee calldata _fee) external override onlyOwner
```

**Params:**

| **Name**   | **Type** | **Description**                                   |
| ---------- | -------- | ------------------------------------------------- |
| underlying | string   | The symbol of underlying asset                    |
| \_fee      | Fee      | The fee ratio for pools with the underlying asset |

## setCollateralWhitelist

Sets the whitelist status for a collateral token. Can only be set by the owner. This function will no longer be in use when the permissionless mode is enabled. Collateral tokens of 18 decimals are supported by default. Those with other decimal places are not recommended for use as collateral due to possible loss of computational precision.

```javascript
function setCollateralWhitelist(address collateral, bool isSupported) external override onlyOwner
```

**Params:**

| **Name**    | **Type** | **Description**                              |
| ----------- | -------- | -------------------------------------------- |
| collateral  | address  | The address of the collateral token          |
| isSupported | bool     | The whitelist status of the collateral token |

## setUnderlyingWhitelist

Sets the whitelist status and fee for an underlying asset.

```javascript
function setUnderlyingWhitelist(string memory underlying, bool isSupported, Fee calldata fee) external override onlyOwner 
```

**Params:**

| **Name**    | **Type** | **Description**                              |
| ----------- | -------- | -------------------------------------------- |
| underlying  | string   | The symbol or name of the underlying asset   |
| isSupported | bool     | The whitelist status of the underlying asset |
| fee         | Fee      | The fee structure for the underlying asset   |

## setPermissionless

Toggles the permissionless mode of the contract. Permissionless mode is disabled initially, when the contracts begin in production. Only whitelisted collateral tokens can be used in battles. Once the permissionless mode is enabled, battles can be created with any ERC-20 token without the need for a whitelist.

```javascript
function setPermissionless() external override onlyOwner
```

## setManager

Sets the manager address

```javascript
function setManager(address _manager) external override onlyOwner
```

## setOracle

Sets the oracle address

```javascript
function setOracle(address _oracle) external override onlyOwner
```

## createBattle

Creates a new battle, aka an options pool, using the specified parameters. A battle is used for one expiry only. Once options expire, a new battle can be created to extend the expiration cycle.

```javascript
function createBattle(BattleKey memory bk) external override returns (address battle);
```

**Params:**

| **Name** | **Type**  | **Description**                                                                                                                    |
| -------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| bk       | BattleKey | The key containing parameters for a battle, such as the collateral token, underlying asset, expiration timestamp, and strike value |

**Returns:**

| **Name** | **Type** | **Description**             |
| -------- | -------- | --------------------------- |
| battle   | address  | The battle contract address |

## getBattle

Gets the battle address for a given battle key

```javascript
function getBattle(BattleKey memory battleKey) external view override returns (address battle);
```

**Params:**

| **Name**  | **Description**                                                                                                                                                                                                                 |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BattleKey | The key containing parameters for a battle, such as the collateral token, underlying asset, expiration timestamp, and strike value. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#BattleKey) |

**Returns:**

| **Name** | **Type** | **Description**             |
| -------- | -------- | --------------------------- |
| battle   | address  | The battle contract address |

## getAllBattles

Fetches information about all battles

```javascript
function getAllBattles() external view override returns (BattleInfo[] memory);
```

**Returns:**

| **Name**   | **Type** | **Description**                                                                                                                                                                          |
| ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BattleInfo | memory   | Information about all battles, each including the battle address, battle key, sqrtPrice, start and expiry timestamps, Spear and Shield token addresses and balances, and battle outcome. |


# Battle

Each options pool is contained in a Battle contract. Battle contracts provide core functionalities including minting and burning liquidity, trading options tokens, settling and exercising options, and

## init

Inits state variable in storage. It is called only once for a battle.

```javascript
function init(DeploymentParams memory params) external override
```

**Params:**

| **Name**         | **Description**                                                                                                                          |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| DeploymentParams | The parameters for deploying a pool. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#DeploymentParams) |

## \_updatePosition

Updates a position and flips its upper tick and/or lower tick from initialized to uninitialized, or vice versa.

```javascript
function _updatePosition(UpdatePositionParams memory params) internal returns (PositionInfo storage position)
```

**Params:**

| **Name**             | **Description**                                                                                                                               |
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------- |
| UpdatePositionParams | Parameters for updating the position. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#UpdatePositionParams) |

**Returns:**

| **Name**     | **Description**                                                                                                                       |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| PositionInfo | The info struct of the given position. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#PositionInfo) |

### checkTicks

Checks whether the given lower tick and upper tick are within the minimum and maximum tick bounds. Also checks whether the lower tick is less than the upper tick.

```javascript
function checkTicks(int24 tickLower, int24 tickUpper) private pure
```

**Params:**

| **Name**  | **Type** | **Description**                         |
| --------- | -------- | --------------------------------------- |
| tickLower | int24    | The lower tick boundary of the position |
| tickUpper | int24    | The upper tick boundary of the position |

## \_modifyPosition

Helper for computing liquidity delta amounts to the curve when liquidity for a position is modified

```javascript
function _modifyPosition(ModifyPositionParams memory params) internal returns (PositionInfo storage position)
```

**Params:**

| **Name**             | **Description**                                                                                                                                |
| -------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| ModifyPositionParams | Parameters for modifying the position. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#ModifyPositionParams) |

**Returns:**

| **Name**     | **Description**                                                                                                                       |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| PositionInfo | The info struct of the given position. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#PositionInfo) |

## mint

Create a liquidity NFT for the given parameters. Only called by the non-fungible position Manager.

```javascript
function mint(BattleMintParams memory params) external override lock onlyManager
```

**Params:**

| **Name**         | **Description**                                                                                                                             |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| BattleMintParams | Parameters for minting a liquidity NFT. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#BattleMintParams) |

**Returns:**

| **Name**     | **Description**                                                                                                                       |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| PositionInfo | The info struct of the given position. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#PositionInfo) |
| seed         | uint256                                                                                                                               |

## burn

Burns a liquidity NFT according to the given parameters. Only called by the non-fungible position manager.

```javascript
function burn(BattleBurnParams memory params) external override lock onlyManager
```

**Params:**

| **Name**         | **Description**                                                                                                                             |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| BattleBurnParams | Parameters for burning a liquidity NFT. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#BattleBurnParams) |

## collect

Collects the specified amounts of collateral, Spear, and Shield tokens. Transfers them to the recipient. Only called by the non-fungible position manager.

```javascript
function collect(address recipient, uint256 cAmount, uint256 spAmount, uint256 shAmount) external override onlyManager
```

**Params:**

| **Name**  | **Type** | **Description**                              |
| --------- | -------- | -------------------------------------------- |
| recipient | address  | Address of the recipient                     |
| cAmount   | uint256  | Amount of collateral tokens to transfer      |
| spAmount  | uint256  | Amount of Spear tokens to mint and transfer  |
| shAmount  | uint256  | Amount of Shield tokens to mint and transfer |

## trade

Executes a trade by swapping collateral to either Spear or Shield tokens. When the price direction is up (down), an amount of Shield (Spear) token output is sent to the buyer.

```javascript
function trade(BattleTradeParams memory params) external returns (uint256 cAmount, uint256 sAmount, uint256 fAmount)
```

**Params:**

| **Name**          | **Description**                                                                                                                        |
| ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| BattleTradeParams | Parameters for executing a trade. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#BattleTradeParams) |

**Returns:**

| **Name** | **Type** | **Description**                                                     |
| -------- | -------- | ------------------------------------------------------------------- |
| cAmount  | uint256  | Amount of collateral token input spent to be spent for the trade    |
| sAmount  | uint256  | Amount of Spear or Shield token output to be received for the trade |
| fAmount  | uint256  | Amount of fee in collateral token to be spent for the trade         |

## settle

Settles options of a pool after their expiry. It updates the battle outcome based on the underlying price retrieved from an external oracle.

```javascript
function settle() external override
```

## exercise

This function allows a participant to exercise their winning long Spear or long Shield position. Each winning Spear or Shield pays 1 collateral. This payoff is claimed after paying an `exerciseFeeAmount`. eg. Alice bought 100 spear. The battle outcome turns out to be `spear_win`. By calling this function, she claims 100 collateral tokens less `exerciseFeeAmount`.

```javascript
function exercise() external override lock
```

## withdrawObligation

Enables the liquidity provider to withdraw the collateral amount reserved for settlement. Only called by the Manager.

```javascript
function withdrawObligation(address recipient, uint256 amount) external override onlyManager lock
```

**Params:**

| **Name**  | **Type** | **Description**                                      |
| --------- | -------- | ---------------------------------------------------- |
| recipient | address  | The liquidity provider address to receive collateral |
| amount    | uint256  | The amount of collateral to be received              |

## collectProtocolFee

Collect the protocol fee accrued to the pool. Can only be called by the owner.

```javascript
function collectProtocolFee(address recipient) external override lock
```

## collateralBalance

This is a private view function that returns the current balance of collateral tokens held by the contract

```javascript
function collateralBalance() private view returns (uint256) 
```

**Returns:**

| **Type** | **Description**                      |
| -------- | ------------------------------------ |
| uint256  | Current balance of collateral tokens |

## positions

Retrieves information about a specific position based on its position key

```javascript
function positions(bytes32 positionKeyB32) external view override returns (PositionInfo memory info)
```

**Params:**

| **Name**       | **Type** | **Description** |
| -------------- | -------- | --------------- |
| positionKeyB32 | bytes32  | Position key    |

**Returns:**

| **Name**     | **Description**                                                                                                                       |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| PositionInfo | The info struct of the given position. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#PositionInfo) |

## battleKey

Returns the battle key, which contains information about the battle configuration.

```javascript
function battleKey() external view override returns (BattleKey memory)
```

**Returns:**

| **Name**  | **Description**                                                                                                                                                                                                                 |
| --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BattleKey | The key containing parameters for a battle, such as the collateral token, underlying asset, expiration timestamp, and strike value. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#BattleKey) |

## startAndEndTS

Returns the start and expiry timestamps of the battle

```javascript
function startAndEndTS() external view override returns (uint256, uint256)
```

**Returns:**

| **Type** | **Description**                |
| -------- | ------------------------------ |
| uint256  | Start timestamp of the battle  |
| uint256  | Expiry timestamp of the battle |

## spearBalanceOf

Returns the amount of Spear tokens held by an account

```javascript
function spearBalanceOf(address account) external view override returns (uint256 amount)
```

**Returns:**

| **Name** | **Type** | **Description**                            |
| -------- | -------- | ------------------------------------------ |
| amount   | uint256  | Amount of Spear tokens held by the account |

## shieldBalanceOf

Returns the amount of shield tokens held by an account

```javascript
function shieldBalanceOf(address account) external view override returns (uint256 amount)
```

**Returns:**

| **Name** | **Type** | **Description**                             |
| -------- | -------- | ------------------------------------------- |
| amount   | uint256  | Amount of shield tokens held by the account |

## spearAndShield

This function returns the addresses of the Spear and Shield tokens

```javascript
function spearAndShield() external view override returns (address, address)
```

**Returns:**

| **Name** | **Type** | **Description**             |
| -------- | -------- | --------------------------- |
| spear    | address  | Address of the Spear token  |
| shield   | address  | Address of the Shield token |

## getInsideLast

This function returns the growth variables for the specified tick range.

```javascript
function getInsideLast(int24 tickLower, int24 tickUpper) external view override returns (GrowthX128 memory)
```

**Params:**

| **Name**  | **Type** | **Description**                      |
| --------- | -------- | ------------------------------------ |
| tickLower | int24    | The lower tick boundary of the range |
| tickUpper | int24    | The upper tick boundary of the range |

**Returns:**

| **Name**   | **Description**                                                                                                                    |
| ---------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| GrowthX128 | Growth variables for the tick range. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#GrowthX128). |


# Oracle

Retrieves underlying asset prices used for settling options.

### setExternalOracle

Defines the underlying asset symbol and oracle address for a pool. Only called by the owner.

```javascript
function setExternalOracle(string[] calldata symbols, address[] calldata oracles_) external onlyOwner 
```

**Params:**

| **Name**  | **Type** | **Description**                                   |
| --------- | -------- | ------------------------------------------------- |
| symbols   | string   | The asset symbol for which to retrieve price feed |
| oracles\_ | address  | The external oracle address                       |

### setFixPrice

Sets the price for an asset.

```javascript
function setFixPrice(string memory symbol, uint256 ts, uint256 price) external onlyOwner 
```

**Params:**

| **Name** | **Type**                                                        | **Description**                               |
| -------- | --------------------------------------------------------------- | --------------------------------------------- |
| symbol   | string The symbol of the asset for which the price is being set |                                               |
| ts       | uint256                                                         | The timestamp associated with the asset price |
| price    | uint256                                                         | The retrieved price of the asset              |

### getPriceByExternal

Gets and computes price from external oracles

```javascript
function getPriceByExternal(address cOracleAddr, uint256 ts) external view returns (uint256 price, uint256 actualTs)
```

**Params:**

| **Name**    | **Type** | **Description**                                 |
| ----------- | -------- | ----------------------------------------------- |
| cOracleAddr | address  | The contract address for a chainlink price feed |
| ts          | uint256  | Timestamp for the asset price                   |

**Returns:**

| **Name** | **Type** | **Description**                                           |
| -------- | -------- | --------------------------------------------------------- |
| price    | uint256  | The retrieved price                                       |
| actualTs | uint256  | The timestamp at which the price is updated by the oracle |

### \_getPrice

This internal helper function retrieves the underlying price from an external oracle.

```javascript
    function _getPrice(
        AggregatorV3Interface cOracle,
        uint80 id,
        uint256 ts,
        uint256 decimalDiff
    )
        private
        view
        returns (uint256 finalPrice, uint256 finalTs)
```

**Params:**

| **Name**    | **Type**              | **Description**                                        |
| ----------- | --------------------- | ------------------------------------------------------ |
| cOracle     | AggregatorV3Interface | Oracle interface for retrieving price feed             |
| id          | uint80                | The roundId using which price is retrieved             |
| ts          | uint256               | Timestamp for the asset price                          |
| decimalDiff | uint256               | Precision differences for the number of decimal places |

**Returns:**

| **Name**   | **Type** | **Description**                                           |
| ---------- | -------- | --------------------------------------------------------- |
| finalPrice | uint256  | The computed price                                        |
| finalTs    | uint256  | The timestamp at which the price is updated by the oracle |

### getCOracle

Returns the address of the chainlink oracle for an underlying asset

```javascript
function getCOracle(string memory symbol) public view returns (address)
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| symbol   | string   | The symbol of the asset for which the price is being set |

**Returns:**

| **Type** | **Description**                                 |
| -------- | ----------------------------------------------- |
| address  | The contract address for a chainlink price feed |

### \_getPhaseIdFromRoundId

Returns the phaseId from the given roundId used by the external oracle

```javascript
function _getPhaseIdFromRoundId(uint80 roundId) internal pure returns (uint80) 
```

**Params:**

| **Name** | **Type** | **Description**   |
| -------- | -------- | ----------------- |
| roundId  | uint80   | The given roundId |

**Returns:**

| **Type** | **Description**                 |
| -------- | ------------------------------- |
| uint80   | The phaseId for the given round |

### \_getStartRoundId

Returns the start roundId given a phaseId

```javascript
function _getStartRoundId(uint80 phaseId) internal pure returns (uint80)
```

**Params:**

| **Name** | **Type** | **Description**   |
| -------- | -------- | ----------------- |
| phaseId  | uint80   | The given phaseId |

**Returns:**

| **Type** | **Description**   |
| -------- | ----------------- |
| uint80   | The start roundId |

### \_getPriceInPhase

Helper for getting the

```javascript
    function _getPriceInPhase(
        AggregatorV3Interface cOracle,
        uint80 start,
        uint80 end,
        uint256 ts,
        uint256 decimalDiff
    )
        internal
        view
        returns (uint256 price, uint256 actualTs)
```

**Params:**

| **Name**    | **Type**              | **Description**                                        |
| ----------- | --------------------- | ------------------------------------------------------ |
| cOracle     | AggregatorV3Interface | Oracle interface for retrieving price feed             |
| start       | uint80                | The start phaseId                                      |
| end         | uint80                | The end phaseId                                        |
| ts          | uint256               | Timestamp for the underlying price                     |
| decimalDiff | uint256               | Precision differences for the number of decimal places |

**Returns:**

| **Name** | **Type** | **Description**                                           |
| -------- | -------- | --------------------------------------------------------- |
| Price    | uint256  | The computed price                                        |
| actualTs | uint256  | The timestamp at which the price is updated by the oracle |


# Utils

### getAdjustPrice

Rounds down price input to two significant digits to adjust it for strike price. Assumes 18 decimal places (e.g., ETH price 1500 as 1500 \* 10\*\*18).

```javascript
function getAdjustPrice(uint256 price) pure returns (uint256 adjustedPrice)
```

**Params:**

| **Name** | **Type** | **Description** |
| -------- | -------- | --------------- |
| price    | uint256  | The input price |

**Returns:**

| **Name**      | **Type** | **Description**    |
| ------------- | -------- | ------------------ |
| adjustedPrice | uint256  | The adjusted price |


# SToken

Implements digital call (Spear) and digital put (Shield) options as ERC-20 tokens (STokens).

## mint

Mints an amount of SToken for an account

```javascript
    function mint(address account, uint256 amount) external override onlyOwner
```

**Params:**

| **Name** | **Type** | **Description**             |
| -------- | -------- | --------------------------- |
| account  | address  | The account address         |
| amount   | uint256  | The amount of SToken minted |

## burn

Burns an amount of SToken for an account

```javascript
function burn(address account, uint256 amount) external override onlyOwner
```

**Params:**

| **Name** | **Type** | **Description**             |
| -------- | -------- | --------------------------- |
| account  | address  | The account address         |
| amount   | uint256  | The amount of SToken burned |

## decimals

Returns the number of decimals used for the SToken token

```javascript
function decimals() public view virtual override returns (uint8)
```

**Returns:**

| **Name**   | **Type** | **Description**                            |
| ---------- | -------- | ------------------------------------------ |
| \_decimals | uint8    | The number of decimals used for the SToken |


# Interface

## IBattle

### IBattleActions

#### IBattleMintBurn

#### mint

Mints liquidity for a battle

```javascript
function mint(BattleMintParams memory mp) external returns (uint256 seed)
```

**Params:**

| **Name** | **Type**         | **Description**                  |
| -------- | ---------------- | -------------------------------- |
| mp       | BattleMintParams | Parameters for minting liquidity |

**Returns:**

| **Name** | **Type** | **Description**                                                                               |
| -------- | -------- | --------------------------------------------------------------------------------------------- |
| seed     | uint256  | The token amount provided for the position, of the collateral, Spear or Shield liquidity type |

#### burn

Removes liquidity from a battle

```javascript
function burn(BattleBurnParams memory BurnParams) external
```

**Params:**

| **Name**         | **Description**                                                                                                                       |
| ---------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| BattleBurnParams | Parameters for burning liquidity. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#BattleBurnParams) |

#### collect

Collects the specified amounts of collateral, Spear, and Shield tokens. Transfers them to the recipient. Only called by the contract Manager.

```javascript
function collect(address recipient, uint256 cAmount, uint256 spAmount, uint256 shAmount) external
```

**Params:**

| **Name**  | **Description**                                      |
| --------- | ---------------------------------------------------- |
| recipient | The address who will receive collateral/spear/shield |
| cAmount   | The amount of collateral to be transferred           |
| spAmount  | The amount of Spear tokens to be transferred         |
| shAmount  | The amount of Shield tokens to be transferred        |

#### IBattleTrade

#### trade

Executes a trade by swapping collateral to either Spear or Shield tokens. When the price direction is up (down), an amount of Shield (Spear) token output is sent to the buyer.

```javascript
function trade(BattleTradeParams memory tp) external returns (uint256 cAmount, uint256 sAmount, uint256 fAmount)
```

**Params:**

| **Name** | **Type**          | **Description**                                                                                                                        |
| -------- | ----------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| tp       | BattleTradeParams | Parameters for executing a trade. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#BattleTradeParams) |

**Returns:**

| **Name** | **Type** | **Description**                                                     |
| -------- | -------- | ------------------------------------------------------------------- |
| cAmount  | uint256  | Amount of collateral token input spent to be spent for the trade    |
| sAmount  | uint256  | Amount of Spear or Shield token output to be received for the trade |
| fAmount  | uint256  | Amount of fee in collateral token to be spent for the trade         |

#### IBattleBase

#### settle

Settles options of a pool after their expiry. It updates the battle outcome based on the underlying price retrieved from an external oracle.

```javascript
function settle() external
```

#### exercise

This function allows a participant to exercise their winning long Spear or long Shield position, and claim the collateral payoff. For each winning Spear or Shield, 1 collateral can be claimed. eg. Alice bought 100 spear. The battle outcome turns out to be `spear_win`. she can claim 100 collateral tokens by call this function.

```javascript
function exercise() external
```

#### withdrawObligation

Returns the amount of unused collateral to the liquidity provider after settlement. For options that expire out-of-money, the amount of collateral obligation reserved prior to settlement becomes claimable. Only called by the Manager.

```javascript
function withdrawObligation(address recipient, uint256 amount) external;
```

**Params:**

| **Name**  | **Type** | **Description**                           |
| --------- | -------- | ----------------------------------------- |
| recipient | address  | Address which will receive the collateral |
| amount    | uint256  | The amount of collateral to be withdrawn  |

#### collectProtocolFee

This function allows the accumulated protocol fee to be collected. Can only be called by the owner.

```javascript
function collectProtocolFee(address recipient) external
```

**Params:**

| **Name**  | **Type** | **Description**            |
| --------- | -------- | -------------------------- |
| recipient | address  | The address receiving fees |

### IBattleInit

#### init

Inits state variable in storage. It is called only once for a battle.

```javascript
function init(DeploymentParams memory params) external override
```

**Params:**

| **Name**         | **Description**                                                                                                                          |
| ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| DeploymentParams | The parameters for deploying a pool. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#DeploymentParams) |

### IBattleState

#### positions

Retrieves position info for a given position key

```javascript
function positions(bytes32 pk) external view returns (PositionInfo memory info)
```

**Params:**

| **Name** | **Type** | **Description** |
| -------- | -------- | --------------- |
| pk       | bytes32  | Position key    |

**Returns:**

| **Name** | **Type**     | **Description**                |
| -------- | ------------ | ------------------------------ |
| info     | PositionInfo | Information about the position |

#### battleOutcome

Gets the result of the battle

```javascript
function battleOutcome() external view returns (Outcome)
```

**Returns:**

| **Name** | **Type** | **Description**           |
| -------- | -------- | ------------------------- |
| result   | Outcome  | The outcome of the battle |

#### battleKey

Returns the BattleKey that uniquely identifies a battle

```javascript
function battleKey() external view returns (BattleKey memory key)
```

**Returns:**

| **Name** | **Type**  | **Description** |
| -------- | --------- | --------------- |
| key      | BattleKey | The battle key  |

#### manager

Returns the address for the manager of the pool

```javascript
function manager()  external  view  returns  (address)
```

**Returns:**

| **Name** | **Type** | **Description**                    |
| -------- | -------- | ---------------------------------- |
| manager  | address  | Address of the manager of the pool |

#### slot0

Returns data stored in the baseInfo struct

```javascript
function slot0() external view returns (uint160 sqrtPriceX96, int24 tick, bool unlocked)
```

**Returns:**

| **Name**     | **Type** | **Description**                           |
| ------------ | -------- | ----------------------------------------- |
| sqrtPriceX96 | uint160  | The current sqrtPrice of the pool         |
| tick         | int24    | The current tick of the battle            |
| unlocked     | bool     | Flag indicating if the battle is unlocked |

#### spearAndShield

Returns the addresses of the Spear and Shield tokens

```javascript
function spearAndShield() external view returns (address, address)
```

**Returns:**

| **Type** | **Description**             |
| -------- | --------------------------- |
| address  | Address of the Spear token  |
| address  | Address of the Shield token |

#### startAndEndTS

Get the start and end timestamps of the battle

```javascript
function startAndEndTS() external view returns (uint256, uint256)
```

**Returns:**

| **Type** | **Description**               |
| -------- | ----------------------------- |
| uint256  | Start timestamp of the battle |
| uint256  | End timestamp of the battle   |

#### spearBalanceOf

Get the balance of Spear tokens for an account

```javascript
function spearBalanceOf(address account) external view returns (uint256 amount)
```

**Params:**

| **Name** | **Type** | **Description**        |
| -------- | -------- | ---------------------- |
| account  | address  | Address of the account |

**Returns:**

| **Name** | **Type** | **Description**             |
| -------- | -------- | --------------------------- |
| amount   | uint256  | The balance of Spear tokens |

#### shieldBalanceOf

Get the balance of Shield tokens for an account

```javascript
function shieldBalanceOf(address account) external view returns (uint256 amount)
```

**Params:**

| **Name** | **Type** | **Description**        |
| -------- | -------- | ---------------------- |
| account  | address  | Address of the account |

**Returns:**

| **Name** | **Type** | **Description**              |
| -------- | -------- | ---------------------------- |
| amount   | uint256  | The balance of Shield tokens |

#### spear

Get the address of the Spear token

```javascript
function spear() external view returns (address)
```

**Returns:**

| **Name** | **Type** | **Description**            |
| -------- | -------- | -------------------------- |
| spear    | address  | Address of the Spear token |

#### shield

Get the address of the Shield token

```javascript
function shield() external view returns (address)
```

**Returns:**

| **Name** | **Type** | **Description**             |
| -------- | -------- | --------------------------- |
| shield   | address  | Address of the Shield token |

#### getInsideLast

Get the growth rate inside a tick range

```javascript
function getInsideLast(int24 tickLower, int24 tickUpper) external view returns (GrowthX128 memory)
```

**Params:**

| **Name**  | **Type** | **Description**         |
| --------- | -------- | ----------------------- |
| tickLower | int24    | Lower tick of the range |
| tickUpper | int24    | Upper tick of the range |

**Returns:**

| **Name**   | **Description**                                                                                                                   |
| ---------- | --------------------------------------------------------------------------------------------------------------------------------- |
| GrowthX128 | Growth variables for the tick range. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#GrowthX128) |

#### fee

Get the fee ratios used for a battle

```javascript
function fee() external view returns (uint256, uint256, uint256)
```

**Returns:**

| **Type** | **Description**                                          |
| -------- | -------------------------------------------------------- |
| uint256  | The fee ratio taken on every trade                       |
| uint256  | The portion of transaction fee that goes to the protocol |
| uint256  | The exercise fee paid by those who call exercise()       |

## Callback

### IMintCallback

#### mintCallback

Sets the amount owed to the pool for the minted liquidity

```javascript
function mintCallback(uint256 amountOwed,  bytes  calldata data)  external
```

**Params:**

| **Name**   | **Type** | **Description**                                      |
| ---------- | -------- | ---------------------------------------------------- |
| amountOwed | uint256  | The amount owed to the pool for the minted liquidity |
| data       | bytes    | Any additional data passed through by the caller     |

### ITradeCallback

#### tradeCallback

Call back function after trading

```javascript
function tradeCallback(uint256 cAmount, uint256 sAmount, bytes calldata data) external;
```

**Params:**

| **Name** | **Type**    | **Description**                                  |
| -------- | ----------- | ------------------------------------------------ |
| cAmount  | TradeAction | The amount of collateral                         |
| sAmount  | TradeAction | The amount of Spear or Shield tokens             |
| data     | bytes       | Any additional data passed through by the caller |

## IArena

### IArenaAdmin

#### setFeeForUnderlying

Sets the fee parameters for an underlying asset

```javascript
function setFeeForUnderlying(string calldata underlying, Fee calldata newFee) external;
```

**Params:**

| **Name**   | **Type** | **Description**                      |
| ---------- | -------- | ------------------------------------ |
| underlying | string   | The name of the underlying asset     |
| newFee     | Fee      | The new fee for the underlying asset |

#### setCollateralWhitelist

Sets the whitelist status for a collateral token. Can only be set by the owner. This function will no longer be in use when the permissionless mode is enabled.

```javascript
function setCollateralWhitelist(address collateral, bool isSupported) external
```

**Params:**

| **Name**    | **Type** | **Description**                              |
| ----------- | -------- | -------------------------------------------- |
| collateral  | address  | The address of the collateral token          |
| isSupported | bool     | The whitelist status of the collateral token |

#### setUnderlyingWhitelist

Sets the whitelist status and fee for an underlying asset.

```javascript
function setUnderlyingWhitelist(string memory underlying, bool isSupported, Fee calldata fee) external
```

**Params:**

| **Name**    | **Type** | **Description**                              |
| ----------- | -------- | -------------------------------------------- |
| underlying  | string   | The symbol or name of the underlying asset   |
| isSupported | bool     | The whitelist status of the underlying asset |
| fee         | Fee      | The fee structure for the underlying asset   |

#### setPermissionless

Toggles the permissionless mode of the contract. Permissionless mode is disabled initially, when the contracts begin in production. Only whitelisted collateral tokens can be used in battles. Once the permissionless mode is enabled, battles can be created with any ERC-20 token without the need for a whitelist.

```javascript
function setPermissionless() external
```

#### setManager

Sets the manager address

```javascript
function setManager(address _manager) external
```

#### setOracle

Sets the oracle address

```javascript
function setOracle(address _oracle) external
```

### IArenaCreation

#### createBattle

Create a new battle

```javascript
function createBattle(BattleKey memory bk) external returns (address battleAddr);
```

**Params:**

| **Name** | **Type**  | **Description**                                                                                                                             |
| -------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
| bk       | BattleKey | Parameters for creating a new battle. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#createbattleparams) |

**Returns:**

| **Name**   | **Type** | **Description**               |
| ---------- | -------- | ----------------------------- |
| battleAddr | address  | The address of the new battle |

#### getBattle

Returns existing battle address from the given BattleKey

```javascript
function getBattle(BattleKey memory battleKey) external view returns (address battleAddr);
```

**Params:**

| **Name**  | **Type** | **Description**                                   |
| --------- | -------- | ------------------------------------------------- |
| battleKey | bytes32  | The battle Key containing a pool's specifications |

**Returns:**

| **Name**   | **Type** | **Description**                                               |
| ---------- | -------- | ------------------------------------------------------------- |
| battleAddr | address  | The address of the existing battle or address(0) if not found |

### IArenaState

#### getAllBattles

Get information for all battles

```javascript
function getAllBattles() external view returns (BattleInfo[] memory);
```

**Returns:**

| **Name**   | **Type** | **Description**                                                                                                                                                                          |
| ---------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| BattleInfo | memory   | Information about all battles, each including the battle address, battle key, sqrtPrice, start and expiry timestamps, spear and shield token addresses and balances, and battle outcome. |

### IOracle

Collects and updates underlying asset prices used for settling options. It retrieves asset prices and supplies them to all contracts that use them.

#### updatePriceByExternal

Gets and computes price from external oracles

```javascript
function getPriceByExternal(address cOracleAddr, uint256 ts) external view returns (uint256 price_, uint256 actualTs)
```

**Params:**

| **Name**    | **Type** | **Description**                                 |
| ----------- | -------- | ----------------------------------------------- |
| cOracleAddr | address  | The contract address for a chainlink price feed |
| ts          | uint256  | Timestamp for the asset price                   |

**Returns:**

| **Name** | **Type** | **Description**                                           |
| -------- | -------- | --------------------------------------------------------- |
| price    | uint256  | The retrieved price                                       |
| actualTs | uint256  | The timestamp at which the price is updated by the oracle |

#### getCOracle

Returns the address of the chainlink oracle for an underlying

```javascript
function getCOracle(string memory symbol) external view returns (address)
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| symbol   | string   | The symbol of the asset for which the price is being set |

**Returns:**

| **Type** | **Description**                                 |
| -------- | ----------------------------------------------- |
| address  | The contract address for a chainlink price feed |

### IOwner

#### owner

Fetches the address of the contract owner

```javascript
function owner() external view returns (address);
```

**Returns:**

| **Type** | **Description**                   |
| -------- | --------------------------------- |
| address  | The address of the contract owner |

### ISToken

Mints or burns Spear or Shield tokens

#### mint

Mints an amount of tokens to a specific account

```javascript
function mint(address account, uint256 amount) external;
```

**Params:**

| **Name** | **Type** | **Description**                                            |
| -------- | -------- | ---------------------------------------------------------- |
| account  | address  | The address to which spear or shield tokens will be minted |
| amount   | uint256  | The amount of spear or shield tokens to mint               |

#### burn

Burns an amount of tokens from a specific account

```javascript
function burn(address account, uint256 amount) external;
```

**Params:**

| **Name** | **Type** | **Description**                                              |
| -------- | -------- | ------------------------------------------------------------ |
| account  | address  | The address from which spear or shield tokens will be burned |
| amount   | uint256  | The amount of spear or shield tokens to burn                 |


# Libraries

Functionalities used by other contracts


# DiverSqrtPriceMath

Contains the math that uses liquidity to compute token deltas or square root of price as a Q64.96

## getSTokenDelta

Gets the delta amount of Spear or Shield tokens based on the given sqrt ratios and liquidity. Computes for Spear token delta when the sqrtPrice moves from upper to lower; or Shield token delta when the sqrtPrice moves from lower to upper. For the same sqrt ratio range and liquidity, the computed delta amounts of Spear and Shield are equal.

The formula for this is spear or shield delta amount = liquidity \* (sqrtRatioBX96 - sqrtRatioAX96) \* (1 + 1 /(sqrtRatioAX96 \* sqrtRatioBX96))

```javascript
function getSTokenDelta(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity, bool roundUp) internal pure returns (uint256 amount)
```

**Params:**

| **Name**      | **Type** | **Description**                                                              |
| ------------- | -------- | ---------------------------------------------------------------------------- |
| sqrtRatioAX96 | uint160  | A sqrt ratio                                                                 |
| sqrtRatioBX96 | uint160  | Another sqrt ratio                                                           |
| liquidity     | uint128  | The change in liquidity for which to compute the Spear or Shield token delta |
| roundUp       | bool     | Whether to round the amount up or down                                       |

**Returns:**

| **Name** | **Type** | **Description**                                                                                       |
| -------- | -------- | ----------------------------------------------------------------------------------------------------- |
| amount   | uint256  | The amount of Spear or Shield token corresponding to the passed liquidityDelta between the two prices |

## getSTokenDelta

Helper that gets signed spear or shield token delta

```javascript
function getSTokenDelta(uint160 sqrtPriceAX96, uint160 sqrtPriceBX96, int128 liquidity) internal pure returns (int256 amount)
```

**Params:**

| **Name**      | **Type** | **Description**                                                              |
| ------------- | -------- | ---------------------------------------------------------------------------- |
| sqrtRatioAX96 | uint160  | A sqrt ratio                                                                 |
| sqrtRatioBX96 | uint160  | Another sqrt ratio                                                           |
| liquidity     | int128   | The change in liquidity for which to compute the Spear or Shield token delta |

**Returns:**

| **Name** | **Type** | **Description**                                                                                       |
| -------- | -------- | ----------------------------------------------------------------------------------------------------- |
| amount   | int256   | The amount of Spear or Shield token corresponding to the passed liquidityDelta between the two prices |

## getNextSqrtPriceFromSpear

Gets the next sqrt ratio based on the given the Spear token delta and liquidity.

```javascript
function getNextSqrtPriceFromSpear(
        uint160 sqrtPrice,
        uint128 liquidity,
        uint256 amount,
        uint256 unit
    )
        internal
        pure
        returns (uint160 nextSqrtPrice)
```

**Params:**

| **Name**  | **Type** | **Description**                                                              |
| --------- | -------- | ---------------------------------------------------------------------------- |
| sqrtPrice | uint160  | The starting price, i.e. before accounting for the spear token delta         |
| liquidity | uint128  | The amount of usable liquidity                                               |
| amount    | uint256  | The amount of Spear token delta to mint for the trade                        |
| unit      | uint256  | The token decimal unit, e.g. a token with 18 decimals has a unit of 10\*\*18 |

**Returns:**

| **Name**      | **Type** | **Description**                                                    |
| ------------- | -------- | ------------------------------------------------------------------ |
| nextSqrtPrice | uint160  | The next sqrt ratio after minting the given amount of Spear tokens |

## getNextSqrtPriceFromShield

Gets the next sqrt ratio based on the given the Shield token delta and liquidity.

```javascript
    function getNextSqrtPriceFromShield(
        uint160 sqrtPrice,
        uint128 liquidity,
        uint256 amount,
        uint256 unit
    )
        internal
        pure
        returns (uint160 nextSqrtPrice)
```

**Params:**

| **Name**  | **Type** | **Description**                                                              |
| --------- | -------- | ---------------------------------------------------------------------------- |
| sqrtPrice | uint160  | The starting price, i.e. before accounting for the Shield token delta        |
| liquidity | uint128  | The amount of usable liquidity                                               |
| amount    | uint256  | The amount of Shield token delta to mint for the trade                       |
| unit      | uint256  | The token decimal unit, e.g. a token with 18 decimals has a unit of 10\*\*18 |

**Returns:**

| **Name**      | **Type** | **Description**                                                     |
| ------------- | -------- | ------------------------------------------------------------------- |
| nextSqrtPrice | uint160  | The next sqrt ratio after minting the given amount of Shield tokens |


# Position

Manages and updates the position information

## get

Retrieves the position information for the given owner and tick range

```javascript
function get(mapping(bytes32 => PositionInfo) storage self, address owner, int24 tickLower, int24 tickUpper) internal view returns (PositionInfo storage position)
```

**Params:**

| **Name**  | **Type**                         | **Description**                          |
| --------- | -------------------------------- | ---------------------------------------- |
| self      | mapping(bytes32 => PositionInfo) | Storage mapping for position information |
| owner     | address                          | The owner of the position                |
| tickLower | int24                            | The lower tick of the position range     |
| tickUpper | int24                            | The upper tick of the position range     |

**Returns:**

| **Name** | **Type**     | **Description**                                                                                                                       |
| -------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------- |
| position | PositionInfo | The info struct of the given position. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#PositionInfo) |

## update

Updates the position information based on the liquidity delta and growth information

```javascript
function update(PositionInfo storage self, int128 liquidityDelta, GrowthX128 memory insideLast) internal
```

**Params:**

| **Name**       | **Type**     | **Description**                                                                                                                                                                 |
| -------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| self           | PositionInfo | The info struct of the given position. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types/#PositionInfo)                                           |
| liquidityDelta | int128       | The change in pool liquidity for the position                                                                                                                                   |
| insideLast     | GrowthX128   | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info struct per unit of liquidity inside the tick range, as of the last update |


# Tick

Manages tick processes and computes variables stored in the tick state

## tickSpacingToMaxLiquidityPerTick

Derives max liquidity per tick from given tick spacing. Executed within the pool constructor.

```javascript
function tickSpacingToMaxLiquidityPerTick(int24 tickSpacing)  internal  pure  returns  (uint128) 
```

**Params:**

| **Name**    | **Type** | **Description**                                                              |
| ----------- | -------- | ---------------------------------------------------------------------------- |
| tickSpacing | int24    | The amount of required tick separation, realized in multiples of tickSpacing |

**Returns:**

| **Type** | **Description**            |
| -------- | -------------------------- |
| uint128  | Maximum liquidity per tick |

## getGrowthInside

Computes growth of fees, collateral, Spear and Shield deltas within a tick boundary.

```javascript
function getGrowthInside(mapping(int24 => TickInfo)  storage self,  int24 tickLower,  int24 tickUpper,  int24 tickCurrent, GrowthX128 memory global)
internal
view
returns  (GrowthX128 memory inside)
```

**Params:**

| **Name**    | **Type**                           | **Description**                                                                                                                                                                     |
| ----------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| self        | mapping(int24 => struct Tick.Info) | The mapping containing TickInfo. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types#tickinfo)                                                          |
| tickLower   | int24                              | The lower tick boundary of the position                                                                                                                                             |
| tickUpper   | int24                              | The upper tick boundary of the position                                                                                                                                             |
| tickCurrent | int24                              | The current tick                                                                                                                                                                    |
| global      | GrowthX128                         | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info struct per unit of liquidity as of the last update to the pool's global state |

**Returns:**

| **Name** | **Type**   | **Description**                                                                                                                                          |
| -------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
| inside   | GrowthX128 | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info struct per unit of liquidity inside the tick range |

## update

Updates a tick and returns true if the tick was flipped from initialized to uninitialized, or vice versa.

```javascript
function update(mapping(int24 => TickInfo) storage self, int24 tick, int24 tickCurrent, int128 liquidityDelta, GrowthX128 memory global, uint128 maxLiquidity, bool upper) internal returns (bool flipped)
```

**Params:**

| **Name**       | **Type**                           | **Description**                                                                                                                                                                     |
| -------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| self           | mapping(int24 => struct Tick.Info) | The mapping containing TickInfo. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types#tickinfo)                                                          |
| tick           | int24                              | The tick that will be updated                                                                                                                                                       |
| tickCurrent    | int24                              | The current tick                                                                                                                                                                    |
| liquidityDelta | int128                             | The change in liquidity                                                                                                                                                             |
| global         | GrowthX128                         | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info struct per unit of liquidity as of the last update to the pool's global state |
| maxLiquidity   | uint128                            | The maximum liquidity allocation for a single tick                                                                                                                                  |
| upper          | bool                               | Indicates whether the tick represents the upper boundary                                                                                                                            |

**Returns:**

| **Name** | **Type** | **Description**                                                               |
| -------- | -------- | ----------------------------------------------------------------------------- |
| flipped  | bool     | Whether the tick was flipped from initialized to uninitialized, or vice versa |

## clear

Clears tick data

```javascript
function clear(mapping(int24 => TickInfo)  storage self,  int24 tick)  internal  
```

**Params:**

| **Name** | **Type**                           | **Description**                                                                                                            |
| -------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------- |
| self     | mapping(int24 => struct Tick.Info) | The mapping containing TickInfo. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types#tickinfo) |
| tick     | int24                              | The tick that will be cleared                                                                                              |

## cross

Transitions to next tick as needed by price movement

```javascript
function cross(mapping(int24 => TickInfo) storage self, int24 tick, GrowthX128 memory global) internal returns (int128 liquidityNet)
```

**Params:**

| **Name** | **Type**                           | **Description**                                                                                                                                                                     |
| -------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| self     | mapping(int24 => struct Tick.Info) | The mapping containing TickInfo. See [Types](https://docs.divergence-protocol.com/technical-reference/core/types#tickinfo)                                                          |
| tick     | int24                              | The destination tick of the transition                                                                                                                                              |
| global   | GrowthX128                         | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info struct per unit of liquidity as of the last update to the pool's global state |

**Returns:**

| **Name**     | **Type** | **Description**   |
| ------------ | -------- | ----------------- |
| liquidityNet | int128   | The net liquidity |


# TickMath

Math library for computing sqrt prices from ticks and vice versa. Sets the minimum and maximum of ticks and sqrt prices.

As digital calls and puts are priced between \[0.01, 0.99] per collateral, per put-call parity, the sqrtPrice is the sqrt ratio of shieldPrice/spearPrice is between \[sqrt(1/99), sqrt(99)].  sqrtPrice is computed for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers.

## getSqrtRatioAtTick

Calculates and returns the square root ratio at the given tick.

```javascript
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96)
```

**Params:**

| **Name** | **Type** | **Description**                      |
| -------- | -------- | ------------------------------------ |
| tick     | int24    | The input tick for the above formula |

**Returns:**

| **Name**     | **Type** | **Description**                                                                          |
| ------------ | -------- | ---------------------------------------------------------------------------------------- |
| sqrtPriceX96 | uint160  | A fixed point Q64.96 number representing the sqrt of the ratio of shieldPrice/spearPrice |

## getTickAtSqrtRatio

Calculates and returns the tick value at the given square root ratio.

```javascript
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick)
```

**Params:**

| **Name**     | **Type** | **Description**                                          |
| ------------ | -------- | -------------------------------------------------------- |
| sqrtPriceX96 | uint160  | The sqrt ratio for which to compute the tick as a Q64.96 |

**Returns:**

| **Name** | **Type** | **Description**                                                                |
| -------- | -------- | ------------------------------------------------------------------------------ |
| tick     | int24    | The greatest tick for which the price is less than or equal to the input ratio |


# TradeMath

Computes the result of a swap within ticks. Contains methods for computing the result of a swap within a single tick price range, i.e., a single tick.

## computeTradeStep

Computes the result of swapping some collateral amount in, or options token amount out, given the parameters of the swap.

```javascript
  function computeTradeStep(ComputeTradeStepParams memory params)
        internal
        pure
        returns (uint160 sqrtRatioNextX96, uint256 amountIn, uint256 amountOut)
```

**Params:**

| **Name**               | **Type** | **Description**                                                                                                                              |
| ---------------------- | -------- | -------------------------------------------------------------------------------------------------------------------------------------------- |
| ComputeTradeStepParams | params   | Params for computing a trade step. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#ComputeTradeStepParams) |

**Returns:**

| **Name**         | **Type** | **Description**                                                                                |
| ---------------- | -------- | ---------------------------------------------------------------------------------------------- |
| sqrtRatioNextX96 | uint160  | The price after swapping the amount in/out, not to exceed the price target                     |
| amountIn         | uint256  | The collateral amount to be swapped in based on the direction of the swap                      |
| amountOut        | uint256  | The amount to be received, of either spear or shield token, based on the direction of the swap |


# Params

Parameters for functions contained in the core contracts

## BattleBurnParams

Params used by burn function in the core Battle contracts

```javascript
struct BattleBurnParams {
    int24 tickLower;
    int24 tickUpper;
    LiquidityType liquidityType;
    uint128 liquidityAmount;
}
```

**Params:**

| **Name**        | **Type**      | **Description**                                                     |
| --------------- | ------------- | ------------------------------------------------------------------- |
| tickLower       | int24         | The lower tick boundary of the position for which to burn liquidity |
| tickUpper       | int24         | The upper tick boundary of the position for which to burn liquidity |
| liquidityType   | LiquidityType | The chosen liquidity type can be Collateral, Spear, or Shield       |
| liquidityAmount | uint128       | The amount of liquidity to be burnt                                 |

## BattleMintParams

Params used by mint function in the core Battle contracts

```javascript
struct BattleMintParams {
    address recipient;
    int24 tickLower;
    int24 tickUpper;
    LiquidityType liquidityType;
    uint128 amount;
    uint128 seed;
    bytes data;
}
```

**Params:**

| **Name**      | **Type**      | **Description**                                                                               |
| ------------- | ------------- | --------------------------------------------------------------------------------------------- |
| recipient     | address       | The address for which the liquidity will be added                                             |
| tickLower     | int24         | The lower tick boundary of the position in which to add liquidity                             |
| tickUpper     | int24         | The upper tick boundary of the position in which to add liquidity                             |
| liquidityType | LiquidityType | The chosen liquidity type can be Collateral, Spear, or Shield                                 |
| amount        | uint128       | The amount of liquidity to be added                                                           |
| seed          | uint128       | The token amount provided for the position, of the collateral, Spear or Shield liquidity type |
| data          | bytes         | Any data to be passed through to the callback                                                 |

## BattleTradeParams

Params used by trade function in the core Battle contracts

```javascript
struct BattleTradeParams {
    address recipient;
    TradeType tradeType;
    uint256 amountSpecified;
    uint160 sqrtPriceLimitX96;
    bytes data;
}
```

**Params:**

| **Name**          | **Type**  | **Description**                                                                                                                          |
| ----------------- | --------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| recipient         | address   | The address to receive the output of the swap                                                                                            |
| tradeType         | TradeType | The type of trade to perform                                                                                                             |
| amountSpecified   | uint256   | The amount of the swap, which implicitly configures the swap as exact input of collateral or exact output of Spear or Shield token delta |
| sqrtPriceLimitX96 | uint160   | The Q64.96 sqrtPrice limit                                                                                                               |
| data              | bytes     | Any data to be passed through to the callback                                                                                            |

## ComputeTradeStepParams

Paramaters used for step computations in a trade

```javascript
struct ComputeTradeStepParams {
    TradeType tradeType;
    uint160 sqrtRatioCurrentX96;
    uint160 sqrtRatioTargetX96;
    uint128 liquidity;
    int256 amountRemaining;
    uint256 unit;
}
```

**Params:**

| **Name**            | **Type**  | **Description**                                                                     |
| ------------------- | --------- | ----------------------------------------------------------------------------------- |
| tradeType           | TradeType | The type of trade to be executed, whether to `BUY_SPEAR` or `BUY_SHIELD`            |
| sqrtRatioCurrentX96 | uint160   | The current sqrt ratio of the pool                                                  |
| sqrtRatioTargetX96  | uint160   | The price that cannot be exceeded, from which the direction of the swap is inferred |
| liquidity           | uint128   | The usable liquidity                                                                |
| amountRemaining     | int256    | How much input or output amount is remaining to be swapped in/out                   |
| unit                | uint256   | The token decimal unit, e.g. a token with 18 decimals has a unit of 10\*\*18        |

## CreateBattleParams

The info struct used in the creation of an options pool, ie, a Battle.

```javascript
struct CreateBattleParams {
    address collateralToken;
    string underlying;
    uint256 expiries;
    uint256 strikeValue;
}
```

**Params:**

| **Name**        | **Type** | **Description**                                       |
| --------------- | -------- | ----------------------------------------------------- |
| collateralToken | address  | The supported collateral token address for the battle |
| underlying      | string   | The underlying asset symbol                           |
| expiries        | uint256  | The of expiry timestamp of the battle                 |
| strikeValue     | uint256  | The value of an option's strike price                 |

## DeploymentParams

Parameters used for deploying battles

```javascript
struct DeploymentParams {
    address arenaAddr;
    BattleKey battleKey;
    address oracleAddr;
    address cOracleAddr;
    Fee fee;
    address spear;
    address shield;
    address manager;
    uint160 sqrtPriceX96;
}
```

**Params:**

| **Name**     | **Type** | **Description**                                   |
| ------------ | -------- | ------------------------------------------------- |
| arenaAddr    | address  | The address for the arena contract                |
| battleKey    | bytes32  | The battle Key containing a pool's specifications |
| oracleAddr   | address  | The address for the oracle                        |
| cOracleAddr  | address  | the contract address for a chainlink price feed   |
| fee          | Fee      | The fee structure for the battle                  |
| spear        | address  | The address of the Spear tokens for a pool        |
| shield       | address  | The address of the Shield tokens for a pool       |
| manager      | address  | The address for the manager contract              |
| sqrtPriceX96 | uint160  | The starting sqrt ratio when initiating a battle  |

## ModifyPositionParams

Info struct used to modify position parameters

```javascript
struct ModifyPositionParams {
    int24 tickLower;
    int24 tickUpper;
    LiquidityType liquidityType;
    int128 liquidityDelta;
}
```

**Params:**

| **Name**       | **Type**      | **Description**                                               |
| -------------- | ------------- | ------------------------------------------------------------- |
| tickLower      | int24         | The lower tick boundary of the position                       |
| tickUpper      | int24         | The upper tick boundary of the position                       |
| liquidityType  | LiquidityType | The chosen liquidity type can be Collateral, Spear, or Shield |
| liquidityDelta | int24         | The change in liquidity                                       |

## UpdatePositionParams

Info struct used to update position parameters

```javascript
struct UpdatePositionParams {
    ModifyPositionParams mpParams;
    int24 tick;
}
```

**Params:**

| **Name** | **Type**             | **Description**                           |
| -------- | -------------------- | ----------------------------------------- |
| mpParams | ModifyPositionParams | The parameters for modifying the position |
| tick     | int24                | The current tick                          |


# Types

## Common

### BattleKey

Info struct containing a pool's specifications

```javascript
struct BattleKey {
    address collateral;
    string underlying;
    uint256 expiries;
    uint256 strikeValue;
}
```

**Params:**

| **Name**    | **Type** | **Description**                             |
| ----------- | -------- | ------------------------------------------- |
| collateral  | address  | The address of the token used as collateral |
| underlying  | string   | The underlying asset symbol                 |
| expiries    | uint256  | The expiry timestamp                        |
| strikeValue | uint256  | The strike price of options within the pool |

### Fee

Info struct representing the fee ratios used in a battle

```javascript
struct Fee {
    uint256 transactionFee;
    uint256 protocolFee;
    uint256 exerciseFee;
}
```

**Params:**

| **Name**       | **Type** | **Description**                                                             |
| -------------- | -------- | --------------------------------------------------------------------------- |
| transactionFee | uint256  | The fee ratio taken on every trade                                          |
| protocolFee    | uint256  | The ratio of the transaction fee that goes to the protocol                  |
| exerciseFee    | uint256  | The fee ratio applied when Spear or Shield tokens are exercised at maturity |

### GrowthX128

Info struct tracking the cumulative amounts of fees and deltas of collateral, Spear and Shield tokens involved in transactions

```javascript
struct GrowthX128 {
    uint256 fee;
    uint256 collateralIn;
    uint256 spearOut;
    uint256 shieldOut;
}

```

**Params:**

| **Name**     | **Type** | **Description**                                                                                  |
| ------------ | -------- | ------------------------------------------------------------------------------------------------ |
| fee          | uint256  | The all-time growth in transaction fee, per unit of liquidity, in collateral token               |
| collateralIn | uint256  | The all-time growth in the received collateral inputs, per unit of liquidity, as options premium |
| spearOut     | uint256  | The all-time growth in Spear token outputs per unit of liquidity                                 |
| shieldOut    | uint256  | The all-time growth in Shield token outputs per unit of liquidity                                |

### Owed

Info struct tracking the amounts of fees and deltas of collateral, Spear and Shield tokens that are owed to a position

```javascript
struct Owed {
    uint128 fee;
    uint128 collateralIn;
    uint128 spearOut;
    uint128 shieldOut;
}
```

**Params:**

| **Name**     | **Type** | **Description**                                                               |
| ------------ | -------- | ----------------------------------------------------------------------------- |
| fee          | uint128  | The amount of transaction fee owed to the position as of the last computation |
| collateralIn | uint128  | The collateral inputs owed to the position as of the last computation         |
| spearOut     | uint128  | The Spear token outputs owed to the position as of the last computation       |
| shieldOut    | uint128  | The Shield token outputs owed to the position as of the last computation      |

### TickInfo

Info struct tracking the state of a tick

```javascript
struct TickInfo {
    uint128 liquidityGross;
    int128 liquidityNet;
    GrowthX128 outside;
    bool initialized;
}
```

**Params:**

| **Name**       | **Type**   | **Description**                                                                                                                                                    |
| -------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| liquidityGross | uint128    | The total amount of liquidity that the pool uses either at tickLower or tickUpper                                                                                  |
| liquidityNet   | int128     | The amount of liquidity added (subtracted) when tick is crossed from left to right (right to left)                                                                 |
| outside        | GrowthX128 | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info recorded on the other side of the tick from the current tick |
| initialized    | bool       | Whether the tick is initialized                                                                                                                                    |

### PositionInfo

Info struct tracking the state of a position

```javascript
struct PositionInfo {
    uint128 liquidity;
    GrowthX128 insideLast;
}
```

**Params:**

| **Name**   | **Type**   | **Description**                                                                                                                                                                 |
| ---------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| liquidity  | uint128    | The amount of usable liquidity                                                                                                                                                  |
| insideLast | GrowthX128 | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info per unit of liquidity inside the a position's bound as of the last action |

## Enums

### LiquidityType

Tracks the type of liquidity used by the LP

```javascript
enum LiquidityType {
    COLLATERAL,
    SPEAR,
    SHIELD
}
```

### Outcome

Tracks the status of a battle

```javascript
enum Outcome {
    ONGOING, 
    SPEAR_WIN, 
    SHIELD_WIN 
}
```

### TradeType

Tracks the type of trade

```javascript
enum TradeType {
    BUY_SPEAR,
    BUY_SHIELD
}
```

## TradeTypes

### TradeCache

Represents cached trade information

```javascript
struct TradeCache {
    uint256 feeProtocol;
}
```

**Params:**

| **Name**    | **Type** | **Description**                |
| ----------- | -------- | ------------------------------ |
| feeProtocol | uint256  | The protocol fee for the trade |

### TradeState

Represents the state of the trade

```javascript
struct TradeState {
    uint256 amountSpecifiedRemaining;
    uint256 amountCalculated;
    uint160 sqrtPriceX96;
    int24 tick;
    GrowthX128 global;
    uint128 protocolFee;
    uint128 liquidity;
    uint256 transactionFee;
}
```

**Params:**

| **Name**                 | **Type**   | **Description**                                                                                                                                                              |
| ------------------------ | ---------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| amountSpecifiedRemaining | uint256    | How much collateral input or SToken output amount is remaining to be swapped in/out                                                                                          |
| amountCalculated         | uint256    | The amount of collateral input or SToken output that has been calculated for the swap                                                                                        |
| sqrtPriceX96             | uint160    | A fixed point Q64.96 number representing the sqrt of the ratio of shieldPrice/spearPrice                                                                                     |
| tick                     | int24      | The current tick                                                                                                                                                             |
| global                   | GrowthX128 | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info per unit of liquidity as of the last update to the pool's global state |
| protocolFee              | uint128    | The amount of collateral token to be paid as protocol fee                                                                                                                    |
| liquidity                | uint128    | The amount of usable liquidity                                                                                                                                               |
| transactionFee           | uint256    | The transaction fee for the trade                                                                                                                                            |

### StepComputations

Info struct used in computing the result of swapping some amount in, or amount out, given the parameters of the swap.

```javascript
struct StepComputations {
    uint160 sqrtPriceStartX96;
    int24 tickNext;
    bool initialized;
    uint160 sqrtPriceNextX96;
    uint256 amountIn;
    uint256 amountOut;
    uint256 feeAmount;
    int24 tickLower;
    int24 tickUpper;
}
```

**Params:**

| **Name**          | **Type** | **Description**                                                                                |
| ----------------- | -------- | ---------------------------------------------------------------------------------------------- |
| sqrtPriceStartX96 | uint160  | The sqrtPrice from which to start step computation                                             |
| tickNext          | int24    | The next tick up to the max or min tick of the virtual curve                                   |
| initialized       | bool     | Whether the next tick is initialized                                                           |
| sqrtPriceNextX96  | uint160  | The price after swapping the amount in/out, not to exceed the price target                     |
| amountIn          | uint256  | The collateral amount to be swapped in, based on the direction of the swap                     |
| amountOut         | uint256  | The amount to be received, of either Spear or Shield token, based on the direction of the swap |
| feeAmount         | uint256  | The amount of collateral input that will be taken as a fee                                     |
| tickLower         | int24    | The lower tick for the step                                                                    |
| tickUpper         | int24    | The upper tick for the step                                                                    |
|                   |          |                                                                                                |


# Periphery


# Manager

Sets up the necessary state variables, mappings, and inheritance to handle position NFTs, manage liquidity, and interact with the battle contracts

## addLiquidity

Adds liquidity to a battle contract, mints a new token representing the liquidity position, and records the position information for later reference.

```javascript
function addLiquidity(AddLiqParams calldata params) external override returns (uint256 tokenId, uint128 liquidity)
```

**Params:**

| **Name**     | **Type** | **Description**                                                                                                                                                |
| ------------ | -------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AddLiqParams | calldata | The parameters for adding liquidity to the position See [Params](https://docs.divergence-protocol.com/technical-reference/periphery/params#AddLiquidityParams) |

**Returns:**

| **Name**  | **Type** | **Description**                                          |
| --------- | -------- | -------------------------------------------------------- |
| tokenId   | uint256  | The ID of the NFT that represents the liquidity position |
| liquidity | uint128  | The amount of liquidity for this position                |

## updateInsideLast

Updates the growth of fees and token deltas as of the last action on the individual position

```javascript
function updateInsideLast(PositionInfo memory pb, Position storage pm) private 
```

**Params:**

| **Name** | **Type**     | **Description**               |
| -------- | ------------ | ----------------------------- |
| pb       | PositionInfo | The position info struct      |
| pm       | Position     | The position owed info struct |

## removeLiquidity

Removes liquidity from the pool, given the tokenId of a position. Only to be called once by the liquidity provider.

```javascript
function removeLiquidity(uint256 tokenId)
    external
    override
    isAuthorizedForToken(tokenId)
    returns (uint256 collateral, uint256 spear, uint256 shield, uint256 spearObligation, uint256 shieldObligation)
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT that represents the liquidity position |

**Returns:**

| **Name**         | **Type** | **Description**                                                                             |
| ---------------- | -------- | ------------------------------------------------------------------------------------------- |
| collateral       | uint256  | The amount of collateral to be received by the liquidity provider                           |
| spear            | uint256  | The amount of Spear to be received by the liquidity provider                                |
| shield           | uint256  | The amount of Shield to be received by the liquidity provider                               |
| spearObligation  | uint256  | The obligatory reserve of collateral amount for settling Spear tokens sold by the position  |
| shieldObligation | uint256  | The obligatory reserve of collateral amount for settling shield tokens sold by the position |

## getObligation

Calculates the obligatory reserve of collateral amounts for settling sold Spear and Shield amounts, and the remaining collateral/Spear/Shield token amounts receivable for a given position.

```javascript
function getObligation(Position memory pm)
    private
    pure
    returns (uint256 collateral, uint256 spear, uint256 shield, uint256 spearObligation, uint256 shieldObligation)
```

**Params:**

| **Name** | **Type** | **Description**                                                                         |
| -------- | -------- | --------------------------------------------------------------------------------------- |
| pm       | Position | The position for which to calculate the obligation amounts and receivable token amounts |

**Returns:**

| **Name**         | **Type** | **Description**                                                                                             |
| ---------------- | -------- | ----------------------------------------------------------------------------------------------------------- |
| collateral       | uint256  | The amount of collateral that can be received by the liquidity provider                                     |
| spear            | uint256  | The remaining Spear amount that can be received by the liquidity provider, after adjusting for obligations  |
| shield           | uint256  | The remaining shield amount that can be received by the liquidity provider, after adjusting for obligations |
| spearObligation  | uint256  | The obligatory reserve of collateral amount for settling Spear tokens sold by the position                  |
| shieldObligation | uint256  | The obligatory reserve of collateral amount for settling Shield tokens sold by the position                 |

## withdrawObligation

Returns the amount of collateral reserved for options that settle out-of-money. Can be called once after expiry by the liquidity provider and must be called after liquidity has been removed.

```javascript
function withdrawObligation(uint256 tokenId) external override isAuthorizedForToken(tokenId)
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT that represents the liquidity position |

## redeemObligation

Returns the amount of collateral reserved for the liquidity providers' open short interest in call or put options, after the pool receives the equavalent amount of call or put option tokens. Can be called once before expiry and must be called when liquidity has been removed.

```javascript
function redeemObligation(uint256 tokenId) external override isAuthorizedForToken(tokenId)
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT that represents the liquidity position |

## trade

Calls the battle contract to execute a trade

```javascript
function trade(TradeParams calldata p) external override returns (uint256 amountIn, uint256 amountOut, uint256 amountFee)
```

**Params:**

| **Name** | **Type**    | **Description**                                                                                                                          |
| -------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------- |
| p        | TradeParams | Params required to complete a trade. See [Params](https://docs.divergence-protocol.com/technical-reference/periphery/params#tradeparams) |

**Returns:**

| **Name**  | **Type** | **Description**                                                                                |
| --------- | -------- | ---------------------------------------------------------------------------------------------- |
| amountIn  | uint256  | The collateral amount to be swapped in based on the direction of the swap                      |
| amountOut | uint256  | The amount to be received, of either Spear or Shield token, based on the direction of the swap |
| amountFee | uint256  | The amount of fee in collateral token to be spent for the trade                                |

## tradeCallback

Called to msg.sender after executing a swap via Manager.

```javascript
function tradeCallback(uint256 cAmount, uint256 sAmount, bytes calldata _data) external override 
```

**Params:**

| **Name** | **Type** | **Description**                                        |
| -------- | -------- | ------------------------------------------------------ |
| cAmount  | uint256  | The amount of collateral transferred in the trade      |
| sAmount  | uint256  | The amount of Spear or Shield transferred in the trade |
| \_data   | bytes    | Data passed through by the caller                      |

## positions

Retrieves the position data for the given TokenId

```javascript
function positions(uint256 tokenId) external view override returns (Position memory)
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT that represents the liquidity position |

**Returns:**

| **Type** | **Description**   |
| -------- | ----------------- |
| Position | The position data |

## handlePosition

Retrieves and updates the position data

```javascript
function handlePosition(uint256 tokenId) private view returns (Position memory p) 
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT that represents the liquidity position |

**Returns:**

| **Name** | **Type** | **Description**   |
| -------- | -------- | ----------------- |
| p        | Position | The position data |

## accountPositions

Retrieves all the positions associated with an account

```javascript
function accountPositions(address account) external view override returns (Position[] memory)
```

**Params:**

| **Name** | **Type** | **Description**                                                |
| -------- | -------- | -------------------------------------------------------------- |
| account  | address  | The address of the account for which to retrieve the positions |

**Returns:**

| **Name** | **Type** | **Description**                    |
| -------- | -------- | ---------------------------------- |
| p        | Position | The positions owned by the account |


# Base

Facilitators of core and periphery contracts.

## BattleInitializer

### createAndInitializeBattle

```javascript
function createAndInitializeBattle(CreateAndInitBattleParams memory params)  external  override  returns  (address battle)  
```

**Params:**

| **Name** | **Type**                  | **Description**                                                                                                                                                    |
| -------- | ------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| params   | CreateAndInitBattleParams | Parameters for creating and initializing a pool. See [Params](https://docs.divergence-protocol.com/technical-reference/periphery/params#createandinitbattleparams) |

**Returns:**

| **Name** | **Type** | **Description**                            |
| -------- | -------- | ------------------------------------------ |
| battle   | address  | The address of the created battle contract |

## LiquidityManagement

### mintCallback

Called to msg.sender after minting liquidity to a position

```javascript
function mintCallback(uint256 amountOwed,  bytes  calldata data)  external  override  
```

**Params:**

| **Name**   | **Type** | **Description**                                    |
| ---------- | -------- | -------------------------------------------------- |
| amountOwed | uint256  | The amount of tokens owed for the minted liquidity |
| data       | bytes    | Any data passed through by the caller              |

### \_addLiquidity

Add liquidity to an initialized pool

```javascript
function _addLiquidity(AddLiqParams memory params) internal returns (uint128 liquidityAmount, address battleAddr)
```

**Params:**

| **Name**     | **Type** | **Description**                                                                                                                                  |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| AddLiqParams | params   | Params required for adding liquidity. See [Params](https://docs.divergence-protocol.com/technical-reference/periphery/params#addliquidityparams) |

**Returns:**

| **Name**        | **Type** | **Description**                             |
| --------------- | -------- | ------------------------------------------- |
| liquidityAmount | uint128  | The amount of liquidity to add              |
| battleAddr      | address  | The address to which an AMM pool is created |

## PeripheryPayments

### pay

Handles the payment of tokens or ETH from one address to another

```javascript
function pay(address tokenAddr,  address payer,  address recipient,  uint256 value)  internal  
```

**Params:**

| **Name**  | **Type** | **Description**                            |
| --------- | -------- | ------------------------------------------ |
| tokenAddr | address  | The address of the token to pay            |
| payer     | address  | The account that should pay the tokens     |
| recipient | address  | The account that should receive the tokens |
| value     | uint256  | The amount to pay                          |


# Interface

## IWETH9

### deposit

Deposit ether to get wrapped ether

```javascript
function deposit()  external  payable
```

### withdraw

Withdraw wrapped ether to get ether

```javascript
function withdraw(uint256 amount)  external
```

**Params:**

| **Name** | **Type** | **Description**                         |
| -------- | -------- | --------------------------------------- |
| amount   | uint256  | Amount of wrapped ether to be withdrawn |

## IBattleInitializer

### createAndInitializeBattle

Creates and initializes a battle contract

```javascript
function createAndInitializeBattle(CreateAndInitBattleParams memory params)  external  returns  (address battle);
```

**Params:**

| **Name**                  | **Type** | **Description**                                                                                                                                                    |
| ------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| CreateAndInitBattleParams | params   | Parameters for creating and initializing a pool. See [Params](https://docs.divergence-protocol.com/technical-reference/periphery/params#createandinitbattleparams) |

**Returns:**

| **Name** | **Type** | **Description**                            |
| -------- | -------- | ------------------------------------------ |
| battle   | address  | The address of the created battle contract |

## IManagerActions

### addLiquidity

Adds liquidity to the protocol.

```javascript
function addLiquidity(AddLiqParams calldata params) external returns (uint256 tokenId, uint128 liquidity)
```

**Params:**

| **Name**     | **Type** | **Description**                                                                                                                                                                |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| AddLiqParams | params   | The params necessary to add liquidity, encoded as AddLiqParams in calldata. See [Params](https://docs.divergence-protocol.com/technical-reference/periphery/params#mintparams) |

**Returns:**

| **Name**  | **Type** | **Description**               |
| --------- | -------- | ----------------------------- |
| tokenId   | uint256  | The ID of the NFT             |
| liquidity | uint128  | The amount of added liquidity |

### removeLiquidity

Removes liquidity from the pool, given the tokenId of a position. Only to be called once by the liquidity provider.

```javascript
function removeLiquidity(uint256 tokenId) external
returns (uint256 collateral, uint256 spear, uint256 shield, uint256 spearObligation, uint256 shieldObligation);
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT that represents the liquidity position |

**Returns:**

| **Name**         | **Type** | **Description**                                                                             |
| ---------------- | -------- | ------------------------------------------------------------------------------------------- |
| collateral       | uint256  | The amount of collateral to be received by the liqudity provider                            |
| spear            | uint256  | The amount of Spear to be received by the liquidity provider                                |
| shield           | uint256  | The amount of Shield to be received by the liquidity provider                               |
| spearObligation  | uint256  | The obligatory reserve of collateral amount for settling Spear tokens sold by the position  |
| shieldObligation | uint256  | The obligatory reserve of collateral amount for settling shield tokens sold by the position |

### withdrawObligation

Calculates the obligatory reserve of collateral amounts for settling sold Spear and Shield amounts, and the remaining collateral/Spear/Shield token amounts receivable for a given position.

```javascript
function withdrawObligation(uint256 tokenId) external;
```

**Params:**

| **Name** | **Type** | **Description**                                       |
| -------- | -------- | ----------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT representing the liquidity position |

### redeemObligation

Returns the amount of collateral reserved for the liquidity providers' open short interest. The LP gets one collateral for sending one Spear or Shield token back to the pool to close the net amount of short options exposure.Can be called once before expiry by the LP and must be called after liquidity has been removed.

```javascript
function redeemObligation(uint256 tokenId) external
```

**Params:**

| **Name** | **Type** | **Description**                                       |
| -------- | -------- | ----------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT representing the liquidity position |

## IManagerTrade

### trade

Calls the battle contract to execute a trade

```javascript
function trade(TradeParams calldata mtp) external returns (uint256, uint256, uint256)
```

**Params:**

| **Name** | **Type**    | **Description**             |
| -------- | ----------- | --------------------------- |
| mtp      | TradeParams | The parameters of the trade |

**Returns:**

| **Type** | **Description**                                                     |
| -------- | ------------------------------------------------------------------- |
| uint256  | Amount of collateral token input spent to be spent for the trade    |
| uint256  | Amount of Spear or Shield token output to be received for the trade |
| uint256  | The amount of fee in collateral token to be spent for the trade     |

## IManagerState

Returns information about positions held by accounts

### positions

Returns position details belonging to a NFT

```javascript
function positions(uint256 tokenId) external view returns (Position memory);
```

**Params:**

| **Name** | **Type** | **Description**   |
| -------- | -------- | ----------------- |
| tokenId  | uint256  | The ID of the NFT |

**Returns:**

| **Name** | **Type** | **Description**  |
| -------- | -------- | ---------------- |
| Position | memory   | Position details |

### nextId

Returns the next token ID for an NFT to be created

```javascript
function nextId() external view returns (uint256)
```

**Returns:**

| **Type** | **Description**              |
| -------- | ---------------------------- |
| uint256  | The next token ID for an NFT |

## IPeripheryImmutableState

Functions that return immutable state of the router

### arena

Returns the address of the arena contract

```javascript
function arena()  external  view  returns  (address)
```

**Returns:**

| **Name** | **Type** | **Description**                    |
| -------- | -------- | ---------------------------------- |
| arena    | address  | The address for the arena contract |

### WETH9

Returns the address of the wrapped ether

```javascript
function WETH9()  external  view  returns  (address)
```

**Returns:**

| **Name** | **Type** | **Description**       |
| -------- | -------- | --------------------- |
| WETH9    | address  | The address for WETH9 |

## IQuoter

### accountPositions

Returns all the position details belonging to an account

```javascript
function accountPositions(address account) external view returns (Position[] memory)
```

**Params:**

| **Name** | **Type** | **Description**     |
| -------- | -------- | ------------------- |
| account  | address  | The account address |

**Returns:**

| **Name** | **Type** | **Description**  |
| -------- | -------- | ---------------- |
| Position | memory   | Position details |

### quoteExactInput

Returns the amount of collateral input and options token output for the given parameters

```javascript
function quoteExactInput(BattleTradeParams memory params, address battleAddr) external returns (uint256 spend, uint256 get)
```

**Params:**

| **Name**          | **Type** | **Description**                               |
| ----------------- | -------- | --------------------------------------------- |
| BattleTradeParams | params   | The params for the trade function of a battle |
| battleAddr        | address  | The address for a battle                      |

**Returns:**

| **Name** | **Type** | **Description**                                                     |
| -------- | -------- | ------------------------------------------------------------------- |
| spend    | uint256  | Amount of collateral token input spent to be spent for the trade    |
| get      | uint256  | Amount of Spear or Shield token output to be received for the trade |


# Quoter

Gets the expected token deltas without executing a swap or providing liquidity. Returns position information for liquidity providers.

### tradeCallback

Callback function that handles the result of a trade. It reverts with the trade amounts.

```javascript
function tradeCallback(uint256 cAmount, uint256 sAmount, bytes calldata data) external pure override 
```

**Params:**

| **Name** | **Type** | **Description**                                                     |
| -------- | -------- | ------------------------------------------------------------------- |
| cAmount  | uint256  | Amount of collateral token input spent to be spent for the trade    |
| sAmount  | uint256  | Amount of Spear or Shield token output to be received for the trade |
| data     | bytes    | Data passed through by the caller                                   |

### parseRevertReason

Parses a revert reason that should contain the numeric quote

```javascript
function parseRevertReason(bytes memory reason) private pure returns (uint256, uint256)  
```

**Params:**

| **Name** | **Type** | **Description**         |
| -------- | -------- | ----------------------- |
| reason   | bytes    | The revert reason bytes |

**Returns:**

| **Type** | **Description**         |
| -------- | ----------------------- |
| uint256  | The first parsed value  |
| uint256  | The second parsed value |

### quoteExactInput

Returns the amounts to spend or receive for a given exact input swap without executing the swap

```javascript
function quoteExactInput(BattleTradeParams memory params, address battleAddr) public returns (uint256 spend, uint256 get) 
```

**Params:**

| **Name**          | **Type** | **Description**                                                                                                                     |
| ----------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------- |
| BattleTradeParams | memory   | Parameters for a trade action. See [Params](https://docs.divergence-protocol.com/technical-reference/core/params#battletradeparams) |
| battleAddr        | address  | The address of the battle contract                                                                                                  |

**Returns:**

| **Name** | **Type** | **Description**                          |
| -------- | -------- | ---------------------------------------- |
| spend    | uint256  | The amount of collateral to spend        |
| get      | uint256  | The amount of Spear or shield to receive |

### getSTokenByLiquidity

Calculates the amount of Spear or shield tokens based on the given liquidity

```javascript
function getSTokenByLiquidity(AddLiqParams calldata params) external view returns (uint256)
```

**Params:**

| **Name**     | **Type** | **Description**                                                                                                                                  |
| ------------ | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |
| AddLiqParams | params   | Params required for adding liquidity. See [Params](https://docs.divergence-protocol.com/technical-reference/periphery/params#addliquidityparams) |

**Returns:**

| **Name** | **Type** | **Description**                                                             |
| -------- | -------- | --------------------------------------------------------------------------- |
| SToken   | uint256  | The amount of Spear or Shield token calculated based on the given liquidity |

### getSTokenByLiquidityWhenCreate

Calculates the amount of Spear or shield tokens based on the given amount of seed collateral when a liquidity position is created

```javascript
function getSTokenByLiquidityWhenCreate(uint160 sqrtPriceX96, int24 tickLower, int24 tickUpper, uint256 amount) public pure returns (uint256)
```

**Params:**

| **Name**     | **Type** | **Description**                                               |
| ------------ | -------- | ------------------------------------------------------------- |
| sqrtPriceX96 | uint160  | The current sqrt price                                        |
| tickLower    | int24    | The lower tick boundary of the position                       |
| tickUpper    | int24    | The upper tick boundary of the position                       |
| amount       | uint256  | The seed collateral amount for minting the liquidity position |

**Returns:**

| **Type** | **Description**                                                             |
| -------- | --------------------------------------------------------------------------- |
| uint256  | The amount of Spear or Shield token calculated based on the given liquidity |

### positions

Gets the position information for the given token ID

```javascript
function positions(uint256 tokenId) external view override returns (Position memory)
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT that represents the liquidity position |

**Returns:**

| **Type** | **Description**   |
| -------- | ----------------- |
| Position | The position data |

### handlePosition

Gets the position information for the given token ID

```javascript
function handlePosition(uint256 tokenId) private view returns (Position memory p)
```

**Params:**

| **Name** | **Type** | **Description**                                          |
| -------- | -------- | -------------------------------------------------------- |
| tokenId  | uint256  | The ID of the NFT that represents the liquidity position |

**Returns:**

| **Type** | **Description**   |
| -------- | ----------------- |
| Position | The position data |

### accountPositions

Gets the positions for the given account

```javascript
function accountPositions(address account) external view override returns (Position[] memory)
```

**Params:**

| **Name** | **Type** | **Description**     |
| -------- | -------- | ------------------- |
| account  | address  | The account address |

**Returns:**

| **Name** | **Type** | **Description**  |
| -------- | -------- | ---------------- |
| Position | memory   | Position details |


# Libraries

Functionalities used by other contracts

### DiverLiquidityAmounts

#### getLiquidityFromCs

Computes the amount of liquidity to be received by the pool, for a given amount of collateral and price range

```javascript
function getLiquidityFromCs(
        uint160 sqrtRatioX96,
        uint160 sqrtRatioAX96,
        uint160 sqrtRatioBX96,
        uint256 amount
    )
        internal
        pure
        returns (uint128 liquidity)
```

**Params:**

| **Name**      | **Type** | **Description**                                               |
| ------------- | -------- | ------------------------------------------------------------- |
| sqrtRatioX96  | uint160  | The current square root ratio                                 |
| sqrtRatioAX96 | uint160  | A sqrt ratio                                                  |
| sqrtRatioBX96 | uint160  | Another sqrt ratio                                            |
| amount        | uint256  | The seed collateral amount for minting the liquidity position |

**Returns:**

| **Name**  | **Type** | **Description**                                    |
| --------- | -------- | -------------------------------------------------- |
| liquidity | uint128  | The amount of liquidity to be received by the pool |

#### getLiquidityFromSToken

Computes the amount of liquidity to be received by the pool, for a given amount of Spear or Shield tokens and price range

```javascript
function getLiquidityFromSToken(uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount) internal pure returns (uint128 liquidity)
```

**Params:**

| **Name**      | **Type** | **Description**                                                    |
| ------------- | -------- | ------------------------------------------------------------------ |
| sqrtRatioAX96 | uint160  | A sqrt ratio                                                       |
| sqrtRatioBX96 | uint160  | Another sqrt ratio                                                 |
| amount        | uint256  | The seed Spear or Shield amount for minting the liquidity position |

**Returns:**

| **Name**  | **Type** | **Description**                 |
| --------- | -------- | ------------------------------- |
| liquidity | uint128  | The calculated liquidity amount |

### CallbackValidation

Provides validation for callbacks from battle

#### verifyCallback

Verifies the arena address of the battle

```javascript
function verifyCallback(address arenaAddr, BattleKey memory battleKey) internal view
```

**Params:**

| **Name**  | **Type**  | **Description**                                     |
| --------- | --------- | --------------------------------------------------- |
| arenaAddr | address   | The address for the arena contract                  |
| battleKey | BattleKey | The battle Key containing a battle's specifications |


# Params

Parameters for functions contained in the periphery contracts:

## CreateAndInitBattleParams

The parameters for creating and initializing a battle

```javascript
struct CreateAndInitBattleParams {
    BattleKey bk;
    uint160 sqrtPriceX96;
}
```

**Params:**

| **Name**     | **Type**  | **Description**                                   |
| ------------ | --------- | ------------------------------------------------- |
| bk           | BattleKey | The battle key containing a pool's specifications |
| sqrtPriceX96 | uint160   | The starting sqrtPrice of the pool                |

## AddLiquidityParams

The parameters for adding liquidity to a battle

```javascript
struct AddLiqParams {
    BattleKey battleKey;
    address recipient;
    int24 tickLower;
    int24 tickUpper;
    LiquidityType liquidityType;
    uint128 amount;
    uint256 deadline;
}
```

**Params:**

| **Name**      | **Type**      | **Description**                                                                        |
| ------------- | ------------- | -------------------------------------------------------------------------------------- |
| battleKey     | BattleKey     | The battle key                                                                         |
| recipient     | address       | The address that receives the NFT                                                      |
| tickLower     | int24         | The lower tick of the position                                                         |
| tickUpper     | int24         | The upper tick of the position                                                         |
| liquidityType | LiquidityType | Specifies the type of liquidity seeded to the position is collateral, Spear, or Shield |
| amount        | uint128       | The amount of collateral, Spear or Shield to add                                       |
| deadline      | uint256       | The deadline of the transaction                                                        |

## TradeParams

Represents the parameters for a trade

```javascript
struct TradeParams {
    BattleKey battleKey;
    TradeType tradeType;
    uint256 amountSpecified;
    address recipient;
    uint256 amountOutMin;
    uint160 sqrtPriceLimitX96;
    uint256 deadline;
}
```

**Params:**

| **Name**          | **Type**  | **Description**                                                                  |
| ----------------- | --------- | -------------------------------------------------------------------------------- |
| battleKey         | BattleKey | The battle key                                                                   |
| tradeType         | TradeType | The trade type (buy Spear or buy Shield)                                         |
| amountSpecified   | uint256   | How much collateral input or SToken output amount to be swapped in/out           |
| recipient         | address   | The address to receive the output of the swap                                    |
| amountOutMin      | uint256   | The minimum amount of Spear or Shield output to receive                          |
| sqrtPriceLimitX96 | uint160   | The maximum/minimum Q64.96 sqrtPrice limit. When reached, the trade is completed |
| deadline          | uint256   | The deadline of the transaction                                                  |


# Types

## Position

Info struct containing the position in a battle

```javascript
struct Position {
    uint256 tokenId;
    address battleAddr;
    int24 tickLower;
    int24 tickUpper;
    uint128 liquidity;
    LiquidityType liquidityType;
    uint256 seed;
    GrowthX128 insideLast;
    Owed owed;
    PositionState state;
    uint256 spearObligation;
    uint256 shieldObligation;
}
```

**Params:**

| **Name**         | **Type**      | **Description**                                                                                                                  |
| ---------------- | ------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| tokenId          | uint256       | The token ID of the position                                                                                                     |
| battleAddr       | address       | The address of the battle                                                                                                        |
| tickLower        | int24         | The lower tick of the position                                                                                                   |
| tickUpper        | int24         | The upper tick of the position                                                                                                   |
| liquidity        | uint128       | The liquidity of the position                                                                                                    |
| liquidityType    | LiquidityType | Specifies the type of liquidity seeded to the position is collateral, Spear, or Shield                                           |
| seed             | uint256       | The token amount provided for the position, of the collateral, Spear or Shield liquidity type                                    |
| insideLast       | GrowthX128    | The [GrowthX128](https://docs.divergence-protocol.com/technical-reference/core/types#growthx128) info struct inside the position |
| owed             | Owed          | The [Owed](https://docs.divergence-protocol.com/technical-reference/core/types#owed) amounts accumulated by the position         |
| state            | PositionState | Record the state of the position liquidity or obligation                                                                         |
| spearObligation  | uint256       | The obligatory reserve of collateral amount for settling Spear tokens sold by the position                                       |
| shieldObligation | uint256       | The obligatory reserve of collateral amount for settling Shield tokens sold by the position                                      |


# Audit Reports

### [ChainSecurity](https://chainsecurity.com)

{% embed url="<https://chainsecurity.com/security-audit/divergence-protocol-v1c/>" %}

### [MixBytes](https://mixbytes.io)

{% embed url="<https://github.com/mixbytes/audits_public/tree/master/Divergence%20Protocol>" %}


# 🌝Tokenomics

DIVER serves as the utility token of the Divergence protocol. It is designed to incentivize protocol adoption and enhances community governance. It accrues value from the growth of the protocol:

#### 1️⃣Trading Fees

Of the options transaction [fees](/overview/protocol-basics/fees), 70% is distributed pro-rata to in-range liquidity providers, whereas the remaining 30% goes to the Divergence Protocol. &#x20;

#### 2️⃣Exercise Fees

Options that expire in the money offer a fixed payoff, and when traders go claim the proceeds, a fee will be charged. The option exercise fee will be used to cover the costs of third-party oracles, and other contingencies. &#x20;


# Token Distribution

The DIVER token has a total supply of 1,000,000,000, which is distributed as follows upon TGE:&#x20;

<table data-header-hidden><thead><tr><th width="341.9876601367536">Distribution Type</th><th width="232.39943208708">Amount</th><th>Percentage %</th></tr></thead><tbody><tr><td><strong>Distribution Type</strong></td><td><strong>Amount</strong></td><td><strong>Percentage %</strong></td></tr><tr><td>Seed Round ($0.018)</td><td>50,000,000</td><td>5.00</td></tr><tr><td>Private Round ($0.025)</td><td>80,000,000</td><td>8.00</td></tr><tr><td>Strategic Round ($0.035)</td><td>20,000,000</td><td>2.00</td></tr><tr><td>Public Launch (on Balancer)</td><td>15,571,703</td><td>1.56</td></tr><tr><td>Community Rewards</td><td>340,000,000</td><td>34.00</td></tr><tr><td>Reserves</td><td>214,428,297</td><td>21.44</td></tr><tr><td>Ecosystem Fund</td><td>100,000,000</td><td>10.00</td></tr><tr><td>Developers &#x26; Early Backers</td><td>150,000,000</td><td>15.00</td></tr><tr><td>Liquidity Provision Fund</td><td>30,000,000</td><td>3.00</td></tr><tr><td><strong>Total Supply</strong></td><td><strong>1,000,000,000</strong></td><td><strong>100.00</strong></td></tr></tbody></table>

## Seed Round Investors

Offering to lead investors and founders.&#x20;

* Total: 50,000,000
* Cost Basis: $0.018
* Released at TGE: 15%
* Remaining vested on a quarterly basis for 12 months&#x20;
* *Status: Fully Vested*&#x20;

## Private Round Investors

Offering to institutions, yield farmers, volatility trading firms, and accredited investors.&#x20;

* Total: 80,000,000
* Cost Basis: $0.025
* Released at TGE: 20%
* Remaining vested on a quarterly basis for 12 months&#x20;
* *Status: Fully Vested*&#x20;

## Strategic Round&#x20;

Offering to accredited investors and key opinion leaders.&#x20;

* Total: 20,000,000
* Cost Basis: $0.035
* Released at TGE: 20%
* Remaining vested on a quarterly basis for 12 months
* *Status: Fully Vested*&#x20;

## Public Launch (on Balancer)&#x20;

100% used to seed liquidity on various DEXs

* Total: 15,571,703
* Released at TGE: 100%
* *Status: Fully Vested*

## Community Rewards

Used for various community incentive/mining programs

* Total: 340,000,000
* Utilized per introduction of community incentive/mining programs
* Status: Non-circulating

## Ecosystem Fund

Used to foster strategic relationships with key ecosystem partners&#x20;

* Total: 100,000,000
* Released at TGE: 10%
* Remaining utilized when partnerships are established to support ecosystem growth
* Status:  Circulating

## Reserves

Reserved for future fundraising and other strategic purposes

* Total: 214,428,297
* Locked for the first 12 months following TGE
* 20% unlock at day 360, remaining vested on a quarterly basis for 12 months
* *Status: Fully Vested*&#x20;

## Developers & Early Backers

Offered as incentives for core team members and key project backers

* Total: 150,000,000
* Locked for the first 12 months following TGE
* 10% unlock at day 360, remaining vested on a monthly basis for 12 months
* *Status: Fully Vested*&#x20;

## Liquidity Provision Fund

Used to support market-making and liquidity provision purposes on different exchanges

* Total: 30,000,000
* Released at TGE: 1/2
* Remaining utilized for new exchange listing relationships
* Status: Circulating


# 🎃DIVΞR NFT Collections

The Year is 2030. The world lives underwater due to climate-induced flooding. Led by a mad scientist, **Chadoshi Dogamoto**, a group of mortals begin their battles against the volatile waters and the monsters within. Together they must protect their farmed yields and reduce carbon emissions. They call themselves **DIVΞRs.** &#x20;

[**https://opensea.io/collection/divergence-divers**](https://opensea.io/collection/divergence-divers)

### **Genesis DIVΞRs**

The genesis DIVΞRs are the first of their kind in the Diver-Gence universe, it includes **a total of 256 unique non-fungible DIVΞR tokens, which are distributed to 256 participants in our Sushiswap IDO.** The genesis DIVΞRs NFT are being graded by Chadoshi for their skill levels. Only those who are exceptional at diving are given the top grade. Among the 256 of them, there are 164 with Grade B, 82 with Grade A, and 10 with Grade A+.

<figure><img src="/files/5st49K1PWhlCQ6zXEfy9" alt=""><figcaption></figcaption></figure>

<figure><img src="/files/2wkHI1qneuMquG4LlYor" alt=""><figcaption></figcaption></figure>

### **DIVΞRs Armory**

To defend their farms, DIVΞRs use spears to hit carbon-emitting targets. These spears, according to the Divers Digest, were forged by Chadoshi’s personal armorer, Harambe-san, before his untimely death in the Squid Wars. Upon his death they were scattered throughout the remains of the upper world — buried and submerged within volcanoes, lakes, snowy peaks, and deep oceans, waiting for warriors to discover them.&#x20;

<figure><img src="/files/URgdGQc7SGNmlIeWoFvk" alt=""><figcaption></figcaption></figure>

Each DIVΞR Spear is uniquely forged and its four key components are made of different materials: 1) Handle — made of metal or wood; 2) Shaft — plain or color; 3) Spear tip — standard or trident shaped, or made of shell, whale tooth or shark tooth; 4) Inlay — Each spear is inlaid with either jewel — emerald, sapphire, ruby, amethyst — or stone. **The exception is the one unique golden spear, made entirely of gold.**


# Terms of Service

**Last Updated:** March 23, 2023

The following terms of service (the “**Terms**”) govern your access to and use of the Divergence website available at <https://www.divergence-protocol.com/> (the “**Website**”) and Divergence platform through the respective subdomains of the Website, such as <https://app.divergence-protocol.com/> (the “**Platform**”). The Terms constitute an agreement between you or the company or other legal entity you represent (“**You**”) and Tenet Technology Limited (“**Tenet**,” “**We**,” or “**Us**”), a company incorporated in Seychelles.

By accessing the Platform, connecting your digital wallet to the Platform, or by clicking the button “I accept”, you (“**You**”) acknowledge that you have read, accept without modifications and agree to be bound by these Terms and all terms incorporated herein by reference. If you do not accept or agree to these Terms, you are not allowed to access or use the Platform, and must immediately discontinue any use thereof.

**1.DIVERGENCE PLATFORM**

Divergence Platform is a web-based user interface to a decentralized autonomous smart-contract system implemented on the Ethereum blockchain that allows for creating/writing and trading particular on-chain derivative products called “Spear” and “Shield”.

“Spear” are virtual contracts that represent the right to claim 1 collateral from the smart contract if the price of an underlying asset rises to or above a pre-determined price at expiration; whereas “Shield” are virtual contracts that represent the right to claim 1 collateral from the smart contract if the price of an underlying asset falls below a pre-determined price at expiration.

It is acknowledged that the Protocol may be further implemented on other blockchain networks, accordingly, “Protocol”, as used herein, includes all and any such implementations and modifications thereto.

The Protocol is comprised of open-sourced smart contracts deployed on the blockchain that can be reviewed, verified, used, and accessed by anyone. You should carefully and thoroughly review and assess the Protocol before you use it, and any such use shall be at your own risk.

**2.USE OF SERVICES**

As a condition to accessing or using the Platform, you represent and warrant:

* If you are an individual, you must be of legal age in the jurisdiction in which you reside and you have the legal capacity to enter into these Terms.
* If you are on behalf of a legal entity, you represent and warrant that (i) such legal entity is duly organized and validly existing under the applicable laws of the jurisdiction of its organization; (ii) you are duly authorized by such legal entity to act on its behalf.
* You are not a Restricted Person or a resident of a Restricted Territory (each as defined below) and you will not be using the Platform for any illegal activity including but not limited to, those Prohibited Activities listed under Section “PROHIBITED ACTIVITY”.
* You may not use our services if you are incorporated or otherwise established in, or a citizen or resident where it would be illegal under applicable laws for you (by reason of your nationality, domicile, citizenship, residence or otherwise) to access or use our services (“Restricted Territories”), including but not limited to: The People's Republic of China (Mainland China), the United States of America, the United Kingdom, European Union, Canada, Australia, Burma, Cote D'Ivoire (Ivory Coast), Cuba, Democratic Republic of Congo, Iran, Iraq, Libya, Mali, Nicaragua, Democratic People’s Republic of Korea (North Korea), Somalia, Sudan, Syria, Yemen.
* You may not use our services if (i) you are a member of any sanctions list or equivalent maintained by the United States government, the United Kingdom government, the European Union (ii) you intend to transact with any Restricted Territories or Restricted Persons.
* You agree that you are solely and entirely responsible for compliance with all laws and regulations that may apply to you. You further agree that we have no obligation to inform you of any potential liabilities or violations of law or regulation that may arise in connection with your access and use of our service and that we are not liable in any respect for any failure by you to comply with any applicable laws or regulations.
* You do not, and will not use a virtual private network (e.g., a VPN) or other means to access or use the Platform to circumvent any restrictions apply to the Platform.

**3.OWNERSHIP OF DIGITAL ASSETS**

When using the Platform, you may connect your digital wallet using one of the compatible third-party software wallets. Software wallets constitute Third-Party Services and Tenet is not responsible for, does not endorse, shall not be held liable or responsible in connection with, and does not make any warranties, whether express or implied, as to the software digital wallets used by you with the Platform.

Tenet never receives access to or control over your digital wallets or digital assets held in such digital wallets. Therefore, you are solely responsible for securing your digital wallet and credentials thereto. And any digital assets used by you in connection with our services are either owned by you or that you are validly authorized to carry out transactions using such digital assets.

**4.MODIFICATION TO THESE TERMS**

We reserve the right, in our sole discretion, to modify these Terms from time to time. If we make changes, we will provide you with notice of such changes, such as by providing notice through the Services or updating the “Last Updated” date at the top of these Terms. Unless we state otherwise in our notice, all such modifications are effective immediately, and your continued use of the Platform will confirm the acceptance of such updated Terms. If you do not agree to any amended Terms, you must immediately discontinue any access to or use of the Platform.

**5.PROHIBITED ACTIVITY**

In connection with your use of our services, you will not:

* Violate or assist any party in violating any law, statute, ordinance, regulation or any rule of any self-regulatory or similar organization of which you are or are required to be a member through your use of our services;
* Provide false, inaccurate, incomplete or misleading information;
* Engage in any illegal activity, including without limitation illegal gambling, money laundering, fraud, blackmail, extortion, ransoming data, the financing of terrorism, other violent activities or any prohibited market practices;
* Distribute unsolicited or unauthorized advertising or promotional material, written media releases, public announcements and public disclosures, junk mail, spam or chain letters;
* Take any action that imposes an unreasonable or disproportionately large load on our infrastructure, or detrimentally interfere with, intercept, or expropriate any system, data or information;
* Transmit or upload any material to the Platform that contains viruses, Trojan horses, worms, or any other harmful or deleterious programs;
* Transfer any rights granted to you under these Terms;
* Engage in any other activity which, in our reasonable opinion, amounts to or may amount to market abuse including without limitation the carrying out of fictitious transactions or wash trades, front running or engaging in disorderly market conduct; or
* Engage in any behavior which is unlawful, violates these Terms, or is otherwise deemed unacceptable in its sole discretion.

**6.THIRD-PARTY SERVICES**

When using the Platform, you may view, use or interact with certain Third-Party Services. Tenet does not endorse or make any warranties, whether express or implied, with regard to the Third-Party Services, and shall not be responsible for or held liable in connection with any Third-Party Services, your use thereof or interaction therewith.

You hereby affirm and acknowledge that your use of Third-Party Services, and your interactions with third parties that are linked to or from the Platform, shall always be at your own risk. To the maximum extent permitted by the applicable law, in no event shall Tenet be responsible for or held liable in connection with any loss or damage of any sort incurred by you as the result of, or in connection with accessing or using any Third-Party Services.

**7.NO ADVICE**

No part of the information or content available on the Platform should be considered to be business, legal, financial, investment, or tax advice, or advice of a broker regarding any matters to which all or any part of such information relates. You should consult your own legal, financial, tax, or other professional advisors regarding this information. We shall not be responsible for the accuracy of the information and materials on the Platform, therefore any use of such information or materials is at your own discretion and risk and you are solely responsible for any possible damages or losses arising from such use.

Any decision to buy or sell digital assets through the Platform is the user’s decision and we will not be liable for any loss suffered. You accept the risk of trading digital assets. You represent that you have been, are, and will be solely responsible for making your own independent appraisal and investigations into the risks of the transaction and the underlying digital asset. You represent that you have sufficient knowledge, market sophistication, professional advice, and experience to make your own evaluation of the merits and risks of any transaction or any underlying digital asset.

**8.NO WARRANTY**

The Platform is provided on “as is” and “as available” basis, and your use of the Platform will always be at your own risk. Tenet makes no warranty of any kind, express or implied, including, but not limited to, the implied warranties of title, non-infringement, integration, merchantability, and fitness for a particular purpose, and any warranties implied by any course of performance or usage of trade, with respect to the Platform, all of which are expressly disclaimed.

Tenet does not warrant, whether expressly or impliedly, and expressly disclaims any warranty and/or representation that:

* the Platform will work as expected, or that any information provided through the Platform or in connection therewith will be timely, accurate, reliable, true or correct;
* the Platform will be secure, error-free or available at any particular time or place, or will continue working, operating or functioning for any period of time;
* any defects, flaws, bugs or errors in the Platform or Protocol will be corrected;
* the Platform will be supported, maintained, operated, managed, further developed, and not abandoned; or
* the Platform will be free of viruses, bugs, trojan horses, malfunctions, or other harmful components, or properly protected from hackers, malware, or other attacks.

**9.FEES AND PRICE ESTIMATES**

In connection with your use of our services, you are required to pay all fees necessary for interacting with the blockchain networks, including “gas” costs, as well as all other fees on the Platform at the time of your use. Although we attempt to provide accurate fee information, this information reflects our estimates of fees, which may vary from the actual fees paid to use the Platform and interact with the blockchain networks. Furthermore, when you conduct transactions through the Platform, certain Third-Party Costs may arise or be incurred by you. You shall bear any and all such Third-party Costs, whether associated with transactions that you carry out through the Platform or arising otherwise. Tenet shall not be responsible for any Third-Party Costs and shall not be in any way held liable in connection therewith.

&#x20;

**10.TAXES**

&#x20;It is your responsibility to determine what, if any, taxes apply to your activities on the Platform, and to collect, report, and remit the correct tax to the appropriate tax authority. Tenet is not responsible for determining whether taxes apply to your transaction, or for collecting, reporting, or remitting any taxes arising from any transaction.

**11.APPLICABLE LAW**

The interpretation and enforcement of these Terms and any dispute related will be governed by and construed under the laws of Seychelles, as applicable, without regard to conflict of law rules or principles that would cause the application of the laws of any other jurisdiction.

&#x20;

**12.LIMITATION OF LIABILITY**

You expressly understand and agree that Tenet will not be liable for any indirect, incidental, special, consequential, exemplary damages, or damages for loss of profits including without limitation damages for loss of goodwill, use, data, or other intangible losses, whether based on contract, tort, negligence, or otherwise, resulting from (i) the use or the inability to use the services; (ii) the cost of procurement of substitute goods and services resulting from any goods, data, information, or services purchased or obtained or messages received or transactions entered into through or from the services; (iii) unauthorized access to or alteration of your transmissions or data; or (iv) any other matter relating to the services.

In no event shall our aggregate liability (together with its affiliates, including its and its affiliates’ respective stockholders, members, directors, managers, officers, employees, attorneys, agents, representatives, suppliers, or contractors) arise out of or in connection with the Platform and the Services (and any of their content and functionality), any performance or nonperformance of the Services, your digital assets, positions, or any other product, service or other item provided by or on behalf of Tenet, whether under contract, tort (including negligence), civil liability, statute, strict liability or other theory of liability exceed the number of fees paid by you under these Terms, if any, in the twelve (12) month period immediately preceding the event giving rise to the claim for liability.

**13.INDEMNIFICATION**

You agree to indemnify and hold Tenet, its affiliates, and service providers, and each of their officers, directors, agents, joint venturers, employees, and representatives harmless from any claim or demand (including attorneys’ fees and any losses, fines, fees, or penalties imposed by any regulatory authority) arising out of your breach of these Terms, or your violation of any law or regulation. The term “losses” means all net costs reasonably incurred by us or the other persons referred to in this Section which are the result of the matters set out in this Section and which may relate to any claims, demands, causes of action, debt, cost, expense or other liability, including reasonable legal fees (without duplication).

**14.DISCLOSURE AND DISCLAIMER**

Tenet is a developer of open-source software. Tenet does not operate a derivatives exchange platform or offer trade execution or clearing services and therefore has no oversight, involvement, or control with respect to your transactions. All transactions on the Platform are executed peer-to-peer directly between the users’ digital wallets through a smart contract.

You are responsible for complying with all laws and regulations applicable to your transactions. You understand that Tenet is not registered or licensed by the U.S. Commodity Futures Trading Commission (“CFTC”), the U.S. Securities and Exchange Commission (“SEC”) or any financial regulatory authority. The Platform does not constitute advice or a recommendation concerning any commodity, security or other assets. The Tenet is not acting as an investment adviser or commodity trading adviser to any person.

You understand that Spear and Shield positions generated using the Platform are commodity contracts, they are shares or any equivalent in any existing or future public or private company, corporation or other entity in any jurisdiction. Tenet does not own or control the underlying software protocols that are used in connection with Spear and Shield positions. The underlying protocols are open source and anyone can use, copy, modify, and distribute them. Tenet is not responsible for the operation of the underlying protocols, and Tenet makes no guarantee of their functionality, security, or availability.

You acknowledge that your data on the Platform may become irretrievably lost or corrupted or temporarily unavailable due to a variety of causes, and agree that, to the maximum extent permitted under Applicable Law, we will not be liable for any loss or damage caused by denial-of-service attacks, software failures, viruses or other technologically harmful materials (including those which may infect your computer equipment), protocol changes by third-party providers, Internet outages, force majeure events or other disasters, scheduled or unscheduled maintenance, or other causes either within or outside our control.


# Risk Disclosure

THE RISK OF LOSS IN TRADING ON DIVERGENCE CAN BE SUBSTANTIAL. YOU SHOULD, THEREFORE, CAREFULLY CONSIDER WHETHER SUCH TRADING IS SUITABLE FOR YOU IN LIGHT OF YOUR CIRCUMSTANCES AND FINANCIAL RESOURCES. YOU SHOULD BE AWARE OF ALL THE POINTS CONTAINED WITHIN THIS RISK DISCLOSURE STATEMENT.

There are numerous risks associated not only with the derivatives tokens traded on Divergence but also with the smart contract system itself. You must ensure that you carefully read and understand this Risk Disclosure Statement, the specifications of the derivative tokens you may trade, including when they expire, and how the smart contract determines which tokens will be “in-the-money” at expiration, and all other relevant rules.&#x20;

1. **Digital options have a different pay-off structure compared to vanilla options.** The holder of the digital option will not receive any gain in excess of the fixed settlement amount of the option. A digital option is like a capped option in the sense that its maximum return is limited. Besides, the payout of a digital option is all or nothing. Accordingly, the holder may experience a relatively greater gain than the holder of a vanilla option when the option is in the money by a smart amount but a relatively small gain when the option is in the money by a greater amount.
2. **Digital options may be more difficult to hedge than vanilla options.** Because of the fixed settlement amount of a digital option, a user wishes to hedge the risk of an increase in the price of a specified quantity of cryptocurrencies, for example, cannot create a perfect hedge by buying a specified quantity of digital options that return a cash settlement amount if the settlement price of the underlying is above the current underlying price. Similarly, a user who writes a digital option on a specific cryptocurrency and wishes to hedge the obligation through ownership of the cryptocurrency would also not be able to do so precisely. &#x20;
3. **There may be times when certain derivative tokens on Divergence lack liquidity.** Certain derivative tokens on Divergence may lack liquidity for users to trade against, especially when derivative tokens approach expiry. There is a possibility that you are unable to liquidate a position that you no longer want to hold in the time frame. Additionally, there is also a chance that no one will offer to sell you a derivative token you want to take a position in due to current market conditions. If that occurs, you may be forced to hold them until they expire, possibly preventing you from hedging the risk to which you are exposed.
4. **Digital option prices may be more volatile than vanilla options prices as expiry approaches.** As expiration approaches, uncertainty regarding whether an option will be exercised will increase if the price of the underlying is very close to the strike price. In the context of digital options, such uncertainty imposes higher risks due to its all-or-nothing payoff. The seller of the option will still be obliged to pay the entire fixed settlement amount even if the option expires slightly in the money or at the money. Thus, binary options prices can be more volatile than vanilla options prices as the expiration date approaches and therefore involve more risk.&#x20;
5. **Holders and sellers of digital options may bear a heightened risk that they will be adversely affected by manipulative behavior in the markets.** Because a binary option that is in the money by even the smallest amount will pay the full fixed settlement amount, there may be incentives for holders or sellers of digital options that are at or near the money at expiration to attempt to influence the market in order to cause a series of options to expire either in or out of the money. While market manipulation is unlawful, there is no assurance that manipulation will not occur at all. If manipulation does occur, the settlement amount may be based on the manipulated price and there may be no adequate remedy available to users.&#x20;
6. **Activities of the platform are subject to various laws and regulations in the countries where it operates or intends to operate.** We might be obliged to obtain different licenses or other permissive documents in some or all jurisdictions where we intend to operate our business, therefore, our business in such jurisdictions shall always be subject to obtaining such licenses or permissive documents, if so directed by applicable laws. There is a risk that certain activities may be deemed in violation of any such law or regulation. Penalties for any such potential violation would be unknown. Additionally, changes in applicable laws or regulations or evolving interpretations of existing law could, in certain circumstances, result in increased compliance costs, which could affect our ability to carry on the business model and develop the platform.&#x20;
7. **Smart contracts may be subjected to exploits.** Although we make reasonable efforts to ensure that the smart contracts of the platform follow the high-security standard, there is no assurance they are fully secure and safe against potential exploits or abuse due to flaws in programming or source code. Any of the above may lead to partial or complete theft or loss of digital assets used in transactions carried out on the platform.&#x20;
8. **Oracles may not provide an accurate settlement price feed.** Digital options traded on the platform are settled per settlement price sourced from decentralized oracles such as ChainLink. While oracles pull data from multiple sources that have no communication in between and utilize an array of external sources to send data to the smart contract to boost the reliability and credibility of the information being provided, there's no assurance the data are completely off manipulation or unflawed.&#x20;
9. **Third-party service providers may be down or malfunction.** Divergence will provide users with information from Third Party Service Providers (“TPSP”) that relates to the digital options traded on the platform. Such information includes, but is not limited to, website links, options data, and any other information provided on the website ("Service"). Divergence does not endorse, warrant, or guarantee the reliability of the service provided by TPSP, nor does Divergence represent that the system is fully protected from derivative fishing, malware, or other malicious attacks, that may have a material adverse effect on the operation of the platform, or may lead to losses and damages for you.&#x20;


# 🔗Official Links

😬 Website - <https://www.divergence-protocol.com/>

🤖 Github - <https://github.com/DivergenceProtocol>

📘 Blog - <https://medium.com/divergence-protocol>&#x20;

🐦Twitter - <https://twitter.com/divergencedefi>&#x20;

🥂 Telegram (community) - <https://t.me/divergenceprotocol>&#x20;

📣Telegram (announcements) - <https://t.me/divergenceannouncement>

📺 Youtube Channel - <https://www.youtube.com/DivergenceProtocol>

**DIVER Token Contract (Ethereum Mainnet)**

{% embed url="<https://etherscan.io/token/0xfb782396c9b20e564a64896181c7ac8d8979d5f4>" %}

**DIVER Token Contract (Arbitrum One)**

{% embed url="<https://arbiscan.io/token/0x5acab15fe93127f550b17eacdf529bc7d3b57e2e>" %}

**DIVER Token Contract (Base)**

{% embed url="<https://basescan.org/address/0x81949bd04fa0eef0239aa7f8caeb72bbc15bf3ae>" %}

**DIVER-ETH Pool (Uniswap V3 Ethereum)**

{% embed url="<https://info.uniswap.org/#/pools/0xb5851eb5ec92afff01840b90ed3bea51a77b3cc6>" %}

**DEX Screener**

{% embed url="<https://dexscreener.com/ethereum/0xb5851eb5ec92afff01840b90ed3bea51a77b3cc6>" %}

**DEX Tools**

{% embed url="<https://www.dextools.io/app/cn/ether/pair-explorer/0xb5851eb5ec92afff01840b90ed3bea51a77b3cc6>" %}

**CoinGecko**

{% embed url="<https://www.coingecko.com/en/coins/divergence-protocol?locale=en>" %}


# 🙌Media Kit

DIVER Lazer Eyez:&#x20;

<https://drive.google.com/drive/folders/160SEQZtnUVYNucgmMw6nWup0uASRcvhv?usp=sharing>

Divergence Logo:

<https://drive.google.com/drive/folders/1V6BKlvmGhfIoTPbtdQ1ssNQ2ACTh45IS?usp=sharing>

Spear & Shield:&#x20;

<https://drive.google.com/drive/folders/1GVgRTGuJFj-1eK5d-THQVxto_UlA6ae1?usp=sharing>


# 🚢Ditanic Test Coins

To experiment with protocol functionality in the live environment, anyone can easily mint Ditanic tokens to use as collateral for options.

The Ditanic coins are for testing only, and their value inevitably sinks to the bottom.  The Ditanics used in some community events are minted with event-specific contracts.   &#x20;

To get some Ditanics, please head over to:

{% embed url="<https://arbiscan.io/address/0x8C2F032c62A59743aAE9B4925f72Ad06ffc4B498#writeContract>" %}

<figure><img src="/files/wXMzKm83cwFALT9wwx2W" alt=""><figcaption></figcaption></figure>

Click "Connect to Web3" to connect your wallet. Then click "Write" and confirm the minting of 10,000 Ditanic tokens to your wallet address.


