【问题标题】:MetaMask Web3: is there any way to make sure website user is connected to a particular network?MetaMask Web3:有什么方法可以确保网站用户连接到特定网络?
【发布时间】:2022-07-26 01:34:38
【问题描述】:

我正在开发一个在 MATIC 网络上使用 MATIC 令牌的应用程序。我想确保用户使用 MetaMask 连接到这个网络,这可能吗?

现在在我的 html 页面所附的 client.js 中,我只有以下内容:

let accounts, web3, contract;

if (typeof window.ethereum !== 'undefined') {
  console.log('MetaMask is installed!');
} else {
    alert("Hello! Consider adding an ethereum wallet such as MetaMask to fully use this website.");
}
accounts = ethereum.request({ method: 'eth_requestAccounts' });
web3 = new Web3();

问题在于,如果用户尝试与网站的其他功能进行交互,他们可能会尝试使用 ETH,这可能会使他们失去代币并且无法使用该功能。所以我想提示他们进入 MATIC 网络。

有没有办法让他们自动进入这个网络,而不需要他们手动将它放入 MetaMask?有助于减少摩擦。

这是我在后端使用的 MATIC 网络 server.js 用于此应用程序:

const WEB3_PROVIDER = "https://polygon-rpc.com" 
// https://blog.polygon.technology/polygon-rpc-gateway-will-provide-a-free-high-performance-connection-to-the-polygon-pos-blockchain/

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);
    console.log("web3 already initialized.");
} else {
    // set the provider you want from Web3.providers
    web3 = new Web3(new Web3.providers.HttpProvider(WEB3_PROVIDER));
    console.log("New web3 object initialized.");
} 

【问题讨论】:

    标签: javascript web3js metamask


    【解决方案1】:

    您可以使用您的 web3 实例 (web3 document) 像这样检查用户网络:

    const yourNetworkId = '137'
    web3.eth.net.getId()
    .then((networkId) => {
      if (networkId != yourNetworkId) {
        // MetaMask network is wrong
      }
    })
    .catch((err) => {
      // unable to retrieve network id
    });
    

    为了以编程方式添加网络 (metamask document):

    ethereum.request({
        method: 'wallet_addEthereumChain',
        params: [{ 
            chainId: web3.utils.toHex('137'),
            chainName: 'Polygon',
            nativeCurrency: {
                name: 'MATIC',
                symbol: 'MATIC',
                decimals: 18
            },
            rpcUrls: ['https://polygon-rpc.com'],
            blockExplorerUrls: ['https://www.polygonscan.com']
        }],
    })
    .then(() => console.log('network added'))
    .catch(() => console.log('could not add network'))
    

    如果您想以编程方式设置 Metamask 网络 (Metamask document):

    ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: web3.utils.toHex('137') }],
    })
    .then(() => console.log('network has been set'))
    .catch((e) => {
        if (e.code === 4902) {
           console.log('network is not available, add it')
        } else {
           console.log('could not set network')
        }
    })
    
    

    您也可以在 Metamask 上监听 chainChanged 事件以检测用户何时更改 Metamask 网络 (metamask document):

    ethereum.on("chainChanged", () => {
        // if network was wrong, you can open a modal to disable activity and ask
        // user to change network back to Polygon or even change it yourself on 
        // user clicking a button, but i don't suggest setting network by yourself
        // without users permission because users may using other dApps on other
        // networks at the same time which changing network immediately on chainChanged
        // would be a bad UX
    })
    

    【讨论】:

    • 是否可以检查是否已经添加了特定网络?
    • @PASH,我不这么认为。但是您可以使用wallet_switchEthereumChain 处理它,结帐docs.metamask.io/guide/…
    • 如果用户还没有输入密码怎么办?有什么办法可以处理这种情况吗?
    • 嘿@eddy,您可以请求更改网络,Metamask 会提示用户确认,但即使这样用户也必须输入密码才能确认。无论您想做什么都需要用户确认,所以我认为最好在连接到 Metamask 后处理它(更好的 UX)。
    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 2019-05-24
    • 2021-12-17
    • 2017-03-25
    • 1970-01-01
    • 1970-01-01
    • 2010-10-05
    • 2018-08-24
    相关资源
    最近更新 更多