Writing your first application

This guide will take you through the Bitxor development cycle.

First, we will architect our solution combining some built-in features available in Bitxor, such as tokens and accounts. By the end of this guide, you will know how to issue and monitor transactions on the blockchain.

Use case

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/bitxor-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 Bitxor 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.

Bitxor 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 bitxor? In the previous guide, you have learned how to create an account with Bitxor CLI. This account will represent the ticket vendor account.

  1. Run the following command to verify if the ticket vendor account has bitxor units.

    bitxor-cli account info --profile testnet
    

    You should see on your screen a line similar to:

    Account Information
    ┌───────────────────┬────────────────────────────────────────────────┐
    │ PropertyValue                                          │
    ├───────────────────┼────────────────────────────────────────────────┤
    │ Address           │ BXRYXK-VYBMO4-NBCUF3-AXKJMX-CGVSYQ-OS7ZG2-TLI  │
    ├───────────────────┼────────────────────────────────────────────────┤
    │ Address Height    │ 1                                              │
    ├───────────────────┼────────────────────────────────────────────────┤
    │ Public Key        │ 203...C0A                                      │
    ├───────────────────┼────────────────────────────────────────────────┤
    │ Public Key Height │ 3442                                           │
    ├───────────────────┼────────────────────────────────────────────────┤
    │ Importance        │ 0                                              │
    ├───────────────────┼────────────────────────────────────────────────┤
    │ Importance Height │ 0                                              │
    └───────────────────┴────────────────────────────────────────────────┘
    
    Balance Information
    ┌──────────────────┬─────────────────┬─────────────────┬───────────────────┐
    │ Token Id        │ Relative Amount │ Absolute Amount │ Expiration Height │
    ├──────────────────┼─────────────────┼─────────────────┼───────────────────┤
    │ 5E62990DCAC5BE8A │ 750.0           │ 750000000       │ Never             │
    └──────────────────┴─────────────────┴─────────────────┴───────────────────┘
    

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

  2. Create a second account with the CLI to identify the customer.

    bitxor-cli account generate --network TEST_NET --save \
               --url <NODE_URL> --profile customer
    
    New Account
    
    ┌─────────────┬────────────────────────────────────────────────┐
    │ PropertyValue                                          │
    ├─────────────┼────────────────────────────────────────────────┤
    │ Address     │ BXRBDE-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 bitxor, 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.

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

    bitxor-cli monitor all --address BXRYXK-VYBMO4-NBCUF3-AXKJMX-CGVSYQ-OS7ZG2-TLI
    

Creating the ticket

We are representing the ticket with Bitxor tokens. This feature can be used to represent any asset on the blockchain, such as objects, tickets, coupons, stock share representation, and even your cryptocurrency.

Tokens 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 token’s creator, avoiding the ticket reselling.

  1. Use the CLI with the ticket vendor account to create a new token that will represent the ticket. This new token can be configured as follows:

    Property

    Value

    Description

    Divisibility

    0

    The token units must not be divisible. No one should be able to send “0.5 tickets”.

    Duration

    1000

    The token will be registered for 1000 blocks.

    Amount

    99

    The number of tickets you are going to create.

    Supply mutable

    True

    The token supply can change at a later point.

    Transferable

    False

    The token can be only transferred back to the token creator.

    bitxor-cli transaction token --amount 99 --supply-mutable \
               --divisibility 0 --duration 1000 --max-fee 2000000 \
               --sync --profile testnet
    
  2. After announcing the transaction, copy the token id displayed in the terminal.

    The new token id is: 7cdf3b117a3c40cc
    

    The transaction should appear as confirmed after 30 seconds at most. If the terminal raises an error, you can check the error code description here.

Sending the ticket

Now that we have defined the token, 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 wait for the transaction to be included on the blockchain. A transaction will be dropped if it stays unconfirmed after this amount of time. The parameter is defined in hours and must be in the 1 to 6 range (1 to 48 for Aggregate bonded transactions).

    Recipient

    BXRBDE…32I

    The recipient account address. In this case, the customer’s address.

    Tokens

    [1 7cdf3b117a3c40cc]

    The array of tokens to send.

    Message

    enjoy your ticket

    The attached message.

    Network

    TEST_NET

    The network type.

    // replace with token id
    const tokenIdHex = '7cdf3b117a3c40cc';
    const tokenId = new TokenId(tokenIdHex);
    // replace with customer address
    const rawAddress = 'BXRBDE-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(epochAdjustment),
      recipientAddress,
      [new Token(tokenId, UInt64.fromUint(1))],
      PlainMessage.create('enjoy your ticket'),
      networkType,
      UInt64.fromUint(2000000),
    );
    
    // replace with token id
    const tokenIdHex = '7cdf3b117a3c40cc';
    const tokenId = new bitxor_sdk_1.TokenId(tokenIdHex);
    // replace with customer address
    const rawAddress = 'BXRBDE-NCLKEB-ILBPWP-3JPB2X-NY64OE-7PYHHE-32I';
    const recipientAddress = bitxor_sdk_1.Address.createFromRawAddress(rawAddress);
    // replace with network type
    const networkType = bitxor_sdk_1.NetworkType.TEST_NET;
    const transferTransaction = bitxor_sdk_1.TransferTransaction.create(
        bitxor_sdk_1.Deadline.create(epochAdjustment),
        recipientAddress, [new bitxor_sdk_1.Token(tokenId, bitxor_sdk_1.UInt64.fromUint(1))],
        bitxor_sdk_1.PlainMessage.create('enjoy your ticket'),
        networkType,
        bitxor_sdk_1.UInt64.fromUint(2000000),
    );
    
            // replace with node endpoint
            try (final RepositoryFactory repositoryFactory = new RepositoryFactoryVertxImpl(
                    "NODE_URL")) {
                // replace with token id
                final String tokenIdHex = "7cdf3b117a3c40cc";
                final TokenId tokenId = new TokenId(tokenIdHex);
    
                // replace with customer address
                final String rawAddress = "BXRBDE-NCLKEB-ILBPWP-3JPB2X-NY64OE-7PYHHE-32I";
                final UnresolvedAddress recipientAddress = Address.createFromRawAddress(rawAddress);
                final NetworkType networkType = repositoryFactory.getNetworkType().toFuture().get();
    
                final Token token = new Token(tokenId, BigInteger.valueOf(1));
                final TransferTransaction transferTransaction = TransferTransactionFactory
                        .create(
                                networkType,
                                recipientAddress,
                                Collections.singletonList(token),
                                PlainMessage.create("Enjoy your ticket"))
                        .maxFee(BigInteger.valueOf(2000000)).build();
    

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

  2. 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 NODE_URL /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 = bitxor_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);
    
  3. Once signed, announce the transaction to the network.

    // replace with node endpoint
    const nodeUrl = 'NODE_URL';
    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 = 'NODE_URL';
    const repositoryFactory = new bitxor_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();
            }
    
    bitxor-cli transaction transfer --recipient-address BXRBDE-NCLKEB-ILBPWP-3JPB2X-NY64OE-7PYHHE-32I --tokens 7cdf3b117a3c40cc::1 --message enjoy_your_ticket --max-fee 2000000 --sync
    
  4. 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.

    bitxor-cli account info --profile customer
    

Did we solve the use case?

  • ✅ Identify each customer: Creating Bitxor accounts for each customer.

  • ✅ Avoid ticket reselling: Creating a non-transferable token.

  • ✅ Avoid non-authentic tickets and duplicate ones: Creating a unique token.

Continue learning about more about Bitxor built-in features.