# Welcome to ZO

## Overview

ZO is the first intelligent on-chain perpetual protocol built on Sui. To Learn more about ZO, please look into below quick links.

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

## Quick links

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

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


# What is ZO

ZO is the first intelligent perpetual protocol that aims to bring AI-assisted perpetual trading to all DeFi users. On top of edge-cutting technology that guarantees you security, transparency, performance and best pricing, ZO comes with intelligent AI agents that can offer you personalized trading advices and help you manage your portfolio based on your risk preference.&#x20;

ZO comes with three modules:

* Core Perpetual DEX - Fastest On-chain Perpetual DEX, featuring zero slippage, best price and high LP returns.
* Intelligence Module: Multi-Agent module designed to simplify trading for traders like you. It can provide you trading advice, gives you market insights, and automate your day-to-day trading flow.
* Agent SDK: Built for AI Agent builders to integrate their agents with ZO at ease. The Agent SDK will be a critical bridge between agents on ZO.

Try out ZO: [https://zofai.io](https://zofai.io/)\
\
You can contact ZO team on following platforms:

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


# ZO Features

### ZO Perpetuals DEX

At its core, ZO is a state-of-the-art Perpetual DEX built by Sudo Finance team. Following trader-to-pool model like GMX / Jupiter Perps, and leaning on best technology from Sui Network, ZO Perpetual DEX is one of the fastest perps on-chain.

As a Perps DEX, ZO provides following features:

* Fully on-chain - Your trades are submitted to chain and settled on-chain. There is no third party, no centralized backend.
* Zero compromises - Our contract is audited by industry leading audit partners. We implemented to contract with best security practice in mind.
* Best Pricing, Zero Slippage - We utilize decentralized price feed like Pyth to ensure you are getting the best price. In addition, you are getting zero slippage with the price feed - that means your whale order can be filled at the same price!
* Subsecond finality - Leaning on top-notch techology from Sui, ZO transaction finality is less than a second. Faster than all major on-chain perps dex on the market.

### ZO Intelligence Module

A typical perpetual trader often spends significant time monitoring the market to identify optimal entry and exit points, while also keeping an eye on market volatility to avoid liquidations.

To address these pain points, ZO is an intelligence module that assists you with day-to-day trading operations. ZO intelligence module will come with following features:

* Market Analysis: It analyzes the market and estimates the best prices for entry and exit, saving you time and effort.
* Trading Strategy: It offers tailored trading strategies based on your risk preferences, ensuring your approach aligns with your goals.
* Automated Trading: It executes trades automatically, eliminating the need for manual intervention and reducing emotional decision-making.
* Liquidation Monitoring: It actively safeguards your positions from liquidations during periods of high market volatility, providing an added layer of protection.

With ZO, perpetual trading becomes seamless, efficient, and secure, allowing you to focus on your strategy while the protocol handles the complexities.

### ZO Agent SDK

Agents Era is coming, we will see more agent traders in DeFi.

ZO Agent SDK is intended to make agent integration effortless and seamless; it will include all tools required to interact with ZO on-chain. When the agents era comes, ZO will be their first choice to trade perpetuals.


# Roadmap

### 🚀 The Launch of ZO

ZO kicked off its ZLP mint campaign on 3/24/2025 00:00 UTC. This is a small first step for ZO, but a big step for Perpetuals to enter Intelligence Era.

The ZO Launch will carry on in following order:

* 3/24/2025 00:00 UTC
  * ZLP Mint Dash Kick-off
* 4/7/2025 00:00 UTC
  * ZLP Redeem Open
  * ZO Perpetuals Trading Open
* 4/14/2025 00:00 UTC
  * ZO Intelligence Module Alpha Launch
* 4/24/2025 00:00 UTC
  * ZLP Mint Dash Campaign Concludes
  * Mint Dash Rewards Distribution

### 🧬 The Evolution of ZO

The Evolution of ZO will be the focus of ZO team for the rest of 2025. We primarily aim for the following milestones implemented as part of ZO Intelligence Module:

* Automation for common trader workflows
* Comprehensive and detailed market analysis and strategy recommendation
* Market monitoring and auto-collateral deposit to prevent liquidation

### 🫅 The Dominance of ZO

We aim to build ZO as the best Perpetual Protocol for the upcoming Intelligence Era.

We expect more agent traders coming onto DeFi, and we want to ensure ZO is the best place for these traders. In addition, ZO Intelligence Module will empower common traders with advanced tools and strategy to help them trade better and compete with automated agent traders.

We envision ZO will be dominating the Perpetuals space if it's done right.


# Security and Audits

### **Security and Audits**

Security is a core pillar of ZO. Every component of the protocol — from smart contracts to oracle flows to backend infrastructure — is designed with a “safety-first” approach to protect both traders and liquidity providers.

**Independent Audits**\
All ZO smart contracts undergo independent, third-party security audits before deployment. Audits focus on critical areas including:

* leverage and liquidation logic
* collateral accounting and asset safety
* oracle integration and price update validation
* pool accounting and fee distribution
* role permissions and upgrade rules
* invariant checks and failure-mode behavior

ZO follows an iterative audit process: major upgrades, new modules (e.g., oracle engine, reserving fee model), and risk-sensitive components are re-audited before release.

Audit Partner: Movebit, Asymptotic

Latest Audit with Asymptotic:

{% embed url="<https://info.asymptotic.tech/sudo-audit-report>" %}

Audit with Movebit:

{% file src="/files/1uYDQCyNJg9UWQC5kYVt" %}

**Formal Verification & Testing**\
Beyond audits, ZO uses extensive internal testing:

* unit tests for all critical price, fee, and accounting functions
* fuzz testing to detect unexpected edge cases under load
* simulation environments that replay market volatility, liquidations, and oracle delays
* continuous integration pipelines to test every update against known attack vectors

**Oracle Safety & Manipulation Resistance**\
ZO integrates Pyth’s low-latency feeds and wraps them with additional protections:

* multiple layers of validation before a price is accepted
* staleness and deviation checks
* rate-limits and sanity bounds
* fallback paths when market conditions diverge sharply

This ensures the protocol is resistant to oracle manipulation, delayed updates, or abnormal market swings.

**Permission Controls & Safe Upgrades**\
ZO employs strict on-chain role separation. Administrative actions, such as upgrading modules or adjusting parameters, require multi-sig approval. Upgrades follow a staged rollout process, allowing for on-chain monitoring and rollback if needed.

**Ongoing Monitoring**\
Post-deployment, the protocol uses continuous monitoring tools to detect abnormal behaviors such as unusual OI imbalances, rapid liquidation clusters, or irregular transaction patterns. When thresholds are met, circuit-breakers and automatic safeguards can slow or restrict actions on the protocol.

**Onchain Programs**

You can find ZO contracts from Move Registry:

{% embed url="<https://www.moveregistry.com/package/@zofai/sudo-perps-core>" %}

{% embed url="<https://www.moveregistry.com/package/@zofai/zo-perps-zlp>" %}

{% embed url="<https://www.moveregistry.com/package/@zofai/zo-perps-usdz>" %}


# Start trading

### Step 1: Connect Wallet&#x20;

### Connect your preferred wallet to ZO

<figure><img src="/files/MpzcZjBQAzkXryLmnVR8" alt=""><figcaption><p>Connect to ZO with any supported wallet</p></figcaption></figure>

### Step 2: Open a Position

ZO allows you to take both long and short positions with leverage, supporting a range of tokens (SUI, DEEP, USDC, WAL and CETUS) as collateral.

Long vs. Short

* **Long:** You profit when the token’s price goes up.

<figure><img src="/files/z4AC6EjIljSITW7cHLBo" alt="" width="355"><figcaption><p>Opening a Long Position on Sui</p></figcaption></figure>

* **Short:** You profit when the token’s price goes down.

<figure><img src="/files/YQEEPXua4XFbAGGMmNbT" alt="" width="355"><figcaption><p>Opening a Short Position on Sui</p></figcaption></figure>

#### Choosing Liquidity Pool

You can select liquidity pool to borrow leverage against from the Liquidity Pool Dropdown. Each liquidity pool supports different assets with different reserving rate depending on the liquidity depth.

For instance, if you are trading with stable (USDC), the USDZ pool may have the most USDC liquidity. Hence you will get a lower reserving rate for borrowing USDC from the pool as your leverage.

On ZO, we already did the hard work for you - liquidity pool is auto-selected based on collateral selection and liquidity depth. Whenever you change your collateral, we automatically find the pool that has the deepest liquidity for you.

<figure><img src="/files/h0aYK8a5ne4NO0xFlxx2" alt="" width="351"><figcaption><p>Liquidity Pool Selector</p></figcaption></figure>

#### Choosing Collateral and Leverage

After selecting a position direction, choose your collateral token from the dropdown menu. The platform will display your collateral value in USD.

Next, enter the amount of collateral you want to use and select a leverage level. ZO automatically calculates your position size based on these inputs.

**Example:**

You’re entering 10 SUI as collateral (\~$21.42 USD), and choosing 10x leverage.

* Position Size: 97.0874 SUI (\~$207.99 USD)
* Leverage: 10x

<figure><img src="/files/lesaCaiyiVQLZrNd7o5v" alt="" width="356"><figcaption></figcaption></figure>

The trading fee to open and close a position is normally 0.2% - 0.5% of the position size depending on the index token.

"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.

#### Review Trade Details

ZO automatically calculates your key trade metrics:

* Entry Price: 2.142
* Est. Liquidation Price: 1.928
* Open Fee: 0.2912 SUI (\~$0.6239)
* Available Reserve: 97.09 / 67,689.45 SUI
* Reserving Fee Rate: 0.0112% per hour

### Step 3: Managing Positions

<figure><img src="/files/hC6DUsrVEHNdeiwGv9YC" alt=""><figcaption><p>Once you open a trade, it will appear under your Positions tab. From there, you can track its performance and make live adjustments as the market moves.</p></figcaption></figure>

#### Adjusting Collateral

Click Adjust to either:

* Deposit more collateral — lowers your leverage and moves your liquidation price farther away
* Withdraw collateral — increases leverage and brings liquidation closer (if you’re confident in your position)

When you deposit collateral, ZO captures a snapshot of its USD value at that moment. This snapshot is used to determine your position size, which remains fixed regardless of future price movement.

<figure><img src="/files/I1lFgaDvFiF5t6pue41C" alt="" width="375"><figcaption><p>Withdraw Collateral View</p></figcaption></figure>

### Step 4: Closing a Position

You can close your position at any time — either partially or fully — directly from the Positions tab.

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

#### How to Close

1. Go to the Positions section of the trading interface
2. Click Close next to the position you want to exit
3. Choose to close the entire position or just a portion of it
4. Confirm the transaction

ZO will handle everything in the background — from calculating PnL to returning your funds.


# Supported Assets

ZO supports a variety of crypto perpetual pairs:

BTC / USD

ETH / USD

SOL / USD

XRP / USD

DOGE / USD

SUI / USD

DEEP / USD

WAL / USD

TRUMP / USD

CETUS / USD

ONDO / USD

HYPE / USD

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


# Fee Structure

Learn about how our fees are structured on ZO

## **ZO Fee Structure**

ZO uses three core fee types designed to keep markets fair, pools protected, and liquidity efficient: **Trading Fees**, **Reserving Fees**, **Funding Fees,** and **Instant Exit Fees.**

### Trading Fees

Trading Fees are charged on both opening and closing a position. These range from **1–20 bps** depending on the market. They are straightforward transactional fees and do not influence OI balance.

Open and Close fees are different per symbol. Please find the details below.

| Symbol | Collaterals | Max Leverage | Open / Close Fee Bps | Minimum Holding Duration (Second) |
| ------ | ----------- | ------------ | -------------------- | --------------------------------- |
| BTC    | ALL         | 50/50        | 4/4                  | 60                                |
| ETH    | ALL         | 50/50        | 4.5/4.5              | 60                                |
| XRP    | ALL         | 50/50        | 5/5                  | 60                                |
| SOL    | ALL         | 50/50        | 3.5/3.5              | 60                                |
| DOGE   | ALL         | 50/50        | 8/8                  | 60                                |
| SUI    | ALL         | 50/50        | 8/8                  | 60                                |
| HYPE   | ALL         | 20/20        | 10/10                | 60                                |
| ONDO   | ALL         | 20/20        | 10/10                | 60                                |
| TRUMP  | ALL         | 20/20        | 10/10                | 60                                |
| WALRUS | ALL         | 10/10        | 8/8                  | 180                               |
| DEEP   | ALL         | 10/10        | 8/8                  | 180                               |
| CETUS  | ALL         | 5/5          | 20/20                | 600                               |

### **Reserving Fee**

A dynamic fee paid for **borrowing assets as leverage** from the pool. The fee scales with **utilization** of the specific asset and accrues over time, capped around **0.1% per 8 hours**.

$$
reserving\_fee\_rate =
\left( multiplier \times utilization \right)
\times
\left( \frac{elapsed\_time}{seconds\_per\_eight\_hours} \right)
$$

#### **Where:**

* **multiplier** — coefficient that scales how fast reserving fees grow
* **utilization** — current utilization ratio of the borrowed asset
* **elapsed\_time** — number of seconds the position has been open
* **seconds\_per\_eight\_hours** — constant equal to 8 × 3600
* **reserving\_fee\_rate** — fee accrued for the elapsed period

This ensures heavily-borrowed assets cost more to reserve, encouraging healthier utilization across the pool.

### **Funding Fee**

A mechanism to balance **long vs short open interest** for each symbol. The side with higher OI pays the side with lower OI. Each market has its own cap, typically **0.01–0.05%**.\
Formula:

$$
\text{FundingFee} =
\min\left(
M \cdot
\frac{(OI\_{\text{long}} - OI\_{\text{short}})^{E}}{OI\_{\text{total}}},
\text{MaxFee}
\right)
$$

**Where:**

* **M** — coefficient that scales the funding strength
* **E** — controls how aggressively imbalance affects funding
* **oi\_long** — total long open interest
* **oi\_short** — total short open interest
* **oi\_total** — sum of both sides (oi\_long + oi\_short)
* **MaxFee** — maximum allowed funding rate for the symbol (e.g., 0.01%–0.05%)

Together, these fees create a system where trading is predictable, leverage usage is efficiently priced, and OI imbalances are continuously corrected to protect liquidity providers.

## Instant Exit Fee

The instant exit fee is an additional fee applied **only when a user closes a position very quickly after opening it**. It is designed to discourage toxic, ultra-short-duration scalping flows that can harm LPs, especially during moments of oracle latency or rapid price updates.

The fee uses **three time tiers**, commonly:

* within **300 seconds**
* within **600 seconds**
* within **1800 seconds**

Each tier applies an extra percentage of fees based on how quickly the position is closed. The longer you hold, the lower the fees will be. If position is held beyond the instant exit fee time tiers, no additional fees will be charged.

<figure><img src="/files/sMGMRmHPeFoJxpxn3QBo" alt="" width="224"><figcaption><p>Instant Exit Fee Details on a Symbol</p></figcaption></figure>

Important condition:

* **If the position is closed at a loss, no instant exit fee is charged.**\
  (LPs are already protected when the trader loses; the fee only targets toxic profit-seeking behavior.)

This mechanism ensures that extremely short, opportunistic trades pay a premium, reducing the impact of latency arbitrage and protecting liquidity providers.


# Market Hours

Market hours for perpetuals symbols on ZO

### Crypto Market

Crypto Symbols are available 24/7.

### LP Mint & Redeem Hours

USDZ is subject to market hours to support equity and commodity trading. Hence it will follow Equity & ETF Market Hours for native minting and redeeming.

USDZ is also available on [FullSail](https://app.fullsail.finance/liquidity/0x64292b3a6c8da6fb28d1f1a3e347434b5a4b57057a0b89c043e95ee8770ac69c), for off market-hour trading.

### Equity & ETF Market

### 📈 US Market Trading Hours (America/New\_York)

| Day       | Trading Hours |
| --------- | ------------- |
| Monday    | 09:30 – 16:00 |
| Tuesday   | 09:30 – 16:00 |
| Wednesday | 09:30 – 16:00 |
| Thursday  | 09:30 – 16:00 |
| Friday    | 09:30 – 16:00 |
| Saturday  | Closed        |
| Sunday    | Closed        |

### 🚫 Market Holidays / Closures

| Date (MM/DD) | Status | Typical Holiday            |
| ------------ | ------ | -------------------------- |
| 01/01        | Closed | New Year’s Day             |
| 01/19        | Closed | Martin Luther King Jr. Day |
| 02/16        | Closed | Presidents’ Day            |
| 04/03        | Closed | Good Friday                |
| 05/25        | Closed | Memorial Day               |
| 06/19        | Closed | Juneteenth                 |

### Commodity Market

XAU/USD, XAG/USD, XPT/USD, XPD/USD

The market is open **Sunday evening through Friday afternoon** with a **daily maintenance break from 5:00–6:00 PM ET** on weekdays.\
The market **closes at 5:00 PM ET on Fridays**, remains **closed on Saturdays**, and **reopens Sunday at 6:00 PM ET**.\
On major U.S. holidays, the market closes early and reopens in the evening.

#### 📍 Time Zone

America/New\_York (ET)

#### 📅 Regular Weekly Market Hours

| Day           | Market Hours                               |
| ------------- | ------------------------------------------ |
| **Monday**    | 12:00 AM – 5:00 PM, **6:00 PM – 12:00 AM** |
| **Tuesday**   | 12:00 AM – 5:00 PM, **6:00 PM – 12:00 AM** |
| **Wednesday** | 12:00 AM – 5:00 PM, **6:00 PM – 12:00 AM** |
| **Thursday**  | 12:00 AM – 5:00 PM, **6:00 PM – 12:00 AM** |
| **Friday**    | 12:00 AM – 5:00 PM                         |
| **Saturday**  | **Closed all day**                         |
| **Sunday**    | **6:00 PM – 12:00 AM**                     |

#### 🎉 Holiday & Special-Date Schedule Overrides

| Date                                | Market Hours                               |
| ----------------------------------- | ------------------------------------------ |
| **Nov 27 (Thanksgiving)**           | 12:00 AM – 2:30 PM, **6:00 PM – 12:00 AM** |
| **Nov 28 (Day after Thanksgiving)** | 12:00 AM – 2:45 PM                         |
| **Dec 24 (Christmas Eve)**          | 12:00 AM – 1:45 PM                         |
| **Dec 25 (Christmas Day)**          | **6:00 PM – 12:00 AM**                     |
| **Dec 31 (New Year’s Eve)**         | 12:00 AM – 5:00 PM                         |
| **Jan 1 (New Year’s Day)**          | **6:00 PM – 12:00 AM**                     |


# Price Impact

### Overview

Price impact on ZO is a **simulated spread** that adjusts execution price based on **open interest (OI) skew**. It behaves like orderbook slippage: the more crowded one side (long or short), the worse execution gets for new trades on that side. It does not change the underlying oracle price; it applies a configurable spread on top of it at execution time.

Typically you can see the simulated spread for a market in the **depth tab** of the **chart section**:

<figure><img src="/files/NkOXCbwGqgF8ApJwNdc3" alt=""><figcaption><p>Simulated Spread for SUI-USD Perps Market</p></figcaption></figure>

### Why it exists

* **Fairer execution** — Trades that add to the crowded side get a worse price; trades that reduce skew can get a better effective price.
* **LP protection** — Reduces adverse selection by making it more expensive to pile into the same direction when OI is already skewed.
* **Predictable caps** — Spread is bounded by a configurable maximum (e.g. up to 10% total spread cap in the implementation).


# Mechanism

### OI utilization and skew&#x20;

For each symbol we track:

* **Long OI** and **Short OI** (current open interest on each side).
* **Max OI** per side (from price impact config or symbol config).

⠀We define utilization and skew as:

* **This side utilization** = (current OI on this side + new trade size) / max OI on this side
* **Opposite side utilization** = current OI on opposite side / max OI on opposite side
* **Skew ratio** = max(0, this side utilization − opposite side utilization), clamped to \[0, 1]

⠀When the side you’re trading is more utilized than the other, skew ratio is positive and spread increases.

### Spread formula

* **Dynamic spread** = `max_dynamic_spread × (skew_ratio ^ impact_exponent)`
* Exponent is between 1 (linear) and 3 (e.g. cubic); higher exponent = spread grows faster as skew increases.
* **Total spread** = base spread + dynamic spread, capped by **max total spread**.

⠀So:

* **Base spread** — Applied to every trade on the symbol.
* **Dynamic spread** — Extra spread from OI skew; larger when your side is more crowded.
* **Cap** — Total spread (base + dynamic) cannot exceed the configured max (e.g. 10% in the contract).

### Direction (how spread affects price)

Spread is applied so that the trader gets a worse execution when adding to the crowded side:

| **Action**  | **Effect on execution price**           |
| ----------- | --------------------------------------- |
| Open long   | Price **increases** (you pay more).     |
| Open short  | Price **decreases** (you receive less). |
| Close long  | Price **decreases** (you receive less). |
| Close short | Price **increases** (you pay more).     |

So: opening long or closing short worsens your price when spread is positive; opening short or closing long does the same in the opposite direction.

### Size scaling

Config can include a **reference size**. When set, the dynamic spread is scaled by a factor that increases with trade size (e.g. `1 + min(1, position_size / reference_size)`), so larger orders see more impact, similar to orderbook depth.

### Average spread over the trade

For large orders we don’t use only the end-state skew. We integrate the spread over the path from “OI before trade” to “OI after trade” and use an **average spread** over that path, so execution reflects the fact that the trade itself moves the skew.

### Summary

* Price impact = **simulated spread** from OI skew, not a change to the oracle.
* **Crowded side** (high utilization) → higher spread → worse execution for trades that add to that side.
* **Base + dynamic** spread, with a **hard cap** (e.g. 10%).
* **Direction logic** ensures longs/shorts and open/close are penalized in the right direction.
* Optional **size scaling** and **path-averaged** spread keep behavior consistent for small and large orders.


# Margin Trading

Welcome to the Alpha Phase of Margin Trading on ZO. This feature allows advanced traders to amplify their positions with leverage.&#x20;

⚠️ Alpha Access Limited: This feature is currently in testing with only 200 slots available. As of now, 82 slots remain. Access is granted on a first-come, first-served basis.

Request your Access: <https://app.zofai.io/margin-trade>

#### Step 1: Connect Wallet

Connect your preferred wallet to ZO to begin. Ensure you have sufficient USDC or supported assets in your wallet to use as collateral.

![](/files/LdkbVPEGfHTEGU8033Vv)

#### Step 2: Request Alpha Access

Since this feature is in Alpha, you must manually request access before trading.

1. After connecting your wallet, locate the "Request Access" button in the trading module.
2. Click the button to claim a tester slot.
3. Once approved, the trading interface will unlock.

![](/files/tf4XfjFgmJBzs9M1q4q2)

#### Step 3: Open a Position

Once access is granted, you can open Long or Short positions. The interface provides granular control over order type, leverage, and position size.

**Available Trading Pairs**

Currently, the Alpha launch supports the following trading pairs against USDC:

* SUI / USDC
* DEEP / USDC
* WAL / USDC
* XBTC / USDC

Select your desired pair from the asset selector at the top of the trading panel to begin configuring your order.

![](/files/NhknagJ2361aMwBRPnaf)

**Long vs. Short**

* Long (Buy): You profit when the token’s price goes up. You borrow funds to increase your buying power.
* Short (Sell): You profit when the token’s price goes down. You borrow the asset to sell immediately, aiming to buy it back later at a lower price.

**Order Configuration**

The trading panel includes several key controls to customize your trade:

1. Order Type: Toggle between Market (instant execution) and Limit (execute at a specific price).
2. Leverage: Click the 1x dropdown to select your desired leverage multiplier up to 5x. Higher leverage increases both potential profit and liquidation risk.
3. Amount & Quantity:&#x20;
4. Enter the Amount of collateral (e.g., USDC) you wish to deploy.
5. Use the slider (0% - 100%) to quickly allocate a percentage of your available wallet balance.
6. Receiving: Displays the estimated amount of the target asset you will receive (for Long) or the stablecoin value (for Short).

**Advanced Options**

Fine-tune your order behavior with these settings:

* Reduce Only: When checked, the order can only reduce an existing position, preventing accidental reversals.
* TIF (Time In Force): GTC (Good Till Cancelled), ensuring the order remains active until filled or cancelled. IOC (Immediate or Cancel), ensuring the order fills what it can immediately and cancels the rest.&#x20;
* Max Fee: Displays the maximum protocol and network fees required for the transaction.

**Review Account Metrics**

Before confirming, review your real-time account status at the bottom of the panel:

* Asset: Total value of assets held in your margin account.
* Debt: The amount currently borrowed (displayed in red if active).
* Account Value: Your net equity (Assets minus Debt).
* Wallet: Your available balance outside of the margin account.

**Execute Trade**

Once all parameters are set:

* Click the green Long button (if Buy is selected) or Short button (if Sell is selected) to submit the order.
* Confirm the transaction in your wallet popup.

💡 Note: Margin trading involves risk. Ensure you monitor your Debt and Account Value to avoid liquidation. Funding fees and reserving rates apply similar to standard ZO trading.

![](/files/dQHymBnSeBUU1QU6KfPi)

#### Step 4: Managing Positions

After opening a trade, it will appear under your Positions tab. From here, you can track PnL, adjust collateral, or close the position.

**Adjusting Collateral**

Click Adjust on an active position to:

* Deposit: Add more collateral to lower leverage and move your liquidation price further away.
* Withdraw: Remove collateral to increase leverage (only if health factor allows).
* Repay: Pay down borrowed debt manually to reduce interest accrual or improve position health.

<br>

Asset Selection

At the middle of the modal, you can toggle between assets involved in your position:

* SUI (the base asset)
* USDC (the quote/collateral asset)

This lets you manage either side of your margin position independently.

<br>

Balance Overview

The panel displays real-time balances:

* Wallet: Your available balance outside the position.&#x20;
* Position: The current amount held within this specific margin position.&#x20;

<br>

Amount Input & Slider

Use the Amount to deposit field to enter a precise value, or use the slider (0% – 100%) to quickly allocate a percentage of your available wallet or position balance.

* Click Max to auto-fill the maximum allowable amount based on your current balance and position constraints.
* The orange dot on the slider indicates your current selection.

![](/files/ftwya9ePIGkwPGKoryT9)

<br>

Closing a Position

You can close your position partially or fully at any time:

1. Go to the Positions section.
2. Click Close next to the specific trade.
3. Select the portion to close and confirm.

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

<br>

ZO automatically calculates your PnL and returns the remaining funds to your wallet upon closure.

***

Have feedback on the Alpha? Click "Leave Feedback" at the bottom of the trading panel to share your thoughts with the team.

<br>


# &#x20;Educational Resources

Welcome to the **ZO 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](/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](/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](/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?](/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](/educational-resources/real-trading-scenarios)

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

🚫 [Avoiding Rookie Mistakes](/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.

📊 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>


# 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


# How to provide liquidity

Everyone can become a liquidity provider of ZO.

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

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

In addition, ZLP holders will be sharing fees charged for the use of ZO agents, allowing liquidity providers to earn potentially higher APY from holding ZLP.

The ZLP APY is calculated based on earned fees and net deposit asset value. Fees are deposited back into the pool directly, so ZLP holders can just earn the yield passively.

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

The ZLP mint will open in March, 2025


# ZLP Overview

The **ZO Liquidity Provider (ZLP) Pool** is a liquidity pool that acts as the counterparty to traders on the ZO Perpetuals exchange. Traders borrow tokens from the pool to open leveraged positions on the platform.

The ZLP token derives its value from:

* An index of major assets (e.g., SUI, DEEP, USDC)
* Trader profit and loss (PnL)
* 75% of the generated fees from:
  * Opening and closing trades
  * Mint and redeem ZLP
* Agent Usage Fees
* Reserving Fees
* Funding Fees

***

### ZO Liquidity Providers (ZLPs)

ZLPs are essential participants in the ZO trading ecosystem. They provide the liquidity that enables perpetual traders to execute leveraged positions.

**Liquidity providers:**

• Enable sufficient liquidity for the platform

• Share in the majority of trading fee revenue

• Help support a stable and deep trading environment

***

### How to Become a Liquidity Provider (LP)

Anyone can become a Liquidity Provider by contributing assets to the ZLP Pool.

• **ZLP tokens** represent your share of the pool.

• Supported assets on ZO Perps can be used to mint ZLP.

• Entry/exit fees may apply based on pool utilization and asset weight (see Target Ratio and Fees).

👉 Tip: The easiest way to mint or redeem ZLP is via ZO Mint page.

***

### Advantages of the ZLP System<br>

The ZLP system is designed to be simple and efficient for passive income generation:

• ✅ No staking or harvesting required – yield auto-compounds into ZLP token price

• 📈 AMM pools can support secondary market trading of ZLP

<br>

> ℹ️ ZLP is the liquidity token for ZO Perps. Governance features may be handled by a separate ZO governance token.

***

### Rewards and Earnings

The APY of ZLP is calculated based on 75% of all fees generated from ZO perpetual trading activity (excluding asset price changes and trader PnL).

• Fees are distributed back to the pool on an hourly basis.

• Yield is reflected in the increasing virtual price of ZLP.

Learn more in How ZLP Works.

### &#x20;ZLP UI Walkthrough

| Section                  | Description                                                             |
| ------------------------ | ----------------------------------------------------------------------- |
| Mint Tab                 | Deposit tokens to the ZLP pool to start earning passive fees            |
| APY                      | Displays current estimated yield from holding ZLP                       |
| Pool                     | Mint, redeem, or swap into and out of ZLP                               |
| Total Value Locked (TVL) | Shows current pool value based on real-time token prices                |
| Token Selector           | Choose tokens to deposit or receive                                     |
| Token List               | Displays all assets held by the pool                                    |
| Pool Size                | Current balance of each token (includes collateral from open positions) |
| Current / Target Weight  | Compare actual vs. target pool composition                              |
| Utilization              | Indicates how much of the pool is being used by traders                 |
| Fees and Estimations     | Shows expected ZLP received and any associated fees                     |
| ZLP Price & Supply       | Displays virtual price (TVL ÷ supply) and total ZLP token supply        |

Learn more in How ZLP Works.


# USDZ Overview

Earn Yield, Not Fiction

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

**USDZ** is the latest stable backed perpetual LP token supporting ZO perpetual market.

USDZ LP Pool is only backed by stable tokens. In the beginning, only USDC will be supported. USDZ yield will come from fees generated by trading activities on the platform.

USDZ is characterized by the following:

* An index of stable assets (e.g., USDC)
* Trader profit and loss (PnL)
* 75% of the generated fees from:
  * Opening and closing trades
  * Mint and redeem USDZ
* Reserving Fees
* Funding Fees


# How ZLP Works

### Liquidity Pool

The ZO Perpetuals exchange uses a trader-to-LP model, meaning traders borrow tokens from the ZLP Pool to open leveraged positions.

Instead of periodic funding payments between long and short traders, ZO implements an hourly borrow fee mechanism.

Traders pay these fees to the pool based on the amount of tokens they’ve borrowed. This helps secure the balance of the pool’s assets and compensates liquidity providers for the use of their capital.

***

## Add / Remove Liquidity to ZLP

### Adding Liquidity

Liquidity providers can acquire ZLP by contributing supported assets via ZO Swap.

* Increases Total Value Locked (TVL), which boosts trading liquidity.
* Deposited assets are allocated to the appropriate pool.
* TVL is re-priced in USD at the time of deposit.
* ZLP is minted and distributed based on the current price determined by underlying assets.

### Removing Liquidity

* ZLP can be redeemed into supported tokens.
* This burns the ZLP token and releases assets from the pool.
* Alternatively, ZLP can be transferred or traded on secondary markets.

***

### Yield Generation

| Action                   | Fee                         |
| ------------------------ | --------------------------- |
| Opening a Position       | 20-40 BPs                   |
| Closing a Position       | 20-40 BPs                   |
| Swap Fee (Mint/Burn ZLP) | 0–100 BPS (based on weight) |
| Borrow Rate              | Dynamic                     |

* 75% of fees go into the pool.
* Fees are settled when position is opened or closed.<br>

ZO generates yield for ZLP holders through fees collected from trading activity.

### Yield Calculation Example

Assumptions:

* Daily Trading Volume = $50M
* Fee Rate = 0.06%
* Revenue Share to Pool = 75%

$50,000,000 x 0.06% x 75% = $22,500/day in pool fees

### &#x20;Your share:

* Contribution = $1,000
* Pool TVL = $4,000,000
* Pool Share = 0.025%

$22,500 x 0.025% = $5.625/day

### ZLP Fee Distribution & APR

<br>

**Fee Distribution**

* Occurs when position is opened or closed
* 75% of realized fees are added to the pool.
* 25% is retained as a protocol fee.

**Weekly APR Calculation**

APR is updated weekly using the following logic:

if current\_time > (last\_updated + 1 week):\
time\_diff = current\_time - last\_updated\
apr\_bps = (realized\_fee\_usd \* YEAR\_IN\_SECONDS \* 10,000) / (pool\_usd\_value \* time\_diff)

APR is expressed in basis points (BPS).

### Risks of Holding ZLP

1\. **Bull Market Performance**

ZLP may underperform assets like SOL, ETH, or BTC due to the mixed asset nature of the pool (stable + volatile).

2\. **Trader PnL**

Trader profits and losses affect the pool:<br>

**Long Profitable Trade**

* Pool loses token quantity, but underlying token price rises (USD value remains stable).

**Short Profitable Trade**

* Pool loses stable coins without offsetting token appreciation (USD value drops).

> ⚠️ Yes, ZLP can go down in value. If trader profits + asset depreciation > fees generated, the pool’s value decreases.

3\. **Token Volatility & Fees**

* ZLP includes both stable and volatile tokens.
* Value of withdrawn tokens may be less than deposited.
* Entry/exit fees can reduce returns, especially for short-term holdings.

***

### Pool Weightage & Rebalancing

Each token has a target weight, which helps balance the pool.

**Maintaining Target Weight**

Swap (mint/redeem) fees adjust dynamically:

| Token > target weight | Deposit fee ↑, Withdraw fee ↓ |
| --------------------- | ----------------------------- |
| Token < target weight | Deposit fee ↓, Withdraw fee ↑ |

> 🧮 Goal: Encourage actions that return the pool closer to target weights.

***

### Weighted Swap Fees Mechanism

A token’s weight can deviate from its target, but it may incur high fees

**Example:**

Target USDC Weight = 26%

Allowed Range = 20.8% to 31.2%

* Above 31.2% → USDC deposits incurs high fees (\~100bps)
* Below 20.8% → USDC withdrawals incurs high fees (\~100bps)

<br>

> 🛡️ Purpose: Prevent destabilization during black swan events or depegs.


# Loss Buffer Vault

### Overview

The **Loss Buffer Vault** (also referred to as the loss protection vault in the protocol) is a **protection layer for LPs** that smooths PnL volatility. It collects a share of **trader losses** (when the pool wins) and uses that buffer to **cover trader profits** (when the pool loses), so LP payouts are less jagged.

### Why it exists

* **Lower LP volatility** — Part of trading losses is set aside instead of going straight to LP liquidity; when traders win, the vault can cover some of that payout.
* **More stable yields** — LPs see a more smoothed stream of gains and losses instead of large swings on big trader wins/losses.
* **Configurable** — Each vault (per collateral type) has its own parameters and can be enabled/disabled by governance.


# Mechanism

### How Loss Buffer Vault Works

**When the trader loses (pool wins)**

* The pool receives the loss (collateral from the position).
* A **configurable percentage** of that amount is sent to the **Loss Buffer Vault** instead of going entirely to the main vault liquidity.
* This **builds the buffer** that will later cover trader profits.

⠀**When the trader wins (pool loses)**

* The pool would normally pay the profit from reserved/collateral.
* If the **Loss Buffer Vault has balance**, up to the profit amount (capped by available vault balance and by what’s actually being paid) is **withdrawn from the vault** and used to cover that payout.
* The rest of the payout still comes from the pool (reserved/liquidity) as before.
* So the vault **softens** the hit to LPs when traders are profitable.

⠀

### Where it applies

* **Decrease / close position** — On position decrease/close, if the trader has profit, the vault can cover part of it; if the trader has loss, a percentage of that loss is deposited into the vault.
* **Liquidation** — When a position is liquidated, a **configurable percentage** of the trader’s loss (the part that goes to the pool) can be sent to the Loss Buffer Vault instead of 100% to main liquidity.
* So both “normal” exits and liquidations feed and use the buffer.

⠀

### Parameters

* **Loss percentage** (e.g. on decrease) — Share of **pool profit** (trader loss) that is sent to the vault.
* **Liquidation percentage** — Share of **trader loss** in a liquidation that is sent to the vault.
* **Enabled flag** — The vault can be turned off so all flows go to/from the main vault only.

### Safety and caps

* Withdrawals from the vault are limited to what’s **actually needed** for the current payout and never exceed the vault’s balance.
* Deposits are capped by the amount actually available (e.g. the pool’s share of the loss).
* So the vault never creates new value; it only **redistributes** between “main LP liquidity” and “buffer” to smooth volatility.

### Summary

* **Loss Buffer Vault** = protection layer for LPs that **decreases volatility**.
* **Trader loses** → a percentage is **deposited** into the vault (builds the buffer).
* **Trader wins** → the vault **covers** part of the payout when it has balance.
* Used on **position decrease/close** and **liquidations**, with separate configurable percentages.
* **Governance** can enable/disable and set percentages per collateral vault.


# ZO Vaults

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

Ever found LP Earning hard to manage?

ZO Vaults provides you a simplified interface to earn more with your LP token.

### What's ZO Vault

ZO Vault is our latest earning product for the LPs. With ZO Vault, you can earn additional yield at ease. Simply deposit supported asset and earn rewards with fixed APY.

The first vault we are launching - USDZ Incentivized Vault, offers up to 20% APY with Max Capacity set to $1M. We may bump the capacity as we see fit.

### How do I earn rewards?

You can earn rewards simply by depositing supported assets into the Pool. Rewards start to accumulate once you deposited asset. You can claim and withdraw at any time. There is no lock-up.

### When can I get my asset back?

You can withdraw your asset any time, there is no lockup.

### What is the risk involved?

There is no additional risk involved besides the underlying LP risk - we are simply offering more rewards for you to provide LP in the first USDZ Incentivized Vault.

More vaults are being built as we speak - some of them will come with delta neutral strategy that may offset some risks involved with LP token. Stay tuned.

### When Launch?

Deposit will be available starting from 9/10/2025. Please check the site for exact timeline.

<https://app.zofai.io/vaults>


# Copy of Copy of Copy of How to provide liquidity

Everyone can become a liquidity provider of ZO.

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

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

In addition, ZLP holders will be sharing fees charged for the use of ZO agents, allowing liquidity providers to earn potentially higher APY from holding ZLP.

The ZLP APY is calculated based on earned fees and net deposit asset value. Fees are deposited back into the pool directly, so ZLP holders can just earn the yield passively.

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

The ZLP mint will open in March, 2025


# ZLP

### What is ZLP?

ZLP is ZO's liquidity provider token, representing your share of ZO's liquidity pool. When you buy ZLP, 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 ZO Perpetuals Liquidity Pool: SUI, DEEP and USDC and more.

### What’s the tokenomics?

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

In addition, ZLP holders will be sharing fees charged for the use of ZO agents, allowing liquidity providers to earn potentially higher APY from holding ZLP.

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

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

### When will the mint open?

ZLP mint will open in March, 2025.

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

Risks associated with Liquidity Provider (LP) 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.


# ZLP 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.


# ZLP Mint Dash

<figure><img src="/files/ylLNUmzTMG4Cd1S3qtVD" alt=""><figcaption><p>ZLP Mint Dash</p></figcaption></figure>

### What is ZLP Mint Dash?

The ZLP Mint Dash is ZO’s way of jumpstarting liquidity—and rewarding early birds like you with a **$5,000** prize pool. Here’s the rundown:

* When: From 3/24 to 4/24.
* How It Works: You’re ranked by points based on the volume you deposit to mint ZLP, plus volume from your referrals.
* Final Countdown: On 4/24, the leaderboard locks, and rewards are handed out based on your rank.<br>

This isn’t just a campaign—it’s your ticket to help shape ZO’s future while scoring big.

### How do I win big?

Provide liquidity and keep them in ZLP pool is the key to win more from the prize pool.

<figure><img src="/files/4plaXA6f9nMhb2itkNoq" alt=""><figcaption></figcaption></figure>

### Campaign Rules

* The top 50 users will share $3,000 following a weighted prize breakdown tallied in the Leaderboard section.
* The remaining 200 winners will enter a raffle and share $2,000 equally among each other.

Users will receive 1 point for $1 usd worth of ZLP minted and will accumulate points until the end of the campaign as long as they keep supplying ZLP liquidity.

### **Eligibility**

* Connect with Wallet
* Mint ZLP and receive **1 point per day** for $1 worth of ZLP

### Where can I learn more about the campaign?

Please refer to <https://app.zofinance.io/mint> for updated campaign details.


# ZO x OKX Wallet Campaign

Campaign Concluded on 7/20

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

Explore the Sui DeFi ecosystem with OKX Wallet and ZO, trade perpetuals, and win rewards from a total prize pool of $55,000 worth of ZLP token.

### Claiming Your Rewards

1. Go to <https://app.zofai.io/okx-wallet-zo-campaign>, connect your okx wallet.
2. If you have won rewards, you will see "Claim Rewards" button in the banner like below.

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

3. Clicking "Claim Rewards" will redirect you to "ZO Hub". Click "Claim Rewards" on Zolian Shard. The rewards amount will be 15 ZLP.

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

4. ZLP will show up in your OKX Wallet after apporoving claiming transaction.


# ZO Points Season 1: HyperBoost

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

ZO Points Season 1: **HyperBoost** is a six-week acceleration phase designed to reward active users, scale the Sui ecosystem, and establish ZO’s long-term progression system.

HyperBoost is not a one-off campaign. It is the first activation of ZO Points as a **persistent ecosystem-wide scoring layer**.

***

### Overview

**Season:** ZO Points Season 1\
**Name:** HyperBoost\
**Duration:** 6 weeks\
Campaign **Date:** 12/8/2025 - 1/19/2026\
**Reward Pool:** 100,000 ZLP\
**Network:** Sui

Participants earn ZO Points by interacting with ZO products and supported ecosystem partners. Points determine tier placement, leaderboard ranking, and future reward eligibility.

***

### What Are ZO Points?

ZO Points are the **universal growth metric** of the ZO ecosystem.

Users earn points by performing on-chain actions such as:

* Trading
* Depositing collateral
* Providing liquidity
* Minting USDZ, ZLP, or SLP
* Interacting with supported partner assets

Points are cumulative and persist across the ecosystem.

***

### Why HyperBoost Exists

HyperBoost was designed with three objectives:

#### 1. Reward Active Users

Core actions such as trading, liquidity provision, and vault participation earn increased point flow during Season 1.

#### 2. Expand the Sui Ecosystem

Partner assets and pools receive point boosters to encourage cross-protocol activity and discovery.

#### 3. Align Long-Term Incentives

ZO Points unify trading, liquidity, vaults, stablecoins, and partners under a single progression system.

***

### How Points Are Earned

#### Partner Power-Ups

ZO integrates with select Sui ecosystem partners to provide automatic point boosters.

Examples:

* Deposit **haSUI** → boosted ZO Points
* Deposit **vSUI** → boosted ZO Points
* Provide liquidity to **MMT**, **Magma**, or **Fullsail** pools
* Trade selected partner-aligned symbols

New partner boosters are announced weekly.

***

#### Core Activity Points

**Trading Points**

Earned based on:

* Trade volume
* Symbol- or category-based multipliers
* Time-based boost windows

**LP & Vault Points**

* Deposits into liquidity vaults earn continuous points
* Points compound the longer positions remain active

**Referral Points**

* Earn points by referring new users
* Both referrer and referee earn points when the referee trades or provides liquidity

***

### Seasonal Tiers

Accumulated points determine your seasonal tier.

| Tier         | Point Range             | Description           |
| ------------ | ----------------------- | --------------------- |
| **Drifter**  | 0 – 999,999             | Starting the journey  |
| **Explorer** | 1,000,000 – 4,999,999   | Actively engaging     |
| **Sentinel** | 5,000,000 – 14,999,999  | Guardian-level user   |
| **Overseer** | 15,000,000 – 49,999,999 | Strategic operator    |
| **Zenith**   | 50,000,000+             | Peak ZO consciousness |

Higher tiers unlock increased visibility, priority access, and larger future rewards.

***

### Season Timeline

HyperBoost runs continuously for six weeks and includes:

* Weekly partner booster launches
* Category-based trading multipliers
* Vault incentives
* Community missions
* Surprise bonus windows
* Live leaderboard updates

Season parameters may evolve dynamically as new partners and features are added.

***

### Reward Distribution

A total of **100,000 ZLP** has been allocated for Season 1.

* All ZO Points earned during HyperBoost contribute to reward allocation
* Allocation scales with total points and tier
* Early participation provides the highest relative upside

Season 1 establishes the baseline for future reward distributions.

***

### Getting Started

You can start earning ZO Points by:

* Trading on ZO
* Depositing collateral
* Minting USDZ, ZLP, or SLP
* Participating in boosted partner pools
* Completing weekly HyperBoost missions
* Tracking progress on the live dashboard

**Every action earns points — some earn significantly more during HyperBoost.**

***

### Start Here

👉 [**https://app.zofai.io/points**](https://app.zofai.io/points)

Welcome to HyperBoost.\
Season 1 sets the foundation for everything that comes next.


# ZO Points Program

## **ZO Points Program & Tier System**

The ZO Points Program rewards meaningful participation across the ZO ecosystem. Points reflect your contributions as a trader, LP, liquidator, or referrer, and determine your rank within the ZOverse through a structured tier system.

This document explains how points are calculated, how referral rewards work, and how tiers are assigned.

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


# How Are Points Calculated?

## **What Are ZO Points?**

ZO Points represent your total contribution to the ZO ecosystem. They are composed of multiple sub-point systems:

* **Core Points** (Trading, LP, Liquidation, Referral)
* **Sudo Points** (imported from legacy Sudo campaigns)
* **Social Points** (community, campaigns, social engagement)

Your final total is the sum of all these categories.

```
Total ZO Points
= Core Points + Sudo Points + Social Points
```

These points unlock your position in the Tier System and may influence future ecosystem rewards.

***

## **How Points Are Calculated**

Your total ZO Points are computed using the following formula:

```
Total Points
= 0.1 * Trading Volume
+ 1 * Net LP Volume
+ 0.1 * LP Hold Value
+ 0.2 * Liquidation Volume
+ Referral Points
```

All figures are denominated in USD-equivalent value.

***

### **Trading Points**

```
Trading Points = 0.1 * Trading Volume
```

* Every $1 traded earns 0.1 points
* Example: $10,000 traded → **1,000 points**

Trading direction (long/short) does not affect points.

***

### **Deposit Points**

```
Deposit Points = 1 * Net LP Volume
```

* Net LP Volume = deposits – withdrawals
* Every $1 provided earns 1 point
* Example: $5,000 net LP → **5,000 points**

LPs receive the highest multiplier because they stabilize protocol liquidity.

***

### **Hold LP Points**

```
Hold LP Points = 0.1 * LP Value
```

* Every $1 LP token balance held earns 0.1 points a day
* Example: $5,000 ZLP Held → **500 points Daily**

***

### **Liquidation Points**

```
Liquidation Points = 0.2 * Liquidation Volume
```

* Liquidators help secure the protocol
* Each $1 liquidated earns 0.2 points

***

## **Referral Points**

The ZO referral system rewards both the **referrer** and the **referee**. Points are based entirely on the referee’s activity.

```
Referral Points
= 0.5 * Referee Net LP Volume
+ 0.05 * Referee Trading Volume
```

Both referrer and referee receive the same Referral Points.

#### **Example**

If your referee:

* Trades $20,000 → 1,000 points
* Deposits $2,000 LP → 1,000 points

Total Referral Points = **2,000**

You earn 2,000 points and your referee earns 2,000 points.

***

## **Sudo Points**

**Sudo Points** are imported from historical user activity from the Sudo ecosystem.

These points recognize early adopters, contributors, and participants who previously supported Sudo and are now transitioning into the ZO ecosystem.

```
Total ZO Points = Core Points + Sudo Points + Social Points
```

If you were active on Sudo, your past efforts are honored here.

***

## **Social Points**

**Social Points** reward community engagement, campaign participation, and off-chain contribution.

You can earn Social Points through:

* Completing campaign quests
* Sharing ZO posts
* Engaging with community events
* Participating in missions (e.g., Galxe, Zealy, X quests)
* Content creation (memes, videos, threads, infographics)
* Ambassador contributions
* Special seasonal tasks

Social Points help ensure that **community energy is recognized alongside on-chain actions**.


# ZO Point Tiers

Your accumulated points place you into one of five tiers within the ZOverse.\
Each tier represents your growth, influence, and identity within the protocol.

***

### **Drifter — 0 to 999,999 Points**

**Role:**\
*A lone traveler beginning their journey through the ZOverse.*

This is the entry tier for users who are starting to explore ZO. Early trades, small LP positions, or initial referrals typically land users here.

***

### **Explorer — 1,000,000 to 4,999,999 Points**

**Role:**\
*Actively navigating the unknown and uncovering opportunities.*

Explorers demonstrate consistent engagement—regular trading, steady LPing, or early referral activity. This tier marks your evolution from beginner to active participant.

***

### **Sentinel — 5,000,000 to 14,999,999 Points**

**Role:**\
*A guardian of the ecosystem equipped with stronger tools and intel.*

Sentinels are reliable contributors: high-volume traders, committed LPs, or active liquidators who help maintain system balance.

***

### **Overseer — 15,000,000 to 49,999,999 Points**

**Role:**\
*Commands a node in the ZO network; strategic and powerful.*

Overseers exhibit large-scale, strategic activity and hold significant influence within the protocol’s economic engine.

***

### **Zenith — 50,000,000+ Points**

**Role:**\
*Peak consciousness in the ZO protocol. Rare, revered, and unstoppable.*

Zenith is the highest tier, reserved for elite contributors. These users demonstrate exceptional scale and dedication, standing at the apex of the ZOverse.

***

## **Tier Summary Table**

| **Tier**     | **Point Range**         | **Role Description**  |
| ------------ | ----------------------- | --------------------- |
| **Drifter**  | 0 – 999,999             | Starting the journey  |
| **Explorer** | 1,000,000 – 4,999,999   | Actively engaging     |
| **Sentinel** | 5,000,000 – 14,999,999  | Guardian-level user   |
| **Overseer** | 15,000,000 – 49,999,999 | Strategic operator    |
| **Zenith**   | 50,000,000+             | Peak ZO consciousness |

***

## **Why Tiers Matter**

Tiers may influence eligibility for:

* Leaderboards
* Seasonal campaigns
* Airdrops
* Exclusive beta access
* Priority in new product releases
* Community faction roles
* Special on-chain or in-app perks

ZO Points and Tiers form the foundation of the long-term reward and identity system within the ZOverse.


# Tracking Your Progress

## **How to Track My Progress?**

Simply go to <https://app.zofai.io/points>

<figure><img src="/files/RAXuhEE71R81wOCoksGS" alt=""><figcaption><p>ZO Points Ranking and Tiers</p></figcaption></figure>

You will see a your **Rank**, **Tier** and **Total Points** in one view.

## **How to Earn Points Faster**

* Trade with consistent volume
* Increase your LP contributions
* Use and share your referral code
* Spread your words about ZO
* Stay active across market cycles

Consistent on-chain activity is the fastest route to tier progression.

## **Start Earning Today**

Get started at: [**https://app.zofai.io**](https://app.zofai.io/)

Trade. LP. Refer. Climb the ranks.\
Become a legend of the ZOverse.


# Affiliate Program

## What is ZO Affiliate Program?

<figure><img src="/files/rnAAHyX2n0J68KgLWgNw" alt=""><figcaption><p>ZO Affiliate Program</p></figcaption></figure>

The ZO Affiliate Program is built for **power users, creators, and community builders** who are excited to grow the ZO ecosystem. As an affiliate, you’ll play a key role in spreading the word across your channels and helping onboard new users. In return, you’ll get **exclusive early access to new features, programs, and alpha drops on ZO**.

## **🔥 Why Become an Affiliate?**

As an affiliate, you’ll be among the first to access new opportunities, earn enhanced rewards, and shape the future of ZO.

## **🏆 Affiliate Benefits**

• Higher referral fee rebates

• Direct contact with the ZO team for support and updates

## 🎯 Expectations

• Share ZO across your social platforms, content, and community.

• Help onboard new users using your unique referral link.

• Engage with the community and provide feedback.

## ✅ How to Join

1. Fill out the [Affiliate Form](https://forms.gle/dkd4X7wbJUmnujsB9) (**Required**)
2. Activate on [Referral Portal](https://app.zofai.io/referral)
3. Contact us on social media for questions or follow-up:

• [Twitter / X](https://x.com/zofaiperps)

• [Telegram](http://t.me/sudofinanceperps)

<br>


# Referral Program

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

**Earn while you grow the ZO ecosystem**. The ZO Referral Program lets you turn your network into real rewards—referrers **earn points** and **fee rebates**, while referees get early access and a smooth onboarding experience. Whether you’re bringing in new users or joining through a trusted link, **everyone benefits**.

### 🎯 How does ZO Referral Program work?

The referral system is designed to give you real returns. There are few steps to follow to activate referral for your wallet:<br>

1. Connect your wallet on ZO
2. Set your referral link via the [referral portal](https://app.zofinance.io/referral)
3. Share your referral link with your network
4. Earn rewards when users trade on ZO

### 🎁 Referrer Benefits

• **10%** trading fee kickbacks

• Referral Points

• Point Multiplier

### ✨ Referee Benefits (People who use your link)

• Points

• Participate in ZO ecosystem growth

• Eligibility for future reward campaigns

• Support from a knowledgeable referrer to help them get started<br>

### 📈 Track Your Performance with Multiple Codes

You can generate up to **5 unique referral codes**—perfect for tracking performance across **different communities, platforms, or campaigns.**

• Use separate codes for **Twitter, Telegram, YouTube, Discord, or private groups.**

• Track how each community performs and **optimize your outreach.**

• All your earnings and activity are displayed in a simple, on-chain dashboard—transparent, reliable, and easy to use.

> 🔒 Interested in Affiliate Program? Apply via the [Affiliate Program](/programs/affiliate-program) below.


# 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>


# 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, Zo'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" %}


# Referral Program

Earn rebates through the Zo referral program.

### How it works <a href="#how-it-works" id="how-it-works"></a>

To create a referral code:

* Go to the Referrals page
* Link your wallet and copy your referral link
* Send your referral link to social media platforms.
* Fee rebate percentage: 10%

Once you've created your code, click on the copy icon next to the code to get your referral link, it should look something like this: [https://app.zofai.io/trade?referral=](https://www.zofinance.io/app/trade?referral=)\<your\_wallet\_address>.

You can share this link on any platform, e.g. Twitter, Telegram. When a user clicks on your link, your referral code would be stored with the user's account. When the user makes a trade you would earn rebates from their trading fees. You will continue to earn rebates even if the user uses another device later on as the referral code is stored on the contract the first time the user makes a trade.


# ZO Terms and Conditions

Terms and Conditions

Last modified: Feb 24th, 2025

Welcome to zofinance.io ("we," "us," or "our"), the informational resource for ZO Protocol, as defined below. zofinance.io provides information and resources about the fundamentals of the decentralized non-custodial protocol called the ZO Protocol (the "ZO Protocol," "Protocol," or "ZO DApp"). zofinance.io is not an available access point to the ZO Protocol. These Terms and Conditions and any other documents incorporated herein by reference (collectively, these "Terms") to you or the company or other legal entity you represent ("you" or "your") explains the terms and conditions by which you may access zofinance.io ("the Site") and app.zofinance.io ("the Interface"). Please do not use the Site or Interface if you disagree with any of these Terms.

1. USE OF THE SITE AND THE INTERFACE

The zofinance.io site is for informational purposes only. zofinance.io is not part of any transaction on the blockchain networks underlying the ZO Protocol; we do not have possession, custody, or control over any crypto assets appearing on the Interface; and we do not have possession, custody, or control over any user's funds. Further, we do not store, send, or receive any crypto assets. You understand that when you interact with any ZO Protocol smart contracts, you always retain control over your crypto assets. We do not have access to your private keys.

* 1.1. As a condition to accessing or using the Site or Interface, you represent and warrant to zofinance.io the following:
* * 1.1.1. If you are an individual person, then you are of legal age in the jurisdiction in which you reside, and you have the legal capacity to enter into these Terms and be bound by them;
  * 1.1.2. If you are an entity, then you must have the legal authority to accept these Terms on that entity's behalf, in which case "you" (except as used in this paragraph) will mean that entity;
  * 1.1.3. You are not a U.S. Person;
  * 1.1.4. You are not a resident, national, or agent of any country to which the United States, the United Kingdom, or the European Union embargoes goods or imposes similar sanctions (collectively, "Restricted Territories");
  * 1.1.5. You are not subject to economic or trade sanctions administered or enforced by any governmental authority; or otherwise, you are not a member of any sanctions list or equivalent maintained by the United States government, the United Kingdom government, the European Union, or the United Nations, including without limitation the U.S. Office of Foreign Asset Control Specifically Designated Nationals and Blocked Person List (collectively, "Sanctions Lists Persons");
  * 1.1.6. You do intend to transact with any Restricted Person or Sanctions List Person;
  * 1.1.7. You do not, and will not, use VPN software or any other privacy or anonymization tools or techniques, or other means, to circumvent, or attempt to circumvent, any restrictions that apply; and
  * 1.1.8. Your access is not (a) prohibited by and does not otherwise violate or assist you in violating any domestic or foreign law, rule, statute, regulation, by-law, order, protocol, code, decree, letter, or another directive, requirement, guidance, or guideline, published or in force that applies to or is otherwise intended to govern or regulate any person, property, transaction, activity, event or other matter, including any rule, letter, order, judgment, directive or other requirements, guidance, or guideline issued by any domestic or foreign federal, provincial or state, municipal, local or other governmental, regulatory, judicial or administrative authority having jurisdiction over zofinance.io or you as otherwise duly enacted, enforceable by law, the common law or equity (collectively, "Applicable Laws"); or (b) contribute to or facilitate any illegal activity.
* 1.2. As a condition to accessing or using the Site or the Interface, you acknowledge, understand, and agree to the following:
* * 1.2.1. From time to time, the Site or the Interface may be inaccessible or inoperable for any reason, including, but not limited to: (a) equipment malfunctions; (b) periodic maintenance procedures or repairs that zofinance.io or any of its suppliers or contractors may undertake from time to time; (c) causes beyond zofinance.io's control or that zofinance.io could not reasonably foresee; (d) disruptions and temporary or permanent unavailability of underlying blockchain infrastructure; or (e) unavailability of third-party service providers or external partners for any reason;
  * 1.2.2. We reserve the right to disable or modify access to the Site at any time in the event of any breach of these Terms, including, without limitation, if we reasonably believe any of your representations and warranties may be untrue or inaccurate, and we will not be liable to you for any losses or damages you may suffer as a result of or in connection with the Site or the Interface being inaccessible to you at any time or for any reason;
  * 1.2.3. The Interface may evolve, which means third parties may apply changes, replace, or discontinue (temporarily or permanently) the access at any time in their sole discretion;
  * 1.2.4. The pricing information provided on the Site or the Interface does not represent an offer, a solicitation of an offer, or any advice regarding, or recommendation to enter into, a transaction with zofinance.io;
  * 1.2.5. zofinance.io does not act as a broker or advisor for you;
  * 1.2.6. You are solely responsible for your use of the Site or the Interface, including all of your transfers of digital assets;
  * 1.2.7. To the fullest not prohibited by Applicable Law, we owe no fiduciary duties or liabilities to you or any other party, and that to the extent any such duties or liabilities may exist at law or in equity, you hereby irrevocably disclaim, waive, and eliminate those duties and liabilities;
  * 1.2.8. You are solely responsible for reporting and paying any taxes applicable to your use of the Interface; and
  * 1.2.9. We have no control over, or liability for, the delivery, quality, safety, legality, or any other aspect of any digital assets that you may transfer to or from a third party, and we are not responsible for ensuring that an entity with whom you transact completes the transaction or is authorized to do so. If you experience a problem with any transactions in digital assets using the Site or the Interface, you bear the entire risk.

1. FEES

You are required to pay all fees for transactions involving certain blockchain networks. These fees may include gas costs and all other fees reflected on the Interface at your use, including trading-related fees. zofinance.io does not receive fees for any blockchain transactions or using the Site or the Interface.

1. NO PROFESSIONAL ADVICE OR FIDUCIARY DUTIES

Nothing herein constitutes legal, financial, business, or tax advice, and you are strongly advised to consult an advisor(s) before engaging in any activity in connection herewith. All information provided by the Site is for informational purposes only and should not be construed as professional advice. You should not take, or refrain from taking, any action based on any information contained on the Site or any other information that we make available at any time, including, without limitation, blog posts, articles, links to third-party content, discord content, news feeds, tutorials, tweets, and videos. The Terms are not intended to, and do not, create or impose any fiduciary duties on us.

1. PROPRIETARY RIGHT

* 4.1. zofinance.io owns all rights, names, logos, and other marks used on the Site and the Interface, including, without limitation, any copyrights in and to any content, code, data, or other materials that you may access or use on or through the Site or the Interface; however, the code for the Zo Protocol and the Interface (app.zofinance.io) deployed on IPFS is open-sourced. Except as expressly set forth herein, your use of or access to the Site or the Interface does not grant you any ownership or other rights therein.
* 4.2. zofinance.io may use and share your comments, bug reports, ideas, or other feedback that you may provide, including suggestions about how we might improve. You agree that zofinance.io is free to use or not use any feedback we receive from you as we see fit, including copying and sharing such feedback with third parties, without any obligation to you.

1. MODIFICATION, SUSPENSION, AND TERMINATION

* 5.1. zofinance.io reserve the right, at our sole discretion, from time to time and with or without prior notice to you, to modify, suspend or disable (temporarily or permanently) the Site or our subdomain to the Interface, in whole or in part, for any reason whatsoever, including, without limitation. Upon termination of your access, your right to use the Site or the Interface from our subdomain will immediately cease. However, it would still be accessible via a third party since we do not host or own its code. zofinance.io will not be liable for any losses suffered by you resulting from any modification to the Site or the Interface or from any modification, suspension, or termination, for any reason, of your access to all or any portion of the Site or the Interface.
* 5.2. zofinance.io may revise these Terms from time to time. We will notify you by updating the date at the top of the Terms and maintaining a current version. The most current version of the Terms will always be at <https://docs.zofinance.io/terms-and-conditions/zo-terms-and-conditions>. All modifications will be effective when they are posted. By continuing to access or use the Site or the Interface after those revisions become effective, you agree to be bound by the revised Terms.

1. RISKS

* 6.1. The use of technology related to blockchain, smart contracts, and cryptocurrencies, among others, entails a risk that by accessing transactions, you are assuming. zofinance.io does not own or control any underlying software through which blockchain networks are formed. The software underlying blockchain networks are open-source so anyone can use, copy, modify, and distribute it. By using the Interface, you acknowledge and agree:
* * 6.1.1. That zofinance.io is not responsible for the operation of the open-source software and networks underlying the Interface;
  * 6.1.2. That there exists no guarantee of the functionality, security, or availability of that software and networks; and
  * 6.1.3. That the underlying networks are subject to sudden changes in operating rules, such as those commonly referred to as "forks," which may materially affect the Interface. You are responsible for securing your private key(s). We do not have access to your private key(s); losing control of your private key(s) will permanently and irreversibly deny you access to any blockchain-based network. Neither zofinance.io nor any other person or entity will be able to retrieve or protect your digital assets. If your private key(s) are lost, you will not be able to transfer your digital assets to any blockchain address or wallet. If this occurs, you will not be able to realize any value or utility from the digital assets you may hold.
* 6.2. zofinance.io is not responsible for the content of any third party, including, but not limited to, information, materials, products, or services that zofinance.io does not own or control. In addition, third parties may offer promotions related to your access and use of the Interface. zofinance.io does not endorse or assume any responsibility for such resources or promotions. Suppose you access any such resources or participate in any such promotions. In that case, you do so at your own risk and understand that these Terms do not apply to your dealings or relationships with any third parties. You expressly relieve zofinance.io of all liability arising from using such resources or participating in such promotions.
* 6.3. You understand that the Sui network blockchain remains under development, which creates technological and security risks when using the Interface, in addition to uncertainty relating to digital assets and transactions therein. You acknowledge that the cost of transacting on the Sui network blockchain is variable and may increase at any time, causing an impact on any activities taking place on these blockchains, which may result in price fluctuations or increased costs when using the Interface.
* 6.4. Transactions entered into in connection with the Interface are irreversible and final, and there are no refunds. You acknowledge and agree that you will access and use the Interface at your own risk.
* 6.5. We must comply with Applicable Law, which may require us to, upon request by government agencies, take certain actions or provide information that may not be in your best interests.
* 6.6. You hereby assume and agree that zofinance.io will have no responsibility or liability for the risks in Section 9. You hereby irrevocably waive, release and discharge all claims, whether known or unknown to you, against zofinance.io, its affiliates, and their respective shareholders, members, directors, officers, employees, agents, representatives, suppliers, and contractors related to any of the risks set forth in this Section 6.

1. PROHIBITED USES

* 7.1 You agree not to engage in the prohibited uses set forth below. The specific activities set forth below are representative but not exhaustive. By using the Site or the Interface, you confirm that you will not do any of the following:
* * 7.1.1. Promote or facilitate illegal activities, including but not limited to money laundering, terrorist financing, tax evasion, buying or selling illegal drugs, contraband, counterfeit goods, or illegal weapons;
  * 7.1.2. Engage in transactions involving items that infringe or violate any copyright, trademark, right of publicity, privacy, or any other proprietary right of zofinance.io;
  * 7.1.3. Engage in improper or abusive trading practices, including but not limited to (a) any fraudulent act or scheme to defraud, deceive, trick, or mislead; (b) trading ahead of another user of the Site or the Interface or front-running; (c) fraudulent trading; (d) accommodation trading; (e) fictitious transactions; (f) pre-arranged or non-competitive transactions; or (g) cornering;
  * 7.1.4. Uploading or transmitting viruses, worms, Trojan horses, time bombs, cancelbots, spiders, malware, or any other type of malicious code that will or may be used in any way that will affect the functionality or operation of the Site or the Interface;
  * 7.1.5. Use the Site or Interface in any way that is, in our sole discretion, libelous, defamatory, profane, obscene, pornographic, sexually explicit, indecent, lewd, vulgar, suggestive, harassing, stalking, hateful, threatening, offensive, discriminatory, bigoted, abusive, inflammatory, fraudulent, deceptive, or otherwise objectionable or likely or intended to incite, threaten, facilitate, promote, or encourage hate, racial intolerance, or violent acts against others;
  * 7.1.6. Harass, abuse, or harm another person or entity, including zofinance.io's collaborator and service providers;
  * 7.1.7. Impersonate another user of the Site or the Interface or otherwise misrepresent yourself; or
  * 7.1.8. Engage or attempt to engage or encourage, induce or assist any third party, or yourself attempt, to engage in any of the activities prohibited under this Section 4 or any other provision of these Terms.

1. DISCLOSURES; DISCLAIMERS

zofinance.io is an informational site for the Zo Protocol. zofinance.io does not operate an exchange platform or offer trade execution or clearing services and has no oversight, involvement, or control concerning your transactions using the Interface. All transactions between users of the Interface are executed peer-to-peer directly between the users' blockchain addresses through a third-party developed open-source smart contract.You are responsible for complying with all Applicable Laws that govern your Perpetual Contracts. As a result of restrictions under the Commodity Exchange Act and the regulations promulgated thereunder by the U.S. Commodity Futures Trading Commission ("CFTC"), no U.S. Person may enter into Perpetual Contracts using the Interface.You understand that zofinance.io is not registered or licensed by any regulatory agency or authority. No such agency or authority has reviewed or approved the use of the Site or the Interface.You agree that the Site and the Interface are provided on an "AS IS" and "AS AVAILABLE" basis. zofinance.io makes no guarantees of any kind or connection with the Site or the Interface.

1. LIMITATION OF LIABILITY

In no event shall zofinance.io, its affiliates, its suppliers and contractors, and its affiliates', suppliers' and contractors' respective stockholders, members, directors, officers, managers, employees, attorneys, agents, representatives, suppliers, and contractors shall be liable for any direct, indirect, incidental, special, punitive, consequential or similar damages or liabilities whatsoever (including, without limitation, damages for loss of fiat, assets, data, information, revenue, opportunities, use, goodwill, profits or other business or financial benefit) arising out of or in connection with the Site or the Interface, or other item provided by or on behalf of zofinance.io, whether under contract, tort (including negligence), civil liability, statute, strict liability, breach of warranties, or under any other theory of liability, and whether or not we have been advised of, knew of or should have known of the possibility of such damages and notwithstanding any failure of the essential purpose of these Terms or any limited remedy hereunder nor is zofinance.io in any way responsible for the execution or settlement of transactions between users of the Interface.In no event shall zofinance.io's aggregate liability arising out of or in connection with the Site or Interface exceed one thousand Singapore Dollars (1,000.00 SGD).

1. INDEMNIFICATION

You will defend, indemnify, and hold harmless zofinance.io, its affiliates, members, member, managers, employees, attorneys, representatives, suppliers, and contractors from any claim, demand, lawsuit, action, proceeding, investigation, liability, damage, loss, cost or expense, including without limitation reasonable attorneys' fees, arising out of or relating to (a) your use of or conduct in connection with the Site or the Interface (b) your violation of these Terms; or (c) your misuse of the Site or the Interface, or any smart contract and/or script related thereto; (d) your violation of any laws, rules, regulations, codes, statutes, ordinances, or orders of any governmental or quasi-governmental authorities; (e) your violation of the rights of any third party, including any intellectual property right, publicity, confidentiality, property, or privacy right; (f) your use of a third-party product, service, and/or website; or (g) any misrepresentation made by you. We reserve the right to assume, at your expense, the exclusive defense, and control of any matter subject to indemnification by you. You agree to cooperate with our defense of any claim. You will not, in any event, settle any claim without.

1. DISPUTE RESOLUTION & ARBITRATION

zofinance.io will use its best efforts to resolve potential disputes through informal, good faith negotiations. If a potential dispute arises, you must contact us by sending a written notice of your claim ("Notice") to zofinance.io on any of our official channels. The notice must (a) describe the nature and basis of the claim and (b) set forth the specific relief sought. Our notice to you will be similar in form to that described above. If you and zofinance.io cannot reach an agreement to resolve the claim within sixty (60) days of your email, then you and zofinance.io agree to resolve the potential dispute according to the process set forth below\.Any claim or controversy arising out of or relating to the Site, the Interface, or these Terms, or any other acts or omissions for which you may contend that we are liable, including (but not limited to) any claim or controversy as to arbitrability ("Dispute"), shall be finally and exclusively settled by arbitration under the Corte Civil y Mercantil de Arbitraje (CIMA). You understand that you are required to resolve all Disputes by binding arbitration. The arbitration shall be confidential before a single arbitrator, who shall be selected pursuant to the CIMA rules. The arbitration will be held in Madrid, Spain, unless you and we both agree to hold it elsewhere. Unless we agree otherwise, the arbitrator may not consolidate your claims with those of any other party. Any judgment on the award rendered by the arbitrator may be entered in any court of competent jurisdiction.Any claim arising out of or related to these Terms or the Site or the Interface must be filed within one year after such claim arose; otherwise, the claim is permanently barred, which means that you and zofinance.io will not have the right to assert the claim.

1. GOVERNING LAW

The interpretation and enforcement of these Terms, and any dispute related to these Terms, the Site, or the Interface, will be governed by and construed and enforced under the laws of the Bahamas, as applicable.

1. GENERAL INFORMATION

* 13.1. Any right or remedy of zofinance.io set forth in these Terms is in addition to, and not in lieu of, any other right or remedy whether described in these Terms, under Applicable Law, at law, or in equity. The failure or delay of zofinance.io in exercising any right, power, or privilege under these Terms shall not operate as a waiver thereof.
* 13.2. The following sections of these Terms will survive any termination of your access to the Site or the Interface, regardless of the reasons for its expiration or termination, in addition to any other provision which by law or by its nature should survive: Sections 3 through 12.
* 13.3. The invalidity or unenforceability of any of these Terms shall not affect the validity or enforceability of any other of these Terms, all of which shall remain in full force and effect.
* 13.4. zofinance.io will have no responsibility or liability for any failure or delay in performance of the Site or the Interface, or any loss or damage that you may incur, due to any circumstance or event beyond our control, including without limitation any flood, extraordinary weather conditions, earthquake, or other act of God, fire, war, insurrection, riot, labor dispute, accident, any law, order regulation, direction, action or request of the government, communications, power failure, or equipment or software malfunction.
* 13.5. You may not assign or transfer any right to use the Site, the Interface, or any of your rights or obligations under these Terms, without our express prior written consent, including by operation of law or in connection with any change of control. We may assign or transfer any or all of our rights or obligations under these Terms, in whole or part, without notice or obtaining your consent or approval.
* 13.6. These Terms contain the entire agreement between you and zofinance.io and supersede all prior and contemporaneous understandings between the parties regarding the Interface and the Site or the Interface.
* 13.7. In the event of any conflict between these Terms and any other agreement you may have with us, these Terms will control unless the other agreement specifically identifies these Terms and declares that the other agreement supersedes these Terms.
* 13.8. You agree that, except as otherwise expressly provided in these Terms, there shall be no third-party beneficiaries to the Terms other than the Indemnified Parties.

CONTACT INFORMATION

If you have any questions about these Terms, the Site, or the Interface, please get in touch with zofinance.io on any of our official channels.

<br>


# Zo Referral Program

Last modified: Feb 24th, 2025

Welcome to Zo.fi ("we," "us," or "our"), the informational resource for Zo Protocol, as defined below\.Zo.fi provides information and resources about the fundamentals of the decentralized non-custodial protocol called the Zo Protocol (the "Zo Protocol," "Zo," or "Zo DApp"). Zo.fi is not an available access point to Zo Protocol.These Terms and Conditions and any other documents incorporated herein by reference (collectively, these "Terms") to you or the company or other legal entity you represent ("you," "your," "the Referrer," "the Affiliate"), explains the terms and conditions by which you may use the Zo Referral Program ("Referral Program") as defined below\.Please do not use the Referral Program if you disagree with any of these Terms.

* USE OF THE REFERRAL PROGRAM

All this content is for informational purposes only.The Referral Program allows you to advertise the Zo DApp, thereby driving traffic to it, whereby you may earn a portion of the fees generated ("Rebates") if a person that is not you ("Trader," "Referred User") trades in the Zo DApp after being referred to it from a hyperlink ("Link") or manually input code ("Referral Code"). The Trader will benefit from a fee discount ("Discount") associated with the Referrer's tier.After being referred to the Zo DApp from a Link, the Trader's browser will save your Referral Code, which will be assigned to the Trader on his first trade.A Trader can also manually enter your Referral Code in the Traders section and change it at any time.

* OBLIGATIONS

2.1 As an Affiliate, Zo DApp provides you with the Links and Referral Codes necessary to promote the Zo Protocol. You acknowledge and agree it is your sole responsibility to indicate your correct Referral Code. You may promote the Zo Protocol offers in any manner you choose unless it misleads someone about the Zo Protocol.2.2 Zo.fi is not responsible for (i) lost sales or lost opportunity to earn Rebates due to any cause, such as technical difficulties or over-capacity, including system overload in the Sui network blockchains; (ii) tracking Rebates, Discounts, or any other data, as this is handled by independent, smart contracts.2.3 You will be excluded from the Referral Program, following the directives of the ABX tokenholders: (i) if you use any language libelous, defamatory, profane, obscene, pornographic, sexually explicit, indecent, lewd, vulgar, suggestive, harassing, stalking, hateful, threatening, offensive, discriminatory, bigoted, abusive, inflammatory, fraudulent, deceptive, or otherwise objectionable or likely or intended to incite, threaten, facilitate, promote, or encourage hate, racial intolerance, or violent acts against others; (ii) if you try any form of gaming through self-referrals.

* REBATES AND DISCOUNTS

Referrers will receive rebates based on a sliding percentage of fees paid by Referred Users. Rebates will never be retroactive.zofinance.io is under no obligation for Rebates or Discounts to any Referrer or Trader. Rebates and Discounts are handled following the directives of the ABX tokenholders.The Rebates and Discounts percentages for the default tier Tier 1, and instructions to upgrade to Tier 2 and Tier 3, are contained in[ ](https://abex-protocol.gitbook.io/abex/terms-and-conditions/abex-terms-and-conditions/abex-referral-program)<https://docs.zofinance.io/referals/referral-mechanism>

* LIMITATION OF LIABILITY

Under no circumstances shall zofinance.io be liable for any direct, indirect, incidental, punitive, special, consequential damages, or similar damages or liabilities whatsoever for any reason whatsoever related to these Terms, your use or inability to use our web site(s), or the materials and content of the web site(s) or any other web sites linked to such web site(s) or your provision of any personally identifiable information to a backend service provider or any third party. This limitation applies regardless of whether the alleged liability is based on contract, tort, warranty, negligence, strict liability, or any other basis, even if we have been advised of the possibility of such damages or such damages were reasonably foreseeable.In no event shall zofinance.io's aggregate liability arising out of or in connection with the Site exceed five hundred Singapore Dollars (500 SGD).

* INDEMNIFICATION

You will defend, indemnify, and hold harmless abexfi, its affiliates, members, member, managers, employees, attorneys, representatives, suppliers, and contractors from any claim, demand, lawsuit, action, proceeding, investigation, liability, damage, loss, cost or expense, including without limitation reasonable attorneys' fees, arising out of or relating to arising under these Terms, the service(s) provided by zofinance.io, or your use of the service(s) provided by zofinance.io, including, without limitation, an infringement by you, or by anyone else using such service(s) we provide to you, of any intellectual property or other proprietary rights of any person or entity, or from the violation of any of our operating rules or policies relating to the service(s) provided. When we may be involved in a suit involving a third party and which is related to our service(s) to you under these Terms, we may seek written assurances from you in which you promise to defend, indemnify and hold us harmless from the costs and liabilities described in this paragraph. Such written assurances may include, in our sole discretion, the posting of a performance bond(s) or other guarantees reasonably calculated to guarantee payment. We may consider your failure to provide such assurances a breach of these Terms by you. The terms of this paragraph will survive any termination or cancellation of the Terms.

* MODIFICATION, SUSPENSION, AND TERMINATION

The Referral Program runs independently from zofinance.io, which the token holders of ABX determine. Due to this, from time to time and with or without prior notice to you, the Referral Program could be subject to modifications, suspensions, or disabilities, in whole or in part, for any reason whatsoever.zofinance.io will not be liable for any losses suffered by you resulting from any modification to the Referral Program or from any modification, suspension, or termination, for any reason, of your access to all or any portion of the Interface or the Protocol.zofinance.io may revise these Terms from time to time. We will notify you by updating the date at the top of the Terms and maintaining a current version. The most current version of the Terms will always be at[ https://zofinance.io/referral-terms](https://abex-protocol.gitbook.io/abex/terms-and-conditions/abex-terms-and-conditions/abex-referral-program). All modifications will be effective when they are posted. By using the Referral Program after those revisions become effective, you agree to be bound by the revised Terms.

* GOVERNING LAW

The interpretation and enforcement of these Terms, and any dispute related to these Terms, the Site, or the Interface, will be governed by and construed and enforced under the laws of the Singapore, as applicable.

* GENERAL

8.1 These Terms, including other policies or agreements incorporated herein, constitute the entire and only agreement between you and zofinance.io concerning the subject matter of these Terms and supersede all prior or contemporaneous agreements, representations, warranties, and understandings, written or oral, concerning the subject matter of these Terms. Any failure by us to exercise or enforce any right or provision of the Terms shall not constitute a waiver of such right or provision.8.2 You must legally be able to enter into the Terms. Using the Referral Program, you represent and warrant that you meet the eligibility requirement. If you do not meet the requirement, you must not access the Referral Program.8.3 Nothing contained herein will be construed to create the relationship of principal and agent, employer and employee, partners or joint venturers. Each party shall ensure that the foregoing persons shall not represent to the contrary, either expressly, implicitly, by appearance, or otherwise.8.4 If any provision of these Terms shall be unenforceable or invalid under any applicable law or be held by any applicable court decision, such unenforceability or invalidity shall not render these Terms unenforceable or invalid as a whole. zofinance.io will amend or replace such provision with one that is valid and enforceable and which achieves, to the extent possible, our original objectives and intent as reflected in the original provision.8.5 You may not assign or transfer any right to use the Referral Program, or any of your rights or obligations under these Terms, without our express prior written consent, including by operation of law or in connection with any change of control. zofinance.io may assign or transfer any or all of our rights or obligations under these Terms, in whole or part, without notice or obtaining your consent or approval.8.6 zofinance.io will have no responsibility or liability for any failure or delay in performance of the Site, or any loss or damage that you may incur, due to any circumstance or event beyond our control, including without limitation any flood, extraordinary weather conditions, earthquake, or other act of God, fire, war, insurrection, riot, labor dispute, accident, any law, order regulation, direction, action or request of the government, communications, power failure, or equipment or software malfunction.

CONTACT INFORMATION

If you have any questions about these Terms, the Site, or the Interface, please get in touch with zofinance.io on any of our official channels.

<br>


# Building on ZO

Enable perpetuals trading and earn rebates using our SDK

### Summary

* [ZO SDK](/building-on-zo/zo-sdk): Typescript ZO SDK for perpetuals trading and LP operations
* [Trading Widget](/building-on-zo/trading-widget): React Perpetual Trading Widget
* [Automated Trading Bot](/building-on-zo/automated-trading-bot): Example Trading Bot that leverages zo-sdk


# ZO SDK

Integrate ZO with our Typescript SDK

## Summary

* [Introduction](/building-on-zo/zo-sdk/introduction)
* [Architecture](/building-on-zo/zo-sdk/architecture)
* [Getting Started](/building-on-zo/zo-sdk/getting-started)
* [Common Operations](/building-on-zo/zo-sdk/common-operations)
* [Trading Examples](/building-on-zo/zo-sdk/trading-examples)
* [Swap Examples](/building-on-zo/zo-sdk/swap-examples)
* [Type Safety](/building-on-zo/zo-sdk/type-safety)
* [Error Handling](/building-on-zo/zo-sdk/error-handling)
* [API Reference](/building-on-zo/zo-sdk/api-reference)

### NPM

{% embed url="<https://www.npmjs.com/package/@zofai/zo-sdk>" %}


# Introduction

ZO SDK is a TypeScript SDK for interacting with multiple LP tokens on Sui Network: **ZLP** (ZO Liquidity Provider), **SLP** (Sudo Liquidity Provider), and **USDZ** (USD Stablecoin).

### Installation

```bash
npm install @zofai/zo-sdk
# or
yarn add @zofai/zo-sdk
# or
pnpm add @zofai/zo-sdk
```

For the full guide, see Getting Started.


# Architecture

The SDK supports multiple LP tokens through a unified interface:

* **ZLP (ZO Liquidity Provider)**: Original ZO Protocol LP token
* **SLP (Sudo Liquidity Provider)**: Sudo SDK-based LP token
* **USDZ (USD Stablecoin)**: Stablecoin LP token

### Key Components

1. **Common Interfaces**: Unified API surface for all LP tokens (`IBaseAPI`, `IBaseDataAPI`)
2. **Abstract Base Classes**: Shared logic with delegation to DataAPI (`BaseAPI`, `BaseDataAPI`)
3. **Concrete Implementations**: LP-specific functionality (`ZLPAPI`, `SLPAPI`, `USDZAPI`)
4. **Factory Pattern**: Type-safe instance creation via `SDK` (e.g. `SDK.createZLPAPI()`)


# Getting Started

1\. Create an API or DataAPI instance

Use the **SDK** factory (exported as `SDK` from `zo-sdk`) to create LP-specific instances. You need a Sui client, network, API endpoint, and connection URL.

```typescript
import { SDK, LPToken, Network } from '@zofai/zo-sdk'
import { SuiClient } from '@mysten/sui/client'

const provider = new SuiClient({ url: 'https://fullnode.mainnet.sui.io' })
const network = Network.MAINNET
const apiEndpoint = 'https://api.zofinance.io'
const connectionURL = 'https://hermes.pyth.network'

// Create API instances (transactions + data)
const zlpAPI = SDK.createZLPAPI(network, provider, apiEndpoint, connectionURL)
const slpAPI = SDK.createSLPAPI(network, provider, apiEndpoint, connectionURL)
const usdzAPI = SDK.createUSDZAPI(network, provider, apiEndpoint, connectionURL)

// Or create by LP token enum
const api = SDK.createAPI(LPToken.ZLP, network, provider, apiEndpoint, connectionURL)

// Create DataAPI instances (read-only; no transaction methods)
const zlpDataAPI = SDK.createZLPDataAPI(network, provider, apiEndpoint, connectionURL)
const slpDataAPI = SDK.createSLPDataAPI(network, provider, apiEndpoint, connectionURL)
const usdzDataAPI = SDK.createUSDZDataAPI(network, provider, apiEndpoint, connectionURL)

// Or create DataAPI by LP token
const dataAPI = SDK.createDataAPI(LPToken.SLP, network, provider, apiEndpoint, connectionURL)
```

### 2. API vs DataAPI

| Use case                           | Class                                          | Use                                                                                                                |
| ---------------------------------- | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| **Build transactions + read data** | **API** (`ZLPAPI`, `SLPAPI`, etc.)             | Deposit, withdraw, open/close positions, stake, and also call data methods (market info, vaults, positions, etc.). |
| **Read-only**                      | **DataAPI** (`ZLPDataAPI`, `SLPDataAPI`, etc.) | Only query chain/API state (market valuation, vault info, positions, orders, history). No transaction building.    |

**API** instances expose both transaction methods and data methods. Data methods (e.g. `getMarketInfo`, `valuateMarket`, `getVaultInfo`) are implemented by delegating to the internal `dataAPI`, so you can call them directly on the API or via `api.dataAPI`:

```typescript
const zlpAPI = SDK.createZLPAPI(network, provider, apiEndpoint, connectionURL)

// Data methods are available directly on the API (same result either way)
const marketData = await zlpAPI.valuateMarket()
const marketDataAlt = await zlpAPI.dataAPI.valuateMarket()

// Transaction methods exist only on the API
const depositTx = await zlpAPI.deposit('usdc', ['coinId'], 1000000)
```

**DataAPI** instances are for read-only usage when you don't need to build transactions:

```typescript
const zlpDataAPI = SDK.createZLPDataAPI(network, provider, apiEndpoint, connectionURL)
const marketData = await zlpDataAPI.valuateMarket()
const vaultInfo = await zlpDataAPI.getVaultInfo('usdc')
// zlpDataAPI.deposit(...) does not exist
```


# Common Operations

These operations work across all LP tokens (ZLP, SLP, USDZ).

### Data / read operations

Use the API or DataAPI; the methods are the same.

```typescript
const zlpMarket = await zlpAPI.valuateMarket()
const slpMarket = await slpAPI.getMarketInfo()
const vaultInfo = await usdzAPI.getVaultInfo('usdc')
const positionCaps = await zlpAPI.getPositionCapInfoList(ownerAddress)
const positions = await zlpAPI.getPositionInfoList(positionCaps, ownerAddress)
```

### Deposit

```typescript
const depositTx = await zlpAPI.deposit(
  'usdc',             // coin type
  ['coinObjectId'],   // coin object IDs
  1000000,            // amount
  0,                  // minimum amount out (optional)
  'referralAddress',  // optional referral
  'senderAddress'     // optional sender
)
const slpDepositTx = await slpAPI.deposit('usdc', ['coinObjectId'], 1000000)
const usdzDepositTx = await usdzAPI.deposit('usdc', ['coinObjectId'], 1000000)
```

### Withdraw

```typescript
const withdrawTx = await zlpAPI.withdraw(
  'usdc',
  ['lpCoinObjectId'],
  1000000,
  0
)
```

### Swap

```typescript
const swapTx = await zlpAPI.swap(
  'usdc',             // from token
  'sui',              // to token
  BigInt(1000000),    // amount
  ['coinObjectId']    // coin objects
)
```


# Trading Examples

### Limit order vs. market order

When you open or decrease a position, you choose how the order is executed:

| Type                | `isLimitOrder` | `isIocOrder` | Behavior                                                                                                                             |
| ------------------- | -------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------ |
| **Market order**    | `false`        | —            | Execute immediately at market. Use **slippage** (`pricesSlippage`, `collateralSlippage`) to bound worst price.                       |
| **Limit order**     | `true`         | `false`      | Stored as a pending order; executes when the price condition is met. Typically use **zero or small slippage** (`pricesSlippage: 0`). |
| **IOC limit order** | `true`         | `true`       | Fill only if the limit can be met immediately; otherwise cancel (no partial fill).                                                   |

* **Market**: best for “get in/out now”; you accept some slippage.
* **Limit**: best when you want a specific price; order stays pending until the price condition is met.
* **IOC limit**: “fill at my price or not at all” in one block.

***

### ZLP / SLP: Open position (market order)

Execute immediately with slippage protection:

```typescript
const tx = await zlpAPI.openPositionV2(
  'usdc',             // collateral token
  'btc',              // index token
  BigInt(1000000),    // size
  BigInt(100000),     // collateral amount
  ['coinObjectId'],   // coin objects
  true,               // long position
  BigInt(50000),      // reserve amount
  30000,              // index price (reference)
  1.5,                // collateral price (reference)
  false,              // isLimitOrder: false = market order
  false,              // isIocOrder (ignored for market)
  0.003,              // pricesSlippage: 0.3% for market
  0.5,                // collateralSlippage: 50% for market
  BigInt(500),        // relayer fee
  'referralAddress',
  'senderAddress'
)
```

***

### ZLP / SLP: Open position (limit order)

Pending order at your limit price; use zero or small slippage:

```typescript
const tx = await zlpAPI.openPositionV2(
  'usdc',
  'btc',
  BigInt(1000000),
  BigInt(100000),
  ['coinObjectId'],
  true,                // long
  BigInt(50000),
  30000,               // your limit price (index)
  1.5,                 // collateral price
  true,                // isLimitOrder: true = limit order
  false,               // isIocOrder: false = pending until price is met
  0,                   // pricesSlippage: 0 for limit (exact price)
  0.5,                 // collateralSlippage
  BigInt(500),
  'referralAddress',
  'senderAddress'
)
```

***

### ZLP / SLP: Open position (IOC limit order)

Fill only if the limit can be met immediately; otherwise the order does not execute:

```typescript
const tx = await zlpAPI.openPositionV2(
  'usdc',
  'btc',
  BigInt(1000000),
  BigInt(100000),
  ['coinObjectId'],
  true,
  BigInt(50000),
  30000,
  1.5,
  true,                // isLimitOrder: true
  true,                // isIocOrder: true = fill now or cancel
  0,
  0.5,
  BigInt(500),
  'referralAddress',
  'senderAddress'
)
```


# Swap Examples

This guide covers how to integrate swaps using the ZO SDK. Swaps are supported on **ZLP**, **SLP**, and **USDZ** via `api.swap()`, `api.swapV2Ptb()`, and fee estimation via `dataAPI.calculateSwapFeeBreakdown()`.

### Overview

A swap flow typically involves:

1. **Estimate fees** – Get the expected fee breakdown for the swap.
2. **Set slippage protection** – Compute `minAmountOut` based on expected output and slippage tolerance.
3. **Build transaction** – Call `api.swap()` to construct the transaction.
4. **Sign and send** – Sign with the wallet and submit to the network.

### Amounts and units

* `fromAmount` is in **atomic units** (raw token units), e.g. `1_000_000` for 1 USDC (6 decimals).
* `minAmountOut` is in **atomic units** of the destination token.
* `calculateSwapFeeBreakdown(fromAmount)` expects atomic units for the source token.

```typescript
// Example: swap 100 USDC (6 decimals) for SUI
const fromAmount = BigInt(100 * 1e6)  // 100_000_000 atomic units
```

### Estimate swap fees

Before building the swap transaction, you can estimate the fee breakdown to display to the user or compute a safe `minAmountOut`.

```typescript
import { SDK, LPToken, Network } from '@zofai/zo-sdk'
import { SuiClient } from '@mysten/sui/client'

const provider = new SuiClient({ url: 'https://fullnode.mainnet.sui.io' })
const network = Network.MAINNET
const apiEndpoint = 'https://api.zofinance.io'
const connectionURL = 'https://hermes.pyth.network'

const slpDataAPI = SDK.createSLPDataAPI(network, provider, apiEndpoint, connectionURL)

// fromAmount in atomic units (e.g. 100 USDC = 100 * 1e6)
const fromToken = 'usdc'
const toToken = 'sui'
const fromAmount = 100 * 1e6

const feeBreakdown = await slpDataAPI.calculateSwapFeeBreakdown(fromToken, toToken, fromAmount)

// feeBreakdown contains:
// - swapValue: notional in USD
// - totalVaultsValue: total vault value in USD
// - rebaseFeeInRate, rebaseFeeOutRate: rates for swap-in and swap-out
// - rebaseFeeInValue, rebaseFeeOutValue: rebase fee amounts in USD
// - swapImpactFeeValue: swap impact fee in USD
// - emaVolatilityFeeValue: EMA volatility fee in USD
// - totalFeeValue: sum of all fee components
// - totalFeeRate: totalFeeValue / swapValue

console.log(`Total fee: ${feeBreakdown.totalFeeValue.toFixed(4)} USD`)
console.log(`Fee rate: ${(feeBreakdown.totalFeeRate * 100).toFixed(2)}%`)
```

### Build and submit swap transaction

Use the **API** instance to build the swap transaction. You need:

* `fromToken`, `toToken` – token identifiers (e.g. `'usdc'`, `'sui'`).
* `fromAmount` – amount in atomic units (bigint).
* `fromCoinObjects` – owned coin object IDs for the source token.
* `minAmountOut` – optional; minimum output amount in atomic units (slippage protection).

```typescript
const slpAPI = SDK.createSLPAPI(network, provider, apiEndpoint, connectionURL)

const fromAmount = BigInt(100 * 1e6)  // 100 USDC
const fromCoinObjects = ['0x...']     // user's USDC coin IDs

// Optional: set minAmountOut to protect against slippage
// e.g. 1% slippage: minAmountOut = expectedOut * 0.99
const minAmountOut = 0  // or compute from oracle + slippage

const tx = await slpAPI.swap(
  'usdc',
  'sui',
  fromAmount,
  fromCoinObjects,
  minAmountOut
)

// Sign with wallet and execute
// const signed = await signAndExecuteTransaction({ transaction: tx })
```

### Swap and return coin to user (swapV2Ptb)

Use `swapV2Ptb()` when you need the output coin returned as a `TransactionObjectArgument`—for example, to pass into another move call or to transfer it within the same transaction. Unlike `swap()`, which consumes the output internally, `swapV2Ptb()` returns the output coin so you can compose it into larger transactions.

Pass an optional `tx` to compose into an existing transaction; otherwise a new transaction is created (you must sign and execute it via your wallet).

```typescript
const slpAPI = SDK.createSLPAPI(network, provider, apiEndpoint, connectionURL)

// Option 1: Standalone swap (tx created internally)
const tx = new Transaction()
const outputCoin = await slpAPI.swapV2Ptb(
  'usdc',
  'sui',
  BigInt(100 * 1e6),
  fromCoinObjects,
  minAmountOut,
  tx
)
// tx is modified in place; sign and execute tx

// Option 2: Compose with other move calls
const composedTx = new Transaction()
const swapCoin = await slpAPI.swapV2Ptb('usdc', 'sui', BigInt(100 * 1e6), fromCoinObjects, minAmountOut, composedTx)
composedTx.transferObjects([swapCoin], composedTx.pure.address(recipientAddress))
```

### Complete integration example

```typescript
import { SDK, LPToken, Network } from '@zofai/zo-sdk'
import { SuiClient } from '@mysten/sui/client'

async function swapWithFeeEstimate(
  fromToken: string,
  toToken: string,
  fromAmountAtomic: number,
  fromCoinObjects: string[],
  slippageBps: number = 50,  // 0.5%
) {
  const provider = new SuiClient({ url: 'https://fullnode.mainnet.sui.io' })
  const api = SDK.createSLPAPI(
    Network.MAINNET,
    provider,
    'https://api.zofinance.io',
    'https://hermes.zofinance.io'
  )

  // 1. Estimate fees
  const feeBreakdown = await api.dataAPI.calculateSwapFeeBreakdown(
    fromToken,
    toToken,
    fromAmountAtomic
  )

  // 2. Compute minAmountOut from fee breakdown (net value after fees) and slippage
  const toPrice = (await api.getOraclePrice(toToken)).getPriceUnchecked().getPriceAsNumberUnchecked()
  const toDecimals = 9  // use deployment consts or lookup
  const netValueUsd = feeBreakdown.swapValue - feeBreakdown.totalFeeValue
  const expectedOutAtomic = (netValueUsd * (10 ** toDecimals)) / toPrice
  const minAmountOut = Math.floor(expectedOutAtomic * (1 - slippageBps / 10000))

  // 3. Build transaction
  const tx = await api.swap(
    fromToken,
    toToken,
    BigInt(fromAmountAtomic),
    fromCoinObjects,
    minAmountOut
  )

  return {
    transaction: tx,
    feeBreakdown,
  }
}
```

### Fee components

| Component              | Description                                                               |
| ---------------------- | ------------------------------------------------------------------------- |
| **Rebase fee (in)**    | Fee on the source token when swapping in; depends on vault utilization.   |
| **Rebase fee (out)**   | Fee on the destination token when swapping out.                           |
| **Swap impact fee**    | Fee from `SwapImpactConfig`; scales with `swapValue / totalVaultsValue`.  |
| **EMA volatility fee** | Fee from `EmaVolatilityFeeConfig`; scales with price divergence from EMA. |

Use `calculateSwapFeeBreakdown` to get the USD value of each component and the total fee before executing the swap.

### Token identifiers

Tokens are identified by their symbol in the deployment config, e.g. `'sui'`, `'usdc'`, `'usdt'`, `'eth'`, `'btc'`. Ensure the `fromToken` and `toToken` values match those in the LP’s supported tokens.


# Type Safety

The SDK is built with TypeScript and provides comprehensive type definitions.

### Interfaces

```typescript
import type {
  IBaseAPI,
  IBaseDataAPI,
  IZLPAPI,
  ISLPAPI,
  IUSDZAPI,
  IBaseMarketValuationInfo,
  IBaseVaultInfo,
  IBaseSymbolInfo,
  IBasePositionInfo,
  IBaseOrderInfo
} from 'zo-sdk'

// All APIs implement their respective interfaces
const zlpAPI: IZLPAPI = SDK.createZLPAPI(network, provider, apiEndpoint, connectionURL)
const slpAPI: ISLPAPI = SDK.createSLPAPI(network, provider, apiEndpoint, connectionURL)
const usdzAPI: IUSDZAPI = SDK.createUSDZAPI(network, provider, apiEndpoint, connectionURL)

// Type-safe data: call data methods directly on the API or via .dataAPI
const marketInfo: IBaseMarketValuationInfo = await zlpAPI.valuateMarket()
const vaultInfo: IBaseVaultInfo = await zlpAPI.getVaultInfo('usdc')
```


# Error Handling

The SDK throws errors for invalid operations and network issues. Always wrap API calls in try-catch blocks:

```typescript
const zlpAPI = SDK.createZLPAPI(network, provider, apiEndpoint, connectionURL)

try {
  const marketInfo = await zlpAPI.getMarketInfo()
  const depositTx = await zlpAPI.deposit('usdc', ['coinId'], 1000000)
} catch (error) {
  console.error('SDK operation failed:', error)
  if (error.message.includes('Unsupported LP token')) {
    console.error('Invalid LP token type provided')
  }
}
```


# API Reference

### Factory methods

**API (full – transactions + data):**

* `SDK.createZLPAPI(network, provider, apiEndpoint, connectionURL)`
* `SDK.createSLPAPI(network, provider, apiEndpoint, connectionURL)`
* `SDK.createUSDZAPI(network, provider, apiEndpoint, connectionURL)`
* `SDK.createAPI(LPToken, network, provider, apiEndpoint, connectionURL)`

**DataAPI (read-only):**

* `SDK.createZLPDataAPI(network, provider, apiEndpoint, connectionURL)`
* `SDK.createSLPDataAPI(network, provider, apiEndpoint, connectionURL)`
* `SDK.createUSDZDataAPI(network, provider, apiEndpoint, connectionURL)`
* `SDK.createDataAPI(LPToken, network, provider, apiEndpoint, connectionURL)`

### Interfaces

* **Base**: `IBaseAPI`, `IBaseDataAPI` for common operations
* **LP-specific**: `IZLPAPI`, `ISLPAPI`, `IUSDZAPI` for typed usage
* **Data types**: `IBaseMarketValuationInfo`, `IBaseVaultInfo`, `IBaseSymbolInfo`, `IBasePositionInfo`, `IBaseOrderInfo`, etc.

### Source code

* **Interfaces**: `src/interfaces/` – TypeScript interface definitions
* **Implementations**: `src/implementations/` – Concrete API implementations
* **Abstract classes**: `src/abstract/` – Shared base functionality
* **Factory**: `src/factory/SDKFactory.ts` – SDK instance creation

See the type definitions and source for detailed method signatures and parameters.


# Trading Widget

#### Overview

The ZO Trading Widget (@zofai/trading-widget) is an embeddable perpetuals trading UI for ZO Finance on Sui.It lets you drop a full-featured trading interface into your dapp:

* Market header – Symbol selector, mark price, funding rate
* Price chart – Pyth-powered OHLC with live updates
* Recent trades – Live trade feed
* Trade panel – Open/close positions (market & limit) on ZLP / SLP / USDZ
* Positions / Orders / History – Bottom tabs, each with a countdown to next refresh
* RPC settings – Predefined or custom RPC URL with latency checks
* Wallet – Sui wallet connect via @mysten/dapp-kit-react and an account sidebar

You can either:

* Use the full widget as a single component, or
* Compose custom layouts using the exported components and hooks.


# Requirements

#### Installation

Install the widget from your package registry:

`pnpm add @zofai/trading-widget` or `npm install @zofai/trading-widget` or `yarn add @zofai/trading-widget`

NPM:

{% embed url="<https://www.npmjs.com/package/@zofai/trading-widget>" %}

### Peer dependencies

Your app must install:

* `react` & `react-dom` (≥18)
* `jotai` (≥2)
* `@tanstack/react-query` (≥5)
* `@mysten/dapp-kit-react` (≥1) & `@mysten/sui` (≥2)
* `zo-sdk` (≥0.1)

#### Styling

The widget uses Tailwind-compatible utility classes (e.g. `flex`, `text-white`, `rounded-lg`). Either:

* Use **Tailwind CSS** or **UnoCSS** in your app so those classes resolve, or
* Import the bundled CSS once in your app: `import '@zofai/trading-widget/style.css'` . This file contains the compiled UnoCSS used by the widget.


# Quick Start

### Full Widget Layout

1. **Wrap your app** with the required providers (order matters):

```tsx
import { appStore } from '@zofai/trading-widget'
import { Provider as JotaiProvider } from 'jotai'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { DAppKitProvider } from '@mysten/dapp-kit-react'

// Your dapp-kit instance (Sui wallet + network)
import { dAppKit } from './dapp-kit'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: { staleTime: 60_000, retry: 2 },
  },
})

export function Root() {
  return (
    <JotaiProvider store={appStore}>
      <QueryClientProvider client={queryClient}>
        <DAppKitProvider dAppKit={dAppKit}>
          <App />
        </DAppKitProvider>
      </QueryClientProvider>
    </JotaiProvider>
  )
}
```

2. **Render the widget** where you want the trading UI:

```tsx
import { TradingWidget } from '@zo/trading-widget'

export function App() {
  return (
    <div className="h-screen flex flex-col">
      <header>{/* Your navbar, connect button, etc. */}</header>
      <main className="min-h-0 flex-1">
        <TradingWidget className="h-full" />
      </main>
    </div>
  )
}
```

**TradingWidget props**

| Prop        | Type     | Description                         |
| ----------- | -------- | ----------------------------------- |
| `symbol`    | `string` | Initial symbol (default `"BTC"`)    |
| `className` | `string` | Extra class on the widget container |

The default `<TradingWidget />` contains:

* Header – MarketHeader
* Symbol dropdown (index tokens from ZLP / SLP)
* Mark price
* 1h funding rate
* Main area
* PriceChart (Pyth candlesticks + streaming)
* RecentTrades (live trades)
* TradePanel (open positions, leverage, collaterals)
* Bottom tabs – BottomTabs
* PositionsList
* OrdersList
* HistoryList
* Each tab shows a circular countdown to the next auto-refresh.
* Dialogs & toasts
* Confirmation and success dialogs (open / close / adjust)
* Toast notifications via react-hot-toast.

Use this when you want the fastest integration path.


# Custom Layout

### Custom layout

Use **`TradingWidgetProvider`** and the sub-components to build your own layout:

```tsx
import {
  TradingWidgetProvider,
  MarketHeader,
  PriceChart,
  RecentTrades,
  TradePanel,
  BottomTabs,
  CustomConnectButton,
  RpcSettings,
} from '@zofai/trading-widget'

export function CustomTradePage() {
  return (
    <TradingWidgetProvider>
      <div className="flex flex-col h-full bg-gray-950 text-white">
        <header className="flex items-center gap-3 border-b border-gray-800 px-4 py-2">
          <MarketHeader />
          <div className="flex-1" />
          <RpcSettings />
          <CustomConnectButton />
        </header>
        <div className="flex flex-1 overflow-hidden">
          <div className="flex-1 min-w-0">
            <PriceChart />
          </div>
          <aside className="w-48 shrink-0">
            <RecentTrades />
          </aside>
          <aside className="w-72 shrink-0">
            <TradePanel />
          </aside>
        </div>
        <div className="h-52 shrink-0 border-t border-gray-800">
          <BottomTabs />
        </div>
      </div>
    </TradingWidgetProvider>
  )
}
```

Ensure your app is wrapped with **Jotai** (`appStore`), **React Query**, and **DAppKit** as in Quick start.


# Components

#### All-in-one

* **`TradingWidget`** – Full layout: header, chart, recent trades, trade panel, bottom tabs (positions/orders/history), dialogs and toasts.

#### Layout & header

* **`TradingWidgetProvider`** – Sui + React Query + Jotai setup. Use when building a custom layout so sub-components have the same context.
* **`MarketHeader`** – Symbol dropdown (from ZLP/SLP index tokens), mark price, funding rate.

#### Market data

* **`PriceChart`** – Pyth-backed candlestick chart (history + streaming).
* **`RecentTrades`** – Recent trades for the selected symbol.

#### Trading & account

* **`TradePanel`** – Long/short, market/limit, leverage, collateral selector; opens positions on ZLP/SLP/USDZ.
* **`CustomConnectButton`** – Connect wallet; when connected opens the account sidebar instead of a dropdown.

#### Tables (bottom section)

* **`BottomTabs`** – Tabs: Positions, Orders, History; each shows a circular countdown to next refresh.
* **`PositionsList`** – Open positions with PnL, adjust/close.
* **`OrdersList`** – Open orders with cancel.
* **`HistoryList`** – Trade history.

#### Settings

* **`RpcSettings`** – Dropdown: choose predefined RPC or enter custom URL; shows latency. Persists to `localStorage` so the widget’s provider uses the selected RPC.


# Hooks & Store

For custom UIs that need widget data or actions:

**Hooks**

* `useEssential()` – wallet, network, consts (zo/sudo/usdz), accountData, refreshAccount
* `useWallet()`, `useNetwork()` – wallet and current network
* `usePosition(address, network)` – positions list, refresh, `dataUpdatedAt`
* `useOrder(address, network)` – orders list, refresh, `dataUpdatedAt`
* `useHistories(address, network)` – trade history
* `useFundingRate(symbol, network, lpToken)` – funding rate
* `usePositionConfig(network, { symbols })` – position config (fees, etc.)
* `useSymbolInfo(network)` – symbol info map (ZLP/SLP/USDZ)
* `useRpc()` – RPC list, custom URL, latency; used by `RpcSettings`
* `useSponsoredGasAvailability(address, network)` – gas sponsorship

**Store (Jotai)**

* `appStore` – same store instance must be used for the widget and your app (see Quick start).
* `currentSymbolAtom` – `{ symbolId, unit, icon }`; set when user picks a market.
* `tokenPriceAtom` – `{ tokenPrice: Record<string, number>, isLoading, error }` (Pyth oracle prices).


# RPC and Wallet

* **RPC** – The widget reads RPC from `localStorage`: `is-custom-rpc`, `custom-rpc-url`, `custom-rpc-index`. Use **`RpcSettings`** in your header (or elsewhere) so users can pick a predefined RPC or set a custom URL. After changing RPC, a full page refresh is recommended.
* **Wallet** – Uses **Sui dapp-kit**. Your app must create a `dAppKit` (e.g. with `createDAppKit`) and wrap the tree in `DAppKitProvider`. **`CustomConnectButton`** triggers the kit’s connect flow; when connected, it opens the widget’s account sidebar.


# Example Integration

### Example app

This [repo](https://github.com/zofinance/zo-integration-examples/tree/main/react-ui) includes an example app that integrates the widget

### Stack

* **React 18** + **TypeScript** + **Vite**
* **@zofai/trading-widget** – ZO trading UI and components
* **@mysten/dapp-kit-react** + **@mysten/sui** – Sui wallet connection (mainnet)
* **UnoCSS** – styling (Tailwind-style utilities + shadcn preset)
* **Jotai** – state (via widget `appStore`)
* **TanStack Query** – data fetching

### Setup

```
pnpm install
```

### Scripts

| Command        | Description              |
| -------------- | ------------------------ |
| `pnpm dev`     | Start dev server (Vite)  |
| `pnpm build`   | Production build         |
| `pnpm preview` | Preview production build |

### Project structure

* `src/main.tsx` – App bootstrap: Jotai, React Query, DAppKit, and root `<App />`
* `src/App.tsx` – Layout with header (brand, RPC settings, connect button) and full-height `<TradingWidget />`
* `src/dapp-kit.ts` – Mysten dApp Kit config (Sui mainnet/testnet gRPC URLs and type registration)

### Requirements

* The widget expects to run inside the providers set up in `main.tsx`: `JotaiProvider` (with `appStore`), `QueryClientProvider`, and `DAppKitProvider`.
* Import the widget styles: `@zofai/trading-widget/style.css`


# Automated Trading Bot

## ZO Trading Bot

Example bot that trades on [ZO Finance](https://zofai.io) using the **zo-sdk**. Supports market orders with take-profit/stop-loss (TPSL), and a grid bot.

{% embed url="<https://github.com/zofinance/zo-integration-examples/tree/main/trading-bot>" %}

### Prerequisites

* **Node.js** (v18+)
* **pnpm** (or npm)
* A **Sui wallet** with a private key you can export (for automated signing)
* **SUI** on the target network (mainnet/testnet) for gas and trading

### Quick start

#### 1. Install dependencies

```bash
pnpm install
```

#### 2. Configure environment

Copy the example env file and set your secrets (never commit `.env`):

```bash
cp .env.example .env
```

Edit `.env`:

| Variable              | Required | Description                                                                              |
| --------------------- | -------- | ---------------------------------------------------------------------------------------- |
| `NETWORK`             | No       | `mainnet` or `testnet`. Default: `mainnet`.                                              |
| `SUI_MAINNET_RPC_URL` | No       | Sui mainnet RPC. Default: public fullnode.                                               |
| `SUI_TESTNET_RPC_URL` | No       | Sui testnet RPC. Default: public fullnode.                                               |
| `PRIVATE_KEY`         | **Yes**  | Sui private key in **Bech32** format (e.g. `suiprivkey1...`). Used to sign transactions. |

**Getting your Bech32 private key**

* From **Sui CLI**: export the key for your key identity (Bech32 is one of the supported formats).
* From **Sui wallet**: use the wallet’s export feature if it supports Bech32; otherwise you may need to convert.

The app uses `decodeSuiPrivateKey(privateKeyBech32)` from `@mysten/sui/cryptography`, so the key must be in a format that function accepts (e.g. Bech32 `suiprivkey1...`).

#### 3. Run the bot

**Market / TPSL bot** (entry point: `index.ts`):

```bash
pnpm start
```

**Grid bot** (entry point: `grid-bot-run.ts`):

```bash
pnpm run grid
```

Before running, edit the config in the corresponding file (see below).

***

### Integration overview

#### How the bot connects to ZO

1. **Connection** (`connection.ts`)
   * Builds a `SuiClient` from `SUI_MAINNET_RPC_URL` or `SUI_TESTNET_RPC_URL` and `NETWORK`.
   * Uses **zo-sdk** `SDKFactory` to create API and DataAPI instances for ZLP, SLP, and USDZ pools.
   * ZO API endpoint: `https://api.zofinance.io`. Pyth price connection: `https://hermes.pyth.network`.
2. **Keypair** (`keypair.ts`)
   * Loads `PRIVATE_KEY` from env and creates an `Ed25519Keypair` via `decodeSuiPrivateKey` + `Ed25519Keypair.fromSecretKey`.
   * Used for signing all Sui transactions (opens/closes positions, places/cancels orders).
3. **Trade config**
   * You choose pool (`LPToken.ZLP`, `LPToken.SLP`, or `LPToken.USDZ`), index token (e.g. `btc`), collateral (e.g. `nusdc`), sizes, and (for TPSL) take-profit/stop-loss percentages.

#### Config for market / TPSL bot

Edit `index.ts` and set `TradeConfig` (and optionally switch between `tradeWithMarketOrder` and `tradeWithTPSL`):

* `indexToken`, `collateralToken`, `pool`, `long`
* `minSize` / `maxSize` (in index token base units, e.g. 1e8 for BTC) or fixed `size`
* `collateralAmount` (in collateral base units, e.g. 6 decimals for USDC)
* `takeProfitPercentage`, `stopLossPercentage`
* `tradeInterval` (ms), `tradeMode`: `'Market'` or `'TPSL'`
* `createOpposite`: whether to open the opposite position after closing.

#### Config for grid bot

Edit `grid-bot-run.ts` and set the grid config object:

* `indexToken`, `collateralToken`, `pool`
* `gridLowerPrice`, `gridUpperPrice`, `gridLevels`
* `orderSize` (index token base units), `collateralAmount` (collateral base units)
* `pollIntervalMs`, optional `maxVolumeUSD`

Then run:

```bash
pnpm run grid
```

#### Project layout

| File              | Purpose                                                                                             |
| ----------------- | --------------------------------------------------------------------------------------------------- |
| `index.ts`        | Market / TPSL bot entry; defines `TradeConfig` and calls `tradeWithMarketOrder` or `tradeWithTPSL`. |
| `grid-bot-run.ts` | Grid bot entry; defines grid config and calls `runGridBot`.                                         |
| `grid-bot.ts`     | Grid bot logic (place/cancel orders, rebalance grid).                                               |
| `trade.ts`        | Core trading: open/close positions, TPSL and market flows.                                          |
| `connection.ts`   | Sui client and ZO SDK API/DataAPI instances (ZLP/SLP/USDZ).                                         |
| `keypair.ts`      | Loads `PRIVATE_KEY` from env and returns Ed25519 keypair.                                           |
| `network.ts`      | Reads `NETWORK` from env (mainnet/testnet).                                                         |
| `order.ts`        | Order caps and order key parsing.                                                                   |
| `position.ts`     | Position helpers.                                                                                   |
| `utils.ts`        | Relayer fee, reserve amount, coin helpers.                                                          |
| `constants.ts`    | Slippage, relayer fee, trade-level constants.                                                       |
| `deployments.ts`  | Uses `zo-sdk` `getConsts(NETWORK)` for contract addresses.                                          |

#### Dependencies

* **zo-sdk** – ZO protocol API and types (pools, positions, orders).
* **@mysten/sui** – Sui client, keypair, transactions.
* **dotenv** – Loads `.env` into `process.env`.
* **bignumber.js** – Numeric handling for sizes and fees.


