Within this piece of code, the intention is for the month to reset "every month of the week", "every week and day", and "every day."
As per the coding logic, upon running it for a single day, the daily percentage should be distinct while maintaining consistency between the weekly and monthly percentages, aligning with the daily value. However, upon executing the code for one day, both the weekly and daily percentages are identical, but the monthly percentage varies. I am perplexed by this discrepancy as the weekly and monthly percentages are expected to remain consistent until a week has passed.
Moreover, I am contemplating whether this anomaly could be influenced by operating a Next.js application on my local machine and sporadically turning my computer off and on throughout the day. Could this be interfering with storing the values?
Below is the provided code snippet:
import { NextResponse } from 'next/server';
let holdersCount: number | null = null;
let priceData: { priceUsd: number, marketCap: string ,liquidity: string} = { priceUsd: 0, marketCap: '' ,liquidity: ''};
let priceHistory = {
month: 0, // Utilize numeric values
day: 0,
week: 0,
};
let pctChange = {
month: '0.00', // Maintain as strings for output
day: '0.00',
week: '0.00',
};
let isInitialFetch = true;
{/* Reduced complexity by removing the fetch holder function */}
const fetchPriceData = async () => {
try {
const response = await fetch('https://api.dexscreener.com/latest/dex/tokens/0x9a26F5433671751C3276a065f57e5a02D2817973');
const data = await response.json();
priceData = {
priceUsd: parseFloat(data.pairs[0].priceUsd) || 0, // Ensure it's always a valid number
marketCap: data.pairs[0].marketCap,
liquidity: data.pairs[0].liquidity.usd
};
if (isInitialFetch) {
// Only set the initial prices after the first successful fetch
priceHistory.month = priceData.priceUsd;
priceHistory.day = priceData.priceUsd;
priceHistory.week = priceData.priceUsd;
isInitialFetch = false; // Disable the flag after setting the initial prices
console.log('inital state done')
}
console.log("Old price:", priceHistory.month);
console.log("Current price:", priceData.priceUsd);
// Calculate the percentage change for each timeframe
const calculatePercentChange = (oldPrice: number, newPrice: number): string => {
if (oldPrice === 0 || isNaN(oldPrice) || isNaN(newPrice)) {
return '0'; // Avoid invalid calculations or division by 0
}
const percentChange = ((newPrice - oldPrice) / oldPrice) * 100;
return percentChange > 0 ? `+${percentChange.toFixed(2)}` : percentChange.toFixed(2);
};
// Only calculate percentage change if the old prices have been set and are valid
if (priceHistory.month > 0) {
pctChange.month = calculatePercentChange(priceHistory.month, priceData.priceUsd);
}
if (priceHistory.day > 0) {
pctChange.day = calculatePercentChange(priceHistory.day, priceData.priceUsd);
}
if (priceHistory.week > 0) {
pctChange.week = calculatePercentChange(priceHistory.week, priceData.priceUsd);
}
console.log("Price data updated:", priceData);
console.log("Percentage change:", pctChange);
} catch (error) {
console.error('Error fetching price data:', error);
}
};
// Fetch holders data every 8 hrs
setInterval(fetchHoldersData, 8 * 60 * 60 * 1000);
// Fetch price data every 8 hrs
setInterval(fetchPriceData, 8 * 60 * 60 * 1000);
// Reset the price history every hour, day, and week
setInterval(() => {
priceHistory.month = priceData.priceUsd;
},31 * 24 * 60 * 60 * 1000); // Every month
setInterval(() => {
priceHistory.day = priceData.priceUsd;
}, 24 * 60 * 60 * 1000); // Every day
setInterval(() => {
priceHistory.week = priceData.priceUsd;
}, 7 * 24 * 60 * 60 * 1000); // Every week
// Initial fetch
fetchHoldersData();
fetchPriceData();
export async function GET() {
return NextResponse.json({
holders: holdersCount,
price: priceData.priceUsd.toFixed(2),
marketCap: priceData.marketCap,
liquidity: priceData.liquidity,
percentChanges: pctChange,
});
}
Captured results after 24 hours
The day value is anticipated to differ from the week and month values rather than observing the month value differing from the week and day’s values after a 24-hour period.
To troubleshoot, debug statements were included, and the code was executed multiple times endeavoring to pinpoint the issue.