Day-5 - Getting started with Python using Algorand: Private Key/Mnemonic Phrase Relationship, keyword explained

in #pythonlast year

On day 4, we ran our first transaction on Algorand testnet. That's pretty simple right? Yeah it is. Take your time to go over it again if you are confused. If yet, you experience difficulty, I'll be willing to attend to attend to questions in the comment section.



Previously On:

Day 3Day 4

Remember articles on this blog are aimed at transforming you from a complete novice to intermediate level as Algorand developer using python programming language, so you will get the best explanation even my granny could understand, perhaps she's fuzzy and had dropped out of school in form 2. Algorand - blockchain technology protocol, is a smart contract platform that enables developers build and deploy decentralized applications free of tampering being a core benefit of blockchain functionality.

Let us extend our last code since we only generated a public/private key pair(see image below) key to do more things for us.

In the Python environment, we installed Algorand package on day-1 so we are able to use every functionalities that Algorand corporation had made available. The Algorand development kit is available in four different programming language - Python, Java, Go and JavaScript. If you do not understand some terminologies/jargon here, don't worry, I have explained the basics at the end of this tutorial.

To create a public/private key pair, we needed just two modules so we imported modules:

  • account and,
  • algod

In the algod module, there is a class - AlgorandClient(expecting 3 arguments) available for us to connect to the network so we can test our code. However, these code do not run using python environment but via API (+ the secret token we got from purestake). So, you need to have internet connection for it to pass through unlike when you can run usual python code locally.

account module has a function named generate_account that expects two arguments to generate a wallet for us.

Note: Think of a wallet as a traditional bank account. To send you some cash, I'll need your account number and account name and most times your bank name or Swift/BIC code as adopted by different countries. A wallet or digital account as it may be addressed is simply the combination of your private key and address which is capable of holding compatible digital assets, in this case, it is ALGO Native Token including other compatible ones like the Tether USDt(USDT), Asia Reserve Currency Fund (ARCC) etc.

You sign a transaction using your private key. It is private to you alone and anyone can access your fund. But Algorand kits is quite flexible in way that as a developer, you can configure your application in a way that will prevent known form of financial malpractices. This is one of the reasons the network is robust.

Private Key/Mnemonic Phrase Relationship

If you are building an application, a user may either log connect using the mnemonic phrase or private key. They are the same. A difference is that mnemonic phrase or seed phrase is a bit longer since is a group of secret words that must be used in sequential order while a private key is a hash of mnemonic phrase created as part of public key cryptography during an asymmetric-key encryption and to decrypt and transform a message into a readable format.

Let us try this by encrypting our mnemonic phrase to private key vice versa. This time, to convert from private key to mnemonic phrase, we need a function to do that for us. For simplicity, we will use a module in Algorand SDK called mnemonic . One of the benefits of using Algorand's provided module is because it is secure and directly provided by the team to ease developers' work.


Take a look at the above codes. I wrote three functions to:

  • Convert the private key we generated, printed from line 14(stored as private_key) to mnemonic phrase in line 19.

  • Again, take the mnemonic phrase - mnemonic_phrase from line 21, convert it to private key in line 26.

  • Lastly, use same mnemonic key and transform it to public key in line 33.

Hey! don't get too excited. We got an error from the terminal. AttributeError : 'tuple' object has not attribute 'split'. But there is nowhere in our code we have used the function split(). That's one of the things you will have to deal with as a developer. Actually, it took me up to 30 minutes to figure this out. It may not be the case if you are smarter than me. Being smart here lies in your ability to debug.

Let me explain this error for you and the solution. From the log in the terminal, it says ==> mnemonic = mnemonic.split() located in the path ==> File "C:\Users\bobman\AppData\Local\Programs\Python\Python37\lib\site-packages\algosdk\", line 113. You'll find the path inside Algorand sdk, in file.

The problem is from the concatenation we made in line 19. Comment out codes subsequent toline 23 and you finds out it runs successfully but for others. Try it before you continue.

Subsequent functions rely on the output from line 19 to run successfully.

 def convertToMnemonicKey():
      return ("My Mnemonic phrase:", mnemonic.from_private_key(private_key))

Notice there is a space after the comma? This can be costly while writing a smart contract. Mnemonic phrase on Algorand is 25 unique words separated by a single space. Space ' ' is treated as a character but in some cases, is ignored.But it has cost us some time here. Time they say is money nevertheless it worth it. By default, the 25 words are generated all choked together so, to make it readable, the function split(' ') is applied which separates the words adding just a space in between each consecutive word and none at the beginning or end of the string.

Line 19 adds a space at the beginning of the string totaling 26 words hence the error. Let us rewrite line 19 and we'll be fine.


Yay! We made it.


  • Locally : To run or develop locally mean to run without connecting to online tools. All to happen on PC or machine.

  • Function in Python is a an organized block of codes that can be reuse over and over again. It makes writing code very easy and less stressful as you do not have to rewrite set of codes again when you need to use them in future. All you need is create a .py extended file and settle it right there. It becomes a module. Use it later by importing the module and call the function. Functions in python are denoted with keyword ==> def followed by the function name, the opening and closing parentheses, a semi-colon hit ENTER key, your IDE should automatically indent the next line(usually an indentation = hitting thespace key 4 times) but not the case if you are using text environment. Then, the function body.

    def doSomething():
         buy  = "Buy some ALGO Token"
         return buy
    invest = doSomething()

Call the function since you are returning a variable. But if you use a print statement instead of return, you only need to call the function. If you doSomething without the parentheses (), you will only doNothing. That's the rule. So, you've got to pay attention to parentheses so you can doSomething.

def buyAlgoToken(amountToBuy):
       your_balance = 2BTC
       algo_current_price = $0.19
       if (your_balance > 0.001BTC):
            available_buy = (your_balance/algo_current_price)
                if (amountToBuy == available_buy or amountToBuy < available_buy):
                     return your_wallet_address.balance += amountToBuy
                      return("You have exceeded your buying capacity)
            return ("Please deposit some BTC")

Note that the above function is only a prototype and not the actual syntax to write a transaction function. Do not sent real Algo Token to the address. It will lost as it is a testnet address. it cannot accept real Algo Token.

  • Argument: This is a value that is passed into a function(also called method) when calling it which can either be a keyword type or argument preceded by an identifier such as that in (name=).

  • Parameter: A parameter is different from argument even though they are similar. Parameter is a variable you define right inside the parentheses at the point you are defining a function. In our code above, amountToBuy is a parameter while 1.5BTC is argument.

  • Module: From learnpython, Modules in Python are simply Python files with a .py extension. The name of the module will be the name of the file. A Python module can have a set of functions, classes or variables defined and implemented.

At the next tutorial, I will expatiate further on block of code we have just written. Happy learning

Posted on my blog