utils#UnsupportedChainIdError TypeScript Examples

The following examples show how to use utils#UnsupportedChainIdError. 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: connection.ts    From frontend-v1 with GNU Affero General Public License v3.0 6 votes vote down vote up
connectionSlice = createSlice({
  name: "connection",
  initialState,
  reducers: {
    update: (state, action: PayloadAction<Update>) => {
      const { account, chainId, provider, signer, name } = action.payload;
      state.account = account ? getAddress(account) : state.account;
      state.provider = provider ?? state.provider;
      // theres a potential problem with this: if onboard says a signer is undefined, we default them back
      // to the previous signer. This means we get out of sync with onboard and could have serious consequences.
      state.signer = signer ?? state.signer;
      state.name = name ?? state.name;
      if (chainId) {
        if (isSupportedChainId(chainId)) {
          state.chainId = chainId;
          if (state.error instanceof UnsupportedChainIdError) {
            state.error = undefined;
          }
        } else {
          state.error = new UnsupportedChainIdError(chainId);
        }
      }
      return state;
    },
    error: (state, action: PayloadAction<ErrorUpdate>) => {
      state.error = action.payload.error;
      return state;
    },
    disconnect: (state) => {
      state = initialState;
      return state;
    },
  },
})
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: 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 #4
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>
  );
}