Zephyrnet Logo

Setup your frontend application / NodeJS Application with Gaia v4.0.0

Date:

As most readers know, the Cosmoshub is one of the hottest crypto applications out there. With more than 200 blockchains in the ecosystem and the Cosmos Hub being on of the reference implementations and example of innovation in the blockchain sphere. If you are keen building stuff on the Cosmos Hub, you probably want to learn how to create a local testnet of the Cosmos Hub and try managing actions with your own script.

Let’s talk blockchain, crypto, development and setup.

In this tutorial we will be working with the Cosmos SDK. The Cosmos Hub is powered by the implementation that is called Gaia. When running Gaia with the correct genesis file and seed peers, you will be connected to the Cosmos Hub.
The “cosmoshub-4” is being built on Gaia 4.0.0, which will bring some significant changes in comparison with its predecessor.

In this tutorial we will dive into the details on how to create keys, setup your developer environment, create and receive transactions.

We will be working with our own testnet of Gaia.

Prerequisites

  • Golang v1.15+

Let’s install Gaia v4.0.0, our blockchain software

git clone https://github.com/cosmos/gaia 
cd gaia
git checkout v4.0.0
make install

For our own network, we need to create a genesis file. At least one account is necessary to start a blockchain. The Cosmos SDK works in the way that you have assigned validators that check every block for its validity and sign it.
So to start a network, we need to have generated an account first. In our test scenario, we will be using the following account:

luggage rotate orient usage program cloud armed warrior rich erase acquire remember

👆 This is our passphrase seed

The BIP 44 path: m/44’/118’/0’/0/0
And the resulting address: cosmos14eadktsf4zzah6har7h7a46tunnj7rq7lmppy5

The following commands will check for your existing keys, in case you already have some setup, let us have a look, else you should just see an empty array “[]”

gaiad keys list --keyring-backend test

If you are, like me, setting up from scratch, let’s initialize a testhub chain-id and add the key from above — for the sake of comparison we use the same account. Outside of a testnet, it is recommended to never share the passphrase seed. Make sure to replace “username” with your own name.

gaiad init username --chain-id testhub 
gaiad keys add username --recover --keyring-backend test
# enter the passphrase from above

The prompt allows you to enter the passphrase seed we defnied above. If you are not doing this the first time, you can choose your own passphrase, make sure to change the account address accordingly in the next steps.

Next, we have to create the genesis file. first we add our genesis account, then we define our validator and in the last step execute those settings with collect-gentxs to create the actual genesis.json.

gaiad add-genesis-account cosmos14eadktsf4zzah6har7h7a46tunnj7rq7lmppy5 10000000000stake,1000000000000uatomgaiad gentx username 10000000000stake --chain-id testhub --keyring-backend testgaiad collect-gentxs 

After these command, we are ready to launch the software using

gaiad start

From here, in order to observe blocks and incoming transactions. I use a terminal block explorer gex and you can do too, install with go get -u github.com/cosmos/gex and then start it with simply typing gex and hit enter in your terminal. When the gaia daemon is running, you will see Latest Blocks and Transactions coming in.

Awesome 🎉, we have our testnet running and can now have a deeper look at how we might want to get information from the blockchain and interact with it.

We will be interacting with the blockchain using JavaScript on NodeJS.

Let’s dive into our NodeJS setup. The scope of this tutorial is the logic of accounts and transactions. We are going to setup a basic JavaScript application. You can do a similar setup with TypeScript. We are using CosmJS, a third-party library from Confio.tech that helps us navigating the crypto for creating addresses and signing our transactions.

In this tutorial, we will be using the following versions of node and npm

> node -v 
v12.18.3
> npm -v
6.14.6

Feel free to use yarn or similar tools as an alternative.

Let’s created a dedicated directory and start our project with

npm init -y

The following commands will install the dependencies to start coding with ES7 and having a potential tests suite ready.

npm install --save bignumber.js bip39 axios @cosmjs/crypto @cosmjs/encoding @cosmjs/proto-signing @cosmjs/stargate @cosmjs/launchpad npm install --save-dev mocha babel-cli babel-core babel-polyfill babel-preset-env babel-preset-es2015 babel-preset-stage-0 babel-register chai chai-as-promised co-mocha moxios nyc sinon sinon-chai rimraf

For our tests, create a .mocharc.yml

diff: trueextension:- jspackage: ./package.jsonreporter: specslow: 75timeout: 2000ui: bddrequire: 'babel-register'file:- './tests.js'recursive: falsecolor: true

For ES6/ES7 to function properly, we set up a .babelrc file

{"presets": [["env",{"targets": {"node": "current"}}],"stage-0"]}

We will mainly be using two documents in our repository. index.js and test.js – so let us create them. Accordingly in order to run it we need to add the following scripts to our package.json:

“scripts”: { “build”: “rimraf dist/ && babel ./ — out-dir dist/ — ignore ./dist,./node_modules,./.babelrc,./package.json,./npm-debug.log — copy-files”, “test”: “mocha — require babel-core/register — require babel-polyfill test.js”, “start”: “npm run build && node dist/index.js” },

We will be using CosmJS to get all the necessary data from the blockchain and help with signing the data we want to submit.

Let’s first look at how we would make a first connection to our blockchain and receive the balance

import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";import { SigningStargateClient } from "@cosmjs/stargate";const sender = {mnemonic: "luggage rotate orient usage program cloud armed warrior rich erase acquire remember",address: "cosmos14eadktsf4zzah6har7h7a46tunnj7rq7lmppy5",path: "m/44'/118'/0'/0/0"};const tendermintUrl = "localhost:26657";(async () => {const wallet = await DirectSecp256k1HdWallet.fromMnemonic(sender.mnemonic);const client = await SigningStargateClient.connectWithSigner(tendermintUrl, wallet);const before = await client.getBalance(sender.address, "uatom");console.log(before);})();

Here we are importing the DirectSecp256k1HdWallet which creates our keys from our mnemonic files. The SigningStargateClient connects with our local running blockchain, has access to the mnemonic via the wallet that we input.

Our SigningStargateClient has a few useful functions for us to manage our application. When everything is setup nice, you can run npm run start and you should see this output:

{ amount: '1000000000000', denom: 'uatom' }

Congrats! 🎉 We have made the first connection to our local blockchain with JavaScript

In order to send token we need to setup a sending wallet and a recipient wallet.

import { coins, GasPrice } from "@cosmjs/launchpad";import { SigningStargateClient } from "@cosmjs/stargate";import { DirectSecp256k1HdWallet } from "@cosmjs/proto-signing";const sender = {mnemonic: "luggage rotate orient usage program cloud armed warrior rich erase acquire remember",address: "cosmos14eadktsf4zzah6har7h7a46tunnj7rq7lmppy5",path: "m/44'/118'/0'/0/0"};const recipient = {mnemonic: "lottery inflict car soup announce vanish loud between cart flag fatigue lottery",address: "cosmos19kwxp2u3w4djkkkfr4gmwuytm57evagr69y69r",path: "m/44'/118'/0'/0/0"};const tendermintUrl = "localhost:26657";(async () => {const wallet = await DirectSecp256k1HdWallet.fromMnemonic(sender.mnemonic);const gasPrice = GasPrice.fromString("3.14uatom");const gasLimits = {send: 160000,};const options = { gasPrice: gasPrice, gasLimits: gasLimits };const client = await SigningStargateClient.connectWithSigner(tendermintUrl, wallet, options);const before = await client.getBalance(recipient.address, "uatom");console.log(before);const transferAmount = coins(7890, "uatom");const send = await client.sendTokens(sender.address, recipient.address, transferAmount, "A gift");console.log(send);})();

Using this code and running npm run start should give us an output like

null 
{
height: 281,
transactionHash: 'DC1AFAB8C417C9C783FECEDD55D276576926ABC79C9955D90172A6EE967B56BF',
rawLog: '[{"events":[{"type":"message","attributes":[{"key":"action","value":"send"},{"key":"sender","value":"cosmos14eadktsf4zzah6har7h7a46tunnj7rq7lmppy5"},{"key":"module","value":"bank"}]},{"type":"transfer","attributes":[{"key":"recipient","value":"cosmos19kwxp2u3w4djkkkfr4gmwuytm57evagr69y69r"},{"key":"sender","value":"cosmos14eadktsf4zzah6har7h7a46tunnj7rq7lmppy5"},{"key":"amount","value":"7890uatom"}]}]}]',
data: [ MsgData { msgType: 'send' } ]
}

As you can see in the code we are adding gasPrice and gasLimit. These settings are optional and not necessary to use. This is chosen for maximum flexibility in crafting our transactions going forward.

🎉 Congratulations, you have created your own Gaia local testnet and sent, received tokens and made a query for balances.

Source: https://blog.cosmos.network/setup-your-frontend-application-nodejs-application-with-gaia-v4-0-0-9546f4b3e302?source=rss—-6c5d35b77e13—4

spot_img

Latest Intelligence

spot_img