Published on August 09, 2024By DeveloperBreeze

Tutorial: Building a Simple Solana Smart Contract with Anchor

Introduction

Solana is known for its high-performance blockchain infrastructure, which supports scalable decentralized applications (dApps). Anchor is a framework that streamlines smart contract development on Solana by providing tools and abstractions that simplify coding and deployment. In this tutorial, we'll create a basic Solana smart contract using Anchor to store and update a counter value. You'll learn how to set up your development environment, write a smart contract, and deploy it to the Solana Devnet.

Objectives

By the end of this tutorial, you will:

  • Set up a Solana development environment with Anchor.

  • Write a simple smart contract to manage a counter.

  • Deploy the contract to the Solana Devnet.

  • Interact with the deployed contract.

Prerequisites

  • Ubuntu system with Rust installed.

  • Basic understanding of Rust programming.

  • Solana CLI installed (as outlined in previous tutorials).

  • Node.js and npm installed for Anchor.

Step 1: Install Anchor

    • Install Node.js and npm:

Anchor requires Node.js for its CLI tool. Install it using the following commands:

sudo apt update
   sudo apt install -y nodejs npm
   

    • Install Anchor CLI:

Use npm to install the Anchor CLI:

npm install -g @project-serum/anchor-cli
   

    • Verify Anchor Installation:

Check that Anchor is installed correctly:

anchor --version
   

You should see the version number of the Anchor CLI.

Step 2: Set Up a New Anchor Project

    • Create a New Project:

Use Anchor to create a new project named counter:

anchor init counter
   

This command creates a new directory named counter with the basic project structure.

    • Navigate to the Project Directory:

cd counter
   

Step 3: Write the Smart Contract

    • Edit the lib.rs File:

Open the lib.rs file located in the programs/counter/src directory:

nano programs/counter/src/lib.rs
   

Replace the contents with the following code to create a counter program:

use anchor_lang::prelude::*;

   declare_id!("Fg6PaFpoGXkYsidMpWxTWG9AAM9QK2ZrhQWk5raUB7Uq");

   #[program]
   pub mod counter {
       use super::*;
       pub fn initialize(ctx: Context<Initialize>) -> ProgramResult {
           let counter = &mut ctx.accounts.counter;
           counter.count = 0;
           Ok(())
       }

       pub fn increment(ctx: Context<Increment>) -> ProgramResult {
           let counter = &mut ctx.accounts.counter;
           counter.count += 1;
           Ok(())
       }
   }

   #[derive(Accounts)]
   pub struct Initialize<'info> {
       #[account(init, payer = user, space = 8 + 8)]
       pub counter: Account<'info, Counter>,
       #[account(mut)]
       pub user: Signer<'info>,
       pub system_program: Program<'info, System>,
   }

   #[derive(Accounts)]
   pub struct Increment<'info> {
       #[account(mut)]
       pub counter: Account<'info, Counter>,
   }

   #[account]
   pub struct Counter {
       pub count: u64,
   }
   

- This code defines a Solana program with two functions: initialize and increment.

- The initialize function sets up the counter with an initial value of zero.

- The increment function increases the counter's value by one.

    • Save and Exit:

Save the file and exit the editor (Ctrl+X, then Y, then Enter).

Step 4: Build and Deploy the Contract

    • Build the Project:

Run the following command to build the smart contract:

anchor build
   

    • Deploy the Contract to Devnet:

Use Anchor to deploy the contract to the Solana Devnet:

anchor deploy
   

- Make sure your Solana CLI is configured to use the Devnet (solana config set --url https://api.devnet.solana.com).

Step 5: Interact with the Deployed Contract

    • Run a Test:

Create a simple test script in the tests directory to interact with the contract:

nano tests/counter.js
   

Add the following JavaScript code:

const anchor = require("@project-serum/anchor");

   describe("counter", () => {
     // Configure the client to use the local cluster.
     const provider = anchor.AnchorProvider.env();
     anchor.setProvider(provider);

     it("Initializes and increments the counter", async () => {
       const program = anchor.workspace.Counter;

       // Create a new account to hold the counter state.
       const counter = anchor.web3.Keypair.generate();

       // Initialize the counter.
       await program.rpc.initialize({
         accounts: {
           counter: counter.publicKey,
           user: provider.wallet.publicKey,
           systemProgram: anchor.web3.SystemProgram.programId,
         },
         signers: [counter],
       });

       // Increment the counter.
       await program.rpc.increment({
         accounts: {
           counter: counter.publicKey,
         },
       });

       // Fetch the account details.
       const account = await program.account.counter.fetch(counter.publicKey);
       console.log("Count:", account.count.toString());
     });
   });
   

    • Run the Test:

Use the following command to run the test and interact with your contract:

anchor test
   

You should see output indicating that the counter was initialized and incremented successfully.

Conclusion

Congratulations! You've successfully set up a Solana development environment using Anchor, written a basic smart contract, and deployed it to the Solana Devnet. This tutorial introduced you to the fundamentals of smart contract development on Solana and demonstrated how Anchor simplifies the process. You can now explore more complex smart contract designs and leverage Solana's capabilities to build scalable decentralized applications.

Anchor makes it easier to develop, test, and deploy smart contracts on Solana, empowering developers to create high-performance dApps quickly and efficiently. Happy coding!

Comments

Please log in to leave a comment.

Continue Reading:

Installing Solana on Ubuntu

Published on August 09, 2024

bashrust

Creating a Token on Solana

Published on August 09, 2024

bashrust

Fetching Address Details from Solana

Published on August 09, 2024

javascriptjson

Tracking Newly Created Tokens on Solana

Published on August 09, 2024

javascriptnodejs

Tracking Solana Address for New Trades and Amounts

Published on August 09, 2024

javascriptnodejs

Introduction to Smart Contracts on Ethereum

Published on August 22, 2024

solidity

Understanding Gas and Optimization in Smart Contracts

Published on August 22, 2024

solidity