Summary
The easiest way, is to check the chainId
of the provider.
const chainId = await provider.request({ method: 'eth_chainId' })
if(chainId == 137){
// do something
}
Please note, that you used to be able to just do ethereum.chainId
or provider.chainId
, but it's recently been deprecated.
if(ethereum.chainId == 137){
// do something
}
The Extra Mile
What you can do if they are not on the chain you want, is request to switch chains. You'll need to use the hex '0x89' since that's the hex of the Polygon chain ID of 137.
await provider.request({
method: 'wallet_switchEthereumChain',
params: [{ chainId: '0x89' }]
})
This may throw an error as they might not have the polygon chain in their metamask. One solution is to offer to add it from your front end, as such:
await provider.request({
method: 'wallet_addEthereumChain',
params: [{
chainName: 'Polygon Mainnet',
chainId: '0x89',
nativeCurrency: { name: 'MATIC', decimals: 18, symbol: 'MATIC' },
rpcUrls: ['https://polygon-rpc.com/']
}]
})
Note: I don't always recommend this, as public RPCs have been known to not be very reliable.
Full Example of detecting chainId
in HTML
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<button id="findIdButton">Find Chain Id</button>
</body>
<script src="https://unpkg.com/@metamask/detect-provider/dist/detect-provider.min.js"></script>
<script type="text/javascript">
const findIdButton = document.getElementById("findIdButton")
findIdButton.onclick = findChainId
async function findChainId(){
const provider = await detectEthereumProvider()
if (provider) {
console.log(provider.chainId)
} else {
console.log("No provider found...")
}
}
</script>
</html>
Full Example of detecting chainId
in NextJS (ReactJS)
import type { NextPage } from "next";
import detectEthereumProvider from "@metamask/detect-provider";
const Home: NextPage = () => {
async function findId() {
const provider = (await detectEthereumProvider()) as any;
if (provider) {
const chainId = await provider.request({ method: "eth_chainId" });
console.log(chainId);
} else {
console.log("No provider found...");
}
}
return (
<div>
<button onClick={findId}>Find ChainId</button>
</div>
);
};
export default Home;