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, in order to create custom transactions.

Skeleton of a custom transaction
const {
    BaseTransaction
} = require('@liskhq/lisk-transactions');

class MyCustomTransaction extends BaseTransaction {
  static get TYPE = /* ... */

  async prepare(store) { /* ... */ }
  validateAsset() { /* ... */ }
  async applyAsset(store) { /* ... */ }
  async undoAsset(store) { /* ... */ }
}

.1. Example of a custom transaction: 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;
    }

    /**
    * 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.
    */
	async applyAsset(store) {
        const errors = [];
        const sender = await 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 {
	        sender.asset = { hello: this.asset.hello };
            store.account.set(sender.address, sender);
        }
        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.
    */
	async undoAsset(store) {
		const sender = await store.account.get(this.senderId);
		sender.asset = null;
		store.account.set(sender.address, sender);
		return [];
	}
}

module.exports = HelloTransaction;

.2. Creating an instance of a transaction

How to create and sign a transaction
import {
    HelloTransaction,
} from 'lisk-hello-transactions';

const helloTransaction = new HelloTransaction({
    asset: {
        hello: this.state.hello,
    },
    fee: utils.convertLSKToBeddows('0.1').toString(),
    nonce: this.state.nonce.toString(),
});

helloTransaction.sign(networkIdentifier,this.state.passphrase);

.3. Registering a custom transaction

Add a custom transaction 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.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.
2 Registers the custom transaction with the application.

For more information on creating your own custom transactions, please refer to the following guides:

Fees

A transaction fee is a specific amount of tokens that needs to be paid by the sender of a transaction.

The fees for every transaction can be defined dynamically, however there is always a minimum amount that needs to be paid for a transaction. We define this minimum fee per transaction as shown below:

trs.minFee = trs.NAME_FEE + trs.MIN_FEE_PER_BYTE * trs.getBytes().length
Name space fee - NAME_FEE

Defines a specific amount of tokens that always need to be paid as a transaction fee, in addition to the fees generated by the MIN_FEE_PER_BYTE property. It defaults to 0, but can be overwritten as desired. Amongst the Lisk default transactions, only one transaction has a custom NAME_FEE: the delegate registration (Type 10) and with a NAME_FEE of 1000000000.

Minimum fee per byte - MIN_FEE_PER_BYTE

Defines the minimum amount of tokens that need to paid per byte of a particular transaction type. It defaults to 1000, but can be overwritten as desired.

The right choice of the minimum fee per byte MIN_FEE_PER_BYTE, will have a significant impact in the network. If the minimum required fee were too high, users would be discouraged from using the network. If the value were too low, attackers would be able to broadcast many valid transactions at a very low cost and congest the network.

Fee distribution

The specified fee is automatically deducted from the account of the sender, after the transaction is included in a block. The trs.fee, trs.minFee is burnt, whereas the trs.fee - trs.minFee is assigned to the delegate forging the block.

Choosing the right fee for a transaction

Transactions with higher fees will often be included faster into the blockchain, as forging delegates prefer to include transactions in their block, that provide them with a high amount of transaction fees. This is often the case if there are many transactions in the transaction pool, as it is not possible to include all of them in a single block. Transactions with lower fees in this case might remain in the transaction pool a little longer, until the transaction pool is less crowded.

Fee estimation algorithm

The user needs to be aware of the current suitable fee for transactions, which is related to the immediate past state of the network. Hence, it is reasonable to develop a fee estimation algorithm to recommend the fee that the users should include in their transaction, for it to be included in a block after a certain period of time.

Most frontend applications should assist the user by finding the right fee for a particular transaction. A simple code example demonstrating how to validate a transaction fee can be found in the Broadcast a transaction guide.

How to invalidate a transaction

In the case whereby a transaction remains in the transaction pool for a long time because of a fee that was too low, it is possible to send a new transaction with identical values, except the fee which of course should be increased. The new transaction with a higher fee will soon be included in a block, and therefore invalidate the old transaction with a low fee.

Is it possible to create transactions with no transaction fees?

Yes, it is still possible to develop custom transactions with no transaction fees by overriding the MIN_FEE_PER_BYTE property of a custom transaction to MIN_FEE_PER_BYTE=0.

Please be aware that this is generally not recommended, as it makes the network vulnerable to spam attacks. If you choose to set MIN_FEE_PER_BYTE to 0 or to a very low amount, think of alternative ways how to avoid spam attacks.

Default transaction types

Transaction types 0-15 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.

Name Type

transfer transaction

8

register delegate transaction

10

multisignature transaction

12

vote transaction

13

unlock transaction

14

proof of misbehaviour transaction

15

For more detailed explanations of all default transaction types, please see the section transactions of the Lisk protocol.

The BaseTransaction interface

The BaseTransaction class is the interface that all other transaction types need to inherit from, including the default transaction types, 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, 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

async 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

async applyAsset(store: StateStore): Promise<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

async undoAsset(store: StateStore): Promise<ReadonlyArray<TransactionError>>

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

Additional methods & properties

It’s possible to override the default values of MIN_FEE_PER_BYTE, NAME_FEE properties of a custom transaction depending on the use case.

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 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 provides an overview of 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 = await 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 = await 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 the updating of an account in the database (account is only read-write store).

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

What is the lifecycle of a transaction?

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

  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 performed by using 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, firstly the transactions are 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 specific use case.