forked from mito-systems/sol-mem-gen
45 lines
1.3 KiB
TypeScript
45 lines
1.3 KiB
TypeScript
import assert from "assert";
|
|
import BN from "bn.js";
|
|
import fetch from 'node-fetch';
|
|
import Big from 'big.js';
|
|
|
|
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();
|
|
|
|
// Handle price with Big.js, then convert to BN
|
|
const priceMTMFor1USDC = new Big(quoteResponse['data'][USDC_MINT]['price']).toFixed(6);
|
|
const priceInBaseUnits = new BN(new Big(priceMTMFor1USDC).times(new Big(10).pow(6)).toString());
|
|
|
|
this.cachedQuotes.push(priceInBaseUnits);
|
|
if (this.cachedQuotes.length > 3) {
|
|
this.cachedQuotes.shift();
|
|
}
|
|
} catch (error) {
|
|
console.error('Error fetching quotes:', error);
|
|
}
|
|
}
|
|
|
|
getQuotes(): BN[] {
|
|
return this.cachedQuotes;
|
|
}
|
|
}
|
|
|
|
export { QuotesService };
|