4

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

2 Answers 2

1

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.

1

"provider" is a reference to Ethereum node providers

A node is essentially a program running on a single computer that allows you to connect with the rest of the blockchain network. It peers with other nodes to send information back and forth, checks that transactions sent between people are valid, and stores important information about the state of the blockchain.

Since the blockchain is completely decentralized, you need to either (1) run a node, or (2) use a node provider in order to communicate with the rest of the network, i.e. send transactions, make updates, read state, etc.

Here are some examples of providers:

Here are some examples of how to use them in your web3 initialization:

// Set Alchemy Provider
web3.setProvider("https://eth-mainnet.alchemyapi.io/v2/<api-key>");

// Set Infura Provider
web3.setProvider("https://mainnet.infura.io/v3/<api-key>");

// Set Quicknode Provider
web3.setProvider("https://<project-name>.quiknode.pro/<api-hash>");

You can read more about web3.setProvider here: https://web3js.readthedocs.io/en/v1.2.11/web3-eth.html?highlight=providers#configuration

There are options to configure http providers and websocket providers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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