Fetching purchase price of each token in users wallet

so this is the first one that doesn’t work?
can you log the parameters used, what is the response?

nothing at all, same results as when the code is completely removed

I just removed the whole code for /getspentonwallettokens - and nothing changed at all, its just not working for some reason, thought to share the whole backend code, maybe there is an issue due to having too many calls happening

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("/getwallettransactions", async (req, res) => {
  try {
    const { query } = req;

    const response = await Moralis.EvmApi.token.getWalletTokenTransfers({
      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();
  }
});

app.get("/getwalletnft", async (req, res) => {
  try {
    const { query } = req;

    const response = await Moralis.EvmApi.nft.getWalletNFTs({
      address: query.address,
      chain: "1",
    });

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

app.get("/getspentonwallettokens", async (req, res) => {
  try {
    const { query } = req;

    const response = await Moralis.Web3API.account.getTransactions({
      address: query.address,
      chain: "0x1",
      from_block: "0",
    });
    console.log('Response:', response.result);

const tokenTransactions = response.result.filter(
  (tx) => tx.from_address === query.address && (tx.to_token !== null || tx.value > 0)
);
    const tokenSpent = {};
    for (let i = 0; i < tokenTransactions.length; i++) {
      const token = tokenTransactions[i].to_token.token_address;
      const amount = parseFloat(
        tokenTransactions[i].value / 10 ** tokenTransactions[i].to_token.decimals
      );
      console.log('Token:', token, 'Amount:', amount);
      const tokenPriceResponse = await Moralis.EvmApi.token.getTokenPrice({
        address: token,
        chain: "0x1",
      });
      console.log('Token Price Response:', tokenPriceResponse.toJSON());
      const usdSpent = amount * tokenPriceResponse.toJSON().usdPrice;
      console.log('USD Spent:', usdSpent);
      if (tokenSpent[token] === undefined) {
        tokenSpent[token] = usdSpent;
      } else {
        tokenSpent[token] += usdSpent;
      }
    }
    
    console.log('Token Spent:', tokenSpent);

    return res.status(200).json(tokenSpent);
  } 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`);
  });
});

All the other calls are working

What address are you using here?

Logged in users address via wagmi useAccount

Sorry for keep bothering but its an extremely important data, end goal is to display the PnL for each token, im sure its possible using Moralis

Also, bare with me, im only 6 months into coding web3 :slight_smile:

Can you give an example of parameters for when you try to get the transactions? You can also compare the result with what you get in docs interface with the same parameters

I will study the api a bit more and redo the code, will share in here if any issues again

It simply was throwing out an error for wrong address being provide, error came from the backend server, while trying to fix it caused more chaos, will reset and start over

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.