Meteora 백서

Meteora

원문

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

ance between two account-state snapshots. | | `parseFeeVaultInfo` | Build display context from two snapshots and USD rates. | | `parseTopStakerListState` | Build ordered top staker display rows. | | `getStakeEscrowEarningPerDay` | Estimate current daily earning for a stake escrow. | | `getStakeEscrowEarningPerDayAfterUnstake` | Estimate daily earning after a proposed unstake. | | `getLockedEscrowPendingFee` | Calculate pending DAMM v1 lock escrow fees. | | `getVirtualPrice` | Calculate constant-product LP virtual price. | | `getTokenBalances` | Calculate Dynamic Vault token balances from LP shares. | ### Transaction Helpers | Helper | Use | | - | - | | `computeUnitIx(units?)` | Build a compute budget limit instruction. | | `getSimulationComputeUnits` | Simulate a transaction to estimate compute units. | | `getEstimatedComputeUnitUsageWithBuffer` | Estimate compute with a buffer. | | `getEstimatedComputeUnitIxWithBuffer` | Build a compute unit instruction from the buffered estimate. | | `unwrapSOLInstruction(owner)` | Build an instruction to close the owner's wrapped SOL ATA. | ## Exported Types | Type | Use | | - | - | | `AccountStates` | Combined decoded state fetched by the SDK. | | `StakeForFeeProgram` | Anchor program type for `stake_for_fee`. | | `FeeVault`, `StakeEscrow`, `Unstake` | IDL account types. | | `TopListMetadata`, `FullBalanceListMetadata` | List account metadata types. | | `StakerMetadata`, `StakerBalance` | Appended list entry types. | | `Metrics`, `TopStakerInfo` | Nested vault state types. | | `InitializeVaultParams` | IDL parameter type for vault creation. | | `FullBalanceListState`, `TopStakerListState` | Decoded list states with metadata and entries. | | `TopStakerListStateContext`, `FeeVaultContext` | Display/helper output types. | ## Integration Notes | Topic | Note | | - | - | | Cached state | Methods use `accountStates` cached on the instance. Call `refreshStates()` after transactions or external state changes. | | Claim behavior | `claimFee` transfers quote token only; base/stake token fees are restaked. | | Unstake key | `unstake` expects a new account public key and the keypair must sign the transaction. | | Admin methods | The TypeScript wrapper does not expose high-level builders for `claim_fee_crank` or admin update instructions. Use the bundled IDL/program helpers for those flows. | | Package name | The published package is `@meteora-ag/m3m3`; some source changelog entries use the older `stake-for-fee` naming. | # Zap Changelog Source: https://docs.meteora.ag/developer-guides/zap/changelog Track Zap program and TypeScript SDK release notes, integration changes, and known source-material gaps. <Tip> Track Zap releases here. </Tip> <Update label="zap 0.2.2" description="Support Zap-In to damm-V2 Compounding Pool Fee Mode and single-sided damm-v2 pool"> ## Release summary | Component | Version | PR | | - | - | - | | Program | `0.2.2` | [zap-program #46](https://github.com/MeteoraAg/zap-program/pull/46) | | TypeScript SDK | `1.3.0` | [zap-sdk #30](https://github.com/MeteoraAg/zap-sdk/pull/30) | ## What We Shipped * Support Zap-In to damm-V2 Compounding Pool Fee Mode * Support Zap-In to single-sided damm-v2 pool ## 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>Support Zap-In to damm-V2 Compounding Pool Fee Mode and single-sided damm-v2 pool</li> </ul> </td> <td> <ul> <li>Bump your SDK version to <code>@meteora-ag/zap-sdk\@1.3.0</code> to start testing.</li> </ul> </td> </tr> </tbody> </table> </div> ## Program: `zap` `0.2.2` Program ID (mainnet and devnet): `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` [Program PR #46](https://github.com/MeteoraAg/zap-program/pull/46) ### Added * Add support for damm-v2 pool with Compounding fee mode ### Fixed * Fix zap in to single-sided damm-v2 pool. A single-sided pool is a pool fully contains only one token in the pool pair, either fully token a (`sqrt_price` at `sqrt_min_price`) or fully token b (`sqrt_price` at `sqrt_max_price`) ## TypeScript SDK: `@meteora-ag/zap-sdk` `1.3.0` [SDK PR #30](https://github.com/MeteoraAg/zap-sdk/pull/30) ### Added * Support Zap-In to damm-V2 Compounding Pool Fee Mode. * Support Zap-In to single-sided damm-v2 pool. A single-sided pool is a pool that fully contains only one token of the pool pair, either fully token A (`sqrt_price` at `sqrt_min_price`) or fully token B (`sqrt_price` at `sqrt_max_price`). ### Fixed * Rebalance DLMM position with 1 bin. Reference: [https://github.com/MeteoraAg/dlmm-sdk/pull/286](https://github.com/MeteoraAg/dlmm-sdk/pull/286) </Update> # Zap Developer Guide Source: https://docs.meteora.ag/developer-guides/zap/index Learn how to build Zap integrations for DAMM v2, DLMM, Jupiter-backed swaps, TypeScript SDK flows, Rust CPI, and release tracking. Zap is Meteora's helper program for composing token movement, swaps, and liquidity actions around DAMM v2, DLMM, and Jupiter routes. It is mainly used to zap into liquidity positions, zap out from token balances produced by another action, or rebalance an existing DLMM position. <Warning> The Meteora UI applies extra output-amount and extreme-impact checks. SDK / CPI integrations must add the same checks themselves: Zap In is multi-step and includes a Jupiter (or pool) **swap**. Example `maxAccounts` and Direct-route Jupiter flags are not safe for every pool or size. See [Zap TS SDK Getting Started](/developer-guides/zap/typescript-sdk/getting-started). </Warning> To learn more about Zap, including supported routes, and limits, you can read the following documentations. <CardGroup> <Card title="What Is Zap?" icon="book-open" href="/helper-products/zap/what-is-zap"> Product overview for Zap, supported AMM paths, and common user flows. </Card> <Card title="Formula And Limits" icon="calculator" href="/helper-products/zap/formula-and-limits"> Product formulas, limits, and route-level constraints. </Card> </CardGroup> ## Integration <CardGroup> <Card title="Program Accounts" icon="table-cells" href="/developer-guides/zap/program/accounts"> Account model, ledger PDA, supported downstream programs, constants, and IDL types. </Card> <Card title="Program Instructions" icon="list" href="/developer-guides/zap/program/instructions"> Instruction flows for ledger setup, zap out, DAMM v2 zap in, DLMM zap in, and DLMM rebalancing. </Card> <Card title="Program Errors" icon="triangle-exclamation" href="/developer-guides/zap/program/errors"> Anchor custom error codes, messages, common causes, and integration fixes. </Card> <Card title="TypeScript SDK" icon="code" href="/developer-guides/zap/typescript-sdk/getting-started"> TypeScript SDK for building Zap transactions and route-specific swap helpers. </Card> <Card title="Rust Integration" icon="terminal" href="/developer-guides/zap/rust-integration/cpi"> Rust CPI guidance and local helper crates for advanced protocol integrations. </Card> </CardGroup> ## Program IDs The `zap` program ID is the same on mainnet and devnet: | Network | Program ID | | - | - | | Mainnet Beta | `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` | | Devnet | `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` | ## Public Source <CardGroup> <Card title="Zap Program" icon="code" href="https://github.com/MeteoraAg/zap-program"> Anchor program source, local Rust helper crates, tests, and changelog. </Card> <Card title="Zap IDL" icon="file-code" href="https://github.com/MeteoraAg/zap-sdk/blob/main/src/idl/zap/idl.json"> Anchor IDL for the deployed `zap` program. </Card> </CardGroup> <CardGroup> <Card title="Zap TypeScript SDK" icon="node-js" href="https://github.com/MeteoraAg/zap-sdk"> TypeScript SDK source, examples, tests, IDL, and package changelog. </Card> </CardGroup> ## Commands | Task | Command | | - | - | | Build program | `cd zap-program && anchor build` | | Run program tests | `cd zap-program && pnpm install && pnpm test` | | Build TypeScript SDK | `cd zap-sdk && pnpm install && pnpm run build` | | Run SDK tests | `cd zap-sdk && pnpm test` | | Type-check SDK | `cd zap-sdk && pnpm run typecheck` | ## Stay Updated <CardGroup> <Card title="Zap Changelog" icon="newspaper" href="/developer-guides/zap/changelog"> Program and TypeScript SDK changes that affect integration planning. </Card> </CardGroup> # Zap Program Accounts Source: https://docs.meteora.ag/developer-guides/zap/program/accounts Understand Zap accounts, ledger PDA seeds, supported downstream program constants, route discriminators, and IDL parameter types. <Note> This page summarizes the `zap` account model from the local Anchor source and bundled IDL. For exact layouts, use the published IDL and generated TypeScript types exported by `@meteora-ag/zap-sdk`. </Note> ## Address Map | Address | How it is chosen | Use | | - | - | - | | `UserLedger` | PDA from `["user_ledger", owner]` | Temporary per-user state used by zap-in flows to record token A/B or token X/Y balances before the Zap instruction adds liquidity. | | DAMM v2 `Pool` | Existing `cp-amm` pool account | Read by `zap_in_damm_v2` to calculate liquidity, detect surplus, and perform an internal DAMM v2 `swap2` when needed. | | DAMM v2 position | Existing position account derived from the position NFT mint | Receives liquidity during `zap_in_damm_v2`. Zap does not create the DAMM v2 position. | | DLMM `LbPair` | Existing DLMM pair account | Read by DLMM zap-in instructions to derive token mints, reserves, active bin, bin step, and rebalance parameters. | | DLMM position | Existing or new position account | Existing positions are rebalanced by `zap_in_dlmm_for_initialized_position`; uninitialized signer accounts are created by `zap_in_dlmm_for_uninitialized_position`. | | User token accounts | Associated token accounts for pool tokens | Source balances for zap-in and zap-out flows. SDK builders create ATAs idempotently. | | Downstream event authorities | DAMM v2 or DLMM event authority PDAs | Required by downstream DAMM v2 and DLMM CPI calls. Zap itself does not emit custom events. | ## PDA Seeds | SDK helper | Seeds | Use | | - | - | - | | `deriveLedgerAccount(owner)` | `["user_ledger", owner]` | Derive the temporary `UserLedger` account for one user. | | `deriveDammV2PoolAuthority()` | `["pool_authority"]` under DAMM v2 | Passed to DAMM v2 CPI calls. | | `deriveDammV2EventAuthority()` | `["__event_authority"]` under DAMM v2 | Passed to DAMM v2 event-CPI instructions. | | `deriveDlmmEventAuthority()` | `["__event_authority"]` under DLMM | Passed to DLMM event-CPI instructions. | ## Program Constants | Constant | Value | Meaning | | - | - | - | | `ZAP_PROGRAM_ID` | `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` | Zap program address. | | `DAMM_V2_PROGRAM_ID` | `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG` | Supported DAMM v2 program for zap in/out. | | `DLMM_PROGRAM_ID` | `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo` | Supported DLMM program for zap in/out. | | `JUP_V6_PROGRAM_ID` | `JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4` | Supported Jupiter V6 program for zap out. | | `MEMO_PROGRAM_ID` | `MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr` | Passed to DLMM CPI flows. | | `MAX_BASIS_POINT` | `10_000` | Basis-point denominator used by program math. | | `USER_LEDGER_PREFIX` | `user_ledger` | Ledger PDA seed prefix. | ## Whitelisted Zap-Out Payloads `zap_out` validates the first 8 bytes of `payload_data` against this whitelist before invoking the downstream program. | Downstream program | Instruction | Discriminator | Amount offset | | - | - | - | - | | DAMM v2 | `swap2` | `[248, 198, 158, 145, 225, 117, 135, 200]` | `AMOUNT_IN_DAMM_V2_OFFSET = 8` | | DLMM | `swap2` | `[65, 75, 63, 76, 235, 91, 91, 136]` | `AMOUNT_IN_DLMM_OFFSET = 8` | | Jupiter V6 | `route` | `[229, 23, 203, 151, 122, 227, 173, 42]` | `payload_data.length - 19` | | Jupiter V6 | `shared_accounts_route` | `[193, 32, 155, 51, 65, 214, 156, 129]` | `payload_data.length - 19` | The amount offset points to the little-endian `u64` input amount that Zap overwrites at runtime with the post-action balance delta. ## UserLedger `UserLedger` is a zero-copy account. The SDK initializes it before zap-in and closes it during cleanup. | Field | Type | Use | | - | - | - | | `owner` | `Pubkey` | User that owns the ledger. Instructions require this signer through `has_one = owner`. | | `amount_a` | `u64` | Token A amount for DAMM v2 or token X amount for DLMM. | | `amount_b` | `u64` | Token B amount for DAMM v2 or token Y amount for DLMM. | ## ZapOutParameters | Field | Type | Use | | - | - | - | | `percentage` | `u8` | Share of the balance increase to swap. Must be greater than `0` and at most `100`. | | `offset_amount_in` | `u16` | Byte offset in `payload_data` where the downstream amount-in `u64` should be overwritten. | | `pre_user_token_balance` | `u64` | User token-account balance before the action that produced zap-out tokens. | | `max_swap_amount` | `u64` | Hard cap applied after percentage calculation. Protects against unrelated deposits into the same token account. | | `payload_data` | `bytes` | Serialized downstream swap instruction data with a whitelisted discriminator. | ## DLMM StrategyType | Variant | Use | | - | - | | `Spot` | Even distribution around the selected bin range. | | `Curve` | Curved distribution around the active bin. | | `BidAsk` | Bid-ask style distribution across the selected bin range. | The TypeScript SDK maps `@meteora-ag/dlmm` `StrategyType` values into the Zap IDL enum before building DLMM zap-in instructions. ## RemainingAccountsInfo | Field | Type | Use | | - | - | - | | `slices` | `Vec<RemainingAccountsSlice>` | Describes grouped DLMM remaining accounts, including Token 2022 transfer-hook accounts. | DLMM zap-in and zap-out flows are remaining-account-heavy. Use SDK helpers such as `getDlmmRemainingAccounts` and `getBinArraysRequiredByPositionRange` rather than hand-ordering account metas unless you are writing a low-level client. ## Account Notes | Flow | Important accounts | | - | - | | DAMM v2 zap in | Pool, position, position NFT token account, token vaults, token mints, token programs, DAMM v2 pool authority, DAMM v2 event authority, and any remaining accounts required by the pool. | | DLMM initialized zap in | LbPair, existing position, optional bin array bitmap extension, user token X/Y accounts, reserves, token mints, token programs, memo program, event authority, bin arrays, and transfer-hook accounts when required. | | DLMM uninitialized zap in | Same as initialized zap in, but `position` must be an uninitialized signer and Zap calls DLMM `initialize_position2` before rebalancing. | | Zap out | User input token account, whitelisted downstream program, and the exact remaining-account list expected by the downstream swap instruction. | ## Account Handling Notes | Note | Guidance | | - | - | | Ledger accounts are temporary | Close the ledger after zap-in cleanup to recover rent and avoid stale balances. | | Zap out uses balance deltas | Read `pre_user_token_balance` before the upstream claim, withdraw, or transfer action. | | Payload amount is overwritten | Build the downstream payload with a placeholder amount, then pass the correct offset for that route. | | Token 2022 may add accounts | DLMM transfer-hook mints require extra remaining accounts and a matching `RemainingAccountsInfo` slice. | | Native SOL is wrapped | SDK builders keep wrapped SOL accounts open until the Zap cleanup stage when needed. | # Zap Program Errors Source: https://docs.meteora.ag/developer-guides/zap/program/errors Understand Zap custom errors, error codes, validation failures, and integration fixes for zap-in and zap-out flows. Zap uses Anchor custom errors starting at code `6000`. ## Error Codes | Code | Name | Message | Common cause | Integration fix | | - | - | - | - | - | | `6000` | `MathOverflow` | `Math operation overflow` | Checked math overflow in balance, percentage, price, or liquidity calculations. | Keep token amounts within `u64`, verify pool math inputs, and avoid invalid price or bin ranges. | | `6001` | `InvalidOffset` | `Invalid offset` | `offset_amount_in + 8` exceeds `payload_data.length`. | Use route-specific offsets from the SDK constants and build payload data from the matching helper. | | `6002` | `InvalidZapOutParameters` | `Invalid zapout parameters` | `percentage` is `0` or greater than `100`. | Pass a zap-out percentage from `1` to `100`. | | `6003` | `TypeCastFailed` | `Type cast error` | A checked conversion from a wider integer failed. | Recheck amount and percentage inputs before building the transaction. | | `6004` | `AmmIsNotSupported` | `Amm program is not supported` | Payload discriminator and `amm_program` are not in the Zap whitelist. | Use DAMM v2 `swap2`, DLMM `swap2`, Jupiter V6 `route`, or Jupiter V6 `shared_accounts_route`. | | `6005` | `InvalidPosition` | `Position is not empty` | DLMM uninitialized-position zap-in received an already initialized account or a position equal to owner/rent payer. | Generate a fresh signer for `zap_in_dlmm_for_uninitialized_position`, or use the initialized-position path. | | `6006` | `ExceededSlippage` | `Exceeded slippage tolerance` | DAMM v2 post-swap square-root price moved beyond `max_sqrt_price_change_bps`. | Refresh pool state, use a tighter transaction path, or increase the accepted price-change bps if appropriate. | | `6007` | `InvalidDlmmZapInParameters` | `Invalid dlmm zap in parameters` | `min_delta_id > max_delta_id`. | Build a valid lower-to-upper bin range around the active bin. | | `6008` | `UnsupportedFeeMode` | `Unsupported fee mode` | DAMM v2 liquidity handler cannot handle the pool fee mode. | Upgrade to current Zap and SDK versions; verify the pool fee mode is supported by the deployed program. | ## Zap-Out Validation Failures | Symptom | Likely cause | Fix | | - | - | - | | `AmmIsNotSupported` | Wrong program ID for the payload discriminator. | Pair the discriminator with the exact downstream program ID. | | `InvalidOffset` | Jupiter payload offset was calculated as a fixed value rather than `payload_data.length - 19`. | Use `zapOutThroughJupiter` or compute the reverse offset from the serialized Jupiter route payload. | | No swap occurs | Post-action token balance is less than or equal to `pre_user_token_balance`. | Read the pre-balance before the upstream claim, withdraw, transfer, or remove-liquidity action. | | Swapped less than expected | `percentage` or `max_swap_amount` capped the balance delta. | Inspect `ZapOutParameters` and the post-action token-account balance. | ## Zap-In Validation Failures | Symptom | Likely cause | Fix | | - | - | - | | Ledger ownership failure | `owner` signer does not match `UserLedger.owner`. | Derive the ledger from the same user used to sign all ledger and zap-in instructions. | | DLMM uninitialized-position failure | Position account is already initialized or is not a fresh signer. | Generate a new keypair and include it as a signer for the zap-in transaction. | | DAMM v2 slippage failure | Pool price changed between client quote and on-chain internal swap. | Refresh pool state and rebuild the zap-in route. | | Downstream CPI error | DAMM v2 or DLMM account order is incomplete. | Preserve SDK-generated account metas, including event authorities, bin arrays, transfer-hook accounts, and rate-limiter accounts when required. | # Zap Program Instructions Source: https://docs.meteora.ag/developer-guides/zap/program/instructions Explore Zap instructions for ledger management, zap out, DAMM v2 zap in, DLMM zap in, and DLMM position rebalancing. The `zap` IDL exposes ledger helpers plus route-specific zap instructions. Most integrations should use the TypeScript SDK builders because they assemble token accounts, ledger transactions, dow
프로젝트로 돌아가기