Create custom transaction types

Custom transactions

Transactions are an essential part of blockchain applications that are created using the Lisk SDK.

The Lisk SDK provides a class BaseTransaction from which developers can inherit and extend from, to create custom transaction types.

The application-specific business logic for custom transaction types is defined according to an abstract interface that is common across all transaction types.

All of the default transaction types of the Lisk SDK transactions implement the abstract interface of the base transaction, and therefore the base transaction can be used as a model for custom transactions. It is also possible to inherit one of the default transaction types, in order to extend or modify them.

Register a custom transaction

Add your custom transaction type to your blockchain application by registering it to the application instance as shown below:

const { Application, genesisBlockDevnet } = require('lisk-sdk');

const MyTransaction = require('./my_transaction');

const app = new Application(genesisBlockDevnet);

app.registerTransaction(MyTransaction); (1)

app
    .run()
    .then(() => app.logger.info('App started...'))
    .catch(error => {
        console.error('Faced error in application', error);
        process.exit(1);
    });
1 Register the custom transaction.

For information on creating your own custom transaction, please follow the tutorials.

The BaseTransaction interface

The BaseTransaction class is the interface that all other Transaction Types need to inherit from, in order to be compatible with the Lisk SDK.

Required Properties

TYPE

The type is a unique identifier for your custom transaction within your own blockchain application. This can be thought of as the hallmark of a transaction. Set this constant to any number, except 0-12, which are reserved for the default transactions.

static TYPE: number

Required Methods

All of the abstract methods and properties on the base transaction’s interface are required to be implemented. These are all listed below:

prepare

prepare(store: StateStorePrepare): Promise<void>

In prepare() the data from the database is filtered and cached, that is needed in the applyAsset and undoAsset functions later.

validateAsset

validateAsset(): ReadonlyArray<TransactionError>

Before a transaction reaches the apply step it is validated. Check the transaction’s asset correctness from the schema perspective, (no access to StateStore here). Invalidate the transaction by pushing an error into the result array. Prepare the relevant information about the accounts, which will be accessible in the later steps during the apply and undo steps.

applyAsset

applyAsset(store: StateStore): ReadonlyArray<TransactionError>

The business use case of a transaction is implemented in the applyAsset method. It applies all of the necessary changes from the received transaction to the affected account(s), by calling store.set. Calling store.get will acquire all of the relevant data. The transaction that is currently processing is the function’s context, (e.g. this.amount). This transaction can be invalidated by pushing an error into the result array.

undoAsset

undoAsset(store: StateStore): ReadonlyArray<TransactionError>

The inversion of the applyAsset method. Undoes all of the changes to the accounts applied by the applyAsset step.

Additional Methods

To increase your application’s performance, the following functions should be overidden: verifyAgainstTransactions, assetFromSync, fromSync.

The BaseTransaction provides the default implementation of the methods revolving around the signatures. As your application matures it is possible to implement custom methods of how your transaction’s signature is derived: sign, getBytes, assetToBytes.

The Store

The Store is responsible for the caching and accessing transaction and account data. The store is available inside the prepare(), applyAsset() and undoAsset() methods and provides methods to get and set the data from the database.

Cache

How to cache data from the database
async prepare(store) {
    await store.account.cache([
        {
            address: this.senderId,
        },
    ]);
}

Filters

Depending on the datatype, there are different filters that can be applied, when caching accounts or transactions from the database.

The following table gives an overview, which filters are available, depending on the datatype of the filtered data.

Filter Type Filter Suffixes Description

BOOLEAN

_eql

returns entries that match the value

_ne

returns entries that do not match the value

TEXT

_eql

returns entries that match the value

_ne

returns entries that do not match the value

_in

returns entries that match any of values from the list

_like

returns entries that match the pattern

NUMBER

_eql

returns entries that match the value

_ne

returns entries that do not match the value

_gt

returns entries greater than the value

_gte

returns entries greater than or equal to the value

_lt

returns entries less than the value

_lte

returns entries less than or equal to the value

_in

returns entries that match any of values from the list

Caches all accounts in the list
async prepare(store) {
    await store.account.cache({
	    address_in: [
        	"16152155423726476379L",
		    "12087516173140285171L"
        ],
    });
}
Join different filters with OR combinator
async prepare(store) {
    await store.account.cache([
        {
            isDelegate_eq: false,
        },
        {
            balance_gt: 0,
        }
    ]);
}
Join different filters with AND combinator
async prepare(store) {
    await store.account.cache([
        {
            isDelegate_eq: false,
            balance_gt: 0,
        }
    ]);
}
Caches accounts based on data from the db
async prepare(store) {
    /**
     * Get packet account.
     */
    await store.account.cache([
        {
            address: this.recipientId,
        }
    ]);
    /**
     * Get sender and recipient accounts of the packet.
     */
    const pckt = store.account.get(this.recipientId);
    await store.account.cache([
        {
            address_in: [
                pckt.asset.carrier, pckt.asset.sender
            ]
        },
    ]);
}

Accounts

Two very useful filters for the accounts are asset_contains and asset_exists:

Caches all accounts that contain the asset key "foo"
async prepare(store) {
    await store.account.cache([
        {
            asset_exists: "foo",
        },
    ]);
}
Caches all accounts that contain the value "bar" in their asset
async prepare(store) {
    await store.account.cache([
        {
            asset_contains: "bar",
        },
    ]);
}

Getter

A getter retrieves a single element from the StateStore and requests an account object.

  • get(key) — Retrieve a single element from the store. The key here accepts an address.

  • getOrDefault(key) — Get account object from store or create default account if it does not exist.

  • find(fn) — Accepts a lambda expression for finding the data that matches the expression.

Gets the account of the sender
const sender = store.account.get(this.senderId);

Setter

A setter allows changes to be made to the overall StateStore, e.g. updating and saving a property for an amount object.

  • set(key, updatedObject) — Allows updating an account in the database (account is only read-write store).

store.account.set(sender.address, newObj);

Default transaction types

Transaction types 0-12 are reserved for the Lisk protocol. Do not use these to register custom transactions.

Each default transaction type implements a different use case of the Lisk network.

For a complete list of all default transaction types, please see the section Lisk Transactions of the Lisk Protocol.

What is the lifecycle of a transaction?

The lifecycle of a general transaction using the Lisk SDK can be summarized in 7 steps:

  1. A transaction is created and signed, (off-chain). The script to execute this is as follows: src/create_and_sign.ts.

  2. The transaction is sent to a network. This can be done by a third party tool, (such as curl or Postman). However this can also be achieved by using Lisk Commander, Lisk Desktop or Mobile. All of the tools need to be authorized to access an HTTP API of a network node.

  3. A network node receives the transaction and after a lightweight schema validation, adds it to a transaction pool.

  4. In the transaction pool, the transactions are firstly validated. In this step, only static checks are performed, which include schema validation and signature validation.

  5. Validated transactions go to the prepare step, as defined in the transaction class, which to limit the I/O database operations, prepares all the information relevant to properly apply or undo the transaction. The store with the prepared data is a parameter of the afore-mentioned methods.

  6. Delegates forge the valid transactions into blocks and broadcasts the blocks to the network. Each network node performs the apply and applyAsset steps, after the successful completion of the validate step.

  7. Shortly after a block is applied, it is possible that a node performs the undo step; (due to decentralized network conditions). If this occurs, then the block containing all of the included transactions is reverted in favor of a competing block.

While implementing a custom transaction, it is necessary to complete some of these steps. Often, a base transaction implements a default behavior. With experience, you may decide to override some of these base transaction methods, resulting in an implementation that is well-tailored and provides the best possible performance for your use case.