types#StakingInfo TypeScript Examples

The following examples show how to use types#StakingInfo. 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: index.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function getEarnedUSDLPFarm(stakingInfo: StakingInfo | undefined) {
  if (!stakingInfo || !stakingInfo.earnedAmount) return;
  const earnedUSD =
    Number(stakingInfo.earnedAmount.toExact()) * stakingInfo.rewardTokenPrice;
  if (earnedUSD < 0.001 && earnedUSD > 0) {
    return '< $0.001';
  }
  return `$${earnedUSD.toLocaleString()}`;
}
Example #2
Source File: index.ts    From interface-v2 with GNU General Public License v3.0 6 votes vote down vote up
export function getFarmLPToken(
  info: StakingInfo | DualStakingInfo | StakingBasic | DualStakingBasic,
) {
  const lp = info.lp;
  const dummyPair = new Pair(
    new TokenAmount(info.tokens[0], '0'),
    new TokenAmount(info.tokens[1], '0'),
  );
  if (lp && lp !== '') return new Token(137, lp, 18, 'SLP', 'Staked LP');
  return dummyPair.liquidityToken;
}
Example #3
Source File: RewardSlider.tsx    From interface-v2 with GNU General Public License v3.0 5 votes vote down vote up
RewardSlider: React.FC = () => {
  const classes = useStyles();
  const theme = useTheme();
  const { chainId } = useActiveWeb3React();
  const tabletWindowSize = useMediaQuery(theme.breakpoints.down('md'));
  const mobileWindowSize = useMediaQuery(theme.breakpoints.down('sm'));
  const rewardItems = useStakingInfo(null, 0, 5);
  const [bulkPairs, setBulkPairs] = useState<any>(null);

  useEffect(() => {
    if (chainId) {
      const stakingPairLists =
        returnStakingInfo()
          [chainId]?.slice(0, 5)
          .map((item) => item.pair) ?? [];
      getBulkPairData(stakingPairLists).then((data) => setBulkPairs(data));
    }
  }, [chainId]);

  const stakingAPYs = useMemo(() => {
    if (bulkPairs && rewardItems.length > 0) {
      return rewardItems.map((info: StakingInfo) => {
        const oneDayVolume = bulkPairs[info.pair]?.oneDayVolumeUSD;
        const reserveUSD = bulkPairs[info.pair]?.reserveUSD;
        if (oneDayVolume && reserveUSD) {
          return getOneYearFee(oneDayVolume, reserveUSD);
        } else {
          return 0;
        }
      });
    } else {
      return [];
    }
  }, [bulkPairs, rewardItems]);

  const rewardSliderSettings = {
    dots: false,
    infinite: true,
    speed: 500,
    slidesToShow: mobileWindowSize ? 1 : tabletWindowSize ? 2 : 3,
    slidesToScroll: 1,
    nextArrow: <ChevronRightIcon />,
    prevArrow: <ChevronLeftIcon />,
  };

  return (
    <Slider {...rewardSliderSettings} className={classes.rewardsSlider}>
      {rewardItems.map((item, index) => (
        <RewardSliderItem
          key={index}
          stakingAPY={stakingAPYs[index]}
          info={item}
        />
      ))}
    </Slider>
  );
}
Example #4
Source File: FarmCard.tsx    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
FarmCard: React.FC<{
  stakingInfo: StakingInfo | DualStakingInfo;
  stakingAPY: number;
  isLPFarm?: boolean;
}> = ({ stakingInfo, stakingAPY, isLPFarm }) => {
  const classes = useStyles();
  const { palette, breakpoints } = useTheme();
  const isMobile = useMediaQuery(breakpoints.down('xs'));
  const [isExpandCard, setExpandCard] = useState(false);

  const lpStakingInfo = stakingInfo as StakingInfo;
  const dualStakingInfo = stakingInfo as DualStakingInfo;

  const token0 = stakingInfo.tokens[0];
  const token1 = stakingInfo.tokens[1];

  const currency0 = unwrappedToken(token0);
  const currency1 = unwrappedToken(token1);

  const stakedAmounts = getStakedAmountStakingInfo(stakingInfo);

  let apyWithFee: number | string = 0;

  if (stakingAPY && stakingAPY > 0 && stakingInfo.perMonthReturnInRewards) {
    apyWithFee = formatAPY(
      getAPYWithFee(stakingInfo.perMonthReturnInRewards, stakingAPY),
    );
  }

  const tvl = getTVLStaking(
    stakedAmounts?.totalStakedUSD,
    stakedAmounts?.totalStakedBase,
  );

  const lpPoolRate = getRewardRate(
    lpStakingInfo.totalRewardRate,
    lpStakingInfo.rewardToken,
  );

  const dualPoolRateA = getRewardRate(
    dualStakingInfo.totalRewardRateA,
    dualStakingInfo.rewardTokenA,
  );
  const dualPoolRateB = getRewardRate(
    dualStakingInfo.totalRewardRateB,
    dualStakingInfo.rewardTokenB,
  );

  const earnedUSDStr = isLPFarm
    ? getEarnedUSDLPFarm(lpStakingInfo)
    : getEarnedUSDDualFarm(dualStakingInfo);

  const lpRewards = lpStakingInfo.rewardTokenPrice * lpStakingInfo.rate;
  const dualRewards =
    dualStakingInfo.rateA * dualStakingInfo.rewardTokenAPrice +
    dualStakingInfo.rateB * dualStakingInfo.rewardTokenBPrice;

  const renderPool = (width: number) => (
    <Box display='flex' alignItems='center' width={width}>
      <DoubleCurrencyLogo
        currency0={currency0}
        currency1={currency1}
        size={28}
      />
      <Box ml={1.5}>
        <Typography variant='body2'>
          {currency0.symbol} / {currency1.symbol} LP
        </Typography>
      </Box>
    </Box>
  );

  return (
    <Box
      className={cx(
        classes.farmLPCard,
        isExpandCard && classes.highlightedCard,
      )}
    >
      <Box
        className={classes.farmLPCardUp}
        onClick={() => setExpandCard(!isExpandCard)}
      >
        {isMobile ? (
          <>
            {renderPool(isExpandCard ? 0.95 : 0.7)}
            {!isExpandCard && (
              <Box width={0.25}>
                <Box display='flex' alignItems='center'>
                  <Typography variant='caption' color='textSecondary'>
                    APY
                  </Typography>
                  <Box ml={0.5} height={16}>
                    <img src={CircleInfoIcon} alt={'arrow up'} />
                  </Box>
                </Box>
                <Box mt={0.5} color={palette.success.main}>
                  <Typography variant='body2'>{apyWithFee}%</Typography>
                </Box>
              </Box>
            )}
            <Box
              width={0.05}
              display='flex'
              justifyContent='flex-end'
              color={palette.primary.main}
            >
              {isExpandCard ? <KeyboardArrowUp /> : <KeyboardArrowDown />}
            </Box>
          </>
        ) : (
          <>
            {renderPool(0.3)}
            <Box width={0.2} textAlign='center'>
              <Typography variant='body2'>{tvl}</Typography>
            </Box>
            <Box width={0.25} textAlign='center'>
              <Typography variant='body2'>
                ${(isLPFarm ? lpRewards : dualRewards).toLocaleString()} / day
              </Typography>
              {isLPFarm ? (
                <Typography variant='body2'>{lpPoolRate}</Typography>
              ) : (
                <>
                  <Typography variant='body2'>{dualPoolRateA}</Typography>
                  <Typography variant='body2'>{dualPoolRateB}</Typography>
                </>
              )}
            </Box>
            <Box
              width={0.15}
              display='flex'
              justifyContent='center'
              alignItems='center'
              color={palette.success.main}
            >
              <Typography variant='body2'>{apyWithFee}%</Typography>
              <Box ml={0.5} height={16}>
                <img src={CircleInfoIcon} alt={'arrow up'} />
              </Box>
            </Box>
            <Box width={0.2} textAlign='right'>
              <Typography variant='body2'>{earnedUSDStr}</Typography>
              {isLPFarm ? (
                <Box
                  display='flex'
                  alignItems='center'
                  justifyContent='flex-end'
                >
                  <CurrencyLogo
                    currency={lpStakingInfo.rewardToken}
                    size='16px'
                  />
                  <Typography variant='body2' style={{ marginLeft: 5 }}>
                    {formatTokenAmount(lpStakingInfo.earnedAmount)}
                    <span>&nbsp;{lpStakingInfo.rewardToken.symbol}</span>
                  </Typography>
                </Box>
              ) : (
                <>
                  <Box
                    display='flex'
                    alignItems='center'
                    justifyContent='flex-end'
                  >
                    <CurrencyLogo
                      currency={unwrappedToken(dualStakingInfo.rewardTokenA)}
                      size='16px'
                    />
                    <Typography variant='body2' style={{ marginLeft: 5 }}>
                      {formatTokenAmount(dualStakingInfo.earnedAmountA)}
                      <span>&nbsp;{dualStakingInfo.rewardTokenA.symbol}</span>
                    </Typography>
                  </Box>
                  <Box
                    display='flex'
                    alignItems='center'
                    justifyContent='flex-end'
                  >
                    <CurrencyLogo
                      currency={unwrappedToken(dualStakingInfo.rewardTokenB)}
                      size='16px'
                    />
                    <Typography variant='body2' style={{ marginLeft: 5 }}>
                      {formatTokenAmount(dualStakingInfo.earnedAmountB)}
                      <span>&nbsp;{dualStakingInfo.rewardTokenB.symbol}</span>
                    </Typography>
                  </Box>
                </>
              )}
            </Box>
          </>
        )}
      </Box>

      {isExpandCard && (
        <FarmCardDetails
          stakingInfo={stakingInfo}
          stakingAPY={stakingAPY}
          isLPFarm={isLPFarm}
        />
      )}
    </Box>
  );
}
Example #5
Source File: FarmCardDetails.tsx    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
FarmCardDetails: React.FC<{
  stakingInfo: StakingInfo | DualStakingInfo;
  stakingAPY: number;
  isLPFarm?: boolean;
}> = ({ stakingInfo, stakingAPY, isLPFarm }) => {
  const classes = useStyles();
  const { t } = useTranslation();
  const { palette, breakpoints } = useTheme();
  const isMobile = useMediaQuery(breakpoints.down('xs'));
  const [stakeAmount, setStakeAmount] = useState('');
  const [attemptStaking, setAttemptStaking] = useState(false);
  const [attemptUnstaking, setAttemptUnstaking] = useState(false);
  const [attemptClaiming, setAttemptClaiming] = useState(false);
  const [approving, setApproving] = useState(false);
  const [unstakeAmount, setUnStakeAmount] = useState('');

  const lpStakingInfo = stakingInfo as StakingInfo;
  const dualStakingInfo = stakingInfo as DualStakingInfo;

  const token0 = stakingInfo ? stakingInfo.tokens[0] : undefined;
  const token1 = stakingInfo ? stakingInfo.tokens[1] : undefined;

  const { account, library } = useActiveWeb3React();
  const addTransaction = useTransactionAdder();

  const currency0 = token0 ? unwrappedToken(token0) : undefined;
  const currency1 = token1 ? unwrappedToken(token1) : undefined;

  const userLiquidityUnstaked = useTokenBalance(
    account ?? undefined,
    stakingInfo.stakedAmount?.token,
  );

  const stakedAmounts = getStakedAmountStakingInfo(
    stakingInfo,
    userLiquidityUnstaked,
  );

  let apyWithFee: number | string = 0;

  if (
    stakingInfo &&
    stakingInfo.perMonthReturnInRewards &&
    stakingAPY &&
    stakingAPY > 0
  ) {
    apyWithFee = formatAPY(
      getAPYWithFee(stakingInfo.perMonthReturnInRewards, stakingAPY),
    );
  }

  const stakingContract = useStakingContract(stakingInfo?.stakingRewardAddress);

  const { parsedAmount: unstakeParsedAmount } = useDerivedStakeInfo(
    unstakeAmount,
    stakingInfo.stakedAmount?.token,
    stakingInfo.stakedAmount,
  );

  const onWithdraw = async () => {
    if (stakingInfo && stakingContract && unstakeParsedAmount) {
      setAttemptUnstaking(true);
      await stakingContract
        .withdraw(`0x${unstakeParsedAmount.raw.toString(16)}`, {
          gasLimit: 300000,
        })
        .then(async (response: TransactionResponse) => {
          addTransaction(response, {
            summary: t('withdrawliquidity'),
          });
          try {
            await response.wait();
            setAttemptUnstaking(false);
          } catch (error) {
            setAttemptUnstaking(false);
          }
        })
        .catch((error: any) => {
          setAttemptUnstaking(false);
          console.log(error);
        });
    }
  };

  const onClaimReward = async () => {
    if (stakingContract && stakingInfo && stakingInfo.stakedAmount) {
      setAttemptClaiming(true);
      await stakingContract
        .getReward({ gasLimit: 350000 })
        .then(async (response: TransactionResponse) => {
          addTransaction(response, {
            summary: t('claimrewards'),
          });
          try {
            await response.wait();
            setAttemptClaiming(false);
          } catch (error) {
            setAttemptClaiming(false);
          }
        })
        .catch((error: any) => {
          setAttemptClaiming(false);
          console.log(error);
        });
    }
  };

  const { parsedAmount } = useDerivedStakeInfo(
    stakeAmount,
    stakingInfo.stakedAmount?.token,
    userLiquidityUnstaked,
  );
  const deadline = useTransactionDeadline();
  const [approval, approveCallback] = useApproveCallback(
    parsedAmount,
    stakingInfo?.stakingRewardAddress,
  );

  const dummyPair = stakingInfo
    ? new Pair(
        new TokenAmount(stakingInfo.tokens[0], '0'),
        new TokenAmount(stakingInfo.tokens[1], '0'),
      )
    : null;
  const pairContract = usePairContract(
    stakingInfo && stakingInfo.lp && stakingInfo.lp !== ''
      ? stakingInfo.lp
      : dummyPair?.liquidityToken.address,
  );

  const onStake = async () => {
    if (stakingContract && parsedAmount && deadline) {
      setAttemptStaking(true);
      stakingContract
        .stake(`0x${parsedAmount.raw.toString(16)}`, {
          gasLimit: 350000,
        })
        .then(async (response: TransactionResponse) => {
          addTransaction(response, {
            summary: t('depositliquidity'),
          });
          try {
            await response.wait();
            setAttemptStaking(false);
          } catch (error) {
            setAttemptStaking(false);
          }
        })
        .catch((error: any) => {
          setAttemptStaking(false);
          console.log(error);
        });
    } else {
      throw new Error(t('stakewithoutapproval'));
    }
  };

  const onAttemptToApprove = async () => {
    if (!pairContract || !library || !deadline)
      throw new Error(t('missingdependencies'));
    const liquidityAmount = parsedAmount;
    if (!liquidityAmount) throw new Error(t('missingliquidity'));
    setApproving(true);
    try {
      await approveCallback();
      setApproving(false);
    } catch (e) {
      setApproving(false);
    }
  };

  const earnedUSDStr = isLPFarm
    ? getEarnedUSDLPFarm(lpStakingInfo)
    : getEarnedUSDDualFarm(dualStakingInfo);

  const tvl = getTVLStaking(
    stakedAmounts?.totalStakedUSD,
    stakedAmounts?.totalStakedBase,
  );

  const lpRewards = lpStakingInfo.rate * lpStakingInfo.rewardTokenPrice;

  const lpPoolRate = getRewardRate(
    lpStakingInfo.totalRewardRate,
    lpStakingInfo.rewardToken,
  );

  const dualRewards =
    dualStakingInfo.rateA * dualStakingInfo.rewardTokenAPrice +
    dualStakingInfo.rateB * Number(dualStakingInfo.rewardTokenBPrice);

  const dualPoolRateA = getRewardRate(
    dualStakingInfo.totalRewardRateA,
    dualStakingInfo.rewardTokenA,
  );
  const dualPoolRateB = getRewardRate(
    dualStakingInfo.totalRewardRateB,
    dualStakingInfo.rewardTokenB,
  );

  const mainRewardRate = isLPFarm
    ? lpStakingInfo.rewardRate
    : dualStakingInfo.rewardRateA;

  const stakeEnabled =
    !approving &&
    !attemptStaking &&
    Number(stakeAmount) > 0 &&
    Number(stakeAmount) <= getExactTokenAmount(userLiquidityUnstaked);

  const unstakeEnabled =
    !attemptUnstaking &&
    Number(unstakeAmount) > 0 &&
    Number(unstakeAmount) <= getExactTokenAmount(stakingInfo.stakedAmount);

  const claimEnabled =
    !attemptClaiming &&
    (isLPFarm
      ? lpStakingInfo.earnedAmount &&
        lpStakingInfo.earnedAmount.greaterThan('0')
      : dualStakingInfo.earnedAmountA &&
        dualStakingInfo.earnedAmountA.greaterThan('0'));

  return (
    <>
      <Box
        width='100%'
        p={2}
        display='flex'
        flexDirection='row'
        flexWrap='wrap'
        borderTop='1px solid #444444'
        alignItems='center'
        justifyContent={stakingInfo?.ended ? 'flex-end' : 'space-between'}
      >
        {stakingInfo && (
          <>
            {isMobile && (
              <>
                <Box
                  mt={2}
                  width={1}
                  display='flex'
                  justifyContent='space-between'
                >
                  <Typography variant='body2' color='textSecondary'>
                    {t('tvl')}
                  </Typography>
                  <Typography variant='body2'>{tvl}</Typography>
                </Box>
                <Box
                  mt={2}
                  width={1}
                  display='flex'
                  justifyContent='space-between'
                >
                  <Typography variant='body2' color='textSecondary'>
                    {t('rewards')}
                  </Typography>
                  <Box textAlign='right'>
                    <Typography variant='body2'>
                      ${(isLPFarm ? lpRewards : dualRewards).toLocaleString()} /
                      {t('day')}
                    </Typography>
                    {isLPFarm ? (
                      <Typography variant='body2'>{lpPoolRate}</Typography>
                    ) : (
                      <>
                        <Typography variant='body2'>{dualPoolRateA}</Typography>
                        <Typography variant='body2'>{dualPoolRateB}</Typography>
                      </>
                    )}
                  </Box>
                </Box>
                <Box
                  mt={2}
                  width={1}
                  display='flex'
                  justifyContent='space-between'
                >
                  <Box display='flex' alignItems='center'>
                    <Typography variant='body2' color='textSecondary'>
                      {t('apy')}
                    </Typography>
                    <Box ml={0.5} height={16}>
                      <img src={CircleInfoIcon} alt={'arrow up'} />
                    </Box>
                  </Box>
                  <Box color={palette.success.main}>
                    <Typography variant='body2'>{apyWithFee}%</Typography>
                  </Box>
                </Box>
              </>
            )}
            {!stakingInfo.ended && (
              <Box className={classes.buttonWrapper} mt={isMobile ? 2 : 0}>
                <Box display='flex' justifyContent='space-between'>
                  <Typography variant='body2'>{t('inwallet')}:</Typography>
                  <Box
                    display='flex'
                    flexDirection='column'
                    alignItems='flex-end'
                    justifyContent='flex-start'
                  >
                    <Typography variant='body2'>
                      {formatTokenAmount(userLiquidityUnstaked)} {t('lp')}{' '}
                      <span>({getUSDString(stakedAmounts?.unStakedUSD)})</span>
                    </Typography>
                    <Link
                      to={`/pools?currency0=${getTokenAddress(
                        token0,
                      )}&currency1=${getTokenAddress(token1)}`}
                      style={{ color: palette.primary.main }}
                    >
                      {t('get')} {currency0?.symbol} / {currency1?.symbol}{' '}
                      {t('lp')}
                    </Link>
                  </Box>
                </Box>
                <Box className={classes.inputVal} mb={2} mt={2} p={2}>
                  <NumericalInput
                    placeholder='0.00'
                    value={stakeAmount}
                    fontSize={16}
                    onUserInput={(value) => {
                      setStakeAmount(value);
                    }}
                  />
                  <Typography
                    variant='body2'
                    style={{
                      color:
                        userLiquidityUnstaked &&
                        userLiquidityUnstaked.greaterThan('0')
                          ? palette.primary.main
                          : palette.text.hint,
                    }}
                    onClick={() => {
                      if (
                        userLiquidityUnstaked &&
                        userLiquidityUnstaked.greaterThan('0')
                      ) {
                        setStakeAmount(userLiquidityUnstaked.toExact());
                      } else {
                        setStakeAmount('');
                      }
                    }}
                  >
                    {t('max')}
                  </Typography>
                </Box>
                <Box
                  className={
                    stakeEnabled ? classes.buttonClaim : classes.buttonToken
                  }
                  mt={2}
                  p={2}
                  onClick={async () => {
                    if (stakeEnabled) {
                      if (approval === ApprovalState.APPROVED) {
                        onStake();
                      } else {
                        onAttemptToApprove();
                      }
                    }
                  }}
                >
                  <Typography variant='body1'>
                    {attemptStaking
                      ? t('stakingLPTokens')
                      : approval === ApprovalState.APPROVED
                      ? t('stakeLPTokens')
                      : approving
                      ? t('approving')
                      : t('approve')}
                  </Typography>
                </Box>
              </Box>
            )}
            <Box className={classes.buttonWrapper} mx={isMobile ? 0 : 2} my={2}>
              <Box display='flex' justifyContent='space-between'>
                <Typography variant='body2'>{t('mydeposits')}:</Typography>
                <Typography variant='body2'>
                  {formatTokenAmount(stakingInfo.stakedAmount)} {t('lp')}{' '}
                  <span>({getUSDString(stakedAmounts?.myStakedUSD)})</span>
                </Typography>
              </Box>
              <Box className={classes.inputVal} mb={2} mt={4.5} p={2}>
                <NumericalInput
                  placeholder='0.00'
                  value={unstakeAmount}
                  fontSize={16}
                  onUserInput={(value) => {
                    setUnStakeAmount(value);
                  }}
                />
                <Typography
                  variant='body2'
                  style={{
                    color:
                      stakingInfo.stakedAmount &&
                      stakingInfo.stakedAmount.greaterThan('0')
                        ? palette.primary.main
                        : palette.text.hint,
                  }}
                  onClick={() => {
                    if (
                      stakingInfo.stakedAmount &&
                      stakingInfo.stakedAmount.greaterThan('0')
                    ) {
                      setUnStakeAmount(stakingInfo.stakedAmount.toExact());
                    } else {
                      setUnStakeAmount('');
                    }
                  }}
                >
                  {t('max')}
                </Typography>
              </Box>
              <Box
                className={
                  unstakeEnabled ? classes.buttonClaim : classes.buttonToken
                }
                mt={2}
                p={2}
                onClick={() => {
                  if (unstakeEnabled) {
                    onWithdraw();
                  }
                }}
              >
                <Typography variant='body1'>
                  {attemptUnstaking
                    ? t('unstakingLPTokens')
                    : t('unstakeLPTokens')}
                </Typography>
              </Box>
            </Box>
            <Box className={classes.buttonWrapper}>
              <Box
                display='flex'
                flexDirection='column'
                alignItems='center'
                justifyContent='space-between'
              >
                <Box mb={1}>
                  <Typography variant='body2'>
                    {t('unclaimedRewards')}:
                  </Typography>
                </Box>
                {isLPFarm ? (
                  <>
                    <Box mb={1}>
                      <CurrencyLogo currency={lpStakingInfo.rewardToken} />
                    </Box>
                    <Box mb={1} textAlign='center'>
                      <Typography variant='body1' color='textSecondary'>
                        {formatTokenAmount(lpStakingInfo.earnedAmount)}
                        <span>&nbsp;{lpStakingInfo.rewardToken.symbol}</span>
                      </Typography>
                      <Typography variant='body2'>{earnedUSDStr}</Typography>
                    </Box>
                  </>
                ) : (
                  <>
                    <Box mb={1} display='flex'>
                      <CurrencyLogo
                        currency={unwrappedToken(dualStakingInfo.rewardTokenA)}
                      />
                      <CurrencyLogo
                        currency={unwrappedToken(dualStakingInfo.rewardTokenB)}
                      />
                    </Box>
                    <Box mb={1} textAlign='center'>
                      <Typography variant='body1'>{earnedUSDStr}</Typography>
                      <Typography variant='body1' color='textSecondary'>
                        {formatTokenAmount(dualStakingInfo.earnedAmountA)}
                        <span>&nbsp;{dualStakingInfo.rewardTokenA.symbol}</span>
                      </Typography>
                      <Typography variant='body1' color='textSecondary'>
                        {formatTokenAmount(dualStakingInfo.earnedAmountB)}
                        <span>&nbsp;{dualStakingInfo.rewardTokenB.symbol}</span>
                      </Typography>
                    </Box>
                  </>
                )}
              </Box>
              <Box
                className={
                  claimEnabled ? classes.buttonClaim : classes.buttonToken
                }
                p={2}
                onClick={() => {
                  if (claimEnabled) {
                    onClaimReward();
                  }
                }}
              >
                <Typography variant='body1'>
                  {attemptClaiming ? t('claiming') : t('claim')}
                </Typography>
              </Box>
            </Box>
          </>
        )}
      </Box>
      {mainRewardRate?.greaterThan('0') && (
        <Box className={classes.dailyRateWrapper}>
          <Box
            display='flex'
            alignItems='center'
            justifyContent={isMobile ? 'space-between' : 'flex-start'}
            mr={isMobile ? 0 : 1.5}
            width={isMobile ? 1 : 'auto'}
            mb={isMobile ? 1 : 0}
            flexWrap='wrap'
          >
            <Box display='flex' mr={1}>
              <Typography variant='body2' color='textSecondary'>
                {t('yourRate', {
                  symbol: isLPFarm ? '' : dualStakingInfo.rewardTokenA.symbol,
                })}
                :
              </Typography>
            </Box>
            <Typography variant='body2' color='textPrimary'>
              {formatMulDivTokenAmount(
                mainRewardRate,
                GlobalConst.utils.ONEDAYSECONDS,
              )}{' '}
              {isLPFarm
                ? lpStakingInfo.rewardToken.symbol
                : dualStakingInfo.rewardTokenA.symbol}{' '}
              / {t('day')}
            </Typography>
          </Box>
          {!isLPFarm && (
            <Box
              display='flex'
              alignItems='center'
              justifyContent={isMobile ? 'space-between' : 'flex-start'}
              mr={isMobile ? 0 : 1.5}
              width={isMobile ? 1 : 'auto'}
              mb={isMobile ? 1 : 0}
              flexWrap='wrap'
            >
              <Box display='flex' mr={1}>
                <Typography variant='body2' color='textSecondary'>
                  {t('yourRate', {
                    symbol: dualStakingInfo.rewardTokenB.symbol,
                  })}
                  :
                </Typography>
              </Box>
              <Typography variant='body2' color='textPrimary'>
                {formatMulDivTokenAmount(
                  dualStakingInfo.rewardRateB,
                  GlobalConst.utils.ONEDAYSECONDS,
                )}{' '}
                {dualStakingInfo.rewardTokenB.symbol} / {t('day')}
              </Typography>
            </Box>
          )}
          <Box
            display='flex'
            justifyContent={isMobile ? 'space-between' : 'flex-start'}
            alignItems='center'
            width={isMobile ? 1 : 'auto'}
            flexWrap='wrap'
          >
            <Box display='flex' mr={1}>
              <Typography variant='body2' color='textSecondary'>
                {t('yourFees')}:
              </Typography>
            </Box>
            <Typography variant='body2' color='textPrimary'>
              ${formatNumber(stakingInfo.accountFee)} / {t('day')}
            </Typography>
          </Box>
        </Box>
      )}
    </>
  );
}
Example #6
Source File: FarmsList.tsx    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
FarmsList: React.FC<FarmsListProps> = ({ bulkPairs, farmIndex }) => {
  const { palette, breakpoints } = useTheme();
  const isMobile = useMediaQuery(breakpoints.down('xs'));

  const [pageIndex, setPageIndex] = useState(0);
  const [pageloading, setPageLoading] = useState(false); //this is used for not loading farms immediately when user is on farms page
  const [isEndedFarm, setIsEndedFarm] = useState(false);
  const [sortBy, setSortBy] = useState(0);
  const [sortDesc, setSortDesc] = useState(false);
  const [stakedOnly, setStakeOnly] = useState(false);
  const [farmSearch, setFarmSearch] = useState('');
  const [farmSearchInput, setFarmSearchInput] = useDebouncedChangeHandler(
    farmSearch,
    setFarmSearch,
  );

  const addedLPStakingInfos = useStakingInfo(
    null,
    pageloading ||
      farmIndex === GlobalConst.farmIndex.DUALFARM_INDEX ||
      isEndedFarm
      ? 0
      : undefined,
    pageloading ||
      farmIndex === GlobalConst.farmIndex.DUALFARM_INDEX ||
      isEndedFarm
      ? 0
      : undefined,
    { search: farmSearch, isStaked: stakedOnly },
  );
  const addedLPStakingOldInfos = useOldStakingInfo(
    null,
    pageloading ||
      farmIndex === GlobalConst.farmIndex.DUALFARM_INDEX ||
      !isEndedFarm
      ? 0
      : undefined,
    pageloading ||
      farmIndex === GlobalConst.farmIndex.DUALFARM_INDEX ||
      !isEndedFarm
      ? 0
      : undefined,
    { search: farmSearch, isStaked: stakedOnly },
  );
  const addedDualStakingInfos = useDualStakingInfo(
    null,
    pageloading || farmIndex === GlobalConst.farmIndex.LPFARM_INDEX
      ? 0
      : undefined,
    pageloading || farmIndex === GlobalConst.farmIndex.LPFARM_INDEX
      ? 0
      : undefined,
    { search: farmSearch, isStaked: stakedOnly },
  );

  const sortIndex = sortDesc ? 1 : -1;

  const sortByToken = useCallback(
    (a: CommonStakingInfo, b: CommonStakingInfo) => {
      const tokenStrA = a.tokens[0].symbol + '/' + a.tokens[1].symbol;
      const tokenStrB = b.tokens[0].symbol + '/' + b.tokens[1].symbol;
      return (tokenStrA > tokenStrB ? -1 : 1) * sortIndex;
    },
    [sortIndex],
  );

  const sortByTVL = useCallback(
    (a: CommonStakingInfo, b: CommonStakingInfo) => {
      return (Number(a.tvl ?? 0) > Number(b.tvl ?? 0) ? -1 : 1) * sortIndex;
    },
    [sortIndex],
  );

  const sortByRewardLP = useCallback(
    (a: StakingInfo, b: StakingInfo) => {
      return (
        (getExactTokenAmount(a.totalRewardRate) >
        getExactTokenAmount(b.totalRewardRate)
          ? -1
          : 1) * sortIndex
      );
    },
    [sortIndex],
  );

  const sortByRewardDual = useCallback(
    (a: DualStakingInfo, b: DualStakingInfo) => {
      const aRewards =
        a.rateA * a.rewardTokenAPrice + a.rateB * a.rewardTokenBPrice;
      const bRewards =
        b.rateA * b.rewardTokenAPrice + b.rateB * b.rewardTokenBPrice;
      return (aRewards > bRewards ? -1 : 1) * sortIndex;
    },
    [sortIndex],
  );

  const sortByAPY = useCallback(
    (a: CommonStakingInfo, b: CommonStakingInfo) => {
      let aYearFee = 0;
      let bYearFee = 0;
      if (bulkPairs) {
        const aDayVolume = bulkPairs[a.pair]?.oneDayVolumeUSD;
        const aReserveUSD = bulkPairs[a.pair]?.reserveUSD;
        const bDayVolume = bulkPairs[b.pair]?.oneDayVolumeUSD;
        const bReserveUSD = bulkPairs[b.pair]?.reserveUSD;
        if (aDayVolume && aReserveUSD) {
          aYearFee = getOneYearFee(aDayVolume, aReserveUSD);
        }
        if (bDayVolume && bReserveUSD) {
          bYearFee = getOneYearFee(bDayVolume, bReserveUSD);
        }
      }
      const aAPYwithFee = getAPYWithFee(
        a.perMonthReturnInRewards ?? 0,
        aYearFee,
      );
      const bAPYwithFee = getAPYWithFee(
        b.perMonthReturnInRewards ?? 0,
        bYearFee,
      );
      return (aAPYwithFee > bAPYwithFee ? -1 : 1) * sortIndex;
    },
    [sortIndex, bulkPairs],
  );

  const sortByEarnedLP = useCallback(
    (a: StakingInfo, b: StakingInfo) => {
      return (
        (getExactTokenAmount(a.earnedAmount) >
        getExactTokenAmount(b.earnedAmount)
          ? -1
          : 1) * sortIndex
      );
    },
    [sortIndex],
  );

  const sortByEarnedDual = useCallback(
    (a: DualStakingInfo, b: DualStakingInfo) => {
      const earnedA =
        getExactTokenAmount(a.earnedAmountA) * a.rewardTokenAPrice +
        getExactTokenAmount(a.earnedAmountB) * a.rewardTokenBPrice;
      const earnedB =
        getExactTokenAmount(b.earnedAmountA) * b.rewardTokenAPrice +
        getExactTokenAmount(b.earnedAmountB) * b.rewardTokenBPrice;
      return (earnedA > earnedB ? -1 : 1) * sortIndex;
    },
    [sortIndex],
  );

  const sortedLPStakingInfos = useMemo(() => {
    const lpStakingInfos = isEndedFarm
      ? addedLPStakingOldInfos
      : addedLPStakingInfos;
    return lpStakingInfos.sort((a, b) => {
      if (sortBy === POOL_COLUMN) {
        return sortByToken(a, b);
      } else if (sortBy === TVL_COLUMN) {
        return sortByTVL(a, b);
      } else if (sortBy === REWARDS_COLUMN) {
        return sortByRewardLP(a, b);
      } else if (sortBy === APY_COLUMN) {
        return sortByAPY(a, b);
      } else if (sortBy === EARNED_COLUMN) {
        return sortByEarnedLP(a, b);
      }
      return 1;
    });
  }, [
    sortBy,
    addedLPStakingOldInfos,
    addedLPStakingInfos,
    isEndedFarm,
    sortByToken,
    sortByTVL,
    sortByRewardLP,
    sortByAPY,
    sortByEarnedLP,
  ]);

  const sortedStakingDualInfos = useMemo(() => {
    const dualStakingInfos = addedDualStakingInfos.filter(
      (info) => info.ended === isEndedFarm,
    );
    return dualStakingInfos.sort((a, b) => {
      if (sortBy === POOL_COLUMN) {
        return sortByToken(a, b);
      } else if (sortBy === TVL_COLUMN) {
        return sortByTVL(a, b);
      } else if (sortBy === REWARDS_COLUMN) {
        return sortByRewardDual(a, b);
      } else if (sortBy === APY_COLUMN) {
        return sortByAPY(a, b);
      } else if (sortBy === EARNED_COLUMN) {
        return sortByEarnedDual(a, b);
      }
      return 1;
    });
  }, [
    addedDualStakingInfos,
    isEndedFarm,
    sortBy,
    sortByToken,
    sortByTVL,
    sortByRewardDual,
    sortByAPY,
    sortByEarnedDual,
  ]);

  const addedStakingInfos = useMemo(
    () =>
      farmIndex === GlobalConst.farmIndex.DUALFARM_INDEX
        ? sortedStakingDualInfos
        : sortedLPStakingInfos,
    [farmIndex, sortedStakingDualInfos, sortedLPStakingInfos],
  );

  const stakingRewardAddress = addedStakingInfos
    ? addedStakingInfos
        .map((stakingInfo) => stakingInfo.stakingRewardAddress.toLowerCase())
        .reduce((totStr, str) => totStr + str, '')
    : null;

  useEffect(() => {
    setPageIndex(0);
  }, [stakingRewardAddress, farmIndex]);

  const stakingInfos = useMemo(() => {
    return sortedLPStakingInfos
      ? sortedLPStakingInfos.slice(
          0,
          getPageItemsToLoad(pageIndex, LOADFARM_COUNT),
        )
      : null;
  }, [sortedLPStakingInfos, pageIndex]);

  const stakingDualInfos = useMemo(() => {
    return sortedStakingDualInfos
      ? sortedStakingDualInfos.slice(
          0,
          getPageItemsToLoad(pageIndex, LOADFARM_COUNT),
        )
      : null;
  }, [sortedStakingDualInfos, pageIndex]);

  const getPoolApy = (pairId: string) => {
    if (!pairId || !bulkPairs) {
      return 0;
    }

    const oneDayVolume = bulkPairs?.[pairId]?.oneDayVolumeUSD;
    const reserveUSD = bulkPairs?.[pairId]?.reserveUSD;
    const oneYearFeeAPY = getOneYearFee(oneDayVolume, reserveUSD);
    return oneYearFeeAPY;
  };

  const loadNext = () => {
    setPageIndex(pageIndex + 1);
  };

  const { loadMoreRef } = useInfiniteLoading(loadNext);

  const sortColumns = [
    { text: 'Pool', index: POOL_COLUMN, width: 0.3, justify: 'flex-start' },
    { text: 'TVL', index: TVL_COLUMN, width: 0.2, justify: 'center' },
    { text: 'Rewards', index: REWARDS_COLUMN, width: 0.25, justify: 'center' },
    { text: 'APY', index: APY_COLUMN, width: 0.15, justify: 'center' },
    { text: 'Earned', index: EARNED_COLUMN, width: 0.2, justify: 'flex-end' },
  ];

  const sortByDesktopItems = sortColumns.map((item) => {
    return {
      ...item,
      onClick: () => {
        if (sortBy === item.index) {
          setSortDesc(!sortDesc);
        } else {
          setSortBy(item.index);
          setSortDesc(false);
        }
      },
    };
  });

  const sortByMobileItems = sortColumns.map((item) => {
    return { text: item.text, onClick: () => setSortBy(item.index) };
  });

  const renderStakedOnly = () => (
    <Box display='flex' alignItems='center'>
      <Typography
        variant='body2'
        style={{ color: palette.text.disabled, marginRight: 8 }}
      >
        Staked Only
      </Typography>
      <ToggleSwitch
        toggled={stakedOnly}
        onToggle={() => setStakeOnly(!stakedOnly)}
      />
    </Box>
  );

  const farmStatusItems = [
    {
      text: 'Active',
      onClick: () => setIsEndedFarm(false),
      condition: !isEndedFarm,
    },
    {
      text: 'Ended',
      onClick: () => setIsEndedFarm(true),
      condition: isEndedFarm,
    },
  ];

  return (
    <>
      <Box
        display='flex'
        flexWrap='wrap'
        justifyContent='space-between'
        alignItems='center'
        mb={3.5}
      >
        <Box>
          <Typography variant='h5'>Earn dQuick</Typography>
          <Typography variant='body2'>
            Stake LP Tokens to earn{' '}
            {farmIndex === GlobalConst.farmIndex.LPFARM_INDEX
              ? 'dQUICK + Pool Fees'
              : 'dQUICK + WMATIC rewards'}
          </Typography>
        </Box>
        <Box display='flex' flexWrap='wrap'>
          <Box
            display='flex'
            justifyContent='space-between'
            width={returnFullWidthMobile(isMobile)}
          >
            <Box width={isMobile ? 'calc(100% - 150px)' : 1} mr={2} my={2}>
              <SearchInput
                placeholder={
                  isMobile ? 'Search' : 'Search name, symbol or paste address'
                }
                value={farmSearchInput}
                setValue={setFarmSearchInput}
              />
            </Box>
            {isMobile && renderStakedOnly()}
          </Box>
          <Box
            width={returnFullWidthMobile(isMobile)}
            display='flex'
            flexWrap='wrap'
            alignItems='center'
          >
            <Box mr={2}>
              <CustomSwitch width={160} height={40} items={farmStatusItems} />
            </Box>
            {isMobile ? (
              <>
                <Box height={40} flex={1}>
                  <CustomMenu title='Sort By' menuItems={sortByMobileItems} />
                </Box>
                <Box mt={2} width={1} display='flex' alignItems='center'>
                  <Typography
                    variant='body2'
                    style={{ color: palette.text.disabled, marginRight: 8 }}
                  >
                    Sort {sortDesc ? 'Desc' : 'Asc'}
                  </Typography>
                  <ToggleSwitch
                    toggled={sortDesc}
                    onToggle={() => setSortDesc(!sortDesc)}
                  />
                </Box>
              </>
            ) : (
              renderStakedOnly()
            )}
          </Box>
        </Box>
      </Box>
      <Divider />
      {!isMobile && (
        <Box mt={2.5} display='flex' paddingX={2}>
          {sortByDesktopItems.map((item) => (
            <Box
              key={item.index}
              display='flex'
              alignItems='center'
              width={item.width}
              style={{ cursor: 'pointer' }}
              justifyContent={item.justify}
              onClick={item.onClick}
              color={
                sortBy === item.index
                  ? palette.text.primary
                  : palette.text.secondary
              }
            >
              <Typography variant='body2'>{item.text}</Typography>
              <Box display='flex' ml={0.5}>
                {sortBy === item.index && sortDesc ? (
                  <ArrowDown size={20} />
                ) : (
                  <ArrowUp size={20} />
                )}
              </Box>
            </Box>
          ))}
        </Box>
      )}
      {(farmIndex === GlobalConst.farmIndex.LPFARM_INDEX && !stakingInfos) ||
        (farmIndex === GlobalConst.farmIndex.DUALFARM_INDEX &&
          !stakingDualInfos && (
            <>
              <Skeleton width='100%' height={100} />
              <Skeleton width='100%' height={100} />
              <Skeleton width='100%' height={100} />
              <Skeleton width='100%' height={100} />
              <Skeleton width='100%' height={100} />
            </>
          ))}
      {farmIndex === GlobalConst.farmIndex.LPFARM_INDEX &&
        stakingInfos &&
        stakingInfos.map((info: StakingInfo, index) => (
          <FarmCard
            key={index}
            stakingInfo={info}
            stakingAPY={getPoolApy(info?.pair)}
            isLPFarm={true}
          />
        ))}
      {farmIndex === GlobalConst.farmIndex.DUALFARM_INDEX &&
        stakingDualInfos &&
        stakingDualInfos.map((info: DualStakingInfo, index) => (
          <FarmCard
            key={index}
            stakingInfo={info}
            stakingAPY={getPoolApy(info?.pair)}
          />
        ))}
      <div ref={loadMoreRef} />
    </>
  );
}
Example #7
Source File: hooks.ts    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
// gets the staking info from the network for the active chain id
export function useStakingInfo(
  pairToFilterBy?: Pair | null,
  startIndex?: number,
  endIndex?: number,
  filter?: { search: string; isStaked: boolean },
): StakingInfo[] {
  const { chainId, account } = useActiveWeb3React();

  const info = useMemo(
    () =>
      chainId
        ? returnStakingInfo()
            [chainId]?.slice(startIndex, endIndex)
            ?.filter((stakingRewardInfo) =>
              pairToFilterBy === undefined || pairToFilterBy === null
                ? getSearchFiltered(
                    stakingRewardInfo,
                    filter ? filter.search : '',
                  )
                : pairToFilterBy.involvesToken(stakingRewardInfo.tokens[0]) &&
                  pairToFilterBy.involvesToken(stakingRewardInfo.tokens[1]),
            ) ?? []
        : [],
    [chainId, pairToFilterBy, startIndex, endIndex, filter],
  );

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

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

  // useEffect(() => {
  //   getBulkPairData(allPairAddress);
  // }, [allPairAddress]);

  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 baseTokens = info.map((item) => {
    const unwrappedCurrency = unwrappedToken(item.baseToken);
    const empty = unwrappedToken(returnTokenFromKey('EMPTY'));
    return unwrappedCurrency === empty ? item.tokens[0] : item.baseToken;
  });
  const rewardTokens = info.map((item) => item.rewardToken);

  const usdPrices = useUSDCPrices(baseTokens);
  const usdPricesRewardTokens = useUSDCPricesToken(rewardTokens);
  const totalSupplys = useTotalSupplys(
    info.map((item) => {
      const lp = item.lp;
      const dummyPair = new Pair(
        new TokenAmount(item.tokens[0], '0'),
        new TokenAmount(item.tokens[1], '0'),
      );
      return lp && lp !== ''
        ? new Token(137, lp, 18, 'SLP', 'Staked LP')
        : dummyPair.liquidityToken;
    }),
  );
  const stakingPairs = usePairs(info.map((item) => item.tokens));

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

    return rewardsAddresses.reduce<StakingInfo[]>(
      (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 stakingInfo = info[index];
        const rewardTokenPrice = usdPricesRewardTokens[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 tokens = stakingInfo.tokens;
          const dummyPair = new Pair(
            new TokenAmount(tokens[0], '0'),
            new TokenAmount(tokens[1], '0'),
          );

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

          const individualRewardRate = getHypotheticalRewardRate(
            stakedAmount,
            totalStakedAmount,
            totalRewardRate01,
          );

          const { oneYearFeeAPY, oneDayFee, accountFee } = getStakingFees(
            stakingInfo,
            balanceState,
            totalSupplyState,
          );

          let valueOfTotalStakedAmountInBaseToken: TokenAmount | undefined;

          const [, stakingTokenPair] = stakingPairs[index];
          const totalSupply = totalSupplys[index];
          const usdPrice = usdPrices[index];

          if (
            totalSupply &&
            stakingTokenPair &&
            baseTokens[index] &&
            totalStakedAmount
          ) {
            // take the total amount of LP tokens staked, multiply by ETH value of all LP tokens, divide by all LP tokens
            valueOfTotalStakedAmountInBaseToken = new TokenAmount(
              baseTokens[index],
              JSBI.divide(
                JSBI.multiply(
                  JSBI.multiply(
                    totalStakedAmount.raw,
                    stakingTokenPair.reserveOf(baseTokens[index]).raw,
                  ),
                  JSBI.BigInt(2), // this is b/c the value of LP shares are ~double the value of the WETH they entitle owner to
                ),
                totalSupply.raw,
              ),
            );
          }

          const valueOfTotalStakedAmountInUSDC =
            valueOfTotalStakedAmountInBaseToken &&
            usdPrice?.quote(valueOfTotalStakedAmountInBaseToken);

          const tvl = valueOfTotalStakedAmountInUSDC
            ? valueOfTotalStakedAmountInUSDC.toExact()
            : valueOfTotalStakedAmountInBaseToken?.toExact();

          const perMonthReturnInRewards =
            (Number(stakingInfo.rate) *
              rewardTokenPrice *
              (getDaysCurrentYear() / 12)) /
            Number(valueOfTotalStakedAmountInUSDC?.toExact());

          memo.push({
            stakingRewardAddress: rewardsAddress,
            tokens: stakingInfo.tokens,
            ended: stakingInfo.ended,
            name: stakingInfo.name,
            lp: stakingInfo.lp,
            rewardToken: stakingInfo.rewardToken,
            rewardTokenPrice,
            earnedAmount: initTokenAmountFromCallResult(uni, earnedAmountState),
            rewardRate: individualRewardRate,
            totalRewardRate: totalRewardRate,
            stakedAmount: stakedAmount,
            totalStakedAmount: totalStakedAmount,
            getHypotheticalRewardRate,
            baseToken: stakingInfo.baseToken,
            pair: stakingInfo.pair,
            rate: stakingInfo.rate,
            oneYearFeeAPY: oneYearFeeAPY,
            oneDayFee,
            accountFee,
            tvl,
            perMonthReturnInRewards,
            valueOfTotalStakedAmountInBaseToken,
            usdPrice,
            stakingTokenPair,
            totalSupply,
          });
        }
        return memo;
      },
      [],
    );
  }, [
    balances,
    chainId,
    earnedAmounts,
    info,
    rewardsAddresses,
    totalSupplies,
    uni,
    rewardRates,
    usdPricesRewardTokens,
    baseTokens,
    totalSupplys,
    usdPrices,
    stakingPairs,
  ]).filter((stakingInfo) =>
    filter && filter.isStaked
      ? stakingInfo.stakedAmount && stakingInfo.stakedAmount.greaterThan('0')
      : true,
  );
}
Example #8
Source File: hooks.ts    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
export function useOldStakingInfo(
  pairToFilterBy?: Pair | null,
  startIndex?: number,
  endIndex?: number,
  filter?: { search: string; isStaked: boolean },
): StakingInfo[] {
  const { chainId, account } = useActiveWeb3React();

  const info = useMemo(
    () =>
      chainId
        ? returnStakingInfo('old')
            [chainId]?.slice(startIndex, endIndex)
            ?.filter((stakingRewardInfo) =>
              pairToFilterBy === undefined || pairToFilterBy === null
                ? getSearchFiltered(
                    stakingRewardInfo,
                    filter ? filter.search : '',
                  )
                : pairToFilterBy.involvesToken(stakingRewardInfo.tokens[0]) &&
                  pairToFilterBy.involvesToken(stakingRewardInfo.tokens[1]),
            ) ?? []
        : [],
    [chainId, pairToFilterBy, startIndex, endIndex, filter],
  );

  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 stakingPairs = usePairs(info.map((item) => item.tokens));

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

    return rewardsAddresses.reduce<StakingInfo[]>(
      (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 stakingInfo = info[index];

        if (
          // these may be undefined if not logged in
          !balanceState?.loading &&
          !earnedAmountState?.loading &&
          // always need these
          totalSupplyState &&
          !totalSupplyState.loading
        ) {
          const stakedAmount = initTokenAmountFromCallResult(
            getFarmLPToken(stakingInfo),
            balanceState,
          );
          const totalStakedAmount = initTokenAmountFromCallResult(
            getFarmLPToken(stakingInfo),
            totalSupplyState,
          );
          const totalRewardRate = new TokenAmount(uni, JSBI.BigInt(0));

          const getHypotheticalRewardRate = (
            stakedAmount?: TokenAmount,
            totalStakedAmount?: TokenAmount,
            totalRewardRate?: TokenAmount,
          ): TokenAmount | undefined => {
            if (!stakedAmount || !totalStakedAmount || !totalRewardRate) return;
            return new TokenAmount(
              uni,
              JSBI.greaterThan(totalStakedAmount.raw, JSBI.BigInt(0))
                ? JSBI.divide(
                    JSBI.multiply(totalRewardRate.raw, stakedAmount.raw),
                    totalStakedAmount.raw,
                  )
                : JSBI.BigInt(0),
            );
          };

          const individualRewardRate = getHypotheticalRewardRate(
            stakedAmount,
            totalStakedAmount,
            totalRewardRate,
          );

          const [, stakingTokenPair] = stakingPairs[index];

          memo.push({
            stakingRewardAddress: rewardsAddress,
            tokens: stakingInfo.tokens,
            ended: stakingInfo.ended,
            name: stakingInfo.name,
            lp: stakingInfo.lp,
            rewardToken: stakingInfo.rewardToken,
            rewardTokenPrice: 0,
            earnedAmount: initTokenAmountFromCallResult(uni, earnedAmountState),
            rewardRate: individualRewardRate,
            totalRewardRate: totalRewardRate,
            stakedAmount: stakedAmount,
            totalStakedAmount: totalStakedAmount,
            baseToken: stakingInfo.baseToken,
            getHypotheticalRewardRate,
            pair: stakingInfo.pair,
            rate: stakingInfo.rate,
            oneYearFeeAPY: 0,
            oneDayFee: 0,
            accountFee: 0,
            stakingTokenPair,
          });
        }
        return memo;
      },
      [],
    );
  }, [
    balances,
    chainId,
    earnedAmounts,
    info,
    rewardsAddresses,
    totalSupplies,
    uni,
    stakingPairs,
  ]).filter((stakingInfo) =>
    filter && filter.isStaked
      ? stakingInfo.stakedAmount && stakingInfo.stakedAmount.greaterThan('0')
      : true,
  );
}
Example #9
Source File: index.ts    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
export function getStakedAmountStakingInfo(
  stakingInfo?: StakingInfo | DualStakingInfo,
  userLiquidityUnstaked?: TokenAmount,
) {
  if (!stakingInfo) return;
  const stakingTokenPair = stakingInfo.stakingTokenPair;
  const baseTokenCurrency = unwrappedToken(stakingInfo.baseToken);
  const empty = unwrappedToken(returnTokenFromKey('EMPTY'));
  const token0 = stakingInfo.tokens[0];
  const baseToken =
    baseTokenCurrency === empty ? token0 : stakingInfo.baseToken;
  if (
    !stakingInfo.totalSupply ||
    !stakingTokenPair ||
    !stakingInfo.totalStakedAmount ||
    !stakingInfo.stakedAmount
  )
    return;
  // take the total amount of LP tokens staked, multiply by ETH value of all LP tokens, divide by all LP tokens
  const valueOfTotalStakedAmountInBaseToken = new TokenAmount(
    baseToken,
    JSBI.divide(
      JSBI.multiply(
        JSBI.multiply(
          stakingInfo.totalStakedAmount.raw,
          stakingTokenPair.reserveOf(baseToken).raw,
        ),
        JSBI.BigInt(2), // this is b/c the value of LP shares are ~double the value of the WETH they entitle owner to
      ),
      stakingInfo.totalSupply.raw,
    ),
  );

  const valueOfMyStakedAmountInBaseToken = new TokenAmount(
    baseToken,
    JSBI.divide(
      JSBI.multiply(
        JSBI.multiply(
          stakingInfo.stakedAmount.raw,
          stakingTokenPair.reserveOf(baseToken).raw,
        ),
        JSBI.BigInt(2), // this is b/c the value of LP shares are ~double the value of the WETH they entitle owner to
      ),
      stakingInfo.totalSupply.raw,
    ),
  );

  // get the USD value of staked WETH
  const USDPrice = stakingInfo.usdPrice;
  const valueOfTotalStakedAmountInUSDC = USDPrice?.quote(
    valueOfTotalStakedAmountInBaseToken,
  );

  const valueOfMyStakedAmountInUSDC = USDPrice?.quote(
    valueOfMyStakedAmountInBaseToken,
  );

  const stakedAmounts = {
    totalStakedBase: valueOfTotalStakedAmountInBaseToken,
    totalStakedUSD: valueOfTotalStakedAmountInUSDC,
    myStakedBase: valueOfMyStakedAmountInBaseToken,
    myStakedUSD: valueOfMyStakedAmountInUSDC,
    unStakedBase: undefined,
    unStakedUSD: undefined,
  };

  if (!userLiquidityUnstaked) return stakedAmounts;

  const valueOfUnstakedAmountInBaseToken = new TokenAmount(
    baseToken,
    JSBI.divide(
      JSBI.multiply(
        JSBI.multiply(
          userLiquidityUnstaked.raw,
          stakingTokenPair.reserveOf(baseToken).raw,
        ),
        JSBI.BigInt(2),
      ),
      stakingInfo.totalSupply.raw,
    ),
  );

  const valueOfUnstakedAmountInUSDC = USDPrice?.quote(
    valueOfUnstakedAmountInBaseToken,
  );
  return {
    ...stakedAmounts,
    unStakedBase: valueOfUnstakedAmountInBaseToken,
    unStakedUSD: valueOfUnstakedAmountInUSDC,
  };
}