@web3-react/injected-connector#InjectedConnector TypeScript Examples

The following examples show how to use @web3-react/injected-connector#InjectedConnector. 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: useNetworkSwitching.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
useNetworkSwitching = () => {
  const { connector, deactivate } = useWeb3React();
  const history = useHistory();

  const trySwitching = async (chain: ChainConfig) => {
    if (connector instanceof InjectedConnector) {
      const chainIdHex = `0x${chain.id.toString(16)}`;
      try {
        await window.ethereum?.send('wallet_switchEthereumChain', [
          { chainId: chainIdHex },
        ]);
      } catch (e: any) {
        window.ethereum?.send('wallet_addEthereumChain', [
          {
            chainId: chainIdHex,
            chainName: chain.displayName,
            nativeCurrency: chain.nativeAsset,
            rpcUrls: [chain.rpcUrl, chain.defaultRpc],
            blockExplorerUrls: [chain.blockExplorer],
          },
        ]);
      }
    }

    deactivate();

    history.push(`/${chain.name}`);
  };

  return {
    trySwitching,
  };
}
Example #2
Source File: MetamaskConnector.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
export class MetamaskConnector extends InjectedConnector {
  constructor(kwargs: AbstractConnectorArguments) {
    super(kwargs);
  }
  public async isAuthorized(): Promise<boolean> {
    // @ts-ignore
    if (!window.ethereum) {
      return false;
    }

    try {
      const provider = await this.getProvider();
      return !!(provider && provider['selectedAddress']);
    } catch {
      return false;
    }
  }
}
Example #3
Source File: connectors.ts    From dxvote with GNU Affero General Public License v3.0 6 votes vote down vote up
findWalletType = (connector: any) => {
  if (connector instanceof InjectedConnector) {
    return 'MetaMask';
  } else if (connector instanceof WalletConnectConnector) {
    return 'WalletConnect';
  } else {
    return null;
  }
}
Example #4
Source File: App.tsx    From ether-swr with MIT License 6 votes vote down vote up
injectedConnector = new InjectedConnector({
  supportedChainIds: [
    Networks.MainNet, // Mainet
    Networks.Ropsten, // Ropsten
    Networks.Rinkeby, // Rinkeby
    Networks.Goerli, // Goerli
    Networks.Kovan // Kovan
  ]
})
Example #5
Source File: index.ts    From dyp with Do What The F*ck You Want To Public License 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [1, 3, 4, 5, 42]
})
Example #6
Source File: web3.ts    From tokenlog with MIT License 5 votes vote down vote up
Injected = new InjectedConnector({
  supportedChainIds: [1, 3, 4, 5, 42, 100, 137],
})
Example #7
Source File: web3.ts    From contraktor with MIT License 5 votes vote down vote up
Injected = new InjectedConnector({
    supportedChainIds: [1, 3, 4, 5, 42, 100]
})
Example #8
Source File: web3React.ts    From vvs-ui with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({ supportedChainIds: [chainId] })
Example #9
Source File: index.ts    From luaswap-interface with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [1, 3, 4, 5, 42, 88, 89, 99]
})
Example #10
Source File: index.ts    From forward.swaps with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  // supportedChainIds: [1, 3, 4, 5, 42]
  supportedChainIds: [42]
})
Example #11
Source File: index.ts    From nft-market with MIT License 5 votes vote down vote up
injected = new InjectedConnector({ supportedChainIds: [5777, 1337, 4] })
Example #12
Source File: index.ts    From pancake-swap-interface-v1 with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [56, 97],
})
Example #13
Source File: ConnectWallet.tsx    From lp-inspector with MIT License 5 votes vote down vote up
injectedConnector = new InjectedConnector({
  supportedChainIds: [56],
})
Example #14
Source File: index.ts    From pancake-swap-testnet with MIT License 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [97],
})
Example #15
Source File: index.ts    From pancake-swap-exchange-testnet with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [56, 97],
})
Example #16
Source File: index.ts    From mozartfinance-swap-interface with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [56, 97],
})
Example #17
Source File: index.ts    From goose-frontend-amm with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [56, 97],
})
Example #18
Source File: web3React.ts    From glide-frontend with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({ supportedChainIds: [1, 20, 56, 128] })
Example #19
Source File: web3.ts    From dope-monorepo with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [1, 10, 42, 69],
})
Example #20
Source File: index.ts    From cheeseswap-interface with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [56, 97]
})
Example #21
Source File: index.ts    From sybil-interface with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [1, 3, 4, 5, 42],
})
Example #22
Source File: index.ts    From interface-v2 with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [137, 80001],
})
Example #23
Source File: connectors.ts    From hypertext with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({ supportedChainIds: [1, 3, 4, 5, 42] })
Example #24
Source File: connectors.ts    From index-ui with MIT License 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [1, 3, 4, 5, 42, 137],
})
Example #25
Source File: index.ts    From cuiswap with GNU General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: [1, 3, 4, 5, 42]
})
Example #26
Source File: connectors.ts    From dxvote with GNU Affero General Public License v3.0 5 votes vote down vote up
injected = new InjectedConnector({
  supportedChainIds: ETH_NETWORKS_IDS,
})
Example #27
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
NetworkModal = observer(() => {
  const {
    context: { modalStore, providerStore },
  } = useContext();
  const { chainId, connector, deactivate } = providerStore.getActiveWeb3React();
  const rpcUrls = useRpcUrls();
  const history = useHistory();
  const [networkErrorMessage, setNetworkErrorMessage] = useState(false);

  const networkModalOpen = modalStore.networkModalVisible;

  const toggleNetworkModal = () => {
    modalStore.toggleNetworkModal();
  };

  // always reset to options view
  useEffect(() => {
    if (networkModalOpen) {
      setNetworkErrorMessage(false);
    }
  }, [networkModalOpen]);

  const trySwitching = async chain => {
    if (connector instanceof InjectedConnector) {
      const chainIdHex = `0x${chain.id.toString(16)}`;
      try {
        await window.ethereum?.send('wallet_switchEthereumChain', [
          { chainId: chainIdHex },
        ]);
      } catch (e: any) {
        if (e?.code == 4902) {
          window.ethereum?.send('wallet_addEthereumChain', [
            {
              chainId: chainIdHex,
              chainName: chain.displayName,
              nativeCurrency: chain.nativeAsset,
              rpcUrls: [chain.rpcUrl, chain.defaultRpc],
              blockExplorerUrls: [chain.blockExplorer],
            },
          ]);
        }
      }
    } else {
      deactivate();
    }

    history.push(`/${chain.name}/proposals`);
  };

  // get networks user can switch to
  function getOptions() {
    if (!rpcUrls) return [];

    const chains = getChains(rpcUrls);
    return chains.map(chain => {
      return (
        <Option
          onClick={() => trySwitching(chain)}
          key={chain.name}
          icon={iconsByChain[chain.id] || null}
          active={chain.id === chainId}
          header={chain.displayName}
        />
      );
    });
  }

  function getModalContent() {
    return (
      <UpperSection>
        <ContentWrapper>
          <OptionGrid>{getOptions()}</OptionGrid>
        </ContentWrapper>
      </UpperSection>
    );
  }

  return (
    <Modal
      header={<div>Switch network</div>}
      isOpen={networkModalOpen}
      onDismiss={toggleNetworkModal}
    >
      <>
        <Wrapper>{getModalContent()}</Wrapper>
        <div>{networkErrorMessage}</div>
      </>
    </Modal>
  );
})
Example #28
Source File: index.tsx    From nouns-monorepo with GNU General Public License v3.0 4 votes vote down vote up
WalletConnectModal: React.FC<{ onDismiss: () => void }> = props => {
  const { onDismiss } = props;
  const { activate } = useEthers();
  const supportedChainIds = [CHAIN_ID];

  const wallets = (
    <div className={classes.walletConnectModal}>
      <WalletButton
        onClick={() => {
          const injected = new InjectedConnector({
            supportedChainIds,
          });
          activate(injected);
        }}
        walletType={WALLET_TYPE.metamask}
      />
      <WalletButton
        onClick={() => {
          const fortmatic = new FortmaticConnector({
            apiKey: 'pk_live_60FAF077265B4CBA',
            chainId: CHAIN_ID,
          });
          activate(fortmatic);
        }}
        walletType={WALLET_TYPE.fortmatic}
      />
      <WalletButton
        onClick={() => {
          const walletlink = new WalletConnectConnector({
            supportedChainIds,
            chainId: CHAIN_ID,
            rpc: {
              [CHAIN_ID]: config.app.jsonRpcUri,
            },
          });
          activate(walletlink);
        }}
        walletType={WALLET_TYPE.walletconnect}
      />
      <WalletButton
        onClick={() => {
          const walletlink = new WalletLinkConnector({
            appName: 'Nouns.WTF',
            appLogoUrl: 'https://nouns.wtf/static/media/logo.cdea1650.svg',
            url: config.app.jsonRpcUri,
            supportedChainIds,
          });
          activate(walletlink);
        }}
        walletType={WALLET_TYPE.coinbaseWallet}
      />
      <WalletButton
        onClick={() => {
          const injected = new InjectedConnector({
            supportedChainIds,
          });
          activate(injected);
        }}
        walletType={WALLET_TYPE.brave}
      />
      {/* <WalletButton
        onClick={() => {
          const ledger = new LedgerConnector({
            //TODO: refactor
            chainId: config.supportedChainId,
            url: config.rinkebyJsonRpc,
          });
          activate(ledger);
        }}
        walletType={WALLET_TYPE.ledger}
      /> */}
      <WalletButton
        onClick={() => {
          const trezor = new TrezorConnector({
            chainId: CHAIN_ID,
            url: config.app.jsonRpcUri,
            manifestAppUrl: 'https://nouns.wtf',
            manifestEmail: '[email protected]',
          });
          activate(trezor);
        }}
        walletType={WALLET_TYPE.trezor}
      />
      <div
        className={clsx(classes.clickable, classes.walletConnectData)}
        onClick={() => localStorage.removeItem('walletconnect')}
      >
        <Trans>Clear WalletConnect Data</Trans>
      </div>
    </div>
  );
  return (
    <Modal title={<Trans>Connect your wallet</Trans>} content={wallets} onDismiss={onDismiss} />
  );
}
Example #29
Source File: index.tsx    From dxvote with GNU Affero General Public License v3.0 4 votes vote down vote up
Web3ReactManager = ({ children }) => {
  const { context } = useContext();
  const { providerStore, blockchainStore } = context;

  const location = useLocation();
  const history = useHistory();
  const rpcUrls = useRpcUrls();

  // Overriding default fetch to check for RPC url and setting correct headers if matched
  const originalFetch = window.fetch;
  window.fetch = (url, opts): Promise<Response> => {
    if (rpcUrls && Object.values(rpcUrls).includes(url.toString()) && opts) {
      opts.headers = opts.headers || {
        'Content-Type': 'application/json',
      };
    }
    return originalFetch(url, opts);
  };

  const web3Context = useWeb3React();
  const {
    active: networkActive,
    error: networkError,
    chainId,
    account,
    connector,
    activate,
  } = web3Context;

  console.debug('[Web3ReactManager] Start of render', {
    web3Context,
  });

  // Make sure providerStore is synchronized with web3-react
  useEffect(() => {
    providerStore.setWeb3Context(web3Context);
  }, [web3Context]);

  // try to eagerly connect to a provider if possible
  const { triedEager, tryConnecting } = useEagerConnect();

  // If eager-connect failed, try to connect to network in the URL
  // If no chain in the URL, fallback to default chain
  useEffect(() => {
    if (triedEager && !networkActive && rpcUrls) {
      const chains = getChains(rpcUrls);
      const urlNetworkName = location.pathname.split('/')[1];
      const chainId =
        chains.find(chain => chain.name == urlNetworkName)?.id ||
        DEFAULT_CHAIN_ID;
      const networkConnector = getNetworkConnector(rpcUrls, chainId);

      activate(networkConnector, undefined, true).catch(e => {
        console.error(
          '[Web3ReactManager] Unable to activate network connector.',
          e
        );
      });
    }
  }, [triedEager, networkActive, activate, rpcUrls, location]);

  const prevChainId = usePrevious(chainId);
  const prevAccount = usePrevious(account);
  useEffect(() => {
    // Listen to chain / account changes and reset the app
    if (prevChainId !== chainId || prevAccount !== account) {
      try {
        providerStore.setWeb3Context(web3Context);
        context.reset();
        if (location.pathname !== '/cache') {
          blockchainStore.fetchData(web3Context, true);
        }
      } catch (e) {
        // Fallback if something goes wrong
        window.location.reload();
      }
    }
  }, [chainId, prevChainId, account, prevAccount]);

  // Setup listener to handle injected wallet events
  useEffect(() => {
    if (!window.ethereum) return () => {};

    const handleChainChange = (chainId: string) => {
      const chains = getChains();
      const chain = chains.find(
        chain => `0x${chain.id.toString(16)}` == chainId
      );

      // If currently connected to an injected wallet, keep synced with it
      if (connector instanceof InjectedConnector) {
        history.push(`/${chain.name}/proposals`);
      } else if (connector instanceof NetworkConnector) {
        const urlNetworkName = location.pathname.split('/')[1];
        if (urlNetworkName == chain.name) {
          tryConnecting();
        }
      }
    };

    window.ethereum.on('chainChanged', handleChainChange);

    return () => {
      window.ethereum?.removeListener('accountsChanged', handleChainChange);
    };
  }, [location, connector]);

  const urlNetworkName = useMemo(
    () => location.pathname.split('/')[1],
    [location]
  );
  const prevUrlNetworkName = usePrevious(urlNetworkName);
  if (
    urlNetworkName &&
    prevUrlNetworkName &&
    urlNetworkName !== prevUrlNetworkName
  ) {
    tryConnecting();
  }

  // Fetch user blockchain data on an interval using current params
  useInterval(
    async () => {
      if (networkActive) {
        if (location.pathname !== '/cache') {
          blockchainStore.fetchData(providerStore.getActiveWeb3React(), false);
        }
      }
    },
    networkActive ? BLOKCHAIN_FETCH_INTERVAL : 10
  );

  const Content = styled.div`
    margin: auto;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
    width: 85%;
  `;

  // on page load, do nothing until we've tried to connect to the injected connector
  if (!triedEager) {
    console.debug('[Web3ReactManager] Render: Eager load not tried');
    return (
      <ThemeProvider>
        <GlobalStyle />
        <Content>
          <LoadingNetworkHeader />
          <LoadingBox>
            <div className="loader">
              <PulsingIcon size={80} inactive={false} />
            </div>
          </LoadingBox>
        </Content>
      </ThemeProvider>
    );
  } else if (networkError) {
    console.debug(
      '[Web3ReactManager] Render: Network error, showing modal error.'
    );
    return null;
  } else {
    console.debug('[Web3ReactManager] Render: Render children', {
      networkActive,
    });
    return children;
  }
}