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
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
๐ Position Management
๐ฐ Fee & Reward Collection
๐ Swap Functions
๐ API Reference
This section provides detailed parameter descriptions for all core functions.
Pool Management Functions
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
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_minandamount_y_minparametersAuto-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
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 incoin_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 validationclock: Clock object for timing validationctx: 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 incoin_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 validationclock: Clock object for timing validationctx: 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 incoin_in: X tokens to swap (excess will be refunded)amount_out: Exact amount of Y tokens to receivesqrt_price_limit: Maximum acceptable sqrt price after swapversioned: Reference to versioned object for package version validationclock: Clock object for timing validationctx: 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 incoin_in: Y tokens to swap (excess will be refunded)amount_out: Exact amount of X tokens to receivesqrt_price_limit: Minimum acceptable sqrt price after swapversioned: Reference to versioned object for package version validationclock: Clock object for timing validationctx: 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 registryfee: Pool fee rate to select the correct poolcoin_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 protectiondeadline: Transaction deadline timestamp to prevent stale transactionsversioned: Reference for package version validationclock: Clock object for timing validationctx: 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 registryfee: Pool fee rate to select the correct poolcoin_in: Input tokens to swap (excess will be refunded)amount_out: Exact amount of output tokens to receivesqrt_price_limit: Price limit for slippage protectiondeadline: Transaction deadline timestamp to prevent stale transactionsversioned: Reference for package version validationclock: Clock object for timing validationctx: 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:
Input Validation: Checks pool state, price limits, and token amounts
Route Calculation: Determines optimal path through active liquidity
Tick Traversal: Executes swap across multiple price ranges if needed
Fee Collection: Deducts swap fees and protocol fees
Price Update: Updates pool price and oracle data
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
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 fromseconds_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 forobservation_cardinality_next: New maximum number of observations (max 1000)versioned: Versioned object for package version validationctx: Transaction context
๐ก TWAP Calculation Examples
Basic TWAP Price Calculation
Data Access Functions
โ ๏ธ Error Handling
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
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 waitE_EXCESSIVE_INPUT_AMOUNT: Price moved unfavorably, retry with updated limitsE_ZERO_AMOUNT: Cannot operate with zero amountsE_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 executionE_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
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?

