Hive JavaScript Tutorial : Hive/HBD transfer tool

in StemSocial2 months ago

HIVE and HBD are the native tokens of the HIVE Blockchain and forms the basis of user rewards there. Users can transfer their earned HIVE and HBD to exchanges or other users via the numerous frontends available. The question many ask me is what if some of these frontends are down due to maybe issue with their hosting provider or some other thing unconnected with the HIVE chain. We saw Binance went down due to an external factor yesterday.

This is why I will take you through the process of creating your own HIVE/HBD transfer tool. You will learn how to make HIVE/HBD transfer using the HIVEjs library. This tool will be useful for others that want to know more on the backend features of HIVE blockchain.

I will guide you through the tutorial and explain every part in a way that a newbie will understand and want to try it out. We will be interacting with the HIVE-js library to transfer HIVE or HBD.

Step 1 : HTML structure

The first step is to create the framework of what we will build on. This is the HTML structure. We will create the HTML structure of our Transfer tool. We need 7 fields which are

  • The private key text field
  • The sender username
  • The receiver username
  • The amount of coin to send
  • A drop down list to select HIVE or HBD
  • A memo text field
  • The Transfer button
    The first thing is to set your HTML specifications in the opened sublime text by typing in the below code
<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

</body>
</html>

Then you can put the below code between the opening and closing body tag.

        <div class="myTransfer">
     <h1><center>HIVE/HBD transfer</center></h1>
     <input id='wif' type='password' placeholder="Private Active Key"></input>
     <input id='sender' type='text' placeholder="Sender"></input>
     <input id='receiver' type='text' placeholder="Receiver"></input>
     <div id="myblock">
     <input id='amount' type='number' placeholder="Amount"></input>
     <select id="coinType">
          <option value="">Please select asset</option>
          <option value="HIVE" >HIVE</option>
          <option value="HBD">HBD</option>
     </select>
     </div>
     <input id='memo' type='text' placeholder="Memo"></input>


     <input type="button" value="Transfer" id='button' />
</div>

The html code shows a heading 1 tag with text HIVE/HBD transfer.
The code above also shows that I used inputs and used the type attributes to distinguish from the text and password field. The password type attribute is needed in order to turn whatever text inputted there into asterisks. This will prevent anyone from seeing the password physically.
All the inputs were assigned id’s which will be used in the CSS part and also in the JavaScript part. The inputs were also given placeholders to let users see information about each field before inputting any details. There is also a select tag with three options. The first option ask users to select an asset which will show a drop-down list of HIVE and HBD when clicked. This will enable the end-user to select the specific coin he wants to send. The button input type was also added. It serves as the button to click which will in-turn trigger the transfer. The button input holds the value Transfer.
All the inputs were wrapped in a div called myTransfer.
tcrxffrjhl831ihhd9ir
The above image shows the way our HTML page displays in the browser. It shows we need to style it further. This will be done in the CSS section to make it more appealing to the end-user.

Step 2 : CSS styling

Our CSS code will also be in the HTML file. It won’t be external. We only need to specify the style type in the head section of our code by using <style type="text/css"></style>. This will ensure that any code that goes in there will reflect in our HTML code.
I started by applying box-sizing: border-box; to the universal selector before styling the myTransfer div.

.myTransfer{
     width: 500px;
     margin: 50px auto;
     padding: 50px;
     background: #BAB3B3;
     border-radius: 5px;
     box-shadow: 5px 0px 15px #000;
     -moz-box-shadow: 5px 0px 15px #000;
     -webkit-box-shadow: 5px 0px 15px #000;

}

The myTransfer div was assigned a width of 500px which means all other elements and tags will be inside that width. The margin was modified to give a top and bottom margin of 50px with the left and right margin left at automatic. Little padding of 50px was added to make it more appealing to the eye and the background colour changed. Box-shadow was added to give a bit of solid appearance and the edges were curved with border-radius.
The heading 1 tag is the next thing to get modified with the by giving it a font size of 20pt, a font-weight of 800px, and assigning it a colour with paddings and margins.

.myTransfer input[type="text"], .myTransfer input[type="password"], . myTransfer input[type="number"],
 .myTransfer select
 {
     display: block;
     width: 100%;
     font: 17px Arial, Helvetica, sans-serif;
     border: 0;
     border-bottom: 2px solid #9D4242;
     padding: 5px;
     margin-bottom: 12px;
     height: 40px;
 }

The above code modifies the input type by changing the display inline to block and applying a width of 100% and adding paddings, margins, and borders.

#coinType, #amount, #myblock {
     display: inline !important;
     width: 49% !important;
 }

The next thing to be modified is the select field and the amount field. I want it to be beside each other and I will have to override the initial code that says display should be block. To override this, I will set display to important and use the !important keyword. I also override the width from 100% to 49%.

.myTransfer input[type="button"]
     {
          background-color: white;
          border: 2px solid #9D4242;
          display: inline-block;
          cursor: pointer;
          color: #9D4242;
          font-size: 18px;
          font-weight: 800;
          padding: 5px 10px;
          margin-left: 34%;
 }
 .myTransfer input[type="button"]:hover,
     {
     background: linear-gradient(to top left, #BAB3B3, #ffff);
 }

The Transfer button is the next thing to be styled. The background colour is changed with border added and the cursor change to pointer. A bit of margin is added to centralize the button with paddings.
This mean our CSS is set and you can see the way it displays in the browser below.
j4f90rsdflzmhbdrjuub

Step 3 : JavaScript

We have now designed the HIVE/HBD transfer tool but it can’t function because we haven’t added any functionality to it. This is where we will use the HIVE JavaScript Library to interact with the HIVE blockchain and make transfers.

We will set our JavaScript in the head section before our CSS script and just after the last html tag in our body tag using <script></script> in both. This is where our JavaScript code will go into.
We will not be installing any npm package on the system and that’s why we will use a Content Delivery Network (CDN) to connect to the HIVE JavaScript Library by typing in <script src="https://cdn.jsdelivr.net/npm/@hiveio/hive-js/dist/hive.min.js"></script> just above the CSS properties. The above means we have connected to the HIVE JavaScript minified library. Then we need to set some parameters before using the JavaScript APIs available to us.

<script>
        hive.api.setOptions({ url: 'https://anyx.io' });
        hive.config.set('address_prefix','STM');
        hive.config.set('chain_id','beeab0de00000000000000000000000000000000000000000000000000000000');
        hive.config.set('alternative_api_endpoints', ['https://api.hive.blog', 'https://anyx.io']);
    </script>

The above code sets the default RPC servers (nodes) to connect to and also include a fallback option in-case one of the nodes fail to work or respond. It also sets the chain id and address prefix.

This mean we can now start working with the HIVE APIs.

The API code to transfer assets is

hive.broadcast.transfer(wif, from, to, amount, memo, function(err, result) {
 console.log(err, result);});
  • and wif stands for the private posting key
  • from stands for the sender
  • to stands for the receiver
  • amount stands for the asset quantity to be sent
  • memo is whatever information to be passed or exchange memo

These are the parameters we will link with our previously created page html and CSS styled page.
A function titled assetTransfer will be created and all our JavaScript code will be placed inside the function scope. This function will run once the Transfer button is clicked.

The next thing is to access the DOM by

var wif= document.getElementById('wif').value;
var from= document.getElementById('sender').value;
var to = document.getElementById('receiver').value;
var amount = document.getElementById('amount').value;
var memo= document.getElementById('memo').value;

var coin = document.getElementById('coinType').value;

The above code is used to assign whatever value that goes into the wif, sender, receiver, amount, memo, field to be assigned to var wif, from, to, amount, and memo respectively. The var coin tracks whatever option is selected by the select tag.
The only thing left to set is the asset type. We need to know if the user select HIVE or HBD and attach it to the amount to be sent. This is where we use the switch case function as seen below.

var coin = document.getElementById('coinType').value;


switch(coin) {
     case "HIVE":
          amount = amount + ' HIVE';
          break;
          case "HBD":
          amount = amount + ' HBD';
          break;
          default:
          alert('Please select HBD or HIVE');
}

The coin variable returns whatever coin is selected which we will now modify using the Switch Case function.
The Switch evaluates the Coin expression which is the value selected by the user. It then look at the first case and see if the user selection matches it. If it is true, it adds that clause HIVE to the amount. If it doesn’t matches, it looks at the second case clause which is HBD and see if user selection matches it. If it is true, it attaches HBD to the amount inputted by the user. If none of the selection matches the case clauses, it runs the default clause by running alert('Please select HBD or HIVE'); which means alert the user to select HBD or HIVE

hive.broadcast.transfer(wif, from, to, amount, memo, function(err, result) {
 alert(err, 'Transferred successfully');
 if (err = err){
     alert(err);
 } else if (result = result){
     alert('Transferred successfully');
 } else {
     alert('Please check again')
 }
});
}

The above code is the final one in our HIVEJs transfer and it is used to notify the user if the transfer is successful or not. The if else statement is used to check. It means if there is err, show an alert of the error and if transfer is successful, show an alert saying Transferred successfully. If none of these happens, show an alert saying Please check again.
The variables will now be used to work on our HIVEJs transfer api. The transfer API

hive.broadcast.transfer(wif, from, to, amount, memo, function(err, result) {
 console.log(err, result);});

will now work normally as all parameters has been set.
If you encounter any problem
• Ensure your amount is written in 3 decimal places like 0.001, 0.100, 1.000

We now have a working transfer tool that will report the error in case of incorrect

Our code is now fully done and functional.
rcor8ulitabbovxbyyty

You can see my block explorer data of the code working. I transferred 1 HBD to zonefund with the memo Zoneboy transfer tool.

The code can be viewed on (https://github.com/zoneboy/Hive-transfer/blob/gh-pages/index.html)[https://github.com/zoneboy/Hive-transfer/blob/gh-pages/index.html]
The code is also live on https://zoneboy.github.io/Hive-transfer/

Check out my previous tutorial

HiveJs post upvote tutorial
Hive JavaScript Tutorial : Hive Power Delegation

Sort:  

Do we have a JS API doc for Hive Engine tokens ?

I think this should help

https://github.com/harpagon210/sscjs

Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!

Please consider supporting our funding proposal, approving our witness (@stem.witness) or delegating to the @stemsocial account (for some ROI).

Thanks for using the STEMsocial app, which gives you stronger support. Including @stemsocial as a beneficiary could yield even more support next time. 
 

Thank you.