Untitled

mail@pastecode.io avatar
unknown
javascript
2 years ago
2.6 kB
3
Indexable
Never
import { Connection, PublicKey } from "@solana/web3.js";
import { pdas as stakePdas } from "psystake-test";
import axios from "axios";
import { VaultInfo } from "./types/vault";
import { BASE_URL } from "./constants/url";

import { fetchStakingRecord } from "./accountsLoader";

import { getUserWalletPosition } from "./utils/wallet";

export const getUserWalletPositionAllVaults = async (
  userWallet: PublicKey,
  connection: Connection,
  isMainnet = true
) => {
  const url = `${BASE_URL}vaults${isMainnet ? "" : "?network=devnet"}`;
  const vaultResponse = await axios.get(url);
  if (!vaultResponse) {
    throw Error("Unable to retrieve vaults from the api");
  }
  let vaults: any;
  await Promise.all(
    (vaults = Object.values(vaultResponse.data.vaults).map(
      async (vaultInfo: VaultInfo) => {
        const stakePoolKey = vaultInfo.staking?.stakePoolKey;
        const VaultPoolReward = vaultInfo.staking?.poolRewards;
        try {
          const result = await getUserWalletPosition(
            userWallet,
            new PublicKey(vaultInfo.accounts.vaultAddress),
            connection,
            stakePoolKey ? new PublicKey(stakePoolKey) : null,
            VaultPoolReward,
            isMainnet
          );
          if (!result) {
            return;
          }
          return (vaults[vaultInfo.name] = result);
        } catch (e) {
          return;
        }
      }
    ))
  );
  return vaults;
};

export async function getVaultsInfo(isMainnet = true) {
  const url = `${BASE_URL}vaults${isMainnet ? "" : "?network=devnet"}`;
  const vaultResponse = await axios.get(url);
  if (!vaultResponse) {
    throw Error("Unable to retrieve vaults from the api");
  }
  const stats = vaultResponse.data.stats;
  const vault = vaultResponse.data.vaults;
  const lastModified = vaultResponse.data.lastModified;

  return {
    vault,
    stats,
    lastModified,
  };
}

export const getUserStakePosition = async (
  psyStakeProgramKey: PublicKey,
  walletAddress: PublicKey,
  stakePool: PublicKey,
  connection: Connection
) => {
  try {
    if (!stakePool) return;
    const [stakingRecordKey] = await stakePdas.deriveStakingRecord(
      psyStakeProgramKey,
      walletAddress,
      stakePool
    );
    const stakingRecord = await fetchStakingRecord(
      stakingRecordKey,
      connection
    );
    if (stakingRecord) return stakingRecord;
  } catch (e) {
    throw Error("Invalid input parameters for getUserStakePosition");
  }
};