Bot Build #13 - Deposit/Withdraw (Simple Bot)

in #utopian-io6 years ago


Repository

e.g. https://github.com/steemit/steem-js

What Will I Learn?

  • You will learn how to create a deposit/withdraw bot.

Requirements

  • Node.JS
  • Steem Package (Install: npm install steem --save)

Difficulty

  • Advanced

Tutorial Contents

  • You will learn how to store sbd/steem from other users and send them back, you will learn how to use JSON to save information but you should use SQL for things like that.

Curriculum

The Tutorial

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'),
    fs = require('fs'),
    path = require('path'),
    sql = require(path.resolve('./sql.json'));

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, sbd, steem, 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, 
        "SBD": sbd, 
        "STEEM": steem,
        "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, sbd + " SBD,", steem + " STEEM,", points, "Points, Deposit ID:", depositId);
    });
}

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

at the second section we creating a json object with the name, the amount of sbd and steem, the amount of points and the depositID.

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, sbd, steem, points){
    sbd = parseFloat(sbd);
    sbd = sbd.toFixed(3);
    steem = parseFloat(steem);
    steem = steem.toFixed(3);
    for(var i=0; i<sql.users.length; i++){
        if(sql.users[i].Name == name){
            var user = {
                "Name": name,
                "SBD": sbd,
                "STEEM": steem,
                "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)

at the second section, we check if the user exists at the system if it is we creating 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, sbd, steem, 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 == "SBD")
        Amount = Amount.toString() + ' SBD';
    else if(type == "STEEM")
        Amount = Amount.toString() + ' STEEM';
    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 == "SBD"){
            sbd = parseFloat(sql.users[id].SBD) + amount;
            sbd = sbd*0.97;
            sbd = sbd.toFixed(3);
            updateUser(sql.users[id].Name, sbd, sql.users[id].STEEM, sql.users[id].Points);
        }else if(type == "STEEM"){
            steem = parseFloat(sql.users[id].STEEM) + amount;
            steem = steem*0.97;
            steem = steem.toFixed(3);
            updateUser(sql.users[id].Name, sql.users[id].SBD, steem, sql.users[id].Points);
        }
        console.log("The user " + sql.users[id].Name + " deposited " + amount + " " + type + " successfully!");
}

first, we creating 2 variables one for sbd and one for steem.

then we check the type of the coin if it's sbd or steem.

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 sbd/steem amount at the file.

** withdraw function**

function withdraw(id, amount, type, memo){
    let newAmount;
    if(type == "SBD"){
        if(amount > sql.users[id].SBD)
        return console.log("SBD amount is higher than the balance!");
        else{
            newAmount = sql.users[id].SBD - amount; 
            updateUser(sql.users[id].Name, newAmount, sql.users[id].SBD, sql.users[id].Points);
            SendTransfer(sql.users[i].Name, memo, amount, "SBD");
        }
    }else{
        if(amount > sql.users[id].STEEM)
            return console.log("STEEM amount is higher the balance!");
        else{
            newAmount = sql.users[id].STEEM - amount;   
            updateUser(sql.users[id].Name, sql.users[id].STEEM, newAmount, sql.users[id].Points);
            SendTransfer(sql.users[i].Name, memo, amount, "STEEM");
        }
    }
    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 sbd or steem.

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 steem type.

Step 4 - streamTransactions, getting real deposit.

first of all we need the streamTransactions function

// Custom Websocket.
steem.api.setOptions({ url: 'wss://rpc.buildteam.io' });

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.

have a great day!

You can check the full work at my repl.it account and other bots that I create!

Proof of Work Done

the work made in Repl.it, https://repl.it/@lonelywolf22/DepositWithdraw-SteemJS-V10
user: https://repl.it/@lonelywolf22

GitHub: https://github.com/lonelywolf1
Utopian Tutorials GitHub Repository: https://github.com/lonelywolf1/Bot-Projects-SteemJS (This tutorial will add to the GitHub repository in the next few days!)

Sort:  

Hey @lonelywolf
Thanks for contributing on Utopian.
We’re already looking forward to your next contribution!

Want to chat? Join us on Discord https://discord.gg/h52nFrV.

Vote for Utopian Witness!

Thank you for your contribution.

Your contribution has been evaluated according to Utopian policies and guidelines, as well as a predefined set of questions pertaining to the category.

To view those questions and the relevant answers related to your post, click here.


Need help? Write a ticket on https://support.utopian.io/.
Chat with us on Discord.
[utopian-moderator]

Thank you, I really appreciate that!

Congratulations! This post has been upvoted from the communal account, @minnowsupport, by TheLonelyWolF🐺 from the Minnow Support Project. It's a witness project run by aggroed, ausbitbank, teamsteem, theprophet0, someguy123, neoxian, followbtcnews, and netuoso. The goal is to help Steemit grow by supporting Minnows. Please find us at the Peace, Abundance, and Liberty Network (PALnet) Discord Channel. It's a completely public and open space to all members of the Steemit community who voluntarily choose to be there.

If you would like to delegate to the Minnow Support Project you can do so by clicking on the following links: 50SP, 100SP, 250SP, 500SP, 1000SP, 5000SP.
Be sure to leave at least 50SP undelegated on your account.

Excellent tutorial, I will be giving this a deeper looksy in a second but its very well put together. I am new to utopian, and this provides an excellent example for a 'tutorials' post imo. Keep em coming :)

thanks, man, just know, a tutorial like that is a one part tutorial, utopian doesn't give money more than one part tutorial (only if needed, for example, the tutorial is built for 2-3 parts or the tutorial need to split because it will be too long)

thanks lonelywolf, I didn't know that!

No problem :)
if you have any suggestions for next tutorials It will be great!

Good job mate! :)

I just mentioned you in my article. In my post I used plain javascript on the client side instead. The next step is to use steemJs on the backend.

Take a look if you want.. :)
https://steemit.com/resteem/@gaottantacinque/let-s-grow-together-a-gift-for-you-all-javascript-code-for-a-client-side-simple-resteem-bot-d

Btw, for the repository section, you don't have to include the "e.g.", that means example. :)

hey @lonelwolf thanks for this helpful tutorial but they are some points are technical which I don't know please help

Posted using Partiko Android

Coin Marketplace

STEEM 0.16
TRX 0.15
JST 0.029
BTC 55400.25
ETH 2294.55
USDT 1.00
SBD 2.33