Web3 .js Ethereum Javascript API

胡家維 Hu Kenneth
Singapore Blockchain-Dapps
4 min readMar 9, 2019

web3.js is a collection of libraries which allow you to interact with a local or remote ethereum node, using a HTTP or IPC connection. The web3 JavaScript library interacts with the Ethereum blockchain. It can retrieve user accounts, send transactions, interact with smart contracts, and more.

Version : 1.0.0-beta.36

Web3.js API Type

  • eth: Etherum blockchain related methods
  • net: Node’s network status
  • personal: Account functions and sending
  • db: Get/put for local LevelDB
  • shh: P2P messaging using Whisper

Install Web3.js

Node

npm install web3

CDN : https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/

<script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/web3.js"><script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@1.0.0-beta.34/dist/web3.min.js">

Instantiating web3

// Modern dapp browsers...
if (window.ethereum) {
App.web3Provider = window.ethereum;
try {
// Request account access
await window.ethereum.enable();
} catch (error) {
// User denied account access...
console.error("User denied account access")
}
}
// Legacy dapp browsers...
else if (window.web3) {
App.web3Provider = window.web3.currentProvider;
}
// If no injected web3 instance is detected, fall back to Ganache
else {
App.web3Provider = new Web3.providers.HttpProvider('http://localhost:7545');
}
web3 = new Web3(App.web3Provider);

First, we check if we are using modern dapp browsers or the more recent versions of MetaMask where an ethereum provider is injected into the windowobject. If so, we use it to create our web3 object, but we also need to explicitly request access to the accounts with ethereum.enable().

If the ethereum object does not exist, we then check for an injected web3instance. If it exists, this indicates that we are using an older dapp browser (like Mist or an older version of MetaMask). If so, we get its provider and use it to create our web3 object.

If no injected web3 instance is present, we create our web3 object based on our local provider. (This fallback is fine for development environments, but insecure and not suitable for production.)

Web3.js examples

NodeInfo :

Get Ethereum Node Information

PS: web3.version.getNode is deprecated.

web3.eth.getNodeInfo(function(error, result){
if(error){
console.log( “error” ,error);
}
else{
console.log( “result”,result ); //Ganaache - "EthereumJS TestRPC/v2.1.0/ethereum-js"
}
});

Balance :

Check User’s balance

web3.eth.getAccounts : get account from Ethereum node, web3.eth.accounts is deprecated.
web3.eth.getBalance : get account’s balance
web3.utils.fromWei : convert wei to ether , web3.fromWei is deprecated.

web3.eth.getAccounts(function(error, accounts) {
if(error) {
console.log(error);
}

web3.eth.getBalance(accounts[0]).then(function(result){
console.log( "Balance : " ,web3.utils.fromWei(result, 'ether'));
});
});

Nonce:

Each Ethereum account has a field called nonce to keep track of the total number of transactions that account has executed. Nonce is incremented for every new transaction and this allows the network to know the order in which the transactions need to be executed. Nonce is also used for the replay protection.

txnCount = web3.eth.getTransactionCount(web3.eth.accounts[0])

Transfer :

Transfer Ether from “A” to “B”

txnObject ( transaction object) is first argument of web3.eth.sendTransaction. txnObject is made of JSON.

from : String -The address for the sending account.

to : String the destination wallet address.

value: Number|String|BigNumber — (optional) the amount of Ether you wish to send to the destination address.

gas: Number|String|BigNumber — (optional, default: To-Be-Determined) The amount of gas to use for the transaction (unused gas is refunded).

gasPrice: Number|String|BigNumber — (optional, default: To-Be-Determined) The price of gas for this transaction in wei, defaults to the mean network gas price.

data: String — (optional) Either a byte string containing the associated data of the message, or in the case of a contract-creation transaction, the initialisation code.
nonce: Number — (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.

var txnObject = {
"from":_from,
"to": _to,
"value": web3.utils.toWei(_Amount,'ether'),
// "gas": 21000, (optional)
// "gasPrice": 4500000, (optional)
// "data": 'For testing' (optional)
// "nonce": 10 (optional)
}

web3.eth.sendTransaction(txnObject, function(error, result){
if(error){
console.log( "Transaction error" ,error);
}
else{
var txn_hash = result; //Get transaction hash
}
});

Practice

I made a web page by using the above methods.

  1. Get Ethereum node Information
  2. Get User’s balance
  3. Transfer Ether

For this practice , you will use MetaMask or Ganache. I will recommend you to use Ganache, a personal blockchain for Ethereum development you can use to deploy contracts, develop applications, and run tests. If you haven’t already, download Ganache and double click the icon to launch the application. This will generate a blockchain running locally on port 7545. You should change the port to 8545.

Source code & Completed code : https://github.com/kennethhutw/Web3JsPractice

I do this because I love it, but if you want me to buy me a cup of coffee I won’t say no :O )Thanks ^^

donation :

XEM : NCWZSUF4FPXJY3L3Y7657QNVBIUZ5D54F4TNJ64S

Ether : 0xf2d15dEAf62b8c4AFC0343006579E8E662c120D9

Bitcoin : 332UiyAfSXyvhqCYgDgBkNLFSf25ccNV9i

*Do CLAP, COMMENT and SHARE! I also welcome any business opportunities that arises**

Connect:

LinkedIn

Telegram

Facebook

--

--

胡家維 Hu Kenneth
Singapore Blockchain-Dapps

撰寫任何事情,O型水瓶混魔羯,咖啡愛好者,Full stack/blockchain Web3 developer,Founder of Blockchain&Dapps meetup ,Udemy teacher。 My Linktree: https://linktr.ee/kennethhutw