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 API, secondly to handle all client-side operations securely and privately. This ensures that keys required for transactions never leave the users device and communication happens 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();
   hybrix.sequential(
    [
     {host:'https://api.hybrix.io/'}, 'addHost'                     //  Connect to host
    ],
    host => alert('Connected to '+ host),                           // 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();
hybrix.sequential(
  [
   {host:'https://api.hybrix.io/'}, 'addHost'                     //  Connect to host
  ],
  host => console.log('Connected to '+ host),                     // Define action to execute on successfull completion
  error => console.error('Oops, something went wrong: ' + error)  // Define action to exectue when an error is encountered
);

Or using npm:

Install the package using npm npm install hybrix-jslib

const Hybrix = require('hybrix-jslib');
const hybrix = new Hybrix.Interface();
hybrix.sequential(
  [
   {host:'https://api.hybrix.io/'}, 'addHost'                     //  Connect to host
  ],
  host => console.log('Connected to '+ host),                     // Define action to execute on successfull completion
  error => console.error('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.

hybrix.addHost({host:'https://www.example.com'});

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 add a host and then query for asset balance one could try the following:

hybrix.addHost({host:'https://www.example.com'});  // This is an asynchronous function. It can take some time to complete.
hybrix.rout({query: 'Query for asset balance'});   // Problem! This will try to request routing before the 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.addHost({host:'https://www.example.com'},
  function(){
    hybrix.rout({query:'/asset/btc/balance/32FCGFdRGeho2HBeWQPaAYawJfPqHHvsCJ'});     //  This will now be called after the addition of the host is successfully completed.
  }
);

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([
{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], [check=true], [offset=0], [host], [channel], [includeBaseAssets=true]}   Add an asset (crypto currency or token) to the session.
addUnifiedAsset{symbol, [offset=0], name, symbols, [info], [host], [channel]}   Add a unified asset TODO
asset{[symbol], [offset=0], [host], [channel]}   Get detailed information about assets
form{amount, factor}   Format a number according to its factor
getAddress{symbol, [offset=0]}   Get the address associated to a specific asset for current session.
getBalance{symbol, [offset=0], [available=false]}   Get the balance of a specific asset for current session.
getFee{symbol, [source], [target], [amount]}   Get the fee object of a specific asset for current session.
getKeys{symbol, [offset=0]}   Get the keys associated to a specific asset for current session. Important: handle your private keys confidentially.
getLoginKeyPair{[username], [password], [offset=0]}   Get the keys associated with a login username/password. Important: handle your private keys confidentially.
getPrivateKey{symbol, [offset=0]}   Get the private key associated to a specific asset for current session.
getPublicKey{symbol, [offset=0]}   Get the public key associated to a specific asset for current session.
getValuation{fromSymbol, toSymbol, [amount=balance], [cacheTime], [channel], [host]}   Get the balance of a specific asset for current session.
getValuations{fromSymbols, toSymbol, [cacheTime], [channel], [host]}   Get the valuations rate of an array of assets.
initAsset{assetDetails, clientModuleCodeBlob, [offset=0], [check=true], [seed], [keys], [privateKey], [host], [channel]}   Initialize an asset (crypto currency or token)
refreshAsset{[symbol], [cache=5000], [offset=0]}   Update the balance of a given asset (or all assets if no symbol is defined)
removeAsset{symbol, [host], [channel], [offset=0]}   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.

Deprecated

init{}   No longer required, is handled automatically before the first call

Encryption

code{data, [target='base256'], [source='base256']}   Change encoding of a string from one format to the other.
decrypt{data, [salt], [publicKey], [secretKey]}   Decrypt and parse data with user keys.
encrypt{data, [salt], [publicKey], [secretKey]}   Stringify and encrypt data with user keys.
hash{data, [salt=''], [method=sha256]}   Stringify and create a 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], [_options,failIfAllFail=true], [_options,failIfAnyFails=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, [regular=true], [encryptByDefault=false]}   Add a hybrixd node as host.
rout{query, [fallback], [channel], [meta=false], [retries=3], [cache=0], [host], [regular=true], [encryptByDefault=false], [data]}   Make an api call to hybrixd node

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, publicKey, secretKey, symbol, privateKey, [offset]}   Create a local deterministic session and - if required - log out of current session.

Storage

burn{key, [sessionKey=false], [host], [channel=''], [local=true], [remote=true]}   Delete a value in storage
list{pattern, [sessionKey=false], [host], [channel=''], [local=true], [remote=true]}   Check which keys matching a given pattern exist in hybrixd node storage
load{key, [encrypted=true], [sessionKey=false], [fallback], [host], [channel=''], [local=true], [remote=true], [mergeStrategy=(local,remote)], [sync=true]}   Retrieve value associated with key from the hybrixd node storage
meta{key, [host], [channel], [meta=false]}   Retrieve the meta data for a storage key
save{key, value, [sessionKey=false], [encrypted=true], [work=true], [queue=false], [submit=true], [host], [channel=''], [local=true], [remote=true]}   Stringify and encrypt data with user keys.
seek{key, [sessionKey=false], [host], [channel=''], [local=true], [remote=true]}   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

addPending{transactiontransaction,ref, transaction,meta, transaction,type, [transaction,timestamp=now]], [transaction,status=0], [sync=true]}   Add pending transaction(s)
assert{}   Test a condition and fail with a message if condition is not met
getPending{, data, [refresh=true], [remove=true], [sync=true]}   Merge the stored pending transactions with the existing ones
rawTransaction{symbol, target, amount, [validate=true], [message], [unspent], [source=address], [offset=0], [comparisonSymbol=hy], [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], [offset=0], unspent}   Create a signed transaction using all inputs.
transaction{symbol, target, amount, [validate=true], [message], [unspent], [source=address], [comparisonSymbol=hy], [offset=0], [fee], [time], [host], [channel], [addToPending=true]}   Create, sign and execute a transaction e.g. push it into the network.

Misc

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