Write and Deploy Your First Solana Program on Solana Playground

realacjoshua

RealACJoshua

Posted on November 29, 2024

Write and Deploy Your First Solana Program on Solana Playground

Welcome Back.
In this tutorial, we’ll explore how to write, compile, and deploy a simple Solana program using Solana Playground, an in-browser development environment. Our program will let users store their favorite number, color, and hobbies on-chain.

What We'll Cover

  1. Setting up Solana Playground.
  2. Writing the Solana program.
  3. Breaking down the code.
  4. Compiling the program.
  5. Deploying the program to Solana Devnet.
  6. Interacting with the program.

1. Setting Up Solana Playground

Solana Playground allows you to write, compile, and deploy Solana programs without setting up a local environment.

  1. Visit Solana Playground.

Solana Playground

  1. Create a new project:
    • Click Create New Project.
    • Choose Anchor Framework as the template.

Choose Anchor


2. Writing the Solana Program

Replace the default code in the lib.rs file with the following program:

use anchor_lang::prelude::*;

declare_id!("");

pub const ANCHOR_DISCRIMINATOR_SIZE: usize = 8;

#[program]
pub mod favorites {
    use super::*;

    pub fn set_favorites(
        context: Context<SetFavorites>,
        number: u64,
        color: String,
        hobbies: Vec<String>,
    ) -> Result<()> {
        msg!("Greeting Human from {}", context.program_id);
        let user_public_key = context.accounts.user.key();

        msg!("User {user_public_key}'s favorite number is {number}, favorite color is {color}, and their hobbies are {hobbies:?}");

        context.accounts.favorites.set_inner(Favorites {
            number,
            color,
            hobbies,
        });

        Ok(())
    }
}

#[account]
#[derive(InitSpace)]
pub struct Favorites {
    pub number: u64,

    #[max_len(50)]
    pub color: String,

    #[max_len(5, 50)]
    pub hobbies: Vec<String>,
}

#[derive(Accounts)]
pub struct SetFavorites<'info> {
    #[account(mut)]
    pub user: Signer<'info>,

    #[account(
        init_if_needed,
        payer = user,
        space = ANCHOR_DISCRIMINATOR_SIZE  + Favorites::INIT_SPACE,
        seeds = [b"favorites", user.key().as_ref()],
        bump
    )]
    pub favorites: Account<'info, Favorites>,

    pub system_program: Program<'info, System>,
}
Enter fullscreen mode Exit fullscreen mode

3. Breaking Down the Code Block by Block

Imports

use anchor_lang::prelude::*;
Enter fullscreen mode Exit fullscreen mode
  • Imports essential components from the Anchor framework for Solana development, such as macros and helper types.

Program ID Declaration

declare_id!("");
Enter fullscreen mode Exit fullscreen mode
  • This unique program ID identifies your deployed program on the blockchain. (Yours will be automatically generated, don't freight!!)

Anchor Discriminator

pub const ANCHOR_DISCRIMINATOR_SIZE: usize = 8;
Enter fullscreen mode Exit fullscreen mode
  • A fixed size used to reserve space in accounts for program-specific metadata. Required for Anchor programs.

Program Module

#[program]
pub mod favorites {
    use super::*;

    pub fn set_favorites(
        context: Context<SetFavorites>,
        number: u64,
        color: String,
        hobbies: Vec<String>,
    ) -> Result<()> {
        msg!("Greeting Human from {}", context.program_id);
        let user_public_key = context.accounts.user.key();

        msg!("User {user_public_key}'s favorite number is {number}, favorite color is {color}, and their hobbies are {hobbies:?}");

        context.accounts.favorites.set_inner(Favorites {
            number,
            color,
            hobbies,
        });

        Ok(())
    }
}
Enter fullscreen mode Exit fullscreen mode
  • The #[program] macro defines the entry point of the program.
  • The set_favorites function:
    • Accepts user inputs: a favorite number, a color, and a list of hobbies.
    • Logs the user's inputs using msg!.
    • Stores the data in the Favorites account.

Favorites Account

#[account]
#[derive(InitSpace)]
pub struct Favorites {
    pub number: u64,

    #[max_len(50)]
    pub color: String,

    #[max_len(5, 50)]
    pub hobbies: Vec<String>,
}
Enter fullscreen mode Exit fullscreen mode
  • The Favorites struct represents the data structure stored in the blockchain.
  • Each field (e.g., number, color, hobbies) represents a piece of data the user can store.
  • The #[max_len] attribute limits the maximum size for String and Vec<String> fields.

SetFavorites Context

#[derive(Accounts)]
pub struct SetFavorites<'info> {
    #[account(mut)]
    pub user: Signer<'info>,

    #[account(
        init_if_needed,
        payer = user,
        space = ANCHOR_DISCRIMINATOR_SIZE  + Favorites::INIT_SPACE,
        seeds = [b"favorites", user.key().as_ref()],
        bump
    )]
    pub favorites: Account<'info, Favorites>,

    pub system_program: Program<'info, System>,
}
Enter fullscreen mode Exit fullscreen mode
  • Defines the accounts required to execute the set_favorites function.
  • The favorites account is initialized with specific constraints (e.g., size, payer, and seed).

4. Compiling the Program

  1. Click the Build button in the Solana Playground interface.

  2. Wait for the program to compile. If successful, you’ll see the message "Build Successful."
    Build Successful


5. Deploying the Program to Solana Devnet

  1. Deploy your program:
    • Click Deploy.
    • Your Solana Playground Wallet will pop up (You need some Devnet $SOL to perform this transaction on the Blochain, by default you should have some $SOL).

Wallet Playground

  1. After deployment, copy the program’s public key (That'd be the ID in the declare_id. You’ll need it to interact with the program.

6. Interacting with the Program

a. Set Favorites

To test the program, you’ll call the set_favorites method:

  1. Go to the Test tab in Solana Playground.
  2. Select set_favorites from the dropdown.
  3. Enter the following inputs under Args:
    • number: Your favorite number (e.g., 7).
    • color: Your favorite color (e.g., "blue").
    • hobbies: A list of your hobbies (e.g., ["reading", "coding"]).
  4. Under Accounts input:
    • user: Select Current Wallet
    • favorites: Select From seed
      • seed(1): type "favorites"
      • click on Add Seed
      • seed(2): select publicKey then select Current Wallet
  5. Click on Generate and then click on Test
  6. Check the transaction on Solana Explorer by clicking on the pop-up.

Conclusion

You’ve successfully written, deployed, and tested a Solana program on Devnet. This foundational knowledge will help you dive deeper into Solana development.

If you enjoyed this tutorial, give it a ❤️ and follow for more Solana content. 🚀

💖 💪 🙅 🚩
realacjoshua
RealACJoshua

Posted on November 29, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related