MetaMask API

Detecting that MetaMask is installed and adding additional networks and custom tokens easily make a great dApp user experience, specially those who are not technically skilled. It is important to streamline the onboarding process as much as you can to make it easier for consumers to operate your application. This guide explains how to build a simple button for your front-end application that will automatically add Velocity to MetaMask.

Summary of actions​

  1. Detect MetaMask or propose its installation

  2. Detect ChainId, and propose to add Velocity if needed

  3. Detect Account, and propose to connect if needed

Detect MetaMask​

if (typeof window.ethereum !== 'undefined') {
  console.log('MetaMask is installed!');
  //TODO: propose users to install MetaMask
}

Detect Velocity​

The following code includes all the parameters needed by MetaMask to add Velocity to its networks programmatically

var VELOCITY_MAINNET_PARAMS = {
    chainId: "**TBD**",
    chainName: "Velocity",
    nativeCurrency: {
        name: "Velocity",
        symbol: "VLCT",
        decimals: 18,
    },
    rpcUrls: ["https://rpc.velocitybtc.com/"],
    blockExplorerUrls: ["https://scan.velocitybtc.com/"],
}

var addVelocityToMetaMask = function() {
    window.ethereum.request({
        method: "wallet_addEthereumChain",
        params: [VELOCITY_MAINNET_PARAMS ],
    })
    .catch((error) => {
        console.log(error);
    });
};

Detect account​

Our dApps need access to the user's account, follow this code example to get it:

Add Custom Token to MetaMask​

In addition to directing the user to manually import tokens using the MetaMask UI, you can add code to your dApp's front end to prompt the user to add it to their MetaMask wallet automatically. This can be done using the wallet_watchAsset method. To do so, add the following code to your dApp's front end:

More info​

Last updated