How to Create Smart Contracts in Solana Using Anchor

Written by talktomaruf | Published 2022/06/30
Tech Story Tags: blockchain | smart-contracts | solana | anchor | create-smart-contracts | blockchain-technology | blockchain-adoption | blockchain-use-cases

TLDRA smart contract is a self-executing digital term of agreement embedded in strings of codes to be executed when the specified conditions have been met. The advent of smart contracts in blockchain technology is genuine in all these features. Solana is a public blockchain that runs on a BFT—Byzantine Fault Tolerance—themed Tower Consensus. The Tower consensus leverages the Proof-of-History consensus mechanism. As one of the fastest blockchain networks, Solana can process about 710,000 TPS.via the TL;DR App

Blockchain is an immutable public ledger that securely stores data or information, making it less susceptible to hacking or modification. It is a decentralized/distributed digital transaction ledger devoid of central governance or a third party. It protects data by distributing it across all nodes in its ecosystem.

When blockchain came to the limelight in 2008, it started as a decentralized P2P public database of transactions; this earliest form of the blockchain is known as Blockchain 1.0. As developers keep exploring more use cases of the blockchain technology with a robust framework and more utilities, they successfully developed another version of the blockchain, the Blockchain 2.0.

Blockchain 2.0 incorporates the earliest version of the blockchain and added more features like transparency, improved security, and smart contract. The advent of smart contracts in blockchain technology is genuine in all these features.

What is Smart Contract?

A smart contract is a self-executing digital term of agreement embedded in strings of codes to be executed when the specified conditions have been met. It is the trusted tool between two anonymous parties that enables them to transact with each other without concern. It is accurate, efficient, secure, and transparent.

Blockchains that supports smart contract have the edge over those that don't. This is because smart contract broadens the use cases of blockchain technology. For example, smart contracts allow for the development of several crypto tokens on a single blockchain, i.e., a single blockchain can be a host to multiple tokens, including the native cryptocurrency of such blockchain.

Another use case of the smart contract in blockchain technology is that it enables the minting of Non-fungible tokens—NFTs. These use cases, and many more are the drives behind blockchains with smart contracts such that non-smart contract-based blockchains are seeking ways to include it in their blockchain network. Such an example is the recent Bitcoin soft-fork, themed "Taproot." One of the blockchain networks that support the smart contract is Solana.

What is Solana?

Solana is a public blockchain that runs on a BFT—Byzantine Fault Tolerance—themed Tower Consensus. The Tower consensus leverages the Proof-of-History consensus mechanism. As one of the fastest blockchain networks, Solana can process about 710,000 TPS.

Solana was created by a former executive of Qualcomm, Anatoly Yakovenko, in 2017. It supports the smart contract and Dapps creation alongside DeFi platforms and NFT marketplaces. The native cryptocurrency of the Solana network is SOL which is used to offset transaction fees on the network and is also traded on the crypto market. All applications or solutions of the Solana network were possible because of the smart contract it supports.

How to Write Smart Contract in Solana Using the Anchor Software

An Anchor is a software tool for Solana's Sealevel runtime providing handy development tools like:

  • Interface Definition Language–IDL–specification
  • Rust crates and eDSL–embedded Domain Specific Language–for writing Solana programs
  • TypeScript package to generate clients from IDL
  • CLI and workspace management to develop complete applications.

Generally, the Anchor incredibly makes creating smart contracts easy on the Solana network. Before delving into the nitty-gritty of this subject, let's familiarize ourselves with some terms

  1. Rust: Rust is a remarkable multi-purpose programming language that will be used to develop this smart contract.
  2. Solana Tool Suite: This includes the command-line interface–CLI.

Now, let's proceed.

To start with, we need to create a new anchor project:

anchor init counterapp

You should see the following files and folders in the project structure:

program: This is the directory or location of the Smart contract

test: The javascript test code is found here

migrations: The launch script

app: The frontend will be built here

Now, let’s find lib.rs file from the program directory


declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");

#[program]
pub mod counterapp {
    use super::*;
    pub fn initialize(ctx: Context<Initialize>) -> ProgramResult {       
        Ok(())
    }
}
#[derive(Accounts)]
pub struct Initialize {}

This is the most straightforward CLI program. It has a function initialize that, when called, successfully executes. The "initialize struct" defines the context of the "initialize" function.

After setting up our project, the next is to create our counter application. To achieve that, we must first set up an account to save our data. In case you're wondering what the account's purpose is, accounts are means for Solana Sealevel users to store and retrieve data.

Recall that we’ve defined two structs: the CounterAccount struct is our Account which comprises variables that will store our count.


#[derive(Accounts)]
pub struct Create<'info> {
    
    #[account(init, payer=user, space = 16+16)]
    pub counter_account: Account<'info, CounterAccount>,
    
    #[account(mut)]
    pub user: Signer<'info>,
    
    pub system_program: Program<'info, System>,
}
#[account]
pub struct CounterAccount {
    pub count: u64,
}

The Create struct is the instruction struct that defines the context for creating an account.

The # [account (…) ] defines the instructions and constraints for Anchor’s pre-processing while building context.

Next is to create our function:


pub fn create(ctx: Context<Create>) -> ProgramResult {
    let counter_account = &mut ctx.accounts.counter_account;
    counter_account.count = 0;
    Ok(())
}

The create the function will be our RPC request handler which takes the context previously created with Create struct.

Now that we’re done, let’s write the test function and launch our smart contract.


import * as anchor from '@project-serum/anchor';
import { Program } from '@project-serum/anchor';
import { Counterapp } from '../target/types/counterapp';describe('counterapp', () => {    const provider = anchor.Provider.env()
    anchor.setProvider(provider);    const program = anchor.workspace.Counterapp as Program<Counterapp>;    const counterAccount = anchor.web3.Keypair.generate();    it('Is initialized!', async () => {
        await program.rpc.create({
            accounts: {
                counterAccount: counterAccount.publicKey,
                user: provider.wallet.publicKey,
                systemProgram: anchor.web3.SystemProgram.programId,
            },
            signers: [counterAccount]
        } as any)
    });    it("Increment counter", async () => {
        await program.rpc.increment({
            accounts: {
                counterAccount: counterAccount.publicKey
            }
        } as any)
    })    it("Fetch account", async () => {
        const account: any = await
        program.account.counterAccount.fetch(counterAccount.publicKey)
        console.log(account.count)
    })
});

Now, run the test.

anchor test

We can now launch the program after the test passes. Ensure that the solana-test-validator is running.

anchor deploy


Written by talktomaruf | Technical writer and enthusiast for everything blockchain
Published by HackerNoon on 2022/06/30