'Hello World' in IOTA: Payments and Messaging Leaderboard

Getting started is the most difficult part of any newly introduced revolutionary technology. Many people are now just learning about Blockchain and the fundamental concepts behind it. Because IOTA is such a novel new approach to consensus, distributed ledgers and IoT protocols, we are putting in extra effort into ensuring that beginners as well as experts in Blockchain will have an easy transition over to our realm of the Tangle, Trinary and feeless micropayments.

This part of our ongoing developer tutorial series will focus on giving you a hands-on experience to the underlying protocol and introduce you to the IOTA API. By the end of this tutorial you will know how to transfer value as well as data through the IOTA Tangle. Giving you a great start to develop your own IOTA-powered applications.

This tutorial is divided into two parts. The first part will introduce you to the application and will help you get started actually playing around with IOTA by sending transaction with data. The second part of the tutorial will give you a deeper dive by showing and explaining you certain parts of the application so that you get a more comprehensive overview and understanding of IOTA and the API.

It should be noted that I am assuming that you have successfully installed IOTA and have it running on port 14265. If you have not done so yet, please go here in order to install IOTA.

‘Hello World’, in IOTA

IOTA is all about IoT and machine-to-machine interactions. Because of this, it was a bit difficult for us to find the perfect ‘Hello World’ example that is both easily accessible (not everyone has a Raspberry Pi readily available) but still introduces the fundamental concepts of IOTA.

This ‘Hello World’ example in our first introductory tutorial will therefore be a messaging leaderboard, where messages are ranked according to the amount of IOTA’s which were sent with it. The more value was sent, the higher the message will be ranked in the leaderboard. A use case of such an application would be to prioritize tasks or messages in a queue - perfect for microservices.

The application itself can be downloaded from the repository on github:

https://github.com/domschiener/leaderboard-example

The important files to look at are index.html and send.html. The former is for receiving payments with messages and listing them according to their respective values; the latter is there to send a transaction which contains a trytes-encoded message. You can either send transactions to yourself, but generally this is more fun with other people. So feel free to follow this tutorial and test it together with other people on Slack or the Forum.

1. Getting Started

Screen Shot 2017-03-21 at 19.42.30.png

As soon as you have your IOTA client up and running, you will be able to send API requests to your node via port 14265 (default). The full list of commands as well as more details about each of them can be found on our official documentation at https://iota.readme.io/. You can also run this tutorial with a remote node, but you need to have the `attachToTangle` function available. In order to use a different port and host, change the IOTA constructor in index.js and send.js (line 6).

Once you’ve cloned the repo, open up index.html in your favorite browser. You should see your empty leaderboard. Open up the menu on the top right. Now as our first step we need to create a seed. A seed in IOTA is simply a string of latin characters and 9’s, consisting of a total of 81 characters (but you do not need to make it full 81 chars, it is recommended though). For example, a seed like AAA99BCDZY is legal, while a seed like AA81ÖÄÜ# is not. Keep that in mind. Create your own, unique seed and then enter it into the input box.

After you’ve entered your seed, you’ll be able to generate an address. Head to “My Addresses” and click on the Generate Address button. What happens now is that you are essentially generating the private key at a specific index from your seed, and from that private key you derive your address. In order to make it possible to deterministically generate addresses, we could “attach” this address to the, which is basically sending an empty transaction which makes it easy to figure out which addresses were already generated (the ones in the Tangle) and which not (the ones which are not in the Tangle yet).

Address generation

Once you’ve generated that seed, you should head over to send.html, where you have two options: either you login with an existing seed which has a balance (for this tutorial you will be sending actual tokens around), or you create a new seed and generate an address to send tokens to. If you don’t own any tokens yet, feel free to ask on Slack or the Forum to get some tokens sent to your address.

Continuing on with this tutorial we assume that:

  • You have a seed and an address for index.html
  • You have a different seed and a confirmed balance on send.html

1.1. Making your First Transaction

Screen Shot 2017-03-21 at 22.00.43.png
Send.html overview

Now that you’re logged in on both index.html and send.html, it’s time to send a transaction and test the application yourself. Head over to send.html and enter your name, a value to transmit (keep in mind that the more you send, the higher your message will be ranked), and an accompanying message which you want to engrave into the Tangle and send to an address (you can use the address which you generated yourself on index.html).

Once you hit the submit button, you are starting the process for making a transaction. The transaction generation process is basically a 3-step process:

  • Bundle Generation: First of all, with the prepareTransfers API call you are generating the bundle (which is a set of transaction), including the signature required for sending tokens.
  • Tip Selection: Secondly, with the getTransactionsToApprove API call you are selecting two transactions which you will approve with your transaction. That’s the whole consensus part of IOTA and quite unique about it.
  • POW: You are doing some Proof of Work (this is a la hashcash, not like in Bitcoin), which is required for you to get your transaction accepted by the network.

The time required for generating a transaction and sending it to the network entirely depends on your hardware as well as the network you’re on, as the testnet has lower POW requirements. If you use the Sandbox, it should take a few seconds, on the mainnet it can take several minutes.

Once your transaction was successfully sent, you can go to index.html and you should see the entry in your dashboard. After doing this a couple of times you should have a full leaderboard with ranked messages. You can even logout and back in and you’ll still see all the messages and payments.

Screen Shot 2017-03-22 at 10.39.43.png
What the final Leaderboard should look like.

2. Under the Hood

Now that we have a high-level overview of the application, let’s take a deep dive into the code to explain what’s happening. Here I’ll explain only the main essential components of the application, but you can feel free to take a deeper dive into the overall code and its structure.

2.1. The Javascript Library

In IOTA there is a client (such as IRI) and a client library. The client exposes a set of API commands which you can send through. A full list of API commands which are available by the core client can be seen here.

What’s more interesting to us though is the Javascript Library, which takes care of a lot of the heavy-lifting such as signatures, bundle generation and useful utility functions for you. You can take a deep dive into the Javascript Library itself through this blog post or you can look on Github.

{{CODE}}

//  Instantiate IOTA with provider 'http://localhost:14265'

var iota = new IOTA({

   'host': 'http://localhost',

   'port': 14265

});

{{ENDCODE}}

2.2. Generating an Address

As with everything, it starts with a seed. When generating an address, you basically derive a private key from that seed, and from that private key you then generate the address. When generating a private key, you start from index: 0, by increasing the counter you get a new private key, and as such, a new address. Pretty straightforward right?

{{CODE}}

// Deterministically generates a new address for the specified seed with a checksum

iota.api.getNewAddress( seed, { 'checksum': true }, function( e, address ) {

   if (!e) {

       console.log("Generated new address: ", address)

   } else {

       console.log("Something went wrong: ", e);

   }

})

{{ENDCODE}}

One of the unique aspects of the Javascript library is that it makes it possible to generate addresses deterministically. What this means is that you can deterministically increase the key index counter by “attaching” the address to the Tangle. Attaching an address to the Tangle is basically sending a transaction (mostly empty) to the address, so that it’s stored in your local database. This way you can determine which address has already been generated, and which not.

Look at challenge #2 for more information on this.

2.3. Binary to Trinary and Back

One of the unique aspects of IOTA is that it’s no longer based on binary, but trinary (long story, which we will explain in more detail in future blog posts). As such, if you want to transfer or store data in the Tangle you have to first convert those bytes into trytes. The Javascript library makes this conversion between bytes and trytes very simple for you, with the functions toTrytes and fromTrytes.

Look at the following example:

{{CODE}}

// the message which we will send with the transaction

var messageToSend = {

   'name': 'Dominik',

   'message': 'My first message sent with IOTA.'

}

// Stringify to JSON

var messageStringified = JSON.stringify(messageToSend);

// Convert the string to trytes

var messageTrytes = iota.utils.toTrytes(messageStringified);

console.log(messageTrytes) //ODGABDPCADTCGADBGANBCDADXCBDXCZCGAQAGAADTCGDGDPCVCTCGADBGAWBMDEAUCXCFDGDHDEAADTCGDGDPCVCTCEAGDTCBDHDEAKDXCHDWCEASBYBCCKBSAGAQD

{{ENDCODE}}

As you can see, we just converted the JSON data from binary to trytes. You can convert it back with the fromTrytes function. The resulting trytes, which will then be sent with a transaction, is the following:

{{CODE}}

ODGABDPCADTCGADBGANBCDADXCBDXCZCGAQAGAADTCGDGDPCVCTCGADBGAWBMDEAUCXCFDGDHDEAADTCGDGDPCVCTCEAGDTCBDHDEAKDXCHDWCEASBYBCCKBSAGAQD

{{ENDCODE}}

2.4. Making a Transaction

Probably the main component of the entire application: making a transaction. The unique thing about IOTA is that you can actually make transactions without owning any tokens, which is incredibly useful for secure data transfer (and especially applications where you want to secure and ensure data integrity). Because we want to showcase the full capabilities of IOTA, for this part we will actually be sending around some tokens as well.

The sendTransfer function from the Javascript library basically takes an array of transfer objects (with address, value, message and tag fields), depth (determines how far into the Tangle the tip selection goes) and minWeightMagnitude (how much Proof of Work has to be done) as input and then does all the heavy lifting for you: it searches for inputs for you, it does the tip selection, attaches your transactions to the Tangle by doing Proof of Work and then sends it to your neighbors. What this function then returns is a bundle, which is the set of transactions which you just sent in your transaction. These transaction objects then have an updated nonce, branchTransaction, trunkTransaction and your signatures added.

{{CODE}}

// here we define the transfers object, each entry is an individual transaction

var transfer = [{

   'address': address,

   'value': 100,

   'message': 'ODGABDPCADTCGADBGANBCDADXCBDXCZCGAQAGAADTCGDGDPCVCTCGADBGAWBMDEAUCXCFDGDHDEAADTCGDGDPCVCTCEAGDTCBDHDEAKDXCHDWCEASBYBCCKBSAGAQD'

}]

// We send the transfer from this seed, with depth 4 and minWeightMagnitude 18

iota.api.sendTransfer(seed, 4, 18, transfer, function(e, bundle) {

   if (e) throw e;

   console.log("Successfully sent your transfer: ", bundle);

})

{{ENDCODE}}

Challenges for You

To make this tutorial more interactive and more demanding (kinda like a school lesson I suppose?), I set out 3 challenges for you to try and figure out yourself.

Challenge #1: Add Transaction Persistence

Making a transaction is not enough in order to make sure that you actually got the tokens which were sent to you. You must wait for the transaction to be confirmed. In IOTA we have this concept of transaction persistence, which basically tells you if a transaction is confirmed or not. In order to make the leaderboard complete, you should try to sort transactions by their confirmed value i.e. transactions which are confirmed. You have a variety of API calls available at your disposal for this. Look through the API docs to figure this out.

Challenge #2: Attach addresses to the Tangle

As mentioned above, you can attach an address to the Tangle in order to make the address generation process completely deterministic and increase the private key index counter. In the address generation process, include a sendTransfer function where you basically send an empty transaction to the newly generated address.

Challenge #3: Show Transaction History in send.html

Send.html currently lacks a history of outgoing transactions which were made. Figure out a way to get this data (hint: getAccountData is pretty useful).

Conclusion

In this tutorial we've looked at a Leaderboard application, which showcases IOTA's micropayments and data transfer capabilities. Once MAM (Masked Authenticated Messaging) is released, we will make a follow-up tutorial which showcases secure, encrypted data transfer with granular access management.

Quos ut hic cum labore sint.

Pariatur quis ad iure. Laudantium ut adipisci vitae repudiandae corporis. Qui laboriosam asperiores nostrum molestias eius quo quia. Deserunt nemo repellendus.

Provident nam voluptas quis sed voluptas.

Velit fugiat exercitationem rerum explicabo. Doloremque praesentium accusamus et. Suscipit tempora rerum quod.

Est sint dolorem. Facere molestiae facilis quo voluptatem. Dolor sed delectus officiis architecto fugit explicabo illo. Blanditiis ut iure maiores quia voluptatem facere veniam. Magni incidunt vitae alias.

Qui corporis magni voluptatem aperiam quam harum ratione id deleniti. Nemo molestias voluptatibus qui in. Pariatur unde iure doloribus. Illo deleniti similique.

Comments

More tutorials