Search code examples
reactjsnext.jsethereumbinanceethers.js

Unsupported keys: rpcUrl when adding Binance smart chain to metamask using ethers.js


I wrote below code to add/switch network to Binance mainnet but it is not working. Why does not it work? I used web3 provider. Is it possible to add binance main net using web3?

try {
    // check if the chain to connect to is installed
    await ethereum.request({
        method: 'wallet_switchEthereumChain',
        params: [{ chainId: '0x38' }], // chainId must be in hexadecimal numbers
    });
} catch (error) {
    // This error code indicates that the chain has not been added to MetaMask
    // if it is not, then install it into the user MetaMask
    
    if (error.code === 4902) {
        try {
            await ethereum.request({
                method: 'wallet_addEthereumChain',
                params: [
                    {
                        chainId: '0x38',
                        rpcUrl: 'https://bsc-dataseed.binance.org/',
                    },
                ],
            });
        } catch (addError) {
            console.error(addError)
            toast.error("Operation failed. Choose the Binance Smart Chain on your wallet")
            return
        }
    } else {
        console.error(error)
        toast.error("Operation failed. Choose the Binance Smart Chain on your wallet")
        return
    }
    
}

Error:

MetaMask - RPC Error: Received unexpected keys on object parameter. Unsupported keys:
rpcUrl Objectcode: -32602message: "Received unexpected keys on object parameter. Unsupported keys:\nrpcUrl"[[Prototype]]: Objectconstructor: ƒ Object()hasOwnProperty: ƒ hasOwnProperty()isPrototypeOf: ƒ isPrototypeOf()propertyIsEnumerable: ƒ propertyIsEnumerable()toLocaleString: ƒ toLocaleString()toString: ƒ toString()valueOf: ƒ valueOf()__defineGetter__: ƒ __defineGetter__()__defineSetter__: ƒ __defineSetter__()__lookupGetter__: ƒ __lookupGetter__()__lookupSetter__: ƒ __lookupSetter__()__proto__: (...)get __proto__: ƒ __proto__()set __proto__: ƒ __proto__()
(anonymous) @ inpage.js:1

Solution

  • Just faced the same problem. Correct params for 'wallet_addEthereumChain' are the following:

    params: [
        {
            chainId: '0x38',
            rpcUrls: ['https://bsc-dataseed.binance.org/'],
            chainName: 'BSC Mainnet'
        }
    ]
    

    More here https://docs.metamask.io/guide/rpc-api.html#unrestricted-methods