Skip to content

Instantly share code, notes, and snippets.

@adrena-orex
Last active March 16, 2023 08:07
Show Gist options
  • Select an option

  • Save adrena-orex/ce6478e7d7602076f8c31908d3d26320 to your computer and use it in GitHub Desktop.

Select an option

Save adrena-orex/ce6478e7d7602076f8c31908d3d26320 to your computer and use it in GitHub Desktop.
// ================================================================
// =========== PART 1
// ================================================================
//
// Fetch tokens prices from URL and calculate the average price
//
async function fetchPrice(url: string): Promise<string> {
const response = await fetch(url);
return await response.text();
}
async function fetchPrices(urls: any[]): Promise<string[]> {
let prices = [];
for (let url of urls) {
let price = await fetchPrice(url);
prices.push(price);
}
return prices;
}
// Load prices
let prices = await fetchPrices([
'https://api.example.com/sol',
'https://api.example.com/btc',
'https://api.example.com/eth',
]);
// Transform string prices into number prices
let pricesNumber = [] as any[];
prices.forEach(price => {
pricesNumber.push(Number(price));
return;
});
// Calculate average price
let totPrice = 0;
pricesNumber.forEach(price => {
totPrice += price;
return;
});
let average_price: number = totPrice / pricesNumber.length;
// ================================================================
// =========== PART 2
// ================================================================
//
// Function to get LP balance
//
import { Connection } from "@solana/web3.js";
import { getAssociatedTokenAddress } from "@solana/spl-token";
import { PublicKey } from "@solana/web3.js";
export async function checkIfAccountExists(
account: PublicKey,
connection: Connection
): Promise<boolean> {
let bal = await connection.getBalance(account);
if (bal > 0) {
return true;
} else {
return false;
}
}
export async function fetchLPBalance(
address: PublicKey, // mint
publicKey: PublicKey, // owner
connection: any
): Promise<number> {
let lpTokenAccount = await getAssociatedTokenAddress(address, publicKey);
if (!(await checkIfAccountExists(lpTokenAccount, connection))) {
return 0;
} else {
let balance = await connection.getTokenAccountBalance(lpTokenAccount);
return balance.value.uiAmount!;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment