# Welcome

Welcome to the DIVA Protocol docs

## Getting started

{% hint style="info" %}
Note that this gitbook is currently under construction. Content and structure is subject to change.
{% endhint %}

### DIVA Protocol

* [Website](https://docs.divaprotocol.io/www.divaprotocol.io)
* [Mainnet announcement](https://www.divaprotocol.io/posts/diva-mainnet-launch)
* [Pitch deck](https://drive.google.com/file/d/1x9tw3n-Ki1gicOhnxn0pL4p33uvW3Bly/view?usp=sharing) (last updated: 29 May 2023)
* [Github](https://github.com/divaprotocol/diva-protocol-v1)
* [Smart contract docs](https://github.com/divaprotocol/diva-protocol-v1/blob/main/DOCUMENTATION.md)

### Socials

* [Discord](https://discord.gg/8fAvUspmv3)
* [Twitter](https://twitter.com/divaprotocol_io)
* [YouTube](https://www.youtube.com/@diva_protocol)
* [Blog](https://www.divaprotocol.io/posts)

### Oracle adapters

* [Tellor](https://github.com/divaprotocol/oracles/blob/main/docs/Tellor.md)
* ... more to come

### Apps

* [DIVA App](https://app.diva.finance/): An OTC marketplace for creating, trading and settling derivative contracts peer-to-peer, powered by DIVA Protocol, [0x Protocol](https://0x.org/) and [Tellor Protocol](https://tellor.io/)
* [DIVA Donate](https://www.divadonate.xyz/): A conditional donation platform, powered by DIVA Protocol
* [DIVA Viz](https://divaviz.com/): An app to visualize derivative product offers and share on Twitter
* ... more to come

DIVA Protocol makes it easy to create novel derivative financial applications with basic web2/web3 programming skills. Embrace the future of finance and start building your own application on DIVA Protocol today. Check out the [project ideas](https://docs.divaprotocol.io/for-developers/project-ideas) section for ideas or reach out in our 👷[Builders channel on Discord](https://discord.gg/hZsvp5FTmN). The best apps will be published in DIVA Protocol's [dApp Store](https://www.divaprotocol.io/dapps).


# Derivative contracts

Understanding the essence of DIVA Protocol

To understand DIVA Protocol, it is essential to first understand what a derivative contract is. A derivative contract is an agreement between two parties that specifies under which conditions payments shall occur. To participate, each party must deposit a specific amount of money. The payout is *derived* (hence the term "derivative") from the outcome of a pre-agreed future event based on a pre-defined payoff function.

The key elements of a derivative contract are illustrated below:

<figure><img src="/files/1YwImDdQlvjIyw4oBKTY" alt=""><figcaption><p>Key elements of a derivative contract</p></figcaption></figure>

Derivatives are widely used for speculation and hedging purposes.

### **Examples**

* **Bet/prediction:** The most basic example of a derivative contract is a bet/prediction. Alice and Bob each contribute $100 to a pool and agree that the total amount of $200 will be distributed based on the outcome of a tennis match between player A and player B. If player A wins, Alice will claim the entire pool while Bob receives nothing. Conversely, if player B wins, Bob will claim the entire pool, while Alice receives nothing.&#x20;
* **Insurance:** Another example of a derivative contract is an insurance agreement. Bob pays $100 in order to receive a payout of $1000 in the event that his house burns down. That is, the insurance company is effectively contributing $900 to the pool. If no fire occurs, the insurance company keeps the full $1000, and Bob does not receive any payout.

Many other financial instruments, including options, swaps, and futures, operate based on the same fundamental principle.

### Derivative positions

Each party's position in a derivative contract is referred to as a derivative position or simply derivative. Each derivative position is associated with a payoff function which assigns a specific value to each possible outcome of the future event. The two payoff functions associated with a derivative contract follow a zero-sum principle, meaning that one party's gain is the other party's loss.

The position that is benefiting from an <mark style="color:green;">**increase in the underlying**</mark> is referred to as the <mark style="color:green;">**long position**</mark>. The position that is benefiting from a <mark style="color:red;">**decrease in the underlying**</mark> is referred to as the <mark style="color:red;">**short position**</mark>.

### Payoff functions

The payoff function can take any form or shape. In our previous example, the payoffs for Alice and Bob can be depicted as two directionally reversed binary functions, where a reported outcome of 1 or higher corresponds to a win for player A and a value less than 1 indicates a win for player B:

<figure><img src="/files/EiokIUk8kPNnfNv796yQ" alt=""><figcaption><p>Payoff profiles associated with Alice's and Bob's derivative positions</p></figcaption></figure>

Another example could include using a linear function within a predefined range for non-binary underlyings such as the price of Bitcoin, as depicted below:

<figure><img src="/files/Ztd9Cq2L2ZXl6GmH6DCe" alt=""><figcaption><p>Linear payoff example</p></figcaption></figure>

Note that the two payoff functions are typically capped as the amount deposited into the derivative contract is capped.

One of the DIVA Protocol's distinctive features is its ability to tailor a derivative contract's underlying payoff profile, accommodating various slopes, barriers, and ranges.


# What is DIVA Protocol

A permissionless protocol for creating derivative contracts peer-to-peer

DIVA Protocol is the first truly universal smart contract-based system for creating and managing derivative financial contracts peer-to-peer. It provides a platform for developers to build a wide range of derivative financial applications, including structured products, insurance, prediction markets, conditional donations, swaps, bets, and more, all in a fully permissionless way without involving a central intermediary.

### What are the unique features of DIVA Protocol?

DIVA Protocol distinguishes itself from peers like Augur, Polymarket, and Opyn in several key ways:

* **⚙️High customization:** DIVA Protocol offers unmatched customization, allowing users to select virtually any metric as the underlying and choose from a wide range of payoff profiles. With its flexibility to accommodate various slopes, barriers, and ranges, DIVA Protocol is especially well-suited for application in structured products.
* **☂️Compliance layer:** DIVA Protocol is one of the first DeFi protocols that implements a compliance feature to enable traditional financial institutions to use DIVA Protocol while complying with existing KYC and AML regulations.
* **⛽Gas optimized:** DIVA Protocol implements an efficient off-chain matching mechanism with an on-chain settlement process leveraging the EIP712 signature standard, thereby optimizing gas usage by creating the derivative contract on-chain only when a counterparty is found.
* **🧩Composable:** DIVA Protocol harnesses the true power of decentralized finance by prioritizing composability. Developers can seamlessly combine DIVA Protocol with any oracle and trading infrastructure when building end-user applications.

An overview of products that can be powered by DIVA Protocol is provided below:

![Example products that can be powered by DIVA Protocol](/files/UTzdYJvTsxqAck7Z1w6C)


# What problem does it solve

Eliminating the need for a central intermediary in derivative contracts

The traditional way of creating and managing derivative products relies on centralized intermediaries. This introduces three main problems:

1. **Counterparty risk:** User funds are at risk if the intermediary defaults or becomes insolvent.
2. **Entry barriers:** The creation and management of derivative products is typically reserved for banks and not easily accessible for normal individuals, hence hampering innovation.
3. **Isolated systems & markets:** The derivative products are issued in isolated systems which means assets are typically not tradeable outside of the issuer's infrastructure, hence negatively impacting liquidity.

### How does it solve these problems?

DIVA Protocol leverages the smart contract technology to provide a secure, open and interoperable system for creating and managing derivative contracts without the need for a central intermediary. This is accomplished through:

* **Full collateralization:** By requiring full collateralization of the derivative positions, counterparty risk and the need for margin calls are eliminated, giving users a safe and frictionless experience.
* **Blockchain:** DIVA Protocol embraces the power of public and permissionless blockchain networks to remove entry barriers and foster inclusivity.
* **Standardization:** Derivatives issued on DIVA Protocol follow the widely adopted ERC20 token standard, which enables the seamlessly integration into any centralized or decentralized trading infrastructure, thereby enhancing liquidity by unlocking new trading opportunities.


# How it works

Leveraging smart contracts to enable peer-to-peer derivative contracts

DIVA Protocol acts as a **programmatic escrow** that receives and securely holds funds from users participating in a derivative contract and releases them based on the outcome of a pre-agreed future event, reported by an [oracle ](/introduction/what-is-diva-protocol/how-it-works/oracles)following expiration.

Upon depositing funds, participants receive ERC20 tokens, referred to as **long and short positions**. These tokens represent **contingent claims** against the funds held in the programmatic escrow, also referred to as the "contingent pool" or simply "pool". Through these positions, each party is exposed to either the <mark style="color:green;">upside</mark> (via the <mark style="color:green;">long</mark> position) or the <mark style="color:red;">downside</mark> (via the <mark style="color:red;">short</mark> position) of the underlying metric.&#x20;

The **payoffs of long and short positions are zero-sum** meaning that for every unit of collateral that the long position may gain, the short position will lose and vice versa. By holding both the short and long position tokens, users are fully hedged, representing a claim against the deposited funds.


# Reference assets

Choose any metric as underlying for your derivative contracts

With DIVA Protocol, users can select virtually any metric, also referred to as "reference asset", to serve as the underlying for their derivative contracts. This includes traditional and digital asset prices, as well as non-tradeable metrics like total value locked (TVL) in DeFi, Ethereum gas price, Bitcoin hash rate, or the total crypto market cap.

![Example reference assets that can be used for derivative contracts issued on DIVA Protocol](/files/gKrB3dZC8I8Te1LIJ0PJ)


# Payoff curves

Enabling unparalleled customization through parametrization

In DIVA Protocol, payoff profiles are parametric, allowing the creation of a wide range of unique and tailored payoff profiles with different slopes, barriers, and ranges. The shape of the *long* payoff curve is governed by four parameters: **floor, inflection, cap, and gradient.**

Due to the zero-sum nature, the short payoff curve is implied via the relationship **payoff(Short) + payoff(Long) = 1**. Visually, the short token payoff curve is just a horizontally mirrored version of the long token payoff curve. This is illustrated in the following graphic:

<figure><img src="/files/olDFJdNv8QoNwrKbNGYt" alt=""><figcaption><p>Illustration: Parametric payoff curves in DIVA Protocol</p></figcaption></figure>

{% hint style="info" %}
The amount of long and short position tokens issued is equal to the amount of collateral held in the contingent pool, resulting in a maximum payout of 1 unit of the collateral token per long/short position token. For instance, if USDC 100 is deposited into the contingent pool, one party will receive 100 long and the other party 100 short tokens, regardless of their individual contributions.
{% endhint %}

Example long and short payoff curves that result from the parametric approach are illustrated below:

### **Long payoff curves**

![Example long payoff curves](/files/TTlzZTsofzUvOAmc2o6K)

### **Short payoff curves**

![Example short payoff curves](/files/prPAy8EvlRxKibDw9iUl)

### Payoff formula

The payoff per long token is calculated as follows (assuming 0 fees):

```
if (finalReferenceValue = inflection):
	payoffLong = gradient
else if (finalReferenceValue ≤ floor):
	payoffLong = 0
else if (finalReferenceValue ≥ cap):
	payoffLong = 1
else if (finalReferenceValue < inflection):
	payoffLong = gradient * (finalReferenceValue - floor)/(inflection - floor)
else if (finalReferenceValue > inflection):
	payoffLong = gradient + (1 - gradient)*(finalReferenceValue - inflection)/(cap - inflection)
```

As `payoffLong + payoffShort = 1` (ignoring fees), the short token payoff is given by `payoffShort = 1 - payoffLong.`


# Collateral

Choose a wide range of ERC20 tokens as collateral

In DIVA Protocol, collateral refers to the asset that is deposited into a contingent pool to back the value of the position tokens. The protocol offers support for a wide range of ERC20 tokens to serve as collateral, including popular options like DAI, USDC, USDT, WBTC, WETH, as well as interest-bearing tokens such as [Compound's cDAI](https://edge.app/blog/company-news/interest-bearing-tokens-in-edge-atokens-ctokens/#:~:text=The%20interest%2Dbearing%20tokens%20have,from%20the%20Compound%20money%20market.) or wrapped staked ETH ([wstETH](https://help.lido.fi/en/articles/5231836-what-is-wrapped-steth-wsteth)).

To qualify as collateral, an ERC20 token must meet the following criteria:

* **Decimal precision:** The token's decimal precision must be between 6 and 18.
* **No transfer fees:** The token must not charge fees on transfers. This will result in a transaction revert when creating a pool. If transfer fees are activated *after* a pool has been created, adding liquidity will no longer be possible. It is important to highlight that the pool can still be settled.
* **Non-rebasable:** The token's balance in a holder's wallet should remain constant. That is, tokens like Ampleforth, Lido's (non-wrapped) staked ETH ([stETH](https://help.lido.fi/en/articles/5231836-what-is-wrapped-steth-wsteth)), or [Aave's aTokens](https://edge.app/blog/company-news/interest-bearing-tokens-in-edge-atokens-ctokens/#:~:text=The%20interest%2Dbearing%20tokens%20have,from%20the%20Compound%20money%20market.), which can alter the holder's balance, should not be used as collateral to prevent rendering a pool undercollateralized or locking any accrued yield/interest. When tokens with a flexible supply are considered as collateral, only tokens with a constant balance mechanism such as [Compound's cToken](https://edge.app/blog/company-news/interest-bearing-tokens-in-edge-atokens-ctokens/#:~:text=The%20interest%2Dbearing%20tokens%20have,from%20the%20Compound%20money%20market.) or the wrapped version of Lido's staked ETH ([wstETH](https://help.lido.fi/en/articles/5231836-what-is-wrapped-steth-wsteth)) should be used. **It's important to highlight that, unlike fee-on-transfer tokens, using rebasable tokens as collateral will NOT cause a transaction revert when creating a pool or adding liquidity.**


# Oracles

Choose any oracle for outcome reporting

Contingent pools require **one data input** - the observed value of the reference asset at the specified expiry time - following pool expiration to determine the payoffs for long and short position tokens. This data is provided by an **oracle** (a.k.a "data provider"), which is **specified by the user at the time of pool creation**.&#x20;

DIVA Protocol has been designed to be oracle agnostic, giving users the freedom to configure the oracle according to their specific setup. This includes the option to use trusted individual accounts (an "EOA"), multisigs, existing decentralized oracle solutions like [Tellor](https://github.com/divaprotocol/diva-protocol-v1/blob/main/README.md#oracles), Chainlink, DIA, as well as custom oracle smart contracts.

Refer to the [Oracle Integrations](https://docs.divaprotocol.io/oracle-integrations/overview) section to see the available oracles that can be used for secure and trustless outcome reporting.


# Settlement

DIVA Protocol's universal settlement process

The goal of the settlement process is to determine the value of the reference asset prevailing at the time of expiration and with that, the payoffs for short and long position tokens. The settlement process starts right after the pool expires and ends when the status of the final reference value reaches "Confirmed" stage in which case position token holders can start redeeming their position tokens.

DIVA's settlement process was **designed to accommodate different types of oracles** including human oracles as well as decentralized oracle solutions such as Tellor, DIA, Band or Chainlink. It implements an **optional dispute mechanism** that can be activated for human oracles and a **fallback data provider** which steps in if the original data provider fails to submit a value (only guaranteed if data provider is whitelisted).

Below graph illustrates DIVA's settlement process:

![Illustration of DIVA's settlement process](/files/bwQ0EAGsWtGg7VRBFoaG)

On a high level, the settlement process can be broken down into the following four paths:

<table><thead><tr><th width="183.33333333333331">Path</th><th width="446.4571428571429">Description</th></tr></thead><tbody><tr><td>Direct confirmation <br><br>(<mark style="color:green;"><strong>A</strong></mark><strong> -> </strong><mark style="color:green;"><strong>B</strong></mark><strong> -> </strong><mark style="color:green;"><strong>C</strong></mark><strong>)</strong></td><td>Final value is confirmed with the first value submission and users can start redeeming their position tokens. While this offers the best user experience, this path is only suitable for oracles that implement their own dispute mechanism outside of DIVA (like Tellor) or oracles that cannot realistically engage in a review process (like Uniswap v3 oracle).</td></tr><tr><td>Challenge<br><br>(<mark style="color:green;"><strong>A</strong></mark><strong> -> </strong><mark style="color:green;"><strong>B</strong></mark><strong> -> </strong><mark style="color:yellow;"><strong>D</strong></mark><strong> -> </strong><mark style="color:yellow;"><strong>...</strong></mark><strong>)</strong></td><td>Final value is submitted and subject to challenge. Best suited for human reporters which can realistically review and update a submitted value after being challenged. The challenge functionality is optional and can be deactivated at the time of value submission by the data provider. Alternatively, the challenge policy of the data provider can be hard-coded inside a wrapper smart contract to inform users ahead of time.</td></tr><tr><td>Fallback 1<br><br>(<mark style="color:green;"><strong>A</strong></mark><strong> -> </strong><mark style="color:red;"><strong>L</strong></mark><strong> -> </strong><mark style="color:red;"><strong>M</strong></mark><strong>)</strong></td><td>Data provider fails to submit a value and the fallback data provider needs to step in. The fallback data provider guarantees to step in if a whitelisted data provider fails to submit a value within the 24h submission window. For non-whitelisted data providers, it's up to the fallback data provider to decide whether to report a value or not. Values submitted by fallback data providers cannot be challenged. </td></tr><tr><td>Fallback 2<br><br>(<mark style="color:green;"><strong>A</strong></mark><strong> -> </strong><mark style="color:red;"><strong>L</strong></mark><strong> -> </strong><mark style="color:blue;"><strong>N</strong></mark><strong>)</strong></td><td>Both data provider and fallback don't submit any value and final value defaults to inflection.</td></tr></tbody></table>

{% hint style="warning" %}
**IMPORTANT:** The dispute mechanism was designed to prevent human error such as fat-finger error or not accounting for token split. **It CANNOT prevent intentional malicious reporting**! Users should always choose a trusted data provider from the [whitelist](/introduction/what-is-diva-protocol/how-it-works/oracles#whitelist) to mitigate the risk of malicious actors.
{% endhint %}

Learn how to settle pools in our [DIVA App Training](/guides/diva-app-training/settle).


# Timelines

Timelines during the settlement process

The following periods and timelines apply during the settlement process:

<table><thead><tr><th width="211.33477321814257">Period</th><th>Description</th><th>Period</th></tr></thead><tbody><tr><td>Submission period</td><td>Time window for the data provider to report the outcome</td><td><strong>7 days</strong> following pool expiration</td></tr><tr><td>Challenge period</td><td>Time window for position token holders to challenge a reported value (only applicable if the option to challenge was given by the data provider)</td><td><strong>3 days</strong> starting from the time of a final value submission by the data provider</td></tr><tr><td>Review period</td><td>Time window for the data provider to react to a challenge and report a new outcome</td><td><strong>5 days</strong> starting from the time of the first challenge</td></tr><tr><td>Fallback submission period</td><td>Time window for the fallback provider to report a value</td><td><strong>10 days</strong> starting from the expiration of the submission period</td></tr></tbody></table>

The timelines represent initial values and can be updated by the DIVA Protocol owner at a later stage with values ranging from a minimum of 1 day to a maximum of 15 days. Further, it's important to note that any changes made will exclusively impact new pools and will not have any effect on existing outstanding pools.

The settlement process is illustrated below and discussed in more detail in the following sections. Also, refer to the official [smart contract documentation](https://github.com/divaprotocol/diva-protocol-v1/blob/main/DOCUMENTATION.md#settlement-process) for more details.

<figure><img src="/files/5KFR2uWHCasTFJHpc19Z" alt=""><figcaption><p>DIVA Protocol's settlement process flow</p></figcaption></figure>


# Challenge

Optional feature to prevent human error during outcome reporting

DIVA Protocol integrates an **optional challenge feature** which can be activated by the data provider to allow position token holders to request a review of the submitted final value if deemed inaccurate. The main goal of the challenge functionality is to **help fix unintentional errors made by the data provider** such as fat finger mistake or incorrect accounting for stock or token split.&#x20;

{% hint style="warning" %}
The challenge feature is NOT meant to prevent malicious data providers from submitting wrong values.
{% endhint %}

The challenge feature can be valuable when DIVA Protocol is used within a trusted and process-driven environment, such as a traditional bank. It is not expected to be used by decentralized oracles like Tellor, Chainlink or UniswapV3, which cannot realistically review their submitted values.

### Enabling the challenge feature

Data providers have the flexibility to choose whether to enable the challenge functionality each time they submit a value during the settlement process, including the initial submission, submission period, or subsequent reviews. To enhance transparency and build user trust, data providers can establish a predefined challenge policy through a separate smart contract, which can be assigned as the data provider. By implementing this approach, pool creators will have clear visibility at the time of pool creation, enabling them to determine whether a submitted value can be challenged or not, thus avoiding any unexpected surprises for users.

### Who can challenge?

Each account that has a non-zero position token holder of the underlying pool can submit a challenge including a value that they deem correct. For more details, refer to the [DIVA Protocol smart contract documentation](https://github.com/divaprotocol/diva-protocol-v1/blob/main/DOCUMENTATION.md#challenge).

### How to challenge a value?

Users can challenge a reported value by calling the [`challengeFinalReferenceValue`](https://github.com/divaprotocol/diva-protocol-v1/blob/main/DOCUMENTATION.md#challengefinalreferencevalue) function.

### Responding to challenges

If a value submission was challenged, the data provider has the following four options to react during the 5-day review period:

* **Option 1:** Submit a new value and *enable* the possibility to challenge. This will trigger a new challenge period.
* **Option 2:** Submit a new value and *disable* the possibility to challenge. In this case the new (revisited) value is directly confirmed and position token holders can redeem their tokens.
* **Option 3:** Submit the same value as before and thereby confirm the previously submitted value. Users can start redeem their position tokens.
* **Option 4:** Don't submit any value. In that case, users will be able to redeem their position tokens after the end of the review period at the originally submitted value.

Option 4 is the only option that allows the data provider to confirm the previously submitted value without spending any gas. While cost-efficient for data providers, position token holders will have to wait 5 days before they can start redeeming their tokens.


# Status

An overview of the states indicating the status of the settlement process

DIVA Protocol has three values to indicate the status of the settlement process:

<table><thead><tr><th width="150">DIVA Protocol Status</th><th>Description</th></tr></thead><tbody><tr><td>Open</td><td>No value has been submitted yet.</td></tr><tr><td>Submitted</td><td>A value has been submitted by the data provider and is subject to challenge.</td></tr><tr><td>Challenged</td><td>The final value submitted by the data provider has been challenged by position token holders.</td></tr><tr><td>Confirmed</td><td>The final value is confirmed, payouts for long and short position tokens have been determined and position token holders can start redeeming their position tokens.</td></tr></tbody></table>

To provide users additional information about the settlement process, the DIVA App implements additional states "Expired", "Fallback" and "Confirmed\*". All states used in the DIVA App are listed below:

| DIVA App Status | Description                                                                                                                                                                                                                                                                                                                                                                     |
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Open            | Pool has not expired yet.                                                                                                                                                                                                                                                                                                                                                       |
| Expired         | Pool has expired but the final value input from the data provider is still pending.                                                                                                                                                                                                                                                                                             |
| Submitted       | A final value has been submitted by the data provider.                                                                                                                                                                                                                                                                                                                          |
| Challenged      | The final value submitted by the data provider has been challenged by position token holders.                                                                                                                                                                                                                                                                                   |
| Fallback        | The data provider failed to submit a final value within the 24h submission period. The fallback data provider has 5 days to step in and submit a value. A submission by the fallback data provider should only be expected for whitelisted data providers. For non-whitelisted data providers, it's up to the the fallback data provider's discretion to submit a value or not. |
| Confirmed\*     | The final value is technically confirmed and will be updated during the next transaction in the DIVA smart contract.                                                                                                                                                                                                                                                            |
| Confirmed       | The final value is confirmed, payouts for long and short position tokens have been determined and position token holders can start redeeming their position tokens.                                                                                                                                                                                                             |


# Fast settlement

How users can exit their positions before the end of the settlement process

While giving position token holders the possibility to challenge the submitted final value increases the trust in correct settlement, long settlement periods can result in a bad user experience. Position token holders have to wait for at least 24h following expiration until they can withdraw their funds.&#x20;

This is not considered a problem in our view as service providers are expected to arise that will offer faster settlement in return for a small fee. In particular, the data providers themselves may step in to benefit from an additional revenue stream.&#x20;

{% hint style="success" %}
**Example:** Let’s assume the following two actors:&#x20;

* Karen has 1'000 long position token worth 1'000 DAI and wants fast settlement&#x20;
* Chad has 990 DAI and is willing to accept the settlement delay and the risk involved

Right after expiration date, Chad offers Karen to buy back her long position tokens for 990 DAI. If Karen accepts the offer, Chad will pay Karen 990 DAI in exchange for her long position tokens which he can then redeem for 1'000 at the end of the settlement period.&#x20;
{% endhint %}

We expect the fast settlement fees paid to compress over time making the procedure completely invisible to users eventually.


# Fallback data provider

Increasing confidence of correct settlement by having a fallback data provider

DIVA Protocol incorporates a fallback data provider that steps in and provides a value if the primary data provider fails to submit within the 7-day submission period. The fallback data provider is granted a **10-day window following the submission period** to report a value.

* The fallback data provider can decide whether to submit a value or not. The fallback provider may not report if:
  * Markets are associated with unethical events such as the death of someone.
  * The collateral token is useful and would not justify the costs for reporting.
* Values submitted by the fallback provider **cannot be challenged** by position token holders.

During the initial phase of the protocol, the fallback provider will be a Multisig entity owned by early contributors to the DIVA Protocol. However, the long-term goal is to transition to a decentralized oracle solution like [Tellor Protocol](https://tellor.io/).


# Fees

Protocol and settlement fees

DIVA Protocol applies the following fees when users redeem position tokens or remove liquidity (% fee applies to the claimable collateral amount):

* Protocol fee: 0.25%
* Settlement fee: 0.05%

{% hint style="success" %}
**Example 1:** Bob owns 100 long position tokens. Based on the final value reported by the oracle, Bob is eligible to claim DAI 70. At redemption, Bob is returned DAI 69.79 and the remaining DAI 0.21 (0.3%) go to the corresponding fee recipients.
{% endhint %}

{% hint style="success" %}
**Example 2:** Bob owns 100 long and 100 short position tokens which represent a claim on DAI 100 in the contingent pool. When Bob removes liquidity, he is returned DAI 99.7 and the remaining DAI 0.3 (0.3%) go to the corresponding fee recipients.
{% endhint %}

The protocol fee is allocated to the DIVA treasury and DIVA token holders can vote on how to spend those funds. The settlement fee is typically paid to the data provider. If the data provider fails to submit a value and the fallback data provider has to step in, the fallback data provider will receive the settlement fee. If both don't report, then the fee goes to the DIVA treasury.

Fees are paid in collateral token and retained within the DIVA Protocol until they are claimed by the respective fee recipients. Fee parameters are updateable by DIVA governance up to a maximum of 2.5%.

### Purpose of fees

Fees were baked into the DIVA Protocol to achieve the following:

* Ensure long-term viability and sustainability of the DIVA Protocol project
* Incentivize users to create position tokens that they can realistically sell
* Incentivize data providers to remain honest

Apps that build on top of DIVA Protocol may introduce their own fees on top. DIVA App, for instance, will implement a small trading fee that will be directed to the DIVA treasury.


# Compliance feature

Bridging the gap between DeFi and TradFi

DIVA Protocol is leading the way in bridging the gap between decentralized and traditional finance by implementing a compliance feature that allows traditional financial institutions to use DIVA Protocol while complying with existing KYC and AML regulations.

This is achieved by giving the creator of the derivative contract the possibility to restrict the transfer of the position tokens to holders of a pre-defined NFT, such as a non-transferrable KYC token issued by a bank or a third party provider.

Furthermore, each derivative contract is a separate entity in DIVA Protocol. This guarantees the segregation of funds, ensuring that assets held in one pool remains entirely separate from those held in any other pool.

By implementing these two critical features, DIVA Protocol directly addresses a key concern of regulators regarding the interaction of traditional financial institutions with DeFi protocols.


# Vision

Powering the world of derivatives

Our vision is to establish DIVA Protocol as the leading infrastructure for creating custom derivative financial contracts peer-to-peer. By providing the necessary tools and resources, the team aims to empower developers to create innovative derivative applications on top of DIVA Protocol independently. The best applications will be published in a dedicated [dApp Store](https://www.divaprotocol.io/dapps) on the DIVA Protocol website, thereby expanding the offerings available to users and fostering the growth of the ecosystem.

To give you some inspiration what you can build on top of DIVA Protocol and how you can contribute to the DIVA ecosystem, check out our [project ideas](/for-developers/project-ideas#app) section.


# Terminology

A glossary of DIVA Protocol specific terminology

### General terms

| Term                 | Description                                                                                                                                                                                                                     |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Contingent pool      | A programmatic escrow that receives and securely holds funds from users participating in a derivative contract and releases them based on the outcome of a pre-agreed future event, reported by an oracle following expiration. |
| Reference asset      | A metric or event whose outcome determines the payout for long and short position tokens.                                                                                                                                       |
| Long position token  | A conditional claim against the contingent pool's collateral that benefits when the value of the reference asset goes up.                                                                                                       |
| Short position token | A conditional claim against the contingent pool's collateral that benefits when the value of the reference asset goes down.                                                                                                     |
| Collateral token     | ERC20 token that is deposited into a contingent pool and backing the corresponding long and short position tokens.                                                                                                              |
| Expiry               | Time when the position tokens expire and the outcome of the underlying event is assessed.                                                                                                                                       |

### Payoff specific terms

| Term       |                                                                                                              |
| ---------- | ------------------------------------------------------------------------------------------------------------ |
| Floor      | Value of the reference asset at or below which the long token pays out 0 and the short token 1 (max payout). |
| Cap        | Value of the reference asset at or above which the long token pays out 1 (max payout) and the short token 0. |
| Inflection | Value of the reference asset at which the long token pays out Gradient and the short token 1-Gradient.       |
| Gradient   | Long token payout at inflection (value between 0 and 1). The short token payout at inflection is 1-Gradient. |

### Oracle specific terms

| Term          | Description                                                                                                                                |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| Data provider | An Ethereum address (individual account or smart contract) that is supposed to report the final reference value following pool expiration. |


# What is DIVA Token

Enabling efficient and effective protocol governance

The DIVA Token is DIVA Protocol's native governance token and empowers its holders to influence the direction of the protocol by delegating the management of the treasury funds and (limited) protocol governance rights to candidates of their choice.

The delegate's rights are summarized in the following illustration:

<figure><img src="/files/OJjqsI5doERHBgLgjRyo" alt=""><figcaption><p>DIVA Tokenomics illustration. Source: DIVA Protocol pitch deck</p></figcaption></figure>

The upcoming sections provide a comprehensive overview of the utilization of the DIVA Token within the DIVA Protocol system, along with detailed insights into the token distribution over time.

### Disclaimer

The DIVA Token is not a fundraising device nor an investment opportunity.


# Owner election mechanism

Enabling effective and efficient protocol governance without sacrificing decentralization

Token holders express their preference for a delegate/owner by locking ("staking") their tokens in the [DIVA Ownership contract](https://etherscan.io/address/0xE39dEC81B2186A1A2e36bFC260F3Df444b36948A) on Ethereum.

If a candidate receives more support than the current owner (as measured by staked amount), a **30-day showdown period** can be triggered by the corresponding candidate.

At the end of this period, a snapshot of the candidates' stakes is taken and candidates that have received more support than the current owner have a **7-day window to submit a claim on the protocol ownership**. Among those, the candidate with the highest stake automatically assumes protocol ownership and has access to all privileged functions after the end of the election cycle. Staking and unstaking are disabled during this period.

In total, an election cycle lasts 37 days. A cooldown period of 7 days applies following the election cycle end where no new election cycle can be triggered. The following illustration summarizes the process:

<figure><img src="/files/lxKLfA0oRyr6aUbQAXrr" alt=""><figcaption><p>Illustration of election process.<br>[1] Manual ownership claim submission process introduced to avoid expensive storage operations inside the smart contract.</p></figcaption></figure>

The owner elected on Ethereum (primary chain) is orchestrated to secondary chains including Polygon, Arbitrum One and Gnosis via a [cross-chain communication](https://github.com/divaprotocol/diva-protocol-v1/blob/main/DOCUMENTATION.md#diva-ownership-on-secondary-chains) mechanism using the Tellor protocol.

Despite the centralized element, the power remains in the hands of the DIVA Token holders. At any point in time (subject to a minimum staking period of 7 days), DIVA Token holders can vote to replace the current protocol owner by directing their stake towards a new candidate.

### Links for further reading

* [Blog post on DIVA Tokenomics](https://www.divaprotocol.io/posts/diva-tokenomics)
* [Ownership section in smart contract docs](https://github.com/divaprotocol/diva-protocol-v1/blob/main/DOCUMENTATION.md#diva-ownership-on-main-chain)


# Token distribution

Long-term focused and sustainable

* Maximum supply (to be reached in June 2053): **100 million**
* Circulating supply at TGE (26 June 2023): **22.7 million**
* Projected circulating supply end of year two (30 June 2025), after vesting and realized token unlocks: **46.0 million**

### Initial token distribution

A total of 34 million DIVA Tokens, out of the maximum supply of 100 million, have been initially allocated among the founding team (25 million), pre-seed investors (5.4 million), community (1.4 million) and other contributors (2.2 million), spanning across 17’482 eligible accounts.

Recipients of more than 15’000 DIVA Tokens, including the team and pre-seed investors, are subject to a two-year vesting period, during which 60% of their allocation will be vested.

Additionally, 58 million tokens have been deposited into the DIVA Development Fund. These tokens will be programmatically unlocked at a rate of 1.93 million tokens p.a. over a period of 30 years to support the on-going development of the ecosystem. Refer to the DIVA Development Fund section to learn more about the purpose and intended use of the funds.

The remaining 8.0 million DIVA Tokens have been temporarily reserved for on-going sale discussions with potential investors and are accessible by the initial protocol delegate, DIVA Technologies AG. If fundraising efforts do not materialize as expected, any unused tokens will be re-deposited into the DIVA Development Fund subject to the same 30-year release period.

Overall, the initial circulating supply amounts to 22.7 million tokens and will increase to approximately 45.6 million tokens by the end of year 2, after vesting and realized token unlocks. It's important to highlight that the circulating supply will decrease if unused strategic reserves are locked back into the DIVA Development Fund.

The chart below illustrates the token distribution over time:

<figure><img src="/files/nI6bnY3aI7v2Jh7bACUS" alt=""><figcaption><p>DIVA Token distribution over time</p></figcaption></figure>

### Links for further reading

* [Mainnet announcement post](https://www.divaprotocol.io/posts/diva-mainnet-launch)


# DIVA Development Fund

Securing the future of DIVA Protocol

To reduce the reliance on external fundraising and grants, the DIVA Protocol team has established the [DIVA Development Fund](https://etherscan.io/address/0xb3e25F6c7d1074f2cfE0F2Dc8586D1e74234338b) to provide an opportunity for individuals to support the ongoing development of the DIVA Protocol ecosystem.

Individuals can contribute to the development by depositing ETH or any other ERC20 token (excluding rebasable and fee tokens) into the fund. This can be done either by directly sending assets to the Ethereum contract, allowing for immediate claimability by the owner/delegate, or by using the [`deposit`](https://etherscan.io/address/0xb3e25F6c7d1074f2cfE0F2Dc8586D1e74234338b#writeContract#F2) function, which enables specifying a release period.

As part of their commitment to fostering community growth and development, the DIVA Protocol founding team has [deposited 58 million tokens](https://etherscan.io/tx/0xe54868c06ea3c89ff1499ec395a5d1e8743bbccfa4d6c3c346045b7638253029) (58%) of unreleased DIVA Tokens into the DIVA Development fund shortly after mainnet deployment. The intention is to distribute them strategically in a retroactive manner to contributors.

**🙏To contribute and support the DIVA Protocol ecosystem, we appreciate your donation to the following Ethereum network address:** [0xb3e25F6c7d1074f2cfE0F2Dc8586D1e74234338b](https://etherscan.io/address/0xb3e25F6c7d1074f2cfE0F2Dc8586D1e74234338b)


# FAQ

Frequently asked questions by the DIVA community

### <mark style="color:blue;">How is the DIVA token used?</mark>

DIVA is the native token that is used to govern the DIVA Protocol. Holding DIVA tokens represents voting power in steering the future direction of the DIVA Protocol. This may include voting on protocol parameter updates or deciding on how to spend the treasury funds.&#x20;

DIVA will be earned by users through various activites including participation in the testnet, providing liquidity and trading on mainnet. Users will earn a share of DIVA proportional to their activity. Token distribution activity will be proposed and voted on by DIVA token holders on a regular basis taking into account prevailing market conditions. DIVA token is not a fundraising device nor an investment opportunity.&#x20;

### <mark style="color:blue;">What is an ERC20 token?</mark>

A token in general is a digital representation of value on the blockchain. It can represent virtually anything of value including a share in a company, a lottery ticket or reputation points in an online platform. Such tokens are tradable and transferrable among the various participants of the blockchain.&#x20;

Having a token standard allows developers to build token applications that are interoperable with other products and services. The ERC20 standard has become the most popular token standard in the crypto space. It defines a set of basic functionality that a token should implement such as:

* Transfer tokens from one account to another
* Get the current token balance of an account
* Get the total supply of the token available on the network
* Approve whether an amount of token from an account can be spent by a third-party account

In DIVA Protocol, [position tokens](/diva-app/trade-position-tokens) are ERC20 compliant which allows to integrate them into existing centralized and decentralized infrastructure and enable applications that are yet beyond our imagination.

### <mark style="color:blue;">Do I have to create a contingent pool before I can start trading?</mark>

Not necessarily. Most of the time someone will have already created a pool and the corresponding position tokens. All available position tokens are listed on the Markets page. Only if you don't find a product that meets your needs, you will have to create your own contingent pool.&#x20;

### <mark style="color:blue;">Why do I have to approve when creating or filling orders?</mark>

The approval process is specific to the [ERC20 standard](https://ethereum.org/en/developers/docs/standards/tokens/erc-20/) and allows accounts other than the original owner to initiate asset transfers up to an allowed amount ("allowance") set by the owner. The abstraction of the initiator of a token transfer is one of the reasons why the ERC20 token standard has gained so much popularity.

As the trading of position tokens involves the exchange of two ERC20 tokens, both the maker and taker of an order need to set an allowance for the exchange smart contract, more precisely the 0x exchange contract, to move the assets during the exchange.&#x20;

While the approval process does not result in the best user experience (mainly due to gas costs incurred), from a security perspective, it's considered best practice to approve only amounts that a user is going to trade. If you wish to reduce the approval frequency, you can approve a larger amount and continue creating or filling orders of smaller sizes.

### <mark style="color:blue;">Why do I receive both long and short position tokens after creating a pool?</mark>

The long and short position tokens represent a claim on the collateral asset that you have deposited. That means that at any point in time, you can return the long and short position tokens in equal proportions and get back your collateral. As holding both the long and short positions will not expose you to the up- or downside of the underlying, you would typically want to sell one of the sides to gain exposure according to your view of the market.

You didn't find your question? Ask us on [Discord](https://discord.gg/Pc7UBqxu2b).


# What is DIVA App

The first app built on DIVA Protocol

DIVA App is the first implementation of an app that uses DIVA Protocol as the underlying technology. Using the DIVA App users can interact with the protocol through a user-friendly interface. They can create and redeem those assets. Data providers can report values via the application. In addition, DIVA App integrates 0x's limit order protocol to allow users to trade those derivative assets in a decentralized way without giving up custody of their assets.

Learn how to to use the DIVA App in our [DIVA App Training](/guides/diva-app-training).


# Overview

DIVA Protocol is a set of smart contracts that allows its users to create and settle derivative assets on virtually anything. DIVA App faciliates the user interaction with the protocol functions and implements a trading functionality built on 0x's limit order protocol. The following sections shall give you a detailed overview of the core functionality of the DIVA Protocol and the usage of the DIVA App.


# Create position tokens

How position tokens are created in DIVA Protocol

The lifetime of position tokens starts with the creation of a so-called contingent pool. A contingent pool is a smart contract that, upon collateral deposit, issues two types of tokenized shares, long and short position tokens, with directionally reversed payoff profiles. Combined those position tokens represent a claim on the deposited collateral. In isolation, however, they expose the user to the up- or downside of the asset.&#x20;

The collateral is held inside the smart contract until any of the below actions occur:

* User sends back an equal amount of both long and short position tokens
* User redeems long or short position tokens after the payout per long/short token has been set

The payoffs per long and short position tokens are determined contingent on the outcome of an external event that a user specifies at the time of the contingent pool creation.&#x20;

To create a contingent pool / position tokens, a user would need to specify the following inputs:&#x20;

* :chart\_with\_upwards\_trend: **Event**: the outcome, defined by a metric and an expiration date, that the position tokens derive their value from
* :moneybag: **Payoff profile**: the parameters governing the shape of the payoff curves
* :dollar: **Collateral asset**: the asset (ERC20 token) that backs the value of the position tokens
* :crystal\_ball: **Data provider / Oracle**: an Ethereum address that is supposed to report the final value of the reference asset following expiration &#x20;

Learn how to create a contingent pool in our [DIVA App Training](https://docs.divaprotocol.io/diva-app/pages/NBlNZa5OrXsIyvWKdvM4#b.-create).


# Trade position tokens

How long and short position tokens are traded in the DIVA App

Position tokens issued by the DIVA Protocol are ERC20 tokens and can be integrated into any DEX and CEX for trading.&#x20;

![](/files/jpEKaHERvTT8gSNIZ32W)

To faciliate the exchange of long and short tokens, the DIVA App offers a trading interface built on [0x protocol](https://0x.org/docs/core-concepts), a decentralized offchain orderbook with an onchain settlement model. We believe that a traditional orderbook approach is more suitable for trading derivative assets than existing AMMs as it gives market makers maximum flexibility to capture all dimensions relevant for the valuation of derivatives.

The short and long position tokens issued against a contingent pool are two independent assets that show up as two separate lines on the **MARKETS** page. As a result, there is one orderbook for the short and one for the long position token. Similar to traditional exchanges, users can create buy and sell orders or fill existing orders in the orderbook. DIVA App will implement a novel orderbook design to make it easier for users to navigate and find the prices at which they can trade. Terms like BID and ASK belong to the past.

{% hint style="info" %}
0x is a protocol that facilitates the peer-to-peer exchange of Ethereum-based assets without giving up custody of the assets. The protocol serves as an open standard and common building block for any developer needing exchange functionality.
{% endhint %}

Learn how to trade on the DIVA App in our [DIVA App Training](https://docs.divaprotocol.io/diva-app/pages/NBlNZa5OrXsIyvWKdvM4#c.-trade).


# Add liquidity

How to add additional collateral to existing pools

At any point in time prior to expiration, users can add collateral to an existing contingent pool and receive an equivalent amount of short and long position tokens in return. Existing position token holders will not be impacted in any way.

{% hint style="success" %}
**Example:** Adding DAI 60'000 in collateral to an existing contingent pool that has already DAI 40'000 deposited into it with 40'000 long and short position tokens outstanding, will result in 60'000 new short and long position tokens being minted.
{% endhint %}

There are two main reasons why adding liquidity to an existing pool can be more attractive than creating a new one:

* **Cheaper:** Adding liquidity skips some of the steps involved in creating a pool (e.g., initial deployment of the position tokens and input validation checks) which results in lower gas costs for the user.
* **Access to liquidity:** Existing pools that already have an active and liquid market are more attractive for users than new pools with no or little liquidity.

The only compromise that a user has to make when adding liquidity is that they have to accept existing pool parameters and cannot modify them according to their needs.

Learn how to add liquidity to an existing pool in our [DIVA App Training](/guides/diva-app-training#add-liquidity-to-an-existing-pool).


# Remove liquidity

How collateral can be withdrawn from existing contingent pools prior to expiration

At any point in time, prior to or after pool expiration but before the payoffs of the long and short position tokens are set, position token holders can withdraw collateral from the pool by sending back an equal amount of long and short tokens to the DIVA smart contract. Position tokens are burnt during that process.

Removing liquidity can be useful in the following two scenarios:

* **Lack of buyers:** Pool creators that do not manage to sell all of their position tokens have the option to withdraw collateral without waiting until expiry (see example 1 below)
* **Liquidity:** The market for the opposite asset (e.g., short) is more liquid than the market for the asset held (e.g. long) (see example 2 below)

{% hint style="success" %}
**Example 1:** Alice has created a new contingent pool using 1'000 USDC as collateral and received 1'000 long and 1'000 short tokens in return. As she didn't manage to sell 400 of the short tokens, she can send back the remaining tokens in equal proportions, i.e. 400 long and 400 short tokens, to the DIVA smart contract to re-claim 400 USDC (minus a small fee) of the collateral that she deposited.
{% endhint %}

{% hint style="success" %}
**Example 2:** Bob owns 10 long tokens. He would like to exit his position to realize the gains he made since his entry but realizes that there are no buy orders for the long token. Luckily, the market for the corresponding short token is much more liquid. He buys 10 short tokens to neutralize his long position and sends back both tokens to the DIVA smart contract to return the corresponding collateral amount.
{% endhint %}

Learn how to remove liquidity from an existing pool in our [DIVA App Training](/guides/diva-app-training#remove-liquidity-from-an-existing-pool).


# DIVA App Training

Step-by-step instructions to use DIVA App features

The DIVA App Training will take you step-by-step to run and test the DIVA App and its features from the creation part to the settlement and post-settlement part. This is the best way to learn about DIVA Protocol and its features.


# Prepare

Preparation steps for interacting with the DIVA App

In order to interact with decentralized applications like DIVA App, users have to set up a few things  before they can get started. This guide will help you set up your wallet and fund it with some test assets so that it becomes easy for you to explore and use the DIVA App by making test transactions. Users that have all of this already set up, can skip this section.

### 1) Set up MetaMask wallet (one-off)

To be able to use the DIVA App and make transactions on-chain, you will need to have MetaMask wallet installed and set up on your browser. You can follow a detailed guide from [here](https://docs.polygon.technology/docs/develop/metamask/hello/).

### 2) Get some test assets

Playing around with the DIVA App on the Goerli testnet allows you to make transactions without spending real money. Once your wallet is set up, you will need to get some test assets to interact with the DIVA App. First, you have to you obtain some Goerli ETH to pay for gas fees on the Goerli network. We suggest to use one of the following faucets:

* [Paradigm faucet](https://faucet.paradigm.xyz/): funds your wallet with 0.5 Goerli ETH and 0.5 [WETH](https://ropsten.etherscan.io/address/0xc778417e063141139fce010982780140aa0cd5ab) (ERC20 version of ETH)
* [Goerli PoW Faucet](https://goerli-faucet.pk910.de/): sends you up to 4 Goerli ETH; does not give you any ERC20 tokens

For the testnet, you need a specific ERC20 token which you can use as collateral while interacting with the DIVA App. Head over to the [Testnet](/guides/diva-app-training/testnet) section to find out how to register and to receive [dUSD](https://goerli.etherscan.io/address/0xFA158C9B780A4213f3201Ae74Cca013712c8538d), the testnet specific collateral token.


# Testnet

Participate in our Learn-to-Earn program to earn a claim on the future DIVA token

{% hint style="info" %}
Note that the testnet has been migrated from the Ropsten to the Goerli network on 20th August.&#x20;
{% endhint %}

The DIVA team is running a testnet until **30th September 2022** where participants can earn a claim on the future DIVA token by trying out and exploring the functionality of the DIVA App. Read the full announcement [here](https://www.divaprotocol.io/posts/diva-testnet-announcement).&#x20;

To participate in the testnet, follow below steps:

* Head over to the [`#testnet`](https://discord.com/invite/ZXpDp9G5b8) in our Discord.
* Type **/register** in the message line, add a **blank space** and paste the **wallet address** that you are going to use to interact with the DIVA App and later to claim the DIVA token. It should look as follows:

![](/files/NS5BbEkLSrZ2iAWX687z)

* **Make sure you are using an address that you control as you won't be able to change it afterwards!**&#x20;
* Hit Enter to confirm. In addition to the address registration, you will receive test ERC20 tokens called dUSD (address: [0xFA158C9B780A4213f3201Ae74Cca013712c8538d](https://goerli.etherscan.io/address/0xFA158C9B780A4213f3201Ae74Cca013712c8538d)) that you will need to start testing the app.&#x20;
* Type **/address** to confirm that your address has been registered. You can also use this command to check which account you have registered in case you forget it.
* Type **/claim-test-assets** to receive more dUSD tokens for testing (works only for registered users). Note that you can claim test assets once per day.

All available commands to interact with our Discord bot are also listed in the testnet channel:

![Available commands to communicate with the DIVA Discord Testnet bot](/files/n4fPrUC4qiRu5VrDj63n)

{% hint style="info" %}
Note that each verified Discord user can only register one single address.
{% endhint %}


# Create

Create position tokens with various payoff profiles

### Create position tokens with a binary payoff

*Make sure your wallet is connected to the application.*

#### **A. Pool setup**

* Go to **CREATE**
* Specify the parameters of the position tokens. By adjusting the values of Floor, Inflection, and Cap along with the values under Advanced Settings you can achieve various payoff profiles (incl. binary payoffs) which will be presented in the chart.
* Click on **NEXT** to set the **Oracle**

![Example: Pool with Binary Payoff](/files/Hpxk4KQ9GNDIBgJCh51s)

#### **B. Oracle setup**

* Select a whitelisted **Data Provider** from the dropdown or enter a wallet address that will report the final reference value (ideally one that you control for testing purposes)
* Click on **NEXT** to review and complete the pool creation process

![Select a data provider to report the final reference value](/files/ltgB50jZVHezGGkIrRkN)

#### **C. Review & create pool**

* Review all pool parameters in a single view
* Click **APPROVE** and confirm the transaction in your wallet
* Click **CREATE** and confirm the transaction in your wallet

Once completed, the pool will be created and you will see two-position tokens with directionally reversed payoff patterns added to MY DASHBOARD -> MY POSITIONS.

![Review pool parameters in a single view](/files/q909f2id54oux4ySw9IQ)

{% hint style="info" %}
**Pro-tip:** If you plan to create multiple pools using the same collateral token, you can save gas costs by approving a larger amount and then creating pools with smaller amounts until the approved amount is exhausted. More precisely, in step 1, enter a larger collateral amount, proceed to step 3 and click approve. Then, return to step 1 and create pools with collateral amounts smaller than you approved.
{% endhint %}

Using similar steps which are described above, you can create position tokens with linear, concave and convex payoff profiles. Try to complete the following tasks to learn how the different parameters impact the shape of the payoff curves.

### Create position tokens with a linear payoff

![Example: Position tokens with a linear payoff](/files/NCSeUdMJSTxVj3Eo2M5q)

### Create position tokens with a convex long payoff (concave short payoff)

![Conxev/concave payoff profile for long/short](/files/9SQPu9JJlqp4rgrX8q4X)

### Create position tokens with a concave long payoff (convex short payoff)

![Concave/convex payoff profile for long/short](/files/pwGfE3OKYsuhqndeXkWJ)


# Trade

Trade position tokens via the DIVA App

### Create a BUY LIMIT order

* Go to **MARKETS**
* Select the position token you want to buy
* In the order widget on the right, select **BUY** and **LIMIT**
* Enter the number of position tokens you want to buy
* Enter the price you want to pay per position token
* Set how long your order shall be valid
* Click **APPROVE**
* Click **CREATE ORDER**

{% hint style="info" %}
Note that it's considered best practice to approve only the amount that you are planning to spend. Instead of approving and spending gas every single time before placing an order, you can approve a larger amount once and then place your orders with a reduced amount until your approved amount is exhausted. This way you will incurr gas fees for the approval transaction only once.&#x20;
{% endhint %}

![Create BUY LIMIT order. Left image shows approve step, right image shows create order step.](/files/LkuhOAM1R80Ks7WnKpKA)

### Create a SELL LIMIT order

* Go to **MY DASHBOARD -> MY POSITIONS**
* Select the position token you want to sell
* In the order widget, select **SELL** and **LIMIT**
* Enter the number of position tokens you want to sell
* Enter the price you ask per position token
* Set how long your order shall be valid
* Click **APPROVE**
* Click **CREATE ORDER**

![Create SELL LIMIT order. Left image shows approve step, right image shows create order step.](/files/NKnlfEYnubGWibP80H8y)

### Fill existing SELL LIMIT orders (BUY MARKET)

* Go to **MARKETS**
* Select the position token you want to buy
* Check that there are existing orders on the **ASK** side of the order book
* In the order widget, select **BUY** and **MARKET**
* Enter the number of position tokens you want to buy
* Click **APPROVE**
* Click **FILL ORDER**

![BUY Market](/files/Kk1jKgbrhaSnfM9y33Jp)

### Fill existing BUY LIMIT orders (SELL MARKET)

* Go to **MY DASHBOARD -> MY POSITIONS**
* Select the position token you want to sell
* Check that there are existing orders on the **BID** side of the order book
* In the order widget, select **SELL** and **MARKET**
* Enter the number of position tokens you want to sell
* Click **APPROVE**
* Click **FILL ORDER**

![SELL Market](/files/hakQuyKFeyEBV12mvGvA)


# Add

Add liquidity to an existing pools

### Add liquidity to an existing pool

* Go to **MARKETS**
* Select a position token that belongs to the pool that you want to add collateral to
* Go to **LIQUIDITY**
* Select **ADD**
* Enter the collateral amount you want to add to the pool
* Click **APPROVE** and confirm the transaction in your wallet
* Click **ADD** and confirm the transaction in your wallet

![Add liquidity to an existing pool. Left image: select an asset from the markets page; right image: add liquidity](/files/KXQ6J6L9FKzigvwVRpsp)


# Remove

Remove liquidity from an existing pool

### Remove liquidity from an existing pool

* Go to **MARKETS**
* Select a position token that belongs to the pool you want to remove liquidity from
* Go to **LIQUIDITY**
* Select **REMOVE**
* Enter the collateral amount you want to remove from the pool
* Click **REMOVE**
* Confirm the transaction in your wallet

![Remove liquidity from an existing pool. Left image: select an asset from the Markets page; right image: remove liquidity](/files/HuV9slquvQPJbttfysNl)


# Settle

Reporting process for human data providers

{% hint style="info" %}
The steps described in this section are only relevant for human data providers. For smart contract oracles, this process is not relevant as they will "automatically" fetch and submit the final value without using the Dashboard in the DIVA App.
{% endhint %}

### Report final value <a href="#report-final-value" id="report-final-value"></a>

* Create a pool where one of the accounts you control is the data provider (for test purposes)
* Create a very short expiry time to be able to report the value (for test purposes)
* Once the pool has expired,
  * Go to **MY DASHBOARD**
  * Switch to the data provider wallet
  * Go to **MY DATA FEEDS**
  * Click on **SUBMIT VALUE** button
  * Enter the value, click on **SUBMIT**, and confirm the transaction in your wallet

![Report final value](/files/9Lh1IVUA8UmksbByBsY7)

### Challenge a reported value

After a value has been submitted by the data provider, any position token holder of the corresponding pool can challenge the value if deemed inaccurate. Note that the challenge functionality is optional in DIVA Protocol but enabled by default in the DIVA App for all submissions.

To challenge a submitted value, follow the following steps:&#x20;

* Go to **MY POSITION**
* Click on **CHALLENGE VALUE**
* Enter the value that you deem to be the correct one
* Click on **SUBMIT**

![Challenge a reported value](/files/G0oQCKNRnwYHhWx3ZKqG)

###


# Redeem

Redeem position tokens after the final value has been confirmed

### Redeem position token

* Go to **MY POSITIONS**
* Choose a position token where status is "Confirmed"
* Click on **REDEEM** button
* Approve transaction from your wallet

![Redeem position token](/files/VjCrwUXfNLELVvMZ1VTK)

* If you don't have a confirmed pool yet, you have 2 options:
  * **Option 1 - wait for 48 hrs:** If the data provider does not react to a challenge for more than 48 hours, the previous value submitted by the data provider is considered confirmed and users can start redeeming their tokens.
  * **Option 2 - re-submission:** If the fat provider re-submits the same value as before, the final value is immediately confirmed and position token holders can start redeeming their position tokens.


# Fees

Claim and transfer fees

Once the final value has been confirmed, the data provider receives a fee as a reward. The data provider can either fully claim the fee or transfer it (fully or partially) to any other account.

### Claim fees as a data provider

* Go to **MY FEE CLAIMS**
* Click on **CLAIM FEES**
* This will initiate a transaction in your wallet
* Click on **Confirm** from your wallet to claim fees into your wallet

![Claim fees](/files/X1NKc5ji8xNsN3bPacqH)

### Transfer fee claims

* Go to **MY FEE CLAIMS**
* Click on **TRANSFER FEES**
* Enter the address you want to transfer fees
* Enter the amount you want to transfer
* This will initiate a transaction in your wallet
* Click on **Confirm** from your wallet to claim fees into your wallet

![Transfer fees](/files/qPUQR6t9Ir4grvf5rpIC)


# Quiz

Test your knowledge by answering below DIVA related questions

**Q1:** Which protocol is DIVA App using under the hood to facilitate the trading of position tokens? What are the benefits of this protocol compared to other solutions?

**Q2:** How many parameters drive the shape of the payoff curves and what’s their name and meaning?

**Q3:** How many different types of payoff profiles does DIVA Protocol allow to create? Use the DIVA App to create examples for each type and respond with a screenshot and name of the corresponding payoff profiles.

**Q4:** What is the maximum payout per position token? How is that achieved? What’s the implication for the price of position tokens?

**Q5:** What’s the difference between creating a contingent pool and adding liquidity?

**Q6:** What happens under the hood when a user creates a contingent pool? Send an etherscan link to a create contingent pool transaction and explain in your own words what it does.

**Q7:** What happens under the hood when a user adds liquidity to an existing pool? Send an etherscan link to an Add Liquidity transaction and explain in your own words the underlying asset flows.

**Q8:** You see a Buy Limit order ("Bid") of dUSD 1.5 in the orderbook for one of the assets in the DIVA App. Explain how you can make a risk-free profit.

**Q9:** Which of the following oracle protocols will DIVA Protocol be able to support and why?

* Tellor Protocol
* UMA Protocol
* Chainlink
* DIA Protocol
* Band Protocol

**Q10:** What was the name of the Protocol that inspired the design of DIVA Protocol?

**Q11:** The LONG position tokens of pools A and B (see screenshots) are traded on the market. Which one is more expensive and why? What can you say about the value of the SHORT position tokens of the two pools?

![Screenshot A](/files/8oYLtJPfTNOY77JODvNB)

![Screenshot B](/files/t3JPoMueW4JZrKQPqdCw)

**Q12:** How would one need to adjust the payoff parameters of Pool A in Q11 such that the provided answer to the cited question is no longer necessarily true? Explain why.

**Q13a:** What are the two ingredients that make up a derivative?&#x20;

**Q13b:** Which of the following statements are TRUE:

1. When holding a derivative you are not holding the underlying directly
2. When holding a derivative you are holding the underlying directly
3. Derivatives can be used to profit from both up- and downside of the underlying
4. Derivatives can be used to profit from the upside of the underlying only
5. Derivatives can be used to profit from the downside of the underlying only

**Q14:** What are two feasible ways to exit a position before expiration. Having a position means owning a long or short position token.

**Q15:** In which case would you choose to remove liquidity rather than sell?

**Q16:** Why is the following statement not true: A position token holder always has to wait until the end of the submission period (i.e. at least 24h after expiration) before they can redeem their position tokens.

**Q17:** What is another scenario where position token holders do not need to wait 24h until they can redeem?

**Q18:** Assume two LONG position tokens A and B with exactly the same configuration except for the expiration time. Token A expires earlier than token B. The current intrinsic value of both is zero, i.e. positions are “out of the money” (underlying value < floor). Which one is more expensive and why?

**Q19:** Assume two LONG position tokens A and B with exactly the same configuration except for the expiration time. Token A expires earlier than token B. The current intrinsic value of both is 1, i.e. underlying value >= cap. Which one is more expensive and why?

**Q20:** What happens if the data provider doesn’t submit a value during the submission period following expiration?

**Q21:** How much time has the fallback data provider to report the final value?

**Q22:** What is the maximum and minimum time fallback data providers could be granted by the protocol?

**Q23:** Is a fallback data provider’s submission challengeable? What’s the implication of the answer for the status of the final reference value?

**Q24:** What does that mean for position token holders if the status is confirmed?

**Q25:** What happens if both the data provider and the fallback provider fail to submit a value?

**Q26:** In which cases should users expect a fallback provider to step in and submit a value?

**Q27:** Who can challenge a submitted value?

**Q28:** Bob creates a pool with 100 USDC as collateral. How much fee is Bob paying to DIVA protocol at the time of pool creation?

**Q29:** During which operations do users pay a fee and how much?

**Q30:** Bob bought 100 LONG position tokens that expired worthless (payout 0 USDC). Alice bought 100 of the corresponding SHORT position tokens and received the maximum payout. How much fees are Bob and Alice paying each in total in USDC when they redeem their position tokens?

**Q31:** The final value defaults to inflection. Who receives the fee payments when users redeem their position tokens and how much is that in %?

**Q32:** How much fee do users pay when adding liquidity to an existing pool?

**Q33:** Bob has created a new contingent pool, but he doesn’t manage to find a buyer for his position tokens. He sends them back to DIVA protocol to return his collateral. How many times does Bob pay fees including blockchain transaction fees in the worst case? Name the actions for which fees are paid.

**Q34:** What’s the gradient in the chart? What is the gradient for the corresponding SHORT position?

![](/files/duvs4ds5XkR3y1hUz2XU)

**Q35:** Assume you have a LONG position token where floor=inflection=cap=1 and gradient=1. What’s the name of the resulting payoff shape and what’s the payout per SHORT position token if the final outcome ends up at 1?

**Q36:** What does the maximum capacity of a pool represent and where can you set it inside the DIVA App?

**Q37:** Bob has created a pool where he deposited 100 USDC and set the maximum capacity to 120 USDC. Bob removes liquidity for 30 USDC after a while. How much can Alice add to the pool as liquidity?

**Q38:** When can it make sense to set a maximum pool capacity?

**Q39:** What’s the payout gross of fees of the corresponding SHORT position token if ETH/USD ends up at 1000?

![](/files/56AgFPr3YuyPG8089tvU)

**Q40:** Referring to the screenshot in Q39, what’s the payout net of fees of the LONG position token if ETH/USD ends up at 1100?

**Q41:** Referring to the screenshot in Q39, what’s the combined payout net of fees of the LONG and SHORT position token if ETH/USD ends up at 10'000?

**Q42:** Referring to the screenshot in Q39, choose an ETH/USD value between 800 (floor) and 1200 (cap) of your choice and give me the payout for the LONG position token gross of fees and the payout for the corresponding SHORT position token net of fees.

**Q43:** What’s the definition of intrinsic value? Use the screenshot in Q39 to provide an example in your explanation.

**Q44:** ETH/USD stands at 1'100 and the LONG position token trades at 0.7. What is the LONG position token’s intrinsic value?

**Q45:** What’s the extrinsic value here? How would you define extrinsic value if you were to include it in our docs?

**Q46:** Can intrinsic value for a position token be negative? Explain your answer.

**Q47:** Can the extrinsic value of a position token be negative? Explain why/why using a concrete example.

**Q48:** What's another term for price in the context of derivatives?

**Q49:** When is extrinsic value equal to zero?

**Q50:** This question consists of three parts:

1. Choose an ETH/USD value of your choice and provide the intrinsic value for the LONG and SHORT position token (see screenshot); ignore any fees for that exercise.
2. Provide an example where the extrinsic value is positive. Use concrete values for ETH/USD and premium in your example.
3. Provide an example where the extrinsic value is negative. Use concrete values for ETH/USD and premium in your example.&#x20;

Answer template:

1. Assumed ETH/USD value: \[...] -> Intrinsic value LONG: dUSD \[...] -> Intrinsic value SHORT: dUSD \[...]
2. Example extrinsic value > 0: ETH/USD: \[...] -> Intrinsic Value: \[...], Premium: dUSD \[...] -> Extrinsic value: dUSD \[...]
3. Example extrinsic value < 0: ETH/USD: \[...] -> Intrinsic Value: \[...], Premium: dUSD \[...] -> Extrinsic value: dUSD \[...]


# Overview

A collection of use cases enabled by DIVA Protocol

This section illustrates example use cases of derivatives issued on DIVA Protocol. Independent of the use case, a user can gain exposure to the up- or downside of the underlying metric in three different ways:

* :dollar: **Buy:** The easiest way to participate in the up- or downside of an asset/metric is to simply buy existing long or short position tokens on the market. This, however, assumes that there are market participants willing to sell the corresponding position tokens at a reasonable price.&#x20;
* :sweat\_drops: **Add liquidity:** If there is a lack of market participants willing to sell at a reasonable price, a user can add liquidity/collateral to the corresponding contingent pool to mint short and long position tokens and put either the long or short side for sale depending on the users' view.
* :gear: **Create a new contingent pool:** If there are no markets that meet a user's needs with regards to underlying metric, payoff profile and/or oracle, a user can create a new contingent pool/position tokens themselves. After receiving the short and long position tokens, the user would put either the long or short side for sale depending on their view.

{% hint style="info" %}
Note that the only difference between adding liquidity and creating a new contingent pool is that latter allows a user to configure the contingent pool parameters themselves while in former this was already done.
{% endhint %}

All the examples in the following sections assume that there exist no market yet and participants have to configure the markets for their particular use case first. In practice, most markets will have already been created and users will be able buy them directly without the need to configure new contingent pools.


# Insurance

Example insurance products that can be built on top of DIVA Protocol

Users can use DIVA Protocol to create a wide range of insurance products. In an insurance, the insurance taker is paying a fee to transfer unwanted risks. The party accepting those risks in return for a fee payment is referred to as insurance seller. As opposed to betting, in an insurance the two parties involved have a preference for the same outcome (e.g., the house doesn't burn down).&#x20;

This section gives a few examples of insurance products that can be created using DIVA Protocol.


# Credit default protection

A product that offers default protection to lenders in an undercollateralized loan

Bob has provided an undercollateralized loan to a DAO using a DeFi protocol. He is concerned that the DAO may not repay the loan in full and he will lose money. Bob would like to protect himself against a (partial) default by purchasing a position whose payout increases as the repayment amount decreases.

### :gear: Pool configuration

Bob uses the DIVA App to create a credit insurance product with the following configuration:

![Example configuration for a credit default insurance product in the DIVA App using a linear payoff profile.](/files/6LGs7uRF1B1TY4xkVWCU)

Notes:

1. The Reference Asset is the on-chain bond address.
2. The Expiry Time is equal to the maturity/grace period end of the bond.
3. Given the on-chain nature of the loan, the repayment amount information is stored on-chain providing a fully trustless oracle for settlement.

### :handshake: Sell long position tokens

After creating the pool, Bob puts all long position tokens for sale (1'000'000 in total in our example), for a price of USDC 0.95 each. Alice purchases all long position tokens for a total of USDC 950'000. After the trade, the two parties end up with the following positions:

![Payoff profiles for Bob and Alice.](/files/TZ1R8W8oRvNMdrDPurFi)

Bob's net contribution / premium paid for the credit default insurance (short position) after the sale is USDC 1'000'000 - 950'000 = USDC 50'000.

### 💵 Payoff scenarios

1\) DAO has repaid the full loan amount (USDC 1'000'000):

* Bob paid a premium of USDC 50'000 but doesn't receive any payout from the short position as the loan was fully repaid: \
  -> <mark style="color:orange;">**net loss for Bob: USDC 50'000**</mark>\
  -> <mark style="color:green;">**net gain for Alice: USDC 50'000**</mark> (5.26% on USDC 950'000)

2\) DAO has repaid 50% of the loan (USDC 500'000):

* Bob paid a premium of USDC 50'000 and receives USDC 500'000 as payout due to partial repayment of the loan:\
  -> <mark style="color:green;">**net gain for Bob: USDC 450'000**</mark>\
  -> <mark style="color:orange;">**net loss for Alice: USDC 450'000**</mark>

3\) DAO doesn't repay the loan (USDC 0):

* Bob paid a premium of USDC 50'000 and receives USDC 1'000'000 as payout due to a full default:\
  -> <mark style="color:green;">**net gain for Bob: USDC 950'000**</mark>\
  -> <mark style="color:orange;">**net loss for Alice: USDC 950'000**</mark>


# Agrarian insurance

How DIVA Protocol can help unlock affordable insurance for farmers

<https://www.divaprotocol.io/posts/diva-how-diva-protocol-can-help-unlock-affordable-insurance-for-farmers>


# DeFi Hack insurance

An insurance product that protects users in the event of a protocol hack

Bob has deposited funds into a new DeFi protocol called FutureOfDeFi. He is concerned that it might get hacked and he may lose all his funds. Bob would like to protect himself by buying an insurance against such an event. In other words, he would like to purchase a position that will pay out a certain amount of money in the event of a hack and zero otherwise.

The FutureOfDeFi team would like to offer such an insurance product to their users to signal confidence in the security of their protocol. In other words, they are willing to accept the risk of losing a certain amount of money (which they have to deposit upfront) in the event of a hack in exchange for a fee (also referred to as "premium").

### :gear: Pool configuration

As there is no existing market, the FutureOfDeFi team uses the DIVA App to create those directionally reversed positions using the following configuration (the oracle is defined in a second step and not displayed below):

![Example configuration for a DeFi Hack insurance product in the DIVA App using a binary payoff profile.   ](/files/kWQ4CoZXfS6fe3DuXd6E)

{% hint style="info" %}

* Note that any outcome value **below inflection** (which is 1 in our example) means **"not hacked"** and any value **equal to or above inflection** means **"hacked"**.
  {% endhint %}

### :handshake: Sell long position tokens

After creating the pool, the FutureOfDeFi team puts 100 long position tokens for sale, for a price of DAI 0.03 each, and keeps the short position tokens. Bob purchases all long position tokens for a total of DAI 3. After the trade, the two parties end up with the following positions:

![Payoff profiles for Bob and FutureOfDeFi team for 100 long/short tokens, each paying out a maximum amount of DAI 1.0 per token. Floor and Cap are automatically set equal to inflection in the background to achieve a binary shaped payoff profile.](/files/YWe6xylYr9R3BGDVIG4h)

### 💵 Payoff scenarios

1\) FutureOfDeFi was hacked (final value=1):

* The FutureOfDeFi team received a premium of DAI 5 from selling the long position tokens to Bob, but loses the collateral that they initially deposited into the pool \
  -> <mark style="color:orange;">**net loss for FutureOfDeFi: DAI 95**</mark>\
  -> <mark style="color:green;">**net gain for Bob: DAI 95**</mark>

2\) FutureOfDeFi was not hacked (final value=0):

* The FutureOfDeFi team can redeem all the collateral that they initially deposited into the pool (DAI 100) and in addition keep the premium of DAI 5\
  -> <mark style="color:green;">**net gain for FutureOfDeFi: DAI 5**</mark> (5% yield on initially deposited capital)\
  -> <mark style="color:orange;">**net loss for Bob: DAI 5**</mark>

### :rainbow: Variations

Instead of using a binary metric ("hacked" or "not hacked"), the FutureOfDeFi team could have chosen the USD amount stolen during a hack as the underlying metric and attach a cliff shaped pattern to it. Below an example configuration using the DIVA App:

![Example configuration of a DeFi Hack insurance products using a non-binary underlying metric and payoff profile.](/files/8RbKsOPzeved1yf8YHPL)

After a trade, the two parties would end up with the following positions:

![Payoff profiles for Bob and FutureOfDeFi team for 100 long/short tokens, each paying out a maximum amount of DAI 1.0 per token.](/files/L3W1swz78ZUdoa1kUoiM)

In this example, if the protocol is hacked, there will be a linearly increasing payout for Bob in the range $10mln to $70mln and a jump to the maximum payoff if the hacked amount exceeds $70mln.


# Peg insurance

An insurance product that protects users from de-pegging of stablecoins

Bob is holding USDT and would like to protect himself from the event of it losing its peg to the US dollar. Alice is holding USDT as well and is quite confident that it will hold its peg. Alice would like to earn some additional yield on her stablecoin holdings by selling insurance to Bob.

### :gear: Pool configuration

Alice uses the DIVA App to create a peg insurance product with the following configuration: &#x20;

![Example configuration for a peg insurance product in the DIVA App.](/files/DF416jRStu0ub6XvefZl)

### :handshake: Sell short position tokens

After creating the pool, Alice sells all 100 short position tokens minted for a total of USDT 3 to Bob and keeps the long position tokens. The payoff profiles for Alice and Bob are depicted below:

![](/files/P4voNtgcImb3aAWRoZkH)

### 💵 Payoff scenarios

1\) USDT >= 1.0:

* Alice can redeem her initially deposited collateral of USDT 100 and keep the premium for selling the short position tokens to Bob for USDT 3 \
  -> <mark style="color:green;">**net gain for Alice: USDT 3**</mark> (3% yield on her initial investment)\
  -> <mark style="color:orange;">**net loss for Bob: USDT 3**</mark>&#x20;

2\) USDT/USD = 0.95:

* Alice received a premium of USDT 3 for selling the short position tokens to Bob but loses 50% / USDT 50 of her initially deposited collateral \
  -> <mark style="color:orange;">**net loss for Alice: USDT 47**</mark>\
  -> <mark style="color:green;">**net gain for Bob: USDT 47**</mark>

3\) USDT/USD <= 0.925:

* Alice received a premium of USDT 3 for selling the short position tokens to Bob but loses the collateral of USDT 100 that she initially deposited\
  -> <mark style="color:orange;">**net loss for Alice: USDT 97**</mark>\
  -> <mark style="color:green;">**net gain for Bob: USDT 97**</mark>

### :rainbow: Variations

Instead of using the value of UST/USD at some specific point in the future as the underlying metric, Alice could have chosen the following metrics alternatively:

* Average UST/USD value over the lifetime of the derivative
* Minimum UST/USD value during the lifetime of the derivative

Also, instead of using a linear payoff curve, she could have used a binary pattern or a combination of both (rug/cliff shape).&#x20;


# Yield optimization

Earn additional yield on otherwise idle sitting assets

Derivatives are powerful tools when it comes to earning additional yield on otherwise idle sitting assets. This section presents two strategies how to accumulate more of an asset that users intend to hold for a long time, both in a bullish as well as in a bearish market environment.&#x20;


# Bullish accumulation

Accumulating long-term holdings in a bullish market environment

Bob owns 100 ETH and wants to accumulate more of it. Lending out ETH for a month is not an option as it only yields 0.01%. Bob is willing to accept some small risk of losing his ETH in exchange for a higher yield. His conservative estimate is that ETH/USD will be above $2'000 in a month. The current ETH price is $3,500.

Alice is bearish on ETH/USD and believes that the price will be below $2'000 in a month. She would like to benefit when the price goes down.

### :gear: Pool configuration

Bob uses the DIVA App to create a long position that is going to return his deposited collateral when ETH/USD stays above $2'000. Bob's yield comes from selling the short position to Alice. An example configuration is provided below:&#x20;

![Example configuration of a low risk yield product using the DIVA App.](/files/rAOskPf29pIAHCKNNUX6)

### :handshake: Sell short position tokens

After creating the pool, Bob sells all 100 short position tokens minted for a total of WETH 3 to Alice and keeps the long position tokens. The payoff profiles for Alice and Bob are depicted below:

![Bob's payoff profile](/files/qyBjqNEK8F6DvjVsog49)

![Alice's payoff profile](/files/ny5jpUFDmotC6jV3h3el)

### 💵 Payoff scenarios

1\) ETH/USD >= $2'000:

* Bob can redeem his collateral of 100 WETH and keep the premium of 3 WETH from selling the short position tokens to Alice \
  -> <mark style="color:green;">**net gain for Bob: WETH 3**</mark> (+3% in a month, +36% in a year).\
  -> <mark style="color:orange;">**net loss for Alice: WETH 3**</mark>

2\) ETH/USD = $1'250:

* Bob can redeem WETH 25 of his collateral and keep the premium of 3 WETH\
  -> <mark style="color:orange;">**net loss for Bob: WETH 72**</mark>\
  -> <mark style="color:green;">**net gain for Alice: WETH 72**</mark> (24x on her investment)

3\) ETH/USD = $800:

* Bob received a premium of 3 WETH and loses the initially deposited collateral of WETH 100\
  -> <mark style="color:orange;">**net loss for Bob: DAI 97**</mark>\
  -> <mark style="color:green;">**net gain for Alice: DAI 97**</mark> (32.3x on her investment)


# Bearish accumulation

Accumulating long-term holdings in a bearish market environment

Alice owns 100 ETH and wants to accumulate more of it. The market environment is bearish and she believes that it will stay like that for a while with ETH/USD dropping below $1‘000 within six months, 71% down from its current value of $3‘500. Alice wants to capitalize on her view, but she doesn’t want to lose more than 3 ETH if she turns out to be wrong.&#x20;

One potential strategy involves selling 24 ETH at the current price of $3‘500 and buying back at $4‘000, hence locking in a loss of 3 ETH if she turns out to be wrong and ETH price continues to rise. If she is right and the price drops to $1‘000, she will be able to buy back 84 ETH increasing her holdings from 100 to 184 ETH (+84%).&#x20;

Alice can achieve a higher return without taking additional risk by using derivatives. More precisely, Alice could create a deep out of the money short position, paying 3 ETH to hold it. If ETH price is at or below $1‘000 in six months, Alice will receive 100 ETH resulting in new total holdings of 197 ETH (+97% in a month), 13 ETH more compared to simply selling the asset and buying it back later.

### ​:gear: Pool configuration <a href="#pool-configuration" id="pool-configuration"></a>

Alice could use the following parameters to configure the desired short position using the DIVA App:

![Example configuration for a short position on ETH/USD](/files/rWPVqj6UG6Cu0pHN7bPF)

### ​🤝Sell long position tokens <a href="#sell-short-position-tokens" id="sell-short-position-tokens"></a>

After creating the pool, Alice sells all 100 long position tokens minted for a total of WETH 97 to Bob and keeps the short position tokens, effectively paying a price of WETH 3 for the 100 short position tokens she has minted.&#x20;


# Risk management

Use derivatives to protect against adverse events

Derivatives are powerful tools to protect against adverse movements. In this section, we give two examples how users can protect themselves against falling asset prices as well as rising ETH gas fees.&#x20;


# Downside protection

Protecting against falling prices

Alice bought 1 ETH at $500 a few months back and the asset has performed strongly since then with current price standing at $3‘500. While she still sees a lot of upside in ETH and wants to participate in it, she also wants to start protecting some of her USD gains. In particular, she wants to lock in a price of $3'000 per ETH.

Alice would like to create a position that increases in value and thereby neutralizes the loss in her ETH holdings as ETH/USD drops below $3'000. The protection mechanism is illustrated below:

![An example strategy to limit the downside of Alice's ETH holdings using short position tokens](/files/bJSfzm80TE8mO39WZyCg)

### :gear: Pool configuration

To achieve her goal, Alice creates a contingent pool with following configuration using the DIVA App:

![Example configuration of a downside protection position using the DIVA App.](/files/tWoLmUQ6FVgCvkImEvK1)

### :handshake: Sell long position tokens

After creating the pool, Alice sells all 3'000 long position tokens minted for a total of USDC 2'700 to Bob and keeps the short position tokens.

### 💵 Payoff scenarios

1\) ETH/USD >= $3'000:

* Alice paid a protection premium of USDC 300 (3'000 initially deposited and 2'700 received back due to the sale of the long side) and didn't receive any payout from her short position as the price stayed above $3'000.\
  -> <mark style="color:orange;">**net loss for Alice: USDC 300**</mark>\
  -> <mark style="color:green;">**net gain for Bob: USDC 300**</mark>

2\) ETH/USD = $2'000:

* Alice paid a protection premium of USDC 300 and received USDC 1'000 from her short position\
  -> <mark style="color:green;">**net gain for Alice: USDC 700**</mark> (neutralizing the loss in her ETH holdings)\
  -> <mark style="color:orange;">**net loss for Bob: USDC 700**</mark>


# Increasing cost protection

Protecting against increasing costs

Bob is developing a smart contract and plans to deploy it in a month. He is concerned that the ETH gas price may go up by then increasing deployment costs. He would like to lock in a gas fee at a maximum of 150 Gwei.&#x20;

Bob would like to create a position that increases in value as the ETH gas price exceeds 150 Gwei thereby neutralizing the increase in deployment costs. The strategy is illustrated below:&#x20;

![An example strategy to protect against increasing gas costs using long position tokens on ETH gas price](/files/EFL890MGaeMCD1Osw9u7)

Alice is willing to take the other side as she believes that the ETH gas price will remain below 150 Gwei due to reduced activity in the prevailing bearish market environment.

### :gear: Pool configuration

Bob uses the DIVA App to configure a contingent pool that gives him the desired long position.

![Example configuration for a product that protects against increasing gas prices](/files/68mWQ5iSvRXX0uaPi7jL)

### ​🤝Sell short position tokens <a href="#sell-long-position-tokens" id="sell-long-position-tokens"></a>

After creating the pool, Bob sells all 5 short position tokens minted for a total of WETH 4.8 and keeps the long position tokens.

### 💵 Payoff scenarios

1\) ETH Gas Price <= 150 Gwei:

* Bob paid a protection premium of WETH 0.2 (5 initially deposited and 4.8 received back due to the sale of the short side) and didn't receive any payout from his long position as the gas price ended up below 150 Gwei.\
  -> <mark style="color:orange;">**net loss for Bob: WETH 0.2**</mark>\
  -> <mark style="color:green;">**net gain for Alice: WETH 0.2**</mark>

2\) ETH/USD = 350 Gwei:

* Bob paid a protection premium of WETH 0.2 and can redeem all his initially deposited collateral of WETH 5 as the gas price ended up above the cap:\
  -> <mark style="color:green;">**net gain for Bob: WETH 4.8**</mark> (which he uses to neutralize the increased deployment costs)\
  -> <mark style="color:orange;">**net loss for Alice: WETH 4.8**</mark>


# Directional bets

Short and long assets in one single step

Users can use derivatives to benefit from up or down movements of an underlying asset. This sections gives two examples, one for each direction.&#x20;


# Downside bet

How to benefit from the downside of an asset with one single transaction

Alice believes that the Bitcoin price will drop from its current level of $37’000. Shorting an asset the traditional way is pretty cumbersome as it involves four steps: 1) borrow BTC, 2) sell it for USD, 3) buy BTC back (at hopefully lower prices), and 4) give back BTC to the lender plus some interest. Alice wants a simple way to participate in the downside of BTC.

Alice could use the DIVA App to create short positions with one of the below example shapes.&#x20;

![Example payoff profiles of short positions on BTC/USD](/files/J6P5Qb9oduOmikakQaBp)

### :gear: Pool configuration

The example configuration for the above three patterns

![Short position on BTC/USD with a linear short position payoff profile](/files/T9bNC3O7OY7fRtilw805)

![Short position on BTC/USD with a rug short position payoff profile](/files/5vR0GyvnF8HcRBQFDKyj)

![Short position on BTC/USD with a binary short position payoff profile](/files/G7FlNjtg7dP0hAyIN2E7)

### 🤝Sell long position tokens <a href="#sell-long-position-tokens" id="sell-long-position-tokens"></a>

After the creation of the pool, Alex would sell the long position tokens and keep the short position tokens.


# "Bottom-Is-In" bet

[Sassal](https://twitter.com/sassal0x/status/1525999745780486146?s=20\&t=t0j1MnsvS3iodhhV_UzY4Q) wants to make a bet with his Twitter friends that ETH's recent drop to $1'700 has marked a bottom. In other words, Sassal would like to create two opposing positions, one that will lose in value if ETH/USD drops below $1'700 (long position owned by Sassal) and one that will gain in the same scenario (short position owned by everyone betting against Sassal).&#x20;

Instead of a binary loss curve with a jump at $1'700, Sassal prefers to have a linear loss curve in the range $1'500 and $1'700. That is, if the ETH price drops slightly below $1'700, he will lose some of his stake but not all. Only if the ETH price drops below $1'500, then Sassal will lose his full stake.

Sassal would like to put WETH at stake. If he is right, he will end up with more WETH.

### :gear: Market configuration

Sassal can use DIVA Protocol to create the desired positions with the following configuration:

<table><thead><tr><th width="150">Input</th><th>Values</th></tr></thead><tbody><tr><td>Event</td><td><ul><li>Reference asset: "Min ETH/USD"</li><li>Expiry time: 31/12/2022 12:00am UTC</li></ul></td></tr><tr><td>Payoff</td><td><ul><li>Floor: 1'500</li><li>Inflection: 1'600</li><li>Cap: 1'700</li><li>Gradient: 0.5</li></ul></td></tr><tr><td>Collateral</td><td><ul><li>Asset: WETH</li><li>Amount: 100</li></ul></td></tr><tr><td>Oracle</td><td><ul><li>Tellor (0x123...fde)</li></ul></td></tr></tbody></table>

The resulting payoff profiles of the two positions are illustrated below:

![Long and short positions for Sassal's bottom-is-in bet](/files/H6EkUbvjm4qWsLvGIH6c)

For the resolution of the market, Sassal assigns the whitelisted Tellor protocol as the data provider.

### 🧙‍♂️ Mint long and short position tokens&#x20;

Sassal deposits 100 WETH to mint the two position tokens. He then sells the short position tokens for a total of 40 WETH. This results in a net deposit/stake of 60 WETH for Sassal.

### ⌛ Settlement

End of year (expiration), the oracle reports the minimum value of ETH/USD during the lifetime of the bet and thereby determines the payoffs for long and short position tokens. Users can then claim their share in the collateral by sending back their position tokens.

### ⚡ Payout scenarios:

* $1'700 was really the bottom (i.e. min ETH/USD >= $1'700): Sassal can return the 10 WETH that he initially deposited and keep the 3 WETH from the sale of the short position -> <mark style="color:green;">**+30% net gain**</mark>
* ETH/USD dips below $1'700: Let's look at two possible scenarios:
  * ETH/USD drops to $1'600: Sassal will lose 50% (5 WETH) of his initially deposited collateral and keep the 3 WETH from the sale of the short position -> <mark style="color:orange;">**-20% net loss**</mark>
  * ETH/USD drops below $1'500: Sassal will lose 100% (10 WETH) of this initially deposited collateral and keep the 3 WETH from the sale of the short position -> <mark style="color:orange;">**70% net loss**</mark>

Note that the payouts depend on the payoff profile. A less risky payoff profile would involve moving the floor lower and thereby slowing down the loss incurred when ETH drops below the $1'700 mark.


# Upside bet

:construction: under construction :construction:&#x20;


# "Top-Is-In" bet

Same as [Bottom-Is-In bet](/use-cases/directional-bets/bottom-is-in-bet) but using max ETH/USD as the underlying metric instead of min ETH/USD.&#x20;


# Leverage

:construction: under construction :construction:&#x20;


# Introduction

What drives the value of derivative asset

The price of a derivative asset and its sensitivity is driven by uncertainty about the outcome of the underlying and hence the uncertainty about the payoff of the derivative asset. The lower the uncertainty, the closer the price is tracking the actual payoff curve. The higher the uncertainty, the higher the divergence between the price and the underlying payoff curve. This basic concept is illustrated in below chart for a long position:

![Price payoff relation of a long derivative asset ](/files/wwgEvkEfq6MxPx3MLsIe)

The grey arrows in the chart indicate the convergence of the price curve towards the payoff curve as the uncertainty about the outcome of the underlying decreases.

The following factors impact the perceived uncertainty and hence the price of a derivative asset:

* **Current underlying value:** The higher the current underlying value, the higher the price of a long position all else equal.
* **Volatility**: The higher the expected volatility of an underlying asset, the higher the chances of a large payoff for the holder of the derivative, the higher the price of the derivative all else equal.&#x20;
* **Time until expiration**: The less time remaining until expiration, the higher the certainty about the final payoff of the derivative asset, hence the closer the price is tracking the actual payoff of the derivative asset.&#x20;

As the maximum payout of position tokens issued by the DIVA Protocol is 1 unit of the collateral asset, the price of a position token always ranges between 0 and 1 and hence can be thought of as a probability. Further, the price is always quoted in the collateral asset. For example, if the collateral asset is WBTC, then the price would represent how much WBTC to pay in order to get a chance for a maximum payoff of 1 WBTC.&#x20;

The goal of this section is to give some intuition behind each of these value drivers for non-technical readers.


# Underlying value

:construction: under construction :construction:


# Volatility

:construction: under construction :construction:&#x20;


# Time

:construction: under construction :construction:&#x20;


# Overview

List of trusted oracles

Oracles play a crucial role in DIVA Protocol by reporting outcomes that determine the payoffs for long and short position tokens.

To ensure reliable data, the table below presents a list of trusted decentralized oracle options for use in DIVA Protocol. To utilize any of these oracles, simply assign the corresponding data provider address to the dataProvider field when creating a pool.

Currently, [Tellor protocol](https://tellor.io/) has been integrated as the initial decentralized oracle provider, and as the protocol progresses, additional oracle integrations will be incorporated to enhance functionality and choice.

<table><thead><tr><th>Oracle</th><th width="549">Data Provider Address</th><th>Networks</th><th>Description</th><th>Audited</th><th>Socials</th></tr></thead><tbody><tr><td>Tellor protocol</td><td><code>0x7950db13cc37774614b0aa406e42a4c4f0bf26a6</code></td><td><a href="https://etherscan.io/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6">Ethereum</a>, <a href="https://polygonscan.com/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6">Polygon</a>, <a href="https://arbiscan.io/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6">Arbitrum One</a>, <a href="https://gnosisscan.io/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6">Gnosis</a></td><td><a href="https://github.com/divaprotocol/oracles/blob/main/docs/Tellor.md">Docs</a></td><td><a href="https://github.com/divaprotocol/diva-protocol-v1/blob/main/audits/Final%20April%202023/Summary.md#tellor-oracle-adapter">✅</a></td><td><a href="https://tellor.io/">Website</a>, <a href="https://discord.gg/tellor">Discord</a>, <a href="https://twitter.com/WeAreTellor">Twitter</a></td></tr></tbody></table>

The following sections provide an overview on how each of the oracles function.


# Tellor

A highly flexible permissionless oracle protocol

Tellor is a decentralized and permissionless oracle protocol for answering **any question** of **any format** on-chain. Data is provided by a network of reporters running Telliot, an open-source reporting client. The oracle mechanism works by using simple crypto-economic incentives to secure data through staking and dispute mechanisms, while the community is bound by a token which utilizes anonymous governance system and monetary policy to reward and motivate adoption and development of the network.

### Available oracles

The table below lists reliable decentralized oracle options for DIVA Protocol. Currently, [Tellor protocol](https://tellor.io/) has been integrated as the first decentralized oracle provider. To use it, simply assign the the data provider address as the `dataProvider` field when creating a pool. As the protocol continues to evolve, the list of oracle integrations will expand over time.

<table><thead><tr><th>Oracle</th><th width="549">Data Provider Address</th><th>Networks</th><th>Description</th><th>Audited</th><th>Socials</th></tr></thead><tbody><tr><td>Tellor protocol</td><td><code>0x7950db13cc37774614b0aa406e42a4c4f0bf26a6</code></td><td><a href="https://etherscan.io/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6">Ethereum</a>, <a href="https://polygonscan.com/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6">Polygon</a>, <a href="https://arbiscan.io/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6">Arbitrum One</a>, <a href="https://gnosisscan.io/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6">Gnosis</a></td><td><a href="https://github.com/divaprotocol/oracles/blob/main/docs/Tellor.md">Docs</a></td><td><a href="https://github.com/divaprotocol/diva-protocol-v1/blob/main/audits/Final%20April%202023/Summary.md#tellor-oracle-adapter">✅</a></td><td><a href="https://tellor.io/">Website</a>, <a href="https://discord.gg/tellor">Discord</a>, <a href="https://twitter.com/WeAreTellor">Twitter</a></td></tr></tbody></table>

❗**IMPORTANT:**

* Prior to utilizing any of the listed oracles, please ensure that your specific data point is supported.
* Users should exercise caution and avoid interacting with pools that utilize untrusted oracles.

### <mark style="color:blue;">Oracle details</mark>

* Type: [Smart contract](https://github.com/divaprotocol/oracles)
* Address: 0x2f4218C9262216B7B73A76334e5A98F3eF71A61c

#### <mark style="color:blue;">Data feeds</mark>

* BTC/USD, ETH/USD

#### <mark style="color:blue;">Networks</mark>

* Ropsten

#### <mark style="color:blue;">Functionality</mark>

* Tellor reporters monitor the [DIVA subgraph](https://thegraph.com/hosted-service/subgraph/divaprotocol/diva-ropsten) for expired pools and submit values where the Tellor oracle was selected as the data provider.&#x20;
* A value reported to the Tellor system is considered valid if it remains undisputed for at least 1 hour. After that delay, anyone can trigger the`setFinalReferenceValue` function inside the [oracle contract](https://github.com/divaprotocol/oracles) to push the value to the DIVA Protocol. Position token holders that are in the money are particularly incentivized to trigger that function.
* After the value has been pushed into DIVA Protocol, the payoffs per long and short position token are calculated and users can start redeeming their position tokens. The possibility to challenge the value inside DIVA Protocol is deactivated for this oracle.
* Position token holders can submit values themselves to the Tellor protocol.

#### <mark style="color:blue;">Fallback</mark>

* If the oracle doesn't report a value within the 24h submission window following pool expiration, DIVA's fallback provider will have 5 days to step in and report a value.
* If the fallback data provider fails to report a value, then the final value will default to inflection.

#### <mark style="color:blue;">Risk disclaimer</mark>

* Reporters may not report any values if the expected gas costs exceed the expected fee reward. In particular, this applies to pools with a low remaining collateral balance. In those cases, position token holders will be able report the values to the Tellor protocol via the DIVA App themselves.
* A wrong value is not disputed for more than 1 hour. Tellor's dispute system is considered robust enough to identify inaccurate value submission before the 1 hour delay expires. If the 1 hour delay turns out to be insufficient, DIVA governance can increase it up to 18 hours.

### <mark style="color:blue;">Links</mark>

* Homepage: <https://tellor.io/>
* Discord: <https://discord.gg/tellor>
* Docs: <https://docs.tellor.io/tellor/>
* Telliot software: <https://github.com/tellor-io/telliot-feed-examples>
* DIVA Oracle specs: <https://github.com/tellor-io/dataSpecs/blob/main/types/DIVAProtocolPolygon.md>


# Overview

DIVA Protocol is a smart contract that takes care of all the logic used to create and settle derivative assets. Web3 developers do not need to write any smart contracts themselves but can fully focus on building the best user experiences for creating and settling insurance, prediction/betting or swap type of products.&#x20;

This section provides an overview on how to interact with the DIVA Protocol functions and how to leverage the DIVA subgraph to query all relevant information. At the end of this section, a few project ideas are presented.&#x20;


# Technical resources

Collection of technical resources about the DIVA protocol

A technical system summary including contract descriptions, function descriptions, and more is available in the DIVA README.

## Technical papers

* [Oracle specs](https://github.com/divaprotocol/oracles/blob/main/README.md)
* [Original whitepaper](https://www.diva.finance/pdf/DIVA_Whitepaper_v1.0.0.pdf) (version as of 8th May 2021; may include outdated elements)

## Security audits

* Peckshield May 2022

{% file src="/files/A1StehuQp3yP4mjGQeoR" %}

## Slides

* Link to slides (TODO)

## Code base

* [Github repository](https://github.com/divaprotocol/diva-contracts)


# Smart contracts

:construction: this section is currently under construction - it will be finalized after the smart contract audit has been completed :construction:

All DIVA smart contract functions, expected inputs and outputs are summarized in the following sections.


# Functions

:construction: under construction - will be completed after the smart contract audit :construction:


# Core protocol functions

Core functions to issue and settle derivative assets using DIVA Protocol

### Create a contingent pool

```
function createContingentPool(
    PoolParams calldata _poolParams
) 
    external;
```

where `PoolParams` contains the following list of parameters in the corresponding order:

<table><thead><tr><th width="204.37209302325581">Parameter</th><th width="150" align="center">Type</th><th width="150">Category</th><th>Description</th></tr></thead><tbody><tr><td><code>referenceAsset</code></td><td align="center">string</td><td>Event</td><td>The metric or event whose outcome will determine the payout for long and short position tokens.</td></tr><tr><td><code>expiryTime</code></td><td align="center">uint96</td><td>Event</td><td>Expiration time of position tokens expressed as a unix timestamp in seconds. The value of the reference asset observed at that point in time determines the payoffs for long and short position tokens.</td></tr><tr><td><code>floor</code></td><td align="center">uint256</td><td>Payoff</td><td>Value of the reference asset at or below which the long token pays out 0 and the short token 1 (max payout). Input expects an integer with 18 decimals.</td></tr><tr><td><code>inflection</code></td><td align="center">uint256</td><td>Payoff</td><td>Value of the reference asset at which the long token pays out <code>gradient</code> and the short token <code>1-gradient</code>. Input expects an integer with 18 decimals.</td></tr><tr><td><code>cap</code></td><td align="center">uint256</td><td>Payoff</td><td>Value of the reference asset at or above which the long token pays out 1 (max payout) and the short token 0. Input expects an integer with 18 decimals.</td></tr><tr><td><code>gradient</code></td><td align="center">uint256</td><td>Payoff</td><td>Long token payout at inflection (value between 0 and 1). Input expects an integer with 18 decimals.</td></tr><tr><td><code>collateralAmount</code></td><td align="center">uint256</td><td>Payoff</td><td>Collateral amount to be deposited into the pool to back the position tokens. Input expects an integer with collateral token decimals.</td></tr><tr><td><code>collateralToken</code></td><td align="center">address</td><td>Settlement asset</td><td>Address of the ERC20 collateral token.</td></tr><tr><td><code>dataProvider</code></td><td align="center">address</td><td>Oracle</td><td>Ethereum account (EOA or smart contract) that will report the final reference asset value.</td></tr><tr><td><code>capacity</code></td><td align="center">uint256</td><td>Pool size</td><td>Maximum collateral amount that a contingent pool can accept. Choose a large number (e.g., <code>2**256 - 1</code>) for unlimited size. Input expects an integer with collateral token decimals.</td></tr></tbody></table>

### Adding liquidity

Add liquidity to an existing pool using the following function:

```
function addLiquidity(
    uint256 _poolId,                // Id of the pool that a user wants to add collateral to
    uint256 _collateralAmountIncr   // Incremental collateral amount to be added to the pool expressed as an integer with collateral token decimals
) 
    external;
```

### Removing liquidity

Remove liquidity from an existing pool using the following function:

```
function removeLiquidity(
    uint256 _poolId,  // Id of the pool that a user wants to remove collateral from 
    uint256 _amount   // Number of position tokens to return (expressed as an integer with position token decimals)
) 
    external;
```


# Getter functions


# Setter functions


# ABI


# Contract addresses


# Example scripts

A collection of example nodejs scripts to interact with the DIVA smart contract functions is provided here: <https://github.com/divaprotocol/diva-monorepo/tree/main/packages/diva-scripts>


# TheGraph

In this section, developers can learn how to query data from the DIVA and Whitelist subgraph.&#x20;

{% hint style="info" %}
Note that the current version of the subgraphs refers to version 0.9.0 of the DIVA Protocol. The subgraphs and the examples herein will be updated after the smart contract audit has been completed (that's when DIVA Protocol v1 will be released).
{% endhint %}


# DIVA subgraphs

Data emitted as the result of DIVA smart contract interactions is indexed using TheGraph.&#x20;

The DIVA subgraph can be accessed here:&#x20;

* Ropsten (deprecated): <https://thegraph.com/hosted-service/subgraph/divaprotocol/diva-ropsten>
* Goerli: <https://thegraph.com/hosted-service/subgraph/divaprotocol/diva-goerli>

### Pool data

The following query can be used to pull the data for a given pool Id (here pool Id = 5):

```
{
  pools(where: {id: 5}) {
    id
    referenceAsset
    floor
    inflection
    cap
    supplyInitial
    supplyShort
    supplyLong
    expiryTime
    collateralToken {
      id
      name
      symbol
      decimals
    }
    collateralBalanceShortInitial
    collateralBalanceLongInitial
    collateralBalance
    shortToken {
      id
      name
      symbol
      decimals
    }
    longToken {
      id
      name
      symbol
      decimals
    }
    finalReferenceValue
    statusFinalReferenceValue
    redemptionAmountLongToken
    redemptionAmountShortToken
    statusTimestamp
    dataProvider
    redemptionFee
    settlementFee
    createdBy
    createdAt
    
  }
}

```

Sample output from the above query:

```
{
  "data": {
    "pools": [
      {
        "id": "5",
        "referenceAsset": "ETH/USD",
        "floor": "2000000000000000000000",
        "inflection": "2000000000000000000000",
        "cap": "4500000000000000000000",
        "supplyInitial": "100000000000000000000",
        "supplyShort": "100000000000000000000",
        "supplyLong": "100000000000000000000",
        "expiryTime": "1647363501",
        "collateralToken": {
          "id": "0x867e53fede91d27101e062bf7002143ebaea3e30",
          "name": "WAGMI18",
          "symbol": "WAGMI18",
          "decimals": 18
        },
        "collateralBalanceShortInitial": "50000000000000000000",
        "collateralBalanceLongInitial": "50000000000000000000",
        "collateralBalance": "100000000000000000000",
        "shortToken": {
          "id": "0x4f946061de10a369de7e689f368053959a67a58e",
          "name": "S5",
          "symbol": "S5",
          "decimals": 18
        },
        "longToken": {
          "id": "0x33aa4370599755b83915dcc87c8eced8a5b9b1d2",
          "name": "L5",
          "symbol": "L5",
          "decimals": 18
        },
        "finalReferenceValue": "80000000000000000000",
        "statusFinalReferenceValue": "Challenged",
        "redemptionAmountLongToken": "0",
        "redemptionAmountShortToken": "0",
        "statusTimestamp": "1647381997",
        "dataProvider": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
        "redemptionFee": "2500000000000000",
        "settlementFee": "500000000000000",
        "createdBy": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
        "createdAt": "1647363941"
      }
    ]
  }
}
```

### Data providers

Data providers that want to listen to pools where they are selected as the data provider can use the following reduced version of the pool query (here using address 0x9adefeb576dcf52f5220709c1b267d89d5208d78 as the data provider, all in small letters):

```
{
  pools (where: {dataProvider: "0x9adefeb576dcf52f5220709c1b267d89d5208d78"}) {
    id
    dataProvider
    referenceAsset
    floor
    inflection
    cap
    expiryTime
    createdAt
  }
}
```

Sample output of the above query:

```
{
  "data": {
    "pools": [
      {
        "id": "10",
        "dataProvider": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
        "referenceAsset": "BTC/USD",
        "floor": "60000000000000000000000",
        "inflection": "70000000000000000000000",
        "cap": "90000000000000000000000",
        "expiryTime": "1648112254",
        "createdAt": "1648022403"
      },
      {
        "id": "13",
        "dataProvider": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
        "referenceAsset": "BTC/USD",
        "floor": "40000000000000000000000",
        "inflection": "60000000000000000000000",
        "cap": "80000000000000000000000",
        "expiryTime": "1651269610",
        "createdAt": "1648197988"
      }
    ]
  }
}
```

### Fees

Query to pull the fee claims for a given address (has to be lower case!):

```
feeRecipients(where: {id: "0x9adefeb576dcf52f5220709c1b267d89d5208d78"}) {
    id
    collateralTokens {
      amount
      collateralToken {
        id
        name
        symbol
        decimals
      }
    }
  }
```

Sample output from the above query:

```
{
  "data": {
    "feeRecipients": [
      {
        "id": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
        "collateralTokens": [
          {
            "amount": "32695586760280840",
            "collateralToken": {
              "id": "0x867e53fede91d27101e062bf7002143ebaea3e30",
              "name": "WAGMI18",
              "symbol": "WAGMI18"
            }
          },
          {
            "amount": "30000",
            "collateralToken": {
              "id": "0x8ca8de48c4507fa54a83dde7ac68097e87520eec",
              "name": "WAGMI6",
              "symbol": "WAGMI6"
            }
          }
        ]
      }
    ]
  }
}
```

### Challenge

Query to retrieve the submitted challenges for a given poolId (here poolId = 5):

```
{
  challenges(where: {pool: "5"}) {
    challengedBy
    proposedFinalReferenceValue
    pool {
      id
    }
  }
}
```

Sample output of above query:

```
{
  "data": {
    "challenges": [
      {
        "challengedBy": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
        "proposedFinalReferenceValue": "1670000000000000000000",
        "pool": {
          "id": "5"
        }
      }
    ]
  }
}
```

### User positions

Query to retrieve a shortlist of position tokens that a user may own. The shortlist is constructed based on user interactions with the DIVA Protocol functions as well as 0x protocol. Note that position tokens received via different avenues (e.g., Uniswap or simple transfer) will not appear in the list. &#x20;

```
{
  user(id: "0x9adefeb576dcf52f5220709c1b267d89d5208d78" ){
    id
    positionTokens(first: 100,
      orderDirection: desc,
      orderBy: receivedAt,) {
        receivedAt,
        positionToken {
        id
        name
        symbol
        decimals
        owner
        pool {
          id
          referenceAsset
          floor
          inflection
          cap
          supplyInitial
          supplyShort
          supplyLong
          expiryTime
          collateralToken {
            id
            name
            decimals
            symbol
          }
  				collateralBalanceLongInitial
          collateralBalanceShortInitial
          collateralBalance
          shortToken {
            id
            name
            symbol
            decimals
            owner
          }
          longToken {
            id
            name
            symbol
            decimals
            owner
          }
          finalReferenceValue
          statusFinalReferenceValue
          redemptionAmountLongToken
          redemptionAmountShortToken
          statusTimestamp
          dataProvider
          redemptionFee
          settlementFee
          createdBy
          createdAt
          capacity
          expiryTime
          challenges {
            challengedBy
            proposedFinalReferenceValue
          }
        }
      }
    }
  }
}
```

Sample output of above query

```
{
  "data": {
    "user": {
      "id": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
      "positionTokens": [
        {
          "receivedAt": "1660894980",
          "positionToken": {
            "id": "0xac9bfbeadb47ab2bd8013eb61e1a636fe04aaeb1",
            "name": "S54459",
            "symbol": "S54459",
            "decimals": 18,
            "owner": "0xebbaa31b1ebd727a1a42e71dc15e304ad8905211",
            "pool": {
              "id": "54459",
              "referenceAsset": "REP/USD",
              "floor": "10000000000000000000",
              "inflection": "15000000000000000000",
              "cap": "20000000000000000000",
              "supplyInitial": "10000000000000000000",
              "supplyShort": "10000000000000000000",
              "supplyLong": "10000000000000000000",
              "expiryTime": "1660895400",
              "collateralToken": {
                "id": "0x134e62bd2ee247d4186a1fdbaa9e076cb26c1355",
                "name": "DIVA USD",
                "decimals": 18,
                "symbol": "dUSD"
              },
              "collateralBalanceLongInitial": "5000000000000000000",
              "collateralBalanceShortInitial": "5000000000000000000",
              "collateralBalance": "10000000000000000000",
              "shortToken": {
                "id": "0xac9bfbeadb47ab2bd8013eb61e1a636fe04aaeb1",
                "name": "S54459",
                "symbol": "S54459",
                "decimals": 18,
                "owner": "0xebbaa31b1ebd727a1a42e71dc15e304ad8905211"
              },
              "longToken": {
                "id": "0x88f4b382c2777ac2ba2e3b5c4e7c1d0215074aed",
                "name": "L54459",
                "symbol": "L54459",
                "decimals": 18,
                "owner": "0xebbaa31b1ebd727a1a42e71dc15e304ad8905211"
              },
              "finalReferenceValue": "0",
              "statusFinalReferenceValue": "Open",
              "redemptionAmountLongToken": "0",
              "redemptionAmountShortToken": "0",
              "statusTimestamp": "1660894980",
              "dataProvider": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
              "redemptionFee": "2500000000000000",
              "settlementFee": "500000000000000",
              "createdBy": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
              "createdAt": "1660894980",
              "capacity": "115792089237316195423570985008687907853269984665640564039457584007913129639935",
              "challenges": []
            }
          }
        },
        {
          "receivedAt": "1660894980",
          "positionToken": {
            "id": "0x88f4b382c2777ac2ba2e3b5c4e7c1d0215074aed",
            "name": "L54459",
            "symbol": "L54459",
            "decimals": 18,
            "owner": "0xebbaa31b1ebd727a1a42e71dc15e304ad8905211",
            "pool": {
              "id": "54459",
              "referenceAsset": "REP/USD",
              "floor": "10000000000000000000",
              "inflection": "15000000000000000000",
              "cap": "20000000000000000000",
              "supplyInitial": "10000000000000000000",
              "supplyShort": "10000000000000000000",
              "supplyLong": "10000000000000000000",
              "expiryTime": "1660895400",
              "collateralToken": {
                "id": "0x134e62bd2ee247d4186a1fdbaa9e076cb26c1355",
                "name": "DIVA USD",
                "decimals": 18,
                "symbol": "dUSD"
              },
              "collateralBalanceLongInitial": "5000000000000000000",
              "collateralBalanceShortInitial": "5000000000000000000",
              "collateralBalance": "10000000000000000000",
              "shortToken": {
                "id": "0xac9bfbeadb47ab2bd8013eb61e1a636fe04aaeb1",
                "name": "S54459",
                "symbol": "S54459",
                "decimals": 18,
                "owner": "0xebbaa31b1ebd727a1a42e71dc15e304ad8905211"
              },
              "longToken": {
                "id": "0x88f4b382c2777ac2ba2e3b5c4e7c1d0215074aed",
                "name": "L54459",
                "symbol": "L54459",
                "decimals": 18,
                "owner": "0xebbaa31b1ebd727a1a42e71dc15e304ad8905211"
              },
              "finalReferenceValue": "0",
              "statusFinalReferenceValue": "Open",
              "redemptionAmountLongToken": "0",
              "redemptionAmountShortToken": "0",
              "statusTimestamp": "1660894980",
              "dataProvider": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
              "redemptionFee": "2500000000000000",
              "settlementFee": "500000000000000",
              "createdBy": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
              "createdAt": "1660894980",
              "capacity": "115792089237316195423570985008687907853269984665640564039457584007913129639935",
              "challenges": []
            }
          }
        },
        {...},
        {...}
      ]
    }
  }
}
```


# Whitelist subgraph

The whitelist stores trusted data providers, their individual data feeds and the collateral tokens that have to be used in order to be eligible for the oracle services:

The whitelist subgraph can be accessed here:&#x20;

* Ropsten (deprecated): <https://thegraph.com/hosted-service/subgraph/divaprotocol/diva-whitelist-ropsten>
* Goerli: <https://thegraph.com/hosted-service/subgraph/divaprotocol/diva-whitelist-goerli>

## Data providers

Data providers can be and their offered data feeds can be queried as follows (here querying the first two data providers in the whitelist):

```
{
  dataProviders(first: 2) {
    id
    name
    publicTrigger
    dataFeeds {
      id
      referenceAsset
      referenceAssetUnified
      active
    }
  }
}
```

Sample output of above query:

```
{
  "data": {
    "dataProviders": [
      {
        "id": "0x9adefeb576dcf52f5220709c1b267d89d5208d78",
        "name": "Individual 1",
        "publicTrigger": false,
        "dataFeeds": [
          {
            "id": "0x9adefeb576dcf52f5220709c1b267d89d5208d78-0",
            "referenceAsset": "DIVA/USD",
            "referenceAssetUnified": "DIVA/USD",
            "active": true
          },
          {
            "id": "0x9adefeb576dcf52f5220709c1b267d89d5208d78-1",
            "referenceAsset": "BTC/USD",
            "referenceAssetUnified": "BTC/USD",
            "active": true
          }
        ]
      },
      {
        "id": "0xed6d661645a11c45f4b82274db677867a7d32675",
        "name": "Tellor",
        "publicTrigger": true,
        "dataFeeds": [
          {
            "id": "0xed6d661645a11c45f4b82274db677867a7d32675-0",
            "referenceAsset": "ETH/USD",
            "referenceAssetUnified": "ETH/USD",
            "active": true
          },
          {
            "id": "0xed6d661645a11c45f4b82274db677867a7d32675-1",
            "referenceAsset": "BTC/USD",
            "referenceAssetUnified": "BTC/USD",
            "active": true
          }
        ]
      }
    ]
  }
}
```

## Data feeds

The following query shows all data providers that can provide a given data feed (here ETH/USD):

```
{
  dataFeeds(where:{referenceAssetUnified:"ETH/USD", active:true}) {
    id
    referenceAsset
    referenceAssetUnified
    dataProvider {
      id
      name
      publicTrigger
    }
    active
  }
}

```

Sample output of above query:

```
{
  "data": {
    "dataFeeds": [
      {
        "id": "0xed6d661645a11c45f4b82274db677867a7d32675-0",
        "referenceAsset": "ETH/USD",
        "referenceAssetUnified": "ETH/USD",
        "dataProvider": {
          "id": "0xed6d661645a11c45f4b82274db677867a7d32675",
          "name": "Tellor",
          "publicTrigger": true
        },
        "active": true
      }
    ]
  }
}
```

## Collateral tokens

The following query returns all collateral tokens that are supported by whitelisted data providers:

```
{
  collateralTokens(first:2){
    id
    name
    symbol
    decimals
  }
}

```

Sample output of above query:

```
{
  "data": {
    "collateralTokens": [
      {
        "id": "0x384a78a65189c696a009681b20880cd9af01bc16",
        "name": "WAGMI20",
        "symbol": "WAGMI20",
        "decimals": 20
      },
      {
        "id": "0x867e53fede91d27101e062bf7002143ebaea3e30",
        "name": "WAGMI18",
        "symbol": "WAGMI18",
        "decimals": 18
      }
    ]
  }
}
```


# Project ideas

A collection of example projects to build on DIVA Protocol

Wanna build on DIVA Protocol and contribute to the DIVA ecosystem? Below is a collection of example projects for inspiration. We would be happy to support you, both technically and financially! Reach out to us via our 👷[Builders channel on Discord](https://discord.gg/hZsvp5FTmN) if interested.

### :apple: App

* Build a prediction markets platform like [Domination Finance](https://domination.finance/), [Augur](https://augur.net/) or [Polymarket ](https://polymarket.com/)using DIVA Protocol
* Build a fantasy sports betting platform
* Build a platform to speculate on the transfer value of football players
* Build a DeFi insurance platform like [Unslashed Finance](https://unslashed.finance/) using DIVA Protocol
* Build a platform where two Twitter individuals can enter a bet
* Build an app to bet on the outcome of select sports events (e.g., the Champions League Finals) using DIVA Protocol
* Contribute to the DIVA App, an OTC market place ([app](https://app.diva.finance/), [GitHub](https://github.com/divaprotocol/diva-monorepo))
* Contribute to the DIVA Donate, a conditional donation platform ([app](https://www.divadonate.xyz/), [GitHub](https://github.com/Walodja1987/DIVA-Donate-App))
* Contribute to DIVA ViZ, an app to visualize derivative contract offers and share on Twitter ([app](https://divaviz.com/), [GitHub](https://github.com/divaprotocol/twitter-bets))

### :lipstick: Oracles

* Build your own oracle solution for DIVA Protocol
* Integrate existing oracle solutions such as Chainlink, Band Protocol, DIA, etc. with DIVA Protocol
* Build a notification service for human reporters to help them never miss a submission
* Develop a dashboard to track reporting statistics for various data providers
* Develop a reputation score for whitelisted data providers

### :chart\_with\_upwards\_trend: Market Making / Trading

* Build a market making bot for the DIVA App using [0x's limit order protocol](https://docs.0x.org/introduction/welcome)
* Research and implement novel market making strategies for derivative assets such as <https://www.paradigm.xyz/2021/10/a-guide-to-designing-effective-nft-launches>
* Build a console based trading experience

### :construction\_site: Smart contracts

* Build an AMM specifically designed for derivative assets issued on DIVA Protocol
* Build an auction smart contract or integrate existing solutions (such as [Gnosis Auction](https://blog.gnosis.pm/announcing-gnosis-auction-launch-390124d56248)) to sell derivative assets created on DIVA Protocol
* Help us bring the DIVA Protocol smart contracts to StarkNet, Solana, Stacks and ICP

### :mortar\_board: Education

* Write blog articles how to build on DIVA Protocol
* Create tutorial videos how to use the DIVA App or how to build a simple front-end on top of DIVA Protocol
* Organize a hackathon

### 🚀Other

* Use DIVA Protocol to implement a conditional token burn
* Airdrop your project token linked to pre-defined conditions&#x20;


# Social media

* [Discord](https://discord.gg/v4KYKms6zh)
* [Twitter](https://twitter.com/divaprotocol_io)


# Flash loans in DIVA Protocol

Author: Wladimir Weinbender, Date: 16 March 2024

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

*Tl;dr: This article explores the use of flash loans in prediction markets built on top of DIVA Protocol, aiming to enhance user experience and optimize market making activities. This idea is inspired by a prediction market app currently under development.*

In prediction market applications, ease of use for participants is key. Users should be able to easily place bets on outcomes and close their positions with a simple click.

This simplicity is achieved by limiting users to market buys and sells of the corresponding outcome shares, reserving the complexity of limit orders for advanced market participants like market makers.

In DIVA Protocol, market makers are essential for liquidity, as they mint position tokens to sell them on the market for a profit. This process involves (i) depositing funds into DIVA Protocol to mint equal quantities of LONG and SHORT position tokens (which combined represent a claim on the deposited funds) and (ii) placing sell limit orders via decentralized protocols such as [0x Protocol](https://0x.org/), facilitating market buys for users. The goal is to sell these tokens to two independent users for an amount exceeding the initial deposit.

{% hint style="success" %}
**Example:** Bob deposits $100 into DIVA Protocol to mint 100 LONG and 100 SHORT Tokens. He then lists the 100 LONG tokens for sale at a total price of $60 and the 100 SHORT tokens at $45. With Charlie buying the LONG tokens and Emily the SHORT tokens, Bob earns a profit of $5.
{% endhint %}

Furthermore, in order to enable users to close their positions via market sell, market makers must provide buy limit orders for both tokens. Consequently, a market maker would have to maintain a four-sided market to achieve the desired simplicity for users. This is adding complexity and operational burden.&#x20;

The following sections will detail how integrating flash loans can significantly reduce this complexity, offering a more streamlined approach for market makers.

### Closing positions with opposite outcome token

The first step towards reducing the complexity for market makers is to realize that instead of selling their position, users can buy an equivalent amount of the opposite outcome token and redeem them for collateral via DIVA Protocol.

{% hint style="success" %}
**Example:** Let's say Alice has 100 LONG tokens, each priced at 20c. Directly selling these tokens would yield her $20. Alternatively, Alice could achieve the same outcome by buying 100 SHORT tokens, trading at an implied price of 80c each, for a total of $80, and redeeming both for $100 from DIVA Protocol, netting her $20.
{% endhint %}

Yet, an issue arises since Alice needs funds ($80 in our example) to purchase the opposite token, which may not be always available.

What if Alice could briefly borrow the necessary funds to buy the opposite token and immediately repay the loan upon redeeming the collateral from DIVA Protocol? That’s where flash loans come in.

## Flash loans

Flash loans introduce an innovative form of lending unique to the blockchain world. These loans do not require collateral but must be repaid within the span of a single smart contract transaction. Failure to do so results in the reversal of the entire transaction, thus eliminating any repayment risk.

To grasp the concept of flash loans, particularly for individuals that come from traditional finance, it's essential to understand the atomic nature of smart contract transactions. Essentially, a smart contract transaction comprises a sequence of instructions executed as one unit. Should any part of this sequence fail, the entire transaction is undone, leaving the blockchain unchanged.

A flash loan is integrated as a specific instruction within a smart contract transaction. It involves borrowing funds at the transaction's start and repaying them by its conclusion. Overcollateralized lending protocols like Aave, Compound or MakerDAO have flash lending capabilities integrated into their protocols for public use.

To illustrate, consider Alice’s situation again: She owns 100 LONG tokens valued at 20c each and aims to liquidate her position. With an implied SHORT token price of 80c, the following steps are executed as part of a single smart contract transaction:

1. Borrow $80 from Aave
2. Purchase 100 SHORT tokens with the $80
3. Redeem 100 LONG and 100 SHORT tokens from DIVA Protocol for $100
4. Repay the $80 loan, retaining $20 as the net proceeds, mirroring the direct sale of LONG tokens

The example shows how the flash loan instructions (steps 1 & 4) encapsulate the transaction's other operations (steps 2 & 3), allowing for their replacement with any other operations, such as exploiting arbitrage opportunities or refinancing outstanding loans.

## Presence of fees

In our previous example, we omitted flash loan fees, trading fees and redemption fees for the sake of simplicity. However, in reality, those fees are not zero. Aave charges a 0.09% interest on the flash loan, DIVA Protocol applies a 0.25% upon redemption, the trading fee is also typically non-zero.

Intuitively, in the presence of fees the net dollar amount received at the end of a transaction will be lower, introducing the possibility that the flash loan cannot be repaid.

To illustrate the impact of fees, let’s revisit our previous example, assuming the standard Aave and DIVA fees and a 1% trading fee:

**Scenario 1:** Alice intends to liquidate her LONG tokens, which are traded at 20c and the implied SHORT token price being 80c.

1. Borrow $80.80 from Aave to cover the $80 purchase price for 100 SHORT tokens and the trading fee of $0.80, leading to a repayment amount of $80.80\*1.0009 = $80.8727
2. Purchase 100 SHORT tokens for $80.80 including trading fee
3. Redeem 100 LONG and 100 SHORT tokens from DIVA Protocol for $100\*(1-0.0025) = $99.75 after the redemption fee
4. Repay the $80.8727 loan, yielding $18.8773 net proceeds after all fees (vs. $20 in the absence of fees)

Here, the funds available after fees ($99.75) suffice for loan repayment ($80.8727), ensuring the transaction concludes successfully. In mathematical terms we have: $99.75 - $80.8727 >= 0.

**Scenario 2:** Now let’s consider a scenario where Alice’s LONG token is valued at 1c, with the SHORT token priced at 99c.

1. Borrow $99.99 from Aave to cover the $99 purchase price for 100 SHORT tokens and the trading fee of $0.99, leading to a repayment amount of $99.99\*1.0009 = $100.08
2. Purchase 100 SHORT tokens for $99.99 including trading fee
3. Redeem 100 LONG and 100 SHORT tokens from DIVA Protocol for $100\*(1-0.0025) = $99.75 after the redemption fee

In this case, loan repayment is not possible since the available funds after step 3 ($99.75) are less than the required repayment amount ($100.08), leading to a transaction failure. In mathematical terms we have: $99.75 - $100.08 < 0.

From these reflections, we can derive a general formula to calculate the threshold price of the opposite token that ensures loan repayment:

$$
m\*(1-redemption fee) - m*p*(1+flash loan fee)\*(1+trading fee) >= 0
$$

where *p* represents the price of the opposite token, and *m* the quantity of the owned token being liquidated (100 in our previous example).

Simplifying this formula yields:

$$
p<=(1-redemption fee) / {(1+flash loan fee) \* (1+trading fee)}
$$

Under the assumed fee structure, the threshold price *p* would be $0.986736, meaning that the flash loan will succeed if the price of the SHORT token is less than or equal to $0.986736.

## Additional considerations

In a scenario where a user has sufficient funds to buy the opposite side, no flash loan is needed. To address instances where a user has partial funds, the smart contract function that triggers the flash loan based liquidation operations could be designed to accept the loan amount as an input parameter.

## Conclusion

This article explored a flash loan-based approach for liquidating derivative positions created on DIVA Protocol, aimed at enhancing the user experience and streamlining market-making processes.

If this concept piques your interest, we invite you to join us in the development of this (small) smart contract adapter to expand the DIVA infrastructure ecosystem.


# NDVI outcome reporting guide for Tellor Reporters

How to report the outcome for the third DIVA Donate campaign

## Introduction

The [third parametric conditional donation campaign](https://www.divaprotocol.io/posts/diva-conditional-donations-pastoralists-3) on DIVA Donate, which uses Tellor Protocol for outcome reporting, will expire and **open for reporting on Monday, June 10, 2024, at 6:00 PM UTC** (unix timestamp: 1718042400). This article provides a guide for Tellor reporters on how to participate in the outcome reporting and verify the accuracy of reported values.

## Pool details

This campaign is linked to the following `poolId` on DIVA Protocol: [0x8c85108a28a163d1722c2140eea57f9d1cb7f83f69dfc04eb0d9e51298dea2b6](https://louper.dev/diamond/0x2C9c47E7d254e493f02acfB410864b9a86c28e1D?network=polygon#read).

To access the pool parameters, visit [louper.dev](https://louper.dev/diamond/0x2C9c47E7d254e493f02acfB410864b9a86c28e1D?network=polygon#read) (Etherscan for EIP-2535 based contracts) and input the `poolId` into the `getPoolParameters` function. The detailed description of the reference asset can be found via the [IPFS](https://bafybeibdjwmxn3r7cxx4bqqolqp3qib6l2co6mdrqh46ry2ab7cgbsamtu.ipfs.w3s.link/tellor_reference_asset_kajiado.json) link in the `referenceAsset` field:

<figure><img src="https://lh7-us.googleusercontent.com/docsz/AD_4nXdGdi9DDiawtFpOxlyVFop9dmnGrBhj_AalTRenwQhUzf_IydarQxSZcqJlpxniWNIuaUtwJxLMNS3z_Zqop5KQVJZjxK-99Z0FVgaHfQSnRsKWM8tHQUXebVxxb2F6e_EjKxDZWgBvAqqxnKiAp__kGtpC?key=WD92XiiSWdXI6vNzb6_qLQ" alt=""><figcaption></figcaption></figure>

Accessing the IPFS link in your browser will display the following:

<figure><img src="https://lh7-us.googleusercontent.com/docsz/AD_4nXcOWslIzjDKt-3YRvsWliOvPfYY6IY3ycxLDkiGYDt1fQDePy7duUMXboj_Kp0HXaKPh5Q6d-2jblQvJCePYFaP_BNTS1ZIPPckFOQpSYsRBxzQAv24OICpMbrWO9dBDz__1QfOeO6k29ENs_SPQ-68r_sW?key=WD92XiiSWdXI6vNzb6_qLQ" alt=""><figcaption></figcaption></figure>

## Reporting

The reporting process consists of the following four steps which are described in detail in the subsequent sections:

1. Sourcing the NDVI value
2. Sourcing the USD rate of the collateral token (USDT)
3. Preparing the values for submission
4. Submitting to Tellor contract
5. Submitting to DIVA Protocol

### 1 - Sourcing the NDVI value

To manually source the NDVI value:

1. Visit [USGS Early Warning Site](https://earlywarning.usgs.gov/fews/ewx/index.html).&#x20;
2. Double-click on “NDVI eVIIRs” in the Dataset panel on the left.

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

3. Locate and select "Kenya Kajiado" on the map.

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

4. Ensure the year 2024 curve is selected.

<figure><img src="/files/12zAUQMPQ1nM3M12EKT7" alt=""><figcaption></figcaption></figure>

5. Read the value on 31th May 2024.

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

### 2 - Sourcing the USD rate of the collateral token (USDT)

In addition to the NDVI value, the reporter must also submit the USD rate of the collateral token, USDT, which is utilized to calculate the reporter's reward. You can confirm that [USDT](https://polygonscan.com/address/0xc2132D05D31c914a87C6611C10748AEb04B58e8F) (at address 0xc2132D05D31c914a87C6611C10748AEb04B58e8F) is the pool's collateral token by checking the `getPoolParameters` [output](#pool-details).

The USD rate can be obtained from price aggregators like [Coingecko](https://www.coingecko.com/en/coins/tether) or [Coinmarketcap](https://coinmarketcap.com/currencies/tether/), or exchanges.

The reference asset description does not specify whether the observation date for the USD rate should be May 31, 2024, or June 10, 2024, at 6:00 PM UTC. For consistency, use the same time as the observation timepoint for the reference asset, which is May 31, 2024. Use the end-of-day price at 11:59:59 PM UTC, round to two decimal places. It is anticipated that the USD value of USDT will be 1.00, thereby minimizing any potential for ambiguity or dispute.

### 3 - Preparing the values for submission

Prepare the two values as per below and encode them as `bytes`:

1. **NDVI value**
   * Shift the observed NDVI value by +1 and round it to two decimal places, which is the default precision in the NDVI chart. For instance, an NDVI value of 0.75 becomes 1.75.
   * Convert the adjusted NDVI value into an unsigned integer with 18 decimals. Thus, 1.75 becomes 1750000000000000000.
2. **USD value of the collateral token (USDT)**
   * Convert the value into an unsigned integer with 18 decimals. Thus, 1.00 becomes 1000000000000000000.

#### Encode the values

Use the following function to encode your values. Check out [this example](https://github.com/divaprotocol/oracles/blob/48d1209bb55d1f1eb0b5dbcbadfad7be2ec3de6b/scripts/examples/tellor_submitValue.js#L116) for reference.

```typescript
encodeOracleValue = (finalReferenceValue, collateralToUSDRate) => {
  return new ethers.utils.AbiCoder().encode(
    ["uint256", "uint256"],
    [finalReferenceValue, collateralToUSDRate]
  );
};
```

**Example:** With `finalReferenceValue =  1750000000000000000` and `collateralToUSDRate = 1000000000000000000`, the encoded oracle value will be:

`0x00000000000000000000000000000000000000000000000018493fba64ef00000000000000000000000000000000000000000000000000000de0b6b3a7640000`

### 4 - Submitting to Tellor contract

To submit the encoded value to the Tellor contract, use the [`submitValue`](https://polygonscan.com/address/0xD9157453E2668B2fc45b7A803D3FEF3642430cC0#writeContract#F8) function on the (old) Tellor contract at the address [0xD9157453E2668B2fc45b7A803D3FEF3642430cC0](https://polygonscan.com/address/0xD9157453E2668B2fc45b7A803D3FEF3642430cC0). Enter the encoded value into the `_value` field and include the following parameters that are independent of the NDVI value / collateral USD value:

* `_queryId`: `0xf5b0d276ce38d3776861fb978b066a0ade32227dd84c282dbdda40d31fbda068`
* `_nonce`: `0`
* `_queryData`: `0x00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000c4449564150726f746f636f6c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000608c85108a28a163d1722c2140eea57f9d1cb7f83f69dfc04eb0d9e51298dea2b60000000000000000000000002c9c47e7d254e493f02acfb410864b9a86c28e1d0000000000000000000000000000000000000000000000000000000000000089`

  <figure><img src="/files/68MuXzRQd5CPnQvdnVEO" alt=""><figcaption></figcaption></figure>

#### Additional comments

* To verify that the provided `queryId` and `queryData` are indeed correct, refer to [this script](https://github.com/divaprotocol/oracles/blob/main/scripts/examples/divaTellor_getQueryDataAndId.js).
* Ensure that you have staked TRB tokens to be eligible for reporting. For detailed instructions on how to become a reporter, refer to the official [Tellor docs](https://docs.tellor.io/tellor/reporting-data/becoming-a-reporter) (note that these documents may reference the newer, gas-optimized Tellor contracts, whereas the DIVA Tellor adapter used in this campaign is still linked to the older version).
* Please note that values submitted to the Tellor contract *before* campaign expiration (**Monday, June 10, 2024, at 6:00 PM UTC**) will be ignored.
* If you prefer to submit the value via a script, refer to [this example](https://github.com/divaprotocol/oracles/blob/main/scripts/examples/tellor_submitValue.js). Make sure to update the script setting `const tellorVersion = TELLOR_VERSION.PLAYGROUND` to `const tellorVersion = TELLOR_VERSION.`**`ACTUAL`** to reflect the mainnet environment.

### 5 - Submitting to DIVA Protocol

If the reported NDVI value remains undisputed for at least 12 hours, anyone can execute the [`setFinalReferenceValue`](https://polygonscan.com/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6#writeContract) function on the DIVA Tellor adapter contract on the Polygon chain at address [0x7950db13cc37774614b0aa406e42a4c4f0bf26a6](https://polygonscan.com/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6). This action pulls the value from the Tellor contract into DIVA Protocol and determines the payouts for each leg of the market.&#x20;

When executing the function `setFinalReferenceFunction`, set `_tippingTokens` to an empty array and `_claimDIVAReward` to `true`. This will transfer the data provider reward from DIVA Protocol to the original Tellor reporter, amounting to 0.05% of the deposited funds, approximately $4.30.

<figure><img src="https://lh7-us.googleusercontent.com/docsz/AD_4nXfUFcc4U5Q0xFp3DL5nkgJpDmvCXcvtt6JWCeZiZK_c8Cj_G2fIPjA1bd_beM3KjV1b6kX1hr8lpRYfvqpMGjNHo3HMJXoRw8uXCdLny9FmDybWZBmZDtRinQzYuLZ6-Lp985ynpjFNnS3JBNhEbkyO8fE?key=WD92XiiSWdXI6vNzb6_qLQ" alt=""><figcaption></figcaption></figure>

## Additional Notes

The NDVI value is updated every five days and historical values are subject to slight variations due to a smoothing algorithm applied to the data. **It is recommended that reporters read the NDVI value for May 31th shortly after the campaign expiration on June 10th, as this timing makes the May 31th value less likely to change. Additionally, it is advisable to record a video of your value reading from the chart as proof should your reported value be disputed later.**

## Reporting information summary

Below table summarizes the key information required for reporting. The mentioned contract addresses can be found in the official [DIVA Tellor oracle adapter docs](https://github.com/divaprotocol/oracles/blob/main/docs/Tellor.md#polygon) on Github.

| Network                               | Polygon                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `poolId`                              | [`0x8c85108a28a163d1722c2140eea57f9d1cb7f83f69dfc04eb0d9e51298dea2b6`](https://louper.dev/diamond/0x2C9c47E7d254e493f02acfB410864b9a86c28e1D?network=polygon#read)                                                                                                                                                                                                                                                                                                                                                                   |
| Tellor contract address (old version) | [`0xD9157453E2668B2fc45b7A803D3FEF3642430cC0`](https://polygonscan.com/address/0xD9157453E2668B2fc45b7A803D3FEF3642430cC0)                                                                                                                                                                                                                                                                                                                                                                                                           |
| DIVA Tellor adapter contract          | [`0x7950db13cc37774614b0aa406e42a4c4f0bf26a6`](https://polygonscan.com/address/0x7950db13cc37774614b0aa406e42a4c4f0bf26a6)                                                                                                                                                                                                                                                                                                                                                                                                           |
| `queryId`                             | `0xf5b0d276ce38d3776861fb978b066a0ade32227dd84c282dbdda40d31fbda068`                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| `queryData`                           | `0x00000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000000c4449564150726f746f636f6c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000608c85108a28a163d1722c2140eea57f9d1cb7f83f69dfc04eb0d9e51298dea2b60000000000000000000000002c9c47e7d254e493f02acfb410864b9a86c28e1d0000000000000000000000000000000000000000000000000000000000000089` |

## Questions?

Reach out to us on:

* [Discord (DIVA)](https://discord.gg/v4KYKms6zh)
* [Twitter (DIVA)](https://twitter.com/divaprotocol_io)
* [Discord (Tellor)](https://discord.gg/n7drGjh)


# Enabling capital efficiency in DeFi

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

***TL;DR:** DeFi is often criticized by traditional finance folks for being capital inefficient due to the full collateralization requirement. This article explores how traditional finance achieves capital efficiency through the practice of fractional reserve and presents a comparable mechanism to enhance capital efficiency in DeFi. The described mechanism offers improved transparency and enhanced protection for end-users and taxpayers compared to traditional setups. While this article uses insurance built on top of* [*DIVA Protocol*](https://docs.divaprotocol.io/) *as an example use case, the model can be extended to prediction markets and any other DeFi application requiring full collateralization.*

### ✨ Introduction

Traditional insurance companies operate on a fractional reserve basis, maintaining only a portion of the maximum potential liabilities in reserve. This practice capitalizes on the uncorrelated nature of risks, making it highly unlikely that an excessive number of insurance claims will be triggered simultaneously, leading to a default.

In contrast, Decentralized Finance (DeFi) protocols, such as DIVA Protocol, require users to fully collateralize their future obligations upfront. While this ensures that all potential claims are covered, thus reinforcing the trustless nature of DeFi, it also greatly limits capital efficiency, reducing the number of policies that can be underwritten relative to traditional settings. This fundamental difference poses a significant challenge for traditional financial institutions considering DeFi integration.

In this article, we will examine the concept of fractional reserve and then derive a comparable mechanism to achieve capital efficiency in DeFi, using insurance as an example use case. Additionally, we will provide a high-level technical implementation guide.

### 🎬 Setting the stage

Vlad plans to build an agricultural insurance business using DIVA Protocol, an open decentralized finance infrastructure to create and manage conditional payment agreements without using banking rails. He issues two harvest loss insurance policies, each fully collateralized with $1,000, and sells them to Bob, a farmer in India, and Alice, a farmer living in Kenya, for $150 each. Vlad collects a total of $300 in premiums and locks up $2,000 in collateral.

In comparison, a traditional insurance company that operates on a 50% fractional reserve basis, would only keep $1,000 in reserve, allowing it to underwrite twice as many policies as Vlad, earning $600 using the same amount of collateral. This highlights the perceived capital inefficiency of DeFi.

### 🧪 Understanding fractional reserve

By running a fractional reserve, traditional insurance companies effectively bet that the total claims submitted will not exceed a certain threshold. For instance, if they sell coverage totaling $2,000 but maintain only $1,000 in reserve, they essentially bet that claims will not surpass $1,000. If an excessive number of claims is filed at once though, the insurance company would not be able to cover its liabilities, resulting in a default.

**Who absorbs the insurer’s shortfall risk? Who will step in to cover the deficit if a shortfall occurs?**

In an ideal scenario, the insurance company buys insurance against such an event from a reinsurance company specialized in assessing and consciously accepting those types of risks. However, often it is either the policyholders themselves who will not receive their promised payout or the government, and by extension the taxpayers, who will step in to compensate the policyholders.

One of the most significant examples is the bailout of American International Group (AIG), a global insurance corporation, during the 2008 financial crisis. AIG faced severe liquidity issues due to its exposure to credit default swaps and other risky financial products. The U.S. government intervened to prevent a collapse affecting the global financial system. This intervention included an [initial bailout of $85 billion](https://www.nytimes.com/2008/09/17/business/17insure.html) from the Federal Reserve, with the total support eventually amounting to approximately [$182 billion](https://www.livemint.com/Politics/B132DlCABbziw3ahadw33M/US-to-sell-off-all-its-AIG-stock-ending-182-bn-rescue.html?facet=amp).

**The key takeaway from this section is that in a fractional reserve system, the burden of covering a shortfall from excess claims is shifted to another party, knowingly or unknowingly.**

In the next section, we will explore how we can enable a similar risk transfer mechanism in DeFi while maintaining full collateralization.

### 🎨 Applying fractional reserve principles to enhance capital efficiency in DeFi

Vlad‘s goal is to unlock a portion of the $2,000 collateral tied up in the two policies in order to be able to underwrite additional policies. By releasing $1,000, he would still have $1,000 in reserve, sufficient to cover obligations in three out of the four possible scenarios.

However, Vlad is programmatically prohibited from withdrawing any funds from DIVA Protocol prior to the policies‘ expiration. This prevents him from silently transferring shortfall risk to policyholders or taxpayers, a common practice in traditional settings. Consequently, his only option is to transfer the risk to a party that is willing to cover the shortfall.

Setting up a reinsurance policy using DIVA Protocol, similar to the original insurance policies, which would cover the shortfall by paying out $1,000 if both policies trigger is not an option as the funds would be locked inside DIVA Protocol until the policy‘s expiry, leaving Vlad without the immediate liquidity he needs to underwrite additional policies.

**To address both needs, transferring shortfall risk and receiving immediate capital, Vlad can bundle and securitize the collateral recoverable from the policies into a synthetic asset and use it as collateral to secure a loan.**

#### Illustrating the payout structure of the synthetic asset

The payout of the synthetic asset mirrors the amount of collateral recovered from the two policies combined. Below table illustrates the payouts under the four possible scenarios:

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

The synthetic asset returns $2,000 if no claims are triggered, $1,000 if one policy triggers, and $0 if both trigger. This is depicted in the following chart.

<figure><img src="/files/7feVloWK78ynG2ZUdx4k" alt=""><figcaption></figcaption></figure>

This intrinsic value of the synthetic asset enables it to be used as collateral to secure a loan from a lender willing to accept the risk of a total loss arising from the synthetic asset becoming worthless when both policies trigger.

In three of the four scenarios - (0,0), (1,0), and (0,1) - the synthetic asset would generate enough payout to repay the lender. However, in the (1,1) scenario, the asset becomes worthless, resulting in a total loss for the lender.

To compensate for the risk of loss, the lender could offer Vlad $950 and expect a repayment of $1,000 when the policies expire, earning a yield of 5.26%. This could be an attractive arrangement if the probability of both policies triggering simultaneously is estimated to be low (e.g., 1%). The pricing of these risks is a complex topic and beyond the scope of this article.

This strategy could be scaled to any number of policies that Vlad has underwritten. For example, with 1000 policies, each pre-funded with $1,000, Vlad could opt to transfer the risk of claims exceeding $600,000, effectively freeing up nearly $400,000 in capital (a bit less due to the risk premium demanded by the lender).

**In this section we have seen how securitizing the recoverable collateral from a portfolio of fully collateralized positions and then borrowing against the resulting synthetic asset provides an effective way to recover a portion of the pre-funded amount, while preserving the assurance that all future policyholder claims will be honored.** This concept extends beyond insurance and can be applied in prediction markets or other DeFi applications that demand full collateralization.

This concludes the theoretical discussion. Next, we will examine the practical implementation of this mechanism by combining various DeFi building blocks.

### 🧰 Technical implementation

In this section, we will walk through the technical steps required to implement the presented mechanism using [DIVA Protocol](https://docs.divaprotocol.io/) in conjunction with a lending protocol like [Myso v2](https://github.com/mysofinance/v2), [Morpho](https://morpho.org/) or [Euler v2](https://www.euler.finance/blog/euler-v2-the-new-modular-age-of-defi).

The implementation involves the following key steps:

1. **Create** insurance policies and pre-fund them with the insurance cover amount.
2. **Bundle and securitize** the positions representing the recoverable collateral into a single synthetic asset.
3. **Borrow** funds using the synthetic asset as collateral.
4. **Recover** any remaining collateral from the policies.
5. **Repay** the lender.
6. **Transfer** any excess funds to the borrower.

#### Create

Using DIVA Protocol, an insurance policy can be created by specifying the policy parameters including the trigger conditions (e.g. harvest loss) and expiration, and then pre-funding it with the insurance cover amount, denominated in a USD-pegged stablecoin such as USDT or USDC.

This process results in the issuance of two conditional claims on the funds, both represented as ERC20 tokens:

1. **Token A**, representing the insurance policy, which is sold to the insurance taker (e.g., Alice or Bob) and redeemable if a harvest loss occurs.
2. **Token B**, representing the insurer's position, which is inversely related to Token A and redeemable if no harvest loss occurs. This token effectively grants the right to recover any remaining collateral.

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

By repeating this step for every new policy, a diverse portfolio of B tokens is built up, with each token distinctly connected to an individual policy.

#### Bundle and securitize

The second step involves bundling the B tokens in a vault and securitizing its payout into a single synthetic asset, represented as an ERC20 token. One approach is to transfer each B token after policy creation individually to a vault, such as [thirdweb‘s multiwrap contract](https://portal.thirdweb.com/contracts/explore/pre-built-contracts/multiwrap). Once consolidated, a synthetic asset can be issued against that vault, representing a claim on the collateral amount recoverable from the bundled positions.

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

A more cost-effective approach is to designate the vault directly as the recipient of the B tokens at the moment of policy creation. This method eliminates the need for separate transfer transactions, thereby reducing transaction costs.

For optimal efficiency, it is recommended that all policies are pre-funded with the same stablecoin, streamlining the financial operations associated with borrowing and repayment.

#### Borrow

The next step is to find a lender willing to issue a loan against the synthetic asset. Existing lending protocols like Myso v2, Morpho or Euler v2 can facilitate this process.

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

Two essential features are required for the chosen lending protocol:

* The ability to accept any ERC20 token as collateral, allowing the synthetic asset to be used for this purpose.
* The absence of a liquidation mechanism, allowing the lender to incur a loss if the collateral value falls below the loan amount.

The specifics of the borrowing process will vary depending on the chosen protocol. Typically, it involves either receiving a signed loan offer from potential lenders or placing a borrow offer at desired terms. Once an offer is accepted, the synthetic asset is deposited and locked in an on-chain escrow, where it remains until the loan reaches maturity, and the loan funds are transferred to the borrower.

#### Claim, repay and transfer

Upon the expiration of the policies, the B tokens must first be redeemed/liquidated for the underlying stablecoin from DIVA Protocol. These funds are then used to repay the loan, with any surplus returned to the borrower (the insurer).

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

The implementation of the repayment mechanism necessitates the development of an adapter contract that interacts with both DIVA Protocol and the lending protocol. If you are interested in contributing to its creation, please reach out on our [Discord](https://discord.gg/8fAvUspmv3).

### 🌔 Conclusion

This article has presented a framework for enhancing capital efficiency in a fully collateralized DeFi system by applying the principles of fractional reserve systems in a decentralized context. By pre-funding insurance policies and refinancing them through lenders, an insurer can return a portion of the collateral initially locked to back the policies, thus enabling the underwriting of additional policies. Crucially, this approach maintains the trustless nature of the system, ensuring that all positions remain fully collateralized.

This framework has broader applications beyond the insurance sector. It can be adapted to prediction markets, which can also be facilitated by DIVA Protocol, and other DeFi applications that require full collateralization.

Adopting such models could significantly enhance transparency, improve protection for end-users, and potentially ease the regulatory burden for insurers. However, the success of this mechanism largely depends on the presence of sophisticated lenders who can effectively assess and manage the associated risks. As this sector continues to evolve, there is a significant opportunity for community involvement and development, especially in refining and scaling these solutions. For those interested in discussing, contributing to, or implementing this model, please reach out on our [Discord](https://discord.gg/8fAvUspmv3).


