• Services
  • Our Team
  • Blogs
  • Portfolio
  • Contact Us
  • Careers
  • Blockchain Training
Menu
  • Services
  • Our Team
  • Blogs
  • Portfolio
  • Contact Us
  • Careers
  • Blockchain Training
Get a quote
  • Author: Kryptomind

How to Build & Deploy a Solana Smart Contract using Anchor

  • June 25, 2022
  • 1:35 pm

You’re in the right place if you want to learn how to create Solana smart contracts and programs. Solana is an up-and-coming, high-performance, permissionless blockchain that enables quick, inexpensive, and scalable transactions and supports smart contracts written in Rust, C++, and C.

What is Solana?

Solana is a decentralized blockchain ecosystem that aims to eliminate the congestion and scalability concerns that affect existing blockchains. The blockchain is primarily concerned with increasing scalability, such as greater (TPS) and faster confirmation times. It’s an open-source initiative that combines cutting-edge technology from Intel, Netscape, Google, and Qualcomm to help Solana maintain high-performance standards. 

Solana Smart Contract’s Architecture

Traditional EVM-enabled blockchains are not the same as Solana’s smart contract model. A traditional EVM-based contract combines code/logic and state into a single contract deployed on-chain. On the other hand, a smart contract on Solana stays in “read-only” or “stateless” mode and only contains the logic of the program. Once the smart contract is set up, it can be accessed by accounts outside it. These accounts interact with the program and store data about how it interacts with them.

This allows for the logical separation of state (accounts) and contracts logic (programs), which distinguishes typical EVM-enabled smart contracts from Solana smart contracts. Additionally, accounts on Solana and other blockchains are very different. Compared to Ethereum accounts, which are simply pointers to users’ wallets, Solana accounts hold data (such as wallet information).

Furthermore, Solana has a CLI and JSON RPC API to improve DApp interaction with Solana. Moreover, decentralized apps may connect with the blockchain and Solana programs using current SDKs.

  • The program on the left in the above diagram depicts the development process that enables users to build and deploy unique Rust, C, and C++ programs on the Solana blockchain.
  • Anyone with programming knowledge can utilize these apps once they have been effectively distributed. Users must create dApps using existing client SDKs and the JSON RPC API to interact with these apps.
  • Users can create decentralized apps for interacting with the deployed programs under the second development workflow, Client (on the bottom left). These apps may construct various applications, such as cryptocurrency wallets, decentralized exchanges, and more, and send transactions to these programs via client SDK.
  • Program and Client, the two components of the process, work together to create a comprehensive network of dApps and programs that can communicate to update the state and analyze the blockchain.

What is Anchor?

A framework for creating Solana smart contracts, Anchor includes a number of developer tools. In short, the Anchor saves your life and makes it incredibly simple to create smart contracts.

Pre Requisite 

Rust:

It is a prerequisite since it is a highly strong general-purpose programming language. This will be applied to the creation of smart contracts. 

Solana Tool Suit: 

This contains the Solana CLI.

Getting Started

To get started, create a new anchor project:

anchor init counterapp

In the project structure, you will see the following files and folders.

program — This is the directory of Solana programs (Smart contracts)

test — This is where javascript test code lives

migrations — This is the deploy script

app — This is where frontend is going to be built

Let’s look at our lib.rs file in the program directory.

use anchor_lang::prelude::*;

declare_id!("Fg6PaFpoGXkYsidMpWTK6W2BeZ7FEfcYkg476zPFsLnS");

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

The most basic CLI program is this one. When called, the initialize function does nothing more than complete; the initialize struct establishes the initialize function’s environment.

After setting up our project, let’s create our counter application.

To achieve that, we must first set up an account where we may keep our data. You’re probably wondering what the heck this account is. Accounts are only a means of accessing and saving data in Solana sealevel.

In the above code, we have defined two structs; the CounterAccount struct is our Account that contains a count variable 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 our instruction struct that defines our context for creating an account, saying, “Hey, I want to create an account counter_account with the space 32 byte”.

The #[account(…)] attributes define constraints and instructions in preprocessing done by Anchor to create context. Now let’s create our function.

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

Create function is our handler for rpc request, which takes the context created with Create struct.

Now let’s create the test function and deploy our masterpiece.

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

After the test passes, we can now deploy the program. Be sure that the solana-test-validator is running.

anchor deploy

Conclusion

The use of decentralized apps is expanding as more sectors adopt blockchain and decentralized technologies. Solana allows the creation of quick and adaptable smart contracts and decentralized apps as an accessible, high-speed, and affordable eco system. It also often provides updates. Because Solana offers a variety of cutting-edge resources, like SDKs, frameworks, and development tools, developers like us are eager to build on it. The platform also includes invasive tools like Solana CLI and Solana Explorer, which let users interact with the protocol via a command line.

  • Categories: Main Category
PreviousHow to Implement Gasless Transactions?
NextCreate NFTs on NEAR Protocol Using Rust

Related Blogs

How is AI Revolutionising Healthcare?

February 3, 2023

How are machine learning and artificial intelligence used in banking and finance?

January 31, 2023

Three essential machine learning techniques that businesses need to know about

January 26, 2023

A Detailed Guide to the Metaverse in Education

January 17, 2023

7 Crypto Coins That Could Reach New All-Highs in 2025

January 13, 2023
  • Categories: Main Category
Facebook Twitter Youtube Instagram Behance Linkedin

© 2022 Copyright, All Right Reserved, Kryptomind.com 

Services

  • Blockchain
  • Web App Development
  • Mobile App Development
  • Consultacny

Careers

Digital Marketing Executive

Company

  • Services
  • Blogs
  • Our Team
  • Portfolio
  • Contact Us
  • Careers
  • Blockchain Training
Menu
  • Services
  • Blogs
  • Our Team
  • Portfolio
  • Contact Us
  • Careers
  • Blockchain Training