Solana Noob? This is For you

Anmol Arora
11 min readDec 15, 2022

Overview

Before we begin, please watch this super important video, make sure to unmute it by clicking on it.

Okay, once that’s out of the way let’s move on!

What is Solana?

Now having given you a brief of what Solana is here are some quick facts coming at you at supersonic speed:

  • Solana is a proof-of-stake non-EVM blockchain with smart contract capabilities including DeFi dApps and NFTs.
  • Uses Proof-of-History mechanism which makes it blazing fast! Solana boasts a theoretical throughput of 65,000 transactions a second with near-zero fees.
  • Smart contracts on Solana are called ‘programs’ and are written in Rust
  • Solana’s runtime is called Sealevel
  • People have started exploring options other than Ethereum (like Solana) because of the increased congestion and rise in fees because of the boom in DeFi and NFT space.

Now that we have a helicopter view, we will deep dive a bit!

💡 Now this next section isn’t neccesary to get started with Solana but it is one of those ‘nice to know’ typa deals

Some core innovations of Solana

  • The Gulf Stream Protocol. This protocol is what enables the network to process up to 50,000 TPS. The protocol is also responsible for pushing transaction caching and nudging it toward the edge of the network so that the validators are able to execute these transactions before time. This process slashes confirmation time, speeds up leader switching, and improves security. Additionally, because the number of unconfirmed transactions will be non-existent, there will be less memory pressure on these validators.
  • Proof of History (POH). The POH consensus algorithm helps the ecosystem to track transactions easily and record the order in which these transactions occur. Therefore, the Solana system is one of the most efficient cryptocurrency projects.
  • The Tower BFT. The Tower BFT mechanism harnesses Solana’s Proof of History as its cryptographic clock, which makes it possible to reach consensus without having to experience transaction latency and attract unnecessary messaging overhead. As a result, the confirmation process for these events is much faster and the exchange of information is seamless.
  • The Sealevel. Sealevel is a feature of the Solana environment that facilitates the smooth running and security of simultaneous transactions on the same state blockchains. This system comprises a robust transaction processing engine that can currently be used to scale operations across Solid State Drives (SSDs) and GPUs.
  • The Turbine. The turbine is the apparatus that boosts the platform’s capacity to process transactions swiftly. It also helps Solana resolve bandwidth issues by breaking down data into smaller packets. The use of smaller packets makes it easier to transmit data from one chain node to another blockchain node in the network chain.
  • The Pipeline. This feature is a procedure in which input data from transactions is allocated to the hardware that is responsible for it. As a result, transaction information is quickly validated and replicated on all the blocks and nodes within the Solana network.
  • Cloudbreak. Cloudbreak is Solana’s robust data structure that facilitates multiple simultaneous read and write operations within the network. It is the feature that is responsible for the level of scalability the network is currently capable of handling.
  • The Archivers. Archivers are a network of nodes where all the data on the Solana blockchain is stored. These nodes vary in size and capacity from small laptops to more sophisticated computer systems. All of these nodes are subject to a regular check to ensure that they are holding the correct block of information.

If you are migrating from the EVM ecosystem, you must be aware of the ERC token standards. Here in the Solana ecosystem SPL (Solana Program Library) token exist.

Here is a lil table stating some of the key differences!

💡 Here is a list of all the terminologies used regularly in the Solana ecosystem, just to you know, catch you up!

Your first ever Solana ‘Program’

You have grown so much my child! Writing your first ever Solana Program (yea, we call em ‘pRoGrAmS ‘in Solana instead of smart contracts 🕵️).

Here at Solana labs, we believe in application based learning and getting to the VSCode window as quickly as possible. We live in a society and are cultured beings so it would be a crime to begin with anything other than the traditional ‘HelloWorld!’ program.

We are going to start with installing the required dev dependencies

You can either refer to ReadMe I have so carefully curated

or I can just list all of it:

The HelloWorld Program

The HelloWorld program is a smart contract that prints output to the console and counts the number of times the program has been called for a given account, storing the number on-chain. Let’s break down the code into separate sections.

The first section defines some standard Solana program parameters and defines an entry point for the program (the ‘process_instruction’ function). In addition to this, it uses borsh for serializing and deserializing parameters being passed to and from the deployed program.

use borsh::{BorshDeserialize, BorshSerialize};
use solana_program::{
account_info::{next_account_info, AccountInfo},
entrypoint,
entrypoint::ProgramResult,
msg,
program_error::ProgramError,
pubkey::Pubkey,
};

/// Define the type of state stored in accounts
#[derive(BorshSerialize, BorshDeserialize, Debug)]
pub struct GreetingAccount {
/// number of greetings
pub counter: u32,
}

// Declare and export the program's entrypoint
entrypoint!(process_instruction);

The process_instruction function accepts the program_id, which is the public key where the program is deployed to, and accountInfo, which is the account to say hello to.

pub fn process_instruction(
program_id: &Pubkey, // Public key of the account the hello world program was loaded into
accounts: &[AccountInfo], // The account to say hello to
_instruction_data: &[u8], // Ignored, all helloworld instructions are hellos

The ProgramResult is where the main logic of the program resides. In this case, it simply prints a message, then selects the accounts by looping through ‘accounts’. However, in our example there will only be one account.

    ) -> ProgramResult {
msg!("Hello World Rust program entrypoint");

// Iterating accounts is safer then indexing
let accounts_iter = &mut accounts.iter();

// Get the account to say hello to
let account = next_account_info(accounts_iter)?;

Next, the program checks to see if the account has permission to modify the data for the specified account.

 // The account must be owned by the program in order to modify its data
if account.owner != program_id {
msg!("Greeted account does not have the correct program id");
return Err(ProgramError::IncorrectProgramId);
}

Finally, the function takes the existing account’s stored number, increases the value by one, writes the result back, and displays a message.

// Increment and store the number of times the account has been greeted
let mut greeting_account = GreetingAccount::try_from_slice(&account.data.borrow())?;
greeting_account.counter += 1;
greeting_account.serialize(&mut &mut account.data.borrow_mut()[..])?;

msg!("Greeted {} time(s)!", greeting_account.counter);

Ok(())

Deploying the Program

The first step is to clone the repository.

git clone https://github.com/solana-labs/example-helloworld
cd example-helloworld

Once this is done, you can then set your current environment to devnet. This is the test network for Solana developers writing and testing smart contracts.

solana config set --url <https://api.devnet.solana.com>

Next, you need to create a new keypair for your account. This is required to interact with deployed programs (smart contracts) on the Solana devnet. Take note: this is an insecure method for storing keys and should only be used for demo purposes. You will be prompted to enter in a passphrase for security reasons.

solana-keygen new --force

Now that you’ve created an account, you can use the airdrop program to obtain some SOL tokens. You will need some lamports (fractions of SOL tokens) to deploy your smart contract. This command requests SOL tokens into your newly generated account:

solana airdrop 2

You’re now ready to build the hello world program. You can build it by running the following command

Compiling the program

Once the program has been built, you can then deploy it to devnet. The previous command’s output will give you the command that you need to run, but it should look something similar to the following:

 solana program deploy dist/program/helloworld.so

The end result is that you have successfully deployed the hello world program to devnet with an assigned program Id. This can then be checked on the Solana Devnet explorer.

Deploying the program
Viewing the deployed program on the Devnet explorer

Interacting With the Deployed Program

To interact with the deployed program, the hello-world repository contains a simple client. This client is written in Typescript using the Solana web3.js SDK and the Solana RPC API.

The Client

The client entry point is the main.ts file, which performs a number of tasks in a specific order, most of which are contained within the hello_world.ts file.

First, the client establishes a connection with the cluster by calling the ‘establishConnection’ function

export async function establishConnection(): Promise {
const rpcUrl = await getRpcUrl();
connection = new Connection(rpcUrl, 'confirmed');
const version = await connection.getVersion();
console.log('Connection to cluster established:', rpcUrl, version);
}

It then calls the ‘establishPayer’ function to ensure there is an account available to pay for transactions, and creates one if required.

export async function establishPayer(): Promise {
let fees = 0;
if (!payer) {
const {feeCalculator} = await connection.getRecentBlockhash();

// Calculate the cost to fund the greeter account
fees += await connection.getMinimumBalanceForRentExemption(GREETING_SIZE);

// Calculate the cost of sending transactions
fees += feeCalculator.lamportsPerSignature * 100; // wag

payer = await getPayer();
}

The client then calls the ‘checkProgram’ function, which loads the keypair of the deployed program from ./dist/program/helloworld-keypair.json and uses the public key for the keypair to fetch the program account. If the program doesn’t exist, the client stops with an error. If the program does exist, it will create a new account with the program assigned as its owner to store the program state, which in this case is the number of times the program has been executed.

 export async function checkProgram(): Promise {
// Read program id from keypair file
try {
const programKeypair = await createKeypairFromFile(PROGRAM_KEYPAIR_PATH);
programId = programKeypair.publicKey;
} catch (err) {
const errMsg = (err as Error).message;
throw new Error(
`Failed to read program keypair at '${PROGRAM_KEYPAIR_PATH}' due to error: ${errMsg}. Program may need to be deployed with \`solana program deploy dist/program/helloworld.so\``,
);
}

// Check if the program has been deployed
const programInfo = await connection.getAccountInfo(programId);
if (programInfo === null) {
if (fs.existsSync(PROGRAM_SO_PATH)) {
throw new Error(
'Program needs to be deployed with `solana program deploy dist/program/helloworld.so`',
);
} else {
throw new Error('Program needs to be built and deployed');
}
} else if (!programInfo.executable) {
throw new Error(`Program is not executable`);
}
console.log(`Using program ${programId.toBase58()}`);

// Derive the address (public key) of a greeting account from the program so that it's easy to find later.
const GREETING_SEED = 'hello';
greetedPubkey = await PublicKey.createWithSeed(
payer.publicKey,
GREETING_SEED,
programId,
);

The client then builds up and sends a ‘hello’ transaction to the program by calling the ‘sayHello’ function. The transaction contains an instruction that holds the public key of the helloworld program account to call, and the account to which the client wishes to say hello to. Each time the client performs this transaction to an account, the program increments a count in the destination account’s data storage.


export async function sayHello(): Promise {
console.log('Saying hello to', greetedPubkey.toBase58());
const instruction = new TransactionInstruction({
keys: [{pubkey: greetedPubkey, isSigner: false, isWritable: true}],
programId,
data: Buffer.alloc(0), // All instructions are hellos
});
await sendAndConfirmTransaction(
connection,
new Transaction().add(instruction),
[payer],
);
}

Finally, the client queries the account’s data to retrieve the current number of times the account has had the sayHello transaction called, by calling ‘reportGreetings’

 export async function reportGreetings(): Promise {
const accountInfo = await connection.getAccountInfo(greetedPubkey);
if (accountInfo === null) {
throw 'Error: cannot find the greeted account';
}
const greeting = borsh.deserialize(
GreetingSchema,
GreetingAccount,
accountInfo.data,
);
console.log(
greetedPubkey.toBase58(),
'has been greeted',
greeting.counter,
'time(s)',
);

Running the Client

Before you can run the client to read data from your deployed program, you need to install the client dependencies.

npm install

Once this is done, you can start the client.

npm run start

You should see output showing your program successfully being executed, and it should display the number of times the account has been greeted. Subsequent runs should increase this number.

Starting the Hello World client to interact with the deployed program

NFT Minting DApp Using Rust

Now that you have completed the tradition of writing your first “Hello World!” application using Rust, it is time to dive into something which you will actually apply in the real world.

Here is a beginner friendly video tutorial we have made containing two of the best methods to mint NFTs on Solana!

Link to the Github Repos (Repo1 & Repo2)

Doc containing commands used in Repo1

Replit link

Bounties for Beginners!

We are aware that a lot of you might be migrating from the Web2 world onto the miraculous land of Web3. We at Solana, are bullish on mobile dApps, that’s why we came up with the Solana Mobile Stack. Solana Mobile Stack is an SDK that comes with the tools you need — including a hardware-encoded Seed Vault — to publish mobile dApps and distribute them through a specialized storefront. Build mobile experiences that have never been possible before.

Mobile dApp specific ideas:

  • A complete replacement of Google Photos/iCloud photo backup. All photos, videos and files stored securely on-chain.
  • Skribbl on-chain. An NFT minting DApp that mints the drawings of you and your friends post the game ending
  • Build a personal Solana Wallet mobile DApp

Some fun ideas to buidl in general:

  • Create a no-code SPL token generator (something similar to https://www.spl-token-ui.com/). You will learn a lot about SPL tokens along the way which will always come in handy.
  • Pick your favourite cartoon from your childhood (mine is Dragon BallZ, don’t come after me saying it’s an anime, I know) and mint the characters as NFT on-chain. Obviously, we are not saying it’s legal but it will help you learn how to write smart contracts in Rust :p

(resources: https://soldev.app/library/tutorials/filter?tag=Rust)

  • Mess around with Sugar: Candy Machine CLI and make your first candy machine

(resources: https://docs.metaplex.com/developer-tools/sugar/tutorials/my-first-candy-machine)

Context: Sugar is our new Candy Machine CLI that replaces the JavaScript CLI. In short, it’s simpler, faster, less complicated and better in every possible way!

  • Read up about DAOs and their working, and write your first governance smart contract! (resources: https://solana.com/developers/dao)
  • As a dev, would you like to be paid every second you work? Who wouldn’t amirite

Build a token streaming protocol on Solana

(resources: https://learn.figment.io/tutorials/solana-token-streaming-protocol)

Some curated resources that I would’ve loved if they had been served on a platter to me

Best of luck on your journey to becoming a pro-Solana dev :)

--

--