Easy to Use Library for NEM in Node.js

[![npm version](https://img.shields.io/npm/v/nem-api.svg?maxAge=2592000)](https://www.npmjs.com/package/nem-api) The NEM API can be a bit hard to start with if you're not able to spend a while reading documentation. Nem-api is the solution to this. Simply find what you want to do on chain in the API documentation and copy paste it into your project. It's great for quickly prototyping apps on the blockchain, and is ready to use in production as well. In addition to this project, we also suggest developers look into the recently released [NEM-sdk](https://github.com/QuantumMechanics/NEM-sdk) for additional options. ## Features - Signing - Transactions - NIS Management - Websockets - Full Transaction 2.0 (Mosaics) Support - Fully commented code for anyone to learn from! ## Installation Just like anything else on npm, just do `npm install nem-api --save` in your project directory. You can then use nem-api by using `require()` in your node.js project. ## Usage Examples More features are being added often. If you contribute to nem-api, please add an example of how to use your feature in the README. It should be fairly simple if you read these examples and the code. ### Initialization ``` var nemapi = require('nem-api'); var san = new nemapi('http://san.nem.ninja:7890'); ``` The API URL can be null if you just want signing. In fact, a lot of things can be null, everything is properly handled. ### Signing ``` var signature = san.sign(hexPrivateKey, thingToSign); console.log(signature); ``` This signs the message converted to raw bytes, perfect for proving you own an account. ### NIS Requests ``` san.get('/account/get', {'address': 'YOUR_ADDRESS'}, function(response) { console.log(response.body); }); ``` For post requests just use `san.post` and the same parameters. Note that `response.body` is a javascript object already, and does not need to be parsed in order to access the insides. ### Making a Transaction Object A transaction object looks like this. ``` var txobject = { 'isMultisig': false, 'recipient': "TXXX-XXXX-XXXX-XXX", // Dashes optional, all parsed later. 'amount': 1, // Amount of XEM to send. 'message': 'Hello receiver!', // Message to send. 'due': 60 // Not sure what this does but the default is probably fine. } ``` You can send this transaction in a couple of ways. You can make it, serialize it, then send it yourself. ``` var transaction = this.makeTX(transactionobject, privatekey); var transactionobject = this.signTX(transaction, privatekey); this.post('/transaction/announce', transactionobject, callback); ``` Or you can just give it to the `doTX()` function, and it'll handle that all for you. ``` san.doTX(transactionobject, privatekey, callback); ``` The callback is a regular `post()` callback, so it is passed an object called response, which contains response.body (parsed JSON). ### Using WebSockets Have an example, it should be self-explanatory. Here is the list of channels you can subscribe to, and what they do. - /errors - Always subscribe to this channel, errors are sent here. - /account/
- This triggers whenever an account's state has changed. - /recenttransactions/
- Gives the recent transactions of an account. - /transactions/
- Sends on transaction confirmed. - /unconfirmed/
- Sends when an unconfirmed transaction is received. - /account/namespace/owned/
- (single) namespace owned by given account - /account/mosaic/owned/
- (single) mosaics owned by given account - /account/mosaic/owned/definition/
- (single) definition of mosaic owned by given account - /unconfirmed - EVERY Unconfirmed Transaction that the NIS receives, this is a lot of data! - /blocks/new - Every new block is sent here. - /blocks - full blocks ``` var nem = require('nem-api'); var bob = new nem("http://bob.nem.ninja:7890/") function getNewBlocks() { var thing = bob.subscribeWS("/blocks/new", function(message) { console.log(message.body); }); // Later you can thing.unsubscribe(); so keep this object safe. } bob.connectWS(function () { getNewBlocks(); }, function() { console.log("This runs in case of a failure."); }); ``` ## Conclusion The `nem-api` library for node.js is the perfect way to build your applications on the NEM platform. It provides nearly everything you will need to build a powerful blockchain backed application with NEM. If you'd like to contribute to development, create a [pull request](https://github.com/nikhiljha/nem-api) on Github. You can also support the project with a donation in XEM at NDLL32-E2LU3M-BOUFCO-ERHSLK-A3O62C-KABXYG-4JYE or a Bitcoin>XEM bridge address at 1Csp78BhddGz9Qj6cF4yc3bnC9Kv49G82f. *The NEM team would like to thank Nikhil Jha writing this blog.*
3 Likes

German Translation:

Benutzerfreundliche Library für NEM in Node.js

Die NEM API kann etwas Anspruchsvoll sein wenn du keine Zeit hast die Dokumentation zu lesen. Nem-api ist die Lösung für dieses Problem. Finde das was du auf der Blockchain realisieren willst in der API Dokumentation und kopiere und füge es in dein Projekt ein, ganz einfach. Es ist grossartig für die Erstellung von Prototypen-Apps auf der Blockchain, und auch schon bereit für die Verwendung in einer produktiven Umgebung.

Zusätzlich zu diesem Projekt ist es auch noch eine gute Idee für Entwickler, in die kürzlich veröffentlichte NEM-sdk zu schauen, um alternative Optionen zu prüfen.

Features

  • Signieren
  • Transaktionen
  • NIS Management
  • Websockets
  • Volle Unterstützung für Mosaic-Transaktionen
  • Vollständig kommentierter Code für jeden zum lernen!

Installation

Wie auch alles andere auf NPM, tippe einfach npm install nem-api --save in deinem Projektverzeichnis ein. Du kannst dann die nem-api mittels require() in deinem node.js Projekt nutzen.

Beispiele für den Gebrauch

Viele Features werden laufend hinzugefügt. Wenn du etwas zur nem-api beitragen willst, füge bitte in der README ein Beispiel ein, damit man weiss wie es genutzt werden soll. Es sollte ein Kinderspiel sein, wenn du diese Beispiele und den Code liest.

Initialisierung

var nemapi = require('nem-api');
var san = new nemapi('http://san.nem.ninja:7890');

Die API URL kann null sein wenn du nur signieren möchtest. Tatsächlich können einige dinge den Wert “null” annehmen, keine sorge, alles wird sauber gehandhabt.

Signieren

var signature = san.sign(hexPrivateKey, thingToSign);
console.log(signature);

Dies signiert die Nachricht mittels konvertierung in reine bytes, perfekt um zu beweisen, dass du Besitzer des Kontos bist

NIS Requests

san.get('/account/get', {'address': 'YOUR_ADDRESS'}, function(response) {
console.log(response.body);
});
Für POST-requiests benutze san.post und die selben Parameter. Beachte dass response.body bereits ein Javascript-Objekt ist und daher nicht geparst werden muss, um auf die Objektinhalte zugreifen zu können.

Transaktionsobjekt erstellen

Ein Transaktionsobjekt sieht wie folgt aus:

var txobject = {
'isMultisig': false,
'recipient': "TXXX-XXXX-XXXX-XXX", // Dashes optional, all parsed later.
'amount': 1, // Amount of XEM to send.
'message': 'Hello receiver!', // Message to send.
'due': 60 // Not sure what this does but the default is probably fine.
}

Du kannst diese Transaktion auf verschiedene Wege versenden.
Du kannst sie erstellen, serialisieren und dann selbst versenden.

var transaction = this.makeTX(transactionobject, privatekey);
var transactionobject = this.signTX(transaction, privatekey);
this.post('/transaction/announce', transactionobject, callback);

Alternativ kannst du es der dotX() Funktion übergeben, diese Funktion regelt dann den Rest für dich.

san.doTX(transactionobject, privatekey, callback);

Der Rückgabewert ist ein reguläres post() callback, es übergibt ein Objekt mit Namen response zurück, welches den response.body enthält (geparstes JSON).

WebSockets nutzen

Mit dem folgenden Beispielen sollte es selbsterklärend sein.

  • /errors - Immer auf diesem Kanal anmelden, Fehlermeldungen werden hier hin gesendet.
  • /account/- Dies wird getriggert sobald ein Kontostatus sich geändert hat
  • /recenttransactions/- Zeigt die kürzlich erfolgten Transaktionen eines Kontos an
  • /transactions/ - Wird gesendet wenn eine Transaktion bestätigt wurde
  • /unconfirmed/ - Wird gesendet wenn eine unbestätigte Transaktion erhalten wird.
  • /account/namespace/owned/ - (einzelner) Namespace im Besitz eines spezifischen Kontos
  • /account/mosaic/owned/ - (einzelner) Mosaic im Besitz eines spezifischen Kontos
  • /account/mosaic/owned/definition/ - (einzelne) Mosaic-Defintion im Besitz eines spezifischen Kontos
  • /unconfirmed - JEDE unbestätigte Transaktion die das NIS empfängt, Achtung, das sind viele Daten!
  • /blocks/new - Jeder neue Block wird hier hin gesendet.
  • /blocks - volle Blöcke

var nem = require('nem-api');
var bob = new nem("http://bob.nem.ninja:7890/")

function getNewBlocks() {
var thing = bob.subscribeWS("/blocks/new", function(message) {
console.log(message.body);
});
// Later you can thing.unsubscribe(); so keep this object safe.
}

bob.connectWS(function () {
getNewBlocks();
}, function() {
console.log("This runs in case of a failure.");
});

Fazit

Die nem-api Library für node.js ist der perfekte Weg um deine Applikationen auf der NEM-Plattform aufzubauen. Es bietet praktisch alles was du brauchst um leistungsstarke blockchain-gesicherte Applikationen mit NEM zu bauen. Wenn du dich an der Entwicklung beteiligen möchtest, erstelle einen pull request auf Github.

Du kannst dieses Projekt auch mit einer Spende in XEM auf NDLL32-E2LU3M-BOUFCO-ERHSLK-A3O62C-KABXYG-4JYE oder mit Bitcoin via Bitcoin->XEM Bridge 1Csp78BhddGz9Qj6cF4yc3bnC9Kv49G82f unterstützen.