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