Interacting with the Algorand Network Using the Python SDK and PureStake API

Using the Python SDK and PureStake API to Interact with the Algorand Network

Share this article:

The following is a very simple tutorial that uses the Python SDK and PureStake API service to interact with the Algorand network. Support for the PureStake API service was added to the Algorand Python SDK last year.

In this tutorial, I will show you how to create a simple Python program that sends an Algorand transaction and queries Algorand account balances using the PureStake API service (rather than running your own node locally or on a cloud server).

Today, syncing a node on the Algorand TestNet currently takes 2+ days with performant hardware and network connectivity. This will only get worse as time goes on and the blockchain grows. Using the PureStake API, you can get up and running immediately without having to wait for a node to sync.

Setting Up the Environment

The environment used in this article is Ubuntu 18.04 and Python 3.6.8, which we assume are already installed. We will be using the Algorand Python SDK which can be installed with Pip. If you don’t have Pip installed, you can install it with:

sudo apt install python3-pip

Pip will install the Python SDK with this command:

pip3 install py-algorand-sdk

You should use the editor of your choice to create the Python script. In my case, I will use Vim. If you are using Vim, here is a good vimrc configuration for syntax highlighting Python.

The next thing you will need is a PureStake API key. You can sign up for one here.

Using the Python SDK and PureStake API Step 1

 

Hit the Register for free option and fill out the registration form.

Using the Python SDK and PureStake API Step 2

 

 

You will need to supply a working email, as you need to confirm your email as part of the sign-up process. Review the T&Cs and click the “I agree to the Terms and Conditions” checkbox.

You will get an email with a registration code that looks like this:

 

Make note of the code you are sent and enter that code into the following screen when prompted:

Using the Python SDK and PureStake API Step 4

 

After submitting, you will be logged into the API Services application:

Using the Python SDK and PureStake API Home Page

 

Here you will see your API Key where the boxes are in the screenshot above. You will need to copy that key to be able to access the PureStake API service from the Python script.

Getting Started with the Python SDK

One of the best resources when developing against the Algorand Python SDK is the developer.algorand.org website. The SDK, along with code examples, can be found on GitHub here and SDK documentation here.

For our simple example script, we will begin by importing a few things from the SDK:

from algosdk import algod
from algosdk import mnemonic
from algosdk import transaction

There are many other objects that the SDK exposes, but we are only importing the ones we specifically need.

Set Up Accounts and Keys We Will Be Working With

In the snippet below we define two accounts to work with, along with the private key for one of the accounts:

mnemonic_secret = "ill purse chaos aisle build awful weather divert man blind sand matter venue heavy awake bachelor own access deer grunt donor nut tent absorb decade"
account_a_private_key = mnemonic.to_private_key(mnemonic_secret)
account_a = mnemonic.to_public_key(mnemonic_secret)
account_b = '7YEPQKFVKJKFQJJVU5XMS22RZL3NSB2WLYZQO5HMWABUNF4MBFSRIMDB5Q'

The secret mnemonic for account a is listed here in plain text, so do not use this account in your own programs. Anyone with access to this blog will be able to spend your funds. You should replace both of these accounts with accounts of your own creation.

You can fund your accounts on the TestNet by using the TestNet dispenser here.

Create the algod Client with a PureStake Key

The following commands construct an algod client object connected to the Algorand TestNet.

purestake_key = 'REPLACE WITH YOUR PURESTAKE API KEY'
endpoint_address = 'https://testnet-algorand.api.purestake.io/ps1'
purestake_header = {'X-Api-key': purestake_key}
acl = algod.AlgodClient(purestake_key, endpoint_address, headers=purestake_header)

The value of purestake_key should be your key as shown in the PureStake API Services application home page. The X-Api-key header is specifically required when using the PureStake API Service. It replaces the X-Algo-API-Token header needed when accessing the Algorand node API directly.

Get Suggested Transaction Parameters

There are several parameters you need when you send a transaction in Algorand. The commands below set several of these useful transaction values:

params = acl.suggested_params()
gen_hash = params["genesishashb64"]
first_valid_round = params["lastRound"]
last_valid_round = first_valid_round + 1000
tx_fee = params["fee"]
tx_amount = 10000

Note that this code sets the first_valid_round to the current round or block height, and the last_valid_round as 1000 blocks in the future. When creating Algorand transactions, they have a maximum validity of 1000 rounds or blocks. We specify the transaction amount as 10000. This is 10000 microalgos.

Be very careful when using the Algorand API and command line as they both work with microalgos. You always need to double-check that you are sending the correct amounts.

Prepare and sign the transaction:

tx = transaction.PaymentTxn(account_a, tx_fee, first_valid_round, last_valid_round, gen_hash, account_b, tx_amount)
signed_tx = tx.sign(account_a_private_key)

These commands prepare the transaction tx and sign it using the private key mnemonic. At this point the signed_tx object is ready to send to the network.

Send the transaction:

tx_confirm = acl.send_transaction(signed_tx, headers={'content-type': 'application/x-binary'})
acl.status_after_block(first_valid_round + 2)

The acl.send_transaction call sends the signed transaction.

Note that the content type for this call needs to be changed to application/x-binary. This is specifically required when using the PureStake API Service, but not required when using the node API directly. The acl.status_after_block call will block execution of the program until two blocks have passed (approx 9 sec). We do this to make sure that our tx is committed to the blockchain before proceeding with the execution of our program. Without this wait, subsequent reads may not reflect the transaction we just sent.

Read back the account balance:

result = acl.account_info(account_a)
print(result["address"] + ": " + str(result["amount"]) + " microalgo")

These final commands retrieve and print the balance in account_a. Account_a has been reduced by 10000 microAlgos sent and a 1000 microAlgo transaction fee.

Putting It All Together

Here are all of the API calls above put together in a script that sends the transaction and prints out account balances.

#!/usr/bin/python3
#
# algo_send.py - toy program to illustrate the use of the algorand python
# sdk with the PureStake API service for querying account balances and
# sending algo from one account to another.
#
from algosdk import algod
from algosdk import mnemonic
from algosdk import transaction

# fund these 2 accounts with some initial algo via the dispenser:
# https://bank.testnet.algorand.network/
# address a: I6Z3SSULKBUH2FH5L3LMCUM63G5FCNQIYOYWZBM4V4CZTFH23M3FRV7GXA
# address b: 7YEPQKFVKJKFQJJVU5XMS22RZL3NSB2WLYZQO5HMWABUNF4MBFSRIMDB5Q
mnemonic_secret = "ill purse chaos aisle build awful weather divert man blind sand matter venue heavy awake bachelor own access deer grunt donor nut tent absorb decade"
account_a_private_key = mnemonic.to_private_key(mnemonic_secret)
account_a = mnemonic.to_public_key(mnemonic_secret)
account_b = '7YEPQKFVKJKFQJJVU5XMS22RZL3NSB2WLYZQO5HMWABUNF4MBFSRIMDB5Q'

# Setup client with PureStake key
purestake_key = 'INSERT YOUR PURESTAKE API KEY HERE'
endpoint_address = 'https://testnet-algorand.api.purestake.io/ps1'
purestake_header = {'X-Api-key': purestake_key}
acl = algod.AlgodClient(purestake_key, endpoint_address, headers=purestake_header)

# get suggested parameters
params = acl.suggested_params()
gen_hash = params["genesishashb64"]
first_valid_round = params["lastRound"]
last_valid_round = first_valid_round + 1000
tx_fee = params["fee"]
tx_amount = 10000

# Create and sign transaction
tx = transaction.PaymentTxn(account_a, tx_fee, first_valid_round, last_valid_round, gen_hash, account_b, tx_amount)
signed_tx = tx.sign(account_a_private_key)

try:
# Send the transaction
print("Sending " + str(tx_amount) + " microalgo from " + account_a + " to " + account_b + "...", end='', flush=True)
# note that the PureStake api requires the content type for the following call to be set to application/x-binary
tx_confirm = acl.send_transaction(signed_tx, headers={'content-type': 'application/x-binary'})
acl.status_after_block(first_valid_round + 2) # wait 2 blocks to make sure our tx has been committed

print("Done.")
print("Sent " + str(tx_amount) + " microalgo in transaction: " + str(tx_confirm))
print("")

# Query resulting balances
result_a = acl.account_info(account_a)
result_b = acl.account_info(account_b)

print("Resulting balances")
print(result_a["address"] + ": " + str(result_a["amount"]) + " microalgo")
print(result_b["address"] + ": " + str(result_b["amount"]) + " microalgo")

except Exception as e:
print(e)

Running the program produces the following output:

derek@derekdev:~$ ./algo_send.py
Sending 10000 microalgo from I6Z3SSULKBUH2FH5L3LMCUM63G5FCNQIYOYWZBM4V4CZTFH23M3FRV7GXA to 7YEPQKFVKJKFQJJVU5XMS22RZL3NSB2WLYZQO5HMWABUNF4MBFSRIMDB5Q...Done.
Sent 10000 microalgo in transaction: 2R6U4PAFRR6YU52ZA7E6N2UDBPCIEXTMQYGMGKBBWAEMRWF6MWGQ

Resulting balances:
I6Z3SSULKBUH2FH5L3LMCUM63G5FCNQIYOYWZBM4V4CZTFH23M3FRV7GXA: 99796984 microalgo
7YEPQKFVKJKFQJJVU5XMS22RZL3NSB2WLYZQO5HMWABUNF4MBFSRIMDB5Q: 100170017 microalgo
derek@derekdev:~$

Using the Algorand Python SDK with the PureStake API service is a quick and easy way to create programs and application logic that interact with the Algorand network without needing to set up, sync, and manage Algorand nodes.

Share this article: