Meteora 백서

Meteora

원문

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

/docs.meteora.ag/developer-guides/dlmm/typescript-sdk/examples Explore TypeScript examples for DLMM swaps, liquidity, positions, fees, rewards, limit orders, and pool creation. These examples are based on the current `ts-client` source in the DLMM SDK repository. They focus on transaction construction patterns. For the full method catalog, see the [SDK Reference](/developer-guides/dlmm/typescript-sdk/reference). ## Setup ```typescript theme={"system"} import DLMM, { StrategyType } from "@meteora-ag/dlmm"; import { Connection, Keypair, PublicKey, sendAndConfirmTransaction } from "@solana/web3.js"; import BN from "bn.js"; const connection = new Connection(process.env.RPC_URL!, "confirmed"); const user = Keypair.fromSecretKey(/* your signer bytes */); const lbPair = new PublicKey("..."); const pool = await DLMM.create(connection, lbPair, { cluster: "mainnet-beta", }); ``` Use `cluster: "devnet"` for devnet. The SDK defaults to the public DLMM program ID; only pass a custom `programId` when Meteora has provided a compatible deployment or test harness. ## Quote And Swap The swap flow is: 1. Load the pool. 2. Fetch bin arrays in the swap direction. 3. Quote using current pool state. 4. Build the transaction with the quote's bin arrays and minimum output. 5. Sign and send. ```typescript theme={"system"} const swapYtoX = true; const inAmount = new BN(5_000_000); const slippageBps = new BN(50); const binArrays = await pool.getBinArrayForSwap(swapYtoX, 4); const quote = pool.swapQuote( inAmount, swapYtoX, slippageBps, binArrays, false, ); const [inToken, outToken] = swapYtoX ? [pool.tokenY.mint.address, pool.tokenX.mint.address] : [pool.tokenX.mint.address, pool.tokenY.mint.address]; const tx = await pool.swap({ inToken, outToken, inAmount: quote.consumedInAmount, minOutAmount: quote.minOutAmount, lbPair: pool.pubkey, user: user.publicKey, binArraysPubkey: quote.binArraysPubkey, }); const signature = await sendAndConfirmTransaction(connection, tx, [user]); ``` <Tip> Use `quote.consumedInAmount` when partial fill is enabled. It may be lower than your requested input amount if the pool cannot consume the full input under the quote constraints. </Tip> ## Create A Position And Add Liquidity For most LP flows, initialize the position and add liquidity in one transaction. The SDK initializes required bin arrays and token accounts when needed. ```typescript theme={"system"} const activeBin = await pool.getActiveBin(); const position = Keypair.generate(); const minBinId = activeBin.binId - 10; const maxBinId = activeBin.binId + 10; const tx = await pool.initializePositionAndAddLiquidityByStrategy({ positionPubKey: position.publicKey, user: user.publicKey, totalXAmount: new BN(1_000_000), totalYAmount: new BN(1_000_000), strategy: { minBinId, maxBinId, strategyType: StrategyType.Spot, }, }); const signature = await sendAndConfirmTransaction(connection, tx, [ user, position, ]); ``` Use `StrategyType.Spot`, `StrategyType.BidAsk`, or `StrategyType.Curve` depending on the distribution you want. The product-level behavior of these strategies is covered in [DLMM Strategies and Use Cases](/core-products/dlmm/strategies-and-use-cases). ## Add Liquidity To An Existing Position ```typescript theme={"system"} const tx = await pool.addLiquidityByStrategy({ positionPubKey: position.publicKey, user: user.publicKey, totalXAmount: new BN(500_000), totalYAmount: new BN(500_000), strategy: { minBinId, maxBinId, strategyType: StrategyType.Spot, }, }); await sendAndConfirmTransaction(connection, tx, [user]); ``` For large ranges, use `addLiquidityByStrategyChunkable` or the multiple-position helpers documented in the [SDK Reference](/developer-guides/dlmm/typescript-sdk/reference). ## Fetch User Positions ```typescript theme={"system"} const { userPositions } = await pool.getPositionsByUserAndLbPair( user.publicKey, ); for (const position of userPositions) { console.log(position.publicKey.toBase58()); console.log(position.positionData.lowerBinId); console.log(position.positionData.upperBinId); } ``` Use `DLMM.getAllLbPairPositionsByUser(connection, user, opt)` when you need all DLMM positions for a wallet across pools. ## Remove Liquidity, Claim, And Close `removeLiquidity` returns one or more transactions because wide positions may need chunking. ```typescript theme={"system"} const txs = await pool.removeLiquidity({ position: position.publicKey, user: user.publicKey, fromBinId: minBinId, toBinId: maxBinId, bps: new BN(10_000), shouldClaimAndClose: true, }); for (const tx of txs) { await sendAndConfirmTransaction(connection, tx, [user]); } ``` `bps: 10_000` removes 100% of liquidity. Set `shouldClaimAndClose` only when the position should claim accrued fees/rewards and close after the remove flow. ## Claim Fees And Rewards ```typescript theme={"system"} const txs = await pool.claimAllRewardsByPosition({ owner: user.publicKey, position: position.publicKey, }); for (const tx of txs) { await sendAndConfirmTransaction(connection, tx, [user]); } ``` Use `claimSwapFee`, `claimAllSwapFee`, `claimLMReward`, `claimAllLMRewards`, `claimAllRewards`, or `claimAllRewardsByPosition` depending on whether you are claiming one position, one reward index, or a wallet-wide set of positions. ## Place A Limit Order Limit orders deposit token X on the ask side and token Y on the bid side. The SDK creates missing bin arrays, initializes bitmap extension accounts when needed, wraps SOL when needed, and builds the `place_limit_order` instruction. ```typescript theme={"system"} const limitOrder = Keypair.generate(); await pool.refetchStates(); const activeId = pool.lbPair.activeId; const isAskSide = true; const binIds = [activeId + 1, activeId + 20]; const amountPerBin = new BN(1_000_000); const tx = await pool.placeLimitOrder({ owner: user.publicKey, sender: user.publicKey, payer: user.publicKey, limitOrder: limitOrder.publicKey, params: { isAskSide, relativeBin: null, bins: binIds.map((id) => ({ id, amount: amountPerBin })), }, }); await sendAndConfirmTransaction(connection, tx, [user, limitOrder]); ``` Before placing a limit order into existing bins, check whether the bins already contain pending limit order liquidity on the opposite side: ```typescript theme={"system"} const { bins } = await pool.getBinsBetweenLowerAndUpperBound( Math.min(...binIds), Math.max(...binIds), ); ``` Cancel by reading non-empty order bins and passing those bin IDs: ```typescript theme={"system"} const { limitOrderData } = await pool.getLimitOrder(limitOrder.publicKey); const binIdsToCancel = limitOrderData.limitOrderBinData .filter((bin) => !bin.empty) .map((bin) => bin.binId); const cancelTx = await pool.cancelLimitOrder({ limitOrderPubkey: limitOrder.publicKey, owner: user.publicKey, rentReceiver: user.publicKey, binIds: binIdsToCancel, }); await sendAndConfirmTransaction(connection, cancelTx, [user]); ``` ## Create A Permissionless V2 Pool Use `createLbPair2` for new permissionless pools. It reads `PresetParameter2`, supports SPL Token and Token-2022, and derives the pool PDA from the preset and token pair. ```typescript theme={"system"} import { NATIVE_MINT } from "@solana/spl-token"; import { DLMM } from "@meteora-ag/dlmm"; import { PublicKey, sendAndConfirmTransaction } from "@solana/web3.js"; import BN from "bn.js"; const tokenX = new PublicKey("..."); const tokenY = NATIVE_MINT; const presetParameter2 = new PublicKey("..."); const presetState = await DLMM.getAllPresetParameters(connection, { cluster: "devnet", }); const binStep = presetState.presetParameter2.find((preset) => preset.publicKey.equals(presetParameter2), )?.account.binStep; if (!binStep) { throw new Error("PresetParameter2 not found"); } const activeId = new BN(DLMM.getBinIdFromPrice(0.000008, binStep, true)); const tx = await DLMM.createLbPair2( connection, user.publicKey, tokenX, tokenY, presetParameter2, activeId, { cluster: "devnet" }, ); await sendAndConfirmTransaction(connection, tx, [user]); ``` Use `createCustomizablePermissionlessLbPair2` when the creator must configure activation behavior, base fee parameters, `ConcreteFunctionType`, or `CollectFeeMode`. # DLMM TS SDK Getting Started Source: https://docs.meteora.ag/developer-guides/dlmm/typescript-sdk/getting-started Learn how to install @meteora-ag/dlmm, create a DLMM pool client, choose a cluster, quote swaps, and test the SDK. This guide shows how to install and initialize the official DLMM TypeScript SDK, `@meteora-ag/dlmm`. Before you begin, here are some important resources: <CardGroup> <Card title="TypeScript SDK" icon="node-js" href="https://github.com/MeteoraAg/dlmm-sdk/tree/main/ts-client"> Meteora DLMM TypeScript SDK </Card> <Card title="DLMM NPM Package" icon="npm" href="https://www.npmjs.com/package/@meteora-ag/dlmm"> Meteora DLMM NPM Package </Card> </CardGroup> ## Installation To use the SDK in your project, install it using your preferred package manager: <Tabs> <Tab title="npm"> ```bash theme={"system"} npm install @meteora-ag/dlmm @solana/web3.js ``` </Tab> <Tab title="pnpm"> ```bash theme={"system"} pnpm install @meteora-ag/dlmm @solana/web3.js ``` </Tab> <Tab title="yarn"> ```bash theme={"system"} yarn add @meteora-ag/dlmm @solana/web3.js ``` </Tab> </Tabs> ## Initialization Once installed, initialize a pool client with a Solana connection and a DLMM pool address: ```typescript theme={"system"} import DLMM from "@meteora-ag/dlmm"; import { Connection, PublicKey } from "@solana/web3.js"; import BN from "bn.js"; const connection = new Connection(process.env.RPC_URL!, "confirmed"); const poolAddress = new PublicKey("ARwi1S4DaiTG5DX7S4M4ZsrXqpMD1MrTmbu9ue2tpmEq"); const dlmmPool = await DLMM.create(connection, poolAddress, { cluster: "mainnet-beta", }); ``` You can find pool addresses with the Data API: ```bash theme={"system"} curl "https://dlmm.datapi.meteora.ag/pools?page=1&page_size=20" ``` To initialize several pools efficiently: ```typescript theme={"system"} const pools = await DLMM.createMultiple(connection, [ poolAddress, ...otherPoolAddresses, ]); ``` ## Cluster And Program ID The SDK defaults to the public DLMM program ID: ```typescript theme={"system"} LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo ``` Pass `opt` when using devnet or a custom program ID: ```typescript theme={"system"} const dlmmPool = await DLMM.create(connection, poolAddress, { cluster: "devnet", }) ``` ## Reference <CardGroup> <Card title="SDK Examples" icon="bolt" href="/developer-guides/dlmm/typescript-sdk/examples"> Explore full transaction flows, including pool initialization, swaps, liquidity, and more. </Card> <Card title="SDK Reference" icon="code" href="/developer-guides/dlmm/typescript-sdk/reference"> Learn about all SDK functions: pool creation, liquidity, swaps, rewards, limit orders, and Token-2022 helpers. </Card> </CardGroup> ## Testing The SDK If you have cloned the SDK repository, start with package-level checks: ```bash theme={"system"} cd ts-client pnpm install pnpm run build pnpm run unit-test ``` For `commons`, CLI, scripts, and broader repository testing notes, see the [DLMM overview](/developer-guides/dlmm#repository-map). ## Faucets <CardGroup> <Card title="Devnet Faucet" icon="faucet" href="https://faucet.solana.com/"> <p>When working on devnet, you might need test tokens. Here is a helpful faucet.</p> </Card> </CardGroup> # DLMM TS SDK Reference Source: https://docs.meteora.ag/developer-guides/dlmm/typescript-sdk/reference Understand @meteora-ag/dlmm exports, client methods, pool creation, positions, liquidity, swaps, fees, rewards, and helpers. 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. ```typescript theme={"system"} import DLMM, { ActivationType, CollectFeeMode, ConcreteFunctionType, PairType, ResizeSide, StrategyType, deriveBinArray, getBinArrayIndexesCoverage, } from "@meteora-ag/dlmm" ``` ## Dependencies Important runtime dependencies: | Package | Use | | - | - | | `@coral-xyz/anchor` | Program client, BN, IDL-derived types. | | `@solana/web3.js` | Connections, transactions, instructions, public keys. | | `@solana/spl-token` | ATA creation, Token and Token-2022 account handling, transfer fee and transfer hook data. | | `decimal.js` | Price, fee, and UI conversion arithmetic. | ## Program IDs ```typescript theme={"system"} 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: ```typescript theme={"system"} 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 | Type | Description | | - | - | | `ClmmProgram` | Anchor `Program&lt;LbClmm&gt;`. | | `LbPair`, `LbPairAccount` | Pool account state and Anchor account wrapper. | | `Bin`, `BinArray`, `BinArrayAccount` | Bin and bin array state. | | `BinArrayBitmapExtensionAccount` | Bitmap extension account wrapper. | | `PositionV2`, `LbPosition`, `PositionInfo`, `PositionData` | Position account and SDK-normalized position data. | | `LimitOrder`, `ParsedLimitOrderWithPubkey` | Limit order account and parsed SDK view. | | `TokenReserve` | Mint, reserve, raw balance, token program owner, and transfer-hook metas. | | `SwapQuote`, `SwapQuoteExactOut` | Exact-in and exact-out quote result types. | | `FeeInfo`, `EmissionRate` | Current pool fee and reward emission views. | | `StrategyParameters` | Position/liquidity strategy input. | ```typescript theme={"system"} interface StrategyParameters { maxBinId: number minBinId: number strategyType: StrategyType singleSidedX?: boolean } ``` ## Enums | Enum | Values | | - | - | | `StrategyType` | `Spot`, `Curve`, `BidAsk` | | `ActivationType` | `Slot`, `Timestamp` | | `PairType` | `Permissionless`, `Permissioned`, `CustomizablePermissionless`, `PermissionlessV2` | | `PairStatus` | `Enabled`, `Disabled` | | `FunctionType` | `Undetermined`, `LiquidityMining`, `LimitOrder` | | `ConcreteFunctionType` | `LimitOrder`, `LiquidityMining` | | `CollectFeeMode` | `InputOnly`, `OnlyY` | | `PositionVersion` | `V1`, `V2` | | `ShrinkMode` | `ShrinkBoth`, `NoShrinkLeft`, `NoShrinkRight`, `NoShrinkBoth` | | `ResizeSide` | `Lower`, `Upper` | | `ActionType` | `Liquidity`, `Reward` | ## Important Constants | Constant | Meaning | | - | - | | `BASIS_POINT_MAX` | `10000`. Used for bps calculations. | | `FEE_PRECISION` | Program fee precision. | | `MAX_FEE_RATE` | Maximum fee rate in program precision. | | `BIN_ARRAY_DEFAULT_VERSION` | Current bin array layout version. | | `MAX_BINS_PER_POSITION` / `POSITION_MAX_LENGTH` | Maximum dynamic position width. | | `MAX_RESIZE_LENGTH` | Maximum position resize increment per instruction. | | `DEFAULT_BIN_PER_POSITION` | Base position width before dynamic extension data. | | `MAX_BIN_LENGTH_ALLOWED_IN_ONE_TX` | Threshold used by legacy weight flows before splitting transactions. | | `MAX_EXTRA_BIN_ARRAYS` | Maximum extra bin arrays quote helpers may include. | | `MAX_BIN_PER_LIMIT_ORDER` | Maximum bins allowed in one limit order account. | | `LIMIT_ORDER_FEE_SHARE` | Program constant for limit order fee share. | | `MAX_CLAIM_ALL_ALLOWED` | Claim-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` ```typescript theme={"system"} 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 ```typescript theme={"system"} const pool = await DLMM.create(connection, poolAddress, { cluster: "mainnet-beta", }) ``` ### `DLMM.createMultiple` ```typescript theme={"system"} 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 | Method | Signature | Description | | | - | - | - | - | | `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\<PublicKey | null>\` | Checks v2 PDA, legacy PDA, and `PresetParameter2`-derived candidate pool addresses. | | `getCustomizablePermissionlessLbPairIfExists` | \`(connection, tokenX, tokenY, opt?) => Promise\<PublicKey | null>\` | 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; string` | Converts UI price to price-per-lamport. | | | `getBinIdFromPrice` | `(price, binStep, min) =&gt; number` | Converts price to bin ID. `min` controls rounding side. | | | `calculateFeeInfo` | `(baseFactor, binStep, protocolShare, baseFeePowerFactor?) =&gt; FeeInfo` | Computes base/max/protocol fee percentages from fee parameters. | | | `updateVolatilityAccumulator` | `(vParameter, sParameter, activeId) =&gt; void` | In-memory helper used by quote simulation. | | | `updateReference` | `(activeId, vParameter, sParameter, currentTimestamp) =&gt; void` | In-memory helper used by quote simulation. | | `getPositionsOpt` supports chunked position loading: ```typescript theme={"system"} type GetPositionsOpt = { chunkSize?: number onChunkFetched?: ChunkCallback isParallelExecution?: boolean } ``` ## Pool Creation Methods Creation helpers return unsigned `Transaction` objects. The caller still signs and sends. | Method | Underlying instruction | Token support | Notes | | - | - | - | - | | `createLbPair` | `initialize_lb_pair` | SPL Token only | Legacy permissionless creation. Requires `binStep`, `baseFactor`, and legacy `presetParameter`. | | `createLbPair2` | `initialize_lb_pair2` | SPL Token and Token-2022 | Current permissionless path. Reads `PresetParameter2`, token badges, token program IDs, and derives pool PDA from preset parameter. | | `createCustomizablePermissionlessLbPair` | `initialize_customizable_permissionless_lb_pair` | SPL Token only | Creator-configurable pool. Throws if computed base fee power factor overflows legacy path. | | `createCustomizablePermissionlessLbPair2` | `initialize_customizable_permissionless_lb_pair2` | SPL Token and Token-2022 | Current customizable path. Supports `ConcreteFunctionType` and `CollectFeeMode`.
프로젝트로 돌아가기