【问题标题】:How to change network in metamask using react js如何使用 React js 更改元掩码中的网络
【发布时间】:2021-05-19 05:53:45
【问题描述】:

我正在开发我的第一个 Dapp,为此我使用了 metamask 和 web3。到目前为止,我能够获取我的钱包余额并将帐户连接到 metamask。现在我正在尝试在两个网络之间切换,我正在使用 handleChainChanged,我也在传递 chainId 和 Networkversion,但是它给了我错误。我不确定从 changeNetwork 函数返回任何内容,或者我只需要传递 chainId 和 Networkversion。

import { useStoreApi } from "./storeApi";
import { useState } from "react";
import useWeb3 from "./useWeb3";
import { Button, TextField } from "@material-ui/core";

import "./App.css";

function App() {
  const { balance, address, message, setAddress, setBalance } = useStoreApi();
  const web3 = useWeb3();

  // get user account on button click
  const getUserAccount = async () => {
    if (window.ethereum) {
      try {
        await window.ethereum.enable();
        web3.eth.getAccounts().then((accounts) => {
          setAddress(accounts[0]);
          updateBalance(accounts[0]);
          console.log(accounts);
        });
      } catch (error) {
        console.error(error);
      }
    } else {
      alert("Metamask extensions not detected!");
    }
    web3.eth.getChainId().then(console.log);
  };

  const updateBalance = async (fromAddress) => {
    await web3.eth.getBalance(fromAddress).then((value) => {
      setBalance(web3.utils.fromWei(value, "ether"));
    });
  };

  const changeNetwork = async () => {
    if (window.ethereum) {
      try {
        await window.ethereum.enable();
        window.ethereum._handleChainChanged({
          chainId: 0x1,
          networkVersion: 1,
        });
      } catch (error) {
        console.error(error);
      }
    }
  };

  return (
    <div className="App">
      <header className="App-header">
        {address ? (
          <>
            <p> Balance: {balance} </p>
          </>
        ) : null}
        <Button
          onClick={() => getUserAccount()}
          variant="contained"
          color="primary"
        >
          Connect your account
        </Button>
        <Button onClick={changeNetwork} variant="contained" color="primary">
          Switch to mainnet ethereum
        </Button>

      </header>
    </div>
  );
}

export default App;

【问题讨论】:

    标签: javascript reactjs web3


    【解决方案1】:

    您可以使用 Metamask 的 RPC API 的 wallet_switchEthereumChain 方法

    访问:https://docs.metamask.io/guide/rpc-api.html#wallet-switchethereumchain

    【讨论】:

      【解决方案2】:

      如果用户没有添加所需的网络怎么办?这是一个尝试切换的扩展版本,否则将网络添加到 Metamask:

      const chainId = 137 // Polygon Mainnet
      
      if (window.ethereum.networkVersion !== chainId) {
            try {
              await window.ethereum.request({
                method: 'wallet_switchEthereumChain',
                params: [{ chainId: web3.utils.toHex(chainId) }],
              });
            } catch (err) {
                // This error code indicates that the chain has not been added to MetaMask.
              if (err.code === 4902) {
                await window.ethereum.request({
                  method: 'wallet_addEthereumChain',
                  params: [
                    {
                      chainName: 'Polygon Mainnet',
                      chainId: web3.utils.toHex(chainId),
                      nativeCurrency: { name: 'MATIC', decimals: 18, symbol: 'MATIC' },
                      rpcUrls: ['https://polygon-rpc.com/'],
                    },
                  ],
                });
              }
            }
          }
      

      【讨论】:

        【解决方案3】:
          const changeNetwork = async () => {
        if (window.ethereum) {
          try {
            await window.ethereum.request({
            method: 'wallet_switchEthereumChain',
              params: [{ chainId: Web3.utils.toHex(chainId) }],
            });
            });
          } catch (error) {
            console.error(error);
          }
        }
        changeNetwork()
        

        【讨论】:

          猜你喜欢
          • 2021-08-04
          • 1970-01-01
          • 1970-01-01
          • 2019-02-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-06-16
          相关资源
          最近更新 更多