Parsing raw transaction data using nknc or protobuf

Transaction data returned by gettransaction API is in protobuf encoding. It can be parsed to human readable content in a few different ways:

Using nknc

nknc can print a transaction by txn hash:

> ./nknc info -t 50353996096f0fbe6810bb906f39e120bb2d32345c73a03294692b22bf7d0c43
{
	"id": "1",
	"jsonrpc": "2.0",
	"result": {
		"attributes": "d56d0d8e8ee9bbcdaeb96b571e09e3ee939ab2f3e1415bf9dd0f704af8be6221",
		"fee": 0,
		"hash": "50353996096f0fbe6810bb906f39e120bb2d32345c73a03294692b22bf7d0c43",
		"nonce": 1499,
		"payloadData": "0a14d9d05ba538b0515f0b5916d0cbc7e9daf48efcd0121412c260d1a74fc3471994472097bc88ac9c5b2d2218809bee02",
		"programs": [
			{
				"code": "204f419174dee36699cab1ee40b399a0dc30ca0e35722dbb2d736498d93c3eec3aac",
				"parameter": "4075daee0d5cc83a25499887892639371d2f3df3796f66c720f8459a5169cdb5c36a4adf9fd62a04788a1781aa88a2b9f9f762622b0856a102f4c11bb414bc9d0e"
			}
		],
		"txType": "TRANSFER_ASSET_TYPE"
	}
}

The payloadData field returned is the raw data in hex string. You can tell nknc to return human readable data instead by adding --pretty, -p argument:

> ./nknc info -t 50353996096f0fbe6810bb906f39e120bb2d32345c73a03294692b22bf7d0c43 -p
{
	"id": "1",
	"jsonrpc": "2.0",
	"result": {
		"attributes": "d56d0d8e8ee9bbcdaeb96b571e09e3ee939ab2f3e1415bf9dd0f704af8be6221",
		"fee": 0,
		"hash": "50353996096f0fbe6810bb906f39e120bb2d32345c73a03294692b22bf7d0c43",
		"nonce": 1499,
		"payloadData": {
			"amount": 6000000,
			"recipient": "NKNDCJ2n8Rr7jWqEDDhhAKoxCh3TjHTd7bbh",
			"sender": "NKNXLoFHYTt8LBx9Hpq6HZzHxSnoUo9VzFFw"
		},
		"programs": [
			{
				"code": "204f419174dee36699cab1ee40b399a0dc30ca0e35722dbb2d736498d93c3eec3aac",
				"parameter": "4075daee0d5cc83a25499887892639371d2f3df3796f66c720f8459a5169cdb5c36a4adf9fd62a04788a1781aa88a2b9f9f762622b0856a102f4c11bb414bc9d0e"
			}
		],
		"txType": "TRANSFER_ASSET_TYPE"
	}
}

Using protobuf

The payloadData above can be parsed in any protobuf-supported language. You just need to compile transaction protobuf (can be found at https://github.com/nknorg/nkn/blob/master/pb/transaction.proto) to the language of your choice using protoc, and then you can parse the payloadData based on transaction type. For example, the above transfer transaction can be parsed in JavaScript using:

const transaction = require('nkn-wallet/lib/pb/transaction_pb'); // this is simply the compile pb file shipped in nkn-wallet-js. You can compile it yourself.

function hexToBytes(hex) {
  for (var bytes = [], c = 0; c < hex.length; c += 2) {
    bytes.push(parseInt(hex.substr(c, 2), 16));
  }
  return new Uint8Array(bytes);
}

let t = transaction.TransferAsset.deserializeBinary(hexToBytes("0a14d9d05ba538b0515f0b5916d0cbc7e9daf48efcd0121412c260d1a74fc3471994472097bc88ac9c5b2d2218809bee02"));

console.log(t.getAmount()); // in unit of 10^-8 NKN