Implement connection to the crypto wallets (BTC, Dash, Zcash, LTC, and BCH) in Nodejs.

12-16-2019    Jaya Sai    Views 6278


I’ll walk you through the initial setup and help you with the Nodejs code that is needed for creating the public address, getting wallet balance and few more primary wallet interactions.

What is RPC in Crypto:

Remote Procedure Call is a technique used to perform actions in a distributed client-server based application. Invoking and executing procedure/subroutine with the same system or on systems connected to a shared network. Allows controlling the QT wallets of a core wallet (i.e we can write a piece of code to control a network, directing the network to perform a specific action of rescanning, create, and encrypt a wallet, etc..).  

This is essentially a request-response messaging passing system  (JSON RPC will enable us to establish an interactive connection between the server and the node wallet).

 

Using Node js code we can connect to the full node BTC wallet using the RPC commands. 

Installation node module 

npm install node-bitcoin-rpc 

 

Code to connect to RPC  

let bitcoin_rpc = require('node-bitcoin-rpc');

bitcoin_rpc.init(host, port, user, pass);

 

Create a file with .js extension and add the deceleration and initiation code. 

let bitcoin_rpc = require('node-bitcoin-rpc');

let host = 'host';

let port = 18332;

let user = "username";

let pass = 'Password';

function initBitCoinRpc() {

 bitcoin_rpc.init(host, port, user, pass);

 bitcoin_rpc.setTimeout(30000);

}

 

Generate public address:

To generate a new public address (called a public key) for a wallet we have to use the below method.

bitcoin_rpc.call('getnewaddress', [], (err, res1) => {});

 

Below is the sample implementation using promises to control the asynchronous property of node js.  

async function generateNewAddress() {

 return new Promise((resolve, reject) => {

   initBitCoinRpc();

   bitcoin_rpc.call('getnewaddress', [], (err, res) => {

     if (err !== null) {

       console.log(err)

     } else {

       console.log(res)

     }

   });

 });

}

 

To maintain accounts in your wallet, you have to mention the account name in the params arrow-like [“accountName”]. This will generate a new account with an output address if there is no account with the name. If there exists an account with a matching name, then it returns a public address for that account. 

For all other methods, you can pass a wallet account address ( public address) as a param as above. 

The accounts functionality is deprecated in the latest node version. If you are willing to use then run the bitcoind with -deprecatedrpc=accounts option bitcoind -deprecatedrpc=accounts

 

Get Wallet Balance:

To get the balance of the node wallet, we have to use the below method.

bitcoin_rpc.call('getbalance', ['*', 1], (err, res1) => {});

Here ‘*’ indicates all the accounts and 1 indicates the minimum number of confirmations.


Below is the sample implementation in nodejs to get balance.

async function getBalance() {

 return new Promise((resolve, reject) => {

   initBitCoinRpc();

   bitcoin_rpc.call(‘getbalance’, ['*', 1], (err, res) => {

     if (err !== null) {

       console.log(err);

     } else {

       console.log(res)

     }

   });

 });

};

 

Get Transactions:

To get the list of transactions, we have to use the below method.

bitcoin_rpc.call(‘Listtransactions’, ['*', 100], (err, res1) => {});

Here * indicates all the accounts, 100 is the limit


Below is the sample implementation in nodejs to get transactions. 

async function getTransactions() {

 return new Promise((resolve, reject) => {

   initBitCoinRpc();

   bitcoin_rpc.call('listtransactions', ['*', 100], (err, res) => {

     if (err !== null) {

       console.log(err)

     } else {

       console.log(res)

     };

   });

 });

};

 

To get a specific transaction, we have to use the below method.

bitcoin_rpc.call('gettransaction', [], (err, res1) => {});

You have to pass transaction Id in params.
 

Transfer Currency:

To send currency to a specific address, we have to use the below method.

bitcoin_rpc.call('sendtoaddress', [address, amount], (err, res1) =>{});

‘Address’ is the receiver's address and ‘amount’ is the quantity 

Below is the sample implementation in nodejs to send money.

async function sendMoneyToAddress() {

   return new Promise((resolve, reject) => {

     initBitCoinRpc();

     }

     bitcoin_rpc.call('getbalance', [], (err, res) => {

       if (err !== null) {

         reject(err);

       } else if (res.result > amount) {   

     bitcoin_rpc.call('sendtoaddress', [address, amount], (err, res1) => 

       {

           if (err !== null) {

             reject(err);

           } else if (res1.error && res1.error.message) {

             resolve({

               message: res1.error.message,

               error: 'OK'

             });

           } else if (res1.result) {

             resolve({

               txid: res1.result,

               success: 'OK'

             });

           }

         });

       } else {

         resolve({

           message: 'No amount in wallet',

           error: 'OK'

         });

       }

     });

   });

 }

 

Receive Currency:

To receive currency to a specific address, we have to use the below method.

bitcoin_rpc.call('gettransaction', ["txid"], (err, res1) => {});

 
Below is the sample implementation in nodejs to get receive money.

async function getTransaction() {

 return new Promise((resolve, reject) => {

   initBitCoinRpc();

   bitcoin_rpc.call('gettransaction', ["txid"], (err, res1) => {

     if (err !== null) {

       console.log(err);

     } else {

       console.log(res1.result);

     }

   });

 });

}

 

All of the above calls are basic RPC calls used in node wallets. To learn more about the RPC methods please check bitcoin official documentation 

If you were unable to connect using the RPC make sure whether the ports were configured correctly or not (like outbound and inbound) open all ports for the outbound and RPC port for inbound. 

Even then it’s not connecting recheck the rpcallowip in config file. In the initial stage try to use rpcallowip=0.0.0.0/0 . Once everything is working, then you can add security.


Note: The above RPC methods and code can be used for other cryptocurrencies  Dash, Zcash, LTC, BCH, BUX, and any other cryptocurrency coins built using the BTC node platform.




Subscribe to Email Updates

Subscribe


Add Comments

Submit Comments

More Blogs


What is Trade Finance Transaction?

Blockchain Technology In Trade Finance Transactions

Hari Kondlapudi        Views 2297
block-chain-transform-your-business

Blockchain to transform your business

Hari Kondlapudi        Views 2174
block-chain-transform-your-business

Localization with React

Hari Kondlapudi        Views 1334

Contact Us

US Address:

Do Systems Inc,
433 Plaza Real, Suite 275
Boca Raton, FL 33432 


India Address:

Jayeesha Software Pvt Ltd
Hitech City Rd, VIP Hills,
Silicon Valley, Madhapur,
Hyderabad, TS 500081


Email: sales@dosystemsinc.com
 

Navigation

Copyright © 2023 Do Systems Inc. All rights reserved. Privacy Policy