components#ToggleSwitch TypeScript Examples

The following examples show how to use components#ToggleSwitch. 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: SettingsModal.tsx    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
SettingsModal: React.FC<SettingsModalProps> = ({ open, onClose }) => {
  const classes = useStyles();
  const { palette } = useTheme();
  const [
    userSlippageTolerance,
    setUserslippageTolerance,
  ] = useUserSlippageTolerance();
  const [ttl, setTtl] = useUserTransactionTTL();
  const { onChangeRecipient } = useSwapActionHandlers();
  const [expertMode, toggleExpertMode] = useExpertModeManager();
  const [slippageInput, setSlippageInput] = useState('');
  const [deadlineInput, setDeadlineInput] = useState('');
  const [expertConfirm, setExpertConfirm] = useState(false);
  const [expertConfirmText, setExpertConfirmText] = useState('');

  const slippageInputIsValid =
    slippageInput === '' ||
    (userSlippageTolerance / 100).toFixed(2) ===
      Number.parseFloat(slippageInput).toFixed(2);
  const deadlineInputIsValid =
    deadlineInput === '' || (ttl / 60).toString() === deadlineInput;

  const slippageError = useMemo(() => {
    if (slippageInput !== '' && !slippageInputIsValid) {
      return SlippageError.InvalidInput;
    } else if (slippageInputIsValid && userSlippageTolerance < 50) {
      return SlippageError.RiskyLow;
    } else if (slippageInputIsValid && userSlippageTolerance > 500) {
      return SlippageError.RiskyHigh;
    } else {
      return undefined;
    }
  }, [slippageInput, userSlippageTolerance, slippageInputIsValid]);

  const slippageAlert =
    !!slippageInput &&
    (slippageError === SlippageError.RiskyLow ||
      slippageError === SlippageError.RiskyHigh);

  const deadlineError = useMemo(() => {
    if (deadlineInput !== '' && !deadlineInputIsValid) {
      return DeadlineError.InvalidInput;
    } else {
      return undefined;
    }
  }, [deadlineInput, deadlineInputIsValid]);

  const parseCustomSlippage = (value: string) => {
    setSlippageInput(value);

    try {
      const valueAsIntFromRoundedFloat = Number.parseInt(
        (Number.parseFloat(value) * 100).toString(),
      );
      if (
        !Number.isNaN(valueAsIntFromRoundedFloat) &&
        valueAsIntFromRoundedFloat < 5000
      ) {
        setUserslippageTolerance(valueAsIntFromRoundedFloat);
      }
    } catch {}
  };

  const parseCustomDeadline = (value: string) => {
    setDeadlineInput(value);

    try {
      const valueAsInt: number = Number.parseInt(value) * 60;
      if (!Number.isNaN(valueAsInt) && valueAsInt > 0) {
        setTtl(valueAsInt);
      }
    } catch {}
  };

  return (
    <CustomModal open={open} onClose={onClose}>
      <CustomModal open={expertConfirm} onClose={() => setExpertConfirm(false)}>
        <Box paddingX={3} paddingY={4}>
          <Box
            mb={3}
            display='flex'
            justifyContent='space-between'
            alignItems='center'
          >
            <Typography variant='h5'>Are you sure?</Typography>
            <CloseIcon
              style={{ cursor: 'pointer' }}
              onClick={() => setExpertConfirm(false)}
            />
          </Box>
          <Divider />
          <Box mt={2.5} mb={1.5}>
            <Typography variant='body1'>
              Expert mode turns off the confirm transaction prompt and allows
              high slippage trades that often result in bad rates and lost
              funds.
            </Typography>
            <Typography
              variant='body1'
              style={{ fontWeight: 'bold', marginTop: 24 }}
            >
              ONLY USE THIS MODE IF YOU KNOW WHAT YOU ARE DOING.
            </Typography>
            <Typography
              variant='body1'
              style={{ fontWeight: 'bold', marginTop: 24 }}
            >
              Please type the word &quot;confirm&quot; to enable expert mode.
            </Typography>
          </Box>
          <Box
            height={40}
            borderRadius={10}
            mb={2.5}
            px={2}
            display='flex'
            alignItems='center'
            bgcolor={palette.background.default}
            border={`1px solid ${palette.secondary.light}`}
          >
            <input
              style={{ textAlign: 'left' }}
              className={classes.settingsInput}
              value={expertConfirmText}
              onChange={(e: any) => setExpertConfirmText(e.target.value)}
            />
          </Box>
          <Box
            style={{
              cursor: 'pointer',
              opacity: expertConfirmText === 'confirm' ? 1 : 0.6,
            }}
            bgcolor='rgb(255, 104, 113)'
            height={42}
            borderRadius={10}
            display='flex'
            alignItems='center'
            justifyContent='center'
            onClick={() => {
              if (expertConfirmText === 'confirm') {
                toggleExpertMode();
                setExpertConfirm(false);
              }
            }}
          >
            <Typography variant='h6'>Turn on Expert Mode</Typography>
          </Box>
        </Box>
      </CustomModal>
      <Box paddingX={3} paddingY={4}>
        <Box
          mb={3}
          display='flex'
          justifyContent='space-between'
          alignItems='center'
        >
          <Typography variant='h5'>Settings</Typography>
          <CloseIcon onClick={onClose} />
        </Box>
        <Divider />
        <Box my={2.5} display='flex' alignItems='center'>
          <Typography variant='body1' style={{ marginRight: 6 }}>
            Slippage Tolerance
          </Typography>
          <QuestionHelper
            size={20}
            text='Your transaction will revert if the price changes unfavorably by more than this percentage.'
          />
        </Box>
        <Box mb={2.5}>
          <Box display='flex' alignItems='center'>
            <Box
              className={cx(
                classes.slippageButton,
                userSlippageTolerance === 10 && classes.activeSlippageButton,
              )}
              onClick={() => {
                setSlippageInput('');
                setUserslippageTolerance(10);
              }}
            >
              <Typography variant='body2'>0.1%</Typography>
            </Box>
            <Box
              className={cx(
                classes.slippageButton,
                userSlippageTolerance === 50 && classes.activeSlippageButton,
              )}
              onClick={() => {
                setSlippageInput('');
                setUserslippageTolerance(50);
              }}
            >
              <Typography variant='body2'>0.5%</Typography>
            </Box>
            <Box
              className={cx(
                classes.slippageButton,
                userSlippageTolerance === 100 && classes.activeSlippageButton,
              )}
              onClick={() => {
                setSlippageInput('');
                setUserslippageTolerance(100);
              }}
            >
              <Typography variant='body2'>1%</Typography>
            </Box>
            <Box
              flex={1}
              height={40}
              borderRadius={10}
              px={2}
              display='flex'
              alignItems='center'
              bgcolor={palette.background.default}
              border={`1px solid
                ${
                  slippageAlert ? palette.primary.main : palette.secondary.light
                }
              `}
            >
              {slippageAlert && <AlertTriangle color='#ffa000' size={16} />}
              <NumericalInput
                placeholder={(userSlippageTolerance / 100).toFixed(2)}
                value={slippageInput}
                fontSize={14}
                fontWeight={500}
                align='right'
                color='rgba(212, 229, 255, 0.8)'
                onBlur={() => {
                  parseCustomSlippage((userSlippageTolerance / 100).toFixed(2));
                }}
                onUserInput={(value) => parseCustomSlippage(value)}
              />
              <Typography variant='body2'>%</Typography>
            </Box>
          </Box>
          {slippageError && (
            <Typography
              variant='body2'
              style={{ color: '#ffa000', marginTop: 12 }}
            >
              {slippageError === SlippageError.InvalidInput
                ? 'Enter a valid slippage percentage'
                : slippageError === SlippageError.RiskyLow
                ? 'Your transaction may fail'
                : 'Your transaction may be frontrun'}
            </Typography>
          )}
        </Box>
        <Divider />
        <Box my={2.5} display='flex' alignItems='center'>
          <Typography variant='body1' style={{ marginRight: 6 }}>
            Transaction Deadline
          </Typography>
          <QuestionHelper
            size={20}
            text='Your transaction will revert if it is pending for more than this long.'
          />
        </Box>
        <Box mb={2.5} display='flex' alignItems='center'>
          <Box
            height={40}
            borderRadius={10}
            px={2}
            display='flex'
            alignItems='center'
            bgcolor={palette.background.default}
            border={`1px solid ${palette.secondary.light}`}
            maxWidth={168}
          >
            <NumericalInput
              placeholder={(ttl / 60).toString()}
              value={deadlineInput}
              fontSize={14}
              fontWeight={500}
              color='rgba(212, 229, 255, 0.8)'
              onBlur={() => {
                parseCustomDeadline((ttl / 60).toString());
              }}
              onUserInput={(value) => parseCustomDeadline(value)}
            />
          </Box>
          <Typography variant='body2' style={{ marginLeft: 8 }}>
            minutes
          </Typography>
        </Box>
        {deadlineError && (
          <Typography
            variant='body2'
            style={{ color: '#ffa000', marginTop: 12 }}
          >
            Enter a valid deadline
          </Typography>
        )}
        <Divider />
        <Box
          my={2.5}
          display='flex'
          justifyContent='space-between'
          alignItems='center'
        >
          <Box display='flex' alignItems='center'>
            <Typography variant='body1' style={{ marginRight: 6 }}>
              Expert Mode
            </Typography>
            <QuestionHelper
              size={20}
              text='Bypasses confirmation modals and allows high slippage trades. Use at your own risk.'
            />
          </Box>
          <ToggleSwitch
            toggled={expertMode}
            onToggle={() => {
              if (expertMode) {
                toggleExpertMode();
                onChangeRecipient(null);
              } else {
                setExpertConfirm(true);
              }
            }}
          />
        </Box>
        <Divider />
        <Box
          mt={2.5}
          display='flex'
          justifyContent='space-between'
          alignItems='center'
        >
          <Typography variant='body1'>Language</Typography>
          <Box display='flex' alignItems='center'>
            <Typography variant='body1'>English (default)</Typography>
            <KeyboardArrowDown />
          </Box>
        </Box>
      </Box>
    </CustomModal>
  );
}
Example #2
Source File: DragonsSyrup.tsx    From interface-v2 with GNU General Public License v3.0 4 votes vote down vote up
DragonsSyrup: React.FC = () => {
  const { palette, breakpoints } = useTheme();
  const isMobile = useMediaQuery(breakpoints.down('xs'));
  const [isEndedSyrup, setIsEndedSyrup] = useState(false);
  const [pageIndex, setPageIndex] = useState(0);
  const [sortBy, setSortBy] = useState(0);
  const [sortDesc, setSortDesc] = useState(false);

  const [stakedOnly, setStakeOnly] = useState(false);
  const [syrupSearch, setSyrupSearch] = useState('');
  const [syrupSearchInput, setSyrupSearchInput] = useDebouncedChangeHandler(
    syrupSearch,
    setSyrupSearch,
  );

  const lairInfo = useLairInfo();
  const dQUICKAPY = useLairDQUICKAPY(lairInfo);

  const addedStakingSyrupInfos = useSyrupInfo(
    null,
    isEndedSyrup ? 0 : undefined,
    isEndedSyrup ? 0 : undefined,
    { search: syrupSearch, isStaked: stakedOnly },
  );
  const addedOldSyrupInfos = useOldSyrupInfo(
    null,
    isEndedSyrup ? undefined : 0,
    isEndedSyrup ? undefined : 0,
    { search: syrupSearch, isStaked: stakedOnly },
  );

  const addedSyrupInfos = isEndedSyrup
    ? addedOldSyrupInfos
    : addedStakingSyrupInfos;

  const sortIndex = sortDesc ? 1 : -1;

  const sortByToken = useCallback(
    (a: SyrupInfo, b: SyrupInfo) => {
      const syrupStrA = a.token.symbol ?? '';
      const syrupStrB = b.token.symbol ?? '';
      return (syrupStrA > syrupStrB ? -1 : 1) * sortIndex;
    },
    [sortIndex],
  );

  const sortByDeposit = useCallback(
    (a: SyrupInfo, b: SyrupInfo) => {
      const depositA =
        a.valueOfTotalStakedAmountInUSDC ??
        getExactTokenAmount(a.totalStakedAmount);
      const depositB =
        b.valueOfTotalStakedAmountInUSDC ??
        getExactTokenAmount(b.totalStakedAmount);
      return (depositA > depositB ? -1 : 1) * sortIndex;
    },
    [sortIndex],
  );

  const sortByAPR = useCallback(
    (a: SyrupInfo, b: SyrupInfo) => {
      return (getTokenAPRSyrup(a) > getTokenAPRSyrup(b) ? -1 : 1) * sortIndex;
    },
    [sortIndex],
  );
  const sortByEarned = useCallback(
    (a: SyrupInfo, b: SyrupInfo) => {
      const earnedUSDA =
        getExactTokenAmount(a.earnedAmount) * (a.rewardTokenPriceinUSD ?? 0);
      const earnedUSDB =
        getExactTokenAmount(b.earnedAmount) * (b.rewardTokenPriceinUSD ?? 0);
      return (earnedUSDA > earnedUSDB ? -1 : 1) * sortIndex;
    },
    [sortIndex],
  );

  const sortedSyrupInfos = useMemo(() => {
    return addedSyrupInfos.sort((a, b) => {
      if (sortBy === TOKEN_COLUMN) {
        return sortByToken(a, b);
      } else if (sortBy === DEPOSIT_COLUMN) {
        return sortByDeposit(a, b);
      } else if (sortBy === APR_COLUMN) {
        return sortByAPR(a, b);
      } else if (sortBy === EARNED_COLUMN) {
        return sortByEarned(a, b);
      }
      return 1;
    });
  }, [
    addedSyrupInfos,
    sortBy,
    sortByToken,
    sortByDeposit,
    sortByAPR,
    sortByEarned,
  ]);

  const syrupRewardAddress = useMemo(
    () =>
      sortedSyrupInfos
        .map((syrupInfo) => syrupInfo.stakingRewardAddress.toLowerCase())
        .reduce((totStr, str) => totStr + str, ''),
    [sortedSyrupInfos],
  );

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

  const syrupInfos = useMemo(() => {
    return sortedSyrupInfos
      ? sortedSyrupInfos.slice(
          0,
          getPageItemsToLoad(pageIndex, LOADSYRUP_COUNT),
        )
      : null;
  }, [sortedSyrupInfos, pageIndex]);

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

  const { loadMoreRef } = useInfiniteLoading(loadNext);

  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 syrupStatusItems = [
    {
      text: 'Active',
      onClick: () => setIsEndedSyrup(false),
      condition: !isEndedSyrup,
    },
    {
      text: 'Ended',
      onClick: () => setIsEndedSyrup(true),
      condition: isEndedSyrup,
    },
  ];

  const sortColumns = [
    {
      text: 'Earn',
      index: TOKEN_COLUMN,
      width: 0.3,
    },
    {
      text: 'Deposits',
      index: DEPOSIT_COLUMN,
      width: 0.3,
    },
    {
      text: 'APR',
      index: APR_COLUMN,
      width: 0.2,
    },
    {
      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) };
  });

  return (
    <>
      <Box display='flex' flexWrap='wrap' alignItems='center' mb={3.5}>
        <Box
          display='flex'
          justifyContent='space-between'
          width={returnFullWidthMobile(isMobile)}
          flex={isMobile ? 'unset' : 1}
        >
          <Box width={isMobile ? 'calc(100% - 150px)' : 1} mr={2} my={2}>
            <SearchInput
              placeholder={
                isMobile ? 'Search' : 'Search name, symbol or paste address'
              }
              value={syrupSearchInput}
              setValue={setSyrupSearchInput}
            />
          </Box>
          {isMobile && renderStakedOnly()}
        </Box>
        <Box
          width={returnFullWidthMobile(isMobile)}
          display='flex'
          flexWrap='wrap'
          alignItems='center'
        >
          <Box mr={2}>
            <CustomSwitch width={160} height={40} items={syrupStatusItems} />
          </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>
      <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>
      )}
      {syrupInfos ? (
        syrupInfos.map((syrup, ind) => (
          <SyrupCard key={ind} syrup={syrup} dQUICKAPY={dQUICKAPY} />
        ))
      ) : (
        <>
          <Skeleton width='100%' height={120} />
          <Skeleton width='100%' height={120} />
          <Skeleton width='100%' height={120} />
          <Skeleton width='100%' height={120} />
          <Skeleton width='100%' height={120} />
        </>
      )}
      <div ref={loadMoreRef} />
    </>
  );
}
Example #3
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} />
    </>
  );
}