68 lines
1.9 KiB
TypeScript
68 lines
1.9 KiB
TypeScript
interface JupiterPriceResponse {
|
|
[mintAddress: string]: {
|
|
usdPrice: number;
|
|
blockId: number;
|
|
decimals: number;
|
|
priceChange24h: number;
|
|
};
|
|
}
|
|
|
|
interface TokenPriceInfo {
|
|
usdPrice: number;
|
|
decimals: number;
|
|
}
|
|
|
|
interface RequiredTokenInfo {
|
|
requiredAmount: number;
|
|
decimals: number;
|
|
}
|
|
|
|
/**
|
|
* Fetches token price from Jupiter aggregator API
|
|
* @param mintAddress The Solana token mint address
|
|
* @returns Token price information including USD price and decimals
|
|
*/
|
|
export async function getTokenInfo(mintAddress: string): Promise<TokenPriceInfo> {
|
|
try {
|
|
const response = await fetch(`https://lite-api.jup.ag/price/v3?ids=${mintAddress}`);
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`Jupiter API error: ${response.status} ${response.statusText}`);
|
|
}
|
|
|
|
const data: JupiterPriceResponse = await response.json();
|
|
|
|
if (!data[mintAddress]) {
|
|
throw new Error(`Price not found for token: ${mintAddress}`);
|
|
}
|
|
|
|
const tokenInfo = data[mintAddress];
|
|
|
|
return {
|
|
usdPrice: tokenInfo.usdPrice,
|
|
decimals: tokenInfo.decimals
|
|
};
|
|
} catch (error) {
|
|
console.error('Error fetching token price from Jupiter:', error);
|
|
throw error;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Calculates the token amount needed for a given USD price
|
|
* @param targetUsdAmount The target amount in USD
|
|
* @param mintAddress The Solana token mint address
|
|
* @returns The token amount (in smallest units) needed and token decimals
|
|
*/
|
|
export async function GetRequiredTokenInfo(targetUsdAmount: number, mintAddress: string): Promise<RequiredTokenInfo> {
|
|
const priceInfo = await getTokenInfo(mintAddress);
|
|
|
|
// Calculate token amount needed
|
|
const tokenAmount = targetUsdAmount / priceInfo.usdPrice;
|
|
|
|
// Convert to smallest units (considering decimals)
|
|
const amountInSmallestUnits = Math.round(tokenAmount * Math.pow(10, priceInfo.decimals));
|
|
|
|
return {requiredAmount: amountInSmallestUnits, decimals: priceInfo.decimals};
|
|
}
|