Skip to main content
In the previous tutorials, we’ve learned how to create a pool, add liquidity, and remove it. Now, let’s look at one of the most common operations: swapping tokens. Swapping tokens in a DLMM pool involves getting a quote for the desired trade and then executing the swap transaction.
Make sure you have your wallet set up. For this tutorial, I’m using a wallet loaded from the command line.

Swap Types and Directions

Before we dive into the code, it’s important to understand the different ways you can swap tokens with Saros DLMM.

Swap Types

There are two types of swaps available:
  • Exact Input: You specify the exact amount of tokens you want to swap, and the pool will give you the corresponding amount of the other token in return.
  • Exact Output: You specify the exact amount of tokens you want to receive, and the pool will calculate how much of the other token you need to provide.

Swap Direction

Swaps can be performed in two directions:
  • Swap for Y: Swap token X (base token) for token Y (quote token).
  • Swap for X: Swap token Y (quote token) for token X (base token).
Now let’s see how to implement this in code.

1. Getting a Quote

Before performing a swap, it’s a good practice to get a quote to see how many tokens you will receive. This helps you to check the price and potential slippage.
Let’s break down the parameters for getQuote:
  • amount: The amount of tokens you want to swap. In this case, 1e4 lamports of the input token.
  • isExactInput: We set this to true because we are using the “Exact Input” swap type. We are specifying the exact amount of tokens we want to send.
  • swapForY: We set this to true to swap token X for token Y (PYUSD for WSOL in our case).
  • pair, tokenBase, tokenQuote: These are the details of the pool and tokens we are interacting with.
  • slippage: The percentage of price change you are willing to tolerate. Here it’s 0.5%.
The getQuote function returns the amount to be swapped and otherAmountOffset, which is the minimum amount of the other token you will receive after accounting for slippage.

2. Executing the Swap

Once we have the quote, we can use it to execute the swap. The swap function will create the transaction for us.
Most of the parameters here are similar to getQuote. The amount and otherAmountOffset are taken directly from the response of the getQuote call.

3. Sending the Transaction

Now that we have the swap transaction, we just need to sign it and send it to the Solana network.
And that’s it! After the transaction is confirmed, the token swap is complete.