Issue fetching token balance from connected wallet using Solana, Jupiter Aggregator, and Jupiter APIs

I’m having trouble fetching the balance of a specific token from the connected wallet when swapping tokens using Solana, Jupiter Aggregator, and Jupiter APIs. I’ve implemented a server-side API to handle the swap process, which includes fetching quotes, generating swap instructions, and transferring platform fees using Jupiter APIs. However, I’m encountering an issue where the balance from the connected wallet is not being fetched correctly.

I’m using the getTokenAccountBalance and getAssociatedTokenAddress methods from the @solana/web3.js library to fetch the balance. Here’s the relevant code snippet from my server.js file:

app.get("/fetchBalance", async (req, res) => {
  const { address, walletAddress } = req.query;
  try {
    const tokenPublicKey = new PublicKey(address);
    const walletPublicKey = new PublicKey(walletAddress);

    const balance = await connection.getTokenAccountBalance(
      await connection.getAssociatedTokenAddress(tokenPublicKey, walletPublicKey)
    );

    return res.status(200).json({
      balance: balance.value.uiAmount,
      decimals: balance.value.decimals
    });
  } catch (error) {
    console.error("Error fetching token balance:", error);
    return res.status(500).json({ error: "Error fetching token balance" });
  }
});

And here’s the relevant code snippet from my swap.js file:

const fetchTokenBalance = useCallback(async (tokenAddress) => {
  if (!publicKey) return;

  try {
    const response = await axios.get("http://localhost:3001/fetchBalance", {
      params: {
        address: tokenAddress,
        walletAddress: publicKey.toString(),
      },
    });
    const balance = response.data.balance;
    setBalances(prevBalances => ({ ...prevBalances, [tokenAddress]: balance }));
    updateTokenBalances({ ...balances, [tokenAddress]: balance });
  } catch (error) {
    console.error("Error fetching token balance:", error);
    messageApi.error("Failed to fetch token balance");
  }
}, [publicKey, updateTokenBalances, balances, messageApi]);

I’m also using Jupiter APIs to fetch prices for the tokens being swapped. Here’s the relevant code snippet from my server.js file:

app.get("/tokenPrice", async (req, res) => {
  const { addressOne, addressTwo } = req.query;
  try {
    const response = await axios.get(`https://price.jup.ag/v6/price`, {
      params: { ids: addressOne, vsToken: addressTwo },
    });
    const priceData = response.data.data[addressOne];
    if (!priceData || !priceData.price) {
      throw new Error("Invalid response from price API");
    }
    const usdPrices = {
      tokenOne: priceData.price,
      tokenTwo: 1 / priceData.price,
      ratio: priceData.price,
    };
    return res.status(200).json(usdPrices);
  } catch (error) {
    console.error("Error fetching token prices:", error);
    return res.status(500).json({ error: "Error fetching token prices" });
  }
});

I’ve added some logging statements to the fetchTokenBalance function to see if it’s being called correctly and if the correct token address and wallet address are being passed to the getTokenAccountBalance and getAssociatedTokenAddress methods. However, I’m still not able to determine the root cause of the issue.

Can anyone help me understand what might be causing the issue with fetching the balance from the connected wallet, and how I can fix it? Additionally, is fetching the balance important for swapping tokens, and if so, how does it fit into the overall swap process?

i have tried everything hlep plz