Skip to content

Instantly share code, notes, and snippets.

@0xBigBoss
Created March 26, 2024 02:39
Show Gist options
  • Save 0xBigBoss/27f29c0ed68f0d9c53e8787e2b13e6b2 to your computer and use it in GitHub Desktop.
Save 0xBigBoss/27f29c0ed68f0d9c53e8787e2b13e6b2 to your computer and use it in GitHub Desktop.
Returns historical prices of POKT in the past n days and the average for that period
 import axios from 'axios';
import { poll } from 'ethers/lib/utils';
import moment from 'moment';
import Logger from '@loaders/logger';
import sleep from '@helpers/utils/sleep';
import { getRandomArbitrary } from '@helpers/utils/get-random-arbitrary';
const pricesPerDayUsd: { [day: string]: number } = {};
let historicalPricesLoaded = false;
async function refreshHistoricalPrices() {
const startedAt = new Date();
while (!historicalPricesLoaded) {
try {
await loadHistoricalPrices();
historicalPricesLoaded = true;
Logger.debug(
'Historical prices loaded in ' +
(new Date().getTime() - startedAt.getTime()) +
'ms'
);
setTimeout(async () => {
historicalPricesLoaded = false;
await refreshHistoricalPrices();
}, 60 * 60 * 1000); // refresh every hour
} catch (e) {
Logger.error(`Cannot load historical prices: ${e}`);
await sleep(10000);
}
}
}
(async () => await refreshHistoricalPrices())();
export async function getPriceData(
date: string,
useCache = true
): Promise<number> {
// use cache if available and if not today
if (
pricesPerDayUsd[date] &&
useCache &&
date !== moment().format('DD-MM-YYYY')
) {
return Promise.resolve(pricesPerDayUsd[date]);
}
const url =
'https://api.coingecko.com/api/v3/coins/pocket-network/history?date=' +
date;
const price = await poll(
() =>
axios
.get(url)
.then((response) => {
if (!response.data['market_data']) {
try {
Logger.warn(
`Response is missing market_data, url: ${url} ${JSON.stringify(
response.data
)}`
);
} catch (_) {
// ignore
Logger.warn(`Response is missing market_data, url: ${url}`);
}
return undefined;
}
return response.data['market_data']['current_price'].usd;
})
.catch((e) => {
if (e.response?.status !== 429) {
Logger.warn(`Cannot get pokt price, url: ${url} ${e}`);
}
return undefined;
}),
{
interval: 10000
}
);
pricesPerDayUsd[date] = price;
return price;
}
async function loadHistoricalPrices() {
for (let i = 0; i < 30; i++) {
const dateString = moment()
.subtract(i + 1, 'days')
.format('DD-MM-YYYY');
// if price is not available, get it
while (!pricesPerDayUsd[dateString]) {
const price = await getPriceData(dateString);
pricesPerDayUsd[dateString] = price;
// about 10-30 requests per minute
await sleep((60 / Math.floor(getRandomArbitrary(10, 30))) * 1000);
}
}
}
/**
* Returns historical prices of POKT in the past n days and the average for that period
*/
export default async (): Promise<{
pricesPerDayUsd: { [day: string]: number };
pokt7dAvg: number;
pokt30dAvg: number;
pokt30dMin: number;
pokt30dMax: number;
}> => {
while (!historicalPricesLoaded) {
await sleep(100);
}
const prices = Object.values(pricesPerDayUsd);
const pokt7dAvg = prices.slice(0, 7).reduce((a, b) => a + b, 0) / 7;
const pokt30dAvg = prices.slice(0, 30).reduce((a, b) => a + b, 0) / 30;
const pokt30dMin = Math.min(...prices);
const pokt30dMax = Math.max(...prices);
return {
pricesPerDayUsd,
pokt7dAvg,
pokt30dAvg,
pokt30dMin,
pokt30dMax
};
};
@0xBigBoss
Copy link
Author

Just return the default export function in the request as JSON.

{
  ...(await getHistoricalTokenPrice())
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment