curl --request POST \
--url https://nd-828-700-214.p2pify.com/a9bca2f0f84b54086ceebe590316fff3 \
--header 'Content-Type: application/json' \
--data '{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_chainId"
}'
{
"jsonrpc": "<string>",
"id": 123,
"result": {}
}
curl --request POST \
--url https://nd-828-700-214.p2pify.com/a9bca2f0f84b54086ceebe590316fff3 \
--header 'Content-Type: application/json' \
--data '{
"id": 1,
"jsonrpc": "2.0",
"method": "eth_chainId"
}'
{
"jsonrpc": "<string>",
"id": 123,
"result": {}
}
none
quantity
— EIP-155 Chain IDeth_chainId
code examplesconst Web3 = require("web3");
const NODE_URL = "CHAINSTACK_NODE_URL";
const web3 = new Web3(NODE_URL);
async function getChainId() {
const chain = await web3.eth.getChainId();
console.log(chain);
}
getChainId();
eth_chainId
method in Polygon is to determine which chain a user is connected to when using a DApp with the MetaMask browser extension. This can be useful to provide a customized user experience based on the specific chain that the user is interacting with.
Here is an example of how the eth_chainId
method might be used in this context with MetaMask. Keep in mind that the Chain ID is returned as a hexadecimal value:
// Check which network is selected on MetaMask
async function checkChain() {
// Declare the desired chain ID to match
const desiredChainId = '0x89'; // Polygon mainnet chain ID
// Retrieve the current Chain ID selected by the user
ethereum.request({
method: 'eth_chainId'
}).then(chainId => {
// compare the actual chain ID it to the declared chain ID
if (chainId !== desiredChainId) {
console.log(`You are currently on the wrong network. Please switch to the mainnet.`);
// Call the promtSwitch function
promtSwitch()
} else {
console.log("This is the correct network")
}
})
}
// Prompt user to switch to a determined network based on the chain ID
async function promtSwitch() {
await window.ethereum.request({
method: 'wallet_switchEthereumChain',
params: [{
chainId: '0x89' // chainId must be in HEX with 0x in front
}],
});
}
checkChain
function is called to get the current chain ID using the Ethereum object provided by MetaMask. The chain ID is then checked to determine if the user is connected to the Polygon mainnet and calls the promtSwitch
function to prompt the user to switch chain in case the chain ID returned does not match the desiredChainId
constant.The chain ID information
The response is of type object
.
Was this page helpful?