Web3.js Basic
Web3.js talks to The Ethereum Blockchain with JSON RPC, which stands for "Remote Procedure Call" protocol. Ethereum is a peer-to-peer network of nodes that stores a copy of all the data and code on the blockchain. Web3.js allows us to make requests to an individual Ethereum node with JSON RPC in order to read and write data to the network. It's kind of like using jQuery with a JSON API to read and write data with a web server.
image credit: iotbl.
image credit: https://www.youtube.com/watch?v=bcgFG0RoIPU
Example: Checking Account Balances
Testing address: https://etherscan.io/address/0xf977814e90da44bfa03b6295a0616a897441acec
$ npm install web3
example1.js:
$ node .\example1.js
balance=2436827.427985396101008923 ETH
const Web3 = require('web3')
const rpcURL = "https://mainnet.infura.io/v3/YOUR_INFURA_API_KEY"
const web3 = new Web3(rpcURL)
const address = "0xf977814e90da44bfa03b6295a0616a897441acec" // Binance 8
web3.eth.getBalance(address, (err, wei) => {
balance = web3.utils.fromWei(wei, 'ether')
console.log(`balance=${balance} ETH`);
})
balance=2436827.427985396101008923 ETH
No comments: