Create a custom transaction

Custom transactions

Transactions are an essential part of blockchain applications that are created using the Lisk SDK, as they define the set of actions that can be performed by users in the network. Each transaction belongs to a specific transaction type that is registered in the network.

The Lisk SDK provides a BaseTransaction interface from which developers can extend from, to create custom transactions.

Example of a custom transaction type: The HelloTransaction

Contents of transactions/hello_transaction.js
const {
    BaseTransaction,
    TransactionError
} = require('@liskhq/lisk-transactions');

class HelloTransaction extends BaseTransaction {

    /**
    * Set the `HelloTransaction` transaction TYPE to `20`.
    * Every time a transaction is received, it is differentiated by the type.
    */
    static get TYPE () {
        return 20;
    }

    /**
    * Set the `HelloTransaction` transaction FEE to 1 LSK.
    * Every time a user posts a transaction to the network, the transaction fee is paid to the delegate who includes the transaction into the block that the delegate forges.
    */
    static get FEE () {
        return `${10 ** 8}`; // (= 1 LSK)
    };

    /**
    * Prepares the necessary data for the `apply` and `undo` step.
    * The "hello" property will be added only to the sender's account, therefore it is the only resource required in the `applyAsset` and `undoAsset` steps.
    */
	async prepare(store) {
		await store.account.cache([
			{
				address: this.senderId,
			},
		]);
	}

    /**
    * Validation of the value of the "hello" property, defined by the `HelloTransaction` transaction signatory.
    * In the implementation shown below, it checks that the value of the "hello" property needs to be a string which does not exceed 64 characters.
    */
	validateAsset() {
		const errors = [];
		if (!this.asset.hello || typeof this.asset.hello !== 'string' || this.asset.hello.length > 64) {
			errors.push(
				new TransactionError(
					'Invalid "asset.hello" defined on transaction',
					this.id,
					'.asset.hello',
					this.asset.hello,
					'A string value no longer than 64 characters',
				)
			);
		}
		return errors;
	}

    /**
    * applyAsset is where the custom logic of the Hello World app is implemented.
    * applyAsset() and undoAsset() uses the information about the sender's account from the `store`.
    * Here it is possible to store additional information regarding the accounts using the `asset` field. The content property of "hello" transaction's asset is saved into the "hello" property of the account's asset.
    */
	applyAsset(store) {
        const errors = [];
        const sender = store.account.get(this.senderId);
        if (sender.asset && sender.asset.hello) {
            errors.push(
                new TransactionError(
                    'You cannot send a hello transaction multiple times',
                    sender.asset.hello,
                    '.asset.hello',
                    this.asset.hello
                )
            );
        } else {
            const newObj = { ...sender, asset: { hello: this.asset.hello } };
            store.account.set(sender.address, newObj);
        }
        return errors; // array of TransactionErrors, returns empty array if no errors are thrown
	}

    /**
    * Inverse of `applyAsset`.
    * Undoes the changes made in applyAsset() step - reverts to the previous value of "hello" property, if not previously set this will be null.
    */
	undoAsset(store) {
		const sender = store.account.get(this.senderId);
		const oldObj = { ...sender, asset: null };
		store.account.set(sender.address, oldObj);
		return [];
	}
}

module.exports = HelloTransaction;

Register a custom transaction type

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

Contents of index.js
const { Application, genesisBlockDevnet, configDevnet} = require('lisk-sdk');
const HelloTransaction = require('./hello_transaction'); (1)

configDevnet.app.label = 'hello-world-blockchain-app';
//configDevnet.components.storage.user = 'lisk';
//configDevnet.components.storage.password = 'password';

const app = new Application(genesisBlockDevnet, configDevnet);
app.registerTransaction(HelloTransaction); (2)

app
    .run()
    .then(() => app.logger.info('App started...'))
    .catch(error => {
        console.error('Faced error in application', error);
        process.exit(1);
    });
1 Imports the custom transaction type.
2 Registers the custom transaction type with the application.
For more information on creating your own custom transaction types, please follow the tutorials.

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.

The BaseTransaction interface

The BaseTransaction class is the interface that all other transaction types - including the default transaction types - need to inherit from, in order to be compatible with the Lisk SDK.

See the BaseTransaction in the lisk-sdk repository on Github.

Required properties

The following properties and methods need to be implemented by a custom transaction type, when extending from the BaseTransaction:

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

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 logic 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.

Best practice: Always extend a custom transaction type from the BaseTransaction

It is also possible to extend from one of the default transactions or other custom transactions, in order to extend or modify them.

In most cases though, this is not recommended because updates in the logic of the inherited transaction can break the logic of the custom transaction.

To avoid the possibility of incompatibilities, always extend from the BaseTransaction:

Extending from the BaseTransaction
const {
    BaseTransaction,
    TransactionError
} = require('@liskhq/lisk-transactions');

class HelloTransaction extends BaseTransaction {
[...]

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

All available filters on GitHub
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
            ]
        },
    ]);
}

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.

Getters are used inside of the applyAsset() and undoAsset() functions of a custom transaction.

  • 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.

Setters are used inside of the applyAsset() and undoAsset() functions of a custom transaction.

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

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

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.