ICrypto

Hotest Blockchain News in First Media Index

An Introduction to Algorand Dapp Development

Algorand has had a fantastic 2021, growing in adoption, use cases and its token price. ALGO kicked off the year at $0.20 and is now well into the $2 range. As a result, more and more developers are keen to build on its blockchain and help grow adoption. In this article, we’ll recap Algorand’s advantages before learning how to write transactions using its SDK. 

In this article:

  • Learn to code
  • Write a transaction
  • Send a transaction

First up, a quick recap on Algorand’s unique selling points: It’s low cost, high throughput and all about block finality. It costs roughly 0.001 ALGO per transaction–less than a cent–making it ideal for DeFi and gaming use cases. The blockchain also handles up to 1000 transactions per second, another notch to its DeFi belt. Finally, block finality happens after a single block, unlike Bitcoin or Ethereum. That means you don’t have to wait for block confirmations to ensure your transaction isn’t included in a fork. 

A further benefit that explains Algorand’s recent success chimes in with worldwide attitude towards carbon neutrality and ESG standards. Algorand strives to become the greenest blockchain on a carbon-negative network. Currently, Algorand is already well on the way, using 0,000008 kWh/transaction based on a network of 4,000 validators. These numbers are a stark contrast to Bitcoin (930 kWh/txn) or Ethereum (70 kWh/txn)–but let’s visualize it just to be sure.

First Steps to a Negative Carbon Footprint

Algorand has pledged to become carbon-negative. To reach this admirable goal, the blockchain and the ClimateTrade organization will implement a ‘sustainability oracle’ that will validate Algorand’s carbon footprint on-chain for each epoch. 

Thanks to advanced smart contracts, Algorand will then lock the equivalent amount of carbon credit as an ASA (Algorand Standard Asset) into a green treasury. As a result, the protocol will run as carbon-negative.

In summary, Algorand offers fast finality and throughput at a low cost. Plus, no trees, squirrels or rivers are harmed. It’s no wonder that the Algorand price has pumped this bull run, and is the team behind the hashtag `#GreenFi` on Twitter.  

Coding on Algorand

Now, the important part: learning to code on Algorand. In this brief explainer you’ll learn how to: 

  • Set up your development environment.
  • Understand Algorand architecture
  • Write a transaction on Algorand
  • Send a transaction on goal CLI tool

 Firstly, when setting up your development environment, you can choose between three options:

Option 1

The most-used option is setting up the Algorand Sandbox. The Sandbox allows developers to create local, private networks. Moreover, you can quickly remove a network, reset its state, or spin up a new network. The only requirement for using the Algorand Sandbox is installing Docker and Docker-Compose. Additionally, you can choose to connect to a real network and catch up to the latest round.

Option 2

Use **third-party API services** to access native Algorand REST APIs for the mainnet, testnet, and betanet. This is an excellent choice if you don’t want to set up a local network using Docker, and just want to experiment with Algorand development initially. Existing service providers are Purestake and Rand Labs.  Bear in mind that the free tiers for both service providers come with certain limitations, like the number of requests per second (more information on both websites). You can access these services via an API key and Algorand node address.

Option 3

You can decide to **run your own Algorand node**, which contains the full implementation of the Algorand software. This solution is more complex to set up and is also less flexible. Unlike the Algorand Sandbox, you can’t throw away a network and set up a new one when you want to. Setting up an Algorand node takes much more time than setting up a local, private network using the Sandbox tools.

**Recommendation?** It’s recommended to install the Algorand Sandbox to be able to complete the entire educational series! However, for this tutorial specifically, you can use a third-party API service

Here are the steps to install the Algorand Sandbox:

```sh// clone the Sandbox from GitHubgit clone https://github.com/algorand/Sandbox.git// enter the Sandbox foldercd Sandbox// run the Sandbox executable to start a private network./Sandbox up```

Starting the Sandbox with the `up` command will take a couple of minutes if this is your first time running the Sandbox. The script will make sure to pull all required Docker images before setting up your network.

A successful node installation will print a list of prefunded accounts, which we will use later. Here’s an example of Sandbox output.

```sh# Available accounts./Sandbox goal account list# [offline]HCNMMIL3MKYILOLUO74NF6OPCJU4RU7IE5PX6JYBIT5YHAMQIVO5YADHMUHCNMMIL3MKYILOLUO74NF6OPCJU4RU7IE5PX6JYBIT5YHAMQIVO5YADHMU1000000000000000 microAlgos# [offline]3KHVQUNTXBFKPTWPPLRYZY3MZIW4EB6XYWRTTIA36O6ZSMRLSEWA2J2HTA3KHVQUNTXBFKPTWPPLRYZY3MZIW4EB6XYWRTTIA36O6ZSMRLSEWA2J2HTA4000000000000000 microAlgos# [online]5FRKKWRG3UAJQNB7QIOWBW2JICZS4YUF2WFAETHGN3CBM4R3N27NY3T2KQ5FRKKWRG3UAJQNB7QIOWBW2JICZS4YUF2WFAETHGN3CBM4R3N27NY3T2KQ4000000000000000 microAlgos```

Understanding the Algorand architecture

An Algorand node contains three main components:

– Key manager -> kmd process -> Exposes a kmd REST API

_The kmd process is responsible for managing wallets and accounts._

– Node software -> algod process -> Eposes an algod REST API

_The algod process contains the Algorand software for executing consensus and adding blocks to the blockchain. You mainly interact with the algod process to add transactions to the blockchain._

– Indexer -> `algorand-indexer` process -> Exposes an indexer REST API

_The indexer is not part of the node itself. It uses a PostgreSQL database to store all kinds of data points about the blockchain like transactions, blocks, accounts, and applications. The indexer reads from the algod process. Developers interact with the indexer REST API to retrieve data from the blockchain._

An overview can be seen here:

The above diagram also shows the different SDKs and how they interact with the Algorand software. Each SDK creates a client using a token and address to interact with a node. Using an SDK, you can use many helpful functions to interact with the exposed REST APIs. If you prefer, you can send requests directly to the exposed APIs as well.

How to write your first transaction using an SDK?

In this section, you’ll learn to send your first transaction to your private network using your SDK of choice. Also, you’ll learn alternative ways of sending transactions using the `goal` CLI tool and verifying transactions via the exposed indexer API.

First, you have to prepare your project setup by installing the right dependencies. This blog post covers JavaScript. You can also find setup steps for Python, Go and Java.

Make sure to create a new folder for your project and execute the following installation steps. You will install the Algorand JavaScript SDK to interact with the algod REST API and indexer REST API.

```sh// initialize projectnpm init// install Algorand sdknpm install algosdk// list the versionnpm list algosdk// This package provides TypeScript types, but you will need TypeScript version 4.2 or higher to use them properly.```

Next, let’s generate a new account to which you’ll send some Algo tokens from one of the pre-funded accounts. The below snippet imports the `algosdk` and uses it to generate a new account. The function both prints the account address and mnemonic.

```jsconst algosdk = require('algosdk');const createAccount =  function (){    try{          const myaccount = algosdk.generateAccount();        console.log("Account Address = " + myaccount.addr);        let account_mnemonic = algosdk.secretKeyToMnemonic(myaccount.sk);        console.log("Account Mnemonic = "+ account_mnemonic);        return myaccount;    }    catch (err) {        console.log("err", err);    }};createAccount();```

Here’s sample output from the above code snippet.

```shAccount Address = OXESBPM4MF7ZDLA6OR4S64E26ZDBA47EQO73BGP3XWLXU4DFOC53Q3DN4QAccount Mnemonic = arm will clever happy organ picnic over cable large mask brother mesh spike square differ cactus road mountain pledge dust eternal zebra random absent track```

Additionally, let’s create some code to submit a transaction to the algod REST API. Therefore, we need to connect to it using a client object. 

If you check the Algorand Sandbox documentation, you can find the connection details for all processes.

```- algod:    - address: http://localhost:4001    - token: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa- kmd:    - address: http://localhost:4002    - token: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa- indexer:    - address: http://localhost:8980```

Before we can start, we also need to export the mnemonic for the prefunded account because we need to construct the private key to sign a transaction to the newly generated account.

To do so, you can use the `goal` CLI tool that interacts with the kmd process via the exposed kmd REST API. Use the below account. Mke sure to replace the address with a prefunded address for your Sandbox.

```sh// sample command./Sandbox goal account export -a HCNMMIL3MKYILOLUO74NF6OPCJU4RU7IE5PX6JYBIT5YHAMQIVO5YADHMU// outputExported key for account HCNMMIL3MKYILOLUO74NF6OPCJU4RU7IE5PX6JYBIT5YHAMQIVO5YADHMU: "cloth intact extend pull sad miss popular mansion lobster napkin space oyster correct warm miss neither confirm snow virtual evoke era lock amused abandon first"// raw command./Sandbox goal account export -a 
```

Here’s the code snippet to send your first transaction. Make sure to replace the mnemonic for the `prefundedAccount` variable and the address for the `receiver` variable.

```js// create client object to connect to Sandbox's algod clientconst algodToken = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';const algodServer = 'http://localhost';const algodPort = 4001;let algodClient = new algosdk.Algodv2(algodToken, algodServer, algodPort);const prefundedAccount = algosdk.mnemonicToSecretKey("cloth intact extend pull sad miss popular mansion lobster napkin space oyster correct warm miss neither confirm snow virtual evoke era lock amused abandon first"); // replace with your mnemonic const receiver = "OXESBPM4MF7ZDLA6OR4S64E26ZDBA47EQO73BGP3XWLXU4DFOC53Q3DN4Q" // replace with generated receiver addressconst firstTransaction = async function() {    try {        // check your balance        let accountInfo = await algodClient.accountInformation(prefundedAccount.addr).do();        console.log("Account balance: %d microAlgos", accountInfo.amount);        // construct the transaction        let params = await algodClient.getTransactionParams().do();        params.fee = 1000;        params.flatFee = true;        const enc = new TextEncoder();        const note = enc.encode("My first transaction");        let amount = 1000000; // = 1 ALGO        let sender = prefundedAccount.addr;        let txn = algosdk.makePaymentTxnWithSuggestedParams(sender, receiver, amount, undefined, note, params);        // Sign the transaction        let signedTxn = txn.signTxn(prefundedAccount.sk);        let txId = txn.txID().toString();        console.log("Signed transaction with txID: %s", txId);        // Submit the transaction        await algodClient.sendRawTransaction(signedTxn).do();        // Wait for confirmation        let confirmedTxn = await waitForConfirmation(algodClient, txId, 4);        // Get the completed Transaction        console.log("Transaction " + txId + " confirmed in round " + confirmedTxn["confirmed-round"]);    } catch (error) {        console.log("err", error);    }}```

Sending a Transaction

To send a transaction, we need to provide the following parameters:

1. sender address

2. receiver address

3. amount to transfer in microAlgos (1 Algo equals 1000000 microAlgos)

4. note (optional) -> Pass `undefined` if you don’t want to add a note with your transaction

5. `params` object -> Used to set the fee for the transaction. You can set a fee yourself or use the default 1000 microAlgos fee per transaction. You can find more info about the difference between the `suggested fee` and `flat fee` in the documentation.

You can find the complete transaction schema reference in the Algorand documentation. For instance, you can pass a `closeRemainderTo` property that will close the sender account and move all remaining funds to the address specified in this property. You don’t want to use this property in this example because we don’t want to close our prefunded account.

Next, add the implementation of the `waitForConfirmation` function below the code you already have. This function verifies if your transaction has been included in a block. This function can be used by all functions that write a transaction to the blockchain. Therefore, in the sections below, you’ll use it each time. 

```js/** * Wait until the transaction is confirmed or rejected, or until 'timeout' * number of rounds have passed. * @param {algosdk.Algodv2} algodClient the Algod V2 client * @param {string} txId the transaction ID to wait for * @param {number} timeout maximum number of rounds to wait * @return {Promise<*>} pending transaction information * @throws Throws an error if the transaction is not confirmed or rejected in the next timeout rounds */const waitForConfirmation = async function (algodClient, txId, timeout) {    if (algodClient == null || txId == null || timeout < 0) {        throw new Error("Bad arguments");    }    const status = (await algodClient.status().do());    if (status === undefined) {        throw new Error("Unable to get node status");    }    const startround = status["last-round"] + 1;    let currentround = startround;    while (currentround < (startround + timeout)) {        const pendingInfo = await algodClient.pendingTransactionInformation(txId).do();        if (pendingInfo !== undefined) {            if (pendingInfo["confirmed-round"] !== null && pendingInfo["confirmed-round"] > 0) {                //Got the completed Transaction                return pendingInfo;            } else {                if (pendingInfo["pool-error"] != null && pendingInfo["pool-error"].length > 0) {                    // If there was a pool error, then the transaction has been rejected!                    throw new Error("Transaction " + txId + " rejected - pool error: " + pendingInfo["pool-error"]);                }            }        }        await algodClient.statusAfterBlock(currentround).do();        currentround++;    }    throw new Error("Transaction " + txId + " not confirmed after " + timeout + " rounds!");};firstTransaction();```

Also, let’s not forget to call the `firstTransaction` function. Your terminal output will look like this when you’ve correctly replaced the `prefundedAccount` and `receiver` variables.

```shAccount balance: 1000247000000000 microAlgosSigned transaction with txID: QILHNKZJN7EU4UGMEGFZCCEI5XOLEGXEEQE2IEFWE3DXPC6YY7UQTransaction QILHNKZJN7EU4UGMEGFZCCEI5XOLEGXEEQE2IEFWE3DXPC6YY7UQ confirmed in round 9901```

Verify transaction via indexer

You can always double-check your transaction by opening the following link in your browser. Make sure to replace the transaction ID with your transaction ID.

```shhttp://localhost:8980/v2/transactions/QILHNKZJN7EU4UGMEGFZCCEI5XOLEGXEEQE2IEFWE3DXPC6YY7UQ// Raw linkhttp://localhost:8980/v2/transactions/```

Your browser will print the JSON object for your confirmed transaction. Note the `”tx-type”: “pay”` property which indicates that it is a payment transaction. You can find an overview of all transaction types in the Algorand documentation.

```json{  "current-round": 10288,  "transaction": {    "close-rewards": 0,    "closing-amount": 0,    "confirmed-round": 9901,    "fee": 1000,    "first-valid": 9899,    "genesis-hash": "OM/i1PkIYLDm/D5MeFJehTOpoLRX1hrVdu0PeGbHY00=",    "genesis-id": "sandnet-v1",    "id": "QILHNKZJN7EU4UGMEGFZCCEI5XOLEGXEEQE2IEFWE3DXPC6YY7UQ",    "intra-round-offset": 0,    "last-valid": 10899,    "note": "TXkgZmlyc3QgdHJhbnNhY3Rpb24=",    "payment-transaction": {      "amount": 1000000,      "close-amount": 0,      "receiver": "OXESBPM4MF7ZDLA6OR4S64E26ZDBA47EQO73BGP3XWLXU4DFOC53Q3DN4Q"    },    "receiver-rewards": 0,    "round-time": 1635332957,    "sender": "HCNMMIL3MKYILOLUO74NF6OPCJU4RU7IE5PX6JYBIT5YHAMQIVO5YADHMU",    "sender-rewards": 247000000000,    "signature": {      "sig": "4n68QeEYY79IeVJD9+4fMUZeA51Flx1lDqOPG++YaBLid0YvfvFPhBEEcDAolbxMHx8AsOktWYpq+/YF7KN1AA=="    },    "tx-type": "pay"  }}```

Sending transactions with goal CLI tool

Alternatively, you can send a transaction faster using the goal CLI tool. You can find the full details for the `goal clerk send` command in the documentation.

In the below command, the `-a` flag represents the amount you want to transfer in microAlgos. The `-f` flag indicates the account from which you are sending the funds. The `-t` flag indicates the account you are sending funds to. The benefit of using goal is that it interacts with the kmd REST API and doesn’t require you to provide your private key to sign transactions if the Sandbox’s wallet manages your account, like the prefunded account. You can find the reference docs for `goal clerk send` here.

```sh./Sandbox goal clerk send -a 125000 -f HCNMMIL3MKYILOLUO74NF6OPCJU4RU7IE5PX6JYBIT5YHAMQIVO5YADHMU -t OXESBPM4MF7ZDLA6OR4S64E26ZDBA47EQO73BGP3XWLXU4DFOC53Q3DN4Q```

Conclusion

This tutorial introduced you to the basics of Algorand development. How can you use an SDK to interact with the Algorand blockchain through APIs, but more importantly, why should you build on Algorand.

Make sure to check out the upcoming articles that will teach you how to build on Algorand. They cover Algorand Standard Assets (ASAs) and how you can manage them with code and using the goal CLI tool.

DISCLAIMER – This is a sponsored article. Readers should do their own research before taking any actions related to the content mentioned in this article.

Share
 26.11.2021

Hotest Cryptocurrency News

End of content

No more pages to load

Next page