Skip to content

Instantly share code, notes, and snippets.

@LucidSamuel
Created August 19, 2022 09:54
Show Gist options
  • Save LucidSamuel/458979c82755b39151ab919990e40f25 to your computer and use it in GitHub Desktop.
Save LucidSamuel/458979c82755b39151ab919990e40f25 to your computer and use it in GitHub Desktop.
Building a Solana Wallet Generator with React

Building a Solana Wallet Generator with React

Wallets are vital for getting into crypto or building any dAPP (decentralized app) as they fulfill several essential functions within the Web3 space. Therefore, in this article, we’ll dive deeper into the Solana ecosystem which is the world's first web-scale, open-source blockchain protocol, that enables developers around the world to build decentralized applications (dApps) on its ecosystem. Presently, Solana is capable of 50,000 TPS (transactions per second), making it the world's fastest blockchain.

Headings

  • Introduction -Prerequisites
  • Setting up the Boilerplate
  • Connecting to the Solana Network
  • Generating an Account
  • Request for Airdrop
  • Getting Started with Axe for Vue.js
  • Bonus: Linting with eslint-plugin-jsx-a11y
  • Conclusion
  • What's next?

Prerequisites

Basic JavaScript knowledge Some experience with React JS Expo CLI Watchman (required only for macOS or Linux users) Git

Introduction

In this practical guide, you will build a basic Wallet application with React and Web3 that will interact with Solana Network.

Setup environment:

Let's set up and install Node.js and Npm first.

Download node here, If you have it installed already, skip this step.

  • Confirm if you have Node installed
node -v

Node.js comes with Npm, so you can use the code below to confirm it's installed.

npm -v

Now that we have our environment setup, let's initialize our project and begin to build.

Setting up the Boilerplate

I have created a boilerplate repository to make it easier to build this Wallet application.

It contains:

A basic skeleton with the empty methods that we will implement along the tutorial. A layout to show the data that we will get from the Solana Network. @solana/web3.js package to communicate with the Solana Network.

To begin, we would install Watchman to enable us to install Expo (required only for macOS or Linux users):

$ brew update
$ brew install watchman

Next, we install Expo or check if already installed

npm install -g expo-cli

Now we're ready to set up our Boilerplate, to proceed you will need to clone the repository:

git clone https://github.com/LucidSamuel/solana-wallet.git

After cloning the repository, install the essential dependencies on the directory:

cd solana-wallet    // the folder directory
yarn install

Then lastly, run Expo

expo web

You should see something like this on your terminal:

![Screenshot 2022-07-28 at 2.35.58 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1659004577068/S6NFkYcbj.png align="left")

To complete the process, press w as instructed in your Terminal to open the server on your web browser, you should see a screen like this on your browser:

![Screenshot 2022-07-28 at 2.40.39 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1659004848880/4BAuLI1ZR.png align="left")

Now that everything is set up and the server is up and running, it's time to commence work on the wallet app.

While following this tutorial, make sure not to close the Terminal and always keep Expo running.

Connecting to the Solana Network

Contrary to other blockchains, where you may need to connect to RPCs or request API keys from third-party services, connecting to the Solana Network is simple and can be accomplished in a few steps.

If you open the App.js from the cloned repository, you'll notice that the imports and empty functions you'll need to implement have already been included:

import {
  Connection, // connection receives an endpoint argument containing the full node's URL.
  clusterApiUrl,
  Keypair,
  LAMPORTS_PER_SOL,
} from "@solana/web3.js";

We would be using devnet, which is designed to serve as a sandbox for everyone interested in building in the test environment of the Solana Network where tokens are not real.

I've already defined the necessary functions; so all that remains is for you to implement them.

To do that you would need to locate the createConnection function in your code and edit the commented code with the following code:

const createConnection = () => {
  return new Connection(clusterApiUrl("devnet"));
};

Finally, we would call this function and print the following in the console to test if it's connected to the network:

console.log(createConnection());

If everything works smoothly, you should see something like this in the console of your browser:

Object{
   "_commitment":"undefined",
   "_confirmTransactionInitialTimeout":"undefined",
   "_rpcEndpoint":"https://api.devnet.solana.com",
   "_rpcWsEndpoint":"wss://api.devnet.solana.com/",
   "_rpcClient":{
      "…"
   },
   "_rpcRequest":"createRpcRequest(method",
   "args)",
   "_rpcBatchRequest":"createRpcBatchRequest(requests)",
   "_rpcWebSocket":{
      "…"
   },
   "_rpcWebSocketConnected":false,
   "_rpcWebSocketHeartbeat":null,
   "…"
}

Creating an Account

An address is essential for communicating on the blockchain since it acts as a unique identifier as well as a digital point where cryptocurrency can be sent and received. To create an account, we must first generate a Keypair that includes both a secret and public key.

You can find the necessary import for that here in the code:

import {
  Connection,
  clusterApiUrl,
  Keypair,      // the keypair import
  LAMPORTS_PER_SOL,
} from "@solana/web3.js";

Next, Line 1: Define the function.

Line 2: Define a keypair variable with the result of calling the function to generate a random Keypair.

Line 3: Define an initialBalance variable and set to 0.

Line 4: Set the state variable with 2 keys: keypair and balance.

look for the createAccount function in our code and implement the following code:

const createAccount = () => {
   const keypair = Keypair.generate();
   const initialBalance = 0;
   setAccount({ keypair: keypair, balance: 0 });
 };

After save, the application should reload and you will able to create new random accounts every time that you press the button Create new account.

![Screenshot 2022-07-28 at 4.03.45 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1659009835985/_1IPusHCp.png align="left")

Get Balance of the Account

To get the balance of an account you will need to look for the getBalance function in the code and implement it like this:

const getBalance = async (publicKey) => {
 const connection = createConnection();

 const lamports = await connection.getBalance(publicKey).catch((err) => {
   console.error(`Error: ${err}`);
 });

   return lamports / LAMPORTS_PER_SOL; // In the Solana Network, a lamport is the smallest unit: 1 SOL = 1 billion lamports.
 };

Request Airdrop

Devnet tokens are not actual tokens. Solana Network allowed us to request tokens in order to conduct testing while developing our applications.

Solana Web3 requestAirdrop function accepts two parameters:

to: PublicKey of the account lamports: number of lamports

For that, we will need to implement the empty requestAirdrop function in our code like this:

const requestAirdrop = async (publicKey) => {
    setRequestAirdropButton({ text: BUTTON_TEXT_LOADING, loading: true });
    const connection = createConnection();

    const airdropSignature = await connection.requestAirdrop(
      publicKey,
      LAMPORTS_PER_SOL
    );

    const signature = await connection.confirmTransaction(airdropSignature);

    const newBalance = await getBalance(publicKey);

    setAccount({ ...account, balance: newBalance });
    setRequestAirdropButton({ text: BUTTON_TEXT, loading: false });
  };

![Screenshot 2022-07-28 at 4.21.01 PM.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1659010875954/h0ag3r3bC.png align="left")

Final Code

Here's what our final App.js code should look like:

%[https://gist.github.com/LucidSamuel/ce8e391a841b2c2c22d318c85a9e1fdd]

Conclusion

We've successfully been able to build a Solana wallet generator web application with basic features, You can proceed to build amazing applications with more interactive user interfaces from here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment