NEM Random Game Discussion

Hi there,

I get an error when I look inside the JS console in the main.js file

According to stackoverflow and other websites it seems that the require('./my-file'); instruction is reserved for node.js on the server side not on the client side.
So what would be a solution?

Actually there is also a tiny error in the nem-sdk.js file at the end the else { is open without any instruction.

The line should be.

var nem = require("nem-sdk").default;

Then it should work. If not, make sure that you include the nem-sdk script in your html before you include main.js.

You are correct that require doesn’t exist in pure js natively. But the nem-sdk library contains logic so that we can use require in the browser.

Now it works. I don’t know why but yesterday I haven’t the code after line 69163 so I guess this is the reason why I got the bug.

Now everything is working.

Thanks

I have the same problem and my date, time and timezone are well set up on my computer.

Any idea?

I have the same problem as you. Did you find a solution?

Try the following.

Create a function called getNEMTimestamp which contains the following.

var NEM_EPOCH = Date.UTC(2015, 2, 29, 0, 6, 25, 0);
return Math.floor(Date.now() / 1000 - NEM_EPOCH / 1000);

Then after you have added the amount to transferTransaction try to add the line.

transferTransaction.timeStamp = getNEMTimestamp();

Hi Filip,

thanks for your answer I tried to add the function you told me but I still get the same error message.

I don’t know where to put it.

Here are some screenshots

First step I have created the function getNEMTimestamp between the roll() and save() functions:

Second step I call it inside the click function of the roll button because I interpret your advice

Blockquote
Then after you have added the amount to transferTransaction try to add the line.

as putting the call after the click on the roll button but it didn’t work:

call

Since it didn’t work I tried another way as it seems to be a property on the object transferTransaction I added it inside the properties assignments and by re-reading the code I think this is what you were saying “after transferTransaction.amount”:

So now I have no clue about why it doesn’t work

Yeah I meant it like you did in the last picture. Seems right to me. Not sure why it doesn’t work. Can you send me all your code from main.js?

Here is my code for the main.js file:

$(document).ready(function () {

	// Load nem-browser library
	var nem = require("nem-sdk").default;

    // Create an NIS endpoint object
	var endpoint = nem.model.objects.create("endpoint")(nem.model.nodes.defaultTestnet, nem.model.nodes.defaultPort);
	var common = nem.model.objects.create("common")("1983Nem2#75019;", "7a431b6f6047ce1b44fb1c779f5dec3f97817ed644340dfe379b798103f507fb");
	var mosaicDefinitions = nem.model.objects.get("mosaicDefinitionMetaDataPair");

	var savedScores = JSON.parse(window.localStorage.getItem('random-game-score'));
	var scores = {};

	if (savedScores !== null)
	{
		scores = savedScores;
	}
	else
	{
		scores = {};
	}

  function roll() {
		var random = Math.floor(Math.random() * 1000001);
		console.log(random);
		$("#result").html(random);
  }

	// NEW FUNCTION
	function getNEMTimestamp() {
		var NEM_EPOCH = Date.UTC(2015, 2, 29, 0, 6, 25, 0);
		return Math.floor(Date.now() / 1000 - NEM_EPOCH / 1000);
	}

  function save() {
		var address = nem.model.address.clean($('#address').val());
		var result = $('#result').html();
		if (!(result => 0)) return alert("You need to roll the dice first!");

		var transferTransaction = nem.model.objects.get('transferTransaction');
		transferTransaction.amount = 0;
		transferTransaction.recipient = address;
		transferTransaction.message = "NEM Random Game Transaction";
		transferTransaction.timeStamp = getNEMTimestamp();

		var mosaicAttachment = nem.model.objects.create('mosaicAttachment')("emacsfreeman", "score", result);
		transferTransaction.mosaics.push(mosaicAttachment);

		nem.com.requests.namespace.mosaicDefinitions(endpoint, mosaicAttachment.mosaicId.namespaceId).then(function(res){
			var definition = nem.utils.helpers.searchMosaicDefinitionArray(res.data, ["score"]);
			var fullName = nem.utils.format.mosaicIdToName(mosaicAttachment.mosaicId);
			mosaicDefinitions[fullName] = {};
			mosaicDefinitions[fullName].mosaicDefinition = definition[fullName];

			var preparedTransaction = nem.model.transactions.prepare("mosaicTransferTransaction")(common, transferTransaction, mosaicDefinitions, nem.model.network.data.testnet.id);
			preparedTransaction.fee = 500000;

			nem.model.transactions.send(common, preparedTransaction, endpoint).then(function(res){
				if (res.code >= 2)
				{
					 alert(res.message);
				}
				else
				{
					scores[address] = result;
					window.localStorage.setItem('random-game-score', JSON.stringify(scores));
					updateScoringTable();
				}
			}, function(err){
				console.log(err);
			});
		}, function(err){
			console.log(err);
		});


  }

	function updateScoringTable(){
		var list = [];
		for (var key in scores)
		{
			if (scores.hasOwnProperty(key))
			{
				list.push(key + ": " + scores[key]);
			}
		}
		var highscoreTable = $('#highscoreTable');
		highscoreTable.html('');
		$.each(list, function(i){
			var li = $('<li/>').appendTo(highscoreTable);
			var text = $('<span/>').text(list[i]).appendTo(li);
		});
	}


	updateScoringTable();

	$("#roll").click(function() {
	  roll();
	});

  $("#save").click(function() {
	  save();
	});

});

And here is the error message I still get:

I’m not sure what’s going on here. Some issue with NEM. It’s due to reasons like this we will stop supporting NEM in the academy very soon. Because there are no developers building stuff for this platform anymore. But here is something you could try to get it to work.

$(document).ready(function () {

	// Load nem-browser library
	var nem = require("nem-sdk").default;

    // Create an NIS endpoint object
	var endpoint = nem.model.objects.create("endpoint")(nem.model.nodes.defaultTestnet, nem.model.nodes.defaultPort);
	var common = nem.model.objects.create("common")("1983Nem2#75019;", "7a431b6f6047ce1b44fb1c779f5dec3f97817ed644340dfe379b798103f507fb");
	var mosaicDefinitions = nem.model.objects.get("mosaicDefinitionMetaDataPair");

	var savedScores = JSON.parse(window.localStorage.getItem('random-game-score'));
	var scores = {};

	if (savedScores !== null)
	{
		scores = savedScores;
	}
	else
	{
		scores = {};
	}

  function roll() {
		var random = Math.floor(Math.random() * 1000001);
		console.log(random);
		$("#result").html(random);
  }

	// NEW FUNCTION
	function getNEMTimestamp() {
		var NEM_EPOCH = Date.UTC(2015, 2, 29, 0, 6, 25, 0);
		return Math.floor(Date.now() / 1000 - NEM_EPOCH / 1000);
	}

  function save() {
		var address = nem.model.address.clean($('#address').val());
		var result = $('#result').html();
		if (!(result => 0)) return alert("You need to roll the dice first!");

		var transferTransaction = nem.model.objects.get('transferTransaction');
		transferTransaction.amount = 0;
		transferTransaction.recipient = address;
		transferTransaction.message = "NEM Random Game Transaction";
		transferTransaction.timeStamp = getNEMTimestamp();

		var mosaicAttachment = nem.model.objects.create('mosaicAttachment')("emacsfreeman", "score", result);
		transferTransaction.mosaics.push(mosaicAttachment);

		nem.com.requests.namespace.mosaicDefinitions(endpoint, mosaicAttachment.mosaicId.namespaceId).then(function(res){
			var definition = nem.utils.helpers.searchMosaicDefinitionArray(res.data, ["score"]);
			var fullName = nem.utils.format.mosaicIdToName(mosaicAttachment.mosaicId);
			mosaicDefinitions[fullName] = {};
			mosaicDefinitions[fullName].mosaicDefinition = definition[fullName];

			var preparedTransaction = nem.model.transactions.prepare("mosaicTransferTransaction")(common, transferTransaction, mosaicDefinitions, nem.model.network.data.testnet.id);
			preparedTransaction.fee = 500000;
      setTimeout(function(){
        nem.model.transactions.send(common, preparedTransaction, endpoint).then(function(res){
          if (res.code >= 2)
          {
             alert(res.message);
          }
          else
          {
            scores[address] = result;
            window.localStorage.setItem('random-game-score', JSON.stringify(scores));
            updateScoringTable();
          }
        }, function(err){
          console.log(err);
        });
      }, 5000);
		}, function(err){
			console.log(err);
		});


  }

	function updateScoringTable(){
		var list = [];
		for (var key in scores)
		{
			if (scores.hasOwnProperty(key))
			{
				list.push(key + ": " + scores[key]);
			}
		}
		var highscoreTable = $('#highscoreTable');
		highscoreTable.html('');
		$.each(list, function(i){
			var li = $('<li/>').appendTo(highscoreTable);
			var text = $('<span/>').text(list[i]).appendTo(li);
		});
	}


	updateScoringTable();

	$("#roll").click(function() {
	  roll();
	});

  $("#save").click(function() {
	  save();
	});

});

1 Like

Thanks a lot for your answer. I don’t know why there are no developers building stuff on this platform because JS is a popular and easy to learn language.

What do you think about Stellar and all the crypto on the Wirex wallet (which by the way is building its own crypto as Binance did for example)?

And what about the Python kit for NEO, maybe there are more developers than NEM?

By the way I found a new NEM faucet if some people are interested in here is the link: https://freenem.com

I haven’t tried NEO in a long time. Maybe it has improved since I tried it back in -18.