forked from mito-systems/sol-mem-gen
38 lines
1.1 KiB
TypeScript
38 lines
1.1 KiB
TypeScript
import assert from "assert";
|
|
import BN from "bn.js";
|
|
import fetch from 'node-fetch';
|
|
|
|
let cachedQuotes: BN[] = [];
|
|
|
|
assert(process.env.NEXT_PUBLIC_USDC_MINT, 'USDC_MINT is required');
|
|
assert(process.env.NEXT_PUBLIC_MTM_TOKEN_MINT, 'MTM_TOKEN_MINT is required');
|
|
|
|
const MTM_TOKEN_MINT = process.env.NEXT_PUBLIC_MTM_TOKEN_MINT;
|
|
const USDC_MINT = process.env.NEXT_PUBLIC_USDC_MINT;
|
|
|
|
export async function fetchAndCacheQuotes(): Promise<void> {
|
|
try {
|
|
const url = `https://api.jup.ag/price/v2?ids=${USDC_MINT}&vsToken=${MTM_TOKEN_MINT}`;
|
|
const response = await fetch(url);
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Failed to fetch quote: ${response.statusText}`);
|
|
}
|
|
|
|
const quoteResponse = await response.json();
|
|
const priceFromAPI = Number(quoteResponse['data'][USDC_MINT]['price']).toFixed(6);
|
|
const price = new BN(priceFromAPI.toString().replace('.', ''));
|
|
|
|
cachedQuotes.push(price);
|
|
if (cachedQuotes.length > 3) {
|
|
cachedQuotes.shift();
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching quotes:', error);
|
|
}
|
|
}
|
|
|
|
export function getLatestQuote(): BN | undefined {
|
|
return cachedQuotes[cachedQuotes.length - 1];
|
|
}
|