All files / src utils.ts

34.48% Statements 10/29
0% Branches 0/14
0% Functions 0/5
24% Lines 6/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62  1x     1x                   1x                       1x                       1x             1x                                
import { Connection, PublicKey } from "@solana/web3.js";
import BN from "bn.js";
import { Market } from "./market";
 
export function throwIfNull<T>(
  value: T | null,
  message = "account not found"
): T {
  Iif (value === null) {
    throw new Error(message);
  }
  return value;
}
 
export const getMintDecimals = async (
  connection: Connection,
  mint: PublicKey
) => {
  const { value } = throwIfNull(
    await connection.getParsedAccountInfo(mint),
    "Mint not found"
  );
  // @ts-ignore
  return value?.data?.parsed.info.decimals;
};
 
export const getTokenBalance = async (
  connection: Connection,
  address: PublicKey
) => {
  const { value } = throwIfNull(
    await connection.getParsedAccountInfo(address),
    "Token account does not exist"
  );
  // @ts-ignore
  return value?.data.parsed.uiAmount;
};
 
export const divideBnToNumber = (numerator: BN, denominator: BN): number => {
  const quotient = numerator.div(denominator).toNumber();
  const rem = numerator.umod(denominator);
  const gcd = rem.gcd(denominator);
  return quotient + rem.div(gcd).toNumber() / denominator.div(gcd).toNumber();
};
 
export const computeFp32Price = (market: Market, uiPrice: number) => {
  const tickSize = new BN(market.tickSize);
 
  const decimalsMul = Math.pow(10, market.quoteDecimals - market.baseDecimals);
  const baseQuoteMul =
    market.baseCurrencyMultiplier.toNumber() /
    market.quoteCurrencyMultiplier.toNumber();
 
  const x = uiPrice * baseQuoteMul * decimalsMul;
  const fracX = Math.pow(2, 32) * (x - Math.floor(x));
 
  const price = new BN(x).mul(new BN(2 ** 32)).add(new BN(fracX));
  const rem = price.umod(tickSize);
 
  return price.sub(rem);
};