DeveloperBreeze

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

  1. 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
  1. Install Anchor CLI:

Use npm to install the Anchor CLI:

   npm install -g @project-serum/anchor-cli
  1. 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

  1. 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.

  1. Navigate to the Project Directory:
   cd counter

Step 3: Write the Smart Contract

  1. 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.
  1. Save and Exit:

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

Step 4: Build and Deploy the Contract

  1. Build the Project:

Run the following command to build the smart contract:

   anchor build
  1. 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

  1. 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());
     });
   });
  1. 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.

Related Posts

More content you might like

Tutorial

Etherscan vs Infura: Choosing the Right API for Your Blockchain Application

  • Etherscan:
  • Primarily a block explorer and data provider. It offers read-only access to Ethereum blockchain data such as transaction histories, balances, token transfers, and more.
  • Does not allow real-time interaction with the blockchain (e.g., sending transactions).
  • Ideal for querying historical data and performing analytics on blockchain data.
  • Infura:
  • Provides full node access to the Ethereum network, allowing developers to interact with the blockchain in real-time.
  • Supports read and write operations, such as sending transactions, deploying smart contracts, and interacting with dApps.
  • Best for applications that require real-time interaction with Ethereum, such as decentralized apps (dApps).

You should use Etherscan when you need to read data from the Ethereum blockchain, such as querying transaction details, wallet balances, or token transfers. Etherscan is a powerful tool for building blockchain explorers or applications that focus on data analytics.

Oct 24, 2024
Read More
Tutorial

ETH vs WETH: Understanding the Difference and Their Roles in Ethereum

  • ETH: The native asset of Ethereum, does not conform to any token standard.
  • WETH: An ERC-20 token, designed to work seamlessly with Ethereum-based DeFi applications and smart contracts.
  • ETH: Used for gas fees, transactions, and interacting directly with the Ethereum network.
  • WETH: Primarily used within decentralized applications and protocols that require ERC-20 tokens, such as decentralized exchanges (e.g., Uniswap) or lending platforms.

Oct 24, 2024
Read More
Tutorial
rust

Using Solana's Program Library: Building Applications with Pre-Built Functions

This command will deploy your program to the Solana cluster you’ve configured (either localnet, devnet, or mainnet).

To interact with your newly deployed program, you can write a simple client script in Rust or JavaScript using Solana's web3.js library. Here's an example using JavaScript:

Aug 27, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

  • Remix IDE: Provides real-time gas estimates while writing and testing smart contracts.
  • Solidity Coverage: A tool for generating gas reports and identifying expensive operations in your code.
  • ETH Gas Station: An online service that provides insights into gas prices and recommended gas limits for transactions.

Example Workflow:

Aug 22, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Be the first to share your thoughts!