简体   繁体   English

如何根据输入的钱包地址连接Metamask

[英]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.当我输入钱包地址并按下“保存”按钮时,我想向该钱包显示一个 Metamask 登录弹出窗口。

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配置文件.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)尝试以这种方式加载 web3,这将要求您先连接到元掩码(弹出窗口)

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中加载它:

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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 React 上的 bsc 测试网上将 Metamask 钱包地址连接到 web3 - How to connect Metamask wallet address to web3 on bsc testnet on React angular uing web3中如何连接钱包MetaMask? - How to connect with wallet MetaMask in angular uing web3? 如何断开 Angular 中的 Metamask 钱包 - How to disconnect Metamask Wallet in Angular 如何从独立的 node.js 应用程序使用 ethers.js 连接到 Metamask 钱包? - How can I connect to a Metamask wallet using ethers.js from a standalone node.js application? 如何将 metamask 连接到 dapp? - How to connect metamask to dapp? 每当我单击连接元掩码按钮时,为什么它会连接 coinbase 钱包? - Whenever i click on connect metamask button why it connects the coinbase wallet? Metamask (web3) 连接钱包并发送交易 - 如何将区块链更改为 Bianance 智能链 (BEP-20) 网络而不是以太坊? - Metamask (web3) connect wallet and send transaction - how to change blockchain to Bianance smart chain (BEP-20) network instead of Ethereum? 如何将 Metamask 连接到 Rootstock.networks? - How to connect Metamask to Rootstock networks? 如何在 React 的元掩码钱包中获取 BNB 代币余额? - How to get BNB token balance in metamask wallet in React? 如何将 ethers.js 与元掩码连接起来? - How to connect ethers.js with metamask?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM