How to do transaction using web3 javascript API

Posted By : Rajat khurana | 27-Oct-2017

Hi guys, here you will learn how to create transactions using web3 javascript API in the Ethereum Blockchain. First of all, you need to know about web3.js.

Web3.js is the collection of libraries which help us to interact with etherium node network. Web3.js contain the lot of objects through which we can get the detail of any block, create accounts etc. Every account that has been created is locked by default in ethereum network. So, for doing the transaction in ethereum network, the first step is to unlock account using web3.js.

Now to carry a transaction from one account to another account, send transaction function is provided by web3. 

To get a balance of an account getBalance function is provided by web3 js. Here is code to understand the concept.

 

var Web3 = require("web3");
var async = require('async');

var web3 = new Web3();

web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

fromAccount = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
fromAccountPassword = 'ppppppppp';
toAccount = 'zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz';
value = 500;


web3.eth.personal.unlockAccount(fromAccount, fromAccountPassword).then(function (result) {

    web3.eth.sendTransaction({
        from: fromAccount,
        to: toAccount,
        value: value
    }).then(function (receipt) {
        web3.eth.getBalance('' + toAccount + '').then(function (result) {
            console.log(" Result in getbalance function", result);
        }).catch(function (error) {
            console.log("Error", error);
        });

    }).catch(function (error) { console.log("Error is:-", error); })
}).catch(function (error) {
    console.log(" Error is:-", error);
});

 

Web3 contain an eth obj and with the use of this, we can get the balance of any account.

 

About Author

Author Image
Rajat khurana

Rajat is a bright Javascript Developer, he has good knowledge of HTML, WordPress, NodeJs, Core Java, Javascript, Jquery. Apart from this he loves to play Badminton and PC Gaming.

Request for Proposal

Name is required

Comment is required

Sending message..