DEV Community

Aseneca
Aseneca

Posted on

Introduction to Solana: A fledging's guide on Web3 development on Solana

In this guide, we will be briefly explaining important web3 concepts such as blockchain, protocols etc. Then we shall dive deeper into key development concepts in Solana blockchain which should serve as an entry point for new Solana developers or blockchain enthusiasts that wish to learn further about Solana.

First of all, let's talk about fundamental terminologies that exist across web3 in general:

Blockchain

A blockchain can be thought of as a series of blocks or an append-only data structure that resembles an ordered back-linked linked list, which uses hashes as pointers to previous blocks. This structure consists of blocks that form a chain, hence the term blockchain. This is a very simple data structure model but it can get more complex than this with different approaches to how these blocks interact with one another

Simple Scheme of Blockchain

Block

A typical Block is a data structure that contains a header comprising three items– the hash of the previous block’s header, metadata and a Merkle root. Metadata depends on the protocol. The Merkle root is a root of the well-known Merkle tree, which can be used to verify later that transactions in a block have not been tampered with. After the head comes the core part of the block, the transaction.

Transaction

Transaction is a protocol-defined message that is stored as a part of a block, which is then stored as a part of a blockchain. The content usually consists of some kind of value transfer or on-chain program execution. Transactions are cryptographically signed by their authors or authority, proving their authenticity. In the case of a value transfer, ownership of the funds or tokens often represents some value in the real world.

Protocol

Protocol in simple and familiar terms refer to a common set of rules network nodes must follow. It defines the ground rules for communication between P2P (Peer-to-Peer) nodes, transaction format for everyone intending to use the network, any special features, and everything else for the network to operate correctly and for the users to know how to transact over the network. An essential part of a good protocol for a decentralized blockchain network is the proper incentive setup; this creates the need for its native token. Examples include SOL(token) for Solana (chain), ETH(token) for Ethereum(chain), BTC for Bitcoin

Smart contracts

A smart contract is a piece of code deployed on a blockchain with a cryptographically signed transaction. Users can then interact with it by sending transactions that invoke a specific function defined in the smart contract and the business logic is executed as stated in the deployed code.
Smart contracts on Solana are called Programs.
Data pertinent to the smart contract "state" are also stored on on-chain. A good analogy would be to compare smart contracts as programs on a decentralized computer that access files in its file system and modify them according to the predefined rules. Such a contract can be made immutable or mutable. If such a contract is made immutable, we can trust that the smart contract will not do anything else than what it is supposed to do.

Okay great. Now we know a little about what blockchain is and its rudimentary building blocks. Lets dive into the blockchain of interest in this guide: Solana.

What is Solana?

SOLANA

Solana is a single-chain blockchain that utilizes a slightly changed PBFT consensus called Tower BFT with Proof-of-Stake as a Sybil protection mechanism. It was engineered with composability at its core, meaning its performance does not depend on hardware. It is able to adapt to any hardware and scale to the utilize the full power of that "hardware."
Solana is a smart contract platform but smart contracts on Solana are called Programs. Programs can be executed in parallel. This parallelization is one of the key USP that gives Solana its composability nature.
Compared to Ethereum which is written in Solidity, development of Programs on Solana revolve around Rust programming language and its frameworks especially Anchor.
We will be breaking down the core concepts of Solana that come together to redefine its engineering perspective and improve its scalability in a subsequent article because those are more advanced concepts beyond the scope of this guide.

The Essentials of Solana Smart Contracts (Programs)

One thing you should have on the back of your mind as you explore building on Solana is: everything in Solana is an account. Accounts are owned by programs.
There are core concepts we need to discuss to help you understand how programs operate:

  1. Transactions
  2. Instructions
  3. Accounts
  4. Program Derived Addresses(PDAs)

1. Transactions
A transaction is a signed instruction sequence that is executed atomically. They are used to interact with programs deployed on the Solana network. A transaction is made up of one or more instructions, a recent blockhash, and signatures.

The recent blockhash, also known as a transaction "recentBlockhash", is used for transaction processing and lifespan. The signatures are the cryptographic proof of the transaction's integrity and authority. Each transaction must be signed by the appropriate account holders as per the instructions contained within. This takes us to the next concept which are instructions.

2. Instructions
Instructions in Solana are "bundled" within a transaction and are executed sequentially. Each instruction contains aprogram ID, accounts that it wishes to interact with, and a data field. The program ID specifies the on-chain program that will process the instruction. The accounts array includes all accounts that the instruction will read from or write to. The accounts array must include at least one signer (authority) who authorizes the instruction.

The data field is an arbitrary byte array that is passed to the program for processing.
It is this combination of transactions and instructions that allows for high throughput and efficient processing in Solana. By virtue of its architecture design, Solana is capable of processing thousands of transactions per second, each containing multiple instructions, which can interact with different programs and accounts. This design can also be attributed to Solana's core scalability and speed.

3. Accounts

In Solana, an account is a persistent memory structure that a program can use for storing state. Every account in Solana is initially owned by the system program, but the system program can change the ownership if the correct private key for the account is provided. Each account includes several properties:

a. Public Key (Pubkey): This is the unique identifier of the
account.

b. Signer Flag (is_signer): This flag indicates whether the account
is a signer of the transaction. If true, the transaction must
include the signature of this account.

c. Writable Flag (is_writable): This flag indicates whether the
data in the account can be modified. If true, the account's data
can be written to in the current transaction.

d. Lamports: This is the number of lamport's (the smallest unit of
the native SOL token) held in the account. Lamports also serve as
rent to keep the account on the network.

e. Data: This is a byte array that can hold arbitrary data.

f. Owner: This is another public key that identifies the program
that has authority over the account's data. Only the owner program
can modify the account's data.

g. Executable Flag: Hold if the account is a smart contract.

h. Rent Epoch: This value represents the latest epoch that rent has
been paid for the account. Rent is paid in SOL and ensures that the
account remains active on the network.

In Solana, accounts not only hold the state of a program but can also be used to create complex relationships between different programs through CPIs (See more on CPIs here)

Getting started on Solana Development

To get started with Solana development, you would need a (MacOS) or a Linux development environment. You can also use WSL on windows.

Step 1: Install Rust, Rustup and Cargo

Open up a terminal window (for MacOS) or command prompt (for Windows) and paste this command.

curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh

Now we have installed Rust language and Cargo (the Rust package manager)which is required for compiling Rust-based Solana programs.


Step 2: Install Solana Tool Suite

Installing for MacOS & Linux

This option is easier but it requires you to have Homebrew package manager on your MacOS or Linux machine.

brew install solana

You can confirm you have the desired version of Solana installed by running:

solana --version

Installing for MacOS & Linux (without homebrew)

Install the Solana release v1.18.7 on your machine by running:

sh -c "$(curl -sSfL https://release.solana.com/v1.18.17/install)"
You can confirm you have the desired version of solana installed by running:

solana --version

For Windows

Open a Command Prompt cmd.exe as an Administrator and paste this command:

cmd /c "curl https://release.solana.com/v1.18.17/solana-install-init-x86_64-pc-windows-msvc.exe --output C:\solana-install-tmp\solana-install-init.exe --create-dirs"

Copy and paste the following command, then press Enter to install the latest version of Solana. If you see a security pop-up by your system, please select to allow the program to run.

C:\solana-install-tmp\solana-install-init.exe v1.18.17

You can confirm you have the desired version of solana installed by running:

solana --version

In addition, ensure you have Node.js and Yarn installed on your computer
Now you have Solana Cli, Node.Js and Yarn installed, lets go ahead and create a Keypair

Creating Keypair

To get started, we're going to create a keygen script and an airdrop script for our account.

Setting up

Opening up your Terminal and use yarn to create a new Typescript project.

npm install touch-cli -g
mkdir airdrop && cd airdrop
yarn init -y
Enter fullscreen mode Exit fullscreen mode

If you get an error in windows after yarn init -y, run Microsoft powershell as administrator and run the following code:

Set-ExecutionPolicy RemoteSigned
This will initialize a new project, we're going to go ahead and add typescript, bs58 and @solana/web3.js, along with generating a tsconfig.js configuration file:

yarn add @types/node typescript @solana/web3.js bs58
yarn add -D ts-node
touch keygen.ts
touch airdrop.ts
touch transfer.ts
yarn tsc --init --rootDir ./ --outDir ./dist --esModuleInterop --lib ES2019 --module commonjs --resolveJsonModule true --noImplicitAny true
Enter fullscreen mode Exit fullscreen mode

Finally, we're going to create some scripts in our package.json file to let us run the three scripts we're going to build today:

{
  "name": "airdrop",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "scripts": {
    "keygen": "ts-node ./keygen.ts",
    "airdrop": "ts-node ./airdrop.ts",
    "transfer": "ts-node ./transfer.ts",
  },
  "dependencies": {
    "@solana/web3.js": "^1.75.0",
    "@types/node": "^18.15.11",
    "typescript": "^5.0.4"
  },
  "devDependencies": {
    "ts-node": "^10.9.1"
  }
}
Enter fullscreen mode Exit fullscreen mode

❗ Ensure to add the scripts part to the .json file. ❗

Generating a Keypair

Open up ./keygen.ts.

Importing Keypair from @solana/web3.js

import { Keypair } from "@solana/web3.js";

Generate a new keypair:

//Generate a new keypair
let kp = Keypair.generate()
console.log(`You've generated a new Solana wallet: ${kp.publicKey.toBase58()}`);
console.log(`Solana Wallet Secret Key: ${kp.secretKey}]`);
Enter fullscreen mode Exit fullscreen mode

run the following script to generate a new keypair!

yarn keygen

This will generate a new Keypair, outputting its Address and Private Key like so:

You've generated a new Solana wallet: 2sNvwMf15WPp94kywgvfn3KBNPNZhr5mWrDHmgjkjMhN
Solana Wallet Secret Key: 63,224,142,27,16,71,3,47,65,3,83,69,169,184,116,97,218,0,1,213,225,174,108,112,40,67,255,32,77,82,140,62,187,6,73,117,82,29,152,252,161,62,35,24,148,199,196,160,92,62,81,179,17,49,7,202,226,213,201,30,73,176,198,11]
Enter fullscreen mode Exit fullscreen mode

Best practice would be to save this wallet locally. runthe following command:

touch dev-wallet.json

This creates the file dev-wallet.json in our ./airdrop root directory.

Now paste the private key from above into this file in this format:

[63,224,142,27,16,71,3,47,65,3,83,69,169,184,116,97,218,0,1,213,225,174,108,112,40,67,255,32,77,82,140,62,187,6,73,117,82,29,152,252,161,62,35,24,148,199,196,160,92,62,81,179,17,49,7,202,226,213,201,30,73,176,198,11]

Congratulations. You've just created a new Keypair and saved first your wallet. Now, Let's go claim some tokens!

Claiming Airdrop Tokens

import Keypair, also going to import Connection to establish a connection to the Solana devnet, and LAMPORTS_PER_SOL to transfer amounts denominated in SOL rather than individual lamports units.

import { Connection, Keypair, LAMPORTS_PER_SOL } from "@solana/web3.js"
Enter fullscreen mode Exit fullscreen mode

get the private key in the .json file by importing the wallet and recreate the Keypair object using its private key:

import wallet from "./dev-wallet.json"
Enter fullscreen mode Exit fullscreen mode

import the keypair from the wallet file

const keypair = Keypair.fromSecretKey(new Uint8Array(wallet));
Enter fullscreen mode Exit fullscreen mode

establish a connection to the Solana devnet:

//Create a Solana devnet connection to devnet SOL tokens
const connection = new Connection("https://api.devnet.solana.com");
Enter fullscreen mode Exit fullscreen mode

Finally, claim 2 devnet SOL tokens:

(async () => {
    try {

        const txhash = await connection.requestAirdrop(keypair.publicKey, 2 * LAMPORTS_PER_SOL);
        console.log(`Success! Check out your TX here: 
        https://explorer.solana.com/tx/${txhash}?cluster=devnet`);
    } catch(e) {
        console.error(`Oops, something went wrong: ${e}`)
    }
})();
Enter fullscreen mode Exit fullscreen mode

Save the code and run it by typing yarn airdrop in the terminal. You should get a successful message with a Tx address.

Congratulations once again for coming this far. You are officially a Solana newbie dev now. But why stop here: As a challenge, try implementing the transfer token challenge and share your result in the comment section.

Top comments (0)