sol-mem-gen/quotes-service.ts

43 lines
1.2 KiB
TypeScript

import assert from "assert";
import BN from "bn.js";
import fetch from 'node-fetch';
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;
class QuotesService {
private cachedQuotes: BN[] = [];
async 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('.', ''));
this.cachedQuotes.push(price);
if (this.cachedQuotes.length > 3) {
this.cachedQuotes.shift();
}
console.log('Cache updated: ', this.cachedQuotes);
} catch (error) {
console.error('Error fetching quotes:', error);
}
}
getQuotes(): BN[] {
return this.cachedQuotes;
}
}
export { QuotesService };