utils#CHAINS TypeScript Examples

The following examples show how to use utils#CHAINS. 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: Wallet.tsx    From frontend-v1 with GNU Affero General Public License v3.0 5 votes vote down vote up
Wallet: FC = () => {
  const { account, isConnected, chainId } = useConnection();
  const [isOpen, setIsOpen] = useState(false);
  const modalRef = useRef(null);
  const { trackEvent } = useMatomo();
  useClickOutsideModal(modalRef, () => setIsOpen(false));

  // Note: this must be before early returns.
  useEffect(() => {
    if (!isConnected && isOpen) setIsOpen(false);
  }, [isConnected, isOpen]);

  const disconnectWallet = () => {
    setIsOpen(false);
    reset();
  };

  // Add Matomo helpers for connect/disconnect
  const initWithMatomo = () => {
    // Matomo track wallet connect
    // TODO: Eventually add address to `name` field
    trackEvent({ category: "wallet", action: "connect", name: "null" });
    init();
  };

  const disconnectWithMatomo = () => {
    // Matomo track wallet disconnect
    // TODO: Eventually add address to `name` field
    trackEvent({ category: "wallet", action: "disconnect", name: "null" });
    disconnectWallet();
  };

  const { data: balance } = useETHBalance(
    { account: account ?? "", chainId: chainId ?? DEFAULT_FROM_CHAIN_ID },
    { skip: !isConnected }
  );

  if (account && !isConnected && !chainId) {
    return (
      <UnsupportedNetwork>
        Unsupported network. Please change networks.
      </UnsupportedNetwork>
    );
  }

  if (!isConnected) {
    return (
      <ConnectButton onClick={initWithMatomo}>Connect Wallet</ConnectButton>
    );
  }

  return (
    <div ref={modalRef}>
      <Wrapper onClick={() => setIsOpen(!isOpen)}>
        <Info>
          <div>
            {formatEther(balance ?? "0")}{" "}
            {CHAINS[chainId ?? 1].nativeCurrency.symbol}
          </div>
          <div>{CHAINS[chainId ?? 1].name}</div>
        </Info>
        <Account>{shortenAddress(account ?? "")}</Account>
      </Wrapper>
      {isOpen && (
        <WalletModal>
          <WalletModalHeader>Connected</WalletModalHeader>
          <WalletModalAccount>{account}</WalletModalAccount>
          <WalletModalChain>{CHAINS[chainId ?? 1].name}</WalletModalChain>
          <WalletModalDisconnect onClick={() => disconnectWithMatomo()}>
            Disconnect
          </WalletModalDisconnect>
        </WalletModal>
      )}
    </div>
  );
}
Example #2
Source File: Routes.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
Routes: FC<Props> = () => {
  const { showConfirmationScreen } = useDeposits();
  const { error, provider, chainId } = useConnection();
  const location = useLocation();
  const sendState = useAppSelector((state) => state.send);
  const { error: globalError, removeError } = useContext(ErrorContext);

  const wrongNetworkSend =
    provider &&
    chainId &&
    (error instanceof UnsupportedChainIdError ||
      chainId !== sendState.currentlySelectedFromChain.chainId);
  const wrongNetworkPool =
    provider &&
    (error instanceof UnsupportedChainIdError ||
      chainId !== DEFAULT_TO_CHAIN_ID);
  return (
    <>
      {showMigrationBanner && (
        <Banner>
          <div>
            Across v2 transition is coming!{" "}
            <a
              href="https://medium.com/across-protocol/lps-migrate-liquidity-from-v1-to-v2-screenshots-and-faqs-8616150b3396"
              target="_blank"
              rel="noreferrer"
            >
              Read here
            </a>{" "}
            to learn how to migrate your pool liquidity from Across v1.
          </div>
        </Banner>
      )}
      {globalError && (
        <SuperHeader>
          <div>{globalError}</div>
          <RemoveErrorSpan onClick={() => removeError()}>X</RemoveErrorSpan>
        </SuperHeader>
      )}
      {wrongNetworkSend && location.pathname === "/" && (
        <SuperHeader>
          <div>
            You are on an incorrect network. Please{" "}
            <button
              onClick={() =>
                switchChain(
                  provider,
                  sendState.currentlySelectedFromChain.chainId
                )
              }
            >
              switch to{" "}
              {CHAINS[sendState.currentlySelectedFromChain.chainId].name}
            </button>
          </div>
        </SuperHeader>
      )}

      {wrongNetworkPool && location.pathname === "/pool" && (
        <SuperHeader>
          <div>
            You are on an incorrect network. Please{" "}
            <button onClick={() => switchChain(provider, DEFAULT_TO_CHAIN_ID)}>
              switch to {CHAINS[DEFAULT_TO_CHAIN_ID].name}
            </button>
          </div>
        </SuperHeader>
      )}
      <Header />
      <Switch>
        {!process.env.REACT_APP_HIDE_POOL ? (
          <Route exact path="/pool" component={Pool} />
        ) : null}

        <Route exact path="/about" component={About} />
        <Route
          exact
          path="/"
          component={showConfirmationScreen ? Confirmation : Send}
        />
      </Switch>
    </>
  );
}
Example #3
Source File: AddressSelection.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
AddressSelection: React.FC = () => {
  const { isConnected } = useConnection();
  const { toChain, toAddress, fromChain, setToAddress } = useSend();
  const [address, setAddress] = useState("");
  const [open, setOpen] = useState(false);
  const dispatch = useAppDispatch();

  const sendState = useAppSelector((state) => state.send);

  const { trackEvent } = useMatomo();

  const {
    isOpen,
    selectedItem,
    getLabelProps,
    getToggleButtonProps,
    getItemProps,
    getMenuProps,
  } = useSelect({
    items: CHAINS_SELECTION,
    defaultSelectedItem: sendState.currentlySelectedToChain,
    selectedItem: sendState.currentlySelectedToChain,
    onSelectedItemChange: ({ selectedItem }) => {
      if (selectedItem) {
        // Matomo track toChain selection
        trackEvent({
          category: "send",
          action: "setToChain",
          name: selectedItem.chainId.toString(),
        });

        const nextState = { ...sendState, toChain: selectedItem.chainId };
        dispatch(actions.toChain(nextState));
        dispatch(actions.updateSelectedToChain(selectedItem));
        const nsToChain = { ...sendState };
        if (selectedItem.chainId === ChainId.MAINNET) {
          nsToChain.fromChain = ChainId.OPTIMISM;
          dispatch(actions.fromChain(nsToChain));
          dispatch(actions.updateSelectedFromChain(CHAINS_SELECTION[0]));
        }
      }
    },
  });

  useEffect(() => {
    if (toAddress) {
      setAddress(toAddress);
    }
  }, [toAddress]);

  const toggle = () => {
    // modal is closing, reset address to the current toAddress
    if (!isConnected) return;
    if (open) setAddress(toAddress || address);
    setOpen((oldOpen) => !oldOpen);
  };
  const clearInput = () => {
    setAddress("");
  };

  const handleChange = (evt: React.ChangeEvent<HTMLInputElement>) => {
    setAddress(evt.target.value);
  };
  const isValid = !address || isValidAddress(address);
  const handleSubmit = () => {
    if (isValid && address) {
      setToAddress({ toAddress: address });
      toggle();
    }
  };

  const isL1toL2 = fromChain === ChainId.MAINNET;

  return (
    <AnimatePresence>
      <LastSection>
        <Wrapper>
          <SectionTitle>To</SectionTitle>
          <InputGroup>
            <RoundBox as="label" {...getLabelProps()}>
              <ToggleButton type="button" {...getToggleButtonProps()}>
                <Logo src={selectedItem?.logoURI} alt={selectedItem?.name} />
                <div>
                  <ToggleChainName>
                    {selectedItem?.name === "Ether"
                      ? "Mainnet"
                      : selectedItem?.name}
                  </ToggleChainName>
                  {toAddress && <Address>{shortenAddress(toAddress)}</Address>}
                </div>
                <ToggleIcon />
              </ToggleButton>
            </RoundBox>
            <Menu isOpen={isOpen} {...getMenuProps()}>
              {isOpen &&
                sendState.currentlySelectedToChain.chainId !==
                  ChainId.MAINNET &&
                CHAINS_SELECTION.map((t, index) => {
                  return (
                    <Item
                      className={
                        t === sendState.currentlySelectedToChain ||
                        t.chainId === ChainId.MAINNET
                          ? "disabled"
                          : ""
                      }
                      {...getItemProps({ item: t, index })}
                      key={t.chainId}
                    >
                      <Logo src={t.logoURI} alt={t.name} />
                      <div>{t.name}</div>
                      <span className="layer-type">
                        {t.chainId !== ChainId.MAINNET ? "L2" : "L1"}
                      </span>
                    </Item>
                  );
                })}
              {isOpen &&
                sendState.currentlySelectedToChain.chainId ===
                  ChainId.MAINNET && (
                  <>
                    <ItemWarning
                      initial={{ y: -10 }}
                      animate={{ y: 0 }}
                      exit={{ y: -10 }}
                    >
                      <p>
                        Transfers between L2 chains is not possible at this time
                      </p>
                    </ItemWarning>
                    {CHAINS_SELECTION.map((t, index) => {
                      return (
                        <Item
                          className={"disabled"}
                          {...getItemProps({ item: t, index })}
                          key={t.chainId}
                          initial={{ y: -10 }}
                          animate={{ y: 0 }}
                          exit={{ y: -10 }}
                        >
                          <Logo src={t.logoURI} alt={t.name} />
                          <div>{t.name}</div>
                          <span className="layer-type">
                            {index !== CHAINS_SELECTION.length - 1
                              ? "L2"
                              : "L1"}
                          </span>
                        </Item>
                      );
                    })}
                  </>
                )}
            </Menu>
          </InputGroup>
          {!isL1toL2 && (
            <ChangeWrapper onClick={toggle}>
              <ChangeButton className={!isConnected ? "disabled" : ""}>
                Change account
              </ChangeButton>
            </ChangeWrapper>
          )}
        </Wrapper>
        <Dialog isOpen={open} onClose={toggle}>
          <h3>Send To</h3>
          <div>Address on {CHAINS[toChain].name}</div>
          <InputWrapper>
            <Input onChange={handleChange} value={address} />
            <ClearButton onClick={clearInput}>
              <XOctagon
                fill="var(--color-gray-300)"
                stroke="var(--color-white)"
              />
            </ClearButton>
            {!isValid && <InputError>Not a valid address</InputError>}
          </InputWrapper>
          <ButtonGroup>
            <CancelButton onClick={toggle}>Cancel</CancelButton>
            <SecondaryButton
              onClick={handleSubmit}
              disabled={!isValid || !address}
            >
              Save Changes
            </SecondaryButton>
          </ButtonGroup>
        </Dialog>
      </LastSection>
    </AnimatePresence>
  );
}
Example #4
Source File: ChainSelection.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
ChainSelection: React.FC = () => {
  const { init } = onboard;
  const { isConnected, provider, chainId, error } = useConnection();
  const sendState = useAppSelector((state) => state.send);
  const dispatch = useAppDispatch();

  const { trackEvent } = useMatomo();

  /*
    The following block will attempt to change the dropdown when the user connects the app.

    Otherwise, it just makes sure to map the dropdown value when the currentSelected block changes.

    This will also change the dropdown value in <AddressSelection /> because of the hook in there.
  */
  const previousChainId = usePrevious(chainId);
  useEffect(() => {
    if (chainId && previousChainId === undefined) {
      const findChain = CHAINS_SELECTION.find((x) => x.chainId === chainId);
      const notFindChain = CHAINS_SELECTION.filter(
        (x) => x.chainId !== chainId
      );

      if (findChain && notFindChain) {
        dispatch(actions.updateSelectedFromChain(findChain));
        dispatch(
          actions.updateSelectedToChain(notFindChain[notFindChain.length - 1])
        );
        dispatch(
          actions.fromChain({ ...sendState, fromChain: findChain.chainId })
        );
        dispatch(
          actions.toChain({
            ...sendState,
            toChain: notFindChain[notFindChain.length - 1].chainId,
          })
        );
      }
    }
  }, [
    chainId,
    previousChainId,
    sendState.currentlySelectedFromChain,
    dispatch,
    sendState,
  ]);

  const wrongNetworkSend =
    provider &&
    chainId &&
    (error instanceof UnsupportedChainIdError ||
      chainId !== sendState.currentlySelectedFromChain.chainId);

  const buttonText = wrongNetworkSend
    ? `Switch to ${CHAINS[sendState.currentlySelectedFromChain.chainId].name}`
    : !isConnected
    ? "Connect Wallet"
    : null;

  const handleClick = () => {
    if (!provider) {
      init();
    } else if (wrongNetworkSend) {
      switchChain(provider, sendState.currentlySelectedFromChain.chainId);
    }
  };

  const {
    isOpen,
    selectedItem,
    getLabelProps,
    getToggleButtonProps,
    getItemProps,
    getMenuProps,
  } = useSelect({
    items: CHAINS_SELECTION,
    defaultSelectedItem: sendState.currentlySelectedFromChain,
    selectedItem: sendState.currentlySelectedFromChain,
    onSelectedItemChange: ({ selectedItem }) => {
      if (selectedItem) {
        // Matomo track fromChain
        trackEvent({
          category: "send",
          action: "setFromChain",
          name: selectedItem.chainId.toString(),
        });

        const nextState = { ...sendState, fromChain: selectedItem.chainId };
        dispatch(actions.fromChain(nextState));
        dispatch(actions.updateSelectedFromChain(selectedItem));
        const nsToChain = { ...sendState, toChain: ChainId.MAINNET };
        if (selectedItem.chainId === ChainId.MAINNET) {
          nsToChain.toChain = ChainId.OPTIMISM;
          dispatch(actions.toChain(nsToChain));
          dispatch(actions.updateSelectedToChain(CHAINS_SELECTION[0]));
        }
        if (
          selectedItem.chainId !== ChainId.MAINNET &&
          sendState.currentlySelectedToChain.chainId !== ChainId.MAINNET
        ) {
          dispatch(
            actions.updateSelectedToChain(
              CHAINS_SELECTION[CHAINS_SELECTION.length - 1]
            )
          );
        }
      }
    },
  });

  return (
    <Section>
      <Wrapper>
        {disableSendForm && (
          <SendBlockedWarning>
            <div>
              Across V1 sending is disabled, please visit{" "}
              <a href="https://v2.across.to" target="_blank" rel="noreferrer">
                {" "}
                Across V2
              </a>{" "}
            </div>
          </SendBlockedWarning>
        )}
        <SectionTitle>From</SectionTitle>
        <InputGroup>
          <RoundBox as="label" {...getLabelProps()}>
            <ToggleButton type="button" {...getToggleButtonProps()}>
              <Logo src={selectedItem?.logoURI} alt={selectedItem?.name} />
              <ToggleChainName>{selectedItem?.name}</ToggleChainName>
              <ToggleIcon />
            </ToggleButton>
          </RoundBox>
          <Menu isOpen={isOpen} {...getMenuProps()}>
            {isOpen &&
              CHAINS_SELECTION.map((t, index) => {
                return (
                  <Item
                    className={
                      t === sendState.currentlySelectedFromChain
                        ? "disabled"
                        : ""
                    }
                    {...getItemProps({ item: t, index })}
                    initial={{ y: -10 }}
                    animate={{ y: 0 }}
                    exit={{ y: -10 }}
                    key={t.chainId}
                  >
                    <Logo src={t.logoURI} alt={t.name} />
                    <div>{t.name}</div>
                    <span className="layer-type">
                      {index !== CHAINS_SELECTION.length - 1 ? "L2" : "L1"}
                    </span>
                  </Item>
                );
              })}
          </Menu>
        </InputGroup>
        {(wrongNetworkSend || !isConnected) && (
          <ConnectButton onClick={handleClick}>{buttonText}</ConnectButton>
        )}
      </Wrapper>
    </Section>
  );
}
Example #5
Source File: AddLiquidityForm.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
AddLiquidityForm: FC<Props> = ({
  error,
  amount,
  onChange,
  bridgeAddress,
  decimals,
  symbol,
  tokenAddress,
  setShowSuccess,
  setDepositUrl,
  balance,
  setAmount,
  wrongNetwork,
  formError,
  onMaxClick,
}) => {
  const { addError } = useContext(ErrorContext);

  const { init } = onboard;
  const { isConnected, provider, signer, notify, account } = useConnection();
  const { approve, allowance: getAllowance } = useERC20(tokenAddress);

  const [allowance, setAllowance] = useState("0");
  const [userNeedsToApprove, setUserNeedsToApprove] = useState(false);
  const [txSubmitted, setTxSubmitted] = useState(false);
  const [updateEthBalance] = api.endpoints.ethBalance.useLazyQuery();

  const updateAllowance = useCallback(async () => {
    if (!account || !provider || symbol === "ETH") return;
    const allowance = await getAllowance({
      account,
      spender: bridgeAddress,
      provider,
    });
    setAllowance(allowance.toString());
  }, [setAllowance, getAllowance, provider, account, bridgeAddress, symbol]);

  // trigger update allowance, only if bridge/token changes. ignore eth.
  useEffect(() => {
    if (isConnected && symbol !== "ETH" && !wrongNetwork) updateAllowance();
  }, [isConnected, symbol, updateAllowance, wrongNetwork]);

  // check if user needs to approve based on amount entered in form or a change in allowance
  useEffect(() => {
    try {
      if (symbol === "ETH") {
        setUserNeedsToApprove(false);
      } else {
        const weiAmount = toWeiSafe(amount, decimals);
        const hasToApprove = weiAmount.gt(allowance);
        setUserNeedsToApprove(hasToApprove);
      }
    } catch (err) {
      // do nothing. this happens when users input is not a number and causes toWei to throw. if we dont
      // catch here, app will crash when user enters something like "0."
    }
  }, [amount, allowance, symbol, decimals]);

  const handleApprove = async () => {
    try {
      const tx = await approve({
        amount: INFINITE_APPROVAL_AMOUNT,
        spender: bridgeAddress,
        signer,
      });

      if (tx) {
        setTxSubmitted(true);
        const { emitter } = notify.hash(tx.hash);
        emitter.on("all", addEtherscan);

        emitter.on("txConfirmed", () => {
          notify.unsubscribe(tx.hash);
          if (account) {
            setTimeout(() => {
              // these need to be delayed, because our providers need time to catch up with notifyjs.
              // If we don't wait then these calls will fail to update correctly, leaving the user to have to refresh.
              setTxSubmitted(false);
              updateAllowance().catch((err) =>
                console.error("Error checking approval:", err)
              );
              updateEthBalance({ chainId: 1, account });
            }, 15000);
          }
        });

        emitter.on("txFailed", () => {
          notify.unsubscribe(tx.hash);
          setTxSubmitted(false);
        });
      }
    } catch (err: any) {
      addError(new Error(`Error in approve call: ${err.message}`));
      console.error(err);
    }
  };

  const approveOrPoolTransactionHandler = async () => {
    if (!provider) {
      return init();
    }
    if (isConnected && userNeedsToApprove) return handleApprove();
    if (isConnected && migrationPoolV2Warning) return false;
    if (isConnected && Number(amount) > 0 && signer) {
      const weiAmount = toWeiSafe(amount, decimals);

      try {
        let txId;
        if (symbol === "ETH") {
          txId = await poolClient.addEthLiquidity(
            signer,
            bridgeAddress,
            weiAmount
          );
        } else {
          txId = await poolClient.addTokenLiquidity(
            signer,
            bridgeAddress,
            weiAmount
          );
        }

        const transaction = poolClient.getTx(txId);

        if (transaction.hash) {
          setTxSubmitted(true);
          const { emitter } = notify.hash(transaction.hash);
          emitter.on("all", addEtherscan);
          emitter.on("txConfirmed", (tx) => {
            if (transaction.hash) notify.unsubscribe(transaction.hash);
            setShowSuccess("deposit");
            setTxSubmitted(false);
            const url = `https://etherscan.io/tx/${transaction.hash}`;
            setDepositUrl(url);
            if (account)
              setTimeout(
                () => updateEthBalance({ chainId: 1, account }),
                15000
              );
          });
          emitter.on("txFailed", () => {
            if (transaction.hash) notify.unsubscribe(transaction.hash);
            setTxSubmitted(false);
          });
        }

        return transaction;
      } catch (err: any) {
        addError(new Error(`Error in add liquidity call: ${err.message}`));

        console.error("err in AddEthLiquidity call", err);
      }
    }
  };

  function buttonMessage() {
    if (!isConnected) return "Connect wallet";
    if (userNeedsToApprove) return "Approve";
    return "Add Liquidity";
  }

  return (
    <>
      <FormHeader>Amount</FormHeader>

      <InputGroup>
        <RoundBox
          as="label"
          htmlFor="amount"
          style={{
            // @ts-expect-error TS does not likes custom CSS vars
            "--color": error
              ? "var(--color-error-light)"
              : "var(--color-white)",
            "--outline-color": error
              ? "var(--color-error)"
              : "var(--color-primary)",
          }}
        >
          <MaxButton onClick={onMaxClick} disabled={!isConnected}>
            max
          </MaxButton>
          <Input
            placeholder="0.00"
            id="amount"
            value={amount}
            onChange={(e) => onChange(e.target.value)}
            disabled={!isConnected}
          />
        </RoundBox>
      </InputGroup>
      {isConnected && (
        <Balance>
          <span>
            Balance: {ethers.utils.formatUnits(balance, decimals)} {symbol}
          </span>
        </Balance>
      )}
      {formError && <LiquidityErrorBox>{formError}</LiquidityErrorBox>}
      {wrongNetwork && provider ? (
        <FormButton onClick={() => switchChain(provider, DEFAULT_TO_CHAIN_ID)}>
          Switch to {CHAINS[DEFAULT_TO_CHAIN_ID].name}
        </FormButton>
      ) : (
        <FormButton
          disabled={
            (!provider ||
              !!formError ||
              Number(amount) <= 0 ||
              !!migrationPoolV2Warning) &&
            isConnected
          }
          onClick={() => {
            // Block adding liqudiity in app if REACT_APP_BLOCK_POOL_LIQUIDITY is true
            if (blockLiquidity) return false;
            return approveOrPoolTransactionHandler().catch((err) =>
              console.error("Error on click to approve or pool tx", err)
            );
          }}
        >
          {buttonMessage()}
          {txSubmitted ? <BouncingDotsLoader /> : null}
        </FormButton>
      )}
    </>
  );
}
Example #6
Source File: RemoveLiquidityForm.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
RemoveLiqudityForm: FC<Props> = ({
  removeAmount,
  setRemoveAmount,
  bridgeAddress,
  lpTokens,
  decimals,
  symbol,
  setShowSuccess,
  setDepositUrl,
  position,
  feesEarned,
  wrongNetwork,
  totalPosition,
}) => {
  const { init } = onboard;
  const { isConnected, provider, signer, notify, account } = useConnection();
  const [txSubmitted, setTxSubmitted] = useState(false);
  const [updateEthBalance] = api.endpoints.ethBalance.useLazyQuery();
  function buttonMessage() {
    if (!isConnected) return "Connect wallet";
    if (wrongNetwork) return "Switch to Ethereum Mainnet";
    return "Remove liquidity";
  }
  const [errorMessage, setErrorMessage] = useState("");
  useEffect(() => {
    setErrorMessage("");
  }, [removeAmount]);

  const handleButtonClick = async () => {
    if (!provider) {
      init();
    }
    if (isConnected && removeAmount > 0 && signer) {
      setErrorMessage("");
      const scaler = toBN("10").pow(decimals);

      const removeAmountToWei = toWeiSafe(
        (removeAmount / 100).toString(),
        decimals
      );

      const weiAmount = lpTokens.mul(removeAmountToWei).div(scaler);

      try {
        let txId;
        if (symbol === "ETH") {
          txId = await poolClient.removeEthliquidity(
            signer,
            bridgeAddress,
            weiAmount
          );
        } else {
          txId = await poolClient.removeTokenLiquidity(
            signer,
            bridgeAddress,
            weiAmount
          );
        }
        const transaction = poolClient.getTx(txId);

        if (transaction.hash) {
          setTxSubmitted(true);

          const { emitter } = notify.hash(transaction.hash);
          emitter.on("all", addEtherscan);

          emitter.on("txConfirmed", (tx) => {
            if (transaction.hash) notify.unsubscribe(transaction.hash);
            const url = `https://etherscan.io/tx/${transaction.hash}`;
            setShowSuccess("withdraw");
            setDepositUrl(url);
            setTxSubmitted(false);
            if (account)
              setTimeout(
                () => updateEthBalance({ chainId: 1, account }),
                15000
              );
          });
          emitter.on("txFailed", () => {
            if (transaction.hash) notify.unsubscribe(transaction.hash);
            setTxSubmitted(false);
          });
        }
        return transaction;
      } catch (err: any) {
        setErrorMessage(err.message);
        console.error("err in RemoveLiquidity call", err);
      }
    }
  };

  const preview = isConnected
    ? previewRemoval(
        {
          totalDeposited: position,
          feesEarned: max(feesEarned, 0),
          positionValue: totalPosition,
        },
        removeAmount / 100
      )
    : null;

  return (
    <>
      <RemoveAmount>
        Amount: <span>{removeAmount}%</span>
      </RemoveAmount>
      <PoolFormSlider value={removeAmount} setValue={setRemoveAmount} />
      <RemovePercentButtonsWrapper>
        <RemovePercentButton onClick={() => setRemoveAmount(25)}>
          25%
        </RemovePercentButton>
        <RemovePercentButton onClick={() => setRemoveAmount(50)}>
          50%
        </RemovePercentButton>
        <RemovePercentButton onClick={() => setRemoveAmount(75)}>
          75%
        </RemovePercentButton>
        <RemovePercentButton onClick={() => setRemoveAmount(100)}>
          MAX
        </RemovePercentButton>
      </RemovePercentButtonsWrapper>

      {isConnected && (
        <>
          <FeesBlockWrapper>
            <FeesBlock>
              <FeesBoldInfo>
                Remove amount <FeesPercent>({removeAmount}%)</FeesPercent>
              </FeesBoldInfo>
              <FeesInfo>Left in pool</FeesInfo>
            </FeesBlock>
            <FeesBlock>
              <FeesValues>
                {preview && formatUnits(preview.position.recieve, decimals)}{" "}
                {symbol}
              </FeesValues>
              <FeesValues>
                {preview && formatUnits(preview.position.remain, decimals)}{" "}
                {symbol}
              </FeesValues>
            </FeesBlock>
          </FeesBlockWrapper>
          <FeesBlockWrapper>
            <FeesBlock>
              <FeesBoldInfo>Fees claimed</FeesBoldInfo>
              <FeesInfo>Left in pool</FeesInfo>
            </FeesBlock>
            <FeesBlock>
              <FeesValues>
                {preview && formatUnits(preview.fees.recieve, decimals)}{" "}
                {symbol}
              </FeesValues>
              <FeesValues>
                {preview && formatUnits(preview.fees.remain, decimals)} {symbol}
              </FeesValues>
            </FeesBlock>
          </FeesBlockWrapper>
          <FeesBlockWrapper>
            <FeesBlock>
              <FeesBoldInfo>You will receive</FeesBoldInfo>
            </FeesBlock>
            <FeesBlock>
              <FeesValues>
                {preview && formatUnits(preview.total.recieve, decimals)}{" "}
                {symbol}
              </FeesValues>
            </FeesBlock>
          </FeesBlockWrapper>
        </>
      )}
      <RemoveFormButtonWrapper>
        {errorMessage && (
          <RemoveFormErrorBox>
            <div>{errorMessage}</div>
          </RemoveFormErrorBox>
        )}
        {wrongNetwork && provider ? (
          <RemoveFormButton
            onClick={() => switchChain(provider, DEFAULT_TO_CHAIN_ID)}
          >
            Switch to {CHAINS[DEFAULT_TO_CHAIN_ID].name}
          </RemoveFormButton>
        ) : (
          <RemoveFormButton
            onClick={handleButtonClick}
            disabled={wrongNetwork && !provider}
          >
            {buttonMessage()}
            {txSubmitted ? <BouncingDotsLoader /> : null}
          </RemoveFormButton>
        )}
      </RemoveFormButtonWrapper>
    </>
  );
}
Example #7
Source File: SendAction.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
SendAction: React.FC = () => {
  const {
    amount,
    token,
    send,
    hasToApprove,
    canApprove,
    canSend,
    toAddress,
    approve,
    fees,
    spender,
  } = useSend();
  const { signer, account, name } = useConnection();
  const sendState = useAppSelector((state) => state.send);
  const [isInfoModalOpen, setOpenInfoModal] = useState(false);
  const toggleInfoModal = () => setOpenInfoModal((oldOpen) => !oldOpen);
  const [isSendPending, setSendPending] = useState(false);
  const [isApprovalPending, setApprovalPending] = useState(false);
  const { addTransaction } = useTransactions();
  const { addDeposit } = useDeposits();
  const [updateEthBalance] = api.endpoints.ethBalance.useLazyQuery();
  const { trackEvent } = useMatomo();
  // trigger balance update
  const [updateBalances] = api.endpoints.balances.useLazyQuery();
  const tokenInfo = TOKENS_LIST[
    sendState.currentlySelectedFromChain.chainId
  ].find((t) => t.address === token);
  const { error, addError, removeError } = useContext(ErrorContext);
  const { refetch } = useAllowance(
    {
      owner: account!,
      spender,
      chainId: sendState.currentlySelectedFromChain.chainId,
      token,
      amount,
    },
    { skip: !account }
  );
  const handleApprove = async () => {
    const tx = await approve();
    if (tx) {
      addTransaction({ ...tx, meta: { label: TransactionTypes.APPROVE } });
      await tx.wait(CONFIRMATIONS);
      refetch();
    }
  };

  const handleSend = async () => {
    const { tx, fees } = await send();
    if (tx && fees) {
      addTransaction({ ...tx, meta: { label: TransactionTypes.DEPOSIT } });
      const receipt = await tx.wait(CONFIRMATIONS);
      addDeposit({
        tx: receipt,
        toChain: sendState.currentlySelectedToChain.chainId,
        fromChain: sendState.currentlySelectedFromChain.chainId,
        amount,
        token,
        toAddress,
        fees,
      });
      // update balances after tx
      if (account) {
        updateEthBalance({
          chainId: sendState.currentlySelectedFromChain.chainId,
          account,
        });
        updateBalances({
          chainId: sendState.currentlySelectedFromChain.chainId,
          account,
        });
      }
    }
  };
  const handleClick = () => {
    if (amount.lte(0) || !signer || disableSendForm) {
      return;
    }
    if (hasToApprove) {
      setApprovalPending(true);
      handleApprove()
        .catch((err) => {
          addError(new Error(`Error in approve call: ${err.message}`));
          console.error(err);
        })
        .finally(() => setApprovalPending(false));
      return;
    }
    if (canSend) {
      // Matomo track send transactions
      trackEvent({
        category: "send",
        action: "bridge",
        name:
          tokenInfo &&
          JSON.stringify({
            symbol: tokenInfo.symbol,
            from: sendState.currentlySelectedFromChain.chainId,
            to: sendState.currentlySelectedToChain.chainId,
          }),
        value: tokenInfo && Number(formatUnits(amount, tokenInfo.decimals)),
      });
      setSendPending(true);
      if (error) removeError();
      handleSend()
        .catch((err) => {
          addError(new Error(`Error with send call: ${err.message}`));
          console.error(err);
        })
        // this actually happens after component unmounts, which is not good. it causes a react warning, but we need
        // it here if user cancels the send. so keep this until theres a better way.
        .finally(() => setSendPending(false));
    }
  };

  const buttonMsg = () => {
    if (isSendPending) return "Sending in progress...";
    if (isApprovalPending) return "Approval in progress...";
    if (hasToApprove) return "Approve";
    return "Send";
  };
  const amountMinusFees = useMemo(() => {
    if (sendState.currentlySelectedFromChain.chainId === ChainId.MAINNET) {
      return amount;
    }
    return receiveAmount(amount, fees);
  }, [amount, fees, sendState.currentlySelectedFromChain.chainId]);

  const buttonDisabled =
    isSendPending ||
    isApprovalPending ||
    (!hasToApprove && !canSend) ||
    (hasToApprove && !canApprove) ||
    amountMinusFees.lte(0);

  const isWETH = tokenInfo?.symbol === "WETH";

  return (
    <AccentSection>
      <Wrapper>
        {amount.gt(0) && fees && tokenInfo && (
          <>
            <InfoHeadlineContainer>
              <SlippageDisclaimer>
                <ConfettiIcon />
                All transfers are slippage free!
              </SlippageDisclaimer>
              <FeesButton onClick={toggleInfoModal}>Fees info</FeesButton>
            </InfoHeadlineContainer>
            <InfoContainer>
              <Info>
                {`Time to ${
                  CHAINS[sendState.currentlySelectedToChain.chainId].name
                }`}
                <div>
                  {getEstimatedDepositTime(
                    sendState.currentlySelectedToChain.chainId
                  )}
                </div>
              </Info>
              {sendState.currentlySelectedFromChain.chainId !==
                ChainId.MAINNET && (
                <Info>
                  <div>Ethereum Network Gas</div>
                  <div>
                    {formatUnits(
                      fees.instantRelayFee.total.add(fees.slowRelayFee.total),
                      tokenInfo.decimals
                    )}{" "}
                    {tokenInfo.symbol}
                  </div>
                </Info>
              )}
              <Info>
                <div>
                  {sendState.currentlySelectedFromChain.chainId ===
                  ChainId.MAINNET
                    ? "Native Bridge Fee"
                    : "Across Bridge Fee"}
                </div>
                <div>
                  {sendState.currentlySelectedFromChain.chainId ===
                  ChainId.MAINNET
                    ? "Free"
                    : `${formatUnits(fees.lpFee.total, tokenInfo.decimals)}
                  ${tokenInfo.symbol}`}
                </div>
              </Info>
            </InfoContainer>
            <AmountToReceive>
              You will receive
              <span>
                {formatUnits(amountMinusFees, tokenInfo.decimals)}{" "}
                {isWETH ? "ETH" : tokenInfo.symbol}
              </span>
            </AmountToReceive>
          </>
        )}

        <PrimaryButton
          onClick={handleClick}
          disabled={buttonDisabled || !!disableSendForm}
        >
          <span>{buttonMsg()}</span>
        </PrimaryButton>
        {name && name === "WalletConnect" && (
          <WalletConnectWarning>
            <span>
              Do not change networks after connecting to Across with
              WalletConnect. Across is not responsible for wallet-based
              integration issues with WalletConnect.
            </span>
          </WalletConnectWarning>
        )}

        {sendState.currentlySelectedFromChain.chainId === ChainId.MAINNET && (
          <L1Info>
            <div>L1 to L2 transfers use the destination’s native bridge</div>
          </L1Info>
        )}
      </Wrapper>
      <InformationDialog isOpen={isInfoModalOpen} onClose={toggleInfoModal} />
    </AccentSection>
  );
}
Example #8
Source File: Confirmation.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
Confirmation: React.FC = () => {
  const { deposit, toggle } = useDeposits();

  if (!deposit) return null;
  const amountMinusFees = receiveAmount(deposit.amount, deposit.fees);
  const tokenInfo = TOKENS_LIST[deposit.fromChain].find(
    (t) => t.address === deposit.token
  );
  const isWETH = tokenInfo?.symbol === "WETH";

  return (
    <Layout>
      <Wrapper>
        <Header>
          <Heading>Deposit succeeded</Heading>
          <SubHeading>
            Your funds will arrive in{" "}
            {getConfirmationDepositTime(deposit.toChain)}
          </SubHeading>
          <SuccessIcon>
            <Check strokeWidth={4} />
          </SuccessIcon>
        </Header>
        <InfoSection>
          <Link
            href={CHAINS[deposit.fromChain].constructExplorerLink(
              deposit.txHash
            )}
            target="_blank"
            rel="noopener norefferrer"
          >
            Explorer <ArrowUpRight width={16} height={16} />
          </Link>
          <div>
            <Row>
              <Info>
                <h3>Sending</h3>
                <div>
                  <Logo
                    src={tokenInfo?.logoURI}
                    alt={`${tokenInfo?.symbol} logo`}
                  />
                  <div>
                    {formatUnits(deposit.amount, tokenInfo?.decimals ?? 18)}{" "}
                    {tokenInfo?.symbol}
                  </div>
                </div>
              </Info>
              <Info></Info>
              <Info>
                <h3>Receiving</h3>
                <div>
                  <Logo
                    src={isWETH ? MAINNET_ETH?.logoURI : tokenInfo?.logoURI}
                    alt={`${
                      isWETH ? MAINNET_ETH?.symbol : tokenInfo?.symbol
                    } logo`}
                  />
                  <div>
                    {formatUnits(
                      amountMinusFees,
                      (isWETH ? MAINNET_ETH?.decimals : tokenInfo?.decimals) ??
                        18
                    )}{" "}
                    {isWETH ? MAINNET_ETH?.symbol : tokenInfo?.symbol}
                  </div>
                </div>
              </Info>
            </Row>
            <Info>
              <h3>From</h3>
              <div>
                <Logo
                  src={CHAINS[deposit.fromChain].logoURI}
                  alt={`${CHAINS[deposit.fromChain].name} logo`}
                />
                <div>
                  <SecondaryLink
                    href={`${CHAINS[deposit.fromChain].explorerUrl}/address/${
                      deposit.from
                    }`}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <span>{deposit.from}</span>
                    <span>{shortenAddressLong(deposit.from ?? "")}</span>
                  </SecondaryLink>
                </div>
              </div>
            </Info>
            <Info>
              <h3>To</h3>
              <div>
                <Logo
                  src={CHAINS[deposit.toChain].logoURI}
                  alt={`${CHAINS[deposit.toChain].name} logo`}
                />
                <div>
                  <SecondaryLink
                    href={`${CHAINS[deposit.toChain].explorerUrl}/address/${
                      deposit.toAddress
                    }`}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    <span>{deposit.toAddress}</span>
                    <span>{shortenAddressLong(deposit.toAddress ?? "")}</span>
                  </SecondaryLink>
                </div>
              </div>
            </Info>
            <Info>
              <h3>Estimated time of arrival</h3>
              <div>
                <div>{getConfirmationDepositTime(deposit.toChain)}</div>
              </div>
            </Info>
          </div>
          <Button onClick={() => toggle({ showConfirmationScreen: false })}>
            Close
          </Button>
        </InfoSection>
      </Wrapper>
    </Layout>
  );
}
Example #9
Source File: NewConfirmation.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
Confirmation: React.FC = () => {
  const { deposit, toggle } = useDeposits();
  const [l1DepositSuccess] = useState(true);

  if (!deposit) return null;
  // const amountMinusFees = receiveAmount(deposit.amount, deposit.fees);

  const tokenInfo = TOKENS_LIST[deposit.fromChain].find(
    (t) => t.address === deposit.token
  );

  return (
    <Layout>
      <Wrapper>
        <Header>
          <SuccessIconRow>
            <SuccessIcon>
              <Check strokeWidth={4} />
            </SuccessIcon>
            {l1DepositSuccess ? (
              <SuccessIcon>
                <Check strokeWidth={4} />
              </SuccessIcon>
            ) : (
              <ConfirmationIcon>
                <div>~2 minutes</div>
              </ConfirmationIcon>
            )}
          </SuccessIconRow>
          {l1DepositSuccess ? <SuccessIconRow /> : <ConfirmationLine />}
          <SuccessInfoRow>
            <SuccessInfoBlock>
              <SuccessInfoText>Deposit succeeded</SuccessInfoText>
              <Link
                href={CHAINS[deposit.fromChain].constructExplorerLink(
                  deposit.txHash
                )}
                target="_blank"
                rel="noopener norefferrer"
              >
                Explorer <ArrowUpRight width={16} height={16} />
              </Link>
            </SuccessInfoBlock>
            <SuccessInfoBlock>
              {l1DepositSuccess ? (
                <>
                  <SuccessInfoText>Transfer succeeded</SuccessInfoText>
                  <Link
                    href={CHAINS[deposit.fromChain].constructExplorerLink(
                      deposit.txHash
                    )}
                    target="_blank"
                    rel="noopener norefferrer"
                  >
                    Explorer <ArrowUpRight width={16} height={16} />
                  </Link>
                </>
              ) : (
                <ConfirmationText>Funds transferred</ConfirmationText>
              )}
            </SuccessInfoBlock>
          </SuccessInfoRow>
        </Header>
        <InfoSection>
          <div>
            <Row>
              <Info>
                <h3>Send</h3>
                <div>
                  <Logo
                    src={tokenInfo?.logoURI}
                    alt={`${tokenInfo?.symbol} logo`}
                  />
                  <div>
                    {formatUnits(deposit.amount, tokenInfo?.decimals ?? 18)}{" "}
                    {tokenInfo?.symbol}
                  </div>
                </div>
              </Info>
              <Info></Info>
              {/* <Info>
                <h3>Receiving</h3>
                <div>
                  <Logo
                    src={tokenInfo?.logoURI}
                    alt={`${tokenInfo?.symbol} logo`}
                  />
                  <div>
                    {formatUnits(amountMinusFees, tokenInfo?.decimals ?? 18)}{" "}
                    {tokenInfo?.symbol}
                  </div>
                </div>
              </Info> */}
            </Row>
            <Info>
              <h3>From</h3>
              <div>
                <Logo
                  src={CHAINS[deposit.fromChain].logoURI}
                  alt={`${CHAINS[deposit.fromChain].name} logo`}
                />
                <div>
                  <SecondaryLink
                    href={`${CHAINS[deposit.fromChain].explorerUrl}/address/${
                      deposit.from
                    }`}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    {deposit.from}
                  </SecondaryLink>
                </div>
              </div>
            </Info>
            <Info>
              <h3>To</h3>
              <div>
                <Logo
                  src={CHAINS[deposit.toChain].logoURI}
                  alt={`${CHAINS[deposit.toChain].name} logo`}
                />
                <div>
                  <SecondaryLink
                    href={`${CHAINS[deposit.toChain].explorerUrl}/address/${
                      deposit.toAddress
                    }`}
                    target="_blank"
                    rel="noopener noreferrer"
                  >
                    {deposit.toAddress}
                  </SecondaryLink>
                </div>
              </div>
            </Info>
            <Info>
              <h3>Estimated time of arrival</h3>
              <div>
                <div>~2 minutes</div>
              </div>
            </Info>
          </div>
          <Button onClick={() => toggle({ showConfirmationScreen: false })}>
            Close
          </Button>
        </InfoSection>
      </Wrapper>
    </Layout>
  );
}