MetaMask recently announced that it had opened up its custom networks API for developers to use. This means that you can help users connect to your non-Ethereum network much easier. Rather than the user typing in the Network Name, RPC URL, ChainId, etc., you can fill it out for them!

Is your coin on the Ethereum network? Well then, how about adding the coin directly to their wallet via one click? No more, “copy this address and paste it!”

wallet_addEthereumChain

First, test it out yourself with the RSK networks, or check out the code on GitHub.

As the developer, we set the chain’s parameters. This is an example of connecting to the RSK Mainnet. Further down in the code, we can have a button, when clicked, adds the network:

const addNetwork = () => {
  const params = [{
    chainId: '0x1e',
    chainName: 'RSK Mainnet',
    nativeCurrency: {
      name: 'RSK BTC',
      symbol: 'RBTC',
      decimals: 18
    },
    rpcUrls: ['https://public-node.rsk.co'],
    blockExplorerUrls: ['https://explorer.rsk.co']
  }]

  window.ethereum.request({ method: 'wallet_addEthereumChain', params })
    .then(() => console.log('Success'))
    .catch((error: Error) => console.log("Error", error.message))
}

return (
  <button onClick={addNetwork}>Add RSK Mainnet to Metamask</button>
)

After clicking on the button, MetaMask will ask the user permission to add the network. After the user clicks “Approve”, a second message asking the user to switch to that network is shown:

Add RSK Mainnet to MetaMask with wallet_addEthereumChain

MetaMask uses the chainId property to detect if the network has been added. If the network exists and the user is not on it, only the switch popup will show.

wallet_watchAsset

Let’s now add an ERC20 token to the user’s wallet. After checking that the user is on the correct network, via the chainId, we can then use the following code to add the token:

const params = addToken({
  type: 'ERC20',
  options: {
    address: '0x2acc95758f8b5f583470ba265eb685a8f45fc9d5',
    symbol: 'RIF',
    decimals: 18,
    image: 'https://s2.coinmarketcap.com/static/img/coins/64x64/3701.png'
  }
})

window.ethereum.request({ method: 'wallet_watchAsset', params })
  .then(() => setLog([...log, 'Success, Token added!']))
  .catch((error: Error) => setLog([...log, `Error: ${error.message}`]))

Add Token

In closing

There is a full React code example on GitHub, specifically, the src/App.tsx file. As of the time of writing, there is no way to detect if a user has a network installed. Also, MetaMask does not let you set an icon for the native currency, even though it is mentioned in the specification.

Resources