Follow

Follow
How to start developing on Hedera Hashgraph

How to start developing on Hedera Hashgraph

Nonstack's photo
Nonstack
·Oct 28, 2022·

9 min read

Play this article

I recently learned about Hedera and found their technology to be quite fascinating. Hedera is not a blockchain; it's a public ledger that utilizes hashgraph consensus.

Hashgraph consensus is a more secure and faster alternative to blockchain consensus mechanisms. Think of Hedera as a graph, with the speed of verifying transactions increasing as users add more transactions to the network. A directed acyclic graph (DAG) is the technology behind this. It helps Hedera in exceeding 100,000 transactions per second. As a result, it is a legitimate competitor to Visa and other TradFi mass-payment systems.

0_qULMYZyMPze0jYu6.jpeg

A council of 19 multinational corporations governs the platform and software that will run on millions of nodes worldwide. Instead of mining, nodes on the hashgraph "gossip" with each other, comparing notes on the network's transaction history.

If you are still trying to decide which network to use for your next DApp, Hedera may be a good option because it will help you launch your DApp fairly, quickly, securely, and cost-effectively. Hedera is the world's greenest proof-of-stake network, and it can help you achieve your environmental sustainability goals by reducing your carbon footprint.

Let's dive in straight on how you can start developing on Hedera. For this lesson, I will refer to an article by Ed Marquez and go into greater detail about it. Here's a link to the article: hedera.com/blog/how-to-develop-on-Hedera-ba..


Here is what we are going to be covering:

  • I will introduce you to the Hedera Portal: Here, you will create a testnet account and receive a fake testnet HBAR. A testnet is simply an instance of the chain used for testing and experimentation without risk to real funds or the main chain.
  • How to configure your environment
  • Here, I will work you through how to set up the environment on your laptop
  • How to create your account
  • Transferring Hbar To start with, let's head to portal.hedera.com. It will welcome you with the screen below.

image.png


Just below the sign-in button, click on "Create a Testnet Account." It will bring up another screen, as seen below.

image.png

For this lesson, we will be using the testnet account. On the right-hand side, input your email and click on "Start building." Hedera will send a verification code to your email address. Input the verification code; another window will prompt you to input your credentials.

image.png

Once you log in, you will see the screen below that contains your private key, public key, and account ID. We will need the private key and account ID for the following steps, so copy them.

image.png

Now let us head over to our code editor. For this example, we will be using Visual Studio Code.

Here, as you can see, I have created a blank project called setup. Now we need to create some files in this setup folder using the terminal window. Open up the terminal windows and follow along.

  • Let's start by creating our .env file. Type touch .env on the terminal window and hit enter

  • NB: Make sure to navigate to the setup directory we created. We will use the env file to store the private key and the account ID we initially copied.

  • We will also be creating an index.js file. Type touch index.js and hit enter.

  • After that, we will initialize our repository using the command npm init –yes—hit enter.

image.png

image.png

Now we need access to the Javascript SDK and the .env, so let's install these packages.

  • To install .env, type npm install dotenv into the terminal window and hit enter.
  • To install the Hashgraph SDK, type npm install --save @hashgraph/sdk and hit enter.

image.png

Now that the SDK is installed let's start by going into our index.js file and referencing the Hedra official docs on the environment set up https://docs.hedera.com/guides/getting-started/environment-set-up; click on the javascript tab and copy the code below.

const { Client } = require("@hashgraph/sdk");
require("dotenv").config();

async function main() {

    //Grab your Hedera testnet account ID and private key from your .env file
    const myAccountId = process.env.MY_ACCOUNT_ID;
    const myPrivateKey = process.env.MY_PRIVATE_KEY;

    // If we weren't able to grab it, we should throw a new error
    if (myAccountId == null ||
        myPrivateKey == null ) {
        throw new Error("Environment variables myAccountId and myPrivateKey must be present");
    }
}
main();

Paste the above code into the index.js file in the code editor.

image.png

Now, go back to the documentation on the Hedera environment setup, copy the code below and paste it into your .env file.

MY_ACCOUNT_ID = ENTER YOUR ACCOUNT ID
MY_PRIVATE_KEY = ENTER YOUR PRIVATE KEY

image.png

Replace the dummy data with your actual data, which are your account ID and Private Key from your hedera testnet portal.

image.png

MY_ACCOUNT_ID = "0.0.48510522"
MY_PRIVATE_KEY = "b252889714fadbc408b4b126c699b244c767fb06265eeaba2352c5edb40abf8f"

We need to create the client object, which we will use to communicate with Hedera nodes. Since we are using a Hedera testnet account ID and private key, we will create a client for the Hedera testnet. Copy the below code from the Hedera official docs on the environment set up docs.hedera.com/guides/getting-started/envi..

// Create our connection to the Hedera network
// The Hedera JS SDK makes this easy!
const client = Client.forTestnet();

client.setOperator(myAccountId, myPrivateKey);

image.png

Let's verify if our code works by adding a quick success message at the end.

console.log(wemadeit)
client.close();

Let's now run the code with node index.js in the terminal windows; this should return the word "wemadeit".

image.png

Let's move on to the third stage: creating an account.

For this step, let's refer to the create an account section of the Hedera documentation https://docs.hedera.com/guides/getting-started/create-an-account.

Here we have to import some updates for our Hedera SDK. Copy the modules under the JavaScript tab in step 1.

NB (Please don't copy the second line because we already have the ("dotenv") configuration, and it will be a repetition to copy it.)

const { Client, PrivateKey, AccountCreateTransaction, AccountBalanceQuery, Hbar }

image.png

const { Client, PrivateKey, AccountCreateTransaction, AccountBalanceQuery, Hbar } = require("@hashgraph/sdk");

Use the above code to replace the first line of code on the index.js file, as seen below.

image.png Replace the code outlined in red

It should look like below:

image.png

We have successfully imported the private key, AccountCreateTransaction, AccountBalanceQuery, and Hbar. We don't need the accountbalancequery, so we can take that out.

Next, we have to generate some new keys to associate with the account you will create. We can do this using the private key method we have just imported.

Copy the code in step 2: "create an account Hedera Documentation."

//const client = Client.forTestnet();
//client.setOperator(myAccountId, myPrivateKey);
//-----------------------<enter code below>--------------------------------------

//Create new keys
const newAccountPrivateKey = PrivateKey.generateED25519(); 
const newAccountPublicKey = newAccountPrivateKey.publicKey;

image.png

Add this code just below the setOperator function. This pair of keys has yet to exist on the testnet. To make the account exist, we need to send a transaction to it. Otherwise, it will not be recorded by the ledger.

image.png

To make the account exist, we need to send a transaction to it. Otherwise, it will not be recorded by the ledger. To do this copy, the code in step 3 of the Hedera creates an account documentation https://docs.hedera.com/guides/getting-started/create-an-account.

//Create a new account with 1,000 tiny bar starting balance
const newAccount = await new AccountCreateTransaction()
    .setKey(newAccountPublicKey)
    .setInitialBalance(Hbar.fromTinybars(1000))
    .execute(client);

image.png

Paste this code directly under create a new account code block.

image.png

Next, we have to retrieve the account ID, to do this we can start by querying for the receipt. Once a transaction is sent, you can always query for the receipt. Then the receipt will contain your new account ID. The code in step 4 of the Hedera creates account documentation to do this copy.

image.png

// Get the new account ID
const getReceipt = await newAccount.getReceipt(client);
const newAccountId = getReceipt.accountId;

//Log the account ID
console.log("The new account ID is: " +newAccountId);

image.png

Let's run this code to test if we have created a new account successfully. To do this, type the command node index.js at the terminal window.

image.png

As you can see, it returned 0.0.48575754 as our new account ID. Yeah! We made it

Now we can transfer some Hbar from our Testnet account to the newly created account.

In the next step, I will show you how to transfer Hbar. Let's create a new file called the transfer.js to keep our code clean.

Open the terminal windows and input the command touch transfer.js

image.png

image.png

Copy the entire code in your index.js file and paste it into the transfer.js file. Please remove the code we don't need from the create new key comment to the last.

image.png

We will need a new account ID because we want to transfer HBAR into this account. Lets define this as const newAccountId = “0.0.48575754”

image.png

Now, refer back to the Transfer HBAR section of the Hedera documentation. The first step now is to define a transfer transaction. But first, let's import it from the HederaSDK. (NB: The net value of the transfer must be equal to zero [Total number of Hbars sent by the sender must be equal to the total number of Hbars received by the recipient)

//console.log("The new account balance is: " +accountBalance.hbars.toTinybars() +" tinybar.");
//-----------------------<enter code below>--------------------------------------

//Create the transfer transaction
const sendHbar = await new TransferTransaction()
     .addHbarTransfer(myAccountId, Hbar.fromTinybars(-1000)) //Sending account
     .addHbarTransfer(newAccountId, Hbar.fromTinybars(1000)) //Receiving account
     .execute(client);

image.png

Head over to your editor and paste in the transfer.js file immediately under the newAccountD as seen below

image.png

If we select the Transfer Transaction Text in yellow, this is because we are yet to import it.

image.png

So let's go ahead and import it. Replace the PrivateKey and AccountCreateTransaction with TransferTransaction,

image.png

The TransferTransaction text should turn green after this. Next, let's receive the receipt for this transaction. To do this, we can use the below code.

const transactionReceipt = await sendHbar.getReceipt(client);
console.log('Status of txn; ${transactionReceipt.status}')

We can also verify the new account balance, but first, let's add the account balance query.

image.png

We then create a new getNewBalance parameter.

This function only accepts one input, in this case, the accountID. We want to know the balance for our `new account.

Lastly, we log the output. Use the getNewBalance and then convert it to tinybars to make it readable.

    const getNewBalance = await new AccountBalanceQuery()
        .setAccountId(newAccountId)
        .execute(client);

    console.log(`New balance: ${getNewBalance.hbar.toTinybars()}`)

    client.close();

To verify the code, open the terminal window and execute the code node transfer.js. Success! Now our new balance for this account is 8000

image.png

Now let us look up the account on the Testnet Explorer. To do this, go to https://hashscan.io.

image.png

Paste our new AccountID on the search bar

image.png

As you can see from the screenshot above, we have 8000 tiny bars (0.00008000h) $0.0001

To learn more about Hedera, I suggest you visit the Hedera Blog hedera.com/blog and the Hedera Documentation docs.hedera.com. An excellent place to start is the try example section docs.hedera.com/guides/getting-started/try-..; here, you will learn how to

  • Create and Transfer Your First NFT
  • Create and transfer your first fungible token
  • Submit your first message
  • Deploy your first smart contract
  • Deploy a contract using the Hedera Token Service
  • Create and transfer an NFT using a Solidity contract
  • Schedule your first transaction

NB: This article was originally published on my blog decentrapress

 
Share this