react-router-dom#createSearchParams JavaScript Examples

The following examples show how to use react-router-dom#createSearchParams. 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: LpPair.js    From plenty-interface with GNU General Public License v3.0 5 votes vote down vote up
LpPair = (props) => {
  const isMobile = useMediaQuery('(max-width: 991px)');

  const closeFlashMessage = () => {
    props.setShowLpPair(false);
  };

  if (props.isLpPairAvailable && props.showLpPair) {
    return (
      <div
        className={clsx(
          'lppair-wrapper',
          isMobile
            ? 'bottomToTopFadeInAnimation-4-floater'
            : 'rightToLeftFadeInAnimation-4-floater',
        )}
      >
        <div className="d-flex lp-header">
          <div>Liquidity pairs</div>
          <div className="ml-auto">
            <span
              className=" material-icons-round "
              onClick={closeFlashMessage}
              style={{ cursor: 'pointer' }}
            >
              close
            </span>
          </div>
        </div>
        {props.pairs?.map((pair, index) => {
          return (
            <div className="d-flex " key={index}>
              <div>
                <img src={pair.tokenA.image} width="26.47" height="26.47" />
                <img src={pair.tokenB.image} width="26.47" height="26.47" />
              </div>
              <div className="floater-text">
                <span className="status-text">
                  {pair.tokenA.name === 'tez'
                    ? 'TEZ'
                    : pair.tokenA.name === 'ctez'
                    ? 'CTEZ'
                    : pair.tokenA.name}
                  /
                  {pair.tokenB.name === 'tez'
                    ? 'TEZ'
                    : pair.tokenB.name === 'ctez'
                    ? 'CTEZ'
                    : pair.tokenB.name}
                </span>
              </div>
              <div className="ml-auto ">
                <Link
                  style={{ textDecoration: 'none' }}
                  to={{
                    pathname: '/liquidity/add',
                    search: `?${createSearchParams({
                      tokenA: pair.tokenA.name,
                      tokenB: pair.tokenB.name,
                    })}`,
                  }}
                  className="w-100"
                >
                  <div className=" add-lp">
                    <span className={clsx('material-icons-round', 'add-icon')}>add</span>
                  </div>
                </Link>
              </div>
            </div>
          );
        })}
      </div>
    );
  } else {
    return null;
  }
}
Example #2
Source File: LiquidityPositions.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
LiquidityPositions = (props) => {
  const isMobile = useMediaQuery('(max-width: 991px)');
  const [positions, setPositions] = useState([]);
  const [positionDetails, setPositionDetails] = useState({});
  const [isOpen, setOpen] = useState(false);
  const [indexPosition, setIndex] = useState(-1);
  const [isEmpty, setEmpty] = useState(false);

  useEffect(async () => {
    const res = await getLiquidityPositionsForUser(props.walletAddress);

    if (res.success && res.data.length > 0) {
      setEmpty(false);
      setPositions(res.data);
    } else {
      setEmpty(true);
    }
  }, [props]);

  const openManage = async (value, index, flag, isStable) => {
    if (index !== indexPosition) {
      setOpen(true);
    } else {
      setOpen(flag);
    }
    setIndex(index);
    let ress = {};
    if (isStable) {
      if (
        CONFIG.AMM[CONFIG.NETWORK][value.tokenA.name].DEX_PAIRS[value.tokenB.name]?.type === 'xtz'
      ) {
        ress = await getLiquidityPositionDetailsStable(
          value.tokenA.name,
          value.tokenB.name,
          props.walletAddress,
        );
      } else if (
        CONFIG.AMM[CONFIG.NETWORK][value.tokenA.name].DEX_PAIRS[value.tokenB.name]?.type ===
        'veStableAMM'
      ) {
        ress = await getLiquidityPositionDetails(
          value.tokenA.name,
          value.tokenB.name,
          props.walletAddress,
        );
      }
    } else {
      ress = await getLiquidityPositionDetails(
        value.tokenA.name,
        value.tokenB.name,
        props.walletAddress,
      );
    }

    setPositionDetails(ress.data);
  };

  return (
    <>
      {isEmpty ? (
        <div className="no-positions">No positions found</div>
      ) : positions.length > 0 ? (
        positions?.map((position, index) => {
          return (
            <>
              <div
                className={clsx(
                  'position d-flex justify-content-between align-items-center',
                  isOpen && indexPosition === index && 'openLqDetails',
                )}
                key={index}
                onClick={() => openManage(position, index, !isOpen, position.isStable)}
                style={{ cursor: 'pointer' }}
              >
                <div className="token-label">
                  <img className="token-img" src={position.tokenA.image} />
                  <img className="ml-1 mr-sm-3 mr-2 token-img" src={position.tokenB.image} />
                  {position.tokenA.name === 'tez'
                    ? 'TEZ'
                    : position.tokenA.name === 'ctez'
                    ? 'CTEZ'
                    : position.tokenA.name}{' '}
                  /{' '}
                  {position.tokenB.name === 'tez'
                    ? 'TEZ'
                    : position.tokenB.name === 'ctez'
                    ? 'CTEZ'
                    : position.tokenB.name}
                </div>
                <div className="d-flex">
                  <div className="lp-fee">
                    <span className="lp-fee-value mr-1">{position.isStable ? '0.10' : '0.25'}</span>
                    % LP fee
                    {position.isStable && (
                      <>
                        <span className="divider-lq mx-2"></span>
                        <img src={props.theme === 'light' ? StableSwap : StableSwapDark} />
                      </>
                    )}
                  </div>
                  <div className="manage-label" style={{ cursor: 'pointer' }}>
                    {!isMobile && 'Manage'}
                    <span
                      className={clsx(
                        'material-icons-round',
                        'manage-arrow',
                        indexPosition === index && isOpen ? 'dropdown-open' : 'dropdown-close',
                      )}
                    >
                      expand_more
                    </span>
                  </div>
                </div>
              </div>
              {isOpen && indexPosition === index && (
                <div className={clsx('position-details ', isOpen && 'openLqDetails-manage', '')}>
                  <div className="scale-in-animation">
                    <div className=" d-sm-flex justify-content-between">
                      <div>
                        <div className="pooled">
                          POOLED{' '}
                          {position.tokenA.name === 'tez'
                            ? 'TEZ'
                            : position.tokenA.name === 'ctez'
                            ? 'CTEZ'
                            : position.tokenA.name}
                          :{' '}
                          <OverlayTrigger
                            placement="top"
                            overlay={
                              <Tooltip id="button-tooltip" {...props}>
                                {positionDetails
                                  ? fromExponential(positionDetails.tokenAPoolBalance)
                                  : '0.00'}
                              </Tooltip>
                            }
                          >
                            <span className="value">
                              {positionDetails.tokenAPoolBalance ? (
                                positionDetails.tokenAPoolBalance?.toFixed(4)
                              ) : (
                                <span className="shimmer">99999</span>
                              )}{' '}
                              {position.tokenA.name === 'tez'
                                ? 'TEZ'
                                : position.tokenA.name === 'ctez'
                                ? 'CTEZ'
                                : position.tokenA.name}
                            </span>
                          </OverlayTrigger>
                        </div>
                        <div className="pooled mt-1">
                          POOLED{' '}
                          {position.tokenB.name === 'tez'
                            ? 'TEZ'
                            : position.tokenB.name === 'ctez'
                            ? 'CTEZ'
                            : position.tokenB.name}
                          :{' '}
                          <OverlayTrigger
                            placement="top"
                            overlay={
                              <Tooltip id="button-tooltip" {...props}>
                                {positionDetails
                                  ? fromExponential(positionDetails.tokenBPoolBalance)
                                  : '0.00'}
                              </Tooltip>
                            }
                          >
                            <span className="value">
                              {positionDetails.tokenBPoolBalance ? (
                                positionDetails.tokenBPoolBalance?.toFixed(4)
                              ) : (
                                <span className="shimmer">99999</span>
                              )}{' '}
                              {position.tokenB.name === 'tez'
                                ? 'TEZ'
                                : position.tokenB.name === 'ctez'
                                ? 'CTEZ'
                                : position.tokenB.name}
                            </span>
                          </OverlayTrigger>
                        </div>
                      </div>
                      <div className="d-flex">
                        <div className="lq-details-right">
                          <div className="label">Pool share</div>
                          <OverlayTrigger
                            placement="top"
                            overlay={
                              <Tooltip id="button-tooltip" {...props}>
                                {positionDetails
                                  ? fromExponential(positionDetails.lpTokenShare)
                                  : '0.00'}
                              </Tooltip>
                            }
                          >
                            <div className="value">
                              {positionDetails.lpTokenShare ? (
                                positionDetails.lpTokenShare?.toFixed(4)
                              ) : (
                                <span className="shimmer">99999</span>
                              )}{' '}
                              %
                            </div>
                          </OverlayTrigger>
                        </div>
                        <div className="ml-2 lq-details-right">
                          <div className="label">Pool tokens</div>
                          <OverlayTrigger
                            placement="top"
                            overlay={
                              <Tooltip id="button-tooltip" {...props}>
                                {positionDetails
                                  ? fromExponential(positionDetails.lpBalance)
                                  : '0.00'}
                              </Tooltip>
                            }
                          >
                            <div className="value">
                              {positionDetails.lpBalance ? (
                                positionDetails.lpBalance?.toFixed(4)
                              ) : (
                                <span className="shimmer">99999</span>
                              )}
                            </div>
                          </OverlayTrigger>
                        </div>
                      </div>
                    </div>
                    <div className="divider-lq-manage"></div>
                    <div className="d-flex justify-content-between ">
                      <Link
                        style={{ textDecoration: 'none' }}
                        to={{
                          pathname: '/liquidity/remove',
                          search: `?${createSearchParams({
                            tokenA: position.isStable ? position.tokenB.name : position.tokenA.name,
                            tokenB: position.isStable ? position.tokenA.name : position.tokenB.name,
                          })}`,
                        }}
                        className="w-100"
                      >
                        <Button color={'primaryOutline'} className={'mr-3 w-100  '}>
                          Remove
                        </Button>
                      </Link>
                      <Link
                        style={{ textDecoration: 'none' }}
                        to={{
                          pathname: '/liquidity/add',
                          search: `?${createSearchParams({
                            tokenA: position.isStable ? position.tokenB.name : position.tokenA.name,
                            tokenB: position.isStable ? position.tokenA.name : position.tokenB.name,
                          })}`,
                        }}
                        className="w-100"
                      >
                        <Button color={'primary'} className={' w-100 ml-3 '}>
                          Add
                        </Button>
                      </Link>
                    </div>
                  </div>
                </div>
              )}
            </>
          );
        })
      ) : (
        <div className="loading-positions">
          <div className="header-lq d-flex">
            <div className="shimmer-circle">999</div>
            <div className="ml-3 shimmer-circle">999</div>
            <div className="ml-3 shimmer">99999999999999</div>
            {!isMobile && (
              <>
                <div className="ml-3 shimmer">99999999</div>
                <div className="ml-4 shimmer">999</div>
              </>
            )}
          </div>
          <div className="content flex justify-content-center align-items-center">
            Loading Positions...
          </div>
        </div>
      )}
    </>
  );
}
Example #3
Source File: index.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
LiquidityNew = (props) => {
  const { activeTab, tokenIn, setTokenIn, tokenOut, setTokenOut, setActiveTab } =
    useLocationStateInLiquidity();

  const [searchQuery, setSearchQuery] = useState('');
  const [swapData, setSwapData] = useState({});
  const [tokenType, setTokenType] = useState('tokenIn');
  const [show, setShow] = useState(false);
  const [slippage, setSlippage] = useState(0.5);
  const [recepient, setRecepient] = useState('');
  const [tokenContractInstances, setTokenContractInstances] = useState({});
  const [showConfirmAddSupply, setShowConfirmAddSupply] = useState(false);
  const [showConfirmRemoveSupply, setShowConfirmRemoveSupply] = useState(false);
  const [showConfirmTransaction, setShowConfirmTransaction] = useState(false);
  const [loaderMessage, setLoaderMessage] = useState({});
  const [loaderInButton, setLoaderInButton] = useState(false);
  const [loading, setLoading] = useState(false);
  const [getTokenPrice, setGetTokenPrice] = useState({});
  const [userBalances, setUserBalances] = useState({});

  const location = useLocation();
  const navigate = useNavigate();
  const { pathname } = location;
  const splitLocation = pathname.split('/');
  const [searchParams] = useSearchParams();
  const [isLiquidityPosition, setLiquidityPosition] = useState(false);
  const [positionDetails, setPositionDetails] = useState({});
  const [isPositionAvailable, setPositionAvailable] = useState(false);

  const [balanceUpdate, setBalanceUpdate] = useState(false);

  useEffect(async () => {
    const isStable = isTokenPairStable(tokenIn.name, tokenOut.name);

    const ress = await getLpTokenBalanceForPair(tokenIn.name, tokenOut.name, props.walletAddress);

    setPositionAvailable(ress.isLiquidityAvailable);
    if (ress.isLiquidityAvailable) {
      let res;
      if (isStable) {
        if (CONFIG.AMM[CONFIG.NETWORK][tokenIn.name].DEX_PAIRS[tokenOut.name]?.type === 'xtz') {
          res = await getLiquidityPositionDetailsStable(
            tokenIn.name,
            tokenOut.name,
            props.walletAddress,
          );
        } else if (
          CONFIG.AMM[CONFIG.NETWORK][tokenIn.name].DEX_PAIRS[tokenOut.name]?.type === 'veStableAMM'
        ) {
          res = await getLiquidityPositionDetails(tokenIn.name, tokenOut.name, props.walletAddress);
        }
      } else {
        res = await getLiquidityPositionDetails(tokenIn.name, tokenOut.name, props.walletAddress);
      }

      setPositionDetails(res);
    }
  }, [tokenIn, tokenOut, props]);

  useEffect(() => {
    setLoaderInButton(true);

    getTokenPrices().then((tokenPrice) => {
      setGetTokenPrice(tokenPrice);
    });
  }, []);

  const activeKey = useMemo(() => {
    if (location.pathname === '/liquidity/remove') {
      return 'remove';
    }

    return 'add';
  }, [location.pathname]);
  useEffect(() => {
    if (!location.pathname.includes('liquidityPositions')) {
      setLiquidityPosition(false);
    }
  }, [searchParams]);

  const handleClose = () => {
    setShow(false);

    setShowConfirmAddSupply(false);
    setShowConfirmRemoveSupply(false);
    setShowConfirmTransaction(false);
    setSearchQuery('');
  };

  useEffect(() => {
    const updateBalance = async () => {
      if (props.walletAddress) {
        setTokenContractInstances({});

        const tzBTCName = 'tzBTC';
        const balancePromises = [];

        tokenIn.name === tzBTCName
          ? balancePromises.push(fetchtzBTCBalance(props.walletAddress))
          : balancePromises.push(
              config.AMM[config.NETWORK][tokenIn.name]?.DEX_PAIRS[tokenOut.name]?.type === 'xtz'
                ? getUserBalanceByRpcStable(tokenIn.name, props.walletAddress)
                : getUserBalanceByRpc(tokenIn.name, props.walletAddress),
            );

        tokenOut.name === tzBTCName
          ? balancePromises.push(fetchtzBTCBalance(props.walletAddress))
          : balancePromises.push(
              config.AMM[config.NETWORK][tokenIn.name]?.DEX_PAIRS[tokenOut.name]?.type === 'xtz'
                ? getUserBalanceByRpcStable(tokenOut.name, props.walletAddress)
                : getUserBalanceByRpc(tokenOut.name, props.walletAddress),
            );

        if (
          config.AMM[config.NETWORK][tokenIn.name]?.DEX_PAIRS[tokenOut.name]?.type === 'xtz'
            ? config.STABLESWAP[config.NETWORK][tokenIn.name].DEX_PAIRS[tokenOut.name]
            : config.AMM[config.NETWORK][tokenIn.name].DEX_PAIRS[tokenOut.name]
        ) {
          const lpToken = isTokenPairStable(tokenIn.name, tokenOut.name)
            ? config.STABLESWAP[config.NETWORK][tokenIn.name].DEX_PAIRS[tokenOut.name]
                .liquidityToken
            : config.AMM[config.NETWORK][tokenIn.name].DEX_PAIRS[tokenOut.name].liquidityToken;

          balancePromises.push(
            config.AMM[config.NETWORK][tokenIn.name]?.DEX_PAIRS[tokenOut.name]?.type === 'xtz'
              ? getUserBalanceByRpcStable(lpToken, props.walletAddress)
              : getUserBalanceByRpc(lpToken, props.walletAddress),
          );
        }
        const balanceResponse = await Promise.all(balancePromises);

        setUserBalances((prev) => ({
          ...prev,
          ...balanceResponse.reduce(
            (acc, cur) => ({
              ...acc,
              [cur.identifier]: cur.balance,
            }),
            {},
          ),
        }));
      }
    };
    updateBalance();
  }, [tokenIn, tokenOut, props, balanceUpdate]);

  const selectToken = (token) => {
    setLoaderInButton(true);

    setSwapData({});

    if (tokenType === 'tokenIn') {
      setTokenIn({
        name: token.name,
        image: token.image,
      });

      if (token.name === 'tez') {
        setTokenOut({
          name: 'ctez',
          image: ctez,
        });
      } else if (token.name === 'EURL') {
        setTokenOut({
          name: 'agEUR.e',
          image: ageure,
        });
      } else if (token.name === 'agEUR.e') {
        setTokenOut({
          name: 'EURL',
          image: eurl,
        });
      }
    } else {
      setTokenOut({
        name: token.name,
        image: token.image,
      });
    }
    handleClose();
  };

  useEffect(() => {
    if (activeTab === 'liquidity') {
      if (
        Object.prototype.hasOwnProperty.call(tokenIn, 'name') &&
        Object.prototype.hasOwnProperty.call(tokenOut, 'name')
      ) {
        const pairExists = isTokenPairStable(tokenIn.name, tokenOut.name)
          ? !!config.STABLESWAP[config.NETWORK][tokenIn.name].DEX_PAIRS[tokenOut.name]
          : !!config.AMM[config.NETWORK][tokenIn.name].DEX_PAIRS[tokenOut.name];

        if (pairExists) {
          if (config.AMM[config.NETWORK][tokenIn.name]?.DEX_PAIRS[tokenOut.name]?.type === 'xtz') {
            loadSwapDataStable(tokenIn.name, tokenOut.name).then((data) => {
              if (data.success) {
                setSwapData(data);

                setLoaderInButton(false);
              }
            });
          } else if (
            config.AMM[config.NETWORK][tokenIn.name]?.DEX_PAIRS[tokenOut.name]?.type ===
            'veStableAMM'
          ) {
            loadSwapDataGeneralStable(tokenIn.name, tokenOut.name).then((data) => {
              if (data.success) {
                setSwapData(data);

                setLoaderInButton(false);
              }
            });
          } else {
            loadSwapData(tokenIn.name, tokenOut.name).then((data) => {
              if (data.success) {
                setSwapData(data);

                setLoaderInButton(false);
              }
            });
          }
        }
      }
    }
  }, [tokenIn, tokenOut, activeTab, splitLocation[1]]);

  const handleTokenType = (type) => {
    setBalanceUpdate(false);
    setShow(true);
    setTokenType(type);
    setLoading(false);
  };

  const fetchUserWalletBalance = () => {
    setLoaderInButton(true);
  };

  const handleLoaderMessage = (type, message) => {
    setLoaderMessage({
      type: type,
      message: message,
    });
    setLoading(false);
  };

  const resetAllValues = () => {
    setRecepient('');
    setTokenType('tokenIn');
  };

  const changeLiquidityType = (tab) => {
    const tokenAFromParam = searchParams.get('tokenA');
    const tokenBFromParam = searchParams.get('tokenB');
    navigate({
      pathname: `/liquidity/${tab}`,
      search: `?${createSearchParams({
        ...(tokenAFromParam ? { tokenA: tokenAFromParam } : {}),
        ...(tokenBFromParam ? { tokenB: tokenBFromParam } : {}),
      })}`,
    });
  };
  const redirectLiquidityPositions = (value) => {
    setLiquidityPosition(value);

    value ? setActiveTab('liquidityPositions') : setActiveTab('liquidity');
  };

  useEffect(() => {
    const tokenAFromParam = searchParams.get('tokenA');
    const tokenBFromParam = searchParams.get('tokenB');

    if (tokenAFromParam !== tokenBFromParam) {
      if (tokenAFromParam) {
        liquidityTokens.map((token) => {
          if (token.name === tokenAFromParam) {
            setTokenIn({
              name: tokenAFromParam,
              image: token.image,
            });
          }
        });
      }

      if (tokenBFromParam) {
        liquidityTokens.map((token) => {
          if (token.name === tokenBFromParam) {
            setTokenOut({
              name: tokenBFromParam,
              image: token.image,
            });
          }
        });
      }
    }
  }, [searchParams]);

  return (
    <Container fluid className="removing-padding">
      {props.walletAddress && (
        <p
          className="redirect-label-lp"
          style={{ cursor: 'pointer' }}
          onClick={() => redirectLiquidityPositions(!isLiquidityPosition)}
        >
          {isLiquidityPosition && (
            <span className={clsx('material-icons', 'arrow-forward', 'mt-1', 'ml-0')}>
              arrow_back_ios_icon
            </span>
          )}
          {isLiquidityPosition ? 'Back' : 'View Liquidity Positions'}
          {!isLiquidityPosition && (
            <span className={clsx('material-icons', 'arrow-forward', 'mt-1')}>
              arrow_forward_ios_icon
            </span>
          )}
        </p>
      )}
      {isLiquidityPosition && <div className="liq-label">Position overview</div>}

      {!isLiquidityPosition ? (
        <Col
          sm={8}
          md={6}
          className={clsx('liquidity-content-container', !props.walletAddress && 'liq-margin')}
        >
          <div className="">
            <Tabs
              activeKey={activeKey}
              className="liq-container-tab"
              onSelect={(e) => changeLiquidityType(e)}
              mountOnEnter={true}
              unmountOnExit={true}
            >
              <Tab eventKey="add" title="Add">
                <AddLiquidity
                  walletAddress={props.walletAddress}
                  connecthWallet={props.connecthWallet}
                  tokenIn={tokenIn}
                  tokenOut={tokenOut}
                  handleTokenType={handleTokenType}
                  swapData={swapData}
                  userBalances={userBalances}
                  tokenContractInstances={tokenContractInstances}
                  getTokenPrice={getTokenPrice}
                  setSlippage={setSlippage}
                  setRecepient={setRecepient}
                  recepient={recepient}
                  slippage={slippage}
                  loading={loading}
                  setLoading={setLoading}
                  handleLoaderMessage={handleLoaderMessage}
                  loaderMessage={loaderMessage}
                  handleClose={handleClose}
                  showConfirmAddSupply={showConfirmAddSupply}
                  setShowConfirmAddSupply={setShowConfirmAddSupply}
                  showConfirmRemoveSupply={showConfirmRemoveSupply}
                  setShowConfirmRemoveSupply={setShowConfirmRemoveSupply}
                  setLoaderMessage={setLoaderMessage}
                  resetAllValues={resetAllValues}
                  fetchUserWalletBalance={fetchUserWalletBalance}
                  setTokenIn={setTokenIn}
                  setTokenOut={setTokenOut}
                  tokens={liquidityTokens}
                  loaderInButton={loaderInButton}
                  setLoaderInButton={setLoaderInButton}
                  setShowConfirmTransaction={setShowConfirmTransaction}
                  showConfirmTransaction={showConfirmTransaction}
                  positionDetails={positionDetails}
                  setPositionAvailable={setPositionAvailable}
                  isPositionAvailable={isPositionAvailable}
                  setPositionDetails={setPositionDetails}
                  theme={props.theme}
                  setBalanceUpdate={setBalanceUpdate}
                  balanceUpdate={balanceUpdate}
                  {...props}
                />
              </Tab>
              {/* {isPositionAvailable ? ( */}
              <Tab eventKey="remove" title="Remove">
                <RemoveLiquidity
                  theme={props.theme}
                  walletAddress={props.walletAddress}
                  connecthWallet={props.connecthWallet}
                  tokenIn={tokenIn}
                  tokenOut={tokenOut}
                  handleTokenType={handleTokenType}
                  swapData={swapData}
                  userBalances={userBalances}
                  tokenContractInstances={tokenContractInstances}
                  getTokenPrice={getTokenPrice}
                  setSlippage={setSlippage}
                  setRecepient={setRecepient}
                  recepient={recepient}
                  slippage={slippage}
                  loading={loading}
                  setLoading={setLoading}
                  handleLoaderMessage={handleLoaderMessage}
                  loaderMessage={loaderMessage}
                  handleClose={handleClose}
                  showConfirmAddSupply={showConfirmAddSupply}
                  setShowConfirmAddSupply={setShowConfirmAddSupply}
                  showConfirmRemoveSupply={showConfirmRemoveSupply}
                  setShowConfirmRemoveSupply={setShowConfirmRemoveSupply}
                  setLoaderMessage={setLoaderMessage}
                  resetAllValues={resetAllValues}
                  fetchUserWalletBalance={fetchUserWalletBalance}
                  setTokenIn={setTokenIn}
                  setTokenOut={setTokenOut}
                  tokens={liquidityTokens}
                  loaderInButton={loaderInButton}
                  setLoaderInButton={setLoaderInButton}
                  isStableSwap={isTokenPairStable(tokenIn.name, tokenOut.name)}
                  setShowConfirmTransaction={setShowConfirmTransaction}
                  showConfirmTransaction={showConfirmTransaction}
                  positionDetails={positionDetails}
                  setPositionAvailable={setPositionAvailable}
                  isPositionAvailable={isPositionAvailable}
                  setPositionDetails={setPositionDetails}
                />
              </Tab>
              {/* ) : null} */}
            </Tabs>
            <div className="settings-liq">
              <SettingsLiq
                slippage={slippage}
                setSlippage={setSlippage}
                walletAddress={props.walletAddress}
                theme={props.theme}
              />
            </div>
          </div>
        </Col>
      ) : (
        <LiquidityPositions walletAddress={props.walletAddress} theme={props.theme} />
      )}
      <LiquidityModal
        show={show}
        activeTab={activeTab}
        onHide={handleClose}
        selectToken={selectToken}
        tokens={liquidityTokens}
        tokenIn={tokenIn}
        tokenOut={tokenOut}
        tokenType={tokenType}
        searchQuery={searchQuery}
        setSearchQuery={setSearchQuery}
      />
    </Container>
  );
}
Example #4
Source File: index.js    From plenty-interface with GNU General Public License v3.0 4 votes vote down vote up
LiquidityPage = () => {
  const {
    data = {
      summary: [],
      liquidity: [],
    },
    isLoading,
    error,
  } = useGetLiquidityQuery({ pollingInterval: 3_000 });

  const { imgPaths } = useLazyImages({ data: data.liquidity, page: 'liquidity' });

  const { isOnlyFavTokens, setIsOnlyFavTokens, favoriteTokens, editFavoriteTokenList } =
    useFavoriteToken('liquidity');

  const { valueFormat, stringSort, numberSort } = useTableNumberUtils();

  // ? Move to React Table filter later
  const finalData = useMemo(() => {
    if (isOnlyFavTokens) {
      return data.liquidity?.filter((datum) => favoriteTokens.includes(datum.pool_contract)) ?? [];
    }

    return data.liquidity;
  }, [favoriteTokens, isOnlyFavTokens, data]);

  const columns = useMemo(
    () => [
      {
        Header: (
          <TokensSymbolHeader
            className={styles.favoriteIcon}
            isOnlyFavTokens={isOnlyFavTokens}
            setIsOnlyFavTokens={setIsOnlyFavTokens}
          />
        ),
        id: 'favorite',
        accessor: 'pool_contract',
        disableSortBy: true,
        Cell: (row) => {
          return (
            <TokensSymbol
              tokenSymbol={row.value}
              className={styles.favoriteIcon}
              favoriteTokens={favoriteTokens}
              editFavoriteTokenList={editFavoriteTokenList}
            />
          );
        },
        width: 200,
      },
      {
        Header: <span className="ml-2">Name</span>,
        id: 'token',
        accessor: 'token1',
        sortType: stringSort,
        Cell: (row) => {
          const { token1, token2 } = row.row.original;
          return (
            <div className="d-flex pl-2 align-items-center">
              <TokenAvatar imgPath1={imgPaths[token1]} imgPath2={imgPaths[token2]} />
              <span className="ml-2 mr-4">
                {token1 === 'tez' ? 'TEZ' : token1 === 'ctez' ? 'CTEZ' : token1} /{' '}
                {token2 === 'tez' ? 'TEZ' : token2 === 'ctez' ? 'CTEZ' : token2}
              </span>
            </div>
          );
        },
        width: 120,
      },
      {
        Header: (
          <span className="flex align-center">
            Liquidity&nbsp;
            <Tooltip id={'liquidity-header'} message={'The value of tokens staked in the pool.'} />
          </span>
        ),
        id: 'liquidity',
        accessor: 'total_liquidity',
        sortType: numberSort,
        Cell: (row) => <span title={row.value}>{valueFormat(row.value)}</span>,
      },
      {
        Header: 'Daily Volume',
        accessor: '24h_volume',
        sortType: numberSort,
        Cell: (row) => <span>{valueFormat(row.value)}</span>,
      },
      {
        Header: 'Weekly Fees',
        accessor: '24h_fee',
        sortType: numberSort,
        Cell: (row) => <span>{valueFormat(row.value)}</span>,
      },
      {
        Header: (
          <span className="flex align-center">
            LP APR&nbsp;
            <Tooltip id={'lp-apr-header'} message={'Based on the annualized trading fees.'} />
          </span>
        ),
        accessor: 'lp_apr',
        sortType: numberSort,
        Cell: (row) => <span>{valueFormat(row.value ?? 0, { percentChange: true })}%</span>,
      },
      {
        Header: (
          <span className="flex align-center">
            Farm&nbsp;
            <Tooltip
              id={'farm-header'}
              message={'Active indicates a farm for the LP tokens of the liquidity pool.'}
            />
          </span>
        ),
        accessor: 'pool_contract',
        sortType: numberSort,
        Cell: (row) => (isActiveFarm(row.value) ? <span>Active</span> : null),
      },
      {
        disableSortBy: true,
        Header: '',
        id: 'trade',
        accessor: (x) => (
          <div className="d-flex">
            <Link
              style={{ textDecoration: 'none' }}
              to={{
                pathname: '/liquidity',
                search: `?${createSearchParams({
                  tokenA: x.token1,
                  tokenB: x.token2,
                })}`,
              }}
            >
              <Button color="primary" isIconBtn startIcon="add" iconBtnType="square" size="large" />
            </Link>

            <Link
              className="ml-2"
              style={{ textDecoration: 'none' }}
              to={{
                pathname: '/swap',
                search: `?${createSearchParams({
                  from: x.token1,
                  to: x.token2,
                })}`,
              }}
            >
              <Button
                color="default"
                isIconBtn
                startIcon="swap_vert"
                iconBtnType="square"
                size="large"
              />
            </Link>
          </div>
        ),
        width: 120,
      },
    ],
    [
      isOnlyFavTokens,
      setIsOnlyFavTokens,
      stringSort,
      numberSort,
      favoriteTokens,
      editFavoriteTokenList,
      imgPaths,
    ],
  );

  const [searchQuery, setSearchQuery] = useState('');

  return (
    <>
      <LiquiditySummary data={data.summary} />

      <Container fluid className={clsx(styles.tokens, styles.liquidityTable)}>
        <div className="w-100 d-flex justify-content-between px-5 align-items-center">
          <h5 className="font-weight-bolder">Liquidity Pools</h5>
          <InputGroup className={styles.searchBar}>
            <InputGroup.Prepend>
              <InputGroup.Text className={`${styles.searchIcon} border-right-0`}>
                <BsSearch />
              </InputGroup.Text>
            </InputGroup.Prepend>
            <FormControl
              placeholder="Search"
              className={`shadow-none border-left-0 ${styles.searchBox}`}
              value={searchQuery}
              onChange={(ev) => setSearchQuery(ev.target.value)}
            />
          </InputGroup>
        </div>

        {data.liquidity.length > 0 && (
          <div>
            <Table searchQuery={searchQuery} data={finalData} columns={columns} />
          </div>
        )}

        {data.liquidity.length === 0 && (isLoading || error) && (
          <div className="d-flex justify-content-between w-100" style={{ height: 800 }}>
            <div className="m-auto">
              {error ? <div>Something went wrong</div> : <PuffLoader color={'#813CE1'} size={56} />}
            </div>
          </div>
        )}
      </Container>

      <FavoriteIconGradient />
    </>
  );
}