Writing your first application

This guide will take you through the Catapult development cycle. First, we will architect our solution combining some built-in features available in Catapult, such as Mosaics and Accounts. Then, you will record your first transaction on the blockchain.

Background

The secondary ticket market, also known as the resale market, is the exchange of tickets that happens between individuals after they have purchased a ticket from an initial vendor. The initial vendor could be the event website, an online ticket vending platform, a shop, or a stall at the entrance of the event.

Buying a ticket from someone that is not the initial vendor does not necessarily only mean to pay more for the ticket. There is the chance to be a victim of buying a fake or duplicate ticket, where the initial original vendor can’t do anything to solve the issue.

What do we want to solve?

../_images/getting-started.png

Authorization model

The ticket vendor wants to set up a system to:

  1. Identify each ticket and customer.
  2. Avoid ticket reselling.
  3. Avoid non-authentic tickets and duplicate ones.

Why Catapult is a good choice?

Blockchain technology makes sense in cases where:

  • There are different participants involved.
  • These participants need to trust each other.
  • There is a need to keep track of an immutable set of events.

Catapult is a flexible blockchain technology. Instead of uploading all the application logic into the blockchain, you can use its tested features through API calls for transfer and storage of value, authorization, traceability, and identification.

The rest of the code will remain off-chain. This reduces the inherent immutability risk, as you could change the process when necessary.

Creating an account for each participant

First, identify the actors involved in the problem to solve:

  • The ticket vendor.
  • The customer.

We have decided to represent the ticket vendor and customer as separate accounts. Each account is unique and identified by an address. An account has access to a deposit box on the blockchain, which can be modified with an appropriate private key.

1. Have you loaded an account with test symbol.xym? The account you have loaded in NEM2-CLI represents the ticket vendor. After running the following command, you should see on your screen a line similar to:

nem2-cli account info --profile testnet

Account Information
┌───────────────────┬────────────────────────────────────────────────┐
│ Property          │ Value                                          │
├───────────────────┼────────────────────────────────────────────────┤
│ Address           │ TCVQ2R-XKJQKH-4RJZWG-DARWJ6-V4J4W7-F4DGH6-ZFAB │
├───────────────────┼────────────────────────────────────────────────┤
│ Address Height    │ 1                                              │
├───────────────────┼────────────────────────────────────────────────┤
│ Public Key        │ 203...C0A                                      │
├───────────────────┼────────────────────────────────────────────────┤
│ Public Key Height │ 3442                                           │
├───────────────────┼────────────────────────────────────────────────┤
│ Importance        │ 0                                              │
├───────────────────┼────────────────────────────────────────────────┤
│ Importance Height │ 0                                              │
└───────────────────┴────────────────────────────────────────────────┘

Balance Information
┌──────────────────┬─────────────────┬─────────────────┬───────────────────┐
│ Mosaic Id        │ Relative Amount │ Absolute Amount │ Expiration Height │
├──────────────────┼─────────────────┼─────────────────┼───────────────────┤
│ 51A99028058245A8 │ 750.0           │ 750000000       │ Never             │
└──────────────────┴─────────────────┴─────────────────┴───────────────────┘

This account owns 750 symbol.xym units. If your row after mosaics is empty, follow the previous guide to get test currency.

  1. Create a second account to identify the customer.
nem2-cli account generate --network TEST_NET --save --url http://api-xym-harvest-3-01.us-west-2.nemtech.network:3000 --profile customer

New Account

┌─────────────┬────────────────────────────────────────────────┐
│ Property    │ Value                                          │
├─────────────┼────────────────────────────────────────────────┤
│ Address     │ TBULEA-UG2CZQ-ISUR44-2HWA6U-AKGWIX-HDABJV-IPS4 │
├─────────────┼────────────────────────────────────────────────┤
│ Public Key  │ E59...82F                                      │
├─────────────┼────────────────────────────────────────────────┤
│ Private Key │ 111...111                                      │
└─────────────┴────────────────────────────────────────────────┘

Monitoring the blockchain

Accounts change the blockchain state through transactions. Once an account announces a transaction, if properly formed, the server will return an OK response.

Receiving an OK response does not mean the transaction is valid, or included in a block. A good practice is to monitor transactions before being announced.

In a new terminal, monitor which transactions involving the ticket vendor’s address are confirmed and which of them are rejected by the network.

nem2-cli monitor all --address TCVQ2R-XKJQKH-4RJZWG-DARWJ6-V4J4W7-F4DGH6-ZFAB

Creating the ticket

We are representing the ticket with Catapult Mosaics. This feature can be used to represent any asset on the blockchain, such as objects, tickets, coupons, stock share representation, and even your cryptocurrency. They have configurable properties, which are defined at the moment of their creation For example, we opt to set transferable property to false. This means that the customer can only send back the ticket to the creator of the mosaic, avoiding the ticket reselling.

  1. Create a new mosaic to represent the ticket configured as follows with the ticket vendor account.
Property Value Description
Divisibility 0 The mosaic units must not be divisible. No one should be able to send “0.5 tickets”.
Duration 1000 The mosaic will be registered for 1000 blocks.
Amount 99 The number of tickets you are going to create.
Supply mutable True The mosaic supply can change at a later point.
Transferable False The mosaic can be only transferred back to the mosaic creator.
nem2-cli transaction mosaic --amount 99 --supply-mutable --divisibility 0 --duration 1000 --max-fee 2000000 --sync
  1. After announcing the transaction, copy the MosaicId displayed in the terminal.
The new mosaic id is: 7cdf3b117a3c40cc

The transaction should appear as confirmed after ±15 seconds. If the terminal raises an error, check the error code meaning here.

Sending the ticket

Now that we have defined the mosaic, we are going to send one ticket unit to a customer announcing a TransferTransaction.

  1. Open a new file, and define a TransferTransaction with the following values.
Property Value Description
Deadline Default (2 hours) The maximum amount of time to include the transaction on the blockchain. A transaction will be dropped if it stays unconfirmed after the stipulated time. The parameter is defined in hours and must in a range of 1 to 23 hours.
Recipient TBULEA…IPS4 The recipient account address. In this case, the customer’s address.
Mosaics [1 7cdf3b117a3c40cc] The array of mosaics to send.
Message enjoy your ticket The attached message.
Network TEST_NET The network type.
// replace with mosaic id
const mosaicIdHex = '7cdf3b117a3c40cc';
const mosaicId = new MosaicId(mosaicIdHex);
// replace with customer address
const rawAddress = 'TBULEA-UG2CZQ-ISUR44-2HWA6U-AKGWIX-HDABJV-IPS4';
const recipientAddress = Address.createFromRawAddress(rawAddress);
// replace with network type
const networkType = NetworkType.TEST_NET;

const transferTransaction = TransferTransaction.create(
    Deadline.create(),
    recipientAddress,
    [new Mosaic(mosaicId, UInt64.fromUint(1))],
    PlainMessage.create('enjoy your ticket'),
    networkType,
    UInt64.fromUint(2000000));
// replace with mosaic id
const mosaicIdHex = '7cdf3b117a3c40cc';
const mosaicId = new nem2_sdk_1.MosaicId(mosaicIdHex);
// replace with customer address
const rawAddress = 'TBULEA-UG2CZQ-ISUR44-2HWA6U-AKGWIX-HDABJV-IPS4';
const recipientAddress = nem2_sdk_1.Address.createFromRawAddress(rawAddress);
// replace with network type
const networkType = nem2_sdk_1.NetworkType.TEST_NET;
const transferTransaction = nem2_sdk_1.TransferTransaction.create(nem2_sdk_1.Deadline.create(), recipientAddress, [new nem2_sdk_1.Mosaic(mosaicId, nem2_sdk_1.UInt64.fromUint(1))], nem2_sdk_1.PlainMessage.create('enjoy your ticket'), networkType, nem2_sdk_1.UInt64.fromUint(2000000));
        // replace with node endpoint
        try (final RepositoryFactory repositoryFactory = new RepositoryFactoryVertxImpl(
                "http://api-xym-harvest-3-01.us-west-2.nemtech.network:3000")) {
            // replace with mosaic id
            final String mosaicIdHex = "7cdf3b117a3c40cc";
            final MosaicId mosaicId = new MosaicId(mosaicIdHex);

            // replace with customer address
            final String rawAddress = "TBULEA-UG2CZQ-ISUR44-2HWA6U-AKGWIX-HDABJV-IPS4";
            final UnresolvedAddress recipientAddress = Address.createFromRawAddress(rawAddress);
            final NetworkType networkType = repositoryFactory.getNetworkType().toFuture().get();

            final Mosaic mosaic = new Mosaic(mosaicId, BigInteger.valueOf(1));
            final TransferTransaction transferTransaction = TransferTransactionFactory
                    .create(
                            networkType,
                            recipientAddress,
                            Collections.singletonList(mosaic),
                            PlainMessage.create("Enjoy your ticket"))
                    .maxFee(BigInteger.valueOf(2000000)).build();

Although the transaction is defined, it has not been announced to the network yet.

  1. Sign the transaction with the ticket vendor account, so that the network can verify the authenticity of the transaction.

Note

Include the first block generation hash to make the transaction only valid for your network. Open nodeUrl + '/block/1' in a new browser tab and copy the meta.generationHash value.

// replace with ticket vendor private key
const privateKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
const account = Account.createFromPrivateKey(privateKey, networkType);
// replace with meta.generationHash (nodeUrl + '/block/1')
const networkGenerationHash = '45870419226A7E51D61D94AD728231EDC6C9B3086EF9255A8421A4F26870456A';
const signedTransaction = account.sign(transferTransaction, networkGenerationHash);
// replace with ticket vendor private key
const privateKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
const account = nem2_sdk_1.Account.createFromPrivateKey(privateKey, networkType);
// replace with meta.generationHash (nodeUrl + '/block/1')
const networkGenerationHash = '45870419226A7E51D61D94AD728231EDC6C9B3086EF9255A8421A4F26870456A';
const signedTransaction = account.sign(transferTransaction, networkGenerationHash);
            // replace with ticket vendor private key
            final String privateKey = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
            // replace with network generation hash
            final String generationHash = repositoryFactory.getGenerationHash().toFuture().get();

            final Account account = Account
                    .createFromPrivateKey(privateKey, networkType);
            final SignedTransaction signedTransaction = account
                    .sign(transferTransaction, generationHash);
  1. Once signed, announce the transaction to the network.
// replace with node endpoint
const nodeUrl = 'http://api-xym-harvest-3-01.us-west-2.nemtech.network:3000';
const repositoryFactory = new RepositoryFactoryHttp(nodeUrl);

const transactionHttp = repositoryFactory.createTransactionRepository();

transactionHttp
    .announce(signedTransaction)
    .subscribe((x) => console.log(x), (err) => console.error(err));
// replace with node endpoint
const nodeUrl = 'http://api-xym-harvest-3-01.us-west-2.nemtech.network:3000';
const repositoryFactory = new nem2_sdk_1.RepositoryFactoryHttp(nodeUrl);
const transactionHttp = repositoryFactory.createTransactionRepository();
transactionHttp
    .announce(signedTransaction)
    .subscribe((x) => console.log(x), (err) => console.error(err));
            final TransactionRepository transactionRepository = repositoryFactory
                    .createTransactionRepository();
            transactionRepository.announce(signedTransaction).toFuture().get();
        }
nem2-cli transaction transfer --recipient-address TBULEA-UG2CZQ-ISUR44-2HWA6U-AKGWIX-HDABJV-IPS4 --mosaics 7cdf3b117a3c40cc::1 --message enjoy_your_ticket --max-fee 2000000 --sync
  1. When the transaction appears as confirmed, check if the customer has received the ticket.
nem2-cli account info --profile customer

Did we solve the use case?

  • ✅ Identify each customer: Creating Catapult accounts for each customer.
  • ✅ Avoid ticket reselling: Creating a non-transferable mosaic.
  • ✅ Avoid non-authentic tickets and duplicate ones: Creating a unique mosaic.

Continue learning about more about Catapult built-in features.