Metamask

Metamask:wallet_addEthereumChain 在使用多邊形主網時不起作用,但適用於多邊形孟買

  • February 23, 2022

我試圖以程式方式切換使用者的元遮罩網路。使用wallet_addEthereumChain

為 Polygon mumbai 請求網路更改時它工作正常,但是在使用時它不起作用Polygon Mainet,我得到:Chain ID returned by RPC URL https://polygon-rpc.com does not match 0x137

如果我在元遮罩上手動添加網路,則使用相同的資訊。

  • 上面的程式碼適用於多邊形孟買
const { ethereum } = window;
await ethereum.request({
               id: 1,
               jsonrpc: "2.0",
               method: "wallet_addEthereumChain",
               params: [
                 {
                   chainId: "0x13881",
                   rpcUrls: ["https://rpc-mumbai.maticvigil.com"],
                   chainName: "Polygon Testnet Mumbai",
                   nativeCurrency: {
                     name: "tMATIC",
                     symbol: "tMATIC", // 2-6 characters long
                     decimals: 18,
                   },
                   blockExplorerUrls: ["https://mumbai.polygonscan.com/"],
                 },
               ],
             }); 
const { ethereum } = window;
await ethereum.request({
                 id: 1,
                 jsonrpc: "2.0",
                 method: "wallet_addEthereumChain",
                 params: [
                   {
                     chainId: "0x137",
                     rpcUrls:[  "https://polygon-rpc.com"],

                     chainName: "Polygon Mainnet",
                     nativeCurrency: {
                       name: "MATIC",
                       symbol: "MATIC", // 2-6 characters long
                       decimals: 18,
                     },
                     blockExplorerUrls: ["https://polygonscan.com/"],
                   },
                 ],
               });
  • 這是我發出請求時使用者打算在他的元遮罩錢包上獲取的內容的螢幕截圖。

在此處輸入圖像描述

嘗試使用 web3.utils.toHex() 函式將chainId轉換為十六進制:

chainId = '137'; chainId = web3.utils.toHex(chainId);

chainData = [{
   chainId: chainId,
   chainName: 'Matic(Polygon) Mainnet',
   nativeCurrency: { name: 'MATIC', symbol: 'MATIC', decimals: 18 },
   rpcUrls: ['https://polygon-rpc.com'],
   blockExplorerUrls: ['https://www.polygonscan.com'],
}];
import { utils } from 'ethers';

const networkMap = {
 POLYGON_MAINNET: {
   chainId: utils.hexValue(137), // '0x89'
   chainName: "Matic(Polygon) Mainnet", 
   nativeCurrency: { name: "MATIC", symbol: "MATIC", decimals: 18 },
   rpcUrls: ["https://polygon-rpc.com"],
   blockExplorerUrls: ["https://www.polygonscan.com/"],
 },
 MUMBAI_TESTNET: {
   chainId: utils.hexValue(80001), // '0x13881'
   chainName: "Matic(Polygon) Mumbai Testnet",
   nativeCurrency: { name: "tMATIC", symbol: "tMATIC", decimals: 18 },
   rpcUrls: ["https://rpc-mumbai.maticvigil.com"],
   blockExplorerUrls: ["https://mumbai.polygonscan.com/"],
 },
};


await window.ethereum.request({
   method: "wallet_addEthereumChain",
   params: [networkMap.MUMBAI_TESTNET],
});

引用自:https://ethereum.stackexchange.com/questions/115565