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

  • API: This script uses Infura’s node access and Ethers.js to send Ether in real-time.
  • Use Case: Essential for dApps, wallets, or any application needing to send transactions or interact with the blockchain live.
  • Data Analytics: Use Etherscan if you need to fetch historical data, such as transaction histories, token balances, or account balances.
  • Blockchain Explorers: Ideal for building tools similar to Etherscan itself, where you query and display blockchain data to users.
  • Read-Only Data: You can’t send transactions, but you can retrieve information about any Ethereum address, smart contract, or token transfer.

Oct 24, 2024
Read More
Tutorial

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

  • Decentralized Exchanges (DEXs): Many decentralized exchanges (like Uniswap) require ERC-20 tokens for trading. WETH allows ETH holders to trade ETH just like any other ERC-20 token.
  • DeFi Lending Platforms: Platforms such as Aave or Compound often require collateral in the form of ERC-20 tokens, making WETH essential for ETH holders who want to participate.
  • Token Swaps: WETH allows for seamless token swaps between ETH and other ERC-20 tokens on platforms that support such swaps.

ETH and WETH serve different but complementary roles in the Ethereum ecosystem. While ETH is the native currency used to power the network, WETH enables ETH to interact with the growing number of decentralized applications and DeFi protocols that rely on the ERC-20 standard. By understanding how to wrap and unwrap ETH, you can effectively engage in the broader Ethereum DeFi ecosystem without leaving the native ETH environment.

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

  • Optimization: Uniswap V2 introduced several optimizations, including reducing the number of state changes in core functions and using assembly code for certain operations.
  • Impact: These optimizations led to significant gas savings, making Uniswap more cost-effective for users.

Aug 22, 2024
Read More
Tutorial
solidity

Building a Decentralized Application (DApp) with Smart Contracts

  • Run truffle init in your terminal to create a new Truffle project.
  • Place your smart contract code in the contracts/ directory.
  • Run truffle compile to compile the smart contract. This will generate the necessary ABI (Application Binary Interface) and bytecode.

Aug 22, 2024
Read More
Tutorial
solidity

Introduction to Smart Contracts on Ethereum

A smart contract is a self-executing contract with the terms of the agreement directly written into code. It runs on the Ethereum blockchain and automatically enforces the terms of the contract. Once deployed, it operates independently without the need for a central authority or intermediary, making transactions transparent, secure, and immutable.

Key Features:

Aug 22, 2024
Read More
Tutorial
javascript nodejs

Tracking Solana Address for New Trades and Amounts

Create a new file called index.js and add the following code to connect to the Solana blockchain:

const solanaWeb3 = require('@solana/web3.js');

// Connect to the Solana Devnet
const connection = new solanaWeb3.Connection(
  solanaWeb3.clusterApiUrl('devnet'),
  'confirmed'
);

console.log('Connected to Solana Devnet');

Aug 09, 2024
Read More
Tutorial
javascript nodejs

Tracking Newly Created Tokens on Solana

In this tutorial, we'll learn how to track newly created tokens on the Solana blockchain. Solana uses the SPL Token Program for its token operations, which allows developers to create, transfer, and manage tokens efficiently. We will explore how to interact with Solana's RPC API and the Solana Web3.js library to monitor new token creation events.

Prerequisites

Aug 09, 2024
Read More
Tutorial
javascript json

Fetching Address Details from Solana

Create a new file called index.js and add the following code to connect to the Solana blockchain:

const solanaWeb3 = require('@solana/web3.js');

// Connect to the Solana Devnet
const connection = new solanaWeb3.Connection(
  solanaWeb3.clusterApiUrl('devnet'),
  'confirmed'
);

console.log('Connected to Solana Devnet');

Aug 09, 2024
Read More
Tutorial
bash rust

Creating a Token on Solana

  • Set up your Solana development environment.
  • Create a new token on the Solana blockchain.
  • Mint new tokens to your wallet.
  • Transfer tokens to another wallet.
  • Ubuntu system with Solana CLI installed (as outlined in the previous tutorial).
  • Basic understanding of blockchain and token concepts.
  • Solana wallet with some SOL tokens for transaction fees (you can request SOL from the Solana faucet for testing).

Aug 09, 2024
Read More
Tutorial
bash rust

Installing Solana on Ubuntu

After installing Solana, you can verify the installation by checking the version of the Solana command-line tools:

solana --version

Aug 09, 2024
Read More

Discussion 0

Please sign in to join the discussion.

No comments yet. Start the discussion!