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.

Continue Reading

Discover more amazing content handpicked just for you

Tutorial

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

In this tutorial, we will compare Etherscan and Infura, two popular services for interacting with the Ethereum blockchain. Both provide APIs, but they serve different purposes and are suited for different types of applications. By understanding the strengths of each, you can choose the right one based on your specific use case, whether it involves querying blockchain data or interacting with the Ethereum network in real-time.

  • Basic understanding of Ethereum and blockchain concepts.
  • Familiarity with APIs and programming in Node.js or any other language.

Oct 24, 2024
Read More
Tutorial

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

  • 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.
  • ETH can be wrapped into WETH and vice versa. There is no change in value—1 ETH always equals 1 WETH.

Oct 24, 2024
Read More
Tutorial
rust

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

Once the build is complete, deploy the program using the following command:

anchor deploy

Aug 27, 2024
Read More
Tutorial
solidity

Understanding Gas and Optimization in Smart Contracts

1. Minimize Storage Writes

  • Writing data to the blockchain is one of the most expensive operations. Whenever possible, minimize storage writes or combine them into a single operation.
  • Example: Instead of updating multiple state variables individually, group them into a struct and update the struct in a single operation.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

Before you start building your DApp, you’ll need to set up your development environment. Here’s what you need:

  • Node.js: For running the development server and installing dependencies.
  • Truffle Suite: A development framework for Ethereum smart contracts and DApps.
  • Ganache: A personal Ethereum blockchain for testing smart contracts locally.
  • MetaMask: A browser extension wallet for interacting with the Ethereum blockchain.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

  • Node.js: Used to install necessary packages and tools.
  • Remix IDE: An online integrated development environment for writing, testing, and deploying smart contracts.
  • MetaMask: A browser extension that acts as a wallet and allows you to interact with the Ethereum blockchain.

Steps to Set Up:

Aug 22, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

Introduction

In this tutorial, we'll learn how to track a specific Solana address for new trades and notify via console.log with the transaction details, including the amount bought or sold. We will use the Solana Web3.js library to connect to the Solana blockchain, listen for new transactions, and fetch their details.

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

Step 3: Fetch New Token Creation Transactions

Solana tokens are created using the SPL Token Program, so we'll track transactions involving this program to identify new tokens. Add the following function to your index.js file:

Aug 09, 2024
Read More
Tutorial
javascript json

Fetching Address Details from Solana

Finally, let's fetch the token holdings of the wallet:

async function getTokenHoldings(walletAddress) {
  try {
    const publicKey = new solanaWeb3.PublicKey(walletAddress);
    const tokenAccounts = await connection.getParsedTokenAccountsByOwner(publicKey, {
      programId: solanaWeb3.TOKEN_PROGRAM_ID,
    });

    console.log('Token Holdings:');
    tokenAccounts.value.forEach((tokenAccount) => {
      const tokenAmount = tokenAccount.account.data.parsed.info.tokenAmount.uiAmount;
      const tokenMint = tokenAccount.account.data.parsed.info.mint;
      console.log(`- Token Mint: ${tokenMint}`);
      console.log(`  Amount: ${tokenAmount}`);
    });
  } catch (error) {
    console.error('Error fetching token holdings:', error);
  }
}

getTokenHoldings(walletAddress);

Aug 09, 2024
Read More
Tutorial
bash rust

Creating a Token on Solana

Create a token account to hold your newly created tokens. This account is associated with your wallet:

   spl-token create-account <TOKEN_MINT_ADDRESS>

Aug 09, 2024
Read More
Tutorial
bash rust

Installing Solana on Ubuntu

Replace v1.16.10 with the latest stable version if a newer version is available.

   cargo build --release

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!