utils#DEFAULT_TO_CHAIN_ID TypeScript Examples

The following examples show how to use utils#DEFAULT_TO_CHAIN_ID. 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: send.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
initialState: State = {
  token: ethers.constants.AddressZero,
  amount: ethers.constants.Zero,
  toChain: DEFAULT_TO_CHAIN_ID,
  fromChain: DEFAULT_FROM_CHAIN_ID,
  // Default to ethereum, which should be end of this array.
  currentlySelectedToChain: CHAINS_SELECTION[CHAINS_SELECTION.length - 1],
  currentlySelectedFromChain: CHAINS_SELECTION[0],
}
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: 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 #4
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 #5
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>
  );
}