[Hive Patched] 4 Easy Steps - Deposit/Withdraw (Simple Bot)

hivejs.png
(Want to use the logo yourself? no problem, check out the post I made about My Art Design For Hive Logo)
(Want to use the thumbnail above? you can use it for free, don't forget to leave a credit 😀)


Repository:

https://www.npmjs.com/package/steem-js-patched

All of this tutorial is patched for Hive, so it works for Hive and steem!

All of the examples and results is from the old tutorial but still same for hive!

  • Helpful tutorials:

[HIVE Patched] SteemJS Full Tutorial - All The Functions - All The Abilities
[Hive Patched Tutorial] SteemJS - Vote, Comment and Follow functions - All In One

This tutorial can be a reference or just something to learn from ;)

This tutorial using json for this to be easier and to not evolve MySQL for this simple tutorial, I will use MySQL for advanced tutorials.


Step 1 - Setup Basic Stuff

first of all we need a few packages and json file to store the information(you should use mysql and not json!),

const steem = require('steem-js-patched'),
    fs = require('fs'),
    path = require('path'),
    sql = require(path.resolve('./sql.json'));

steem.api.setOptions({ url: 'https://api.hive.blog' }); // Load the HIVE API to use the hive blockchain
  • You will need to add the API of HIVE to use the hive blockchain

fs - file system package, with this package we can edit, save and create new files
steem - the steemjs package
path - with this package we can get path locations easily or fix path location problems.

we need a limit variable, this variable will be more important at the next step

const limit = 4; //start from 0 so 4 = 3, this limit is for the deleteUser function.

and we need the account name and private wif key

//Account Name & WIF(Posting) Key
const ACC_NAME = 'guest123', //Account Name
    ACC_KEY = '5JRaypasxMx1L97ZUX7YuC5Psb5EAbF821kkAGtBj7xCJFQcbLg';

now create a new file called sql.json, this step is only for who doesn't use mysql!

Step 2 - User functions

first, we need a function that creates a new user.

function addUser(name, hbd, hive, points, depositId){
    for(var i=0; i<sql.users.length; i++){
        if(sql.users[i].Name == name){
            return console.log("This user already exists, please use 'updateUser'/'deleteUser' function!");
        }
    }
    var user = {
        "Name": name, 
        "HBD": hbd, 
        "HIVE": hive,
        "Points": points,
        "depositID": depositId
    };
    sql.users.push(user);
    fs.writeFile('./sql.json', JSON.stringify(sql, null, 2), function(err){
        if(!!err)
            throw err;
        console.log("User Added To The Database, Details: " + name, hbd + " HBD,", hive + " HIVE,", points, "Points, Deposit ID:", depositId);
    });
}

In the first section, we check if the username already exists in our system, if it is the function stop!

In the second section we creating a json object with the name, the amount of hbd and hive, the number of points and the deposit.

then we adding the object to the SQL json object and then we're using fs to write the object inside the json file.

update user function

function updateUser(name, hbd, hive, points){
    hbd = parseFloat(hbd);
    hbd = hbd.toFixed(3);
    hive = parseFloat(hive);
    hive = hive.toFixed(3);
    for(var i=0; i<sql.users.length; i++){
        if(sql.users[i].Name == name){
            var user = {
                "Name": name,
                "HBD": hbd,
                "HIVE": hive,
                "Points": points,
                "depositID": sql.users[i].depositID
            };
            sql.users[i] = user;
            fs.writeFile('./sql.json', JSON.stringify(sql, null, 2), function(err){
                if(!!err)
                    throw err;
                console.log("The user " + name + " updated successfully!");
            });
        }else{
            return console.log("The user " + name + " Does not exists on the system!");
        }
    }
}

at the first section, we change the variables that we get to float numbers and make it at fixed 3 (example: 18.796)

In the second section, we check if the user exists at the system if it is we create a new json object and we change the value of our user object at sql to the new object and then write it back to the file.

** delete user function**

function deleteUser(name){
    for(var i=0; i<sql.users.length; i++){
        if(sql.users[i].Name == name){
            sql.users.splice(i,limit);
            
            fs.writeFile('./sql.json', JSON.stringify(sql, null, 2), function(err){
                if(!!err)
                    throw err;
                console.log("The user " + name + " deleted!");
            });
        }else{
            return console.log("The user " + name + " Does not exists on the system!"); 
        }
    }
}

first, we check if the user is exists at the system if he exists we starting to splice the object from the point of i (the user row) at limit times (the variable that we created at the start) the limit is equal to the number of rows that we have at the sql so for example we have (name, hbd, hive, points, depositid) it means that we have 5 but because it starts from 0 it means that we have 4, 0-1-2-3-4 (5).

and then we write back to the file the sql object.

one more thing, to make a new user you need to make a depositID, you can use the makeid function to get a random ID.

function makeid(number) {
  var text = "";
  var possible = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789";

  for (var i = 0; i < number; i++)
    text += possible.charAt(Math.floor(Math.random() * possible.length));

  return text;
}

Step 3 - the last functions

now because I already talked about the transfer function I'll paste it here without explanations, you can go back few tutorials ago to check the full explanation.

// Send Transfer Function
function SendTransfer(Name, Memo, Amount, type) {
    if(type == "HBD")
        Amount = Amount.toString() + ' HBD';
    else if(type == "HIVE")
        Amount = Amount.toString() + ' HIVE';
    steem.broadcast.transfer(ACC_KEY, ACC_NAME, Name, Amount, Memo, function(err, result) {
        console.log(err, 'Sent ' + Amount + ' To ' + Name + ' With The Memo: ' + Memo
        );
    });
}

deposit function

function deposit(id, amount, type){
        let sbd, steem;
        if(type == "HBD"){
            hbd = parseFloat(sql.users[id].HBD) + amount;
            hbd = hbd*0.97;
            hbd = hbd.toFixed(3);
            updateUser(sql.users[id].Name, hbd, sql.users[id].HIVE, sql.users[id].Points);
        }else if(type == "HIVE"){
            hive = parseFloat(sql.users[id].HIVE) + amount;
            hive = hive*0.97;
            hive = hive.toFixed(3);
            updateUser(sql.users[id].Name, sql.users[id].HBD, hive, sql.users[id].Points);
        }
        console.log("The user " + sql.users[id].Name + " deposited " + amount + " " + type + " successfully!");
}

first, we creating 2 variables one for hbd and one for hive.

then we check the type of the coin if it's hbd or hive.

then we adding it to the full amount, parsing it to float number and make it fixed 3 (example: 18.764)

and then we're using the updateUser function to update the hbd/hive amount at the file.

** withdraw function**

function withdraw(id, amount, type, memo){
    let newAmount;
    if(type == "HBD"){
        if(amount > sql.users[id].HBD)
        return console.log("HBD amount is higher than the balance!");
        else{
            newAmount = sql.users[id].HBD - amount; 
            updateUser(sql.users[id].Name, sql.users[id].HIVE, newAmount, sql.users[id].Points);
            SendTransfer(sql.users[i].Name, memo, amount, "HBD");
        }
    }else{
        if(amount > sql.users[id].HIVE)
            return console.log("HIVE amount is higher the balance!");
        else{
            newAmount = sql.users[id].HIVE - amount;    
            updateUser(sql.users[id].Name, newAmount, sql.users[id].HBD, sql.users[id].Points);
            SendTransfer(sql.users[i].Name, memo, amount, "HIVE");
        }
    }
    console.log("The user " + sql.users[id].Name + " withdrew " + amount + " " + type + " from his balance.");
}

first we creating a variable called newAmount, we need the variable to store the new amount of the user balance.

again, we check the type of the coin type is hbd or hive.

and we check if the requested amount is higher then the user balance, if it is higher we break the function.

then we get the new amount, save it at the file with updateUser function and sending transfer with the amount to the user.

same for hive type.

Step 4 - streamTransactions, getting real deposit.

first of all we need the streamTransactions function

steem.api.streamTransactions('head', function(err, result) { 
        // transaction type, the type of the transaction
    let type = result.operations[0][0];
        // transaction data, the data that comes with the transaction
    let data = result.operations[0][1];
}

we need to check if the type is transfer and the reciever is our ACC_NAME(account name)

if(type == 'transfer' && data.to == ACC_NAME){
}

if it is we need to get the value, the amount, the amount type and the sender.

const value = data.amount.split(' ');
let amount = value[0],
    aType = value[1],
    aFrom = data.from;
console.log(aType, aFrom, amount, data.memo);

then we check if the user is exists at the system and we check the memo (check if the memo is the user's depositID)

if it's true we're making a new deposit.

if the memo is "Withdraw" we're making a new withdraw.

for(var i=0; i<sql.users.length; i++){
    if(sql.users[i].Name == aFrom){
        if(data.memo == sql.users[i].depositId){
            deposit(i, amount, aType);
        }else if(data.memo == "Withdraw"){
            withdraw(i, amount, aType, "Withdrawl");
        }
    }
}

easy enough I think.


I hope I helped you if you have any suggestions for the next tutorials to leave a comment and upvote!
I want to say thanks to @appreciator, @likwid, @netuoso & @tipu and all of the others for the support, you make this process easier for me and for the users to find it!

Have a good day!

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center