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

create_pool_v2 - Create a new liquidity pool

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

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:

create_and_initialize_pool_v2 - Create and initialize pool with price

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

Parameters:

  • sqrt_price: Initial square root price as Q64.64 fixed-point number

  • Additional parameters same as create_pool_v2

Example:

๐Ÿ“ Position Management

open_position - Open a new liquidity position

Opens a new liquidity position within specified tick range.

Example:

Complete Liquidity Provider Workflow Example:

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

increase_liquidity - Add liquidity to position

Adds liquidity to an existing position with slippage protection.

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:

decrease_liquidity - Remove liquidity from position

Removes liquidity from a position and returns tokens.

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:

๐Ÿ’ฐ Fee & Reward Collection

collect - Collect accumulated fees

Collects accumulated trading fees from a position.

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:

collect_pool_reward - Collect reward tokens

Collects accumulated reward tokens for a position.

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:

๐Ÿ”„ Swap Functions

Exact Input Swaps - Swap exact amount in for maximum out

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:

Exact Output Swaps - Swap minimum in for exact amount out

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:

๐Ÿ“‹ 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.

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.

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.

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:

๐Ÿš€ Quick Integration Examples

Basic Liquidity Provision

Basic Token Swap

Router Function Examples

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):

Exact Output Swaps (swap_x_to_exact_y, swap_y_to_exact_x):

Position Management Best Practices

Opening Positions:

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:

Defensive Programming Practices

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:

Direct Pool Liquidity Modification Integration

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

Position Fees and Rewards Management

Best practices for collecting fees and rewards from positions:

Position Monitoring

Best practices for getting position token amounts:

Multi-Hop Swaps

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

Flash Loans Integration

Leverage flash loans for arbitrage and other strategies:

๐Ÿ”ฎ 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

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

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

Data Access Functions

โš ๏ธ 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

๐Ÿ“ Environment Configuration

Environment Variables

๐Ÿ“ฆ Deployment

๐Ÿงช Testnet Deployment

๐Ÿš€ Mainnet Deployment

Last updated

Was this helpful?