Writing your first application

This guide will take you through the Symbol development cycle.

First, we will architect our solution combining some built-in features available in Symbol, such as mosaics and accounts. By the end of this guide, you will know how to issue and monitor transactions 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 mean paying 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

A 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 Symbol is the right 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.

Symbol is a flexible blockchain technology. Instead of uploading all the application logic into the blockchain, you can use its tested features through API calls to transfer and store 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, let’s identify the actors involved in the use case we want to solve:

  • The ticket vendor.
  • The customer.

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

Have you loaded an account with test symbol.xym? In the previous guide, you have learned how to create an account with Symbol CLI. This account will represent the ticket vendor account.

  1. Run the following command to verify if the ticket vendor account has symbol.xym units.
symbol-cli account info --profile testnet

You should see on your screen a line similar to:

Account Information
┌───────────────────┬────────────────────────────────────────────────┐
│ Property          │ Value                                          │
├───────────────────┼────────────────────────────────────────────────┤
│ Address           │ TCWYXK-VYBMO4-NBCUF3-AXKJMX-CGVSYQ-OS7ZG2-TLI  │
├───────────────────┼────────────────────────────────────────────────┤
│ 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 │
├──────────────────┼─────────────────┼─────────────────┼───────────────────┤
│ 5E62990DCAC5BE8A │ 750.0           │ 750000000       │ Never             │
└──────────────────┴─────────────────┴─────────────────┴───────────────────┘

This account owns 750 symbol.xym relative units. If your row after “Balance Information” is empty, follow the previous guide to get test currency.

  1. Create a second account with the CLI to identify the customer.
symbol-cli account generate --network TEST_NET --save --url http://api-01.us-east-1.096x.symboldev.network:3000 --profile customer

New Account

┌─────────────┬────────────────────────────────────────────────┐
│ Property    │ Value                                          │
├─────────────┼────────────────────────────────────────────────┤
│ Address     │ TCHBDE-NCLKEB-ILBPWP-3JPB2X-NY64OE-7PYHHE-32I  │
├─────────────┼────────────────────────────────────────────────┤
│ Public Key  │ E59...82F                                      │
├─────────────┼────────────────────────────────────────────────┤
│ Private Key │ 111...111                                      │
└─────────────┴────────────────────────────────────────────────┘

Monitoring the blockchain

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

However, receiving an OK response does not mean the transaction is valid or included in a block. For example, the transaction could be rejected because the issuer does not have enough symbol.xym, the message set is too large, or the fee set is too low.

A good practice is to monitor transactions before being announced to know when they get confirmed or rejected by the network.

1In a new terminal, monitor the transactions involving the ticket vendor’s account to know if they are confirmed or rejected by the network.

symbol-cli monitor all --address TCWYXK-VYBMO4-NBCUF3-AXKJMX-CGVSYQ-OS7ZG2-TLI

Creating the ticket

We are representing the ticket with Symbol 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.

Mosaics 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 the ticket back to the mosaic’s creator, avoiding the ticket reselling.

  1. Use the CLI with the ticket vendor account to create a new mosaic that will represent the ticket. This new mosaic can be configured as follows:
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.
symbol-cli transaction mosaic --amount 99 --supply-mutable --divisibility 0 --duration 1000 --max-fee 2000000 --sync --profile testnet
  1. After announcing the transaction, copy the mosaic id 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, you can check the error code description here.

Sending the ticket

Now that we have defined the mosaic, we will 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 TCHBDE…32I 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 = 'TCHBDE-NCLKEB-ILBPWP-3JPB2X-NY64OE-7PYHHE-32I';
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 symbol_sdk_1.MosaicId(mosaicIdHex);
// replace with customer address
const rawAddress = 'TCHBDE-NCLKEB-ILBPWP-3JPB2X-NY64OE-7PYHHE-32I';
const recipientAddress = symbol_sdk_1.Address.createFromRawAddress(rawAddress);
// replace with network type
const networkType = symbol_sdk_1.NetworkType.TEST_NET;
const transferTransaction = symbol_sdk_1.TransferTransaction.create(symbol_sdk_1.Deadline.create(), recipientAddress, [new symbol_sdk_1.Mosaic(mosaicId, symbol_sdk_1.UInt64.fromUint(1))], symbol_sdk_1.PlainMessage.create('enjoy your ticket'), networkType, symbol_sdk_1.UInt64.fromUint(2000000));
        // replace with node endpoint
        try (final RepositoryFactory repositoryFactory = new RepositoryFactoryVertxImpl(
                "http://api-01.us-east-1.096x.symboldev.network:3000")) {
            // replace with mosaic id
            final String mosaicIdHex = "7cdf3b117a3c40cc";
            final MosaicId mosaicId = new MosaicId(mosaicIdHex);

            // replace with customer address
            final String rawAddress = "TCHBDE-NCLKEB-ILBPWP-3JPB2X-NY64OE-7PYHHE-32I";
            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 network generation hash to make the transaction only valid for your network. Open nodeUrl + '/node/info' in a new browser tab and copy the meta.networkGenerationHash value.

// replace with ticket vendor private key
const privateKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
const account = Account.createFromPrivateKey(privateKey, networkType);
// replace with meta.networkGenerationHash (nodeUrl + '/node/info')
const networkGenerationHash = '1DFB2FAA9E7F054168B0C5FCB84F4DEB62CC2B4D317D861F3168D161F54EA78B';
const signedTransaction = account.sign(transferTransaction, networkGenerationHash);
// replace with ticket vendor private key
const privateKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA';
const account = symbol_sdk_1.Account.createFromPrivateKey(privateKey, networkType);
// replace with meta.networkGenerationHash (nodeUrl + '/node/info')
const networkGenerationHash = '1DFB2FAA9E7F054168B0C5FCB84F4DEB62CC2B4D317D861F3168D161F54EA78B';
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-01.us-east-1.096x.symboldev.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-01.us-east-1.096x.symboldev.network:3000';
const repositoryFactory = new symbol_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();
        }
symbol-cli transaction transfer --recipient-address TCHBDE-NCLKEB-ILBPWP-3JPB2X-NY64OE-7PYHHE-32I --mosaics 7cdf3b117a3c40cc::1 --message enjoy_your_ticket --max-fee 2000000 --sync
  1. Look at the terminal window where you are monitoring transactions. When the transaction appears as confirmed, you can check if the customer has received the ticket with the following command.
symbol-cli account info --profile customer

Did we solve the use case?

  • ✅ Identify each customer: Creating Symbol 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 Symbol built-in features.