Tutorials
No Results

Create Publication

We are looking for publications that demonstrate building dApps or smart contracts!
See the full list of Gitcoin bounties that are eligible for rewards.

Tutorial

Beginner · 15 minutes or less

Building a Mobile Key Vault

This tutorial will show/teach us a step by step procedure of how we can build a Mobile Application on the Algorand Network that can be used to recover an account and retrieve the account details on the Algorand Network using the Algorand SDK on the Xamarin Framework.

Requirements

Algorand .NET SDK Package
Visual Studio 2019 IDE with .NET Core Framework
Xamarin Framework
Before we begin, make sure you you have your Algorand 25-word recovery passphrase handy.
See How to Create an account to get the mnemonic phrase

Background

Additional Information:

  • It’s best to recover your passphrase in a private place, where no person or camera could be watching. You never want someone to see your recovery passphrase!
  • If your passphrase isn’t working, try re-typing each word. Since it’s a high security phrase (with 25 words), errors are likely to happen. Also, make sure the passphrase is in the correct order.

Mobile Development has changed over the year, hence many improvements have been made to how Mobile Development works, making it easier, faster, better, secure, and more convenient to build.
Sensitive data that may risk being lost can be written somewhere and kept secured or even build an application having a secure storage system to store data and also retrieve it.

In the case of storing sensitive data that may be at risk of being lost, with Xamarin Essentials, Developers can make use of Secure Storage to store data easily and also retrieve it.

We will also be making use of Secure Storage to store, retrieve, and remove data from the Secure Storage in this tutorial.

Let us also take a look at some solutions that have implemented storing and using private keys.

Steps

1. Create/Setup Mobile Application (Android/iOS)

To get started, open Visual Studio IDE as shown below in Figure 1-1 and click on the “Create New Project” to begin.
EditorImages/2021/06/01 19:21/2021-05-29_12_47_14-Window.png

Figure 1-1 Create New Project

Select the Project Type you want to develop with - Mobile App (Xamarin Forms)
EditorImages/2021/06/01 19:32/2021-05-29_12_49_53-Window.png

Figure 1-2 Select Project Type - Mobile App (Xamarin Forms)

Configure Project as shown in Figure 1-3 below:
EditorImages/2021/06/01 19:41/2021-05-29_12_55_49-Window.png
EditorImages/2021/06/01 19:42/2021-05-29_12_59_39-Window.png

Figure 1-3 Configure the Project

At this stage, we have successfully created the Project!

EditorImages/2021/06/01 20:00/2021-05-29_13_09_44-WindowStartupProjectMain.png

Figure 1-4 Created Project

2. Install the Algorand SDK

In step, we will install the Algorand Package/SDK into our Project Solution that will be used together with our Android/iOS Application.

Navigate to the NuGet Package Manager and Search for Algorand to Install as shown below in Figure 2-1:
EditorImages/2021/06/01 20:03/2021-05-29_13_16_20-WindowPackages.png

Figure 2-1 Install Algorand Package

3. Create a Content Page

In this step, we will create a Content Page called RecoverAccountPage inside the Views Folder as shown below in Figure 3-1

EditorImages/2021/06/01 20:10/2021-05-29_15_12_01-RecoverAccount_-_Microsoft_Visual_StudioRecoverPage.png

Figure 3-1 Create a Content Page - RecoverAccountPage

Modify the RecoverAccountPage.xaml as shown in the code snippet below:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="RecoverAccount.Views.RecoverAccountPage">

    <ContentPage.Resources>
        <ResourceDictionary>
            <Color x:Key="Accent">#96d1ff</Color>
        </ResourceDictionary>
    </ContentPage.Resources>

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="*" />
        </Grid.RowDefinitions>
        <StackLayout BackgroundColor="{StaticResource Accent}" VerticalOptions="FillAndExpand" HorizontalOptions="Fill">
            <StackLayout Orientation="Horizontal" HorizontalOptions="Center" VerticalOptions="Center">
                <ContentView Padding="0,40,0,40" VerticalOptions="FillAndExpand">
                    <Image Source="algorand_removebg_preview.png" VerticalOptions="Center" HeightRequest="64" />
                </ContentView>
            </StackLayout>
        </StackLayout>
        <ScrollView Grid.Row="1">
            <StackLayout Orientation="Vertical" Padding="30,24,30,24" Spacing="10">
                <Label Text="Recover Algorand Account!" FontSize="Title"/>
                <Label Text="Recover and View Your Algorand Account Details with your Mnemonic Key!" FontSize="16" Padding="0,0,0,0"/>
                <Entry x:Name="MnemonicKey" ReturnType="Next" Placeholder="Enter PassPhrase Key" FontSize="Medium" FlexLayout.AlignSelf="Stretch"  HorizontalOptions="CenterAndExpand"  TextColor="Black" Keyboard="Text" />
                <Button Margin="0,10,0,0" Text="Recover Account"
                        Clicked="recoverAccount"
                        BackgroundColor="{StaticResource Primary}"
                        TextColor="White" />

                <Entry x:Name="AccountAddress" ReturnType="Next" Placeholder="Account Address" FontSize="Medium" FlexLayout.AlignSelf="Stretch"  HorizontalOptions="CenterAndExpand"  TextColor="Black" Keyboard="Text" />
                <Entry x:Name="Amount" ReturnType="Next" Placeholder="Amount in Algos" FontSize="Medium" FlexLayout.AlignSelf="Stretch"  HorizontalOptions="CenterAndExpand"  TextColor="Black" Keyboard="Text" />

                <Button x:Name="StoreKey" Margin="0,10,0,0" Text="Store Secret Key"
                        Clicked="storeKey"
                        IsEnabled="False"
                        BackgroundColor="{StaticResource Primary}"
                        TextColor="White" />
                <Button x:Name="RetrieveKey" Margin="0,10,0,0" Text="Retrieve Secret Key"
                        Clicked="retrieveKey"
                        BackgroundColor="Green"
                        IsEnabled="False"
                        TextColor="White" />
                <Button x:Name="RemoveKey" Margin="0,10,0,0" Text="Remove Secret Key"
                        Clicked="removeKey"
                        IsEnabled="False"
                        BackgroundColor="Red"
                        TextColor="White" />
            </StackLayout>

        </ScrollView>
    </Grid>


</ContentPage>

The code snippet above designs the UI/UX of the page, this will contain the Text Entry Field for the Mnemonic that will be used to retrieve an account address and the amount in algos the account has.

The last two Entry Fields below in the code snippet above will contain the fields that will display the retrieved account address and the amount the account has in algos.

Modify the RecoverAccountPage.xaml.cs as shown in the code snippet below:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Algorand;
using Algorand.V2;
using Algorand.Client;
using Algorand.V2.Model;
using Account = Algorand.Account;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using Xamarin.Essentials;


namespace RecoverAccount.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class RecoverAccountPage : ContentPage
    {
        public RecoverAccountPage()
        {
            InitializeComponent();
        }
        private async void recoverAccount(object sender, EventArgs e)
        {
            string ALGOD_API_ADDR = "https://testnet-algorand.api.purestake.io/ps2"; //find in algod.net
            string ALGOD_API_TOKEN = "B3SU4KcVKi94Jap2VXkK83xx38bsv95K5UZm2lab"; //find in algod.token  
            AlgodApi algodApiInstance = new AlgodApi(ALGOD_API_ADDR, ALGOD_API_TOKEN);
            if(MnemonicKey.Text != null)
            {
                Account src = new Account(MnemonicKey.Text);
                var accountInfo = algodApiInstance.AccountInformation(src.Address.ToString());
                if (Address.IsValid(src.Address.ToString())){
                    AccountAddress.Text = $"{src.Address.ToString()}";
                    Amount.Text = $"{accountInfo.Amount} algos";
                    StoreKey.IsEnabled = true;                    
                }
                else
                {
                    await DisplayAlert("Invalid Account Address", "No such Account Exists", "OK");
                }                
            }
            else
            {
                await DisplayAlert("Mnemonic Key Needed!!", $"Please Enter a Mnemonic Key", "OK");
            }
        }
        private async void storeKey(object sender, EventArgs e)
        {
            try
            {
                var key = AccountAddress.Text.ToString();
                await SecureStorage.SetAsync("oauth_token", key);
                await DisplayAlert("Key Stored", $"Key Successfully Stored", "OK");
                RetrieveKey.IsEnabled = true;
                RemoveKey.IsEnabled = true;
            }
            catch (Exception ex)
            {
                // Possible that device doesn't support secure storage on device.
            }
        }
        private async void retrieveKey(object sender, EventArgs e)
        {
            try
            {
                var oauthToken = await SecureStorage.GetAsync("oauth_token");
                await DisplayAlert("Key Recovered", $"{oauthToken}", "OK");
            }
            catch (Exception ex)
            {
                // Possible that device doesn't support secure storage on device.
            }
        }
        private async void removeKey(object sender, EventArgs e)
        {
            try
            {
                SecureStorage.Remove("oauth_token");
                await DisplayAlert("Key Deleted", $"Key Successfully Removed from Storage", "OK");
                StoreKey.IsEnabled = false;
                RetrieveKey.IsEnabled = false;
                RemoveKey.IsEnabled = false;
            }
            catch (Exception ex)
            {
                // Possible that device doesn't support secure storage on device.
            }
        }
    }
}

The code snippet above handles the functionalities of what happens when a user enters a Mnemonic Key which will be used to retrieve account details (Account Address and Amount in Algos) of that account, store the account key using Xamarin Essentails Secure Storeage, retrieve the stored key and also remove the key if needed.
This solution demonstrate storing the secret key, via a button, And then retrieving it via another button.
These storage buttons (Store Key, Retrieve Key, and Remove Key) are only enabled after the original account is restored.
The Store Key button gets enabled after an account gets restored.
The Retrieve Key button gets enabled after an account is stored.
The Remove button gets enabled after an account has been stored.
When the Remove button is triggered, the storage buttons (Store Key, Retrieve Key, and Remove Key) will become disabled.

See the last step in the solution to see the page design.

4. Setup/Configure Startup Page

Lastly, we need to setup the Starup Page.
The Startup page is the initial page or first page that will display on the Mobile Application first after it opens.
To do that, Navigate to the App.xaml.cs class as shown below in Figure 4-1 below.

EditorImages/2021/06/01 20:17/2021-05-29_15_13_58-RecoverAccount_-_Microsoft_Visual_StudioApp.xamlpage.png
Figure 4-1 Open the App.xaml.cs class

In this last step, we need to Modify the App.xaml.cs class as shown below in Figure 4-2 to set the RecoverAccountPage as the Application Startup Page.
EditorImages/2021/06/01 20:18/2021-05-29_15_14_51-RecoverAccount_-_Microsoft_Visual_StudioStartupPage.png
Figure 4-2 Modify the startup page to RecoverAccount Page

5. Launch the Application

Launch your application using your desired device (Android/iOS) or an Emulator.
This demo was launched using an Android device.

EditorImages/2021/06/08 12:44/WhatsApp_Image_2021-06-08_at_1.43.07_PM.jpeg
Figure 5-1 Application Sample Image

EditorImages/2021/06/08 12:44/WhatsApp_Image_2021-06-08_at_1.43.07_PM_1.jpeg
Figure 5-2 Application Sample Image

How it Works

  • Paste in your 25 word passphrase key into the Entry Field for PassPhrase Key
  • After typing/pasting in the passphrase key, click on the Recover Account Button.

This will retrieve the account address and the balance of the account in algos back to the Entry Fields below for Account Address and Amount.

6. Complete Solution Source Code

View/Clone the Project Solution on GitHub

June 09, 2021