# Quickstart

Nekodex is the easiest way to start trading crypto on your phone!

## Installation

* Visit <https://app.nekodex.org> on your iPhone or Android device
* Tap "Install" and add to home screen

### Android Play Store

Install Nekodex directly from the Play Store:

[https://play.google.com/store/apps/details?id=org.nekodex.app.twa](https://play.google.com/store/apps/details?id=org.nekodex.app.twa\&pcampaignid=web_share)

**📱 iPhone app is coming soon™️**

## Scan to install

<figure><img src="/files/pyZZVocZ294jdSORZAib" alt=""><figcaption><p>Scan with your phone</p></figcaption></figure>

## About

Nekodex lets you go on-chain without worries. It is a decentralized exchange for buying and selling cryptocurrency, powered by next-gen web3 technology.&#x20;

Features

* No Metamask required  (or any extension/plugin)
* No recovery phrases to keep safe
* Trades happen on Uniswap and other top exchanges
* Buy/sell on multiple chains with chain abstraction
* Biometric-secured with Passkey
* Phishing-proof thanks to Passkey


# Sign up and log in

Nekodex uses your email & a passkey generated by your phone to create your on-chain wallet. Passkeys are secured by your device biometrics like FaceID or your fingerprint (if you only use a lockscreen PIN that is ok too).

## Device Requirements

* A mobile device supporting Passkey
* Recommended: iCloud Keychain or Google Password Manager to back-up Passkeys
* Mobile device lockscreen turned on using FaceID, fingerprint and/or PIN
* iOS 16+, Android 9+&#x20;
* [More details here](https://passkeys.dev/device-support/#matrix)

## Sign Up

Nekodex only requires a valid email to create your account. Your phone will use your email to create a passkey, which is used to create and secure your account.

In the app, choose Sign Up and enter + verify your email address with an OTP code. When prompted, please choose to save your passkey in iCloud Keychain or Google Password Manager whenever possible. It should be the default option.

During signup, you will be required to confirm using your FaceID, fingerprint or PIN.

If you have trouble signing up, make sure your phone supports passkeys.

{% hint style="danger" %}
**Never delete your passkey**\
If you delete a passkey from your mobile device or iCloud/Google account, it may be lost forever. Your account will not be recoverable.\
\
**Use a reliable email address**\
If you lose access to your email, you will not be able to log into your Nekodex account.
{% endhint %}

## Login

1. Enter your account email and verify using the OTP code sent by Nekodex. You must be able to receive the OTP code to log in.
2. Complete login using the passkey for your Nekodex account. This passkey is created when you sign up and create the account. Passkeys are stored on your phone, and normally backed up automatically in your Google or iCloud account.


# Deposit & Withdrawal

Nekodex currently supports USDC deposit and withdrawal

{% hint style="warning" %}
**Deposit USDC on supported chains only**

* Optimism USDC
* Arbitrum USDC
* Base USDC

Other chains are not supported.
{% endhint %}

{% hint style="warning" %}
**Do not deposit non-USDC coins**

* Do not deposit ETH
* Do not deposit USDT
* Do not deposit other non-USDC assets
  {% endhint %}

## Which network should I choose?

**Cheapest**

Optimism (OP Mainnet) is the cheapest and fastest deposit option, because you will not need to convert your funds after depositing.

**Additional options**

Base and Arbitrum are also available options. Note that you will need to convert these funds after you deposit them.

Choose one of these options if you already have funds on these networks, or if your exchange does not support withdrawing USDC to Optimism directly.

If you are depositing a large amount of funds, you may want to investigate available options to minimize fees and spread which may be incurred when funds are converted (bridged) to Optimism. Please [About](/about#contact-us) if you would like help with this.

## Deposit

{% hint style="warning" %}

* Do not deposit ETH
* Do not deposit on an unsupported chain
  {% endhint %}

You can fund your Nekodex account by transferring from an exchange or an existing Web3 wallet.

### Your deposit information

From the main page of Nekodex, click ↓ Deposit to view your wallet address.

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

{% hint style="info" %}
**Deposit to Contract**

Your exchange or wallet may warn you that you are depositing to a contract address. Nekodex accounts are smart contract wallets, so this is expected.

🧠 Make a small test deposit first to confirm everything is working.
{% endhint %}

{% hint style="warning" %}
**Always double check your deposit address!**
{% endhint %}

#### Deposit from an exchange (Binance, Bybit, etc.)

1. Open your exchange app and make sure you have USDC in your account.
2. Choose "Withdraw" to transfer USDC from the exchange to Nekodex.
3. **Network or Chain:** Optimism
4. **Wallet Address:** Enter your Nekodex address
5. **Token:** USDC
6. **Amount:** Start with a smaller amount like $10 to ensure the transaction goes smoothly before transferring a larger amount.

#### Deposit from a Web3 Wallet (Metamask, Rainbow, Trust Wallet, etc.)

1. Make sure you have USDC on Optimism in your wallet.
2. Open your wallet app and select USDC on the Optimism network.
3. Choose "Send".
4. **Token:** [USDC](https://optimistic.etherscan.io/token/0x0b2c639c533813f4aa9d7837caf62653d097ff85) (Optimism)
5. **Wallet Address:** Enter your Nekodex address
6. **Amount:** Start with a smaller amount like $10 to ensure the transaction goes smoothly before transferring a larger amount.

If you don't have USDC on Optimism, you can check the many bridge options for [Optimism](https://optimism.io/apps#bridge) or transfer USDC to Optimism from an exchange. Always research bridge safety before using them. If you need help or recommendations, please come to our [Discord](https://discord.perp.com/).

## Withdrawal

{% hint style="info" %}
Nekodex currently supports USDC withdrawal on Optimism
{% endhint %}

From the main page of Nekodex, click **Withdraw**.

* **Wallet address**: fill in your destination address, this address must be on Optimism
* **Amount:** Start with a smaller amount like $10 to ensure the transaction goes through before transferring a larger amount.
* **Biometric confirmation** is required

To complete a withdrawal, you will need to confirm with your passkey (FaceID, fingerprint or PIN).


# Nekodex Account


# Passkey

{% hint style="warning" %}

#### **Never Delete Your Passkey**

Deleting a passkey may cause you to lose your account permanently. There is nothing we can do to recover your account if your passkey is deleted.

#### **General Warning**

Never deposit more funds than you can afford to lose. Nekodex has been tested extensively but it is never possible to ensure software is 100% free from bugs.

#### Set up Fund Recovery

Make sure to set up [Fund Recovery](/nekodex-account/fund-recovery) with a web3 wallet that you control.

#### Check your backups

Make sure your passkey is backed up. See more in [#backups](#backups "mention").
{% endhint %}

Nekodex uses passkeys to create and manage your account. Passkeys are a new, secure way to secure digital assets and accounts.

## Benefits

* A separate passkey is used for every service you sign up for, ensuring there is no password reuse.
* Passkeys only work with the service you signed up for, meaning phishing is virtually impossible.
* Passkeys cannot be exported or revealed to others, keeping you safe against social engineering attempts.
* Passkeys are automatically backed up with iCloud Keychain and Google One, so if you lose your phone, they will be synced to your new phone when you log in.

## Passkey Basics

Passkeys are a type of password created securely by your device (usually you phone). It is stored on the device, and can also be backed up securely in your iCloud or Google account. The backup features strong encryption ensuring no one, including Apple and Google, can access your passkeys.

A new passkey is created for each service you use passkeys with, so if the service's data is hacked somehow, your passkey cannot from that service cannot be used to access other passkey protected services.

Each passkey is tied to an email. This is the email you used to sign up to the service. Passkeys are also tied to the service internet domain name (e.g. perp.com), making it impossible to use with another domain (e.g. uniswap.org).

Passkeys are backed up using your iCloud or Google account. Note that the account used to back up the passkey and the email used to create a given passkey can be totally separate. E.g. if you create a Nekodex account with `meow@nekodex.org` and your phone is logged into Google using `meow@gmail.com`, your passkeys will be backed up in your `meow@gmail.com` Google account.

## Biometrics

Passkeys are not tied to your biometrics like FaceID or fingerprints, but access to your passkeys *is* controlled using biometrics via your phone or other mobile device. This means that you can use your fingerprint to tell your phone it's ok to use a passkey to log into a service. However if you change phones, you will need to log into your iCloud or Google account and set up biometrics again. Your passkey will not be lost if something happens to your finger!

Biometrics are not required for passkeys to work. You can also use a code to secure your phone if you prefer to avoid biometrics.

## Backups

On iOS and Android devices, passkeys should be backed up automatically.

It's a good practice to double-check that backups are being performed:

* iOS: After setting up your Nekodex account,, go to Settings > \[your name] > iCloud > Passwords and Keychain and verify that a passkey for app.nekodex.org is present.
* Android: After setting up your Nekodex account, go to <https://passwords.google.com/> and double check that your passkey for app.nekodex.org is listed there.

## Renaming

The order passkeys are shown to you on your device is likely to change. Your device will automatically name passkeys when they are created but it may be helpful to change the name, making them easier to identify.

## Fund recovery

See [Fund Recovery](/nekodex-account/fund-recovery)


# Fund Recovery

Fund Recovery lets you move all of your funds out of Nekodex if you lose access to your account, or just need to rescue your funds for whatever reason. Nekodex Fund Recovery uses [Privy](https://x.com/privy_io) ([privy.io](https://www.privy.io/)), a 3rd party service, to trigger movement of funds to your specified recovery address.

{% hint style="danger" %}

### Fund Recovery requires set up

You cannot use Fund Recovery until you set it up. Set it up now!
{% endhint %}

{% hint style="warning" %}
Earned (unclaimed) Nekocoin is **not** transferable, including transfer via Fund Recovery
{% endhint %}

## Recovery Address

Step 1 in setting up is to choose a Recovery Address. You can use any EVM-compatible wallet with an address starting with `0x...` like Metamask, Rabby, Argent, or another Nekodex account.

{% hint style="danger" %}
**WARNING**

Do **not** use a centralized exchange (CEX) address as your Recovery Address.

You will likely permanently lose any funds that the centralized exchange does not support, if you send those funds to the CEX address.
{% endhint %}

## Recovery Email

You must use the same email that you use with your Nekodex account.

{% hint style="danger" %}
**WARNING**

Use an email that you are sure you can always access. You need to receive email to recover your Nekodex funds. Make sure the email recovery setup has also been completed.
{% endhint %}

## Setup

Read the steps below, or watch the how-to video:

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

Start by tapping Add/Edit

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

Enter your Recovery Address, agree to the warning messages, and tap Save

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

The app will walk you through signing the recovery setup authorization for each chain (network). After the process is complete, your Fund Recovery screen will show your Recovery Address.

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

## Recover Funds / Rescue Funds

When you need to recover funds, first go to the Nekodex app.&#x20;

### If you cannot log in

The process is the same whether you are logged into your Nekodex account or not.

### If you did not set up account recovery

Account recovery only works if you set it up before you lost access to your account!

### Recovery steps

1. Tap the Profile icon 👤 on the upper right corner of the Nekodex app.

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

2. Tap the Fund Recovery option.

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

3. Tap Transfer Assets

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

4. Enter your Nekodex email

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

5. Tap Start Transfer. Your assets will be sent to your registered recovery address on each chain. The recovered asset will remain on the chain it was on in your Nekodex account. E.g. $OP will be sent on Optimism, $ARB will be sent on Arbitrum, etc.

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

6. You will need to sign a confirmation message for each chain that contains funds.

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

7. Transfer should continue until all chains have transfered. If you have no assets on a given chain, nothing will be transfered for that chain.

## FAQ

* Can I recover Earned Nekocoin?
  * No. Earned Nekocoin is not transferable, even by using Fund Recovery. You can only recover Nekocoin that is in your Portfolio.
* Can I recovery just one type of coin or just one asset in my portfolio?
  * No, recovery is for emergency purposes and all coins are recovered at the same time.
* Can I recovery funds in Nekodex Earn?
  * Yes, funds in Nekodex Earn will be sent to your wallet on the respective chain. These funds may be in vault tokens. Contact us if you need help exchanging them back to USDC.
* Can I recover funds if I didn't set up fund recovery?
  * No. Make sure you set up Fund Recovery as soon as possible 👍
* Where do my funds go when I recover them?
  * Funds go to your recovery address and stay on the chain they came from. So if you have $OP, it will be sent to your recovery address on Optimism; If you have $ARB, it will be sent to your recovery address on Arbitrum; etc.
* Can I use my Nekodex account again after recovery?
  * Do you have your original account email and passkey? If yes, then you can continue using that account. If no, then you still cannot use the account unless you recovery access to the email and passkey.
* Can this recover my passkey?
  * No. Check with your phone provider (e.g. Apple or Google) to see what options there might be for recovering your passkey.
* Can this recovery my email?
  * No. Check with your email provider (e.g. Gmail) to see if they offer any recovery options.
* How are fees paid? Do I need gas?
  * As of Nov 2024, fees for fund recovery are paid for by the Nekodex team. You do not need gas to trigger recovery, but you do need gas to move funds from your recovery address if you used your own wallet (ie. not another Nekodex account).


# Features


# Spot Trading

## Buy

1. Go to any market
2. Tap **Buy** and enter amount\*
3. Click **Continue** to review and place your order
4. That's it!

\*You will need to follow the in-app instructions to activate each chain the first time you use it.

The order will be sent on-chain and should be processed within 45 to 60 seconds. Note that network congestion may affect transaction speed.

## Sell

* The process is generally the same as buying.
* If it's your first time selling on certain markets, you'll be prompted to "**Activate Chain**". Simply confirm with your biometrics or device PIN.

## Cancelled / Refunded Orders

Orders may occasionally fail due to rate changes during execution. To protect you from unfavorable prices, we cancel such orders. Retrying often resolves this issue.

If an order fails to execute, your funds will be automatically refunded to your account. This process can take up to 4 hours.

## Interrupted Orders

Rest assured, all funds are safe.&#x20;

If an order is interrupted, you may see "Arb USDC", "Base USDC", or "Mainnet USDC" in your portfolio. Simply tap **Convert** to convert them back to USDC.

## Minimum Order Value

Depending on the market, there are different minimum order values, typically between 50 and 200 USDC. For example, some markets on Ethereum Mainnet have a higher minimum order value.


# Nekodex Earn

## Deposit USDC and Earn!

Nekodex Earn vaults are live! Earning yield with top DeFi protocols using your USDC has never been easier.

Just deposit USDC, and start earning 🙌

{% embed url="<https://app.nekodex.org/earn>" %}
Link straight to the Nekodex Earn page
{% endembed %}

### Stablecoin Earn

The most advanced Nekodex Earn USDC vault. Deposits in this vault will be migrated to the best yield sources available, so you don't have to wonder if you're getting the best return on your USDC. With regular migrations and new pools being added soon, there's no easier way to access actively managed Defi yield.

At launch, this vault connects to [Morpho](https://x.com/MorphoLabs), the latest in Defi money market technology.

## Depracated Earn Vaults

"Now you're just somebody that I used to know" - Gotye

### Stablecoin Simple (USDM)

{% hint style="warning" %}
USDM is being sunset as the team behind it, Mountain Protocol, pivots to [new projects](https://x.com/MountainUSDM/status/1921960086362108270).\
\
USDM is not available to US residents, citizens or users located in the US.
{% endhint %}

Deposit USDC and receive USDM. USDM is a yield bearing stablecoin, meaning

* It is pegged to the US dollar (1 USDM = $1 USD, assuming normal liquidity and market conditions)
* While holding USDM, you'll automatically receive more USDM according to the current APY.&#x20;

APY for the USDM vault is variable, but is typically in the 4%-5% range. Check in the Nekodex app to see the current APY.

Learn more about USDM, created by Mountain Protocol.

* Project website: [https://mountainprotocol.com](https://mountainprotocol.com/)
* Risk statement: <https://docs.mountainprotocol.com/reference/risks>

### BTC Earn (LBTC)

{% hint style="warning" %}
This Earn vault is on Ethereum mainnet and may have higher fees than other Earn products.
{% endhint %}

Buy LBTC and deposit in this vault to earn yield while holding BTC! This product uses [Yearn's](https://yearn.fi/) auto-rolling (auto-renewing) [Pendle PT vault](https://yearn.fi/v3/1/0x57a8b4061aa598d2bb5f70c5f931a75c9f511fc8).

* The vault pays interest in LBTC, a BTC pegged token from Lombard. "Designed to be the stETH of Bitcoin, LBTC provides holders with a native staking yield".
* The amount of yPT-LBTC you hold will increase over time to reflect your interest income.

Earn interest while holding the world's biggest crypto asset!

{% hint style="warning" %}
**Yearn risk statement**

Read the [Pendle Docs](https://docs.pendle.finance/) to learn about the associated risks. Withdrawals may result in a loss depending on withdrawal size and current market conditions.
{% endhint %}

## ETH Earn (weETH)

Buy weETH and deposit in this vault to earn yield while holding BTC! This product uses [Yearn's](https://yearn.fi/) auto-rolling (auto-renewing) [Pendle PT vault](https://yearn.fi/v3/42161/0x044e75fcbf7bd3f8f4577ff317554e9c0037f145).

* The vault pays interest in weETH (wrapped eETH), a liquid restaking token from [ether.fi](https://app.ether.fi).
* The amount of yPT-weETH you hold will increase over time to reflect your interest income.

Earn interest while investing in the world's top smart contract platform!

{% hint style="warning" %}
**Yearn risk statement**

Read the [Pendle Docs](https://docs.pendle.finance/) to learn about the associated risks. Withdrawals may result in a loss depending on withdrawal size and current market conditions.
{% endhint %}


# Perp Trading

{% hint style="info" %}
Perp trading will be back soon!
{% endhint %}


# Nekocoin

Earn Nekocoin simply by using Nekodex.

## What is Nekocoin?

Nekocoin is a loyalty token for rewarding Nekodex users, backed by OP tokens from the Perpetual Protocol treasury.

{% hint style="warning" %}
Earned Nekocoin will be redistributed to active users if you are **inactive for 28 days.**

\
[#how-to-be-an-active-user](#how-to-be-an-active-user "mention")
{% endhint %}

### How to earn Nekocoin?

You can earn Nekocoin simply by trading on Nekodex and complete quests. You can view Earned Nekocoin in the  "Quests" tab.

### How to claim

{% hint style="danger" %}
You can only claim Nekocoin within Nekodex. Be ware of scams.&#x20;
{% endhint %}

You can claim available Nekocoin by tapping the "Claim" button. After claiming, your Nekocoin balance will be available in your portfolio. After you claim, Nekocoin moves to your Portfolio. Nekocoin in your Portfolio is yours forever 💕.

**Earned Nekocoin**\
Nekocoin rewards enter your Earned Nekocoin balance. To claim, you can deposit USDC or use Nekodex for trading, Earn vaults and more. The more you deposit and user Nekodex, the faster you can claim your Earned Nekocoin.

Earned Nekocoin expires after **28 days** of inactivity, so make sure you **stay active 🙌**

### **How to be an Active User**

**Active User benefits**

* Earn Nekocoin re-drops\*, which are coins redistributed from inactive user accounts
* Your claimed Nekocoin (in your Assets tab) **never** get redistributed

\*Still in planning phase

**How to stay Active**

* Complete daily-check in at least once every **28 days**
* Earn or claim Nekocoin at least once every **28 days**

### Buy or sell

You can then buy or sell on [Nekodex](https://app.nekodex.org/markets/NEKOCOINUSD?chain=optimism\&group=new-listings\&amount=) just like other coins.&#x20;

Or you can trade Nekocoin on Uniswap if you wish. Contract address:

`0x139052115f8b1773cf7dcba6a553f922a2e54f69`

### Holder benefits

Note: All benefits are in development and to be confirmed. Please let us know if you have requests or ideas!

* Loyalty shares: Active Nekodex users who also hold Nekocoin will receive unclaimed Nekocoin from inactive users. So don't forget your daily check-in!
* Surprise airdrops
* Future benefits like discounts, merch, APY boosts, deposit rewards and more

## Token Details

* Token symbol: `(=ↀωↀ=)`
* Contract address (Optimism):  `0x139052115F8B1773cF7DcBA6a553F922a2E54F69`
* [Optimism Etherscan](https://optimistic.etherscan.io/address/0x139052115F8B1773cF7DcBA6a553F922a2E54F69)
* Chain: Optimism
* Total Supply: 2.7 billion Nekocoin with **no allocation** for investors, team, or influencers⁠.

### Distribution

Total Supply: 2.7 billion Nekocoin&#x20;

* 25% for retroactive airdrop to Nekodex Playground users
* 25% for future user rewards
* 50% for OP-Nekocoin liquidity pool⁠

### Initial TGE Price

1 Nekocoin = 0.000599072 OP with 500K OP initial liquidity and up to 700K OP for post-TGE injections⁠.⁠


# Passive Claim

You can claim more Nekocoin every Monday 😸👍

{% hint style="info" %}

## Want to claim more? tl;dr

Claiming Nekocoin is based on your Nekodex account value. If you want to claim more, faster, you need to increase your account value.

How?

There are many ways:

* Hold Nekocoin. Nekocoin adds to your account value.
* Hold other coins on Nekodex, like BTC, ETC, etc.
* Hold funds in Nekodex Earn. This also lets you claim Earn bonuses every day!
* Hold USDC on Nekodex.

The current threshold to double your claim speed is $100 but we may add more options in the future.
{% endhint %}

### Earned Neko Passive Claiming Rules

This document provides detailed instructions on how to convert your "Earned Nekocoin" into Nekocoin in your Portfolio.

#### What is Passive Claiming

Passive claiming enables users to convert their Earned Nekocoin balance to Claimable Nekocoin gradually over time.

Every Monday, a portion of your Earned Nekocoin balance will become Claimable Nekocoin based upon your Earned Nekocoin balance, Nekocoin balance and account value from the previous week.

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

* If there are no funds in your account, **0.1%** of the total amount of **(Nekocoin + Earned Nekocoin)** each day.
* If your account holds more funds, the daily claiming percentage increases with your account value, up to a maximum of 2.0\*\*%\*\* of the total **(Nekocoin + Earned Nekocoin)**.
* Here’s a table showing how the changes in your account value relate to the daily claiming percentage.

| User Level | User account value (USD) | **Daily** claiming percentage | **Weekly** claiming percentage |
| ---------- | ------------------------ | ----------------------------- | ------------------------------ |
| 1          | 0                        | 0.1%                          | 0.7%                           |
| 2          | 100                      | 0.2%                          | 1.4%                           |
| 3          | 1,000                    | 0.5%                          | 3.5%                           |
| 4          | 2,000                    | 0.7%                          | 4.9%                           |
| 5          | 10,000                   | 1.0%                          | 7.0%                           |
| 6          | 100,000                  | 2.0%                          | 14.0%                          |

**How to Increase Claiming Percentage?**

Simply increase the value of funds in your account, and the system will automatically adjust your claiming percentage. Once your account value reaches a higher level, the new claiming percentage will be applied starting from the next day.

Your account value takes into account all the assets in your account, including all coins, funds invested in Earn products, and Nekocoin.

#### Weekly Calculation of Claimable Nekocoin

Every week, we calculate how much Claimable Nekocoin you’ve accumulated based on your account’s net value over the previous week. Here’s how it works:

* **Every Monday**, we calculate the Claimable Nekocoin earned from the previous Monday to Sunday and update your account.
* The calculation is based on:
  * Your User level at each day
  * The total Nekocoin and Earned Nekocoin balance each day

The formula for Daily Claimable Nekocoin is:

```java
Daily Claimable Nekocoin = Total Neko Amount × Claiming Percentage
```

* The Total Neko Amount includes the **Nekocoin** and **Earned Nekocoin** in your account at 8 AM daily.
* The claiming percentage is determined by your User level.

#### Calculation Example

Here’s an example of how Claimable Nekocoin accumulates over a week:

| Day   | Total Neko Amount\* | Claiming Percentage | Daily Claimable Nekocoin |
| ----- | ------------------- | ------------------- | ------------------------ |
| Day 1 | 10,000              | 0.5%                | 50.0                     |
| Day 2 | 10,100              | 0.5%                | 50.5                     |
| Day 3 | 10,200              | 1.0%                | 102.0                    |
| Day 4 | 10,200              | 1.0%                | 102.0                    |
| Day 5 | 10,300              | 1.0%                | 103.0                    |
| Day 6 | 10,300              | 1.0%                | 103.0                    |
| Day 7 | 10,400              | 2.0%                | 208.0                    |
| Total |                     |                     | 718.5                    |

\*Total Neko Amount includes the Nekocoin and Earned Nekocoin.

#### Weekly Claimable Nekocoin Cap

There is a weekly cap on the total amount of Claimable Nekocoin for all users. If the total Claimable Nekocoin for a week exceeds this cap, your Claimable Nekocoin will be proportionally reduced.

* The weekly cap is **25,000,000 (25 million)**.
* If the total Claimable Nekocoin for a week exceeds 25 million, your Claimable Nekocoin will be reduced proportionally. For example, if the total is 30 million, your Claimable Nekocoin will be reduced to **25/30** of the original amount.
* Team will adjust the cap base on the NekoDex user number, tvl, etc.

#### How To Claim Your “Earned Nekocoin" To Portfolio

In NekoDex, go to the **Quest** tab and check your **Claimable** amount. Once you see a number under Claimable, you can click **Claim** buttom to receive the same amount of Nekocoin.

#### Difference Between Earned Nekocoin and Claimable Nekocoin

**What is Earned Nekocoin?**

Earned Nekocoin represents the portion of Nekocoin in your account that hasn’t been converted yet. You need to accumulate Claimable Neko to convert it into Nekocoin.

**What is Claimable Nekocoin?**

Claimable Nekocoin means the amount that can be converted into Nekocoin, and you can claim them by clicking the “Claim” button.

### FAQ

**When will my Claimable balance update?**

Each Monday, the system will automatically update your Claimable Nekocoin.

**If I forget or miss a daily check in, will my Claimable balance still update from Passive Claiming?**

Yes, your claimable balance will be automatically calculated and updated each Monday - you don’t have to do anything!

**Will account value fluctuations affect my claiming** **percentage for the week?**

Yes, we will take a snapshot of your account value in USD daily, this will determine your user level for that day. Fluctuations and market volatility will impact your USD account value and therefore your user level.

**I deposited funds, when will my claiming percentage update?**

Your claiming percentage is based upon your daily snapshot. If you recently added funds, you should see your percentage update within 1 day. If this still looks abnormal, please leave a message for the team on Discord.

**I only buy or earn and hold Nekocoin, can I still boost my User Level?**

Absolutely! Your User Level is based on the total net value of all the assets in your account, including Nekocoin!

**What happens if I forget to claim my Nekocoin**

You can claim your claimable Nekocoin at any time! If you forget this week, you can still claim this balance when you next check Nekodex.

**What happens to my Claimable Nekocoin if my Earned Nekocoin is reduced due to account inactivity?**

Your Claimable balance is the portion of your Earned balance that can be converted into Nekocoin. If your Earned Nekocoin balance is reduced due to inactivity, your Claimable balance will also be reduced.


# Earn Bonus

Limited-time only campaign

{% hint style="info" %}
This is a time-limited quest for all Nekodex users with an account value of over 50 USDC.
{% endhint %}

To celebrate your Nekodex journey, deposit over $50 to claim daily bonuses.

### Earn Bonus

Starting on September 5th, 2024, if you move funds to any of the Earn vault you can claim a daily bonus:

* Earn vault holding $50 ➡ claim another 25 Nekocoin/day
* Earn vault holding $100 ➡ claim another 50 Nekocoin/day
* Earn vault holding $200 ➡ claim another 100 Nekocoin/day
* ...and so on, up to 5,000 Nekocoin/day for $10,000 value deposited.

If your account value is 0, don't worry! Just deposit some USDC and you're ready to go.

{% hint style="info" %}

### **USD Value**

Earn Bonus is based on the USD value of your total Earn deposits. Stablecoins may vary in value slightly, meaning that 100 USDC, USDM, etc. may not always be $100 in value. This will affect your ability to claim the Earn Bonus. Deposit a little extra, e.g. 101 USDC, to enure you can always claim the maximum daily bonus 👍
{% endhint %}

## Check your Earn holdings

You can check you earn vault holdings on the "Earn" page

<figure><img src="/files/9g121cxa4anjJ6beRDNq" alt="" width="375"><figcaption></figcaption></figure>

## Claim Reward

If you are eligible, you will be able to claim the daily reward.

Go to the "**Quests**" page, go to Earn Bonus, and tap "**Claim**"! Don't forget to do it every day 😸👍

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

You can come back every day to claim as long as your account value remains over 50 USDC.


# Referral Program

## Promote Nekodex, Get paid

&#x20;Are you enjoying Nekodex? Get paid when you introduce friends!

## Rewards

💰 **Earn 2,500 Nekocoin** when your friend starts using Nekodex.&#x20;

💰 Your friend will earn an extra 1,500 Nekocoin bonus!

To get the rewards:

1. Your friend must use your referral code
2. Your friend must use Nekodex to earn 1,500 Nekocoin or more
3. Your friend must pass Proof of Personhood 👇

   <figure><img src="/files/3T6bLvi9ZJt61JeAHL09" alt=""><figcaption></figcaption></figure>

#### Limits

1. You can earn rewards for up to 10 friends. If you refer more than 10 friends, you won't get additional rewards for them.
2. 1,500 Nekocoin must be earned after Nov. 12, 2024. If you earned Nekocoin before that, don't worry—earn some more and you'll be set!

## Have more ideas?

Want to get paid to promote Nekodex? Contact us on X:

{% embed url="<https://x.com/Nekodex_app>" %}


# FAQ & Roadmap

Don't see your question here? Ask us on [Discord](https://discord.perp.com/) or by tagging us on X: `Nekodex_app`

## Sign up & Log in

#### Passkey not available

Make sure your phone lockscreen is turned on. Passkeys do not work without the lockscreen feature turned on, to keep your credentials secure.

If you are using the lockscreen and still have an issue, you can also try reinstalling the app, or restarting your phone.

#### Passkey does not match account

If you have more than one, you may need to rename your passkeys in order to tell them apart.

## Trading

#### My order did not go through

Sometimes an order can fail if the price changed, or for other reasons. Please try again. Your funds are safe throughout the order process.

#### My coins did not appear

It's possible your order did not go through (cancelled). Please check [Order History](https://app.nekodex.org/history).

## 🗺️ Roadmap

The Perp Labs (Perpetual Protocol) roadmap is driven by our **mission**: to build the best, easiest to use finance app—one you want to use every day and helps secure your financial future. That means working tirelessly to build features and optimize Nekodex.

{% hint style="info" %}
**Note**

Our roadmap will change often as new defi tech becomes available and market conditions change, so check back often and follow us on X! \[[Perp Labs on X](https://x.com/perpprotocol)] \[[Nekodex on X](https://x.com/Nekodex_app)]
{% endhint %}

{% stepper %}
{% step %}

### 2024

* Perp v3 R\&D
* Nekodex Playground
* Nekodex Spot Trading
* Nekocoin TGE & Rewards campaign
* In-app help chat with trained AI agent
  {% endstep %}

{% step %}

### 2025

* Complete
  * Rebrand as Perp Labs
  * Nekodex Android app launch
  * Migrate Nekodex Earn USDC vault to Morpho
  * PERP holder rewards
* In progress
  * Nekodex iOS app launch
  * Nekodex v2
* R\&D
  * AI/Agentic tools for crypto investors & traders
  * Gen. 2 cross chain swaps w/ Solana, Sui & more
  * PERP tokenomics & staking reboot
    {% endstep %}
    {% endstepper %}

If you have feedback, let us know via the in-app help!


# Links

Find official Nekodex and Perpetual Protocol links here

{% hint style="warning" %}
**Get support in the app!**

Due to the volume of scams, we **do not** provide user help on X, Telegram, Discord etc.

\
To get help, open the 👤 menu in Nekodex, and tap Help

![](/files/mDAd2PCN4zbDeKwmnkK9)
{% endhint %}

## Nekodex Official Links

* **Website:** [https://nekodex.org](http://nekodex.org/)
* **Web app:** [app.nekodex.org](http://app.nekodex.org)
* **Twitter/X:** [@Nekodex\_app](https://twitter.com/Nekodex_app)
* **Discord:**
  * Invite: [Nekodex By Perp](https://discord.perp.com/)
  * Mod usernames & IDs
    * lkb (757387821286686783)
    * terrarekt (326453067669045248)
    * hanamizuki[<br>](https://discord.com/settings/premium) (590529876818133036)
* **Telegram:** [@nekodex\_app](https://t.me/nekodex_app)
* **Telegram Announcements**: [@nekodex\_org](https://t.me/nekodex_org)
* **Email**: Any email ending with @nekodex.org
* **Docs**: <https://docs.nekodex.org/>

## App Store Links

Google Play: <https://play.google.com/store/apps/details?id=org.nekodex.app.twa>

Apple App Store: Coming Soon™️!

## **VIP Telegram Bot**

{% hint style="info" %}
VIP bot is whitelisted and will not relay messages from non-WL accounts

If you need assistance, contact us via in-app help 🙏
{% endhint %}

* @hana\_nekobot&#x20;
* @lkb\_nekobot

## Perpetual Protocol Official Links

* **Website**: <https://perp.com/>
* **Email:** Any email ending with @perp.com or @perp.fi
* **X/Twitter:** <https://x.com/perpprotocol>
* **Telegram general chat**: @perpetualprotocol
* **Telegram price chat**: @perp\_trading
* **Docs**: [https://support.perp.com](https://support.perp.com/)
* **Dev docs**: [https://docs.perp.com](https://docs.perp.com/)
* **Merch**: <https://shop.perp.com>
* **Youtube**: <https://www.youtube.com/c/perpetualprotocol>
* **Medium**: [https://perpetualprotocol.medium.com](https://perpetualprotocol.medium.com/)
* **Legacy products**
  * Perp v2: [https://app.perp.com](https://app.perp.com/)
  * Hot Tub: [https://vaults.perp.com](https://vaults.perp.com/arbop-op)
  * Staking v2: <https://token.perp.com/lazy-river>
  * Staking v1: [https://staking.perp.exchange](https://staking.perp.exchange/)

## Token Contracts

* $PERP
  * Optimism: [0x9e1028f5f1d5ede59748ffcee5532509976840e0](https://optimistic.etherscan.io/token/0x9e1028f5f1d5ede59748ffcee5532509976840e0)
  * Ethereum: [0xbC396689893D065F41bc2C6EcbeE5e0085233447](https://etherscan.io/token/0xbC396689893D065F41bc2C6EcbeE5e0085233447)
* Nekocoin loyalty token
  * Optimism: [0x6668bc6eea73404b4da5775c774fafc815b66b36](https://optimistic.etherscan.io/token/0x6668bc6eea73404b4da5775c774fafc815b66b36)


# About

## Contact us

Discord: <https://discord.perp.fi/>

X: <https://x.com/Nekodex_app>

Telegram: [https://t.me/perpetualprotocol](https://t.me/perpetualprotocol/1)

## About Nekodex

Nekodex is made by [Perp Labs](https://perp.com/) with 🐾🐾

Nekodex is powered by next-gen web3 technology like chain abstraction and account abstraction. Buy and sell crypto without a wallet, without confusing gas tokens, and without bridging funds between blockchains.

## History

Nekodex began in early 2024 as an idea to put together all of the advanced crypto tools that were ready to go but sadly underutilized. The Perp team used their 4+ years of DeFi building experience to chose and combine the best tech available to create an amazingly simple, intuitive crypto trading app!

## About Perp Labs (Perpetual Protocol)

Founded in October 2019, Perp Labs developed and launched their first derivatives DEX, called Perpetual Protocol (aka Perp v1) in December 2020. Perp v2 launched in November 2021. Perp Labs launched the ultra-smooth retail oriented Nekodex app in 2024, with a v2 expected in 2025.

The core contributors are [doxxed](https://www.kraken.com/learn/what-is-perpetual-protocol-perp) and one of the oldest in the game. We look forward to building great financial software together for users for many years to come.


# Nekodex $(=ↀωↀ=)

gmeow <img src="/files/6ok9ozavLRATZwf1E2sg" alt="" data-size="line">

## What is going on?

Nekodex is the first and only DEX allowing you to earn **rewards with 0 upfront cost**.

There’s nothing you can lose but only get more Nekocoin $(=ↀωↀ=)!

Nekodex is also the first onchain DEX with **gas-less and wallet-less** user experience.

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

## Nekocoin $(=ↀωↀ=)

Nekocoin is

* Your collateral for trading on Nekodex -- it's a virtual USD token to back your trades
* Your ticket to rewards: collect as much $(=ↀωↀ=) as you can!
* Ticker symbol: $(=ↀωↀ=)

Nekocoin is an ERC20 that is airdropped to you based on different campaigns and quests. You can use $(=ↀωↀ=) to trade on 50 markets, and do your best to earn more $(=ↀωↀ=) with winning trades.

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

## Nekodex 📈

Nekodex lets you long or short up to 50 tokens, with leverage between 10x and 30x depending on the token. Your $(=ↀωↀ=) holdings represent a virtual USD that can be used on Nekodex. If your trades make money, you will increase your $(=ↀωↀ=) holdings!

* Nekodex is a playground for users to try out Perp v3
* Nekodex uses $(=ↀωↀ=) as collateral, a limited ERC-20 token that will be swappable for rewards
* Your mission: collect more $(=ↀωↀ=)

Btw Nekodex uses isolated margin (each position has its own margin) lmeow

See some Nekostats here:

{% embed url="<https://dune.com/nekodex/nekodex>" %}
Neko Dashboard 🐾
{% endembed %}

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

## Cash out!

Simple cat explanations:&#x20;

get $(=ↀωↀ=) for free -> earn more by trading -> use to claim rewards in the end

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

## Nekodex invites

You need an invite link to access Nekodex. We will be giving these out so watch our socials 👀

All invite links are limited-use, so if you get one, **be careful who you give it to**! Farmers and sybils might try to use them up ...

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

## What about Perp v3?

Nekodex is the playground where you can learn about how Perp v3 works, how it feels, and get comfy. Perp v3 will launch after the Nekodex campaign is over (roughly 2 months from launch - TBC).

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

## Nekodex account

Nekodex and Perp v3 all use Ethereum Account Abstraction (ERC-4337) powered by ZeroDev. It has some very cozy features to get your paws on :feet:

* No wallet: Quick & easy sign up with an email & Passkey on your phone
* No gas: All trades are gas free / network fee free
* No signing: Tap-to-trade lets you confirm trades fast, no opening wallet, no wasting time
* No deposit: You can start trading right away with $(=ↀωↀ=) collateral

📱 Smartphone optimized: use your iPhone or Android to trade anywhere, anytime.

<img src="/files/Tb8rJzjHGbrVvZYnL4By" alt="" data-size="line"> Passkey enabled: use your iPhone or Android to sign up in seconds using Passkey.

{% hint style="warning" %}
**Account safety**

DO NOT lose your account email. If you cannot access the email used to sign up, you cannot log in again (if you are logged out). You need to be able to receive emails at this address to log in in the future 🐾

You will also need this email account to claim rewards in the end, so use an email you plan to keep.

DO backup / sync your account with iCloud or Google One. You will need this backup if your phone is broken or lost in order to sign in from a new device.
{% endhint %}

Learn more about [Perp Smart Account](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-smart-account)

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

## More info

If you want to know more about how Nekodex really works, it is based 100% on Perp v3. Please check out the other articles here, like [Introducing Perp v3](/nekodex-playground/introducing-perp-v3), [Trade perpetual futures](/nekodex-playground/docs-for-users/trade-perpetual-futures) & [How Perp v3 works](/nekodex-playground/docs-for-users/how-perp-v3-works).

## FAQ

So manys questions lmeow <img src="/files/6ok9ozavLRATZwf1E2sg" alt="" data-size="line">

### Sign-up

* WTF?
  * lmeow
* Why Nekodex and not Perp v3?
  * Fun, no risk
  * Earn real rewards
  * Get comfy with new Ethereum account abstraction technology & Passkey
  * Get ready for trading on Perp v3 when the bull market hits
  * Perp team can improve the Perp v3 UI and protocol based on your feedback
* Is this testnet?
  * We are testing in production on Optimism Mainnet, but the collateral used for trading is $(=ↀωↀ=). You can think of it as a live-fire exercise, but with rubber bullets.
* Why do we need invite links?
  * We want to limit the amount of users to make sure everyone has a fair chance to collect a tasty amount of rewards.
* Why do we need to sign up with email?
  * The ERC-4337 account system from ZeroDev creates your account using an email address as the identifier. You will need to maintain access to this email in order to log in! ⚠️ Do not use a temporary or disposable email address - you could lose access to your account.
* Can't log in ...
  * Make sure to use the same email, and the same authentication method (Passkey). If you created the account with Passkey, you cannot sign in with web3 wallet and vice versa.

### Nekodex account

An account is created for you when you sign up. For more help, see [Perp Smart Account](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-smart-account#faq-troubleshooting)

* Why can't we use an existing wallet?
  * In order to let you trade with 2 clicks, no gas fees, and more, we have to use a separate smart account with a new address.
* I already have a Passkey wallet but a whole new wallet was created?
  * Passkey-created wallets (for now) can only be used with one app (the one you set it up with). So if you set a Passkey wallet up on another app, it does not work on Nekodex.

### Trading

Please see main [FAQs](/nekodex-playground/all-about-perp/faqs)

* Why not use real collateral like USDC, USDT?
  * Nekodex uses Nekocoin so you can try risk-free while also earning some rewards.
  * Perp v3 will use USDT and possibly other types of collateral in the future.
* Cross margin or isolated?
  * Nekodex and Perp v3 use isolated margin.
* Are there charting tools for drawing, etc.?
  * Perp v3 desktop version should have this.
* Wen stop loss and take profit ...
  * This will have to wait for Perp v3 post-launch, but for you you can set a Take Profit by creating a limit order for the opposite position (use a short to close a long, etc.). The two positions will cancel out. Fill the exact position size by tapping on the 'Current Position Size'.\
    &#x20;![](/files/2YV9PLONcftUujOo9MnU)

### Rewards

* What & how many rewards will each trader get?
  * The reward type and amount is TBC—to be confirmed.
* What is the total reward pool?
  * TBC depending on how many people participate. Focus will be on fairness.
* Will Nekocoin $(=ↀωↀ=) continue to exist after the campaign?
  * $(=ↀωↀ=) is an ERC-20 that you will be able to sell, hold, or do most things you can do with an ERC-20 token. So it will continue to exist as long as the blockchain exists.
* Will $PERP holders be affected?
  * No $PERP will be used in this campaign.&#x20;
  * $(=ↀωↀ=) will not replace or affect $PERP.
* Is this a points campaign? Is this an airdrop?
  * Points make our noses itch. Users will be dropped $(=ↀωↀ=) ERC-20 tokens but we aren't sure if they are from the air or somewhere else. Maybe they grow like catnip? <img src="/files/v2ikwsXM9S9NCJ9kpYQ2" alt="" data-size="line">
* What is the token contract?
  * [https://optimistic.etherscan.io/token/0x6668BC6EEa73404B4DA5775c774FAFC815b66b36](https://optimistic.etherscan.io/token/0x6668BC6EEa73404B4DA5775c774FAFC815b66b36#balances)
* Who are the pre-launch Nekocoin holders?
  * All addresses with tokens used pre-launch are barred from future rewards.
  * Holders also include key DEX functions like the team liquidity provider, keepers and airdrop distributor.


# Terms of Service

**OUR SERVICES ARE&#x20;*****NOT*****&#x20;OFFERED TO PERSONS OR ENTITIES WHO RESIDE IN, ARE CITIZENS OF, ARE INCORPORATED IN, OR HAVE A REGISTERED OFFICE IN THE UNITED STATES OF AMERICA OR ANY RESTRICTED TERRITORY, AS DEFINED BELOW (ANY SUCH PERSON OR ENTITY FROM THE UNITED STATES OF AMERICAN OR A RESTRICTED TERRITORY, A “RESTRICTED PERSON”). WE DO NOT MAKE EXCEPTIONS; THEREFORE, IF YOU ARE A RESTRICTED PERSON, THEN DO NOT ATTEMPT TO USE OR USE THE INTERFACE. USE OF A VIRTUAL PRIVATE NETWORK (E.G., A VPN) TO USE OUR SERVICES AS A RESTRICTED PERSON OR FROM THE UNITED STATES OF AMERICA OR A RESTRICTED TERRITORY IS PROHIBITED.** Welcome to [https://app.nekodex.org](https://app.perp.com/), a website-hosted user interface (the “Interface”) made available by Strike Co. Ltd. (“we”, “our”, or “us”). The Interface provides access to a decentralized protocol on the Ethereum blockchain that allows users to create perpetual contracts enabled by a virtual automated market maker (the “Protocol”). These Terms of Use and any terms and conditions incorporated herein by reference (collectively, the “Terms”) govern your access and use of the Interface. You must read the Terms carefully. By accessing, browsing or otherwise using the Interface, or by acknowledging agreement to the Terms on the Interface, you agree that you have read, understood and accepted all of the Terms and our Privacy Policy (the “Privacy Policy”), which is incorporated by reference into the Terms. THE TERMS CONTAIN IMPORTANT INFORMATION, INCLUDING A BINDING ARBITRATION PROVISION AND A CLASS ACTION WAIVER, BOTH OF WHICH IMPACT YOUR RIGHTS AS TO HOW DISPUTES ARE RESOLVED. We may change, amend, or revise the Terms from time to time and at any time, in our sole discretion. When we make changes, we will make the updated Terms available on the Interface and update the “Last Updated” date at the beginning of the Terms accordingly. Please check the Terms periodically for changes. Any changes to the Terms will apply on the date that they are made, and your continued access or use of the Interface after the Terms have been updated will constitute your binding acceptance of the updates. If you do not agree to the revised Terms, then you should not continue to access or use the Interface.

#### **1) Eligibility** <a href="#id-1-eligibility" id="id-1-eligibility"></a>

In order to use the Interface, you must satisfy the following eligibility requirements:

1. You are of legal age in the jurisdiction in which you reside and you have legal capacity to enter into the Terms and be bound by them;
2. If you accept the Terms on behalf of a legal entity, you must have the legal authority to accept the Terms on that entity’s behalf, in which case “you” (except as used in this paragraph) will mean that entity;
3. You are not a resident, national or agent of Antigua and Barbuda, Algeria, Bangladesh, Bolivia, Belarus, Burundi, Myanmar (Burma), Cote D'Ivoire (Ivory Coast), Crimea and Sevastopol, Cuba, Democratic Republic of Congo, Ecuador, Iran, Iraq, Libya, Mali, Morocco, Magnitsky, Liberia, Nepal, North Korea, Somalia, Sudan, Syria, Venezuela, Zimbabwe or any other country to which the United States, the United Kingdom or the European Union embargoes goods or imposes similar sanctions (collectively, “Restricted Territories”); (ii) you are a member of any sanctions list or equivalent maintained by the United States government, the United Kingdom government, by the European Union or the United Nations (collectively, “Sanctions Lists Persons”); or (iii) you intend to transact with any Restricted Territories or Sanctions List Persons;
4. You are not a Restricted Person;
5. You are not a resident of, reside in, a citizen of, incorporated in, or have a registered office in Taiwan (Republic of China), or the United States of America, or the United Kingdom; and
6. Your use of the Interface is not prohibited by and does not otherwise violate, assist you in the violation of any applicable laws or regulations, or contribute to or facilitate any illegal activity.

#### **2) Access to the Interface** <a href="#id-2-access-to-the-interface" id="id-2-access-to-the-interface"></a>

We reserve the right to disable access to the Interface at any time in the event of any breach of the Terms, including without limitation, if we reasonably believe that you, at any time, fail to satisfy the eligibility requirements set forth in the Terms. Further, we reserve the right to limit or restrict access to the Interface by any person or entity, or within any geographic area or legal jurisdiction, at any time and in our sole discretion. We will not be liable to you for any losses or damages you may suffer as a result of or in connection with the Interface being inaccessible to you at any time or for any reason.

#### **3) Proprietary Rights** <a href="#id-3-proprietary-rights" id="id-3-proprietary-rights"></a>

1. We own all intellectual property and other rights in the Interface and its contents, including, but not limited to, software, text, images, trademarks, service marks, copyrights, patents, and designs. Unless expressly authorized by us, you may not copy, modify, adapt, rent, license, sell, publish, distribute, or otherwise permit any third party to access or use the Interface or any of its contents. Accessing or using the Interface does not constitute a grant to you of any proprietary intellectual property or other rights in the Interface or its contents.
2. You will retain ownership of all intellectual property and other rights in any information and materials you submit through the Interface. However, by uploading such information or materials, you grant us a worldwide, royalty-free, irrevocable license to use, copy, distribute, publish and send this data in any manner in accordance with applicable laws and regulations.
3. You may choose to submit comments, bug reports, ideas or other feedback about the Interface, including, without limitation, about how to improve the Interface (collectively, “Feedback”). By submitting any Feedback, you agree that we are free to use such Feedback at our discretion and without additional compensation to you, and to disclose such Feedback to third parties (whether on a non-confidential basis, or otherwise). If necessary under applicable law, then you hereby grant us a perpetual, irrevocable, non-exclusive, transferable, worldwide license under all rights necessary for us to incorporate and use your Feedback for any purpose.
4. If you satisfy all of the eligibility requirements in the Terms and that your access to and use of the Interface complies with the Terms, you hereby are granted a single, personal, limited license to access and use the Interface. This license is non-exclusive, non-transferable, and freely revocable by us at any time without notice or cause. Use of the Interface for any purpose not expressly permitted by the Terms is strictly prohibited. Unlike the Interface, the Protocol is comprised entirely of open-source software running on the public Ethereum blockchain and is not our proprietary property.

#### **4) Prohibited Activity** <a href="#id-4-prohibited-activity" id="id-4-prohibited-activity"></a>

You agree not to engage in, or attempt to engage in, any of the following categories of prohibited activity in relation to your access or use of the Interface:

1. Activity that breaches the Terms;
2. Activity that infringes on or violates any copyright, trademark, service mark, patent, right of publicity, right of privacy, or other proprietary or intellectual property rights under the law.
3. Activity that seeks to interfere with or compromise the integrity, security, or proper functioning of any computer, server, network, personal device, or other information technology system, including, but not limited to, the deployment of viruses and denial of service attacks.
4. Activity that seeks to defraud us or any other person or entity, including, but not limited to, providing any false, inaccurate, or misleading information in order to unlawfully obtain the property of another.
5. Activity that violates any applicable law, rule, or regulation concerning the integrity of trading markets, including, but not limited to, the manipulative tactics commonly known as spoofing and wash trading.
6. Activity that violates any applicable law, rule, or regulation of the United States or another relevant jurisdiction, including, but not limited to, the restrictions and regulatory requirements imposed by U.S. law.
7. Activity that disguises or interferes in any way with the IP address of the computer you are using to access or use the Interface or that otherwise prevents us from correctly identifying the IP address of the computer you are using to access the Interface.
8. Activity that transmits, exchanges, or is otherwise supported by the direct or indirect proceeds of criminal or fraudulent activity.

#### **5) No Professional Advice or Fiduciary Duties** <a href="#id-5-no-professional-advice-or-fiduciary-duties" id="id-5-no-professional-advice-or-fiduciary-duties"></a>

1. All information provided in connection with your access and use of the Interface is for informational purposes only and should not be construed as professional advice. You should not take, or refrain from taking, any action based on any information contained in the Interface or any other information that we make available at any time, including, without limitation, blog posts, articles, links to third-party content, news feeds, tutorials, tweets and videos. Before you make any financial, legal, or other decisions involving the Interface, you should seek independent professional advice from an individual who is licensed and qualified in the area for which such advice would be appropriate.
2. The Terms are not intended to, and do not, create or impose any fiduciary duties on us. To the fullest extent permitted by law, you acknowledge and agree that we owe no fiduciary duties or liabilities to you or any other party, and that to the extent any such duties or liabilities may exist at law or in equity, those duties and liabilities are hereby irrevocably disclaimed, waived, and eliminated. You further agree that the only duties and obligations that we owe you are those set out expressly in the Terms.

#### **6) No Warranties** <a href="#id-6-no-warranties" id="id-6-no-warranties"></a>

The Interface is provided on an “AS IS” and “AS AVAILABLE” basis. To the fullest extent permitted by law, we disclaim any representations and warranties of any kind, whether express, implied, or statutory, including, but not limited to, the warranties of merchantability and fitness for a particular purpose. You acknowledge and agree that your access and use of the Interface is at your own risk. We do not represent or warrant that access to the Interface will be continuous, uninterrupted, timely, or secure; that the information contained in the Interface will be accurate, reliable, complete, or current; or that the Interface will be free from errors, defects, viruses, or other harmful elements. No advice, information, or statement that we make should be treated as creating any warranty concerning the Interface. We do not endorse, guarantee, or assume responsibility for any advertisements, offers, or statements made by third parties concerning the Interface.

#### **7) Compliance Obligations** <a href="#id-7-compliance-obligations" id="id-7-compliance-obligations"></a>

The Interface may not be available or appropriate for use in all jurisdictions. By accessing or using the Interface, you agree that you are solely and entirely responsible for compliance with all laws and regulations that may apply to you. You further agree that we have no obligation to inform you of any potential liabilities or violations of law or regulation that may arise in connection with your access and use of the Interface and that we are not liable in any respect for any failure by you to comply with any applicable laws or regulations.

#### **8) Assumption of Risk** <a href="#id-8-assumption-of-risk" id="id-8-assumption-of-risk"></a>

By accessing and using the Interface, you represent that you understand (a) the inherent risks associated with products made available through the Protocol, and (b) the inherent risks associated with using cryptographic and blockchain-based systems. You further represent that you have a working knowledge of the usage and intricacies of blockchain-based digital assets, including, without limitation, ERC-20 token standard available on the Ethereum blockchain. You further understand that the markets for these blockchain-based digital assets are highly volatile due to factors that include, but are not limited to, adoption, speculation, technology, security, and regulation. You acknowledge that the cost and speed of transacting with blockchain-based systems, such as Ethereum, are variable and may increase or decrease, respectively, drastically at any time. You hereby acknowledge and agree that we are not responsible for any of these variables or risks associated with the Protocol and cannot be held liable for any resulting losses that you experience while accessing or using the Interface. Accordingly, you understand and agree to assume full responsibility for all of the risks of accessing and using the Interface to interact with the Protocol.

#### **9) Third-Party Resources and Promotions** <a href="#id-9-third-party-resources-and-promotions" id="id-9-third-party-resources-and-promotions"></a>

The Interface may contain references or links to third-party resources, including, but not limited to, information, materials, products, or services, that we do not own or control. In addition, third parties may offer promotions related to your access and use of the Interface. We do not endorse or assume any responsibility for any such resources or promotions. If you access any such resources or participate in any such promotions, you do so at your own risk, and you understand that the Terms do not apply to your dealings or relationships with any third parties. You expressly relieve us of any and all liability arising from your use of any such resources or participation in any such promotions.

#### **10) Release of Claims** <a href="#id-10-release-of-claims" id="id-10-release-of-claims"></a>

You expressly agree that you assume all risks in connection with your access and use of the Interface. You further expressly waive and release us from any and all liability, claims, causes of action, or damages arising from or in any way relating to your access and use of the Interface.

#### **11) Indemnity** <a href="#id-11-indemnity" id="id-11-indemnity"></a>

You agree to hold harmless, release, defend, and indemnify us and our officers, directors, employees, contractors, agents, affiliates, and subsidiaries from and against all claims, damages, obligations, losses, liabilities, costs, and expenses arising from: (a) your access and use of the Interface; (b) your violation of the Terms, the rights of any third party, or any other applicable law, rule, or regulation; and (c) any other party’s access and use of the Interface with your assistance or using any device or account that you own or control.

#### **12) Limitation of Liability** <a href="#id-12-limitation-of-liability" id="id-12-limitation-of-liability"></a>

Under no circumstances shall we or any of our officers, directors, employees, contractors, agents, affiliates, or subsidiaries be liable to you for any indirect, punitive, incidental, special, consequential, or exemplary damages, including (but not limited to) damages for loss of profits, goodwill, use, data, or other intangible property, arising out of or relating to any access or use of the Interface, nor will we be responsible for any damage, loss, or injury resulting from hacking, tampering, or other unauthorized access or use of the Interface or the information contained within it. We assume no liability or responsibility for any: (a) errors, mistakes, or inaccuracies of content; (b) personal injury or property damage, of any nature whatsoever, resulting from any access or use of the Interface; (c) unauthorized access or use of any secure server or database in our control, or the use of any information or data stored therein; (d) interruption or cessation of function related to the Interface; (e) bugs, viruses, trojan horses, or the like that may be transmitted to or through the Interface; (f) errors or omissions in, or loss or damage incurred as a result of the use of, any content made available through the Interface; and (g) the defamatory, offensive, or illegal conduct of any third party. Under no circumstances shall we or any of our officers, directors, employees, contractors, agents, affiliates, or subsidiaries be liable to you for any claims, proceedings, liabilities, obligations, damages, losses, or costs in an amount exceeding the amount you paid to us in exchange for access to and use of the Interface, or $100.00, whichever is greater. This limitation of liability applies regardless of whether the alleged liability is based on contract, tort, negligence, strict liability, or any other basis, and even if we have been advised of the possibility of such liability. Some jurisdictions do not allow the exclusion of certain warranties or the limitation or exclusion of certain liabilities and damages. Accordingly, some of the disclaimers and limitations set forth in the Terms may not apply to you. This limitation of liability shall apply to the fullest extent permitted by law.

#### **13) Dispute Resolution** <a href="#id-13-dispute-resolution" id="id-13-dispute-resolution"></a>

We will use our best efforts to resolve any potential disputes through informal, good faith negotiations. If a potential dispute arises, you must contact us by sending an email to \[<help@perp.fi>] so that we can attempt to resolve it without resorting to formal dispute resolution. If we are not able to reach an informal resolution within sixty days of your email, then you and we both agree to resolve the potential dispute according to the process set forth below. Any claim or controversy arising out of or relating to the Interface, the Terms, or any other acts or omissions for which you may contend that we are liable, including (but not limited to) any claim or controversy as to arbitrability (“Dispute”), shall be finally and exclusively settled by arbitration administered by the CAA International Arbitration Centre (CAAI) under the Chinese Arbitration Association, Taipei (CAA) Arbitration Rules in force at the time of the filing for arbitration of any Dispute. You understand that you are required to resolve all Disputes by binding arbitration. The arbitration shall be held on a confidential basis before a single arbitrator and shall be conducted in English. Unless we agree otherwise, the arbitrator may not consolidate your claims with those of any other party. Any judgment on the award rendered by the arbitrator may be entered in any court of competent jurisdiction other than the United States of America, to the extent a court therein would be deemed to be a court of competent jurisdiction. You further agree that the Interface shall be deemed to be based solely in the Republic of Seychelles and that, although the Interface may be available in other jurisdictions, its availability does not give rise to general or specific personal jurisdiction in any forum outside the Republic of Seychelles.

#### **14) Class Action and Jury Trial Waiver** <a href="#id-14-class-action-and-jury-trial-waiver" id="id-14-class-action-and-jury-trial-waiver"></a>

You must bring any and all Disputes against us in your individual capacity and not as a plaintiff in or member of any purported class action, collective action, private attorney general action, or other representative proceeding. This provision applies to class arbitration. You and we both agree to waive the right to demand a trial by jury.

#### **15) Governing Law** <a href="#id-15-governing-law" id="id-15-governing-law"></a>

You agree that the laws of the Republic of Seychelles, without regard to principles of conflict of laws, govern the Terms and any Dispute between you and us.

#### **16) Entire Agreement** <a href="#id-16-entire-agreement" id="id-16-entire-agreement"></a>

The Terms, including the Privacy Policy, constitute the entire agreement between you and us with respect to the subject matter hereof, including the Interface. The Terms, including the Privacy Policy, supersede any and all prior or contemporaneous written and oral agreements, communications and other understandings relating to the subject matter of the Terms.

#### **17) Privacy Policy** <a href="#id-17-privacy-policy" id="id-17-privacy-policy"></a>

The Privacy Policy describes the ways we collect, use, store and disclose your personal information. You agree to the collection, use, storage, and disclosure of your data in accordance with the Privacy Policy.


# Introducing Perp v3

{% hint style="info" %}
These are docs for Perp v3.&#x20;

* Nekodex is 100% based on Perp v3.
* For older Perp versions, see legacy docs for [v1](https://v1docs.perp.fi/) and [v2](https://support.perp.com/).
  {% endhint %}

Introducting Perp v3, the latest, greatest decentralized exchange from the team that

* Launched the world's first onchain perpetual swaps using vAMM in 2020
* Launched next-gen perps markets based on Uniswap v3 in 2021
* Is one of the most Lindy teams in Defi (here since 2019)
* Is a doxxed, non-US based team co-founded by experienced serial entrepreneurs

## What is Perp v3?

Our latest DEX uses a modular liquidity framework that adapts easily to changing market needs and new Defi innovations. The design goals of Perp v3 include:

* Deep liquidity with oracle pricing for major assets like ETH and BTC
* Faster launches for hot and emerging assets using spot-hedged LP pools
* A framework for launching new, innovative liquidity mechanisms quickly without rebuilding
* Easy, feature rich trading UI serving retail and pro traders alike

## More about Perp v3

Check out our products in [Product info](/nekodex-playground/all-about-perp/project-overview/product-info)

Start trading now in [Trade perpetual futures](/nekodex-playground/docs-for-users/trade-perpetual-futures)

Learn more about [How Perp v3 works](/nekodex-playground/docs-for-users/how-perp-v3-works)

## More about Perpetual Protocol

[Product info](/nekodex-playground/all-about-perp/project-overview/product-info)

[About us](/nekodex-playground/all-about-perp/project-overview/about-us)

[Contact us](/nekodex-playground/all-about-perp/contact-us)


# Project overview

Founded in October 2019, Perpetual Protocol wrote and launched their first derivatives DEX in December 2020. Perp v2 launched in November 2021, and Perp v3 arrived on the scene in 2024.

The team is doxxed and one of the oldest in the game. We look forward to building great software together for users for many years to come.

## 🧭 Mission

Our mission is driven by 2 key elements:

1. **Access:** Traditionally there are a class of financial products that are only available to "sophisticated investors", aka people with money. We want to provide accessibility of financial products to all retail users regardless of their financial status
2. **Simplicity**: We want to take these complex financial products and make them simple in such a way where it's fair and understandable by all. No more confusing products or negative UX!

## Learn more

[Product info](/nekodex-playground/all-about-perp/project-overview/product-info)

[About us](/nekodex-playground/all-about-perp/project-overview/about-us)


# Product info

Perpetual Protocol has built products for just about every type of user.

<table data-view="cards"><thead><tr><th></th><th></th><th></th></tr></thead><tbody><tr><td><h2>Earn</h2></td><td><p>Easy to use vaults. Deposit your funds and watch your earnings grow.</p><p></p><p>Read the docs</p><p><a data-mention href="/pages/wdSgM3rQqXHQu2dSqWdM">/pages/wdSgM3rQqXHQu2dSqWdM</a></p><p></p><p>Go to the dApp</p></td><td><a href="https://perp.com/earn">https://perp.com/earn</a></td></tr><tr><td><h2>Trade</h2></td><td>Go long or short, with up to 50x leverage.</td><td><p></p><p>Read the docs</p><p><a data-mention href="/pages/BHNALvwGthSrblYNnH10">/pages/BHNALvwGthSrblYNnH10</a></p><p></p><p>Go to the dApp</p><p><a href="https://app.perp.com/">https://app.perp.com</a></p></td></tr><tr><td><h2>Be an LP</h2></td><td><p>Tools for experienced Defi users who want to put their money to work. </p><p></p><p>Read the docs</p><p><a data-mention href="/pages/KDMkt8ojwTiJ1WrY15qg">/pages/KDMkt8ojwTiJ1WrY15qg</a></p><p></p><p>Go to the dApp</p></td><td><a href="https://app.perp.com/pools/">https://app.perp.com/pools</a></td></tr></tbody></table>


# About us

## About the team

Currently the team is based in many countries around the world, with a majority of team members based in Taiwan. There are no team members based in the United States.

The Perp team is mostly doxxed, including our two co-founders. The team is comprised of:

* 2 co-founders
* 8 dev team members
* 2 design & FE team members
* 4 growth & data team members
* 1 support & community team member
* 2 community mods (Sharks)

## Project history

The project was founded in Q4 2019 by a small team of 3 crypto enthusiasts. Over the following months, the project developed into it's current form—an onchain perpetual futures exchange.

Building on Uniswap's Automated Market Maker (AMM) model, Perp v1 pioneered the virtual AMM concept. The plan was to launch on Ethereum mainnet in September 2020. A large spike in gas fees on Ethereum during DeFi Summer (2020) led Perpetual Protocol's core team to change course and instead deploy on xDai (now Gnosis Chain). After a few months of porting work, audits and final tweaks, Perp v1 launched in December 2020.

As Perp v1 gained traction, a slow drain on the insurance fund was discovered, and the core team set to work seeking solutions. The underlying cause, known as the long-short skew (explained in more detail [here](https://insights.deribit.com/market-research/the-quest-for-perp-amms/)) refers to the situation where there was a high chance of funding being paid from the insurance fund due to an imbalance between longs and shorts, something that is unavoidable in a pure vAMM system like Perp v1 where liquidity is static. The assumption was that inflows and outflows would balance out over the long-term, but the sustained bull market during 2021 caused the insurance fund to struggle to grow and at times decrease dramatically.

This issue and others were discussed in [Community call #4](https://www.youtube.com/watch?v=H5qvFuL83QM) during April 2021. The team also discussed these issues with different people involved in the crypto ecosystem, including investors and other experts, but since automated market makers were a fairly new concept, a satisfactory solution remained elusive.

### Perp v1

Docs Archive: [Perp v1](https://v3docs.perp.com/perp-v1/)

This section covers some noteworthy implementation details and challenges.

* A key planned feature of Perp v1 was a “dynamic k” system which would allow k values for each perpetual swap market to be adjusted manually or automatically was completed in May 2021 but never rolled out. Despite months of research and consultation, no “ideal” dynamic k system could be found, and the model that was developed but not deployed used certain trade-offs that would have made the trading experience more complex and diverge farther from the traditional orderbook model many traders are familiar with. This uncertainty and the shift to the Perp v2 model led the core team to put the dynamic k rollout on hold indefinitely.
* A PERP backstop minting feature was intended as part of the original Ethereum mainnet design. This minting mechanism would allow the exchange to automatically mint and sell PERP in the event of the insurance fund balance reaching zero. However, as Perp v1 ultimately launched on xDai, the minting system was not built as planned due to most PERP liquidity being on mainnet with very little liquidity available on xDai, making the system infeasible. It can also be noted that the Perp v1 insurance fund never reached the proposed minting conditions during its time of operation.

### Perp v2

Docs Archive: [Perp v2](https://support.perp.com/)

While researching ideas to counter the issues of v1, the team came up with a completely new model that moved away from a pure vAMM model toward an LP-driven derivatives AMM (dAMM) solution that solved v1’s issues and promised improved composability and performance. Work started on Perp v2 Curie in May 2021 and v1 entered maintenance mode.

After the launch of Perp v2 on Optimism in November 2021, active maintenance on v1 began to wind down and warnings were placed on the UI to alert traders to the risks of continuing to use the old version. While maintenance was reduced, active monitoring continued as usual and Perp v1 remained operational, was stable and had many active users, so there was no motivation to shut it down.

### Closing Perp v1

Up to April 2022, monitoring showed v1 to be running well, however, the market downturn in April & May brought v1’s flaws back to the fore. As asset prices fell, perp prices could not keep up with spot and the funding payments became very large. A short-term solution was implemented in the form of a funding rate cap to stem outflows from the insurance fund and maintain solvency while the search for a longer term fix continued.

The funding rate cap had a side effect that some arbitragers were no longer attracted to trade, despite APRs over 100%. Combined with rapidly changing prices, many Perp v1 markets diverged from spot prices significantly.

At this point, a decision was made to upgrade the vAMM contracts and decrease the K value of each, making it easier to keep the perpetual swap prices closer to the spot price.

A few days later, on May 15, a large short position in the CREAM market was liquidated during chaotic price action, causing over $2 million in bad debt. The v1 protocol moved money from the insurance fund to the clearinghouse to ensure solvency, bringing the insurance fund to a dangerously low level.

At this point, the core team decided an emergency halt in trading was required to prevent further loss of funds. Extensive discussions began both internally, with advisors and with the v1 user community as to how to handle the disbursement of remaining funds.

Ultimately a governance vote was held to decide how to distribute the remaining funds. The full proposal can be found on the project governance forum: [Sunsetting Perp v1](https://gov.perp.fi/t/sunsetting-perp-v1/698). From among several options, the vote decided that the remaining funds were to be distributed to cover 99% of users according to their margin plus PnL (where negative PnL would reduce the amount), from smallest to largest account. The remaining funds would be distributed to the largest accounts, again proportionally to margin plus PnL.

The [distribution](https://blockscout.com/xdai/mainnet/address/0x371D128A0a286800d3A5E830F1D26dFf237A3279/token-transfers#address-tabs%C2%A0) occurred on June 1st, 2022.

### Staking 1.0 to vePERP

The original staking system rolled out a few months after the launch of Perp v1, in March 2021. The original design anticipated fee sharing to start not long afterward, but as issues with Perp v1 became apparent, work on Perp v1 and Staking 1.0 were put on pause as resources were directed toward the development of Perp v2.

After Perp v2 launched in November 2021, development of key features and upgrades, as well as countless optimizations and improvements, occupied the core team for several months. Ultimately, Staking 2.0 featuring vePERP began its rollout in August 2022.

## Project investors

In August 2020, $1.8 million was raised in a [seed round](https://blog.perp.fi/perpetual-protocol-announces-1-8m-strategic-investment-83cff55b6dfe) led by Multicoin Capital, with investors such as Alameda Research, Binance Labs, CMS Holdings, Three Arrows Capital, and Zee Prime Capital taking part.  All investor tokens were full vested as of December 2021.

The PERP token was also distributed to community investors through the very first Liquidity Bootstrapping Pool via Balancer, which you can find out more about [here](https://blog.perp.fi/why-we-chose-to-distribute-perp-using-a-balancer-liquidity-bootstrapping-pool-aac7f1ab6181).&#x20;


# Governance

## Governance Model <a href="#governance-model" id="governance-model"></a>

Perpetual Protocol is governed by the community via forum discussions and voting on proposals. We welcome any discussion about how the governance model works, as well as discussion on any topic relevant to protocol development, management, operations etc.

#### Governance forum

* Current: [Discord governance forum](https://discord.com/channels/687397941383659579/1216985506252849162)
* Archived: [https://gov.perp.fi](https://gov.perp.fi/)

Currently governance of Perpetual Protocol operates under a hybrid model.

* **Community governance**: Covers all aspects that can be reasonably handled via community discussion and voting.
  * Use of Perpetual DAO funds, including PERP tokens
  * Exchange parameters, such as insurance fund threshold, fee level & distribution, etc.
* **Foundation team**: Covers aspects that cannot be reasonably handled via governance at this time, or are of a sensitive nature.
  * Short- and mid-term strategy
  * Protocol design & development
  * Website (UI) development and maintenance
  * Emergency updates, fixes and operations

As the protocol develops and more governance tools become available, community governance will take over more aspects of protocol development and operations.

## Perpetual DAO <a href="#perpetual-dao" id="perpetual-dao"></a>

The core of the project is the Perpetual DAO, which controls the DAO treasury including PERP tokens, excess DEX income. All PERP holders are DAO members with voting rights (assuming they self-custody).

To streamline DAO governance, operational tasks are divided among a set of sub-DAOs. New sub-DAOs may be proposed and added / removed as required.

## Sub-DAOs <a href="#sub-daos" id="sub-daos"></a>

{% hint style="warning" %}
Sub DAO activity is currently reduced due to the bear market and the shift in focus to Perp v3. Regular Sub DAO activites are expected to resume as community interest returns.
{% endhint %}

The vision for Perpetual Protocol is to decentralize gradually over time, eventually dissolving the foundation and transitioning it into a fully fledged Decentralized Autonomous Organization (DAO) so that the community has complete stewardship of the protocol.

Following the lead of DAOs such as Yearn Finance, one of the first projects to successfully partition itself, Perpetual Protocol is working towards compartmentalizing different aspects of the protocol, where each sub-DAO is responsible for making decisions and managing their own budgets independently.

These sub-DAOs sow the seeds for grassroots participation, enabling new forms of coordination and creating a user-centric network. Currently, a committee model is used across sub-DAOs, where token holders periodically vote for a committee, which will then make the decisions for a particular focus area.

However, the plan is for sub-DAOs to be self-organizing, allowing individuals who share a common view to create a group and then work together for the Perpetual Protocol DAO. This approach to governance is inspired by MakerDAO’s ‘[The Endgame Plan](https://forum.makerdao.com/t/the-endgame-plan-parts-1-2/15456)’.

The current sub-DAO structure is shown below. Any use of the DAO treasury funds must be first approved by token holders, through community dialogue, governance forum proposals and voting via Snapshot.

Below, we detail the sub-DAOs that currently exist or are being proposed. The formation of further sub-DAOs in the future across different areas (e.g., engineering, marketing, partnerships, etc.) will help the project achieve its goal of decentralization and immutability.

### **Grants DAO**

The [Grants DAO](https://blog.perp.fi/introducing-the-grants-program-and-grants-committee-e97f35f7864c) was introduced in [August 2021](https://gov.perp.fi/t/proposal-grants-program/495) and updated [September 2021](https://gov.perp.fi/t/proposal-grants-v2/550). The DAO was funded initially by [DAO vote](https://gov.perp.fi/t/proposal-unlocking-perp-tokens-for-growth/245#bounties-program-7), and a second round via the [Optimism community](https://gov.optimism.io/t/gf-phase-0-proposal-perpetual-protocol/201).

1. **Business solutions/integrations:** anything that utilizes Perp as a base layer (e.g., structured products).
2. **Tooling:** building out any tooling that may be helpful for either makers, traders or token holders.
3. **Marketing:** anything that focuses on explaining Perp and how it works, as well as getting the word out to the community. This can be anything from design to written content.

{% hint style="warning" %}
The Grants DAO is currently dormant, but proposals can still be submitted via the Partnership [form](https://forms.gle/BtSPgTfSVjmhE9Ax5).
{% endhint %}

Depending on the ask, proposals will have to either go through the Grants DAO (<$50K) or submit a public proposal through the governance forum (>$50K).

All grants are priced in USD and then paid out in PERP, using a 7-day TWAP price at the time of payout. For example, if we payout a milestone, then we take the USD amount / TWAP price and send out the required amount of PERP. We expect there also to be up-front payments to kick start grants, but this will be at the discretion of the committee.

### **Token Listing DAO**

The [Token Listing DAO](https://blog.perp.fi/fine-tuning-token-listings-the-creation-of-the-perpetual-protocol-token-listing-sub-dao-76d7d1d938e3), created in November 2021, was updated in [April 2023](https://gov.perp.fi/t/update-2023-token-listing-reboot/966) as an interim step to facilitate building in the bear market. With the launch of Perp v3, a new token listing mechanism will be developed and launched.

### **Community DAO (concept)**

Future community management should be handled by a Community DAO to decentralize community initiatives and build the Perpetual brand in areas such as marketing, localization, community moderation, and more.

Similar to other sub-DAOs, a committee would steer the direction and control the budget. This committee would be responsible for reviewing, evaluating and planning the execution of campaigns to increase the number of active traders and raise awareness about the Perp brand. Quarterly reviews would be used to gauge the effectiveness of these campaigns.

### **Treasury DAO (concept)**

Future Treasury management would be delegated to a sub-DAO whose members are elected periodically and given a mandate by token holders to manage the Perpetual DAO treasury and fund all other sub-DAOs. At some point in the future, the foundation team would transition into its own sub-DAO and receive funding from the Treasury DAO.

### Market Making Entity (MME)

Established in [April 2022](https://gov.perp.fi/t/proposal-market-making-entity/634), the Market Making Entity is an arms-length sub-DAO initially funded by the Perpetual DAO with a mandate to provide market making services for Perp products, such as the Perp v2 DEX.

The MME was allocated 20MM PERP and the allocation was completed as of Q1 2024.

### Security Entity (SE)

Established in [May 2023](https://gov.perp.fi/t/proposal-fund-ongoing-security/974/4), the Security Entity is a sub-DAO that is responsible for maintaining a high starndard of security in protocol development and operations. This includes

* Funding third party audits of production code
* Funding bug bounties
* Maintaining staff to perform internal audits of code and operations systems, manage bug bounty programs, etc.

## PERP as Governance Token <a href="#perp-as-a-governance-token" id="perp-as-a-governance-token"></a>

The PERP token is used by its holders to vote on governance proposals.

The [governance forum](#governance-forums) is the main place to propose and discuss new ideas as well as their pros and cons (such as new collateral types, new features, etc.). [Snapshot](https://vote.perp.fi/), a third party off-chain voting platform, is used for voting on governance proposals.

### **vePERP Vote Boosting**

The 1 token-1 vote model clearly has drawbacks, where voting power is concentrated in the hands of the few and majority rules is the default. To improve the governance process, we have transitioned to a [veToken model](https://mirror.xyz/0x071B76df4a05Fb162569930aB82d8d265Bb8A497/GzzvxvNFeTjH9au6cllJ_4ffshySn3M3iAmKe34sxdw) where token holders can lock PERP into vePERP for up to 52 weeks to boost their voting power. The longer the tokens are locked for, the greater the boost to voting power, similar to veCRV.

The amount of time tokens are locked into vePERP and the quantity of tokens held jointly determine voting power, reducing the likelihood of governance attacks (such as voting using borrowed tokens).

The vote boost can be approximated as follows:

**Voting power = PERP x 4 x 1/52 x remaining weeks locked**

*Note that this is an approximate as the voting boost decreases every block, not every week.*

## Governance Proposal Lifecycle <a href="#proposal-lifecycle" id="proposal-lifecycle"></a>

1. Gauge community sentiment for a potential proposal through our community channels on [Discord](https://discord.com/invite/Dq9mTmCaBb), [Telegram](https://t.me/perpetualprotocol) and/or [Twitter](https://twitter.com/perpprotocol).
2. Create an account at [gov.perp.fi](https://gov.perp.fi/) and submit a proposal (see proposal template here).
3. Proposals must be discussed for at least 7 days and generate meaningful discourse. Go to [this page](https://gov.perp.fi/c/proposals/10/none/l/latest) to check and discuss current proposals.
4. Author or (author’s delegate) must submit their web3 address to a forum mod to be added to the [Snapshot](https://vote.perp.fi/) account.
5. Author/author’s delegate creates a vote, to last 7 days.
6. Votes are subject to a minimum 10% quorum.
7. If the proposal passes the voting stage with majority support (>50% of the vote), then it will be accepted as actionable by the Core team.
8. Any vote that doesn’t pass or cannot reach the quorum will be rejected, and can restart at the proposal stage.

## Snapshot Voting <a href="#snapshot-voting" id="snapshot-voting"></a>

Snapshot voting calculates voting power based on the number of PERP/vePERP that you have locked up, and allows stakeholders to support proposals without any gas costs.

Follow the steps below to cast your vote:

1. Head over to <https://snapshot.org/#/vote-perp.eth>
2. Click on “Connect Wallet” and connect with an account that holds PERP/vePERP
3. Browse the active proposals
4. Select your preferred choice(s): for weighted voting, you can vote for more than one option.
5. Sign the message using your wallet and submit your vote.
6. Once the vote has enough support, the foundation team will implement the proposal.


# Roadmap

🗺️ Because everyone loves a roadmap!

| Date              | Milestone                                             | Status |
| ----------------- | ----------------------------------------------------- | :----: |
| Oct 2019          | Project founding                                      |    ✅   |
| Aug 2020          | Funding round                                         |    ✅   |
| Sept 2020         | PERP token LBP                                        |    ✅   |
| Dec 2020          | Perp v1 launch                                        |    ✅   |
| Nov 2021          | Perp v2 launch                                        |    ✅   |
| Jan 2023          | Hot Tub launch                                        |    ✅   |
| May '23 - Feb '24 | 🐻 market 🏗️ 🤫                                      |    ✅   |
| March 2024        | Perp v3 Sherlock Audit                                |    ✅   |
| April 2024        | Nekodex launch                                        |    ✅   |
| April 2024        | ERC-4337 Accounts                                     |    ✅   |
| Q2 2024           | Perp v3 Smart Maker                                   |   🏗️  |
| Q2 2024           | Perp v3 LP pools open                                 |   🔬   |
| Q2-Q3 2024        | Multi-collateral                                      |   🔬   |
| Q2-Q3 2024        | R\&D based on Perp v3 performance                     |   🔬   |
| Q2-Q3 2024        | Activate protocol fees and Lazy River 3.0 fee sharing |   🔬   |

## Perp Evolution

|              | Perp v1       | Perp v2       | Perp v3             |
| ------------ | ------------- | ------------- | ------------------- |
| Launch       | Dec 2020      | Nov 2021      | Mar 2024            |
| Chain        | xDai / Gnosis | Optimism      | Optimism            |
| Margining    | Isolated      | Cross-margin  | Isolated            |
| Collateral   | USDC          | Multi         | USDT\*              |
| Max leverage | 10x           | 10x           | 10-50x              |
| DEX type     | vAMM          | AMM w/ vToken | Multi-strategy      |
| LPs          | None          | Range orders  | Liquidity Framework |
| Account      | EOA/CA        | EOA/CA        | EOA/CA/SCW          |

\*Multi-collateral planned


# Official links

Website: <https://www.perp.com>\
DEX: <https://app.perp.com>\
Earn: <https://perp.com/earn>

## Products

Hot Tub: <https://vaults.perp.com> (arb vaults) \
Perps trading: <https://app.perp.com/markets> \
LP on Perp: <https://app.perp.com/pools> \
Pool Party: <https://rewards.perp.com/liquidity-mining> \
Lazy River: <https://token.perp.com> (RealYield™ staking)

## Socials

Twitter: <https://twitter.com/perpprotocol>\
Discord: <https://discord.perp.com>\
Debank: <https://debank.com/official/Perp_Protocol>\
Telegram (no price chat): [https://t.me/perpetualprotocol/](https://t.me/perpetualprotocol/106489)\
Telegram **price chat**: <https://t.me/perp_trading>\
Telegram Announcements: <https://t.me/perpprotocol>\
Blog:[ https://blog.perp.fi ](< https://blog.perp.fi >)\
Mirror: [https://perpprotocol.mirror.xyz](< https://perpprotocol.mirror.xyz>)\
Youtube: <https://www.youtube.com/c/perpetualprotocol>

## User Support

Discord: See `#open-a-ticket` channel\
Telegram support: <https://t.me/perpSupBot> (our team will reply via bot) \
dApp UI: Click blue button on lower right corner 🗪 \
User docs: <📍You are here>

## Docs & Tools User&#x20;

Docs: <https://support.perp.com>\
Governance: <https://gov.perp.fi>\
Dune dashboard: Coming Soon™️ 🏗️\
🌉 Bridges: <https://www.optimism.io/apps/bridges>

## $PERP Token & More&#x20;

$PERP info: [PERP Token](/nekodex-playground/all-about-perp/perp-token) \
$PERP stats: <https://dune.com/perpetual_protocol/perp-hodl>

⚠️ The following are 3rd party sites. \
Perpetual Protocol is not in control nor responsible for data shown on any 3rd party site. \
Coingecko: [https://www.coingecko.com/en/coins/perpetual-protocol ](<https://www.coingecko.com/en/coins/perpetual-protocol >)\
CMC: [https://coinmarketcap.com/currencies/perpetual-protocol ](<https://coinmarketcap.com/currencies/perpetual-protocol >)\
Binance: <https://www.binance.com/en/price/perpetual-protocol>

## Dev Resources

Testnet: Coming Soon™️ 🏗️ (open ticket to request tUSDT) \
Github: [https://github.com/perpetual-protocol ](<https://github.com/perpetual-protocol >)\
Subgraph: Coming Soon™️ 🏗️

## Jobs & Collaboration&#x20;

Submit your resume: [https://jobs.perp.fi/open-application ](<https://jobs.perp.fi/open-application >)\
Propose a partnership: <https://forms.gle/cWCiStVRELVpok6LA> \
Apply for a grant: <https://forms.gle/BtSPgTfSVjmhE9Ax5>


# FAQs

Don't see your question answered? [Contact us](/nekodex-playground/all-about-perp/contact-us)!

{% hint style="info" %}
These FAQs are for Perp v3. For older versions, see legacy docs for [v1](https://v1docs.perp.fi/) and [v2](https://support.perp.com/).
{% endhint %}

## Contents

[FAQs](/nekodex-playground/all-about-perp/faqs#about-perp)

[#trading-on-perp-v3](#trading-on-perp-v3 "mention")

[#perp-smart-account](#perp-smart-account "mention")

[#perp-token](#perp-token "mention")

## About Perp

### Where is the project based?&#x20;

Our team is located across several countries, but it was initially founded in Taiwan.

### Who do I contact for proposals (business, marketing, collaboration, listing)

Please see [Contact us](/nekodex-playground/all-about-perp/contact-us). Note that we do not do listing collaborations with centralized exchanges.

### How big is the team?

The team has roughly 15 full time and 2 part time members.

### Who is on the team?

We don't have a published list of team members but the co-founders and key team members are doxxed (e.g. have appeared in public, Youtube, etc.). See more in [About us](/nekodex-playground/all-about-perp/project-overview/about-us).

### Is there merch?

Yes! Please visit [https://shop.perp.fi](https://shop.perp.fi/)

## Trading on Perp v3

### How do I start trading?

Initially, Perp v3 will launch as an early access campaign called Nekodex. Read more: [Nekodex $(=ↀωↀ=)](/nekodex-playground)

### How do I deposit?

⚠️ **Do not deposit**

Perp v3 is currently in the Nekodex phase and *only* Nekocoin can be used to trade. Read more: [Nekodex $(=ↀωↀ=)](/nekodex-playground)

### I saw an error

Sorry about that! Please refresh (ctrl-F5) or Empty Cash & Hard Refresh (right-click Inspect, then right-click the browser refresh button 👇). If that doesn't work, [Contact us](/nekodex-playground/all-about-perp/contact-us) 🙏

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

### Error: Unable to get quote for this market

There are a few possible causes:

* Network connection is unreliable/slow for some reason
* Your device hardware is struggling (too many markets with open positions, or possibly too many apps running)
* The size of your trade is too big/small (it must be worth >10 USDT and < your available collateral)

### How do I set leverage?

Each market has a max leverage, according to the [Perp contract specs](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs).

<figure><img src="/files/3hugIwhXDxUsas62ebzP" alt=""><figcaption><p>Set yer leverage degens!</p></figcaption></figure>

### How does Perp v3 work?

Quick version [here](/nekodex-playground/docs-for-users/trade-perpetual-futures#quick-start) or long version [here](/nekodex-playground/docs-for-users/how-perp-v3-works).

Perp v3 is a Decentralized Exchange (DEX) built on the Optimism network that allows anyone to buy/long or sell/short various assets with up to 50x leverage. You can use the web UI or trade permissionlessly via smart contract. Perp v3 integrates multiple ways to provide liquidity with the goal of offering traders the best possible prices, and the freshest possible markets. Among various available methods, Perp v3 is starting with using oracle prices for trading major pairs like ETH and BTC, and an innovative spot-hedge LP mechanism for newly launched and lower volume markets. These liquidity strategies connect to a order router, ensuring a seamless trading experience for users.

### Has Perp v3 been audited?

Yes. Perp v3 was audited using a Sherlock campaign and has undergone extensive internal testing and audits.

### What are the trading fees?

A: See [Trade perpetual futures](/nekodex-playground/docs-for-users/trade-perpetual-futures#fees)

### Can I have multiple positions for one asset?

A: No, all positions for the same asset add together, so if you open a short and then a long, they will cancel out. For more see [Trade perpetual futures](/nekodex-playground/docs-for-users/trade-perpetual-futures#managing-your-position).

### Is there a dashboard / stats / metrics?

Coming Soon™️ 🏗️

### Why is \_\_\_ country blocked?

Due to regulatory realities and the way the internet works, we cannot offer the web UI in some countries. Make sure to follow your country's laws regarding crypto trading. Do not use VPN to circumvent our restrictions or your country's laws.

### Will there be a trading competition?

Yes! Using the Nekodex early access platform, there will be ongoing competitions. Make sure to join our [Discord](/nekodex-playground/all-about-perp/contact-us) for the latest news.

### Where does liquidity come from?

*Note:* Initially LPing is limited to whitelisted accounts

Liquidity for trades is provided in different ways depending on the underlying strategy. Our goal is to remove liquidity as a concern for most traders: the Perp v3 router will chose the best liquidity source and execute the trade for you. That said, the initial two liquidity strategies provide liquidity as follows.

* For oracle price trades, each market has a liquidity pool, and trades will be made with the pool according to current oracle prices.&#x20;
* For spot-hedge trades, each market will have a spot vault similar to Hot Tub, where trades made on Perp v3 are hedged atomically with trades made between the vault and the associated spot market.

### How can I provide liquidity?

Initially LPing is limited to whitelisted market makers to ensure system stability. Pools will be opened to all market participants SoonTM, starting with oracle pools with spot-hedge pools opening next.

### What chain will Perp v3 launch on?

Perp v3 will be on [Optimism](https://optimism.io/).

### Where is the API?

Please see [API](/nekodex-playground/docs-for-devs/api)

## Perp Smart Account

Please see the Smart Account [Perp Smart Account](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-smart-account#faq)

## PERP Token

For more info, see [PERP Token](/nekodex-playground/all-about-perp/perp-token)

### What is the circulating supply?

This varies depending on how you define the circulating supply. Please see [#perp-token](#perp-token "mention") for more. The main difference in calculation methods is whether PERP locked as vePERP are counted as circulating. See various sites like Coingecko or CoinMarketCap, the team tokenomics [Dune dashboard](https://dune.com/perpetual_protocol/perp-hodl), or the Perpetual DAO [locked wallet](https://etherscan.io/address/0xc49f76a596d6200e4f08f8931d15b69dd1f8033e).

### What is the vesting schedule?

There are two categories of vested tokens, and all have been unlocked.&#x20;

* Investor tokens finished unlocking in Dec 2021.&#x20;
* Team tokens finished unlocking in Sept 2023.&#x20;

Team tokens are issued to team members on a monthly basis. Less than 10% of the team token allocation has been issued to team members.


# PERP Token

{% hint style="info" %}
**tl;dr**

PERP token vesting & unlocks are 100% complete as of Sept. 2023. See also [#circulating-supply](#circulating-supply "mention").
{% endhint %}

## Staking

For PERP staking see [Earn yield](/nekodex-playground/docs-for-users/earn-yield#staking)

## Contract addresses

```solidity
Ethereum: 0xbc396689893d065f41bc2c6ecbee5e0085233447
Optimism: 0x9e1028f5f1d5ede59748ffcee5532509976840e0

// ⚠️ Other chains may have low/no liquidity
BNB: 0x9e1028f5f1d5ede59748ffcee5532509976840e0
Gnosis: 0x7ecF26cd9A36990b8ea477853663092333f59979
Arbitrum: 0x753d224bcf9aafacd81558c32341416df61d3dac
```

## Tokenomics

{% hint style="info" %}
Any additional mint or unlock of PERP tokens **must** first pass a [Governance](/nekodex-playground/all-about-perp/project-overview/governance) vote
{% endhint %}

Total supply: 150MM PERP

### Circulating supply

Circulating supply changes depending on how you define it.

* The Perpetual DAO [locked wallet](https://etherscan.io/address/0xc49f76a596d6200e4f08f8931d15b69dd1f8033e) contains all locked PERP held by the Perpetual DAO. These tokens can only be unlocked via DAO governance vote. The most conservative view would be all tokens not in the DAO locked wallet are 'circulating'.
* The [Dune](https://dune.com/perpetual_protocol/perp-hodl) dashboard maintained by the Perp Foundation team does not include PERP locked in the [vePERP vault](https://optimistic.etherscan.io/address/0xd360b73b19fb20ac874633553fb1007e9fcb2b78) in the circulating supply.
* Lastly, most token tracking sites like Coingecko use their own methods but generally consider PERP locked in vePERP as part of the circulating supply. See [#id-3rd-party-token-stats](#id-3rd-party-token-stats "mention") below.

## Allocations & Vesting

{% tabs %}
{% tab title="Token LBP (TGE)" %}

#### Allocation: 5%

#### Status: Complete as of Sept 2020

A Balancer liquidity bootstrapping pool was launched in Sept 2020 and seeded with 5% of the token supply.

#### Balancer pool

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

A Balancer pool was seeded with PERP rewards to inventivize liquidity.
{% endtab %}

{% tab title="Perp DAO" %}

#### Allocation: 54.8% (Ecosystem & Rewards)

#### Status: Ongoing

This allocation is managed by the Perpetual DAO as a treasury pool. The main purpose of the treasury is for ecosystem and rewards, but may extend to any purpose voted on by the Perpetual DAO.

🗳️ All unlocks and deployments of DAO tokens are subject to DAO governance vote.

#### Current allocations

* 21 million PERP for rewards, grants, and bootstrapping ([link](https://gov.perp.fi/t/proposal-unlocking-perp-tokens-for-growth/245))
* 20 million PERP to establish an arms-length Market Making Entity ([link](https://gov.perp.fi/t/proposal-market-making-entity/634))
* 5 million PERP to establish a Security Entity handling audits & bounties ([link](https://gov.perp.fi/t/proposal-fund-ongoing-security/974))
* Small amounts for community building ([link1](https://gov.perp.fi/t/perpvangelist-funding-proposal/923), [link2](https://gov.perp.fi/t/proposal-funding-for-perp-user-support/973))

#### Proposals

Past proposals: See [gov.perp.fi](https://gov.perp.fi/) and [vote.perp.fi](https://vote.perp.fi/) for past proposals.

Future proposals: See the [#governance](https://discord.com/channels/687397941383659579/1216985506252849162) channel on Discord.
{% endtab %}

{% tab title="Investors" %}

#### Allocation: 19.2%

#### Status: Complete as of Dec 2021

Quarterly investor issuance began in Dec 2020 and completed Dec 2021.

* Q4 2020 - [link](https://etherscan.io/token/0xbc396689893d065f41bc2c6ecbee5e0085233447?a=0xc49f76a596d6200e4f08f8931d15b69dd1f8033e) (see Dec 21, 2020 to March 3, 2021)
* Q1 2021 - [link](https://etherscan.io/tx/0x94dd567f2384e135e488f7afc8e4eb4417516e1d3c056fd7536249a8ce8c2de2)
* Q2 2021 - [link](https://etherscan.io/tx/0xacf6afc7f3a9b563f6cfbcefb26cdefd6e49999d05c7f8320cec71c1dcc33f5b)
* Q3 2021 - [link](https://etherscan.io/tx/0x858f247d481faa50e9bf3e3039d2f6a29dbbc3f27cb4679ea83eefe2dae8853b)
* Q4 2021 - [link](https://etherscan.io/tx/0x6750251f32c5b2220f9a132f5ad7b2ba2cc79b6678e1f2599d6c4b0c2f538374)

#### Key investors

|                            |                                |
| -------------------------- | ------------------------------ |
| Zee Prime Capital          | Binance Labs                   |
| Multicoin Capital          | Mechanism Labs                 |
| Divergence Ventures        | CMS Holdings, LLC              |
| \[Former] Alameda Research | \[Former] Three Arrows Capital |
| {% endtab %}               |                                |

{% tab title="Team Token" %}

#### Allocation: 21%

#### Status: Complete as of Dec 2023

Team issuance was 2.1MM PERP/quarter starting June 2021 and completed in Dec 2023.

Approximately 90% of team token remains in the team treasury, with around 10% being progressively vested to current team members on a monthly basis.
{% endtab %}
{% endtabs %}

### Distribution chart

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

## 3rd Party Token Stats

{% hint style="warning" %}

* 3rd party tools may be inaccurate

* Data may be out of date

* 3rd parties use their own definitions, methods and data sources for calculation of circulating supply, market cap and other metrics.
  {% endhint %}

* Coingecko <https://www.coingecko.com/en/coins/perpetual-protocol>

* CoinMarketCap <https://coinmarketcap.com/currencies/perpetual-protocol/>

* Live Coin Watch <https://www.livecoinwatch.com/price/PerpetualProtocol-PERP>

* Birdeye [Optimism](https://birdeye.so/token/0x9e1028F5F1D5eDE59748FFceE5532509976840E0?chain=optimism) [Ethereum](https://birdeye.so/token/0xbC396689893D065F41bc2C6EcbeE5e0085233447?chain=ethereum)

* Token Terminal <https://tokenterminal.com/terminal/projects/perpetual-protocol>

* Binance <https://www.binance.com/en/price/perpetual-protocol>

* OKX <https://www.okx.com/price/perpetual-protocol-perp>

* Coinbase <https://www.coinbase.com/price/perpetual-protocol>


# Contact us

We love hearing from users!

## Discord (best choice)

The Perpetual Protocol team hangs out on Discord most of the time!

Join us: <https://discord.perp.fi/>

### Other options

Telegram: [https://t.me/perpetualprotocol/](https://t.me/perpetualprotocol/1)

Twitter: <https://twitter.com/perpprotocol>

Debank: <https://debank.com/official/Perp_Protocol>

## Partnerships & Collaboration

All such requests should be made via these forms:

Propose a partnership: [https://forms.gle/cWCiStVRELVpok6LA ](<https://forms.gle/cWCiStVRELVpok6LA >)

Apply for a grant: <https://forms.gle/BtSPgTfSVjmhE9Ax5>

## Marketing

Come chat with us on Discord or email us at <marketing@perp.com>

## Careers

View open positions: <https://jobs.perp.fi/> (no positions currently, sorry!)

Submit your resume: <https://jobs.perp.fi/open-application>


# More

Find more info about the project here. Don't see the thing you're looking for? Contact us!

{% content-ref url="/pages/j1fHffH7CuzZFQT5T1Cg" %}
[Contact us](/nekodex-playground/all-about-perp/contact-us)
{% endcontent-ref %}

{% content-ref url="/pages/wmDyWz6fbcolbqDwpDJY" %}
[Security & Audits](/nekodex-playground/all-about-perp/more/security-and-audits)
{% endcontent-ref %}

{% content-ref url="/pages/jsmuZNleOwLS1hy8mwNw" %}
[Partnerships](/nekodex-playground/all-about-perp/more/partnerships)
{% endcontent-ref %}

{% content-ref url="/pages/ls73h1vkLpQV871bQ679" %}
[Careers](/nekodex-playground/all-about-perp/more/careers)
{% endcontent-ref %}

{% content-ref url="/pages/tiHPJSnGyXOjf6gFxlfo" %}
[Marketing](/nekodex-playground/all-about-perp/more/marketing)
{% endcontent-ref %}


# Security & Audits

## Overview

The security and safety of our users' funds is our highest priority.

Perpetual Protocol is one of the most lindy teams in Defi, with our first DEX launched in Dec 2020. The team has been doxxed from day one, and both cofounders are known in the local Taiwanese startup scene.

Code audits have been carried out on a rolling basis since the second half of 2020, and continue to this day for each point release.

## Audits

Audits of Perp v3 were performed in collaboration with Sherlock.

## Bug Bounty

We run bug bounties via ImmuneFi, and also welcome whitehats to contact us directly for any bug that is out of scope or if you have any other suggestions or concerns.

ImmuneFi: <https://immunefi.com/bounty/perpetual/>

Direct contact: [Contact us](/nekodex-playground/all-about-perp/contact-us)

## DAO Security Entity

A DAO entity was set up in in May, 2023, to handle all aspects of protocol security and ensure stable funding for audits, bounties and other security efforts. Please see [Governance](/nekodex-playground/all-about-perp/project-overview/governance#security-entity-se).


# Partnerships

## Overview

We have partnered with many fellow Defi projects over the years and look forward to partnering with many more! WAGMI 🫂

{% hint style="warning" %}
**CEX Token Listings**

We do not work with centralized exchanges on token listings. Please feel free to list the PERP token if you believe it benefits your users.
{% endhint %}

## Proposals

There are 3 ways to start partnering with us.

1. Complete this form: <https://forms.gle/BtSPgTfSVjmhE9Ax5>
2. Chat with us on [Discord](/nekodex-playground/all-about-perp/contact-us) (please use the Collaboration channel 🙏)
3. Post a proposal in the [Governance](/nekodex-playground/all-about-perp/project-overview/governance#governance-forum) (Note: this method is much more involved and is suited mostly to proposals that will require DAO funds)


# Careers

Please see [Contact us](/nekodex-playground/all-about-perp/contact-us#careers)


# Marketing

The Perpetual Protocol team carries out marketing campaigns of many kinds.

If you would like to propose a marketing campaign or marketing collaboration of some kind, please get in touch:

* Pitch your idea in [Discord](https://discord.com/channels/687397941383659579/889390817217773569)
* Directly send your pitch via this [form](https://forms.gle/cWCiStVRELVpok6LA)


# Legacy Docs

[Perp v2](https://support.perp.com/)

[Perp v1](https://v3docs.perp.com/perp-v1/)


# Earn yield

Get a complete overview of Earn products at <https://perp.com/earn>

## Hot Tub

Launched in early 2023, Hot Tub lets you earn arbitrage income using automated on-chain vaults.

Simply choose your asset, deposit, and relax. The automated vaults take advantage of price variations between the Perp DEX and onchain spot markets, all in a trustless, decentralized way.

Start earning now at <https://vaults.perp.com/>

## Staking

{% hint style="warning" %}
Staking is currently connected to Perp v2 and does not recieve fees from Perp v3. For now we suggest looking at Hot Tub options above for better yield short term.
{% endhint %}

The classic way to earn yield.&#x20;

Lock PERP tokens in Lazy River, Perpetual Protocol's staking system, to earn a share of protocol revenue.

Lazy River uses the ve system pioneered by Curve (with max 1 year lock):&#x20;

* If you lock 1 PERP for up to 52 weeks (1 year) you will have 1 vePERP. Rewards are distributed based on how much vePERP you hold relative to the pool.&#x20;
* Your amount of vePERP decays as time passes, so that at 26 weeks 1 PERP = 0.5 vePERP, at 13 weeks 1 PERP = 0.25 vePERP, etc.
* You cannot unlock staked PERP early.
* Staking is only available on Optimism.

For more info and to stake PERP, visit [https://token.perp.com](https://token.perp.com/)


# Trade perpetual futures

{% hint style="info" %}
This is a guide to trading on Perp v3. For older versions, see [Legacy Docs](/nekodex-playground/all-about-perp/more/legacy-docs).
{% endhint %}

{% hint style="info" %}
**Pre-launch Campaign**

Perp v3 is being promoted via Nekodex. Check it out: [Nekodex $(=ↀωↀ=)](/nekodex-playground)
{% endhint %}

## For new users

Perpetual Contracts, aka perps, are a simple tool that let you trade assets that might otherwise be hard to access for you. For example, if your funds are on Ethereum or similar network, it's not easy to trade assets from other networks, like SOL, or real world assets, like currencies or commodities. Perps provide an easy way to trade these assets.

At the same time, perps let you trade both long and short, and with leverage, making them a powerful tool indeed.

Perpetual Protocol is working hard to make trading in this way as easy and accessible as possible.

## Quick start

Currently Perp v3 is being tested and promoted via a campaign know as Nekodex. Check it out at [Nekodex $(=ↀωↀ=)](/nekodex-playground)!

{% hint style="danger" %}
**Account creation**

Perp v3 uses Ethereum account abstraction (aka ERC-4337). This account is tied to an email address. You can use any email, but it is critical that you are able to continue receiving email at this address in order to sign in.&#x20;

⚠️ Do not use a disposable or temporary email address.
{% endhint %}

{% hint style="warning" %}
If you are not familiar with the following terms, we highly recommend that you learn the basics of perpetuals trading and web3 before proceeding!

* long position / short position
* leverage
* funding rate / funding payment
  {% endhint %}

## Funding your account

Perp ve uses Perp Smart Account, one of the first DEXs to use Ethereum-based account abstraction. Perp Smart Account can be controlled using a Passkey, or using a web3 wallet. Passkeys are created and stored using an iOS or Android device. Learn more in [Perp Smart Account](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-smart-account).

Read on to set up an [#account-using-passkey](#account-using-passkey "mention") or an [#account-using-web3-wallet](#account-using-web3-wallet "mention")

### Account using a Passkey

If you have used Passkey on your phone before, simply follow the steps in the Perp v3 interface to create a Perp Smart Account. For a detailed how-to, see [Perp Smart Account](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-smart-account).

<figure><img src="/files/80YNwP4MEgxbrGjK8h3C" alt=""><figcaption><p>👇</p></figcaption></figure>

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

### Account using a web3 wallet

**You have a wallet**\
Click Sign Up and then connect a wallet like Metamask, Rabby or WalletConnect enabled wallet. Sign the message to create your account. You will need to sign to sign up and withdraw, but other operations will be handled using your session key. Learn more in [Perp Smart Account](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-smart-account).&#x20;

**You don't have a wallet**\
We recommend using Passkey if you don't have a wallet. If you prefer using a web3 wallets, there are many options including Metamask, Rabby and others. Make sure to read about and research web3 wallets before choosing one. You are trusting your funds with the wallet provider, and will likely need to manage backups and secret recovery phrase on your own. In most cases if you lose your wallet and your secret recovery phrase, or your secret phrase is stolen / revealed to a 3rd party, your funds will be **lost permanently**.

### Account address

Your Perp Smart Account can be found via the user interface:

<figure><img src="/files/cHNidRhLxDf4mLlJRN1V" alt=""><figcaption><p>👇</p></figcaption></figure>

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

You will need to deposit funds into this address in order to start trading.

### Bridge & deposit

{% hint style="warning" %}
**Test before depositing**

It is recommended to perform a small test deposit and withdrawal before depositing more funds.
{% endhint %}

1. Bridge funds
   1. You need ETH on Optimism to pay for transaction fees (aka gas). Don't worry, most transactions on Perpetual Protocol do not need gas, just a signature.
   2. You need USDT for collateral. Collateral will back all of your trades. For now, USDT is the collateral used on Perp v3, and more options will be added soon.
   3. See bridge options at the [Optimism Bridge](https://app.optimism.io/bridge/deposit) or see [Optimism Apps](https://www.optimism.io/apps) for 3rd party bridges and on-ramps.
2. Use the deposit function on the UI to deposit funds from your web3 wallet to your Perp v3 exchange wallet.
3. All trades will be backed with funds in your account. Fees, P\&L, funding payments, etc., will be paid to/from your account.

## Perpetual Protocol Smart Account

{% hint style="warning" %}
**Test before depositing**

It is highly recommended to perform a small test deposit and withdrawal before depositing more funds.
{% endhint %}

#### Key benefits

* Trade without signing every transaction
* Gas is payed for you ⛽👌
* Recover your account easily

Smart Account allows you can use your email or other login method to create and manage an account on Perpetual Protocol. Simply go to app.perp.com and follow the steps to sign up with the social or email account of your choice, or use your existing web3 wallet.

Read more at [Perp Smart Account](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-smart-account)

## Opening a position

{% hint style="info" %}
You can only have one position in each asset. If you have a position and buy/long or sell/short the same asset, the new position will be added to the old position. E.g. if you have a 1 ETH long and open a 1 ETH short, the two positions will cancel each other and sum to 0.
{% endhint %}

Once your account has funds deposited, you can open long and short positions in any asset offered on the exchange interface.

All transactions on Perp v3 are gas-less thanks to our built-in relayer system. All you need to do is confirm the order with two clicks and transaction fees will be paid via the relayer.

## Order types

{% tabs %}
{% tab title="Market orders" %}

### **Market order**

Price impact: Orders do not have price impact in the sense that the price moves due to the order consuming an amount of liquidity. Prices are determined by the underlying liquidity framework module.

Place your order using the current market price. Orders are fill-or-kill (there are no partial fills for market orders; limit orders support partial fills).

#### Slippage

Orders may experience slippage, where the expected execution price is different from the actual execution price due to a change in price between the time the transaction is sent and the time it is executed. You can control slippage using the Max Slippage setting. Max Slippage of 0.1% or 0.5% is reasonable. It is very rare to need a value above 0.5%.

<figure><img src="/files/DolQjlcifFssG0oXQBGD" alt=""><figcaption></figcaption></figure>
{% endtab %}

{% tab title="Limit orders" %}

### **Limit order**

Place your order at a price you set or better. ⚠️ This means if you set a long price below the current market price, the order will fill right away. The same is true if you set a short price above the current market price.

{% hint style="info" %}
Sufficient collateral is required for any limit order, even if the order closes an existing position (e.g. a short limit order that closes a long position). This will be updated once take-profit and stop-loss orders are launched.
{% endhint %}

#### Minimum order size

10 USDT

#### Partial fills

Limit orders allow partial fills if there is insufficient liquidity to fill your entire order at your set price.

#### Slippage

See the Market Order tab above.

#### Fees

Limit orders pay the standard relayer fee one time per order, at the time of the first fill.

Once filled, limit orders pay applicable borrowing fees and funding fees at the same rate as a market order.

#### Collateral requirements

Each limit order requires a certain amount of funds in your futures account to be available when the limit order triggers. If you remove funds or your futures account balance falls below the level needed to fill the orders, some or all of your orders may be automatically cancelled.
{% endtab %}

{% tab title="Take-Profit/Stop-Loss" %}
Take Profit & Stop-Loss orders will be available at a later date.
{% endtab %}
{% endtabs %}

## Leverage

{% hint style="info" %}
Perp v3 uses isolated margin. This means each position has it's own margin, leverage and liquidation price.
{% endhint %}

Set leverage using the leverage panel (initially shows as a 2x button). The max leverage may be different for each asset.

<figure><img src="/files/vOGCJhdppLOnMFdzbTZY" alt=""><figcaption><p>👇</p></figcaption></figure>

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

Each asset has its own leverage setting, so make sure to check the leverage before trading.

## Position size

Enter the position size of your order in either collateral token (USDT) or the asset (base token, ETH, BTC, etc.)

To set the size in the asset token, toggle the size unit by clicking the collateral token symbol (USDT).

<figure><img src="/files/kAXJyWWZeP5omrNPEZA3" alt=""><figcaption><p>👇</p></figcaption></figure>

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

## Fees

The UI will show estimated fees for you, and show fees in the transaction summary before you sign your order. If you'd like to understand Perp v3 better, read on.

#### Borrowing fees

Traders (takers) pay borrowing fees for all positions, similar to when you borrow using Defi lending protocols. This fee is paid continuously on a percent basis depending on how much of the available liquidity is used, and is paid to liquidity providers.

#### Matcher fee

Current fee: 1 USDT (flat fee)

Similar to other designs like Synthetix and GMX, for each transaction you'll pay a fixed matcher fee to cover gas fees paid on your behalf by the matching engine. You won't need to pay separately for gas for trades on Perp v3.

In the future, matcher fees may change to become based on current trading volume.

#### Funding payments

At launch, funding payments will be turned off. Funding payments may be applicable in the future, depending on the liquidity provision mechanism.

## Collateral and margin ratio

{% hint style="info" %}
**tl;dr**

Margining type: isolated margin

Maintenance margin: see [Perp contract specs](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs)

Max leverage: see [Perp contract specs](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs)
{% endhint %}

Perp v3 uses isolated margin: all positions on Perp v3 have their own independent margin. When your collateral (funds you deposited in your Perp v3 account) are used to back a position, this backing is called position margin, or simply margin.

Isolated margin allows us to offer higher leverage, and helps both users and the protocol manage risk. Cross-margin is possible with Perp v3's modular design and may be added at a later date.

The value of your position vs the value of the position margin determines the amount of leverage of each position. If `position margin = position value` then your leverage is 1x.

A key indicator to watch is **margin ratio**. This shows your margin value as a percentage of your position value. If the margin value falls too low, margin ratio will fall, and you risk [liquidation](#account-health-and-liquidation).&#x20;

## Managing your position

**Multiple positions**\
You can only have one position for each asset. If you open a second position for an asset, it will be added to the first. So two longs will add together to create a bigger long, or a long and a short will add together and result in a smaller position or cancel out entirely.

**Close position**\
Click the Close Position button next to the position you want to close in order to close it completely.

**Reduce (partial close)**\
To close part of a position, make an opposite direction trade. Ie. if you want to close part of a long, open a new short (e.g. close half of a 1 ETH long position by opening a 0.5 ETH short position.)

**Increase leverage (reduce margin)**\
Remove margin from your position if you want to increase your leverage for that position. \
ℹ️ You are limited in how much margin can be removed from a profitable position. You cannot remove more than your initial margin. To remove more, you must reduce your position size.

**Decrease leverage (increase margin)**\
Add margin to your position if you want to decrease your leverage for that position.

## Leverage

{% hint style="danger" %}
**Warning**

Leverage trading can lead to complete loss of funds. Use low leverage (2x-3x).

Actively monitor all leveraged positions and trade with caution.

Never trade more than you can afford to lose.
{% endhint %}

Always actively monitor your positions when trading with leverage. If your position value is higher than your margin value (ie. margin ratio is less than 100%), you are trading with leverage!

[**Contract specs**](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs): Familiarize yourself with the perpetual contract specs before trading. Ensure you are aware of the assets' max leverage and maintenance margin to avoid liquidation.

Coming Soon™️ 🏗️ (will add details based on UI)

## Account health and liquidation

{% hint style="warning" %}
**Caution**

Liquidation will lead to partial or complete loss of funds.
{% endhint %}

#### **Liquidation**

If your margin ratio falls below the maintenance margin ratio (MMR) for the asset you are trading ([ref](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs)) you may be liquidated. During liquidation, your position will be closed or reduced in size, and some or all of your margin will be taken as a penalty and paid to the liquidator.

Liquidations are triggered by liquidators who call the DEX smart contracts when a position is detected with a margin ratio below the required level. The smart contracts evaluate the position's state, and if the conditions for liquidation are met, the position will be liquidated.

#### Partial liquidation

Positions will be partly liquidated (50% per liquidation) if they meet certain conditions:

* Position margin is 100 USDT or more\
  and
* Margin ratio is half the maintenance margin ratio (MMR) or higher (if MMR is 5%, the position must have a margin ratio between 5% and 2.5% to be eligible for partial liquidation).

If any conditions is not met, the position will be fully liquidated when margin ratio falls below MMR.

#### **Liquidators**

Anyone can act as a liquidator on Perpetual Protocol by triggering liquidations via the exchange smart contracts. Liquidators receive a bonus, paid by the trader as a penalty, in return for monitoring the system and triggering liquidations when necessary. This is a technical task that requires liquidators to write and maintain software to monitor user positions and trigger the exchange contracts at the correct time.

## Profit and Loss

P\&L is divided into three types. If you have further questions about unclaimable P\&L, please see [How Perp v3 works](/nekodex-playground/docs-for-users/how-perp-v3-works#p-and-l-pool) for details or [Contact us](/nekodex-playground/all-about-perp/contact-us).

| Type                        | Notes                                                                                                                                                                                         |
| --------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Unrealized P\&L             | P\&L in open positions is 'unrealized' and continues to change as price changes.                                                                                                              |
| Realized + Claimable P\&L   | When a position is closed, its final P\&L is locked in, resulting in a realized profit or loss. Normally this can be claimed automatically or by going to Account and checking P\&L balances. |
| Realized + Unclaimable P\&L | In some cases a temporary hold is place on profits to ensure protocol solvency and guard against attacks and exploits. These funds are safe.                                                  |

## Withdrawing funds

Go to the account overview to withdraw funds back to your wallet.

If you have open positions, you will not be able to withdraw funds. Close all of your positions if you want to withdraw all funds.

Some funds may also be in the form of claimable or unclaimable P\&L (see [#profit-and-loss](#profit-and-loss "mention")).

## Rug protection

When LPs' funds are used in trades, these funds are locked. This ensures traders can always exit their positions as well as ensuring protocol solvency.


# Fees & system limits

## Fees

| Action                           | Protocol Fee                                                                                   | Gas (network fee)                                                            |
| -------------------------------- | ---------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------- |
| Deposit                          | 0                                                                                              | User pays (if applicable)                                                    |
| Transfer to/from futures account | 0                                                                                              | Subsidized                                                                   |
| Open position                    | <ol><li>Relay fee: 0.20 USDT</li><li>Borrowing fee: variable</li></ol>                         | Relayer pays                                                                 |
| Increase/decrease position size  | Relay fee: 0.10 USDT                                                                           | Relayer pays                                                                 |
| Create limit order               | <ol><li>Relay fee: 0.10 USDT<br>(paid when order triggers)</li><li>2nd fill, etc.: 0</li></ol> | <ol><li>Order creation: No fee</li><li>Order trigger: Relayer pays</li></ol> |
| Add/remove margin                | 0                                                                                              | Subsidized                                                                   |
| Close position                   | Relay fee: 0                                                                                   | Subsidized                                                                   |
| Cancel limit order               | 0                                                                                              | Subsidized                                                                   |
| Withdraw                         | 0                                                                                              | Subsidized                                                                   |

## Limitations

#### Deposit limit

None

#### Withdrawal

WIP 25% of TVL per 4 hour period

#### Max position size

Limited by liquidity


# Perp Smart Account

Perp v3 uses a Smart Account system based on account abstraction, aka ERC-4337. Perpetual Protocol Smart Account is powered by [ZeroDev](https://zerodev.app/).

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

## tl;dr

Perp Smart Account makes crypto trading so much easier.

* Sign up without needing a wallet
* No wallet credentials to store or backup
* Trade without signing (just tap and confirm)
* No separate network (gas) fees
* All funds are 100% onchain and in your control (non-custodial)

Smart Accounts are created using an email, and an authentication method: Passkey or a web3 wallet. Each Smart Account has its own address (starting with 0x). You cannot use an exising address for the Smart Account.

To log in and perform critical operations (e.g. withdraw) you will need the same email and Passkey/web3 wallet that you used when creating the account.

## Benefits

* User experience
  * Sign up and start trading in seconds - no wallet or complex registration needed
  * Trade with 2 clicks - only sign-up/withdrawal requires your Passkey signature
* Security
  * Wallet credentials (e.g. seed words) are stored securely, protecting you from loss or mistakes
  * Easy account recovery using your [#passkey](#passkey "mention")
  * Easy account migration without exporting/handling private keys
* Leading edge tech
  * Fully client-side solution puts the you in complete control of your wallet
  * Industry-leading implementation from ZeroDev

{% hint style="info" %}
**🤔 Is this even web3 bro?**

Good question. Everyone defines web3 a little differently, but if your definition includes the following

* Non-custodial / not your keys, not your coins
* Permissionless
* Open, public blockchain
* No lock-in / easy migration

then yes, this is web3.

Perp Smart Account uses ERC-4337 account abstraction to create user accounts, leveraging the Kernel wallet from ZeroDev for the implementation. If you have more questions about what all of this means, welcome to [Contact us](/nekodex-playground/all-about-perp/contact-us)!
{% endhint %}

## Signup

{% hint style="warning" %}
Nekodex only supports Passkey signup. We want to encourage users to try this new user-friendly option for securing your crypto account.
{% endhint %}

First enter an email address to create an account, then link it to a Passkey or Web3 wallet. The key or wallet will be used to authenticate you and sign for critical operations like sign-up and withdrawals.

{% hint style="info" %}
**Passkey requirements**

🍎 Passkeys are available for all iPhones and iPads from iOS 16 onward.

🤖 Passkeys are available for most Android phones from Android 9\* onward.

Some manufacturers have not added Passkey so be sure to check your device. \*Higher versions of Android may be required for 3rd party applications like Proton Pass.
{% endhint %}

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

## Session keys <a href="#session-keys" id="session-keys"></a>

ZeroDev's session keys implementation opens the door to a faster, smoother trading experience onchain. A session key is created using your Passkey. The session key lets you  perform low-risk operations like opening and closing trades without having to authenticate again using your Passkey.

#### More benefits

* Using session keys instead of the private-key-backed Passkey means less exposure for the private key.
* Session keys allow easy management of what operations are permitted, and what operations require full Passkey authentication.
* Substantial gas savings compared to verifying Passkey signatures for onchain operations.

## Passkey

[Passkeys](https://docs.zerodev.app/sdk/plugins/passkeys#passkeys) (FIDO credential) are a standard for managing passwords, login credentials and more, using a Passkey-enabled hardware device like your iPhone or Android smartphone.

{% hint style="danger" %}

1. Passkeys on your computer may be difficult or impossible to back up. We do not recommend users to store Passkeys this way unless you know what you are doing. If your Passkey is lost, you will **permanently lose access** to your funds. ☠️
2. Perp Smart Account does not currently support Linux. If you use Linux, please sign in using your phone or a [#web3-wallet](#web3-wallet "mention").
   {% endhint %}

When creating your Perp Smart Account or logging into an existing Smart Account, you can use your device's Passkey for authentication.

Check with your phone manufacturer for information about setting up and using Passkeys on your phone.

* Android: <https://support.google.com/chrome/answer/13168025>
* iOS: <https://support.apple.com/guide/iphone/use-passkeys-to-sign-in-to-apps-and-websites-iphf538ea8d0/ios>

#### Backups

It is important to backup your Passkey in order to maintain access to your Perp Smart Account if your device is lost or broken.

From the ZeroDev docs:

<https://docs.zerodev.app/sdk/plugins/passkeys#how-are-passkeys-sync-ed-and-recovered>

> Synchronization and recovery are both supported natively by Apple and Google:
>
> * With Apple, Passkeys created on one device are synced through iCloud [Keychain](https://support.apple.com/en-us/109016) as long as the user is logged in with their Apple ID. Apple covers both syncing and recovery in "[About the security of passkeys](https://support.apple.com/en-us/102195)". For some additional detail, see this [Q\&A with the passkey team](https://developer.apple.com/news/?id=21mnmxow). Apple's account recovery process is documented in this [support page](https://support.apple.com/en-us/HT204921).
> * With Google, [Google Password Manager](https://passwords.google/) syncs passkeys across devices seamlessly. Google has plans to support syncing more broadly across different operating systems, see this [support summary](https://developers.google.com/identity/passkeys/supported-environments#chrome-passkey-support-summary). Recovery is covered in this FAQ ("[What happens if a user loses their device?](https://developers.google.com/identity/passkeys/faq#what_happens_if_a_user_loses_their_device)"): it relies on Google's overall [account recovery process](https://support.google.com/accounts/answer/7682439?hl=en) because passkeys are attached to Google accounts.

## web3 wallet

If you don't want to use Passkey or do not have access to one, you can use a good old fashioned web3 wallet like a proper OG.

Connect your wallet, e.g. Metamask, and sign the `ValidatorApproved` message to set up your account abstraction wallet. You can verify you are signing the message from this contract:

```
0x884bc49b4af83f77bfce93df4d38c7fd2f916c76
```

This will set up your Perp Smart Account which is ready to be funded and used for trading. You won't need to sign for most operations, which will be controlled using your session key. Critical operations like sign-up & withdrawal will requires a signature from your web3 wallet to re-authenticate you.

## FAQ / Troubleshooting

{% tabs %}
{% tab title="General" %}

* Passkeys are linked to an email and a service like a website (e.g. nekodex.org). Make sure to use the Passkey linked to the email you used to sign up to Nekodex.
* Passkeys are created on one device. If you use a phone and backup the phone using iCloud or Google One, the Passkeys should migrate to the new phone.
* Make sure to use the same device to log in, or migrate as mentioned above. You won't be able to log in using a different Passkey.
* One device can create multiple Passkeys so when you log in, make sure to choose the Passkey you used to create your Nekodex account.
  {% endtab %}

{% tab title="Android" %}

* Google Authenticator App: make sure you have it installed and up to date.
* Bluetooth must be turned on and wifi/mobile data connected.
* Passkeys are saved in your Google account. If you have more than one account, make sure to save the Passkey in the account you want to use.
* If you have many Passkeys, make sure to choose the one linked to your Nekodex account.
* **No Passkeys Available Error**
  * Make sure you have Google Authenticator installed.
  * On your phone, go to Settings > Search for password > Password Manager > see if any Passkeys were created for Nekodex. If Passkeys were created, remove them and try logging into Nekodex again (using your same email).
  * Go to the [Passkey demo site](https://www.passkeys.io/) and make sure everything is working. If Passkeys were created, remove them and try logging into Nekodex again (using your same email).
    {% endtab %}

{% tab title="iOS" %}
We aren't aware of any iOS issues at this time! If you have trouble, please [Contact us](/nekodex-playground/all-about-perp/contact-us)
{% endtab %}
{% endtabs %}


# Perp contract specs

Specs for perpetual futures contracts

{% hint style="info" %}
Looking for smart contracts? Please see [Contracts](/nekodex-playground/docs-for-devs/contracts)
{% endhint %}

<table><thead><tr><th>Market</th><th>Max leverage</th><th>Maintenance margin ratio</th><th>Initial Margin</th><th data-type="checkbox">Funding Fees</th></tr></thead><tbody><tr><td>ETHUSD</td><td>50x</td><td>x%</td><td>2%</td><td>true</td></tr><tr><td>BTCUSD</td><td>50x</td><td>x%</td><td>2%</td><td>true</td></tr><tr><td>XRPUSD</td><td>50x</td><td>x%</td><td>2%</td><td>false</td></tr><tr><td>More...</td><td></td><td></td><td></td><td>false</td></tr></tbody></table>


# Provide liquidity (LP)

In the alpha phase, liquidity will be provided by the MME [established](https://gov.perp.fi/t/proposal-market-making-entity/634) by the Perpetual DAO.

## Future

Once Perp v3 is out of beta, users will be able to provide liquidity in pools similar to [Hot Tub](https://vaults.perp.com/).


# How Perp v3 works

## Overview

With Perp v3, we have built something that’s better for traders, better for LPs and better for the ecosystem. Perp v3 offers four key unique selling points:

#### **Flexible Liquidity Framework**

There are many ways to trade perps onchain these days, with no clear winner yet. Previous and current generations of onchain perp exchanges rely on oracles for pricing, use AMM or vAMM models, or handle order matching offchain.&#x20;

Perp v3 moves beyond this with a flexible liquidity framework that makes it easy to add new liquidity models quickly without having to rebuild the entire system. This lets Perp v3 provide:

1. Easier ways for new and casual users to trade and \[Soon™️] provide liquidity.
2. Sophisticated ways for expert users and builders to trade and LP.
3. More flexibility for devs to integrate with, expand and build on top of Perpetual Protocol.

#### **Liquidity and longtails**

To start, Perp v3 will offer 2 liquidity provisioning methods, with more to come soon.

* **Oracle pricing** for major, mature assets where robust oracle prices are available.
* **Spot-hedged liquidity** pools let you trade new and niche assets that don't have a mature or readily available oracle price feed, as well as give arb traders new opportunities to cash in on slower moving spot markets.
* \[Soon™️] Smart Maker JIT-style liquidity that brings you the benefit of CEX-tier liquidity while giving you full custody of your funds for the entire lifecycle of your trade.
* More to be announced...

Learn more in [Liquidity Provision Strategies](https://v3docs.perp.com/perp-v3/docs-for-users/how-perp-v3-works#liquidity-provision-strategies).

#### **More performance**

Perp v3 marks a big step forward in ease of use and performance, with the goal of matching and exceeding the CEX trading experience. This includes

* 2-click trades - no waiting for your wallet to open
* Higher leverage, up to 50x and beyond
* Fast price updates with pull-oracles from [Pyth](/nekodex-playground/docs-for-users/how-perp-v3-works/pyth-oracles)
* More markets, including hot tokens

#### **Not just an aggregator**

Maybe you’re thinking, sounds like an aggregator. Well it kind of is, but with a major advantage.&#x20;

An aggregator also **aggregates risk** from each platform where you have positions. No thanks. With Perp v3 you benefit from having all your positions under one roof, with one of the most credible teams in Defi:

* High Lindy Effect
* Doxxed team
* Non-US-based
* Building onchain since 2020
* Fully non-custodial

### **How is this achieved?**

Perp v3 is a modular platform that allows unprecedented flexibility for liquidity providers, traders and builders. It consists of

* Multiple liquidity sources within the Liquidity Framework to find the best prices from multiple options.
* A router that fetches the best prices from all sources for the trader.
* The vault, router and clearinghouse smart contracts work together to execute trades, track user accounts and manage user funds completely onchain.
* An offchain database holds signed orders and sends them to be executed after the front-running period (3 seconds) or, for limit orders, when the trigger price is reached.
* All positions are backed by isolated margins using collateral from users' futures accounts (ie. Perp v3 vault).

### How a trade happens

1. User enters order details (leverage, position size or value)
2. The Perp v3 router requests quotes from available Liquidity Strategies to find the best price
3. User confirms order which is signed using Session Keys (see [Perp Smart Account](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-smart-account))
4. The order is sent to the Order Gateway, which either executes the order after a safety delay (if applicable depending on the Liquidity Strategy) or stores the order for future execution (in the case of limit orders, etc.)
5. The order is executed
   1. &#x20;Market orders: by the clearinghouse and either
      1. succeeds: the order went through; collateral is assigned to the position as margin, and the position is updated in the user's account;
      2. fails: the order failed due to slippage; the user is notified and collateral is returned to the user's account.
   2. Limit orders, etc.: when the user's trigger conditions are met, the order is retrieved from the offchain database and sent for execution;&#x20;
      1. succeeds (full fill): the order went through (see Market order above)
      2. succeeds (partial fill): the order partially completed, and will continue to stay active until either filled or the order expiry date passes;
      3. fails: the order failed due to slippage; the system will continue trying to fill the order when the trigger conditions are met.

## **Liquidity Framework Strategies**

The liquidity framework integrates liquidity sources we're calling Strategies. The Perp v3 router will automatically get quotes from all available Strategies and choose the best price for you. At launch, two Strategies will be available: Oracle and Spot-Hedge.

### **Oracle Strategy**

The Oracle Strategy is simple on the surface: LPs place funds in pools which provide liquidity for traders to trade using oracle prices. Perp v3 innovates on this model with dynamic spreads and a flexible fee structure that uses a borrowing fee similar to lending markets and, depending on the market, funding payments.

Initially we will work with [Pyth](/nekodex-playground/docs-for-users/how-perp-v3-works/pyth-oracles), leveraging their pull-oracle price feeds to get the freshest prices exactly when traders need them. As other oracles with similar performance become available, we will look at integrating them as well.

### **Spot-Hedge Strategy**

The Spot-Hedge Strategy employs hedging using onchain spot markets. This type of pool will allow LPs to benefit from automated market-making using prices from onchain spot markets. This has at least three benefits:

* Any token with an onchain spot market can support a perpetual futures market, even before oracles are available.
* Traders can arb spot prices if the market connected to the Strategy is lagging other markets.
* LPs market-make in a delta neutral way, so every trade is hedged atomically in the same transaction as it is executed.

Perp OGs familiar with [Hot Tub](/nekodex-playground/docs-for-users/earn-yield#hot-tub) will notice this sounds familiar for a reason: this is an extension of the same vault tech that Hot Tub is based on.

### Future

Perp v3's liquidity framework allows a high level of flexibility when designing and implementing more ways to provide liquidity. Look forward to more in the future. We also welcome your ideas! [Contact us](/nekodex-playground/all-about-perp/contact-us)

## Trader-facing components

### Relay & Gateway

The **gateway** seeks the best path to execute a trade by evaluating the status of liquidity sources for the requested asset. This works in a similar way to routers used by Uniswap, 1inch and other spot DEXs.

Once the path is found and the transaction is signed by the user, the gateway sends the transaction to the blockchain and pays the gas fee.&#x20;

The gateway also handles the system-imposed 3 second delay for oracle-price trades to protect against attempts to frontrun the oracle. This is a common delay in any oracle-based trading system, and is designed to prevent traders from being able to reliably frontrun oracle price updates.

If a significant price change occurs during this delay and your slippage settings are exceeded, you will be notified that the transactions was cancelled (reverted).

### Clearinghouse

All positions are recorded in the clearinghouse, and each position's state (size, notional value, margin, fees due/owed, etc.) is recorded and updated here. Margin for each position is held by the clearinghouse. Position PnL, margin ratio, liquidation conditions, etc. are determined by the clearinghouse.

### Futures Account (Vault)

All funds needed to place trades must be deposited into the trader's futures account. When a trade is placed (position is opened), collateral is moved from the futures account to the clearinghouse, where it serves as the position margin. When a position is closed, margin is returned to the futures account, and can be used to back new positions or withdrawn to the trader's wallet.

Actions such as add margin and remove margin update the user's account so that funds in their futures account are allocated to a specific position.

### P\&L Pool

{% hint style="info" %}
**If your P\&L Pool amount shows 0.00 USD**

P\&L is claimed automatically when you close your position, but sometimes profit cannot be fully claimed if many traders with losses have not close their positions yet. In that case you may need to claim the P\&L here. If you cannot claim right away, please try again later.
{% endhint %}

All position P\&L flows via the P\&L pool between being realized and returning to the trader's futures account. This ensures all profits earned by traders have corresponding losses from other system participants, as well as helping guard against exploits and attacks that might withdraw outsize profits.&#x20;

Before allowing a trader's P\&L to be moved to their futures account, the P\&L pool ensures there is enough margin available in the system to allow withdrawal, as well as checking that the trader's account does not have bad debt.

#### Unclaimable P\&L

In some cases, profits may not be claimable right away if a significant amount of other traders' losses have not been realized. In this case, it may be necessary for losses to be realized before your profits are unlocked.&#x20;

While in the P\&L pool, profits are realized and guaranteed to be claimable once losses are claimed.

### Order fulfillment

| Order type   | Notes                                                                                                                                                                                                                    |
| ------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Market order | <p>Market orders are 'fill or kill'. Either they are 100% filled, or they are killed and there is no change to your account.<br>A typical cause for an order to be killed is your slippage tolerance being exceeded.</p> |
| Limit order  | Limit orders may be partially filled and generally will not be killed until the order is fully filled. Limit orders may be killed if the remaining order size is below the min. order size after partial fill.           |

### Funding rate and payments

Depending on the market, traders may pay or earn premiums, called funding payments in perpetual contract terms, to hold a position.

In Perp v3, funding is paid according to:

1. Open Interest (OI) skew - if long OI exceeds short OI, longs pay shorts; if short OI exceeds long OI, shorts pay longs.
2. Funding rates based on point 1 above, updated every block (15 seconds).
3. Funding payments based on point 2 above, to the nearest second that a trade is open. So if a trade is open for 60 seconds, the aggregate funding rate during those 60 seconds will be used to calculate the funding due or owed for that position.

Funding payments are tracked by the clearinghouse and settle when updates to the position occur (close, add/remove margin, liquidation). Funding payments are made directly to/from the position margin.

## LP-facing components

### Oracle-price LP pools

This pool type became popular in 2022, quickly becoming a trader favorite thanks to easy-to-understand pricing and spreads, as well as simple LP options compared to Uniswap v3 and Perp v2.

Perp v3 establishes a liquidity pool for each asset that uses oracle price, and all trades using this liquidity option are filled according to the current oracle price plus a dynamic spread based on open interest skew (the relative balance of longs vs shorts in any given market).

To prevent oracle frontrunning, all trades are delayed by 3 seconds before they can be executed.

### Spot-hedge LP pools

This is a novel pool type based on the [Hot Tub](/nekodex-playground/docs-for-users/earn-yield#hot-tub) product launched by Perpetual Protocol in early 2023. Hot Tubs perform automated arbitrage between a perpetual futures DEX and onchain spot markets, for example buying an asset and shorting the asset's futures contract when the two diverge, and reversing the process when prices return to the same level.

In Perp v3, a similar method is used to provide a counterparty to traders. When a trader places a trade, the opposite trade is taken on the spot market via the automated vault.

There are several benefits of such a system:

* Relative lack of reliance of outside oracles, meaning markets can launch as soon as there is a reasonable level of liquidity onchain.
* Multiple onchain spot markets can be used at the same time by leveraging aggregators such as 1inch.
* LPs earn yield in a similar way to Hot Tub users, so rather than facing impermanent loss in an unhedged liquidity pool, LPs provide and earn in one token, including stable assets in the case of quote vaults (e.g. USDT denominated vaults).

As with Hot Tub, spot-hedge pools are deployed in pairs:

* QuoteVault containing liquidity in a stable asset (the quote asset)
* BaseVault containing liquidity in the underlying asset (the base asset).&#x20;

Long positions are opened using the QuoteVault (spot-hedge pool buys the spot asset), and short positions are opened using the BaseVault (spot-hedge pool sells the spot asset).

### Funding payments for LPs

Currently makers/LPs do not pay funding on Perp v3.

## Fee and Spread Calculation

## Fees

{% hint style="info" %}
For actual fees, see [Fees & system limits](/nekodex-playground/docs-for-users/trade-perpetual-futures/fees-and-system-limits)
{% endhint %}

#### Taker fees

* Relayer fee
  * A flat fee is paid in USDT for each trade to cover gas. This fee is bundled in the price of each trade, and paid from your futures account.
  * Relayer fees apply to market orders, limit orders and close position.
* Protocol fee
  * 0% initially. This fee may be charged at a later date.
* Borrowing fee
  * This fee is paid continuously as long as the position is open.
  * The fee is based on the utilization ratio of the liquidity used to open the position. The higher the proportion of liquidity in a Strategy is used, the higher the borrowing fee will be.
  * Borrowing fees for longs and shorts will be different.
  * Borrowing fees are based on the position's open notional (USD value at the time the position is opened).
  * Borrowing fees can be 0 but not negative (ie. traders cannot receive borrowing fees).
* Funding fee
  * Some markets may have funding fees, paid based on the ratio of longs to shorts (ratio of long open interest and short open interest).

#### Maker / LP fees

{% hint style="success" %}
Makers aka LPs **always** earn fees - you never pay a fee as a maker or LP.
{% endhint %}

Coming Soon™️ 🏗️ At launch, Perp v3 is limited to whitelisted makers only. Once the liquidity framework model has been proven, Strategies will be opened to users to add liquidity permissionlessly.

### **Oracle Strategy spreads**

Spreads are calculated dynamically based on the ratio of longs to shorts. For detailed information, see [Oracle Maker Pricing](/nekodex-playground/docs-for-devs/contracts/maker/oracle-maker#pricing).

### **Spot-hedge Strategy spreads**

Spreads in spot-hedge pools are based on spot liquidity, pool liquidity, plus the borrowing fee. This makes it highly dynamic, and it is therefore recommended to take quotes directly from the UI or from the [Quoter](/nekodex-playground/docs-for-devs/contracts/quoter) contract.

### Other Strategy spreads

Each Liquidity Framework Strategy has its own risk considerations relating to liquidity provisioning, and therefore has its own spread mechanism. Details will be published as new Stategies are researched and deployed.

## Liquidation

{% hint style="info" %}
For maintenance margin ratios see [Perp contract specs](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs)
{% endhint %}

Liquidations are based on position value according to index prices (oracle prices). This includes positions opened in spot-hedge pools, where spot TWAP or other oracles may be used.

### Taker liquidation

Liquidations occur when the value of the position and the value of the underlying margin reach a set ratio: the maintenance margin ratio (MMR). If the ratio of position to margin falls below the MMR, the position will generally be partly liquidated in such a way that leaves the margin ratio above the MMR. Please see [Perp contract specs](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs)for the MMR of each market.

#### Partial liquidation conditions

Perp v3 supports partial liquidations for positions in order to minimize the impact on traders. If the margin ratio is between the MMR and 0.5 x MMR, the liquidator must perform a partial liquidation. If the margin ratio is below 0.5 x MMR, the entire position may be liquidated. (E.g. if MMR is 5%, as long as the margin ratio is between 5% and 2.5%, partial liquidation will be used.)

#### Liquidators

Liquidators monitor position health and call the clearinghouse liquidation function when the position appears eligible for liquidation. The clearinghouse evaluates the state of the position and permits or denies the liquidation call.&#x20;

If the liquidation is permitted, the position is partly or completely liquidated depending on the position size and margin ratio. The trader pays a liquidation penalty from the position margin, which is first paid into the [#p-and-l-pool](#p-and-l-pool "mention"). This penalty is then added to the liquidator's unrealized PnL as a reward which the liquidator can realize via the P\&L Pool. The liquidator also takes control of the liquidated portion of the position, with a discount, and may choose to close or hold the position.

### Maker/LP liquidation

It is possible to provide liquidity with leverage in some pool types, and a minimum margin ratio is enforced by each pool. If a maker's margin ratio falls below the minimum, liquidators can liquidate the position.

### Liquidation penalty

* 50% of the liquidated margin is awarded to the liquidator
* 50% of the liquidated margin is retained by the [#pnl-pool](#pnl-pool "mention")


# Pyth Oracles

Initially, Perp v3 uses the [Pyth Network](https://pyth.network/) to provide price feed services in various places across the platform. Pronounced '[peeth](https://pyth.network/blog/whats-in-a-name-pyth-and-the-pythia)', the Pyth Network is a cutting edge onchain data service offering real-time prices via pull oracles.

## Pull oracles

Earlier generation onchain oracles were 'push' oracles: each price update was pushed onchain based on triggers like a price change threshold. The next generation is moving to 'pull' oracles where dApps request prices at the time they are needed, increasing efficiency and freshness.

The efficiency of pull oracles makes it much easier to scale and provide a large number of feeds. Pyth currently offers approximately 500 feeds to a large number of blockchains—a feat that seemed impossible in the push oracle paradigm.

## Fresh feeds

With over 500 feeds and counting, the range of assets Perp v3 can list is truly incredible. If you have an asset you feel would benefit Perp v3 users and has yet to be listed, please [Contact us](/nekodex-playground/all-about-perp/contact-us)!

#### Feed me <img src="/files/ZDdoQpKpGAdh7cqyZH0T" alt="" data-size="line">

Perp v3 uses feeds from `pythnet`. Find them below.

{% embed url="<https://pyth.network/price-feeds>" %}


# Security

The security of users' funds and the platform as a whole is our number 1 priority. We have many measures in place, both on- and off-chain in support of this goal.

## System limits

### Circuit Breaker

Perp v3 uses an onchain circuit breaker mechanism to protect the system when certain conditions are met that indicate a hack, exploit or breach. When the circuit breaker conditions are met, some operations will revert, such as withdrawals.&#x20;

In addition, when the circuit breaker is triggered, the system can be manually locked if an attack is confirmed to be taking place, causing a full system pause. If locked, a governance vote will be held to determine subsequent steps.&#x20;

#### Triggers

* TBC
* Grace Period

### Liquidity limits

While not a parametric limit, open interest in the system cannot exceed the value of liquidity provided by LPs. If liquidity is exhausted, it will only be possible to close or reduce positions.

### System collateral caps

Coming Soon™️ 🏗️

### User deposit caps

Coming Soon™️ 🏗️

### Frontrun protection

For trades with oracle price pools, a 3 second delay is enforced to prevent traders from frontrunning the oracle price feed received by the DEX. For trades performed via the DEX [gateway](/nekodex-playground/docs-for-users/how-perp-v3-works#router-and-gateway), this is handled automatically. For trades performed using smart contract interaction, two transactions must be sent: the initializing transaction, and an execution transaction with a timestamp 3 seconds later or more.

### Oracle safety

Coming Soon™️ 🏗️

## Audits

See [Security & Audits](/nekodex-playground/all-about-perp/more/security-and-audits) for details.

## Project security

Perpetual Protocol contracts external auditors to check production code before users deposit the first $1 of funds. Once code goes live, our bug bounty program serves to attract whitehats to find vulnerabilities and exploits in return for prize money. See [Security & Audits](/nekodex-playground/all-about-perp/more/security-and-audits) for details.

Perpetual Protocol also has policies in place to ensure the code being sent to auditors is as strong as it can be. Programmers work in pairs while coding, putting two sets of eyes on the task at all times. Internal reviews ensure each commit is checked before being pulled. Our team also includes a security specialist who researches exploits and code integrity on a continuing basis.

All funds and contract owner addresses are held by multi-sig safes. The signer wallets are intentionally distributed across different wallet types and manufacturers to mitigate spread of contagion should a wallet experience a hack.

In addition to our official bug bounty program administered by [ImmuneFi](https://immunefi.com/bounty/perpetual/), we also regularly work with community researchers and whitehats to find bugs and offer rewards for issues outside the official bug bounty scope. **If you found a bug**, [Contact us](/nekodex-playground/all-about-perp/contact-us)!

## Smart Accounts

[ERC-4337](https://www.erc4337.io/) smart accounts are powered by ZeroDev (Kernel). Smart accounts (aka account abstraction) let users sign up for and use decentralized financial tools without relying on a third party custodian, while also having the technical aspects of self-custody abstracted out of the experience. This is a major advantage for non-technical users.

**Audit**: The ZeroDev Kernel wallet was audited by [Kalos](https://kalos.xyz/).

**2FA**: Using ZeroDev, users can add a second factor for use in authentication, further enhancing the security of their account.


# Technical Overview

At a high level, Perp v3 is a DEX system that uses a vault to hold user collateral, a router to choose from among several liquidity/pricing options in a liquidity framework, and a clearinghouse to record user account information.

For details about liquidity framework components, see [Maker](/nekodex-playground/docs-for-devs/contracts/maker).

## Contracts

The core Perp v3 contracts handle user deposits, trades, settlement and liquidation.

### Vault contract

User deposits and withdrawals are made to/from the vault contract (called Funding Account for users). All collateral deposits are kept in the user's exchange funding account. All trades are backed by margin drawn from this collateral, and each position has its own margin. All user deposits remain in the vault at all times, and user accounts are updated according to the clearinghouse contract (below).

See [Vault](/nekodex-playground/docs-for-devs/contracts/vault) for details and code examples.

### Order Gateway contract

You may choose to let the order gateway find the best price for you, or directly trade with the pool you want to use. This section assumes you want to trade using the order gateway.

The benefit of using the order gateway is easier setup via API, simplified quoting and automated price finding. The cons of using the order gateway are slightly slower execution and slightly increased potential for downtime due to an increased number of moving parts.

See [Order Gateway](/nekodex-playground/docs-for-devs/contracts/order-gateway) for details and code examples.

### Clearinghouse contract

{% hint style="info" %}
Only one position of each asset can be open at a time, for a given account. If a second order for an asset with an existing position is created, the two resulting positions will be summed together. E.g. if you have a 1 ETH long and open a 1 ETH short, the two positions will sum to 0.
{% endhint %}

All trades and updates to account balance are handled by the clearinghouse contract.

Adding and removing position margin is controlled by the clearinghouse. Perp v3 uses isolated margin (each position has its own discrete margin). Rules regarding removal of margin are set and enforced by the clearinghouse.

See [Clearinghouse](/nekodex-playground/docs-for-devs/contracts/clearinghouse) for details and code examples.

#### Clearinghouse role in trade sequence

<figure><img src="/files/F1R53AQN7q6UEiG02sZZ" alt=""><figcaption><p>A trade is initiated, price is chosen by the router, and executed.</p></figcaption></figure>

<figure><img src="/files/f5IbwHuA7Xb4YruMWVrC" alt=""><figcaption><p>Detailed settlement between clearinghouse and vault</p></figcaption></figure>

### Quoter contract

Prices for trades (quotes) can be obtained using the Quoter contract.

Note: Quoter contract only considers onchain prices. Ie. it does not take live limit orders into account.

### Maker contracts

Each maker has a contract housed under [Maker](/nekodex-playground/docs-for-devs/contracts/maker). See each type for details.

Some maker types allow LPs to use leverage, such as Perp v3 oracle maker pools.

## Fees

#### Borrowing fee

A fee is paid to maintain an open position in the same way you would pay interest on a loan from a Defi lending platform. All takers pay borrowing fees, and makers may pay in some circumstances.

The borrowing fee for each market is calculated based on the aggregate utilization ratio of all makers (LPs) in that market.

Details: [Borrowing Fee](/nekodex-playground/docs-for-devs/contracts/borrowing-fee)

#### Funding fees / funding payments

{% hint style="info" %}
Notes

* Funding payments only apply to some markets. See [Perp contract specs](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs).
* Funding payments relate to the ratio of long/short open interest, not the ratio of market and index prices. Regardless, longs still pay shorts when funding is positive, and vice versa.
  {% endhint %}

Funding fees are designed to mitigate makers' exposure to price movement in cases where hedging is not possible (e.g. Oracle pools). The funding rate is based on the long/short skew of the [`basePool`](#basepool).&#x20;

* If the basePool has more shorts, takers (and possibly some makers) holding longs will pay funding fees.&#x20;
* If the basePool had more longs, takers (and possibly some makers) holding shorts will pay funding fees.
* Non-basePool makers pay or receive funding based on their own long/short skew.

```solidity
maxCapacity = basePool.totalDepositedAmount / basePool.minMarginRatio
imbalanceRatio = abs(basePool.openNotional)^fundingExponentFactor / maxCapacity
fundingRate = -1 * imbalanceRatio * fundingFactor
funding = trader.openNotional * fundingRate * deltaTimeInSeconds
```

Traders holding positions opposite to the base maker's direction need to pay a funding fee to traders holding positions in the same direction as the base maker.

#### Matcher fee

In general the matcher fee applies to UI users only. At launch this is a flat fee and in the future may be dynamic based on volume.

## Account value

Account value is dependent on margin and unrealized PnL, and derived as follows.

$$
\begin{aligned}
pendingMargin &:= borrowingFee + fundingFee
\\
margin &:= depositedMargin + unsettledPnl + pendingMargin
\\
positionValue &:= positionSize \times oraclePrice
\\
unrealizedPnl &:= openNotional + positionValue
\\
accountValue &:= margin + unrealizedPnl
\end{aligned}
$$

## Margin & Leverage

Each market may have separate parameters for initial and maintenance margin ratios (and corresponding leverage values). See values in [Perp contract specs](/nekodex-playground/docs-for-users/trade-perpetual-futures/perp-contract-specs).

$$
\begin{aligned}
leverage &:= \cfrac{Abs(openNotional)}{accountValue}
\end{aligned}
$$

#### Initial Margin Ratio

$$
initailMarginRequirement:=Abs(openNotional) \times initialMarginRatio
$$

Positions must have a margin ration equal to or higher than the initial margin ratio when opened. The open position transaction will revert if the margin ratio is lower than the initial margin ratio. Initial Margin Ratio applies to

* Open position (including when trading in reverse direction, e.g. opening a short with an existing long)
* Increase position size\*

#### Maintenance Margin Ratio

$$
maintenanceMarginRequirement:=Abs(openNotional) \times maintenanceMarginRatio
$$

Positions must have a margin ratio higher than the maintenance margin ratio. Positions with a lower margin ratio may be liquidated. Maintenance margin ratio applies to

* Decrease position size\* (includes close position and partial close)
* Liquidation conditions (margin ratio must be equal to or lower than MMR for a liquidation transaction to succeed)

{% hint style="info" %}
Reduce vs Close Position

Reducing a position is done by calling `openingPosition` in the opposite direction of the existing position. The clearinghouse will evaluate the position's margin according to `positionSizeBefore` and `positionSizeAfter` as well as taking into account position direction (long or short).

Depending on the result of the trade, either `maintenanceMarginRatio` or `initialMarginRatio` will be used to evaluate the validity of the transaction.

```
// evaluate maintenanceMarginRatio
positionSizeAfter < positionSizeBefore & direction is same
positionSizeAfter = 0

// evaluate initialMarginRatio
positionSizeAfter > positionSizeBefore & direction is same
positionSizeAfter < positionSizeBefore & direction is not same
```

Close or partial close will always use `maintenanceMarginRatio`.
{% endhint %}

## Free collateral

The vault (funding account) contract checks the user's free collateral when trades and withdrawals. Depending on the action, the method for calculating free collateral is as follows.

{% hint style="warning" %}
Collateral needed for untriggered limit orders, etc., will cause orders to fail if removed.
{% endhint %}

#### For trades

$$
\begin{aligned}
freeCollateral\_{open} &:= min(margin, accountValue) - initialMarginRequirement
\\
freeCollateral\_{reduce} &:= min(margin, accountValue) - maintenanceMarginRequirement
\end{aligned}
$$

#### For withdrawals

$$
\begin{aligned}
freeMargin &= max(depositedMargin + min(unsettledMargin+pendingMargin, pnlPoolBalance), 0)
\\
freeCollateral\_{withdraw} &= min(freeMargin, accountValue) - initialMarginRequirement
\end{aligned}
$$

## Liquidation

When the account value falls below the maintenance margin requirement, the position will start to undergo liquidation. When a position is liquidated, it will be transferred to the liquidator at the current oracle price. This means that the liquidator must hold sufficient margin to take over the liquidated position. The margin amount will determine how many positions they can take over.

#### Maximum Liquidatable Position Size

When the account margin ratio falls below the maintenance margin requirement (MMR) but remains above 0.5\*MMR, the liquidator may only liquidate up to half of the position size. If the margin ratio < 0.5\*MMR, liquidators may liquidate the entire position.

#### Liquidation Penalty & Liquidation Fee

Traders pay a liquidation penalty after liquidation, and the liquidator will receive a portion of the liquidation penalty as fee for triggering the liquidation. The remaining penalty is reserved by the protocol. To prevent bad debt exploits, both the liquidation penalty and liquidation fee are settled through the [Pnl Pool](#pnl-pool). Traders pay liquidation penalties to Pnl Pool, and liquidators and the protocol receive liquidation fees from the Pnl Pool.

#### Liqudation Penalty Calculation

$$
\begin{aligned}
liquidationPenaltyRatio &:= \text{the percentage of the open notional that the trader needs to pay as a liquidation penalty} \\
liquidaitonRatio&:= \cfrac{liquidatedPositionSize}{positionSize}
\\
liquidationPenalty &:= \text{the actual amount that the trader needs to pay to the PnlPool} \\
\\&= openNotional \times liquidaitonRatio \times liquidationPenaltyRatio
\end{aligned}
$$

#### Liquidation Fee Calculation

$$
\begin{aligned}
liquidationFeeRatio &:= \text{the percentage of the liquidation penalty that the liquidator can receive as a liquidation fee.} \\

liquidationFee\_{liquidator} &:= \text{the actual amount that the liquidator can receive from the PnlPool} \\
\\&= liquidatinPenalty \times liquidaitonFeeRatio
\\
liquidationFee\_{protocol} &:= \text{the actual amount that the protocol can receive from the PnlPool} \\
\\&= liquidatinPenalty - liquidationFee\_{liquidator}
\\
\end{aligned}
$$

## PnL Pool

{% hint style="warning" %}
PnL pool is pending confirmation
{% endhint %}

{% hint style="info" %}
Each market has a separate PnL pool
{% endhint %}

All PnL, positive or negative, passes through the market's PnL pool before being withdrawn to the user's funding account (vault). The purpose of the PnL pool is to settle PnL and ensuring all losses match profits for the given market before profits can be withdrawn. Negative PnL is retained by the pool to pay to accounts that settle positive PnL.

If settlement is not possible (settled positive PnL > PnL pool balance), withdrawal will be delayed until positions with negative PnL (unrealized losses) are settled, adding funds to the PnL pool. Withdrawal delays could occur for example when there is a large amount of realized profit *and* unrealized loss within one market. Traders in profit would need to wait for some of the unrealized losses to be realized before being able to withdraw fully. In general conditions when withdrawals would be blocked are considered an edge case.

{% @github-files/github-code-block url="<https://github.com/perpetual-protocol/lugia-contract/blob/develop/src/vault/LibPositionModel.sol#L17>" %}

This architecture allows the protocol trading engine to be less restrictive without compromising the safety of user funds. Using the PnL pool, the protocol ensures that PnL always balances and user funds are safe from exploitation. The PnL Pool replaces the Insurance Fund in more traditional leverage trading.

#### PnL Pool Actions

* Open position
  * no action needed
* Reduce, close or liquidate position
  * If PnL > 0 →&#x20;
    * Withdraw only if PnL Pool has enough funds
    * When positive PnL is settled, the PnL pool balance decreases
  * If PnL < 0 →&#x20;
    * Withdraw only if `trader.margin` has enough funds
    * When negative PnL is settled, the PnL pool balance increases
* `_settlePnl()`
  * What is it
  * Deposit: Should `_settlePnl()` as much as possible to clear the trader’s existing unsettled PnL.&#x20;
  * Withdraw: Should `_settlePnl()` as much as possible before calculating free collateral so it could maximize withdrawal limit.

#### Bad debt

The PnL pool is intended to serve in place of an insurance fund, which means it will have to handle cases where bad debt occurs.&#x20;

## Price band

A price band is in place to ensure trades happen within a safe range compared to the underlying price mechanism (e.g. oracle price). This guards against exploits and extreme volatility. Query `priceBandRatio` using [Config](/nekodex-playground/docs-for-devs/contracts/config).

$$
\begin{aligned}
\&bias := oraclePrice \times priceBandRatio
\\
&{oraclePrice - bias} \le{tradePrice}\le{oraclePrice + bias}
\end{aligned}
$$

## baseMaker

The baseMaker is used when calculating funding rates. A base maker is a whitelisted liquidity provider that meets the following conditions:

* Cannot increase/decrease positions actively (may increase/decrease margin)
* Must always accept taker orders
* Must use index price as main pricing mechanism
* Only one `baseMaker` per market
* The `baseMaker` always receives funding, and other makers and takers that have positions with the same direction as the `baseMaker` also receive funding

#### Updating baseMaker

🏗️ Admin function - how this is updated is a future decision.

## Circuit Breaker

Perp v3 employs the [ERC-7265](https://ethereum-magicians.org/t/eip-7265-circuit-breaker-standard/14909) circuit breaker in order to rate limit withdrawals. The withdrawal rate is limited to a set percentage of TVL withdrawn per time period. The circuit breaker is controlled by a multisig that is controlled by the team and/or protocol governance.

#### Rate Limit Procedure

The rate limit will revert any operation that exceeds the set limit. Operations within the limit can continue to execute, e.g. if rate limit is 1000 and current rate is 900, a withdrawal of 200 will be limited but a subsequent withdrawal of 50 will be permitted.

1. When rate limit is triggered:
   1. Vault withdrawal transactions will revert
   2. Some withdrawals from maker (LP) positions will revert
   3. Spot hedge maker `fillOrder()` may also revert because it withdraws from vault
2. Multisig owners check if there’s a hack or just a whale withdrawing or trading against spot hedge maker.
3. Next steps
   1. It's a hack: Multisig is used to call `markAsNotOperational()`. Withdrawals are permanently locked and funds can only be removed by calling `migrateFundsAfterExploit()`.
   2. It's not a hack:
      1. Take no action - withdrawals will be limited until the `_rateLimitCooldownPeriod` has passed. After cooldown, anyone can call `overrideExpiredRateLimit()` to remove rate limiting once `_rateLimitCooldownPeriod` has passed.
      2. &#x20;If it’s not a hack, the multisig owners can choose to call `overrideRateLimit()` to establish a grace period. Rate limit will be suspended until `gracePeriodEndTimestamp`.

## Oracle System

In oracle price markets, Perp v3 relies on oracle prices to calculate account value and for liquidations. The Pyth Network is currently used as the source for oracle prices. To avoid oracle front-running issues, most actions require two steps separated by a delay to execute, or actions are handled via a trusted off-chain service to relay the tx:

* Send transactions in two steps, first to update the oracle price and second to execute the transaction, with a min. timestamp delay of 3 seconds (applies to add/remove margin, open/close positions, and liquidations)
* Bundle the two transactions using the [`multicaller`](#multicaller-library) contract

(Trades performed using the UI use `multicaller`.)

## Limit orders

Limit orders are held in an offchain database (orderbook) and will be matched against orders (market or limit orders) or filled using liquidity framework makers when the trigger conditions are met.

#### Key considerations

* Limit order creation via contract or API is not currently supported but may be in the future.
* Limit orders are treated like market orders once they are triggered; all fees are paid the same as market orders.
* Order expiry is currently fixed and will be updatable in a future release.
* A min. order size (openNotional, currently 10 USDT) applies to limit orders.
* Market orders can be matched directly against open limit orders, if the price is preferential.
* Order will be cancelled if user's futures account does not hold enough funds to back the order.
* Limit orders are filled FCFS (lower timestamps fill first; if timestamp is the same, order may be determined according to the database specs.)

#### Fees

Limit orders are subject to a relayer fee:

* Fee is paid one time, no matter how many times order is filled
* Fee is paid from the user's futures account
* Fee is paid at the time of the first fill for each order&#x20;

## Multicaller Library

Perp v3 uses the Multicaller library to "efficiently call multiple contracts in a single transaction." See the library here: <https://github.com/vectorized/multicaller>


# Contracts

## Contract addresses

Find a complete list of up to date contract addresses here:

{% embed url="<https://metadata.perp.exchange/lugia/optimism.json>" %}

## Contract descriptions

The main contracts users interact with are:

[Vault](/nekodex-playground/docs-for-devs/contracts/vault) - holds user deposits and manages user funds

[Order Gateway](/nekodex-playground/docs-for-devs/contracts/order-gateway) - receives and triggers orders

[Clearinghouse](/nekodex-playground/docs-for-devs/contracts/clearinghouse) - processes exchange functions such as open position, close position and liquidations, as well as handling accounting.

For other contracts, use the menu on the left.

## Metadata

Key metadata such as `marketID`, exchange contract addresses, market contract addresses, price feed contracts, etc. can be found here:

{% embed url="<https://metadata.perp.exchange/lugia/optimism.json>" %}

## Decimal usage

EVM Smart contracts do not recognize decimals. The general convention in Perp v3 contracts is all amounts use 18 decimal.

In cases where the native decimals of the token are used (e.g. USDT uses 6 decimals), the contract parameter will have XCD appended to it (cross to collateral decimal). E.g.&#x20;

* `amountXCD`
* `marginXCD`


# Address Manager

## addressManager

### `getAddress`

Query the address for a given contract, `_name`.

{% code overflow="wrap" %}

```solidity
/// @notice Get `_name` parameters from events log
event AddressSet(
    string indexed _name, 
    address _newAddress, 
    address _oldAddress
);
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
function getAddress(
        string memory _name
) 

return _addresses[_getNameHash(_name)]
```

{% endcode %}

## addressResolver

Get the address of addressManager.

{% code overflow="wrap" %}

```solidity
function getAddressManager()

return IAddressManager(
    _getAddressResolverStorage().addressManager
)
```

{% endcode %}


# Borrowing Fee

Takers pay borrowing fees similar to interest paid to borrow tokens on lending platforms and it based on the utilization ratio of makers in that market.

* In general, takers pay borrowing fees for all open positions.&#x20;
* Maker (LP) positions generally receive a borrowing fee, and pay the fee in some instances.
* Borrowing fees are pending until settlement by the [Vault](/nekodex-playground/docs-for-devs/contracts/vault) when certain events occur.
* A positive fee is one that is payed; a negative fee is one that is received (earned).
* Borrowing fees are paid directly to/from the position margin, thus affecting margin ratio over time.

## Overview

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

Borrowing fees are initially pending fees, and can be settled by calling `_settleBorrowingFee`.

## Definitions

* Long and short states are separate and independent.
* Receiver: a user that earns borrowing fees: generally a subset of makers; cannot increase position proactively; cannot censor orders in any circumstances.
* Payer: a user that pays borrowing fees; any user that is not a receiver is a payer.
* Takers can only be payers; makers/LPs can be either payer or receiver.

### Utilization Ratio

$$
utilizationRatio := \begin{cases}
Min(1, \cfrac{Abs(openNotional)}{margin}) &\text{if margin > 0}
\\
1 &\text{if margin <=0}
\end{cases}
$$

### Borrowing fee calculation

A trader can have one or two roles

* Maker: trader who guarantees to provide passive liquidity
* Taker: trader who takes that liquidity

If a certain type of maker qualifies as a receiver, the system will compensate the maker with borrowing fees paid by takers.

{% code overflow="wrap" %}

```solidity
borrowingFeeRate per second = abs(openNotional) * utilRatio * maxBorrowingFeeRate
```

{% endcode %}

Borrowing fees for long and short positions are separate. Unlike traditional funding rates based on position size, borrowing fee rates are based on open notional. Example:&#x20;

{% code overflow="wrap" %}

```solidity
maxBorrowingFeeRate = 10%
utilRatio = 50%
// Assume there's only one receiver (maker)
margin notional = 2
// A trader opens a long
position notional = 1
// The trader's borrowing fee rate will be:
borrowingFeeRate = abs(-1) * 0.5 * 0.1 = 0.05 = 5%
```

{% endcode %}

### Whitelisted Maker

* Receives borrowing fees based on their utilization ratio
* Does not pay borrowing fees

#### Whitelist Criteria

* Maker must fill any order received. Notes:
  1. The only way we can think of that can guarantee is to whitelist smart contract controlled by DAO, and the pricing mechanism has no off-chain component
  2. Other than that there’s no perfect way to guarantee this on-chain. bad actor can accept order in a ridiculous price if she does not want to accept the order. restricting a price range may help but still not good enough
* Maker cannot increase position actively. Notes:
  1. This limitation is needed to prevent whitelisted makers from gaming borrowing fees.
  2. Can reduce position actively, which gives the maker some characteristics of a taker.
* Maker must have no position initially.
* The Perpetual DAO is charged with adding/removing makers from whitelist.

### Non-Whitelisted Maker

{% hint style="warning" %}
Non-whitelisted maker feature will be activated after launch.
{% endhint %}

Accounts that are not a whitelisted maker will earn, and may also pay borrowing fees.

* No restrictions on what orders may be filled / not filled
* Examples

  * The party acting as the maker in the off-chain order book.
  * Other unofficially maintained private makers. (Not open to private makers for now)

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

## Contract

{% code overflow="wrap" %}

```solidity
struct SettleBorrowingFeeParams {
    uint256 marketId;
    address trader;
    int256 positionSizeDelta;
    int256 openNotionalDelta;
}
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
function getPendingFee(
    uint256 marketId, 
    address trader
)

/// @notice For payer (liquidity consumer)
return int256 payerBorrowingFee;

/// @notice For receiver (liquidity provider)
return int256 receiverBorrowingFee;
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
/// @dev Additional contract functions
/// @notice Query market max borrowing fee
function getMaxBorrowingFeeRate(
    uint256 marketId
)
returns (
    uint256, // MaxBorrowingFeeRate
    uint256 // marketId
) 

/// @notice Query total open notional held by receivers
function getTotalReceiverOpenNotional(
    uint256 marketId
) 
returns (
    uint256, // TotalReceiverOpenNotional
    uint256 // marketId
)

/// @notice Query total open notional held by payers
function getTotalPayerOpenNotional(
    uint256 marketId
)
returns (
    uint256, // TotalPayerOpenNotional
    uint256 // marketId
)

/// @dev getUtilRatio has moved to the individual maker contracts
function getUtilRatio
```

{% endcode %}


# Circuit Breaker

Controls and limits flow of funds, etc., to maintain system security.

For more information, see [Security](/nekodex-playground/docs-for-users/security#circuit-breaker).


# Clearinghouse

All basic exchange functions are kept in the clearinghouse contract. This includes open and close position, and liquidation functions.

{% hint style="info" %}
Find parameters like `marketID` in [Contracts](/nekodex-playground/docs-for-devs/contracts#metadata)
{% endhint %}

## `openPosition`

Open a position or update the size of an existing position (you can only have one position in a given asset).

#### Parameters

<pre class="language-solidity"><code class="lang-solidity">struct OpenPositionParams {
        uint256 <a data-footnote-ref href="#user-content-fn-1">marketId</a>;
        address maker; // Maker type, e.g. spotHedgeMaker
        bool isBaseToQuote;
        bool isExactInput;
        uint256 amount;
        uint256 oppositeAmountBound; // Control slippage
        uint256 deadline; // Timestamp
        bytes makerData; // @param makerData Encoded calls are custom data defined by maker
    }
</code></pre>

#### Returns

```solidity
returns (int256 base, int256 quote);
```

## `closePosition`

Close a position. Note you can also close using `openPosition` and opening an equal size position of the opposite direction (e.g. long closes short).

#### Parameters

```solidity
struct ClosePositionParams {
        uint256 marketId;
        address maker;
        uint256 oppositeAmountBound;
        uint256 deadline;
        bytes makerData;
    }
```

#### Returns

```solidity
returns (int256 base, int256 quote);
```

## `liquidate`

Liquidate a position. Contract will test the position for eligibility before liquidation.

#### Parameters

```solidity
struct LiquidatePositionParams {
        uint256 marketId;
        address liquidator;
        address trader;
        uint256 positionSize;
    }
```

#### Returns

```solidity
returns (int256 liquidatedAccountBaseDelta, int256 liquidatedAccountQuoteDelta)
```

#### Event

```solidity
event Liquidated(
        uint256 indexed marketId,
        address indexed liquidator,
        address indexed trader,
        int256 positionSizeDelta,
        int256 positionNotionalDelta,
        uint256 price,
        uint256 penalty,
        uint256 liquidationFeeToLiquidator,
        uint256 liquidationFeeToProtocol
    )
```

## `setAuthorization`

Delegate open and close permissions; delegation is currently limited to order gateway contracts only.

## `isLiquidatable`

#### Parameters

```solidity
struct isLiquidatableParams {
        uint256 marketId;
        address trader;
        uint256 price;
    }
```

#### Returns

```solidity
bool
```

[^1]: See [Contracts](/nekodex-playground/docs-for-devs/contracts#metadata)


# Config

The config contract sets key exchange parameters.

## Contract

{% code overflow="wrap" %}

```solidity
/// @notice For maker types that requires mitigation of oracle front-running, order must comes from a gateway that will execute the order in a 2-step process with a delay that's longer than `orderDelaySeconds`
function getOrderDelaySeconds() external view returns (uint256) {
    return _getConfigStorage().orderDelaySeconds;
}

/// @notice Query max order validity duration
function getMaxOrderValidDuration() external view returns (uint256) {
    return _getConfigStorage().maxOrderValidDuration;
}

/// @notice Query max relayer fee. Denominated in collateral token.
function getMaxRelayFee() external view returns (uint256) {
    return _getConfigStorage().maxRelayFee;
}

/// @notice Query the margin ratio needed to open a position.
function getInitialMarginRatio(uint256 marketId) external view returns (uint256) {
    uint256 mRatio = _getConfigStorage().initialMarginRatioMap[marketId];
    if (mRatio == 0) {
        return 1 ether; // 100%
    }
    return mRatio;
}

/// @notice Query the margin ratio required to prevent liquidation.
function getMaintenanceMarginRatio(uint256 marketId) external view returns (uint256) {
    uint256 mRatio = _getConfigStorage().maintenanceMarginRatioMap[marketId];
    if (mRatio == 0) {
        return 1 ether; // 100%
    }
    return mRatio;
}

/// @notice Query what percentage of the liquidation penalty the liquidator can receive.
function getLiquidationFeeRatio(uint256 marketId) external view returns (uint256) {
    uint256 feeRatio = _getConfigStorage().liquidationFeeRatioMap[marketId];
    return feeRatio;
}

/// @notice Query what proportion of the liquidated position may charged as penalty.
function getLiquidationPenaltyRatio(uint256 marketId) external view returns (uint256) {
    uint256 penaltyRatio = _getConfigStorage().liquidationPenaltyRatioMap[marketId];
    return penaltyRatio;
}

/// @notice Query the borrowing fee rate when utilization ratio is 100% (for all borrowing fee receivers).
function getMaxBorrowingFeeRate(uint256 marketId) external view returns (uint256, uint256) {
    return IBorrowingFee(getAddressManager().getBorrowingFee()).getMaxBorrowingFeeRate(marketId);
}

/// @notice Query Pyth's price feed id for the given market.
function getPriceFeedId(uint256 marketId) external view returns (bytes32) {
    return _getConfigStorage().marketMap[marketId];
}

/// @notice Query whether a maker can use the vault callback function and receive borrowing fees.
function isWhitelistedMaker(uint256 marketId, address trader) external view returns (bool) {
    return _getConfigStorage().whitelistedMakerMap[marketId][trader];
}

/// @notice Query the global maximum amount of deposits allowed.
function getDepositCap() external view returns (uint256) {
    return _getConfigStorage().depositCap;
}

/// #notice Query the price band ratio.
function getPriceBandRatio(uint256 marketId) external view returns (uint256) {
    return _getConfigStorage().priceBandRatioMap[marketId];
}
```

{% endcode %}

## `fundingConfig`

Query market funding config for funding factor and `basePool` address.

{% code overflow="wrap" %}

```solidity
struct FundingConfig {
    uint256 fundingFactor;
    uint256 fundingExponentFactor;
    address basePool;
}

function getFundingConfig(
    uint256 marketId
)
returns (
    FundingConfig memory
)
```

{% endcode %}


# Funding Fee

The `fundingFee` contract provides logic for calculating and settling funding fees, as well as querying the funding rate and pending (pre-settlement) funding fees.

## basePool

Funding rates are calculated using `basePool`. If for a given market the `basePool` is not set (ie. set to `0x000...`), funding fees will not be applied in this market.&#x20;

The `basePool` address can be queried using [Config](/nekodex-playground/docs-for-devs/contracts/config).

## Contract

<pre class="language-solidity" data-overflow="wrap"><code class="lang-solidity"><strong>/// #notice Check the settlement event to see amount of funding paid/received. This information may also be available from The Graph.
</strong>event FundingFeeSettled(uint256 marketId, address trader, int256 fundingFee);

function getCurrentFundingRate(uint256 marketId) public view returns (int256)

/// @notice Amount of pending fees from the trader's perspective.
/// @return When settled, margin will decrease if fee is positive, increase if fee is negative.
function getPendingFee(
    uint256 marketId,
    address trader
) 

returns (
    int256 pendingFee
)

/// @notice Query latest funding rate. Historical funding rates should be queried from The Graph or similiar provider.
function getCurrentFundingRate(
    uint256 marketId
)

returns (
    int256 fundingRate
)
</code></pre>


# Maker

Collection of contracts for each maker (liquidity framework) type. See the subpage for details.

[Oracle Maker](/nekodex-playground/docs-for-devs/contracts/maker/oracle-maker)

[Spot Hedge Maker](/nekodex-playground/docs-for-devs/contracts/maker/spot-hedge-maker)

## Key maker concepts

#### `minMarginRatio`

This is a minimum margin ratio set by a maker (LPs / pool participant). If this ratio is reached, the maker will stop providing more liquidity. In some Liquidity Strategies it is possible to LP with leverage (e.g. oracle pools), and in some Strategies leverage is not desirable (e.g. spot-hedge pools), and `minMarginRatio` controls the amount of leverage the maker allows.

#### `fillOrder`

Maker contracts provide a public fillOrder function to allow users to fill orders using pool liquidity.

#### Callback

Some maker types, such as spot hedge, may function best when funds can be removed from the vault for user in hedging or other functions. This ability is named `callback`, and is initially restricted to whitelisted LPs. This function will either be made permissionless or replaced by a more secure mechanism in the future.

#### Matching priority

Currently there is no prioritization. Orders will be filled using the maker with the best price including fees.

## Future

More maker types will be added to the liquidity framework as they are developed. Maker types can be developed by the Foundation team and by 3rd parties. The scope for maker types is very broad and can include JIT liquidity, off-chain orderbooks, and much more.

Please [Contact us](/nekodex-playground/all-about-perp/contact-us) if you are interested in developing novel liquidity framework strategies!


# Oracle Maker

{% hint style="danger" %}
Liquidity provision is whitelisted until initial beta testing has completed.
{% endhint %}

## Overview

Oracle maker uses price feeds from Pyth and may employ feeds from Chainlink and other providers as they become available/needed.&#x20;

* Each market backed by an oracle maker has a discrete liquidity pool.&#x20;
* Market orders with oracle pools are fill-or-kill, ie. no partial fills unless this logic is handled at a higher layer in the stack (e.g. by the [Order Gateway](/nekodex-playground/docs-for-devs/contracts/order-gateway) for limit orders filled by oracle maker pools).
* All orders sent to an oracle maker pool must include a delay for front running protection - this can be handled by the order gateway.&#x20;

### Filling taker orders

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

#### Order filled event

{% code overflow="wrap" %}

```solidity
/// @notice Emitted when an order is filled by a Pyth Oracle Maker. 
///         It reveals all information associated with the trade price.
event PythOracleOrderFilled(
    uint256 orcalePrice,    // In quote asset as wei
                            // Assumes price >= 0
    uint256 tradePrice,     // In quote asset as wei
                            // Assumes price >= 0
    uint256 size,           // In base asset as wei
    uint256 fee,            // In quote asset as wei
    uint256 spread          // In percentage (1e6 = 100%)
);
```

{% endcode %}

### Deposit liquidity

Deposits are managed via the [Vault](/nekodex-playground/docs-for-devs/contracts/vault) contract. Only collateral supported by the vault can be used by makers (LPs).

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

### Withdraw liquidity

LP holds a share of the global Maker account value, and can withdraw according to the value of their share.

* Example:
  * Maker account value = 100 USDC
    * `accountValue = margin + positionSize * price + openNotional`
    * `price = abs(fillOrder(positionSize) / positionSize)`
  * LP withdraw 10% of liquidity
    * `withdraw(share)`
    * `sharePrice = accountValue / totalSupply()`
  * LP gets 10 USDC (`share * sharePrice`)

## Pricing

### Quote Token

* At launch, all prices are in USD

### Dynamic Premium (spread calculation)

A spread is added to trades to offset makers' risk exposure. Risk exposure potentially includes:

* Long/short skew
* Entry price
* Funding (however, impacts should be minimal because the maker aims to have zero positions over a long period of time)

Risk mitigation:

* Minimize inventory risk (e.g. target position size = 0)
* One-sided circuit breaker when maximum risk exposure is reached (stop taking more long or short, but accept trades that reduce exposure)

Dynamic premium is modeled on a simplified Avellaneda-Stoikov model.

* Givens
  * `midPrice = oraclePrice`: Traditionally in a CLOB, `midPrice` is the midpoint of max bid & min ask; in `PythOracleMaker` we let `oraclePrice` assume this role because you can think of it as the center of bid & ask when spread = 0.
  * `reservationPrice`: Risk-adjusted price for market making. It is a function of `midPrice` (`oraclePrice`), the maker’s risk exposure, and the configurables below. The premium is the difference between `reservationPrice` and `midPrice`
    * `reservationPrice = midPrice * (1 - maxSpread * makerPosition / maxAbsPosition)`
  * `bid = min(midPrice, reservationPrice)`
  * `ask = max(midPrice, reservationPrice)`
* Configurables
  * `maxSpread`: Sensitivity of the maker’s price premium to its risk exposure. This is modeled as the maximum price difference allowed between `midPrice` and `reservationPrice`. The larger `maxSpread` is, the faster the maker increases the premium in response to higher risk exposure.
  * `maxAbsPosition`: Position size cap where the maker would stop taking more positions. We also use it to calculate `reservationPrice`. The max position is a safety threshold and should be configured so that it is not reached too often, because once it is reached, the maker would stop providing liquidity on one side.

## Contracts

{% hint style="info" %}
See [Order Gateway](/nekodex-playground/docs-for-devs/contracts/order-gateway)for more details about interacting with oracle maker pools.
{% endhint %}

### OracleMaker.sol

#### Event

{% code overflow="wrap" %}

```solidity
event Deposited(
    address depositor,
    uint256 shares, // Amount of shares minted
    uint256 underlying // Amount of underlying token deposited
);
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
event Withdrawn(
    address withdrawer,
    uint256 shares, // Amount of shares burned
    uint256 underlying // Amount of underlying tokens withdrawn
);
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
/// @notice Emitted when an order is filled by a Pyth Oracle Maker.
///         It reveals information associated with the trade price.
event OMOrderFilled(
    uint256 marketId,
    uint256 oraclePrice, // In quote asset as wei, assume price >= 0
    int256 baseAmount, // Base token amount filled (from taker's perspective)
    int256 quoteAmount // Quote token amount filled (from taker's perspective)
);
```

{% endcode %}

#### Public functions (write)

{% code overflow="wrap" %}

```solidity
/// @notice Function is currently whitelisted.
///         Whitelist will be removed at a future date.
function deposit(uint256 amountXCD) external onlyWhitelistLp returns (uint256) {
        address depositor = _sender();
        address maker = address(this);

...
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
/// @notice Function is currently whitelisted.
///         Whitelist will be removed at a future date.
function withdraw(uint256 shares) external onlyWhitelistLp returns (uint256) {
        address withdrawer = _sender();

...
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
/// @notice Function should be called via the order gateway
function fillOrder(
        bool isBaseToQuote,
        bool isExactInput,
        uint256 amount,
        bytes calldata
    ) external onlyClearingHouse returns (uint256, bytes memory) {
        uint256 basePrice = _getPrice();
        uint256 basePriceWithSpread = _getBasePriceWithSpread(basePrice, isBaseToQuote);

        // - `amount` base -> `amount * basePrice` quote
        //   (isBaseToQuote=true, isExactInput=true, openNotional = `amount * basePrice`)
        // - `amount` base <- `amount * basePrice` quote
        //   (isBaseToQuote=false, isExactInput=false, openNotional = -`amount * basePrice`)
        // - `amount / basePrice` base -> `amount` quote
        //   (isBaseToQuote=true, isExactInput=false, openNotional = `amount`)
        // - `amount / basePrice` base <- `amount` quote
        //   (isBaseToQuote=false, isExactInput=true, openNotional = -`amount`)

        int256 baseAmount;
        int256 quoteAmount;
        uint256 oppositeAmount;

...
```

{% endcode %}

#### Public functions (read)

{% code overflow="wrap" %}

```solidity
/// @notice Read current pool utilization ratio
function getUtilRatio() external view returns (uint256, uint256) {
        if (totalSupply() == 0) {
            return (0, 0);
        }
    
        IVault vault = _getVault();
        int256 positionSize = vault.getPositionSize(_getOracleMakerStorage().marketId, address(this));
    
        if (positionSize == 0) {
            return (0, 0);
        }
    
        uint256 price = _getPrice();
        int256 positionRate = _getPositionRate(price);
        // position rate > 0, maker has long position, set long util ratio to 0 so taker tends to long
        // position rate < 0, maker has short position, set short util ratio to 0 so taker tends to short
        return positionRate > 0 ? (uint256(0), positionRate.toUint256()) : ((-positionRate).toUint256(), uint256(0));
    }

/// @param
function getUtilRatio() external view returns (
        uint256 longUtilRatio, 
        uint256 shortUtilRatio
    );
```

{% endcode %}

## Numeric Representation

* Pyth uses [fixed-point numeric representation](https://docs.pyth.network/documentation/pythnet-price-feeds/best-practices#fixed-point-numeric-representation).
* `PythOracleMaker` will translate Pyth price into its own native numeric representation: `wei`
* Assumes `oraclePrice >= 0`

## Run-time Dependencies

* [Pyth EVM contract addresses](https://docs.pyth.network/price-feeds/contract-addresses/evm)


# Spot Hedge Maker

{% hint style="danger" %}
Liquidity provision is whitelisted until initial beta testing has completed
{% endhint %}

## Overview

Spot hedge maker model is based on Hot Tub, vaults developed by Perpetual Protocol during 2022-2023. Spot hedge maker vaults are divided into Base (asset token, e.g. ETH, BTC) and Quote (settlement token, e.g. USDT) vaults.

The basic concept is that all taker trades made via this vault on the perpetual futures DEX are automatically hedged using tokens purchased on spot markets. So if a trader on Perp v3 opens a 1 ETH long, thus creating a 1 ETH short for the maker, the vault will automatically buy 1 ETH on spot markets to hedge the maker's position. The futures trade and the spot hedge occur atomically.

Requests to fill an order (`fillOrder()`) should be made via the [Order Gateway](/nekodex-playground/docs-for-devs/contracts/order-gateway).

## SpotHedgeBaseMaker

Each vault accepts liquidity deposits in one base asset (e.g. ETH, BTC), so each market has a distinct vault.

#### Taker opens short

Base vault sells an equal amount of base asset to hedge the maker's long.

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

#### Taker opens long

Base vault buys an equal amount of base asset to hedge the maker's long.

<figure><img src="/files/4Vwrd2flfbVGZ24FCxse" alt=""><figcaption></figcaption></figure>

### Utilization Ratio

{% code overflow="wrap" %}

```solidity
utilRatio = 1 - (assetBalance / assetLiability)

/// @notice Example
///         LP deposits 1 ETH, and taker opens a 1 ETH short
deposit 1 ETH → 
    assetLiability += 1 ETH
    assetBalance += 1 ETH
fillOrder(1 ETH short) → 
swap(1 ETH) →
     assetBalance -= 1 ETH
utilRatio = 1 - (0 ETH / 1 ETH) = 1
```

{% endcode %}

### Maker shares

Liquidity providers receive shares (similar to LP tokens) representing their stake in the liquidity pool. Shares must be redeemed to withdraw funds from the vault.

{% code overflow="wrap" %}

```solidity
totalAsset = assetBalance + accountValueAsAsset

/// @notice `totalShare` is updated on deposit and withdrawal
/// @notice Deposit
totalShare <- totalShare * (1 + deltaAsset / totalAsset)
deltaAsset > 0
assetBalance <- assetBalance + deltaAsset
assetLiability <- assetLiability + deltaAsset

/// @notice Withdraw
deltaAsset = totalAsset * deltaShare / totalShare
deltaShare < 0
deltaAsset < 0
assetBalance <- assetBalance + deltaAsset
totalShare <- totalShare + deltaShare
/// @notice `assetLiability` is updated in a similar way openNotional is updated when reducing position on the Exchange
assetLiability <- assetLiability * (1 - deltaShare / totalShare)
/// @dev Withdraw will revert if
abs(deltaAsset) > assetBalance
vaultMarginRatio < minMarginRatio // after withdrawal
```

{% endcode %}

## SpotHedgeQuoteMaker

{% hint style="warning" %}
Quote maker vaults are not currently available and will launch at a future date.
{% endhint %}

Quote vaults work the same way as base vaults, but in reverse. Each vault accepts liquidity deposits in one quote asset (e.g. USDT), so each market has a distinct vault.

## Circuit Breaker

Maker will stop filling orders if risk thresholds are reached. When called, `fillOrderCallBack()` will check `minMarginRatio` to ensure it is above the set threshold.

For details, see [Circuit Breaker](/nekodex-playground/docs-for-devs/contracts/circuit-breaker).

## `fillOrderCallBack()`

In many instances, a maker must withdraw funds from the vault to execute a spot trade. This is managed using the `fillOrderCallBack()` function and is currently executable by whitelisted users only.


# Maker Reporter

Reports the utilization ratio of each maker. This is required for borrowing fee calculation to ensure makers do not over-report their utilization ratio and receive more fees than they should.

## Contract

{% code overflow="wrap" %}

```solidity
function getUtilRatioFactor(
    uint256 marketId, 
    address receiver
)
/// @notice Return if long
returns (
    uint256 0,     
    uint256 defaultUtilRatioFactor
)
/// @ notice Return if short
returns (
    uint256 defaultUtilRatioFactor,     
    uint256 0
)
```

{% endcode %}


# Order Gateway

## Overview

The order gateway has two contracts

* DelayedOrderGateway
* orderGatewayV2 (used by front end and [API](/nekodex-playground/docs-for-devs/api))

DelayedOrderGateway is covered here; orderGatewayV2 is limited to use by the Perp v3 frontend and API (no external functions for direct contract interaction).

The order gateways have two key roles:

1. Route orders to the optimal liquidity source
2. Prevent trades from front-running the oracle using a 3 second delay

## Workflow

1. Call `createOrder()` to generate an order, including `createdAt` and `executableAt` timestamps
2. Wait for `executableAt()` timestamp
3. Call `executeOrder()` with `orderId` to execute a trade
4. Call `cancelOrder()` with `orderID` to cancel an unexecuted order

## Contract

<pre class="language-solidity" data-overflow="wrap"><code class="lang-solidity">struct DelayedOrder {
    DelayedOrderType orderType; // Types: OpenPosition or ClosePosition
    address sender; // Sender address
    uint256 <a data-footnote-ref href="#user-content-fn-1">marketId</a>; // See annotation
    uint256 createdAt; // block.timestamp
    uint256 executableAt; // block.timestamp + orderDelaySeconds
    bytes data;
}
</code></pre>

{% code overflow="wrap" %}

```solidity
/// @notice Create an order (but do not execute)
function createOrder(
    DelayedOrderType orderType, 
    bytes calldata data
) 

emit OrderCreated(
    orderId, 
    delayedOrder.sender, 
    marketId, 
    abi.encode(delayedOrder)
);
```

{% endcode %}

{% code overflow="wrap" %}

```solidity
/// @notice Execute an order (probably first call createOrder)
function executeOrder(
        uint256 orderId,
        bytes calldata makerData
)

returns (
        int256 base, 
        int256 quote
);
```

{% endcode %}

<pre class="language-solidity" data-overflow="wrap"><code class="lang-solidity"><strong>/// @notice Cancel unexecuted order
</strong><strong>function cancelOrder(
</strong>    uint256 orderId
)

emit OrderCanceled(
    orderId
);
</code></pre>

```solidity
/// @notice There are many public view functions available
function getCurrentNonce() public view returns (uint256) {
        return _getOrderGatewayStorage().nonce;
}

function getOrdersCount() public view returns (uint256) {
    return _getOrderGatewayStorage().orderIds.length();
}

function getOrderIds(uint256 start, uint256 end) public view returns (uint256[] memory) {
    return _getOrderGatewayStorage().orderIds.valuesAt(start, end);
}

function getUserOrdersCount(address taker) public view returns (uint256) {
    return _getOrderGatewayStorage().userOrderIdsMap[taker].length();
}

function getUserOrderIds(address taker, uint256 start, uint256 end) public view returns (uint256[] memory) {
    return _getOrderGatewayStorage().userOrderIdsMap[taker].valuesAt(start, end);
}

function getOrder(uint256 orderId) public view returns (DelayedOrder memory) {
    return _getOrderGatewayStorage().ordersMap[orderId];
}
```

[^1]: See [Contracts](/nekodex-playground/docs-for-devs/contracts#metadata)


# Quoter

The quoter contract provides price estimates using onchain data. Additional APIs will be exposed for accessing offchain prices, when available.

## Request a quote

`quote` takes the same parameters as [`ClearingHouse.OpenPosition`](/nekodex-playground/docs-for-devs/contracts/clearinghouse#openposition).

{% code overflow="wrap" %}

```solidity
function quote(
    IClearingHouse.OpenPositionParams calldata params
)

returns (
    int256, // Amount of base token
    int256 // Amount of quote token
)
```

{% endcode %}


# Vault

The Perp v3 vault is a collection of contracts responsible for holding and managing all user collateral (maker, taker).

## `Vault`

Deposit and withdraw.

{% code overflow="wrap" %}

```solidity
/// @notice `amountXCD` uses collateral token decimals (6 decimals for USDT)
function deposit(
    address trader, 
    uint256 amountXCD
)

function withdraw(
    uint256 amountXCD
)
```

{% endcode %}

Add / remove margin. Get `marketId` from [Contracts](/nekodex-playground/docs-for-devs/contracts#metadata).

{% code overflow="wrap" %}

```solidity
/// @inheritdoc IVault
/// @notice `amountXCD` uses collateral token decimals (6 decimals for USDT)
function transferFundToMargin(
    uint256 marketId, 
    uint256 amountXCD
)

function transferMarginToFund(
    uint256 marketId, 
    uint256 amountXCD
)
```

{% endcode %}

Read PnL, margin and other account data. Get `marketId` from [Contracts](/nekodex-playground/docs-for-devs/contracts#metadata).

{% code overflow="wrap" %}

```solidity
/// @notice Read pending (unrealized) PnL for a given market.
function getUnsettledPnl(
    uint256 marketId, 
    address trader
)
returns (
    int256 unsettledPnl
)

/// @notice Read `fund`; the user's free (usable) collateral balance.
function getFund(
    address trader
)
returns (
    uint256 fund
)

/// @notice Read position margin exclusive of pending fees, unsettledPnLetc.
function getSettledMargin(
    uint256 marketId, 
    address trader
)
returns (
    int256 marginWithoutPending
)

/// @notice Read total position margin
/// @dev margin = settledMargin + unsettledPnl
function getMargin(
    uint256 marketId,
    address trader
)
returns (
    int256 margin
)

/// @notice Read position free margin (removable margin)
/// @dev free margin = max(margin state + pending margin + settleable unsettled pnl, 0)
function getFreeMargin(
    uint256 marketId,
    address trader
)
returns (
    uint256 freeMargin
)

/// @notice Read position size
function getPositionSize(
    uint256 marketId,
    address trader
)
returns (
    int256 positionSize
)

/// @notice Read position open notional (position value in settlement token at time of position entry.
function getOpenNotional(
    uint256 marketId,
    address trader
)
returns (
    int256 openNotional
)

/// @notice Read position pending margin; margin after current unsettled PnL, borrowing fees, funding fees are settled.
function getPendingMargin(
    uint256 marketId, 
    address trader
)
returns (
    int256 pendingMargin
)
```

{% endcode %}

## `IMarginProfile`

{% code overflow="wrap" %}

```solidity
/// @notice Margin requirement types
enum MarginRequirementType {
    INITIAL,
    MAINTENANCE
}

/// @notice margin ratio = account value / open notional
function getMarginRatio(
    uint256 marketId, 
    address trader, 
    uint256 price
)
returns (
    int256 marginRatio
)

/// @notice free collateral (for withdrawal) = min(free margin, account value) - initial margin requirement
/// @notice See free collateral for trades below
function getFreeCollateral(
    uint256 marketId, 
    address trader, 
    uint256 price
)
returns (
    uint256 freeCollateral
)

/// @notice free collateral (for trades) = min(margin, account value) - initial or maintenance margin requirement
/// INITIAL is for increasing position, MAINTENANCE is for reducing position
function getFreeCollateralForTrade(
    uint256 marketId,
    address trader,
    uint256 price, // User supplied price (recommend using latest Pyth price)
    MarginRequirementType marginRequirementType
)
returns (
    int256 freeCollateralForTrade
);

/// @notice margin requirement = open notional * required margin ratio (initial or maintenance)
function getMarginRequirement(
    uint256 marketId,
    address trader,
    MarginRequirementType marginRequirementType
) external view returns (uint256);

/// @notice unrealized pnl = position value + open notional
function getUnrealizedPnl(uint256 marketId, address trader, uint256 price) external view returns (int256);

/// @notice account value = margin (note it should include unsettled pnl and borrowing fee) + unrealized pnl
function getAccountValue(uint256 marketId, address trader, uint256 price) external view returns (int256);

/// @notice the margin trader can use for trading. when positive, it's always greater than or equal to "free margin"
function getMargin(uint256 marketId, address trader) external view returns (int256);

/// @notice the margin trader can access in any cases. it may be less than margin when pnl pool doesn't has enough
/// liquidity for unsettled profit
function getFreeMargin(uint256 marketId, address trader) external view returns (uint256);

function getOpenNotional(uint256 marketId, address trader) external view returns (int256);

function getPositionSize(uint256 marketId, address trader) external view returns (int256);
```

{% endcode %}


# Dev FAQ

## Where's the API?

Please see [API](/nekodex-playground/docs-for-devs/api)

## What does \`error xyz\` mean?

Error code definitions can be found here: \<tbc - link to library hopefully?>

## What are the contract addresses?

Please see [Contracts](/nekodex-playground/docs-for-devs/contracts)

1. back-end api
2.
3. Order gateway info
4. get account info
   1. margin ratio
   2. position info
5. ethers

## How to calculate spread

WIP

## How to calculate fees

WIP


# API

You can use `ethers.js`, `viem` or similar tools to automate trading.

You can also retrieve data from The Graph; see [Subgraph](/nekodex-playground/docs-for-devs/api/subgraph).

## Create an order

#### Contract struct

For `marketID`, see [Contracts](/nekodex-playground/docs-for-devs/contracts#metadata)

{% code overflow="wrap" %}

```solidity
struct Order {
    ActionType action; // Order action, 0 for OpenPosition, 1 for ReduceOnly
    uint256 marketId; // See link above
    /// @notice Use `amount` and `price` to control slippage
    int256 amount; // Amount of base token, 18 decimals
    uint256 price; // Order price, 18 decimals
    uint256 expiry; // Expiry timestamp
    TradeType tradeType; // Fill type, 0 for Fill or Kill, 1 for Partial Fill
    address owner; // Order address (must be same as signer)
    uint256 marginXCD; // Margin amount for the order, decimals match collateral
    /// @notice `relayFee` is 0.10 USDT; in the future this fee will be queryable via API
    uint256 relayFee; // Relayer fee, decimals match collateral
    bytes32 id; // User generated; may not repeat
}
```

{% endcode %}

#### API Endpoint

{% code overflow="wrap" %}

```http
POST https://dcn9cxclqj1v1.cloudfront.net/production/place-order
```

{% endcode %}

#### Request

{% code overflow="wrap" %}

```json
{
"signedOrder": {
		"order": {
		    "action": integer,
		    "marketId": integer,
		    "amount": string,
		    "price": string,
		    "expiry": integer,
		    "tradeType": integer,
		    "owner": string,
		    "margin": string,
		    "relayFee": string,
		    "id": string, // length 66
    }
    "signature": string // length 132
  }
}
```

{% endcode %}

#### Response

{% code overflow="wrap" %}

```solidity
if success
{
  "isSuccess": true
}
else
{
  "isSuccess": false,
  "message": "Error message here"
}
```

{% endcode %}

## Cancel an order

Orders are cancelled using the signed order and orderID (not just orderID, since it would allow anyone to cancel another account's order).

#### API Endpoint

{% code overflow="wrap" %}

```http
POST https://dcn9cxclqj1v1.cloudfront.net/production/cancel-order
```

{% endcode %}

**Request**

```solidity
{
  "orderId": string, // length 66
  "signature": string // length 132
}
```

**Response**

```solidity
if success
{
  "isSuccess": true
}
else
{
  "isSuccess": false,
  "message": "Error message here"
}
```

## Examples

### Create order

<pre class="language-typescript" data-overflow="wrap"><code class="lang-typescript">const order = {
    action: 0,
    marketId: 0,
    amount: parseEther("1", 18),
    price: parseEther("100", 18),
    expiry: DateTime.now().plus({ minutes: 1 }).toUnixInteger(),
    tradeType: 1,
    owner: 0xbeef...,
    margin: parseEther("10", 6),
    relayFee: signedOrder.order.relayFee.toFixed(),
    id: signedOrder.order.id,
}

const domain = {
    name: "OrderGatewayV2",
    version: "1",
    chainId: publicClient.chain.id,
    verifyingContract: orderGatewayV2Proxy.contractAddress,
}

const typeWithoutDomain = {
    Order: [
        { name: "action", type: "uint8" },
        { name: "marketId", type: "uint256" },
        { name: "amount", type: "int256" },
        { name: "price", type: "uint256" },
        { name: "expiry", type: "uint256" },
        { name: "tradeType", type: "uint8" },
        { name: "owner", type: "address" },
        { name: "marginXCD", type: "uint256" },
        { name: "relayFee", type: "uint256" },
        { name: "id", type: "bytes32" },
    ],
}

const typedData = {
    domain: domain,
    types: typeWithoutDomain,
    primaryType: "Order",
    message: {
        action: order.action,
        marketId: order.marketId,
        amount: big2Bigint(order.amount, this.weiDecimals),
        price: big2Bigint(order.price, this.weiDecimals),
        expiry: order.expiry,
        tradeType: order.tradeType,
        owner: signerAddress,
        marginXCD: big2Bigint(order.margin, this.collateralDecimals),
        relayFee: big2Bigint(order.relayFee, this.collateralDecimals),
        id: order.id,
    },
}

const signature = signTypedData(walletAddress, order)

const body = JSON.stringify({
   signedOrder: {
       order,
      signature,
   }
})

await fetch(placeOrderApi, {
<strong>   method: "POST",
</strong>   body,
})
</code></pre>

### Cancel order

{% code overflow="wrap" %}

```typescript
const signature = signMessage({
      account: 0xbeef...
      orderId: 0xdead...
})

const body = JSON.stringify({
      orderId,
      signature,
})

await fetch(cancelOrderApi, {
      method: "POST",
      body,
})
```

{% endcode %}


# Subgraph

## Overview

Trading and other data is stored via The Graph. Query the subgraph using [GraphQL](https://thegraph.com/docs/en/querying/graphql-api/).

{% embed url="<https://subgraph.satsuma-prod.com/perp/lugia-optimism/playground>" %}

{% @github-files/github-code-block url="<https://github.com/perpetual-protocol/lugia-subgraph>" %}

## Examples

### `owedRealizedPnl`

Retrieve a trader's unrealized P\&L

```graphql
{
  traderProfiles(
    where: {
      trader:"0x6cf8aba4b2bc2cd9be2e78cf61ef617b02893502" // Lowercase only
      }
    )
  {
    owedRealizedPnl
    market {
      id
    }
  }
}
```


# Error codes

{% hint style="warning" %}
Content will show when Github repo is public
{% endhint %}

{% @github-files/github-code-block url="<https://github.com/perpetual-protocol/lugia-contract/blob/develop/src/common/LibError.sol>" %}


