wevm / wagmi

Reactive primitives for Ethereum apps
https://wagmi.sh
MIT License
5.99k stars 1.07k forks source link

switch netwrok failure: ConnectorNotFoundError: Connector not found #2478

Closed JoyCood closed 1 year ago

JoyCood commented 1 year ago
error image
import { isProduction } from "@/config/site";
import { useEffect, useState } from "react";
import { polygon, polygonMumbai } from "viem/chains";
import { configureChains, createConfig, useNetwork } from "wagmi";
import { useAccount, useConnect, useSwitchNetwork } from "wagmi";
import { MetaMaskConnector } from 'wagmi/connectors/metaMask'
import { publicProvider } from 'wagmi/providers/public'

const chain = isProduction ? polygon : polygonMumbai

const { publicClient, webSocketPublicClient } = configureChains(
  [chain],
  [
    publicProvider(),
  ]
);

const connector = new MetaMaskConnector({
  chains: [chain],
  options: {
    shimDisconnect: true,
  },
});

const config = createConfig({
  autoConnect: true,
  connectors: [
    connector
  ],
  publicClient,
  webSocketPublicClient
});

export function useUserInfo() {
  const { connect, isLoading, error, pendingConnector } = useConnect(config);

  const { address } = useAccount();
  const network = useNetwork();

  const switchNetwork = useSwitchNetwork({
    chainId: chain.id,
    onSuccess: () => console.log("switch network successful"),
    onError: (err) => console.error("switch network failure:", err)
  });

  useEffect(() => {
    if (!address && !isLoading && !pendingConnector) {
      connect({connector: connector});
    }
  }, []);

  useEffect(() => {
    if (address && (network.chain?.id != chain.id)) {
      switchNetwork.switchNetwork?.(chain.id)
    }
  }, [address, switchNetwork.switchNetwork, network.chain?.id]);
}

package.json:

{
  "name": "xtest",
  "version": "0.1.0",
  "private": true,
  "engines": {
    "node": "16.19.1",
    "npm": "please-use-yarn"
  },
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint",
    "extract": "lingui extract --clean",
    "compile": "lingui compile --strict"
  },
  "dependencies": {
    "@lingui/react": "^3.14.0",
    "@prisma/client": "^4.14.1",
    "@radix-ui/colors": "^0.1.8",
    "@radix-ui/react-avatar": "^1.0.2",
    "@radix-ui/react-dropdown-menu": "^2.0.4",
    "@radix-ui/react-icons": "^1.3.0",
    "@radix-ui/react-navigation-menu": "^1.1.2",
    "@radix-ui/react-scroll-area": "^1.0.3",
    "@radix-ui/react-toast": "^1.1.3",
    "@reduxjs/toolkit": "^1.9.5",
    "@t3-oss/env-nextjs": "^0.3.1",
    "@types/node": "20.1.2",
    "@types/react": "18.2.6",
    "@types/react-dom": "18.2.4",
    "apexcharts": "^3.40.0",
    "bignumber.js": "^9.1.1",
    "classnames": "^2.3.2",
    "clsx": "^1.2.1",
    "eslint": "8.40.0",
    "eslint-config-next": "13.4.1",
    "lucide-react": "^0.216.0",
    "make-plural": "^7.3.0",
    "next": "^13.4.3",
    "next-redux-wrapper": "^8.1.0",
    "next-themes": "^0.2.1",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-redux": "^8.0.5",
    "redux-persist": "^6.0.0",
    "redux-saga": "^1.2.3",
    "tailwind-merge": "^1.12.0",
    "tailwindcss-animate": "^1.0.5",
    "ts-node": "^10.9.1",
    "typescript": "5.0.4",
    "viem": "^0.3.37",
    "wagmi": "^1.0.7",
    "zod": "^3.21.4"
  },
  "devDependencies": {
    "@babel/core": "^7.21.8",
    "@lingui/cli": "^3.14.0",
    "@lingui/macro": "^3.14.0",
    "@tailwindcss/typography": "^0.5.9",
    "autoprefixer": "^10.4.14",
    "postcss": "^8.4.23",
    "prisma": "^4.14.0",
    "tailwindcss": "^3.3.2"
  }
}

Originally posted by @youthinn in https://github.com/wagmi-dev/wagmi/issues/838#issuecomment-1544314707

tmm commented 1 year ago

Passing in config to useConnect is not correct (below). Can you create a minimal reproduction using next.wagmi.sh?

const { connect, isLoading, error, pendingConnector } = useConnect(config);
JoyCood commented 1 year ago

Passing in config to useConnect is not correct (below). Can you create a minimal reproduction using next.wagmi.sh?

const { connect, isLoading, error, pendingConnector } = useConnect(config);

you save my life, it is working now! thank you!

kfazil commented 10 months ago

@tmm I'm also getting this error but I can't reproduce it. It doesn't happen everytime, I get this error randomly and it resolves autometically when I try to connect or switch network. This is how I'm creating config (Check below).

import { createConfig, configureChains, CreateConfigParameters, PublicClient, WebSocketPublicClient } from 'wagmi'
import { publicProvider } from 'wagmi/providers/public';
import { MetaMaskConnector } from 'wagmi/connectors/metaMask';
import { avalanche, bsc, mainnet, arbitrum, fantom, polygon, base, optimism} from '@wagmi/chains';
import { alchemyProvider } from 'wagmi/providers/alchemy';
import { infuraProvider } from 'wagmi/providers/infura';
import { FallbackTransport } from 'viem';

const supportedChains = [mainnet, bsc, avalanche, arbitrum, fantom, polygon, base, optimism];

const { chains, publicClient, webSocketPublicClient } = configureChains(
    supportedChains,
    [
        infuraProvider({ apiKey: import.meta.env.VITE_INFURA_KEY }),
        alchemyProvider({ apiKey: import.meta.env.VITE_ALCHEMY_KEY }),
        publicProvider(),
    ]
);

const metaMaskConnector = new MetaMaskConnector({ chains, options: {
    shimDisconnect: true
}});

const supportedConnectors = [metaMaskConnector];

// Set up wagmi config
const configParameters: CreateConfigParameters<PublicClient<FallbackTransport>, WebSocketPublicClient<FallbackTransport>> = {
    autoConnect: true,
    connectors: supportedConnectors,
    publicClient,
    webSocketPublicClient
};

const config = createConfig(configParameters);

export {
    config
}

App Root Component

import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
import "./index.css";
import App from "./App";
import { WagmiConfig } from 'wagmi';
import { config } from './utils/walletConnector';

const rootElement = document.getElementById('root');
const root = createRoot(rootElement!);

root.render(
  <StrictMode>
    <WagmiConfig config={config}>
      <App />
    </WagmiConfig>
  </StrictMode>
);

Connect Button

import styles from "./style.module.scss";
import { useConnect } from "wagmi";

const ConnectWalletButton = () => {
  const { connectAsync, connectors, isLoading, pendingConnector} = useConnect({
    onSuccess(data) {
      console.log('Connect', data)
    },
    onError(error, variables) {
      console.log('error', { error, variables });
      if (variables.connector.id === 'metaMask') {
        // log metamask connector related error
      }
    }
  });

  return (
    <>
      {connectors.map((connector) => {
        const buttonStatus = connector.ready ? connectButtonText ?? `Connect Wallet` : (!connector.ready ? `${connector.name} (unsupported)` : (isLoading &&
          connector.id === pendingConnector?.id) ? `Connecting to ${connector.name}` : '')
        return (
          <Button
            isDisabled={!connector.ready}
            key={connector.id}
            text={buttonStatus}
            isLoading={isLoading}
            onClickHandler={() => connectAsync({ connector })}
          />
        )
      })}
    </>
  );
};

export default ConnectWalletButton;
github-actions[bot] commented 10 months ago

This issue has been locked since it has been closed for more than 14 days.

If you found a concrete bug or regression related to it, please open a new bug report with a reproduction against the latest wagmi version. If you have any other comments you can create a new discussion.