Skip to content

Instantly share code, notes, and snippets.

@evias

evias/read_scores.js

Created May 29, 2017
Embed
What would you like to do?
NEM-sdk: Read outgoing Transactions for a given Account (Scores stored as Mosaic Transfer Transactions)
console.log("Hello, NEMber");
// Configure a Blockchain endpoint and include SDK
var NEM_HOST = "http://bob.nem.ninja"; // bob is Testnet!
var NEM_PORT = 7890;
var nem = require("nem-sdk").default;
var node = nem.model.objects.create("endpoint")(NEM_HOST, NEM_PORT);
// Read Outgoing Transactions for the given game/application Account (pacnem-business)
nem.com.requests.account.outgoingTransactions(node, "TCTIMURL5LPKNJYF3OB3ACQVAXO3GK5IU2BJMPSU")
.then(function(response)
{
var scores = {};
// each row in `response` array is a Transaction on the NEM Blockchain.
for (var i in response) {
var transaction = response[i];
var trxMeta = transaction.meta;
var trxContent = transaction.transaction;
var trxRecipient = trxContent.recipient;
if (! trxContent.mosaics || !trxContent.mosaics.length)
continue; // not interested in this transaction
for (var j in trxContent.mosaics) {
var mosaic = trxContent.mosaics[j];
if ("evias.pacnem" != mosaic.mosaicId.namespaceId || "cheese" != mosaic.mosaicId.name)
continue; // we want only evias.pacnem:cheese
var gameScore = mosaic.quantity;
var score = {
"timeStamp": trxContent.timeStamp,
"score": gameScore,
"player": trxRecipient
};
// create score entry in case no one had this score before
if (! scores.hasOwnProperty(gameScore))
scores[gameScore] = [];
// append the built high score object to the array of high scores
// with the same `gameScore`.
scores[gameScore].push(score);
}
}
// scores are not sorted yet, we must sort in descending order by score.
var distinctScores = Object.keys(scores);
distinctScores.sort().reverse();
// Distinct scores might have multiple entries (more than one Player can have one score)
// Scores are ordered now, we only need to dedup the scores to build a final history (Best Player on Top)
var orderedHighScores = [];
for (var i in distinctScores) {
var gameScore = distinctScores[i];
var scoreEntries = scores[gameScore];
// There might be multiple Players with the same High Score.
for (var j in scoreEntries)
orderedHighScores.push(scoreEntries[j]);
}
// save this somewhere.. you don't want to query the blockchain every time for this.
var allTimeHighScore = orderedHighScores.length ? orderedHighScores[0] : 0;
// DONE.
// Print our High Scores to the Console
console.log("PacNEM Hall of Fame:");
console.log("--------------------");
console.log("");
for (var i in orderedHighScores) {
var highScore = orderedHighScores[i];
var position = " (" * (i+1) + ")";
console.log(position + " Player " + highScore.player + " with a Score of: " + highScore.score);
}
},
function(error) { // General Error OR wrong Network for Address OR No Mosaics available });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment