Transaction Processor Tutorial JavaScript


This tutorial covers the creation of a new Sawtooth Lake transaction family in JavaScript, based on the Sawtooth Lake SDK. We will construct a transaction handler which implements a distributed version of the multi-player game tic- tac-toe.


The SDK contains a fully-implemented version of tic-tac-toe. This tutorial is meant to demonstrate the relevant concepts, rather than to create a complete implementation. See the SDK for full implemenations in multiple languages.

A general description of tic-tac-toe, including the rules, can be found on Wikipedia at:

A full implementation of the tic-tac-toe transaction family can be found in



This tutorial assumes that you have gone through Getting Started with Hyperledger Sawtooth and are familiar with the concepts introduced there.

Prior to going through this tutorial, you should have a working Vagrant environment running to which you can login. Specific setup instructions are available in Environment Setup.

The Transaction Processor

There are two top-level components of a transaction processor: a processor class and a handler class. The SDK provides a general-purpose processor class. The handler class is application-dependent and contains the business logic for a particular family of transactions. Multiple handlers can be connected to an instance of the processor class.

Handlers get called in two ways:

  1. An apply method
  2. Various “metadata” methods

The metadata is used to connect the handler to the processor, and we’ll discuss it at the end of this tutorial. The bulk of the handler, however, is made up of apply and its helper functions, so that’s where we’ll start.

The apply Method

apply gets called with two arguments, transactionProcessRequest and stateStore. transactionProcessRequest holds the command that is to be executed (e.g. taking a space or creating a game), while stateStore stores information about the current state of the game (e.g. the board layout and whose turn it is).

The transaction contains payload bytes that are opaque to the validator core, and transaction family specific. When implementing a transaction handler the binary serialization protocol is up to the implementer.

Without yet getting into the details of how this information is encoded, we can start to think about what apply needs to do. apply needs to

  1. unpack the command data from the transaction,
  2. retrieve the game data from the state store,
  3. play the game, and
  4. save the updated game data.

Accordingly, a top-down approach to apply might look like this:

  apply (transactionProcessRequest, stateStore) {
    return _unpackTransaction(transactionProcessRequest)
    .then((transactionData) => {

    let stateData = _getStateData(transactionData.gameName, stateStore)

    let updatedGameData = _playXO(
    _storeGameData(transactionData.gameName, updatedGameData, stateStore)

Note that the third step is the only one that actually concerns tic-tac-toe; the other three steps all concern the coordination of data.



Transactions and Batches! contains a detailed description of how transactions are structured and used. Please read this document before proceeding, if you have not reviewed it.

So how do we get data out of the transaction? The transaction consists of a header and a payload. The header contains the “signer”, which is used to identify the current player. The payload will contain an encoding of the game name, the action (‘create’ a game, ‘take’ a space), and the space (which will be an empty string if the action isn’t ‘take’). So our _unpackTransaction function will look like this:

const _unpackTransaction = (transaction) =>
  new Promise((resolve, reject) => {
    let header = TransactionHeader.decode(transaction.header)
    let signer = header.signerPubkey
    try {
      let payload = _decodeData(transaction.payload)
      resolve({gameName: payload[0],
              action: payload[1],
              space: payload[2],
              signer: signer})
    } catch (err) {
      let reason =  new InvalidTransaction("Invalid payload serialization")

Before we say how exactly the transaction payload will be decoded, let’s look at _getStateData. Now, as far as the handler is concerned, it doesn’t matter how the game data is stored. The only thing that matters is that given a game name, the state store is able to give back the correct game data. (In our full XO implementation, the game data is stored in a Merkle-radix tree.)

const _getStateData = (gameName, stateStore) => {
    let address = _makeGameAddress(gameName)

    return stateStore.get([address])
    .then((stateEntries) => {
    try {
      let data =  _decodeData(stateEntries[address])
      if (data.length < 5){
        while (data.length < 5){
      return {board: data[0],
              gameState: data[1],
              player1: data[2],
              player2: data[3],
              storedName: data[4]}
    } catch(err) {
      throw new InternalError("Failed to deserialize game data." + err)

const _toInternalError = (err) => {
  let message = (err.message) ? err.message : err
  throw new InternalError(message)

By convention, we’ll store game data at an address obtained from hashing the game name prepended with some constant:

const _makeGameAddress = (gameName) => {
   let prefix = XO_NAMESPACE
   let gameHash = crypto.createHash('sha512').update(gameName).digest('hex').toLowerCase()
   return prefix + gameHash

Finally, we’ll store the game data. To do this, we simply need to encode the updated state of the game and store it back at the address from which it came.

const _storeGameData = (gameName, gameData, stateStore) => {
  let gameAddress = _makeGameAddress(gameName)

  let encodedGameData = _encodeData(gameData)

  let entries = {[gameAddress]: gameData}
  .then((gameAddresses) => {
    if (gameAddresses.length < 1) {
      throw new InternalError('State Error!')
    console.log(`Set ${gameAddress} to ${gameData}`)

So, how should we encode and decode the data? We have many options in binary encoding schemes; the binary data stored in the validator state is up to the implementer of the handler. In this case, we’ll encode the data as a simple UTF-8 comma-separated value string, but we could use something more sophisticated, BSON.

const _decodeData = (data) => {
  return data.toString().split(",")

const _encodeData = (data) => {
  return Buffer.from(data.join())

Playing the Game

All that’s left to do is describe how to play tic-tac-toe. The details here are fairly straighforward, and the _playXO function could certainly be implemented in different ways. To see our implementation, go to /project/sawtooth- core/sdk/examples/xo_javascript. We choose to represent the board as a string of length 9, with each character in the string representing a space taken by X, a space taken by O, or a free space. Updating the board configuration and the current state of the game proceeds straightforwardly.

The XOHandler Class

And that’s all there is to apply! All that’s left to do is set up the XOHandler class and its metadata. The metadata is used to register the transaction processor with a validator by sending it information about what kinds of transactions it can handle.

class XOHandler extends TransactionHandler {
  constructor () {
    super(XO_FAMILY, '1.0', 'csv-utf8', [XO_NAMESPACE])

  apply (transactionProcessRequest, stateStore) {

Note that the XOHandler class extends the TransactionHandler class defined in the JavaScript SDK.