Integrate Raydium Swap Functionality on a Solana Program

Posted By : Rahul

Oct 02, 2024

Solana is recognized as a top platform for blockchain app development due to its low transaction fees and excellent throughput. With its smooth token swaps, yield farming, and liquidity pools, Raydium is a well-known automated market maker (AMM) and liquidity provider among the many protocols that flourish on Solana. Developers wishing to expand on this dynamic environment have many options when integrating Raydium's switch feature into custom Solana software.


This blog will guide you through the process of using the Raydium SDK and the Solana Web3.js framework to integrate the swap functionality of Raydium into your Solana program.

 

You may also like | How to Build a Solana Sniper Bot

 

Using Raydium SDK and Solana Web.js to Integrate Swap Functionality on a Solana Prorgram 

 

Prerequisites:

 

  • Node.js is installed on your machine.
  • Solana CLI installed and configured.
  • Basic knowledge of TypeScript and Solana development.
  • A basic understanding of how Raydium works.

     

    Setting Up the Environment: 

     

  • npm init -y
  • npm install @solana/web3.js @solana/spl-token @raydium-io/raydium-sdk decimal.js fs
  • @solana/web3.js: The official Solana JavaScript SDK.
  • @solana/spl-token: A library for interacting with the Solana Program Library (SPL) tokens.
  • @raydium-io/raydium-sdk: The Raydium SDK interacts with the protocol's AMM and liquidity pools.
  • decimal.js: A library for handling arbitrary-precision decimal arithmetic.

 

Also, Explore | SPL-404 Token Standard | Enhancing Utility in the Solana Ecosystem

 

Connect with Solana Cluster 

 

import { Connection, clusterApiUrl, Keypair, PublicKey, Transaction } from '@solana/web3.js';

const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
console.log('Connected to Solana Devnet');

 

Payer's Keypair Loading:

 

import * as fs from 'fs';

const data = fs.readFileSync('./secret.json', 'utf8');
const secretKey = Uint8Array.from(JSON.parse(data));
const payer = Keypair.fromSecretKey(secretKey);
console.log('Payer's public key:', payer.publicKey.toBase58());

 

Creating and Minting SPL Tokens

 

import { createMint, getMint, mintTo, getOrCreateAssociatedTokenAccount } from '@solana/spl-token';
const token1 = await createMint(connection, payer, payer.publicKey, null, 9);
const token2 = await createMint(connection, payer, payer.publicKey, null, 9);
const token1Account = await getOrCreateAssociatedTokenAccount(connection, payer, token1, payer.publicKey);
const token2Account = await getOrCreateAssociatedTokenAccount(connection, payer, token2, payer.publicKey);
await mintTo(connection, payer, token1, token1Account.address, payer.publicKey, 1000000000); // 1000 tokens
await mintTo(connection, payer, token2, token2Account.address, payer.publicKey, 1000000000);
console.log('Minted tokens and created associated token accounts.');

 

Creating a Liquidity Pool on Raydium:

 

import { Liquidity, DEVNET_PROGRAM_ID, TxVersion, BN } from '@raydium-io/raydium-sdk';
const targetMarketId = Keypair.generate().publicKey;
const startTime = Math.floor(Date.now() / 1000) + 60 * 60 * 24 * 7;
const walletAccount = await getWalletTokenAccount(connection, payer.publicKey);
const createPoolTx = await Liquidity.makeCreatePoolV4InstructionV2Simple({
    connection,
    programId: DEVNET_PROGRAM_ID.AmmV4,
    marketInfo: {
        marketId: targetMarketId,
        programId: DEVNET_PROGRAM_ID.OPENBOOK_MARKET,
    },
    baseMintInfo: { mint: token1, decimals: 9 },
    quoteMintInfo: { mint: new PublicKey('So11111111111111111111111111111111111111112'), decimals: 9 },
    baseAmount: new BN(10000),
    quoteAmount: new BN(10000),
    startTime: new BN(Math.floor(startTime)),
    ownerInfo: {
        feePayer: payer.publicKey,
        wallet: payer.publicKey,
        tokenAccounts: walletAccount,
        useSOLBalance: true,
    },
    associatedOnly: false,
    checkCreateATAOwner: true,
    makeTxVersion: TxVersion.V0,
});
console.log('Liquidity pool created on Raydium.');

 

Add Liquidity:

 

const addLiquidityTx = await Liquidity.makeAddLiquidityInstructionSimple({
    connection,
    poolKeys,
    userKeys: {
        owner: payer.publicKey,
        payer: payer.publicKey,
        tokenAccounts: walletAccount,
    },
    amountInA: new TokenAmount(new Token(TOKEN_PROGRAM_ID, token1, 9, 'Token1', 'Token1'), 100),
    amountInB: maxAnotherAmount,
    fixedSide: 'a',
    makeTxVersion,
});
console.log('Liquidity added to the pool.');

 

Perform a Swap: 

 

 const swapInstruction = await Liquidity.makeSwapInstruction({
    poolKeys,
    userKeys: {
      owner: payer.publicKey,
      tokenAccountIn: fromTokenAccount,
      tokenAccountOut: toTokenAccount,
    },
    amountIn,
    amountOut: minimumAmountOut,
    fixedSide: 'in',
  });

  // Correcting the transaction creation by accessing the correct innerTransaction
  const transaction = new Transaction().add(...swapInstruction.innerTransaction.instructions);

  const transactionSignature = await connection.sendTransaction(
    transaction,
    [payer],
    { skipPreflight: false, preflightCommitment: 'confirmed' }
  );

  console.log('Swap transaction signature:', transactionSignature);

 

Also, Explore | How to Get the Transaction Logs on Solana

 

Conclusion

 

You have successfully included Raydium's swap feature into your Solana program by following the instructions provided in this Blog. In the DeFi space, Raydium offers strong tools for swapping and liquidity. If you want to leverage the potential of Solana and Raydium Swap Functionality for your project, connect with our skilled Solana developers to get started. 

Leave a

Comment

Name is required

Invalid Name

Comment is required

Recaptcha is required.

blog-detail

October 15, 2024 at 06:43 pm

Your comment is awaiting moderation.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.

Chat with Us
Telegram Button
Youtube Button
Contact Us

Oodles | Blockchain Development Company

Name is required

Please enter a valid Name

Please enter a valid Phone Number

Please remove URL from text