bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 62쪽
nstream payloads, bin arrays, and cleanup transactions.
## Instruction Index
| Instruction | TypeScript SDK path | Use |
| - | - | - |
| `initialize_ledger_account` | Internal to zap-in builders | Create the user's temporary `UserLedger` PDA. |
| `close_ledger_account` | Internal to zap-in builders | Close the ledger and send rent to `rent_receiver`. |
| `set_ledger_balance` | Internal to zap-in builders | Set one ledger side directly when the user already holds the pool token. |
| `update_ledger_balance_after_swap` | Internal to zap-in builders | Store the post-swap token-account balance delta, capped by `max_transfer_amount`. |
| `zap_out` | `zapOut`, `zapOutThroughDammV2`, `zapOutThroughDlmm`, `zapOutThroughJupiter` | Swap a newly received token-account balance increase through a whitelisted downstream payload. |
| `zap_in_damm_v2` | `buildZapInDammV2Transaction` | Add ledger balances to a DAMM v2 position, swap surplus, then add remaining liquidity. |
| `zap_in_dlmm_for_initialized_position` | `rebalanceDlmmPosition` | Rebalance an existing DLMM position using ledger balances and a selected strategy. |
| `zap_in_dlmm_for_uninitialized_position` | `buildZapInDlmmTransaction` | Initialize a new DLMM position and add liquidity using ledger balances. |
## Ledger Instructions
Zap-in flows use a short-lived ledger to keep token balances consistent across multiple transactions.
| Instruction | Accounts | Arguments | Behavior |
| - | - | - | - |
| `initialize_ledger_account` | `ledger`, `owner`, `payer`, `system_program` | None | Initializes `UserLedger` at `["user_ledger", owner]` and stores `owner`. |
| `close_ledger_account` | `ledger`, `owner`, `rent_receiver` | None | Requires `ledger.owner == owner`, closes the ledger, and sends rent to `rent_receiver`. |
| `set_ledger_balance` | `ledger`, `owner` | `amount`, `is_token_a` | Sets `amount_a` when `is_token_a` is true, otherwise sets `amount_b`. |
| `update_ledger_balance_after_swap` | `ledger`, `token_account`, `owner` | `pre_source_token_balance`, `max_transfer_amount`, `is_token_a` | Reads the current token account amount, stores `min(current - pre_source_token_balance, max_transfer_amount)` into the selected ledger side. |
Use `set_ledger_balance` for a pool token the user already contributes directly. Use `update_ledger_balance_after_swap` when a previous swap transaction produced the token.
## Zap Out
`zap_out` is a generic wrapper around a whitelisted downstream swap instruction.
| Input | Requirement |
| - | - |
| `percentage` | Must be from `1` to `100`. |
| `payload_data` | First 8 bytes must match a whitelisted DAMM v2, DLMM, or Jupiter V6 discriminator. |
| `offset_amount_in` | Must point to an 8-byte `u64` range inside `payload_data`. |
| `pre_user_token_balance` | Must be read before the upstream action that adds input tokens. |
| `max_swap_amount` | Caps the computed swap amount. |
| `remaining_accounts` | Must exactly match the downstream swap instruction account order. |
Execution:
1. Validate zap-out parameters and downstream discriminator.
2. Read the post-action balance from `user_token_in_account`.
3. Return without swapping if the balance did not increase.
4. Compute `swap_amount = min(balance_delta * percentage / 100, max_swap_amount)`.
5. Overwrite the downstream payload amount at `offset_amount_in`.
6. Invoke the downstream swap instruction with the provided remaining accounts.
## DAMM v2 Zap In
`zap_in_damm_v2` uses ledger balances to add liquidity to an existing DAMM v2 position.
| Account | Notes |
| - | - |
| `ledger` | Mutable `UserLedger`; owner must sign. |
| `pool` | Mutable DAMM v2 pool account. |
| `position` | Mutable existing DAMM v2 position. |
| `token_a_account`, `token_b_account` | User token accounts. |
| `token_a_vault`, `token_b_vault` | Pool token vaults. |
| `token_a_mint`, `token_b_mint` | Pool token mints. |
| `position_nft_account` | Position NFT token account proving position ownership to DAMM v2. |
| `damm_program`, `damm_event_authority` | DAMM v2 program and event authority. |
| Argument | Type | Use |
| - | - | - |
| `pre_sqrt_price` | `u128` | Pool square-root price observed before building the transaction. |
| `max_sqrt_price_change_bps` | `u32` | Maximum allowed square-root price movement after the internal surplus swap. |
Execution:
1. Calculate liquidity from ledger token A/B amounts after transfer-fee exclusion.
2. Add liquidity once so any following internal swap can still accrue pool fees to the position.
3. Update the ledger with the amounts consumed by the first add-liquidity call.
4. If one side remains, calculate a DAMM v2 `swap2` amount for the surplus side and perform the swap through CPI.
5. Check `post_sqrt_price` against `pre_sqrt_price` and `max_sqrt_price_change_bps`.
6. Add liquidity again with the newly balanced token amounts.
7. Update and log remaining ledger balances.
<Note>
DAMM v2 rate-limited pools can require extra remaining accounts for the internal `swap2` CPI. Preserve the remaining-account list generated by the SDK.
</Note>
## DLMM Zap In
DLMM zap-in uses DLMM `rebalance_liquidity` after constructing an add-liquidity distribution from the selected strategy.
| Instruction | Position behavior | Use |
| - | - | - |
| `zap_in_dlmm_for_initialized_position` | `position` is an existing DLMM position | Rebalance or add liquidity to an existing position. |
| `zap_in_dlmm_for_uninitialized_position` | `position` is an uninitialized signer | Create a DLMM position with `initialize_position2`, then rebalance liquidity into it. |
| Argument | Type | Use |
| - | - | - |
| `active_id` | `i32` | Active bin expected by the client. |
| `min_delta_id` | `i32` | Lower bin offset from the pair active bin. Must be less than or equal to `max_delta_id`. |
| `max_delta_id` | `i32` | Upper bin offset from the pair active bin. |
| `max_active_bin_slippage` | `u16` | Maximum active-bin movement accepted by DLMM rebalance. |
| `favor_x_in_active_id` | `bool` | Whether the active bin allocation favors token X. |
| `strategy` | `StrategyType` | `Spot`, `Curve`, or `BidAsk`. |
| `remaining_accounts_info` | `RemainingAccountsInfo` | Describes transfer-hook and other DLMM remaining-account slices. |
For uninitialized positions, Zap derives:
| Derived value | Formula |
| - | - |
| `lower_bin_id` | `lb_pair.active_id + min_delta_id` |
| `width` | `max_delta_id - min_delta_id + 1` |
The uninitialized `position` account must have the default owner and empty data, and must not equal `owner` or `rent_payer`.
## Transaction Sequencing
| Step | Typical content |
| - | - |
| 1. Setup | Create ATAs, wrap SOL if needed, and prepare any route-specific accounts. |
| 2. Swap | Execute Jupiter, DAMM v2, or DLMM swaps that produce pool token balances. |
| 3. Ledger | Initialize or reset `UserLedger`; set direct balances and record post-swap deltas. |
| 4. Zap | Call `zap_in_damm_v2`, `zap_in_dlmm_for_uninitialized_position`, or `zap_in_dlmm_for_initialized_position`. |
| 5. Cleanup | Close `UserLedger`; unwrap SOL if needed. |
For zap out, place the upstream action that creates the input token balance before the `zap_out` instruction in the same transaction or transaction sequence that preserves the pre-balance assumption.
# Zap CPI Integration
Source: https://docs.meteora.ag/developer-guides/zap/rust-integration/cpi
Learn how to call Zap instructions through Rust CPI, pass ledger and downstream accounts, and handle zap-out payload constraints.
Use CPI when your Solana program needs to call Zap directly. Most client apps should use the TypeScript SDK instead because Zap flows require careful transaction ordering, token account setup, and downstream remaining accounts.
## Program ID
| Network | Program ID |
| - | - |
| Mainnet Beta | `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` |
| Devnet | `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` |
## Generated Bindings
For a Rust program in the same workspace, enable the Zap program crate with the `cpi` feature:
```toml theme={"system"}
[dependencies]
zap = { path = "../zap-program/programs/zap", features = ["cpi"] }
```
The crate name in Rust code is `zap`.
## CPI Pattern
Anchor generates CPI helpers from the program crate. For low-level zap out:
```rust theme={"system"}
use anchor_lang::prelude::*;
use zap::cpi;
use zap::cpi::accounts::ZapOutCtx;
use zap::ZapOutParameters;
pub fn zap_out_via_cpi<'info>(
ctx: Context<'_, '_, '_, 'info, YourZapOutCtx<'info>>,
params: ZapOutParameters,
remaining_accounts: Vec<AccountInfo<'info>>,
) -> Result<()> {
let cpi_program = ctx.accounts.zap_program.to_account_info();
let cpi_accounts = ZapOutCtx {
user_token_in_account: ctx.accounts.user_token_in_account.to_account_info(),
amm_program: ctx.accounts.amm_program.to_account_info(),
};
cpi::zap_out(
CpiContext::new(cpi_program, cpi_accounts)
.with_remaining_accounts(remaining_accounts),
params,
)
}
```
The remaining accounts are forwarded by Zap to the whitelisted downstream swap instruction. Their order, signer flags, and writable flags must match the downstream program's expected account list.
## Common CPI Calls
| CPI call | Account context | Parameters | Notes |
| - | - | - | - |
| `cpi::initialize_ledger_account` | `InitializeLedgerAccountCtx` | None | Creates `UserLedger` at `["user_ledger", owner]`. |
| `cpi::close_ledger_account` | `CloseLedgerAccountCtx` | None | Closes the ledger and sends rent to `rent_receiver`. |
| `cpi::set_ledger_balance` | `SetLedgerBalanceCtx` | `amount`, `is_token_a` | Writes a direct token A/X or token B/Y amount. |
| `cpi::update_ledger_balance_after_swap` | `UpdateLedgerBalanceAfterSwapCtx` | `pre_source_token_balance`, `max_transfer_amount`, `is_token_a` | Stores a capped token-account balance delta. |
| `cpi::zap_out` | `ZapOutCtx` | `ZapOutParameters` | Invokes a whitelisted downstream swap payload. |
| `cpi::zap_in_damm_v2` | `ZapInDammv2Ctx` | `pre_sqrt_price`, `max_sqrt_price_change_bps` | Adds liquidity to an existing DAMM v2 position and may CPI to DAMM v2 `swap2`. |
| `cpi::zap_in_dlmm_for_initialized_position` | `ZapInDlmmForInitializedPositionCtx` | DLMM bin, strategy, and remaining-account info args | Rebalances an existing DLMM position. |
| `cpi::zap_in_dlmm_for_uninitialized_position` | `ZapInDlmmForUnintializedPositionCtx` | DLMM bin, strategy, and remaining-account info args | Initializes a new DLMM position, then rebalances liquidity. |
<Note>
The uninitialized DLMM account context name is spelled `ZapInDlmmForUnintializedPositionCtx` in the current Rust source. Use the generated binding name exactly.
</Note>
## Zap-Out CPI Requirements
| Requirement | Details |
| - | - |
| Whitelisted program | `amm_program` and the first 8 bytes of `payload_data` must match DAMM v2 `swap2`, DLMM `swap2`, Jupiter V6 `route`, or Jupiter V6 `shared_accounts_route`. |
| Amount offset | DAMM v2 and DLMM use offset `8`; Jupiter V6 route payloads use `payload_data.length - 19`. |
| Input token account | `user_token_in_account` is the token account whose balance increase Zap will swap. |
| Signers | Downstream signer accounts in `remaining_accounts` must already be transaction signers or PDA signer accounts provided by the caller. |
| Balance delta | Zap swaps only `post_balance - pre_user_token_balance`, multiplied by `percentage` and capped by `max_swap_amount`. |
## Zap-In CPI Requirements
| Flow | Required setup |
| - | - |
| DAMM v2 zap in | Ledger initialized and populated, existing DAMM v2 position, position NFT account, pool vaults, token mints, token programs, DAMM v2 program, and DAMM v2 event authority. |
| DLMM initialized zap in | Ledger initialized and populated, existing DLMM position, LbPair, reserves, token accounts, token mints, token programs, memo program, system program, DLMM event authority, bin arrays, and transfer-hook accounts when required. |
| DLMM uninitialized zap in | Same as initialized, but `position` is a fresh signer and Zap calls DLMM `initialize_position2`. |
Zap does not emit its own custom events, but DAMM v2 and DLMM downstream CPI calls require their event authority accounts.
## Token And Account Planning
| Area | CPI guidance |
| - | - |
| Token accounts | Create ATAs or token accounts before calling Zap. The CPI helpers do not create them for you. |
| Native SOL | Wrap SOL into a token account before CPI and unwrap after your flow if needed. |
| Token 2022 | Pass the correct token program for each mint and include transfer-hook extra accounts for DLMM flows when required. |
| Ledger cleanup | Close the ledger after the zap-in instruction when it is no longer needed. |
| Remaining accounts | Preserve the exact downstream account order generated by the corresponding SDK or IDL helper. |
## Common CPI Failures
| Error area | CPI-side fix |
| - | - |
| `InvalidOffset` | Recalculate `offset_amount_in` for the exact serialized payload. |
| `AmmIsNotSupported` | Match the payload discriminator to the downstream program ID. |
| Ledger owner mismatch | Derive the ledger from the same `owner` signer used in the CPI context. |
| DLMM invalid position | Use the initialized-position path for existing positions, or pass a fresh signer for the uninitialized-position path. |
| Downstream account error | Include event authorities, bin arrays, token programs, transfer-hook accounts, and any rate-limiter accounts required by the downstream route. |
## Best Practices
| Practice | Why it matters |
| - | - |
| Prefer generated bindings | Anchor CPI helpers keep account structs and argument order aligned with the IDL. |
| Use SDK-built payloads as references | The TypeScript SDK source shows the exact DAMM v2, DLMM, and Jupiter payload formats. |
| Simulate full flows | Zap calls downstream programs and depends on token balance deltas. |
| Keep caps conservative | `max_transfer_amount` and `max_swap_amount` are safety limits, not quote outputs. |
| Test every route variant | DAMM v2, DLMM, Jupiter route, Jupiter shared route, Token 2022, and native SOL paths differ in account requirements. |
# Zap TS SDK Examples
Source: https://docs.meteora.ag/developer-guides/zap/typescript-sdk/examples
Explore Zap TypeScript examples for DAMM v2 zap in, DLMM zap in, zap out through Jupiter, and DLMM position rebalancing.
These examples use the SDK methods exported by `@meteora-ag/zap-sdk`. The SDK returns unsigned `Transaction` objects; sign and submit them with your wallet adapter, backend signer, or test keypair.
<Warning>
Examples are **starting points for specific pools and sizes**, not production defaults for every token.
* `maxAccounts: 50` / `40` and Direct zap-in (`estimateDlmmDirectSwap`, `getZapInDlmmDirectParams`) restrict Jupiter to **single-hop** routes (`onlyDirectRoutes=true` inside the estimator). The Jupiter UI does not use those limits and can quote a safer multi-hop path for the same size.
* Zap In includes a **swap step**. Jupiter slippage does not protect against a quote that is already a bad price. Validate `outAmount` / price impact / simulated wallet deltas before send.
* A size that is fine on Jupiter UI (for example a \~10k USDC buy) can still be toxic on Direct + `maxAccounts` at much larger size.
See [Getting Started](/developer-guides/zap/typescript-sdk/getting-started) and [Jupiter support](https://developers.jup.ag/docs/resources/support#customer-support).
</Warning>
## Create A Client
```typescript theme={"system"}
import { Connection } from "@solana/web3.js";
import { Zap } from "@meteora-ag/zap-sdk";
const connection = new Connection(process.env.RPC_URL!, "confirmed");
const zap = new Zap(connection, {
jupiterApiUrl: "https://api.jup.ag",
jupiterApiKey: process.env.JUPITER_API_KEY,
});
```
## Submit Zap-In Transactions In Order
Zap-in builders return multiple transactions because swaps, ledger writes, zap instructions, and cleanup are deliberately separated.
```typescript theme={"system"}
import { Transaction } from "@solana/web3.js";
const transactions: Transaction[] = [];
if (result.setupTransaction) {
transactions.push(result.setupTransaction);
}
transactions.push(...result.swapTransactions);
transactions.push(result.ledgerTransaction);
transactions.push(result.zapInTransaction);
transactions.push(result.cleanUpTransaction);
for (const tx of transactions) {
tx.feePayer = user.publicKey;
tx.recentBlockhash = (await connection.getLatestBlockhash()).blockhash;
}
```
If a DLMM zap-in creates a new position, sign the zap transaction with the generated `position` keypair as well as the user.
## DAMM v2 Direct Zap In
Use this path when the input token is one of the DAMM v2 pool tokens. `dammV2Quote` and `jupiterQuote` are used to choose the swap route for balancing; pass `null` for a route you do not want to consider.
```typescript theme={"system"}
import { BN } from "@coral-xyz/anchor";
import { PublicKey } from "@solana/web3.js";
import { getJupiterQuote } from "@meteora-ag/zap-sdk";
const user = wallet.publicKey;
const pool = new PublicKey("DAMM_V2_POOL_ADDRESS");
const inputTokenMint = new PublicKey("INPUT_TOKEN_MINT");
const positionNftMint = new PublicKey("POSITION_NFT_MINT");
const amountIn = new BN(1_000_000);
const jupiterQuote = await getJupiterQuote(
inputTokenMint,
new PublicKey("OTHER_POOL_TOKEN_MINT"),
amountIn,
40,
300,
false,
true,
true,
{ jupiterApiKey: process.env.JUPITER_API_KEY },
);
const params = await zap.getZapInDammV2DirectPoolParams({
user,
inputTokenMint,
amountIn,
pool,
positionNftMint,
maxSqrtPriceChangeBps: 1_000,
maxTransferAmountExtendPercentage: 20,
maxAccounts: 40,
slippageBps: 300,
dammV2Quote: null,
jupiterQuote,
});
const result = await zap.buildZapInDammV2Transaction(params);
```
<Note>
The source repository includes richer DAMM v2 examples that prepare both DAMM v2 and Jupiter quotes. The published package root exports the generic Jupiter helpers; use DAMM v2 SDK quote helpers directly when you want to compare both routes.
</Note>
## DLMM Direct Zap In
Use this path when the input token is token X or token Y of the DLMM pair.
<Warning>
`estimateDlmmDirectSwap` quotes Jupiter with `onlyDirectRoutes=true` and `maxAccounts=50`. `maxAccounts: 50` in `getZapInDlmmDirectParams` is an example value, not a universal safe setting. Confirm the Direct route can absorb **your** input size, or disable Direct / raise `maxAccounts` / compare to a multi-hop quote before sending.
</Warning>
```typescript theme={"system"}
import { StrategyType } from "@meteora-ag/dlmm";
import { BN } from "@coral-xyz/anchor";
import { Keypair, PublicKey } from "@solana/web3.js";
import { estimateDlmmDirectSwap } from "@meteora-ag/zap-sdk";
const user = wallet.publicKey;
const lbPair = new PublicKey("DLMM_PAIR_ADDRESS");
const inputTokenMint = new PublicKey("TOKEN_X_OR_TOKEN_Y_MINT");
const amountIn = new BN(100_000_000);
const position = Keypair.generate();
const estimate = await estimateDlmmDirectSwap({
amountIn,
inputTokenMint,
lbPair,
connection,
swapSlippageBps: 150,
minDeltaId: -34,
maxDeltaId: 34,
strategy: StrategyType.Spot,
config: { jupiterApiKey: process.env.JUPITER_API_KEY },
});
const params = await zap.getZapInDlmmDirectParams({
user,
directSwapEstimate: estimate.result,
maxActiveBinSlippage: 50,
favorXInActiveId: false,
maxAccounts: 50,
maxTransferAmountExtendPercentage: 0,
...estimate.context,
});
const result = await zap.buildZapInDlmmTransaction({
...params,
position: position.publicKey,
});
```
The generated `position` keypair must sign the transaction that includes `zapInTransaction` because the Zap program calls DLMM `initialize_position2`.
## Zap Out Through Jupiter
Use zap out when another instruction first creates a balance increase in the user's input token account, for example after a claim or remove-liquidity action.
```typescript theme={"system"}
import { BN } from "@coral-xyz/anchor";
import { PublicKey, Transaction } from "@solana/web3.js";
impor프로젝트로 돌아가기