What does this command does "web3.setProvider(provider)"? Does it helps one to connect peers to a node? What is a "provider"?


To use the web3 object, you need to specify where and how to connect to an ethereum node.

'where' can be localhost or an external provider such as infura.io or etherscan.io

'how' can be http or websocket, etc.

Once you have set this value e.g. var web3 = new Web3(new Web3.providers.WebsocketProvider("ws://localhost:7545")) then the web3 object will know which protocol to use and which hostname to contact to get the block data for the blockchain or where to send transaction calls to.

| improve this answer | |

I think we can skip this if we are using Metamask only. Since Metamask would set web3. If you are using Metamask all you need to do is check if Metamask is working fine and you are logged-in to Metamask and Metamask has connected to the network.

if (typeof web3 !== 'undefined') {
    web3 = new Web3(web3.currentProvider);     
} else {    
    console.log('Error: web3 is "undefined". Is metamask working? if yes, Try page refresh');

netId = web3.version.network;
if ( isNaN(netId) || !netId ) {
    console.log('Error: web3.version.network not detected. Are you logged-in to metamask? if yes, Try page refresh');
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.