bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 30쪽
ce, liquidity, amountIn)` | Simulate exact-input A to B swap math for concentrated liquidity. |
| `calculateBtoAFromAmountInForConcentratedLiquidity(sqrtMaxPrice, sqrtPrice, liquidity, amountIn)` | Simulate exact-input B to A swap math for concentrated liquidity. |
| `calculateAtoBFromPartialAmountInForConcentratedLiquidity(sqrtMinPrice, sqrtPrice, liquidity, amountIn)` | Simulate partial-input A to B swap math for concentrated liquidity. |
| `calculateBtoAFromPartialAmountInForConcentratedLiquidity(sqrtMaxPrice, sqrtPrice, liquidity, amountIn)` | Simulate partial-input B to A swap math for concentrated liquidity. |
| `calculateAtoBFromAmountOutForConcentratedLiquidity(sqrtMinPrice, sqrtPrice, liquidity, amountOut)` | Simulate exact-output A to B swap math for concentrated liquidity. |
| `calculateBtoAFromAmountOutForConcentratedLiquidity(sqrtMaxPrice, sqrtPrice, liquidity, amountOut)` | Simulate exact-output B to A swap math for concentrated liquidity. |
| `getReservesAmountForConcentratedLiquidity(sqrtPrice, sqrtMinPrice, sqrtMaxPrice, liquidity)` | Compute token A and token B reserves for a concentrated position. |
| `getAmountBFromLiquidityDeltaForConcentratedLiquidity(lowerSqrtPrice, upperSqrtPrice, liquidity, rounding)` | Compute token B amount from concentrated liquidity delta. |
| `getAmountAFromLiquidityDeltaForConcentratedLiquidity(lowerSqrtPrice, upperSqrtPrice, liquidity, rounding)` | Compute token A amount from concentrated liquidity delta. |
| `getNextSqrtPriceFromInput(sqrtPrice, liquidity, amountIn, aForB)` | Compute next square-root price from exact input. |
| `getNextSqrtPriceFromOutput(sqrtPrice, liquidity, amountOut, aForB)` | Compute next square-root price from exact output. |
| `getNextSqrtPriceFromAmountInARoundingUp(sqrtPrice, liquidity, amount)` | Compute next square-root price from token A input, rounding up. |
| `getNextSqrtPriceFromAmountOutARoundingUp(sqrtPrice, liquidity, amount)` | Compute next square-root price from token A output, rounding up. |
| `getNextSqrtPriceFromAmountInBRoundingDown(sqrtPrice, liquidity, amount)` | Compute next square-root price from token B input, rounding down. |
| `getNextSqrtPriceFromAmountOutBRoundingDown(sqrtPrice, liquidity, amount)` | Compute next square-root price from token B output, rounding down. |
| `getLiquidityDeltaFromAmountAForConcentratedLiquidity(amountA, lowerSqrtPrice, upperSqrtPrice)` | Compute concentrated liquidity delta from token A amount. |
| `getLiquidityDeltaFromAmountBForConcentratedLiquidity(amountB, lowerSqrtPrice, upperSqrtPrice)` | Compute concentrated liquidity delta from token B amount. |
### Generic Liquidity Math
| Function | Use |
| - | - |
| `getLiquidityHandler(poolState)` | Return a compounding or concentrated liquidity handler for a pool. |
| `getInitialPoolInformation(collectFeeMode, sqrtMinPrice, sqrtMaxPrice, sqrtPrice, liquidity)` | Dispatch initial-pool math by collect-fee mode. |
| `getLiquidityDeltaFromAmountA(amountA, sqrtPrice, sqrtMaxPrice, collectFeeMode, tokenAAmount?, liquidity?)` | Dispatch token A liquidity math by collect-fee mode. |
| `getLiquidityDeltaFromAmountB(amountB, sqrtMinPrice, sqrtPrice, collectFeeMode, tokenBAmount?, liquidity?)` | Dispatch token B liquidity math by collect-fee mode. |
| `getAmountAFromLiquidityDelta(sqrtPrice, sqrtMaxPrice, liquidityDelta, rounding, collectFeeMode, tokenAAmount?, liquidity?)` | Dispatch token A amount math by collect-fee mode. |
| `getAmountBFromLiquidityDelta(sqrtMinPrice, sqrtPrice, liquidityDelta, rounding, collectFeeMode, tokenBAmount?, liquidity?)` | Dispatch token B amount math by collect-fee mode. |
### Liquidity Handler Classes
`CompoundingLiquidityHandler` and `ConcentratedLiquidityHandler` implement the same public method surface:
| Method | Use |
| - | - |
| `constructor(...)` | Create a handler with the pool reserves or price range. |
| `getAmountsForModifyLiquidity(liquidityDelta, round)` | Compute token amounts for a liquidity delta. |
| `calculateAtoBFromAmountIn(amountIn)` | Simulate exact-input A to B. |
| `calculateBtoAFromAmountIn(amountIn)` | Simulate exact-input B to A. |
| `calculateAtoBFromPartialAmountIn(amountIn)` | Simulate partial-input A to B. |
| `calculateBtoAFromPartialAmountIn(amountIn)` | Simulate partial-input B to A. |
| `calculateAtoBFromAmountOut(amountOut)` | Simulate exact-output A to B. |
| `calculateBtoAFromAmountOut(amountOut)` | Simulate exact-output B to A. |
| `getReservesAmount()` | Return current reserves. |
| `getNextSqrtPrice(nextSqrtPrice)` | Return or clamp the next square-root price for the handler. |
| `getMaxAmountIn(tradeDirection)` | Compute the maximum input for one trade direction. |
### Base Fee Handler Classes
`FeeRateLimiter`, `FeeTimeScheduler`, and `FeeMarketCapScheduler` implement the same public method surface:
| Method | Use |
| - | - |
| `constructor(...)` | Create the fee handler from decoded fee parameters. |
| `validate(collectFeeMode, activationType, feeVersion)` | Validate the handler against pool settings. |
| `getBaseFeeNumeratorFromIncludedFeeAmount(currentPoint, activationPoint, tradeDirection, includedFeeAmount, initSqrtPrice, currentSqrtPrice)` | Compute base fee from an amount that already includes fees. |
| `getBaseFeeNumeratorFromExcludedFeeAmount(currentPoint, activationPoint, tradeDirection, excludedFeeAmount, initSqrtPrice, currentSqrtPrice)` | Compute base fee from an amount before fees. |
| `validateBaseFeeIsStatic(currentPoint, activationPoint)` | Check whether the base fee is static at the current point. |
| `getMinFeeNumerator()` | Return the minimum base-fee numerator. |
| `getMaxFeeNumerator()` | Return the maximum base-fee numerator. |
### Base Fee And Pool Fee Math
| Function | Use |
| - | - |
| `getBaseFeeHandlerFromPodAlignedData(rawData)` | Decode pool-state fee bytes into a base-fee handler. |
| `getBaseFeeHandlerFromBorshData(rawData)` | Decode event or Borsh fee bytes into a base-fee handler. |
| `getFeeNumeratorOnLinearFeeScheduler(cliffFeeNumerator, reductionFactor, period)` | Compute one linear scheduler fee numerator. |
| `getFeeNumeratorOnExponentialFeeScheduler(cliffFeeNumerator, reductionFactor, period)` | Compute one exponential scheduler fee numerator. |
| `getMaxBaseFeeNumerator(cliffFeeNumerator)` | Compute maximum base fee from cliff fee. |
| `getFeeTimeBaseFeeNumeratorByPeriod(cliffFeeNumerator, numberOfPeriod, period, reductionFactor, feeTimeSchedulerMode)` | Compute time-scheduler base fee by period. |
| `getFeeTimeBaseFeeNumerator(cliffFeeNumerator, numberOfPeriod, periodFrequency, reductionFactor, feeTimeSchedulerMode, currentPoint, activationPoint)` | Compute current time-scheduler base fee. |
| `getFeeTimeMinBaseFeeNumerator(cliffFeeNumerator, numberOfPeriod, reductionFactor, feeTimeSchedulerMode)` | Compute time-scheduler minimum base fee. |
| `getFeeMarketCapBaseFeeNumeratorByPeriod(cliffFeeNumerator, numberOfPeriod, period, reductionFactor, feeMarketCapSchedulerMode)` | Compute market-cap scheduler base fee by period. |
| `getFeeMarketCapBaseFeeNumerator(cliffFeeNumerator, numberOfPeriod, sqrtPriceStepBps, schedulerExpirationDuration, reductionFactor, feeMarketCapSchedulerMode, currentPoint, activationPoint, initSqrtPrice, currentSqrtPrice)` | Compute current market-cap scheduler base fee. |
| `getFeeMarketCapMinBaseFeeNumerator(cliffFeeNumerator, numberOfPeriod, reductionFactor, feeMarketCapSchedulerMode)` | Compute market-cap scheduler minimum base fee. |
| `isZeroRateLimiter(referenceAmount, maxLimiterDuration, maxFeeBps, feeIncrementBps)` | Check whether a rate limiter is effectively disabled. |
| `isNonZeroRateLimiter(referenceAmount, maxLimiterDuration, maxFeeBps, feeIncrementBps)` | Check whether a rate limiter has non-zero params. |
| `isRateLimiterApplied(referenceAmount, maxLimiterDuration, maxFeeBps, feeIncrementBps, currentPoint, activationPoint, tradeDirection)` | Check whether a rate limiter applies to the current trade. |
| `getMaxIndex(maxFeeBps, cliffFeeNumerator, feeIncrementBps)` | Compute the maximum rate-limiter index. |
| `getFeeNumeratorFromIncludedFeeAmount(inputAmount, referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps)` | Compute rate-limiter fee numerator from included amount. |
| `getExcludedFeeAmountFromIncludedFeeAmount(includedFeeAmount, referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps)` | Convert included amount to excluded amount for rate-limiter math. |
| `getCheckedAmounts(referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps)` | Compute checked included/excluded amounts and overflow status. |
| `getFeeNumeratorFromExcludedFeeAmount(excludedFeeAmount, referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps)` | Compute rate-limiter fee numerator from excluded amount. |
| `getRateLimiterMinBaseFeeNumerator(cliffFeeNumerator)` | Compute rate-limiter minimum base fee. |
| `getRateLimiterMaxBaseFeeNumerator(includedFeeAmount, referenceAmount, cliffFeeNumerator, maxFeeBps, feeIncrementBps)` | Compute rate-limiter maximum base fee for an amount. |
| `isDynamicFeeEnabled(dynamicFee)` | Check whether dynamic fees are enabled. |
| `getDynamicFeeNumerator(volatilityAccumulator, binStep, variableFeeControl)` | Compute dynamic-fee numerator from volatility data. |
| `toNumerator(bps, feeDenominator)` | Convert basis points to a numerator for a given denominator. |
| `getFeeInPeriod(cliffFeeNumerator, reductionFactor, passedPeriod)` | Compute scheduled fee for a passed period. |
| `getFeeMode(collectFeeMode, tradeDirection, hasReferral)` | Resolve protocol, LP-claiming, compounding, and referral fee mode. |
| `getTotalFeeNumerator(poolFees, baseFeeNumerator, maxFeeNumerator)` | Compute total trading fee numerator capped by pool version. |
| `getTotalTradingFeeFromIncludedFeeAmount(poolFees, currentPoint, activationPoint, includedFeeAmount, tradeDirection, maxFeeNumerator, initSqrtPrice, currentSqrtPrice)` | Compute trading fee from included amount. |
| `getTotalTradingFeeFromExcludedFeeAmount(poolFees, currentPoint, activationPoint, excludedFeeAmount, tradeDirection, maxFeeNumerator, initSqrtPrice, currentSqrtPrice)` | Compute trading fee from excluded amount. |
| `splitFees(poolFees, feeAmount, hasReferral)` | Split a fee amount into protocol, claiming, compounding, and referral shares. |
| `getFeeOnAmount(poolFees, amount, tradeFeeNumerator, hasReferral)` | Compute total fee and split shares for an amount. |
| `getExcludedFeeAmount(tradeFeeNumerator, includedFeeAmount)` | Convert included amount to excluded amount and trading fee. |
| `getIncludedFeeAmount(tradeFeeNumerator, excludedFeeAmount)` | Convert excluded amount to included amount and fee amount. |
| `getMaxFeeNumerator(feeVersion)` | Return max fee numerator for a pool fee version. |
| `getMaxFeeBps(feeVersion)` | Return max fee bps for a pool fee version. |
| `calculateInitSqrtPrice(tokenAAmount, tokenBAmount, minSqrtPrice, maxSqrtPrice)` | Calculate initial square-root price from token amounts and bounds. |
### Swap Quote Math
| Function | Use |
| - | - |
| `applySwapResult(poolState, result, feeMode, tradeDirection)` | Apply an in-memory swap result to pool state and return the post-swap square-root price. |
| `getSwapResultFromExactInput(poolState, amountIn, feeMode, tradeDirection, currentPoint)` | Compute swap result for exact input. |
| `getSwapResultFromPartialInput(poolState, amountIn, feeMode, tradeDirection, currentPoint)` | Compute swap result for partial input. |
| `getSwapResultFromExactOutput(poolState, amountOut, feeMode, tradeDirection, currentPoint)` | Compute swap result for exact output. |
| `swapQuoteExactInput(pool, currentPoint, amountIn, slippage, aToB, hasReferral, tokenADecimal, tokenBDecimal, inputTokenInfo?, outputTokenInfo?)` | Build an exact-input quote result. |
| `swapQuoteExactOutput(pool, currentPoint, amountOut, slippage, aToB, hasReferral, tokenADecimal, tokenBDecimal, inputTokenInfo?, outputTokenInfo?)` | Build an exact-output quote result. |
| `swapQuotePartialInput(pool, currentPoint, amountIn, slippage, aToB, hasReferral, tokenADecimal, tokenBDecimal, inputTokenInfo?, outputTokenInfo?)` | Build a partial-input quote result. |
### Math Utilities
| Function | Use |
| - | - |
| `mulDiv(x, y, denominator, rounding)` | Multiply, divide, and apply explicit rounding. |
| `q64ToDecimal(num, decimalPlaces?)` | Convert Q64 number to `Decimal`. |
| `decimalToQ64(num)` | Convert `Decimal` to Q64 `BN`. |
| `sqrt(value)` | Integer square-root helper. |
| `pow(base, exp)` | Integer exponentiation helper. |
## Core Types
The SDK exports many parameter and result aliases so app code can keep transaction-building code typed:
| Type | Description |
| - | - |
| `CreatePoolParams`, `InitializeCustomizeablePoolParams`, `InitializeCustomizeablePoolWithDynamicConfigParams` | Pool creation inputs. |
| `PreparePoolCreationParams`, `PreparedPoolCreation`, `PreparePoolCreationSingleSide` | Pool creation pre-calculation inputs and result. |
| `CreatePositionParams`, `AddLiquidityParams`, `CreatePositionAndAddLiquidity` | Position creation and add-liquidity inputs. |
| `LiquidityDeltaParams`, `GetDepositQuoteParams`, `GetWithdrawQuoteParams` | Liquidity and deposit/withdraw quote inputs. |
| `RemoveLiquidityParams`, `RemoveAllLiquidityParams`, `RemoveAllLiquidityAndClosePositionParams`, `MergePositionParams` | Remove, close, and merge inputs. |
| `GetQuoteParams`, `GetQuote2Params`, `SwapParams`, `Swap2Params`, `SwapAmount` | Swap quote and swap transaction inputs. |
| `LockPositionParams`, `PermanentLockParams`, `RefreshVestingParams` | Lock and vesting inputs. |
| `InitializeRewardParams`, `InitializeAndFundReward`, `FundRewardParams`, `ClaimRewardParams` | Reward setup, funding, and claim inputs. |
| `UpdateRewardDurationParams`, `UpdateRewardFunderParams`, `WithdrawIneligibleRewardParams` | Reward admin inputs. |
| `ClaimPositionFeeParams`, `ClaimPositionFeeParams2` | Position-fee claim inputs. |
| `SplitPositionParams`, `SplitPosition2Params` | Position split inputs. |
| `PoolFeesParams`, `DynamicFeeParams`, `FeeMode`, `FeeOnAmountResult`, `SplitFees` | Fee construction and fee-calculation types. |
| `InitialPoolInformation`, `SwapAmountFromInput`, `SwapAmountFromOutput` | Liquidity and swap math result types. |
| `TransferHookState`, `TransferFeeIncludedAmount`, `TransferFeeExcludedAmount` | Token-2022 helper result types. |
## Common Workflows
### Fetch Pool And Build A Quote
```typescript theme={"system"}
import BN from "bn.js"
import { CpAmm, SwapMode, getTokenProgram } from "@meteora-ag/cp-amm-sdk"
const cpAmm = new CpAmm(connection)
const poolState = await cpAmm.fetchPoolState(pool)
const quote = cpAmm.getQuote2({
poolState,
inputTokenMint: poolState.tokenAMint,
amountIn: new BN(1_000_000),
slippage: 0.5,
swapMode: SwapMode.ExactIn,
currentPoint,
tokenADecimal: 6,
tokenBDecimal: 6,
hasReferral: false,
})
```
`getQuote2` is the preferred quote path for new integrations because it supports exact-in, partial-fill, and exact-out behavior.
### Build A Swap Transaction
```typescript theme={"system"}
const tx = await cpAmm.swap2({
payer: user,
pool,
inputTokenMint: poolState.tokenAMint,
outputTokenMint: poolState.tokenBMint,
tokenAMint: poolState.tokenAMint,
tokenBMint: poolState.tokenBMint,
tokenAVault: poolState.tokenAVault,
tokenBVault: poolState.tokenBVault,
tokenAProgram: getTokenProgram(poolState.tokenAFlag),
tokenBProgram: getTokenProgram(poolState.tokenBFlag),
referralTokenAccount: null,
poolState,
swapMode: SwapMode.ExactIn,
amountIn: new BN(1_000_000),
minimumAmountOut: quote.minimumAmountOut!,
})
```
<Note>
Rate-limiter pools require the instructions sysvar account on low-level swap builders. The TypeScript SDK detects existing rate-limiter pools in `swap` and `swap2` when it has `poolState`; pass `poolState` to avoid an extra RPC read and to keep account planning explicit.
</Note>
### Decode Pool Fees
```typescript theme={"system"}
const poolFees = await cpAmm.fetchPoolFees(pool)
if (poolFees) {
// `poolFees` is one of the pod-aligned scheduler layouts.
}
```
Use the pod-aligned decoders for pool-state bytes and Borsh decoders for event bytes.
## Error Classes
The SDK exports typed errors that validation, quote, and math helpers may throw:
| Error | Typical trigger |
| - | - |
| `DepositTokenNotAcceptedError` | Deposit token does not match the position or pool side expected by the quote. |
| `InvalidFeeError` | Fee params are malformed or out of range. |
| `ExceedMaxFeeBpsError` | Fee bps exceeds the pool-version maximum. |
| `InvalidActivationTypeError` | Activation type is not a supported enum value. |
| `InvalidPriceRangeError` | Square-root price bounds are invalid for the collect-fee mode. |
| `InvalidCollectFeeModeError` | Collect-fee mode is not supported by the requested flow. |
| `InvalidCompoundingFeeBpsError` | Compounding fee bps is invalid. |
| `InvalidFeeTimeSchedulerError` | Time-scheduler fee params are invalid. |
| `InvalidFeeMarketCapSchedulerError` | Market-cap scheduler fee params are invalid. |
| `InvalidFeeRateLimiterError` | Rate-limiter params are invalid. |
| `InvalidDynamicFeeParametersError` | Dynamic-fee params are invalid. |
| `InvalidMinimumLiquidityError` | Initial liquidity is below the minimum, especially in compounding pool creation. |
| `AmountIsZeroError` | Required amount or liquidity delta is zero. |
| `InvalidBaseFeeModeError` | Base-fee mode is unsupported for the selected helper. |
| `DeprecatedBaseFeeModeError` | `getBaseFeeParams`, `validatePoolFees`, `createPool`, `createCustomPool`, or `createCustomPoolWithDynamicConfig` received `BaseFeeMode.RateLimiter`. |
| `InvalidPoolVersionError` | Pool version is unsupported by a helper. |
| `MathOverflowError` | Integer math overflows or cannot be represented. |
| `InsufficientLiquidityError` | Swap or withdraw math requests more liquidity than available. |
| `SwapDisabledError` | Pool is disabled or not activated for swapping. |
| `InvalidInputError` | General invalid input error. |
| `PriceRangeViolationError` | Quote or liquidity math would move outside allowed price bounds. |
| `SameTokenMintsError` | Pool creation or validation received identical mints. |
| `InvalidParametersError` | General invalid parameter error. |
| `InvalidSplitPositionParametersError` | Split position params are invalid. |
| `InvalidVestingInfoError` | Vesting data is invalid for lock or unlock flow. |
| `InvalidRewardIndexError` | Reward index is outside the supported range. |
| `InvalidRewardDurationError` | Reward duration is below or above allowed bounds. |
## Notes
| Topic | What to remember |
| - | - |
| Token order | Pool PDAs sort mints, but transaction params still need the pool's `tokenAMint` and `tokenBMint` fields. |
| Compounding mode | `CollectFeeMode.Compounding` uses full-range constant-product liquidity and splits swap fees into `claimingFee` and `compoundingFee`. |
| Rate limiter | Existing rate-limiter pools still require the instructions sysvar remaining account on low-level swap builders when the limiter is active. The SDK handles this when it can identify the pool mode. New configs and new pools cannot use `RateLimiter`. |
| Layout version | V1 pools track `tokenAAmount` and `tokenBAmount`. Use current SDK quote paths for compounding pools. |
| Swap events | Prefer `EvtSwap2` for swap indexing. Older swap events were deprecated and removed from newer program versions. |
| Position NFTs | Position ownership is verified through the Token-2022 position NFT account. Pass the derived `positionNftAccount` for liquidity, fee, lock, reward, split, and close flows. |
| Wrapped SOL | Transaction builders add wrap and unwrap instructions for native SOL paths, but your signing flow still needs enough SOL for rent, transaction fees, and wrapped input amounts. |
| Token-2022 fees | Pass mint and epoch data into quote helpers when a Token-2022 transfer-fee 프로젝트로 돌아가기