Prerequisites

  • Ensure you have a wallet created.
  • API Key: Ensure you have an API key with the scopes: wallets:transactions.create.

Swap Tokens

This guide explains how to swap tokens in Solana using the Jupiter advanced routing engine, which requires special configuration to work with smart wallets. If you’re using EVM chains, you can use 0x or 1inch directly. To perform a swap with the Jupiter Swap API and Crossmint wallets, follow these steps:
  1. Request a quote from the Jupiter API.
  2. Build the swap transaction for that quote using the Jupiter API.
  3. Send the transaction using the Crossmint wallet.
For tokens with lower liquidity, the number of hops required to reach the destination token may be higher. This can make the transaction size larger and increase the risk of failure. To minimize this risk, always set maxAccounts=33 when building the swap transaction. This ensures that even multi-hop swaps fit within Solana’s transaction account limits and execute reliably.
import { useWallet, SolanaWallet } from '@crossmint/client-sdk-react-ui';
import { VersionedTransaction } from '@solana/web3.js';

export function SwapTokensComponent() {
    const { wallet } = useWallet();

    async function swapTokens(tokenIn: string, tokenOut: string, amount: number) {
        // Get a quote from the Jupiter API
        const queryParams = new URLSearchParams({
            inputMint: tokenIn, // e.g "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v"
            outputMint: tokenOut, // e.g "XsCPL9dNWBMvFtTmwcCA5v3xWPSMEBCszbQdiLLq6aN"
            amount: amount.toString(), // In lamports!
            slippageBps: "50",
            maxAccounts: "33", // This ensures that even multi-hop swaps fit within Solana's transaction account limits and execute reliably.
        });

        const response = await fetch(`https://lite-api.jup.ag/swap/v1/quote?${queryParams}`, {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            },
        });

        const quoteResponse = await response.json();

        // Build the swap transaction
        const swapResponse = await fetch("https://lite-api.jup.ag/swap/v1/swap", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                userPublicKey: wallet.address,
                quoteResponse: quoteResponse,
            }),
        });

        const swapResponseData = await swapResponse.json();

        // Send the transaction
        const solanaWallet = SolanaWallet.from(wallet);

        const versionedTransaction = VersionedTransaction.deserialize(
            Buffer.from(swapResponseData.swapTransaction, "base64")
        );

        const tx = await solanaWallet.sendTransaction({
            transaction: versionedTransaction,
        });

        console.log("Swap transaction sent successfully!");
    }

    return (
        <div>
            <button onClick={() => swapTokens("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", "XsCPL9dNWBMvFtTmwcCA5v3xWPSMEBCszbQdiLLq6aN", 1)}>Swap Tokens</button>
        </div>
    );
}