My Image
CoursesQuizzesProblemsContestsSmartBooks
Contest!

No results found

LOGINREGISTER
My ProgressCoursesQuizzesProblemsContestsSmartbooks
Published on 12 Aug 2021
Web3 Providers
We will look at web3 providers in detail
img
Aniket Savji
0
Like
2627

Introduction

The provider helps web3 dapps to talk or interact with the blockchain. These Providers take JSON-RPC requests and return the response. HTTP , Web Socket , IPC socket based server takes this request and returns the response. Simply, Web3 Provider is a server/website running geth or parity node which talks to Ethereum network. 

An Ethereum node (like geth or parity) is a program which serves as a node for the Ethereum blockchain, and through which a user can mine Ether, create software which runs on the EVM and is part of ethereum network.

Web3's web.providers helps dapps or users to interact with those nodes engaged in Ethereum consensus.  We will take a look at different web3 functions it provides.

 

web3.providers

Providers

Web3 Providers are of three types,

  • HTTP Provider
  • Websocket Provider
  • IPC Provider

a) Http Provider

As name suggests http provider is a node which communicates through http protocols. Http has request response messaging pattern , thus to interact with a http provider or communicate with it request must be send everytime to gete response.

HttpProvider() takes two arguments,

  • Rpc url  (Required)
  • Options (optional)

We can initialise http provider as follows :

const Web3 = require('web3');

var options = {
    keepAlive: true,
    withCredentials: false,
    timeout: 20000, // ms
    headers: [
        {
            name: 'Access-Control-Allow-Origin',
            value: '*'
        },
        {
            ...
        }
    ],
    agent: {
        http: http.Agent(...),
        baseUrl: ''
    }
};

var provider = new Web3.providers.HttpProvider('http://localhost:8545', options); 

Note that rpc url can be any http provider url , http://localhost:8545 is used as an example which implies that our provider is a local node serving at port 8545.  

b) Web Socket Provider

Websocket Provider uses web socket communication protocol over TCP that enables bidirectional communication between client and server. Unlike with HTTP protocol we do not need to do use request response messaging pattern. Once the connection is established, the server can send as many requests as it prefers.

WebsocketProvider()  also takes two arguments,

  • Web socket url  (Required)
  • Options (optional)

We can initialise Web socket provider as follows :

const Web3 = require('web3');

const options = {
    timeout: 30000, // ms

    // Useful for credentialed urls, e.g: ws://username:password@localhost:8546
    headers: {
      authorization: 'Basic username:password'
    },

    clientConfig: {
      // Useful if requests are large
      maxReceivedFrameSize: 100000000,   // bytes - default: 1MiB
      maxReceivedMessageSize: 100000000, // bytes - default: 8MiB

      // Useful to keep a connection alive
      keepalive: true,
      keepaliveInterval: 60000 // ms
    },

    // Enable auto reconnection
    reconnect: {
        auto: true,
        delay: 5000, // ms
        maxAttempts: 5,
        onTimeout: false
    }
};

const ws = new Web3.providers.WebsocketProvider('ws://localhost:8546', options);

c) IPC Provider

The IPC provider is running a local node. It gives the most secure connection.

var Web3 = require('web3');
var net = require('net');

var ipc_provider = new Web3.providers.IpcProvider('<Path to geth.ipc>', net); 

 

Functions

a) setProvider()

We can change provider for its module 

var Web3 = require('web3');
var web3 = new Web3('http://localhost:8545');
// or
var web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'));

// change provider
web3.setProvider('ws://localhost:8546');
// or
web3.setProvider(new Web3.providers.WebsocketProvider('ws://localhost:8546'));

b) givenProvider

When using web3.js in an Ethereum compatible browser, it will set with the current native provider by that browser. Will return the given provider by the (browser) environment, otherwise null.

var Web3 = require('web3');

var web3 = new Web3(Web3.givenProvider);

c) currentProvider

This will return the current provider, otherwise null.

var Web3 = require('web3');

var web3 = new Web3(Web3.currentProvider);

 

Enjoyed the SmartBook?
Like
logo
contact@dapp-world.com
Katraj, Pune, Maharashtra, India - 411048

Follow Us

linkedintwitteryoutubediscordinstagram

Products

  • SmartBooks
  • Courses
  • Quizzes
  • Assessments

Support

  • Contact Us
  • FAQ
  • Privacy Policy
  • T&C

Backed By

ah! ventures

Copyright 2023 - All Rights Reserved.

Recommended from DAppWorld
img
1 May 2021
How to connect Ganache with Metamask and deploy Smart contracts on remix without
Set up your development environment with (Metamask + Ganache + Remix) and skip truffle :)
3 min read
11492
5
img
8 Jul 2021
How to interact with smart contarct from backend node js
call and send functions from backend server side using nodejs
3 min read
8068
2
img
18 Aug 2021
Send transaction with web3 using python
Introduction to web3.py and sending transaction on testnet
3 min read
6215
5
img
5 Aug 2021
Deploy Smart Contract on Polygon POS using Hardhat
how to deploy smart contracts on polygon pos chain using hardhat both mainnet and testnet ?
3 min read
5533
3