Meteora 백서

Meteora

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 46쪽

| ### `createLbPair2` ```typescript theme={"system"} 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` ```typescript theme={"system"} 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: | Field | Type | Description | | | - | - | - | - | | `pubkey` | `PublicKey` | Pool address. | | | `program` | `ClmmProgram` | Anchor program client. | | | `lbPair` | `LbPair` | Current pool account state. | | | `binArrayBitmapExtension` | \`BinArrayBitmapExtensionAccount | null\` | Bitmap extension account if present. | | `tokenX`, `tokenY` | `TokenReserve` | Pool token mint/reserve metadata. | | | `rewards` | \`(TokenReserve | null)\[]\` | Up to two reward token reserves. | | `clock` | `Clock` | Clock 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 | Method | Signature | Description | | - | - | - | | `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; FeeInfo` | Returns base, max, and protocol fee percentages. | | `getDynamicFee` | `() =&gt; Decimal` | Returns current variable fee percentage. | | `getEmissionRate` | `() =&gt; EmissionRate` | Returns 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 | Method | Description | | - | - | | `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: ```typescript theme={"system"} const activeBin = await pool.getActiveBin() const price = pool.fromPricePerLamport(Number(activeBin.price)) const binId = pool.getBinIdFromPrice(Number(price), true) ``` ## Positions ### Querying Positions | Method | Signature | Description | | - | - | - | | `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.getAllLbPairPositionsByUser` | Static | Fetches 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 | Method | Signature | Description | | - | - | - | | `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 | Method | Description | | - | - | | `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 | Method | Return | Description | | - | - | - | | `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: ```typescript theme={"system"} type TInitializePositionAndAddLiquidityParamsByStrategy = { positionPubKey: PublicKey totalXAmount: BN totalYAmount: BN strategy: StrategyParameters user: PublicKey slippage?: number } ``` ### Weight-Based Liquidity | Method | Return | Description | | | - | - | - | - | | `initializePositionAndAddLiquidityByWeight(params)` | \`Promise\<Transaction | Transaction\[]>\` | Deprecated legacy path. Initializes a position and deposits explicit bin weights. | | `addLiquidityByWeight(params)` | \`Promise\<Transaction | Transaction\[]>\` | 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: ```typescript theme={"system"} type TInitializePositionAndAddLiquidityParams = { positionPubKey: PublicKey totalXAmount: BN totalYAmount: BN xYAmountDistribution: BinAndAmount[] user: PublicKey slippage?: number } ``` ### Removing Liquidity ```typescript theme={"system"} 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 | Method | Signature | Description | | - | - | - | | `swapQuote` | `(inAmount, swapForY, allowedSlippage, binArrays, isPartialFill?, maxExtraBinArrays?) =&gt; SwapQuote` | Exact-in quote. `swapForY = true` means token X to token Y. Slippage is bps. | | `swapQuoteExactOut` | `(outAmount, swapForY, allowedSlippage, binArrays, maxExtraBinArrays?) =&gt; SwapQuoteExactOut` | Exact-out quote. Returns max input amount after slippage. | Quote result fields: | Field | Exact in | Exact out | Description | | - | - | - | - | | `consumedInAmount` | Yes | No | Input amount actually consumed, transfer-fee included. | | `inAmount` | No | Yes | Required input amount. | | `outAmount` | Yes | Yes | Output amount, transfer-fee adjusted where applicable. | | `fee` | Yes | Yes | Swap fee amount. | | `protocolFee` | Yes | Yes | Protocol fee amount. | | `minOutAmount` | Yes | No | Minimum output after slippage. | | `maxInAmount` | No | Yes | Maximum input after slippage. | | `priceImpact` | Yes | Yes | Price impact as `Decimal`. | | `binArraysPubkey` | Yes | Yes | Bin arrays to pass into swap transaction builder. | | `endPrice` | Yes | No | End bin price after simulated exact-in swap. | | `feeOnInput` | Yes | No | Whether fees are collected on input for this direction. | ### Transaction Builders | Method | Instruction | Description | | - | - | - | | `swap(params)` | `swap2` | Exact-in swap transaction. | | `swapExactOut(params)` | `swap_exact_out2` | Exact-out swap transaction. Uses a fixed `1_400_000` CU limit. | | `swapWithPriceImpact(params)` | `swap_with_price_impact2` | Exact-in style swap with price-impact bps guard. | ```typescript theme={"system"} 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 | Method | Return | Description | | - | - | - | | `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 | Method | Return | Description | | | - | - | - | - | | `getLimitOrder(limitOrder)` | \`Promise\<ParsedLimitOrderWithPubkey | null>\` | 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 quote | Estimates limit order rent, uninitialized bin arrays, bitmap extension cost. | | `relativeBin` treats each `bin.id` as an offset from current `activeId`. ### Transaction Builders | Method | Description | | - | - | | `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. | Method | Description | | - | - | | `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: ```typescript theme={"system"} { 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. | Method | Return | Description | | - | - | - | | `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: | Field | Description | | - | - | | `sendPositionOwnerTokenProveIxs` | Optional owner proof instructions. | | `initializeBinArraysAndPositionIxs` | Grouped setup instructions. | | `addLiquidityIxs` | Grouped deposit instructions. | | `costBreakdown` | Estimated rent/lamport costs. | ## Bin Arrays | Method | Description | | - | - | | `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 | Method | Description | | - | - | | `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: ```typescript theme={"system"} getPotentialToken2022IxDataAndAccounts(actionType, rewardIndex?) ``` This returns `RemainingAccountsInfoSlice[]` and account metas for Token-2022 transfer hooks. Public Token-2022 helper exports include: | Helper | Description | | - | - | | `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 | Helper | Description | | - | - | | `derivePresetParameterWithIndex` | Derives `PresetParameter2` with index key. | | `deriveLbPairWithPresetParamWithIndexKey` | Derives v2 pool PDA from preset parameter key and token mints. | | `derivePresetParameter`, `derivePresetParameter2` | Derive preset parameter accounts. | | `deriveLbPair`, `deriveLbPair2` | Derive legacy/v2 pool PDAs. | | `deriveCustomizablePermissionlessLbPair`, `derivePermissionLbPair` | Derive pool PDAs for specialized pool types. | | `deriveOracle`, `derivePosition`, `deriveBinArray`, `deriveReserve`, `deriveRewardVault` | Derive common pool accounts. | | `deriveTokenBadge`, `deriveOperator`, `deriveEventAuthority` | Derive program support accounts. | ### Bin Array Helpers | Helper | Description | | - | - |
프로젝트로 돌아가기