admin管理员组

文章数量:1023230

I am developing an application that uses the MATIC token on the MATIC network. I want to make sure the user is connected to this network with MetaMask, is this possible?

Right now in my client.js attached to my html page, I just have the following:

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

The issue is that if the user tries to interact with other features of the website, they could attempt to use ETH, which could make them lose their token and just not have the feature work. So I want to prompt them to get onto the MATIC network.

Is there any way to get them onto this network automatically, without having them need to put it into MetaMask manually? Would help reduce friction.

This is the MATIC network I've been using on my backend server.js for this application:

const WEB3_PROVIDER = "; 
// /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.");
} 

I am developing an application that uses the MATIC token on the MATIC network. I want to make sure the user is connected to this network with MetaMask, is this possible?

Right now in my client.js attached to my html page, I just have the following:

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

The issue is that if the user tries to interact with other features of the website, they could attempt to use ETH, which could make them lose their token and just not have the feature work. So I want to prompt them to get onto the MATIC network.

Is there any way to get them onto this network automatically, without having them need to put it into MetaMask manually? Would help reduce friction.

This is the MATIC network I've been using on my backend server.js for this application:

const WEB3_PROVIDER = "https://polygon-rpc." 
// 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.");
} 
Share Improve this question edited Jan 24, 2023 at 18:53 Yilmaz 50.1k19 gold badges218 silver badges271 bronze badges asked Feb 10, 2022 at 20:11 JDSJDS 17k47 gold badges171 silver badges234 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

you can check user network like this using your web3 instance (web3 document):

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

in order to add network programmatically (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.'],
        blockExplorerUrls: ['https://www.polygonscan.']
    }],
})
.then(() => console.log('network added'))
.catch(() => console.log('could not add network'))

and if you want to set Metamask network programmatically (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')
    }
})

also you can listen chainChanged event on Metamask to detect when user changes Metamask network (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
})

write a mapping for metamask networks. You can find all the chains here: https://chainlist/

const NETWORKS = {
  1: "Ethereum Main Network",
  3: "Ropsten Test Network",
  5: "Goerli Test Network",
  42: "Kovan Test Network",
  56: "Binance Smart Chain",
  137: "Polygon Mainnet",
  1337: "Ganache",
};

set your target networK

// matic chain 137
const targetNetwork = NETWORKS[process.env.TARGET_CHAIN_ID];


const getNetwork= async () => {
      const chainId = await web3.eth.getChainId();
      // handle the error here
      if (!chainId) {
        throw new Error(
          "Cannot retrieve an account. Please refresh the browser"
        );
      }
      return NETWORKS[chainId];
    }
  );

write the logic

const connectedNetwork=getNetwork()
const supported=targetNetwork===connectedNetwork

if supported=true you are connected to the right network

I am developing an application that uses the MATIC token on the MATIC network. I want to make sure the user is connected to this network with MetaMask, is this possible?

Right now in my client.js attached to my html page, I just have the following:

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

The issue is that if the user tries to interact with other features of the website, they could attempt to use ETH, which could make them lose their token and just not have the feature work. So I want to prompt them to get onto the MATIC network.

Is there any way to get them onto this network automatically, without having them need to put it into MetaMask manually? Would help reduce friction.

This is the MATIC network I've been using on my backend server.js for this application:

const WEB3_PROVIDER = "; 
// /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.");
} 

I am developing an application that uses the MATIC token on the MATIC network. I want to make sure the user is connected to this network with MetaMask, is this possible?

Right now in my client.js attached to my html page, I just have the following:

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

The issue is that if the user tries to interact with other features of the website, they could attempt to use ETH, which could make them lose their token and just not have the feature work. So I want to prompt them to get onto the MATIC network.

Is there any way to get them onto this network automatically, without having them need to put it into MetaMask manually? Would help reduce friction.

This is the MATIC network I've been using on my backend server.js for this application:

const WEB3_PROVIDER = "https://polygon-rpc." 
// 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.");
} 
Share Improve this question edited Jan 24, 2023 at 18:53 Yilmaz 50.1k19 gold badges218 silver badges271 bronze badges asked Feb 10, 2022 at 20:11 JDSJDS 17k47 gold badges171 silver badges234 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

you can check user network like this using your web3 instance (web3 document):

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

in order to add network programmatically (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.'],
        blockExplorerUrls: ['https://www.polygonscan.']
    }],
})
.then(() => console.log('network added'))
.catch(() => console.log('could not add network'))

and if you want to set Metamask network programmatically (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')
    }
})

also you can listen chainChanged event on Metamask to detect when user changes Metamask network (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
})

write a mapping for metamask networks. You can find all the chains here: https://chainlist/

const NETWORKS = {
  1: "Ethereum Main Network",
  3: "Ropsten Test Network",
  5: "Goerli Test Network",
  42: "Kovan Test Network",
  56: "Binance Smart Chain",
  137: "Polygon Mainnet",
  1337: "Ganache",
};

set your target networK

// matic chain 137
const targetNetwork = NETWORKS[process.env.TARGET_CHAIN_ID];


const getNetwork= async () => {
      const chainId = await web3.eth.getChainId();
      // handle the error here
      if (!chainId) {
        throw new Error(
          "Cannot retrieve an account. Please refresh the browser"
        );
      }
      return NETWORKS[chainId];
    }
  );

write the logic

const connectedNetwork=getNetwork()
const supported=targetNetwork===connectedNetwork

if supported=true you are connected to the right network

本文标签: