t {
getJupiterQuote,
getJupiterSwapInstruction,
getTokenProgramFromMint,
} from "@meteora-ag/zap-sdk";
const user = wallet.publicKey;
const inputMint = new PublicKey("INPUT_MINT");
const outputMint = new PublicKey("OUTPUT_MINT");
const maxSwapAmount = new BN(1_000_000);
const quote = await getJupiterQuote(
inputMint,
outputMint,
maxSwapAmount,
40,
50,
false,
true,
true,
{ jupiterApiKey: process.env.JUPITER_API_KEY },
);
if (!quote) {
throw new Error("Jupiter quote unavailable");
}
const swapInstructionResponse = await getJupiterSwapInstruction(user, quote, {
jupiterApiKey: process.env.JUPITER_API_KEY,
});
const inputTokenProgram = await getTokenProgramFromMint(connection, inputMint);
const outputTokenProgram = await getTokenProgramFromMint(connection, outputMint);
const zapOutTx = await zap.zapOutThroughJupiter({
user,
inputMint,
outputMint,
inputTokenProgram,
outputTokenProgram,
jupiterSwapResponse: swapInstructionResponse,
maxSwapAmount,
percentageToZapOut: 100,
});
const tx = new Transaction()
.add(upstreamClaimOrWithdrawInstruction)
.add(zapOutTx);
```
`zapOutThroughJupiter` reads the user's input token balance before the zap-out instruction is built. Build the zap-out transaction after you know which token account receives the upstream balance increase.
## DLMM Position Rebalance
`rebalanceDlmmPosition` builds a full rebalance sequence for an existing DLMM position: remove liquidity through DLMM helpers, optionally swap the withdrawn tokens, write ledger balances, zap back in, and clean up.
```typescript theme={"system"}
import { StrategyType } from "@meteora-ag/dlmm";
import { PublicKey } from "@solana/web3.js";
import { estimateDlmmRebalanceSwap } from "@meteora-ag/zap-sdk";
const user = wallet.publicKey;
const lbPair = new PublicKey("DLMM_PAIR_ADDRESS");
const position = new PublicKey("DLMM_POSITION_ADDRESS");
const estimate = await estimateDlmmRebalanceSwap({
lbPair,
position,
connection,
swapSlippageBps: 150,
minDeltaId: -34,
maxDeltaId: 34,
strategy: StrategyType.Spot,
config: { jupiterApiKey: process.env.JUPITER_API_KEY },
});
const result = await zap.rebalanceDlmmPosition({
user,
liquiditySlippageBps: 50,
favorXInActiveId: false,
directSwapEstimate: estimate.result,
...estimate.context,
});
```
# Zap TS SDK Getting Started
Source: https://docs.meteora.ag/developer-guides/zap/typescript-sdk/getting-started
Learn how to install @meteora-ag/zap-sdk, create a Zap client, configure Jupiter access, and plan Zap transaction sequences.
This guide shows how to install and initialize the official Zap TypeScript SDK, `@meteora-ag/zap-sdk`.
Before you begin, here are the main resources:
<CardGroup>
<Card title="TypeScript SDK" icon="node-js" href="https://github.com/MeteoraAg/zap-sdk">
Zap TypeScript SDK repository.
</Card>
<Card title="Zap NPM Package" icon="npm" href="https://www.npmjs.com/package/@meteora-ag/zap-sdk">
Published package for transaction builders, state reads, PDA helpers, and examples.
</Card>
</CardGroup>
## Install
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/zap-sdk @solana/web3.js @solana/spl-token @coral-xyz/anchor bn.js
```
</Tab>
<Tab title="pnpm">
```bash theme={"system"}
pnpm install @meteora-ag/zap-sdk @solana/web3.js @solana/spl-token @coral-xyz/anchor bn.js
```
</Tab>
<Tab title="yarn">
```bash theme={"system"}
yarn add @meteora-ag/zap-sdk @solana/web3.js @solana/spl-token @coral-xyz/anchor bn.js
```
</Tab>
</Tabs>
## Dependencies
| Package | Version |
| - | - |
| `@coral-xyz/anchor` | `^0.31.0` |
| `@solana/web3.js` | `^1.98.0` |
| `@solana/spl-token` | `^0.3.10` or newer |
| `@meteora-ag/cp-amm-sdk` | Compatible |
| `@meteora-ag/dlmm` | Compatible |
| `bn.js` | `^5.2.1` |
| `decimal.js` | `^10.4.3` |
## 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,
});
```
`jupiterApiUrl` and `jupiterApiKey` are optional in the SDK constructor. Pass them whenever your Jupiter endpoint requires authenticated quote or swap-instruction requests. You can get the API key from [Jupiter Developer Portal](https://developers.jup.ag/sign-in).
## Program ID
| Network | Program ID |
| - | - |
| Mainnet Beta | `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` |
| Devnet | `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` |
The SDK also exports `ZAP_PROGRAM_ID`, `DAMM_V2_PROGRAM_ID`, `DLMM_PROGRAM_ID`, `JUP_V6_PROGRAM_ID`, and `MEMO_PROGRAM_ID`.
## Transaction Model
Zap builders return unsigned `Transaction` objects. The caller is responsible for fee payer, blockhash, signing, simulation, and submission.
| Flow stage | Purpose |
| - | - |
| Setup transaction | Create token accounts and wrap native SOL when required. |
| Swap transaction or transactions | Move the input token into pool token A/B or X/Y before zap-in, or perform a standalone swap used in rebalancing. |
| Ledger transaction | Initialize or reset `UserLedger`, then record token amounts from direct balances or post-swap deltas. |
| Zap transaction | Call the Zap program to add liquidity, rebalance DLMM liquidity, or invoke a whitelisted zap-out swap payload. |
| Cleanup transaction | Close the ledger and unwrap native SOL when required. |
For zap-in flows, preserve this order. The ledger stores intermediate token amounts that the following Zap instruction consumes.
<Warning>
Zap In is **not a single instruction**. It is a multi-step sequence (setup → **swap** → ledger → zap-in → cleanup). The swap leg is a Jupiter (or pool) quote that your integration must validate **before** signing.
* `simulateTransaction` passing only means the swap will not revert. It does **not** mean the quoted `outAmount` is a reasonable market price for the input size.
* Jupiter slippage bounds execution against **that quote / that route**, not input-vs-output fair value. See [Jupiter customer support](https://developers.jup.ag/docs/resources/support#customer-support).
* Direct zap-in estimators currently request Jupiter with `onlyDirectRoutes=true` and `maxAccounts` around `50`. That can return a much thinner route than the Jupiter UI, which does not apply those limits.
* The Meteora UI applies extra output-amount / USD / extreme-impact checks. The SDK does **not**. Copying an example is not a production guardrail for every pool or size.
Before submitting, compare quoted output to a reference price, reject extreme price impact, and simulate **token balance deltas** (not only `err`). If Direct is far worse than a multi-hop quote, fall back to broader routing (`onlyDirectRoutes=false`) or skip the zap.
</Warning>
## Supported SDK Workflows
| Workflow | Methods |
| - | - |
| DAMM v2 zap in, direct input token | `getZapInDammV2DirectPoolParams`, then `buildZapInDammV2Transaction` |
| DAMM v2 zap in, indirect input token | `getZapInDammV2IndirectPoolParams`, then `buildZapInDammV2Transaction` |
| DLMM zap in, direct input token | `estimateDlmmDirectSwap`, `getZapInDlmmDirectParams`, then `buildZapInDlmmTransaction` |
| DLMM zap in, indirect input token | `estimateDlmmIndirectSwap`, `getZapInDlmmIndirectParams`, then `buildZapInDlmmTransaction` |
| DLMM position rebalance | `estimateDlmmRebalanceSwap`, then `rebalanceDlmmPosition` |
| Zap out through DAMM v2 | `zapOutThroughDammV2` |
| Zap out through DLMM | `zapOutThroughDlmm` |
| Zap out through Jupiter | `getJupiterQuote`, `getJupiterSwapInstruction`, then `zapOutThroughJupiter` |
| Low-level zap out | `zapOut` with your own whitelisted payload and account metas |
## Testing the SDK
If you have cloned the SDK repository, start with package-level checks and tests:
```bash theme={"system"}
pnpm install
pnpm run build
pnpm test
```
# Zap TS SDK Reference
Source: https://docs.meteora.ag/developer-guides/zap/typescript-sdk/reference
Understand @meteora-ag/zap-sdk exports, Zap methods, constants, helper functions, route estimators, types, and transaction outputs.
This page is based on `@meteora-ag/zap-sdk`. Use it as the high-level map, then open the package types when you need exact parameter shapes.
```typescript theme={"system"}
import {
Zap,
ZAP_PROGRAM_ID,
estimateDlmmDirectSwap,
estimateDlmmIndirectSwap,
estimateDlmmRebalanceSwap,
getJupiterQuote,
getJupiterSwapInstruction,
deriveLedgerAccount,
} from "@meteora-ag/zap-sdk";
```
## Dependencies
| Package | Use |
| - | - |
| `@coral-xyz/anchor` | Program client, IDL types, and `BN`. |
| `@solana/web3.js` | Connections, public keys, transactions, and account metas. |
| `@solana/spl-token` | Token accounts, ATAs, Token 2022, and wrapped SOL helpers. |
| `@meteora-ag/cp-amm-sdk` | DAMM v2 state, position derivation, token program flags, and swap quote helpers. |
| `@meteora-ag/dlmm` | DLMM state, strategies, bin arrays, quotes, and rebalance helpers. |
| `bn.js` | Integer token amount inputs and SDK return values. |
| `decimal.js` | UI amount conversion, route comparison, and estimate calculations. |
## Program IDs
| Constant | Value |
| - | - |
| `ZAP_PROGRAM_ID` | `zapvX9M3uf5pvy4wRPAbQgdQsM1xmuiFnkfHKPvwMiz` |
| `DAMM_V2_PROGRAM_ID` | `cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG` |
| `DLMM_PROGRAM_ID` | `LBUZKhRxPF3XUpBCjp4YzTKgLccjZhTSDM9YuVaPwxo` |
| `JUP_V6_PROGRAM_ID` | `JUP6LkbZbjS1jKKwapdHNy74zcZ3tLUZoi5QNyVTaV4` |
| `MEMO_PROGRAM_ID` | `MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr` |
## Creating 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,
});
```
| Constructor option | Type | Default | Use |
| - | - | - | - |
| `jupiterApiUrl` | `string` | `https://api.jup.ag` | Jupiter quote and swap-instruction endpoint base URL. |
| `jupiterApiKey` | `string` | Empty string | Optional API key header for Jupiter requests. |
## Zap Methods
| Method | Returns | Use |
| - | - | - |
| `constructor(connection, config?)` | `Zap` | Create a Zap client with an Anchor `Program` from the bundled IDL. |
| `getZapInDammV2DirectPoolParams(params)` | `ZapInDammV2DirectPoolParam` | Prepare DAMM v2 zap-in params when the input mint is token A or token B. |
| `getZapInDammV2IndirectPoolParams(params)` | `ZapInDammV2IndirectPoolParam` | Prepare DAMM v2 zap-in params when the input mint is neither pool token. |
| `buildZapInDammV2Transaction(params)` | `ZapInDammV2Response` | Build setup, swap, ledger, zap-in, and cleanup transactions for DAMM v2. |
| `getZapInDlmmDirectParams(params)` | `ZapInDlmmDirectPoolParam` | Prepare DLMM zap-in params when the input mint is token X or token Y. |
| `getZapInDlmmIndirectParams(params)` | `ZapInDlmmIndirectPoolParam` | Prepare DLMM zap-in params when the input mint is neither pool token. |
| `buildZapInDlmmTransaction(params)` | `ZapInDlmmResponse` | Build setup, swap, ledger, zap-in, and cleanup transactions for a new DLMM position. |
| `rebalanceDlmmPosition(params)` | `RebalanceDlmmPositionResponse` | Build a DLMM remove-liquidity, optional swap, ledger, zap-in, and cleanup sequence for an existing position. |
| `zapOut(params)` | `Transaction` | Low-level generic zap-out builder with caller-supplied payload and account metas. |
| `zapOutThroughJupiter(params)` | `Transaction` | Build a zap-out transaction using a Jupiter V6 swap-instruction response. |
| `zapOutThroughDammV2(params)` | `Transaction` | Build a zap-out transaction through DAMM v2 `swap2`. |
| `zapOutThroughDlmm(params)` | `Transaction` | Build a zap-out transaction through DLMM `swap2`. |
## Zap-In Parameter Builders
| Method | Required route inputs | Important controls |
| - | - | - |
| `getZapInDammV2DirectPoolParams` | `user`, `inputTokenMint`, `amountIn`, `pool`, `positionNftMint`, optional DAMM v2 and Jupiter quotes | `maxSqrtPriceChangeBps`, `slippageBps`, `maxAccounts`, `maxTransferAmountExtendPercentage` |
| `getZapInDammV2IndirectPoolParams` | `user`, `inputTokenMint`, `amountIn`, `pool`, `positionNftMint`, optional Jupiter quotes to token A and token B | Same DAMM v2 controls plus per-side route estimates |
| `getZapInDlmmDirectParams` | `user`, `lbPair`, `inputTokenMint`, `amountIn`, `directSwapEstimate` | `minDeltaId`, `maxDeltaId`, `strategy`, `favorXInActiveId`, `maxActiveBinSlippage`, `singleSided` |
| `getZapInDlmmIndirectParams` | `user`, `lbPair`, `inputTokenMint`, `amountIn`, `indirectSwapEstimate` | Same DLMM controls plus Jupiter route caps |
## Zap-In Responses
| Response type | Fields |
| - | - |
| `ZapInDammV2Response` | `setupTransaction?`, `swapTransactions`, `ledgerTransaction`, `zapInTransaction`, `cleanUpTransaction` |
| `ZapInDlmmResponse` | `setupTransaction?`, `swapTransactions`, `ledgerTransaction`, `zapInTransaction`, `cleanUpTransaction` |
| `RebalanceDlmmPositionResponse` | `setupTransaction`, `initBinArrayTransaction?`, `rebalancePositionTransaction?`, `swapTransaction?`, `ledgerTransaction`, `zapInTransaction`, `cleanUpTransaction`, `estimation` |
## Zap-Out Methods
| Method | Route source | Notes |
| - | - | - |
| `zapOut` | Caller-supplied whitelisted payload | Lowest-level builder. Use only when you already know the downstream account order and amount offset. |
| `zapOutThroughJupiter` | Jupiter V6 swap-instruction response | Builds ATAs, calculates reverse amount offset, forwards Jupiter accounts, and unwraps SOL when needed. |
| `zapOutThroughDammV2` | DAMM v2 pool state and `createDammV2SwapPayload` | Builds DAMM v2 remaining accounts and uses amount offset `8`. |
| `zapOutThroughDlmm` | DLMM pair state and `createDlmmSwapPayload` | Builds DLMM remaining accounts, including transfer-hook slices when required, and uses amount offset `8`. |
## Estimator Functions
| Function | Use |
| - | - |
| `estimateDlmmDirectSwap(params)` | Estimate whether and how much to swap when the input mint is token X or token Y. Compares DLMM and Jupiter routes. |
| `estimateDlmmIndirectSwap(params)` | Estimate split amounts to swap an unrelated input token into token X and/or token Y through Jupiter. |
| `estimateDlmmRebalanceSwap(params)` | Estimate the swap needed after removing liquidity from an existing DLMM position before zapping back in. |
## Jupiter Helpers
| Function | Use |
| - | - |
| `getJupiterQuote(inputMint, outputMint, amount, maxAccounts, slippageBps, dynamicSlippage, onlyDirectRoutes, restrictIntermediateTokens, config?)` | Fetch a Jupiter quote. Returns `null` when the request fails or the endpoint rejects it. |
| `getJupiterSwapInstruction(userPublicKey, quoteResponse, config?)` | Fetch Jupiter swap instructions for a quote. Throws when the request fails. |
| `buildJupiterSwapTransaction(user, inputMint, outputMint, amount, maxAccounts, slippageBps, quote?, config?)` | Build a transaction containing the Jupiter swap instruction. Reuses a supplied quote when provided. |
<Warning>
`getJupiterQuote(..., maxAccounts, ..., onlyDirectRoutes, ...)` forwards those flags to Jupiter `/swap/v1/quote`. Direct zap-in estimators pass `onlyDirectRoutes=true` and `maxAccounts=50`. That is **not** equivalent to a Jupiter UI quote. Slippage on the quote does not mean the output is a fair market vs the input. Integrations must validate `outAmount` before signing. See [Jupiter customer support](https://developers.jup.ag/docs/resources/support#customer-support).
</Warning>
## DAMM v2 Helpers
| Function | Use |
| - | - |
| `getDammV2Pool(connection, poolAddress)` | Fetch a DAMM v2 pool state through `@meteora-ag/cp-amm-sdk`. |
| `getDammV2RemainingAccounts(poolAddress, user, userInputTokenAccount, userTokenOutAccount, tokenAProgram, tokenBProgram, poolState)` | Build account metas for DAMM v2 `swap2` in zap-out flows. |
| `createDammV2SwapPayload(amountIn, minimumSwapAmountOut)` | Serialize DAMM v2 `swap2` payload data for generic `zapOut`. |
| `isSingleSidedA(poolState)` / `isSingleSidedB(poolState)` | Detect DAMM v2 single-sided pool boundary states. |
## DLMM Helpers
| Function | Use |
| - | - |
| `getLbPairState(connection, lbPair)` | Fetch a DLMM pair state. |
| `getDlmmRemainingAccounts(connection, lbPair, user, userInputTokenAccount, userTokenOutAccount, tokenXProgram, tokenYProgram, lbPairState)` | Build DLMM swap remaining accounts and `RemainingAccountInfo`. |
| `createDlmmSwapPayload(amountIn, minimumSwapAmountOut, remainingAccountsInfo)` | Serialize DLMM `swap2` payload data for generic `zapOut`. |
| `getBinArrayBitmapExtension(connection, binArray)` | Decode a bin array bitmap extension account when it exists. |
| `getNextBinArrayIndexWithLiquidity(...)` | Scan DLMM bitmap state for the next bin array with liquidity. |
| `toProgramStrategyType(strategy)` | Convert DLMM SDK strategy enum values into Zap IDL enum values. |
| `convertAccountTypeToNumber(accountType)` | Encode DLMM remaining-account slice account types. |
## PDA, Token, And Utility Helpers
| Function | Use |
| - | - |
| `deriveLedgerAccount(owner)` | Derive the Zap user ledger PDA. |
| `deriveDammV2EventAuthority()` | Derive DAMM v2 event authority. |
| `deriveDammV2PoolAuthority()` | Derive DAMM v2 pool authority. |
| `deriveDlmmEventAuthority()` | Derive DLMM event authority. |
| `getOrCreateATAInstruction(connection, tokenMint, owner, payer, allowOwnerOffCurve, tokenProgram)` | Return an ATA and an idempotent creation instruction. |
| `getTokenProgramFromMint(connection, mint)` | Detect SPL Token versus Token 2022 from mint ownership, defaulting to SPL Token on lookup failure. |
| `getTokenAccountBalance(connection, tokenAccount)` | Return a token-account balance string, or `"0"` when the account lookup fails. |
| `wrapSOLInstruction(from, to, amount, tokenProgram?)` | Build native SOL wrap instructions. |
| `unwrapSOLInstruction(owner, receiver, allowOwnerOffCurve?)` | Build a wrapped SOL close-account instruction. |
| `filterOutCloseSplTokenAccountInstructions(instructions)` | Remove SPL Token `CloseAccount` instructions from a list. |
| `getExtraAccountMetasForTransferHook(connection, mint)` | Return Token 2022 transfer-hook extra accounts for a mint. |
| `convertLamportsToUiAmount(amount, decimals)` / `convertUiAmountToLamports(amount, decimals)` | Convert between integer and UI decimal amounts. |
## Constants And Enums
| Export | Values or meaning |
| - | - |
| `AMOUNT_IN_DAMM_V2_OFFSET` | `8` |
| `AMOUNT_IN_DLMM_OFFSET` | `8` |
| `AMOUNT_IN_JUP_V6_REVERSE_OFFSET` | `19` |
| `DAMM_V2_SWAP_DISCRIMINATOR` | DAMM v2 `swap2` discriminator. |
| `DLMM_SWAP_DISCRIMINATOR` | DLMM `swap2` discriminator. |
| `DEFAULT_JUPITER_API_URL` | `https://api.jup.ag` |
| `ZapInDammV2PoolSwapRoute` | `Jupiter`, `DammV2` |
| `SwapExternalType` | `swapToA`, `swapToB`, `swapToBoth` |
| `DlmmDirectSwapQuoteRoute` | `Jupiter`, `Dlmm` |
| `DlmmSwapType` | `XToY`, `YToX`, `NoSwap` |
| `DlmmSingleSided` | `X`, `Y` |
| `AccountsType` | Transfer-hook slice account types used for DLMM remaining accounts. |
## Core Types
| Type | Use |
| - | - |
| `ZapConfig` | Optional Jupiter API URL and API key. |
| `ZapOutParameters` | IDL-derived payload fields for `zap_out`. |
| `ZapOutParams` | Low-level generic zap-out builder input. |
| `ZapOutThroughDammV2Params`, `ZapOutThroughDlmmParams`, `ZapOutThroughJupiterParams` | Route-specific zap-out builder inputs. |
| `GetZapInDammV2DirectPoolParams`, `GetZapInDammV2IndirectPoolParams` | DAMM v2 zap-in parameter preparation inputs. |
| `GetZapInDlmmDirectParams`, `GetZapInDlmmIndirectParams` | DLMM zap-in parameter preparation inputs. |
| `EstimateDlmmDirectSwapParams`, `EstimateDlmmIndirectSwapParams`,프로젝트로 돌아가기