How To Build Simple .NET Apps Using miyabi Blockchain (Part 1)

Thomas Nguy
Aug 3, 2020 · 5 min read

In this series of short articles, I will guide you step by step on how to use the miyabi blockchain in real life applications.

The goal of this series is to teach developers how to build applications on top of the miyabi blockchain. Each of these tutorials will present a concrete problem that can be solved using blockchain technology. It will be followed by the solution and the detailed explanation of the implementation. I hope that through this journey, you will enjoy working with miyabi and consider using it for future applications.

In the first part, I will explain how to build a simple cryptocurrency wallet on miyabi.

Prerequisites :

  • Basic understanding of cryptography in blockchain
  • Read miyabi Documentation (Asset Table)

Quick Definitions :

What is miyabi? — miyabi is a proprietary blockchain solution developed by bitFlyer Blockchain. It is built to make practical use of blockchain technology in common applications by focusing on fast transaction speed and by providing powerful tools to query and operate data.
What is a table? — A table is a collection of data that is logically organized and stored in the blockchain. Each type of table defines its own view and the set of operations that can be performed on them.
What is a cryptocurrency wallet? — A cryptocurrency wallet is software that manages a digital asset. It deals with public and private keys and allows users to store or retrieve assets.

Scenario:

Alice owns a chain of cake shops. She wants to implement a reward system that will help her to boost her business by building customer loyalty and increasing retention rate. This system will issue a crypto token called “CookiePoint” to each customer based on a percentage of the total price of their purchases. CookiePoints can be freely transferred between customers or redeemed at her shop’s locations for extra items. Alice can generate as many CookiePoints as she wants as the central bank of this economy. However she wants to give to her customers the full ownership of their tokens and freedom to exchange without her control. For that reason Alice decided to use the miyabi blockchain in her backend system. It has the benefits of a traditional blockchain solution without the upcoming cost of sending transactions and providing enough tps to support her business.

Following Alice’s requirements, Miyabi’s Asset Table is the most suitable structure for storing our wallet’s data. The table supports natively all high level features that is needed to be implemented for a crypto-currency, including complex cryptographical permissions check and atomic transfers.

Get Started with Asset Module

The Asset Module allows the creation of an Asset Table in miyabi. The table keeps track of a logical view of the data organized by a Key-Value pairs format

<Address, Balance>.

The table natively supports the following operations:
- AssetGen: Increase the balance of an address by a specific amount, only the table owner can use this operation.
- AssetMove: Reduce the balance of an origin address by a specific amount, and increase the balance of a receiver address by the same amount at the same time. The transaction should be signed by the private key of the origin address.

In order to use the module, a method needs to be called to register all the module’s serialized objects type-code in the registry:

AssetTypesRegisterer.RegisterTypes();

We also need to create a general client singleton that will be used later on to broadcast transactions to miyabi:

var client = new Client(SdkConfig.Load(SDK_CONFIG_PATH));
var _generalClient = new GeneralApi(client);

Step 1: Creation of the asset table

Some parameters need to be defined when creating an asset table:
- Table name, an unique identifier of the table across the world state. The name of the cryptocurrency will be used for the table name. In this case, “CookiePoint”.
- Table’s owner, which is an address that holds permissions to perform restricted operations, such as minting tokens. We use Alice’s public key address.

var alicePubKey = PublicKey.Parse(ALICE_PUBLIC_KEY_ADDRESS);
var aliceAddress= new PublicKeyAddress(alicePubKey);
var assetTable = new CreateTable(new AssetTableDescriptor(
"CookiePoint", false, false, new []{aliceAddress}));

Let’s build the transaction along with a memo entry. It should be signed with a private key having “TableAdmin” permission:

Note: There are TableAdmin and TableOwner permissions. The first one allows operations on the table registry (such as create or delete tables) and the second one allows operations on the table that it owns (such as move asset, create entry etc…).

var memo = new MemoEntry(new []{"Point system for Alice's shops"});

var tx = TransactionCreator.SimpleSignedTransaction(
new ITransactionEntry[]{assetTable, memo},
new []{PrivateKey.Parse(TABLE_ADMIN_PRIVATE_KEY)});

And finally send the transaction to miyabi :

async Task SendTransaction(Transaction tx)
{
try
{
var send = await _generalClient.SendTransactionAsync(tx);
var result_code = send.Value;

if (result_code != TransactionResultCode.Success
&& result_code != TransactionResultCode.Pending)
{
//Transaction rejected, log result_code.
}
}
catch (Exception e)
{
//Log error.
}
}

Step 2: Mint asset

The table was created with Alice’s public key address as table owner. She has the ability to generate assets to any addresses using her private key. Let’s say she wants to generate 1,000,000 points to herself in order to distribute them to her customers.

var generateAsset = new AssetGen("CookiePoint", 1000000m, aliceAddress);

This time, the transaction should be signed using Alice’s private key (table owner) :

var tx = TransactionCreator.SimpleSignedTransaction(
new ITransactionEntry[]{generateAsset},
new []{PrivateKey.Parse(ALICE_PRIVATE_KEY))});

Broadcast the transaction like previously.

SendTransaction(tx);

Step 3: Build the wallet

Alice needs to build a wallet for her customers to manage their points. The wallet should manage each user’s private/public key, keep track of the total balance of the owner and allow sending points to another person, including to Alice, at her shops’ locations.

We define the wallet interface as the following.

public interface IWalletService
{
Address GetAddress();
Task Send(decimal amount, Address to);
Task<decimal> GetBalance();
}

miyabi provides several cryptographic packages for key-pair generation. Commonly we use SECP256k1, the same curve as Bitcoin.

private ICryptographicService _cryptographicService;

WalletService()
{
_cryptographicService = new Secp256k1EccService();
}

The cryptographic service abstracts all the complexity of generating keys and exposed high level functions that can directly be used within the application. The KeyPair needs to be stored within the wallet service in order to sign all the transactions.

private ICryptographicService _cryptographicService;
private KeyPair _keyPair;

Getting the address from the KeyPair is very straightforward:

public Address GetAddress()
{
return new PublicKeyAddress(_keyPair.PublicKey);
}

To send coins, we need to broadcast a transaction type “AssetMove” to miyabi signed by the wallet’s private key previously generated.

public async Task Send(decimal amount, Address to)
{
var from = GetAddress();
var moveCoin = new AssetMove("CookiePoint", amount, from, to);
var tx = TransactionCreator.SimpleSignedTransaction(
new ITransactionEntry[] {moveCoin},
new PrivateKey[] {_keyPair.PrivateKey});
await SendTransaction(tx);
}

AssetClient provides a high-level read operation on the asset table. It needs to be instantiated the same way as a the GeneralApi client.

var client = new Client(SdkConfig.Load(SDK_CONFIG_PATH));
var _assetClient = new AssetClient(client);

In the WalletService:

public async Task<decimal> GetBalance()
{
var myAddress = GetAddress();
var result = await _assetClient.GetAssetAsync("CookiePoint", myAddress);
return result.Value;
}

Step 4: Integrate WalletService within Alice’s payment system

Alice can start issuing tokens after purchases. Customers who have a wallet can display their own address to Alice (using a QR code for example) in order to receive points. Conversely, they can also consume their points by sending them back to Alice to redeem for items.

What’s next?
In this part, we learn how to build a sample wallet service for managing cryptocurrency on miyabi by using the asset module and the crypto package, and with very few lines of code.

In the next part, I will explain how to use a complex data structure on miyabi with the Entity Table and how it can be used to build a classified ads platform.