Logo

dev-resources.site

for different kinds of informations.

Write and Deploy Your First Solana Program on Solana Playground

Published at
11/29/2024
Categories
anchor
solana
rust
blockchain
Author
realacjoshua
Categories
4 categories in total
anchor
open
solana
open
rust
open
blockchain
open
Author
12 person written this
realacjoshua
open
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. 🚀

solana Article's
30 articles in total
Favicon
Building a Solana Wallet Backend with .NET (Part 1)
Favicon
Solana Account Model Simplified
Favicon
Introducing Yamaswap
Favicon
I Just Launched a Meme Coin!
Favicon
solana
Favicon
Bitcoin vs Ethereum vs Solana: Trendsetters in the Web3 Revolution ✨⚛✨
Favicon
🔐 Mastering Account Initialization and PDAs on Solana 🚀
Favicon
From NFTs to DeFi: What Developers Can Do on Solana in 2025
Favicon
solana是如何算seed地址
Favicon
Ethereum vs Solana: Understanding Data Storage Differences in Their Ecosystems
Favicon
Build a Solana Wallet Balance Checker API with (C#) .NET and Solnett
Favicon
🔍 Why Are There So Many Bots on Solana, Especially in Meme Tokens?
Favicon
Solana Pro RPC with X2 Performance Launched by GetBlock
Favicon
Ironforge: A Comprehensive DevOps Platform for Web3 Applications
Favicon
GetBlock Introduces Solana PRO - Enhanced SOL RPC Powered with Rich SDK Support, Jito, Yellowstone Geyser gRPC, and More!
Favicon
Need some help for getting Web3 internship
Favicon
Shorts. Solana Versioned Transaction structure
Favicon
Shorts. Get CompactU16 array length
Favicon
A Developer’s Guide into Account Abstraction Models
Favicon
solana 获取钱包token余额,及优化
Favicon
Accounts: The Digital DNA of Solana
Favicon
Welcome to Solana: A Web2 Developer's Travel Guide to the Blockchain Nation
Favicon
Web3 explained for Web2 Developers: My Personal Journey from SQL to Solana
Favicon
How to Use DefiLlama: A Comprehensive Guide
Favicon
OKX DEX API Guide: Building a Solana Token Swap Interface
Favicon
Solana Safe Transfer (Fat-Finger-proof Transfer)
Favicon
Atom transactions using Jito bundles
Favicon
Blinks on AWS with SST
Favicon
Write and Deploy Your First Solana Program on Solana Playground
Favicon
Running Your First Solana Project with Anchor

Featured ones: