# Welcome to Sudo

## Overview

Sudo is the first on-chain perpetual protocol built with Move on Sui. It provides traders sub-second speed and zero price impact trading experience on-chain. It also allows high leverage trading with zero slippage.

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

## Quick links

{% content-ref url="/pages/ov2MtlnWLBPyIS5EnBJq" %}
[What is Sudo](/overview/what-is-sudo)
{% endcontent-ref %}

{% content-ref url="/pages/ww1uIzQdZ7mRGWbIyFSa" %}
[Sudo Features](/overview/sudo-features)
{% endcontent-ref %}


# What is Sudo

Sudo is the first on-chain perpetual protocol built with Move on Sui. It provides traders sub-second speed and zero price impact trading experience on-chain. It also allows high leverage trading with zero slippage.

Try out Sudo: <https://app.sudo.finance>\
\
You can contact Sudo team on following platforms:

\
Twitter / X: [@sudofinance](https://twitter.com/sudofinance) \
Discord: <https://discord.gg/Jrm7nnuAFa>\
Telegram: <https://t.me/sudofinanceperps>


# Sudo Features

## Trading Features

* **No Account Required**: Sudo enables users to trader without registration, facilitating quick and convenient access to trading.
* **High Leverage:** Depending on the token type, Sudo offers up to 25X leverage, allowing traders to enhance their potential returns.
* **Zero Price Impact:** By utilizing concentrated liquidity from Sudo Liquidity Providers and oracle feed price, the platform ensures that traders can enter and exit positions at market prices without impacting market rates.
* **Decentralized Quotation:** To maintain transparent and stable pricing, Sudo incorporates multiple data sources, such as mainstream oracles and self-quotation through leading exchanges. We use **Pyth** [price feed oracle](https://pyth.network/price-feeds) to ensure low latency and high frequency price updates.

## Liquidity Provider Feature

* **Protocol Fee Sharing:** By becoming a LP on Sudo, you are entitled to protocol fee earned on the platform
* **Mint and Redeem at your ease:** You can mint SLP and redeem your assets back at anytime within market hour.
* **LP Privileges:** LPs are entitled to certain privileges on the platform, for instance, early access to features and new alphas.

##


# Start trading

Sudo is live on mainnet! Make your first trade [here](https://app.sudo.finance)

### Step 1: Connect Wallet

Connect your preferred wallet to Sudo

<div align="center" data-full-width="false"><figure><img src="/files/OKedSlYXwehVunxYUUVD" alt=""><figcaption></figcaption></figure></div>

### Step 2: Open a position

Find a pair you want to open position against:

<figure><img src="/files/D7Y0QY7HTA1G8367PR3f" alt="" width="287"><figcaption></figcaption></figure>

Please click either "Long" or "Short" based on your preference for opening a leveraged position.

<figure><img src="/files/M90sLMFC5knkG9srLR0R" alt="" width="354"><figcaption></figcaption></figure>

* Long position
  * Profit is gained if the token's price increases.
  * Loss is incurred if the token's price decreases.
* Short position
  * Profit is gained if the token's price decreases.
  * Loss is incurred if the token's price increases.

Once you've chosen your preferred position, you can select any index token from the dropdown menu as collateral. The corresponding value of your collateral in USD will be displayed. Upon entering your collateral amount and selecting your desired leverage level, the quantity of the underlying asset will be automatically calculated.

In the below example 15 USDC (worth 15 USD) is being used to buy a 10x BTC long position of size 150 USD.

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

The "Entry Price" is $101,096 and the estimated liquidation price is $90,986.4.

The trading fee to open and close a position is normally 0.15% - 0.3% of the position size.

"Reserving Fee Rate" is deducted every 8 hours, which is paid to liquidity providers based on the reserve amount. The hourly reserving fee is calculated as (borrowed assets) / (total assets in the pool) \* 0.01%.

Although trades don't cause price impacts, potential slippage can occur due to price changes between when a trade is submitted and confirmed on the blockchain. Slippage represents the disparity between the expected trade price and the actual execution price. Customizing slippage can be done by clicking the "settings" option below "short" in the above screenshot.

At the commencement of each 8-hour period, a funding fee is also deducted. This fee can be either positive or negative to facilitate adjustments. See "Algorithm Balanced Funding Rate" for more details.

#### Managing Positions

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

Once a trade is initiated, it becomes visible in your Positions list. By selecting "Adjust," you can deposit or withdraw collateral, enabling you to control your leverage and liquidation price. When you initiate a position or deposit collateral, a snapshot of your collateral's USD price is captured. For instance, if your collateral is 15 USDC and the entry price of BTC is $101,096 at that time, your size is 141.48 USD. This value remains constant even if BTC's price changes.

Leverage for a position is indicated as (position size + PnL - Fees) / (position collateral).

#### **Closing a Position**

You can fully or partially close a position by clicking the 'Close' button. Profits are disbursed in the same asset you used as collateral. For example, if you went long on BTC with USDC as collateral, your profits will be in USDC.

#### **Liquidation**

The Liquidation Price is determined as the price at which (collateral - losses - reserving fee) becomes less than 2% of your position's size. If the token's price crosses this threshold, the position is automatically liquidated. Due to changes in collateral prices and the reserving fee, your liquidation price alters over time. If you request a sizable reserve value from the Sudo Liquidity Pool, the reserving fee will be notably higher, your liquidation price will also be affected. Any remaining collateral after accounting for losses and fees will be returned to your account.


# Supported Assets

Sudo offers a variety of crypto assets:

BTC / USD

ETH / USD

SOL / USD

XRP / USD

DOGE / USD

SUI / USD

NAVX / USD

BONK / USD

CETUS / USD

and more...

Sudo leans on **pyth** for low-latency price feed to determine asset price.


# Fees

We charge following fees when you trade on our platform:

#### **Open/Close Position**

| Symbol | Supported Collaterals | Max Leverage | Open / Close Fee Bps | Minimum Holding Duration (Second) | Max Funding Fee Bps |
| ------ | --------------------- | ------------ | -------------------- | --------------------------------- | ------------------- |
| BTC    | ALL                   | 25/25        | 25/25                | 180                               | 10/10               |
| ETH    | ALL                   | 25/25        | 25/25                | 180                               | 10/10               |
| XRP    | ALL                   | 25/25        | 35/35                | 180                               | 10/10               |
| SOL    | ALL                   | 25/25        | 35/35                | 180                               | 10/10               |
| DOGE   | ALL                   | 25/25        | 35/35                | 180                               | 10/10               |
| SUI    | ALL                   | 25/25        | 35/35                | 180                               | 10/10               |
| APTOS  | ALL                   | 25/25        | 35/35                | 180                               | 10/10               |
| TIA    | ALL                   | 25/25        | 35/35                | 180                               | 10/10               |
| TRUMP  | ALL                   | 25/25        | 45/45                | 180                               | 15/15               |
| WALRUS | ALL                   | 10/10        | 40/40                | 180                               | 10/10               |
| DEEP   | ALL                   | 10/10        | 40/40                | 180                               | 10/10               |
| CETUS  | ALL                   | 5/5          | 60/60                | 300                               | 15/15               |
| W      | ALL                   | 5/5          | 60/60                | 300                               | 15/15               |

#### Reserving Fee

Fee per hour: (assets borrowed) / (total assets in pool) \* 0.01%.

#### Funding Fee

Fee or subsidy per 8 hours: Position size \* ABFR (Algorithm Balanced Funding Rate)


# Market Hours

Sudo trading and SLP withdrawal / minting are 24/7.


# Educational Resources

Welcome to the **Sudo Perpetual Futures Educational Hub** — your go-to resource for becoming a more informed, confident, and responsible trader in the world of crypto perps.

Whether you’re a beginner or already taking leveraged positions, this guide will help you:

• Understand how perpetual futures work

• Learn how to use leverage safely

• Apply proven risk management strategies

• Improve your performance using metrics like the Sharpe Ratio

• Avoid common mistakes that lead to liquidation

• Make better, more consistent trading decisions

## 🧭 What You’ll Learn

[🛠️ Trading Perpetual Futures 101](/trade-on-sudo/educational-resources/what-are-perpetual-futures)

> Learn what perpetual contracts are, how they differ from traditional futures, and how funding rates keep prices in line with the spot market.

[⚙️ Using Leverage Wisely](/trade-on-sudo/educational-resources/using-leverage-wisely)

> Understand how leverage amplifies gains *and* losses — and how to use it to your advantage without getting rekt.

[🛡️ Risk Management Fundamentals](/trade-on-sudo/educational-resources/risk-management-fundamentals)

> Learn how to size your trades, set stop-losses, and limit risk exposure to stay in the game long-term.

[📈 What is Sharpe Ratio?](/trade-on-sudo/educational-resources/what-is-sharpe-ratio)

> Discover how to measure your strategy’s efficiency using risk-adjusted returns — and how to improve it.

[🧪 Real Trade Scenarios](/trade-on-sudo/educational-resources/real-trading-scenarios)

> See example setups with entries, exits, leverage, risk-to-reward ratios, and capital management techniques.

🚫 [Avoiding Rookie Mistakes](/trade-on-sudo/educational-resources/avoiding-rookie-mistakes)

> Don’t repeat the same mistakes we see from 90% of traders. Learn how to avoid overtrading, revenge trades, and emotional decisions.

***

🔄 Why This Matters

Crypto leverage can be powerful — but only if you respect it.

This resource hub exists to make sure our community trades smarter, not harder. With responsible use and strong discipline, perps can be an effective tool to express market views, hedge, and generate returns.

Let’s build good habits from the start. 🚀


# What Are Perpetual Futures?

**Perpetual futures contracts** (or perps) are crypto derivatives that allow traders to speculate on the price of an asset without owning it. Unlike traditional futures, they don’t have an expiration date and instead use a **funding rate** mechanism to tether their price to the spot market.

**Key Features:**

• Trade long or short with leverage

• No expiry — hold positions indefinitely

• Settle in SUI/USDC&#x20;

• Funding fees paid between traders to balance long/short positioning

### 🚀 Spot vs. Perpetual Futures at a Glance

|                   | Spot Trading                   | Perpetual Futures                                      |
| ----------------- | ------------------------------ | ------------------------------------------------------ |
| Ownership         | Direct asset ownership         | No ownership — you're trading a contract               |
| Settlement        | Immediate                      | No expiry; settled through margin/funding              |
| Leverage          | None (unless using margin)     | High leverage available (up to 100x on some platforms) |
| Volatility Impact | 1:1 with price                 | Gains/losses amplified via leverage                    |
| Liquidation Risk  | None                           | High (if margin < maintenance level)                   |
| Market Risk       | Exchange halts can isolate you | Index pricing avoids manipulation                      |


# Using Leverage Wisely

Leverage multiplies your exposure — and your risk. Here’s how different levels of leverage impact your position size and the risk of liquidation:

📊 Leverage vs. Position Size

| Leverage | Capital at Risk | Max Position Size | Liquidation Risk |
| -------- | --------------- | ----------------- | ---------------- |
| 1x       | $1,000          | $1,000            | Low              |
| 5x       | $1,000          | $5,000            | Moderate         |
| 10x      | $1,000          | $10,000           | High             |

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

Liquidation occurs when your margin drops below maintenance levels.


# Risk Management Fundamentals

**🛡️ Risk Management 101: Protecting Your Capital in Perps Trading**

Risk management is the foundation of long-term success in crypto perpetual futures trading. It’s not about maximizing wins — it’s about *minimizing catastrophic losses* and staying in the game when volatility strikes.

> *“Amateurs focus on rewards. Professionals focus on risk.”*&#x20;
>
> — Jack Schwager

***

### ✅ Core Principles of Risk Management

**1. Only Risk 1–2% Per Trade**

Never risk more than 1–2% of your total trading capital on a single position. This ensures that even a string of losing trades won’t wipe you out.

Example:

• Trading account size: $10,000

• Max risk per trade (2%): $200

• If stop-loss is $50 below entry → your position size should be 4 contracts.

This is known as position sizing.

***

**2. Use Stop-Loss Orders — Always**

Stop-losses should be pre-defined *before* entering the trade.

• Hard stop-loss: Automated order set at a specific price

• Mental stop-loss: You monitor manually (less reliable)

***

**3. Avoid Overleveraging**

\
High leverage can destroy your capital fast. While 20x+ leverage is available, professional traders rarely go beyond 5x.

| **Leverage** | **Drawdown Needed to Liquidate** |
| ------------ | -------------------------------- |
| 3x           | \~33%                            |
| 10x          | \~10%                            |
| 20x          | \~5%                             |

**Pro tip:** Use lower leverage and increase position size if you want more exposure — not the other way around.

***

**4. Factor in Maintenance Margin & Liquidation**

Understand that liquidation occurs if your equity falls below the maintenance margin level.

• Initial margin: Collateral to open the trade

• Maintenance margin: Minimum required to keep it open

Always monitor how close your trade is to liquidation and avoid maxing out margin usage.

***

**5. Diversify Trade Risk**

Don’t stack multiple trades in the same direction on highly correlated assets (e.g., BTC, ETH, SOL). This concentrates risk and can trigger a cascade of losses.

> *“Risk management is not just about single trades — it’s portfolio-wide discipline.”*

***

**6. Avoid Emotional Trading**

Trading on tilt (after a loss) often leads to revenge trading, oversized positions, and irrational decisions.

Create a trading journal to:

• Log your rationale

• Track R:R ratio

• Measure performance over time

• Identify emotional triggers

***

**7. Understand Volatility and Slippage**

Set wider stops during volatile market periods, and always account for slippage (getting filled at worse-than-expected prices) when calculating risk.

| Tool                | Purpose                                     |
| ------------------- | ------------------------------------------- |
| Stop-loss orders    | Limit downside per trade                    |
| Take-profit orders  | Lock in gains and avoid FOMO exits          |
| Position size calc. | Adjust trade size to match % risk rule      |
| Journal/log         | Improve emotional control & strategy review |
| Volatility metrics  | Adjust entries, stops, and size accordingly |

**🧠 Final Takeaways**

• Think like a risk manager, not a profit chaser

• Always have a plan for the worst-case scenario

• Survive first, then thrive

> *“There are old traders, and there are bold traders, but there are no old bold traders.”*


# What is Sharpe Ratio

### Sharpe Ratio: Risk-Adjusted Returns

The Sharpe Ratio is a metric used to evaluate the *quality* of your trading strategy — not just how much you earn, but *how much risk you take* to earn it.

<br>

📊 Formula:&#x20;

Sharpe Ratio = (Average Return − Risk-Free Rate) / Standard Deviation of Return

🧠 Why It Matters:

• Higher Sharpe = smoother, more stable returns

• Lower Sharpe = big swings, high volatility

<br>

🔼 How to Improve Sharpe Ratio:

• Focus on setups with high risk-to-reward (R:R)

• Cut losing trades quickly

• Reduce trade frequency and avoid noise

• Keep a trade journal to iterate and improve


# Real Trading Scenarios

### 🧪 Trade Scenario: Long SUI at $2.25

Let’s walk through a practical example using perpetual futures and proper risk management.<br>

📊 Trade Setup

• Asset: SUI

• Current Price: $2.25

• Trade Direction: Long (expecting price to rise)

• Account Capital: $2,000

• Risk Per Trade: 2% = $40

• Leverage Used: 5x

🛠️ Trade Details

| Component        | Value                        |
| ---------------- | ---------------------------- |
| Entry Price      | $2.25                        |
| Target Price     | $2.55                        |
| Stop-Loss Price  | $2.17                        |
| Price Risk       | $0.08 per coin               |
| Position Size    | $40 ÷ $0.08 = 500 SUI        |
| Notional Value   | 500 × $2.25 = $1,125         |
| Leverage Applied | 5x → Only $225 margin needed |

📈 Risk/Reward Breakdown

• Risk: $0.08 downside × 500 SUI = $40

• Reward: $0.30 upside × 500 SUI = $150

• Risk/Reward Ratio: 1 : 3.75

📌 *This is a high-conviction trade with a clearly defined stop-loss and a favorable R:R ratio.*

***

✅ Trade Logic

• You’re risking 2% of your capital to potentially gain 7.5%.

• With 5x leverage, you’re maximizing efficiency without being overexposed.

• If SUI drops to $2.17, the trade is auto-stopped to prevent larger losses.

• If it hits $2.55, you secure a strong profit.

***

🔒 Risk Management in Action

Even if you take 5 trades like this and only win 2 out of 5:

• Losses: 3 × $40 = $120

• Wins: 2 × $150 = $300

• Net Profit: $180

<br>

💡 *The math works in your favor when risk is controlled and reward is maximized.*<br>


# Avoiding Rookie Mistakes

> *“Every trader will eventually learn that the market punishes arrogance and rewards humility.”* -Linda Raschke

Trading crypto perps can be exciting — but without discipline, it’s easy to turn a promising strategy into a blown account. This page walks through the most common rookie mistakes and how to avoid them with practical tips and mindset shifts.

***

### **1. Overleveraging**

> ***Mistake**:* Using 20x+ leverage on volatile assets hoping for quick gains.
>
> *Consequence:* A 5% move against you can liquidate your position entirely.

✅ Fix:

• Stick to 3x–5x leverage as a max (or lower when starting out)

• Use smaller size with tighter risk instead of boosting leverage

• Focus on building capital through consistency, not gambling

***

### 2. Not Using Stop-Losses

> ***Mistake:*** Refusing to set stop-losses because you “believe” the price will come back.
>
> *Consequence:* You become a bagholder or get liquidated without a plan.

✅ Fix:

• Define your stop *before* opening a trade

• Use hard stops in volatile markets to limit downside

• Accept small, planned losses as part of the game

> *“Plan your exit before you enter.”*

***

### 3. Revenge Trading After a Loss

> ***Mistake:*** Doubling down or opening new trades emotionally after taking a hit.
>
> *Consequence:* Stack losses quickly and blow up your account.<br>

✅ Fix:

• Take a 15-minute break after every stop-loss

• Set a “2 losses per day” rule

• Journal what triggered the loss and move on

***

### 4. Ignoring the Funding Rate

> ***Mistake:*** Holding a long position during extreme bullish sentiment and paying huge funding fees.
>
> *Consequence:* Your PnL gets eaten by fees even if price stays flat.

✅ Fix:

• Monitor the funding rate before holding perps long-term

• If funding is high, consider reducing size or switching to spot

• Use exchanges with lower fees or zero funding windows during volatile periods

***

### 5. Going All In / YOLO Trading

> ***Mistake:*** Betting your entire account on a single “high-conviction” idea.
>
> *Consequence:* One mistake ends your trading journey.

✅ Fix:

• Follow a portfolio risk rule: never risk more than 2% of your total capital per trade

• Diversify positions and scale in if necessary

• Think long-term: capital preservation > short-term glory

***

### 6. No Trade Journal or Review Process

> ***Mistake:*** Not tracking trades, emotions, reasons, or mistakes.
>
> *Consequence:* You keep repeating poor behavior without realizing it.

✅ Fix:

• Maintain a simple trade journal with these fields:

• Setup / thesis

• Entry, stop, and target

• Outcome (win/loss and why)

• Emotions felt

• Review trades weekly and look for patterns (good and bad)

***

### 7. Chasing Pumps or FOMO Trading

> ***Mistake:*** Entering trades after large green candles out of fear of missing out.
>
> *Consequence:* You’re often the exit liquidity for early buyers.

✅ Fix:

• Have pre-defined entries based on setups, not emotion

• Set alerts and wait for pullbacks or confirmation

• Let the trade come to you — don’t chase

***

### 8. Trading Too Many Pairs at Once

> ***Mistake:*** Trying to trade 5+ markets simultaneously without proper focus.
>
> *Consequence:* Overwhelm, decision fatigue, and sloppy execution.

✅ Fix:

• Focus on 1–3 assets you understand well (like SUI, ETH, BTC)

• Specialize before expanding your scope

• Quality setups > quantity of trades

***

### 9. Not Accounting for Slippage or Liquidity

> ***Mistake:*** Entering a large position in a low-liquidity market and getting filled far from expected price.
>
> *Consequence:* Worse entry, poor stop fill, or unintended liquidation.

✅ Fix:

• Check the order book depth before entering

• Avoid trading obscure altcoins with thin books

• Stick to perps with high 24h volume and tight spreads

***

### 10. Believing You’re Smarter Than the Market

> ***Mistake:*** Refusing to cut losses or adjust strategy because of ego.
>
> *Consequence:* The market humbles you — hard.

✅ Fix:

• Be flexible. Adapt when market conditions change.

• Accept being wrong as part of the profession.

• Confidence is good — but humility keeps you solvent.

***

### 🧠 Golden Rule

> *“Your #1 job is not to make money. It’s to not lose money.*

Approach every trade as a risk manager first, and a speculator second.

***

## 📌 Recap: Rookie Mistake Checklist

✅ Use stop-losses on every trade

✅ Don’t exceed 2% risk per trade

✅ Avoid revenge and emotional trades

✅ Monitor funding rates before holding

✅ Log and review every trade

✅ Focus on process, not outcome

✅ Be patient, humble, and deliberate


# How to provide liquidity

Everyone can become a liquidity provider of Sudo.

Sudo enables trading with Liquidity Pools funded by SLP (Sudo Liquidity Provider) token. SLP is a certificate of a user's stake in our liquidity pool. A user can mint SLP with native tokens supported by Sudo (SUI, USDC, USDT and more). SLP will initially have the value of $1 per token.

SLP holders will share the protocol profit earned from trading fees. The more people trade on Sudo, the more profits will SLP holders earn. SLP holders can redeem them into Sudo-supported native tokens at any time.

SLP price will fluctuate with the underlying token prices, trader profits and losses and protocol fees.

Visit <https://app.sudo.finance/pool> to mint or redeem SLP.


# SLP

### What is SLP?

SLP is Sudo’s liquidity provider token, representing your share of Sudo’s liquidity pool. When you buy SLP, it means you are staking your asset in our pool as liquidity used for leveraged trading. You can provide different kinds of assets to the sudo liquidity pool: SUI, USDC and USDT and more.

You can learn more about SLP current value and supply [here](https://app.sudo.finance/pool)

### What’s the tokenomics?

SLP is a LP token ([Liquidity Provider Tokens (LP Tokens) Definition](https://coinmarketcap.com/academy/glossary/liquidity-provider-tokens-lp-tokens)). SLP’s total value represents how much liquidity we have in the pool. Since SLP is always backed by asset you minted SLP with, it’s not an inflationary coin. While more supplies can be added to SLP, more assets are added into the pool, keep the price unchanged.

### What’s the benefit of minting SLP?

In short, with SLP you can earn passive income from the protocol. Some other incentive features are being implemented as we speak.

### What’s the max supply?

SLP supply is currently capped to 1M. The more liquidity we have, more leveraged trading can happen, and more fees can be generated to benefit SLP holders. We may open up some more supply to grow the protocol.

### How can I mint SLP?&#x20;

Go to <https://app.sudo.finance/pool>, select your desired asset to mint SLP and click Mint SLP

### Can I trade SLP outside of Sudo?

Yes. We have a pool setup on Cetus so that you can swap SLP to other tokens outside of our trading hours.

### What are the risks associated with SLP token?

Risks associated with Liquidity Provider tokens:

1. **Market and Liquidity Risks**:
   * Prices of assets in the pool can swing, causing losses (impermanent loss) or making it hard to withdraw funds.
2. **Smart Contract and Platform Risks**:
   * Bugs, hacks, or platform failures could lead to loss of funds, even on trusted platforms.
3. **Trading PnL Risks**:
   * High leverage in perpetual trading can amplify losses when trader wins from trades.


# SLP Staking

<figure><img src="/files/De16ju5tOK2kfvbVLuwy" alt=""><figcaption><p>Earn more with SLP Staking</p></figcaption></figure>

### How does SLP Staking work?

SLP Staking is a new incentive feature to reward long term SLP holders. SLP holders can stake and unstake SLP at any time needed. When SLP is staked, you will earn rewards in SLP.

### What's the lock period?

There's none! You can stake, unstake and claim rewards accumulated at anytime!

### How much can I earn from SLP Staking?

SLP staking reward is estimated to around 10% APY at this time, but it may differ by the time when your staking period starts. In total, the cap of SLP Staking pool is 50,000 SLP and the reward pool size is 5000 SLP.

### Will the rewards APY change?

Team will evaluate exchange performance and add rewards to the pool on biweekly basis. We may increase the staking cap and reward size if Sudo is doing well!

### Where and when can I stake SLP?&#x20;

Go to <https://app.sudo.finance/pool>, the staking feature will be available on 1/29/2025 00:00 UTC.


# S Card

S Card is a dynamic NFT collection launched by Sudo and Studio Mirai. This card is designed to incentivize and reward user activities on the platform. User can earn S Points by trading and providing liquidity to Sudo. S Points can be used to level up S Card.

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


# Getting S Card

## Upcoming Mint

On January 14th, 2025, we will open up the final round of S Card Mint. Don’t miss your chance to get your S Card if you missed the first round!

You can mint S Card on our site: <https://app.sudo.finance/mint>

### Eligibility

We have already issued mint tickets to eligible users following below criteria:

Black Card Mint Ticket:

* Top 133 users in S Leaderboard without a S Card yet.

Emerald Card Mint Ticket:

* Top 134–920 users in S Leaderboard without a S Card yet.
* Double Citizens with Sudo Green Hoodie trait.

Silver Card Mint Ticket:

* All other users who have interacted with Sudo but don’t hold a card yet.

Mark your calendar, don’t miss the mint!

In addition, you can participate campaigns launched on our twitter to win a mint ticket:

<https://x.com/sudofinance/status/1877491924543946763>

### Mint Price

WL Mint: 15 SUI

Public Mint: 20 SUI

Note Public Mint happens 1 hour after WL mint.

## Getting it from Marketplace

You can get a S Card from tradeport: [https://www.tradeport.xyz/sui/collection/s-card](https://www.tradeport.xyz/sui/collection/s-card?bottomTab=trades\&tab=items)


# S Points

Everything about S Points

As Sudo grows, we want to ensure that our valued users are rewarded for their activities and contributions to the Sudo ecosystem. With the S Points program, it will be easy for you to keep track of your Sudo usage and receive appropriate rewards based on the points you accumulate.

## Unveiling S Points: quantifying interactions on Sudo <a href="#id-3f6c" id="id-3f6c"></a>

### Calculating your S Points <a href="#id-6ab0" id="id-6ab0"></a>

S Points are designed to quantify and recognize participants for their contributions to the Sudo platform. They can be earned through a combination of trading volume, liquidity providing, and liquidation amount on Sudo.

The formula for calculating S Points is as follows:

S Points = (0.05 × Trading Volume) + (0.5 × LP Amount) + (0.1 × Liquidation Amount)

This means that for every dollar value of trading volume, you’ll earn 0.05 S Point. For every dollar value of liquidity you provide (LP Amount), you’ll receive 0.5 S Point. Finally, for every dollar value of liquidation amount, you’ll gain 0.1 S Point.

## Tracking S Points <a href="#d616" id="d616"></a>

### Track your S Rank in S Points Leaderboard <a href="#fef5" id="fef5"></a>

Staying informed about your S Points is crucial for understanding your activities on Sudo. We’re thrilled to introduce the **S Points Leaderboard**, a feature that allows you to easily track your points and engage in friendly competition within the Sudo community.

The S Points Leaderboard is your key to:

1. Monitor your S Points accumulation progress.
2. Assess your S Rank among the Sudo community.

### S Points Leaderboard <a href="#id-717e" id="id-717e"></a>

<figure><img src="/files/JEaDnptmeN8AXrjp0zrH" alt=""><figcaption><p>S Rank</p></figcaption></figure>

\
The leaderboard showcases top active users on Sudo, and reveals your rank among all Sudo users. Want to earn more rewards with Sudo? Track your S Rank in the leaderboard.

## Claiming S Points <a href="#b672" id="b672"></a>

S Points is not just a number. The S Points you have accumulated will be issued to you on-chain, on a weekly basis. You can claim your S Points onto the S Card you own and level up your S Card with the points.

### S Points Claim Page <a href="#id-56d4" id="id-56d4"></a>

The S Points Claim page will provide you with a comprehensive overview of your earned points and make the claiming process a breeze. Here’s what you can expect:

<figure><img src="/files/Y89ySz6J3j67jXPRDiZM" alt=""><figcaption><p>S Points Page</p></figcaption></figure>

### Points History <a href="#e5fb" id="e5fb"></a>

The page will feature the history of your earned points, with each row representing two weeks of points accumulated. This visual representation will allow you to easily track your progress and see how your trading activities have contributed to your S Points balance over time.

### One-Click Point Claiming <a href="#id-252a" id="id-252a"></a>

<figure><img src="/files/HP439XDcPxidnUX3jlif" alt=""><figcaption><p>Claim Points Modal</p></figcaption></figure>

Collect your rewards effortlessly with our “Claim Points” button next to each S Card. A single click instantly adds the card’s points to your S Points balance. No fuss, no hassle — just a streamlined process for quick and easy point claiming

### On-chain Points and Off-chain Points <a href="#id-252a" id="id-252a"></a>

We store your points in our backend record, and meanwhile we issue points to you in the form of objects. Since on-chain points are issued in weekly / biweekly cadence, and we update your off-chain points daily, there is a lag between how many points are issued to your wallet and what's shown in S Rank leaderboard.

<br>


# Using Your S Card

### Link Your S Card To Earn Fee Reabtes

Once you have obtained a s card, use it in your trades! You can open the S Card Link Modal by clicking the "⛓️‍💥 S Card" button on the right side of wallet connect button.

Open the Modal, and find the card you want to link to your trades

<figure><img src="/files/roG7UJWNEhWzlmNfNvgl" alt="" width="563"><figcaption><p>Link S Card Modal</p></figcaption></figure>

Once a S Card is linked, you can preview rebates in position open modal on the last two rows:

<figure><img src="/files/jU1fV0Edd4O53XvOqGHH" alt="" width="375"><figcaption><p>S Card Linked in Position Open Modal</p></figcaption></figure>

### Level up your S Card for Higher Rebates

You can use your claim points onto S Card and level up your card for higher fee rebates and other privileges.

Go to S Portal and select a card you want to manage

<figure><img src="/files/vAtHbw6ftyjgnlIGzIUy" alt=""><figcaption><p>S Portal</p></figcaption></figure>

Click on "Show Details"

<figure><img src="/files/EBi6z4uq7hWudru0vZ8O" alt="" width="563"><figcaption><p>S Card Details</p></figcaption></figure>

Click on "Level Up" to upgrade your S Card

###

### Claim Fee Rebates

You can claim fee rebates from "Link Your S Card" Modal and S Card Modal in S Portal. Simply click "Claim" button next to the token you want to claim.

<figure><img src="/files/4UEU5E2RlG1ISmL4XUTJ" alt="" width="563"><figcaption><p>Link Your S Card Modal</p></figcaption></figure>

### Claim Rewards

We issue rewards to S Card holders occasionally in the form of Lootbox. Simply go to S Card Modal in S Portal, find "Rewards" tab, and claim lootboxes!

<figure><img src="/files/ryBhF8vyq7KNajizKN9G" alt="" width="563"><figcaption><p>Rewards tab in S Card Modal</p></figcaption></figure>


# Sudo API Reference

The Sudo API provides access to trading data and market information functionality for the Sudo platform.

## Base URL

```
https://api.sudofinance.xyz/
```


# Trader Data

## **GET /traderSummary**

Returns trading summary statistics for a specific trader.

**Parameters:**

| Name   | Type   | Required | Description          |
| ------ | ------ | -------- | -------------------- |
| trader | string | Yes      | The trader's address |

**Response:**

```json
{
  "totalVolume": 1000,
  "totalPnl": 100,
  "totalLiquidationVolume": 0,
  "totalTrades": 10
}
```

## **GET /traderEvents**

Returns a list of trading events for a specific trader.

**Parameters:**

| Name   | Type   | Required | Description          |
| ------ | ------ | -------- | -------------------- |
| trader | string | Yes      | The trader's address |

**Response:**

```json
[
  {
    "eventName": "OpenPositionSuccessEvent",
    "owner": "0x123...",
    "txid": "transaction-hash",
    "volume": 100,
    "fee": 1,
    "pnl": 5,
    "network": "mainnet",
    "created": 1642348800000,
    "indexPrice": 50000,
    "indexToken": "BTC",
    "direction": "long",
    "collateralAmount": 10,
    "collateralPrice": 1,
    "positionId": "position-id"
  }
]
```

## **GET /traderSlpEntryPrice**

Returns the average entry price for SLP tokens for a specific trader.

**Parameters:**

| Name   | Type   | Required | Description          |
| ------ | ------ | -------- | -------------------- |
| trader | string | Yes      | The trader's address |

**Response:**

```json
{
  "entryPrice": 1.05
}
```

## **GET /traderPoints**

Returns the points accumulated by a trader.

**Parameters:**

| Name    | Type   | Required | Description          |
| ------- | ------ | -------- | -------------------- |
| address | string | Yes      | The trader's address |

**Response:**

```json
{
  "distinctUserId": "0x123...",
  "offChainPoints": 1500,
  "suiNsName": "@trader"
}
```


# Market Info

## **Market Data**

### **GET /openInterests**

Returns the total open interest positions for long and short positions.

**Response:**

```json
{
  "long": 1000000,
  "short": 800000
}
```

### **GET /marketInfo**

Returns general market information.

**Response:**

```json
{
  "marketCap": 10000000,
  "slpPrice": 2,
  "slpSupply": 5000000,
  "apr": 100%
}
```

### **GET /totalVolume**

Returns the total trading volume across the platform since launch.

**Response:**

```json
{
  "totalVolume": 50000000
}
```

### **GET /volume**

Returns daily and total trading volume.

**Parameters:**

| Name      | Type   | Required | Description                                                                                    |
| --------- | ------ | -------- | ---------------------------------------------------------------------------------------------- |
| timestamp | number | No       | Unix timestamp to get volume for a specific day ending at timestamp (defaults to current time) |

**Response:**

```json
{
  "dailyVolume": 1000000,
  "totalVolume": 50000000
}
```

## Fee Data

### **GET /fee**

Returns fee information for a specific day.

**Parameters:**

| Name      | Type   | Required | Description                                                                                  |
| --------- | ------ | -------- | -------------------------------------------------------------------------------------------- |
| timestamp | number | No       | Unix timestamp to get fees for a specific day ending at timestamp (defaults to current time) |

**Response:**

```json
{
  "fee": 10000,
  "tradingFee": 8000,
  "fundingFee": 1000,
  "poolFee": 1000,
  "timestamp": "2023-01-01T00:00:00.000Z"
}
```

### **GET /totalFee**

Returns total fee information across the platform since launch.

**Response:**

```json
{
  "totalFee": 500000,
  "totalTradingFee": 400000,
  "totalFundingFee": 50000,
  "totalPoolFee": 50000
}
```

## APR Data

### **GET /cumulativeApr**

Returns the cumulative annual percentage rate since launch.

**Response:**

```json
{
  "cumulativeApr": 0.15,
  "cumulativeFundingApr": 0.05,
  "netDepositVolume": 10000000
}
```

### **GET /apr**

Returns the annual percentage rate for a specific time range with "1d" or "7d" only.

**Parameters:**

| Name        | Type   | Required | Description                                                          |
| ----------- | ------ | -------- | -------------------------------------------------------------------- |
| time\_range | string | No       | Time range for APR calculation (Only supported values: "7d" or "1d") |

**Response:**

```json
{
  "apr": 0.18,
  "fundingApr": 0.06
}
```


# Introduction to Sudo SDK

The Sudo SDK is a TypeScript library designed to interact with Sudo's Move smart contracts on the Sui blockchain. It provides a simple and intuitive interface for developers to integrate Sudo's perpetual futures trading functionality into your applications.


# Core Concepts

### Introduction to Perpetual Futures

Perpetual futures, often simply called "perps," are a type of derivative contract that allows traders to speculate on the future price of an asset without an expiration date. Unlike traditional futures contracts, perps can be held indefinitely.

Key features of perpetual futures:

* No expiration date
* Ability to go long or short
* Use of leverage
* Funding rate mechanism to keep the contract price close to the spot price

The Sudo protocol implements perpetual futures on the Sui blockchain, allowing for decentralized trading of these instruments.

### Key Components of the Sudo Protocol

The Sudo protocol consists of several key components:

1. **Market**: The core contract that manages positions, orders, and trades.
2. **Vault**: Stores and manages collateral for positions.
3. **Oracle**: Provides price feeds for the underlying assets.
4. **Fee Models**: Determine various fees including trading fees and funding rates.

The Sudo SDK provides an interface to interact with these components, allowing developers to build applications on top of the Sudo protocol.

### Position Types: Long and Short

In perpetual futures trading, there are two types of positions:

1. **Long Position**: Traders open a long position when they believe the price of the asset will increase. They profit if the price goes up and lose if it goes down.
2. **Short Position**: Traders open a short position when they believe the price of the asset will decrease. They profit if the price goes down and lose if it goes up.

The Sudo SDK provides functions to open, modify, and close both long and short positions.

### Collateral and Leverage

Collateral is the asset that traders deposit to open and maintain positions. In the Sudo protocol, this is typically SUI or a stablecoin like USDC.

Leverage allows traders to open positions larger than their collateral. For example, 10x leverage means a trader can open a $10,000 position with only $1,000 of collateral.

Key concepts:

* **Initial Margin**: The minimum amount of collateral required to open a position.
* **Maintenance Margin**: The minimum amount of collateral required to keep a position open.
* **Effective Leverage**: The actual leverage of a position, which changes as the market moves.

The Sudo SDK includes functions to deposit and withdraw collateral.

### Funding Rate

The funding rate is a mechanism used in perpetual futures to keep the contract price close to the spot price of the underlying asset. It's a periodic payment between long and short position holders.

* If the contract price is higher than the spot price, longs pay shorts.
* If the contract price is lower than the spot price, shorts pay longs.

### Liquidation

Liquidation occurs when a trader's position doesn't have enough collateral to cover potential losses. To protect the protocol and other traders, the position is forcibly closed.

Key points about liquidation:

* Triggered when a position's collateral falls below the maintenance margin
* The position is closed at the current market price
* Any remaining collateral after closing the position and paying fees is returned to the trader

### Order Types

The Sudo protocol supports various order types to give traders flexibility:

1. **Market Orders**: Executed immediately at the best available price.
2. **Limit Orders**: Executed only at a specified price or better.
3. **Stop Orders**: Triggered when the market price reaches a specified level.
4. **Take Profit Orders**: Similar to stop orders, but used to lock in profits.

The SDK provides functions to place, modify, and cancel these different order types.

### Price Oracles

Price oracles are crucial for the functioning of the Sudo protocol. They provide reliable price feeds for the assets traded on the platform.

The Sudo protocol uses Pyth Network as its primary oracle solution. This ensures:

* Real-time price updates
* High reliability and accuracy
* Resistance to manipulation


# Installation and Setup

### Installation

To install the Sudo SDK in your project, use your preferred package manager:

```bash
npm install sudo-sdk
# or
yarn add sudo-sdk
```

You can find the package on npm at: <https://www.npmjs.com/package/sudo-sdk>

### Setup

```
import { SudoAPI } from 'sudo-sdk';

const provider = getProvider(network);
const sudoAPI = new SudoAPI(network, provider);

// Now you're ready to use the SDK!
```


# Quick Start

This section gives you a working example on how to quickly open and close a position.

```typescript
import { SudoAPI, OracleAPI, SudoDataAPI, IPositionInfo, IPositionConfig, getConsts, parseSymbolKey, joinSymbol } from 'sudo-sdk';
import { Transaction } from '@mysten/sui/transactions';
import { SuiClient } from '@mysten/sui/client';
import { decodeSuiPrivateKey } from '@mysten/sui.js/cryptography';
import {
  Ed25519Keypair,
} from '@mysten/sui.js/keypairs/ed25519';
import { useCallback, useEffect, useState } from 'react';

type SudoApiCall = (api: SudoAPI) => Promise<Transaction>;
interface ITokenBalance {
  symbol: string;
  balance: string;
  objectId: string;
}

const privateKey = <yourPrivateKey>;
const rpc = <yourRpc>;
const network = 'mainnet';
const GAS_BUDGET = 100000000;

const { secretKey } = decodeSuiPrivateKey(privateKey);
const kpImport0 = Ed25519Keypair.fromSecretKey(secretKey);
const pk = kpImport0.getPublicKey();
const signer = pk.toSuiAddress();

const provider = new SuiClient({ url: rpc });
const consts = getConsts(network);

const openPosition = true;
const mode = 'long';
const orderType = 'limit';

const collateralToken = 'USDC';
const indexToken = 'SUI';
const leverage = 10;
const payAmount = 100;
const symbol = joinSymbol(mode, indexToken);

const amountToDecrease = 100;
const indexPrice = 100;
const priceSlippage = 0.003;
const collateralSlippage = 0.5;
const RELAYER_FEE = 1;

export function sudo_sdk_sample() {
  const [prices, setPrices] = useState<{ [key: string]: number }>({});
  const [positions, setPositions] = useState<IPositionInfo[]>([]);
  const [positionConfigMap, setPositionConfigMap] = useState<{
    [key: string]: IPositionConfig;
  }>({});

  useEffect(() => {
    const oracleAPI = new OracleAPI(network);

    Promise.all([
      oracleAPI.subOraclePrices(
        Array.from(
          new Set([...Object.keys(oracleAPI.consts.pythFeeder.feeder)]),
        ),
        priceInfo => {
          setPrices(prevPrice => ({
            ...prevPrice,
            [priceInfo.id]: priceInfo
              .getPriceUnchecked()
              .getPriceAsNumberUnchecked(),
          }));
        },
      ),
      
    ]);
  }, [network]);

  const fetchPositions = useCallback(async () => {
    const dataAPI = new SudoDataAPI(network, provider);
    const capInfoList = await dataAPI.getPositionCapInfoList(signer);
    const infoList = await dataAPI.getPositionInfoList(
      capInfoList,
      signer,
    );
    setPositions(infoList);

  }, [signer, network, setPositions]);

  useEffect(() => {
    fetchPositions();
  }, [fetchPositions]);

  const fetchPositionConfigs = useCallback(async () => {
    const symbols = Object.keys(consts.sudoCore.symbols),
    if (symbols.length === 0) return;
  
    const dataAPI = new SudoDataAPI(network, provider);

    await Promise.all([
      ...symbols.map(async symbol => {
        const [direction, indexToken] = parseSymbolKey(symbol);
        const config = await dataAPI.getPositionConfig(
          indexToken,
          direction === 'long',
        );
        setPositionConfigMap(prevMap => ({
          ...prevMap,
          [`sudo-${symbol}`]: config,
        }));
      }),
    ]);
  }, [
    network,
    setPositionConfigMap,
  ]);

  useEffect(() => {
    fetchPositionConfigs();
  }, [fetchPositionConfigs]);

  const executeSudoApiCall = async (
    apiCall: SudoApiCall,
  ) => {
    const sudoAPI = new SudoAPI(network, provider);
    const txb = await apiCall(sudoAPI);
    
    txb.setSender(signer);
    txb.setGasBudget(GAS_BUDGET);
    const bytes = await txb.build({ client: provider });
    const serializedSignature = (await kpImport0.signTransactionBlock(bytes)).signature;
  
    const res = await provider.executeTransactionBlock({
      transactionBlock: bytes,
      signature: serializedSignature,
      options: {
        showEffects: false,
        showEvents: false,
      },
    });
  };
  
  async function getCoins(
    owner: string,
    coinType: string,
  ) {
    let _continue = true;
    let cursor = null;
    let coins: ITokenBalance[] = [];
    while (_continue) {
      const tmp: any = await provider.getCoins({ owner, coinType, cursor });
      if (tmp.hasNextPage) {
        cursor = tmp.nextCursor;
      } else {
        _continue = false;
      }
      coins = coins.concat(
        tmp.data.map((coin: any) => ({
          // eslint-disable-next-line
          symbol: coin.coinType.split('::')[2],
          balance: coin.balance.toString(),
          objectId: coin.coinObjectId,
        })),
      );
    }
    return coins;
  }
  
  if (openPosition) {
    const coins = await getCoins(
      signer,
      consts.coins[collateralToken].module,
    );
    const coinObjects = coins.map(e => e.objectId);
  
    executeSudoApiCall(
      async sudoApi => {
        return sudoApi.openPosition(
          collateralToken,
          indexToken,
          leverage,
          payAmount,
          positionConfigMap[`sudo-${symbol}`],
          coinObjects,
          mode === 'long',
          prices[indexToken],
          prices[collateralToken],
          priceSlippage,
          collateralSlippage,
          orderType === 'limit',
          false,
          orderType === 'limit' ? BigInt(RELAYER_FEE * 1e9) : BigInt(1),
        );
      }
    ).finally(() => {});
  } else {
    executeSudoApiCall(
      async sudoApi => {
        return sudoApi.decreasePosition(
          positions[0].id,
          positions[0].collateralToken,
          positions[0].indexToken,
          positions[0].positionAmount,
          amountToDecrease,
          positions[0].long,
          prices[positions[0].indexToken],
          indexPrice || 0,
          prices[positions[0].collateralToken],
          orderType === 'limit',
          false,
          priceSlippage,
          collateralSlippage,
          orderType === 'limit' ? BigInt(RELAYER_FEE * 1e9) : BigInt(1),
        );
      }
    ).finally(() => {});
  }  
}

```


# v0.0.6

Welcome to the Sudo SDK documentation. This SDK allows you to interact with Sudo's perpetual futures trading platform on the Sui blockchain.

### Table of Contents

1. Introduction
2. Installation and Setup
3. Core Concepts
4. API Reference
   * Open Position
   * Close Position
   * Get Pyth Price
   * Other APIs
5. Best Practices
6. Troubleshooting
7. Changelog

### Quick Start

```typescript
import { SudoAPI } from 'sudo-sdk';

const provider = getProvider(network);
const sudoAPI = new SudoAPI(network, provider);

// Now you're ready to use the SDK!
```

For more detailed information, please refer to the Introduction and Installation and Setup pages.


# API Reference


# SudoAPI

This section describes all APIs related to perps positions in Sudo.


# Open Position

The `openPosition` function allows users to open a new position in the perpetual futures market.

### Function Signature

```typescript
openPosition(
  collateralToken: string,
  indexToken: string,
  leverage: number,
  collateral: number,
  positionConfig: IPositionConfig,
  coinObjects: string[],
  long: boolean,
  indexPrice: number,
  collateralPrice: number,
  pricesSlippage: number = 0.003,
  collateralSlippage: number = 0.5,
  isLimitOrder: boolean = false,
  isIocOrder: boolean = false,
  relayerFee: bigint = BigInt(1)
): Promise<Transaction>
```

### Parameters

* `collateralToken` (string): The token used as collateral for the position
* `indexToken` (string): The token being traded
* `leverage` (number): The leverage multiplier for the position
* `collateral` (number): The amount of collateral to be used
* `positionConfig` (IPositionConfig): Configuration object for the position
* `coinObjects` (string\[]): Array of coin object IDs to be used
* `long` (boolean): Whether this is a long (true) or short (false) position
* `indexPrice` (number): The market price or limit price of the index token. Refer to [subOraclePrices](/sudo-sdk/v0.0.6/api-reference/oracleapi/suboracleprices) on how you can get the token prices via Pyth using our provided API with a working example.

> Note: For market order, the index price parameter will not be used. The smart contract internally will use Pyth to get the current index price. For limit order, the index price parameter will be used and set as the limited order price when the order is executed.

* `collateralPrice` (number): The market price of the collateral token. Refer to [subOraclePrices](/sudo-sdk/v0.0.6/api-reference/oracleapi/suboracleprices) on how you can get the token prices via Pyth using our provided API with a working example.
* `pricesSlippage` (number, default: 0.003): Maximum allowed slippage for prices
* `collateralSlippage` (number, default: 0.5): Maximum allowed slippage for collateral
* `isLimitOrder` (boolean, default: false): Whether this is a limit order
* `isIocOrder` (boolean, default: false): Whether this is an Immediate-or-Cancel order

> Note: This parameter is currently a placeholder.

* `relayerFee` (bigint, default: BigInt(1)): Fee paid to the relayer

### Returns

`Promise<Transaction>`: A promise that resolves to a transaction object.

### Usage Example

<pre class="language-typescript"><code class="lang-typescript"><strong>const tx = await sudoAPI.openPosition(
</strong>  'USDC',           // collateralToken
  'SUI',            // indexToken
  5,                // 5x leverage
  1000,             // 1000 USDC as collateral
  myPositionConfig, // check getPositionConfig API
  ['0x123...', '0x456...'], // coinObjects
  true,             // long position
<strong>  2,                // indexPrice (SUI price in USD)
</strong>  1,                // collateralPrice (USDC price in USD)
  0.001,            // pricesSlippage (0.1%)
  0.1,              // collateralSlippage (10%)
  false,            // not a limit order
  false,            // not an IOC order
  BigInt(2)         // relayerFee
);
</code></pre>

### Notes

* Ensure you have sufficient balance and have approved the necessary permissions before calling this function.
* The function uses the current oracle prices for the tokens. Ensure your frontend is updated with the latest prices before calling this function.
* The `pricesSlippage` and `collateralSlippage` parameters allow you to control the maximum allowed price movement. Adjust these based on market volatility and your risk tolerance.
* For limit orders, set `isLimitOrder` to `true`.
* The `relayerFee` is paid in SUI. Adjust this value based on the current network conditions and relayer requirements.

### Error Handling

This function may throw errors if:

* The input parameters are invalid
* There's insufficient balance
* The slippage tolerance is exceeded
* The position size is outside allowed limits

Always wrap the function call in a try-catch block and handle potential errors appropriately in your application.


# Decrease Position

The `decreasePosition` function allows users to reduce the size of an existing position.

#### Function Signature

```typescript
decreasePosition(
  pcpId: string,
  collateralToken: string,
  indexToken: string,
  amount: bigint,
  long: boolean,
  indexPrice: number,
  collateralPrice: number,
  isTriggerOrder?: boolean,
  isTakeProfitOrder?: boolean,
  isIocOrder?: boolean,
  pricesSlippage?: number,
  collateralSlippage?: number,
  relayerFee?: bigint
): Promise<TransactionBlock>
```

#### Parameters

* `pcpId`: The ID of the position to decrease
* `collateralToken`: The token used as collateral (e.g., "USDC")
* `indexToken`: The token used as the market index (e.g., "BTC")
* `amount`: The amount to decrease the position by
* `long`: Boolean indicating if this is a long (true) or short (false) position
* `indexPrice`: The current price of the index token
* `collateralPrice`: The current price of the collateral token
* `isTriggerOrder`: Boolean indicating if this is a trigger order (default: false)
* `isTakeProfitOrder`: Boolean indicating if this is a take profit order (default: true)
* `isIocOrder`: Boolean indicating if this is an IOC (Immediate-or-Cancel) order (default: false)
* `pricesSlippage`: Maximum allowed slippage for prices (default: 0.003 or 0.3%)
* `collateralSlippage`: Maximum allowed slippage for collateral (default: 0.5 or 50%)
* `relayerFee`: Fee paid to the relayer (default: 1)

#### Return Value

Returns a `Promise` that resolves to a `TransactionBlock` object.

#### Usage Example

```typescript
const tx = await sudoAPI.decreasePosition(
  '0x123...', // pcpId
  'USDC',     // collateralToken
  'BTC',      // indexToken
  BigInt(500000), // amount (0.5 BTC if BTC has 6 decimals)
  true,       // long position
  50000,      // indexPrice (BTC price in USD)
  1,          // collateralPrice (USDC price in USD)
  false,      // not a trigger order
  true,       // is a take profit order
  false,      // not an IOC order
  0.001,      // pricesSlippage (0.1%)
  0.1,        // collateralSlippage (10%)
  BigInt(2)   // relayerFee
);
```


# Pledge In Position

The `pledgeInPosition` function allows users to add more collateral to an existing position.

#### Function Signature

```typescript
pledgeInPosition(
  pcpId: string,
  collateralToken: string,
  indexToken: string,
  amount: number,
  coinObjects: string[],
  long: boolean
): Promise<TransactionBlock>
```

#### Parameters

* `pcpId`: The ID of the position to pledge into
* `collateralToken`: The token used as collateral (e.g., "USDC")
* `indexToken`: The token used as the market index (e.g., "BTC")
* `amount`: The amount of collateral to add
* `coinObjects`: Array of coin object IDs to use for the transaction
* `long`: Boolean indicating if this is a long (true) or short (false) position

#### Return Value

Returns a `Promise` that resolves to a `TransactionBlock` object.

#### Usage Example

```typescript
const tx = await sudoAPI.pledgeInPosition(
  '0x123...', // pcpId
  'USDC',     // collateralToken
  'BTC',      // indexToken
  1000000,    // amount (1 USDC if USDC has 6 decimals)
  ['0x456...', '0x789...'], // coinObjects
  true        // long position
);
```


# Redeem From Position

The `redeemFromPosition` function allows users to withdraw collateral from an existing position.

#### Function Signature

```typescript
redeemFromPosition(
  pcpId: string,
  collateralToken: string,
  indexToken: string,
  amount: number,
  long: boolean
): Promise<TransactionBlock>
```

#### Parameters

* `pcpId`: The ID of the position to redeem from
* `collateralToken`: The token used as collateral (e.g., "USDC")
* `indexToken`: The token used as the market index (e.g., "BTC")
* `amount`: The amount of collateral to withdraw
* `long`: Boolean indicating if this is a long (true) or short (false) position

#### Return Value

Returns a `Promise` that resolves to a `TransactionBlock` object.

#### Usage Example

```typescript
const tx = await sudoAPI.redeemFromPosition(
  '0x123...', // pcpId
  'USDC',     // collateralToken
  'BTC',      // indexToken
  500000,     // amount (0.5 USDC if USDC has 6 decimals)
  true        // long position
);
```


# Cancel Order

The `cancelOrder` function allows users to cancel an existing order.

#### Function Signature

```typescript
cancelOrder(
  orderCapId: string,
  collateralToken: string,
  indexToken: string,
  long: boolean,
  type: string
): Promise<TransactionBlock>
```

#### Parameters

* `orderCapId`: The ID of the order to cancel
* `collateralToken`: The token used as collateral (e.g., "USDC")
* `indexToken`: The token used as the market index (e.g., "BTC")
* `long`: Boolean indicating if this is a long (true) or short (false) position
* `type`: The type of order ("OPEN\_POSITION" or "DECREASE\_POSITION")

#### Return Value

Returns a `Promise` that resolves to a `TransactionBlock` object.

#### Usage Example

```typescript
const tx = await sudoAPI.cancelOrder(
  '0x123...', // orderCapId
  'USDC',     // collateralToken
  'BTC',      // indexToken
  true,       // long position
  'OPEN_POSITION' // order type
);
```

###


# getPositionCapInfoList

The `getPositionCapInfoList` function retrieves a list of position cap information for a given owner address.

#### Function Signature

```typescript
getPositionCapInfoList(owner: string): Promise<IPositionCapInfo[]>
```

#### Parameters

* `owner`: A string representing the owner's address.

#### Return Value

Returns a `Promise` that resolves to an array of `IPositionCapInfo` objects. Each `IPositionCapInfo` object has the following structure:

```typescript
interface IPositionCapInfo {
  positionCapId: string;
  symbol0: string;
  symbol1: string;
  long: boolean;
}
```

* `positionCapId`: The ID of the position cap.
* `symbol0`: The first symbol in the trading pair.
* `symbol1`: The second symbol in the trading pair.
* `long`: A boolean indicating whether the position is long (true) or short (false).

#### Description

This function fetches all position caps owned by the specified address. It filters for objects of type `PositionCap` and extracts relevant information from each position cap.

#### Usage Example

```typescript
const owner = "0x1234..."; // Replace with actual owner address
const sudoAPI = new SudoAPI(network, provider);

try {
  const positionCaps = await sudoAPI.getPositionCapInfoList(owner);
  console.log("Position Caps:", positionCaps);
} catch (error) {
  console.error("Error fetching position caps:", error);
}
```


# getPositionInfoList

The `getPositionInfoList` function retrieves detailed information about positions based on a list of position cap information.

#### Function Signature

```typescript
getPositionInfoList(
  positionCapInfoList: IPositionCapInfo[],
  owner: string
): Promise<IPositionInfo[]>
```

#### Parameters

* `positionCapInfoList`: An array of `IPositionCapInfo` objects, typically obtained from `getPositionCapInfoList`.
* `owner`: A string representing the owner's address.

#### Return Value

Returns a `Promise` that resolves to an array of `IPositionInfo` objects. Each `IPositionInfo` object contains detailed information about a position, including:

```typescript
interface IPositionInfo {
  id: string;
  long: boolean;
  owner: string;
  version: number;
  collateralToken: string;
  indexToken: string;
  collateralAmount: number;
  positionAmount: number;
  reservedAmount: number;
  positionSize: number;
  lastFundingRate: number;
  lastReservingRate: number;
  reservingFeeAmount: number;
  fundingFeeValue: number;
  closed: boolean;
  openTimestamp: number;
  protocol?: string;
}
```

#### Description

This function takes a list of position cap information and fetches detailed data for each position. It calculates additional information such as reserving fee amount and funding fee value for open positions.

#### Usage Example

```typescript
const owner = "0x1234..."; // Replace with actual owner address
const sudoAPI = new SudoAPI(provider);

try {
  const positionCaps = await sudoAPI.getPositionCapInfoList(owner);
  const positionInfoList = await sudoAPI.getPositionInfoList(positionCaps, owner);
  console.log("Position Info List:", positionInfoList);
} catch (error) {
  console.error("Error fetching position information:", error);
}
```

#### Notes

* The function sorts the returned positions by `openTimestamp` in ascending order.
* For open positions, the function calculates `reservingFeeAmount` and `fundingFeeValue` using separate API calls.
* If there's an error calculating `reservingFeeAmount` or `fundingFeeValue`, these values are set to 0 and the error is logged.


# getPositionConfig

Retrieves and parses the position configuration for a given index token and position type (long or short).

#### Function Signature

```typescript
getPositionConfig(
  indexToken: string
  long: boolean
): Promise<IPositionConfig>
```

#### Parameters

* `indexToken` (string): The token for which to retrieve the position configuration.
* `long` (boolean): Indicates whether to retrieve the configuration for a long (true) or short (false) position.

#### Return Value

Returns a `Promise` that resolves to an `IPositionConfig` object. The object contains parsed position configuration, including:

```typescript
interface IPositionConfig {
    decreaseFeeBps: number;
    liquidationBonus: number;
    liquidationThreshold: number;
    maxLeverage: number;
    minHoldingDuration: number;
    openFeeBps: number;
    maxReservedMultiplier: number;
    minCollateralValue: number;
}
```

#### Description

This method fetches the position configuration data from the blockchain for a specified index token and position type. It performs the following steps:

#### Usage Example

```typescript
const sudoAPI = new SudoAPI(provider);

try {
  const positionConfig = await sudoAPI.getPositionConfig('BTC', true);
  console.log("Fetched position config:", positionConfig);
} catch (error) {
  console.error("Error fetching position config:", error);
}
```


# OracleAPI

This section describes all APIs related to token prices.


# subOraclePrices

Subscribes to price feed updates for specified tokens.

#### Parameters

* `tokens` (string\[]): An array of token identifiers.
* `callback` ((price: PriceFeed) => void): A function to be called with each price update.

#### Returns

* `Promise<void>`: A promise that resolves when the subscription is set up.

#### Description

This method establishes a subscription to price feed updates for the specified tokens. It maps the token identifiers to their corresponding Pyth object IDs and price feed IDs, then sets up a subscription using the Sui Price Service Connection.

When a price update is received, the method modifies the `price.id` to match the token identifier format used in the system, then calls the provided callback function with the updated price information.

#### Example Usage

```typescript
export function useTokenPrice(network: string) {
  const [tokenPrice, setTokenPrice] = useState<{ [key: string]: number }>({});
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    if (isLoading) return;

    setIsLoading(true);
    const oracleAPI = new OracleAPI(network);

    Promise.all([
      oracleAPI.subOraclePrices(
        Array.from(
          new Set([...Object.keys(oracleAPI.consts.pythFeeder.feeder)]),
        ),
        priceInfo => {
          setTokenPrice(prevPrice => ({
            ...prevPrice,
            [priceInfo.id]: priceInfo
              .getPriceUnchecked()
              .getPriceAsNumberUnchecked(),
          }));
        },
      ),
    ])
      .then(() => {
        setIsLoading(false);
      })
      .catch(err => {
        console.error(err);
        setError(err.message);
        setIsLoading(false);
      });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [network]);

  return {
    tokenPrice,
    isLoading,
    error,
  };
}
```


# Changelog

### # v0.0.2 -> v0.0.3

### Major Update

* Upgraded from "@mysten/sui.js": "0.54.1" to "@mysten/sui": "1.3.0"

### Key Changes

1. Parameter Updates:
   * Removed: `size`, `collateralAmount`, `reserveAmount` (all bigint)
   * Added: `leverage` (number), `collateral` (number), `positionConfig` (IPositionConfig)
2. Calculation Approach:
   * Position size and reserve amount now calculated internally based on leverage and collateral
3. Return Type:
   * Changed from `Promise<TransactionBlock>` to implicit `Promise<Transaction>`

### Impact

* More intuitive position opening with leverage-based calculations
* Increased flexibility with `positionConfig`
* Less pre-processing and calculation required from the caller
* Potential breaking changes due to major Sui SDK upgrade


# Best Practices

When using the Sudo SDK, consider the following best practices:

1. **Error Handling**: Always implement proper error handling to manage potential issues gracefully.
2. **Price Updates**: Ensure you're using the most up-to-date price information when opening positions.
3. **Gas Management**: Be mindful of gas costs, especially when executing multiple transactions.
4. **Testing**: Thoroughly test your integration on a testnet before deploying to mainnet.
5. **Security**: Never expose your private keys. Use secure key management practices.


# Troubleshooting


# Algorithm Balanced Funding Rate (ABFR)

The fundamental principle underlying ABFR is to safeguard the interests of SLP holders by dynamically adapting the funding rate according to the specific direction of a trading pair. When traders exhibit net profitability in a given trading pair, fees are gathered from them and provided as support to LPs. When traders face an overall loss, fees are acquired from LPs and allocated to traders. This mechanism guarantees that the combined unrealized and realized PNL of each trading pair tends to balance out to approximately zero over the long run. In this way, LPs wouldn't experience excessive returns but rather would generate income from fees (transaction fee + borrowing interest). The subsequent steps outline the overall process for calculating these dynamic funding fees.

#### Calculate the total profit and loss of LP at time t on the the trading pair

$$\begin{aligned}sign&=\begin{cases}1\&short\\-1\&long\end{cases}\\\Delta\_t&=openAmount\_t \times price\_t - openSize\_t\pnl\_t&=realizedPnl+fundingFee+sign\times\Delta\_t\end{aligned}$$

{% hint style="info" %}

* Realized PNL signifies the actual profit and loss experienced by LPs due to changes in traders' positions, excluding the influence of fees.
* FundingFee embodies the cumulative funding fees that have been gathered or distributed.
  {% endhint %}

When PNL\_t < 0:

$$ABFR\_t=\begin{aligned}min\left{K\_1\times log\left|PNL\_t\right|,R\_x\right}\end{aligned}$$

When PNL\_t > 0:

$$ABFR\_t=\begin{aligned}-min\left{K\_2\times log\left|PNL\_t\right|,R\_y\right}\end{aligned}$$

{% hint style="info" %}
K1, K2 are constant coefficients
{% endhint %}

* The reason for using the logarithm of pnl is to make ABFR change significantly when pnl is small and change slowly when pnl is large
* ABFR has upper and lower bounds, with corresponding upper and lower rate limits Rx, Ry when pnl < 0 and pnl > 0, respectively

If a trader opens a position at time t1 and closes it at time t2, with a position size of ***size*****,** the funding fee to be paid/received by the trader is

$$fundingFee=size\times\int\_{t\_1}^{t\_2}ABFR\_t\ dt$$

When the fee is positive, trader pays the funding fee to the LP

When the fee is negative, LP pays the funding fee to the trader


# Risk control

### Risk Control

Fluctuations in both the value of the collateral token and the token underlying the contract can lead to the potential liquidation of the position. Traders should vigilantly monitor both the position's profit and loss and any changes in the collateral's value.

A trader is required to establish a maximum margin size for the counterparty, which would also be the highest feasible profit excluding fees. If the position reaches this maximum profit, further profit won't be generated.

Opting for a larger counterparty margin also entails higher position maintenance fees. This is slightly different from the approach taken by other centralized exchanges. Those exchanges usually involve a contract borrow fee that is more closely tied to the position's value, influenced by its leverage. In contrast, Sudo's borrowing fee for perpetual contracts is predominantly determined by the potential maximum profit/loss of the position.


# FAQ


# Roadmap

#### ~~Milestone 1: Contract Implementation~~

* ~~Validate the feasibility of innovation points and implement smart contracts.~~
* ~~Expected Completion Date: 8/15/2023~~
* ~~Deliverables:~~
* ~~Feasibility of innovation points verified.~~
* ~~Smart contracts implemented.~~

#### ~~Milestone 2: Testnet launch~~

* ~~Launch Sudo on Sui Testnet~~
* ~~Expected Completion Date: 10/15/2023~~
* ~~Deliverables:~~
  * ~~Make sudo available for testing on testnet to every degen~~

#### ~~Milestone 3: Mainnet launch~~

* ~~Launch Sudo on Mainnet~~
* ~~Expected Completion Date: 12/15/2023~~
* ~~Deliverables:~~
  * ~~Mainnet launch completed.~~
  * ~~Smart contract audited.~~
  * ~~Onboarding documentation for sudo~~
  * ~~Referral and loyalty program~~
  * ~~Trading competition~~

~~2024 Q1 Milestone~~

* ~~Reach $10M in trading volume~~
* ~~Make over $50k in trading fee~~
* ~~Grow Users to 500+~~
* ~~Launch 10+ trading pairs~~
* ~~TVL $300k+~~

~~2024 Q2 Milestone~~

* ~~Reach $30M in trading volume~~
* ~~Make over $200k in trading fee~~
* ~~Grow Users to 800+~~
* ~~Launch 20+ trading pairs~~
* ~~Launch "S" Card~~
* ~~Launch "S" Card rebate~~

~~2024 Q3 Milestone~~

* ~~Reach $50M intrading volume~~
* ~~Make over $500k in trading fee~~
* ~~Grow Users to 1500+~~
* ~~Launch referral feature~~
* ~~Launch Sudo SDK~~


# On-chain program

Original Package:&#x20;

{% embed url="<https://suivision.xyz/package/0xc44d97a4bc4e5a33ca847b72b123172c88a6328196b71414f32c3070233604b2>" %}

Latest Package:

{% embed url="<https://suivision.xyz/package/0x601acc608030324a973d39835883e07ff123e4cc7b0d1142c245ae59666d6043>" %}

Audit Partner: MoveBit

Audit Report:

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


