DEV Community

Cover image for Ethereum JavaScript API- web3.js
Mansoor Ahmed
Mansoor Ahmed

Posted on

Ethereum JavaScript API- web3.js

Introduction
In this post, we will discuss how to get started using the Web3.js library. Ethereum JavaScript API web3.js is an assembly of libraries. It permits us to relate with a local or remote Ethereum node using HTTP, IPC or WebSocket.
Web3.js allows us to accomplish the responsibility of developing clients that interact with The Ethereum Blockchain. It is a collection of libraries that enable us to do activities like;
Direct Ether from one account to another
Deliver and write data from smart contracts
Make smart contracts, and
So much more
Description
The web3.js library is an open-source JavaScript library. It is made by the Ethereum Foundation. It comprises functions to connect with an Ethereum node through the JavaScript Object Notation — Remote Procedure Call (JSON-RPC) protocol. It is a JavaScript library that enables a developer to interact with the Ethereum blockchain. Web3.js is at present on version 1.2.9. It is a buildup of four modules.
What is a module?
Module in JavaScript is code that has precise functionality within a larger program. Modules would be self-contained. Therefore, the overall library, program, or application would not stop working if we eliminate a module from a library, program, or application.
Modules make up web3.js
Web3.js has a key class called web3. The majority of the functionality of the library is originated within this class. The following are five additional modules that makeup web3js:
web3-eth
The web3-eth module holds functions that permit a user of web3.js to interact with the Ethereum blockchain. These functions are intelligent to interact with;
Smart contracts
Externally-owned accounts
Nodes
Mined blocks
Three explanatory instances are given away below:
eth.getBalance enables us to become the ETH balance of an address at a given block.
eth.signTransaction permits us to sign a transaction.
eth.sendSignedTransaction allows us to direct a signed transaction to the Ethereum blockchain.
web3-shh
The web3-shh module permits us to relate with the Whisper protocol. Whisper is a messaging protocol. It is designed to broadcast messages simply and for low-level asynchronous communication. Two descriptive illustrations are shown below:
shh.post uprights a whisper message to the network.
shh.subscribe makes a subscription to incoming whisper messages.
web3-bzz
The web3-bzz module enables us to interact with Swarm. Swarm is a decentralized storage platform. It is also a content distribution service. It may serve as a home to store files for example images or videos for our decentralized application. Two descriptive examples are given away below:
bzz. upload permits us to upload files and folders to Swarm
bzz. the download enables us to download files and folders from Swarm
web3-net
The web3-net module permits us to interrelate with the network properties of an Ethereum node. By using web3-net would allow us to find out information about the node. Two illustrative instances are given below:
.net.getID proceeds the network ID
.net.getPeerCount proceeds the number of peers that the node is associated with.
web3-utils
The web3-utils module delivers us by utility functions. That we can use within an Ethereum Dapp along with other web3.js modules. A utility function is a returnable function to style writing code simple that is common in JavaScript and other programming languages. Web3-utils contains utility functions. That changes numbers, confirm if a value happens in a certain condition, and search datasets. Three descriptive illustrations are shown below:
utils.toWei changes Ether to Wei.
utils.hexToNumberString changes a hexadecimal value to a string.
utils. address forms if a provided string is a valid Ethereum address.
Installation
We can install the Web3.js library with NPM in our terminal as:
$ npm install web3
Infura RPC URL
We need access to an Ethereum node in order to connect to an Ethereum node with JSON RPC on the Main Net. There are some ways we would do this. For one, we could run our own Ethereum node with Geth or Parity. Nonetheless, this needs us to download a lot of data from the blockchain and place it in sync. This is an enormous annoyance if we’ve ever tried to do this before.
We can use Infura to access an Ethereum node without having to run one manually mostly for suitability. Infura is a facility that offers a remote Ethereum node for free. We require to do is sign up, get an API key and the RPC URL for the network we want to connect to.
Our Infura RPC URL should look like this once we’ve signed up:
https://mainnet.infura.io/YOUR_INFURA_API_KEY
Data reading from Smart Contracts with Web3.js
We may achieve a JavaScript representation of an Ethereum smart contract with the web3.eth.Contract() function. This function expects two arguments:
One for the smart contract ABI
One for the smart contract address.
A smart contract ABI is a JSON array. It defines how an exact smart contract works. Below is an instance of an ABI:
const abi = [{"constant":true,"inputs":[],"name":"mintingFini
How to Deploy a Smart Contract with Web3.js
There are many ways we may deploy smart contracts to The Ethereum Blockchain. There are unfluctuating multiple conducts to deploy them within Web3.js itself. We will use the app.js file and set it up like this:
var Tx = require('ethereumjs-tx')
const Web3 = require('web3')
const web3 = new Web3('https://ropsten.infura.io/YOUR_INFURA_API_KEY')
const account1 = '' // Your account address 1
const privateKey1 = Buffer.from('YOUR_PRIVATE_KEY_1', 'hex')
This example has consisted on three basic steps:
Build a transaction object
Sign the transaction
Send the transaction
We’re up till now building a transaction and sending it to the network. The just variance is the transaction parameters.
Next, we will build the transaction object like this:
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(1000000), // Raise the gas limit to a much higher amount
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
data: data
}
The data parameter is the compiled bytecode representation of the smart contract in hexadecimal. We first need a smart contract in order to obtain this value. Then we need to compile it. We are welcome to use any smart contract we like. Though, we will use an ERC-20 token smart contract along with the accompanying Web3.js. We may assign the data value to a variable once we’ve compiled our contract.
Now we may also assign the nonce value by getting the transaction count:
web3.eth.getTransactionCount(account1, (err, txCount) => {
const data = '' // Your data value goes here...
const txObject = {
nonce: web3.utils.toHex(txCount),
gasLimit: web3.utils.toHex(1000000),
gasPrice: web3.utils.toHex(web3.utils.toWei('10', 'gwei')),
data: data
}
})
For more details visit:https://www.technologiesinindustry4.com/ethereum-javascript-api-web3-js/

Discussion (0)