> ## Documentation Index
> Fetch the complete documentation index at: https://creator-a1160a86.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Removing Liquidity

In the last tutorial, we learned how to add liquidity to a DLMM pool. Now, let's see how to remove that liquidity. We will cover two strategies: removing liquidity from a specific range of bins, and removing all of your liquidity from the pool.

> [!NOTE]
>
> Make sure you have your wallet set up. For this tutorial, I'm using a wallet
> loaded from the command line.

First, let's start with some initial setup that is common for both strategies. We need to import the necessary libraries and get the pool information.

```typescript theme={null}
import { PublicKey, Transaction } from "@solana/web3.js";
import { sarosDLMM } from "./service.js";
import { PYUSD_TOKEN_DEVNET, PYUSD_WSOL_POOL_DEVNET, WSOL_TOKEN_DEVNET } from "./constants.js";
import { loadWalletFromCLI } from "./wallet.js";
import { PositionInfo, RemoveLiquidityType } from "@saros-finance/dlmm-sdk";

const wallet = loadWalletFromCLI();

const pair = new PublicKey(PYUSD_WSOL_POOL_DEVNET.address);
const pairInfo = await sarosDLMM.getPairAccount(pair);
const activeId = pairInfo.activeId;
```

Next, let's fetch all your positions in the pool. This is also a common step for both strategies.

```typescript theme={null}
const positions = await sarosDLMM.getUserPositions({ payer: wallet.publicKey, pair });

if (!positions.length) throw new Error("No positions found");
```

## Strategy 1: Removing Liquidity from a Specific Range

This strategy is useful when you want to remove liquidity only from a certain part of the price range.

### 1. Define a Range and Filter Positions

First, we define the range from which we want to remove liquidity. In this example, we are targeting 10 bins above and below the active bin. Then, we filter the `positions` we fetched earlier.

```typescript theme={null}
const range: [number, number] = [activeId - 10, activeId + 10];

const positionList = positions.filter(
  (item: PositionInfo) => !(item.upperBinId! < range[0] || item.lowerBinId! > range[1])
);

if (!positionList.length) throw new Error("No position found in this range");
```

### 2. Prepare the Position List for Removal

Next, we prepare the list of positions for the `removeMultipleLiquidity` function. We need to specify the exact `start` and `end` bins for removal for each position, making sure they don't go outside our defined `range`.

```typescript theme={null}
const maxPositionList = positionList.map((item: PositionInfo) => {
  const start = Math.max(range[0], item.lowerBinId!);
  const end = Math.min(range[1], item.upperBinId!);

  return {
    position: item.position,
    start,
    end,
    positionMint: item.positionMint,
  };
});
```

Now you can proceed to the **"Removing the Liquidity"** and **"Sending the Transactions"** sections below to complete the process.

## Strategy 2: Removing All Your Liquidity

If you want to withdraw all your liquidity from the pool, the process is even simpler. Since we have already fetched all positions, we can directly proceed to prepare them for removal.

### 1. Prepare the Full Position List for Removal

We map over all positions to prepare them for removal. The `start` and `end` bins will be the position's own `lowerBinId` and `upperBinId`.

```typescript theme={null}
const maxPositionList = positions.map((item: PositionInfo) => {
  return {
    position: item.position,
    start: item.lowerBinId!,
    end: item.upperBinId!,
    positionMint: item.positionMint,
  };
});
```

## Removing the Liquidity

This step is the same for both strategies. Now we are ready to call the main function to remove the liquidity using the `maxPositionList` we prepared.

```typescript theme={null}
const { txs, txCreateAccount, txCloseAccount } =
  await sarosDLMM.removeMultipleLiquidity({
    maxPositionList,
    payer: wallet.publicKey,
    type: RemoveLiquidityType.Both,
    pair,
    tokenMintX: new PublicKey(PYUSD_TOKEN_DEVNET.mintAddress),
    tokenMintY: new PublicKey(WSOL_TOKEN_DEVNET.mintAddress),
    activeId,
  });
```

The `removeMultipleLiquidity` function creates the necessary transactions to withdraw your tokens. In the `type` parameter, we have specified `RemoveLiquidityType.Both`, which means we are withdrawing both tokens from the pool.

You can change this based on your needs:

* `RemoveLiquidityType.Both`: To withdraw both the base and quote tokens.
* `RemoveLiquidityType.BaseToken`: To withdraw only the base token.
* `RemoveLiquidityType.QuoteToken`: To withdraw only the quote token.

## Sending the Transactions

Finally, we collect all the transactions returned by the `removeMultipleLiquidity` function, sign them, and send them to the Solana network. This part is also common for both strategies.

1. **Collect Transactions**: We put all the transactions into a single array.

   ```typescript theme={null}
   const allTxs: Transaction[] = [];
   if (txCreateAccount) allTxs.push(txCreateAccount as any);
   allTxs.push(...txs as any);
   if (txCloseAccount) allTxs.push(txCloseAccount as any);
   ```

2. **Sign and Send**: We loop through each transaction, sign it with our wallet, and send it.

   ```typescript theme={null}
   const {blockhash} = await sarosDLMM.connection.getLatestBlockhash({ commitment: "confirmed" });

   for (const tx of allTxs) {
     tx.recentBlockhash = blockhash;
     tx.feePayer = wallet.publicKey;
     tx.sign(wallet);
     const sig = await sarosDLMM.connection.sendRawTransaction(tx.serialize(), {
       skipPreflight: false,
       preflightCommitment: "confirmed",
     });
     await sarosDLMM.connection.confirmTransaction(sig, "confirmed");
     console.log("Sent tx:", sig);
   }
   ```

And that's it! Once these transactions are confirmed, your liquidity will be removed from the pool, and the tokens will be back in your wallet.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.