How to build an app on Cosmos Blockchain SDK?

business resilience

Cosmos is a blockchain platform for developing and connecting parallel independent blockchains into a large interoperable network. It offers a complete set of tools for multiple tasks, including hosting a dApp in the Cosmos Hub ecosystem, building enterprise blockchains or implementing a small mode for everyone’s usage.

Before Cosmos arrived, blockchains were siloed and unable to interact with each other. Cosmos overcomes these issues with a new vision. Let’s understand how Cosmos fit in the broader blockchain ecosystem and build an app using Cosmos SDK.

How does Cosmos fit in the blockchain ecosystem?

To know how Cosmos fits in the blockchain ecosystem, we first need to understand the limitations that other platforms such as Ethereum could not overcome. Following are some of the limitations that led to the introduction of the Cosmos blockchain platform:

  1. Scalability
    dApps built on top of Ethereum are executed by a rate of 15 transactions per second. It is because Ethereum uses proof-of-work and the Ethereum dApps compete for specific resources of a single blockchain.
  2. Sovereignty
    One of the limitations is that each application is restricted in sovereignty as they all share the same environment. It creates two layers of governance: application and that of the underlying environment. If you find any bug in the application, nothing can be done about it without the approval of the governance of the Ethereum platform. If the app needs a new feature in the EVM, it has to depend on the governance of the Ethereum platform to accept it.
  3. Usability
    It is the low flexibility offered to developers. Since EVM is a sandbox that accommodates all use cases, it optimizes for the average use case. Therefore, developers have to make compromises on the efficiency and design of the application. Also, they are limited to only a few programming languages and cannot implement the code execution.

The restrictions are not specific to Ethereum but to all blockchains that create a single platform that would fit all use cases. This is where Cosmos comes into the picture.

A glance at the Cosmos Blockchain

Cosmos enables developers to build blockchains and break the barrier between blockchains by allowing them to communicate. The goal of Cosmos blockchain is to create an internet of blockchains, a network that enables blockchains to interact with each other in a decentralized way.

With Cosmos, blockchains can process transactions quickly, maintain sovereignty and interact with other blockchains in the ecosystem, making it ideal for a wide range of use cases.

The goal is achieved via a set of open-source tools, including Cosmos SDK, IBC and Tendermint, designed to allow people to develop secure, custom and scalable blockchain apps. Let’s have a look at some of the essential tools in the ecosystem and understand how to build a blockchain app on Cosmos blockchain.

How to build a blockchain app with Cosmos SDK?

The Cosmos SDK is the modular software suite for the development of blockchain apps and blockchains.

The platform comprises a template project, which provides the full blockchain app source ready and allows developers to spend time only on the application logic. The SDK takes care of the blocks, daemons, consensus, staking and more.

Once the code is ready and compiled, the Cosmos SDK develops a daemon with REST API access, console line interface and a set of utilities for staking, running lite clients or full nodes. You don’t need to set up the network. A user should launch a daemon and access it like they access the Cosmos Hub’s Gaia to connect to a network.

Share the utility and settings and set up the ATOM wallet to pay out to the delegates if you need to allow staking in your blockchain. Cosmos takes care of everything from transactions to exchange.

Like other blockchain platforms, your Cosmos blockchain app can also roll out updates without a hard fork. Also, the governance mechanism is already implemented in the Cosmos platform.

The difference is that you have the only valid vote if you want to update the private blockchain. In the high-load distributed networks, the Tendermint BFT consensus ensures that the blockchain saves only valid data, and you don’t have conflicting evidence.

Before you think about building a blockchain app on the Cosmos blockchain, let’s have a look at the Cosmos Developer Kit required for developing a Cosmos app.

Cosmos Developer Kit

  • Golang for building replicated state machines
  • Ruby-on-Rails for Blockchain
  • Tendermint for Consensus and Networking

Let’s understand the process of building a Cosmos app with a demo of the Polling app. The tutorial of the Polling app uses the Starport tool, which enables you to build a blockchain and promotes chain development.

For installing starport into /usr/local/bin, run the command:

curl https://get.starport.network/starport@v0.15.1! | bash [/sourcecode]

Once the installation is done, you can see the message as:

Installed at /usr/local/bin/starport

Though you can use Starport on a browser-based IDE, we have used a local Starport installation in this tutorial.

In this demo app, we will create a blockchain-based polling app with the voting module. End users on this app can sign in, create polls, cast votes and check voting results.

Use Starport to structure the blockchain app and the voting module.

To create a new blockchain for the polling app, we are naming it as voter using the following command:

starport app github.com/username/voter

The above command creates a directory named voter in the home directory. “voter” directory involves a working blockchain app and the code you require to develop and launch a blockchain-based app, including the files and directories:

  • cmd is responsible for voterd daemon that interacts with the app
  • app contains files that connect all moving parts of the application
  • x comprises the Cosmos SDK voter module
  • proto involves the protobuf types
  • vue contains the web interface

Cosmos SDK modules are the essential building blocks of apps.

Step 1 is to launch the voter app. To launch the app from the voter project, run the following command:

cd voter
starport serve

By running this command, you created and launched a blockchain app.

The next step is to add a poll transaction.

The voter app does not execute anything. So, we need to add some types to the apps. We will add types to generate files that implement read, create, update and remove functionality for a new custom type.

Voting applications contain two types of entities: polls and votes.

Adding the poll type

A poll type has a list of options and a title. Run the following command in the voter directory in a new terminal window:

starport type poll title options

It will create the poll type. Using this command, we have generated a code that manages the creation of poll items.

To see the front-end app for creating polls:

It will take a few minutes to build the app again. If your localhost:8080 is already in use, your app can be seen on the next port.

Then, you need to sign in as the end-user on the front-end application. Once you are signed in, you can import the existing wallet created with the app. The wallet in the voter app can manage multiple accounts; therefore, we need to give it a specific name. Using a descriptive wallet name can help you recognize the wallet for future transactions.

In this demo app, we are naming it as voter_wallet.

To include multiple options in the poll, you need to change the value string options in the protobuffer definitions.

  • Open the poll.proto file in the proto/voter directory.
  • Add the keyword “repeated” before string options to allow passing an array of strings:

    message Poll {string creator = 1;uint64 id = 2;string title = 3;repeated string options = 4;}

Update CRUD (Create, Read, Update, Delete) types for the poll transaction in the proto/voter/tx.proto file.

Add the keyword “repeated” again before string options for the MsgCreatePoll and MsgUpdatePoll message:

message MsgCreatePoll {
string creator = 1;
string title = 2;
repeated string options = 3;
}

message MsgUpdatePoll {
string creator = 1;
uint64 id = 2;
string title = 3;
repeated string options = 4;
}

Go to the message_poll.go file at x/voter/types/message_poll.go to define a message that creates a poll.

For storing the options as a list rather than a string, we will replace options string with options []string in the NewMsgCreatePoll and NewMsgUpdatePoll function:

// x/voter/types/message_poll.go
func NewMsgCreatePoll(creator string, title string, options []string) *MsgCreatePoll {
return &MsgCreatePoll{
Creator: creator,
Title: title,
Options: options,
}
}

// x/voter/types/message_poll.go
func NewMsgUpdatePoll(creator string, id uint64, title string, options []string) *MsgUpdatePoll {
return &MsgUpdatePoll{
Id: id,
Creator: creator,
Title: title,
Options: options,
}
}

A client creates an HTTP POST request to perform any state transition or write anything to a blockchain. In this scenario, the voter web app is a client.

The POST request goes to the http://localhost:1317/voter/poll endpoint handler, which is defined in x/voter/client/rest/txPoll.go.

The handler makes an unsigned transaction containing an array of messages. The client then signs the transaction and transfers it to http://localhost:1317/txs.

The app executes the transaction by sending every message to a corresponding handler. On the other hand, the handler calls a CreatePoll function defined in x/voter/keeper/poll.go that writes the poll data into the store.

The keeper puts in the polls to the blockchain database. Go to the poll.go file at x/voter/keeper/poll.go. Now, we will make changes to modify the poll keeper to use the list of options.

// x/voter/keeper/poll.go
func (k Keeper) AppendPoll(
ctx sdk.Context,
creator string,
title string,
options []string,
) uint64 {
// Create the poll
count := k.GetPollCount(ctx)
var poll = types.Poll{
Creator: creator,
Id: count,
Title: title,
Options: options,
}

store := prefix.NewStore(ctx.KVStore(k.storeKey), types.KeyPrefix(types.PollKey))
value := k.cdc.MustMarshalBinaryBare(&poll)
store.Set(GetPollIDBytes(poll.Id), value)

// Update poll count
k.SetPollCount(ctx, count+1)

return count
}

The REST endpoint is created in the txPoll.go file at x/voter/client/rest/txPoll.go. Change options string with options []string in the CreatePollRequest UpdatePollRequest and struct.

type createPollRequest struct {
BaseReq rest.BaseReq `json:”base_req”`
Creator string `json:”creator”`
Title string `json:”title”`
Options []string `json:”options”`
}

type updatePollRequest struct {
BaseReq rest.BaseReq `json:”base_req”`
Creator string `json:”creator”`
Title string `json:”title”`
Options []string `json:”options”`
}

The end-user on the poll app can also interact with the app using CLI (command line interface). The definition of CLI is available at x/voter/client/cli/txPoll.go.

In this demo app, we have created a blockchain app that allows end-users to create polls.

Conclusion

Enterprise blockchain application is beneficial for various businesses, but building it from scratch limits them to create the blockchain app. However, Cosmos SDK offers the infrastructure for the app deployment and allows developers to focus on the programming instead of building a blockchain from scratch.

Get in touch with our blockchain development team to build and launch your blockchain app successfully.

Author’s Bio

Akash Takyar
Akash Takyar
CEO LeewayHertz
Akash Takyar is the founder and CEO at LeewayHertz. With the experience of building over 100+ platforms for startups and enterprise allows Akash to rapidly architect and design solutions that are scalable and beautiful.
Akash's ability to build enterprise-grade technology solutions has attracted over 30 Fortune 500 companies, including Siemens, 3M, P&G and Hershey’s. Akash is an early adopter of new technology, a passionate technology enthusiast, and an investor in AI and IoT startups.

Start a conversation by filling the form

Once you let us know your requirement, our technical expert will schedule a call and discuss your idea in detail post sign of an NDA.

All information will be kept confidential.

 Send me the signed Non-Disclosure Agreement (NDA)