Core Functions
createPool
Creates a new standard pool according to a predefined configuration. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Both token amounts must be greater than zero
- If using native SOL, it will be automatically wrapped to wSOL
- The
config
parameter should be a valid configuration account - Pool creation automatically creates an initial position
- Use
preparePoolCreationParams
to calculate properinitSqrtPrice
andliquidityDelta
createCustomPool
Creates a customizable pool with specific fee parameters, reward settings, and activation conditions. Functiontx
: The transaction to sign and sendpool
: The public key of the created poolposition
: The public key of the initial position
- Use this function instead of
createPool
when you need custom fee structures - Use
preparePoolCreationParams
to calculate properinitSqrtPrice
andliquidityDelta
createCustomPoolWithDynamicConfig
Creates a customizable pool with dynamic configuration, allowing for specific fee parameters with specified pool creator authority Functiontx
: The transaction to sign and sendpool
: The public key of the created poolposition
: The public key of the initial position
createPosition
Creates a new position in an existing pool. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- The
positionNft
should be a new mint that doesn’t already have a position - Creating a position doesn’t automatically add liquidity
- After creating a position, use
addLiquidity
to provide tokens
getLiquidityDelta
Calculates the liquidity delta based on the provided token amounts and price ranges. FunctiongetQuote
Calculates the expected output amount for a swap, including fees and slippage protection. FunctionswapInAmount
: The original input amountconsumedInAmount
: The actual input amount used (after transfer fees)swapOutAmount
: The expected output amountminSwapOutAmount
: The minimum output amount accounting for slippagetotalFee
: The total fee to be paidpriceImpact
: The price impact of the swap as a percentage
- Always check the price impact before executing a swap
- The
slippage
parameter protects users from price movements - Use the
minSwapOutAmount
as theminimumAmountOut
parameter forswap
- For Token2022 tokens with transfer fees, provide the token info parameters
getQuoteExactOut
Calculates the expected input amount for a swap based on an exact output amount, including fees and slippage protection. FunctionoutputAmount
: The expected output amountoutputTokenMint
: The mint of the output tokenslippage
: The slippage tolerance in percentagepoolState
: The state of the poolcurrentTime
: The current timestampcurrentSlot
: The current slotinputTokenInfo
: Token info for Token2022 transfer fee calculationsoutputTokenInfo
: Token info for Token2022 transfer fee calculations
- Always check the price impact before executing a swap
- The
slippage
parameter protects users from price movements - Use the
maxInputAmount
as theamountIn
parameter forswap
- For Token2022 tokens with transfer fees, provide the token info parameters
getDepositQuote
Calculates the deposit quote for adding liquidity to a pool based on a single token input. FunctionactualInputAmount
: The actual input amount (after transfer fees)consumedInputAmount
: The full input amount including transfer feesliquidityDelta
: The amount of liquidity that will be addedoutputAmount
: The calculated amount of the other token to be paired
- Use this to calculate how much of token B is needed when adding token A (or vice versa)
- Particularly useful for single-sided liquidity provision
- The function handles Token2022 transfer fees if token info is provided
getWithdrawQuote
Calculates the withdrawal quote for removing liquidity from a pool. FunctionliquidityDelta
: The amount of liquidity being removedoutAmountA
: The calculated amount of token A to receiveoutAmountB
: The calculated amount of token B to receive
- Use this to estimate the tokens you’ll receive when removing liquidity
- The function handles Token2022 transfer fees if token info is provided
- The calculation accounts for the current price relative to the position’s price range
swap
Executes a token swap in the pool. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Get a quote first using
getQuote
to determine theminimumAmountOut
- The SDK handles wrapping/unwrapping of SOL automatically
- Token accounts are created automatically if they don’t exist
- The transaction will fail if the output amount would be less than
minimumAmountOut
- Optional referral tokenAccount will receive a portion of fees if the pool is configured for referrals
addLiquidity
Adds liquidity to an existing position. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Calculate the liquidity delta first using
getDepositQuote
- The SDK handles wrapping/unwrapping of SOL automatically
- Token accounts are created automatically if they don’t exist
- Set appropriate thresholds to protect against slippage
removeLiquidity
Removes a specific amount of liquidity from an existing position. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- You can only remove unlocked liquidity
- The SDK handles wrapping/unwrapping of SOL automatically
- Token accounts are created automatically if they don’t exist
- Set appropriate thresholds to protect against slippage
- Removing all liquidity doesn’t close the position
removeAllLiquidity
Removes all available liquidity from a position. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- This removes all unlocked liquidity in one transaction
- The position remains open after removing all liquidity
- You can’t remove locked liquidity (use
refreshVesting
first if needed) - The SDK handles wrapping/unwrapping of SOL automatically
removeAllLiquidityAndClosePosition
Removes all liquidity from a position and closes it in a single transaction. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- This combines multiple operations in a single transaction:
- Claims any accumulated fees
- Removes all liquidity
- Closes the position and returns the rent
- The position must be completely unlocked
- The function will throw an error if the position has any locked liquidity
- This is more gas-efficient than doing these operations separately
- If there are vesting schedules, they must be refreshed before closing the position
mergePosition
Merges liquidity from one position into another in a single transaction. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- This function combines multiple operations:
- Claims any accumulated fees from the source position
- Removes all liquidity from the source position
- Adds the liquidity to the target position
- Closes the source position
- Both positions must be owned by the same wallet
- The source position must be completely unlocked
- This is more gas-efficient than performing these operations separately
- Set appropriate thresholds to protect against slippage for both add and remove operations
lockPosition
Builds a transaction to lock a position with vesting schedule. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Locking positions is useful for creating various incentive mechanisms
- The vesting schedule controls how quickly liquidity unlocks over time
- Locked liquidity cannot be withdrawn until it becomes unlocked
- The vesting account is a new account that must be created
- The function only locks currently unlocked liquidity
permanentLockPosition
Permanently locks a portion of liquidity in a position. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Permanently locked liquidity can never be withdrawn
- This is useful for deep liquidity protocols or governance mechanisms
- Once liquidity is permanently locked, this action cannot be reversed
- The owner can still collect fees from permanently locked liquidity
refreshVesting
Refreshes vesting status of a position to unlock available liquidity. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Call this function to update the vesting state and unlock available liquidity
- Should be called periodically to ensure liquidity is properly unlocked
- If all liquidity is unlocked, the vesting account remains but is no longer used
- Must be called before removing liquidity if position has vesting accounts
claimPositionFee
Claims accumulated fees for a position. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Fees are collected when trades occur in the pool
- Only the position owner can claim fees
- Fees are earned on both token A and token B based on the amount of liquidity provided
- Fees accumulate over time and should be claimed periodically
- The SDK handles wrapping/unwrapping of SOL automatically
claimPositionFee2
Claims accumulated fees for a position. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Fees are collected when trades occur in the pool
- Only the position owner can claim fees
- Fees will claim to receiver address
- Fees are earned on both token A and token B based on the amount of liquidity provided
- The SDK handles wrapping/unwrapping of SOL automatically
claimPartnerFee
Claims partner fee rewards. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Partner fees are a portion of trading fees directed to a specific account
- Only the configured partner address can claim these fees
- Partner fees must be enabled in the pool configuration
- The SDK handles wrapping/unwrapping of SOL automatically
- Token accounts are created automatically if they don’t exist
claimReward
Claims reward tokens from a position. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Pools can have multiple reward tokens configured
- The rewardIndex parameter specifies which reward token to claim
- Rewards accrue based on the amount of liquidity provided and duration
- Only the position owner can claim rewards
- The SDK handles wrapping/unwrapping of SOL automatically
closePosition
Closes a position with no liquidity. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- Position must have zero liquidity before closing
- Use
removeAllLiquidity
first if the position still has liquidity - Closing a position returns the rent to the owner
- This function only closes the position account, not the NFT
- For a full cleanup, use
removeAllLiquidityAndClosePosition
instead
splitPosition
Splits a position into two positions. FunctionTxBuilder
) that can be used to build, sign, and send the transaction.
Example
- The first position must already exist for that pool
- The second position can be a new empty position for that same pool
State Functions
fetchConfigState
Fetches the Config state of the program. Functionconfig
: Public key of the config account.
- Throws an error if the config account does not exist
fetchPoolState
Fetches the Pool state. Functionpool
: Public key of the pool.
- Throws an error if the pool account does not exist
- Contains all essential information about the pool including prices, liquidity, and fees
fetchPositionState
Fetches the Position state. Functionposition
: Public key of the position.
- Throws an error if the position account does not exist
- Contains information about liquidity amounts, fee collection, and rewards
getAllConfigs
Retrieves all config accounts. FunctiongetAllPools
Retrieves all pool accounts. FunctiongetAllPositions
Retrieves all position accounts. FunctiongetAllPositionsByPool
Gets all positions for a specific pool. Functionpool
: Public key of the pool.
getUserPositionByPool
Gets all positions of a user for a specific pool. Functionpool
: Public key of the pool.user
: Public key of the user.
getPositionsByUser
Gets all positions of a user across all pools. Functionuser
: Public key of the user.
- Positions are sorted by total liquidity in descending order
- Returns position NFT accounts, position addresses, and full position states
getAllVestingsByPosition
Retrieves all vesting accounts associated with a position. Functionposition
: Public key of the position.
isLockedPosition
Checks if a position has any locked liquidity. Functionposition
: The position state.
isPoolExist
Checks if a pool exists. Functionpool
: Public key of the pool.
Helper Functions
preparePoolCreationParams
Prepares parameters required for pool creation, including initial sqrt price and liquidity. FunctioninitSqrtPrice
: The initial sqrt price in Q64 formatliquidityDelta
: The initial liquidity in Q64 format
- This function calculates the correct initial price and liquidity based on the token amounts
- Both token amounts must be greater than zero
- The function handles Token2022 transfer fees if token info is provided
isVestingComplete
Checks if a vesting schedule is ready for full release. FunctionvestingData
: The vesting account state datacurrentPoint
: Current timestamp or slot number
- This function checks if the current point (timestamp or slot) has passed the end of the vesting schedule
- The end point is calculated as: cliffPoint + (periodFrequency * numberOfPeriods)
- Returns true if currentPoint >= endPoint, false otherwise
- Useful to determine if a position can be fully unlocked
getTotalLockedLiquidity
Gets the total amount of liquidity in the vesting schedule. FunctionvestingData
: The vesting account state data
- Calculates the sum of cliff unlock liquidity and periodic unlock liquidity
- Formula: cliffUnlockLiquidity + (liquidityPerPeriod * numberOfPeriod)
- This is the total amount of liquidity that was initially locked in the vesting schedule
- Does not account for already released liquidity
getAvailableVestingLiquidity
Calculates the available liquidity to withdraw based on vesting schedule. FunctionvestingData
: The vesting account state datacurrentPoint
: Current timestamp or slot number
getMaxAmountWithSlippage
Calculates the maximum amount after applying a slippage rate. Functionamount
: The base amount as a BNrate
: The slippage rate as a percentage (e.g., 0.5 for 0.5%)
- Used when you need to calculate the upper bound of an amount with slippage tolerance
- Formula: amount * (100 + rate) / 100
- Common use case: Setting a maximum deposit amount when adding liquidity
- Slippage rate is expressed as a percentage and supports up to 2 decimal places
getMinAmountWithSlippage
Calculates the minimum amount after applying a slippage rate. Functionamount
: The base amount as a BNrate
: The slippage rate as a percentage (e.g., 0.5 for 0.5%)
- Used when you need to calculate the lower bound of an amount with slippage tolerance
- Formula: amount * (100 - rate) / 100
- Common use case: Setting a minimum output amount when swapping tokens
- Slippage rate is expressed as a percentage and supports up to 2 decimal places
getPriceImpact
Calculates the price impact as a percentage. FunctionactualAmount
: The actual amount after slippage in token unitsidealAmount
: The theoretical amount without slippage in token units
- Used to express how much a transaction will affect the price
- Formula: ((idealAmount - actualAmount) / idealAmount) * 100
- Higher price impact indicates a greater effect on the market price
- Common use case: Showing users the effect of their swap on the pool
Price Conversion Utilities
getPriceFromSqrtPrice
Converts a sqrt price in Q64 format to a human-readable price. FunctionsqrtPrice
: The sqrt price in Q64 formattokenADecimal
: The number of decimals for token AtokenBDecimal
: The number of decimals for token B
- Converts the internal sqrt price representation to a human-readable price
- Formula: (sqrtPrice >> 64)^2 * 10^(tokenADecimal - tokenBDecimal)
- The result represents the price of token B in terms of token A
- Useful for displaying current pool prices to users
getSqrtPriceFromPrice
Converts a human-readable price to a sqrt price in Q64 format. Functionprice
: The price as a string in human-readable formattokenADecimal
: The number of decimals for token AtokenBDecimal
: The number of decimals for token B
- Converts a human-readable price to the internal sqrt price representation
- Formula:
sqrt(price / 10^(tokenADecimal - tokenBDecimal)) << 64
- Useful when creating pools with a specific initial price
- Can be used to define price boundaries for concentrated liquidity positions
Fee Calculation Utilities
getUnClaimReward
Calculates unclaimed fees and rewards for a position. FunctionpoolState
: The current state of the poolpositionState
: The current state of the position
feeTokenA
: Unclaimed fees in token AfeeTokenB
: Unclaimed fees in token Brewards
: Array of unclaimed reward amounts for each reward token
getBaseFeeNumerator
Calculates the current base fee numerator based on the configured fee scheduler mode and elapsed periods. FunctionfeeSchedulerMode
: The fee reduction mode (Linear or Exponential)cliffFeeNumerator
: The initial maximum fee numerator (starting point)period
: The number of elapsed periods since fee reduction beganreductionFactor
: The rate of fee reduction per period
BN
: The calculated base fee numerator for the current period
getDynamicFeeNumerator
Calculates a dynamic fee component based on market volatility FunctionvolatilityAccumulator
: Accumulated measure of market volatility over timebinStep
: The price bin step size used in the liquidity distribution systemvariableFeeControl
: Control parameter that determines how much volatility affects fees
BN
: The calculated dynamic fee numerator- Returns
0
ifvariableFeeControl
is zero (dynamic fees disabled)
bpsToFeeNumerator
Converts basis points to fee numerator format. Mathematical FormulafeeNumeratorToBps
Converts fee numerator back to basis points. Mathematical FormulagetBaseFeeParams
Calculates the initial parameters for a base fee Key Features- Supports both linear and exponential fee reduction
- Validates parameter consistency
- Calculates period frequency and reduction factors
getDynamicFeeParams
Calculates the parameters needed for dynamic fee. Key Features- Configures volatility-based fee parameters
- Sets maximum price change thresholds
- Calculates variable fee control parameters