Updated NodeJS Witness Price Feed Script

in #witnesslast month

image.png

Rewrote my NodeJS price feed update script. Removed a shit ton of bloat as well as get rid of the naggy vote me for witness shit. No warranty or liability upon myself incurred for using this script.

/*------------------------------------------------------------------------
--------------------------------------------------------------------------
---- Pricesnatcher.js v0.0.3 || Open Source Price Feed Node.js Script ----
----- Developed by @KLYE || Free to Use for All! || Free to Modify -------
--------------------------------------------------------------------------
--------------------------------------------------------------------------

Having issues getting the script to run? Copy and Paste the whole line below
in order to install the necessary NodeJS dependencies for app to Function:

 npm install @hiveio/hive-js || npm install fancy-log || npm install prompt

------------------------------------------------------------------------*/

// Load dependencies for app
var hivejs = require('@hiveio/hive-js');
var log = require('fancy-log');
var prompt = require('prompt');
var request = require('request');
var fs = require('fs');

// Parse 3 decimal places
function toThree(n) {
    var number = n.toString().substring(0, n.toString().indexOf(".") + 4);
    parseFloat(number);
    return number;
}

// No need to modify these variables - setting them up for later
var witnessname;
var wif;
var url;
var bkey;
var hivefeedprice;
var sleeptime = 60000; // set this to a number to avoid sleepmins being undefined
var sleepmins = Number(sleeptime / 60000);


// Setup / New configuration file prompts
function newconfig() {
    // Start user prompts
    prompt.start();
    prompt.message = "";
    prompt.get([{
        name: 'witnessname',
        description: 'Witness Account Name? (No @)',
        required: true
    }, {
        name: 'witnessurl',
        description: "Witness Campaign URL/Website?",
        required: true
    }, {
        name: 'wifinput',
        description: "Witness Account Posting Private Key?",
        required: true,
        replace: '*',
        hidden: true
    }, {
        name: 'activekey',
        description: "Witness Account Active Key?",
        required: true,
        replace: '*',
        hidden: true
    }, {
        name: 'bkey',
        description: "Witness Account Block Signing Key?",
        required: true,
        replace: '*',
        hidden: true
    }, {
        name: 'interval',
        description: "Number of Minutes Between Update? (1 block = 3 seconds)",
        required: false,
        default: 10
    }], function(err, result) {
        // If we messed up and got error on setup
        if (err) {
            log("Prompt ERROR: Something Went Wrong During Config.. Restarting! Service! (ctrl + c to exit)")
        };
        // if setup was completed properly
        if (result) {
            // create array of answers to save
            var newconfig = {
                witnessname: result.witnessname,
                wif: result.wifinput,
                url: result.witnessurl,
                activekey: result.activekey,
                bkey: result.bkey,
                interval: result.interval * 1000,
            };
            log("SUCCESS: You Completed The Configuration - Saving to Disk!");
            // Save data to file
            fs.writeFile(__dirname + "/pricesnatcher.config", JSON.stringify(newconfig), function(err, win) {
                if (err) {
                    log("ERROR: Unable to Save Config to Disk!");
                };
                if (win) {
                    log("Config SUCCESS: New Configuration Saved");
                    // Start price feed
                    getPrice();
                };
            }); // END config writeFile
            // Start price feed (backup/redundancy)
            getPrice();
        }; //END if (result)
    }); // END Setup Prompt
}; // END newconfig();

// Update / Publish Price Function
function updateprice() {
    // if HIVE price is borked (NaN) request price again
    if (hivefeedprice == NaN) {
      log(`Price ERROR: hivefeedprice == NaN! - Restarting!!`);
      getPrice();
    } else {
        // create array vairable to contain update message
        var exchangeRate = {
            "base": hivefeedprice + " HBD",
            "quote": "1.000 HIVE"
        };
        // Set RPC Node to HIVE
        hivejs.config.set('websocket', 'wss://api.hive.blog');
        // Broadcast the updated price feed
        hivejs.broadcast.feedPublish(activekey, witnessname, exchangeRate, function(err, result) {
            // if price feed publish errors
            if (err) {
                log("Publish ERROR: Price Feed Update FAILED!");
            };
            // if price feed publish success
            if (result) {
              // Check update interval after updating and show correctly timescale to user
              if(sleepmins <= 1) {
                log(`Update SUCCESS: 1 HIVE = $${hivefeedprice} USD - Checking in ${sleeptime / 1000} Seconds`);
              } else {
                log(`Update SUCCESS: 1 HIVE = $${hivefeedprice} USD - Checking in ${sleepmins} Minutes`);
              } // END else
            }; // END if (result)
        }); // END hivejs.broadcast.feedPublish
    }; // END else
}; // END function updateprice

function getPrice(){
  // clear get getPrice loop interval (to avoid potential insanity)
  clearInterval(getPrice);
      // Read the config
      fs.readFile(__dirname + "/pricesnatcher.config", function(err, data) {
          if (err) {
              log("Config ERROR: Reading Config File!");
          };
          if (data) {
            try{
              data = JSON.parse(data);
              witnessname = data.witnessname;
              wif = data.wif;
              url = data.url;
              activekey = data.activekey;
              bkey = data.bkey;
              sleeptime = data.interval;
              sleepmins = Number(sleeptime / 60000);
            } catch(e) {
              log("Config ERROR: Reading Config File!");
            }
          }; // END if (data)
      }); // End readFile
      // Connect to Coingecko.com to retrieve HIVE/BTC price
      request('https://api.coingecko.com/api/v3/simple/price?ids=hive&vs_currencies=usd&include_market_cap=false', function(error, response, body) {

        // Create a variable to stuff request response into
        var pricereply;
        // Attempt to parse received response for HIVE price
        try {
          pricereply = JSON.parse(body);
          pricereply = pricereply.hive;
          pricereply = pricereply["usd"];
          hivefeedprice = toThree(pricereply);
        } catch(e){
          log(`Fetch ERROR: Price Call Failed! - Restarting!`);
          getPrice();
        }
          // if the HIVE price has been found and isn't undefined, NaN or null
          if (hivefeedprice != undefined && hivefeedprice != NaN && hivefeedprice != null) {
             updateprice();
          } else {
            log(`Fetch ERROR: Price Call Failed! - Restarting!`);
            getPrice();
          }; // END else
      });
  };

// Check if config file exists
if (!fs.existsSync(__dirname + "/pricesnatcher.config")) {
    log("WARNING: No Configuration Found! Please Run Setup Below!");
    newconfig();
} else {
    // Read config if found
    fs.readFile(__dirname + "/pricesnatcher.config", function(err, details) {
        if (err) {
            log("Config ERROR: Unable to Read Configuration File!");
        }
        if (details) {
            details = JSON.parse(details);
            sleeptime = details.interval;

            // Start Price Feed
            log(`STARTING: Hive Price Feed v0.0.3 by @KLYE`);
            setInterval(getPrice, sleeptime);
        };
    });
};

It's only the coingecko average.. But I figured they aggregate their price from a variety of exchanges so rather than do a bunch of price queries just do one for efficiency sake. Includes a setup wizard and anyone with the knowledge of how to run a NodeJS script locally should be able to get this one running. Prior script had a bug in it which caused it to spaz the fuck out and try to update to much.

Welp, I'm back off to go work on the upcoming Hive-Roller.com release. Cheers!


image.png

Vote KLYE for Witness, Every Single Vote Helps, Thanks for the Support!

Need to get in Contact with KLYE?
Join the Official #KLYE Discord Server Today!


image.png
Looking for an Affordable, Secure & Reliable Server Host for Your Witness Server or Other Web Related Projects? Check out Privex.io!

Sort:  

PRICESNATCHERS!!!!!!!

Like booty snatchers but less ass.