简体   繁体   中英

How to connect Metamask based on the input wallet adress

When I type a wallet address and press the Save button I want to show a Metamask sign in popup to that wallet.

for now, It's just randomly connects with the selected wallet. Basically, I want to be able to connect wallets with just wallet address.

profile.jsx

import React from "react";
import { useContext, MainContext } from "../hook/Context";
import Web3 from "web3";

const Profile = () => {
  const { data, setData } = useContext(MainContext);

  const detectCurrentProvider = () => {
    let provider;
    if (window.ethereum) {
      provider = window.ethereum;
    } else if (window.web3) {
      provider = window.web3.currentProvider;
    } else {
      alert(
        "Non-Ethereum browser detected. You should consider trying MetaMask!"
      );
    }
    return provider;
  };

  const onConnect = async (e) => {
    e.preventDefault();
    try {
      const currentProvider = detectCurrentProvider();
      if (currentProvider) {
        if (currentProvider !== window.ethereum) {
          alert(
            "Non-Ethereum browser detected. You should consider trying MetaMask!"
          );
        }
        await currentProvider.request({ method: "eth_requestAccounts" });
        const web3 = new Web3(currentProvider);
        const userAccount = await web3.eth.getAccounts();
        const chainId = await web3.eth.getChainId();
        const account = userAccount[0];
        let ethBalance = await web3.eth.getBalance(account); // Get wallet balance
        ethBalance = web3.utils.fromWei(ethBalance, "ether"); //Convert balance to wei
        setData(ethBalance, account, chainId);
        if (userAccount.length === 0) {
          console.log("Please connect to meta mask");
        }
      }
    } catch (err) {
      alert(
        "There was an error fetching your accounts. Make sure your Ethereum client is configured correctly."
      );
    }
  };

  return (
    <div className="container-fluid">
      <div className="wallets__wrapper">
        Your wallets:
        {data.account}
      </div>
      <form className="token__form" onSubmit={onConnect}>
        <input type="text" placeholder="Account Name" />
        <input type="text" placeholder="Wallet Adress" />
        <button className="add__btn">SAVE</button>
      </form>
    </div>
  );
};

export default Profile;

try to load web3 in this way, this will ask you to connect to metamask first(pop-up)

const getWeb3 = () => {
  return new Promise((resolve, reject) => {
    // Wait for loading completion to avoid race conditions with web3 injection timing.
    window.addEventListener("load", async () => {
      // Modern dapp browsers...
      if (window.ethereum) {
        const web3 = new Web3(window.ethereum);
        try {
          // Request account access if needed
          await window.ethereum.enable();
          // Acccounts now exposed
          resolve(web3);
        } catch (error) {
          reject(error);
        }
      }
      // Legacy dapp browsers...
      else if (window.web3) {
        // Use Mist/MetaMask's provider.
        const web3 = window.web3;
        console.log("Injected web3 detected.");
        resolve(web3);
      }
      // Fallback to localhost; use dev console port by default...
      else {
        const provider = new Web3.providers.HttpProvider(
          "http://localhost:9545"
        );
        const web3 = new Web3(provider);
        console.log("No web3 instance injected, using Local web3.");
        resolve(web3);
      }
    });
  });
};

load this in your useEffect:

useEffect(() => {
const init = async () => {
  const web3 = await getWeb3();
//set accounts ,etc to state from web3 by awaiting them 
const accounts = await web3.eth.getAccounts(); 
 }
init();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM