# Protocol Overview

FlowX is the ecosystem-focused decentralized exchange built on the Sui Blockchain.

FlowX Finance is an ecosystem-focused decentralized exchange (DEX) built on the Sui blockchain. It is the ultimate destination for all trading needs, designed to provide a seamless, user-friendly experience.

For users, they can enjoy a smooth trading experience with the best rates aggregated from all AMMs on SUI. The platform offers an intuitive UI and allows users to participate in various vital services in DeFi, such as token swapping, liquidity contribution, yield farming, and joining IDO campaigns on FlowX launchpad.&#x20;

FlowX Finance also provides listing and market-making services, making it easy to operate farming campaigns with Farming as a Service features.


# Our Advantages

How FlowX Finance differs from other DEX?

FlowX Finance stands out by prioritizing the improvement of the DeFi user experience with a variety of advanced features. Our platform offers multi-token swap function, a liquidity management dashboard, position migrating, and a decentralized exchange aggregator.

* **DEX Aggregator**: By pooling liquidity from various DEXs, FlowX Finance optimizes user trading by providing better prices, lower transaction costs, and reduced slippage compared to trading on any single DEX.
* **Various Swap Types**: Instant Swap, Dollar-Cost Averaging, Limit Order, suitable for use with your investment strategies while always ensuring the best slippage and can be used with any token on Sui
* **Lucky Swap**: Earn tickets by swapping via FlowX Aggregator to enter a daily draw for the grand prize.
* **Position Migrating**: FlowX Finance allows users to effortlessly move their Liquidity Positions while ensuring minimal slippage.
* **Farming as a Service:** FaaS provides new projects with a convenient and efficient way to launch their token's liquidity pool. By utilizing FlowX's FaaS, projects can reduce their contract creation costs and reach a wider user base.
* **One-stop Project Launch:** This package includes all the necessary features for a team to successfully launch a project on Sui such as raising funds, initiating and bootstrapping liquidity, providing market maker volume services, and among others.<br>


# Getting Started

As FlowX Finance operates on the Sui Blockchain, users need to have a crypto wallet that can connect to this blockchain to access the platform's features and services.

1. Click on the “Connect Wallet” button on the top right corner.&#x20;
2. Select a compatible crypto wallet from the list of supported wallets to start using FlowX.

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

{% hint style="info" %}
Users also need SUI tokens to pay gas fees for transactions at FlowX.
{% endhint %}

### List of supported wallets:

* Sui Wallet&#x20;
* Fewcha Wallet
* Martian Wallet
* Surf Wallet
* Ethos Wallet
* Coin98 Wallet


# Roadmap

Our goal is to play a significant role in the development of Sui Blockchain. For the year 2023, we are prioritizing the development of fundamental features.

### Q1-Q2 2023: Under the hood

* [x] Multiple Token Swap Feature Testnet&#x20;
* [x] Yield Farming / Boost Function Testnet
* [x] Uni v2 Liquidity Pool Testnet
* [x] Testnet Marketing Campaign
* [x] Analytics Dashboard
* [x] Liquidity Management

### Q3 2023:  Feature flourishing

* [x] Mainnet Launch
* [x] Genesis Farming Launch
* [x] Trading Competition&#x20;
* [x] One-click Liquidity Migration
* [x] Real-time Price Chart
* [x] Regular Yield Farming
* [x] Farming as a Service
* [x] DEX Aggregator

### Q4 2023: On-board Feature

* [x] LaunchpaX&#x20;
  * [x] Pre-sale FLX
  * [x] Public sale FLX
* [x] FLX / xFLX Convert
* [x] Bot Notification

### Q1 2024: Community - Driven

* [x] FLX Liquidity Mining Program ( Pending Release )
* [x] Governance Feature ( Pending Release )
  * [ ] Proposal
  * [ ] Gauges
  * [ ] Bribes
  * [x] Dividend Room

### Q2 2024: Efficiency Improvement

* [x] Concentrated Liquidity Market Makers
* [x] FlowX Aggregator V2
* [x] Auto-invest (DCA) Feature

### Q3 2024: Invest Strategy Customize&#x20;

* [ ] Automated Liquidity Management for CLMM
* [x] Limit Order

### Q4 2024: Expand Ecosystem

* [x] FlowX Private Market Marker release
* [x] Sui Wallet integration
* [x] Lucky Swap Features

### Q1 2025: Build Stronger Partnership&#x20;

* [x] Revamp UI
* [x] New DEX integration
  * [x] Full Sail
  * [x] Magma Finance


# Swap

FlowX Swap, our core product, represents a new approach to optimizing the user experience in decentralized exchanges. By leveraging the flexibility features of the Move language, FlowX is able to offer a superior user experience when compared to traditional AMMs:&#x20;

* Allows swapping from one token to multiple tokens and vice versa.
* Aggregates liquidity from other DEXs within the Sui ecosystem to optimize prices and reduce slippage.

## **How to Swap on FlowX Finance**

On FlowX, we support users as much as possible in Swap tokens. We have developed Aggregator to help users find the best route with optimal slippage, avoiding affecting the swap experience. Besides, we support One to Many swap users to ensure convenience for users without worrying about LP slippage and to boost ecosystem liquidity.

In order to swap, access the [Swap](https://flowx.finance/swap) tab.

### &#x20;Swap a token to another token

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcp8s2HaKBpDLFovWfVUKTHjbd3VXMSoXuosmGy7eMYUjNVQXtSN1pQumaVGPKzeE1l7T3kmvo0qMsUg2l1qieZOQwxXTvOQT49SCsAwW8eUjgwhFiv2SAPJMb0yaM5oKtMMw_ITQ?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

* Select the token you'd like to swap
* Enter the amount
* Select the token you would like to receive
* Click on “Swap” button

{% hint style="info" %}
You can view detailed information about the order you want to swap such as: Slippage, Rate, Price Impact, Fee, Route by clicking on the "Trade Details" button.
{% endhint %}

### Change the “Slippage Tolerance”

* To be able to change Slippage Tolerance, users click on the "Gear" icon on the right corner.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdRPLNFXq_pJwjQ50T57rkKR1WJMnVSNX5_EAEcZgtsKeLaR_n9NQiRylRRz-8lkK5qjdsM8b_IC3enazsQa85OSj37HbaQzzwbAjC6Q2IOrcAo9WW3aIHqsa3wG8r-f7rnyASS?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

* After that, you can choose the amount of the slippage tolerance you would like.


# DEX Aggregator

FlowX Aggregator is a tool designed to enhance your on-chain swap experience.

\
FlowX Aggregator enhances the DeFi swap experience by dividing and redirecting swaps across all incorporated DEXs on Sui Ecosystems. Through analyzing swap rates for the same token pair and considering potential price impacts of the swap against certain pools, FlowX Aggregator can provide the best possible liquidity to facilitate a specific trade.&#x20;

The Aggregator not only provides the best possible slippage, effectively increasing profits in each swap, but also saves you time.

### Integrated Liquidity sources

<table data-view="cards"><thead><tr><th></th><th></th><th></th><th></th><th></th><th></th></tr></thead><tbody><tr><td><img src="/files/4iHAhOQDocFpuDByw4QX" alt="" data-size="line"> Cetus Zone</td><td><img src="/files/dp9aPOpUsl3Fu4TjqPfu" alt="" data-size="line"> FlowX Finance</td><td><img src="/files/QdmlfpidbXtwRqOcpJWe" alt="" data-size="line"> Aftermath Finance</td><td><img src="/files/FPXEK8vqWEtPQEWVUfk8" alt="" data-size="line"> DeepBook</td><td><img src="/files/r1cDzitcvozgTm9fjnUS" alt="" data-size="line"> Turbos Finance</td><td><img src="/files/kb8aXbK4XkaWvQzVJQq4" alt="" data-size="line"> Kryia DEX</td></tr><tr><td><img src="/files/t1UQIOxwNkIQxx7GzoaK" alt="" data-size="line"> Bluefin</td><td><img src="/files/e504BXYigG8X1QzO3luR" alt="" data-size="line"> STEAMM</td><td><img src="/files/t1jUbQqKo5cU1msZxd74" alt="" data-size="line"> Magma Finance</td><td><img src="/files/M470cy8ZUUKfqN7dPMqX" alt="" data-size="line"> Momentum</td><td><img src="/files/MvggzQTZWls3N9rwnv2P" alt="" data-size="line"> Haedal LST</td><td><img src="/files/BE0MrAd0wINeIb3s457O" alt="" data-size="line"> Volo LST</td></tr><tr><td><img src="/files/xDC0UDNeWqtrh6gVJCPc" alt="" data-size="line"> Scallop </td><td><img src="/files/ZVYq4o0mDy8UAAEbXl3b" alt="" data-size="line"> Spring LST</td><td><img src="/files/3nNKi3brTojF8jO2Hggf" alt="" data-size="line">Obric</td><td><img src="/files/98YxG64VSh6XMAJoeMt4" alt="" data-size="line"> Metastable</td><td><img src="/files/gLt8R7sMyNhyEFeqvzVh" alt="" data-size="line"> Full Sail</td><td><img src="/files/l2UGvXpp6MzHxMcEYEbI" alt="" data-size="line"> Bolt Liquidity</td></tr></tbody></table>

### How to use FlowX Aggregator&#x20;

DEX Aggregator is the default feature provided to users when accessing the swap interface of FlowX Finance.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcd9EYCB493a3X55Ey4XTLrVs5EyjgHJhE7dOtQHtEEyfWoRXejEnBeTzFKPFebhkjy5dpoDIjxU7t2AoIDSu0i4uBR8-8mocpBzNRri_nQkmx-krGAetB16UZADQDRq2eL52dJUw?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

To turn off the DEX Aggregator feature (not recommended), you can go to the Settings icon, select active Legacy Swap V2 to only use liquidity at FlowX V2.

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

Users can choose the Liquidity Sources used to aggregate liquidity in the Liquidity Source section, selecting the used Liquidity Sources.

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

{% hint style="info" %}
For the best rate, we encourage users to always activate all available liquidity sources. It should only be turned off in certain cases if an error occurs.
{% endhint %}


# Perpetuals


# Fee

Fees are based on your rolling 14 day volume and are assessed at the end of each day in UTC.

| 14D Weighted Volume | Maker  | Taker  |
| ------------------- | ------ | ------ |
| Under 5M            | 0.015% | 0.045% |
| Above 5M            | 0.012% | 0.040% |
| Above 25M           | 0.008% | 0.035% |
| Above 100M          | 0.004% | 0.030% |
| Above 500M          | 0.000% | 0.028% |

Maker rebates are paid out continuously on each trade directly to the trading wallet.

### Deposit / Withdrawal Fee

FlowX Perp does not charge any deposit fees when users deposit to Perp Account.

A fee of **1 USDC** will be charged for each withdrawal.


# Funding Rate

### What is the funding rate? <a href="#what-is-the-funding-rate" id="what-is-the-funding-rate"></a>

In perpetual futures contracts, the funding rate is a periodic payment exchanged between traders holding long and short positions. This mechanism helps ensure that the contract price stays close to the underlying spot market price.

* Positive funding rate: When the contract price is above the mark price, long traders pay short traders.
* Negative funding rate: When the contract price is below the mark price, short traders pay long traders.

### Funding Amount

The funding amount is how much you will actually pay or receive based on the funding rate.

Funding amount = Position size × Mark price × Funding rate

This value is transferred between long and short traders depending on the direction of the funding rate. **FlowX does not charge or receive funding** — it is a peer-to-peer transfer.

<br>


# Lucky Swap

FlowX Lottery is the latest feature on FlowX Finance, where users earn tickets to enter a daily draw.

Your ticket needs to match the winning number to win the prizes from the pool! The Draw happens at 12:00 UTC daily.

&#x20;Each ticket has 6 digits. To win a share of the prize pool, you need to match all 6 in exact order, left to right, with the winning numbers.

Find out more about FlowX Lottery here: <https://flowx.finance/lucky-swap>&#x20;

## 🎫 How to get Tickets at “FlowX Lottery”?

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

There are 4 ways to earn tickets:

### 1️⃣ Swap on FlowX:&#x20;

Every $1,000 in trading volume = 1 ticket (max 5 tickets per round).

### 2️⃣ Stake xFLX:&#x20;

Stake 100 xFLX in an epoch to increase your max tickets for each day of the next epoch by 1.

### 3️⃣ Invite Friends:&#x20;

Earn 10% of the tickets collected by your referrals—unlimited!&#x20;

### 4️⃣ Hold NOVAGEN NFTs:

Hold at least 5 NOVAGEN = 1 ticket daily

Hold 10 NOVAGEN = 3 tickets daily

You can buy Novagen NFTs: <https://www.tradeport.xyz/sui/collection/novagen>&#x20;

## 🏅 Winning Criteria

Let's take a real example here:

\- Ticket A: Matches first 3 and last 2 numbers, but not the 4th => it will win a “Matches First 3” prize.

\- Ticket B: The last 5 numbers match, but the first doesn’t => no prize. Matching must begin from the first digit.

Prize pots don't 'stack': if you match the first 3 digits in order, you'll only win prizes from the "Matches First 3" pot, and not from "Matches First 1" and "Matches First 2".

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

## 🏆 Reward Pool

The Prizes for each lottery round come from:

### FLX injections

At the beginning of each round, an amount of FLX taken from the DAO Treasury will be used to deposit as the pool's reward.

### Rollover Prizes

After every round, if nobody wins in one of the prize brackets, the unclaimed FLX for that bracket rolls over into the next round and is redistributed among the prize pools.


# Liquidity Pools

FlowX Finance offers two distinct liquidity pools to users: the **Constant Product Liquidity ( V2 )** and the **Concentrated Liquidity (V3)** .

### How to Add Liquidity V2

Go to [Position ](https://flowx.finance/position)tab, then click “Create Position”

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdOV3X17tdzLOOplHdU-eEWe6wxzxSz0BGjHP45AV3t-AekD7xv7d-VLqiaSO6L5miZxzLaaY2ybQ97K6BzXaaMAg6q8It9klj9t3ZVzuFUDK97L1tGSnZhAfUjjbu8jXFSgLJE8w?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

Click on “Select Tokens” to choose the pool you want to add liquidity. (If you cannot find the token you want to add liquidity to, you can copy the contract address of that token here, then select to add liquidity)&#x20;

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXd-uC16WDgTDtp3llEOt29fZaBLKakOQ0Fz8GbVEL5M7FryfSadMHlp6Ls155ETHzq2kPYxXRq4COK6ZVICiTbLwE1WvUVaWwEch60hkP8bbsDih6Y4JQTX-Ed5d-0p2mQ368mYhA?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

Select the number of tokens of each type that you want to add liquidity to the pool (you need to make sure there are enough for both tokens), then click "Create New Position”

### How to Add Liquidity V3

Go to FlowX Portfolio at:[ ](https://flowx.finance/portfolio)<https://flowx.finance/position>, choose Create Position, then choose the token’s pair you want to add, select V3 Position, and click Continue

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXfBVxzInWRIVwTvOncZElts82fevpUe9lP8wgkUYGpkIv8GgL8M_0NNVh1tUTVMdwNIbszGM9AaTIndgpaqOvo_QH2kvHeM3VsOpFeHcP6L00IYUwgd3wkWotNs4MeeiQliRMW3jA?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

Set a range for each token respectively, where you think it has the most concentrated liquidity.

<br>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdbgJsDnCmPeJMTltVdZfGTelm4gWzvGAzrSfmdU9BL-avvDkV0AVKOp5zJaM1gfWWOmqngno0bl-ydxlbz3w06zqg4g4NOl0a-1y7eisG6Bxh1QhetcQKcNfR9TdVjtHjRdmI5lg?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

After choosing the amount of token you want to add, click “Create”.

<br>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXemaIPk47F1bActg2SVCeT8bNZpftsC7-BE9cZiHnznc1prjXpsYX5-9ac2A7n4pKSDYHFmnL-u5j4hjHovbkiY0UZ0VxYRlSUTT5jLsF660hzQ7rPVYGYrFzI3edE_8eRoM_G6nQ?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

Confirm and approve on your wallet, then Transaction Submitted.

After successfully adding liquidity, your liquidity position will appear at[ ](https://flowx.finance/portfolio)<https://flowx.finance/position>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcdzUJJTNQ8WM453cXdjW5m8LCsMZ6LDOvSc_kxR9nvbwFmzP81EwaVW3XTqfEeH21oro7Nrod1XZWauMd1JehWZY3jwdcIfS70BX1CvWh0R9zoZNL3rhLqFpAkXRuzamBDpsuHaQ?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>


# Position Management

The FlowX Dashboard is a powerful portfolio management tool that allows liquidity providers and users to seamlessly track their assets in one place. Users can monitor their portfolio value, including tokens, yield farming rewards, and liquidity pools, with ease.

Key Features:

* Open new liquidity positions directly from the Portfolio tab.
* Find the most attractive liquidity pools on FlowX Finance to maximize returns.
* Monitor and manage all liquidity positions on a single page, whether in-range or out-of-range.
* Tracking unclaimed earning reward for each position


# Farming as a Service

Besides supporting new projects easily and conveniently when launching liquidity pools on FlowX, Farming as a Service (FaaS) also supports projects:

* Projects can **reduce their contract creation costs**, reach a wider user base and bootstrap liquidity in a pool by incentivizing liquidity providers with token emissions.
* Creating FaaS on FlowX is **permissionless**. Projects can create their own liquidity pools (if not already on FlowX) and then initialize farming pools.
* In addition, if projects want to integrate FaaS into the project's dapp, we have a complete **set of SDKs** for projects.

FaaS is a choice for you when solving issues related to liquidity and you will be able to make the most suitable decisions for your project.

### ⛔ Some IMPORTANT NOTE before creating a farm

It is highly suggested to carefully read and understand this entire guide before creating a farm.

Besides creating farming pools for available pools on FlowX, if you want to create farming pools for new pools on FlowX, you can directly create a new pool and add liquidity to that pool, then create a farming pool for that pool.

Setting Reward and Duration: With FaaS, project teams can crowdsource liquidity from the community in a decentralized manner, so setting up reward and duration is very important.

#### Reward:&#x20;

* The project can choose tokens to reward farming pool participants. The project can choose up to 2 tokens in the pool to reward users.
* Regarding the number of reward tokens: The project will have to choose the reward to suit the duration of the farming pool. The reward per second will not be less than 1 token unit. That's why the project must choose a reasonable reward pool.

#### **Duration:**

* The duration of farming pool is not limited, projects can choose farming pool to take place in a short period of time (a few days) or take place over a longer period of time (a few weeks, a few months).
* But projects must note that the farming pool's duration must be consistent with the reward pool that the project has added to the farming pool.

### 🔌Creating a Farming as a Service&#x20;

* Connect wallet and choose target liquidity pool
* Go into: <https://flowx.finance/faas> and click “New FaaS pool.” Make sure your wallet is connected.&#x20;
* Search for the liquidity pool you want to create a farm for in the drop-down menu or by pasting the AMM ID. Every new farm must be linked to an AMM ID. The same AMM ID can be used for more than one farm on SUI.

<figure><img src="https://lh7-us.googleusercontent.com/LtUu5v2-ULBcMd_bZ1KR-7D5oew0PFRDgpx311g4QOh13dScM2hrpTow5b5GwzZEzRku2qsFZKgHHafcixkCaYsf-JVgLBksK1q8PRRcnlvJFL84JVGTib3VsfYQTcTfrfvSEdAYiqIXCcRBmaerLCw" alt=""><figcaption></figcaption></figure>

NOTE: If you want to create a Farming as a Service for a pool that is not on FlowX, you can directly create a new pool and add liquidity to that pool.

<figure><img src="https://lh7-us.googleusercontent.com/7zAGkWMp8rYx43_Sz4t62TdCoPAfdU2Vdo3txke3oCPvtG0sdqExcOmIyip75nW9C7tv2YquizGvSKNPQg4EeUFKVaM-RGBxYFWrz_bwWKkdf4QesqsPZDLQoG7VY7ywbJiNdpbOyeZQSlW1R6-15HY" alt=""><figcaption></figcaption></figure>

* Set up duration and rewards:&#x20;

**Rewards:** Choose the reward token and amount to be emitted from the farm. Farms support a minimum of 1 reward token and a maximum of 2 reward tokens.

**Duration and Start Time**: Choose a duration for farming period. The period for farming pool is not limited to the number of days (projects can choose the duration for farming pool depending on the project plan). Then select the date and time for the farming to start. The farming end time will be calculated accordingly.

<figure><img src="https://lh7-us.googleusercontent.com/hCw2PFRaGpMu4zvn1p3iEgOYwumbO8UXsooOVF0XYgdso0eFn-j1HaDVc8g3EI1a9UouQ3ZlBDPTSYcfBVAl1iyTvAXoa9sgef3mjQs_Le_ffvldaYS7vomzldW7Ucqtuint87rX-lApFPjvItPKnuY" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}

**Some important notes:**&#x20;

* Rewards allocated to farms are final and cannot be withdrawn once the farm is created. Additional rewards can be added to the farm, more details on adding rewards are below.

* After the start time, rewards are only emitted if there are LP tokens staked in the farm. Meaning APR may remain at 0% if there are no users staking LP tokens at the start. In this case, you may want to consider staking a small amount of LP tokens to ensure APR displays properly.
  {% endhint %}

* Make sure to confirm that rewards, duration and start time are correct. These can not be changed once the farm is created.&#x20;

* Confirm that your wallet has 100 SUI for the creation fee, then click 'CONFIRM'.

That's it, your farm should be live right after clicking “CONFIRM". You can click the “[Farm as a Service](https://flowx.finance/faas)” tab on the Farm tab to view your farms.

### 🚜 Farming at Community Pool

#### 1. Check out existing Farming as a Service (FaaS) Pools on FlowX

Go into [FaaS](https://flowx.finance/faas) to check all available FaaS pools on FlowX  Finance

<figure><img src="https://lh7-us.googleusercontent.com/xCzIWLze9n1-SZxeFUmLtUoZsIynpQBftduFuB1epy9-0ebGUVO2S4g4nshE1aNSY6mdOG2PZBnNQZpQIOoVHVQmqVx2MnfryRc8opsqu9USiF71pksNTItIMMufzhUz5GbsH63P70CZIYf3V1zraJ8" alt=""><figcaption></figcaption></figure>

NOTE: To join FaaS pools on FlowX, you need LP tokens of the token pair you want to join.

#### 2. Add liquidity and take LP Token

Go to [Portfolio](https://flowx.finance/portfolio) tab, then click “New Position”&#x20;

<figure><img src="https://lh7-us.googleusercontent.com/qCaGBVNvI_u6FuVZZ6ZQBibw_ufgfL4fdpjO0XDlsEMWJSfVpLJqQ0x57WycIyBcQrQBITwuRWhFU3OPsNES-9e_V3FYRh-lkK1OLMtK70NqUjgLVfPQiXrwYhDwKpYGaStUMZVBZKOPi8CxxSMj1KM" alt=""><figcaption></figcaption></figure>

&#x20;Click to “Select 2 tokens” to choose the pool you want to add liquidity

<figure><img src="https://lh7-us.googleusercontent.com/2hVIOknaDZCebtejTacNrL8Gx8QBSGiMjO6YEMU7XqU3GSSb5OtbTPlrmgNwMDjyC0eTcUYzEKVSnSfewfW2lBnJcwyjgFC-SRgTXl2OHlVf1cOPyRG2AhKI1tsSKCmE2OqGswN69-xu5lffFOVQ3yM" alt=""><figcaption></figcaption></figure>

NOTE: If you cannot find the token you want to add liquidity to, you can copy the token contract of that token here, then select to add liquidity.

<br>

<figure><img src="https://lh7-us.googleusercontent.com/HvRg4LExaSS1gn16hqwE8agC6TQzslcEmMDqCDBnE68hIr9tjvOLKgB-CdY937MsD42eOLSk7ItH06bnMMdso6VFY3wtgiSW8fGJB1oOhN9RSdvuqx7ZSeMve4Hk3eEgq7t0DkvbEXAERIRv7owyy60" alt=""><figcaption></figcaption></figure>

Select the number of tokens of each type that you want to add liquidity to the pool (you need to make sure there are enough for both tokens), then click "Supply"

<figure><img src="https://lh7-us.googleusercontent.com/ilcb4JzVOkVhF4cKnHAyXX6HaSazMkd37KjiMh5cIS-V8cNAMrV4lJtMgz3J8XhYleza6U8C5jE869OLU3kHQvhuRINSBGFsGln9mkcexlhh7UiT6oXNMgwoZSQLBFcQUgqYeMqx04jO7vpPOzA7r1M" alt=""><figcaption></figcaption></figure>

After adding liquidity, you will receive the LP token of Liquidity pool you just added, you can check it in your wallet.&#x20;

#### 3. Stake LP Token to Pool

Choose a FaaS pool you want to enjoy, then click to them

<figure><img src="https://lh7-us.googleusercontent.com/bxfZxnTo2sigEGEGAQkPqOCThCl29edJCofZC2XyzAKAzEJEaAuz0x-km-af_tzs7fhLA0TNg3AKcYFGD2KzGNpIBw7Gn4R5aBa1BG4YcCGJMWGZh2NY_LSjv2MSZF_Jqpm3yeJnkf5jhnKT0WGJMQI" alt=""><figcaption></figcaption></figure>

Click here to choose the amount of LP token you want to deposit to the FaaS pool, then click “Confirm”

<figure><img src="https://lh7-us.googleusercontent.com/KcUOGkG-TLMr5ORZnK9rt-a_q-RNgIPkzzSRwpNcXMi_X7OUTqX5DWIw-HnMzf3FSMt9AZhuleSE85Gk10fKRZxq3ap_f9CYRnLU_cQhYZVNG6aODQrymfp-dJJURa5jL7olWO9f3371mNs6UQ65Og0" alt=""><figcaption></figcaption></figure>

NOTE:&#x20;

* You can check your pending reward and can claim all pending rewards by clicking “Harvest”.&#x20;
* You can Deposit more LP token to the FaaS pool by clicking “Deposit”. After you add more LP Tokens to the FaaS pool you added previously, the rewards will be automatically harvested and sent to your wallet.

<figure><img src="https://lh7-us.googleusercontent.com/Lkh6YeQ_m1tUTvZ_QTBJMWQpnC-7ssxhXmqCmNtNAXTItUBtFj-gz0IcxzH_RtKGlkOyIuuGyBAeOrUhRm2UJysRCngwTZT2luxF-f5HvbO2CdJnhslVywZC-xnpYlWn0rh1WZAvA6K9M_O-ecYsXqg" alt=""><figcaption></figcaption></figure>


# Earning Protocol Fee

Users deposit xFLX tokens on FlowX Finance to earn protocol fees, which include trading fees.

Stake here: <https://flowx.finance/stake>

Protocol fees will be converted into Sui on a regular basis and added to the reward pool. The converted fees will then be distributed to users at the end of each Epoch.

FlowX team also committed to using half of protocol revenue to buy back and burn $FLX weekly.

Protocol Fee Address: [0x31f02af26aeb374d2fe1bd1d5eaf4a6ac4a01e78c27f71363b70f2a5fec8111b](https://suiexplorer.com/address/0x31f02af26aeb374d2fe1bd1d5eaf4a6ac4a01e78c27f71363b70f2a5fec8111b)

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

{% hint style="info" %}
When making a withdrawal, users' xFLX will be prepared and available to be claimed to their wallets in the next epoch.
{% endhint %}

{% hint style="danger" %}
Please note that users will not receive any rewards for the withdrawn amount xFLX during this epoch.
{% endhint %}


# Trading Competition


# Referral

The FlowX Referral Program is designed to reward users who help grow the ecosystem by inviting others to trade on our aggregator. By sharing your unique referral link, you can earn a percentage of the trading fees generated by users you refer. It's a simple and effective way to earn while supporting the FlowX community.&#x20;

## Guide to Create Referral Links on FlowX&#x20;

* Head to:[ flowx.finance/referral](http://flowx.finance/referral) and Connect your Sui wallet

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXe1w60wlSNhxeM3ZIU30HLuZ90ymQaknDSd5W3e0zYNDBuTcBbpTzuGXRBl45eCGgC-s73rGERtXGFfySEjh_Plw23HZXTrSweVzbqGbA_rfAhunHJNRUFNts9ChEbFZUJ54ypIoQ?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

* Choose your personalized ID name, then click “Confirm” and confirm the tx in your wallet

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXeAEFf3PhHIOjlLGSiikdJnmdYNJEPDbNWTL2nBbgt1L5-6WUDBaScVkBEt1Vh8CUlyFgKskZ4wmdGIJPw3BDf3uk1NlVVw7DY-211HQQPwuHTsSpEbg4c5rVvh_oGlhfNo7GSjdw?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

* Set your referral fee and select the trading pair you want to earn from.
* Setting Referral link:&#x20;
  * Choose a referral fee percentage to earn from each transaction made through your link. You can set it anywhere between 0.01% and 1% and even zero.
  * Remember, you can change the default USDC-SUI pair to any other trading pair you want to earn from by editing the link later on.
  * A referral link could look like this:[ https://flowx.finance/swap/USDC-SUI?ref=flowx\&fee=1](https://flowx.finance/swap/USDC-SUI?ref=flowx\&fee=1) (This means you'll earn a 0.01% fee for every trade made by others using your link for the USDC/SUI pair)

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXcRpoO6VBP-K5v3zyANd3qjU0307ethy9tZVcUQ969W9g1R_PqGWeAaVCS-qEEH3rtqq9Wv1ON013XdHa1UhJj58nxirjbUo3-Tk7uiyYtBp8zaQoSmE1KS4xw4VYElX-fOk5hZwQ?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

* Share your referral link Once your link is ready, copy it and share it with your friends, followers, or community.

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXdTYNswSvC2s-SfPmB8L1jdtquhcJYOMGyns0ycQ1A0RJeco-m47DctHd7yKe-y0bDam6ZFVMwYE8ONm8UVyR-vo8aK6VbYwSDu0chybRkGBxEtxz0cmpZgXm5Vdtk-v3bgYGLnOQ?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>

## FAQs

<details>

<summary>1.How are referral fees earned?</summary>

Referral fees are automatically claimed in the output token of the trade. For example, if your link is used for a USDC-SUI trade, you’ll earn fees in SUI tokens.

</details>

<details>

<summary>2.Can my referral ID be used with multiple wallets?</summary>

No, each referral ID is unique and permanently tied to a single wallet address.

</details>

<details>

<summary>3.Can I set different referral fees for different links?</summary>

Yes, you can create multiple referral links with different fee percentages for various audiences or purposes. Changing the fee percentage for a new link won’t affect your existing links.

</details>

<details>

<summary>4.Can I set a referral fee higher than 1%?</summary>

No, the maximum referral fee you can choose is 1%.

</details>

<details>

<summary>5.Can I change the default trading pair for my referral link?</summary>

Yes, the default trading pair is USDC-SUI, but you can change it to any other pair you prefer such as SUI-FLX, sbETH-USDC, etc.

</details>

<details>

<summary>6.How do I track my referral earnings?</summary>

You can track your earnings directly on the platform's referral dashboard, where you’ll see accumulated fees and trade details.

</details>

<details>

<summary>7.Do referral fees apply to all trades made by a referred user?</summary>

Yes, when users trade using your referral link, all their trades across any pairs will continue to generate referral fees for you. However, they can disable tipping via your referral link at any time.

</details>

<details>

<summary>8. Is there a limit to how many referral links I can create? </summary>

No, you can create multiple referral links with different settings to optimize your earnings.

</details>

When users trade using your referral link, the FlowX Swap page will display like this:

<br>

<figure><img src="https://lh7-rt.googleusercontent.com/docsz/AD_4nXe8Qm6poreOvFMPRN2Kt5hyFV4uUMWjARKG22MVeCWSdawWIC6X-KTwxRFwdKPqw4_F--0GFp2vpMecZL6gFaRLy256PAZnLsQ72862OrjdZrc4itF1rsh_lX4R5AhCDR3ehEo0BQ?key=WiPrJJ1GJFwp1aeCjDPzJLMg" alt=""><figcaption></figcaption></figure>


# Audit

AMM Audit Report from Verichain:

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

AMM Audit Report from SotaLabs:&#x20;

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

FlowX V3 ( CLMM ) Audit Report from Movebit:&#x20;

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

Vaults Audit Report from Certik:

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


# Media Kit

Please use suitable logos for light and dark backgrounds as shown below.

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

### Logos

Please find both .PNG and .SVG files below:&#x20;

### PNG

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

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

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

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

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

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

{% file src="/files/5mDfdHl2Wyk2t8PEdWss" %}

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

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

{% file src="/files/6y7R8bUSvn4v9gac3xBU" %}

### SVG

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

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

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

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

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

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

### Color Palettes

* Blue: #1890FF
* Black: #1E1E1E
* White: #FFFFFF
* Gray: #4A4A4A

### Font

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


# Partners

The protocol is all about community and is built by the community.&#x20;

FlowX Finance focuses on teaming up with innovative web3 partners, being their DeFi layer to provide the best web3 experience.

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


# Overview

The FlowX.Finance Developer Documentation provides comprehensive guidance on integrating and utilizing FlowX's decentralized exchange (DEX) and liquidity aggregation services built on the Sui blockchain. Developers can access detailed instructions on leveraging the FlowX Finance SDK and Swap Widget to enhance their DeFi applications. To stay informed about the latest developments, updates, and feature releases, developers are encouraged to join the FlowX Dev Update channel on Telegram: <https://t.me/FlowXDevUpdate>.

## FlowX SDK and Widget

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

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

## FlowX open source

{% embed url="<https://github.com/FlowX-Finance/amm-interface>" %}

{% embed url="<https://github.com/FlowX-Finance/clmm-contracts>" %}

## FlowX Contract

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

<table><thead><tr><th width="152">Contract</th><th>PackageId</th></tr></thead><tbody><tr><td>CLMM Contract</td><td>0x25929e7f29e0a30eb4e692952ba1b5b65a3a4d65ab5f2a32e1ba3edcb587f26d</td></tr><tr><td>AMM Contract</td><td>0xba153169476e8c3114962261d1edc70de5ad9781b83cc617ecc8c1923191cae0</td></tr></tbody></table>

{% endtab %}

{% tab title="Testnet" %}

<table><thead><tr><th width="152">Contract</th><th>PackageId</th></tr></thead><tbody><tr><td>CLMM Contract</td><td>0x40aa5119ae0633e7ba3c80fe4fd3d9b5277300dead42f6f9e565e7dd589cf6cb</td></tr><tr><td>AMM Contract</td><td>0xebebb67fc6fc6a74be5e57d90563c709631b4da86091c0926db81894add36ed3</td></tr></tbody></table>
{% endtab %}
{% endtabs %}


# FlowX SDK

An FlowX Typescript SDK is a software development kit that allows developers to interact with FlowX protocols using the Typescript programming language.

## Features

* Retrieve coin (include price, fee of any coin in Sui)
* Retrieve transaction block for Swap Aggregator
* Liquidity management AMM
* Liquidity management CLMM
* Auto Invest
* Limit Order

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


# Getting Started

## **NPM or Yarn install**

```
npm i @flowx-finance/sdk
yarn add @flowx-finance/sdk
```

## Network explaination

In each instance of the class, a `network` is required, which includes two types of networks: `mainnet` and `testnet`. Currently, FlowX doesn't support `devnet`, but you can easily modify the configuration to support your contract.


# Retrieve coin

### Example Code

```typescript
const coins = await coinProvider.getCoins({
  coinTypes: ['0x2::sui::SUI'],
});
```

### Example Response

It will return `Coin[]` instances, with `Coin`intance you can do a lot of thing not just JSON

#### Key Properties:

1. **coinType**: Identifies the coin type.
2. **decimals**: The number of decimal places (e.g., 18 decimals for Ether).
3. **symbol, name, description, iconUrl**: Optional information about the coin, like its name, symbol, description, and an icon URL.
4. **derivedPriceInUSD, derivedSUI**: Optional values for the coin’s price in USD or SUI.
5. **isVerified**: Marks if the coin is verified.

#### Main Methods:

1. **`sortsBefore`**: Compares this coin with another to see which comes first in a sorted list.
2. **`wrapped`**: Returns the coin itself (currently does nothing extra).
3. **`equals`**: Checks if this coin is the same as another by comparing their `coinType`.
4. **`fetchAllOwnedCoins`**: Retrieves all the coins owned by an address.
5. **`take`**: Transfers a specified amount of coins to a transaction, making sure the balance is enough and handling the SUI-specific coins appropriately.

####


# Swap Aggregator

### Get Swap Router

WARNING: `amountOut` FROM QUOTE WHEN USE WITH COMMISSION ONLY FOR DISPLAY, NOT FOR CALCULATE ONCHAIN.

To find best route for swap

```javascript
const quoter = new AggregatorQuoter('mainnet');
const params: SingleQuoteQueryParams = {
  tokenIn: '0x2::sui::SUI',
  tokenOut: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN',
  amountIn: '1000000000',
  includeSources: null, //optional
  excludeSources: null, //optional
  commission: null, //optional, and will be explain later
  maxHops: null, //optional: default and max is 3
  splitDistributionPercent: null, //optional: default 1 and max 100
  excludePools: null, //optional: list pool you want excude example: 0xpool1,0xpool2 
};

const routes = await quoter.getRoutes(params);
```

### Build Transaction for aggregator swap

#### Normal case if you want fast swap

```javascript
const tradeBuilder = new TradeBuilder(NETWORK.MAINNET, routes); //routes get from quoter
const tx = tradeBuilder
  .sender('0xSenderAddress') //Optional if you want pass coin later
  .slippage((1 / 100) * 1e6) // Slippage 1%
  .commission(null) // Optional: commission will be explain later
  .build()
  .buildTransaction({ client });
```

#### Return coin for later use

```javascript
const tradeBuilder = new TradeBuilder(NETWORK.MAINNET, routes); //routes get from quoter
const tx = new Transaction();
const trade = tradeBuilder
  .sender('0xSenderAddress') //Optional if you want pass coin later
  .slippage((1 / 100) * 1e6) // Slippage 1%
  .commission(null) // Optional: commission will be explain later
  .build();
const coinOut = trade.swap({ client, tx }) 
```

#### Commission

The `Commission` class represents a commission configuration for transactions, defining the partner, commission type, and value. It includes methods for computing the commission amount based on the specified type.

```typescript
const commission = new Commission('0xPartnerAddress', new Coin('0x2::sui::SUI'), CommissionType.PERCENTAGE, '500', true);
```

if `CommissionType.PERCENTAGE` then `value` should be input `1/100 * 1e6` it is example of 1% if `CommissionType.FLAT` then `value` should be the amount of token you want to fee include decimals Then you should pass `commission` variable to both `tradeBuilder` and `getRoutes` for exact values

if `directTransfer`= `true` then commission will transfer directly to partner address, else you need go to contract and claim partner fee later

The `coin`pass in commission that mean coin you want collect fee in transaction, for example, if you pass SUI is coin collect fee, when you swap SUI -> USDC or USDC->SUI you will collect SUI is a fee, but if you swap FLX->USDC and USDC->FLX you receive nothing and coin is SUI, then you SHOULD NOT pass commission to TradeBuilder

**Usage**

If `const routes = await quoter.getRoutes(params)`include commssion then amount will return amount that include commission

if `trade = tradeBuilder.commission(commission)` then the transaction will include commission, if not pass commission in tradeBuilder then transaction will execute without commission


# Multiple Swap Aggregator

### Get Multiple Swap Router

To find best route for swap

```javascript
const quoter = new AggregatorQuoter('mainnet');
const singleQuoteQueryParams: SingleQuoteQueryParams = {
  tokenIn: '0x2::sui::SUI',
  tokenOut: '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN',
  amountIn: '1000000000',
  includeSources: null, //optional
  excludeSources: null, //optional
  commission: null, //optional, and will be explain later
  maxHops: null, //optional: default and max is 3
  splitDistributionPercent: null, //optional: default 1 and max 100
  excludePools: null, //optional: list pool you want excude example: 0xpool1,0xpool2 
};

const multipleQuoteQueryParams: SingleQuoteQueryParams[] = [singleQuoteQueryParams, singleQuoteQueryParams2]

const routes = await quoter.getMultipleRoutes(multipleQuoteQueryParams);
```

{% hint style="info" %}
**Only support maximum 5 coin**
{% endhint %}

### Build Transaction for multiple aggregator swap

#### Normal case if you want fast swap

```javascript
const tradeBuilder = MultiTradesBuilder.fromRoutesGroups(
  routes.map((r) => r.routes)
);

const tx = tradeBuilder
  .sender('0xSenderAddress') //Optional if you want pass coin later
  .slippage((1 / 100) * 1e6) // Slippage 1%
  .commission(null) // Optional: commission will be explain later
  .build()
  .buildTransaction({ client });
```

#### Return coin for later use

```javascript
const tradeBuilder = MultiTradesBuilder.fromRoutesGroups(
  routes.map((r) => r.routes)
);
const tx = new Transaction();
const trade = tradeBuilder
  .sender('0xSenderAddress') //Optional if you want pass coin later
  .slippage((1 / 100) * 1e6) // Slippage 1%
  .commission(null) // Optional: commission will be explain later
  .build();
const coinOut = trade.swap({ client, tx }) 
```

#### Commission

[Swap Aggregator](/developer/flowx-sdk/swap-aggregator#commission)


# AMM Management

### Get pool detail

```typescript
    const poolManager = new AmmPoolManager('mainnet');

    const params = {
      coinX: new Coin('0x2::sui::SUI'),
      coinY: new Coin(
        '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN'
      ),
    };
    const pool = await poolManager.getPool(params);

```

### Get multiple pool

```typescript
  const poolManager = new AmmPoolManager('mainnet');

    const params = [
      {
        coinX: new Coin('0x2::sui::SUI'),
        coinY: new Coin(
          '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN'
        ),
      },
      {
        coinX: new Coin(
          '0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH'
        ),
        coinY: new Coin(
          '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC'
        ),
      },
      {
        coinX: new Coin(
          '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN'
        ),
        coinY: new Coin(
          '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN'
        ),
      },
    ];

    const pools = await poolManager.multiGetPools(params);

```

### Get all pools

```typescript
 const poolManager = new AmmPoolManager('mainnet');
 const pools = await poolManager.getPools();
```


# Pool Management

### Get pool detail

```typescript
    const poolManager = new AmmPoolManager('mainnet');

    const params = {
      coinX: new Coin('0x2::sui::SUI'),
      coinY: new Coin(
        '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN'
      ),
    };
    const pool = await poolManager.getPool(params);

```

### Get multiple pool

```typescript
  const poolManager = new AmmPoolManager('mainnet');

    const params = [
      {
        coinX: new Coin('0x2::sui::SUI'),
        coinY: new Coin(
          '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN'
        ),
      },
      {
        coinX: new Coin(
          '0xd0e89b2af5e4910726fbcd8b8dd37bb79b29e5f83f7491bca830e94f7f226d29::eth::ETH'
        ),
        coinY: new Coin(
          '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC'
        ),
      },
      {
        coinX: new Coin(
          '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN'
        ),
        coinY: new Coin(
          '0xc060006111016b8a020ad5b33834984a437aaa7d3c74c18e09a95d48aceab08c::coin::COIN'
        ),
      },
    ];

    const pools = await poolManager.multiGetPools(params);

```

### Get all pools

```typescript
 const poolManager = new AmmPoolManager('mainnet');
 const pools = await poolManager.getPools();
```


# Position Management

### Get user position detail

```typescript
const positionManager = new AmmPositionManager('mainnet');
const positions = await positionManager.getUserPositions('userAddress');
```

### Create Position

```typescript
const pool = new AmmPool({
      objectId: '',
      coins: [
        new Coin(
          '0xd1b72982e40348d069bb1ff701e634c117bb5f741f44dff91e472d3b01461e55::stsui::STSUI'
        ),
        new Coin(
          '0xdeeb7a4662eec9f2f3def03fb937a663dddaa2e215b8078a284d026b7946c270::deep::DEEP'
        ),
      ],
      reserves: [0, 0],
      feeRate: 0,
      liquiditySupply: 0,
      kLast: 0,
    });

    const position = Position.fromAmounts({
      owner:
        '0xUserAddress',
      pool: pool,
      amountX: 0,
      amountY: 0,
    });

    const mintAmounts = position.mintAmountsWithSlippage(new Percent(0.0001));
```

### Increase Position

```typescript
const poolManager = new AmmPoolManager('mainnet');

    const pool = await poolManager.getPool({
      coinX: new Coin('0x2::sui::SUI'),
      coinY: new Coin(
        '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC'
      ),
    });

    const position = Position.fromAmounts({
      owner:
        '0xUserAddrexx',
      pool: pool,
      amountX: 1e9,
      amountY: 1e5,
    });

    const mintAmounts = position.mintAmountsWithSlippage(new Percent(0.0001));
```


# CLMM Management


# Pool Management

## Get all pool

```typescript
const poolManager = new ClmmPoolManager('mainnet');
const pools = await poolManager.getPools();
```

## Get specific pool

```typescript
const pool = await clmmPoolManager.getPoolDetail(poolId);
```

## Create Pool

<pre class="language-typescript"><code class="lang-typescript">const coinX = new Coin(TEST_SUI_COIN);
const coinY = new Coin(TEST_USDC_COIN);
const TEST_SQRT_PRICE_X64 = '18446744073709551616'; // Price = 1.0
const pool = new ClmmPool(
  "",
  [coinX, coinY],
  [],
  [0, 0],
  FeeAmount.MEDIUM,
  TEST_SQRT_PRICE_X64,
  0,
  0,
  0,
  0,
);

// Act
const tx = new Transaction();
<strong>await cmmPoolManager.tx(tx).createPoolV2(pool);
</strong></code></pre>


# Position Management

## Get user positions

<pre class="language-typescript"><code class="lang-typescript"><strong>const positions: ClmmPosition[] = positionManager.getUserPositions('0xaddress');
</strong></code></pre>

## Get position reward

```typescript
const positions: ClmmPosition[] = positionManager.getUserPositions('0xaddress');
const positionWithReward: ClmmPosition[] = positionManager.getPositionReward(positions);
```

## Open/Increase a Position

```typescript
import { ClmmPosition, CoinAmount, Percent, BN } from '@flowx-finance/sdk';
import { TransactionResult } from '@mysten/sui/transactions';


// Method 1: Create position with specific liquidity amount
const tickLower = -3000; // Lower price tick (must be divisible by tick spacing: 60 for MEDIUM fee)
const tickUpper = 3000; // Upper price tick (must be divisible by tick spacing: 60 for MEDIUM fee)
const liquidity = new BN(1000);

const position = new ClmmPosition({
  objectId: '0x...', // Optional: Your position object id if you want increase exist position
  owner: '0x...', // Your address
  pool: pool,
  tickLower,
  tickUpper,
  liquidity,
  coinsOwedX: 0,
  coinsOwedY: 0,
  feeGrowthInsideXLast: 0,
  feeGrowthInsideYLast: 0,
  rewardInfos: [],
});

// Method 2: Create position with specific token amounts
const amountX = new BN('1000000000'); // 1 SUI (9 decimals)
const amountY = new BN('1000000'); // 1 USDC (6 decimals)

const positionFromAmounts = ClmmPosition.fromAmounts({
  objectId: '0x...', // Optional: Your position object id if you want increase exist position
  owner: '0x...', // Your address
  pool: pool,
  tickLower: -3000,
  tickUpper: 3000,
  amountX: amountX,
  amountY: amountY,
  useFullPrecision: true, // Use full precision for liquidity calculation
});

// Method 3: Create position with only amountX (single-sided liquidity)
const positionOnlyX = ClmmPosition.fromAmountX({
  objectId: '0x...', // Optional: Your position object id if you want increase exist position
  owner: '0x...', // Your address
  pool: pool,
  tickLower: -3000,
  tickUpper: 3000,
  amountX: amountX, // Only provide amountX
  // amountY not provided - will be calculated based on current price
  useFullPrecision: true,
});

// Method 4: Create position with only amountY (single-sided liquidity)
const positionOnlyY = ClmmPosition.fromAmountY({
  objectId: '0x...', // Optional: Your position object id if you want increase exist position
  owner: '0x...', // Your address
  pool: pool,
  tickLower: -3000,
  tickUpper: 3000,
  amountY: amountY, // Only provide amountY
  // amountX not provided - will be calculated based on current price
  useFullPrecision: true,
});

// Create position with liquidity

const options = {
  slippageTolerance: new Percent(1, 100), // 1% slippage
  deadline: Date.now() + 3600 * 1000, // 1 hour from now
  createPosition: true,
};
const tx = new Transaction();
const createdPosition = positionManager.tx(tx).increaseLiquidity(position, options);
tx.transferObjects([createdPosition], recipient);
```

## Decrease Liquidity

<pre class="language-typescript"><code class="lang-typescript">
// Define MaxU64 constant for convenience
const MaxU64 = new BN('18446744073709551615');

<strong>// Example 1: Remove 50% of liquidity
</strong>const positionId = '0x...'; // Position object ID
const position = await positionManager.getPosition(positionId);
const liquidityToRemove = position.liquidity.div(new BN(2));

const positionWillBeDecreased = new ClmmPosition({
  owner: position.owner,
  pool: position.pool,
  tickLower: position.tickLower,
  tickUpper: position.tickUpper,
  liquidity: liquidityToRemove,
  coinsOwedX: 0,
  coinsOwedY: 0,
  feeGrowthInsideXLast: 0,
  feeGrowthInsideYLast: 0,
  rewardInfos: [],
});

const burnAmounts = {
  amountX: positionWillBeDecreased.amountX,
  amountY: positionWillBeDecreased.amountY,
};

const decreaseOptions = {
  slippageTolerance: new Percent(1, 100),
  deadline: Date.now() + 3600 * 1000, // 1 hour from now
  collectOptions: {
    expectedCoinOwedX: CoinAmount.fromRawAmount(coinX, burnAmounts.amountX),
    expectedCoinOwedY: CoinAmount.fromRawAmount(coinY, burnAmounts.amountY),
  },
};

const tx = new Transaction();
positionManager.tx(tx).decreaseLiquidity(position, decreaseOptions);

// Example 2: Remove all liquidity and close position
const positionToClose = await positionManager.getPosition(positionId);

const closeOptions = {
  slippageTolerance: new Percent(1, 100),
  deadline: Date.now() + 3600 * 1000, // 1 hour from now
  collectOptions: {
    // Use MaxU64 to ensure we collect all available fees regardless of fee growth during processing
    expectedCoinOwedX: CoinAmount.fromRawAmount(coinX, MaxU64),
    expectedCoinOwedY: CoinAmount.fromRawAmount(coinY, MaxU64),
  },
};

const closeTx = new Transaction();
positionManager.tx(closeTx).decreaseLiquidity(positionToClose, closeOptions);

// Get all available rewards before closing
const rewards = await positionToClose.getRewards();

// Collect all available rewards
for (let i = 0; i &#x3C; rewards.length; i++) {
  if (rewards[i].gt(new BN(0))) {
    const collectRewardOptions = {
      expectedRewardOwed: CoinAmount.fromRawAmount(
        positionToClose.pool.poolRewards[i].coin,
        MaxU64 // Use MaxU64 for rewards as well
      ),
      recipient: '0x...', // Optional recipient
    };

    positionManager.collectPoolReward(positionToClose, i, collectRewardOptions);
  }
}

// Close the position (burn the NFT)
positionManager.closePosition(positionToClose, closeTx);
</code></pre>

## Collecting Fees and Rewards

```typescript

// Define MaxU64 constant for convenience
const MaxU64 = new BN('18446744073709551615');

// Example 1: Collect accumulated fees only
const positionId = '0x...'; // Position object ID
const position = await positionManager.getPosition(positionId);

// Get current fees
const fees = await position.getFees();

if (fees.amountX.gt(new BN(0)) || fees.amountY.gt(new BN(0))) {
  const collectFeeOptions = {
    expectedCoinOwedX: CoinAmount.fromRawAmount(coinX, MaxU64),
    expectedCoinOwedY: CoinAmount.fromRawAmount(coinY, MaxU64),
    recipient: '0x...', // Optional recipient
  };

  const tx = new Transaction();
  positionManager.tx(tx);

  // Collect returns the collected coin objects
  const [collectedX, collectedY] = positionManager.collect(position, collectFeeOptions) as TransactionResult;

  // Transfer to recipient if not specified in collectFeeOptions
  if (!collectFeeOptions.recipient) {
    tx.transferObjects([collectedX, collectedY], position.owner);
  }
}

// Example 2: Collect specific reward tokens
const rewards = await position.getRewards();

for (let i = 0; i < rewards.length; i++) {
  if (rewards[i].gt(new BN(0))) {
    const collectRewardOptions = {
      expectedRewardOwed: CoinAmount.fromRawAmount(position.pool.poolRewards[i].coin, MaxU64),
      recipient: '0x...', // Optional recipient
    };

    const tx = new Transaction();
    positionManager.tx(tx);
    positionManager.collectPoolReward(position, i, collectRewardOptions);
  }
}
```

## Rebalance example

```typescript
const tx = new Transaction();
const rebalancer = new Rebalancer({
  network: "mainnet",
});
const newPosition = await rebalancer.rebalance(
  clmmPosition,
  tickLower,
  tickUpper,
  {
    slippageTolerance: 1000,
    priceImpactPercentThreshold: -5000,
    minZapAmounts: {
      amountX: 1000,
      amountY: 1000,
    },
  },
)(tx);
tx.transferObjects([newPosition], position.owner);

```


# Auto Invest

## Create Plan

```typescript
// Initialize a new transaction instance to manage the on-chain operations.
const tx = new Transaction();

// Create an AutoInvest instance for the "mainnet" network to automate the investment process.
const autoInvest = new AutoInvest("mainnet");

// Instantiate a PlanBuilder to configure the details of the investment plan.
const planBuilder = new PlanBuilder();

// Create a Coin instance representing the token to be sold in the investment process.
const sellCoin = new Coin("0TokenSell");

// Associate the transaction instance with the AutoInvest instance to track operations.
autoInvest.tx(tx);

// Perform a deposit of the specified token using the `AutoInvest` instance.
// - `type`: Specifies the token type being sold.
// - `object`: Represents the token amount to be deposited using the `sellCoin.take()` function.
// - `owner`: Your account address ('0xAddress').
// - `amount`: The amount of tokens to deposit, specified as a string (e.g., 1000000000000).
// - `client`: The provider instance responsible for blockchain interaction.
// - `tx`: The initialized transaction object to include the deposit action.
autoInvest.deposit({
  type: tokenSell.type,
  object: await sellCoin.take({
    owner: '0xAddress', // Replace with your actual account address
    amount: '1000000000000', // Token amount in smallest units
    client: provider as any,
    tx,
  }),
});

// Determine the plan's start time based on the `instantStart` flag.
// - If `instantStart` is true, the plan starts immediately (`undefined`).
// - Otherwise, a custom start date (`customDate`) is used. Milisecond, example: new Date().getTime() 
const startTime = instantStart ? undefined : customDate;

// Build the investment plan using the PlanBuilder instance by setting various parameters:
// - `setReceiver`: Specifies the wallet address to receive the invested tokens.
// - `setSubscriptionStartTime`: Defines when the subscription will start.
// - `setOwner`: Sets the account that owns the investment plan.
// - `setSubscriptionAmount`: Calculates the per-cycle investment amount using the `BigNumberInstance`.
// - `setSubscriptionCycle`: Defines the cycle frequency using the mapped time unit ["HOUR, DAY, WEEK"] and frequency value.
// - `setExecutionLimit`: Limits the number of investment cycles to the specified `repeat` value.
// - `setSourceAsset`: Specifies the asset being sold, normalized using `normalizeStructTag`.
// - `setTargetAsset`: Specifies the asset being purchased, normalized using `normalizeStructTag`.
// - `build()`: Finalizes the plan configuration.
const plan = planBuilder
  .setReceiver("0xAddress")
  .setSubscriptionStartTime(startTime)
  .setOwner("0xAddess")
  .setSubscriptionAmount(
    BigNumberInstance('1000000000000').div(repeat).toFixed(0)
  )
  .setSubscriptionCycle("DAY", 10) //for example execute for each 10 days
  .setExecutionLimit(10) //number order you want to buy, for example with this setup, you need 100 days to execute order.
  .setSourceAsset(normalizeStructTag(tokenSell.type))
  .setTargetAsset(normalizeStructTag(tokenBuy.type))
  .build();


autoInvest.createPlan(plan);
```

## Remove or cancle plan

```typescript
const tx = new Transaction();
autoInvest.tx(tx);
autoInvest.removePlan({ planId });
```


# Limit Order

## Create Limit&#x20;

```typescript
    const coinMaker = new Coin('0x2::sui::SUI');
    const coinTaker = new Coin(
      '0xea10912247c015ead590e481ae8545ff1518492dee41d6d03abdad828c1d2bde::usdc::USDC'
    );
    const sender = '0xAddress';
    const makingAmount = 0.001 * 1e9;
    const takingAmount = 1 * 1e6;

    const txb = await LimitOrderBuilder.createInstance<
      LimitOrderBuilder<Coin, Coin>
    >('mainnet')
      .coinMaker(coinMaker)
      .coinTaker(coinTaker)
      .suiClient(client)
      .sender(sender);
    await txb.placeOrder({
      amountIn: new BN(makingAmount),
      amountOutExpected: new BN(takingAmount),
      expiredTimestamp: 0,
    });
```

## Cancel Limit Order

```typescript
     const coinMaker = new Coin('0x2::sui::SUI');
    const coinTaker = new Coin(
      '0xea10912247c015ead590e481ae8545ff1518492dee41d6d03abdad828c1d2bde::usdc::USDC'
    );
    const sender = '0xAddress';

    const txb = await LimitOrderBuilder.createInstance<
      LimitOrderBuilder<Coin, Coin>
    >('mainnet')
      .coinMaker(coinMaker)
      .coinTaker(coinTaker);

    await txb.cancelOrder({
      orderId: 1, //orderId
    });
```


# FlowX Widget

### Overview

FlowX Finance Widget is a customizable financial tool designed for the Sui blockchain ecosystem. It provides best rate swap for user.

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

### Live Example

Here's a more comprehensive example of how to integrate the FlowX Finance Widget into a web application:

* [Flowx Finance](https://flowx.finance/)
* [Birdeye](https://birdeye.so/token/0x2::sui::SUI?chain=sui)
* ...

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

### Key Features

* **Swap Aggregator Service**: Our advanced algorithm finds the best swap routes across multiple DEXes to ensure optimal trading outcomes.
* Partner fee customization
* Style customization

### Installation

```typescript
npm install @flowx-finance/swap-widget
```

### Usage

```typescript
import { SwapWidget } from '@flowx-finance/swap-widget';
import "@mysten/dapp-kit/dist/index.css";
import "@flowx-finance/swap-widget/index.esm.css";

const config: IConfig = {};

 <SwapWidget config={config} />
```

### Customization

#### Partner fee customize

We support 3 type of partner fee

* Collect input as a fee
* Collect output as a fee
* Collect only specific tokens as a fee

```typescript
const config = {
    commission: {
        partner: '0xWALLET_ADDRESS', //wallet that you want collect fee
        valueType: CommissionType.PERCENTAGE, //Type of fee, now support percentage and specific amount
        value: (1 / 100) * 1e6, // Fee collect, in this case 1%
        strategy: 'TOKEN', // Collect fee by specific token, current support 'INPUT' | 'OUTPUT' | 'TOKEN'
        listCoins: [
          '0x2::sui::SUI',
          '0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN', //If you chose TOKEN you must specific list tokens want to collect fee
        ],
        directTransfer: true, //We have 2 strategy transfer, direct to your address, store in the contract and collect later
      }
    }
```

#### Customize default token

Change default pair for swap

```typescript
const config = {
    defaultPair: ["0x6dae8ca14311574fdfe555524ea48558e3d1360d1607d1c7f98af867e3b7976c::flx::FLX", "0x2::sui::SUI"]
}
```

#### Token list

Default token list

```typescript
const config = {
    customList: ["0x6dae8ca14311574fdfe555524ea48558e3d1360d1607d1c7f98af867e3b7976c::flx::FLX", "0x2::sui::SUI", "0x5d4b302506645c37ff133b98c4b50a5ae14841659738d6d733d59d0d217a93bf::coin::COIN"] // In this case, only SUI, FLX, USDC show on the token selection
}
```

#### Explorer customize

Currently we support SuiVision and SuiScan for Explorer

```typescript
const config = {
    suiExplorer: 'SUI_VISION', //Value: 'SUI_VISION'| 'SUI_SCAN';
}
```

<br>


# FlowX CLMM Guideline

A concentrated liquidity market maker (CLMM) protocol built on the Sui blockchain, inspired by Uniswap v3. FlowX CLMM allows liquidity providers to concentrate their capital within custom price ranges

### 📖 Overview

FlowX CLMM implements a concentrated liquidity model with the following core features:

#### 🎯 Key Features

| Feature                    | Description                                      |
| -------------------------- | ------------------------------------------------ |
| **Concentrated Liquidity** | Capital efficiency through custom price ranges   |
| **Multiple Fee Tiers**     | Flexible fee structures (0.01%, 0.05%, 0.3%, 1%) |
| **Position Management**    | NFT-based position tracking and management       |
| **Protocol Rewards**       | Built-in reward distribution system              |
| **Oracle Integration**     | Price feeds and historical data tracking         |
| **Modular Architecture**   | Clean separation with versioning support         |

#### 💰 Benefits

* **For Liquidity Providers**: Higher capital efficiency and customizable risk exposure
* **For Traders**: Lower slippage and better price discovery
* **For Developers**: Modular design for easy integration and extension

#### 🏗️ Architecture

**Core Modules**

**🏦 Pool Manager (`pool_manager.move`)**

Central registry for all pools in the protocol.

* Pool creation and registration
* Fee tier management
* Administrative functions
* Protocol fee collection

**🌊 Pool (`pool.move`)**

Individual pool implementation containing the core AMM logic.

* Liquidity management
* Swap execution
* Tick state management
* Oracle data collection
* Reward distribution

**📊 Position Manager (`position_manager.move`)**

Manages the lifecycle of liquidity positions.

* Position creation and closure
* Liquidity adjustments
* Fee collection
* Reward claiming

**🔄 Swap Router (`swap_router.move`)**

Handles swap execution with various input/output specifications.

* Exact input/output swaps
* Price limit enforcement
* Slippage protection

### 🔧 Core Functions

#### 🏊 Pool Management

<details>

<summary><strong>create_pool_v2</strong> - Create a new liquidity pool</summary>

Creates a new liquidity pool for token pair X/Y with specified fee rate.

```move
public fun create_pool_v2<X, Y>(
    self: &mut PoolRegistry,
    fee_rate: u64,
    metadata_x: &CoinMetadata<X>,
    metadata_y: &CoinMetadata<Y>,
    versioned: &Versioned,
    ctx: &mut TxContext
)
```

**Parameters:**

* `fee_rate`: Fee rate in basis points (e.g., 3000 = 0.3%)
* `metadata_x/y`: Coin metadata for validation
* `versioned`: Package version validation

**Example:**

```move
// Create a new USDC/SUI pool with 0.3% fee
// Note: Fee rate must be enabled first via enable_fee_rate_for_testing in tests
pool_manager::create_pool_v2<USDC, SUI>(
    &mut pool_registry,
    3000, // 0.3% fee tier
    &usdc_metadata,
    &sui_metadata,
    &versioned,
    ctx
);
```

</details>

<details>

<summary><strong>create_and_initialize_pool_v2</strong> - Create and initialize pool with price</summary>

Creates and initializes a new pool in a single transaction with an initial price.

```move
public fun create_and_initialize_pool_v2<X, Y>(
    self: &mut PoolRegistry,
    fee_rate: u64,
    sqrt_price: u128,
    metadata_x: &CoinMetadata<X>,
    metadata_y: &CoinMetadata<Y>,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
)
```

**Parameters:**

* `sqrt_price`: Initial square root price as Q64.64 fixed-point number
* Additional parameters same as `create_pool_v2`

**Example:**

```move
// Create and initialize USDC/SUI pool with initial price of 1 USDC = 2 SUI
// sqrt_price = sqrt(0.5) * 2^64 for price of 0.5 USDC per SUI
let initial_sqrt_price = 13043817825332782212; // sqrt(0.5) in Q64.64 format

pool_manager::create_and_initialize_pool_v2<USDC, SUI>(
    &mut pool_registry,
    3000, // 0.3% fee tier
    initial_sqrt_price,
    &usdc_metadata,
    &sui_metadata,
    &versioned,
    &clock,
    ctx
);
```

</details>

#### 📍 Position Management

<details>

<summary><strong>open_position</strong> - Open a new liquidity position</summary>

Opens a new liquidity position within specified tick range.

```move
public fun open_position<X, Y>(
    self: &mut PositionRegistry,
    pool_registry: &PoolRegistry,
    fee_rate: u64,
    tick_lower_index: I32,
    tick_upper_index: I32,
    versioned: &Versioned,
    ctx: &mut TxContext
): Position
```

**Example:**

```move
let position = position_manager::open_position<USDC, SUI>(
    &mut position_registry,
    &pool_registry,
    3000, // 0.3% fee
    tick_lower,
    tick_upper,
    &versioned,
    ctx
);
```

**Complete Liquidity Provider Workflow Example:**

```move
// 1. Calculate tick range for price range $1.80 - $2.20 per SUI
// Assuming USDC has 6 decimals and SUI has 9 decimals
let lower_price = 1_800000; // $1.80 in USDC units (6 decimals)
let upper_price = 2_200000; // $2.20 in USDC units (6 decimals)

// Convert prices to sqrt prices (Q64.64 format)
let lower_sqrt_price = price_to_sqrt_price(lower_price, 6, 9);
let upper_sqrt_price = price_to_sqrt_price(upper_price, 6, 9);

// Convert sqrt prices to ticks
let tick_lower = tick_math::get_tick_at_sqrt_price(lower_sqrt_price);
let tick_upper = tick_math::get_tick_at_sqrt_price(upper_sqrt_price);

// 2. Open position in the calculated range
let position = position_manager::open_position<USDC, SUI>(
    &mut position_registry,
    &pool_registry,
    3000, // 0.3% fee tier
    tick_lower,
    tick_upper,
    &versioned,
    ctx
);
```

**Parameters:**

* `self`: Mutable reference to the position registry
* `pool_registry`: Reference to the pool registry for validation
* `fee_rate`: Pool fee rate in basis points (e.g., 3000 = 0.3%)
* `tick_lower_index`: Lower bound of the price range as tick index
* `tick_upper_index`: Upper bound of the price range as tick index
* `versioned`: Reference for package version validation
* `ctx`: Transaction context

**Returns:**

* `Position`: New position NFT for tracking and management

</details>

<details>

<summary><strong>increase_liquidity</strong> - Add liquidity to position</summary>

Adds liquidity to an existing position with slippage protection.

```move
public fun increase_liquidity<X, Y>(
    self: &mut PoolRegistry,
    position: &mut Position,
    x_in: Coin<X>,
    y_in: Coin<Y>,
    amount_x_min: u64,
    amount_y_min: u64,
    deadline: u64,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
)
```

**Parameters:**

* `self`: Mutable reference to the pool registry
* `position`: Mutable reference to the position to add liquidity to
* `x_in`: Coin of token X to add as liquidity
* `y_in`: Coin of token Y to add as liquidity
* `amount_x_min`: Minimum amount of X tokens to add (slippage protection)
* `amount_y_min`: Minimum amount of Y tokens to add (slippage protection)
* `deadline`: Transaction deadline timestamp to prevent stale transactions
* `versioned`: Reference for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* Excess tokens are automatically refunded to the caller

**Example:**

```move
// Add 1000 USDC and 2000 SUI to position with slippage protection
let usdc_coins = coin::mint_for_testing<USDC>(1000_000000, ctx); // 1000 USDC (6 decimals)
let sui_coins = coin::mint_for_testing<SUI>(2000_000000000, ctx); // 2000 SUI (9 decimals)
let deadline = clock::timestamp_ms(&clock) + 300_000; // 5 minutes from now

position_manager::increase_liquidity<USDC, SUI>(
    &mut pool_registry,
    &mut position,
    usdc_coins,
    sui_coins,
    950_000000,  // Min 950 USDC (5% slippage tolerance)
    1900_000000000, // Min 1900 SUI (5% slippage tolerance)
    deadline,
    &versioned,
    &clock,
    ctx
);
```

</details>

<details>

<summary><strong>decrease_liquidity</strong> - Remove liquidity from position</summary>

Removes liquidity from a position and returns tokens.

```move
public fun decrease_liquidity<X, Y>(
    self: &mut PoolRegistry,
    position: &mut Position,
    liquidity: u128,
    amount_x_min: u64,
    amount_y_min: u64,
    deadline: u64,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
)
```

**Parameters:**

* `self`: Mutable reference to the pool registry
* `position`: Mutable reference to the position to remove liquidity from
* `liquidity`: Amount of liquidity to remove (in liquidity units)
* `amount_x_min`: Minimum amount of X tokens to receive (slippage protection)
* `amount_y_min`: Minimum amount of Y tokens to receive (slippage protection)
* `deadline`: Transaction deadline timestamp to prevent stale transactions
* `versioned`: Reference for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* Token balances proportional to the liquidity removed

**Example:**

```move
// Remove 50% of position liquidity
let current_liquidity = position::liquidity(&position);
let liquidity_to_remove = current_liquidity / 2;
let deadline = clock::timestamp_ms(&clock) + 300_000; // 5 minutes from now

position_manager::decrease_liquidity<USDC, SUI>(
    &mut pool_registry,
    &mut position,
    liquidity_to_remove,
    100_000000,   // Min 100 USDC expected
    200_000000000, // Min 200 SUI expected
    deadline,
    &versioned,
    &clock,
    ctx
);
```

</details>

#### 💰 Fee & Reward Collection

<details>

<summary><strong>collect</strong> - Collect accumulated fees</summary>

Collects accumulated trading fees from a position.

```move
public fun collect<X, Y>(
    self: &mut PoolRegistry,
    position: &mut Position,
    amount_x_requested: u64,
    amount_y_requested: u64,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): (Coin<X>, Coin<Y>)
```

**Parameters:**

* `self`: Mutable reference to the pool registry
* `position`: Mutable reference to the position to collect fees from
* `amount_x_requested`: Maximum amount of X token fees to collect
* `amount_y_requested`: Maximum amount of Y token fees to collect
* `versioned`: Reference for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `(Coin<X>, Coin<Y>)`: Tuple of collected fee coins for both tokens

**Example:**

```move
// Collect all accumulated trading fees from position
let (usdc_fees, sui_fees) = position_manager::collect<USDC, SUI>(
    &mut pool_registry,
    &mut position,
    18446744073709551615, // Max u64 to collect all USDC fees
    18446744073709551615, // Max u64 to collect all SUI fees
    &versioned,
    &clock,
    ctx
);

// Use collected fees
let usdc_fee_amount = coin::value(&usdc_fees);
let sui_fee_amount = coin::value(&sui_fees);
// Transfer to treasury or reinvest
```

</details>

<details>

<summary><strong>collect_pool_reward</strong> - Collect reward tokens</summary>

Collects accumulated reward tokens for a position.

```move
public fun collect_pool_reward<X, Y, RewardCoinType>(
    self: &mut PoolRegistry,
    position: &mut Position,
    amount_requested: u64,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): Coin<RewardCoinType>
```

**Parameters:**

* `self`: Mutable reference to the pool registry
* `position`: Mutable reference to the position to collect rewards from
* `amount_requested`: Maximum amount of reward tokens to collect
* `versioned`: Reference for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Type Parameters:**

* `X`: First token type of the pool
* `Y`: Second token type of the pool
* `RewardCoinType`: Type of the reward token to collect

**Returns:**

* `Coin<RewardCoinType>`: Collected reward tokens of the specified type

**Example:**

```move
// Collect FLOW reward tokens from USDC/SUI position
let flow_rewards = position_manager::collect_pool_reward<USDC, SUI, FLOW>(
    &mut pool_registry,
    &mut position,
    18446744073709551615, // Max u64 to collect all available FLOW rewards
    &versioned,
    &clock,
    ctx
);

let reward_amount = coin::value(&flow_rewards);
// Transfer rewards to user wallet
transfer::public_transfer(flow_rewards, tx_context::sender(ctx));
```

</details>

#### 🔄 Swap Functions

<details>

<summary><strong>Exact Input Swaps</strong> - Swap exact amount in for maximum out</summary>

```move
// Swap exact X for maximum Y
public fun swap_exact_x_to_y<X, Y>(
    pool: &mut Pool<X, Y>,
    coin_in: Coin<X>,
    sqrt_price_limit: u128,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &TxContext
): Balance<Y>

// Swap exact Y for maximum X
public fun swap_exact_y_to_x<X, Y>(
    pool: &mut Pool<X, Y>,
    coin_in: Coin<Y>,
    sqrt_price_limit: u128,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &TxContext
): Balance<X>
```

**Parameters:**

* `pool`: Mutable reference to the pool to execute swap in
* `coin_in`: Input tokens to swap (entire amount will be consumed)
* `sqrt_price_limit`: Price limit for slippage protection:
  * For X→Y swaps: Maximum acceptable sqrt price after swap (price decreasing)
  * For Y→X swaps: Minimum acceptable sqrt price after swap (price increasing)
* `versioned`: Reference for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `Balance<Y>` or `Balance<X>`: Output token balance from the swap

**Use Case:** When you want to swap all of a token

**Example:**

```move
// Swap 1000 USDC for maximum SUI possible
let usdc_in = coin::mint_for_testing<USDC>(1000_000000, ctx); // 1000 USDC
let current_sqrt_price = pool::sqrt_price_current(&pool);
let min_sqrt_price = (current_sqrt_price * 95) / 100; // 5% slippage tolerance

let sui_out = swap_router::swap_exact_x_to_y<USDC, SUI>(
    &mut pool,
    usdc_in,
    min_sqrt_price,
    &versioned,
    &clock,
    ctx
);

let sui_amount_received = balance::value(&sui_out);
// Convert balance to coin if needed
let sui_coin = coin::from_balance(sui_out, ctx);
```

</details>

<details>

<summary><strong>Exact Output Swaps</strong> - Swap minimum in for exact amount out</summary>

```move
// Swap minimum X for exact Y
public fun swap_x_to_exact_y<X, Y>(
    pool: &mut Pool<X, Y>,
    coin_in: Coin<X>,
    amount_out: u64,
    sqrt_price_limit: u128,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &TxContext
): Balance<Y>

// Swap minimum Y for exact X
public fun swap_y_to_exact_x<X, Y>(
    pool: &mut Pool<X, Y>,
    coin_in: Coin<Y>,
    amount_out: u64,
    sqrt_price_limit: u128,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &TxContext
): Balance<X>
```

**Parameters:**

* `pool`: Mutable reference to the pool to execute swap in
* `coin_in`: Input tokens to swap (excess will be refunded)
* `amount_out`: Exact amount of output tokens to receive
* `sqrt_price_limit`: Price limit for slippage protection:
  * For X→Y swaps: Maximum acceptable sqrt price after swap
  * For Y→X swaps: Minimum acceptable sqrt price after swap
* `versioned`: Reference for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `Balance<Y>` or `Balance<X>`: Exact amount of output tokens requested

**Use Case:** When you need a precise output amount

**Example:**

```move
// Swap minimum USDC needed to get exactly 500 SUI
let usdc_in = coin::mint_for_testing<USDC>(2000_000000, ctx); // 2000 USDC (excess will be refunded)
let desired_sui_out = 500_000000000; // Exactly 500 SUI (9 decimals)
let current_sqrt_price = pool::sqrt_price_current(&pool);
let max_sqrt_price = (current_sqrt_price * 105) / 100; // 5% slippage tolerance

let sui_out = swap_router::swap_x_to_exact_y<USDC, SUI>(
    &mut pool,
    usdc_in, // Will be split internally, excess refunded
    desired_sui_out,
    max_sqrt_price,
    &versioned,
    &clock,
    ctx
);

// Verify exact amount received
assert!(balance::value(&sui_out) == desired_sui_out, 0);
let sui_coin = coin::from_balance(sui_out, ctx);
```

</details>

### 📋 API Reference

This section provides detailed parameter descriptions for all core functions.

#### Pool Management Functions

| Function                              | Purpose                                                            | Access Level |
| ------------------------------------- | ------------------------------------------------------------------ | ------------ |
| `create_pool_v2<X, Y>`                | Creates a new liquidity pool for token pair X/Y                    | Public       |
| `create_and_initialize_pool_v2<X, Y>` | Creates and initializes pool with initial price in one transaction | Public       |

**create\_pool\_v2\<X, Y>**

* **Purpose**: Creates a new liquidity pool for token pair X/Y
* **Fee Rate**: Must be previously enabled (e.g., 3000 for 0.3%)
* **Access**: Public - can be called by any user

**create\_and\_initialize\_pool\_v2\<X, Y>**

* **Purpose**: Creates and initializes pool with initial price in one transaction
* **Initial Price**: Specified as Q64.64 fixed-point sqrt price
* **Access**: Public - can be called by any user

#### Position Management Functions

| Function                                 | Purpose                                                  | Returns             |
| ---------------------------------------- | -------------------------------------------------------- | ------------------- |
| `open_position<X, Y>`                    | Opens new liquidity position within specified tick range | Position NFT        |
| `close_position`                         | Closes empty position and destroys NFT                   | None                |
| `increase_liquidity<X, Y>`               | Adds liquidity to existing position                      | Auto-refunds excess |
| `decrease_liquidity<X, Y>`               | Removes liquidity from position                          | Token balances      |
| `collect<X, Y>`                          | Collects accumulated trading fees from position          | Fee coins           |
| `collect_pool_reward<X, Y, RewardToken>` | Collects reward tokens earned by position                | Reward coins        |

**open\_position\<X, Y>**

* **Purpose**: Opens new liquidity position within specified tick range
* **Tick Range**: Must respect pool's tick spacing requirements
* **Returns**: Position NFT for tracking and management

**increase\_liquidity\<X, Y>**

* **Purpose**: Adds liquidity to existing position
* **Slippage Protection**: `amount_x_min` and `amount_y_min` parameters
* **Auto-refund**: Excess tokens automatically returned
* **Deadline**: Prevents execution of stale transactions

**decrease\_liquidity\<X, Y>**

* **Purpose**: Removes liquidity from position
* **Returns**: Token balances proportional to liquidity removed
* **Minimum Output**: Slippage protection via `amount_x_min`/`amount_y_min`

**collect\<X, Y>**

* **Purpose**: Collects accumulated trading fees from position
* **Fee Collection**: Specify maximum amounts to collect
* **Returns**: Collected fee balances for both tokens

**collect\_pool\_reward\<X, Y, RewardToken>**

* **Purpose**: Collects reward tokens earned by position
* **Reward Type**: Specify exact reward token type
* **Returns**: Coin of specified reward token type

**close\_position**

* **Purpose**: Closes empty position and destroys NFT
* **Requirements**: Position must have zero liquidity, fees, and rewards

#### Swap Functions

| Function Category     | Functions                                | Use Case                                      |
| --------------------- | ---------------------------------------- | --------------------------------------------- |
| **Exact Input**       | `swap_exact_x_to_y`, `swap_exact_y_to_x` | Swap all tokens for maximum output            |
| **Exact Output**      | `swap_x_to_exact_y`, `swap_y_to_exact_x` | Use minimum input for precise output          |
| **High-Level Router** | `swap_exact_input`, `swap_exact_output`  | Simplified interface with auto pool selection |

**Exact Input Swaps**

* **swap\_exact\_x\_to\_y**: Swap all X tokens for maximum Y tokens
* **swap\_exact\_y\_to\_x**: Swap all Y tokens for maximum X tokens
* **Use Case**: When you want to sell entire token balance

**Exact Output Swaps**

* **swap\_x\_to\_exact\_y**: Use minimum X tokens to get exact Y amount
* **swap\_y\_to\_exact\_x**: Use minimum Y tokens to get exact X amount
* **Use Case**: When you need precise output amount

**High-Level Router Functions**

* **swap\_exact\_input**: Router function for exact input swaps with deadline validation
* **swap\_exact\_output**: Router function for exact output swaps with deadline validation
* **Use Case**: Simplified interface for common swap operations with automatic pool selection

#### Swap Functions

**`swap_exact_x_to_y<X, Y>(pool, coin_in, sqrt_price_limit, versioned, clock, ctx)`**

Swaps an exact amount of token X for token Y.

```move
public fun swap_exact_x_to_y<X, Y>(
    pool: &mut Pool<X, Y>,
    coin_in: Coin<X>,
    sqrt_price_limit: u128,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &TxContext
): Balance<Y>
```

**Parameters:**

* `pool`: Mutable reference to the pool to execute swap in
* `coin_in`: X tokens to swap (entire amount will be consumed)
* `sqrt_price_limit`: Maximum acceptable sqrt price after swap (slippage protection)
* `versioned`: Reference to versioned object for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `Balance<Y>`: Resulting Y token balance from the swap

**`swap_exact_y_to_x<X, Y>(pool, coin_in, sqrt_price_limit, versioned, clock, ctx)`**

Swaps an exact amount of token Y for token X.

**Parameters:**

* `pool`: Mutable reference to the pool to execute swap in
* `coin_in`: Y tokens to swap (entire amount will be consumed)
* `sqrt_price_limit`: Minimum acceptable sqrt price after swap (slippage protection)
* `versioned`: Reference to versioned object for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `Balance<X>`: Resulting X token balance from the swap

**`swap_x_to_exact_y<X, Y>(pool, coin_in, amount_out, sqrt_price_limit, versioned, clock, ctx)`**

Swaps token X for an exact amount of token Y.

**Parameters:**

* `pool`: Mutable reference to the pool to execute swap in
* `coin_in`: X tokens to swap (excess will be refunded)
* `amount_out`: Exact amount of Y tokens to receive
* `sqrt_price_limit`: Maximum acceptable sqrt price after swap
* `versioned`: Reference to versioned object for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `Balance<Y>`: Exact amount of Y tokens requested

**`swap_y_to_exact_x<X, Y>(pool, coin_in, amount_out, sqrt_price_limit, versioned, clock, ctx)`**

Swaps token Y for an exact amount of token X.

**Parameters:**

* `pool`: Mutable reference to the pool to execute swap in
* `coin_in`: Y tokens to swap (excess will be refunded)
* `amount_out`: Exact amount of X tokens to receive
* `sqrt_price_limit`: Minimum acceptable sqrt price after swap
* `versioned`: Reference to versioned object for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `Balance<X>`: Exact amount of X tokens requested

**`swap_exact_input<X, Y>(pool_registry, fee, coin_in, amount_out_min, sqrt_price_limit, deadline, versioned, clock, ctx)`**

High-level router function for exact input swaps with automatic pool selection and deadline validation.

```move
public fun swap_exact_input<X, Y>(
    pool_registry: &mut PoolRegistry,
    fee: u64,
    coin_in: Coin<X>,
    amount_out_min: u64,
    sqrt_price_limit: u128,
    deadline: u64,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): Coin<Y>
```

**Parameters:**

* `pool_registry`: Mutable reference to the pool registry
* `fee`: Pool fee rate to select the correct pool
* `coin_in`: Input tokens to swap (entire amount will be consumed)
* `amount_out_min`: Minimum amount of output tokens expected (slippage protection)
* `sqrt_price_limit`: Price limit for slippage protection
* `deadline`: Transaction deadline timestamp to prevent stale transactions
* `versioned`: Reference for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `Coin<Y>`: Output token coin from the swap

**Features:**

* Automatic token ordering (handles both X→Y and Y→X directions)
* Built-in deadline validation
* Minimum output amount validation
* Simplified interface for common swap operations

**`swap_exact_output<X, Y>(pool_registry, fee, coin_in, amount_out, sqrt_price_limit, deadline, versioned, clock, ctx)`**

High-level router function for exact output swaps with automatic pool selection and deadline validation.

```move
public fun swap_exact_output<X, Y>(
    pool_registry: &mut PoolRegistry,
    fee: u64,
    coin_in: Coin<X>,
    amount_out: u64,
    sqrt_price_limit: u128,
    deadline: u64,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): Coin<Y>
```

**Parameters:**

* `pool_registry`: Mutable reference to the pool registry
* `fee`: Pool fee rate to select the correct pool
* `coin_in`: Input tokens to swap (excess will be refunded)
* `amount_out`: Exact amount of output tokens to receive
* `sqrt_price_limit`: Price limit for slippage protection
* `deadline`: Transaction deadline timestamp to prevent stale transactions
* `versioned`: Reference for package version validation
* `clock`: Clock object for timing validation
* `ctx`: Transaction context

**Returns:**

* `Coin<Y>`: Exact amount of output tokens requested

**Features:**

* Automatic token ordering (handles both X→Y and Y→X directions)
* Built-in deadline validation
* Automatic refund of excess input tokens
* Simplified interface for precise output amount swaps

### 💡 Developer Guide

#### 🎯 Complete End-to-End Example

Here's a comprehensive example showing how to create a pool, provide liquidity, perform swaps, and collect fees:

```move
public fun complete_clmm_example<USDC, SUI>(
    pool_registry: &mut PoolRegistry,
    position_registry: &mut PositionRegistry,
    usdc_metadata: &CoinMetadata<USDC>,
    sui_metadata: &CoinMetadata<SUI>,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
) {
    // 1. Create and initialize pool
    let initial_sqrt_price = 13043817825332782212; // sqrt(0.5) for 1 USDC = 2 SUI
    pool_manager::create_and_initialize_pool_v2<USDC, SUI>(
        pool_registry,
        3000, // 0.3% fee
        initial_sqrt_price,
        usdc_metadata,
        sui_metadata,
        versioned,
        clock,
        ctx
    );

    // 2. Open position in price range $1.80 - $2.20 per SUI
    let lower_sqrt_price = 11832159566199029792; // sqrt(1/2.20)
    let upper_sqrt_price = 14142135623730950624; // sqrt(1/1.80)
    let tick_lower = tick_math::get_tick_at_sqrt_price(lower_sqrt_price);
    let tick_upper = tick_math::get_tick_at_sqrt_price(upper_sqrt_price);

    let position = position_manager::open_position<USDC, SUI>(
        position_registry,
        pool_registry,
        3000,
        tick_lower,
        tick_upper,
        versioned,
        ctx
    );

    // 3. Add liquidity to position
    let usdc_coins = coin::mint_for_testing<USDC>(10000_000000, ctx); // 10,000 USDC
    let sui_coins = coin::mint_for_testing<SUI>(20000_000000000, ctx); // 20,000 SUI
    let deadline = clock::timestamp_ms(clock) + 300_000; // 5 minutes

    position_manager::increase_liquidity<USDC, SUI>(
        pool_registry,
        &mut position,
        usdc_coins,
        sui_coins,
        9500_000000,    // Min 9,500 USDC (5% slippage)
        19000_000000000, // Min 19,000 SUI (5% slippage)
        deadline,
        versioned,
        clock,
        ctx
    );

    // 4. Perform a swap (someone else trades)
    let trader_usdc = coin::mint_for_testing<USDC>(1000_000000, ctx); // 1,000 USDC
    let pool = pool_manager::borrow_mut_pool<USDC, SUI>(pool_registry, 3000);
    let current_sqrt_price = pool::sqrt_price_current(pool);
    let min_sqrt_price = (current_sqrt_price * 95) / 100; // 5% slippage

    let sui_out = swap_router::swap_exact_x_to_y<USDC, SUI>(
        pool,
        trader_usdc,
        min_sqrt_price,
        versioned,
        clock,
        ctx
    );

    // 5. Collect accumulated fees after some trading activity
    let (usdc_fees, sui_fees) = position_manager::collect<USDC, SUI>(
        pool_registry,
        &mut position,
        18446744073709551615, // Collect all fees (max u64)
        18446744073709551615,
        versioned,
        clock,
        ctx
    );

    // 6. Collect any reward tokens (if available)
    let rewards = position_manager::collect_pool_reward<USDC, SUI, FLOW>(
        pool_registry,
        &mut position,
        18446744073709551615, // Collect all rewards (max u64)
        versioned,
        clock,
        ctx
    );

    // 7. Remove liquidity when done
    let position_liquidity = position::liquidity(&position);
    let remove_deadline = clock::timestamp_ms(clock) + 300_000;

    position_manager::decrease_liquidity<USDC, SUI>(
        pool_registry,
        &mut position,
        position_liquidity, // Remove all liquidity
        0, // Accept any amount (or set minimums)
        0,
        remove_deadline,
        versioned,
        clock,
        ctx
    );

    // 8. Close empty position
    position_manager::close_position(position_registry, position, versioned, ctx);

    // Transfer collected fees and rewards
    transfer::public_transfer(usdc_fees, tx_context::sender(ctx));
    transfer::public_transfer(sui_fees, tx_context::sender(ctx));
    transfer::public_transfer(rewards, tx_context::sender(ctx));
    transfer::public_transfer(coin::from_balance(sui_out, ctx), tx_context::sender(ctx));
}
```

#### 🚀 Quick Integration Examples

**Basic Liquidity Provision**

```move
// 1. Open position
let position = position_manager::open_position<USDC, SUI>(
    &mut position_registry,
    &pool_registry,
    3000, // 0.3% fee
    tick_lower,
    tick_upper,
    &versioned,
    ctx
);

// 2. Add liquidity
position_manager::increase_liquidity<USDC, SUI>(
    &mut pool_registry,
    &mut position,
    usdc_coins,
    sui_coins,
    min_usdc_amount,
    min_sui_amount,
    deadline,
    &versioned,
    &clock,
    ctx
);
```

**Basic Token Swap**

```move
// Swap exact USDC for maximum SUI
let sui_out = swap_router::swap_exact_x_to_y<USDC, SUI>(
    &mut pool,
    usdc_in,
    min_sqrt_price, // Slippage protection
    &versioned,
    &clock,
    ctx
);
```

**Router Function Examples**

```move
// High-level exact input swap with automatic pool selection
let usdc_in = coin::mint_for_testing<USDC>(1000_000000, ctx); // 1000 USDC
let deadline = clock::timestamp_ms(&clock) + 300_000; // 5 minutes
let current_sqrt_price = pool::sqrt_price_current(&pool);
let min_sqrt_price = (current_sqrt_price * 95) / 100; // 5% slippage

let sui_out = swap_router::swap_exact_input<USDC, SUI>(
    &mut pool_registry,
    3000, // 0.3% fee pool
    usdc_in,
    1900_000000000, // Min 1900 SUI output (5% slippage)
    min_sqrt_price,
    deadline,
    &versioned,
    &clock,
    ctx
);

// High-level exact output swap with automatic pool selection
let usdc_in = coin::mint_for_testing<USDC>(2000_000000, ctx); // 2000 USDC (excess refunded)
let exact_sui_out = 500_000000000; // Exactly 500 SUI
let max_sqrt_price = (current_sqrt_price * 105) / 100; // 5% slippage

let sui_out = swap_router::swap_exact_output<USDC, SUI>(
    &mut pool_registry,
    3000, // 0.3% fee pool
    usdc_in, // Excess will be refunded
    exact_sui_out,
    max_sqrt_price,
    deadline,
    &versioned,
    &clock,
    ctx
);

// Verify exact amount received
assert!(coin::value(&sui_out) == exact_sui_out, 0);
```

**Swap Best Practices**

**Swap Flow:**

1. **Input Validation**: Checks pool state, price limits, and token amounts
2. **Route Calculation**: Determines optimal path through active liquidity
3. **Tick Traversal**: Executes swap across multiple price ranges if needed
4. **Fee Collection**: Deducts swap fees and protocol fees
5. **Price Update**: Updates pool price and oracle data
6. **Output Delivery**: Transfers resulting tokens to user

**Swap Types:**

**Exact Input Swaps** (`swap_exact_x_to_y`, `swap_exact_y_to_x`):

```move
// Swap all USDC for maximum SUI possible
let sui_out = swap_router::swap_exact_x_to_y<USDC, SUI>(
    &mut pool,
    usdc_in,           // Entire amount consumed
    min_sqrt_price,    // Price limit (slippage protection)
    &versioned,
    &clock,
    ctx
);
```

**Exact Output Swaps** (`swap_x_to_exact_y`, `swap_y_to_exact_x`):

```move
// Swap minimum USDC needed for exact 1 SUI
let sui_out = swap_router::swap_x_to_exact_y<USDC, SUI>(
    &mut pool,
    usdc_in,           // May have excess refunded
    1_000_000_000,     // Exactly 1 SUI (9 decimals)
    max_sqrt_price,    // Price limit
    &versioned,
    &clock,
    ctx
);
```

**Position Management Best Practices**

**Opening Positions:**

```move
// Choose tick range based on strategy
let tick_lower = tick_math::get_tick_at_sqrt_price(lower_price_sqrt);
let tick_upper = tick_math::get_tick_at_sqrt_price(upper_price_sqrt);

// Ensure ticks are valid for the pool's tick spacing
let tick_spacing = pool::tick_spacing(&pool);
let adjusted_lower = (tick_lower / tick_spacing) * tick_spacing;
let adjusted_upper = (tick_upper / tick_spacing) * tick_spacing;
```

**Liquidity Management:**

* **Narrow Ranges**: Higher fees, higher impermanent loss risk
* **Wide Ranges**: Lower fees, lower impermanent loss risk
* **Active Management**: Monitor price movements and adjust ranges

**Fee Collection Strategy:**

```move
// Collect fees regularly to compound returns
let (fee_x, fee_y) = position_manager::collect<X, Y>(
    &mut pool_registry,
    &mut position,
    18446744073709551615,  // Max u64 to collect all
    18446744073709551615,  // Max u64 to collect all
    &versioned,
    &clock,
    ctx
);

// Reinvest fees by adding liquidity
position_manager::increase_liquidity<X, Y>(
    &mut pool_registry,
    &mut position,
    coin::from_balance(fee_x, ctx),
    coin::from_balance(fee_y, ctx),
    0, // No minimum since we're reinvesting fees
    0,
    deadline,
    &versioned,
    &clock,
    ctx
);
```

**Defensive Programming Practices**

```move
// Always use deadlines for time-sensitive operations
let deadline = clock::timestamp_ms(clock) + 300_000; // 5 minutes

// Set reasonable slippage tolerance (e.g., 0.5%)
let amount_min = (expected_amount * 995) / 1000;

// Check pool state before operations
assert!(pool::is_initialized(&pool), E_POOL_NOT_INITIALIZED);

// Set appropriate price limits for swaps
let current_sqrt_price = pool::sqrt_price_current(&pool);

// For X to Y swaps (price decreasing), set a lower limit
let min_sqrt_price_limit = (current_sqrt_price * 95) / 100; // 5% slippage
// Ensure it's above the absolute minimum
let safe_min_limit = math::max(min_sqrt_price_limit, tick_math::min_sqrt_price() + 1);

// For Y to X swaps (price increasing), set an upper limit
let max_sqrt_price_limit = (current_sqrt_price * 105) / 100; // 5% slippage
// Ensure it's below the absolute maximum
let safe_max_limit = math::min(max_sqrt_price_limit, tick_math::max_sqrt_price() - 1);

// Check price limits before swap to avoid errors
if (x_for_y) {
    assert!(sqrt_price_limit < current_sqrt_price, E_PRICE_LIMIT_ALREADY_EXCEEDED);
    assert!(sqrt_price_limit > tick_math::min_sqrt_price(), E_PRICE_LIMIT_OUT_OF_BOUNDS);
} else {
    assert!(sqrt_price_limit > current_sqrt_price, E_PRICE_LIMIT_ALREADY_EXCEEDED);
    assert!(sqrt_price_limit < tick_math::max_sqrt_price(), E_PRICE_LIMIT_OUT_OF_BOUNDS);
};
```

#### Precision & Safety Features

* **Q64.64 Fixed-Point Arithmetic**: For precise price calculations
* **Overflow-Safe Operations**: Implements overflow-safe arithmetic operations
* **Rounding Controls**: Provides rounding controls for fee calculations

#### Integration Patterns

**Direct Pool Swap Integration**

Best practices for integrating with the core `pool::swap` function for custom swap implementations:

```move
// Complete swap integration pattern
public fun custom_swap_exact_input<X, Y>(
    pool: &mut Pool<X, Y>,
    input_coin: Coin<X>,
    min_output_amount: u64,
    max_slippage_bps: u64, // basis points (e.g., 50 = 0.5%)
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): Coin<Y> {
    let input_amount = coin::value(&input_coin);
    let current_sqrt_price = pool::sqrt_price_current(pool);

    // Calculate price limit based on slippage tolerance
    let price_limit = if (true) { // x_for_y = true
        let slippage_factor = 10000 - max_slippage_bps; // e.g., 9950 for 0.5%
        (current_sqrt_price * (slippage_factor as u128)) / 10000
    } else {
        let slippage_factor = 10000 + max_slippage_bps; // e.g., 10050 for 0.5%
        (current_sqrt_price * (slippage_factor as u128)) / 10000
    };

    // Execute swap
    let (balance_x_out, balance_y_out, receipt) = pool::swap<X, Y>(
        pool,
        true,           // x_for_y
        true,           // exact_in
        input_amount,   // amount_specified
        price_limit,
        versioned,
        clock,
        ctx
    );

    // Pay for the swap
    pool::pay<X, Y>(
        pool,
        receipt,
        coin::into_balance(input_coin), // payment_x
        balance::zero<Y>(),             // payment_y
        versioned,
        ctx
    );

    // Validate minimum output
    let output_amount = balance::value(&balance_y_out);
    assert!(output_amount >= min_output_amount, E_INSUFFICIENT_OUTPUT_AMOUNT);

    // Return output (balance_x_out should be zero for x_for_y swaps)
    balance::destroy_zero(balance_x_out);
    coin::from_balance(balance_y_out, ctx)
}

// Precise swap with receipt-based payment amounts
public fun precise_swap_exact_input<X, Y>(
    pool: &mut Pool<X, Y>,
    input_coin: Coin<X>,
    min_output_amount: u64,
    sqrt_price_limit: u128,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): (Coin<X>, Coin<Y>) { // Returns refunded input and output in (x, y) order
    let input_amount = coin::value(&input_coin);

    // Execute swap
    let (balance_x_out, balance_y_out, receipt) = pool::swap<X, Y>(
        pool,
        true,           // x_for_y
        true,           // exact_in
        input_amount,   // amount_specified
        sqrt_price_limit,
        versioned,
        clock,
        ctx
    );

    // Extract exact payment amounts from receipt
    let amount_x_needed = swap_receipt::amount_x_needed(&receipt);
    let amount_y_needed = swap_receipt::amount_y_needed(&receipt);

    // For exact_in swaps, amount_x_needed should equal input_amount
    // For x_for_y swaps, amount_y_needed should be zero
    assert!(amount_y_needed == 0, E_UNEXPECTED_Y_PAYMENT_REQUIRED); // Should be zero for x_for_y

    // Split exact amount needed for payment
    let payment_coin = coin::split(&mut input_coin, amount_x_needed, ctx);
    let payment_x = coin::into_balance(payment_coin);

    // Complete the payment
    pool::pay<X, Y>(
        pool,
        receipt,
        payment_x,
        balance::zero<Y>(),
        versioned,
        ctx
    );

    // Validate minimum output
    let output_amount = balance::value(&balance_y_out);
    assert!(output_amount >= min_output_amount, E_INSUFFICIENT_OUTPUT_AMOUNT);

    // Convert output balance to coin
    let output_coin = coin::from_balance(balance_y_out, ctx);
    balance::destroy_zero(balance_x_out); // Should be zero for x_for_y swaps

    // Return refunded input and output in (x, y) order
    (input_coin, output_coin)
}
```

**Direct Pool Liquidity Modification Integration**

Best practices for integrating with the core `pool::modify_liquidity` function for custom liquidity management:

```move
// Complete liquidity addition integration pattern
public fun add_liquidity_to_position<X, Y>(
    pool: &mut Pool<X, Y>,
    position: &mut Position,
    desired_amount_x: u64,
    desired_amount_y: u64,
    min_amount_x: u64,
    min_amount_y: u64,
    coin_x: Coin<X>,
    coin_y: Coin<Y>,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): (Coin<X>, Coin<Y>) { // Returns refunded coins

    // Validate input amounts
    assert!(coin::value(&coin_x) >= desired_amount_x, E_INSUFFICIENT_INPUT_AMOUNT);
    assert!(coin::value(&coin_y) >= desired_amount_y, E_INSUFFICIENT_INPUT_AMOUNT);

    // Get current pool state for calculations
    let current_sqrt_price = pool::sqrt_price_current(pool);
    let current_liquidity = pool::liquidity(pool);
    let tick_lower = position::tick_lower_index(position);
    let tick_upper = position::tick_upper_index(position);

    // Calculate optimal liquidity amount based on desired token amounts
    let target_liquidity = calculate_liquidity_for_amounts(
        current_sqrt_price,
        tick_lower,
        tick_upper,
        desired_amount_x,
        desired_amount_y
    );

    // Prepare exact amounts needed (may be less than desired)
    // Convert tick boundaries to sqrt prices
    let sqrt_price_lower = tick_math::get_sqrt_price_at_tick(tick_lower);
    let sqrt_price_upper = tick_math::get_sqrt_price_at_tick(tick_upper);

    let (exact_amount_x, exact_amount_y) = liquidity_math::get_amounts_for_liquidity(
        current_sqrt_price,
        sqrt_price_lower,
        sqrt_price_upper,
        target_liquidity,
        true // add = true for adding liquidity
    );

    // Validate minimum amounts
    assert!(exact_amount_x >= min_amount_x, E_INSUFFICIENT_OUTPUT_AMOUNT);
    assert!(exact_amount_y >= min_amount_y, E_INSUFFICIENT_OUTPUT_AMOUNT);

    // Split exact amounts from input coins
    let balance_x_in = coin::into_balance(coin::split(&mut coin_x, exact_amount_x, ctx));
    let balance_y_in = coin::into_balance(coin::split(&mut coin_y, exact_amount_y, ctx));

    // Execute liquidity modification
    let liquidity_delta = i128::from(target_liquidity);
    let (actual_amount_x, actual_amount_y) = pool::modify_liquidity<X, Y>(
        pool,
        position,
        liquidity_delta,
        balance_x_in,
        balance_y_in,
        versioned,
        clock,
        ctx
    );

    // Validate actual amounts meet expectations
    assert!(actual_amount_x >= min_amount_x, E_INSUFFICIENT_LIQUIDITY_ADDED);
    assert!(actual_amount_y >= min_amount_y, E_INSUFFICIENT_LIQUIDITY_ADDED);

    // Return any remaining coins as refund
    (coin_x, coin_y)
}

// Advanced liquidity removal with precise control
public fun remove_liquidity_from_position<X, Y>(
    pool_registry: &mut PoolRegistry,
    pool: &mut Pool<X, Y>,
    position: &mut Position,
    liquidity_to_remove: u128,
    min_amount_x_out: u64,
    min_amount_y_out: u64,
    collect_fees: bool,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): (Balance<X>, Balance<Y>) {

    // Validate position has enough liquidity
    let current_position_liquidity = position::liquidity(position);
    assert!(current_position_liquidity >= liquidity_to_remove, E_INSUFFICIENT_LIQUIDITY);

    // Get position details for calculations
    let tick_lower = position::tick_lower_index(position);
    let tick_upper = position::tick_upper_index(position);
    let current_sqrt_price = pool::sqrt_price_current(pool);

    // Calculate expected amounts to receive
    // Convert tick boundaries to sqrt prices
    let sqrt_price_lower = tick_math::get_sqrt_price_at_tick(tick_lower);
    let sqrt_price_upper = tick_math::get_sqrt_price_at_tick(tick_upper);

    let (expected_amount_x, expected_amount_y) = liquidity_math::get_amounts_for_liquidity(
        current_sqrt_price,
        sqrt_price_lower,
        sqrt_price_upper,
        liquidity_to_remove,
        false // add = false for removing liquidity
    );

    // Ensure expected amounts meet minimum requirements
    assert!(expected_amount_x >= min_amount_x_out, E_INSUFFICIENT_EXPECTED_OUTPUT);
    assert!(expected_amount_y >= min_amount_y_out, E_INSUFFICIENT_EXPECTED_OUTPUT);

    // Execute liquidity removal
    let liquidity_delta = i128::neg_from(liquidity_to_remove);
    let (actual_amount_x, actual_amount_y) = pool::modify_liquidity<X, Y>(
        pool,
        position,
        liquidity_delta,
        balance::zero<X>(), // No input when removing liquidity
        balance::zero<Y>(), // No input when removing liquidity
        versioned,
        clock,
        ctx
    );

    // Validate actual amounts meet minimum requirements
    assert!(actual_amount_x >= min_amount_x_out, E_INSUFFICIENT_OUTPUT_AMOUNT);
    assert!(actual_amount_y >= min_amount_y_out, E_INSUFFICIENT_OUTPUT_AMOUNT);

    // Collect fees if requested
    if (collect_fees) {
        let (collected_x, collected_y) = position_manager::collect<X, Y>(
            pool_registry,
            position,
            max_u64, // Collect all available fees
            max_u64, // Collect all available fees
            ctx
        );

        (collected_x, collected_y)
    } else {
        (
            balance::zero<X>(),
            balance::zero<Y>()
        )
    }
}

```

**Position Fees and Rewards Management**

Best practices for collecting fees and rewards from positions:

```move
// Optimized fee collection with threshold checking
public fun collect_fees<X, Y>(
    pool_registry: &mut PoolRegistry,
    position: &mut Position,
    versioned: &Versioned,
    ctx: &mut TxContext
): (Balance<X>, Balance<Y>) {
    let (fee_x, fee_y) = position_manager::collect<X, Y>(
        pool_registry,
        position,
        max_u64, // Collect all available fees
        max_u64, // Collect all available fees
        versioned,
        ctx
    );
    (fee_x, fee_y)
}

// Collect specific reward token type from position
public fun collect_position_reward<X, Y, RewardToken>(
    pool_registry: &mut PoolRegistry,
    position: &mut Position,
    versioned: &Versioned,
    clock: &Clock,
    ctx: &mut TxContext
): Coin<RewardToken> { // Returns collected reward coin

    // Collect the specific reward token type
    let collected_reward = position_manager::collect_pool_reward<X, Y, RewardToken>(
        pool_registry,
        position,
        max_u64, // Collect all available rewards
        versioned,
        clock,
        ctx
    );

    collected_reward
}
```

**Position Monitoring**

Best practices for getting position token amounts:

```move
// Get current token amounts in a position
public fun get_position_amounts<X, Y>(
    pool: &Pool<X, Y>,
    position: &Position
): (u64, u64) { // Returns (amount_x, amount_y)

    let tick_lower = position::tick_lower_index(position);
    let tick_upper = position::tick_upper_index(position);
    let current_sqrt_price = pool::sqrt_price_current(pool);
    let position_liquidity = position::liquidity(position);

    // Calculate current token amounts in the position
    if (position_liquidity > 0) {
        // Convert tick boundaries to sqrt prices
        let sqrt_price_lower = tick_math::get_sqrt_price_at_tick(tick_lower);
        let sqrt_price_upper = tick_math::get_sqrt_price_at_tick(tick_upper);

        liquidity_math::get_amounts_for_liquidity(
            current_sqrt_price,
            sqrt_price_lower,
            sqrt_price_upper,
            position_liquidity,
            false // add = false for getting amounts
        )
    } else {
        (0, 0)
    }
}
```

**Multi-Hop Swaps**

For token pairs without direct pools, implement multi-hop routing:

```move
// USDC -> SUI -> BTC (two-hop swap)
// Step 1: USDC -> SUI
let sui_balance = swap_router::swap_exact_x_to_y<USDC, SUI>(
    &mut usdc_sui_pool,
    usdc_in,
    min_sqrt_price_1,
    &versioned,
    &clock,
    ctx
);

// Step 2: SUI -> BTC
let btc_balance = swap_router::swap_exact_x_to_y<SUI, BTC>(
    &mut sui_btc_pool,
    coin::from_balance(sui_balance, ctx),
    min_sqrt_price_2,
    &versioned,
    &clock,
    ctx
);
```

**Flash Loans Integration**

Leverage flash loans for arbitrage and other strategies:

```move
// Flash loan pattern for arbitrage
public fun arbitrage_opportunity<X, Y>(
    pool: &mut Pool<X, Y>,
    flash_amount_x: u64,
    flash_amount_y: u64,
    versioned: &Versioned,
    ctx: &mut TxContext
): (Balance<X>, Balance<Y>) {
    // 1. Flash loan tokens from pool
    let (loan_x, loan_y, flash_receipt) = pool::flash<X, Y>(
        pool,
        flash_amount_x,
        flash_amount_y,
        versioned,
        ctx
    );

    // 2. Get debt amounts from receipt (includes fees)
    let (total_debt_x, total_debt_y) = pool::flash_receipt_debts(&flash_receipt);

    // 3. Execute arbitrage logic here
    // Example: swap tokens, interact with other protocols, etc.
    // ...your arbitrage logic...

    // 4. Prepare repayment (must include loan amount + fees)
    // Ensure you have enough to repay the debt
    let repay_x = loan_x; // Add your tokens if needed: balance::join(&mut loan_x, additional_x);
    let repay_y = loan_y; // Add your tokens if needed: balance::join(&mut loan_y, additional_y);

    // 5. Repay the flash loan with fees
    pool::repay<X, Y>(
        pool,
        flash_receipt,
        repay_x,
        repay_y,
        versioned,
        ctx
    );

    // 6. Return any profit
    (balance::zero<X>(), balance::zero<Y>())
}
```

### 🔮 Price Oracle System

FlowX CLMM includes a sophisticated time-weighted average price (TWAP) oracle system that provides reliable price feeds and historical data tracking. The oracle automatically records price and liquidity data with each swap, creating a decentralized price feed that follows the Uniswap V3 oracle design.

#### 🎯 Oracle Features

| Feature                    | Description                                       |
| -------------------------- | ------------------------------------------------- |
| **TWAP Calculation**       | Time-weighted average prices over any time period |
| **Automated Recording**    | Automatic price updates with every transaction    |
| **Historical Data**        | Up to 1000 observations stored per pool           |
| **Manipulation Resistant** | Requires significant capital to manipulate prices |
| **Gas Efficient**          | Optimized storage and calculation algorithms      |

#### 📊 Oracle Data Structure

Each oracle observation contains:

* **Timestamp (seconds)**: When the observation was recorded (in seconds, not milliseconds)
* **Tick Cumulative (I64)**: Cumulative sum of tick values over time (signed integer)
* **Seconds per Liquidity (u256)**: Time-weighted measure of liquidity depth
* **Initialization Status**: Whether the observation slot is active

#### 🔧 Core Oracle Functions

**Get Historical Price Data**

```move
/// Get TWAP data for specified time periods
public fun observe<X, Y>(
    self: &Pool<X, Y>,
    seconds_agos: vector<u64>,
    clock: &Clock
): (vector<I64>, vector<u256>)
```

**Parameters:**

* `self`: Pool to query oracle data from
* `seconds_agos`: Array of time periods to look back (in seconds)
* `clock`: Clock object for current timestamp

**Returns:**

* `vector<I64>`: Tick cumulatives for each time period (signed integers)
* `vector<u256>`: Seconds per liquidity cumulatives for each time period

**Increase Oracle Capacity**

```move
/// Increase the maximum number of observations this pool will store
public fun increase_observation_cardinality_next<X, Y>(
    self: &mut Pool<X, Y>,
    observation_cardinality_next: u64,
    versioned: &Versioned,
    ctx: &TxContext
)
```

**Parameters:**

* `self`: Pool to increase capacity for
* `observation_cardinality_next`: New maximum number of observations (max 1000)
* `versioned`: Versioned object for package version validation
* `ctx`: Transaction context

#### 💡 TWAP Calculation Examples

**Basic TWAP Price Calculation**

```move
use flowx_clmm::i64;
use flowx_clmm::i32;
use flowx_clmm::tick_math;

/// Calculate TWAP price over specified time period
public fun calculate_twap_price<X, Y>(
    pool: &Pool<X, Y>,
    period_seconds: u64,
    clock: &Clock
): u128 {
    // Get tick cumulatives for current time and period ago
    let seconds_agos = vector[0, period_seconds];
    let (tick_cumulatives, _) = pool.observe(seconds_agos, clock);

    let current_cumulative = *vector::borrow(&tick_cumulatives, 0);
    let past_cumulative = *vector::borrow(&tick_cumulatives, 1);

    // Calculate time-weighted average tick (handle signed arithmetic)
    let tick_delta = i64::sub(current_cumulative, past_cumulative);
    let average_tick_i64 = i64::div(tick_delta, i64::from(period_seconds));

    // Convert I64 to I32 for tick math
    let average_tick = if (i64::is_neg(average_tick_i64)) {
        i32::neg_from(i64::abs_u64(average_tick_i64))
    } else {
        i32::from_u64(i64::abs_u64(average_tick_i64))
    };

    // Convert tick to sqrt price
    tick_math::get_sqrt_price_at_tick(average_tick)
}

/// Get current oracle state information
public fun get_oracle_info<X, Y>(pool: &Pool<X, Y>): (u64, u64, u64) {
    (
        pool.observation_index(),           // Current observation index
        pool.observation_cardinality(),     // Number of populated observations
        pool.observation_cardinality_next() // Maximum observations capacity
    )
}
```

#### Data Access Functions

```move
// Pool oracle state getters (read-only)
pool.observation_index();           // Current observation index: u64
pool.observation_cardinality();     // Active observations count: u64
pool.observation_cardinality_next(); // Maximum capacity: u64
pool.borrow_observations();         // Direct access to observations vector
```

#### ⚠️ Error Handling

**Common Error Scenarios**

| Error Code                       | Description                           | Solution                              |
| -------------------------------- | ------------------------------------- | ------------------------------------- |
| `E_INSUFFICIENT_OUTPUT_AMOUNT`   | Slippage exceeded                     | Increase tolerance or wait            |
| `E_EXCESSIVE_INPUT_AMOUNT`       | Price moved unfavorably               | Retry with updated limits             |
| `E_ZERO_AMOUNT`                  | Cannot operate with zero amounts      | Provide non-zero amounts              |
| `E_NOT_EMPTY_POSITION`           | Position must be empty before closing | Remove all liquidity and collect fees |
| `E_PRICE_LIMIT_ALREADY_EXCEEDED` | Current price beyond specified limit  | Update price limit                    |
| `E_PRICE_LIMIT_OUT_OF_BOUNDS`    | Price limit outside valid range       | Use valid price range                 |

**Error Handling and Edge Cases**

**Common Error Scenarios:**

* `E_INSUFFICIENT_OUTPUT_AMOUNT`: Slippage exceeded, increase tolerance or wait
* `E_EXCESSIVE_INPUT_AMOUNT`: Price moved unfavorably, retry with updated limits
* `E_ZERO_AMOUNT`: Cannot operate with zero amounts
* `E_NOT_EMPTY_POSITION`: Position must be empty before closing (zero liquidity, zero coin owed, and zero reward)
* `E_PRICE_LIMIT_ALREADY_EXCEEDED`: The current price has already moved beyond the specified price limit before swap execution
* `E_PRICE_LIMIT_OUT_OF_BOUNDS`: The specified price limit is outside the valid range (below minimum or above maximum sqrt price)

### 🧮 Mathematical Libraries

FlowX CLMM includes optimized mathematical libraries for precise calculations:

#### Core Math Libraries

| Library                | Purpose                        | Key Functions                                         |
| ---------------------- | ------------------------------ | ----------------------------------------------------- |
| `tick_math.move`       | Tick ↔ Price conversions       | `get_sqrt_price_at_tick`, `get_tick_at_sqrt_price`    |
| `sqrt_price_math.move` | Square root price calculations | `get_next_sqrt_price_from_amount`, `get_amount_delta` |
| `liquidity_math.move`  | Liquidity calculations         | `add_delta`, `get_amounts_for_liquidity`              |
| `full_math_u128.move`  | High-precision arithmetic      | `mul_div`, `mul_div_round_up`                         |
| `swap_math.move`       | Swap calculations              | `compute_swap_step`                                   |

### 🛠️ Development

#### 🧪 Testing

**Unit Tests**

```bash
# Run all tests
sui move test

# Run with verbose output
sui move test --verbose

# Run with gas profiling
sui move test --gas-limit 1000000000
```

#### 📝 Environment Configuration

**Environment Variables**

```bash
# .env.example
SUI_NETWORK=testnet
JSON_RPC_ENDPOINT=https://fullnode.testnet.sui.io:443  # RPC endpoint for Sui network (testnet/mainnet)
PRIVATE_KEY=your_private_key_here
```

### 📦 Deployment

#### 🧪 Testnet Deployment

```bash
# 2. Build package
sui move build

# 3. Deploy to testnet
sui client publish --gas-budget 100000000
```

#### 🚀 Mainnet Deployment

```bash
# 1. Switch to mainnet
sui client switch --env mainnet

# 2. Verify build
sui move build --verification

# 3. Deploy with higher gas budget
sui client publish --gas-budget 200000000
```


# Additional Documents


# Meta SDK

MetaAggregatorSDK is a unified quoting and transaction builder for Sui-based DEX aggregators. It allows you to fetch the best swap route across multiple exchanges and build transactions for optimal trading.

### Features

* Aggregates quotes from multiple supported exchanges (Cetus, Bluefin, Aftermath, FlowX, etc.)
* Returns the best route based on output amount
* Supports custom exchange selection and slippage configuration
* **Flexible exchange selection:** Use `includeExchanges` option to specify which exchanges to use for quoting and routing

### Example

```typescript
import { MetaAgQuoter, Exchange } from '@flowx-finance/sdk';

// Use all supported exchanges
const quoter = new MetaAgQuoter('mainnet');

// Or specify only certain exchanges
const quoterCetusOnly = new MetaAgQuoter('mainnet', [Exchange.CETUS]);

const params = {
  tokenIn: '0x2::sui::SUI',
  tokenOut: '0xdba34672e30cb065b1f93e3ab55318768fd6fef66c15942c9f7cb846e2f900e7::usdc::USDC',
  amountIn: '10000000000',
};

const quote = await quoter.getBestRoute(params);
const txb = new Transaction()
const { coinOut, tx } = await quoter.buildTransaction(txb, quote, sender, 0.01); //slippage 1%, 1/100 = 0.01
tx.transferObjects([coinOut], '0xAddesss');
```

### Methods

#### `getBestRoute(params: QuoteQueryParams): Promise<QuoteResult | null>`

Fetches the best swap route from all enabled exchanges.

* `params`: Object containing swap parameters:
  * `tokenIn`: Input token address.
  * `tokenOut`: Output token address.
  * `amountIn`: Amount to swap.
  * ...other query options.

**Returns:**\
A `QuoteResult` object with the best route, or `null` if no route is found.

***

#### `buildTransaction(tx: Transaction, quote: QuoteResult, sender: string, slippage: number, coinIn?: TransactionObjectArgument): Promise<any>`

Builds a Sui transaction for the given quote.

* `tx`: The transaction object to build on.
* `quote`: The best route quote returned from `getBestRoute`.
* `sender`: The sender address.
* `slippage`: Slippage in basis points.
* `coinIn` (optional): The input coin object. If not provided, it will be auto-selected except for Aftermath exchange.

**Returns:**\
An object containing the output coin and, for Aftermath, the updated transaction.

###


# Bug Bounty

The FlowX.Finance Bug Bounty program is focused around our smart contracts with a primary interest in the prevention of loss of user funds.

#### Program fund is 50.000 USD

<h3 align="center">Rewards</h3>

| Level of vulnerability | Amount          |
| ---------------------- | --------------- |
| Critical               | Up to 5.000 USD |
| High                   | 2.000 USD       |
| Medium                 | 500 USD         |

These rewards may be increased in the future.

<h3 align="center">Smart Contracts</h3>

Currently the scope of program only includes CLMM contract. The scope might be extended with other versions in the future.

| Name of Contract | Link                                              |
| ---------------- | ------------------------------------------------- |
| CLMM Contract    | <https://github.com/FlowX-Finance/clmm-contracts> |

The contracts version may be updated in the future. Please contact our support team in Discord or Telegram to get access to scope.&#x20;

<h3 align="center">Impacts in scope</h3>

Only the following impacts are accepted within this Bug Bounty program. All other impacts are not considered as in-scope, even if they affect something in the assets in scope table.

| Type                                                                                      | Level    |
| ----------------------------------------------------------------------------------------- | -------- |
| Direct theft of any user funds                                                            | Critical |
| Permanent freezing of funds                                                               | Critical |
| Protocol insolvency                                                                       | Critical |
| Theft of unclaimed yield                                                                  | High     |
| Freeze ability of other users to trade                                                    | High     |
| Temporary freezing of funds                                                               | High     |
| Griefing (e.g. no profit motive for an attacker, but damage to the users or the protocol) | Medium   |

<h3 align="center"></h3>

<h3 align="center">Rules</h3>

The following activities are prohibited by this Bug Bounty program:

* Any testing with mainnet.
* Any testing with pricing oracles or third party Smart Contracts
* Attempting phishing or other social engineering attacks against our employees and/or customers
* Any testing with third party systems and applications (e.g. browser extensions) as well as websites (e.g. SSO providers, advertising networks)
* Automated testing of services that generates significant amounts of traffic
* Any denial of service attacks

<h3 align="center">Non-issues</h3>

The following issues are excluded from the rewards for this Bug Bounty program:

* Lack of liquidity
* Best practice critiques
* Centralization risks
* Issues with information about user balances
* Cases with disguising one asset with another asset
* Issues with precision when providing liquidity: e.g. in certain case, if you provide liquidity and after that you directly burn it, you may receive a bit less of one jetton and a bit more of the other one
* Any kind of optimization/logic improvements/coding style improvements
* Issues related to contract deletion caused by inability to pay rent
* Issues related to gas optimisation
* Issues related to loss of funds caused by price slippage: frontrunning, backrunning, sandwich attacks, etc.
* Possible loss of funds when attempting to perform a swap in non-initialized pool (before successful provideLP)

<h3 align="center">Reports</h3>

All bug reports must include a Proof of Concept demonstrating how the vulnerability can be exploited to be eligible for a reward. This may be a Smart Contract itself or a transaction. Only the reports that meet the requirements will be considered by the experts.

Please send reports to <development@flowx.finance>


# FLX Token

**Max Supply:** 10,000,000

**Ticker:** FLX&#x20;

**Contract:** 0x6dae8ca14311574fdfe555524ea48558e3d1360d1607d1c7f98af867e3b7976c::flx::FLX

**Allocation:**&#x20;

* 4.5% for GenesisX farming (0% at TGE. 12 weeks linear vesting. 50% in FLX — 50% in xFLX).
* 0.2% for Airdrop (01 week cliff, 100% in FLX).
* 8% for Pre-sale (100% atTGE. 35% in FLX — 65% in xFLX).
* 11% for Public sale (100% at TGE 50% in FLX — 50% in xFLX).
* 3.3% for Initiating liquidity (100% at TGE).
* 8.02% for CEX listing (0% at TGE. DAO will vote on minting amount. Max mintable = 802,000 FLX).
* 27.9% for Incentive Reward (01 month cliff. Then start emitting in 36 months for liquidity providers. 50% in FLX — 50% in xFLX).
* 10.8% for Core Contributor (06 months cliffs. 30 months linear vesting. 50% FLX — 50% xFLX).
* 14.04% for Partnership (06 months cliff. 30 months linear vesting. 100% in FLX).
* 12.24% for DAO Treasury (03 months cliff. 36 months linear vesting. 100% in FLX).

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

**Distribution:**

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


# xFLX Governance Token

xFLX is a unique system that FlowX Finance has learned from other high-performance protocols.

By using FLX directly as a pass to access utilities for FlowX Finance Holders, it provide simplicity and convenience for holders. However, this also brings liquidity risks to the token because there are no constraints or separate rights for long-term investors compared to short-term speculators.

Therefore, to address this concern, we have separated the FlowX Finance token system into 2 tokens: FLX and xFLX. FLX is used for liquidity and speculation purposes, while xFLX is used to access utilities such as Boost Yield, Dividend, Governance, etc for long-term supporters.

### Conversion mechanism

xFLX and FLX can be converted back and forth through the Convert Room.

**FLX to xFLX**

FLX can always be instantly converted to xFLX at a ratio of 1:1

**xFLX to FLX**

To convert from xFLX to FLX, users have the option to choose a conversion time ratio.&#x20;

The longer the conversion time, up to 90 days, the higher the conversion ratio from xFLX to FLX will be at 1:1.&#x20;

Not selecting a conversion time will allow for instant conversion of xFLX to FLX at a ratio of 10:1

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

Among these, "t" represents the time converted into days.

We believe that this new system will provide our investors with greater flexibility and options in managing their investments, while also reducing liquidity risks for the protocol's tokenomic.&#x20;

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


# How to add Liquidity V3

### Step 1

Go to FlowX **Portfolio** at <https://flowx.finance/portfolio> , chose tab **Liquidity V3** and click to button **New Position**

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

### Step 2

Select the pair of tokens that you want to add . You can choose 2 tokens at once.

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

### Step 3

Feel free to choose to your preferable tier. Then, set a range for each token respectively, where you think it has most concentrated liquidity.

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

### Step 4

After FlowX V3 recommend the proper rate between two tokens, please “Add Liquidity”.

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

### Step 5

Confirm and approve on your wallet, then Transaction Submitted.

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

After successful adding liquidity, your liquidity position will appear at <https://flowx.finance/portfolio>


# GenesiX Farming

GenesiX: <https://suiexplorer.com/object/0x6be2e5847e91ca2f18de8cbd711367b87440e6a5ca99c63b1ea1d29d743c8212>


# Swap

AMM: <https://suiexplorer.com/object/0xba153169476e8c3114962261d1edc70de5ad9781b83cc617ecc8c1923191cae0>

ZAPPER: <https://suiexplorer.com/object/0x38eff60545e56d3bc1bab5f3efa31f50089e5f4b2d55d77717adcc041d34839f>


# Claim Token

How to claim FLX tokens when participating in external Launchpad

Access the token claim page specifically for external Launchpads.

### Step 1:&#x20;

Access the claim token page exclusively for presale participants at FlowX Finance's Partner Launchpad.

If you purchased the presale at Spores Network, visit: <https://flowx.finance/presale/spores>

If you purchased the presale at [GameFi.org](http://gamefi.org/), visit: <https://flowx.finance/presale/gamefi>

If you purchased the presale at RedKite, visit: <https://flowx.finance/presale/redkite>

### Step 2:&#x20;

Use the registered Sui wallet with the Launchpad to Connect

<figure><img src="/files/55ehCAiLpbWukPuV8gnd" alt=""><figcaption></figcaption></figure>

### Step 3:&#x20;

After logging in with the registered wallet, the UI will display the amount of FLX and xFLX tokens that you can claim.

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

Users have the option to **Claim** or **Give Up**.

Once claimed, a successful claim notification will appear on the screen and the status will be updated to Claimed.

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

If the user wishes to request a Refund, they can click on the **Give Up** instruction and confirm at notification pop-up.

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

{% hint style="info" %}
**Important:**

* Please note that once this action is performed, it cannot be undone.
* Refunds cannot be obtained directly from FlowX Finance. Instead, they must be claimed through FlowX Finance's Partner Launchpad.
* The time limit for the "Give Up" action is determined by the refund time policy set by each Partner Launchpad. Once the refund time has expired, users will no longer have the option to Give Up and will only be able to Claim their tokens.
  {% endhint %}


# GenesiX Farming

GenesiX participants will be eligible to receive a 4.5% share of the total supply of $FLX tokens

📌 **July 1st, 2023 — July 8th, 2023:**

Participant can deposit their LP tokens as many as they want to GenesiX Pools. During this specified timeframe, there are no restrictions on the number of tokens users can deposit.

*However, after this period, no further additions can be made to the pools as the LP tokens will become locked until October 4th, 2023.*

📌 **July 8th, 2023 — October 6th, 2023:**

The rewards token in FLX will be calculated and distributed.

*Please note that $FLX can only be claimed by participants after the IDO has concluded, which is expected to take place in August.*

📌 **October 6th, 2023:**

Participants can withdraw their LP tokens.

### 🧪Pools Reward Information: <a href="#id-879f" id="id-879f"></a>

Total Reward: 225,000 FLX and 225,000 xFLX

🔷 SUI / USDC — Reward 65,000 FLX — 65,000 xFLX

🔷 SUI / WETH — Reward 45,000 FLX — 45,000 xFLX

🔷 WBNB / WETH— Reward 50,000 FLX —50,000 xFLX

🔹WETH / USDC — Reward 35,000 FLX — 35,000 xFLX

🔹USDT / USDC — Reward 30,000 FLX — 30,000 xFLX


# Risk Disclaimer

Acknowledgment of Terms & Conditions of access

By using FlowX.Finance website, services, dapp or application, you agree to the following Terms & Conditions.&#x20;

You confirm that you are aware of them and accept them in full: FlowX Finance is a smart contract protocol in its early stages. Though multiple security reviews have been conducted on the smart contracts, you acknowledge that there is a risk associated with using FlowX and its associated functions.&#x20;

Any interactions with the associated FlowX dapps, smart contracts, or related functions MAY put your funds at risk. By using these functions, you release the FlowX protocol and its contributors, team members, and service providers from any and all liability.&#x20;

You confirm that you are lawfully permitted to access this site and use the FlowX Finance protocol functions, and you are not in contravention of any laws governing your jurisdiction of residence or citizenship.&#x20;

You confirm that you are not a resident of Belarus, the Central African Republic, the Democratic Republic of Congo, the Democratic People's Republic of Korea, the Crimea region of Ukraine, Cuba, Iran, Libya, Somalia, South Sudan, Syria, the USA, Yemen, and Zimbabwe, or any other jurisdiction in which accessing or using FlowX Finance protocol is prohibited.&#x20;

You also confirm that you are not located in, incorporated, or otherwise established in a prohibited locality and that you are not using any Virtual Private Network (VPN) to modify your internet protocol address or otherwise circumvent or attempt to circumvent this prohibition.


# Terms of Service

#### Last modified: Dec 13th, 2023

These Terms of Service (the “Agreement”) explains the terms and conditions by which you may access and use [https://flowx.finance](https://flowx.finance/) and any subdomains associated with the Website. You must read this Agreement carefully as it governs your use of the Website. By accessing or using the Website, you signify that you have read, understand, and agree to be bound by this Agreement in its entirety. If you do not agree, you are not authorized to access or use the Website and should not use the Website.

NOTICE: This Agreement contains important information, including a binding arbitration provision and a class action waiver, both of which impact your rights as to how disputes are resolved. The Website is only available to you — and you should only access the Website — if you agree completely with these terms.

#### Introduction

The Website provides access to (a) a decentralized protocol on various public blockchains, including but not limited to Sui Network that allow users to trade certain compatible digital assets (“the FlowX Finance protocol” or the “Protocol”), among other services. The Website is one, but not the exclusive, means of accessing the Protocol.

To access the Website, you must use non-custodial wallet software, which allows you to interact with public blockchains. Your relationship with that non-custodial wallet provider is governed by the applicable terms of service of that third party, not this Agreement. Wallets are not operated by, maintained by, or affiliated with us, and we do not have custody or control over the contents of your wallet and have no ability to retrieve or transfer its contents. By connecting your wallet to our Website, you agree to be bound by this Agreement and all of the terms incorporated herein by reference.

#### Modification of this Agreement

We reserve the right, in our sole discretion, to modify this Agreement from time to time. If we make any material modifications, we will notify you by updating the date at the top of the Agreement and by maintaining a current version of the Agreement at <https://flowx.finance/terms-of-service>. All modifications will be effective when they are posted, and your continued accessing or use of the Website will serve as confirmation of your acceptance of those modifications. If you do not agree with any modifications to this Agreement, you must immediately stop accessing and using the Website.

#### Description of Services provided through the Website

The Website provides a web or mobile-based means of accessing the Protocol.

#### Website for accessing Protocol

The Website is distinct from the Protocol and is one, but not the exclusive, means of accessing the Protocol. By using the Website, you understand that you are not buying or selling digital assets from us and that we do not operate any liquidity pools on the Protocol or control trade execution on the Protocol. When traders pay fees for trades, those fees accrue to liquidity providers for the Protocol. As a general matter, the FlowX FInance team is not a liquidity provider into Protocol liquidity pools and liquidity providers are independent third parties. The Protocol was initially deployed on the Sui blockchain.

#### Eligibility

To access or use the Website, you must be able to form a legally binding contract with us. Accordingly, you represent that you are at least the age of majority in your jurisdiction (e.g., 18 years old in the United States) and have the full right, power, and authority to enter into and comply with the terms and conditions of this Agreement on behalf of yourself and any company or legal entity for which you may access or use the Website.

You further represent that you are not (a) the subject of economic or trade sanctions administered or enforced by any governmental authority or otherwise designated on any list of prohibited or restricted parties (including but not limited to the list maintained by the Office of Foreign Assets Control of the U.S. Department of the Treasury) or (b) a citizen, resident, or organized in a jurisdiction or territory that is the subject of comprehensive country-wide, territory-wide, or regional economic sanctions by the United States. Finally, you represent that your access and use of the Website will fully comply with all applicable laws and regulations, and that you will not access or use the Website to conduct, promote, or otherwise facilitate any illegal activity.

#### Intellectual Property Rights

FlowX Finance owns all intellectual property and other rights in the Website and its contents, including (but not limited to) software, text, images, trademarks, service marks, copyrights, patents, designs, and its “look and feel.” Unlike the Website, versions 1-3 of the Protocol are comprised entirely of open-source or source-available software running on public blockchains.

By using the Website to list, post, promote, or display NFTs, you grant us a worldwide, non-exclusive, sublicensable, royalty-free license to use, copy, modify, and display any content, including but not limited to text, materials, images, files, communications, comments, feedback, suggestions, ideas, concepts, questions, data, or otherwise, that you post on or through the Website for our current and future business purposes, including to provide, promote, and improve the services. This includes any digital file, art, or other material linked to or associated with any NFTs that are displayed.

You represent and warrant that you have, or have obtained, all rights, licenses, consents, permissions, power and/or authority necessary to grant the rights granted herein for any NFTs that you list, post, promote, or display on or through the Website. You represent and warrant that such content does not contain material subject to copyright, trademark, publicity rights, or other intellectual property rights, unless you have necessary permission or are otherwise legally entitled to post the material and to grant us the license described above, and that the content does not violate any laws.

#### Additional Rights

We reserve the following rights, which do not constitute obligations of ours: (a) with or without notice to you, to modify, substitute, eliminate or add to the Website; (b) to review, modify, filter, disable, delete and remove any and all content and information from the Website; and (c) to cooperate with any law enforcement, court or government investigation or order or third party requesting or directing that we disclose information or content or information that you provide.

#### Prohibited Activity

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

* Intellectual Property Infringement. Activity that infringes on or violates any copyright, trademark, service mark, patent, right of publicity, right of privacy, or other proprietary or intellectual property rights under the law.
* Cyberattack. Activity that seeks to interfere with or compromise the integrity, security, or proper functioning of any computer, server, network, personal device, or other information technology system, including (but not limited to) the deployment of viruses and denial of service attacks.
* Fraud and Misrepresentation. Activity that seeks to defraud us or any other person or entity, including (but not limited to) providing any false, inaccurate, or misleading information in order to unlawfully obtain the property of another.
* Market Manipulation. Activity that violates any applicable law, rule, or regulation concerning the integrity of trading markets, including (but not limited to) the manipulative tactics commonly known as “rug pulls”, pumping and dumping, and wash trading.
* Securities and Derivatives Violations. Activity that violates any applicable law, rule, or regulation concerning the trading of securities or derivatives, including (but not limited to) the unregistered offering of securities and the offering of leveraged and margined commodity products to retail customers in the United States.
* Sale of Stolen Property. Buying, selling, or transferring of stolen items, fraudulently obtained items, items taken without authorization, and/or any other illegally obtained items.
* Data Mining or Scraping. Activity that involves data mining, robots, scraping, or similar data gathering or extraction methods of content or information from the Website.
* Objectionable Content. Activity that involves soliciting information from anyone under the age of 18 or that is otherwise harmful, threatening, abusive, harassing, tortious, excessively violent, defamatory, vulgar, obscene, pornographic, libelous, invasive of another’s privacy, hateful, discriminatory, or otherwise objectionable.
* Any Other Unlawful Conduct. Activity that violates any applicable law, rule, or regulation of the United States or another relevant jurisdiction, including (but not limited to) the restrictions and regulatory requirements imposed by U.S. law.

#### Initial Farm Offering

You represent that you are not a user from the following countries or regions when participating in our Initial Farm Offerings:

Belarus, Cuba, Crimea Region, Democratic Republic of Congo, Iran, Iraq, New Zealand, North Korea, South Sudan, Sudan, Syria, United States of America and its territories (American Samoa, Guam, Puerto Rico, the Northern Mariana Islands, and the U.S. Virgin Islands), Zimbabwe.

#### Not Registered with the SEC or Any Other Agency

We are not registered with the U.S. Securities and Exchange Commission as a national securities exchange or in any other capacity. You understand and acknowledge that we do not broker trading orders on your behalf. We also do not facilitate the execution or settlement of your trades, which occur entirely on the public distributed blockchains like Sui. As a result, we do not (and cannot) guarantee market best pricing or best execution through the Website or when using our Smart Router feature, which routes trades across liquidity pools on the Protocol only. Any references in the Website to “best price” do not constitute a representation or warranty about pricing available through the Website, on the Protocol, or elsewhere.

#### Non-Solicitation; No Investment Advice

You agree and understand that: (a) all trades you submit through the Website are considered unsolicited, which means that they are solely initiated by you; (b) you have not received any investment advice from us in connection with any trades, including those you place via our Smart Router API; and (c) we do not conduct a suitability review of any trades you submit.

We may provide information about tokens in the Website sourced from third-party data partners through features such as rarity scores, token explorer or token lists (which includes the FlowX Finance default token list and FlowX Finance expanded list hosted at tokenlists.org). We may also provide warning labels for certain tokens. The provision of informational materials does not make trades in those tokens solicited; we are not attempting to induce you to make any purchase as a result of information provided. All such information provided by the Website is for informational purposes only and should not be construed as investment advice or a recommendation that a particular token is a safe or sound investment. You should not take, or refrain from taking, any action based on any information contained in the Website. By providing token information for your convenience, we do not make any investment recommendations to you or opine on the merits of any transaction or opportunity. You alone are responsible for determining whether any investment, investment strategy or related transaction is appropriate for you based on your personal investment objectives, financial circumstances, and risk tolerance.

#### Non-Custodial and No Fiduciary Duties

The Website is a purely non-custodial application, meaning we do not ever have custody, possession, or control of your digital assets at any time. It further means you are solely responsible for the custody of the cryptographic private keys to the digital asset wallets you hold and you should never share your wallet credentials or seed phrase with anyone. We accept no responsibility for, or liability to you, in connection with your use of a wallet and make no representations or warranties regarding how the Website will operate with any specific wallet. Likewise, you are solely responsible for any associated wallet and we are not liable for any acts or omissions by you in connection with or as a result of your wallet being compromised.

This Agreement is not intended to, and does not, create or impose any fiduciary duties on us. To the fullest extent permitted by law, you acknowledge and agree that we owe no fiduciary duties or liabilities to you or any other party, and that to the extent any such duties or liabilities may exist at law or in equity, those duties and liabilities are hereby irrevocably disclaimed, waived, and eliminated. You further agree that the only duties and obligations that we owe you are those set out expressly in this Agreement.

#### Compliance and Tax Obligations

The Website may not be available or appropriate for use in your jurisdiction. By accessing or using the Website, you agree that you are solely and entirely responsible for compliance with all laws and regulations that may apply to you.

Specifically, your use of the Website or the Protocol may result in various tax consequences, such as income or capital gains tax, value-added tax, goods and services tax, or sales tax in certain jurisdictions.It is your responsibility to determine whether taxes apply to any transactions you initiate or receive and, if so, to report and/or remit the correct tax to the appropriate tax authority.

#### Assumption of Risk

By accessing and using the Website, you represent that you are financially and technically sophisticated enough to understand the inherent risks associated with using cryptographic and blockchain-based systems, and that you have a working knowledge of the usage and intricacies of digital assets such as Sui, so-called stablecoins, and other digital tokens such as those following the Sui Standard Token, or standards of any other digital tokens which are transacted on FlowX Finance.

In particular, you understand that the markets for these digital assets are nascent and highly volatile due to risk factors including (but not limited to) adoption, speculation, technology, security, and regulation. You understand that anyone can create a token, including fake versions of existing tokens and tokens that falsely claim to represent projects, and acknowledge and accept the risk that you may mistakenly trade those or other tokens. So-called stablecoins may not be as stable as they purport to be, may not be fully or adequately collateralized, and may be subject to panics and runs.

Further, you understand that smart contract transactions automatically execute and settle, and that blockchain-based transactions are irreversible when confirmed. You acknowledge and accept that the cost and speed of transacting with cryptographic and blockchain-based systems such as Sui are variable and may increase dramatically at any time. You further acknowledge and accept the risk of selecting to trade in Expert Modes, which can expose you to potentially significant price slippage and higher costs.

If you act as a liquidity provider to the Protocol through the Website, you understand that your digital assets may lose some or all of their value while they are supplied to the Protocol through the Website due to the fluctuation of prices of tokens in a trading pair or liquidity pool.

Finally, you understand that we do not create, own, or operate cross-chain bridges and we do not make any representation or warranty about the safety or soundness of any cross-chain bridge, including its use for FlowX Finance governance.

In summary, you acknowledge that we are not responsible for any of these variables or risks, do not own or control the Protocol, and cannot be held liable for any resulting losses that you experience while accessing or using the Website. Accordingly, you understand and agree to assume full responsibility for all of the risks of accessing and using the Website to interact with the Protocol.

#### Third-Party Resources and Promotions

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

#### Release of Claims

You expressly agree that you assume all risks in connection with your access and use of the Website. You further expressly waive and release us from any and all liability, claims, causes of action, or damages arising from or in any way relating to your use of the Website. If you are a California resident, you waive the benefits and protections of California Civil Code § 1542, which provides: "\[a] general release does not extend to claims that the creditor or releasing party does not know or suspect to exist in his or her favor at the time of executing the release and that, if known by him or her, would have materially affected his or her settlement with the debtor or released party."

#### Indemnity

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

#### No Warranties

The Website is provided on an "AS IS" and "AS AVAILABLE" basis. TO THE FULLEST EXTENT PERMITTED BY LAW, WE DISCLAIM ANY REPRESENTATIONS AND WARRANTIES OF ANY KIND, WHETHER EXPRESS, IMPLIED, OR STATUTORY, INCLUDING (BUT NOT LIMITED TO) THE WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. You acknowledge and agree that your use of the Website is at your own risk. We do not represent or warrant that access to the Website will be continuous, uninterrupted, timely, or secure; that the information contained in the Website will be accurate, reliable, complete, or current; or that the Website will be free from errors, defects, viruses, or other harmful elements. No advice, information, or statement that we make should be treated as creating any warranty concerning the Website. We do not endorse, guarantee, or assume responsibility for any advertisements, offers, or statements made by third parties concerning the Website.

Similarly, the Protocol is provided "AS IS", at your own risk, and without warranties of any kind. Although we contributed to the initial code for the Protocol, we do not provide, own, or control the Protocol, which is run autonomously without any headcount by smart contracts deployed on various blockchains. Upgrades and modifications to the Protocol are generally managed in a community-driven way by holders of the CAKE token. No developer or entity involved in creating the Protocol will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of, the Protocol, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value. We do not endorse, guarantee, or assume responsibility for any advertisements, offers, or statements made by third parties concerning the Website.

#### Limitation of Liability

UNDER NO CIRCUMSTANCES SHALL WE OR ANY OF OUR OFFICERS, DIRECTORS, EMPLOYEES, CONTRACTORS, AGENTS, AFFILIATES, OR SUBSIDIARIES BE LIABLE TO YOU FOR ANY INDIRECT, PUNITIVE, INCIDENTAL, SPECIAL, CONSEQUENTIAL, OR EXEMPLARY DAMAGES, INCLUDING (BUT NOT LIMITED TO) DAMAGES FOR LOSS OF PROFITS, GOODWILL, USE, DATA, OR OTHER INTANGIBLE PROPERTY, ARISING OUT OF OR RELATING TO ANY ACCESS OR USE OF THE INTERFACE, NOR WILL WE BE RESPONSIBLE FOR ANY DAMAGE, LOSS, OR INJURY RESULTING FROM HACKING, TAMPERING, OR OTHER UNAUTHORIZED ACCESS OR USE OF THE INTERFACE OR THE INFORMATION CONTAINED WITHIN IT. WE ASSUME NO LIABILITY OR RESPONSIBILITY FOR ANY: (A) ERRORS, MISTAKES, OR INACCURACIES OF CONTENT; (B) PERSONAL INJURY OR PROPERTY DAMAGE, OF ANY NATURE WHATSOEVER, RESULTING FROM ANY ACCESS OR USE OF THE INTERFACE; (C) UNAUTHORIZED ACCESS OR USE OF ANY SECURE SERVER OR DATABASE IN OUR CONTROL, OR THE USE OF ANY INFORMATION OR DATA STORED THEREIN; (D) INTERRUPTION OR CESSATION OF FUNCTION RELATED TO THE INTERFACE; (E) BUGS, VIRUSES, TROJAN HORSES, OR THE LIKE THAT MAY BE TRANSMITTED TO OR THROUGH THE INTERFACE; (F) ERRORS OR OMISSIONS IN, OR LOSS OR DAMAGE INCURRED AS A RESULT OF THE USE OF, ANY CONTENT MADE AVAILABLE THROUGH THE INTERFACE; AND (G) THE DEFAMATORY, OFFENSIVE, OR ILLEGAL CONDUCT OF ANY THIRD PARTY.

#### Dispute Resolution

We will use our best efforts to resolve any potential disputes through informal, good faith negotiations. If a potential dispute arises, you must contact us by sending an email to <hello@flowx.finance> so that we can attempt to resolve it without resorting to formal dispute resolution. If we aren't able to reach an informal resolution within sixty days of your email, then you and we both agree to resolve the potential dispute according to the process set forth below.

Any claim or controversy arising out of or relating to the Website, this Agreement, 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 Arbitration Rules of the Hong Kong International Arbitration Centre. You understand that you are required to resolve all Disputes by binding arbitration. The arbitration shall be held on a confidential basis before a single arbitrator, who shall be selected pursuant to Arbitration Rules of the Centre. The arbitration will be held in Hong Kong, 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.

#### Class Action and Jury Trial Waiver

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

#### Governing Law

You agree that the laws of Hong Kong, without regard to principles of conflict of laws, govern this Agreement and any Dispute between you and us. You further agree that the Website shall be deemed to be based solely in the State of Hong Kong, and that although the Website may be available in other jurisdictions, its availability does not give rise to general or specific personal jurisdiction in any forum outside Hong Kong. Any arbitration conducted pursuant to this Agreement shall be governed by the Arbitration Rules of the Centre. You agree that the courts of Hong Kong are the proper forum for any appeals of an arbitration award or for court proceedings in the event that this Agreement's binding arbitration clause is found to be unenforceable.

#### Entire Agreement

These terms constitute the entire agreement between you and us with respect to the subject matter hereof. This Agreement supersedes any and all prior or contemporaneous written and oral agreements, communications and other understandings (if any) relating to the subject matter of the terms.

#### Gas Fees

Blockchain transactions require the payment of transaction fees to the appropriate network (“Gas Fees”). Except as otherwise expressly set forth in the terms of another offer by FlowX Finance, you will be solely responsible to pay the Gas Fees for any transaction that you initiate.


