How to build an app on Cosmos Blockchain?
The growth of blockchain since the introduction of Bitcoin has been exponential. Many found a decentralized and distributed ledger the need of the time and started either building on existing networks or developing new blockchains. From large open-source chains to single-purpose enterprise networks, blockchain protocols built for various purposes are dominating the web3 ecosystem at present. However, one drawback of most of these networks lies in their inability to connect with each other to interact and transfer data and value. The majority of the existing blockchains are disparate and isolated networks without any connection to one another. A highly functional interoperable protocol was an absolute necessity in the blockchain ecosystem to connect these siloed networks. Cosmos, an internet of blockchains, was introduced to serve the purpose of connecting blockchains.
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?
- A glance at the Cosmos blockchain
- The Cosmos development stack
- How to build a blockchain app with 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:
- 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. - 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. - 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.
The Cosmos development stack
The Tendermint Core
The Tendermint Core is the software solution possessing the Tendermint Byzantine Fault Tolerance or BFT consensus algorithm. It is a blockchain application platform that offers the equivalent of a database, web server and supporting libraries for blockchain applications compiled in any programming language. It also houses the inter-blockchain communication protocol or IBC.
The IBC Protocol
IBC is a method through which network layers and the consensus layer communicate to the hub and all the other connected blockchains. The inter-blockchain communication protocol is a secure and reliable protocol that helps modules, which are deterministic processes running on independent machines, to interact with each other. Any cross-chain application, like multichain smart contract applications, cross-chain token transfers, or decentralized oracles, can be created on top of IBC. It is, thus, an interoperability solution. Moreover, it manages data transport, reliability and authentication.
Application Blockchain Interface layer
Application Blockchain Interface layer or ABCI layer facilitates dApp replication with various programming languages. As this layer is not constricted to a single language, developers can construct applications on their blockchain in their preferred language. Furthermore, ABCI acts as a bridge between the Tendermint Core and Cosmos SDK to facilitate the interaction between the two.
The Cosmos SDK
Cosmos SDK is the application layer of the project’s network, offering a basic blockchain framework for developers interested in building on Cosmos. It aims to minimize complexities by providing the most common functionalities involved in many blockchains, like governance, staking and tokens. It also enables developers to build plugins to add any additional features they wish to include.
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
Get unified blockchain solutions for your business needs
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
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 voterstarport 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:
- Run starport serve
- Go to http://localhost:8080/
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.gofunc NewMsgCreatePoll(creator string, title string, options []string) *MsgCreatePoll {return &MsgCreatePoll{Creator: creator,Title: title,Options: options,}}// x/voter/types/message_poll.gofunc 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.gofunc (k Keeper) AppendPoll(ctx sdk.Context,creator string,title string,options []string,) uint64 {// Create the pollcount := 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 countk.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 applications are beneficial for various businesses but building them from scratch limits developers’ creativity. Thanks to Cosmos SDK, developers can now build web3 apps without building them from the ground up. They can rely on the SDK that provides a basic framework of the common functionalities of blockchains to build dApps with maximum composability, security and modularity. It cuts down the complexities of building web3 applications, offers the right infrastructure for app deployment and allows developers to focus on programming instead of building a blockchain from scratch.
Get in touch with our Cosmos development experts to successfully build and launch your blockchain app.
Start a conversation by filling the form
All information will be kept confidential.