utils#TOKENS_LIST TypeScript Examples

The following examples show how to use utils#TOKENS_LIST. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: hooks.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
export function useBalance({
  chainId,
  account,
  tokenAddress,
}: useBalanceParams) {
  const { data: allBalances, refetch } = chainApi.endpoints.balances.useQuery(
    {
      account: account ?? "",
      chainId,
    },
    { skip: !account }
  );
  const selectedIndex = useMemo(
    () =>
      TOKENS_LIST[chainId].findIndex(({ address }) => address === tokenAddress),
    [chainId, tokenAddress]
  );
  const balance = allBalances?.[selectedIndex] ?? ethers.BigNumber.from(0);

  return {
    balance,
    refetch,
  };
}
Example #2
Source File: Confirmation.tsx    From frontend-v1 with GNU Affero General Public License v3.0 5 votes vote down vote up
MAINNET_ETH = TOKENS_LIST[ChainId.MAINNET].find(
  (t) => t.symbol === "ETH"
)
Example #3
Source File: CoinSelection.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
CoinSelection = () => {
  const { account, isConnected } = useConnection();
  const { setAmount, setToken, amount, token, fees } = useSend();

  const { trackEvent } = useMatomo();

  const [error, setError] = React.useState<Error>();
  const sendState = useAppSelector((state) => state.send);
  const tokenList = useMemo(() => {
    const filterByToChain = (token: Token) =>
      TOKENS_LIST[sendState.currentlySelectedToChain.chainId].some(
        (element) => element.symbol === token.symbol
      );
    if (
      sendState.currentlySelectedFromChain.chainId === ChainId.MAINNET &&
      sendState.currentlySelectedToChain.chainId === ChainId.OPTIMISM
    ) {
      // Note: because of how Optimism treats WETH, it must not be sent over their canonical bridge.
      return TOKENS_LIST[sendState.currentlySelectedFromChain.chainId]
        .filter((element) => element.symbol !== "WETH")
        .filter(filterByToChain);
    }
    return TOKENS_LIST[sendState.currentlySelectedFromChain.chainId].filter(
      filterByToChain
    );
  }, [
    sendState.currentlySelectedFromChain.chainId,
    sendState.currentlySelectedToChain.chainId,
  ]);
  const { data: balances } = useBalances(
    {
      account: account!,
      chainId: sendState.currentlySelectedFromChain.chainId,
    },
    { skip: !account }
  );
  const tokenBalanceMap = useMemo(() => {
    return TOKENS_LIST[sendState.currentlySelectedFromChain.chainId].reduce(
      (acc, val, idx) => {
        return {
          ...acc,
          [val.address]: balances ? balances[idx] : undefined,
        };
      },
      {} as Record<string, BigNumber | undefined>
    );
  }, [balances, sendState.currentlySelectedFromChain.chainId]);

  const [dropdownItem, setDropdownItem] = useState(() =>
    tokenList.find((t) => t.address === token)
  );

  // Adjust coin dropdown when chain id changes, as some tokens don't exist on all chains.
  useEffect(() => {
    const newToken = tokenList.find(
      (t) => t.address === ethers.constants.AddressZero
    );
    setInputAmount("");
    // since we are resetting input to 0, reset any errors
    setError(undefined);
    setAmount({ amount: BigNumber.from("0") });
    setDropdownItem(() => newToken);
    setToken({ token: newToken?.address || "" });
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sendState.currentlySelectedFromChain.chainId, tokenList]);

  const {
    isOpen,
    selectedItem,
    getLabelProps,
    getToggleButtonProps,
    getItemProps,
    getMenuProps,
  } = useSelect({
    items: tokenList,
    defaultSelectedItem: tokenList.find((t) => t.address === token),
    selectedItem: dropdownItem,
    onSelectedItemChange: ({ selectedItem }) => {
      if (selectedItem) {
        // Matomo track token selection
        trackEvent({
          category: "send",
          action: "setAsset",
          name: selectedItem.symbol,
        });

        setInputAmount("");
        // since we are resetting input to 0, reset any errors
        setError(undefined);
        setAmount({ amount: BigNumber.from("0") });
        setToken({ token: selectedItem.address });
        setDropdownItem(selectedItem);
      }
    },
  });
  const [inputAmount, setInputAmount] = React.useState<string>(
    selectedItem && amount.gt("0")
      ? formatUnits(amount, selectedItem.decimals)
      : ""
  );

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    const value = event.target.value;
    setInputAmount(value);
    if (value === "") {
      setAmount({ amount: ethers.constants.Zero });
      setError(undefined);
      return;
    }
    try {
      const amount = parseUnits(value, selectedItem!.decimals);
      // just throw an error if lt 0 and let the catch set the parsing error
      if (amount.lt(0)) throw new Error();
      setAmount({ amount });
      if (error instanceof ParsingError) {
        setError(undefined);
      }
    } catch (e) {
      setError(new ParsingError());
    }
  };

  // checks for insufficient balance errors
  useEffect(() => {
    if (amount && inputAmount) {
      // clear the previous error if it is not a parsing error
      setError((oldError) => {
        if (oldError instanceof ParsingError) {
          return oldError;
        }
        return undefined;
      });

      if (balances && amount.gt(0)) {
        const selectedIndex = tokenList.findIndex(
          ({ address }) => address === token
        );
        const balance = tokenBalanceMap[token];
        const isEth = tokenList[selectedIndex]?.symbol === "ETH";
        if (
          balance &&
          amount.gt(
            isEth
              ? balance.sub(ethers.utils.parseEther(FEE_ESTIMATION))
              : balance
          )
        ) {
          setError(new Error("Insufficient balance."));
        }
      }
    }
  }, [balances, amount, token, tokenList, inputAmount, tokenBalanceMap]);

  const handleMaxClick = () => {
    if (balances && selectedItem) {
      const selectedIndex = tokenList.findIndex(
        ({ address }) => address === selectedItem.address
      );
      const isEth = tokenList[selectedIndex].symbol === "ETH";
      let balance = tokenBalanceMap[token];

      if (balance) {
        if (isEth) {
          balance = max(
            balance.sub(ethers.utils.parseEther(FEE_ESTIMATION)),
            0
          );
        }
        setAmount({ amount: balance });
        setInputAmount(formatUnits(balance, selectedItem.decimals));
      } else {
        setAmount({ amount: ethers.BigNumber.from("0") });
        setInputAmount(
          formatUnits(ethers.BigNumber.from("0"), selectedItem.decimals)
        );
      }
    }
  };
  const errorMsg = error
    ? error.message
    : fees?.isAmountTooLow
    ? "Bridge fee is high for this amount. Send a larger amount."
    : fees?.isLiquidityInsufficient
    ? `Insufficient liquidity for ${selectedItem?.symbol}.`
    : undefined;

  const showError =
    error ||
    (fees?.isAmountTooLow && amount.gt(0)) ||
    (fees?.isLiquidityInsufficient && amount.gt(0));

  return (
    <AnimatePresence>
      <Section>
        <Wrapper>
          <SectionTitle>Asset</SectionTitle>
          <InputGroup>
            <RoundBox as="label" {...getLabelProps()}>
              <ToggleButton type="button" {...getToggleButtonProps()}>
                <Logo src={selectedItem?.logoURI} alt={selectedItem?.name} />
                <div>{selectedItem?.symbol}</div>
                <ToggleIcon />
              </ToggleButton>
            </RoundBox>
            <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={handleMaxClick} disabled={!isConnected}>
                max
              </MaxButton>
              <Input
                placeholder="0.00"
                id="amount"
                value={inputAmount}
                onChange={handleChange}
              />
            </RoundBox>
            <Menu {...getMenuProps()} isOpen={isOpen}>
              {isOpen &&
                tokenList.map((token, index) => (
                  <Item
                    {...getItemProps({ item: token, index })}
                    initial={{ y: -10 }}
                    animate={{ y: 0 }}
                    exit={{ y: -10 }}
                    key={token.address}
                  >
                    <Logo src={token.logoURI} alt={token.name} />
                    <div>{token.name}</div>
                    <div>
                      {tokenBalanceMap &&
                        formatUnits(
                          tokenBalanceMap[token.address] || "0",
                          tokenList[index].decimals
                        )}
                    </div>
                  </Item>
                ))}
            </Menu>
          </InputGroup>
          {showError && <ErrorBox>{errorMsg}</ErrorBox>}
        </Wrapper>
      </Section>
    </AnimatePresence>
  );
}
Example #4
Source File: PoolSelection.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
PoolSelection: FC<Props> = ({ token, setToken, position }) => {
  const { account } = useConnection();

  const { data: balances } = useBalances(
    {
      account: account!,
      chainId: ChainId.MAINNET,
    },
    { skip: !account }
  );

  const {
    isOpen,
    selectedItem,
    getLabelProps,
    getToggleButtonProps,
    getItemProps,
    getMenuProps,
  } = useSelect({
    items: TOKENS_LIST[ChainId.MAINNET],
    defaultSelectedItem: token,
    onSelectedItemChange: ({ selectedItem }) => {
      if (selectedItem) {
        setToken(selectedItem);
      }
    },
  });

  return (
    <AnimatePresence>
      <Wrapper>
        {migrationPoolV2Warning ? (
          <MigrationWarning>
            <div>
              If you have not migrated liquidity from Across v1 to Across v2,
              please follow{" "}
              <a
                href="https://docs.across.to/v2/migrating-from-v1"
                target="_blank"
                rel="noreferrer"
              >
                {" "}
                these instructions
              </a>{" "}
            </div>
          </MigrationWarning>
        ) : null}
        <SectionTitle>Select pool</SectionTitle>
        <InputGroup>
          <RoundBox as="label" {...getLabelProps()}>
            <ToggleButton type="button" {...getToggleButtonProps()}>
              <Logo src={selectedItem?.logoURI} alt={selectedItem?.name} />
              <div>{selectedItem?.symbol}</div>
              <ToggleIcon />
            </ToggleButton>
          </RoundBox>
          <Menu {...getMenuProps()} isOpen={isOpen}>
            {isOpen &&
              TOKENS_LIST[ChainId.MAINNET].map((t, index) => {
                return (
                  <Item
                    {...getItemProps({ item: t, index })}
                    key={t.address}
                    initial={{ y: -10 }}
                    animate={{ y: 0 }}
                    exit={{ y: -10 }}
                  >
                    <Logo src={t.logoURI} alt={t.name} />
                    <div>{t.name}</div>
                    <div>
                      {balances && formatUnits(balances[index], t.decimals)}
                    </div>
                  </Item>
                );
              })}
          </Menu>
        </InputGroup>
      </Wrapper>
    </AnimatePresence>
  );
}
Example #5
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 #6
Source File: chainApi.ts    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
api = createApi({
  baseQuery: fakeBaseQuery(),
  endpoints: (build) => ({
    balances: build.query<ethers.BigNumber[], BalancesQueryArgs>({
      queryFn: async ({ account, chainId }) => {
        try {
          const provider = PROVIDERS[chainId]();
          const balances = await Promise.all(
            TOKENS_LIST[chainId].map(async (token) => {
              try {
                // If it is ETH, use getBalance from the provider
                if (token.address === ethers.constants.AddressZero) {
                  return provider.getBalance(account);
                }
                const contract = ERC20Ethers__factory.connect(
                  token.address,
                  provider
                );
                return await contract.balanceOf(account);
              } catch (err) {
                console.error(
                  `Error fetching balance for: ${token.name} at ${token.address}`
                );
                console.error(err);
                return BigNumber.from("0");
              }
            })
          );
          return { data: balances };
        } catch (error) {
          return { error };
        }
      },
    }),
    allowance: build.query<
      { hasToApprove: boolean; allowance: ethers.BigNumber },
      AllowanceQueryArgs
    >({
      queryFn: async ({ owner, spender, chainId, token, amount }) => {
        try {
          const provider = PROVIDERS[chainId]();
          // For ETH, allowance does not make sense
          if (token === ethers.constants.AddressZero) {
            return {
              data: {
                hasToApprove: false,
                allowance: ethers.constants.MaxUint256,
              },
            };
          }
          const contract = clients.erc20.connect(token, provider);
          const allowance = await contract.allowance(owner, spender);
          const hasToApprove = amount.gt(allowance);

          return { data: { allowance, hasToApprove } };
        } catch (error) {
          return { error };
        }
      },
    }),
    ethBalance: build.query<ethers.BigNumber, BalancesQueryArgs>({
      queryFn: async ({ account, chainId }) => {
        try {
          const provider = PROVIDERS[chainId]();
          const balance = await provider.getBalance(account);
          return { data: balance };
        } catch (error) {
          return { error };
        }
      },
    }),
    bridgeFees: build.query<BridgeFeesQueryResult, BridgeFeesQueryArgs>({
      // We want to re-run the fee query on each block change
      queryFn: async ({ amount, tokenSymbol, blockTime }) => {
        try {
          const { instantRelayFee, slowRelayFee, isAmountTooLow } =
            await getRelayFees(tokenSymbol, amount);

          const { isLiquidityInsufficient, ...lpFee } = await getLpFee(
            tokenSymbol,
            amount,
            blockTime
          );

          return {
            data: {
              instantRelayFee,
              slowRelayFee,
              lpFee,
              isAmountTooLow,
              isLiquidityInsufficient,
            },
          };
        } catch (error) {
          console.error("bridge fee calculation failed");
          console.error(error);
          return { error };
        }
      },
    }),
  }),
})
Example #7
Source File: hooks.ts    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
export function useSendAcross() {
  const { referrer } = useQuery();
  const { isConnected, chainId, account, signer } = useConnection();
  const {
    fromChain,
    toChain,
    toAddress,
    amount,
    token,
    error,
    currentlySelectedFromChain,
    currentlySelectedToChain,
  } = useAppSelector((state) => state.send);
  const { balance } = useBalance({
    chainId: currentlySelectedFromChain.chainId,
    account,
    tokenAddress: token,
  });
  const { block } = useL2Block();

  const depositBox = getDepositBox(currentlySelectedFromChain.chainId);
  const { data: allowance } = useAllowance(
    {
      chainId: currentlySelectedFromChain.chainId,
      token,
      owner: account!,
      spender: depositBox.address,
      amount,
    },
    { skip: !account || !isConnected || !depositBox }
  );
  const { approve: rawApprove } = useERC20(token);
  const canApprove = balance.gte(amount) && amount.gte(0);
  const hasToApprove = allowance?.hasToApprove ?? false;

  async function approve() {
    return rawApprove({
      amount: MAX_APPROVAL_AMOUNT,
      spender: depositBox.address,
      signer,
    });
  }
  const hasToSwitchChain =
    isConnected && currentlySelectedFromChain.chainId !== chainId;

  const tokenSymbol =
    TOKENS_LIST[currentlySelectedFromChain.chainId].find(
      (t) => t.address === token
    )?.symbol ?? "";

  const { data: fees, isFetching: isFetchingFees } = useBridgeFees(
    {
      amount,
      tokenSymbol,
      blockTime: block?.timestamp!,
    },
    { skip: tokenSymbol === "" || amount.lte(0) || !block?.timestamp }
  );

  const canSend = useMemo(
    () =>
      currentlySelectedFromChain.chainId &&
      block &&
      currentlySelectedToChain.chainId &&
      amount &&
      token &&
      fees &&
      !isFetchingFees &&
      toAddress &&
      isValidAddress(toAddress) &&
      !hasToApprove &&
      !hasToSwitchChain &&
      !error &&
      !fees.isAmountTooLow &&
      !fees.isLiquidityInsufficient &&
      balance
        .sub(
          token === "0x0000000000000000000000000000000000000000"
            ? BigNumber.from(ethers.utils.parseEther(FEE_ESTIMATION))
            : BigNumber.from("0")
        )
        .gte(amount),
    [
      currentlySelectedFromChain.chainId,
      block,
      currentlySelectedToChain.chainId,
      amount,
      token,
      fees,
      isFetchingFees,
      toAddress,
      hasToApprove,
      hasToSwitchChain,
      error,
      balance,
    ]
  );

  const send = useCallback(async () => {
    if (
      !signer ||
      !canSend ||
      !fees ||
      isFetchingFees ||
      !toAddress ||
      !block
    ) {
      return {};
    }

    try {
      const depositBox = getDepositBox(
        currentlySelectedFromChain.chainId,
        signer
      );
      const isETH = token === ethers.constants.AddressZero;
      const value = isETH ? amount : ethers.constants.Zero;
      const l2Token = isETH
        ? TOKENS_LIST[currentlySelectedFromChain.chainId][0].address
        : token;
      const { instantRelayFee, slowRelayFee } = fees;
      let timestamp = block.timestamp;

      const data = depositBox.interface.encodeFunctionData("deposit", [
        toAddress,
        l2Token,
        amount,
        slowRelayFee.pct,
        instantRelayFee.pct,
        timestamp,
      ]);

      // do not tag a referrer if data is not provided as a hex string.
      const taggedData =
        referrer && ethers.utils.isAddress(referrer)
          ? tagAddress(data, referrer)
          : data;

      if (
        !(await validateContractAndChain(
          depositBox.address,
          currentlySelectedFromChain.chainId,
          signer
        ))
      ) {
        return {};
      }

      const tx = await signer.sendTransaction({
        data: taggedData,
        value,
        to: depositBox.address,
        chainId: currentlySelectedFromChain.chainId,
      });
      return { tx, fees };
    } catch (e) {
      throw new TransactionError(
        depositBox.address,
        "deposit",
        toAddress,
        token,
        amount,
        fees.slowRelayFee.pct,
        fees.instantRelayFee.pct,
        block.timestamp
      );
    }
  }, [
    amount,
    block,
    canSend,
    depositBox.address,
    fees,
    isFetchingFees,
    currentlySelectedFromChain.chainId,
    signer,
    toAddress,
    token,
    referrer,
  ]);

  return {
    fromChain,
    toChain,
    toAddress,
    amount,
    token,
    error,
    canSend,
    canApprove,
    hasToApprove,
    hasToSwitchChain,
    send,
    approve,
    fees: isFetchingFees ? undefined : fees,
    spender: depositBox.address,
  };
}
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>
  );
}
Example #10
Source File: Pool.tsx    From frontend-v1 with GNU Affero General Public License v3.0 4 votes vote down vote up
Pool: FC = () => {
  const [token, setToken] = useState<Token>(TOKENS_LIST[ChainId.MAINNET][2]);
  const [showSuccess, setShowSuccess] = useState<ShowSuccess | undefined>();
  const [depositUrl, setDepositUrl] = useState("");
  const [loadingPoolState, setLoadingPoolState] = useState(false);
  const [defaultTab, setDefaultTab] = useState("Add");
  const pool = useAppSelector((state) => state.pools.pools[token.bridgePool]);
  const connection = useAppSelector((state) => state.connection);
  const userPosition = useAppSelector((state) =>
    get(state, [
      "pools",
      "users",
      state?.connection?.account || "",
      token.bridgePool,
    ])
  );

  const { isConnected, account, provider, error, chainId } = useConnection();

  const queries = useAppSelector((state) => state.api.queries);

  const { balance, refetch: refetchBalance } = useBalance({
    chainId: ChainId.MAINNET,
    account,
    tokenAddress: token.address,
  });

  const wrongNetwork =
    provider &&
    (error instanceof UnsupportedChainIdError ||
      chainId !== DEFAULT_TO_CHAIN_ID);

  // Update pool info when token changes
  useEffect(() => {
    setLoadingPoolState(true);

    poolClient.updatePool(token.bridgePool).then((res) => {
      setLoadingPoolState(false);
    });
  }, [token, setLoadingPoolState]);

  useEffect(() => {
    if (isConnected && connection.account && token.bridgePool) {
      poolClient.updateUser(connection.account, token.bridgePool);
    }
  }, [isConnected, connection.account, token.bridgePool]);

  useEffect(() => {
    // Recheck for balances. note: Onboard provider is faster than ours.
    if (depositUrl) {
      setTimeout(() => {
        refetchBalance();
      }, 15000);
    }
  }, [depositUrl, refetchBalance]);

  return (
    <Layout>
      {!showSuccess ? (
        <Wrapper>
          <PoolSelection
            wrongNetwork={wrongNetwork}
            token={token}
            setToken={setToken}
            position={
              userPosition
                ? ethers.BigNumber.from(userPosition.positionValue)
                : ethers.BigNumber.from("0")
            }
          />
          {!loadingPoolState ? (
            <PoolForm
              wrongNetwork={wrongNetwork}
              symbol={token.symbol}
              icon={token.logoURI}
              decimals={token.decimals}
              tokenAddress={token.address}
              totalPoolSize={
                pool && pool.totalPoolSize
                  ? ethers.BigNumber.from(pool.totalPoolSize)
                  : ethers.BigNumber.from("0")
              }
              apy={
                pool && pool.estimatedApy
                  ? `${Number(pool.estimatedApy) * 100}`
                  : "0"
              }
              projectedApr={
                pool && pool.projectedApr
                  ? `${Number(pool.projectedApr) * 100}`
                  : "0"
              }
              position={
                userPosition
                  ? ethers.BigNumber.from(userPosition.positionValue)
                  : ethers.BigNumber.from("0")
              }
              feesEarned={
                userPosition
                  ? max(ethers.BigNumber.from(userPosition.feesEarned), 0)
                  : ethers.BigNumber.from("0")
              }
              totalPosition={
                userPosition
                  ? ethers.BigNumber.from(userPosition.positionValue)
                  : ethers.BigNumber.from("0")
              }
              lpTokens={
                userPosition
                  ? ethers.BigNumber.from(userPosition.lpTokens)
                  : ethers.BigNumber.from("0")
              }
              bridgeAddress={token.bridgePool}
              ethBalance={
                account
                  ? // Very odd key assigned to these values.
                    queries[`ethBalance({"account":"${account}","chainId":1})`]
                  : null
              }
              erc20Balances={
                account
                  ? queries[`balances({"account":"${account}","chainId":1})`]
                  : null
              }
              setShowSuccess={setShowSuccess}
              setDepositUrl={setDepositUrl}
              balance={balance.toString()}
              refetchBalance={refetchBalance}
              defaultTab={defaultTab}
              setDefaultTab={setDefaultTab}
              utilization={
                pool && pool.liquidityUtilizationCurrent
                  ? pool.liquidityUtilizationCurrent
                  : "0"
              }
            />
          ) : (
            <LoadingWrapper>
              <LoadingInfo>
                <LoadingLogo src={token.logoURI} />
                <InfoText>{token.symbol} Pool</InfoText>
                <BouncingDotsLoader type={"big" as BounceType} />
              </LoadingInfo>
              <LoadingPositionWrapper />
              <BigLoadingPositionWrapper />
            </LoadingWrapper>
          )}
        </Wrapper>
      ) : (
        <DepositSuccess
          depositUrl={depositUrl}
          setShowSuccess={setShowSuccess}
          showSuccess={showSuccess}
          setDepositUrl={setDepositUrl}
        />
      )}
    </Layout>
  );
}