Loading...
Web3.js is a series of libraries that can help you complete the functions of sending Ether, reading and writing smart contract data, creating smart contracts, and other functions.
Its adoption JSON RPC ("Remote Procedure Call) Remote procedure call to interact with the blockchain. Ethereum is a peer-to-peer network composed of nodes that contains all the data and code on the blockchain. Web3.js allows us to send a request to an Ethereum node to read and write data through JSON RPC, which is a bit like using jQuery with a JSON API to read and write data from a web server.
we can use Infura to connect to Ethereum nodes Infura is a free service that provides remote Ethereum nodes. Just register to get an API key and the RPC URL of the network you want to connect.
After successful registration, your Infura RPC URL will look like this:
https://mainnet.infura.io/YOUR_INFURA_API_KEY
In the command line, first cd to the directory with the node module directory, and then enter the node command to enter the node console. And then install Web3.js directly.
npm i web3
If you want to achieve in your script file then, firstly you require this library of our file.
Example:
const Web3 = require('web3')
Now you have a variable that can be used to create a Web3 connection. Before creating, you need to save the Infura URL assignment in the variable like:
const rpcURL = "https://mainnet.infura.io/YOUR_INFURA_API_KEY"
If you use a local ganache client with a graphical interface, rpcURL us http://localhost:7545 after startup
Remember to replace your Infura API key, you can then instantiate a Web3 connection:
const web3 = new Web3(rpcURL)
With the Web3 connection, you can communicate with the Ethereum main chain.
If using an Infura connection, we use this connection to check the account balance:0x90e63c3d53E0Ea496845b7a03ec7548B70014A91.
Use web3.eth.getBalance() Method can get the balance. If you use ganache connection, you can copy the account address in ganache to check the balance.
const account = "0x90e63c3d53E0Ea496845b7a03ec7548B70014A91"
web3.eth.getBalance(address, (err,wei) => {
balance = web3.utils.fromWei(wei, 'ether')
})
We first call web3.eth.getBalance() function, it accepts a callback function with two parameters, an error and the balance. Ignore the error, for the time being, use the web parameter to refer to the balance, the unit is Wei, which can be converted to ether web.utils.fromWei(wei, 'ehter').
All code is as follows:
const Web3 = require('web3')
const rpcURL = '' // Your RPC URL goes here
const web3 = new Web3(rpcURL)
const address = '' // Your account address goes here
web3.eth.getBalance(address, (err, wei) => {
balance = web3.utils.fromWei(wei, 'ether')
})