hybrix-jslib

This Javascript library can be used to connect software to leverage the capabilities of the hybrix platform. It serves two purposes: first to facilitate the logistics of interfacing with the hybrixd REST API, secondly to handle all client-side operations securely and privately. This ensures that keys required for transaction never leave the users device and communication over an encrypted channel.

Download for web <script src="./hybrix-lib.web.js"></script>

Download for NodeJS const Hybrix = require('./hybrix-lib.nodejs');

Install using NPM $ npm install hybrix-jslib
const Hybrix = require('./hybrix-lib');

Quick start

There are two flavours of the library: the web version to include in your webpage or front-end, and the node js version to include when you are building back-end software.

Here is a Hello World example of how to use hybrix-lib.js in your front-end. First include the library using script tags.

<html>
 <head>
  <script src='hybrix-lib.web.js'></script>
 </head>
 <body>
  <script>
   var hybrix = new Hybrix.Interface({XMLHttpRequest:XMLHttpRequest});
   hybrix.sequential(
    [
     'init'                                                        // Initialize hybrix
    ],
    ()=>{alert('Hello World!');},                                   // Define action to execute on successfull completion
    error=>{alert('Oops, something went wrong: '+error);}           // Define action to exectue when an error is encountered
   );
  </script>
 </body>
</html>

For nodejs projects:

const Hybrix = require('./hybrix-lib.nodejs.js');
const hybrix = new Hybrix.Interface({http:require('http')});
hybrix.sequential(
[
 'init',                                                        // Initialize hybrix
],
()=>{console.log('Hello World!');},                             // Define action to execute on successfull completion
error=>{console.log('Oops, something went wrong: '+error);}     // Define action to exectue when an error is encountered
              );

Or Using npm

Install using npm

npm install hybrix-jslib

const Hybrix = require('./hybrix-jslib.js');
const hybrix = new Hybrix.Interface({http:require('http')});
hybrix.sequential(
[
 'init',                                                        // Initialize hybrix
],
()=>{console.log('Hello World!');},                             // Define action to execute on successfull completion
error=>{console.log('Oops, something went wrong: '+error);}     // Define action to exectue when an error is encountered
      );

Callbacks

Each command is implemented as a member function of the Hybrix.Interface class. Adding a host can be done as follows.

Connectors

The connector is the method that is used to make calls to the host. For NodeJS the http and/or https modules can be used:

const hybrix = new Hybrix.Interface({http:require('http')}); // Provide a http connector
const hybrix = new Hybrix.Interface({https:require('https')}); // Provide a https connector
const hybrix = new Hybrix.Interface({http:require('http'),https:require('https')}); // Provide http and https connectors for mixed usage

For web/html implementations the XMLHttpRequest method is used which is supplied by the browser.

const hybrix = new Hybrix.Interface({XMLHttpRequest:XMLHttpRequest});

There is also the option to define a custom connector which should be a function with the following signature:

(host,query,dataCallback,errorCallback) => {
  // do the call to the host using the query and return the result or error
  if(error){
    errorCallback(error);
  }else{
    dataCallback(result);
  }
}

Callbacks

Here only one parameter is passed but each member function has four parameters: data, onSuccess, onError and onProgress.

The first is used to pass parameter data to the function. The last three are callback functions. onSuccess is called once when the method has finished successfully. onError is called once when an error is encountered. onProgress is called whenever a progress update is available, passing a number between 0 and 1, and 1 upon completion.

To first initialize the interface, add a host, and then query for asset balance one could try the following:

hybrix.init();                                     // This is an asynchronous function. It can take some time to complete.
hybrix.addHost({host:'https://www.example.com'});  // Problem! This will try to add the host before the initialization is done.
hybrix.rout({query: 'Query for asset balance'});   // Problem! This will try to request routing before the initialization and/or addition of the host is done.

This results in serious problems due to asynchronicity. One could use the callbacks to ensure the execution order.

hybrix.init(null,
  function(){
    hybrix.addHost({host:'https://www.example.com'}, // This will now be called after initialization is successfully completed.
      function(){
        hybrix.rout({query: '/asset/btc/balance/32FCGFdRGeho2HBeWQPaAYawJfPqHHvsCJ'});     // Query for asset balance
      }
    );
  }
);

But adding more steps or error handling will end up with code that is both very hard to read and maintain. (This is sometimes dubbed callback hell.) To mitigate this the library comes equiped with a sequential and a parallel command to handle these asynchronious call flows. With an added bonus of handling the progress for combined commands as well.

hybrix.sequential([
'init',                                                        // Initialize hybrix
{host: 'http://localhost:1111/'}, 'addHost',                   // Add and initialize the host
{query: '/asset/btc/balance/32FCGFdRGeho2HBeWQPaAYawJfPqHHvsCJ'}, 'rout'  // Query for asset balance
],
onSuccess,                                                      // Define action to execute on successfull completion
onError,                                                        // Define action to execute when an error is encountered
onProgress                                                      // Define action to execute whenever there is a progress update
);

For even more complex behaviour we advice you to implement your own favourite flavour method of handling the call flow, be it promises, streams, or async, etc.

Live example

Progress

Result

...

Reference

No results. Change your search filter or reset the filter.

AssetManagement

addAsset{symbol, [seed], [keys], [privateKey], [clientModuleCodeBlob], [host], [channel]}Add an asset (crypto currency or token) to the session.
addUnifiedAsset{symbol, name, symbols, [info], [host], [channel]}Add a unified asset TODO
asset{}Get detailed information about assets
form{amount, factor}Format a number according to its factor
getAddress{symbol}Get the address associated to a specific asset for current session.
getKeys{symbol}Get the keys associated to a specific asset for current session. Important: handle your private keys confidentially.
getPrivateKey{symbol}Get the private key associated to a specific asset for current session.
getPublicKey{symbol}Get the public key associated to a specific asset for current session.
initAsset{assetDetails, clientModuleCodeBlob, [seed], [keys], [privateKey]}Initialize an asset (crypto currency or token)
refreshAsset{[symbol]}Update the balance of a given asset (or all assets if no symbol is defined)
removeAsset{symbol, [host], [channel]}Remove an asset (crypto currency or token) from the session.
setPrivateKey{symbol, privateKey}Set the private key associated to a specific asset for current session.

ClientModule

client{[symbol], [id], func, data}Execute a function in a client module.
export{id}Export a client module code blob.
import{id, blob, [check=true], [channel], [host]}Import a client module code blob.
modules{}List locally available client modules.

Encryption

decrypt{data}Decrypt and parse data with user keys.
encrypt{data}Stringify and encrypt data with user keys.
hash{data, [salt]}Stringify and create a DJB2 hash.
keys{[secret]}Create signing keys
sign{message, [public], [secret], [signature]}Sign a message with a secret key or verify the signature for a public key.

Flow

call{func, [data]}Execute a custom function with callbacks. Usefull for sequential and parallel.
id{}Identity function, outputs the data that is passed
parallel{$label, $label,data, $label,step, [_options], [_options,passErrors=false]}Parallely executes several threads and collects results in a single object.
sequential{}Sequentually executes functions and passes results to next step.

Host

addHost{host}Add a hybrixd node as host.
rout{query, [fallback], [channel], [meta=false], [host], [retries=3]}Make a routing call to hybrixd node

Init

init{}Initialize the NACL factory if nacl has not been defined yet.

Session

createAccount{[entropy], [offset], [pool]}Create a new deterministic account with the entropy provided.
login{host}Create an encrypted session with a host.
logout{}Log out of current session.
session{username, password}Create a local deterministic session and - if required - log out of current session.

Storage

load{key, [encrypted=true], [legacy=false], [host], [channel='']}Retrieve value associated with key from the hybrixd node storage
meta{key, [host], [channel], [meta=false]}Retrieve the meta data for a storage key in the hybrixd node storage
save{key, value, [legacy=false], [encrypted=true], [work=true], [queue=false], [submit=true], [host], [channel], [meta=false]}Stringify and encrypt data with user keys.
seek{key, [legacy=false], [host], [channel='']}Check if a value is associated with key in the hybrixd node storage
work{challenge, difficulty, [submit], [key], [host], [channel], [meta=false]}Perform Proof of Work required to extend saved data retention.

Transaction

assert{}Test a condition and fail with a message if condition is not met
rawTransaction{symbol, target, amount, [validate=true], [message], [unspent], [fee], [time], [host], [channel]}Creates a raw transaction that is signed but not yet pushed to the network. Required assets and inputs are collected accordingly.
signTransaction{symbol, target, amount, [message], [fee], [time], unspent}Create a signed transaction using all inputs.
transaction{symbol, target, amount, [data], [fee], [host], [channel]}Create, sign and execute a transaction e.g. push it into the network.

Misc

atom{amount, [factor], [symbol]}Convert decimal numbers to atomic numbers