utils#getSyrupLPToken TypeScript Examples

The following examples show how to use utils#getSyrupLPToken. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: hooks.ts    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
export function useSyrupInfo(
  tokenToFilterBy?: Token | null,
  startIndex?: number,
  endIndex?: number,
  filter?: { search: string; isStaked: boolean },
): SyrupInfo[] {
  const { chainId, account } = useActiveWeb3React();
  const currentTimestamp = dayjs().unix();

  const info = useMemo(
    () =>
      chainId
        ? returnSyrupInfo()
            [chainId]?.slice(startIndex, endIndex)
            .filter(
              (syrupInfo) =>
                syrupInfo.ending > currentTimestamp &&
                (tokenToFilterBy === undefined || tokenToFilterBy === null
                  ? getSearchFiltered(syrupInfo, filter ? filter.search : '')
                  : tokenToFilterBy.equals(syrupInfo.token)),
            ) ?? []
        : [],
    [chainId, tokenToFilterBy, startIndex, endIndex, filter, currentTimestamp],
  );

  const uni = chainId ? GlobalValue.tokens.UNI[chainId] : undefined;

  const rewardsAddresses = useMemo(
    () => info.map(({ stakingRewardAddress }) => stakingRewardAddress),
    [info],
  );

  const accountArg = useMemo(() => [account ?? undefined], [account]);

  // get all the info from the staking rewards contracts
  const balances = useMultipleContractSingleData(
    rewardsAddresses,
    STAKING_REWARDS_INTERFACE,
    'balanceOf',
    accountArg,
  );
  const earnedAmounts = useMultipleContractSingleData(
    rewardsAddresses,
    STAKING_REWARDS_INTERFACE,
    'earned',
    accountArg,
  );
  const totalSupplies = useMultipleContractSingleData(
    rewardsAddresses,
    STAKING_REWARDS_INTERFACE,
    'totalSupply',
  );
  const rewardRates = useMultipleContractSingleData(
    rewardsAddresses,
    STAKING_REWARDS_INTERFACE,
    'rewardRate',
    undefined,
    NEVER_RELOAD,
  );

  const stakingTokenPairs = usePairs(
    info.map((item) => [
      unwrappedToken(item.token),
      unwrappedToken(item.baseToken),
    ]),
  );

  const usdBaseTokenPrices = useUSDCPrices(
    info.map((item) => unwrappedToken(item.baseToken)),
  );

  const stakingTokenPrices = useUSDCPricesToken(
    info.map((item) => item.stakingToken),
  );

  return useMemo(() => {
    if (!chainId || !uni) return [];

    return rewardsAddresses.reduce<SyrupInfo[]>(
      (memo, rewardsAddress, index) => {
        // these two are dependent on account
        const balanceState = balances[index];
        const earnedAmountState = earnedAmounts[index];
        const stakingTokenPrice = stakingTokenPrices[index];

        // these get fetched regardless of account
        const totalSupplyState = totalSupplies[index];
        const rewardRateState = rewardRates[index];
        const syrupInfo = info[index];

        if (
          // these may be undefined if not logged in
          !balanceState?.loading &&
          !earnedAmountState?.loading &&
          // always need these
          totalSupplyState &&
          !totalSupplyState.loading &&
          rewardRateState &&
          !rewardRateState.loading
        ) {
          // get the LP token
          const token = syrupInfo.token;
          const [, stakingTokenPair] = stakingTokenPairs[index];
          const tokenPairPrice = stakingTokenPair?.priceOf(token);
          const usdPriceBaseToken = usdBaseTokenPrices[index];
          const priceOfRewardTokenInUSD =
            tokenPairPrice && usdPriceBaseToken
              ? Number(tokenPairPrice.toSignificant()) *
                Number(usdPriceBaseToken.toSignificant())
              : undefined;

          const rewards = syrupInfo.rate * (priceOfRewardTokenInUSD ?? 0);

          // check for account, if no account set to 0
          const rate = web3.utils.toWei(syrupInfo.rate.toString());
          const syrupToken = getSyrupLPToken(syrupInfo);
          const stakedAmount = initTokenAmountFromCallResult(
            syrupToken,
            balanceState,
          );
          const totalStakedAmount = initTokenAmountFromCallResult(
            syrupToken,
            totalSupplyState,
          );
          const totalRewardRate = new TokenAmount(token, JSBI.BigInt(rate));
          //const pair = info[index].pair.toLowerCase();
          //const fees = (pairData && pairData[pair] ? pairData[pair].oneDayVolumeUSD * 0.0025: 0);
          const rewardRate = initTokenAmountFromCallResult(
            token,
            rewardRateState,
          );
          const getHypotheticalRewardRate = (
            stakedAmount?: TokenAmount,
            totalStakedAmount?: TokenAmount,
          ): TokenAmount | undefined => {
            if (!stakedAmount || !totalStakedAmount || !rewardRate) return;
            return new TokenAmount(
              token,
              JSBI.greaterThan(totalStakedAmount.raw, JSBI.BigInt(0))
                ? JSBI.divide(
                    JSBI.multiply(rewardRate.raw, stakedAmount.raw),
                    totalStakedAmount.raw,
                  )
                : JSBI.BigInt(0),
            );
          };

          const individualRewardRate = getHypotheticalRewardRate(
            stakedAmount,
            totalStakedAmount,
          );

          const periodFinishMs = syrupInfo.ending;

          memo.push({
            stakingRewardAddress: rewardsAddress,
            token: syrupInfo.token,
            ended: syrupInfo.ended,
            name: syrupInfo.name,
            lp: syrupInfo.lp,
            periodFinish: periodFinishMs,
            earnedAmount: initTokenAmountFromCallResult(
              token,
              earnedAmountState,
            ),
            rewardRate: individualRewardRate,
            totalRewardRate: totalRewardRate,
            stakedAmount: stakedAmount,
            totalStakedAmount: totalStakedAmount,
            getHypotheticalRewardRate,
            baseToken: syrupInfo.baseToken,
            rate: syrupInfo.rate,
            rewardTokenPriceinUSD: priceOfRewardTokenInUSD,
            rewards,
            stakingToken: syrupInfo.stakingToken,
            valueOfTotalStakedAmountInUSDC: totalStakedAmount
              ? Number(totalStakedAmount.toExact()) * stakingTokenPrice
              : undefined,
          });
        }
        return memo;
      },
      [],
    );
  }, [
    balances,
    chainId,
    earnedAmounts,
    info,
    rewardsAddresses,
    totalSupplies,
    uni,
    rewardRates,
    stakingTokenPairs,
    usdBaseTokenPrices,
    stakingTokenPrices,
  ]).filter((syrupInfo) =>
    filter && filter.isStaked
      ? syrupInfo.stakedAmount && syrupInfo.stakedAmount.greaterThan('0')
      : true,
  );
}
Example #2
Source File: hooks.ts    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
export function useOldSyrupInfo(
  tokenToFilterBy?: Token | null,
  startIndex?: number,
  endIndex?: number,
  filter?: { search: string; isStaked: boolean },
): SyrupInfo[] {
  const { chainId, account } = useActiveWeb3React();
  const currentTimestamp = dayjs().unix();

  const info = useMemo(() => {
    if (!chainId) return [];
    const endedSyrupInfos =
      returnSyrupInfo(false)[chainId]?.filter(
        (syrupInfo) => syrupInfo.ending <= currentTimestamp,
      ) ?? [];
    const oldSyrupInfos = returnSyrupInfo(true)[chainId] ?? [];
    const allOldSyrupInfos = endedSyrupInfos.concat(oldSyrupInfos);
    return allOldSyrupInfos
      .slice(startIndex, endIndex)
      .filter((syrupInfo) =>
        tokenToFilterBy === undefined || tokenToFilterBy === null
          ? getSearchFiltered(syrupInfo, filter ? filter.search : '')
          : tokenToFilterBy.equals(syrupInfo.token),
      );
  }, [
    chainId,
    tokenToFilterBy,
    startIndex,
    endIndex,
    filter,
    currentTimestamp,
  ]);

  const uni = chainId ? GlobalValue.tokens.UNI[chainId] : undefined;

  const rewardsAddresses = useMemo(
    () => info.map(({ stakingRewardAddress }) => stakingRewardAddress),
    [info],
  );

  const accountArg = useMemo(() => [account ?? undefined], [account]);

  // get all the info from the staking rewards contracts
  const balances = useMultipleContractSingleData(
    rewardsAddresses,
    STAKING_REWARDS_INTERFACE,
    'balanceOf',
    accountArg,
  );
  const earnedAmounts = useMultipleContractSingleData(
    rewardsAddresses,
    STAKING_REWARDS_INTERFACE,
    'earned',
    accountArg,
  );
  const totalSupplies = useMultipleContractSingleData(
    rewardsAddresses,
    STAKING_REWARDS_INTERFACE,
    'totalSupply',
  );

  const rewardRates = useMultipleContractSingleData(
    rewardsAddresses,
    STAKING_REWARDS_INTERFACE,
    'rewardRate',
    undefined,
    NEVER_RELOAD,
  );

  const stakingTokenPairs = usePairs(
    info.map((item) => [
      unwrappedToken(item.token),
      unwrappedToken(item.baseToken),
    ]),
  );

  const usdBaseTokenPrices = useUSDCPrices(
    info.map((item) => unwrappedToken(item.baseToken)),
  );

  const stakingTokenPrices = useUSDCPricesToken(
    info.map((item) => item.stakingToken),
  );

  return useMemo(() => {
    if (!chainId || !uni) return [];

    return rewardsAddresses.reduce<SyrupInfo[]>(
      (memo, rewardsAddress, index) => {
        // these two are dependent on account
        const balanceState = balances[index];
        const earnedAmountState = earnedAmounts[index];

        // these get fetched regardless of account
        const totalSupplyState = totalSupplies[index];
        const rewardRateState = rewardRates[index];
        const syrupInfo = info[index];
        const stakingTokenPrice = stakingTokenPrices[index];

        if (
          // these may be undefined if not logged in
          !balanceState?.loading &&
          !earnedAmountState?.loading &&
          // always need these
          totalSupplyState &&
          !totalSupplyState.loading &&
          rewardRateState &&
          !rewardRateState.loading
        ) {
          // get the LP token
          const token = syrupInfo.token;

          // check for account, if no account set to 0
          const rate = web3.utils.toWei(syrupInfo.rate.toString());
          const stakedAmount = initTokenAmountFromCallResult(
            getSyrupLPToken(syrupInfo),
            balanceState,
          );
          const totalStakedAmount = initTokenAmountFromCallResult(
            getSyrupLPToken(syrupInfo),
            totalSupplyState,
          );
          const totalRewardRate = new TokenAmount(token, JSBI.BigInt(rate));
          //const pair = info[index].pair.toLowerCase();
          //const fees = (pairData && pairData[pair] ? pairData[pair].oneDayVolumeUSD * 0.0025: 0);
          const rewardRate = initTokenAmountFromCallResult(
            token,
            rewardRateState,
          );
          const getHypotheticalRewardRate = (
            stakedAmount?: TokenAmount,
            totalStakedAmount?: TokenAmount,
          ): TokenAmount | undefined => {
            if (!stakedAmount || !totalStakedAmount || !rewardRate) return;
            return new TokenAmount(
              token,
              JSBI.greaterThan(totalStakedAmount.raw, JSBI.BigInt(0))
                ? JSBI.divide(
                    JSBI.multiply(rewardRate.raw, stakedAmount.raw),
                    totalStakedAmount.raw,
                  )
                : JSBI.BigInt(0),
            );
          };

          const individualRewardRate = getHypotheticalRewardRate(
            stakedAmount,
            totalStakedAmount,
          );

          const periodFinishMs = syrupInfo.ending;

          const [, stakingTokenPair] = stakingTokenPairs[index];
          const tokenPairPrice = stakingTokenPair?.priceOf(token);
          const usdPriceBaseToken = usdBaseTokenPrices[index];
          const priceOfRewardTokenInUSD =
            Number(tokenPairPrice?.toSignificant()) *
            Number(usdPriceBaseToken?.toSignificant());

          memo.push({
            stakingRewardAddress: rewardsAddress,
            token: syrupInfo.token,
            ended: true,
            name: syrupInfo.name,
            lp: syrupInfo.lp,
            periodFinish: periodFinishMs,
            earnedAmount: initTokenAmountFromCallResult(
              token,
              earnedAmountState,
            ),
            rewardRate: individualRewardRate,
            totalRewardRate: totalRewardRate,
            stakedAmount: stakedAmount,
            totalStakedAmount: totalStakedAmount,
            getHypotheticalRewardRate,
            baseToken: syrupInfo.baseToken,
            rate: 0,
            rewardTokenPriceinUSD: priceOfRewardTokenInUSD,
            stakingToken: syrupInfo.stakingToken,
            valueOfTotalStakedAmountInUSDC: totalStakedAmount
              ? Number(totalStakedAmount.toExact()) * stakingTokenPrice
              : undefined,
          });
        }
        return memo;
      },
      [],
    );
  }, [
    balances,
    chainId,
    earnedAmounts,
    info,
    rewardsAddresses,
    totalSupplies,
    uni,
    rewardRates,
    stakingTokenPairs,
    usdBaseTokenPrices,
    stakingTokenPrices,
  ]).filter((syrupInfo) =>
    filter && filter.isStaked
      ? syrupInfo.stakedAmount && syrupInfo.stakedAmount.greaterThan('0')
      : true,
  );
}