# Welcome to Kwenta

Kwenta is a multichain perps marketplace offering [perpetual futures](/using-kwenta/perpetual-futures) on Optimism, Base, and Arbitrum. Kwenta integrates with leading derivatives liquidity protocols to bring you the most markets, best pricing, and deepest liquidity available onchain.

{% hint style="info" %}
Kwenta is a non-custodial platform, with users having full control over their assets.
{% endhint %}

{% hint style="success" %}
Optimism token address: [0x920Cf626a271321C151D027030D5d08aF699456b](https://optimistic.etherscan.io/address/0x920Cf626a271321C151D027030D5d08aF699456b)
{% endhint %}

## Copyright

Except where otherwise noted, the content in this documentation is licensed under a [Creative Commons Attribution-ShareAlike 4.0 International license](https://creativecommons.org/licenses/by-sa/4.0/).

### Start Trading

{% content-ref url="/pages/aCZUEcxJGwMNLDRW1HMv" %}
[Access Kwenta](/overview/access-kwenta)
{% endcontent-ref %}

{% content-ref url="/pages/zx6DVtwRNyB5alBSkgjE" %}
[How to start using Kwenta](/overview/how-to-start-using-kwenta)
{% endcontent-ref %}

### Products

{% content-ref url="/pages/Nxdd9qTKD2jN2jEdM3Dz" %}
[Broken mention](broken://pages/Nxdd9qTKD2jN2jEdM3Dz)
{% endcontent-ref %}

{% content-ref url="/pages/e6TdrkOL3zfVRmUOXDdI" %}
[Smart Margin](/using-kwenta/perpetual-futures/smart-margin)
{% endcontent-ref %}

{% content-ref url="/pages/l2GIql6FMJ2GbaPUDQoZ" %}
[Staking KWENTA](/kwenta-token/staking-kwenta)
{% endcontent-ref %}

### Decentralized Organization (DAO)

{% content-ref url="/pages/qgNcIo99JJwyD4dxBqRQ" %}
[Governance](/dao/governance-framework)
{% endcontent-ref %}

### Developers

{% content-ref url="/pages/q3M2WzDzyFGsu7A2Cf55" %}
[devDAO](/dao/devdao-contribute)
{% endcontent-ref %}

{% content-ref url="/pages/MWIiVT3DVQNl9XXIyhqJ" %}
[Contributing to the Kwenta Frontend](/dao/devdao-contribute/contributing-to-the-kwenta-frontend)
{% endcontent-ref %}

{% content-ref url="/pages/Z7UDwnHCyPfVqtnRqnol" %}
[Deployed Contracts](/developers/deployed-contracts)
{% endcontent-ref %}

#### Other Resources

{% content-ref url="/pages/eC2gZFza5UyZ5ilCXlUt" %}
[Kwenta Token](/dao/kwenta-tokenomics)
{% endcontent-ref %}


# How to start using Kwenta

## Things you can do on Kwenta:

* Buy or sell a growing number of synthetic assets&#x20;
* Trade with up to 25x leverage
* Stake KWENTA to receive inflationary rewards (coming soon)

## Benefits of using Kwenta

* Trade with **low gas fees and near-instant transactions** on Optimism
* Trading is 100% on-chain
* Chainlink oracle protected price data

You will need:

* Web3 wallet (See [Getting Started with DeFi](/overview/defi-what-is-it-how-do-i-start#benefits-of-defi) for help)
* ETH for gas and [sUSD](/overview/why-susd) to trade on the [Optimism layer 2 network](/overview/getting-started-on-optimistic-ethereum)
* Start trading!

> **Kwenta works different from traditional exchanges as it:**
>
> 1. Price feeds come from decentralized Chainlink oracles
> 2. There is no order book
>
> Instead, trades executed on Kwenta leverage the Synthetix debt pool (a huge pool of liquidity). This ensures that traders have the liquidity they need at any price point to execute trades. This model requires a liquid and immutable stable coin such as [sUSD](/overview/why-susd).

## To start trading, visit Kwenta

{% embed url="<https://kwenta.io>" %}


# Introduction

What does DeFi accomplish?

## What are Synthetic Asset

A synthetic asset is **a tokenized derivative that mimics the value of another asset**. Using a synthetic, you can trade $sXAG (Synthetic Gold) instead, which behaves like the underlying asset by tracking its price using data oracles such as [Chainlink](https://chain.link/) & [Pyth](https://pyth.network/).

## What is DeFi?

DeFi brings financial services to blockchains like Ethereum.

DeFi creates fair financial tools that anyone can utilize so long an internet connection is available. DeFi supports tools only banks could make available in the past; users can trade derivatives, options, borrow/lend funds.

## Benefits of DeFi?

* Assets are free to be transferred anywhere at any time.
* DeFi transactions 100% on-chain (transparent).
* Anyone can participate in DeFi by becoming a member of one of the DAOs which govern decentralized applications. A web3 wallet and an internet connection are all that's needed.

{% hint style="info" %}
For help accessing and setting up a web3 wallet -> [How to setup MetaMask guide](https://blog.kwenta.io/installing-metamask/).
{% endhint %}


# Getting started on Optimism

How to begin your optimistic journey

Ethereum Mainnet transactions are increasingly becoming expensive. This ongoing crisis birthed layer 2 scaling solutions like [Optimism](https://optimism.io).

Transactions are processed on a layer 2 network such as Optimism (a network built on top of Ethereum) instead of occurring directly on mainnet Ethereum. The layer 2 solution submits transactions in groups to the Ethereum Mainnet. They are then secured by Ethereums leading security, significantly reducing end-user fees and increasing transaction speed. Optimism states users can save up to 50x in transaction fees.

## Getting started with Optimism

Optimism provides near-instant transactions, lower transaction fees, while providing the same level of security as Ethereum.

{% hint style="info" %}
The upcoming steps assume you already have setup and funded a web3 wallet on Ethereum Mainnet. Make sure you add the [Optimism network](https://chainid.link/?network=optimism) to your web3 wallet. If you need help with setting up a wallet, please follow our [web3 setup guide](https://blog.kwenta.io/installing-metamask) and fund it with Ether (ETH).
{% endhint %}

## Moving assets to Optimism

Using Optimism requires users to bridge Ether (ETH) or other supported ERC-20 tokens to the Optimism network. Making use of the official [Optimism Gateway](https://gateway.optimism.io) bridge makes this process simple and intuitive.

![Main Optimism Bridge Screen](/files/stAVYGLrsWPWdZzI4wJP)

Connect your wallet by selecting `Connect` and select your web3 wallet provider. Make sure you are connected to `Ethereum Mainnet`.

![Select the connectivity option you would like to use](/files/izRrggvZk3uohewctFF6)

Once you connected your wallet to the Optimism bridge you can choose supported assets and the amount you wish to send over to layer 2 Optimism.

![Official Bridge to Layer 2 Screen](/files/WjgdApaNYCEuMkPoyPzE)

Finalize the bridge transaction by selecting `Deposit` and approve the transaction via your connected wallet.

![Deposit en Route Screen](/files/xOD4RWWdcxcXeFk5TAJ7)

The entire bridging process will take about 5-10 minutes, once complete you are ready to interact with dApps on Optimism.

## Withdrawing assets from layer 2

Withdrawing assets back to layer 1 or Ethereum Mainnet can be accomplished via the same [Optimism Gateway](https://gateway.optimism.io). Instead of selecting `Deposit` users instead use the `Withdraw` function.

{% hint style="info" %}
There are many bridging solutions available. Note that withdrawals processed via the official Optimism bridge are subject to a 7 day challenge period. Withdrawn funds will be unavailable until this 7 day period is complete. Alternatively users can use [other bridges](https://www.optimism.io/apps/bridges) for off-ramp purposes that don't require a 7 day challenge period.
{% endhint %}

![Withdraw from Layer 2 Ethereum](/files/r6qBkEIDiselVAGHt72w)

* <https://gateway.optimism.io/> - Official Bridge, however, withdrawals can take up to 7 days
* <https://hop.exchange/> - Fast Bridge Recommended
* <https://www.optimism.io/apps/bridges> - More bridges


# How to get sUSD

Explains why Kwenta uses and why traders need sUSD to utilize Kwenta

## Why do I need sUSD?

Kwenta quotes its asset prices against sUSD. Traders that want to purchase synthetic assets, open a Futures position, or leverage any of the financial tools provided by Kwenta will need to do so in sUSD.

Supporting sUSD helps Kwenta stay true to its decentralized ethos. sUSD is a fully decentralized stablecoin minted by [Synthetix](https://synthetix.io/), a decentralized liquidity protocol. sUSD, because of its decentralized issuance, cannot be muted, blocked, or stopped.

## Getting sUSD on Optimistic Ethereum

{% hint style="info" %}
In order to be able to get (swap) sUSD on Optimism you must have already bridged eligible ERC-20 tokens via a bridge. A tutorial how to use bridges [can be found here](/overview/getting-started-on-optimistic-ethereum).
{% endhint %}

First, head over to [Kwenta Exchange](https://kwenta.eth.limo/exchange/).

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

Connect your web3 wallet to Uniswap and make sure the `Optimistic Ethereum` network in your wallet is selected.

![](/files/bMFrdojLFvFmdvUHRynj)

Swap from any supported ERC-20 token to sUSD

{% hint style="info" %}
Remember to always keep some ETH in your wallet to pay for transaction fees
{% endhint %}

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

You now have sUSD to trade on [Kwenta.](https://kwenta.eth.limo/)


# Access Kwenta

Different way on how to access Kwenta

{% hint style="success" %}
The official DAO endorsed deployment can be accessed via [**https://kwenta.eth.limo**](https://kwenta.eth.limo) **(decentralized deployment) or** [**https://kwenta.io**](https://kwenta.io) **(centralized deployment)**
{% endhint %}

Copies of the Kwenta deployment, in case the endorsed deployment is not available, can be found at the following places:

* <https://kwenta.eth.limo>
* <https://kwenta.io>
* <https://bafybeie67qpog5obr334sxifvfrtkixc6dlnrpruhb7m2quildcm6usplm.ipfs.dweb.link/>

In order to access the IPFS deployment via the IPNS record, Brave Browser and/or the IPFS companion extension [might be needed](/overview/access-kwenta/installing-the-ipfs-companion-to-access-kwenta). Those can be access then by using the following:

* `ipns://kwenta.eth`
* `ipfs://bafybeie67qpog5obr334sxifvfrtkixc6dlnrpruhb7m2quildcm6usplm`

### Legacy Deployments

The old Synthetix Perpetual **Futures V1** contracts and its respective deployments can be accessed through:

* <https://v1.kwenta.eth.limo>

The old **isolated margin** deployment for Synthetix Perpetual **Futures** **V2** contracts can be found here:

* <https://bafybeig62jb5jhwwfh43mnrsojwqhxhgspm54nbjkvsgefribuvwnpt74m.ipfs.dweb.link/>
* `ipfs://bafybeig62jb5jhwwfh43mnrsojwqhxhgspm54nbjkvsgefribuvwnpt74m`


# Installing the IPFS Companion to Access Kwenta

This tutorial will guide you through the process of installing and configuring the IPFS Companion browser extension to access Kwenta. IPFS Companion is a powerful tool that enhances your browsing experience by connecting your browser to the decentralized web via the InterPlanetary File System (IPFS). By following these steps, you will be able to access Kwenta through IPFS.

{% hint style="info" %}
For its full functionality to be enabled, IPFS Companion requires a local IPFS node. As such, it is recommended that you have an IPFS node installed and running on your computer. Any one of the following will satisfy the requirement:
{% endhint %}

* [Install IPFS Desktop](https://docs.ipfs.tech/install/ipfs-desktop/)
* [Install IPFS Kubo for Go](https://docs.ipfs.tech/install/command-line/)
* [Install IPFS for JavaScript](https://docs.ipfs.tech/install/js-ipfs/)

{% hint style="warning" %}
You can still use IPFS Companion without a local node running, although you will lose some functionality, such as the ability to load websites with DNSLink via a gateway.
{% endhint %}

Step 1: Install the IPFS Companion browser extension

1.

```
| [Firefox ](https://www.mozilla.org/firefox/new/)\| [Firefox for Android](https://play.google.com/store/apps/details?id=org.mozilla.firefox)          | [Chrome ](https://www.google.com/chrome/)\| [Brave ](https://brave.com/)\| [Opera ](https://www.opera.com/)\| [Edge](https://www.microsoftedgeinsider.com/)                                    |
```

```
| ---------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [![Install From AMO](https://ipfs.io/ipfs/QmWNa64XjA78QvK3zG2593bSMizkDXXcubDHjnRDYUivqt)](https://addons.mozilla.org/firefox/addon/ipfs-companion/) | [![Install from Chrome Store](https://ipfs.io/ipfs/QmU4Qm5YEKy5yHmdAgU2fD7PjZLgrYTUUbxTydqG2QK3TT)](https://chrome.google.com/webstore/detail/ipfs-companion/nibjojkomfdiaoajekhjakgkdhaomnch) |
```

Step 2: Configure IPFS Companion settings

1. After installing the IPFS Companion extension, click on its icon in your browser's toolbar to open its settings.
2. In the settings menu, make sure "Public Gateway" is selected as the "IPFS Provider."
3. (Optional) Customize the "Public Gateway" field with a preferred IPFS gateway if desired. Otherwise, leave it as the default value.

Step 3: Access Kwenta using IPFS Companion

1. With IPFS Companion installed and configured, you can now access Kwenta through the IPFS gateway. In your browser's address bar, enter the following link: ipns\://kwenta.eth
2. The IPFS Companion extension will automatically redirect you to the IPFS version of the Kwenta website.
3. Enjoy seamless and decentralized access to Kwenta through the IPFS network!

By following these steps, you will have successfully installed the IPFS Companion browser extension and configured it for accessing Kwenta. Enjoy trading on the decentralized platform with the added benefits of the InterPlanetary File System.


# Backup RPCs

Data queries and transaction submissions are facilitated through an RPC (Remote Procedure Call) URL. Occasionally, the responsiveness of the RPC URL may be suboptimal, causing slow data loading or an inability to load data on your page. Additionally, exceeding the rate limit for the public RPC URL may result in 429 errors.

To maintain uninterrupted use of the exchange during such periods, you can opt for a backup URL from service providers like  [Alchemy](https://www.alchemy.com/), [Ankr](https://www.ankr.com/protocol/public/) or [QuickNode](https://www.quicknode.com/chains/arb). By changing the RPC URL in your wallet's network settings, the page should load properly. You can visit <https://chainlist.org/> to access a comprehensive list of RPC URLs and their respective statuses.

### Steps to change the RPC URL in MetaMask

* Click on the MetaMask icon
* Click on the three-dot icon and select `Expand View`
* Click on your account icon on the top right and select `Settings`
* Click on `Networks`
* Key in the New RPC URL
* Click `Save`

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


# Withdrawing from v2 Isolated Margin using Optimistic Etherscan

Kwenta v2 Isolated Margin has been deprecated with the release of Smart Margin v2. Users who did not withdraw before Isolated Margin was deprecated may still withdraw from the contracts using the Optimistic Etherscan interface.

### 1. Register on Optimistic Etherscan

To get started, please ensure you have registered for an Optimistic Etherscan account. It's free, and is required to use custom contract interactions.

{% embed url="<https://optimistic.etherscan.io/register>" %}
An Optimistic Etherscan account is required to use a custom ABI.&#x20;
{% endembed %}

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

### 2. Locate Your Deposit

Each market has its own a unique proxy contract address. If you know the contract address, simply navigate to the contract on Optimistic Etherscan.

> **Note:** Most users will find their deposit in the ETH market proxy contract:\
> <https://optimistic.etherscan.io/address/0x2B3bb4c683BFc5239B029131EEf3B1d214478d93>

If you don't know the contract address, you find it in the Synthetix Github. You can search for the correct address by searching the page for `PerpsV2ProxyETHPERP`. If you were trading another market, you'll need to replace the ticker in your search (for example, `PerpsV2Proxy1INCHPERP` if you were trading 1inch.

Ensure you've located the mainnet address (this should be the first result in your search), and follow the link directly to the contract on Optimistic Etherscan.

{% embed url="<https://github.com/Synthetixio/synthetix-docs/blob/master/content/addresses.md>" %}
Some proxy contracts are mislabeled on Etherscan. Follow the link directly from the Synthetix Github to locate the correct contract.
{% endembed %}

<figure><img src="/files/5LNe7TsdwxHV2SgZTLif" alt=""><figcaption><p>Search for your market proxy contract</p></figcaption></figure>

### 3. Locate the Custom Contract ABI

The contract code should list a Custom Contract ABI. To speed up the process, the `Custom Contract ABI` for all contracts has been copied below. \
\
Simply copy the text in the Custom ABI box below to your clipboard for use in the next step:

{% code title="Custom ABI" %}

```markup
[{"inputs":[{"internalType":"address payable","name":"_proxy","type":"address"},{"internalType":"address","name":"_marketState","type":"address"},{"internalType":"address","name":"_owner","type":"address"},{"internalType":"address","name":"_resolver","type":"address"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"bytes32","name":"name","type":"bytes32"},{"indexed":false,"internalType":"address","name":"destination","type":"address"}],"name":"CacheUpdated","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"int256","name":"funding","type":"int256"},{"indexed":false,"internalType":"int256","name":"fundingRate","type":"int256"},{"indexed":false,"internalType":"uint256","name":"index","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"timestamp","type":"uint256"}],"name":"FundingRecomputed","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"int256","name":"marginDelta","type":"int256"}],"name":"MarginTransferred","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"oldOwner","type":"address"},{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerChanged","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"newOwner","type":"address"}],"name":"OwnerNominated","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"bytes32","name":"trackingCode","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"baseAsset","type":"bytes32"},{"indexed":false,"internalType":"bytes32","name":"marketKey","type":"bytes32"},{"indexed":false,"internalType":"int256","name":"sizeDelta","type":"int256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"}],"name":"PerpsTracking","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"internalType":"uint256","name":"id","type":"uint256"},{"indexed":true,"internalType":"address","name":"account","type":"address"},{"indexed":false,"internalType":"uint256","name":"margin","type":"uint256"},{"indexed":false,"internalType":"int256","name":"size","type":"int256"},{"indexed":false,"internalType":"int256","name":"tradeSize","type":"int256"},{"indexed":false,"internalType":"uint256","name":"lastPrice","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fundingIndex","type":"uint256"},{"indexed":false,"internalType":"uint256","name":"fee","type":"uint256"},{"indexed":false,"internalType":"int256","name":"skew","type":"int256"}],"name":"PositionModified","type":"event"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"proxyAddress","type":"address"}],"name":"ProxyUpdated","type":"event"},{"constant":false,"inputs":[],"name":"acceptOwnership","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"}],"name":"closePosition","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"},{"internalType":"bytes32","name":"trackingCode","type":"bytes32"}],"name":"closePositionWithTracking","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"isResolverCached","outputs":[{"internalType":"bool","name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"marketState","outputs":[{"internalType":"contract IPerpsV2MarketState","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"messageSender","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"int256","name":"sizeDelta","type":"int256"},{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"}],"name":"modifyPosition","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"int256","name":"sizeDelta","type":"int256"},{"internalType":"uint256","name":"desiredFillPrice","type":"uint256"},{"internalType":"bytes32","name":"trackingCode","type":"bytes32"}],"name":"modifyPositionWithTracking","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"_owner","type":"address"}],"name":"nominateNewOwner","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"nominatedOwner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"owner","outputs":[{"internalType":"address","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"proxy","outputs":[{"internalType":"contract Proxy","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[],"name":"rebuildCache","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"recomputeFunding","outputs":[{"internalType":"uint256","name":"lastIndex","type":"uint256"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"resolver","outputs":[{"internalType":"contract AddressResolver","name":"","type":"address"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[],"name":"resolverAddressesRequired","outputs":[{"internalType":"bytes32[]","name":"addresses","type":"bytes32[]"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"internalType":"address","name":"sender","type":"address"}],"name":"setMessageSender","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"address payable","name":"_proxy","type":"address"}],"name":"setProxy","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"internalType":"int256","name":"marginDelta","type":"int256"}],"name":"transferMargin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[],"name":"withdrawAllMargin","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"}]
```

{% endcode %}

<figure><img src="/files/w1F7VuxAwOtr2StsWIe0" alt=""><figcaption><p>You'll copy and paste this data in the next step</p></figcaption></figure>

### 4. Add Custom ABI to Optimistic Etherscan

Using the data found on this contract page, we'll add a custom ABI to Optimistic Etherscan. This allows us to withdraw from the contract. You'll need to be logged in to complete this step.

{% embed url="<https://optimistic.etherscan.io/mycustomabi>" %}
A custom ABI can be added here
{% endembed %}

Click `+Add` to add your Custom Contract ABI, and enter the following information:

* **Name:** Enter a name to identify the contract. Any name may be entered.&#x20;
* **Address:** Copy the proxy contract address from the previous step, and paste it in this field
* **Custom ABI:** `Copy the Custom Contract ABI`to this field

<figure><img src="/files/rPfHJQk4olZCSNQPcSvX" alt=""><figcaption><p>Cut and paste the data to ensure accuracy</p></figcaption></figure>

### 5. Withdraw Margin

1. Navigate to the contract page and select **Connect to Web3** to connect your wallet.
2. Once connected, select **Write Custom** at the top of the page.
3. If the ABI was added correctly, you'll have access to the withdraw function. For the ETH market, this can be done at <https://optimistic.etherscan.io/address/0x2B3bb4c683BFc5239B029131EEf3B1d214478d93#writeCustomContract>.
4. Find the function **12. withdrawAllMargin** at the bottom of the page and select **Write** to withdraw all margin.

<figure><img src="/files/85lIh9OEHdEsDPCBg4s2" alt=""><figcaption><p>Ensue your wallet is connected and Write the function, 12. withdrawAllMargin</p></figcaption></figure>

These steps will guide you through withdrawing your funds from the deprecated Isolated Margin contracts using the Optimistic Etherscan interface. If you need additional assistance please open a ticket in [Discord. ](https://discord.gg/kwentaio)


# Futures on Kwenta

Kwenta currently offers sUSD-margined Futures. These Futures contracts offer the following:

* Settlement in sUSD-pegged assets are denominated and settled in sUSD.
* Expiration: Perpetual
* Pricing: Each Futures contract specifies the base assets quantity delivered for a single contract, also known as "Contract Unit." For instance, BTC/sUSD or ETH/sUSD Futures contracts represent only one unit of their respective base asset, similar to spot markets.

{% hint style="info" %}
sUSD will always be pegged to 1$ when using it to transact on Kwenta. Regardless of any 3rd party pricing.
{% endhint %}

### Advantages of sUSD-margined contracts

sUSD-margined contracts are linear futures quoted and settled in sUSD. One of the critical benefits of sUSD settlement is that traders can easily calculate their returns. This makes sUSD-margined contracts more intuitive. \
\
For example, when you make 500 sUSD in profit, you can easily estimate that the profit is worth approximately $500 - since the value of 1 sUSD is pegged closely to 1 USD. A universal settlement currency, such as sUSD, also provides more flexibility. You can use the same settlement currency across various Futures contracts.

This eliminates the need to buy the underlying coins to fund Futures positions. You will not incur additional fees as no additional conversion is required when trading with sUSD. In times of elevated volatility, sUSD-margined contracts help reduce the risk. Traders won't need to worry about hedging their underlying collateral exposure.

### Pros&#x20;

* Trading Futures allows one to profit from both the up and downside of an asset.
* Futures allow for the use of leverage. This is the most sought-after advantage, as traders can execute orders at a lower cost than the matching spot market price.
* It allows for advanced trading methods.

### Cons

* The high volatility in the crypto space can be a blessing or an agony. Market movement is something no one can guarantee. Due to the leverage involved, Futures is one of the most challenging trading tools. Traders, in turn, should trade them with a robust risk management strategy.
* Futures allow a trader to speculate on asset prices. Becoming familiar with the basics of Futures is a must. Futures trading can be lucrative if you apply risk management to avoid non-proportional losses.

In short, you should strategize and do your research before trading Futures and understand their advantages and risks. Trading Futures **can result in significant financial loss**; keep this in mind at all times:

{% hint style="warning" %}
Never invest more than you can afford to lose!
{% endhint %}


# Jargon

**Unrealized P\&L:** The unrealized P\&L is based on the difference between the average entry and oracle prices. It is a reference P\&L of a position.&#x20;

**Realized P\&L*****:*** This is based on the difference between a position's entry and close prices. Trading Fees and Funding Fees are also included in the realized P\&L.

[**Delayed Orders:**](/using-kwenta/perpetual-futures/delayed-orders) On Kwenta, all transactions are processed as delayed orders for up to 15 seconds.

[**Liquidation:**](/using-kwenta/perpetual-futures/liquidations) To keep the positions open, traders are required to hold a percentage of the value of their position, i.e., the maintenance margin percentage. If a trader fails to fulfill the maintenance requirement, their position will be flagged for liquidation, and any margin will be lost.

[**Initial margin:**](/using-kwenta/perpetual-futures/initial-maintenance-margin) Is the percentage of the purchase price of a future position that must be covered by cash or collateral when leverage trading.

[**Maintenance Margin:**](/using-kwenta/perpetual-futures/initial-maintenance-margin) This is the percentage of the purchase price of a future position that must be covered by cash or collateral when leverage trading.

[**Leverage:**](/using-kwenta/perpetual-futures/leverage) Leverage refers to using borrowed capital to make trades. Leverage trading applies a multiplier to your buying or selling power, allowing you to trade more significant amounts.

[**Funding Rate:**](/using-kwenta/perpetual-futures/funding) Funding rates are periodic payments to or from traders depending on their trade direction. Kwenta uses these rates to balance the skew of the Open Interest, be aware of these rates because they impact the daily holding cost of a perpetual contract position.

**Open Interest:** Open interest is the total number of outstanding derivative contracts, futures that have not been settled.

**Volume:** Volume is the total notional value being traded between market participants.

**Notional Position Size:** The notional value is the total amount of an asset's underlying value at its spot price. The notional value distinguishes between the amount of money invested and the amount of money associated with the whole position. The notional value is calculated by multiplying the units in one contract by the spot price.


# Synthetix Isolated Margin

Perps on Optimism

Perpetual futures, also known as perpetual swaps, are a type of derivative contract commonly used in the cryptocurrency market. They allow traders to speculate on the future price of an underlying asset, such as Bitcoin or Ethereum, without an expiration date. This makes them different from traditional futures contracts, which have a fixed expiry date and need to be settled or rolled over at that time.

Going long and going short are two crucial concepts in trading.

Going long, also known as buying, is a strategy where traders purchase an asset with the expectation that its value will increase over time. On the other hand, going short, also known as selling short, is a strategy where traders sell an asset with the expectation that its value will decrease over time. This strategy is often used in the market by traders who believe that a particular asset is overvalued and will eventually decrease in price.&#x20;

{% hint style="info" %}
To go short, traders usually borrow assets from someone else and sell them or, to repurchase them at a lower price in the future.
{% endhint %}

Here are some essential things to take note of before beginning your trading adventure:

<table data-view="cards"><thead><tr><th data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><a href="/pages/FTcJjUS0cMlTZBZxrFTE">/pages/FTcJjUS0cMlTZBZxrFTE</a></td></tr><tr><td><a href="/pages/Z3GaPhKPIvBwjn4PzL0c">/pages/Z3GaPhKPIvBwjn4PzL0c</a></td></tr><tr><td><a href="/pages/STJaK8zXhLT1RKC8gPHi">/pages/STJaK8zXhLT1RKC8gPHi</a></td></tr><tr><td><a href="/pages/LJCxahlwAMA4lZ6p9fk1">/pages/LJCxahlwAMA4lZ6p9fk1</a></td></tr><tr><td><a href="/pages/aHIM3zZDH55uAp1UyvKH">/pages/aHIM3zZDH55uAp1UyvKH</a></td></tr><tr><td><a href="/pages/HovPUFIjtiZnTZrHu58Z">/pages/HovPUFIjtiZnTZrHu58Z</a></td></tr><tr><td><a href="/pages/U0zR98qlWT79lxAThDsZ">/pages/U0zR98qlWT79lxAThDsZ</a></td></tr><tr><td><a href="/pages/yAQfNL2WOcDYLp2IBdFA">/pages/yAQfNL2WOcDYLp2IBdFA</a></td></tr></tbody></table>


# Funding

The funding rate and premium/discount mechanism on Kwenta is unique; we have compiled a page that aims to address these topics in a comprehensive manner.

🔸The basics of funding\
🔸Kwenta's unique mechanism

#### What is funding?

Funding can be likened to an interest payment in that it represents a percentage of your position size, after taking into account the impact of leverage, that is paid or received at regular intervals. When funding is positive, those with long positions pay those with short positions, whereas when funding is negative, those with short positions pay those with long positions.

#### Why does funding exist?

Funding exists because sometimes it's more attractive to hold one side of a trade. For every long, someone must be short. On Kwenta, Synthetix stakers take the other side of every trade. Funding rates attract traders on each side, balancing the skew.

<figure><img src="/files/7DpEin9cShVfPgyolq4i" alt=""><figcaption><p>1hr Funding rate displayed on Kwenta</p></figcaption></figure>

#### What are the risks?

Funding reduces the profitability of a trade and increases the risk of liquidation. For example, hourly funding of 0.01% is about 87% annualized. With liquidation buffers and fees, traders could be liquidated in about a year, even if the price remains flat. By using leverage, this risk is compounded. Since funding is charged on notional position size, the impact on your collateral is directly proportional to your leverage.

> For example, 100% annualized funding at 2x will liquidate traders in under 6 months. At 25x, about 2 weeks.

#### What are the advantages?

Just as traders pay funding, those on the opposite side of the trade collect funding. This can be a boost to PnL on directional positions or used as part of a more complex strategy. Common strategies include basis trading and funding rate arbitrage. These common strategies are Delta Neutral -- meaning short and long exposure is balanced.

In basis trading, a trader shorts positive funding and collects spot. In funding rate arbitrage, two perps positions are taken on different exchanges. Just as leverage increases the risks of funding, leverage also allows traders to increase their exposure to gains from funding payments.

#### How does funding work on Kwenta?

On Kwenta, funding is not directly proportional to skew, but instead, skew is used to calculate funding rate velocity.

📈 If the skew is long, funding goes up.

📉 If the skew is short, funding goes down.

⚖️ If the skew is neutral, funding stays the same.

This means that if the skew moves rapidly due to large traders entering and exiting, funding does not immediately change but will change over time if the skew remains. This also means some assets may settle and persistently positive or negative funding, even if the skew is neutral.

#### Why would Kwenta want this?

"Fair market" funding on assets is rarely zero. If the market is extremely bullish, "fair" funding may be positive. If an asset has high inflation, "fair" funding may be negative. Kwenta ensures "fair" pricing for both sides of the trade.

By creating a market for funding, Kwenta can find the point where longs and shorts are equally incentivized to take positions, balancing OI. This means higher OI caps and more assets without increased risk to liquidity providers, protecting system integrity.

Kwenta includes a premium or discount, which is directly proportional to the skew. Premium serves 2 functions.

🔸 Premium is the basis for price impact, which simulates order book liquidity. By simulating liquidity, Kwenta can accommodate large trades or lower liquidity assets.\
🔸 Premium provides added incentive for arbitrage traders, ensuring that OI is balanced and funding rate arbitrage remains attractive.

> Since this price impact is persistent, it makes no difference whether demand comes from a single trader, or many traders.

{% hint style="info" %}
Although this system is experimental, early results are promising. Skew on Kwenta is frequently neutral, resulting in low risk for LPs. This low risk should translate to future OI cap increases and additional asset listings without introducing significant systemic risk.
{% endhint %}


# Technical Details

***Premium/discount function***

The architecture outlined in this SIP takes a layered approach to risk management. Rather than leaning exclusively on funding payments to limit LP risk, a skew-dependent premium is applied to prices quoted by the market (premium for long skew, discount for short skew). By storing premium from takers (expanding skew) to adiabatically distribute to makers (compressing skew), this mechanism creates a high frequency rebalancing incentive while also placing soft limits on maximum exposure held by the debt pool (without the need for explicit restrictive OI limit). Simulating price impact in this way also increases compatibility for assets with a wider range of liquidity profiles and protects LPs from market manipulation.

***Funding rate velocity***

This model represents a mathematically minor adjustment to the current system, but with significant implications to the overall mechanism. Put simply, instead of `r = c * skew`, instead we have `dr/dt = c * skew`. In practice, the effect of this change is that funding rates will continuously drift higher/lower in the presence of uncorrected position imbalances, creating a natural price discovery mechanism for funding rates while simultaneously smoothing out funding rate trajectories. Another notable change is that with this mechanism, LPs would no longer exclusively earn funding (e.g. short skew + positive funding, LPs pay funding). Instead, funding flows through LPs without gain or loss over time (i.e. can be mathematically shown that net funding earned by LPs over time is zero). See plots below illustrating debt pool earning funding when `dr/dt > 0` while paying equal and opposite funding when `dr/dt < 0`

<figure><img src="https://user-images.githubusercontent.com/83029531/192562639-ca83bc05-6c32-4910-8536-55af9365a1d8.png" alt=""><figcaption></figcaption></figure>

<figure><img src="https://user-images.githubusercontent.com/83029531/192562723-90a548a5-89f2-4ba2-b6a9-f4ae2a68d160.png" alt=""><figcaption></figcaption></figure>

<figure><img src="https://user-images.githubusercontent.com/83029531/192562574-2f42c7f9-2ac6-4d2c-94e4-f96be611d945.png" alt=""><figcaption></figcaption></figure>

***Hybrid oracle approach***

This approach creates multiple execution tiers: (1) traditional execution through purely on-chain oracle, (2) asynchronous execution through on-chain oracle, or (3) asynchronous execution using off-chain oracle network whose validity is verified on-chain. Tier (1) is superior in composability, while tier (3) is superior in performance and execution efficiency (tier (2) is somewhere in between). With signed price updates made available off-chain, on-chain costs are only incurred when an exchange is made thus improving cost sustainability while also improving liveliness.

#### Technical Specification <a href="#technical-specification" id="technical-specification"></a>

*Find more details at* [*https://sips.synthetix.io/sips/sip-279/*](https://sips.synthetix.io/sips/sip-279/)


# Delayed Orders

On Kwenta, all transactions are processed as delayed orders. These delayed orders function similarly to market orders but incorporate a time delay. Some may remember the next-price order system in our perps v1 implementation. These delayed orders improve on this mechanism. &#x20;

Instead of executing a 'next-price' order following a Chainlink price update, the system now allows the executor (either a trader or a keeper) to complete the transaction after a specified number of seconds have elapsed.

{% hint style="info" %}
Delayed order waiting periods are specific to each available market. Orders are currently executable after 1 second on ETH-PERP and BTC-PERP markets, and 2 seconds on all other markets.
{% endhint %}

Once a delayed order fails to execute within this set time window, it goes stale. Once stale, the order needs to be canceled in order to place another, as traders can only have one active delayed order per market.

{% hint style="info" %}
Once stale, the order cannot be canceled until 60 seconds have passed since going stale.
{% endhint %}


# Maker/Takers on Kwenta

### Traditionally

In derivatives trading, makers are traders who create orders that add liquidity to the market, while takers are those who accept those orders, taking liquidity away, commonly via an order book system. Makers help keep the market running smoothly by ensuring there are enough orders (liquidity) on the order books, while takers help execute those orders and keep the market active.

{% hint style="info" %}
Often, makers will receive a discount for having preset "resting" orders (liquidity) executed vs. market buying (taking) liquidity.
{% endhint %}

> Imagine you're at a lemonade stand in a marketplace. The people who set up the stand and put up a sign with the lemonade price are like "makers" in derivatives trading. They create offers in the market, providing liquidity. The people who come to buy the lemonade at the displayed price are like "takers." They accept the offers created by makers, quickly filling orders and removing liquidity.

### On Kwenta&#x20;

Kwenta uses an automated market maker, or AMM, which fills all orders at a skew-adjusted oracle price by leveraging the Synthetix liquidity pool. In the Kwenta system, "maker" orders are those placed against the [current market skew](/using-kwenta/perpetual-futures/funding#how-does-funding-work-on-kwenta), which results in a trader paying lower maker fees. "Taker" orders are placed with the skew, and result in higher taker fees. If a trade causes the overall market skew to change from positive to negative, a trader may have an order partially filled at each fee tier.&#x20;

[To understand the fees you will pay on a trade, check the market skew as demonstrated below, or see the estimated fee in the trade preview.](#user-content-fn-1)[^1]

<figure><img src="/files/LH6hp03YZtGGuneu6nzU" alt=""><figcaption><p>FLOW-PERP is skewed $4,000 short</p></figcaption></figure>

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

The market above has $4,000 higher short open interest than long open interest, indicating a short skew of $4,000.&#x20;

* All short traders will pay taker fees.&#x20;
* Long traders up to $4,000 will pay maker fees.&#x20;
* A long trader opening a trade larger than $4,000 will pay maker fees on the first $4,000, and taker fees on the remaining size of the position.
  {% endhint %}

[^1]:


# Leverage

Leverage, a fundamental concept in finance, refers to the practice of using borrowed capital to amplify a position size. This financial tool enables market participants to control larger positions than their initial investment would allow, magnifying the outcome of their trades. Utilizing leverage is prevalent across various financial instruments, including crypto.

The primary advantage of leveraging lies in its capacity to enhance potential returns. With a relatively small initial investment, traders can achieve considerable market exposure, which can lead to substantial profits if the investment's value increases. In this sense, leveraging allows investors to maximize their returns on successful trades without committing additional capital.&#x20;

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

{% hint style="info" %}
Kwenta currently allows for 25x leverage, allowing someone with 100$ in initial margin to open a trade worth $2,500.
{% endhint %}

**Note that leverage is a double-edged sword!**

While it can amplify potential profits, it also magnifies potential losses. As the level of leverage increases, so does the degree of risk, which means that traders employing leverage may experience total losses of their initial investment, also known as liquidation.

Prudent use of leverage necessitates effective risk management. Traders should carefully assess their risk tolerance and employ strategies to mitigate potential losses. These strategies may include setting stop-loss orders, which automatically close a position if the asset's price reaches a predetermined level, or position sizing, which involves adjusting the size of a trade based on the investor's risk tolerance and the specific characteristics of the investment.&#x20;

{% hint style="info" %}
While leverage presents opportunities for enhanced returns, it also carries the potential for significant losses, making it imperative for traders to approach this financial tool with caution and employ effective risk management strategies.
{% endhint %}


# Liquidations

Liquidations in futures trading refer to the forced closure or unwinding of a trader's open futures position due to insufficient margin or collateral to cover potential losses.&#x20;

Liquidations in futures trading happen for several reasons:

1. Margin requirements: When trading futures, traders are required to deposit a certain amount of money, called margin, as collateral to enter into a contract. This margin acts as a safety buffer to ensure that both counterparties can meet their obligations in the event of adverse market movements. The margin consists of two components: the initial margin and the maintenance margin. The initial margin is the amount required to open a futures position, while the maintenance margin is the minimum amount of equity that must be maintained in the account to keep the position open.
2. Market volatility: Unexpected price movements or increased market volatility can cause the value of a futures position to decrease rapidly. If the account balance falls below the maintenance margin, the trader will receive a margin call, requiring them to either deposit additional funds or close their positions to meet the margin requirements. Failure to do so may lead to liquidation, wherein the broker forcibly closes the trader's open positions to protect against further losses.
3. Leverage: Futures trading involves leverage, which amplifies both profits and losses. While leverage allows traders to control larger positions with a smaller amount of capital, it also increases the risk of liquidation. A highly leveraged position can quickly lead to significant losses if the market moves against the trader, causing their account balance to fall below the maintenance margin level.

In summary, liquidations in futures trading occur when traders fail to maintain the required margin levels due to market volatility and leverage.


# Initial/Maintenance Margin

Margin requirements play a crucial role in ensuring the stability and efficiency markets, particularly in the context of trading leveraged instruments such as futures, options, and other derivatives. Initial and maintenance margins serve as risk management tools that protect market participants and platforms from potential losses due to severe adverse market movements.

**Initial margin**\
Refers to the minimum amount of collateral that traders must deposit with their exchange to open a leveraged position. This deposit serves as a safety buffer, ensuring that traders can meet their obligations.

Calculation: The initial margin is typically calculated as a percentage of the total value of the position. This percentage varies depending on the traders selected leverage.&#x20;

> If a trader wants to open a $100,000 position with a 25x leverage modifier, they would need to deposit $5,000 as collateral.

**Maintenance Margin**\
The maintenance margin is the minimum amount of equity that traders must maintain in their account to keep their leveraged positions open. If the account balance falls below the maintenance margin, traders may face a margin call, requiring them to either deposit additional funds or close some or all of their positions to meet the margin requirements.

Calculation Similar to the initial margin, the maintenance margin is calculated as a percentage of the total value of the position. This percentage is usually lower than the initial margin requirement, allowing for some fluctuations in the market value of the position.&#x20;

> For instance, if the maintenance margin is set at 150 bps or 1.5% for a $100,000 position with $5000 in initial margin, the trader must maintain an account balance of at least $1,500 to avoid a margin call.


# One-Click Trading

One-click trading (1CT) removes the need to interact with a wallet when submitting transactions, reducing the time and user actions required to trade.&#x20;

It does this through the use of two new mechanisms:

* 1CT wallet
* Trade delegation

When utilizing 1CT, please be aware that each "enabled session" is unique to the particular browser you are using. These sessions cannot be moved or used across different browsers or devices. While you can have multiple instances open, they will all access the same 1CT account and use the ETH you have deposited there.&#x20;

Each session's key is stored in the local storage of the specific browser in use. Therefore, if you decide to use a different browser or switch devices, you will have to enable a new session on each new browser or device you use.

#### 1CT Wallet

Kwenta uses a derived externally owned account (EOA) wallet for submitting trading transactions.&#x20;

It relies on the following sequence:

* Creating a Smart Margin Account
* Creating & delegate trading rights to your 1CT account
* Funding the 1CT account with ETH
* Activating the session

#### Trade Delegation

Kwenta Smart Margin supports a delegation feature, allowing EOAs to submit transactions on behalf of other EOAs.

To delegate trading to another EOA, a trader must approve the address as a delegate through the trading contract.&#x20;

#### Get Started with 1CT Now!

{% content-ref url="/pages/C3FrW4ONl4uo2j1tKBAJ" %}
[Onboarding to 1CT](/using-kwenta/perpetual-futures/one-click-trading/onboarding-to-1ct)
{% endcontent-ref %}


# Onboarding to 1CT

Get started with your seamless trading experience

The onboarding experience:

* Create a Smart Margin Account \
  \*If you don't have one, creating one is easy!
* Create 1CT account\
  *\*This creates, and delegates trade rights to your 1CT wallet*
* Fund 1CT wallet
* Enable feature

### <mark style="color:yellow;">**Step 1**</mark>**&#x20;- Finding the 1-Click Trading Feature**

To start, navigate to kwenta.eth.limo and bring up the account management interface by selecting "Deposit Funds."

{% hint style="info" %}
If sUSD is available in your margin account, the "Deposit Funds" button will be called "Manage"
{% endhint %}

<figure><img src="/files/FvnicnQVRt6LkqGCkNeb" alt=""><figcaption><p>Find the new One-Click Trading Feature</p></figcaption></figure>

Once in the manage interface and on the One-Click Trading tab, you will have two options:

* One-Click Trading
* Sign Every Transaction

Select One-Click Trading and select "Activate One-Click Trading"

### <mark style="color:yellow;">**Step 2**</mark>**&#x20;- Create a 1-Click Trading Account**

Confirm your selection of One-Click Trading and select Activate!

<figure><img src="/files/MosFqn41OJ53ovc80ovl" alt=""><figcaption><p>Step 1 in the activation will add an account delegate</p></figcaption></figure>

Success! You've created a 1CT account.

### <mark style="color:yellow;">**Step 3**</mark>**&#x20;- Fund your 1CT account with ETH**

It's time to fund it with $ETH. Select the "Fund" tab. Some things to note on this window are:

* You're 1CT wallet address
* You're 1CT trade account ETH balance\
  \**Without ETH in the 1CT account no transactions will execute*

<figure><img src="/files/sTq2LbJI4bALb16vDGKV" alt=""><figcaption><p>Fund your 1CT account with ETH</p></figcaption></figure>

Funding your account with ETH is easy. You can either enter a custom amount of ETH to deposit for transaction fees or select one of the predefined amounts.

> We've included an estimated transaction amount based on your deposited amount of ETH.

Select how much ETH you'd like to deposit and execute the transaction.

### <mark style="color:yellow;">**Step 4**</mark>**&#x20;- Starting 1CT**

<figure><img src="/files/K1chkqJXyNqGJa31NZ0G" alt=""><figcaption><p>Select a session length &#x26; activate the 1CT Trade Session</p></figcaption></figure>

The last step is to enable the 1-Click Trading session. Select how long you would like your session to last from the Duration dropdown and sign the transaction once enable is clicked.

### <mark style="color:yellow;">**Step 5**</mark>**&#x20;- Execute Trades without the need to Sign**

<figure><img src="/files/LgXYOaLSnerVMoVSRmHQ" alt=""><figcaption><p>Execute trades without signing</p></figcaption></figure>

You can now trade on Kwenta without signing every transaction so long as "Open Trade with One-Click Trading" is selected.&#x20;

{% hint style="info" %}
Should 1CT not work, traders can unselect "Open Trade with One-Click Trading" and execute transactions traditionally.
{% endhint %}

### <mark style="color:yellow;">Disabling</mark>

To disable 1CT, simply repeat step 1 above but select the ***Sign Every Transaction*** mode instead of 1CT. Users can revert to manually signing every action on Kwenta as often as they like.&#x20;


# FAQ

**Are trades opened against my 1CT wallet?**\
No, they are opened against your Smart Margin wallet.

**Do I have to have 1CT enabled to interact with trades I opened with it?** \
No, you may toggle the feature on and off whenever you'd like.

**Can I use the same 1CT wallet on multiple devices?**\
No, currently, each enabled instance is its own siloed environment&#x20;

**What if my transaction is stuck?**\
In your web3 wallet, you'll find a transactions list. Here, you may speed up and/or cancel a stuck transaction.

**How do I cancel/end a session?**

With an active session, head back to the manage account interface and navigate to One-Click Trading. The "enable" button during setup will now be a "disable" button.

**Gas Deposits?**

1CT trading still requires traders to pay Ethereum transaction fees, thus requiring traders to deposit and maintain an adequate amount of ETH to use it.

**Withdrawing ETH from 1CT?**

Traders can withdraw any remaining ETH in the 1CT manage interface. Navigate to the withdraw tab and withdraw as much ETH as needed.


# Smart Margin

Trade any market with a single account using Smart Margin

Kwenta's on-chain margin engine "Smart Margin" offers a comprehensive suite of tools for trading derivatives powered by Synthetix. Smart Margin (SM) accounts utilize a script-like trading language that defines ordered commands (or steps) to be batch executed by the trader in a single transaction.&#x20;

The command structure supports unrestricted interactions with Synthetix (like modifying position margin and size across multiple markets) and other protocols integrated into the engine. Commands ranging from depositing margin from an EOA to the SM account and executing swaps via Uniswap's UniversalRouter can all be scripted in whatever order the trader desires.

<figure><img src="/files/XGsP8YIZ3MiEHWkjTVBZ" alt=""><figcaption><p>Smart Margin Command Execution Flow</p></figcaption></figure>

Furthermore, given the upgradable nature of the SM system, future protocol integrations can happen seamlessly without disrupting the functionality already offered.

<figure><img src="/files/MXqPzB9vGgHkdOHveRSh" alt=""><figcaption><p>Smart Margin Account Proxy Architecture</p></figcaption></figure>

Additional details concerning protocol architecture and direct usage can be found in the [README](https://github.com/Kwenta/smart-margin/blob/main/README.md). A complete list of supported commands and related inputs can be found in our Smart Margin [wiki](https://github.com/Kwenta/smart-margin/wiki/Commands). Finally, specific interaction flows have been tested natively in solidity [here](https://github.com/Kwenta/smart-margin/blob/main/test/integration/margin.behavior.t.sol) and offer a great starting place for anyone looking to integrate Kwenta's margin engine.

<figure><img src="/files/K6CHlhIEFydnyM3bk7R5" alt=""><figcaption><p>Smart Margin Account Creation UI</p></figcaption></figure>

<table data-view="cards"><thead><tr><th data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><a href="/pages/hiwPZweFedVMqdOrH598">/pages/hiwPZweFedVMqdOrH598</a></td></tr><tr><td><a href="/pages/Ek7gKxNYvyqcVJuxHA8J">/pages/Ek7gKxNYvyqcVJuxHA8J</a></td></tr><tr><td><a href="/pages/MsTb5Gyegpbswz97mTCq">/pages/MsTb5Gyegpbswz97mTCq</a></td></tr><tr><td><a href="/pages/dRFvi1mtiRoI5RrG5cAh">/pages/dRFvi1mtiRoI5RrG5cAh</a></td></tr><tr><td><a href="/pages/3kGsxePENrGSE0yYnJNL">/pages/3kGsxePENrGSE0yYnJNL</a></td></tr></tbody></table>


# Dashboard Overview

How to use cross margin on Kwenta

### Dashboard

Below, you'll find the main dashboard for Futures on Kwenta; from here, you'll get an overview of everything Futures, any open positions, and markets available to trade.

Smart margin is the default margin type when traders come to Kwenta. If you find yourself needing to switch between isolated margin and Smart Margin, hit the `Futures` tab at the top left and select either `Isolated Margin`or`Smart Margin.`

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

1. The menu section contains links to other pages inside of Kwenta..
2. Displays Current Portfolio value along with a chart over time
3. A quick overview of any open positions a trader currently has.
4. The Watchlist and be accessed here (controlled by what assets you have in your favorites)
5. An overview of any open orders


# Futures UI Overview

### **Understanding the Kwenta Futures Trading Interface**

<figure><img src="/files/UB9EL4mOmcZSDi9etSO3" alt=""><figcaption><p>Futures Overview Page</p></figcaption></figure>

1. Trade history on a given asset with an optional toggle to hide this panel.
2. Price chart of the chosen contract. As well as market details:

* **Market Price** - Adjusted price, including premium/discount for the asset, based on skew
* **Index Price** - Raw asset price provided by Pyth with no skew adjustments
* **24H Change** - Dollar amount change of an asset on a rolling 24h basis
* [**Funding Rate**](/using-kwenta/perpetual-futures/funding) - A continuous funding rate is levied on Kwenta and is charged every block. Longs pay shorts when funding is positive, and shorts pay longs when funding is negative. Funding is designed to incentivize balanced open interest. Skew is not directly proportional to funding, but impacts funding rate velocity. If skew is positive, funding is increasing, and if skew is negative, funding is decreasing.
* **Open Interest** - The total size of all outstanding positions on either side of the market
* **Skew -** The balance between long and short open interest. Positive skew means longs outnumber shorts, and negative skew means shorts outnumber longs.

4. **Market Selector** - Select the asset you wish to trade
5. Order entry panel. Place orders either Long (Buy) or Short (Sell). Enter the amount of collateral you wish to allocate and specify how much leverage to apply.

* Account Details
  * **Free Account Margin** - Total amount of unused (available) sUSD in your CM account&#x20;
  * **Market Margin** - sUSD collateral allocated to the selected markets position
  * **Margin Usage** - Percentage of margin used across all markets&#x20;
  * **Account ETH Balance** - Cross-Margin ETH balance **(users will need to deposit .01 ETH into the cross-margin account, to execute advanced orders)**
* **Order Type**
  * [Market](/using-kwenta/perpetual-futures/delayed-orders) - Execute a delayed market order at current price
  * [Limit order](/using-kwenta/perpetual-futures/smart-margin/trading-on-kwenta/conditional-orders/limit-orders) - Set an entry order to execute at a specified trigger price
  * [Stop-market](/using-kwenta/perpetual-futures/smart-margin/trading-on-kwenta/conditional-orders/stop-loss-orders) - Increase or decrease risk by setting a **trigger price once the asset has traded at or through a specified price** (the "stop price"); the order will execute
* [Fee Details](/using-kwenta/perpetual-futures/exchange-fees)&#x20;
  * **Protocol Fee** - Fees imposed by Synthetix for making use of their liquidity
  * **Keeper Fee** - $2 Fee paid to the person or robot executing and orders as delayed market orders. &#x20;
  * **Total Fees** - Sub-total of all fees to execute an order

**​5.** Pertinent information pertaining to your open position. It allows you to navigate between your position, (open) orders, trades, and transfers (deposits and withdrawals).

* **Asset name** - Displays the open positions asset, e.g. ETH-PERP, and its current value in sUSD
* **Position Direction** - Long or Short
* **Total Position size** - In asset denomination and its current sUSD value
* **Entry Price** - Average executed buy/sell price for your current position
* **Liquidation Price** - If the oracle price of the contract reaches the liquidation price when long or short, your position will be liquidated
* **Unrealized P\&L** - Displayed in sUSD and a percentage and is profit and or loss that hasn't been settled yet
* **Net Funding Rate** - Displays the current funding rebated or paid up until this point
* **TP/SL** - Displays any take profit and stop losses set for the open position


# Get Started with Smart Margin

How start trading with Smart margin on Kwenta

### Getting Started <a href="#getting-started" id="getting-started"></a>

Select Futures in the navigation tab to begin.

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

### Connecting Your web3 wallet <a href="#connecting-your-web3-wallet" id="connecting-your-web3-wallet"></a>

If your wallet isn’t already connected, you’ll want to hit **‘Connect wallet’** at the top right of the screen and follow any MetaMask prompts.

### **Create your Smart Margin Account**

Upon initiating your inaugural trade utilizing the Smart-Margin feature, you will be prompted through the onboarding procedure, during which you will:

* Step 1: Create your account&#x20;
* Step 2: Authorize the contract to spend sUSD.
* Step 3: Complete thefirst deposit and proceed to opening your position

{% hint style="info" %}
In order to trade, make sure you are using a minimum of at least $50 sUSD.
{% endhint %}


# Withdrawing sUSD & ETH

How to withdraw funds from Smart & Isolated Margin

### Withdrawing sUSD

From the dashboard, select where you need to deposit or withdraw sUSD by picking either Isolated or Smart Margin.

{% hint style="info" %}
Isolated Margin will require you to deposit/withdraw sUSD for every perp market you trade or last traded.
{% endhint %}

Once you've selected your margin type & make sure the correct wallet is connected, you can easily withdraw funds in your smart margin wallet by selecting `Manage` in the order entry panel.

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

A modal will appear in which you can select to withdraw sUSD in or out of individual perps markets if trading isolated markets or a Smart Margin account.

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

### Withdrawing Account ETH

Any ETH in your Smart Margin account that hasn't been used to execute advanced orders can easily be withdrawn by:

* Selecting the pencil next to `Keeper balance`
* Select the amount to withdraw and complete the transaction

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


# Opening/Closing Positions

### Opening a position

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

* **Trade Type** and whether it is **long (buy) or short (sell)**.
  1. **Market:** To be used to open a trade immediately via a delayed market order.
  2. **Limit**: To be used when you want to go long at a lower price than present or to go short if the price reaches a higher price than present.&#x20;
  3. **Stop:** To be used when you want to go long if the price reaches a higher price than present (breakup) or to go short if the price reaches a lower price than present (breakdown).&#x20;

{% hint style="info" %}
Conditional orders execute at an exact price, if the price reaches the condition. Fill may slightly vary depending on the Oracle price at the time the delayed order execution is complete.
{% endhint %}

* **Collateral:** Maximum amount you are risking if you are liquidated. Your collateral to open your planned trade.
* **Leverage/Positions Size:** Traders can either pick a leverage multiplier or set their position size changes in one field will always correspond with changes in the other.
* **Your Stop Loss and Take Profit.** You are not obligated to use a stop loss, but this allows you to set up the entire trade before submitting an order.

### Closing an open position

{% hint style="info" %}
Closing an open position if all margin is exhausted or the trader doesn't have enough margin to reserve to execute the trade, the close has to be done through the `close position` modal by selecting `close` on the positions table on an open position.
{% endhint %}

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

Traders can only close a position by opening the opposite direction of the current trade only if they have sufficient margin for the order to reserve for execution.


# Conditional Orders

Leveraging Gelatos keeper system, Kwenta can automate advanced orders through Smart Margin. The first two products to come out of this will be limit and stop-market orders. [**Gelato Network**](http://gelato.network/) is a decentralized network of keepers used by web3 apps to automate smart contract executions on all major public EVM-compatible blockchains, including Optimism. Using Gelato gives Kwenta peace of mind when it comes to automating and relaying transactions with confidence.

Keepers can do things like execute limit orders, liquidate an under-collateralized position, on-chain, and autonomously. Automated keeper are set in place to automatically execute advanced orders when their conditions are met. Due to this development, there is no manual intervention needed from traders on Kwenta to execute orders on Kwenta.

{% hint style="success" %}
Using advanced orders on Kwenta will automatically deposit **0.01 ETH** into your margin accounts Keeper. This ETH will be used to pay the blockchain transaction cost when Gelato submits your order.
{% endhint %}

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

{% hint style="danger" %}
Anytime your account ETH balance is less than 0.01 ETH, the next advanced order you place will deposit enough ETH to restore it back to the 0.01 ETH (if available). At any time, traders can withdraw this ETH back to their wallet by selecting the `up arrow` and completing the withdrawal transaction.
{% endhint %}

### Why does Kwenta need to deposit 0.01 ETH?

Transaction costs on Optimism generally range between 0.05$ and 0.50$, depending on the type of transaction and current gas price conditions on L1.  At the current value of about 13$ for 0.01 ETH (as of October 2022), the deposit should allow a trader to execute approx. twenty advanced orders with ease.&#x20;

{% hint style="info" %}
To ensure that your advanced order transactions are being executed by the Keeper even under extremely volatile market conditions, a buffer of 0.01 ETH has been implemented to ensure timely execution and avoid failed advanced order transactions.
{% endhint %}


# Limit Orders

What is a limit order and how to execute it

A Limit order is an order to buy or sell a given asset at a specified (or better) price. A limit order to buy will only execute at the limit price or lower, and a limit order to sell will only execute at the limit price or higher.

<figure><img src="/files/ppq1bFWZLem5EqwvG9na" alt=""><figcaption><p>Limit Orders on Kwenta</p></figcaption></figure>

{% hint style="danger" %}
Advanced orders are only available on cross margin & have a minimum keeper requirement of 0.01 ETH.
{% endhint %}

### Place a Limit Order

1. Select the asset you are going to trade in the asset selector drop-down
2. Choose a side, either long or short
3. Pick an order type (limit order)
4. Input your desired Collateral
5. Enter your limit price in the price field&#x20;
6. Input your position size
7. Click on `Place Limit Order`

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

{% hint style="info" %}
The submission of the limit order is done on-chain, so any margin required to open this order will be earmarked until the order is canceled. The transaction will automatically deposit the 0.01 ETH account requirement, if applicable.
{% endhint %}

Once you’ve executed the transaction, the order will appear under the `Orders tab`. When the **Chainlink Oracle price** reaches the limit price, the order will be executed, and your position will be opened.&#x20;

{% hint style="info" %}
The execution price of a limit order may differ depending on oracle price. There are no partial fills with advanced order types, and limit orders will either be fully executed or not at all. Once a limit order has been executed, it will be shown in the Trades column.
{% endhint %}

### Cancel a Limit Order

If you want to cancel a limit order before it has been executed, then click the `orders tab` and hit `Cancel` on the order that you wish to discard.   As mentioned above, cancellations are done on-chain, so this will carry a gas fee.&#x20;

{% hint style="success" %}
You can open multiple limit orders for the same market. You can manage your stop orders (cancel them) on the Orders tab. No fee is imposed unless the order is executed.
{% endhint %}


# Stop-Loss Orders

Stop-loss Market orders only execute when the oracle price crosses a given stop price. A market order will be placed when the price reaches a specified stop price.&#x20;

By automatically closing your positions when the price crosses the stop price (for long positions) or goes below it (for short positions), stop market orders can be used to prevent losses on your positions. Once triggered, the resulting market order will be immediately filled.

<figure><img src="/files/25Hch7RsJWjbT19wGlnT" alt=""><figcaption></figcaption></figure>

{% hint style="danger" %}
To place advanced orders, you must be using cross-margin & have a minimum keeper requirement of .01 ETH.
{% endhint %}

### Place a Stop-Loss Order:&#x20;

Traders need an open position to execute this order type.

1. Select the asset you are going to trade in the asset selector drop-down
2. Choose a side, either long or short (opposite of your open position)
3. Pick an order type (stop order)
4. Input your desired Collateral
5. Enter your limit price in the price field&#x20;
6. Input your position size
7. Click on `Place Stop Order`

{% hint style="info" %}
The submission of the Stop-Market orders is done on-chain; no additional margin will be tied up.
{% endhint %}

Once you’ve executed the transaction, the order will appear under the  Orders tab. When the oracle price reaches the take profit price, the order will be executed, and your position will be opened.&#x20;

{% hint style="info" %}
The execution price of a limit order may differ depending Oracle price. There are no partial fills with advanced order types, and limit orders will either be fully executed or not at all. Once a limit order has been executed, it will be shown in the Trades column.
{% endhint %}

### Canceling a Stop-Loss Order

If you want to cancel a Stop-Loss order before it has been executed, then click on `Cancel` and confirm in your wallet. As mentioned above, cancellations are done on-chain so this will carry a gas fee.&#x20;

{% hint style="success" %}
You can open multiple limit orders for the same market. You can manage your stop orders (cancel them) on the Orders tab. No fee is imposed unless the order is executed.
{% endhint %}

**Stop-Market orders are dual-purpose and can be used to exit profitable or unprofitable positions at a certain price point or open new positions once a price barrier has been breached.**

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


# FAQ

Smart Margin: Frequently Asked Questions

### What is Smart margin?

Smart margin accounts are a unique Kwenta offering that allows traders to trade any market by using a single margin account. With smart margin accounts, traders can seamlessly trade different markets with fewer transactions and less hassle. Learn here how to trade Smart Margin.

### Can I have positions open on Smart and Isolated Margin?

Yes, it is possible to open positions on the same market on both smart margin and isolated margin. Traders can have e.g. an ETH-PERP long position open on smart margin, switch to isolated margin and open a short on ETH-PERP, and manage them independently.

### Is Smart Margin better than Isolated Margin?

Smart margin provides traders with powerful risk management tools, letting them tailor each position to their personal trading style with an optional fee rejection parameter. This allows traders to have orders rejected if the current dynamic exchange fee spikes beyond acceptable levels.

Under isolated market contracts, users are forced to risk all of the collateral in a single market they deposit and can only protect collateral from liquidation by completely withdrawing the collateral they wish to protect. With Smart Margin, traders are able to select the amount of collateral they are comfortable risking when opening a position while unused collateral will stay safe in the Smart Margin if liquidations should occur.

### How will a Smart Margin account affect my trading?

By default, all Synthetix Futures contracts are isolated markets with no advanced order support, requiring traders to deposit and withdraw separately for each asset they wish to trade. With a Smart Margin account, traders can seamlessly trade different markets from a single account while receiving access to more advanced order types such as limit and stop market orders.

### Is there a minimum deposit requirement?

The minimum deposit and position size value for Smart Margin accounts is 50 sUSD.

{% hint style="info" %}
In addition, the minimum position size must be 50 sUSD without any leverage. If your order is below the 50 sUSD minimum, reduce your leverage and reattempt the trade.&#x20;

**Example:** A 250 sUSD position order at 10x leverage will only require 25 sUSD in collateral, which will fail to execute. Reducing your leverage to 5x will now require 50 sUSD collateral (the minimum) to open a 250 sUSD position. Alternatively increasing your position size to 500 sUSD will also solve this.
{% endhint %}

### Multiple advanced orders per Smart Margin account?

**When Closing a Position**

Traders can set as many limit or stop market orders as they want when closing an open position. So long the advanced orders do not exceed the current open position the advanced order will not reserve additional margin.

#### **When Opening a Position**

Traders can set as many limit or stop market orders up until their account margin is exhausted.

### Are any fees charged if an advance order fails to execute?

No trade fees will be imposed unless the keeper has successfully executed a traders advanced order.

{% hint style="info" %}
This excludes eth paid to the network as a transaction fee
{% endhint %}

### What is account ETH balance?

Advanced orders such as limit and stop market are executed by Gelato Keepers. Keepers need ETH to pay for gas in order to submit transactions to the blockchain. These costs will be drawn out of your account ETH balance. Traders can withdraw their account eth balance at any time if they do not have any pending advanced orders open.

{% hint style="info" %}
The minimum account ETH balance is 0.01 ETH. Anytime your account ETH balance is below this minimum, the next advanced order will automatically deposit enough ETH to bring it back to 0.01 ETH.
{% endhint %}

### Smart Margin fees

Kwenta charges no additional fees for any of the tooling (advanced orders included); it provides outside of the required fees charged by our liquidity provider.

<table><thead><tr><th width="235">Order Type</th><th width="151">Kwenta Fee</th><th>Keeper Fee</th></tr></thead><tbody><tr><td>Trade Fee</td><td>0 bps</td><td>Dynamic depending on network gas prices, usually 2$</td></tr><tr><td>Limit</td><td>0 bps</td><td>Dynamic depending on network gas prices, usually 2$</td></tr><tr><td>Stop</td><td>0 bps</td><td>Dynamic depending on network gas prices, usually 2$</td></tr></tbody></table>


# Delegated Trading

Add and manage delegates to trade on your behalf.

### The Essence of Delegated Trading?

Delegated Trading on Kwenta allows users to delegate trading to multiple wallets, enabling a seamless trading experience across hardware wallets, hot wallets, and more.

#### What Makes Delegated Trading Different?

While wallet delegation features do exist on other platforms, Kwenta’s delegation system brings unique advantages. In some other systems, a delegated wallet gains full administrative control over the account, increasing the risk for users with each additional delegated address.

With Kwenta’s Delegated Trading, deposit and withdrawal are not enabled for delegated wallets. This means that while users still assume the risks of any trades placed by delegated wallets, a compromised delegated wallet has a barrier of security against theft of assets deposited in to the Smart Margin account.

#### Why Use Delegated Trading?

This feature allows traders to manage a single Kwenta Smart Margin account from multiple devices or for teams of traders operating a single fund. While traders can imagine their own use cases, a few examples can help us imagine the possibilities.

* **Trading across multiple devices:** Currently, trading across multiple devices requires exposure of a seed phrase or private key, and often users seeking convenience will copy and paste their credentials, or even send them through email or other insecure means. With Delegated trading, users can avoid these risks by generating keys locally, and simply delegating to each device.
* **Easy trading from a hardware wallet:** In addition to the convenience of trading across multiple devices, traders can improve security by ensuring the owner of their Kwenta Smart Margin Account is a hardware wallet with a proper physical backup. This ensures that while the hardware wallet must be present for delegation setup and withdrawals, it may be safely and conveniently stored away for everyday trading.
* **Team Trading and Fund Management:** For institutional traders, security is of the utmost importance. Currently, few institutions use decentralized tools, and infrastructure allowing a team to manage an onchain fund is nonexistent, leading to poor security or excessive overhead for the fund. Delegated trading provides a simple solution for multiple people to handle a single fund largely missing from existing platforms.

{% content-ref url="/pages/f9v28OGFfM6OVqd1O0XC" %}
[Getting started](/using-kwenta/perpetual-futures/delegation/getting-started)
{% endcontent-ref %}


# Getting started

Set Up delegated access

#### How to Access Delegated Trading Settings

* **Connect Your Wallet:** Start by connecting your primary wallet to Kwenta.

{% hint style="danger" %}
Note: Ensure you’ve created and funded your Smart Margin account from your primary wallet before trading from a delegated wallet.
{% endhint %}

<figure><img src="https://lh7-us.googleusercontent.com/F9m2BHFRJ0e3Fo8DF1XnXuYlRiS5baCSA1H3_G70e8OKB7o-3-XSETLFbWcd-5WvhbKpPDcLy3Y_5SO1MLX_1lC59md-PxVSSwHZmeLb4r0OQptIaPS2X5SdOcE8MIgJODqWR3xVLZCaY0Y1c7TahLo" alt=""><figcaption></figcaption></figure>

* **Navigate to Manage:** Click on your ENS or connected wallet address at the top right of the screen and select “Manage” to access wallet delegation.

{% hint style="success" %}
The account management modal can be accessed here or in the order entry panel.&#x20;
{% endhint %}

* **Find Delegation:** Find the **NEW** delegation setting page within the management modal. On this page, you'll be able to manage all things on delegation.&#x20;

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

* **You'll have a few options from here, which include:**
  * Add New Delegates&#x20;
    * Rename existing Delegates
      * Remove assigned Delegates

{% content-ref url="/pages/tZUBzkYhyuOZQYsr3hoQ" %}
[Managing Delegates](/using-kwenta/perpetual-futures/delegation/managing-delegates)
{% endcontent-ref %}

* **Trading or accessing an account already delegated to you:**&#x20;

{% content-ref url="/pages/4XtDScSp2hd38hWbHk66" %}
[Accessing Accounts Delegate to You](/using-kwenta/perpetual-futures/delegation/accessing-accounts-delegate-to-you)
{% endcontent-ref %}

{% hint style="danger" %}
Remember: Although delegated wallets cannot withdraw funds, leveraged trading still carries risk. Only delegate to wallets you trust!
{% endhint %}

<br>


# Managing Delegates

Adding, removing & renaming existing delegates is a simple task. Let's start by adding a delegate to an existing Smart Margin account.

**Adding a New Delegate:**

* **Step 1:** In the manage modal in the Delegation section, you'll find two sub-tabs, **Delegated To & Delegated From**. Select Delegated To, and in the input field, enter the wallet address you want to delegate trade rights to; once a wallet address has been entered, push through the onchain transaction.

{% hint style="info" %}
ENS names are an accepted input and will automatically convert to its resolver address
{% endhint %}

<figure><img src="/files/UjG9OdCrfciCmGpIAf2y" alt=""><figcaption><p>Enter a Wallet Address</p></figcaption></figure>

* **Step 2:** Assigning a nickname. The last step in creating a new delegate is to attach a nickname for personal references.

{% hint style="info" %}
**Pro Tip:** Custom names are stored in local browser storage, thus will be cleared if users reset their browser cache
{% endhint %}

<figure><img src="/files/upORDdA6buXmSUdLPLg9" alt=""><figcaption><p>Optional NIck Name</p></figcaption></figure>

* **Step 3:** Complete. Once these steps are complete, you'll see the newly assigned delegate within the "Delegated To" tab in the delegation modal.

<figure><img src="/files/dhtCWLTMCnX3dsOBf11k" alt=""><figcaption><p>Sucessfully added a Delegate</p></figcaption></figure>

**Removing a Delegate:**

Removing a delegate is a painless task. Smart margin account owners can remove delegated access rights at a moment's notice. This can be completed by visiting the delegation setting module and finding the wallet address that needs to be removed. Once located the removal option can be found under the three dots.

<figure><img src="/files/AnbJb0UJS9n92UxXo6nR" alt=""><figcaption><p>Select Remove and push the transaction onchain</p></figcaption></figure>

**Renaming Delegates:**

Did you make a mistake naming your delegate? Renaming can be accessed under the same options tab traders use to remove/delete existing delegates.


# Accessing Accounts Delegate to You

A guide to help traders who have had trade rights delegated to them from another Kwenta Smart Margin Account access them.

Are you looking to trade on an account that has delegated its right to you? Look no further & head over to Kwenta.

#### How to Access an account Delegated to you

* **Connect Your Wallet:** Start by connecting a wallet with the right to trade on behalf of another account to Kwenta.

{% hint style="danger" %}
Note: Deposit/Withdrawal, as well as other functions, may not be available while in delegation mode.
{% endhint %}

* **Switching between accounts:** Users can switch between their connected account and any accounts that have delegated access to them quickly. Simply click on your connected wallet in the top right navigation bar.&#x20;

<figure><img src="/files/EroJTfKAUpVue8mp9P1u" alt=""><figcaption><p>Users will see their own connected EOA</p></figcaption></figure>

Inside the spawned modal traders will have access to managing their own connected wallet & will see any smart accounts that have delegated trade rights to them below "Delegated Acess". To assume control of one of the alternative trade accounts a user simply presses the "connect" button next to the address they want to access.


# Fees

{% hint style="info" %}
Note that Kwenta charges no additional fees for any of the tooling (advanced orders included) it provides outside of the required fees charged by our liquidity provider.
{% endhint %}

Kwenta is built upon the Synthetix Protocol. In order to enable the exchange of synthetic assets, an exchange fee is charged by Synthetix, whose fees are sent to the fee pool for Synthetix (SNX) stakers.

### Synthetix Fees

**Keeper deposit:** Dynamic fee given to the keeper bots to execute the trade. Before implementing the dynamic gas fee module, keepers were paid a flat fee for executing off-chain perps orders.&#x20;

However, this flat fee system proved inadequate in covering gas costs for order execution and couldn't properly incentivize community keepers, as gas costs often exceeded the rewards earned from order execution.

The dynamic gas fee module is designed to adjust the minKeeperFee within bounds set by governance, allowing the system to adapt to varying gas prices and ensuring a decentralized network of keepers remains cost-effective.

#### **The Benefits of the Dynamic Gas Fee Module** <a href="#the-benefits-of-the-dynamic-gas-fee-module" id="the-benefits-of-the-dynamic-gas-fee-module"></a>

1. Ensuring keepers are fairly rewarded for order execution, encouraging more users to run their own keepers.
2. Making the keeper system more resilient to fluctuating gas prices
3. Enhancing decentralization within the Perps ecosystem, contributing to network stability and reliability.

[**Maker/Taker:**](/using-kwenta/perpetual-futures/maker-takers-on-kwenta) Maker & Taker fees may vary depending on a selected market. The most current fees are prominently displayed within the Kwenta trading platform.

{% hint style="info" %}
Basis Points (BPS) are a unit of measurement equal to 1/100th of 1 percent commonly used in financial markets. Find actual exchange fees within [Kwenta](https://kwenta.eth.limo/market/?accountType=isolated_margin\&asset=sETH).
{% endhint %}

| Percentage | .bps   |
| ---------- | ------ |
| 0.02%      | 2 bps  |
| 0.10%      | 10 bps |

{% hint style="danger" %}
All fees are charged against the notional position size during order execution, and up-to-date fees can are always displayed in the order entry panel. Fees are only charged when the trade successfully executes.
{% endhint %}

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


# Referral Program

The Kwenta referral program is live in private alpha.

### **Referrals**

The Kwenta Referral program is a growth tool which allows for a fully on-chain system of NFTs to govern the distribution of rewards to affiliates. The affiliate program has been designed and built from the ground up. The current fully onchain referral program uses the Optimism network, and you **must have ETH on Optimism** to participate.

In the future, Kwenta may migrate to an offchain referral program or provide another upgrade, but please be aware of the Optimism requirement at this time. Once an NFT is minted on Optimism, some rewards such as points will be earned on any network.&#x20;

## Rewards&#x20;

The Kwenta referral program currently offers users 2 types of rewards for participation.

#### $OP Token Rewards

Traders who mint a Boost NFT and trade on Optimism will earn a 30% fee rebate for trades on Optimism v2. The address which referred each trader also earns 30% of their fees as a rebate, allowing both the trader and affiliate to earn liquid rewards. $OP rewards are issued on a **first come, first serve** basis, and will end when all $OP tokens have been distributed.&#x20;

Please see the Rewards Guide for updates and details:

> <https://mirror.xyz/kwenta.eth/-WuyXleDYy80mo5oQH_8MSyM4BLYKvXZ3-VLJFNYB30>


# The Traders Tab

Track your boost tier and earned $KWENTA rewards.

The Traders Tab allows traders to view and confirm that they have minted a Boost NFT and track boosted rewards. To get started using the Traders Tab, you'll need to first mint a [Boost NFT](/using-kwenta/perpetual-futures/referral/incentive-tiers-and-rewards).&#x20;

<figure><img src="/files/LY8fuhQOIqIUycneXSWx" alt=""><figcaption><p>Select the Traders tab to view your Boost NFT tier.</p></figcaption></figure>

## Rewards Tier and All-Time Statistics

At the top of the page, you'll see your rewards tier and all-time statistics. These stats represent your trading performance since minting your Boost NFT.&#x20;

<figure><img src="/files/ghVcaRJKgaprVd9v4nbb" alt=""><figcaption><p>These stats represent rewards since minting your Boost NFT</p></figcaption></figure>

### Elements of the table

1. **Rewards Boost:** This column shows the boost tier and associated rewards boost multiplier.
2. **Total Volume:** This column shows all trading volume from the connected wallet beginning from the epoch the Boost NFT was minted.
3. **Total $KWENTA Earned:** This column shows the $KWENTA rewards earned as a trader, beginning from the epoch the Boost NFT was minted, after boost is applied.&#x20;

> **NOTE: $KWENTA Rewards have been discontinued. For current referral reward $OP earnings, please see the rewards dashboard:** [**https://kwenta.io/rewards/**](https://kwenta.io/rewards/)

## Boosted Rewards History Table

At the bottom of the page you’ll find a table displaying previous epochs you have earned boosted rewards, and your rewards and trading history for these epochs. Each epoch listed in the table is one for which a boost has been applied.&#x20;

<figure><img src="/files/BmCfUau1jnvz3stGmT67" alt=""><figcaption><p>The Boosted Rewards History table only shows boosted rewards. You may have earned rewards in epochs prior to minting your Boost NFT.</p></figcaption></figure>

**Elements of the Referral Code Table:**

1. **Epoch:** Rewards epochs are one week long, rolling over every Wednesday at 00:00 UTC, and count up from Epoch 0, the launch of the $KWENTA token.
2. **Total Volume:** This column shows the total volume generated by the connected wallet during the epoch if a Boost NFT was held during the epoch.
3. **Trades:** This column shows the total number of trades made by the connected wallet during the epoch if a Boost NFT was held during the epoch.
4. **$KWENTA Earned:** This column shows the $KWENTA rewards earned from trading during an epoch after boost is applied if a Boost NFT was held during the epoch.

## Manual Entry

Currently, the only way to mint a Boost NFT is by following a referral link. In future updates, manual entry will be enabled via a text box, allowing users to share referral codes more easily in a wider variety of contexts and mediums.

## $OP rewards

Rewards currently include a 30% fee rebate for all traders who follow a referral link and mint a Boost NFT. These rewards are **the same** no matter which Boost NFT you mint. For more details, check out the [rewards guide](https://mirror.xyz/kwenta.eth/-WuyXleDYy80mo5oQH_8MSyM4BLYKvXZ3-VLJFNYB30) and join [Discord](https://discord.gg/kwentaio) for announcements on future incentive programs.


# The Affiliates Tab

Register and share referral codes, and track referrals and rewards.

The first step to taking advantage of the Kwenta referral program is registering your code. To register a code, earn, and track the progress of your referrals, navigate to the Referrals dashboard (<https://kwenta.eth.limo/referrals>), and connect the wallet to which you’d like to receive referral rewards. Select the Affiliates tab to manage your Affiliate dashboard.

<figure><img src="/files/ZlLQMkXTRjbzjSubQtwo" alt=""><figcaption><p>Select the Affiliates tab to create referral codes</p></figcaption></figure>

## All-Time Statistics

At the top of the page, you'll see your all-time statistics. These stats represent the performance of all the referral codes created from the connected wallet.&#x20;

<figure><img src="/files/mzmtL5zgoBwt34jixZjH" alt=""><figcaption><p>All-time stats include all generated referral codes</p></figcaption></figure>

Elements of the table are as follows:

1. **Total Traders Referred:** This column shows the unique wallets which have generated a Boost NFT using any of the codes generated from the connected wallet.
2. **Total Trading Volume:** This column shows the total volume generated by traders who have used any codes generated by the connected wallet since the beginning of the epoch in which they minted your Boost NFT.
3. **Total $KWENTA Earned:** This column shows the $KWENTA rewards earned as an Affiliate Bonus all referral links. Rewards are claimed weekly alongside any trading rewards.

> **NOTE: $KWENTA Rewards have been discontinued. For current referral reward $OP earnings, please see the rewards dashboard:** [**https://kwenta.io/rewards/**](https://kwenta.io/rewards/)

## Referral Tier

**NOTE: Referral Tiers&#x20;*****do not*****&#x20;impact $OP earnings from our current referral and rebate program. All tiers are currently earning the same rewards. Please see the** [**rewards guide**](https://mirror.xyz/kwenta.eth/-WuyXleDYy80mo5oQH_8MSyM4BLYKvXZ3-VLJFNYB30) **for details.**

Under your all-time statistics, you’ll see the power of your referral link represented as Bronze, Silver, or Gold. Higher tiers mean higher Boosts for traders you refer, and higher Bonus rewards for you. To increase the power of your referral code, stake $KWENTA, or apply for an Affiliate NFT.&#x20;

<figure><img src="/files/Rj6Yf34YV0MM2uyIGNo7" alt=""><figcaption><p>This wallet has at least 200 Referral Power</p></figcaption></figure>

The Referral Tier progress bar measures the number of $KWENTA tokens staked in the connected wallet, including both liquid and escrow staked in v2. Affiliate NFTs come in Silver or Gold tier, and add 100 or 200 to your Referral Tier balance, respectively.

See the breakdown of tier rewards in the incentive tiers and rewards section.

> Please Note: increasing your referral power only impacts newly referred traders, and does not increase the rewards associated with traders referred in the past.&#x20;

## Referral Code Table

At the bottom of the page you’ll find a table displaying all your existing referral codes. If you have not created a referral code from your connected wallet, this table will be empty. Once you create and share a referral code, you can use this table to track your progress and rewards.&#x20;

<figure><img src="/files/42dY32Ka8a9OmIcAmbWG" alt=""><figcaption><p>This wallet has only minted a single code, but you may have more</p></figcaption></figure>

**Elements of the Referral Code Table:**

1. **Referral Code:** This column lists all the referral codes registered from your connected wallet, and allows referral links to be copied to your clipboard.
2. **Total Volume:** This column shows the total volume generated by traders who have used your code since the beginning of the epoch in which they minted your Boost NFT.
3. **Traders Referred:** This column shows the number of unique wallets which have followed each referral link and minted a Boost NFT.
4. **$KWENTA Earned:** This column shows the $KWENTA rewards earned as an Affiliate Bonus from each referral link. Rewards are claimed weekly alongside any trading rewards.
5. **"Create Code" Button:** This button opens a modal allowing you to register a code to the connected wallet.

## Creating a Referral Code

To create a new referral code, select the “Create Code” button at the top right of the Referral Codes table. Enter your desired code, select the “Create Referral” button, and approve the transaction on the Optimism network.&#x20;

<figure><img src="/files/SVE03sfgNQwDe7Hkx26k" alt=""><figcaption><p>This transaction creates the referral link <a href="https://kwenta.eth.limo/market/?ref=kwenta">https://kwenta.eth.limo/market/?ref=kwenta</a></p></figcaption></figure>

Once your transaction is confirmed, your referral code will be permanently registered to the connected wallet onchain.

**Important Notes on Referral Code Creation:**

1. Registering a new code through the UI is not case sensitive, and all characters will be parsed to lowercase in referral links.
2. Each code may only be registered by a single user. If your code has already been registered, please choose an alternative code.
3. Affiliates may register more than one referral code, allowing affiliates to customize branding and track referrals from multiple sources using onchain data.
4. Once your referral code has been registered, simply use the copy icon to copy and paste your unique link for traders to follow. Any trader who has not previously minted a Boost NFT may mint one from a referral link, and you’ll earn rewards from each trader.


# Incentive Tiers and Rewards

Rewards calculations and referral tier benefits.

The Kwenta Referral Program is governed and tracked by Boost NFTs which are minted by traders. Traders are given the opportunity to mint Boost NFTs by Kwenta Affiliates through following a referral link.&#x20;

## Boost NFTs

Boost NFTs come in 3 types: Bronze, Silver, and Gold. The tier of Boost NFT minted by the trader depends on the Referral Score of the Affiliate at the time of minting.

### **Boost NFT Tiers**

**Boost NFT Contract:** `oeth:0xD3B8876073949D790AB718CAD21d9326a3adA60f`

Boost NFTs come in bronze, silver, and gold, however tiered rewards have now been deprecated. Though these legacy tiers may show a different color NFT, everyone now earns the same rewards.

### Minting a Boost NFT

Boost NFTs are minted by following a referral link. Real Kwenta referral links should look similar to this one:

<https://kwenta.eth.limo/market/?ref=kwenta>

When following a referral link, simply connect the wallet with which you intend to trade, and follow the onscreen instructions. A confirmation will appear when your Boost NFT is successfully minted. You may also view your Boost NFT in Optimistic Etherscan or Opensea. For security, please ensure the contract matches the address above before performing any interaction.

### **Important Notes on the Boost NFT**

1. Boost NFTs are soulbound, and each wallet may only contain one Boost NFT. Boost NFTs may not be transferred or upgraded at this time.
2. Although the Boost NFT itself does not change, all rewards associated with the Boost NFT may change via the KwentaDAO governance process.

## Rewards Calculations

Rewards for both Traders and Affiliates are now part of a new program supported by the Optimism DAO. Traders earn rewards for following a referral link and minting a Boost NFT, while Affiliates earn rewards for referring new traders who do the same.

Here's how the new rewards system works:

**Network: Optimism**

**Action Required:**

1. Follow a referral link and mint a Boost NFT.
2. Refer a trader who follows your referral link and mints a Boost NFT.

**Potential Rewards:**

* 200,000 $OP distributed on a first-come, first-serve basis.

**Program Details:**

Rewards are distributed based on the trading fees paid by referred traders. Both traders and affiliates benefit from this structure.

**Reward Distribution:**

* For each trader who mints a Boost NFT and pays fees, 30% of the fees are rebated to the trader, and 30% to the affiliate who referred them.

**Example Calculation:**

In this example, Tom is an affiliate who has referred Ily. Ily follows Tom's referral link, mints a Boost NFT, and pays $100 in trading fees.

1. Ily's Fees Paid: $100
2. Trader Rebate (Ily): 30% of $100 = $30
3. Affiliate Rebate (Tom): 30% of $100 = $30

At the end of the weekly epoch, Ily will earn $30, and Tom will earn $30, both in $OP tokens. The value of the $OP tokens will be calculated based on the market value at the time of distribution.

**Epochs:**

* Weekly rewards epochs are ongoing and will be announced at the start of the program.

**Reward Distribution:**

* OP rewards are claimable from the [Rewards Dashboard](https://kwenta.io/rewards/) at the conclusion of each weekly epoch.

<figure><img src="/files/XinRalTgSaOAW3HgBJYm" alt=""><figcaption><p>Claim all rewards in the Staking and Rewards dashboard. Note that rewards from other sources, such as SNX OP rewards, will not have boost applied.</p></figcaption></figure>


# FAQ

Frequently Asked Questions

#### Where does the liquidity come from?

Kwenta is built on the Synthetix protocol, so the liquidity traders can access on Kwenta is entirely created by SNX stakers on Synthetix.

#### How does trading work if there are no counterparts?

There are no direct counterparties for each trade in the Synthetix protocol, but it does use a counterparty-like model in which SNX stakers assume a proportion of the Synthetix debt pool when they mint sUSD. For more details, see the Synthetix [litepaper](https://docs.synthetix.io/litepaper/).

#### Why Layer 2 Optimism?

To aid us in scaling on-chain derivatives trading, Kwenta is built on Layer 2 Optimism for isolated perpetual futures, utilizing Synthetix smart contracts. Traders can expect significantly lower gas costs, and in turn, much lower trading fees and minimum trade sizes.

Optimism is an "Optimistic Rollup," which is basically just a fancy way of describing a blockchain that piggy-backs off of the security of another "parent" blockchain. Specifically, Optimistic Rollups take advantage of the consensus mechanism (like PoW or PoS) of their parent chain instead of providing their own. In Optimism's case, this parent blockchain is Ethereum.Trades transactions are settled on a Layer 2 and batched to Ethereum l1

#### **How Optimistic Roll-ups work?**

Optimistic rollups sit in parallel to the main Ethereum chain on layer 2. They can offer improvements in scalability because they don't do any computation by default. Instead, after a transaction, they propose the new state to Mainnet or "notarise" the transaction. With Optimistic rollups, transactions are written to the main Ethereum chain as calldata, optimizing them further by reducing the gas cost.

As computation is the slow, expensive part of using Ethereum, Optimistic rollups can offer up to 10-100x improvements in scalability dependent on the transaction. This number will increase even more with the introduction of shard chains as more data will be available if a transaction is disputed.

**Type of Collateral accepted on Kwenta?**

Kwenta currently denotes its quote asset in sUSD, anyone trading on Kwenta must deposit sUSD to begin trading.

#### **How do I deposit sUSD?**

Traders looking to use Kwenta Perpetual Futures need a metamask wallet, optimism added as a selectable network, and sUSD on layer 2 optimism. Once traders have all of the above they can head to Kwenta, select any of the available assets to trade connect their wallet, and deposit funds to begin trading. Once done trading a specific asset pair traders can remove any sUSD back to their wallet and make use of their funds elsewhere.

#### **Minimum Deposit & Why?**

Due to being built on Optimism transaction costs to execute trades are ridiculously cheap allowing us to have low minimum deposit requirements. Liquidations on Kwenta can be executed by anyone with a web3 wallet and since there are no centralized entities making sure positions get liquidated in a timely manner we must incentivize liquidations to happen timely for system stability reasons.

Because of this liquidators are paid $25 sUSD as an incentive to aid in making sure liquidations are actually occurring. Since there is a minimum fee paid to these liquidators a $40 minimum deposit has been implemented as depositing anything less wouldn’t leave a ton of room between opening a position and having that position liquidated with enough funds to cover the liquidator cost.

#### **How does isolated margin work?**

An isolated Margin is the margin balance allocated to an individual asset. Isolated Margin contracts allow traders to manage their risk on individual assets being traded by restricting the amount of margin allocated to each one. The allocated margin balance for each asset can be individually adjusted.

#### **How much leverage is available?**

Currently, Kwenta offers 25x leverage, with plans to raise the available leverage in the future dynamically per asset.

#### **How does Kwenta determine an assets price?**

Pricing for market, stop, and limit orders is provided by Pyth. Pyth is a decentralized oracle network which provides an aggregated price for markets on Kwenta. Prices are published offchain along with a cryptographic signature. When orders are submitted to Kwenta, a realtime price and its signature are published and verified onchain to ensure the most up-to-date, accurate pricing for each trade.

Pricing for liquidations is provided by Chainlink. Liquidation is performed by keeper bots for a fee, and may be performed if the most recent Chainlink price is below a user's liquidation price for a long position, or above for a short position. As an additional safety measure, market, stop, and limit orders also must be executed near the most recent Chainlink price, preventing trades from occurring if large divergences between Pyth and Chainlink trigger a circuit breaker event. This threshold may be set by Synthetix.


# Perennial Isolated Margin

Perpetual Futures on Arbitrum

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2Fcontent.gitbook.com%2Fcontent%2FesXIGSYvKcOjqMTCdsjo%2Fblobs%2FnWf1laoqx49ir9YRL1us%2F1500x500%2520perennial.jpeg&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=cc18de2d&#x26;sv=1" alt=""><figcaption></figcaption></figure>

Perennial is a DeFi-native derivatives primitive that allows for the creation of two-sided markets that trade exposure to an underlying price feed in a capital efficient manner.

#### **How does it work?** <a href="#how-does-it-work" id="how-does-it-work"></a>

Perennial acts as a peer-to-pool derivatives AMM that perpetually offers to take the other side of any Taker’s position directly at the oracle price, in exchange for funding & interest rates based on market skew & utilization.

**Takers (Traders)** deposit collateral to get leveraged exposure to different price feeds (long, short, and exotic payoffs). A Taker's exposure within a market is matched against positions in the opposite direction. Where a shortfall between Takers exists in a market, **Makers (Liquidity Providers)** provided capital earns fees for filling the shortfall in the market. Makers take on exposure relative to the amount required to fill the exposure mismatch between takers.

On a continuous, on-going basis, takers & makers settle up; the losing side of the trade pays the winning side.

#### Why Perennial? <a href="#why-perennial" id="why-perennial"></a>

Perennial is minimalist at its core, designed to be a low-level, unopinionated primitive that lays the basic infrastructure and leaves the rest up to market creators and participants to define/optimize.

Some things that make Perennial stand out:

* **Cash-settled** — trades settled in $USD, not crypto, in line the most popular crypto derivatives
* **Low fees** — a hyperefficient protocol (in terms of mechanism design & capital efficiency) that minimizes fees for takers & makers
* **Customizable LP experience (both simple & pro)** — Makers can LP with significant leverage (up to 50x) and can fully customize their risk exposure & hedging strategy (or lack thereof); Retail LPs can utilize vaults built on top that abstract complexity. Perennial makes very few assumptions about LPs at the protocol level, giving LPs full control.
* **Designed for the needs of Developers** — not just another trading protocol; Perennial is built to be a composable primitive (low fee, fully-on chain, easy to integrate)
* **Permissionless** — Permissionless market creation, integration, and composability.


# Perennial Intro

Perennial in its most basic form is infrastructure for derivative markets.

A market in Perennial is a two-sided market (makers & taker) that trades synthetic exposure derived from a price oracle, over a given payoff function. Each market is independent & has isolated risk.

A Market in Perennial is defined by things like:

* [**Oracle**](/using-kwenta/perennial-isolated-margin/perennial-intro/oracles)
* [**Payoff function**](/using-kwenta/perennial-isolated-margin/perennial-intro/payoff-and-positions)
* [**Fee structure**](/using-kwenta/perennial-isolated-margin/perennial-intro/trading-fees-and-price-impact)
* [**Funding Rate**](/using-kwenta/perennial-isolated-margin/perennial-intro/funding-rate)
* [**Interest Rate**](/using-kwenta/perennial-isolated-margin/perennial-intro/interest-rate)
* [**Leverage & Liquidation**](/using-kwenta/perennial-isolated-margin/perennial-intro/leverage-and-liquidations)

Implications of this worth calling out:

1. **Payoffs are fully synthetic** — There can be a Perennial market for any price feed (or any programmable deviation of that price feed). A market could theoretically be created for crypto tokens, currencies, commodities, or any other non-manipulable price feed.
2. **Each price feed may have multiple markets** —  There may be a Long-ETH market with the payoff function 1\*ETH, and a Short-ETH market with the payoff (-1)\*ETH)
3. **Each payoff function may have multiple markets** — There may multiple Short-ETH markets (payoff: (-1)\*ETH), each with its own utilization curve, fees structure, parameters, etc.


# Market Design

## Market Mechanism <a href="#market-mechanism" id="market-mechanism"></a>

In V2 of Perennial, markets natively net long positions against short positions, and only utilize maker liquidity to cover the resulting imbalance. This yields markets that are up to an order of magnitude more efficient in terms of open interest to required maker liquidity.

V2 now nets longs & shorts instead of V1's design which had segregated markets for long & short payoffs.

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2F2608572446-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FesXIGSYvKcOjqMTCdsjo%252Fuploads%252FqOJYqINcVXDq5D9uC9kS%252FPerennial%2520V2%2520Mechanism%2520Overview.png%3Falt%3Dmedia%26token%3Dd3f92fba-8302-4afe-8715-f2299cf827aa&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=bb323e31&#x26;sv=1" alt=""><figcaption><p>V2 now nets longs &#x26; shorts instead of V1's design which had segregated markets for long &#x26; short payoffs.</p></figcaption></figure>

## Utilization of Maker Liquidity <a href="#utilization-of-maker-liquidity" id="utilization-of-maker-liquidity"></a>

The maker side of the market is only required to cover the net exposure of the taker side: longs & shorts. Long and short taker positions are first netted out against each other with the resulting exposure directed to the maker pool pro-rata.

With 10u long & 6u short, the maker pool (consisting of 5u total) is taking on 4u short exposure pro-rata or is 0.80x short.

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2F2608572446-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FesXIGSYvKcOjqMTCdsjo%252Fuploads%252FUkxOoPZcGYAf0cew9zyA%252FPerennial%2520V2%2520Mechanism%2520Overview%2520%281%29.png%3Falt%3Dmedia%26token%3D914fd2fc-34c1-4bdc-ac1b-f75d1e35b340&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=a4d94666&#x26;sv=1" alt=""><figcaption><p>With 10u long &#x26; 6u short, the maker pool (consisting of 5u total) is taking on 4u short exposure pro-rata or is 0.80x short.</p></figcaption></figure>

## Market Simulator <a href="#market-simulator" id="market-simulator"></a>

To help understand how different mixes of maker/long/short effect the market we've built a little simulator. Try it out for your self here: [Perennial Market Simulator](https://pnl-sim.vercel.app/)

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2F2608572446-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FesXIGSYvKcOjqMTCdsjo%252Fuploads%252FLYjeyHHaSvkboV1mWrSo%252FScreenshot%25202024-02-20%2520at%25203.29.27%25E2%2580%25AFpm.png%3Falt%3Dmedia%26token%3D6c86a1f0-768c-463a-87d6-4774d4fbb6ff&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=66f0871e&#x26;sv=1" alt=""><figcaption></figcaption></figure>


# Oracles

Oracles are the core of each market within Perennial. Each market pulls in one or more prices from oracles to be used in the payoff function.

While a simple market will just use a single price feed (ex. ETH), more complex market could use payoffs with multiple price feeds (ex. ETH / BTC).

Perennial's modular design supports custom oracles. Currently, Perennial markets use an implementation of [Pyth's](https://pyth.network/) low latency oracles, allowing for fast & efficient price updates.

### Settlement <a href="#settlement" id="settlement"></a>

Since the [market payoff](https://docs.perennial.finance/protocol-design/payoff-and-positions) is computed directly from the oracle price, a lag needs to introduced into the settlement system so that entering and exiting positions cannot be timed to arbitrage the market.

Time in Perennial markets is split into units called *oracle versions*. **Settlement only occurs on the transition of one oracle version to another.** When a user requests to open or close a new position, that position delta sits in a pending state until the next oracle version update, after which it takes effect.

**Settlement Flow:**

In this example: the user calls open(10) at during oracle version 1, and close(10) during oracle version 3. The user's position opens at the start of version 2 and closes at the start of version 4, meaning they are exposed to the price difference between versions 2 and 4.

| Oracle Version | User Action | Pending                             | Oracle Price | Position (Profit/loss) |
| -------------- | ----------- | ----------------------------------- | ------------ | ---------------------- |
| 1              | Open 1 ETH  | <p>Opening: 10</p><p>Closing: 0</p> | $1000        | - (0)                  |
| 2              |             | <p>Opening: 0</p><p>Closing: 0</p>  | $1025        | 1 ETH (0)              |
| 3              | Close 1 ETH | <p>Opening: 0</p><p>Closing: 10</p> | $1075        | 1 ETH (+$50)           |
| 4              |             | <p>Opening: 0</p><p>Closing: 0</p>  | $1050        | - (+$25)               |

**Developer Note:** The settlement flow happens entirely on-chain, giving strong guarantees for projects building on top of Perennial.

Perennial smart contracts store the current version for position adjustments, allowing for the positions opening price & PnL to be retroactively calculated at the next on-chain settlement period (when the contracts are interacted with again), avoiding the need for a second interaction during opens/closing (or the need for a keeper).


# Payoff & Positions

When initializing a market, the market operator will select a payoff function. A payoff function describes the logic the smart contracts should use to divide the money between the two sides of the market: long & short, when the market settles.

Perennial allows for developers to define any payoff function they desire — everything from simple long \<asset> markets to 3x short \<asset> markets to options & exotic payoffs. Below are some examples of possible payoff functions:

**Example Payoff Functions**

| Product            | Payoff      | Oracle             |
| ------------------ | ----------- | ------------------ |
| 3x Leveraged Ether | 3 \* ETH    | Chainlink ETH Feed |
| Squeeth            | ETH \* ETH  | Chainlink ETH Feed |
| ETH-USDC UniV2 LP  | sqrt( ETH ) | Chainlink ETH Feed |

The payoff function for a market can be any function over an available oracle feed. This function is the definition of the exposure one (`1e18`) taker position represents within the market.

In the case of the "3x Leveraged ETH" payoff function, the payoff function itself is leveraged. This is independent of Maker positions that can also be leveraged (Ex. a Maker could be 2x leveraged on a 3\*ETH market). For more information on Maker/Taker leverage, see the Maintenance (& Leverage) section.

#### Positions <a href="#positions" id="positions"></a>

Positions in Perennial are represented as units of a payoff function. This means exposure is tethered to the payoff function, not in terms of USD.

For example, say one wanted to open a 1 ETH long position (payoff = 1 \* ETH). This will open a taker position for 1 \* market\_payoff, so 1 \* ETH. This position would keep 1 ETH of exposure until closed or liquidated.

Conversely, if a user is trying to open a position in terms of some $USD amount, they would have to estimate the USD value in units of the underlying payoff and open a position accordingly.

For example, if ETH is about $1000, and a user wants to open a $2500 long-eth position, they could call openTake(2.5), which will open a position that tracks 2.5\*ETH, which will be approximately (but not exactly, because of delayed settlement) equal to $2500.

[Funding](https://docs.perennial.finance/protocol-design/funding-rate) & [fees](https://docs.perennial.finance/protocol-design/trading-fees-and-price-impact) are debited from a position's collateral account.


# Trading Fees and Price Impact

Price impact and trading fees are incurred whenever an account's position changes.

#### **Settlement Fee** <a href="#settlement-fee" id="settlement-fee"></a>

The settlement fee is charged anytime the position changes – this is a fixed amount set by the settlementFee parameter and is used to cover the oracle keeper fee.

𝑠𝑒𝑡𝑡𝑙𝑒𝑚𝑒𝑛𝑡𝐹𝑒𝑒=𝑠𝑒𝑡𝑡𝑙𝑒𝑚𝑒𝑛𝑡𝐹𝑒𝑒settlementFee=settlementFee

#### **Taker Price Impact** <a href="#taker-price-impact" id="taker-price-impact"></a>

Charged when a long or short position is opened or closed – there are three components to the taker impact:

* Notional size of the order,
* Change in skew that it causes the market
* Impact that it causes the market.

The change in skew is defined as ∣𝑠𝑘𝑒𝑤’−𝑠𝑘𝑒𝑤∣∣skew’−skew∣, and is meant to measure the size of the order relative to the market.

The impact is defined as ∣𝑠𝑘𝑒𝑤’∣−∣𝑠𝑘𝑒𝑤∣∣skew’∣−∣skew∣, and is meant to measure how much the order hurt or helped the overall skew of the market.

𝑠𝑘𝑒𝑤𝐹𝑒𝑒=Δ𝑠𝑘𝑒𝑤∗𝑡𝑎𝑘𝑒𝑟𝑆𝑘𝑒𝑤𝐹𝑒𝑒𝑖𝑚𝑝𝑎𝑐𝑡𝐹𝑒𝑒=𝑖𝑚𝑝𝑎𝑐𝑡∗𝑡𝑎𝑘𝑒𝑟𝐼𝑚𝑝𝑎𝑐𝑡𝐹𝑒𝑒𝑡𝑎𝑘𝑒𝑟𝑃𝑟𝑖𝑐𝑒𝐼𝑚𝑝𝑎𝑐𝑡=𝑛𝑜𝑡𝑖𝑜𝑛𝑎𝑙∗(𝑏𝑎𝑠𝑒𝐹𝑒𝑒+𝑠𝑘𝑒𝑤𝐹𝑒𝑒+𝑖𝑚𝑝𝑎𝑐𝑡𝐹𝑒𝑒)skewFeeimpactFeetakerPriceImpact​=Δskew∗takerSkewFee=impact∗takerImpactFee=notional∗(baseFee+skewFee+impactFee)​

#### **Maker Fee** <a href="#maker-fee" id="maker-fee"></a>

Similarly, the maker fee is charged when a maker position is opened or closed – There are two components to the maker fee:

* Notional size of the order
* Change in utilization that it causes the market.

The change in utilization is defined as `utilization’ - utilization`, and is meant to measure how much the order hurt or helped the overall utilization of the market.

𝑚𝑎𝑘𝑒𝑟𝑓𝑒𝑒=𝑛𝑜𝑡𝑖𝑜𝑛𝑎𝑙∗(𝑚𝑎𝑘𝑒𝑟𝐹𝑒𝑒+Δ𝑢𝑡𝑖𝑙𝑖𝑧𝑎𝑡𝑖𝑜𝑛∗𝑚𝑎𝑘𝑒𝑟𝐼𝑚𝑝𝑎𝑐𝑡𝐹𝑒𝑒)makerfee=notional∗(makerFee+Δutilization∗makerImpactFee)

### Fee Split <a href="#fee-split" id="fee-split"></a>

All collected fees are split between the Makers (and in rare cases takers), Perennial treasury, and the respective Product owner's treasury.

This allows market owners (whether individual organization or DAOs / protocols) to collect revenue directly from the administration of the Products and their parameters.


# Funding Rate

In Perennial V2, the funding flows from longs to shorts (or vice versa), while being controlled with a P-controller over the skew in long vs short.

#### Market Skew <a href="#market-skew" id="market-skew"></a>

The 𝑠𝑘𝑒𝑤skew is a measure of how imbalanced a given market is. The higher the skew the greater difference in positions from takers on the long & short sides of the market. Ideally, markets are perfectly balanced, this ensures maximum capital efficiency. However, in situations where there is an imbalance, makers will take on exposure to the lesser side of the market to ensure the larger side of the market is always backed.

$$
skew=
max(long,short)
long−short
​
$$

In order to rebalance the market (reduce skew), a funding rate is utilized to incentivize market participants change their positions or enter new ones.

#### Funding Rate <a href="#funding-rate" id="funding-rate"></a>

At each market update, the P-controller recalculates and updates the rate of change of the funding based on the skew and a risk parameter (*k*). The funding rate continues to virtually adjust linearly at its latest updated rate of change in between market updates.

$$
Δ𝑓𝑢𝑛𝑑𝑖𝑛𝑔=𝑠𝑘𝑒𝑤/𝑘Δfunding=skew/k
$$

If the market has a skew, then at each oracle update the P-controller will adjust the funding rate that each side will pay. If the skew is larger than the size of the funding change per update also increases.

The figure shows an example of how skew in a market can effect the funding rate.

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2Flh4.googleusercontent.com%2FMqpggtMHq7XldXiFpjLfOXPt6LfpRI9sNsOgRwzhvHdsT0-N3rQW8820Zr2bMXIM0hclBSAsnqwpB1-mQsPqs_OnhBLqTGQJ-ozzZEYfabdrdMNLPKiJpFp6klqX8vpKUZwsFimTA2AutArx-XEY6Q&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=6e0f45eb&#x26;sv=1" alt=""><figcaption><p>The figure shows an example of how skew in a market can effect the funding rate.</p></figcaption></figure>

The maker side has no ability to effect the pricing of the funding, aside from indirectly through limits on the magnitude of long and short.

#### Makers <a href="#makers" id="makers"></a>

In the event of skew, the maker side will supplement the lesser side of the market to ensure the larger side of the market is matches. In exchange, they receive pro-rata funding for the exposure it is covering. Intuitively, the maker side of the market is being compensated for taking whatever is currently the unfavourable side of the market pro-rata.

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2F2608572446-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FesXIGSYvKcOjqMTCdsjo%252Fuploads%252FpLM20ZCUGJ98ueghEjrf%252FPerennial%2520V2%2520Mechanism%2520Overview%2520%282%29.png%3Falt%3Dmedia%26token%3Dbcb6bfa7-4909-44b9-a98d-2a1b762fef51&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=2447e7fd&#x26;sv=1" alt=""><figcaption></figcaption></figure>

In this example, the skew of the market is (10 - 6) / 10 or 40%. This will cause the funding rate of the market to steadily increase until the skew changes. The maker side of the market is receiving 80% of the funding (per position) that the short side of the market is receiving for the exposure it is taking on.


# Interest Rate

In order to keep the maker side of the market incentivized even when we have relatively balanced long and shorts, markets can charge an interest rate. This is meant to measure the delta-neutral capital costs of the makers, whereas funding covers their net exposure.

### Utilization <a href="#utilization" id="utilization"></a>

The interest rate is determined by a utilization curve and is given to **all** maker positions. In order to cap the spread, if there is a greater amount of maker position than the sum of the long and short positions, the interest rate is pro-rata discounted. Utilization is determined by measuring the greater side against the sum of the maker and lesser side. Intuitively, the interest rate is a funding spread used to incentivize idle liquidity.

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2F2608572446-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FesXIGSYvKcOjqMTCdsjo%252Fuploads%252Fy7ZNbJITJCLunVsyg1bB%252FPerennial%2520V2%2520Mechanism%2520Overview%2520%283%29.png%3Falt%3Dmedia%26token%3Da218b6fb-59a5-4d9d-9a4f-a20b040b2a74&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=71aef28a&#x26;sv=1" alt=""><figcaption></figcaption></figure>

In this example, the utilization is 10 / (5 + 6) or 91%. Both longs and shorts pay their pro-rata portion of the overall market interest to the maker side of the market.

### Utilization Curve <a href="#utilization-curve" id="utilization-curve"></a>

On market creation, the market operator selects a utilization function which defines the interest rate paid to makers at every level of utilization, allowing each market to have have a different delta-neutral cost of capital. Perennial uses Compound-style utilization curves that are algorithmic & continuous.

**Jump-rate Curves**

The search for a perfect curve is an ongoing battle, and these curves will need to be actively managed.

In JumpRate curves, the curve is parameterized to slowly increase in a linear fashion as utilization climbs to the target utilization at which it reaches its target rate. Then, beyond this target utilization, the rate increases rapidly to incentivize the market to rebalance back to the target utilization/rate.

To construct a jump rate curve, 4 parameters are needed:

**Min Rate**: Lowest acceptable rate

**Max Rate**: highest rate traders would be. willing to pay (sufficiently high to balance liquidity during times of high utilization)

**Target Rate**: The rate when the market is at equilibrium

**Target Utilization**: the equilibrium utilization level

$$
\left{
\begin{array}{ll}
\text{minRate} + \text{Utilization} \cdot (\text{targetRate} - \text{minRate}) & \text{Utilization} \leq \text{targetUtilization} \\
\text{targetRate} + (\text{Utilization} - \text{targetUtilization}) \cdot (\text{maxRate} - \text{targetRate}) & \text{Utilization} > \text{targetUtilization}
\end{array}
\right.
$$

Example of a JumpRate curve with the following parameters:

| MinRate | MaxRate | TargetUtilization | TargetRate |
| ------- | ------- | ----------------- | ---------- |
| 0%      | 125%    | 80%               | 15%        |

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2Fcontent.gitbook.com%2Fcontent%2FesXIGSYvKcOjqMTCdsjo%2Fblobs%2F7T3wXUKKU7BPbg3Dqfj9%2FScreen%2520Shot%25202022-11-30%2520at%25207.16.21%2520PM.png&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=57607399&#x26;sv=1" alt=""><figcaption></figcaption></figure>


# Leverage & Liquidations

### Leverage <a href="#leverage" id="leverage"></a>

Both makers & takers have the ability to trade in a more capital efficient manner by using leverage. This allows a participant's notional exposure to far exceed the amount of collateral provided. Solvency of the system is ensured by a maintenance margin & liquidation system.

$$
\text{MaximumLeverage} = \frac{1}{\text{maintenance}%}
$$

*For example: if maintenance is 20%, then 1 / 20% = 5, so 5.0x max leverage.*

#### Maintenance <a href="#maintenance" id="maintenance"></a>

A maintenance margin is set by the market operator. It is the minimum ratio of collateral to notional exposure that a market will allow. This sets how much notional exposure a maker can provide and how much leverage a taker can get.

If the value of the collateral posted by a maker or taker falls below the maintenance requirement, the maker/taker position will enter liquidation to ensure solvency of the protocol.

Both makers and takers have a maintenance requirement based on the notional of their position *times* the margin percentage requirement for the product.

**Example Product: Long-ETH @ 20% maintenance (up to 5x leverage)**

We use `ETH = $1000` for this example.

| Side  | Position | Notional | Maintenance |
| ----- | -------- | -------- | ----------- |
| Maker | 10       | $10,000  | $2,000      |
| Taker | 5        | $5,000   | $1,000      |

### Liquidations <a href="#liquidations" id="liquidations"></a>

An account can be liquidated whenever its collateral drops below the maintenance requirement of their position.

Like with any other position change, a liquidation must sit in a pending state until the next oracle update. During this period however, a special lock is placed on the account so that the liquidation process may not be interfered with. The user may not open or close a new position (or be liquidated again) until the liquidation process is completely settled and the lock is cleared.

{% hint style="info" %}
*Margin and maintenance requirements are the same: a single value both for opening and keeping open a position.*
{% endhint %}

The maintenance requirement for makers is calculated assuming 100% utilization of their exposure, so for a maker position of 10, even if the net exposure was only 1, 10 is still used as the position in the above equation. Since the utilization can change instantaneously, this is to ensure that we’re taking a worst case approach to the maintenance calculation.

$$
\text{maintenanceRequirement} = \max(\text{position} \cdot \text{price} \cdot \text{maintenance}, \text{minMaintenance})
$$

`minMaintenance` is used as a floor on the collateral to ensure that any non-zero position has a sufficient incentive to liquidate in the case of under-collateralization.

Upon successful liquidation, the liquidator is allowed to withdraw up to liquidation fee collateral from the account. This fee is optional, as you may want to self-liquidate, and can be computed as follows:

$$
\begin{aligned}
&\text{maintenance} = \max(\text{maintenanceRequirement} \cdot \text{liquidationFee}, \text{minMaintenance}) \\
&\text{liquidationFee} = \min(\text{maintenance}, \text{maxMaintenance})
\end{aligned}
$$

The `liquidationFee` is a percentage of the maintenance requirement of the position at time of liquidation, capped above and below by the maxMaintenance and minMaintence respectively.

#### Reward <a href="#reward" id="reward"></a>

Liquidators are immediately granted a liquidation reward equal to the maintenance requirement of the account *times* the `liquidationFee` upon the successful initiation of a liquidation.

**Example Liquidation: Collateral @ 20% liquidationFee**

| Collateral | Maintenance | Liquidation Reward     |
| ---------- | ----------- | ---------------------- |
| $10,000    | $15,000     | $3,000                 |
| $30,000    | $32,000     | $6,400                 |
| $25,000    | $20,000     | N/A - cannot liquidate |

Perennial does not take a protocol or product owner cut of the liquidation fee.


# Collateral

Perennial is built upon the stablecoin: Digital Standard Unit (DSU).

Think of it as *USDC+*. DSU has all the properties of USDC + additional censorship-resistance properties that protect users of DSU & the protocols that build upon it.

Properties of DSU:

* Fully collateralized
* 100%+ backed by USDC (and 1:1 redeemable for USDC)
* Trust-minimized USDC

DSU is a wrapped version of USDC (deposit 1 USDC, get 1 DSU). DSU is an ERC-20 that can that can then be used in DeFi and redeemed at any time for 1 USDC.

When the DSU protocol receives USDC, it deposits it into a DeFi protocol (namely Compound) that is liquid, battle-tested, and safe from a regulatory perspective.

The core benefit of this: DSU wrapping minimizes trust assumptions in dollar-backed stablecoins (without impacting UX) and reduces risk associated with upstream protocols, making it an ideal stablecoin primitive to build upon.

#### Use in Perennial <a href="#use-in-perennial" id="use-in-perennial"></a>

**Most Perennial users will not have to directly interact with DSU.** When a user uses the Perennial frontend with USDC as collateral, Perennial automatically wraps USDC into DSU and deposits the DSU into the protocol. When a user withdraws their collateral, Perennial will unwrap the DSU and return USDC to their wallet.

**If a user is directly interacting with the Perennial smart contracts, they will need to obtain DSU to open Maker/Taker positions.** This can be done by wrapping/unwrapping directly through the DSU smart contracts ([see here](https://github.com/emptysetsquad/emptyset)). Alternatively, for gas efficiency, developers can use the Batcher contract (see Deployed Contracts) to wrap/unwrap.

#### More info: <a href="#more-info" id="more-info"></a>

Website: [dsu.money](https://www.dsu.money/)

Docs: <https://docs.dsu.money/>


# CodeBase

Perennial V2 has been designed to be as modular as possible, allowing for horizontal scaling to many markets, oracles & vaults.

#### Ownership Hierarchy <a href="#ownership-hierarchy" id="ownership-hierarchy"></a>

In terms of structure, the protocol owns three factories covering Markets, Oracles & Vaults. The protocol owner can use these factories to spawn new markets, exotic oracles & vaults to direct liquidity. Additionally, the protocol owns the Multi Invoker (an Operator contract for the UI)

<figure><img src="https://2608572446-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FesXIGSYvKcOjqMTCdsjo%2Fuploads%2Fb53tsPq646RXGUcbeSO0%2Fperennial-v2-Protocol%20View.drawio.svg?alt=media&#x26;token=ec8f35ea-02e8-4966-915a-6101b38586e5" alt=""><figcaption><p>A hierarchical ownership tree for the perennial protocol.</p></figcaption></figure>

#### Standard Market Flow w/ MultiInvoker <a href="#standard-market-flow-w-multiinvoker" id="standard-market-flow-w-multiinvoker"></a>

When a user interacts with a market using the MultiInvoker they are able to bundle a number of steps required to modify their position.

A user takes a 1 unit position in a market.

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2F2608572446-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FesXIGSYvKcOjqMTCdsjo%252Fuploads%252F8hlaGLicChYwQlsayryD%252Fmarket_USER.drawio.png%3Falt%3Dmedia%26token%3D22422cb4-1c3c-4622-940f-cd2b61cfafa4&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=ac7b423c&#x26;sv=1" alt=""><figcaption><p>A user takes a 1 unit position in a market.</p></figcaption></figure>

#### Standard Vault flow w/ MultiInvoker <a href="#standard-vault-flow-w-multiinvoker" id="standard-vault-flow-w-multiinvoker"></a>

When a user interacts with a Vault they generally follow this flow to adjust the vault balances between markets.

<figure><img src="https://docs.perennial.finance/~gitbook/image?url=https%3A%2F%2F2608572446-files.gitbook.io%2F%7E%2Ffiles%2Fv0%2Fb%2Fgitbook-x-prod.appspot.com%2Fo%2Fspaces%252FesXIGSYvKcOjqMTCdsjo%252Fuploads%252Fxn4jvxr17Y5MRCa8uMEs%252Fuser_make.drawio.png%3Falt%3Dmedia%26token%3D619bf715-85e8-4685-84e5-d8decc5fc6f8&#x26;width=768&#x26;dpr=4&#x26;quality=100&#x26;sign=4272ac6b&#x26;sv=1" alt=""><figcaption></figcaption></figure>


# Bridging to Arbitrum

To get started, you’ll need a wallet and some ETH. Kwenta’s interface will allow you to select your preferred network and liquidity source, switch between networks, swap and bridge assets, and begin trading.

If you are totally new to DeFi, you can start with a beginner guide like [this one from Business Insider](https://www.businessinsider.com/metamask-wallet-ethereum-defi-nft-crypto-web3-user-guide-solana-2022-1). If you’ve already funded your wallet and are eager to get trading, simply follow the steps below.

## **Select the Perennial Interface on Arbitrum**

You can easily navigate through all our available networks and liquidity sources in the Futures menu in the top navigation bar of the trading interface.&#x20;

To get started using Arbitrum, choose Perennial ARB from the dropdown.

<figure><img src="https://images.mirror-media.xyz/publication-images/PnRBBJ1VwQU8DVYQ_Pkp8.png?height=1808&#x26;width=3360" alt="Navigate to the Perennial ARB interface"><figcaption></figcaption></figure>

## **Switch to the Arbitrum Network**

If you don’t already have the Arbitrum network added to your wallet, use the Switch to Arbitrum button or select the Network Selector button at the top right.

<figure><img src="https://images.mirror-media.xyz/publication-images/dSbdvesuVQibNY9gG2rHW.png?height=1808&#x26;width=3360" alt="Select Arbitrum and confirm in your DeFi Wallet"><figcaption></figcaption></figure>

## **Bridging to Arbitrum**

New to Arbitrum? We've got you covered! While withdrawing ETH and USDC directly from your favorite CEX is the fastest way to get started, Kwenta’s **Bridge & Swap** modal, powered by [Socket](https://www.socket.tech/), allows users to onboard from any network with these steps:

* Access the **Bridge & Swap** modal using the **Manage** button, found at the bottom of the order entry panel on the left side of the trading interface.
* Find your existing assets. In this screenshot, the user has USDC on the Optimism network.
* Ensure USDC on Arbitrum is selected. Use only USDC, and \*\**not* \*\*USDC.e or “Bridged USDC”. (Don’t worry! If you got the wrong one, you can always swap.)

> \*\**NOTE:* \*\**If you have never traded on Arbitrum before, you will need a small amount of ETH on the Arbitrum network for gas fees. Simply complete this process twice, but toggle the second asset to ETH on Arbitrum. Keeping greater than 0.01 ETH balance at all times is recommended.*

* Review your route to ensure acceptable speed and output. If you don’t like your route, you can change routes by selecting the gear icon.
* Depending on the assets you select, bridging may require multiple transactions.

<figure><img src="https://images.mirror-media.xyz/publication-images/1YMyo6dYbhw-bJwhXNUZc.png?height=1808&#x26;width=3360" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
Trading on Arbitrum through Perennial does not require margin deposits. Funds are transfered directly out of users wallets when a trade is placed.
{% endhint %}


# Trading on Perennial

Perpetual futures, also known as perpetual swaps, are a type of derivative contract commonly used in the cryptocurrency market. They allow traders to speculate on the future price of an underlying asset, such as Bitcoin or Ethereum, without an expiration date. This makes them different from traditional futures contracts, which have a fixed expiry date and need to be settled or rolled over at that time.

Going long and going short are two crucial concepts in trading.

Going long, also known as buying, is a strategy where traders purchase an asset with the expectation that its value will increase over time. On the other hand, going short, also known as selling short, is a strategy where traders sell an asset with the expectation that its value will decrease over time. This strategy is often used in the market by traders who believe that a particular asset is overvalued and will eventually decrease in price.&#x20;

{% hint style="info" %}
To go short, traders usually borrow assets from someone else and sell them or, to repurchase them at a lower price in the future.
{% endhint %}

Here are some essential things to take note of before beginning your trading adventure:

<table data-view="cards"><thead><tr><th data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><a href="/pages/X0OMksHU99aGn0Z0BRvQ">/pages/X0OMksHU99aGn0Z0BRvQ</a></td></tr><tr><td><a href="/pages/Z3GaPhKPIvBwjn4PzL0c">/pages/Z3GaPhKPIvBwjn4PzL0c</a></td></tr><tr><td><a href="/pages/zYA6XilKkiZwUxMfneao">/pages/zYA6XilKkiZwUxMfneao</a></td></tr><tr><td><a href="/pages/6COJRLWhMU9a8SD0TLaC">/pages/6COJRLWhMU9a8SD0TLaC</a></td></tr><tr><td><a href="/pages/3rWJNPYW2rjDpIdNGoez">/pages/3rWJNPYW2rjDpIdNGoez</a></td></tr><tr><td><a href="/pages/YszfT9AxZPnJpmf73W5W">/pages/YszfT9AxZPnJpmf73W5W</a></td></tr></tbody></table>


# Dashboard Overview

How to use Isolated margin on Perennial

### Dashboard

Below, you'll find the main dashboard for Futures on Kwenta; from here, you'll get an overview of everything Futures, any open positions, and markets available to trade.

<figure><img src="/files/48oUcpgFjqQJR0ViP83f" alt=""><figcaption></figcaption></figure>

1. The menu section contains links to other pages inside of Kwenta.
2. Displays Current Portfolio value along with a chart over time
3. A quick overview of any open positions a trader currently has.
4. The Watchlist and be accessed here (controlled by what assets you have in your favorites)
5. An overview of any open orders


# Futures UI Overview

### **Understanding the Kwenta Futures Trading Interface**

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

1. Trade history on a given asset with an optional toggle to hide this panel.
2. Price chart of the chosen contract. As well as market details:

* **Market Price** - Adjusted price, including premium/discount for the asset, based on skew
* **Index Price** - Raw asset price provided by Pyth with no skew adjustments
* **24H Change** - Dollar amount change of an asset on a rolling 24h basis
* [**Funding Rate**](/using-kwenta/perennial-isolated-margin/perennial-intro/funding-rate) - A continuous funding rate is levied on Kwenta and is charged every block. Longs pay shorts when funding is positive, and shorts pay longs when funding is negative. Funding is designed to incentivize balanced open interest. Skew is not directly proportional to funding, but impacts funding rate velocity. If skew is positive, funding is increasing, and if skew is negative, funding is decreasing.
* **Open Interest** - The total size of all outstanding positions on either side of the market
* **Skew -** The balance between long and short open interest. Positive skew means longs outnumber shorts, and negative skew means shorts outnumber longs.

4. **Market Selector** - Select the asset you wish to trade
5. **Order entry panel -** Place orders either Long (Buy) or Short (Sell). Enter the amount of collateral you wish to allocate and specify how much leverage to apply.

* Account Details
  * **Account Equity** - Total amount of unused (available margin) for your account (including UPNL)
  * **Unrealized PNL** - Amount of profit or loss waiting to be realized (accounted for in available equity)
* **Order Type**
  * Market - Execute a delayed market order at current price
  * [Limit order](/using-kwenta/perennial-isolated-margin/trading-on-perennial/conditional-orders/limit-orders) - Set an entry order to execute at a specified trigger price
  * [Stop-market](/using-kwenta/perennial-isolated-margin/trading-on-perennial/conditional-orders/stop-loss-orders) - Increase or decrease risk by setting a **trigger price once the asset has traded at or through a specified price** (the "stop price"); the order will execute
* Fee Details&#x20;
  * **Protocol Fee** - Fees imposed by the provider for making use of their liquidity
  * **Total Fees** - Sub-total of all fees to execute an order

**​5.** Pertinent information pertaining to your open position. It allows you to navigate between your position, (open) orders, trades, and transfers (deposits and withdrawals).

* **Asset name** - Displays the open positions asset, e.g. ETH-PERP, and its current value in sUSD
* **Position Direction** - Long or Short
* **Total Position size** - In asset denomination and its current sUSD value
* **Entry Price** - Average executed buy/sell price for your current position
* **Liquidation Price** - If the oracle price of the contract reaches the liquidation price when long or short, your position will be liquidated
* **Unrealized P\&L** - Displayed in sUSD and a percentage and is profit and or loss that hasn't been settled yet
* **Net Funding Rate** - Displays the current funding rebated or paid up until this point
* **TP/SL** - Displays any take profit and stop losses set for the open position


# Opening/Closing Positions

### Opening a position

Opening and closing a position functions similar to any other perps exchange.

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

* **Trade Type** and whether it is **long (buy) or short (sell)**.
  1. **Market:** To be used to open a trade immediately.
  2. **Limit**: To be used when you want to go long at a lower price than present or to go short if the price reaches a higher price than present.&#x20;
  3. **Stop:** To be used when you want to go long if the price reaches a higher price than present (breakup) or to go short if the price reaches a lower price than present (breakdown).&#x20;

{% hint style="info" %}
Conditional orders execute at an exact price, if the price reaches the condition. Fill may slightly vary depending on the Oracle price at the time the order execution is complete.
{% endhint %}

* **Collateral:** Maximum amount you are risking if you are liquidated. Your collateral to open your planned trade.
* **Leverage/Positions Size:** Traders can either pick a leverage multiplier or set their position size changes in one field will always correspond with changes in the other.
* **Your Stop Loss and Take Profit.** You are not obligated to use a stop loss, but this allows you to set up the entire trade before submitting an order.

### Closing an open position

{% hint style="info" %}
Closing an open position if all margin is exhausted or the trader doesn't have enough margin to reserve to execute the trade, the close has to be done through the `close position` modal by selecting `close` on the positions table on an open position.
{% endhint %}

<figure><img src="/files/6niAQGO2kEpuNhjo3W6s" alt=""><figcaption></figcaption></figure>

Traders can only close a position by opening the opposite direction of the current trade only if they have sufficient margin for the order to reserve for execution.


# Advanced Orders

### Advanced Orders in Perpetual Trading on Kwenta

**Introduction to Advanced Orders** Advanced orders are a powerful feature in perpetual trading on Kwenta, designed to give traders more control, flexibility, and precision in their trading strategies. These orders go beyond the basic market and limit orders, offering tools that can help you execute more sophisticated trading plans, manage risk better, and optimize your entries and exits.

### Find out more about advanced order types supported on Kwenta:

{% content-ref url="/pages/ZKR7Ab3iRPzrelXmZzQU" %}
[Limit Orders](/using-kwenta/perennial-isolated-margin/trading-on-perennial/conditional-orders/limit-orders)
{% endcontent-ref %}

{% content-ref url="/pages/1sZlxsMqU1Iz53I0V3ey" %}
[Stop-Loss Orders](/using-kwenta/perennial-isolated-margin/trading-on-perennial/conditional-orders/stop-loss-orders)
{% endcontent-ref %}


# Limit Orders

What is a limit order and how to execute it

A Limit order is an order to buy or sell a given asset at a specified (or better) price. A limit order to buy will only execute at the limit price or lower, and a limit order to sell will only execute at the limit price or higher.

<figure><img src="/files/ppq1bFWZLem5EqwvG9na" alt=""><figcaption><p>Limit Orders on Kwenta</p></figcaption></figure>

{% hint style="danger" %}
Advanced orders are only available on cross margin & have a minimum keeper requirement of 0.01 ETH.
{% endhint %}

### Place a Limit Order

1. Select the asset you are going to trade in the asset selector drop-down
2. Choose a side, either long or short
3. Pick an order type (limit order)
4. Input your desired Collateral
5. Enter your limit price in the price field&#x20;
6. Input your position size
7. Click on `Place Limit Order`

{% hint style="info" %}
The submission of the limit order is done on-chain, so any margin required to open this order will be earmarked until the order is canceled. The transaction will automatically deposit the 0.01 ETH account requirement, if applicable.
{% endhint %}

### Cancel a Limit Order

If you want to cancel a limit order before it has been executed, then click the `orders tab` and hit `Cancel` on the order that you wish to discard.&#x20;

{% hint style="success" %}
You can open multiple limit orders for the same market. You can manage your stop orders (cancel them) on the Orders tab. No fee is imposed unless the order is executed.
{% endhint %}


# Stop-Loss Orders

Stop-loss Market orders only execute when the oracle price crosses a given stop price. A market order will be placed when the price reaches a specified stop price.&#x20;

By automatically closing your positions when the price crosses the stop price (for long positions) or goes below it (for short positions), stop market orders can be used to prevent losses on your positions. Once triggered, the resulting market order will be immediately filled.

<figure><img src="/files/25Hch7RsJWjbT19wGlnT" alt=""><figcaption></figcaption></figure>

### Place a Stop-Loss Order:&#x20;

Traders need an open position to execute this order type.

1. Select the asset you are going to trade in the asset selector drop-down
2. Choose a side, either long or short (opposite of your open position)
3. Pick an order type (stop order)
4. Input your desired Collateral
5. Enter your limit price in the price field&#x20;
6. Input your position size
7. Click on `Place Stop Order`

Once you’ve executed the transaction, the order will appear under the  Orders tab. When the oracle price reaches the take profit price, the order will be executed, and your position will be opened.&#x20;

### Canceling a Stop-Loss Order

If you want to cancel a Stop-Loss order before it has been executed, then click on `Cancel` and confirm in your wallet. As mentioned above, cancellations are done on-chain so this will carry a gas fee.&#x20;

{% hint style="success" %}
You can open multiple limit orders for the same market. You can manage your stop orders (cancel them) on the Orders tab. No fee is imposed unless the order is executed.
{% endhint %}

**Stop-Market orders are dual-purpose and can be used to exit profitable or unprofitable positions at a certain price point or open new positions once a price barrier has been breached.**

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


# Gasless Trading

New on Arbitrum for the first time since launching the feature One-click trading (1CT) not only removes the need to interact with a wallet when submitting transactions but now is gasless ensuring a smooth trading experience while using Kwenta, reducing both time and user actions required to trade.&#x20;

It does this through the use of two new mechanisms:

* 1CT wallet
* Trade delegation

When utilizing 1CT, please be aware that each "enabled session" is unique to the particular browser you are using. These sessions cannot be moved or used across different browsers or devices. While you can have multiple instances open, they will all access the same 1CT account and use the ETH you have deposited there.&#x20;

{% hint style="info" %}
Each session's key is stored in the local storage of the specific browser in use. Therefore, if you decide to use a different browser or switch devices, you will have to enable a new session on each new browser or device you use.
{% endhint %}

### 1CT Wallet

Kwenta uses a derived externally owned account (EOA) wallet for submitting trading transactions. It relies on the following sequence:

* Creating a Smart Margin Account
* Creating & delegate trading rights to your 1CT account
* Activating the session

### Get Started with 1CT Now!

{% content-ref url="/pages/C3FrW4ONl4uo2j1tKBAJ" %}
[Onboarding to 1CT](/using-kwenta/perpetual-futures/one-click-trading/onboarding-to-1ct)
{% endcontent-ref %}


# Onboarding to 1-Click-Trading

Get started with your seamless trading experience

### The onboarding experience:

* Create a Smart Margin Account \
  \*If you don't have one, creating one is easy!
* Create 1CT account\
  *\*This creates, and delegates trade rights to your 1CT wallet*
* Approve USDC Spend & Enable feature

### <mark style="color:yellow;">**Step 1**</mark>**&#x20;- Finding the 1-Click Trading Feature**

To start, navigate to kwenta.eth.limo and bring up the account management interface by selecting "Deposit Funds."

{% hint style="info" %}
If USD is available in your margin account, the "Deposit Funds" button will be called "Manage"
{% endhint %}

<figure><img src="/files/s8apSSQrWahl4dInjgFG" alt=""><figcaption><p>Find 1-cick-trading settings</p></figcaption></figure>

Once in the manage interface and on the One-Click Trading tab, you will have two options:

* One-Click Trading
* Sign Every Transaction

Select One-Click Trading and select **"Activate One-Click Trading"**

### <mark style="color:yellow;">**Step 2**</mark>**&#x20;- Create a 1-Click Trading Account**

Confirm your selection of One-Click Trading and select Activate!

<figure><img src="/files/MosFqn41OJ53ovc80ovl" alt=""><figcaption><p>Step 1 in the activation will add an account delegate</p></figcaption></figure>

Success! You've created a 1CT account.

### <mark style="color:yellow;">**Step 3**</mark>**&#x20;- Approve USDC for Engine Use**

Approving this transaction allows the account to spend USDC

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

{% hint style="info" %}
Notice anything missing? The need to fund aa abstraction gas tank is no longer REQUIRED! The entire experience is gasless once activated!
{% endhint %}

### <mark style="color:yellow;">**Step 4**</mark>**&#x20;- Starting 1CT**

<figure><img src="/files/1Byx0P1ZyE8lnMjxhIDO" alt=""><figcaption><p>Select a session length &#x26; activate the 1CT Trade Session</p></figcaption></figure>

The last step is to enable the 1-Click Trading session. Select how long you would like your session to last from the Duration dropdown and sign the transaction once enable is clicked.

### <mark style="color:yellow;">**Step 5**</mark>**&#x20;- Execute Trades without the need to Sign**

<figure><img src="/files/LgXYOaLSnerVMoVSRmHQ" alt=""><figcaption><p>Execute trades without signing</p></figcaption></figure>

You can now trade on Kwenta without signing every transaction so long as "Open Trade with One-Click Trading" is selected.&#x20;

{% hint style="info" %}
Should 1CT not work, traders can unselect "Open Trade with One-Click Trading" and execute transactions traditionally.
{% endhint %}

### <mark style="color:yellow;">Disabling</mark>

To disable 1CT, simply repeat step 1 above but select the disable.&#x20;


# FAQ

**Do I have to have 1CT enabled to interact with trades I opened with it?** \
No, you may toggle the feature on and off whenever you'd like.

**Can I use the same 1CT wallet on multiple devices?**\
Yes each active session operates independently. Users can have multiple active sessions across multiple devices or browsers&#x20;

{% hint style="info" %}
Sessions cannot be remotely disabled and will run for the selected duration, we encourage users to stop their active sessions once they are done trading!
{% endhint %}

**What if my transaction is stuck?**\
Re-attempt the transaction, if the issue persist unselect disable 1CT and submit the transaction the traditional way.

**How do I cancel/end a session?**

With an active session, head back to the manage account interface and navigate to One-Click Trading. The "enable" button during setup will now be a "disable" button.

**Gas Deposits?**

None, 1CT on Arbitrum is gasless


# Staking KWENTA

Stake your Kwenta token to earn staking rewards and voting power

The Kwenta staking contract allows users to lock Kwenta tokens in exchange for various benefits.

* Staked KWENTA will gain **voting power** within the system enabling stakers to vote in Elite Council elections and CKIPs, offering the protocol a decentralized decision-making mechanism.
  * 1 $KWENTA = 1 Vote  &#x20;
* Staked KWENTA will earn **inflationary rewards**. Staked wallets with trading activity will earn additional rewards to place active Kwenta users at the center of decision-making. **Staking is only available on the Optimism L2 Network.**

{% hint style="info" %}
Staking rewards are continuously accrued and can be claimed at any time. Trading rewards are allocated to you once a week. View [KIP-3 ](https://github.com/Kwenta/KIPs/blob/master/content/kips/kip-3.md)for more details on the staking mechanism.
{% endhint %}

### Cooldown period?

The cooldown period is NEW, and the time required before unstaking your tokens is possible. The cooldown period to unstake your tokens is two weeks & the clock starts ticking from the last time a staker interacted with the v2 staking contracts. This includes adding to your staked balance with liquid $KWENTA or escrow $KWENTA.&#x20;

{% hint style="danger" %}
The cooldown period  is 7 days, but this can be further extended/reduced via governance.
{% endhint %}

**IMPORTANT:** After the cooldown period is complete, you have an unlimited window to withdraw your unstaked tokens. If you do not withdraw before interacting with the staking contract again, you will have to start the cooldown process again.&#x20;

**Example:**&#x20;

* If the cooldown period was activated 7 days ago, you could withdraw!&#x20;
* If the cooldown period was activated 7 days and 2 hours ago, you claim rewards and will now need to start the 7-day cooldown period again.&#x20;

{% content-ref url="/pages/ENBGvdwlZedsFcu2ZFRn" %}
[How to stake KWENTA](/kwenta-token/staking-kwenta/how-to-stake-kwenta)
{% endcontent-ref %}

{% content-ref url="/pages/nVw5xoEM3a2CIENLRUwS" %}
[Escrow and Vesting](/kwenta-token/staking-kwenta/escrow-and-vesting)
{% endcontent-ref %}


# How to stake KWENTA

Tutorial on how to stake your Kwenta tokens

###

{% hint style="danger" %}
The cooldown period is NEW, and the time required before unstaking your tokens is possible. The cooldown period to unstake your tokens is two weeks & the clock starts ticking from the last time a staker interacted with the v2 staking contracts. This includes adding to your staked balance with liquid $KWENTA or escrow $KWENTA.&#x20;
{% endhint %}

### Basic Steps for Staking on Optimism

1. Transfer $KWENTA to a compatible wallet: MetaMask, Trezor, Ledger, Coinbase Wallet, Trust Wallet, Rainbow Wallet, or other Wallet Connect-supported wallets.
2. Visit <https://kwenta.eth.limo/dashboard/staking/>.
3. Before proceeding, ensure you're connected to the Optimism network

### Step 1: Navigate to the Kwenta Staking Dashboard <a href="#step-1-navigate-to-the-kwenta-staking-tab" id="step-1-navigate-to-the-kwenta-staking-tab"></a>

The Kwenta *Staking* tab is a part of the Kwenta Dashboard. You can navigate to it using the sidebar on the left side of the [Dashboard.](https://kwenta.eth.limo/dashboard/)

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

### Step 2: Connect your wallet <a href="#step-2-connect-your-wallet" id="step-2-connect-your-wallet"></a>

The first step is to connect your wallet holding KWENTA tokens to the Kwenta staking page. Click the *Connect Wallet* button on the top right corner and connect your wallet of choice.

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

### Step 3: Stake KWENTA

In the staking tab, you can see the **stake or unstake** buttons:

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

This section is used to deposit your KWENTA into the staking contract and start staking. Here you can see the amount of KWENTA you have available for staking next to "Balance".

### Executing a staking transaction

* Input the amount of KWENTA you want to stake into the input field
* Approve: Send a transaction to approve the contract to stake your Kwenta
* Stake: Click on the **`Stake`** button to send your Kwenta allocation to the staking contract
* Confirm the transaction in our wallet

**Congratulations! You are now staking KWENTA!**

Inflationary KWENTA rewards are locked for a period of 1 year but transferable as they are NFTs.&#x20;

Once the one-year vesting period is complete, KWENTA can be withdrawn from the staking portal and freely used at the stakers’ discretion. KWENTA rewards that are vesting can be staked to increase voting power and weekly rewards.&#x20;


# Escrow and Vesting

Kwenta token information

### KWENTA Escrow and Vesting

* All $KWENTA rewards (staking or trading) are subject to a 12-month escrow.
* Escrowed $KWENta can be staked and will continue to earn staking rewards.
* After a 12-month lock, $KWENTA can be vested.

{% hint style="info" %}
If a staker wants to vest their $KWENTA immediately, a 90% early vest fee is applied, which diminishes linearly over the 12-month period. The potential early vest fee on escrowed KWENTA can be found under the Escrow tab.
{% endhint %}

### **How do I vest my Escrowed $KWENTA?**

* Go to <https://kwenta.eth.limo/dashboard/staking/>
* Navigate to the 'Escrow' tab and pick which escrow entries to vest.\
  Note: If there is a fee for vesting $KWENTA it will display in the UI

Once you claim staking rewards, you will have escrowed Kwenta. Escrowed Kwenta is easily managed within the Kwenta Staking UI by navigating to the *Escrow* tab on the staking dashboard:

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

All inflationary rewards and trading rewards earned on Kwenta are locked for a period of 1-year. This means that rewards will be in `Escrow` until the 1-year timer expires. Our “burn to vest” model makes escrowed rewards available immediately, **but** if vested early, any remaining % is returned (*"burned"*) to the Kwenta treasury. The early vests fee starts at %90 and goes down linearly over the course of a year.&#x20;

{% hint style="success" %}
While your escrowed KWENTA tokens vest over one year, they can also be staked to accrue additional inflationary rewards. In order to do so, escrowed Kwenta has to be staked on the Escrow tab (see box #2 below). Staked escrowed KWENTA can also be used to vote in Kwenta governance.
{% endhint %}

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

Here you will find your *Escrow* entries. Anytime a Kwenta staker claims rewards an entry is populated within this table. Information in this table includes:

* **Date -** The date the rewards were originally claimed
* **Time Until Vestable -** Time until rewards for the specific claim entry are fully vested (0% early vest fee)
* **Immediately Vestable -** Amount of KWENTA you would receive if vested now, already including the early vest fees
* **Amount -** Total amount of KWENTA claimed for a specific escrow entry
* **Early Vest Fee -** Shows the amount of KWENTA forfeited if vested early&#x20;
* **Status**
  * **Vesting -** The vesting timer has not expired; an early vest fee still applies
  * **Vested -** Escrow complete; rewards are 100% vested and have no fee to vest &#x20;

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

Since escrow tokens are stakeable, they can be used to vote in elections as well as capture additional rewards. In this entry field, stakers can choose to stake or unstake their escrowed KWENTA.&#x20;

{% hint style="warning" %}
When vesting escrowed KWENTA, staked escrowed Kwenta will be automatically unstaked and vested. There is no need to unstake escrowed KWENTA first.
{% endhint %}


# Transferring Escrow Entries

### **How do I transfer** KWENTA escrow entries?

{% hint style="danger" %}

* **Only unstaked escrow entries can be transferred!**
* We recommend that stakers unstake all escrow entries before transferring entries.&#x20;
* Unstaking is subject to a 7-day cooldown. If you need to take advantage of this feature, ensure you do not stake any additional $KWENTA for 7 days.

  Once your cooldown period has passed, unstake and transfer at any time.
* Don't forget to restake!
  {% endhint %}

Navigate to the [Kwenta Staking dashboard](https://kwenta.eth.limo/dashboard/staking/), connect your wallet & head over to the escrow tab.

<figure><img src="/files/ROaacLnFtl4wbLcmUGbJ" alt=""><figcaption><p>The escrow entries transfer button is in the "escrow" tab</p></figcaption></figure>

In the Escrow table, select the escrow entries you wish to send & select the transfer button.

> Note if a staked escrow entry is selected the button will become unavailable until the ineligble escrow entry is either unselected or unstaked&#x20;

<figure><img src="/files/hWw6BovOEANGstgcZ6hD" alt=""><figcaption><p>Select your escrow entrues and select transfer</p></figcaption></figure>

Almost done! Enter the receiving address of the selected escrow entries and sign the transaction.

> Note if you enter an ENS the app will automatically resolve the matching address for you!

<figure><img src="/files/oKW4IPoGpzMQuIcQVEqf" alt=""><figcaption><p>No turning back once this is executed</p></figcaption></figure>

Repeat these steps for any future entries you wish to transfer!


# Claiming Rewards

## Claim Rewards

When staking on Kwenta, there are two types of rewards to claim. Weekly inflationary rewards and extra trading rewards for those using the platform.

{% hint style="warning" %}
**Staking Rewards** are allocated to stakers on a continuous basis depending on your`staked balance`and can be claimed at any time.

**Trade Rewards** are allocated to stakers every Wednesday at 00:01 UTC

*<mark style="color:red;">**Any**</mark>* *<mark style="color:red;">**unclaimed rewards will accrue until claimed; however**</mark>**,\*\*\*\*&#x20;**<mark style="color:red;">**unclaimed rewards are not being vested.**</mark>*
{% endhint %}

Inflationary staking rewards can be claimed on the *Staking Dashboard*.

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

Trading rewards can be viewed & claimed in the same tab:

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

You're all done claiming; see you next time!


# Trading Rewards

With the launch of our v2 perps engine, stakers will now earn $KWENTA token rewards for both staking and trading. Holders of liquid $KWENTA tokens may also have the opportunity to earn incentives as liquidity providers. All these opportunities are now accessible from your Kwenta dashboard alongside other features available on the Kwenta exchange. Let’s dive in and learn how to stake, how to claim, and how to earn.

### Earning Trading Rewards

Kwenta stakers are eligible for a share of 5% of all inflationary rewards, which are earned by paying trading fees. To become eligible for a share of these rewards, users must:

* Have any amount of $KWENTA staked
* Place a futures trade on Kwenta ([https://www.kwenta.eth.limo](https://www.kwenta.eth.limo/))

That’s it! If both of these conditions are met before the end of each epoch, you’ll be eligible for trading rewards.

### Claiming Trading Rewards

Trading rewards are calculated and become claimable at the end of each epoch. The epoch countdown clock resets each week when rewards become claimable. After each epoch ends, you can continue trading to earn rewards for the next epoch.

To see your current qualifying fees paid during the epoch, navigate to the “Trading Rewards” section of the [Staking UI](https://kwenta.eth.limo/dashboard/staking/).

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

Total rewards are decided at the end of each epoch based on a traders rewards score. The rewards score increases as more $KWENTA is staked, and as more trading fees are paid, according to the formula below:

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

### **Individual stakers trading rewards are then evaluated as follows:**

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

Fees and staked $KWENTA are weighted with a configurable value, currently set at 0.7, adding extra weight to trading fees paid.

Once the epoch is complete, trading rewards will appear as claimable on the left side of the trading rewards page. Once the epoch ends, these rewards will keep accumulating until claimed. Like other staking rewards, these rewards are claimed as escrowed rewards and follow the same unlock schedule.

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

### Remember to stake your rewards after you claim!


# Kwenta Token

Kwenta tokenomics explained

The Kwenta token (KWENTA) will be used to incentivize coordination and growth within the Kwenta DAO. It will have two primary functions: (a) **Staking** and (b) **Governance**.

* Optimism token address: [0x920Cf626a271321C151D027030D5d08aF699456b](https://optimistic.etherscan.io/address/0x920Cf626a271321C151D027030D5d08aF699456b)

{% hint style="info" %}
Further reading: [KIP-4: Kwenta Tokenomics](https://github.com/Kwenta/KIPs/blob/master/content/kips/kip-4.md)
{% endhint %}

## Supply

KWENTA will have an initial **supply of 313,373.** Weekly emissions will start at 14,463.37 $KWENTA the first week and drop to around 200 $KWENTA (1% APY) at the end of four years. Resulting in a total supply at the end of four years of 1,009,409.43.

![Kwenta Tokenomics Chart](/files/S5LRj1HAZrYOvgs0kXnw)

* 30% - Synthetix Stakers (Complete)
* 5% - Early Synth Traders (Complete)
* 5% - Investment
* 25% - Community Growth Fund
* 15% - Core Contributors
* 20% - Kwenta Treasury

## Inflation and Fee Allocation:

<figure><img src="/files/0PJSNeNV3wFbw2wUUKg2" alt=""><figcaption></figcaption></figure>

20% of inflation is routed to the treasury, 20% of inflation is dedicated towards trading rewards (15% is earmarked for future trading incentives by the treasury) and 60% of inflation is routed to stakers.

This will enable Kwenta to sustainably fund DAO roles while enabling the community to use the entire token supply as needed.

Inflation is minted once per week by a keeper; however, this mint functionality can be called by anyone in the event the Kwenta DAO keeper is unable to mint rewards. The reward for minting is 1 KWENTA per mint.

## Vesting Mechanism

KWENTA printed via inflation will undergo a 1-year lock-up period. The lock-up mechanism will begin with an 90% fee for vesting KWENTA early which will decay linearly. If tokens are vested early, the percentage of tokens that are still applicable to the fee will be sent back to the treasury. After one year, the fee would reach 0% and no tokens would be burned when vesting KWENTA.

{% hint style="info" %}
Ex. If you have 1 $KWENTA, and its vesting, and you vest immediately, you’ll be left with 0.1 $KWENTA, if you wait a year and you vest, you get 1 $KWENTA
{% endhint %}


# Governance

Kwenta governance explained

Kwenta requires a governance framework that enables the community to coordinate on maintaining and improving the protocol. To do this, the Elite Council will vote on a system, outlined in this proposal, that will dictate roles and processes that the Kwenta community will use to operate.

By having a clear framework in which Kwenta governance will operate, the community will have the faculties it needs to achieve desired outcomes, such as a defined way to propose new features, reward DAO participants, and manage routine affairs.

{% hint style="info" %}
Further reading: <https://github.com/Kwenta/KIPs/blob/master/content/kips/kip-2.md>
{% endhint %}

## DAO Structure

![](/files/rupqOjfQY5afZoHaTrKX)

Kwenta governance follows a democratic structure with multiple semi-independent governing bodies, each with its own goals and operational structure.


# MarketingDAO

The marketingDAO is a community organization responsible for marketing and communications initiatives, and invites community members to participate in each step of the process from the ideation phase to the execution.

Join the #commmunity-marketing channel on our[ Discord](https://www.discord.gg/Kwenta) to participate in the marketingDAO.

#### **Why a marketingDAO**

Marketing efforts in DeFi often rely on input from community members, regardless of the actual structure of the organization. Kwenta strives to be an organization that is fully community built, owned, and maintained, so it is important that marketing efforts include structures that allow community participation, and compensation for marketing work. To strike a balance between open participation and unified marketing efforts, Kwenta relies on predetermined roles within the marketingDAO which are filled by community members with specific strengths and areas of interest.

**MarketingDAO PM**

The MarketingDAO PM is responsible for organizing and overseeing initiatives within the MarketingDAO, and facilitating community member participation. If you wish to participate in any aspect of the MarketingDAO or have a comment, suggestion, or question about marketing initiatives, please tag the MarketingDAO PM in the #commmunity-marketing channel on our Discord. The current MarketingDAO PM will be listed underneath the Discord role.

**How to contribute**

The marketingDAO handles a variety of tasks. Make sure you join the #community-marketing channel on the Kwenta Discord and explain a little bit about your skills. There are two primary ways to get involved.

**The Agency:**

Are you a strong communicator with a presence on social media? Ask about joining the Agency, which is Kwenta’s social media marketing group. The Agency currently includes 4 tiers, which may change over time.

**Current tiers and responsibilities include:**

* Agency Recruit: Any community member who has expressed interest in social media marketing will have access to introductory tasks to boost content related to Kwenta.&#x20;
* Special Agent: A community member who has demonstrated a base level of participation, and is invited to give suggestions and feedback on future social media marketing efforts.&#x20;
* Intelligence Officer: A community member who has demonstrated deep involvement in Kwenta, and will be asked to complete more complex tasks such as canvassing new community members or influencers and seeking out partnerships and c&#x6F;**-**&#x6D;arketing efforts with related communities.&#x20;
* Men In Black: Men In Black are trusted and involved community members who will be asked to take on administrative tasks such as drafting social media posts on Kwenta’s behalf, or serving as moderators in Kwenta communities across social media platforms.

**MarketingDAO Proposals and Tickets:**

Involvement with the Agency is not required for a community member to participate in marketing initiatives, and marketing initiatives outside the scope of the Agency are discussed openly and transparently to allow for community feedback.

**There are 2 steps to creating a marketing initiative:**

* **Marketing Ticket:** If a Marketing Proposal demonstrates a clear value to Kwenta and appropriate costs and criteria for completion have been defined, a community member may draft a Marketing Ticket, which will be approved and announced to the community by the MarketingDAO PM.&#x20;
* **Marketing tickets:** may be assigned to a community member for completion upon creation, or may be opened for community members to request assignment. Upon completion, a predetermined bounty will be awarded to the assigned community member.


# devDAO

Kwenta is a dApp enabling derivates trading - powered by the Synthetix protocol. We're community-driven and welcome all contributions. We aim to provide a constructive, respectful and fun environment for collaboration.

If you wish to help out, please first join the **Kwenta devDAO** on our Discord `#devdao-chat` channel. For more information, see [devDAO](#devdao) below.

This guide is geared towards beginners. If you're an open-source veteran feel free to just skim this document and get straight into crushing issues.

## Why Contribute

There are many reasons you might contribute to Kwenta. For example, you may wish to:

* contribute to the Ethereum ecosystem.
* establish yourself as an Ethereum developer.
* work on cutting-edge technology.
* learn how to participate in open-source projects.
* expand your software development skills.
* flex your skills in a public forum to expand your career opportunities (or simply for the fun of it).
* grow your network by working with fellow Ethereum developers.

## How to Contribute

Regardless of the reason, the process to begin contributing is very much the same. We operate like a typical open-source project operating on GitHub: the repository [Issues](https://github.com/kwenta/kwenta/issues) is where we track what needs to be done and [Pull Requests](https://github.com/kwenta/kwenta/pulls) is where code gets reviewed. We use Discord to chat and distribute tickets to community members.

## devDAO <a href="#devdao" id="devdao"></a>

The devDAO has been created specifically to foster open community development and reward community, developers. It is an essential piece in our collaborative effort to fully decentralize Kwenta.

Be welcome to join the Kwenta devDAO on our Discord `#devdao-chat`channel.

This is where discussions take place, new tickets will be announced by the devDAO PM and assigned to the respective community members and roles on a first-come, first-served base.

There are different roles depending on the severity of a ticket. As a new community member, you should watch out for *good first issue* tickets and work your way up from there.

### General Work-Flow

We recommend the following work-flow for contributors:

1. **Find an open ticket** to work on in our Discord, either because it's interesting or suitable to your skill-set. Use the `#devdao-chat channel` to communicate your intentions and ask questions.
2. **Work in a feature branch** of your personal fork (github.com/YOUR\_NAME/kwenta) of the main repository (github.com/kwenta/kwenta).
3. Once you feel you have addressed the issue, **create a pull-request** to merge your changes in to the main repository. In case of any doubts, don't hesitate to contact the community PM or ask away in the channel.
4. Wait for a CC or auditor to **review your changes** to ensure the issue is addressed satisfactorily. Optionally, mention your PR on Discord.
5. If the issue is addressed the repository maintainers will **merge your pull-request** and you'll be an official contributor!

### First-time Set-up

First-time contributors can get their git environment up and running with these steps:

1. [Create a fork](https://help.github.com/articles/fork-a-repo/#fork-an-example-repository) and [clone it](https://help.github.com/articles/fork-a-repo/#step-2-create-a-local-clone-of-your-fork) to your local machine.
2. [Add an *"upstream"* branch](https://help.github.com/articles/fork-a-repo/#step-3-configure-git-to-sync-your-fork-with-the-original-spoon-knife-repository) that tracks the Kwenta repository using `$ git remote add upstream https://github.com/kwenta/kwenta.git` (pro-tip: [use SSH](https://help.github.com/articles/connecting-to-github-with-ssh/) instead of HTTPS).
3. Create a new feature branch with `$ git checkout -b your_feature_name`. The name of your branch isn't critical but it should be short and instructive. E.g., if you're fixing a bug with serialization, you could name your branch `fix/serialization_bug`.
4. Make sure you sign your commits. See the [relevant doc](https://help.github.com/en/github/authenticating-to-github/about-commit-signature-verification).
5. Commit your changes and push them to your fork with `$ git push origin your_feature_name`.
6. Go to your fork on github.com and use the web interface to create a pull request into the Kwenta repository.

From there, the CCs or auditors will review the PR and either accept it or provide some constructive feedback.

{% hint style="info" %}
Always branch off of the`dev`branch for your contributions.
{% endhint %}

If you have any questions along the way, the community PM will be there to guide and assist you!

There's a great [guide](https://akrabat.com/the-beginners-guide-to-contributing-to-a-github-project/) by Rob Allen that provides much more detail on each of these steps, if you're having trouble. As always, jump on Discord if you get stuck.

## FAQs

### I don't think I have anything to add

There's lots to be done and there's all sorts of tasks. You can do anything from correcting typos through to writing core dApp code. If you reach out, we'll include you.

### I'm not sure my programming level is good enough

We're open to developers of all levels. If you create a PR and your code doesn't meet our standards, we'll help you fix it and we'll share the reasoning with you. Contributing to open-source is a great way to learn.

### I'm not sure I know enough about Ethereum

No problems, there's plenty of tasks that don't require extensive Ethereum knowledge. You can learn about Ethereum as you go.

### I'm afraid of making a mistake and looking silly

Don't be. We're all about personal development and constructive feedback. If you make a mistake and learn from it, everyone wins.

### I don't like the way you do things

Please, make an issue and explain why. We're open to constructive criticism and will happily change our ways.


# Contributing to the Kwenta Frontend

## Frontend

#### Introduction

To ensure that contributing to the Kwenta UI remains simple and straightforward, this document aims to provide some standards and guidelines around how the codebase is structured, and how various components interact with one another.

Please note:

1. There are areas this document does not cover. Please feel free to create an issue, or make a pull request to address them.
2. Most parts of the codebase do not adhere to these guidelines yet. Please feel free to contribute to our refactoring efforts.
3. This document is new, and evolving.

With these guidelines are in place, we should aim for the following:

* Modularity and composablity: All code should be reusable and extendable. When adding new features, existing code should not be duplicated. In the situation that a similar solution already exists in the codebase, the existing version should be updated to accommodate the new use case.
* Structure and organization: It should be apparent where code should go. This makes it easier to add new features and find where existing features are implemented.
* Best practices:
* Simplicity:
* Security: Since this code is trusted by a number of people to handle important financial transactions, it is imperative that changes and dependency updates are audited, to guard potential attack vectors.

#### Components

The codebase should contain three types of components, screen components, section components and base components. Their uses, differences and intricacies between them are outlined below:

**Screen components**

Screen components are high-level components that lay out the contents of a screen. These should generally not contain any state. In the case that it seems imperative to add some state here, developers should consider making that state global (in Recoil) instead. This will prevent prop drilling and unnecessary renders.

There should be no custom styling on screen components, as the styling should be applied on the base components or section components (if deemed absolutely necessary). In general, section components should contain fixed heights/widths if these values can be computed beforehand, to make sure that there is little to no layout shift when the UI is being rendered.

In addition to this, sometimes these components might also contain both the mobile and desktop version of certain screens (when it is impossible to handle the layout differences between both in CSS only).

**Section components**

Section components compose base components to create a functional block of the UI. They are generally stateful, and can contain their own state, or depend on global state. They generally should not contain styling, except in edge cases that are too high-level for the base components (usually these occur when dealing with difficult responsiveness issues).

They are expected to be fairly larger than screen components on average, but developers can break them down into smaller sections at their discretion, to reduce complexity and increase modularity. One advantage of doing this is that it might reveal opportunities to reuse "sub-sections" in other parts of the app, or even create new base components.

All section components must contain a target height in order to prevent layout shifting. On a refresh, all components should render with a `height` or `min-height` value and the key layout components should stay in place while components are rendered.

**Base (core) components**

Base/core components are atomic components that wrap base HTML elements and apply basic but custom logic and styling, in accordance with Kwenta's design primitives. They are the foundational layer of the entire UI. Good examples of these include: `Button`, `Icon`, `Text` etc.

The goal is for the entirety of the UI to be composed using these components. To make this possible, a number of things must be in place:

* They should have props that cover all expected states, based on the design primitives. It is important to note that these props should also be easy to update without requiring extensive refactoring.
* They must contain exhaustive, yet extendable styles that respond to the state of the component.
* They should generally be stateless. This means that the component's appearance is entirely dependent on its props at any point in time, making sure that its behaviour is predictable and easily tested.
* They should be responsive, if possible.
* They should be developed with theming in mind.
* The components and all its states should be documented in Storybook, so they can be viewed and inspected in isolation, and updated without having to disrupt feature development.

We should eventually be able to migrate the existing section components to depend on only the base components. This will reduce the number of changes we need to make if colors, sizes, border radii or other design motifs change in the future. It should also make it easier to ensure consistency in the behaviour of components across the UI.

#### Theming

Recently, we rolled out light theme support on Kwenta. This means that going forward, style changes and additions have to account for both dark and light theme variants, as well as any other themes that might be added in the future. To make this easier, the current theme is available within the body of styled-components, as well as Recoil state (should only be used if absolutely necessary). The theme definitions can also be edited or augmented, to account for new design elements, but should generally use some existing base colors.

To make sure that code changes don't break theming, this will become one of the criteria for PR reviews.

#### Translations

To support future translations of the app, all text is managed through a translation file using the `react-i18next` library. You can find the english translations at [`./translations/en.json`](https://github.com/Kwenta/kwenta/blob/main/translations/en.json).

The translations file is laid out with the primary keys being shared components (`header`, `mobile-menu`, `common`) or elements of the main navigation (`dashboard`, `futures`, `exchange`, etc.) All proposed changes must store fixed text in the translations file (instead of components) and must follow this structure.

#### Responsiveness

The existing Kwenta UI was developed with desktop users in mind. While this accounts for most users already, it is important that the experience be optimized for mobile users as well. To this end, mobile versions of the existing screens are being built. Responsiveness will also be one of the criteria for the acceptance of future pull requests.

It should be noted that this is one of the places where section components are quite handy. Section component can be easily adapted for use in mobile contexts, since they generally contain smaller portions of the interface that are reused in the mobile designs.

#### Logic (state, queries, hooks and contexts)

**State**

State management is a very important part of any application. Since this application contains a number of features, it follows that there is a lot of state to keep track of. Currently, there is a hybrid approach to managing state. Some state is stored in components (which leads to prop drilling when other components have to depend on that state), and we also store some "global" state in Recoil. There is nothing particularly wrong with this approach, but it sometimes leads to confusion. How do you know what state should be stored in Recoil vs. in section components?

A good rule of thumb is to consider the "influence" of each piece of state. This should generally influence where it should be stored. For example, the open/closed state of a modal should probably be stored inside a component, while the position data for the currently selected market should probably be stored in global state (Recoil), as it is accessed by multiple components.

A hidden benefit of global state is it removes the need to add/remove props from multiple components, or contorting component hierarchy, just to get access to state from another component.

In addition to this, selectors should be used instead of atoms when creating derived state. This removes the complexity of having to "listen" to updates from atoms, to update other atoms.

**Queries & Refetching**

Since this application depends on more than one data source (we display information from contracts, subgraphs and external APIs), handling data fetching, mutations and refetching is a complicated task.

For example, one of the problems currently being dealt with is triggering data refetches to the subgraph after data is written to a contract. While this seems trivial, there are a lot of variables to account for, including, but not limited to:

* Failed transactions
* Transaction confirmation taking a long time
* Latency between transaction confirmation and subgraph handling.

We are currently working on a solution to mitigate issues around data fetching, while also accounting for every conceivable edge case.

**Hooks**

Hooks are very helpful in ecapsulating reusable logic. The fact that hooks can also be composed to create other hooks also means that we can further extract application logic from components, so that they can be reused, optimized and tested in isolation. Ideally, the number of hooks directly accessed within components should be reduced to a bare minimum, so that there is some form of separation of concerns. Components should handle rendering and layout, while hooks handle data and state manipulation.

**Contexts**

Sometimes, we may need to hoist data that cannot be stored in state (usually functions). Sometimes, it may be possible to put the function logic in a hook and reuse it, but in other cases, it is important to share the same instance of the function (e.g. calling refetch on multiple queries). Contexts are the preferred method of handling these cases. However, it should be noted that there are usually very few situations where this is necessary, and hooks or global state are usually sufficient. A good example of a context in the codebase is the [RefetchContext](https://github.com/Kwenta/kwenta/blob/dev/contexts/RefetchContext.tsx).


# Troubleshooting

Dev Environment Setup and commonly reported issues

If you run into issues with the dev environment for the Kwenta dApp, please read the troubleshooting information below. If this doesn't help you further, don't hesitate to ask the devDAO community in the `#community-dev` channel for assistance!&#x20;

Please make sure you are on the latest stable (LTS) versions of `nodejs` and `npm`.

### NPM issues with webpack

When introducing new packages or updating packages, users reported errors, similar to these below:

```
platschi@platschi kwenta % npm run dev
[...]
TypeError: Cannot read properties of undefined (reading 'tap')
    at /Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/@next/react-refresh-utils/ReactRefreshWebpackPlugin.js:100:61
    at SyncHook.eval [as call] (eval at create (/Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/tapable/lib/HookCodeFactory.js:19:10), <anonymous>:7:1)
    at SyncHook.lazyCompileHook (/Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.newCompilation (/Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/next/node_modules/webpack/lib/Compiler.js:631:26)
    at /Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/next/node_modules/webpack/lib/Compiler.js:667:29
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:6:1)
    at AsyncSeriesHook.lazyCompileHook (/Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/tapable/lib/Hook.js:154:20)
    at Compiler.compile (/Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/next/node_modules/webpack/lib/Compiler.js:662:28)
    at /Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/next/node_modules/webpack/lib/Watching.js:77:18
    at AsyncSeriesHook.eval [as callAsync] (eval at create (/Users/platschi/Templates/devDAO/leovct/kwenta/node_modules/tapable/lib/HookCodeFactory.js:33:10), <anonymous>:15:1)
```

```
platschi@platschi kwenta % npm i
npm WARN ERESOLVE overriding peer dependency
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR! 
npm ERR! While resolving: eslint-config-react-app@6.0.0
npm ERR! Found: eslint-plugin-testing-library@5.3.1
npm ERR! node_modules/eslint-plugin-testing-library
npm ERR!   dev eslint-plugin-testing-library@"^5.1.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peerOptional eslint-plugin-testing-library@"^3.9.0" from eslint-config-react-app@6.0.0
npm ERR! node_modules/eslint-config-react-app
npm ERR!   dev eslint-config-react-app@"6.0.0" from the root project
npm ERR! 
npm ERR! Conflicting peer dependency: eslint-plugin-testing-library@3.10.2
npm ERR! node_modules/eslint-plugin-testing-library
npm ERR!   peerOptional eslint-plugin-testing-library@"^3.9.0" from eslint-config-react-app@6.0.0
npm ERR!   node_modules/eslint-config-react-app
npm ERR!     dev eslint-config-react-app@"6.0.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /Users/platschi/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/platschi/.npm/_logs/2022-04-20T17_24_43_242Z-debug-0.log
```

One temporary solution here is to do the following:

```
rm -r nodes_modules
rm package-lock.json
npm i --legacy-peer-deps
```

## Apple M1 Silicon&#x20;

When trying to run `npm run dev` on the Kwenta repository, community members with the latest M1 reported several issues with regard to the `sharp` package.&#x20;

{% hint style="success" %}
The recommended solution currently is to use Rosetta Terminal in order to avoid running into runtime errors.
{% endhint %}

There might be a possible solution by upgrading `sharp` from `v0.26` to `v0.28`.

Further possible solutions might be found here, depending on the situation:

* <https://github.com/lovell/sharp/issues/2954>
* <https://github.com/lovell/sharp/issues/2460>
* <https://github.com/lovell/sharp/issues/2460#issuecomment-751491241>

### How to set up the Kwenta dev environment on an Apple M1 Silicon machine

First, it is recommended to create a duplicate copy of the `Terminal` app. Open Finder > Applications > Utilities, right-click on `Terminal` and select *Duplicate*. Rename the new duplicated Terminal app to something useful, e.g. `Rosetta-Terminal`.

Right-click on the new `Rosetta-Terminal`and select *Get Info*. In the settings window popping up, make sure *Open with Rosetta* is checked. Now open the new duplicated app.

{% hint style="info" %}
To verify if Rosetta is working, type `arch` in the Terminal. It should return `i386`.
{% endhint %}

{% hint style="warning" %}
While it is possible to run two version of homebrew and node (M1 and Rosetta), it is recommended to remove any `arm64`homebrew or node installations to avoid issues later on.
{% endhint %}

Now install the `i386`version of homebrew according to their [website instructions](https://brew.sh/). It should install into the `/usr/local/homebrew` directory.

Once brew is installed, you can run `brew install npm`. You can verify that you installed the correct version by typing `node -p process.arch` which should return `x64`.

Now, you are ready to clone your fork of the Kwenta repository. If you already cloned the repository earlier, make sure to delete the `node_modules`folder. Once done, run `npm i` and start your local environment with `npm run dev`. Voila, it should work now.

If you have questions or still run into trouble, do not hesitate to join our Discord channel and ask away in the `#community-dev`channel.

## Windows

Community members on Windows reported the following issue:

```
error: cannot spawn .husky/pre-commit: Invalid argument
```

In order to fix this issue, open the `.husky/pre-commit` file in your favourite text editor and edit the following:

```git
-# #!/bin/sh
+#!/bin/sh
```

Additionally, the `.eslintrc` file might need to be changed:

```diff
    "plugins": ["prettier"],
    "rules": {
             "react/react-in-jsx-scope": "off",
-            "prettier/prettier": "error",
+           "prettier/prettier": ["error",
+            {
+                "endOfLine": "auto"
+            }
+            ],
              "no-mixed-spaces-and-tabs": ["warn", "smart-tabs"], 
```

<br>


# Testing

devDAO guide to set up automated e2e testing with Kwenta

### Introduction

Automated end-2-end (e2e) testing for functional scenarios of the Kwenta dApp is essential for detecting regressions in functionality after updates. To reduce technical debt, the devDAO is assisting the [Core Contributors](broken://pages/BkKcUMpDRKKP6dY5ZR3D) in developing an e2e testing framework for the Kwenta dApp.

### Current Status

At the moment, two e2e test for UI features are available:

* Wallet login: `login-spec.js`
* Exchange: `trade-spec.js`

Bounty hunters of the devDAO are currently working on improving and adding additional e2e tests for all other major UI features. If you're interested in helping out, don't be shy to drop a line in the `#community-dev` channel on our [Discord](https://discord.gg/)!

### How-to: End-2-end testing guidance

In order to run fully automated end-2-end (e2e) tests Kwenta uses [Synpress](https://github.com/Synthetixio/synpress) (a wrapper around [Cynpress](https://www.cypress.io/)).

{% hint style="success" %}
Contact the community PM on Discord if you're working on a ticket and are looking for kETH and Kovan sUSD for testing purposes.
{% endhint %}

#### **Constraints**

The current e2e tests are written to be run on Optimistic Kovan using Chrome as the browser.

#### **Setup**

* Download and install Google Chrome
* Setup a test wallet on Optimistic Kovan and fund it with plenty of ETH (to pay for gas) and sUSD
* Prior to running the tests you must set the environment variables below in the shell from which npm is started. Unfortunately, at this time other methods to set said environment variables (eg. through `.env.local`) don't work in conjunction with Synpress.

```bash
PRIVATE_KEY=<INSERTPRIVATEKEY>
NETWORK_NAME=OptimisticKovan
RPC_URL=https://kovan.optimism.io
CHAIN_ID=69
BLOCK_EXPLORER=https://kovan-optimistic.etherscan.io
IS_TESTNET=true
```

#### **Bash convenience script for setting up the environment**

A Bash convenience script [has been made available here](https://gist.github.com/raffiegang/b24a6b97bcd054645abf59be852bc88d).

* Open bash
* Copy the private key of the test wallet into the file `SYNPRESS_PRIVATEKEY` into the same folder location as the script. While using this method, please don't forget to update your .gitignore file to prevent your private key to be leaked.
* Run the following command `source ./synpress-envsetter.sh`

#### Run the tests

```bash
npm run build
npm start
npm run test:e2e:only:tests
```


# Deployed Contracts

### KWENTA:

{% hint style="success" %}
Optimism token address: [0x920Cf626a271321C151D027030D5d08aF699456b](https://optimistic.etherscan.io/address/0x920Cf626a271321C151D027030D5d08aF699456b)
{% endhint %}

### Base Mainnet:

<table><thead><tr><th width="224">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Smart Margin v3 Engine</td><td><a href="https://basescan.org/address/0xD1F129e0cDd3Cc5c65ea00041623841C3d709F83">0xD1F129e0cDd3Cc5c65ea00041623841C3d709F83</a></td></tr><tr><td>Smart Margin v3 Engine Proxy</td><td><a href="https://basescan.org/address/0xe331a7eeC851Ba702aA8BF43070a178451d6D28E">0xe331a7eeC851Ba702aA8BF43070a178451d6D28E</a></td></tr></tbody></table>

### Base Sepolia Testnet:

<table><thead><tr><th width="224">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Smart Margin v3 Engine</td><td><a href="https://sepolia.basescan.org/address/0x33B725a1B2dE9178121D423D2A1c062C5452f310">0x33B725a1B2dE9178121D423D2A1c062C5452f310</a></td></tr><tr><td>Smart Margin v3 Engine Proxy</td><td><a href="https://sepolia.basescan.org/address/0xe5bB889B1f0B6B4B7384Bd19cbb37adBDDa941a6">0xe5bB889B1f0B6B4B7384Bd19cbb37adBDDa941a6</a></td></tr></tbody></table>

### Optimism Mainnet:

#### Smart Margin v2.1.0 (latest):

<table><thead><tr><th width="224">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Smart Margin Account Factory</td><td><a href="https://optimistic.etherscan.io/address/0x8234F990b149Ae59416dc260305E565e5DAfEb54">0x8234F990b149Ae59416dc260305E565e5DAfEb54</a></td></tr><tr><td>Smart Margin Account Implementation</td><td><a href="https://optimistic.etherscan.io/address/0x83E13069aA457778ca349E0128927B417A2c2B3f#code">0x83E13069aA457778ca349E0128927B417A2c2B3f</a></td></tr><tr><td>Smart Margin Events</td><td><a href="https://optimistic.etherscan.io/address/0xB753d2EE5dcA1fF39A83CA3Ec500656c31Be940b">0xB753d2EE5dcA1fF39A83CA3Ec500656c31Be940b</a></td></tr><tr><td>Smart Margin Settings</td><td><a href="https://optimistic.etherscan.io/address/0x865dA103d126b3Be3599D84caB57109A861F5631#code">0x865dA103d126b3Be3599D84caB57109A861F5631</a></td></tr></tbody></table>

#### Token:

<table><thead><tr><th width="300">Contract</th><th width="546">Address</th></tr></thead><tbody><tr><td>SupplySchedule</td><td><a href="https://optimistic.etherscan.io/address/0x3e8b82326Ff5f2f10da8CEa117bD44343ccb9c26">0x3e8b82326Ff5f2f10da8CEa117bD44343ccb9c26</a></td></tr><tr><td>RewardEscrow v1</td><td><a href="https://optimistic.etherscan.io/address/0x1066A8eB3d90Af0Ad3F89839b974658577e75BE2">0x1066A8eB3d90Af0Ad3F89839b974658577e75BE2</a></td></tr><tr><td>StakingRewards v1</td><td><a href="https://optimistic.etherscan.io/address/0x6e56a5d49f775ba08041e28030bc7826b13489e0">0x6e56a5d49f775ba08041e28030bc7826b13489e0</a></td></tr><tr><td>vKwentaRedeemer</td><td><a href="https://optimistic.etherscan.io/address/0x8132EE584bCD6f8Eb1bea141DB7a7AC1E72917b9">0x8132EE584bCD6f8Eb1bea141DB7a7AC1E72917b9</a></td></tr><tr><td>Multiple Merkle Distributor</td><td><a href="https://optimistic.etherscan.io/address/0x2787cc20e5ecb4bf1bfb79eae284201027683179">0x2787cc20e5ecb4bf1bfb79eae284201027683179</a></td></tr><tr><td>Staking Rewards Notifier</td><td>0x03f6dC6e616AB3a367a1F2C26B8Bc146f632b451</td></tr><tr><td>RewardEscrowV2 Proxy</td><td>0xb2a20fCdc506a685122847b21E34536359E94C56</td></tr><tr><td>StakingRewardsV2 Proxy</td><td>0x61294940CE7cD1BDA10e349adC5B538B722CeB88</td></tr><tr><td>EscrowMigrator Proxy</td><td>0xC9aF789Ae606F69cF8Ed073A04eC92f2354b027d</td></tr><tr><td>RewardEscrowV2</td><td>0x15725a8159629ca9763deC4211e309c94d9f5CB0</td></tr><tr><td>StakingRewardsV2 </td><td>0x626e666c95f4a31439A9cA2d5ef757EA3d72A2fd</td></tr><tr><td>EscrowMigrator</td><td>0x10B04483d762Bd4F193F35600112ad52391004A7</td></tr></tbody></table>

#### Swaps:

<table><thead><tr><th width="224">Contract</th><th>Address</th></tr></thead><tbody><tr><td>SynthSwap (Swaps)</td><td><a href="https://optimistic.etherscan.io/address/0x6d6273f52b0C8eaB388141393c1e8cfDB3311De6">0x6d6273f52b0C8eaB388141393c1e8cfDB3311De6</a></td></tr></tbody></table>

### Optimism Görli Testnet:

#### Smart Margin v2.1.0 (latest):

<table><thead><tr><th width="224">Contract</th><th>Address</th></tr></thead><tbody><tr><td>Smart Margin Account Factory</td><td><a href="https://goerli-optimism.etherscan.io/address/0x30582eeE34719fe22b1B6c3b607636A3ab94522E">0x30582eeE34719fe22b1B6c3b607636A3ab94522E</a></td></tr><tr><td>Smart Margin Account Implementation</td><td><a href="https://goerli-optimism.etherscan.io/address/0x0fcef9608b9f7a8c57d53b98e78fa64b4d786a9f#contracts">0x0fCeF9608B9F7a8C57D53B98E78fA64b4D786a9F</a></td></tr><tr><td>Smart Margin Events</td><td><a href="https://goerli-optimism.etherscan.io/address/0xe32F27B27F4ea5f10f269b52223910bA83e2933C#code">0xe32F27B27F4ea5f10f269b52223910bA83e2933C</a></td></tr><tr><td>Smart Margin Settings</td><td><a href="https://goerli-optimism.etherscan.io/address/0x8B9CbD3da94c637c0652c680Abd3CF7f787aBAF4#code">0x8B9CbD3da94c637c0652c680Abd3CF7f787aBAF4</a></td></tr></tbody></table>


# V2 Futures Market Proxy Contracts

| PerpsV2ProxyAAVEPERP  | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x5374761526175B59f1E583246E20639909E189cE](https://optimistic.etherscan.io/address/0x5374761526175B59f1E583246E20639909E189cE) |
| --------------------- | ---------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
| PerpsV2ProxyAPEPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x5B6BeB79E959Aac2659bEE60fE0D0885468BF886](https://optimistic.etherscan.io/address/0x5B6BeB79E959Aac2659bEE60fE0D0885468BF886) |
| PerpsV2ProxyATOMPERP  | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0xbB16C7B3244DFA1a6BF83Fcce3EE4560837763CD](https://optimistic.etherscan.io/address/0xbB16C7B3244DFA1a6BF83Fcce3EE4560837763CD) |
| PerpsV2ProxyAUDPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x9De146b5663b82F44E5052dEDe2aA3Fd4CBcDC99](https://optimistic.etherscan.io/address/0x9De146b5663b82F44E5052dEDe2aA3Fd4CBcDC99) |
| PerpsV2ProxyAVAXPERP  | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0xc203A12F298CE73E44F7d45A4f59a43DBfFe204D](https://optimistic.etherscan.io/address/0xc203A12F298CE73E44F7d45A4f59a43DBfFe204D) |
| PerpsV2ProxyAXSPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x3a52b21816168dfe35bE99b7C5fc209f17a0aDb1](https://optimistic.etherscan.io/address/0x3a52b21816168dfe35bE99b7C5fc209f17a0aDb1) |
| PerpsV2ProxyBNBPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x0940B0A96C5e1ba33AEE331a9f950Bb2a6F2Fb25](https://optimistic.etherscan.io/address/0x0940B0A96C5e1ba33AEE331a9f950Bb2a6F2Fb25) |
| PerpsV2ProxyBTCPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x59b007E9ea8F89b069c43F8f45834d30853e3699](https://optimistic.etherscan.io/address/0x59b007E9ea8F89b069c43F8f45834d30853e3699) |
| PerpsV2ProxyDOGEPERP  | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x98cCbC721cc05E28a125943D69039B39BE6A21e9](https://optimistic.etherscan.io/address/0x98cCbC721cc05E28a125943D69039B39BE6A21e9) |
| PerpsV2ProxyDYDXPERP  | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x139F94E4f0e1101c1464a321CBA815c34d58B5D9](https://optimistic.etherscan.io/address/0x139F94E4f0e1101c1464a321CBA815c34d58B5D9) |
| PerpsV2ProxyETHPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x2B3bb4c683BFc5239B029131EEf3B1d214478d93](https://optimistic.etherscan.io/address/0x2B3bb4c683BFc5239B029131EEf3B1d214478d93) |
| PerpsV2ProxyEURPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x87AE62c5720DAB812BDacba66cc24839440048d1](https://optimistic.etherscan.io/address/0x87AE62c5720DAB812BDacba66cc24839440048d1) |
| PerpsV2ProxyFLOWPERP  | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x27665271210aCff4Fab08AD9Bb657E91866471F0](https://optimistic.etherscan.io/address/0x27665271210aCff4Fab08AD9Bb657E91866471F0) |
| PerpsV2ProxyFTMPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0xC18f85A6DD3Bcd0516a1CA08d3B1f0A4E191A2C4](https://optimistic.etherscan.io/address/0xC18f85A6DD3Bcd0516a1CA08d3B1f0A4E191A2C4) |
| PerpsV2ProxyGBPPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x1dAd8808D8aC58a0df912aDC4b215ca3B93D6C49](https://optimistic.etherscan.io/address/0x1dAd8808D8aC58a0df912aDC4b215ca3B93D6C49) |
| PerpsV2ProxyLINKPERP  | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x31A1659Ca00F617E86Dc765B6494Afe70a5A9c1A](https://optimistic.etherscan.io/address/0x31A1659Ca00F617E86Dc765B6494Afe70a5A9c1A) |
| PerpsV2ProxyMATICPERP | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x074B8F19fc91d6B2eb51143E1f186Ca0DDB88042](https://optimistic.etherscan.io/address/0x074B8F19fc91d6B2eb51143E1f186Ca0DDB88042) |
| PerpsV2ProxyNEARPERP  | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0xC8fCd6fB4D15dD7C455373297dEF375a08942eCe](https://optimistic.etherscan.io/address/0xC8fCd6fB4D15dD7C455373297dEF375a08942eCe) |
| PerpsV2ProxyOPPERP    | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x442b69937a0daf9D46439a71567fABE6Cb69FBaf](https://optimistic.etherscan.io/address/0x442b69937a0daf9D46439a71567fABE6Cb69FBaf) |
| PerpsV2ProxySOLPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x0EA09D97b4084d859328ec4bF8eBCF9ecCA26F1D](https://optimistic.etherscan.io/address/0x0EA09D97b4084d859328ec4bF8eBCF9ecCA26F1D) |
| PerpsV2ProxyUNIPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x4308427C463CAEAaB50FFf98a9deC569C31E4E87](https://optimistic.etherscan.io/address/0x4308427C463CAEAaB50FFf98a9deC569C31E4E87) |
| PerpsV2ProxyXAGPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0xdcB8438c979fA030581314e5A5Df42bbFEd744a0](https://optimistic.etherscan.io/address/0xdcB8438c979fA030581314e5A5Df42bbFEd744a0) |
| PerpsV2ProxyXAUPERP   | [ProxyPerpsV2.sol](https://github.com/Synthetixio/synthetix/blob/v2.83.1/contracts/ProxyPerpsV2.sol) | [0x549dbDFfbd47bD5639f9348eBE82E63e2f9F777A](https://optimistic.etherscan.io/address/0x549dbDFfbd47bD5639f9348eBE82E63e2f9F777A) |


# Verify Kwenta

This article explains how to verify the advanced decentralized deployment

Kwenta is currently hosted on the distributed [`IPFS`](https://ipfs.io/#how) network. Each release is stored with an unique cryptographical hash on this network. These hashes however are difficult to remember, hence gateways such as `eth.limo` exist.<br>

{% hint style="info" %}
Users with the IPFS Companion extension installed (or Brave Browser which comes with IPFS built-in) can visit Kwenta by visiting `kwenta.eth/,`bypassing the centralized gateway.&#x20;
{% endhint %}

\
This article explains different ways on how to verify that when you visit [`kwenta.eth.limo`](https://kwenta.eth.limo), you are actually seeing the currently endorsed release voted on by the Kwenta Elite Council in accordance with [`KIP-22`](https://github.com/Kwenta/KIPs/blob/master/content/kips/kip-22.md).

### Check ENS records

The Elite Council has control over the ENS records set for the `kwenta.eth` domain name via a multisig. When a new release IPFS hash is proposed by the DAO, the Elite Council needs to verify and sign a transaction in order to change the ENS record to point to the new release IPFS hash.&#x20;

In order to check the latest IPFS hash signed by the Elite Council, head over to [`https://ens.domains`](https://ens.domains) and search for `kwenta.eth`. Under *Records,* you will find the correct IPFS hash set which the `eth.limo` gateway is pointing to for kwenta:

<figure><img src="/files/ZYOHwdLDa9NxwdyPpgpp" alt="Verify Kwenta ENS"><figcaption><p>Kwenta ENS Records</p></figcaption></figure>

### Check on GitHub

But where does the DAO derive this IPFS hash from? To check this, you can head over to GitHub where releases are currently published. Note that this solution is temporary and will change in the future due to the envisioned switch to Radicle [(KIP-31).](https://github.com/Kwenta/KIPs/blob/master/content/kips/kip-31.md)

Currently the devDAO publishes information on new releases to <https://github.com/Kwenta/kwenta/releases>. Each new release includes the IPFS hashes of the new deployments, as well as a summary of the changes. Community members can read through the changes and audit the code that has been changed since the last release.

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

You can now verify the `CIDv1` IPFS hash with the hash shown on ENS (see above).&#x20;

To fully verify that the IPFS hash relates to the release shown on GitHub, you can also verify the commit hash by double checking the commit hash shown on the release (see left sidebar of the screenshot) with the latest git hash printed on any page on Kwenta at the very bottom:

<figure><img src="/files/G10mLCC26mQ4g7dFPVW6" alt=""><figcaption><p>Release git commit hash at the bottom of Kwenta</p></figcaption></figure>

As seen in the screenshots, the hash `7e409f3` matches on both Github and Kwenta.

If you now visit Kwenta on IPFS and all hashes match, you can be relatively certain that you are visiting the correct and Elite Council endorsed version of Kwenta.

{% hint style="info" %}
A commit hash is a cryptographic checksum that is calculated from the state of the repository.
{% endhint %}


# Kwenta SDK

## Kwenta Python SDK

Python SDK to interact with Kwenta's smart contracts, subgraphs, and Synthetix perps.

### Installation

Install the SDK using pip:

```bash
  pip install kwenta
```

For more information on usage, see the Usage section and the sample scripts.

### Development

Create a python virtual environment, activate it and install libraries:

```bash
python3 -m venv env
source env/bin/activate
pip install -r requirements.txt
pip install -e ./module
```

This method will install the local version of the module in editable mode. You can make changes to the SDK and test them without reinstalling the module.

### Usage

To configure an instance of the Kwenta SDK, you need to specify some parameters. At minimum you need to specify the `network_id` and `provider_rpc` to read data from the contracts. If you specify a `wallet_address` and `private_key` you can also submit transactions or create transaction data using the SDK.:

```python
from kwenta import Kwenta

kwenta = Kwenta(
    network_id=10,
    provider_rpc=YOUR_RPC,
    wallet_address=YOUR_ADDRESS,
    private_key=YOUR_PRIVATE_KEY
)
```

### VERSIONS

SDK Versions below 1.6.0 will only support Kwenta V1 isolated margin. Please use the current version to utilize Smart Margin functionality.

#### Queries / Subgraphs:

Queries will default to Kwenta's public Hosted Service endpoints for The Graph.

* To fetch perps data specify endpoint `gql_endpoint_perps`: defaults to [Optimism-perps subgraph](https://thegraph.com/hosted-service/subgraph/kwenta/optimism-perps)
* To fetch rates specify endpoint `gql_endpoint_perps`: defaults to [Optimism-perps subgraph](https://thegraph.com/hosted-service/subgraph/kwenta/optimism-perps)

#### Pyth:

* Specify the endpoint of a Pyth price service as `price_service_endpoint` defaults to the public Pyth price service. This should be updated for any production applications to use a private Pyth price service.

#### Telegram:

1. Search telegram for bot named "@botfather"
2. Message the bot with and type "/newbot"
3. Input bot name (This will become channel name)
4. Specify API token as `telegram_token`
5. Specify channel name as `telegram_channel_name`

### Features

`kwenta`:

* Fetch market info
* Fetch position info
* Open positions
* Close positions
* Modify open positions
* Transfer margin
* Execute and cancel orders
* Limit and stop limit orders

`kwenta.queries`:

* Fetch historical trades
* Fetch historical positions

`kwenta.pyth`:

* Fetch price update data from Pyth price feed

### Initialization Parameters

| Parameter                | Type     | Description                                                                            |
| ------------------------ | -------- | -------------------------------------------------------------------------------------- |
| `provider_rpc`           | `string` | **Required.** Endpoint for the provider's RPC.                                         |
| `wallet_address`         | `string` | **Required.** Wallet address for transactions.                                         |
| `sm_address`             | `string` | **Optional.** Address of the smart contract, defaults to None.                         |
| `private_key`            | `string` | **Optional.** Private key for the wallet, defaults to None.                            |
| `network_id`             | `int`    | **Optional.** Network ID to connect to, defaults to None.                              |
| `use_estimate_gas`       | `bool`   | **Optional.** Whether or not to use gas estimation for transactions, defaults to True. |
| `gql_endpoint_perps`     | `string` | **Optional.** GraphQL endpoint for perps, defaults to None.                            |
| `gql_endpoint_rates`     | `string` | **Optional.** GraphQL endpoint for rates, defaults to None.                            |
| `price_service_endpoint` | `string` | **Optional.** Endpoint for the price service, defaults to None.                        |
| `telegram_token`         | `string` | **Optional.** Token for the Telegram bot, defaults to None.                            |
| `telegram_channel_name`  | `string` | **Optional.** Name of the Telegram channel for notifications, defaults to None.        |


# Audits

Kwenta has been audited extensively by several security specialists: Macro, Iosiro, Omniscia, 0xCommit, and other highly respected independent auditors.&#x20;

The latest audits of any Kwenta smart contracts can be found below or within respective GitHub repositories.

## Smart Margin v2 Audits

{% embed url="<https://github.com/Kwenta/smart-margin/blob/main/audits/v1.0.0/Kwenta_A-3.pdf>" %}

{% embed url="<https://github.com/Kwenta/smart-margin/blob/main/audits/v2.0.0/Kwenta_A-4.pdf>" %}

{% embed url="<https://github.com/Kwenta/smart-margin/blob/main/audits/v2.0.2/Kwenta_A-5.pdf>" %}

{% embed url="<https://github.com/Kwenta/smart-margin/blob/main/audits/v2.1.0/Kwenta_A-6.pdf>" %}

{% embed url="<https://github.com/Kwenta/smart-margin/blob/main/audits/v2.1.1/Kwenta%20A-9%20|%20Macro%20Audits%20|%20The%200xMacro%20Library.pdf>" %}

## Smart Margin v3 Audits

{% embed url="<https://github.com/Kwenta/smart-margin-v3/blob/main/audits/external/v3.0.0/Kwenta%20A-11.pdf>" %}
SMv3 0xMacro A-11
{% endembed %}

{% embed url="<https://github.com/Kwenta/smart-margin-v3/blob/main/audits/external/v3.0.0/kwenta-smv3-guhu.md>" %}
SMv3 Guhu
{% endembed %}

{% embed url="<https://github.com/Kwenta/smart-margin-v3/blob/main/audits/external/v3.0.0/09192023_Omniscia_Audit_Kwenta_SmartMarginV3.pdf>" %}
SMv3 Omniscia
{% endembed %}

{% embed url="<https://github.com/Kwenta/smart-margin-v3/blob/main/audits/external/v3.0.0/Kwenta%20A-8%20|%20Macro%20Audits%20|%20The%200xMacro%20Library.pdf>" %}
SMv3 0xMacro A-8
{% endembed %}

## SCW-Contracts Audits

{% embed url="<https://github.com/Kwenta/scw-contracts/blob/main/audits/0xCommit.pdf>" %}

## Staking V2 Audits

[Guhu](https://github.com/guhu95): - <https://gist.github.com/guhu95/3330fad8e6417b567a3787f86392ae32>

[Macro](https://0xmacro.com/): - <https://0xmacro.com/library/audits/kwenta-7.html>

[Omniscia](https://omniscia.io/): - <https://omniscia.io/reports/kwenta-staking-v2-w-migrators-64e48aba18c4480014cf4897/>


# Development progress Epoch 1 2024

Progress of major milestones

<table><thead><tr><th width="234">Component</th><th width="169.33333333333331">Status</th><th>Notes / further reading</th></tr></thead><tbody><tr><td>Smart Margin V2</td><td>✅ on mainnet</td><td><a href="https://mirror.xyz/kwenta.eth/I9l_QSOvf6kGQos3SXltES9WCAvEklS56aIbKHccHUg">V2 Smart Margin is live</a></td></tr><tr><td>Python SDK</td><td>✅ on mainnet</td><td></td></tr><tr><td>Staking V2</td><td>✅ on mainnet</td><td></td></tr><tr><td>Referral Program</td><td>✅ on mainnet</td><td></td></tr><tr><td>One Click Trading</td><td>✅ on mainnet</td><td></td></tr><tr><td>Smart Margin/Perps V3</td><td>✅ on mainnet</td><td></td></tr><tr><td>Delegated Trading</td><td>✅ on mainnet</td><td></td></tr></tbody></table>

{% embed url="<https://mirror.xyz/kwenta.eth/I9l_QSOvf6kGQos3SXltES9WCAvEklS56aIbKHccHUg>" %}
The Kwenta Margin Engine
{% endembed %}


