Meteora 백서

Meteora

원문

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

| `binIdToBinArrayIndex` | Converts a bin ID to bin array index. | | `deriveBinArrayBitmapExtension` | Derives the bitmap extension account for a pool. | | `getBinArrayLowerUpperBinId` | Returns lower/upper bin IDs for a bin array index. | | `isBinIdWithinBinArray` | Checks whether a bin belongs to a bin array. | | `getBinFromBinArray` | Returns one bin from a loaded bin array. | | `isOverflowDefaultBinArrayBitmap` | Checks if a bin array index requires bitmap extension. | | `findNextBinArrayIndexWithLiquidity` | Finds next initialized bin array with liquidity in a direction. | | `findNextBinArrayWithLiquidity` | Same, but returns an account from loaded bin arrays. | | `getBinArraysRequiredByPositionRange` | Returns bin array PDAs required for a position range. | | `getBinIdIndexInBinArray` | Converts bin ID to its index inside a bin array. | | `binDeltaToMinMaxBinId` | Converts a bin delta around an active bin into min/max bin IDs. | | `decodeRewardPerTokenStored` | Decodes reward-per-token state from a bin. | | `enumerateBins` | Iterates bins across loaded bin arrays. | | `getBinArrayInfoForNonContiguousBinIds` | Returns bin array metas and bitmap account for arbitrary bin IDs. | ### Position Helpers | Helper | Description | | - | - | | `wrapPosition` | Wraps raw account data in a position wrapper. | | `getBinArrayIndexesCoverage`, `getBinArrayKeysCoverage`, `getBinArrayAccountMetasCoverage` | Derive bin array coverage for ranges. | | `getPositionLowerUpperBinIdWithLiquidity` | Trims a position range to bins with liquidity. | | `isPositionNoFee`, `isPositionNoReward` | Checks whether processed position data has claimable fees/rewards. | | `chunkBinRangeIntoExtendedPositions`, `chunkBinRange`, `chunkPositionBinRange` | Splits bin ranges for transaction and dynamic-position limits. | | `calculatePositionSize`, `getPositionRentExemption`, `getPositionExpandRentExemption` | Rent and account-size helpers. | | `getExtendedPositionBinCount`, `decodeExtendedPosition` | Dynamic position data helpers. | ### Strategy And Weight Helpers | Helper | Description | | - | - | | `getPriceOfBinByBinId` | Converts a bin ID and bin step to a decimal price. | | `calculateSpotDistribution` | Builds spot weight distribution. | | `calculateBidAskDistribution` | Builds bid/ask weight distribution. | | `calculateNormalDistribution` | Builds curve/normal distribution. | | `toAmountsBothSideByStrategy` | Converts strategy into token amounts per bin. | | `autoFillYByStrategy`, `autoFillXByStrategy` | Calculates missing side amount for strategy deposits. | | `toStrategyParameters` | Converts SDK strategy enum into program strategy parameters. | | `toWeightDistribution` | Converts bps distributions into program weights. | | `fromWeightDistributionToAmount`, `fromWeightDistributionToAmountOneSide` | Converts weights back to token amounts. | | `toAmountBidSide`, `toAmountAskSide`, `toAmountBothSide` | Lower-level helpers for converting weight distribution to token amounts by side. | | `autoFillYByWeight`, `autoFillXByWeight` | Calculates missing side amount for weight deposits. | ### Fee And Math Helpers | Helper | Description | | - | - | | `getBaseFee`, `getVariableFee`, `getTotalFee` | Fee rate helpers. | | `computeFee`, `computeFeeFromAmount`, `computeProtocolFee` | Fee amount helpers. | | `getExcludedFeeAmount`, `getIncludedFeeAmount`, `splitFee` | Fee-inclusive/exclusive calculations. | | `computeBaseFactorFromFeeBps` | Converts fee bps into base factor and base fee power factor. | | `getQPriceFromId`, `getQPriceBaseFactor` | Q64.64 price helpers. | | `mulShr`, `shlDiv`, `mulDiv`, `pow` | Fixed-point arithmetic helpers. | | `getC`, `distributeAmountToCompressedBinsByRatio` | Seed-liquidity and compression math helpers. | | `generateAmountForBinRange`, `generateBinAmount`, `compressBinAmount`, `findOptimumDecompressMultiplier` | Seed liquidity compression helpers. | ### RPC And Transaction Helpers | Helper | Description | | - | - | | `chunks`, `range` | Array utilities. | | `chunkedFetchMultiplePoolAccount`, `chunkedFetchMultipleBinArrayBitmapExtensionAccount` | Batched account fetch helpers. | | `chunkedGetMultipleAccountInfos`, `chunkedGetProgramAccounts` | RPC-safe batched reads. | | `getTokenDecimals`, `getTokenBalance` | Token account reads. | | `getOrCreateATAInstruction` | Returns ATA address and optional create instruction. | | `wrapSOLInstruction`, `unwrapSOLInstruction` | Native SOL wrapping helpers. | | `parseLogs` | Parses Anchor events from transaction logs. | | `getEstimatedComputeUnitUsageWithBuffer`, `getEstimatedComputeUnitIxWithBuffer` | Simulation-based compute budget helpers. | | `getDefaultExtendPositionCU`, `getSimulationComputeUnits` | Lower-level compute unit helpers. | | `createProgram`, `decodeAccount`, `getAccountDiscriminator` | Anchor program/account helpers. | | `capSlippagePercentage`, `getAndCapMaxActiveBinSlippage`, `getSlippageMaxAmount`, `getSlippageMinAmount` | Slippage helpers. | | `getBinCount`, `getPositionCountByBinCount` | Position/bin count helpers. | | `resetUninvolvedLiquidityParams` | Clears liquidity params outside the active update range. | | `encodePositionPermissions` | Encodes position permission bits. | ### Pool State Helpers | Helper | Description | | - | - | | `getTokenProgramId` | Returns token X/Y program IDs from an `LbPair`. | | `isSupportLimitOrder` | Checks whether a pool supports limit order behavior. | | `getFeeMode` | Returns fee-on-input/output behavior for a swap direction. | ### Rebalance Helper Exports | Helper | Description | | - | - | | `getLiquidityStrategyParameterBuilder` | Returns the strategy parameter builder for spot, curve, or bid/ask strategies. | | `suggestBalancedXParametersFromY`, `suggestBalancedYParametersFromX` | Suggest balanced strategy parameters from a single-side input. | | `getAutoFillAmountByRebalancedPosition` | Computes autofill amounts for rebalance simulation. | | `buildLiquidityStrategyParameters` | Builds rebalance liquidity strategy parameters. | | `buildBitFlagAndNegateStrategyParameters` | Encodes rebalance deposit/withdraw flags. | | `getAmountInBinsBidSide`, `getAmountInBinsAskSide`, `toAmountIntoBins` | Convert rebalance amounts into per-bin values. | | `getRebalanceBinArrayIndexesAndBitmapCoverage` | Computes 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: | Export | Description | | - | - | | `swapExactInQuoteAtBin`, `swapExactOutQuoteAtBin`, `getAmountIn`, `getAmountOut`, `getBinMaxAmountOut`, `getLimitOrderLiquidity` | Single-bin quote and liquidity helpers used internally by quote simulation. | | `BalancedStrategyBuilder`, `SpotStrategyParameterBuilder`, `CurveStrategyParameterBuilder`, `BidAskStrategyParameterBuilder` | Strategy builder classes used by rebalance and liquidity strategy helpers. | | `PositionV2Wrapper`, `LimitOrderV1Wrapper`, `LimitOrderBinDataWrapper` | Account wrapper classes for parsed position and limit order data. | | `capBps`, `MAX_BPS`, `REBALANCE_POSITION_PADDING` | Rebalance 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_CU` | Compute unit defaults used by transaction builders. | | `POSITION_MIN_SIZE`, `POSITION_BIN_DATA_SIZE`, `LIMIT_ORDER_MIN_SIZE`, `LIMIT_ORDER_BIN_DATA_SIZE` | Dynamic account size constants. | | `ClockLayout`, `MEMO_PROGRAM_ID` | Clock account decoder and memo program constant used by v2 builders. | | `chunkDepositWithRebalanceEndpoint` | Internal-style helper for chunking deposit instructions through the rebalance endpoint. | | `derivePlaceHolderAccountMeta` | Derives the placeholder account meta used for optional accounts. | | `getTokensMintFromPoolAddress` | Helper for decoding token mints from a pool address. | | `DLMMError` | Legacy SDK error export alongside `DlmmSdkError`. | ### Account Filters Use these with `getProgramAccounts`: | Filter | Description | | - | - | | `presetParameter2BinStepFilter` | Filter `PresetParameter2` by bin step. | | `presetParameter2BaseFactorFilter` | Filter `PresetParameter2` by base factor. | | `presetParameter2BaseFeePowerFactor` | Filter `PresetParameter2` by base fee power factor. | | `binArrayLbPairFilter` | Filter bin arrays by pool. | | `positionOwnerFilter` | Filter positions by owner. | | `positionLbPairFilter` | Filter positions by pool. | | `positionV2Filter` | Filter `PositionV2` accounts. | | `limitOrderFilter` | Filter limit order accounts. | | `limitOrderOwnerFilter` | Filter limit orders by owner. | | `limitOrderLbPairFilter` | Filter 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: | Export | Description | | - | - | | `wrapOracle` | Wraps a raw oracle account. | | `DynamicOracle` | Oracle wrapper class. | | `Observation` | Observation wrapper. | | `TwapResult&lt;T&gt;` | Result type for TWAP reads. | ## Limit Order Wrappers Low-level exports from `helpers/limitOrders` include: | Export | Description | | - | - | | `decodeLimitOrderBinData` | Decodes dynamic limit order bin data bytes. | | `wrapLimitOrder` | Wraps a `LimitOrder` account and dynamic bin data. | | `LimitOrderV1Wrapper` | Wrapper implementing the limit order interface. | | `LimitOrderBinDataWrapper` | Wrapper for one limit order bin entry. | | `ParsedLimitOrder`, `ParsedLimitOrderBinData` | Parsed limit order views. | ## Error Handling Quote methods throw `DlmmSdkError` for SDK-level quote failures. Common cases include: | Code | Meaning | | - | - | | `INVALID_MAX_EXTRA_BIN_ARRAYS` | `maxExtraBinArrays` is outside the supported range. | | `SWAP_QUOTE_INSUFFICIENT_LIQUIDITY` | Loaded 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. # Dynamic Fee Sharing Changelog Source: https://docs.meteora.ag/developer-guides/dynamic-fee-sharing/changelog Track Dynamic Fee Sharing program and TypeScript SDK release notes, integration changes, and known source-material gaps. <Tip> Track Dynamic Fee Sharing releases here. </Tip> <Update label="dynamic-fee-sharing 0.1.1" description="Direct Fee Funding Support with DAMM v2 and Dynamic Bonding Curve"> ## Release summary | Component | Version | PR | | - | - | - | | Program | `0.1.1` | [dynamic-fee-sharing #8](https://github.com/MeteoraAg/dynamic-fee-sharing/pull/8) | | TypeScript SDK | `1.0.3` | [dynamic-fee-sharing-sdk #7](https://github.com/MeteoraAg/dynamic-fee-sharing-sdk/pull/7) | ## What We Shipped * Direct Fee Funding Support with DAMM v2 and Dynamic Bonding Curve ## What To Do <div> <table> <thead> <tr> <th>Integrators</th> <th>What Changed</th> <th>What To Do</th> </tr> </thead> <tbody> <tr> <td><strong>Partners</strong></td> <td> <ul> <li>Direct Fee Funding Support with DAMM v2 and Dynamic Bonding Curve</li> </ul> </td> <td> <ul> <li>Bump your SDK version to <code>@meteora-ag/dynamic-fee-sharing-sdk\@1.0.3</code> to start testing.</li> </ul> </td> </tr> </tbody> </table> </div> ## Program: `dynamic-fee-sharing` `0.1.1` Program ID (mainnet and devnet): `dfsdo2UqvwfN8DuUVrMRNfQe11VaiNoKcMqLHVvDPzh` [Program PR #8](https://github.com/MeteoraAg/dynamic-fee-sharing/pull/8) ### Added * Add new field `fee_vault_type` in `FeeVault` to distinguish between PDA-derived and keypair-derived fee vaults. * Add new endpoint `fund_by_claiming_fee`, that allow share holder in fee vault to claim fees from whitelisted endpoints of DAMM-v2 or Dynamic Bonding Curve ## TypeScript SDK: `@meteora-ag/dynamic-fee-sharing-sdk` `1.0.3` [SDK PR #7](https://github.com/MeteoraAg/dynamic-fee-sharing-sdk/pull/7) ### Added * `fundByClaimDammV2Fee` function to fund a fee vault by claiming fee from a DAMM v2 pool. * `fundByClaimDammV2Reward` function to fund a fee vault by claiming reward from a DAMM v2 pool. * `fundByClaimDbcCreatorTradingFee` function to fund a fee vault by claiming creator trading fee from a DBC pool. * `fundByClaimDbcPartnerTradingFee` function to fund a fee vault by claiming partner trading fee from a DBC pool. * `fundByWithdrawDbcCreatorSurplus` function to fund a fee vault by withdrawing creator surplus from a DBC pool. * `fundByWithdrawDbcPartnerSurplus` function to fund a fee vault by withdrawing partner surplus from a DBC pool. * `fundByWithdrawMigrationFee` function to fund a fee vault by withdrawing migration fee from a DBC pool. </Update> # Dynamic Fee Sharing Developer Guide Source: https://docs.meteora.ag/developer-guides/dynamic-fee-sharing/index Learn how to build Dynamic Fee Sharing integrations with the on-chain program, TypeScript SDK, Rust CPI bindings, and release notes. Dynamic Fee Sharing lets a project configure a token fee vault, fund fees into it, and let configured shareholders claim their share over time. To learn more about product behavior, design considerations, compatibility, and formulas, you can read the following documentations. <CardGroup> <Card title="Learn more about Dynamic Fee Sharing" icon="book-open" href="/helper-products/dynamic-fee-sharing/what-is-dynamic-fee-sharing"> Product overview for fee vaults, fee sharing flows, and high-level integration behavior. </Card> <Card title="Dynamic Fee Sharing Formulas" icon="calculator" href="/helper-products/dynamic-fee-sharing/formulas"> Formula references for fee allocation, user shares, and claim accounting. </Card> </CardGroup> ## Integration <CardGroup> <Card title="Program Accounts" icon="table-cells" href="/developer-guides/dynamic-fee-sharing/program/accounts"> Fee vault state, token vault PDA, fee vault authority PDA, constants, and token support. </Card> <Card title="Program Instructions" icon="list" href="/developer-guides/dynamic-fee-sharing/program/instructions"> Initialization, direct funding, source-program funding, and fee claim instruction details. </Card> <Card title="Program Events" icon="list" href="/developer-guides/dynamic-fee-sharing/program/events"> Anchor event-CPI payloads for vault initialization, funding, and user claims. </Card> <Card title="Program Errors" icon="triangle-exclamation" href="/developer-guides/dynamic-fee-sharing/program/errors"> Anchor custom error codes, enum names, messages, and common integration causes. </Card> <Card title="TypeScript SDK" icon="code" href="/developer-guides/dynamic-fee-sharing/typescript-sdk/getting-started"> TypeScript SDK for creating vaults, funding them, reading state, and claiming user fees. </Card> <Card title="Rust CPI" icon="terminal" href="/developer-guides/dynamic-fee-sharing/rust-integration/cpi"> Anchor CPI integration with the `dynamic-fee-sharing` program crate. </Card> </CardGroup> ## Program IDs The `dynamic_fee_sharing` program ID is the same on mainnet and devnet: | Network | Program ID | | - | - | | Mainnet Beta | `dfsdo2UqvwfN8DuUVrMRNfQe11VaiNoKcMqLHVvDPzh` | | Devnet | `dfsdo2UqvwfN8DuUVrMRNfQe11VaiNoKcMqLHVvDPzh` | The program-wide fee vault authority PDA is: | Authority | Address | | - | - | | Fee Vault Authority | `EYqHRdtepv1KKUkPAYMBYpSfiGfNd8sa55ZtswodTfBS` | ## Fee Vault Types | Vault type | Address model | Created by | Main use | | - | - | - | - | | Non-PDA fee vault | External keypair account | `initialize_fee_vault` / `createFeeVault` | Standalone fee sharing when the vault address can be created and stored off-chain. | | PDA fee vault | PDA from `["fee_vault", base, token_mint]` | `initialize_fee_vault_pda` / `createFeeVaultPda` | Protocol integrations where a deterministic vault address must sign source-program fee claims. | Both vault types share the same `FeeVault` state layout and support direct funding plus user claims. Only PDA fee vaults support `fund_by_claiming_fee`, because the vault PDA signs the downstream whitelisted claim or withdrawal instruction. ## Source Repositories <CardGroup> <Card title="Dynamic Fee Sharing Program" icon="code" href="https://github.com/MeteoraAg/dynamic-fee-sharing"> Anchor program source for `dynamic_fee_sharing`. </Card> <Card title="Dynamic Fee Sharing IDL" icon="file-code" href="https://github.com/MeteoraAg/dynamic-fee-sharing-sdk/blob/main/src/idl/idl.json"> Published IDL used by the TypeScript SDK. </Card> </CardGroup> <CardGroup> <Card title="TypeScript SDK" icon="node-js" href="https://github.com/MeteoraAg/dynamic-fee-sharing-sdk"> SDK for transaction builders, state reads, PDA helpers, and example scripts. </Card> </CardGroup> ## Commands | Task | Command | | - | - | | Build program | `cd dynamic-fee-sharing && anchor build` | | Run program tests | `cd dynamic-fee-sharing && pnpm install && pnpm test` | | Build TypeScript SDK | `cd dynamic-fee-sharing-sdk && pnpm install && pnpm run build` | | Run TypeScript SDK tests | `cd dynamic-fee-sharing-sdk && bun test` | ## Stay Updated <CardGroup> <Card title="Dynamic Fee Sharing Changelog" icon="newspaper" href="/developer-guides/dynamic-fee-sharing/changelog"> Program and SDK changes for integration planning. </Card> </CardGroup> # Dynamic Fee Sharing Program Accounts Source: https://docs.meteora.ag/developer-guides/dynamic-fee-sharing/program/accounts Understand Dynamic Fee Sharing accounts, PDA seeds, constants, fee vault state, user share accounting, and token support. <Note> This page summarizes the `dynamic_fee_sharing` account model from the local Anchor source and SDK IDL. For generated TypeScript layouts, use the account types exported by `@meteora-ag/dynamic-fee-sharing-sdk`. </Note> ## Address Map | Address | How it is chosen | Use | | - | - | - | | `FeeVault` | External signer account for non-PDA vaults, or PDA from `["fee_vault", base, token_mint]` for PDA vaults | Main zero-copy state for one token fee sharing configuration. | | Fee vault authority | PDA from `["fee_vault_authority"]` | Program signer authority for vault token transfers. | | Token vault | PDA token account from `["token_vault", fee_vault]` | Holds the funded token mint for the fee vault. | | Event authority | Anchor event-CPI PDA from `["__event_authority"]` | Required by event-emitting instructions as generated by Anchor clients. | ## PDA Seeds | SDK helper | Seeds | Returns | Use | | - | - | - | - | | `deriveFeeVaultAuthorityAddress()` | `["fee_vault_authority"]` | `PublicKey` | Program-wide authority over token vault accounts. | | `deriveTokenVaultAddress(feeVault)` | `["token_vault", fee_vault]` | `PublicKey` | Token account PDA for a fee vault. | | `deriveFeeVaultPdaAddress(base, tokenMint)` | `["fee_vault", base, token_mint]` | `PublicKey` | Deterministic PDA fee vault address. | | `deriveDammV2EventAuthorityAddress()` | `["__event_authority"]` under the DAMM v2 program | `PublicKey` | Helper for DAMM v2 source-pro
프로젝트로 돌아가기