I would like to have a button that switches between main net and ropsten on my app, in order to do so I need to programatically change the current network with MetaMask. But I cannot find aby reference about this. Do you guys have any idea on how to achieve this?
-
I saw some modern apps that cause metamask to open a dialogue in Metamask asking for permission to change to a specific network. Anyone knows how to do this?– Manuel AraozSep 18, 2021 at 2:45
1 Answer
You will need to prompt the users to change their network via MetaMask.
Assuming web3 is an initialised instance of the Web3 library with a provider:
import Web3 from "web3";
const FALLBACK_WEB3_PROVIDER = process.env.REACT_APP_NETWORK || 'http://0.0.0.0:8545';
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(
FALLBACK_WEB3_PROVIDER
);
const web3 = new Web3(provider);
console.log("No web3 instance injected, using Infura/Local web3.");
resolve(web3);
}
});
});
}
const detectEthereumNetwork = async () => {
const web3 = await getWeb3();
web3.eth.net.getNetworkType().then(async (netId) => {
// Do something based on which network ID the user is connected to
});
}
detectEthereumNetwork();
-
1
-
It would be done where the "// Do something based on which network ID the user is connected to" comment is, based on the network ID. But this code is quite dated now, I'd recommend using something like github.com/EthWorks/useDApp nowadays– JaySep 30, 2021 at 11:43