Wrapping Up Our Dragonchain-Powered Asset Tracker: the API, Web UI, and Flutter App

Whew. I’m alive. Had an absurd few months professionally and personally (including competing in and winning a category of the Dragonchain hackathon which I’ll be talking about soon!), but I’m back to the “normal swing of things” and ready to kick out some more Dragonchain developer content.

Let’s kick things off by wrapping things up (on the asset tracker project).

Get the Git

In case you haven’t already seen it, you can view, clone, or fork the code I’ve been working with right over here:

dragonchain-asset-tracker (this link opens in a new window) by Dragonchain-Community (this link opens in a new window)

A NodeJS smart contract, API server, web demo, and NFC-enabled Flutter mobile app demonstrating blockchain-enabled asset tracking.

Where We Left Off

In the last installment, I talked about testing our smart contract code as we develop it and how important it is to include test-driven development principles in the process (cause no one wants bad data on a blockchain).

I covered manual testing using the DCTL tool and a tool like Insomnia to test the RESTful API plus my method for adding some light integration testing using a custom mock Dragonchain SDK client and dependency injection to ensure that our smart contract is ingesting and processing data as we expect.

I also promised I’d be talking more about even better testing in the future, and I will be (like soon).

For now, though, let’s wrap up this asset tracker project and discuss (briefly) the API server, web demo, and (extremely basic) Flutter app I built to tie it all together.

The API

So we have our fancy-shmancy smart contract all written up and doing smart contracty things, but how are we supposed to actually access the contract to get it doing that voodoo that it do so well?

(Sorry, I’m a little punchy this evening.)

We certainly don’t want to expose the credentials for actually accessing our central Dragonchain business node, even if we encrypt the credentials, as that opens an attack vector (although I think “wide open door to a house party with all of our most valuable possessions left in the foyer” is a more appropriate description).

Enter the very common solution to such problems: an API.

For almost every one of the projects I envision building using Dragonchain, I plan to have a RESTful API (or possibly a GraphQL interface once I learn how the hell it actually works).

Basically, we use the API as the protected and authenticated interface and shield that lives between the outside world (our customers) and our highly vulnerable data source (the Dragonchain L1 business node, a more traditional database, etc.).

My Super Fancy API Server

Is not very fancy at all.

Seriously. It’s just a basic RESTful API server built using very standard Node.js with Express and some goodies to handle CORS stuff. I didn’t even add proper routing (I’m still learning Node.js/Express).

The benefit of using Node.js and express, of course, is that the Dragonchain SDK already works as an NPM package, so there’s literally zero magic I have to work to be able to get my API talking to my business node.

Note: You’ll see that I added “authentication” that’s not safe at all; it’s just meant as a stub so that REAL authentication can be added later.

The one thing I will point out is that I didn’t code all of the Dragonchain client code directly into the API methods.

Instead, I separated those interfacing methods into a “helper” object and file and used dependency injection to pass the SDK client in so that we could add proper integration testing at some point and to keep the API methods themselves relatively simple.

Here’s one such helper method to get all of the assets in the system using the queryTransactions method of the SDK client:

getAssets: async (client, options) => {    
        try {
            const assetTransactions = await client.queryTransactions({
                transactionType: config.contractTxnType,
                redisearchQuery: `@response_type:{asset}`,
                limit: 999999
            });

            if (assetTransactions.response.results)
            {
                return assetTransactions.response.results.map(result => {return result.payload.response.asset});
            } else 
                return [];
        } catch (exception)
        {
            // Pass back to caller to handle gracefully //
            throw exception;
        }
}

Pretty simple, eh? We use the redisearchQuery option field to use our custom indexing to find transactions that resulted in creating an asset, then pass those raw asset objects back to the API method to do its thing.

In this case, “its thing” is to then use the helper AGAIN in a potentially big-ass Promise.all chain to pull the latest version of each asset directly off the object heap:

const assetObjects = await Promise.all(assets.map(async a => {return await helper.getCurrentAssetObject(client, {assetId: a.id})}));

By the way: I have it on good authority that the developers will be adding the ability to pull multiple smart contract heap objects in one client method call soon.

And that’s pretty much the flow of things on the API server.

Onward!

The Web Demo

Okay, so…

Okay.

I hate front end development. Let me just get that stated right out of the gate. I can DO front end work, but I don’t like it.

So don’t make fun of my web demo.

Or do, just not to my face. Fragile ego and what-not.

Anyhoo, the point of this web demo is not to show off the world’s coolest and fanciest web app. I just needed an easy way to:

  • Interact with my API
  • Do it in a way that illustrates what CAN be done by more competent UI developers
  • Provide code that doesn’t require knowledge of a framework like React or Vue or Angular, etc. to be able to get your head around it

So that’s what you get here. The interface lives entirely in index.html, and the code lives entirely in asset-tools.js in the public folder.

And I’m quite literally just calling the API with standard jQuery AJAX stuff to get things done and render them with a Bootstrap wrapper.

Now imagine what you could do with it if you’re a good front end developer.

That’s me, inspiring better developers to do what I’m too lazy to learn. 😀

To the finish!

The Flutter App

Okay, so remember that this WHOLE PROJECT was inspired by the Cardano/New Balance collaboration that involved scanning an NFC tag on your new pair of stupidly expensive shoes and “claiming” them forever on the blockchain.

Now if I’m a mediocre (that’s a stretch) front end WEB developer, I’m a god-awful mobile app developer.

Seriously. Ain’t my thing.

But I managed to get Flutter working by building with Android Studio on my Windows machine.

Now why did I need Flutter or some other mobile app framework to begin with? Because we need to access the NFC device functionality on our smart devices.

So with all of that said, and aside from using an AWESOME library that makes using the NFC features on smart devices a breeze, the mobile app is once again just using the API we’ve already built:

Future _postAssetData() async {
    String username = authenticatedCustodianId;
    String password = 'mypassword';
    String basicAuth = 'Basic ' + base64Encode(utf8.encode('$username:$password'));

    var res = await http.post(
        Uri.encodeFull(baseURL + "/custodian/assets/add-data"),
        headers: {"content-type": "application/json", "authorization": basicAuth},
        body: jsonEncode({
          "asset_external_data": {
            "assetId": _selectedAssetController.text,
            "external_data": {
              "data": {
                "nfcTagId": nfcTagId
              }
            }
          }
        })
    );

    print("Posted asset data");

  }

Seriously. I friggin love APIs.

Now what is useful to note is how simple this ultimately ended up being.

When I started my design for this whole project, I envisioned writing a JSON payload with all the asset data directly to the NFC tag so that it can “stand alone” and be read by even an offline mobile app to prove what the asset is, who owns it, etc.

This could absolutely still be done, but I’d have to think through ways to protect that data (since someone could tamper with it).

The much, much simpler solution is just to read the immutable and unique NFC tag ID, then read the asset’s data from a simple QR code that represents an asset’s ID on our blockchain, then pass both up to my API to log the association.

And presto: the NFC tag is now forever associated with our asset, and with another simple query to our Dragonchain node using our custom indexing, we can always and forever look up and verify an asset’s information including current ownership.

Nifty.

Wrapping Up

And there you have it folks.

It took roughly a bajillion times as long to write about the asset tracker project as it took to actually develop it as a functional proof-of-concept solution.

That’s incredible for this to be a smart contract-powered blockchain solution ready for interchaining with the Bitcoin, Ethereum, or other blockchain networks.

And to be 150% clear, I’m not tooting my own horn: it’s the hard work and magic enabled by the Dragonchain team that makes it possible.

I know there’s probably more detail I could have covered here, but I’d like to move on to some more exciting stuff that’s been going on behind the scenes in the time since I wrapped this project up.

That said, if there’s anything YOU want me to address or cover in more detail, hit me up on Twitter, in the Dragonchain Telegram, or on the Dragonchain Slack for developers.

Otherwise, and until next time,
John

Testing a Blockchain Asset Tracker on Dragonchain: the Node.js Smart Contract, Part 2

Annnnd I’m back. Gotta love when the cheap WordPress host you’ve used for years up and decides to shut down and you have to move in a hurry.

Ah well. It’s time to pick up where we left off, and while today’s subject may seem boring (because it is), it’s actually an INCREDIBLY important part of developing for any blockchain, Dragonchain included.

We’re gonna talk about testing our smart contracts and the challenges and tools we have to meet ’em. Let’s get after it.

Continue reading “Testing a Blockchain Asset Tracker on Dragonchain: the Node.js Smart Contract, Part 2”

Building a Blockchain Asset Tracker on Dragonchain: the Node.js Smart Contract, Part 1

And we’re back. It’s time to start exploring the core of our asset tracking blockchain solution.

(In case you missed the last post, I showed a demo and explained the design thinking behind this project: it’ll be very helpful to understanding what I discuss below.)

Let’s take a look at the smart contract that controls our assets.

Continue reading “Building a Blockchain Asset Tracker on Dragonchain: the Node.js Smart Contract, Part 1”

Building a Blockchain Asset Tracker on Dragonchain: Design Considerations

Alrighty, the code’s done and this thing works, so let’s start diving into how I built it.

First up, let’s discuss some of the design thinking I did for the first few days before I wrote the first line of code. Since I’m an “old hat” developer new to the blockchain world and paradigm, this was a critical phase for me on this project.

Continue reading “Building a Blockchain Asset Tracker on Dragonchain: Design Considerations”

Project: Asset Tracker, a Node.js Smart Contract on Dragonchain

So what do my old beat up Nike runners, Dragonchain, New Balance, and Cardano all have in common? Well the title of the post kinda gives it away, but….

I was inspired by the New Balance/Cardano collab that was launched recently. NFC tech combined with blockchain-based product authenticity verification? Sweet.

But then I got to thinking: the moving pieces of such a system aren’t really that complicated, and I bet I could build a functional proof-of-concept demo of it pretty quickly with Dragonchain given how easy and awesome Dragonchain smart contracts are to work with

So I did (or rather I am almost finished doing so…). Let’s talk about what this project series is actually going to cover.

Continue reading “Project: Asset Tracker, a Node.js Smart Contract on Dragonchain”

Our Second Dragonchain Smart Contract: a Node.js Example

Welcome back!

In our last post, we went through the start-to-finish process for deploying a simple, shell script-based, automatically invoked Dragonchain smart contract. It was neat.

Let’s do something neater.

Continue reading “Our Second Dragonchain Smart Contract: a Node.js Example”

Let’s Play with Docker (giggity)

I don’t know why Docker sounds dirty to me, but I’m apparently a 12 year old boy and it does.

Anyhoo, Docker is going to play a central role in building and maintaining smart contracts that run on Dragonchain. In this post, I’ll share my first experiments creating a simple Docker container, pushing it to Docker hub, and making sure it all works as expected.

Continue reading “Let’s Play with Docker (giggity)”

Let’s Play With DCTL and the Transaction Explorer

Before we dive into actually creating smart contracts and making blockchain magic, it’ll be worth taking ONE MORE POST to learn about the Dragonchain command line tool and a simple block explorer app we can use to see our transactions happening.

Continue reading “Let’s Play With DCTL and the Transaction Explorer”