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

Image source

Step 1: Install Solana Wallet Adapter and Build a Frontend App

There are many wallets available on Solana blockchain. To handle the wallet connection, it is recommended to use Solana wallet adapter. You may follow the guideline to install the dependencies.

// You can add or remove the wallet options hereconst wallets = useMemo(
() => [
new PhantomWalletAdapter(),
new GlowWalletAdapter(),
new SlopeWalletAdapter(),
new SolflareWalletAdapter({ network }),
new TorusWalletAdapter(),
],
[network]
);
The wallet options shown in the modal when clicking connect button

Some tips that might be useful:

  1. If you meet any issue to install @solana/web3.js , check the Node version that you are using.
  2. After successfully install the packages, you might face some issues when running the app. Read the error messages and try to polyfill them.
resolve: {  fallback: {    "crypto": require.resolve("crypto-browserify"),    "stream": require.resolve("stream-browserify"),    "os": require.resolve("os-browserify/browser"),  }}

Step 2: Build a UI with the library of your choice.

In my project, I reused the UI from my previous ETH Swap project which utilises Bootstrap v5 and built in React. The main UI code is in this file.

Step 3: Get the token balances

It is different to get the balance of SOL and the other tokens (eg: RAY).

  1. To get the balance of SOL:
import { useConnection, useWallet } from '@solana/wallet-adapter-react';import { LAMPORTS_PER_SOL } from '@solana/web3.js';
const { publicKey } = useWallet();const { connection } = useConnection();const [solBalance, setSolBalance] = useState<number>(0);// ...if (publicKey !== null) {
const
balance = await connection.getBalance(publicKey);
setSolBalance(balance / LAMPORTS_PER_SOL);
}
import { useConnection, useWallet } from '@solana/wallet-adapter-react';import { PublicKey } from '@solana/web3.js';import { getTokenAccountsByOwner } from '../utils';
const
{ publicKey } = useWallet();
const { connection } = useConnection();const RAY_TOKEN_MINT = '4k3Dyjzvzp8eMZWUXbBCjEvwSkkk59S5iCNLY3QrkX6R';const [rayBalance, setRayBalance] = useState<number>(0);// ...if (publicKey !== null) { // get all token accounts const tokenAccs = await getTokenAccountsByOwner(connection, publicKey as PublicKey); let rayTokenAddress: PublicKey; tokenAccs.filter(acc => acc.accountInfo.mint.toBase58() === RAY_TOKEN_MINT).map(async (acc) => { rayTokenAddress = acc.pubkey; const accBalance = await connection.getTokenAccountBalance(rayTokenAddress); const rayBal = accBalance.value.uiAmount || 0; setRayBalance(rayBal); });}

--

--

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

22 Followers

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