How to Use Raydium SDK to Build a Swap — Part 2

Raydium is the first decentralized automated market maker (AMM) on the Solana blockchain, which is an excellent layer-one blockchain, much faster and cheaper than Ethereum.

Isn’t it cool if we can build something like the swap feature in Raydium?

Final output:

Source code is available here:

Recap Part 1 here.

Step 4: Get the liquidity pool information

Search the liquidity token in Solscan and use the token address to filter the pool key information from Liquidity Pools List.

import { jsonInfo2PoolKeys, LiquidityPoolJsonInfo, LiquidityPoolKeys } from "@raydium-io/raydium-sdk";const RAY_SOL_LP_V4_POOL_KEY = '89ZKE4aoyfLBe2RuV6jM3JGNhaV18Nxh8eNtjRcndBip';const RAYDIUM_LIQUIDITY_JSON = '';const [raySolPoolKey, setRaySolPoolKey] = useState<LiquidityPoolKeys>();// ...const getPoolInfo = async () => {// fetch the liquidity pool list
const liquidityJsonResp = await fetch(RAYDIUM_LIQUIDITY_JSON);
if (!(await liquidityJsonResp).ok) return []const liquidityJson = await liquidityJsonResp.json();const allPoolKeysJson = [...(liquidityJson?.official ?? []), ...(liquidityJson?.unOfficial ?? [])]// find the liquidity pair
poolKeysRaySolJson: LiquidityPoolJsonInfo = allPoolKeysJson.filter((item) => item.lpMint === RAY_SOL_LP_V4_POOL_KEY)?.[0] || null;
// convert the json info to pool key using jsonInfo2PoolKeys
raySolPk = jsonInfo2PoolKeys(poolKeysRaySolJson);

Step 5: Calculate the amount out using the pool key

We almost got every information we need to make the swap transaction! But first, we have to calculate the minimum amount out. Refer to the calcAmountOut function, we use the Liquidity.fetchInfo from Raydium SDK to get the pool information. After that, we use Liquidity.computeAmountOut to get the price and minimum amount out.

If you wonder what priceImpact means, you may check this out.

Step 6: Make the swap transaction and send it! 🚀

After calculating the amount out, we can use Liquidity.makeSwapTransaction to generate the transaction and then use the sendTransaction from to ask user to sign and send it.

import { Liquidity } from "@raydium-io/raydium-sdk";import { useConnection, useWallet } from '@solana/wallet-adapter-react';import { calcAmountOut } from '../utils';const { publicKey, sendTransaction } = useWallet();const { connection } = useConnection();// ...const { amountIn, minAmountOut } = await calcAmountOut(connection, raySolPoolKey, inputNumber, swapInDirection);const { transaction, signers } = await Liquidity.makeSwapTransaction({  connection,  poolKeys: raySolPoolKey,  userKeys: {    tokenAccounts,    owner: publicKey,  },  amountIn,  amountOut: minAmountOut,  fixedSide: "in"});const txid = await sendTransaction(transaction, connection, { signers, skipPreflight: true });console.log(`${txid}`);

That’s all. You may add on some features like switch the tokens and display the exchange rate to make the app more complete.

Hope that you have fun to build the swap application with me. Cheers!



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abby Low

Abby Low


Software engineer, dreamer, another cat lover. Just share what I’ve learned.