Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.meteora.ag/llms.txt

Use this file to discover all available pages before exploring further.

This page is based on the public ts-client source for @meteora-ag/dlmm. The package exports the DLMM class as its default export, plus helper modules, constants, IDL types, account filters, and low-level wrappers.
import DLMM, {
  ActivationType,
  CollectFeeMode,
  ConcreteFunctionType,
  PairType,
  ResizeSide,
  StrategyType,
  deriveBinArray,
  getBinArrayIndexesCoverage,
} from "@meteora-ag/dlmm"

Dependencies

Important runtime dependencies:
PackageUse
@coral-xyz/anchorProgram client, BN, IDL-derived types.
@solana/web3.jsConnections, transactions, instructions, public keys.
@solana/spl-tokenATA creation, Token and Token-2022 account handling, transfer fee and transfer hook data.
decimal.jsPrice, fee, and UI conversion arithmetic.

Program IDs

LBCLMM_PROGRAM_IDS = {
  devnet: "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo",
  localhost: "LbVRzDTvBDEcrthxfZ4RL6yiq3uZw8bS6MwtdY6UhFQ",
  "mainnet-beta": "LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo",
}
localhost is an SDK constant for local test harnesses. Pass opt to most static methods and DLMM.create when you need a non-default cluster or program ID:
type Opt = {
  cluster?: Cluster | "localhost"
  programId?: PublicKey
  skipSolWrappingOperation?: boolean
}
skipSolWrappingOperation is useful when another integration, such as a zap flow, manages wrapped SOL accounts itself.

Core Types

TypeDescription
ClmmProgramAnchor Program<LbClmm>.
LbPair, LbPairAccountPool account state and Anchor account wrapper.
Bin, BinArray, BinArrayAccountBin and bin array state.
BinArrayBitmapExtensionAccountBitmap extension account wrapper.
PositionV2, LbPosition, PositionInfo, PositionDataPosition account and SDK-normalized position data.
LimitOrder, ParsedLimitOrderWithPubkeyLimit order account and parsed SDK view.
TokenReserveMint, reserve, raw balance, token program owner, and transfer-hook metas.
SwapQuote, SwapQuoteExactOutExact-in and exact-out quote result types.
FeeInfo, EmissionRateCurrent pool fee and reward emission views.
StrategyParametersPosition/liquidity strategy input.
interface StrategyParameters {
  maxBinId: number
  minBinId: number
  strategyType: StrategyType
  singleSidedX?: boolean
}

Enums

EnumValues
StrategyTypeSpot, Curve, BidAsk
ActivationTypeSlot, Timestamp
PairTypePermissionless, Permissioned, CustomizablePermissionless, PermissionlessV2
PairStatusEnabled, Disabled
FunctionTypeUndetermined, LiquidityMining, LimitOrder
ConcreteFunctionTypeLimitOrder, LiquidityMining
CollectFeeModeInputOnly, OnlyY
PositionVersionV1, V2
ShrinkModeShrinkBoth, NoShrinkLeft, NoShrinkRight, NoShrinkBoth
ResizeSideLower, Upper
ActionTypeLiquidity, Reward

Important Constants

ConstantMeaning
BASIS_POINT_MAX10000. Used for bps calculations.
FEE_PRECISIONProgram fee precision.
MAX_FEE_RATEMaximum fee rate in program precision.
BIN_ARRAY_DEFAULT_VERSIONCurrent bin array layout version.
MAX_BINS_PER_POSITION / POSITION_MAX_LENGTHMaximum dynamic position width.
MAX_RESIZE_LENGTHMaximum position resize increment per instruction.
DEFAULT_BIN_PER_POSITIONBase position width before dynamic extension data.
MAX_BIN_LENGTH_ALLOWED_IN_ONE_TXThreshold used by legacy weight flows before splitting transactions.
MAX_EXTRA_BIN_ARRAYSMaximum extra bin arrays quote helpers may include.
MAX_BIN_PER_LIMIT_ORDERMaximum bins allowed in one limit order account.
LIMIT_ORDER_FEE_SHAREProgram constant for limit order fee share.
MAX_CLAIM_ALL_ALLOWEDClaim-all transaction chunk size.
The SDK also exports approximate rent constants such as BIN_ARRAY_FEE, POSITION_FEE, POOL_FEE, TOKEN_ACCOUNT_FEE, and BIN_ARRAY_BITMAP_FEE, plus BN versions of those amounts.

Creating A Client

DLMM.create

static create(
  connection: Connection,
  dlmm: PublicKey,
  opt?: Opt,
): Promise<DLMM>
Creates one hydrated DLMM pool client. It fetches:
  • LbPair
  • BinArrayBitmapExtension, if initialized
  • SYSVAR_CLOCK
  • reserve token accounts
  • token X/Y mint accounts
  • reward vaults and reward mint accounts
  • Token-2022 transfer-hook extra account metas for pool and reward mints
const pool = await DLMM.create(connection, poolAddress, {
  cluster: "mainnet-beta",
})

DLMM.createMultiple

static createMultiple(
  connection: Connection,
  dlmmList: PublicKey[],
  opt?: Opt,
): Promise<DLMM[]>
Batch version of create. Prefer this for dashboards, portfolio pages, routing, or any flow loading multiple pools. It batches pool, reserve, mint, reward, bitmap, and transfer-hook reads.

Static Discovery Methods

MethodSignatureDescription
getLbPairs(connection, opt?) =&gt; Promise&lt;LbPairAccount[]&gt;Fetches all LbPair accounts from the configured program. Requires RPC support for getProgramAccounts.
getPairPubkeyIfExists`(connection, tokenX, tokenY, binStep, baseFactor, baseFeePowerFactor, concreteFunctionType?, collectFeeMode?, opt?) => Promise<PublicKeynull>`Checks v2 PDA, legacy PDA, and PresetParameter2-derived candidate pool addresses.
getCustomizablePermissionlessLbPairIfExists`(connection, tokenX, tokenY, opt?) => Promise<PublicKeynull>`Checks the customizable permissionless pool PDA for a token pair.
getAllPresetParameters(connection, opt?) =&gt; Promise&lt;{ presetParameter; presetParameter2 }&gt;Fetches legacy and v2 preset parameter accounts.
getAllLbPairPositionsByUser(connection, userPubKey, opt?, getPositionsOpt?) =&gt; Promise&lt;Map&lt;string, PositionInfo&gt;&gt;Fetches every PositionV2 owned by a user, groups by pool, loads bin arrays and pool accounts, and returns processed position data.
getPricePerLamport(baseTokenDecimal, quoteTokenDecimal, price) =&gt; stringConverts UI price to price-per-lamport.
getBinIdFromPrice(price, binStep, min) =&gt; numberConverts price to bin ID. min controls rounding side.
calculateFeeInfo(baseFactor, binStep, protocolShare, baseFeePowerFactor?) =&gt; FeeInfoComputes base/max/protocol fee percentages from fee parameters.
updateVolatilityAccumulator(vParameter, sParameter, activeId) =&gt; voidIn-memory helper used by quote simulation.
updateReference(activeId, vParameter, sParameter, currentTimestamp) =&gt; voidIn-memory helper used by quote simulation.
getPositionsOpt supports chunked position loading:
type GetPositionsOpt = {
  chunkSize?: number
  onChunkFetched?: ChunkCallback
  isParallelExecution?: boolean
}

Pool Creation Methods

Creation helpers return unsigned Transaction objects. The caller still signs and sends.
MethodUnderlying instructionToken supportNotes
createLbPairinitialize_lb_pairSPL Token onlyLegacy permissionless creation. Requires binStep, baseFactor, and legacy presetParameter.
createLbPair2initialize_lb_pair2SPL Token and Token-2022Current permissionless path. Reads PresetParameter2, token badges, token program IDs, and derives pool PDA from preset parameter.
createCustomizablePermissionlessLbPairinitialize_customizable_permissionless_lb_pairSPL Token onlyCreator-configurable pool. Throws if computed base fee power factor overflows legacy path.
createCustomizablePermissionlessLbPair2initialize_customizable_permissionless_lb_pair2SPL Token and Token-2022Current customizable path. Supports ConcreteFunctionType and CollectFeeMode.

createLbPair2

static createLbPair2(
  connection: Connection,
  funder: PublicKey,
  tokenX: PublicKey,
  tokenY: PublicKey,
  presetParameter: PublicKey,
  activeId: BN,
  opt?: Opt,
): Promise<Transaction>
Use this for new permissionless pools when you already know the PresetParameter2 account.

createCustomizablePermissionlessLbPair2

static createCustomizablePermissionlessLbPair2(
  connection: Connection,
  binStep: BN,
  tokenX: PublicKey,
  tokenY: PublicKey,
  activeId: BN,
  feeBps: BN,
  activationType: ActivationType,
  hasAlphaVault: boolean,
  creatorKey: PublicKey,
  activationPoint?: BN,
  creatorPoolOnOffControl?: boolean,
  concreteFunctionType?: ConcreteFunctionType,
  collectFeeMode?: CollectFeeMode,
  opt?: Opt,
): Promise<Transaction>
Defaults:
  • concreteFunctionType: ConcreteFunctionType.LimitOrder
  • collectFeeMode: CollectFeeMode.InputOnly
  • creatorPoolOnOffControl: false
When either token is native SOL and skipSolWrappingOperation is not set, the SDK adds temporary wrap and unwrap instructions.

Instance State

Each DLMM instance exposes these public fields:
FieldTypeDescription
pubkeyPublicKeyPool address.
programClmmProgramAnchor program client.
lbPairLbPairCurrent pool account state.
binArrayBitmapExtension`BinArrayBitmapExtensionAccountnull`Bitmap extension account if present.
tokenX, tokenYTokenReservePool token mint/reserve metadata.
rewards`(TokenReservenull)[]`Up to two reward token reserves.
clockClockClock state loaded when the client was created/refetched.
Call refetchStates() after sending transactions if you need the client to reflect current pool state.

Reading Pool State

MethodSignatureDescription
refetchStates() =&gt; Promise&lt;void&gt;Reloads pool, bitmap, reserves, rewards, token mints, transfer hooks, and clock.
getLbPairLockInfo(lockDurationOpt?, getPositionsOpt?) =&gt; Promise&lt;PairLockInfo&gt;Finds positions whose lockReleasePoint is greater than the current slot/timestamp plus optional duration.
getBinArrays() =&gt; Promise&lt;BinArrayAccount[]&gt;Fetches initialized bin arrays tracked by pool bitmap and bitmap extension.
getBinArrayForSwap(swapForY, count?) =&gt; Promise&lt;BinArrayAccount[]&gt;Fetches bin arrays from the active bin in the swap direction.
getBinsAroundActiveBin(numberOfBinsToTheLeft, numberOfBinsToTheRight) =&gt; Promise&lt;{ activeBin; bins }&gt;Reads a window of bins around activeId.
getBinsBetweenMinAndMaxPrice(minPrice, maxPrice) =&gt; Promise&lt;BinLiquidity[]&gt;Reads bins in a UI price range.
getBinsBetweenLowerAndUpperBound(lowerBinId, upperBinId) =&gt; Promise&lt;BinLiquidity[]&gt;Reads bins in an absolute bin range.
getActiveBin() =&gt; Promise&lt;BinLiquidity&gt;Returns processed active-bin liquidity.
getFeeInfo() =&gt; FeeInfoReturns base, max, and protocol fee percentages.
getDynamicFee() =&gt; DecimalReturns current variable fee percentage.
getEmissionRate() =&gt; EmissionRateReturns reward emissions for reward slots.
getOracle() =&gt; Promise&lt;IDynamicOracle&gt;Wraps the oracle account for observation and TWAP reads.
increaseOracleLength(lengthToAdd, funder) =&gt; Promise&lt;Transaction&gt;Builds a transaction to increase oracle account length.

Price Helpers

MethodDescription
toPricePerLamport(price)Converts UI token price using the pool token decimals.
fromPricePerLamport(pricePerLamport)Converts price-per-lamport into UI token price.
getBinIdFromPrice(price, min)Pool-aware bin ID conversion using the pool binStep.
getMaxPriceInBinArrays(binArrayAccounts)Finds the max price with token X liquidity in a set of bin arrays.
Example:
const activeBin = await pool.getActiveBin()
const price = pool.fromPricePerLamport(Number(activeBin.price))
const binId = pool.getBinIdFromPrice(Number(price), true)

Positions

Querying Positions

MethodSignatureDescription
getPosition(positionPubKey) =&gt; Promise&lt;LbPosition&gt;Fetches one position, loads covered bin arrays, and returns processed balances, fees, rewards, and per-bin data.
getPositionsByUserAndLbPair(userPubKey?, getPositionsOpt?) =&gt; Promise&lt;{ activeBin; userPositions }&gt;Fetches user positions for this pool. If no user is provided, returns only activeBin and an empty array.
DLMM.getAllLbPairPositionsByUserStaticFetches positions across all pools and returns a map keyed by pool address.
PositionData includes:
  • total token X/Y amounts
  • per-bin position data
  • fees and rewards
  • transfer-fee-excluded amounts
  • owner and fee owner
  • claimed fee/reward totals

Creating Positions

MethodSignatureDescription
createEmptyPosition({ positionPubKey, minBinId, maxBinId, user }) =&gt; Promise&lt;Transaction&gt;Initializes a legacy-width position and needed bin arrays.
createExtendedEmptyPosition(lowerBinId, upperBinId, position, owner) =&gt; Promise&lt;Transaction&gt;Creates a position and adds extension instructions for wide ranges.
initializePositionByOperator({ lowerBinId, positionWidth, owner, feeOwner, base, operator, payer, lockReleasePoint }) =&gt; Promise&lt;Transaction&gt;Creates an operator-managed PDA position with fee owner and lock release point.
quoteCreatePosition({ strategy }) =&gt; Promise&lt;QuoteCreatePositionResult&gt;Estimates position count, position rent, realloc cost, bitmap extension cost, bin array count, and transaction count.
quoteExtendPosition(currentMinBinId, currentMaxBinId, binCountToExpand) =&gt; Promise&lt;{ positionExtendCost; binArrayCost }&gt;Estimates rent and bin array costs for extension.

Resizing And Closing Positions

MethodDescription
increasePositionLength(position, side, length, funder, allowParallelExecution?)Builds one or more transactions to extend lower or upper side. The final width is capped at POSITION_MAX_LENGTH.
decreasePositionLength(position, side, length, allowParallelExecution?)Builds one or more transactions to shrink an empty lower or upper segment. The position keeps at least one bin.
closePosition({ owner, position })Closes a position with closePosition2.
closePositionIfEmpty({ owner, position })Closes only when empty; otherwise the program no-ops/fails according to program rules.
enablePositionPermissionlessClaimFee({ position, owner })Sets the position permission bit for permissionless fee claiming.

Liquidity

Strategy-Based Liquidity

MethodReturnDescription
initializePositionAndAddLiquidityByStrategy(params)Promise&lt;Transaction&gt;Initializes a position, initializes needed bin arrays, creates ATAs, handles SOL wrapping, and calls addLiquidityByStrategy2.
initializeMultiplePositionAndAddLiquidityByStrategy(...)Promise&lt;InitializeMultiplePositionAndAddLiquidityByStrategyResponse&gt;Splits a range across multiple base-width positions and returns grouped instructions.
initializeMultiplePositionAndAddLiquidityByStrategy2(...)Promise&lt;InitializeMultiplePositionAndAddLiquidityByStrategyResponse2&gt;Current multi-position path. Supports extended positions, optional ALT, and chunked transaction instruction groups.
addLiquidityByStrategy(params)Promise&lt;Transaction&gt;Adds liquidity to an existing position using addLiquidityByStrategy2.
addLiquidityByStrategyChunkable(params)Promise&lt;Transaction[]&gt;Adds strategy liquidity with chunked transaction output. Can auto-expand through rebalance endpoint.
params for single-position strategy flows:
type TInitializePositionAndAddLiquidityParamsByStrategy = {
  positionPubKey: PublicKey
  totalXAmount: BN
  totalYAmount: BN
  strategy: StrategyParameters
  user: PublicKey
  slippage?: number
}

Weight-Based Liquidity

MethodReturnDescription
initializePositionAndAddLiquidityByWeight(params)`Promise<TransactionTransaction[]>`Deprecated legacy path. Initializes a position and deposits explicit bin weights.
addLiquidityByWeight(params)`Promise<TransactionTransaction[]>`Legacy explicit-weight deposit path.
addLiquidityByWeight2(params, binPerChunk?)Promise&lt;Transaction[]&gt;Current chunked weight deposit path for existing positions. Validates the deposit range is inside the position range.
Weight params:
type TInitializePositionAndAddLiquidityParams = {
  positionPubKey: PublicKey
  totalXAmount: BN
  totalYAmount: BN
  xYAmountDistribution: BinAndAmount[]
  user: PublicKey
  slippage?: number
}

Removing Liquidity

removeLiquidity({
  user,
  position,
  fromBinId,
  toBinId,
  bps,
  shouldClaimAndClose = false,
  skipUnwrapSOL = false,
}): Promise<Transaction[]>
The SDK:
  • trims requested range to bins with liquidity, fees, or rewards
  • creates owner and fee-owner ATAs
  • optionally claims fees and rewards
  • optionally closes the position if empty
  • chunks by bin range
  • uses removeLiquidityByRange2

Swaps

Quote Methods

MethodSignatureDescription
swapQuote(inAmount, swapForY, allowedSlippage, binArrays, isPartialFill?, maxExtraBinArrays?) =&gt; SwapQuoteExact-in quote. swapForY = true means token X to token Y. Slippage is bps.
swapQuoteExactOut(outAmount, swapForY, allowedSlippage, binArrays, maxExtraBinArrays?) =&gt; SwapQuoteExactOutExact-out quote. Returns max input amount after slippage.
Quote result fields:
FieldExact inExact outDescription
consumedInAmountYesNoInput amount actually consumed, transfer-fee included.
inAmountNoYesRequired input amount.
outAmountYesYesOutput amount, transfer-fee adjusted where applicable.
feeYesYesSwap fee amount.
protocolFeeYesYesProtocol fee amount.
minOutAmountYesNoMinimum output after slippage.
maxInAmountNoYesMaximum input after slippage.
priceImpactYesYesPrice impact as Decimal.
binArraysPubkeyYesYesBin arrays to pass into swap transaction builder.
endPriceYesNoEnd bin price after simulated exact-in swap.
feeOnInputYesNoWhether fees are collected on input for this direction.

Transaction Builders

MethodInstructionDescription
swap(params)swap2Exact-in swap transaction.
swapExactOut(params)swap_exact_out2Exact-out swap transaction. Uses a fixed 1_400_000 CU limit.
swapWithPriceImpact(params)swap_with_price_impact2Exact-in style swap with price-impact bps guard.
const binArrays = await pool.getBinArrayForSwap(true)
const quote = pool.swapQuote(new BN(1_000_000), true, new BN(50), binArrays)

const tx = await pool.swap({
  inToken: pool.tokenX.publicKey,
  outToken: pool.tokenY.publicKey,
  inAmount: quote.consumedInAmount,
  minOutAmount: quote.minOutAmount,
  lbPair: pool.pubkey,
  user: wallet.publicKey,
  binArraysPubkey: quote.binArraysPubkey,
})
The swap builders create missing ATAs, handle wrapped SOL unless disabled, add Token-2022 transfer-hook remaining accounts, and pass bin arrays as remaining writable accounts.

Fees And Rewards

MethodReturnDescription
claimSwapFee({ owner, position })Promise&lt;Transaction[]&gt;Claims swap fees for one position. Throws if there are no fees.
claimAllSwapFee({ owner, positions })Promise&lt;Transaction[]&gt;Claims swap fees for multiple positions. Chunks by MAX_CLAIM_ALL_ALLOWED.
claimLMReward({ owner, position })Promise&lt;Transaction[]&gt;Claims liquidity mining rewards for one position. Throws if no rewards.
claimAllLMRewards({ owner, positions })Promise&lt;Transaction[]&gt;Claims LM rewards for multiple positions.
claimAllRewardsByPosition({ owner, position })Promise&lt;Transaction[]&gt;Claims fees and rewards for a single position.
claimAllRewards({ owner, positions })Promise&lt;Transaction[]&gt;Claims fees and rewards across multiple positions.
The claim builders create token accounts as needed and use Token-2022 transfer-hook remaining accounts for pool tokens and reward tokens.

Limit Orders

Limit order methods are available for pools that support limit orders.

Query Methods

MethodReturnDescription
getLimitOrder(limitOrder)`Promise<ParsedLimitOrderWithPubkeynull>`Fetches and parses one limit order account.
getLimitOrderByUserAndLbPair(user)Promise&lt;ParsedLimitOrderWithPubkey[]&gt;Fetches parsed limit orders for the user and current pool.
quoteCreateLimitOrder({ bins, relativeBin? })Cost quoteEstimates limit order rent, uninitialized bin arrays, bitmap extension cost.
relativeBin treats each bin.id as an offset from current activeId.

Transaction Builders

MethodDescription
placeLimitOrder({ owner, payer, sender, limitOrder, params })Creates bin arrays if needed, optionally initializes bitmap extension, wraps SOL if needed, and calls place_limit_order.
cancelLimitOrder({ limitOrderPubkey, owner, rentReceiver, binIds })Cancels bins, creates owner ATAs, unwraps SOL if needed, and appends close_limit_order_if_empty.
closeLimitOrderIfEmpty({ limitOrder, owner, rentReceiver })Closes an empty limit order account.
placeLimitOrder accepts params: Omit&lt;PlaceLimitOrderParams, "padding"&gt;; the SDK injects padding.

Rebalancing

Rebalance helpers simulate a desired position update off-chain, then build a rebalance_liquidity instruction.
MethodDescription
simulateRebalancePositionWithBalancedStrategy(positionAddress, positionData, strategy, topUpAmountX, topUpAmountY, xWithdrawBps, yWithdrawBps)Builds balanced strategy parameters and simulates deposits/withdrawals.
simulateRebalancePosition(positionAddress, positionData, shouldClaimFee, shouldClaimReward, deposits, withdraws)Low-level simulation for custom rebalance parameters.
rebalancePosition(rebalancePositionResponse, maxActiveBinSlippage, rentPayer?, slippage?)Builds initialization instructions for missing bin arrays and the final rebalance instruction group.
Returned simulation data includes:
  • rebalancePosition
  • simulationResult
  • binArrayExistence
  • binArrayCount
  • binArrayCost
  • bitmapExtensionCost
rebalancePosition returns:
{
  initBinArrayInstructions: TransactionInstruction[]
  rebalancePositionInstruction: TransactionInstruction[]
}

Seed Liquidity

Seed liquidity helpers are for launch/operator workflows and return instruction groups rather than ready-to-send signed transactions.
MethodReturnDescription
seedLiquidity(owner, seedAmount, curvature, minPrice, maxPrice, base, payer, feeOwner, operator, lockReleasePoint, shouldSeedPositionOwner?)Promise&lt;SeedLiquidityResponse&gt;Creates grouped instructions for owner proof, bin array/position initialization, and one-sided precise deposits across a price range.
seedLiquiditySingleBin(payer, base, seedAmount, price, roundingUp, positionOwner, feeOwner, operator, lockReleasePoint, shouldSeedPositionOwner?)Promise&lt;SeedLiquiditySingleBinResponse&gt;Seeds token X into one bin and initializes bin array/position if needed.
SeedLiquidityResponse groups instructions for parallel/sequential execution:
FieldDescription
sendPositionOwnerTokenProveIxsOptional owner proof instructions.
initializeBinArraysAndPositionIxsGrouped setup instructions.
addLiquidityIxsGrouped deposit instructions.
costBreakdownEstimated rent/lamport costs.

Bin Arrays

MethodDescription
initializeBinArrays(binArrayIndexes, funder)Returns instructions to initialize missing bin arrays, with compute-budget instruction prepended if needed.
getBinArrays()Fetch all initialized bin arrays for the pool.
getBinArrayForSwap(swapForY, count?)Fetch bin arrays in the swap direction.
initialize_bin_array is compute-heavy because it initializes bin prices. Use the SDK helper or add compute budget manually in custom flows.

Pool Controls

MethodDescription
setPairStatusPermissionless(enabled, creator)Creator-controlled status transaction for eligible customizable permissionless pools.
setPairStatus(enabled)Builds admin/creator pair status transaction using lbPair.creator as fee payer/signing account.
setActivationPoint(activationPoint)Builds activation point transaction using lbPair.creator.
isSwapDisabled(swapInitiator)Local check for disabled status, permissioned/customizable activation point, and pre-activation swap address.
canSyncWithMarketPrice(marketPrice, activeBinId)Checks whether active bin can be moved to market price without crossing liquidity.
syncWithMarketPrice(marketPrice, owner)Builds go_to_a_bin transaction and initializes bitmap extension when needed.

Token-2022 Support

The SDK automatically detects token program ownership when DLMM.create or createMultiple loads a pool. It also fetches transfer-hook extra account metas for token X, token Y, and reward mints. Internally, transaction builders use:
getPotentialToken2022IxDataAndAccounts(actionType, rewardIndex?)
This returns RemainingAccountsInfoSlice[] and account metas for Token-2022 transfer hooks. Public Token-2022 helper exports include:
HelperDescription
getPotentialToken2022IxDataAndAccounts(actionType, rewardIndex?)Instance helper that returns remaining-account slices and metas for Token-2022 transfer hooks used by liquidity, swap, fee, and reward flows.
calculateTransferFeeIncludedAmount(amount, mint, epoch)Grosses up an amount so the receiver gets the intended net amount after transfer fee.
calculateTransferFeeExcludedAmount(amount, mint, epoch)Calculates net amount after transfer fee.
getExtraAccountMetasForTransferHook(connection, mint, mintAccount)Reads transfer-hook extra account metas for one mint.
getMultipleMintsExtraAccountMetasForTransferHook(connection, mintAccounts)Batch version used by createMultiple.

Helper Exports

PDA Helpers

HelperDescription
derivePresetParameterWithIndexDerives PresetParameter2 with index key.
deriveLbPairWithPresetParamWithIndexKeyDerives v2 pool PDA from preset parameter key and token mints.
derivePresetParameter, derivePresetParameter2Derive preset parameter accounts.
deriveLbPair, deriveLbPair2Derive legacy/v2 pool PDAs.
deriveCustomizablePermissionlessLbPair, derivePermissionLbPairDerive pool PDAs for specialized pool types.
deriveOracle, derivePosition, deriveBinArray, deriveReserve, deriveRewardVaultDerive common pool accounts.
deriveTokenBadge, deriveOperator, deriveEventAuthorityDerive program support accounts.

Bin Array Helpers

HelperDescription
binIdToBinArrayIndexConverts a bin ID to bin array index.
deriveBinArrayBitmapExtensionDerives the bitmap extension account for a pool.
getBinArrayLowerUpperBinIdReturns lower/upper bin IDs for a bin array index.
isBinIdWithinBinArrayChecks whether a bin belongs to a bin array.
getBinFromBinArrayReturns one bin from a loaded bin array.
isOverflowDefaultBinArrayBitmapChecks if a bin array index requires bitmap extension.
findNextBinArrayIndexWithLiquidityFinds next initialized bin array with liquidity in a direction.
findNextBinArrayWithLiquiditySame, but returns an account from loaded bin arrays.
getBinArraysRequiredByPositionRangeReturns bin array PDAs required for a position range.
getBinIdIndexInBinArrayConverts bin ID to its index inside a bin array.
binDeltaToMinMaxBinIdConverts a bin delta around an active bin into min/max bin IDs.
decodeRewardPerTokenStoredDecodes reward-per-token state from a bin.
enumerateBinsIterates bins across loaded bin arrays.
getBinArrayInfoForNonContiguousBinIdsReturns bin array metas and bitmap account for arbitrary bin IDs.

Position Helpers

HelperDescription
wrapPositionWraps raw account data in a position wrapper.
getBinArrayIndexesCoverage, getBinArrayKeysCoverage, getBinArrayAccountMetasCoverageDerive bin array coverage for ranges.
getPositionLowerUpperBinIdWithLiquidityTrims a position range to bins with liquidity.
isPositionNoFee, isPositionNoRewardChecks whether processed position data has claimable fees/rewards.
chunkBinRangeIntoExtendedPositions, chunkBinRange, chunkPositionBinRangeSplits bin ranges for transaction and dynamic-position limits.
calculatePositionSize, getPositionRentExemption, getPositionExpandRentExemptionRent and account-size helpers.
getExtendedPositionBinCount, decodeExtendedPositionDynamic position data helpers.

Strategy And Weight Helpers

HelperDescription
getPriceOfBinByBinIdConverts a bin ID and bin step to a decimal price.
calculateSpotDistributionBuilds spot weight distribution.
calculateBidAskDistributionBuilds bid/ask weight distribution.
calculateNormalDistributionBuilds curve/normal distribution.
toAmountsBothSideByStrategyConverts strategy into token amounts per bin.
autoFillYByStrategy, autoFillXByStrategyCalculates missing side amount for strategy deposits.
toStrategyParametersConverts SDK strategy enum into program strategy parameters.
toWeightDistributionConverts bps distributions into program weights.
fromWeightDistributionToAmount, fromWeightDistributionToAmountOneSideConverts weights back to token amounts.
toAmountBidSide, toAmountAskSide, toAmountBothSideLower-level helpers for converting weight distribution to token amounts by side.
autoFillYByWeight, autoFillXByWeightCalculates missing side amount for weight deposits.

Fee And Math Helpers

HelperDescription
getBaseFee, getVariableFee, getTotalFeeFee rate helpers.
computeFee, computeFeeFromAmount, computeProtocolFeeFee amount helpers.
getExcludedFeeAmount, getIncludedFeeAmount, splitFeeFee-inclusive/exclusive calculations.
computeBaseFactorFromFeeBpsConverts fee bps into base factor and base fee power factor.
getQPriceFromId, getQPriceBaseFactorQ64.64 price helpers.
mulShr, shlDiv, mulDiv, powFixed-point arithmetic helpers.
getC, distributeAmountToCompressedBinsByRatioSeed-liquidity and compression math helpers.
generateAmountForBinRange, generateBinAmount, compressBinAmount, findOptimumDecompressMultiplierSeed liquidity compression helpers.

RPC And Transaction Helpers

HelperDescription
chunks, rangeArray utilities.
chunkedFetchMultiplePoolAccount, chunkedFetchMultipleBinArrayBitmapExtensionAccountBatched account fetch helpers.
chunkedGetMultipleAccountInfos, chunkedGetProgramAccountsRPC-safe batched reads.
getTokenDecimals, getTokenBalanceToken account reads.
getOrCreateATAInstructionReturns ATA address and optional create instruction.
wrapSOLInstruction, unwrapSOLInstructionNative SOL wrapping helpers.
parseLogsParses Anchor events from transaction logs.
getEstimatedComputeUnitUsageWithBuffer, getEstimatedComputeUnitIxWithBufferSimulation-based compute budget helpers.
getDefaultExtendPositionCU, getSimulationComputeUnitsLower-level compute unit helpers.
createProgram, decodeAccount, getAccountDiscriminatorAnchor program/account helpers.
capSlippagePercentage, getAndCapMaxActiveBinSlippage, getSlippageMaxAmount, getSlippageMinAmountSlippage helpers.
getBinCount, getPositionCountByBinCountPosition/bin count helpers.
resetUninvolvedLiquidityParamsClears liquidity params outside the active update range.
encodePositionPermissionsEncodes position permission bits.

Pool State Helpers

HelperDescription
getTokenProgramIdReturns token X/Y program IDs from an LbPair.
isSupportLimitOrderChecks whether a pool supports limit order behavior.
getFeeModeReturns fee-on-input/output behavior for a swap direction.

Rebalance Helper Exports

HelperDescription
getLiquidityStrategyParameterBuilderReturns the strategy parameter builder for spot, curve, or bid/ask strategies.
suggestBalancedXParametersFromY, suggestBalancedYParametersFromXSuggest balanced strategy parameters from a single-side input.
getAutoFillAmountByRebalancedPositionComputes autofill amounts for rebalance simulation.
buildLiquidityStrategyParametersBuilds rebalance liquidity strategy parameters.
buildBitFlagAndNegateStrategyParametersEncodes rebalance deposit/withdraw flags.
getAmountInBinsBidSide, getAmountInBinsAskSide, toAmountIntoBinsConvert rebalance amounts into per-bin values.
getRebalanceBinArrayIndexesAndBitmapCoverageComputes bin array coverage and bitmap extension requirements for rebalance.

Low-Level Export Notes

These exports are available for advanced integrations and tests, but most applications do not need to call them directly:
ExportDescription
swapExactInQuoteAtBin, swapExactOutQuoteAtBin, getAmountIn, getAmountOut, getBinMaxAmountOut, getLimitOrderLiquiditySingle-bin quote and liquidity helpers used internally by quote simulation.
BalancedStrategyBuilder, SpotStrategyParameterBuilder, CurveStrategyParameterBuilder, BidAskStrategyParameterBuilderStrategy builder classes used by rebalance and liquidity strategy helpers.
PositionV2Wrapper, LimitOrderV1Wrapper, LimitOrderBinDataWrapperAccount wrapper classes for parsed position and limit order data.
capBps, MAX_BPS, REBALANCE_POSITION_PADDINGRebalance helper constants and bounds.
DEFAULT_ADD_LIQUIDITY_CU, DEFAULT_EXTEND_POSITION_HIGH_CU, DEFAULT_EXTEND_POSITION_LOW_CU, DEFAULT_INIT_POSITION_CU, DEFAULT_INIT_BIN_ARRAY_CU, MIN_CU_BUFFER, MAX_CU_BUFFER, MAX_CUCompute unit defaults used by transaction builders.
POSITION_MIN_SIZE, POSITION_BIN_DATA_SIZE, LIMIT_ORDER_MIN_SIZE, LIMIT_ORDER_BIN_DATA_SIZEDynamic account size constants.
ClockLayout, MEMO_PROGRAM_IDClock account decoder and memo program constant used by v2 builders.
chunkDepositWithRebalanceEndpointInternal-style helper for chunking deposit instructions through the rebalance endpoint.
derivePlaceHolderAccountMetaDerives the placeholder account meta used for optional accounts.
getTokensMintFromPoolAddressHelper for decoding token mints from a pool address.
DLMMErrorLegacy SDK error export alongside DlmmSdkError.

Account Filters

Use these with getProgramAccounts:
FilterDescription
presetParameter2BinStepFilterFilter PresetParameter2 by bin step.
presetParameter2BaseFactorFilterFilter PresetParameter2 by base factor.
presetParameter2BaseFeePowerFactorFilter PresetParameter2 by base fee power factor.
binArrayLbPairFilterFilter bin arrays by pool.
positionOwnerFilterFilter positions by owner.
positionLbPairFilterFilter positions by pool.
positionV2FilterFilter PositionV2 accounts.
limitOrderFilterFilter limit order accounts.
limitOrderOwnerFilterFilter limit orders by owner.
limitOrderLbPairFilterFilter limit orders by pool.

Oracle Helpers

The getOracle() instance method returns an IDynamicOracle wrapper. It exposes observation and TWAP functionality around the pool oracle account. Important exports:
ExportDescription
wrapOracleWraps a raw oracle account.
DynamicOracleOracle wrapper class.
ObservationObservation wrapper.
TwapResult&lt;T&gt;Result type for TWAP reads.

Limit Order Wrappers

Low-level exports from helpers/limitOrders include:
ExportDescription
decodeLimitOrderBinDataDecodes dynamic limit order bin data bytes.
wrapLimitOrderWraps a LimitOrder account and dynamic bin data.
LimitOrderV1WrapperWrapper implementing the limit order interface.
LimitOrderBinDataWrapperWrapper for one limit order bin entry.
ParsedLimitOrder, ParsedLimitOrderBinDataParsed limit order views.

Error Handling

Quote methods throw DlmmSdkError for SDK-level quote failures. Common cases include:
CodeMeaning
INVALID_MAX_EXTRA_BIN_ARRAYSmaxExtraBinArrays is outside the supported range.
SWAP_QUOTE_INSUFFICIENT_LIQUIDITYLoaded bin arrays do not contain enough liquidity for the requested quote.
Transaction builders may also throw standard Error objects for invalid ranges, missing accounts, existing pools, no claimable fees/rewards, or unsupported state.

Notes

  • All token amounts are raw integer token amounts, usually BN, not UI decimals.
  • Slippage values in quote methods are bps. A 0.5% slippage is new BN(50).
  • swapForY = true means swapping token X into token Y.
  • Most current transaction builders use the v2 program instructions and support Token-2022.
  • Legacy methods remain exported for older flows, but new integrations should prefer v2 creation, v2 liquidity, and v2 swap paths.
  • Methods that return TransactionInstruction[][] or grouped instruction objects are intended for callers that need custom transaction assembly, ALT usage, or parallel execution.
  • After sending a transaction, call refetchStates() before quoting or reading from the same DLMM instance again.