How to Use Algorand Python SDK

Introduction

 
In this article, we will learn how we can use Algorand Python SDK to create a simple application.
 

Algorand

 
Algorand is a scalability-focused blockchain cryptocurrency technology. The Algorand platform supports smart contracts, and its consensus method is pure proof-of-stake (PPoS), which recruits network operators from the whole pool of ALGO currency holders, as well as a Byzantine agreement protocol. ALGO is the name of Algorand's native cryptocurrency. ALGO is a digital currency as well as a blockchain platform that is used to secure the Algorand blockchain and pay transaction fees for Algorand-based transactions. The Algorand platform is meant to handle a large number of transactions fast, much like a big payment processor such as Mastercard or Visa. Algorand is a direct competitor to Ethereum since it can host other cryptocurrencies and blockchain-based initiatives. Because it is an open-source blockchain, anybody may access and contribute to the platform's code.
  • Transactions handled over the Algorand network are completed in around four seconds.
  • The transaction charge is merely 1,000 microAlgos, or.001 Algos.
  • Because Algorand does not support forking, transactions are final once they are verified in a block. A throughput of 1,000 TPS translates to 1,000 completed transactions per second.
You can learn more about Algorand here.
 

Run Algorand Testnet

 
We need to run Algorand Testnet locally on our PC. For that open Git Bash and type and execute the following command.
  1. ./sandbox up testnet -v   
Note: Make sure Docker is up and running before executing the open command.
 

Install Python SDK

  1. pip3 install py-algorand-sdk
Import the following dependencies.
  1. import json  
  2. import base64  
  3. from algosdk import account, mnemonic, constants  
  4. from algosdk.v2client import algod  
  5. from algosdk.future import transaction  
  • json - used to convert the result into JSON string, which can be printed and broken down easily
  • base64 - used to decode the base64 result into a human-understandable format
  • algosdk - used to provide account, mnemonic, and constants specific operations
  • v2client - Algorand Client API
  • future - used to provide transaction-related issues

Create Algorand Account

 
To start interacting with the Algorand Chain we need to first create an algorand wallet account.
  1. def generate_algorand_keypair():  
  2.     private_key, address = account.generate_account()  
  3.     print("My address: {}".format(address))  
  4.     print("My private key: {}".format(private_key))  
  5.     print("My passphrase: {}".format(mnemonic.from_private_key(private_key)))  
  6.   
  7. # Write down the address, private key, and the passphrase for later usage  
  8. generate_algorand_keypair()  
The above function is used to get the
  • Algorand Wallet address
  • Private Key
  • Passphrase
After running the above command, note down all the 3 details, as we will be needing them later.
 
Since any newly created account will be empty, we need to fund our account. You can either buy some Algos, or you can use Algorand Faucet to fund. 
 

Establishing Connection with Algorand Client

 
Once we are done funding, we will need to connect our application with the Algorand Sandbox client API.
 
Note: At the time of writing this article, I am using version 2, you can use an earlier or later version.
  1. algod_address = "http://localhost:4001"  
  2. algod_token = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"  
  3. algod_client = algod.AlgodClient(algod_token, algod_address)  
  • algod_address is the IP from which API endpoints can be accessed. 4001 is the default port. You can change it according to your need.
  • algod_token is an authentication token. 'aaaa.....' is the default value for the sandbox. If you are using a 3rd party tool, your token value will change.

Checking Algorand Wallet Balance

  1. print("My address: {}".format(my_address))  
  2. account_info = algod_client.account_info(my_address)  
  3. print("Account balance: {} microAlgos".format(account_info.get('amount')))  
  • my_address is the address value you saved earlier.
  • We can get the account information of a wallet by using the command account_info. It will result in a JSON output.
Since only need to print the amount value, we will use get('amount'). Output will be
  1. My address: YMNXAWERMPYIKA3BL6FXIZQB7WXI46MKEUG47ZOGOGBJZJL7TKNVTFRRMU  
  2. Account balance: 1997000 microAlgos   

Build Transaction

 
We use suggested_params() to get the details about the transaction.
  1. # build transaction  
  2. params = algod_client.suggested_params()  
To build the transaction we need to specify the following details.
  1. params.flat_fee = constants.MIN_TXN_FEE   
  2. params.fee = 1000  
  3. amount=1000  
  4. receiver = "HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA"  
  5. note = "Hello World".encode()  
  • I have kept flat_fee to be the minimum possible.
  • I have kept the transaction fee and amount to be sent as 1000 microAlgos
  • I have kept the message to be sent with the transaction as "Hello World", and have encoded it before transmitting it.
You can change all values according to your need.
 
After specifying all the attributes, we will make the transaction. I have kept "close_reminder" as null, you can read about it yourself. 
  1. unsigned_txn = transaction.PaymentTxn(my_address, params, receiver, 1000000None, note)  
The output will be
  1. {  
  2.     'sender':'YMNXAWERMPYIKA3BL6FXIZQB7WXI46MKEUG47ZOGOGBJZJL7TKNVTFRRMU',  
  3.     'fee': 1000,  
  4.     'first_valid_round': 20089540,  
  5.     'last_valid_round': 20090540,  
  6.     'note':b'Hello World',  
  7.     'genesis_id':'testnet-v1.0',  
  8.     'genesis_hash':'SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=',  
  9.     'group':None,  
  10.     'lease':None,  
  11.     'type':'pay',  
  12.     'rekey_to':None,  
  13.     'receiver':'HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA',  
  14.     'amt': 1000000,  
  15.     'close_remainder_to':None  
  16. }   

Sign First Transaction

 
Before the transaction is considered valid, it must be signed by a private key. Use the following code to sign the transaction.​
  1. signed_txn = unsigned_txn.sign(private_key)  
The output will be
  1. <algosdk.future.transaction.SignedTransaction object at 0x0000014EDA864550>   

Submit the Transaction

 
The signed transaction can now be submitted to the network. wait_for_confirmation SDK Method is called after the transaction is submitted to wait until the transaction is broadcast to the Algorand blockchain and is confirmed.​
  1. txid = algod_client.send_transaction(signed_txn)  
  2. print("Signed transaction with txID: {}".format(txid))  
The output will be
  1. Signed transaction with txID: MA7MOY6BKOTUG6XBKLVFLWEHS45QNKGUYTFAHMBGN3TMKQQPVD3A   
In the above code, we push our transaction to the testnet and print the transaction ID.
  1. try:  
  2.      confirmed_txn = transaction.wait_for_confirmation(algod_client, txid, 4)    
  3. except Exception as err:  
  4.      print(err)  
  5.      return  
In the above code, we are waiting for the transaction to get submitted and verified from the testnet. I have kept it under try-except so as to catch any error or exception which may cause hindrance. 
 

Printing the Final Details

 
After everything is done we need to print the below details:
  • Transaction Information
  • Decoded Note
  • Initial Balance
  • Amount Transferred
  • Transaction Fee
  • Final Balance 
All of the above can be found using the following commands
  1. print("Transaction information: {}".format(  
  2.         json.dumps(confirmed_txn, indent=4)))  
  3. print("Decoded note: {}".format(base64.b64decode(  
  4.         confirmed_txn["txn"]["txn"]["note"]).decode()))  
  5.   
  6. print("Starting Account balance: {} microAlgos".format(account_info.get('amount')) )  
  7. print("Amount transfered: {} microAlgos".format(amount) )      
  8. print("Fee: {} microAlgos".format(params.fee) )   
  9.   
  10. account_info = algod_client.account_info(my_address)  
  11. print("Final Account balance: {} microAlgos".format(account_info.get('amount')) + "\n")  
The output will be
  1. Transaction information: {  
  2.     "confirmed-round": 20089542,  
  3.     "pool-error""",  
  4.     "txn": {  
  5.         "sig""hUdsUVumfjgQkVXLJ2nGPkNdj+/EUGRifchywnf3CTcASfaFNZ6ec+61fK+WaxyKhuMZEIKnMlxI1Pq3aOeqDg==",  
  6.         "txn": {  
  7.             "amt": 1000000,  
  8.             "fee": 1000,  
  9.             "fv": 20089540,  
  10.             "gen""testnet-v1.0",  
  11.             "gh""SGO1GKSzyE7IEPItTxCByw9x8FmnrCDexi9/cOUJOiI=",  
  12.             "lv": 20090540,  
  13.             "note""SGVsbG8gV29ybGQ=",  
  14.             "rcv""HZ57J3K46JIJXILONBBZOHX6BKPXEM2VVXNRFSUED6DKFD5ZD24PMJ3MVA",  
  15.             "snd""YMNXAWERMPYIKA3BL6FXIZQB7WXI46MKEUG47ZOGOGBJZJL7TKNVTFRRMU",  
  16.             "type""pay"  
  17.         }  
  18.     }  
  19. }  
  1. Decoded note: Hello World  
  2. Starting Account balance: 1997000 microAlgos  
  3. Amount transfered: 1000 microAlgos  
  4. Fee: 1000 microAlgos  
  5. Final Account balance: 996000 microAlgos   
You can watch a demo of the code here.
 

Conclusion

 
Thank you for reading the article, hope you got to know about Algorand, and how we can use Algorand Python SDK to create a simple application.
 
We will continue the Algorand series.