[SOLVED] Aiming to combine multiple queries, token balances work but the added query for native balance isnt working. Any idea what i did wrong when adding the native balance query?

const express = require("express");
const app = express();
const port = 5001;
const Moralis = require("moralis").default;
const cors = require("cors");

require("dotenv").config({ path: ".env" });

app.use(cors());
app.use(express.json());

const MORALIS_API_KEY = process.env.MORALIS_API_KEY;

app.get("/gettokens", async (req, res) => {
  try {
    let modifiedResponse = [];
    let totalWalletUsdValue = 0;
    const { query } = req;

    const response = await Moralis.EvmApi.token.getWalletTokenBalances({
      address: query.address,
      chain: "0x1",
    });

    for (let i = 0; i < response.toJSON().length; i++) {
      const tokenPriceResponse = await Moralis.EvmApi.token.getTokenPrice({
        address: response.toJSON()[i].token_address,
        chain: "0x1",
      });
      modifiedResponse.push({
        walletBalance: response.toJSON()[i],
        calculatedBalance: (
          response.toJSON()[i].balance /
          10 ** response.toJSON()[i].decimals
        ).toFixed(2),
        usdPrice: tokenPriceResponse.toJSON().usdPrice,
      });
      totalWalletUsdValue +=
        (response.toJSON()[i].balance / 10 ** response.toJSON()[i].decimals) *
        tokenPriceResponse.toJSON().usdPrice;
    }

    modifiedResponse.push(totalWalletUsdValue);

    return res.status(200).json(modifiedResponse);
  } catch (e) {
    console.log(`Something went wrong ${e}`);
    return res.status(400).json();
  }
});

app.get("/balance", async (req, res) => {
  try {
    const { query } = req;
   
    const response = await Moralis.EvmApi.balance.getNativeBalance({
      address: query.address,
      chain: query.chain,
    });

    return res.status(200).json(response);
  } catch (e) {
    console.log(`Something went wrong ${e}`);
    return res.status(400).json();
  }
});

Moralis.start({
  apiKey: MORALIS_API_KEY,
}).then(() => {
  app.listen(port, () => {
    console.log(`Listening for API Calls`);
  });
});

Hey @Jthopkins1986,

Thanks for reaching out to us :grinning_face_with_smiling_eyes:!

Can you describe further what do you mean by not working, if there is any error what are those, etc?

Hi, thanks for quick response, no errors at all, simply not displaying the balance when i run the backend, i am 100% sure i missed something

const express = require("express");
const app = express();
const port = 5001;
const Moralis = require("moralis").default;
const cors = require("cors");

require("dotenv").config({ path: ".env" });

app.use(cors());
app.use(express.json());

const MORALIS_API_KEY = process.env.MORALIS_API_KEY;
app.get("/balance", async (req, res) => {
  try {
    const { query } = req;
   
    const response = await Moralis.EvmApi.balance.getNativeBalance({
      address: query.address,
      chain: query.chain,
    });

    return res.status(200).json(response);
  } catch (e) {
    console.log(`Something went wrong ${e}`);
    return res.status(400).json();
  }
});

Moralis.start({
  apiKey: MORALIS_API_KEY,
}).then(() => {
  app.listen(port, () => {
    console.log(`Listening for API Calls`);
  });
});

i removed the part that is working, just tried running this on its own, didnt fetch the balance of logged in user

Not really sure, I think I need more detail on what do you mean by working or not working :thinking:

Also did you try to console.log the response from getNativeBalance?

will give that a try once more, as far as what i posted in the first code, everything is correct for having two api calls running? If yes, will be able to eliminate this option

It looks like correct. Let me know if you need any other help~

1 Like

Sorry for taking long to come back, only receiving api results for the token balances of the wallet but not the ETH balance. Really not sure what im doing wrong here. Besides the part of the code coming from the backend, maybe its something wrong with this one?

import axios from "axios";
import { useEffect, useState } from "react";
import { useAccount } from "wagmi";

export default function ethBalance() {
  const [balance, setBalance] = useState([]);
  const { address } = useAccount();

  useEffect(() => {
    let response;
    async function getData() {
      response = await axios
        .get(`http://localhost:5001/balance`, {
          params: { address },
        })
        .then((response) => {
          console.log(response.data);
          setBalance(response.data);
        });
    }
    getData();
  }, []);

  return (      
             {balance}     
    );
  }

tokens work perfectly

Pretty sure its the return function thats wrong

Hmmm quite strange that you said you receive only the token balances since looks like from your API it should have been just getting the ETH balance, unless you make a switch to the path on the backend.

If you would like to get token balances and ETH balance, either you call both /balance and /gettoken or combine them into one REST API to call.

1 Like

Actually just found your documentation for it, cant believe i spent hours online and just now figured out where to look. We can close this ticket as solved, thank you

Here is the article for anyone else who might have the same problem, you guys really do make it simple, it was me that was over complicating things as thas what im used to :slight_smile:

1 Like

i simply had to add this line to the main page

const { data: nativeBalance } = useEvmNativeBalance({ address });

1 Like