Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import "../styles/globals.css";
- import type { AppProps } from "next/app";
- import { useEffect, useState } from "react";
- import { ethers } from "ethers";
- function MyApp({ Component, pageProps }: AppProps) {
- const [loadingState, setLoadingState] = useState("not-loaded");
- async function connectWallet() {
- // A Web3Provider wraps a standard Web3 provider, which is
- // what MetaMask injects as window.ethereum into each page
- const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
- // MetaMask requires requesting permission to connect users accounts
- await provider.send("eth_requestAccounts", [])
- // The MetaMask plugin also allows signing transactions to
- // send ether and pay to change state within the blockchain.
- // For this, you need the account signer...
- const signer = provider.getSigner();
- const { chainId } = await provider.getNetwork();
- console.log(chainId);
- if (chainId != 137) {
- window.ethereum
- .request({
- method: "wallet_addEthereumChain",
- params: [
- {
- chainId: "0x89",
- rpcUrls: ["https://rpc-mainnet.matic.network/"],
- chainName: "Matic Mainnet",
- nativeCurrency: {
- name: "MATIC",
- symbol: "MATIC",
- decimals: 18,
- },
- blockExplorerUrls: ["https://polygonscan.com/"],
- },
- ],
- })
- .catch((e) => {
- if (e.code === -32002) {
- //user rejected the transaction
- setLoadingState("error");
- } else {
- console.log(e);
- }
- });
- } else {
- setLoadingState("OK");
- }
- provider.on("network", (newNetwork, oldNetwork) => {
- // When a Provider makes its initial connection, it emits a "network"
- // event with a null oldNetwork along with the newNetwork. So, if the
- // oldNetwork exists, it represents a changing network
- if (oldNetwork) {
- window.location.reload();
- }
- });
- }
- useEffect(() => {
- connectWallet();
- }, []);
- return loadingState == "error" ? (
- <div>error</div>
- ) : (
- <Component {...pageProps} />
- );
- }
- export default MyApp;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement