Advertisement
rezacute

_app.tsx

Jul 15th, 2022
1,143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import "../styles/globals.css";
  2. import type { AppProps } from "next/app";
  3. import { useEffect, useState } from "react";
  4. import { ethers } from "ethers";
  5.  
  6. function MyApp({ Component, pageProps }: AppProps) {
  7.   const [loadingState, setLoadingState] = useState("not-loaded");
  8.  
  9.   async function connectWallet() {
  10.     // A Web3Provider wraps a standard Web3 provider, which is
  11.     // what MetaMask injects as window.ethereum into each page
  12.     const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
  13.  
  14.     // MetaMask requires requesting permission to connect users accounts
  15.     await provider.send("eth_requestAccounts", [])
  16.  
  17.     // The MetaMask plugin also allows signing transactions to
  18.     // send ether and pay to change state within the blockchain.
  19.     // For this, you need the account signer...
  20.     const signer = provider.getSigner();
  21.     const { chainId } = await provider.getNetwork();
  22.     console.log(chainId);
  23.  
  24.     if (chainId != 137) {
  25.       window.ethereum
  26.         .request({
  27.           method: "wallet_addEthereumChain",
  28.           params: [
  29.             {
  30.               chainId: "0x89",
  31.               rpcUrls: ["https://rpc-mainnet.matic.network/"],
  32.               chainName: "Matic Mainnet",
  33.               nativeCurrency: {
  34.                 name: "MATIC",
  35.                 symbol: "MATIC",
  36.                 decimals: 18,
  37.               },
  38.               blockExplorerUrls: ["https://polygonscan.com/"],
  39.             },
  40.           ],
  41.         })
  42.         .catch((e) => {
  43.           if (e.code === -32002) {
  44.             //user rejected the transaction
  45.             setLoadingState("error");
  46.           } else {
  47.             console.log(e);
  48.           }
  49.         });
  50.     } else {
  51.       setLoadingState("OK");
  52.     }
  53.     provider.on("network", (newNetwork, oldNetwork) => {
  54.       // When a Provider makes its initial connection, it emits a "network"
  55.       // event with a null oldNetwork along with the newNetwork. So, if the
  56.       // oldNetwork exists, it represents a changing network
  57.       if (oldNetwork) {
  58.         window.location.reload();
  59.       }
  60.     });
  61.   }
  62.  
  63.   useEffect(() => {
  64.     connectWallet();
  65.   }, []);
  66.   return loadingState == "error" ? (
  67.     <div>error</div>
  68.   ) : (
  69.     <Component {...pageProps} />
  70.   );
  71. }
  72.  
  73. export default MyApp;
  74.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement