Fetching purchase price of each token in users wallet

Console returns the filtering of tokens but returns spent value as 0. Been trying to change this code around and ran out of ideas of why its not fetching the purchase price and displays zero. Please provide insights of what the possible issue can be.

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();
  }
});



This is where its passed on to the frontend

import axios from "axios";
import { useEffect, useState } from "react";
import { useAccount } from "wagmi";
import Card from "./card.js";

export default function GetWalletTokens() {
  const [tokens, setTokens] = useState([]);
  const [totalValue, setTotalValue] = useState(0);
  const { address } = useAccount();

  useEffect(() => {
    async function getData() {
      const response = await axios.get(`http://localhost:5001/gettokens`, {
        params: { address },
      });
      console.log(response.data);
      setTokens(response.data.slice(0, -1));
      setTotalValue(response.data.slice(-1)[0]);
    }
    getData();
  }, []);

  const tokensSpent = {};

  console.log("tokens", tokens);
  console.log("tokensSpent", tokensSpent);

  return (
    <section>
      <p>Total value: ${totalValue.toFixed(2)}</p>
      {tokens.map((token) => {
        let filteredTokens = tokens.filter((t) => t.usdPrice && t.walletBalance?.symbol === token.walletBalance?.symbol);
        console.log("filteredTokens", filteredTokens);
        if (filteredTokens.length === 1) {
          const spent = tokensSpent[token.walletBalance?.address] || 0;
          console.log("spent", spent);
          return (
            <Card
              key={token.walletBalance?.symbol}
              token={token}
              spent={spent}
              total={totalValue}
            />
          );
        }
        const filteredToken = filteredTokens.reduce((a, b) => {
          if (a.walletBalance?.balance > b.walletBalance?.balance) {
            return a;
          } else {
            return b;
          }
        }, {});
        const filteredTokenAddress = filteredToken.walletBalance?.address;
        if (!tokensSpent[filteredTokenAddress]) {
          tokensSpent[filteredTokenAddress] = 0;
        }
        const spent = tokensSpent[filteredTokenAddress];
        console.log("spent", spent);
        const calculatedBalance = parseFloat(filteredToken.walletBalance?.balance / 10 ** filteredToken.walletBalance?.decimals);
        tokensSpent[filteredTokenAddress] += calculatedBalance * filteredToken.usdPrice;
        console.log("tokensSpent", tokensSpent);
        return (
          <Card
            key={filteredToken.walletBalance?.symbol}
            token={filteredToken}
            spent={spent}
            total={totalValue}
          />
        );
      })}
    </section>
  );
}


and here is where the prop is passed on to the card

import styles from "../styles/Home.module.css";

export default function Card(props) {
  return (
    
    <section className={styles.tableAsset}>
      <section className={styles.titleData}>
      <img src={props.token.walletBalance.thumbnail} />
            <section className={styles.nameAndSymbol}>
          {
            <span className={styles.tokenSymbol}>
              {props.token.walletBalance.symbol}
            </span>
          }
          {
            <span className={styles.tokenName}>
              {props.token.walletBalance.name}
            </span>
          }
        </section>
      </section>
      <section className={styles.portfolioValues}>
        <span>
          {`${(
            ((props.token.calculatedBalance * props.token.usdPrice) /
              props.total) *
            100
          ).toFixed(2)} %`}
        </span>
      </section>
      <section className={styles.price}>
        <span>{`$${props.token.usdPrice.toFixed(2)}`}</span>
      </section>
      <section className={styles.dollarAndAmount}>
        <span className={styles.dollarAmount}>{`$${(
          props.token.calculatedBalance * props.token.usdPrice
        ).toFixed(2)}`}</span>
        <span>{`${props.token.calculatedBalance} ${props.token.walletBalance.symbol}`}</span>
        <p>Spent: ${props.spent.toFixed(2)}</p>
      </section>
    </section>
  );
}


this is the part that doesn’t work?

if you use the docs interface with the same parameters then it works?

it actually seems to be fetching the price but not sure where its not picking up the usd value spent for each token in wallet. This is from console

This is what i get for value spent

you mean that the calculatedBalance should be multiplied by usdPrice to get that spent value?

no, that would just give me the usd value currently

I want to display the total amount spent on each token in the wallet

For example i bought 10 chainlink at price of 5$ each

I spent a total of $50, that is what i want displayed

And that value where should be computed?

In this first code i shared, backend, here is a snippet

console.log('Token Price Response:', tokenPriceResponse.toJSON());
      const usdSpent = amount * tokenPriceResponse.toJSON().usdPrice;

In the backend what i intended to do is

Pull transactions and add the amounts of tokens bought

Pull the price value paid from each transaction

Multiply both

All done according to each token present in the users wallet

Not sure where the error is from my side in doing so, the return value is 0 spent for each token

The title is incorrect for this topic, it should have been getting and displaying the total amount spent for each token in a users wallet

The idea is to carry out this step and provide a PnL for each token as the next step, wasnt able to find any examples using moralis to do this so reached out to you here

Once done i believe this discussion will be very useful for others as it will market even more functions moralis can help achieve

It works ok here, it logs the expected values?

it doesnt for me, it logs the image i shared, 0 spent value. Are you sure it provides you the amount you spent on the tokens in your wallet?

I don’t know what you mean with this question

you said it works ok here, i assumed you tried the code and it worked for you. I really dont know what else to add, i shared all the information already, i mentioned twice that it doesnt log the expected value, but you asked again, not sure what to say. Can you help or no?

I don’t know what line doesn’t log the expected value. I thought that it logs the expected value and the issue is somewhere else.

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();
  }
});

None of this is being logged, i have more apis in the backed with this one, the others are working, so the setup is correct, has to be an issue with the code i wrote, maybe we can start with the first part, fetching wallet transactions, to see why its not being logged