Meteora 백서

Meteora

원문

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

connection.getLatestBlockhash()).blockhash; console.log(await connection.simulateTransaction(tx)); const signature = await sendAndConfirmTransaction(connection, tx, [user]); console.log("Swap signature", signature); ``` <Tip> Use `SwapMode.PartialFill` when the swap may consume less than the requested input. Use `SwapMode.ExactOut` with `maximumAmountIn` when the output amount is fixed. </Tip> ## Create A Position And Add Liquidity `createPositionAndAddLiquidity` creates the position NFT and adds liquidity in one transaction. ```typescript theme={"system"} const poolState = await cpAmm.fetchPoolState(pool); const positionNft = Keypair.generate(); const position = derivePositionAddress(positionNft.publicKey); const maxAmountTokenA = new BN(1_000_000); const maxAmountTokenB = new BN(1_000_000); const liquidityDelta = cpAmm.getLiquidityDelta({ maxAmountTokenA, maxAmountTokenB, sqrtPrice: poolState.sqrtPrice, sqrtMinPrice: poolState.sqrtMinPrice, sqrtMaxPrice: poolState.sqrtMaxPrice, collectFeeMode: poolState.collectFeeMode, tokenAAmount: poolState.tokenAAmount, tokenBAmount: poolState.tokenBAmount, liquidity: poolState.liquidity, }); const tx = await cpAmm.createPositionAndAddLiquidity({ owner: user.publicKey, pool, positionNft: positionNft.publicKey, liquidityDelta, maxAmountTokenA, maxAmountTokenB, tokenAAmountThreshold: maxAmountTokenA, tokenBAmountThreshold: maxAmountTokenB, tokenAMint: poolState.tokenAMint, tokenBMint: poolState.tokenBMint, tokenAProgram: getTokenProgram(poolState.tokenAFlag), tokenBProgram: getTokenProgram(poolState.tokenBFlag), }); await sendAndConfirmTransaction(connection, tx, [user, positionNft]); console.log("Created position", position.toBase58()); ``` For compounding pools, include `tokenAAmount`, `tokenBAmount`, and `liquidity` when calculating liquidity so the quote uses the current pool reserves. ## Add Liquidity To An Existing Position Use `getDepositQuote` before building the transaction. The quote returns the liquidity delta and the counterpart token amount. ```typescript theme={"system"} const poolState = await cpAmm.fetchPoolState(pool); const positionNftMint = new PublicKey("..."); const position = derivePositionAddress(positionNftMint); const positionNftAccount = derivePositionNftAccount(positionNftMint); const inAmount = new BN(1_000_000); const depositQuote = cpAmm.getDepositQuote({ inAmount, isTokenA: true, sqrtPrice: poolState.sqrtPrice, minSqrtPrice: poolState.sqrtMinPrice, maxSqrtPrice: poolState.sqrtMaxPrice, collectFeeMode: poolState.collectFeeMode, tokenAAmount: poolState.tokenAAmount, tokenBAmount: poolState.tokenBAmount, liquidity: poolState.liquidity, }); const tx = await cpAmm.addLiquidity({ owner: user.publicKey, pool, position, positionNftAccount, liquidityDelta: depositQuote.liquidityDelta, maxAmountTokenA: depositQuote.actualInputAmount, maxAmountTokenB: depositQuote.outputAmount, tokenAAmountThreshold: depositQuote.actualInputAmount, tokenBAmountThreshold: depositQuote.outputAmount, tokenAMint: poolState.tokenAMint, tokenBMint: poolState.tokenBMint, tokenAVault: poolState.tokenAVault, tokenBVault: poolState.tokenBVault, tokenAProgram: getTokenProgram(poolState.tokenAFlag), tokenBProgram: getTokenProgram(poolState.tokenBFlag), }); await sendAndConfirmTransaction(connection, tx, [user]); ``` ## Remove Liquidity And Close A Position `removeAllLiquidityAndClosePosition` combines fee claim, full liquidity removal, and position close. It will reject locked positions, so load vesting accounts and the current point first. ```typescript theme={"system"} const poolState = await cpAmm.fetchPoolState(pool); const position = new PublicKey("..."); const positionNftAccount = new PublicKey("..."); const positionState = await cpAmm.fetchPositionState(position); const currentPoint = await getCurrentPoint( connection, poolState.activationType as ActivationType, ); const vestings = (await cpAmm.getAllVestingsByPosition(position)).map( ({ publicKey, account }) => ({ account: publicKey, vestingState: account, }), ); const tx = await cpAmm.removeAllLiquidityAndClosePosition({ owner: user.publicKey, position, positionNftAccount, poolState, positionState, tokenAAmountThreshold: new BN(0), tokenBAmountThreshold: new BN(0), vestings, currentPoint, }); await sendAndConfirmTransaction(connection, tx, [user]); ``` Use `removeLiquidity` when you only want to remove a specific liquidity delta and keep the position open. ## Claim Position Fees `claimPositionFee2` is the preferred fee claim helper for new integrations. ```typescript theme={"system"} const poolState = await cpAmm.fetchPoolState(pool); const userPositions = await cpAmm.getUserPositionByPool(pool, user.publicKey); const { position, positionNftAccount } = userPositions[0]; const tx = await cpAmm.claimPositionFee2({ receiver: user.publicKey, feePayer: user.publicKey, owner: user.publicKey, pool, position, positionNftAccount, tokenAMint: poolState.tokenAMint, tokenBMint: poolState.tokenBMint, tokenAVault: poolState.tokenAVault, tokenBVault: poolState.tokenBVault, tokenAProgram: getTokenProgram(poolState.tokenAFlag), tokenBProgram: getTokenProgram(poolState.tokenBFlag), }); await sendAndConfirmTransaction(connection, tx, [user]); ``` ## Lock Liquidity Use `permanentLockPosition` for irreversible locks and `lockPosition` for vesting schedules. ```typescript theme={"system"} const positionNftMint = new PublicKey("..."); const position = derivePositionAddress(positionNftMint); const positionNftAccount = derivePositionNftAccount(positionNftMint); const unlockedLiquidity = new BN("1000000000000"); const permanentLockTx = await cpAmm.permanentLockPosition({ owner: user.publicKey, pool, position, positionNftAccount, unlockedLiquidity, }); await sendAndConfirmTransaction(connection, permanentLockTx, [user]); ``` For scheduled vesting, create a vesting account signer and pass the cliff and period settings: ```typescript theme={"system"} const vestingAccount = Keypair.generate(); const vestingTx = await cpAmm.lockPosition({ owner: user.publicKey, payer: user.publicKey, pool, position, positionNftAccount, cliffPoint: null, periodFrequency: new BN(24 * 60 * 60), cliffUnlockLiquidity: new BN(0), liquidityPerPeriod: new BN("250000000000"), numberOfPeriod: 4, vestingAccount: vestingAccount.publicKey, }); await sendAndConfirmTransaction(connection, vestingTx, [user, vestingAccount]); ``` ## Initialize And Claim Rewards `initializeAndFundReward` creates a reward slot and funds it in one transaction. ```typescript theme={"system"} const rewardMint = new PublicKey("..."); const rewardIndex = 0; const initRewardTx = await cpAmm.initializeAndFundReward({ rewardIndex, rewardDuration: new BN(24 * 60 * 60), pool, creator: user.publicKey, payer: user.publicKey, rewardMint, carryForward: false, amount: new BN(1_000_000_000), rewardMintProgram: TOKEN_PROGRAM_ID, }); await sendAndConfirmTransaction(connection, initRewardTx, [user]); ``` Claim rewards by loading the current pool and position state: ```typescript theme={"system"} const position = new PublicKey("..."); const positionNftAccount = new PublicKey("..."); const poolState = await cpAmm.fetchPoolState(pool); const positionState = await cpAmm.fetchPositionState(position); const claimRewardTx = await cpAmm.claimReward({ user: user.publicKey, position, poolState, positionState, positionNftAccount, rewardIndex: 0, isSkipReward: false, feePayer: user.publicKey, }); await sendAndConfirmTransaction(connection, claimRewardTx, [user]); ``` Use `initializeReward` plus `fundReward` when initialization and funding should be separate admin actions. ## Create A Customizable Pool Customizable pools let the creator set fee behavior, activation behavior, and whether initial liquidity should be locked. ```typescript theme={"system"} const tokenAMint = new PublicKey("..."); const tokenBMint = new PublicKey("..."); const tokenADecimals = 6; const tokenBDecimals = 6; const tokenAAmount = new BN(1_000_000).mul( new BN(10).pow(new BN(tokenADecimals)), ); const tokenBAmount = new BN(1_000_000).mul( new BN(10).pow(new BN(tokenBDecimals)), ); const initSqrtPrice = getSqrtPriceFromPrice("1", tokenADecimals, tokenBDecimals); const liquidityDelta = cpAmm.getLiquidityDelta({ maxAmountTokenA: tokenAAmount, maxAmountTokenB: tokenBAmount, sqrtPrice: initSqrtPrice, sqrtMinPrice: MIN_SQRT_PRICE, sqrtMaxPrice: MAX_SQRT_PRICE, collectFeeMode: CollectFeeMode.BothToken, }); const baseFee = getBaseFeeParams( { baseFeeMode: BaseFeeMode.FeeTimeSchedulerExponential, feeTimeSchedulerParam: { startingFeeBps: 5000, endingFeeBps: 25, numberOfPeriod: 60, totalDuration: 3600, }, }, tokenBDecimals, ActivationType.Timestamp, ); const poolFees: PoolFeesParams = { baseFee, compoundingFeeBps: 0, padding: 0, dynamicFee: getDynamicFeeParams(25), }; const positionNft = Keypair.generate(); const { tx, pool: newPool, position: initialPosition, } = await cpAmm.createCustomPool({ payer: user.publicKey, creator: user.publicKey, positionNft: positionNft.publicKey, tokenAMint, tokenBMint, tokenAAmount, tokenBAmount, sqrtMinPrice: MIN_SQRT_PRICE, sqrtMaxPrice: MAX_SQRT_PRICE, liquidityDelta, initSqrtPrice, poolFees, hasAlphaVault: false, activationType: ActivationType.Timestamp, collectFeeMode: CollectFeeMode.BothToken, activationPoint: null, tokenAProgram: TOKEN_PROGRAM_ID, tokenBProgram: TOKEN_PROGRAM_ID, isLockLiquidity: false, }); await sendAndConfirmTransaction(connection, tx, [user, positionNft]); console.log({ pool: newPool.toBase58(), position: initialPosition.toBase58(), }); ``` Use `createPool` instead when you are creating against an existing DAMM v2 config account. Use `createCustomPoolWithDynamicConfig` when your flow needs to create through a dynamic config account. ## Token-2022 Transfer Fee Inputs For Token-2022 transfer-fee mints, pass mint and epoch data into quote helpers so the SDK can account for transfer fees. ```typescript theme={"system"} async function getTransferFeeInfo(mint: PublicKey, tokenProgram: PublicKey) { if (!tokenProgram.equals(TOKEN_2022_PROGRAM_ID)) { return undefined; } const [mintAccount, epochInfo] = await Promise.all([ getMint(connection, mint, connection.commitment, tokenProgram), connection.getEpochInfo(), ]); return { mint: mintAccount, currentEpoch: epochInfo.epoch, }; } const poolState = await cpAmm.fetchPoolState(pool); const tokenAProgram = getTokenProgram(poolState.tokenAFlag); const tokenBProgram = getTokenProgram(poolState.tokenBFlag); const quote = cpAmm.getQuote2({ inputTokenMint: poolState.tokenAMint, poolState, currentPoint: await getCurrentPoint( connection, poolState.activationType as ActivationType, ), amountIn: new BN(1_000_000), slippage: 0.5, swapMode: SwapMode.ExactIn, tokenADecimal: 6, tokenBDecimal: 6, hasReferral: false, inputTokenInfo: await getTransferFeeInfo(poolState.tokenAMint, tokenAProgram), outputTokenInfo: await getTransferFeeInfo(poolState.tokenBMint, tokenBProgram), }); console.log(quote.minimumAmountOut?.toString()); ``` # DAMM v2 TS SDK Getting Started Source: https://docs.meteora.ag/developer-guides/damm-v2/typescript-sdk/getting-started Learn how to install @meteora-ag/cp-amm-sdk, initialize CpAmm, fetch DAMM v2 state, quote swaps, and build transactions. This guide shows how to install and initialize the official DAMM v2 TypeScript SDK, `@meteora-ag/cp-amm-sdk`. Before you begin, here are the main resources: <CardGroup> <Card title="TypeScript SDK" icon="node-js" href="https://github.com/MeteoraAg/damm-v2-sdk"> Public SDK source, examples, tests, and generated `cp_amm` IDL. </Card> <Card title="NPM Package" icon="npm" href="https://www.npmjs.com/package/@meteora-ag/cp-amm-sdk"> Published `@meteora-ag/cp-amm-sdk` package. </Card> </CardGroup> ## Installation To use the SDK in your project, install it with your preferred package manager: <Tabs> <Tab title="npm"> ```bash theme={"system"} npm install @meteora-ag/cp-amm-sdk @solana/web3.js @coral-xyz/anchor bn.js ``` </Tab> <Tab title="pnpm"> ```bash theme={"system"} pnpm add @meteora-ag/cp-amm-sdk @solana/web3.js @coral-xyz/anchor bn.js ``` </Tab> <Tab title="yarn"> ```bash theme={"system"} yarn add @meteora-ag/cp-amm-sdk @solana/web3.js @coral-xyz/anchor bn.js ``` </Tab> </Tabs> ## Initialization ```typescript theme={"system"} import { Connection, PublicKey } from "@solana/web3.js"; import { CpAmm } from "@meteora-ag/cp-amm-sdk"; const connection = new Connection("https://api.mainnet-beta.solana.com", "confirmed"); const cpAmm = new CpAmm(connection); const pool = new PublicKey("POOL_ADDRESS"); const poolState = await cpAmm.fetchPoolState(pool); ``` You can also find pool addresses with the Data API: ```bash theme={"system"} curl "https://damm-v2.datapi.meteora.ag/pools?page=1&page_size=20" ``` ## Program ID The SDK uses the public DAMM v2 program ID by default: ```typescript theme={"system"} cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG ``` ## Reference <CardGroup> <Card title="SDK Examples" icon="bolt" href="/developer-guides/damm-v2/typescript-sdk/example"> Explore full transaction flows, including pool initialization, swaps, liquidity, and more. </Card> <Card title="SDK Reference" icon="code" href="/developer-guides/damm-v2/typescript-sdk/reference"> Access the full method map, PDA helpers, and fee helpers for DAMM v2. </Card> </CardGroup> ## Testing the SDK The SDK repository includes Vitest and Bankrun tests. They use the SDK source and a local program fixture, so they are best for SDK contributors and regression testing. App integrators should also test against devnet or their own local validator flow before shipping transaction code. ```bash theme={"system"} git clone https://github.com/MeteoraAg/damm-v2-sdk.git cd damm-v2-sdk pnpm install pnpm run build pnpm run check-types pnpm test ``` ## Faucets <CardGroup> <Card title="Devnet Faucet" icon="faucet" href="https://faucet.solana.com/"> <p>Use this when your devnet test wallet needs SOL for fees and rent.</p> </Card> </CardGroup> # DAMM v2 TS SDK Reference Source: https://docs.meteora.ag/developer-guides/damm-v2/typescript-sdk/reference Understand the @meteora-ag/cp-amm-sdk exports, CpAmm methods, transaction builders, helpers, constants, types, and errors. This page is based on the public declaration surface of `@meteora-ag/cp-amm-sdk`. Use it as the high-level map for the SDK, then open the package types when you need exact parameter shapes. ```typescript theme={"system"} import { CpAmm, ActivationType, BaseFeeMode, CollectFeeMode, ConfigPermission, SwapMode, derivePoolAddress, derivePositionAddress, getBaseFeeParams, getDynamicFeeParams, getSqrtPriceFromPrice, getTokenProgram, isConfigPermissionAllow, } from "@meteora-ag/cp-amm-sdk" ``` ## Dependencies Important runtime dependencies: | Package | Use | | - | - | | `@coral-xyz/anchor` | Program client, IDL types, and `BN`. | | `@solana/web3.js` | Connections, transactions, instructions, lookup tables, and public keys. | | `@solana/spl-token` | SPL Token, Token-2022, ATA, mint, transfer-fee, transfer-hook, and wrapped SOL helpers. | | `bn.js` | Integer math inputs and SDK return values. | | `decimal.js` | Price, price impact, and UI conversion arithmetic. | | `chain` | Transaction composition helpers used by SDK builders. | ## Program ID ```typescript theme={"system"} CP_AMM_PROGRAM_ID = "cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG" ``` `CpAmm` constructs an Anchor `Program` from the packaged `cp_amm` IDL and the connection you provide. ## Core Exports | Export | Use | | - | - | | `CpAmm` | Main class for fetching state, quoting, and building transactions. | | `CpAmmIdl` / `CpAmmTypes` | Published IDL JSON and generated Anchor type. | | `AmmProgram` | Anchor `Program&lt;CpAmmTypes&gt;` type alias. | | `TxBuilder` | SDK transaction-builder return type, currently `Promise&lt;Transaction&gt;`. | | `cpAmmCoder` | Anchor `BorshCoder` configured with the packaged IDL. | | `CP_AMM_PROGRAM_ID` | Program ID constant. | | `PoolState`, `PositionState`, `VestingState`, `ConfigState`, `TokenBadgeState` | IDL-derived account state types. `ConfigState.permission` is a `BN` (IDL `u128` bitmask). | | `PoolFeesStruct`, `DynamicFeeStruct`, `BaseFee`, `DynamicFee`, `DecodedPoolFees` | Fee configuration and decoded fee-data types. | | `DepositQuote`, `WithdrawQuote`, `Quote2Result`, `SwapResult2` | Quote result types. | | `BaseFeeHandler`, `LiquidityHandler` | Interfaces implemented by exported fee and liquidity handler classes. | ## Enums | Enum | Values | | - | - | | `Rounding` | `Up`, `Down`. | | `ActivationPoint` | `Timestamp`, `Slot`. | | `ActivationType` | `Slot`, `Timestamp`. | | `BaseFeeMode` | `FeeTimeSchedulerLinear`, `FeeTimeSchedulerExponential`, `RateLimiter` (deprecated for new configs and new pools), `FeeMarketCapSchedulerLinear`, `FeeMarketCapSchedulerExponential`. | | `CollectFeeMode` | `BothToken`, `OnlyB`, `Compounding`. | | `ConfigPermission` | `CreatePoolWithoutMintValidation` (`0`). | | `TradeDirection` | `AtoB`, `BtoA`. | | `LayoutVersion` | `V0`, `V1`. | | `PoolStatus` | `Enable`, `Disable`. | | `SwapMode` | `ExactIn`, `PartialFill`, `ExactOut`. | ## Important Constants | Constant | Meaning | | - | - | | `LIQUIDITY_SCALE`, `SCALE_OFFSET`, `ONE_Q64` | Q64 liquidity and price scale constants. | | `BASIS_POINT_MAX`, `FEE_DENOMINATOR` | Basis-point and fee-numerator denominators. | | `MIN_FEE_BPS`, `MIN_FEE_NUMERATOR` | Minimum base fee. | | `MAX_FEE_BPS_V0`, `MAX_FEE_NUMERATOR_V0` | V0 pool maximum fee. | | `MAX_FEE_BPS_V1`, `MAX_FEE_NUMERATOR_V1` | V1 pool maximum fee. | | `MIN_SQRT_PRICE`, `MAX_SQRT_PRICE` | Global square-root price bounds. | | `MIN_CU_BUFFER`, `MAX_CU_BUFFER` | Compute-unit buffer bounds for compute helper functions. | | `DYNAMIC_FEE_SCALING_FACTOR`, `DYNAMIC_FEE_ROUNDING_OFFSET` | Dynamic-fee math constants. | | `DYNAMIC_FEE_FILTER_PERIOD_DEFAULT`, `DYNAMIC_FEE_DECAY_PERIOD_DEFAULT`, `DYNAMIC_FEE_REDUCTION_FACTOR_DEFAULT` | Default dynamic-fee parameters. | | `BIN_STEP_BPS_DEFAULT`, `BIN_STEP_BPS_U128_DEFAULT`, `MAX_PRICE_CHANGE_BPS_DEFAULT` | Default dynamic-fee bin and price-change parameters. | | `U128_MAX`, `U64_MAX`, `U24_MAX`, `U16_MAX` | Integer bounds used by validation and math helpers. | | `MAX_RATE_LIMITER_DURATION_IN_SECONDS`, `MAX_RATE_LIMITER_DURATION_IN_SLOTS` | Rate-limiter duration bounds. | | `SPLIT_POSITION_DENOMINATOR` | Denominator for position split ratios. | | `CURRENT_POOL_VERSION` | Current pool layout version. | | `DEAD_LIQUIDITY` | Compounding-pool dead liquidity constant. | | `NUM_REWARDS`, `MIN_REWARD_DURATION`, `MAX_REWARD_DURATION` | Reward count and duration bounds. | | `MAX_EXPONENTIAL`, `MAX` | Internal upper bounds used by math helpers. | ## Creating A Client ```typescript theme={"system"} import { Connection, PublicKey } from "@solana/web3.js" import { CpAmm } from "@meteora-ag/cp-amm-sdk" const connection = new Connection("https://api.mainnet-beta.solana.com") const cpAmm = new CpAmm(connection) const poolState = await cpAmm.fetchPoolState(new PublicKey("...")) ``` The client stores the connection-backed Anchor program and exposes read methods, quote methods, and unsigned transaction builders. The caller still sets the fee payer, recent blockhash, signs, simulates, and submits. ## Complete Public Function Index This section lists the public functions and methods exported by the SDK. Private helper methods emitted in declaration files are intentionally excluded. ### `CpAmm` State And Discovery | Method | Use | | - | - | | `constructor(connection)` | Create a client for one Solana connection. | | `fetchConfigState(config)` | Fetch one config account. | | `fetchPoolState(pool)` | Fetch one pool account. | | `fetchPoolStatesByTokenAMint(tokenAM
프로젝트로 돌아가기