Introduction to @solana/web3.js

Antematter
Towards Dev
Published in
5 min readSep 24, 2023

--

Solana blockchain was launched in 2017 and it promised to solve scalability issues major blockchains were facing at the time.

There is something really special about transactions in Solana. Solana supports programs, programs are pieces of code that execute automatically when specific conditions apply.

These programs can make actions like lending, borrowing and creating agreements with one another really easy. For example, you write a program that sends money from person A to person B but only if Pakistan beats India in a cricket match or a program to loan out money and receive interest on that money without using any bank.

In major financial institutions there are still middlemen to verify that transactions are processed correctly. However, with the use of programs middlemen are no longer needed and the whole process can be automated. There are other blockchains that support programs. The most well-known example is Ethereum, but Solana has a lot of advantages over Ethereum that make it likely to reach massive adoption. Some of the advantages of Solana are:

  1. Solana transactions are much faster than Ethereum.
  2. Solana is cheaper than Ethereum, transactions on Ethereum can cost hundreds of Dollars.
  3. Solana is easier to program (Solidity only built for Ethereum, RUST has use cases outside of blockchain)
  4. New and expanding rapidly.

In this article, we’ll be developing an airdrop project on Solana. Airdropping means creating a currency and then sending that currency to your own wallet. The currency we use will have no real value, however, this is still really useful because we can use fake Solana currency to test out features of Solana and develop fully fledged applications without having to spend real life money.

Before we begin, you need to have a basic understanding of:

  1. Blockchains
  2. JavaScript
  3. Node JS and NPM

What is a Solana Wallet?

A Solana wallet is a program for sending and receiving Solana currency. Wallet does this by interacting with the Solana blockchain. It is a bit like an email account where in order to send an email you need to have an account with a mail provider, likewise, in order to receive an email you need to be able to provide your email address in order to receive mails. Similarly, with Solana we have a public and a secret key associated with a wallet which are used to interact with the Solana blockchain.

Solana/Web3.js

To interact with the Solana blockchain we need to connect to the Solana network. Solana provides us a very handy JS package called Web3.js. Let’s setup our development environment, open up the terminal and create the project folder using:

mkdir airdrop-project

then change working directory to the project folder using the following command:

cd airdrop-project

Now we need to initialize a Node JS project:

npm init -y

The step creates a package.json file for us which will be used by NPM to keep track of the dependencies of the project. Now we can install the Solana Web3 package as a dependency as we will use it to connect to the Solana blockchain network.

npm install --save @solana/web3.js

Now we are going to create a wallet using code. To create a wallet, we will create a new file within the project folder called index.js. After creating the file, we can import the required modules that we will be using in our project. We will import these modules from Solana Web3 package we installed earlier.

const { Connection, PublicKey, clusterApiUrl, Keypair, LAMPORTS_PER_SOL } = require('@solana/web3.js');

Here, The Keypair class that we imported allows us to create a new wallet. We will add the following code to the script.

const wallet = Keypair.generate();

This will create a new wallet for us, which we can use to airdrop Solana currency. Each wallet has a secret key and a public key. The public key as its name suggests is public, it allows us to receive Solana currency from other people. If someone has your public key, they can send Solana currency to you. The secret key on the other hand allows you to send currency to other people. Therefore, your secret key should not be shared with anyone else apart from you. If other people have access to it, they can perform transactions without your authorization. The wallet object that we just created contains our public and secret keys. In order to extract these, we can add the following lines to our code:

console.log(public key: ${wallet.publicKey.toBase58()});

console.log(private key(raw): ${wallet.secretKey});

Since we have logged these to the console, let’s find out what our keys are. We can do that by typing node index.js in the terminal. Both the keys will be displayed as:

Now, let’s create a function that will log the balance of the wallet. So, web3.js allows us to fetch the balance using the getBalance method inside of the Connection class that we imported. First we will have to create a connection to the Solana blockchain network, this can be done using:

const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');

The first argument makes sure that we are connecting to the development environment of Solana network. clusterApiUrl provides us with endpoint of the environment that we wish to connect to. There are three development environments available on Solana, main network, test and development network. We are using development network as we won't be initiating transactions that involve real world money.

Now that we have both connection and wallet, we will use both to retrieve the balance of the wallet.

const getWalletBalance = async (wallet) => {
try {
const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
const balance = await connection.getBalance(wallet.publicKey);
console.log(`Wallet Balance: ${balance}`);
} catch (error) {
console.error(error.toString());
}
}

Now, lets write the main method that will call getWalletBalance method to retrieve wallet balance.

const main = async () => {
getWalletBalance(wallet)
}
main();

Now we will run the script again. We see that the wallet balance is 0.

Let’s write a method to airdrop some Solana currency in the wallet so that we see some balance in our wallet.

const airdropSol = async (wallet) => {
try {
const connection = new Connection(clusterApiUrl('devnet'), 'confirmed');
const requestAirdrop = await connection.requestAirdrop(wallet.publicKey, LAMPORTS_PER_SOL);
const latestBlockHash = await connection.getLatestBlockhash();
await connection.confirmTransaction({
blockhash: latestBlockHash.blockhash,
lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
signature: requestAirdrop,
});
} catch (error) {
console.error(error.toString());
}
}

LAMPORTS_PER_SOL is a constant and it represents the amount of LAMPORTS that make up a SOL. Lamport's are the smallest unit of currency in Solana. As with every other blockchain, we need to confirm from the network if transaction was successful. Therefore, after requesting we confirm whether the request was successful or not.

Finally, we will modify our main method to print balance before and after the SOL airdrop.

const main = async () => {
await getWalletBalance(wallet);
await airdropSol(wallet);
await getWalletBalance(wallet);
}

main();

Congratulations, we have now been able to successfully airdrop Solana currency into our personal wallet. We will be using this currency airdropped currency to develop and play around with smart contracts in the next article!

This article is written by Saad Ahmed Siddiqui , Senior Blockchain Developer at Antematter.io

--

--

The world moves fast, your software should move faster. We develop and improve cutting-edge solutions using Blockchain & AI with maximum performance