Writing a Simple Anchor Program

Chapter 5: Writing a Simple Anchor Program

Let’s implement a basic vault program with deposit and withdraw functions.

Task

Create a vault to store and retrieve SOL.

Code

use anchor_lang::prelude::*;

declare_id!("22222222222222222222222222222222222222222222");

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

    pub fn deposit(ctx: Context<VaultAction>, amount: u64) -> Result<()> {
        require!(amount > 0, VaultError::InvalidAmount);
        **ctx.accounts.vault.try_lamports_mut()? += amount;
        **ctx.accounts.signer.try_lamports_mut()? -= amount;
        Ok(())
    }

    pub fn withdraw(ctx: Context<VaultAction>) -> Result<()> {
        let amount = ctx.accounts.vault.lamports();
        **ctx.accounts.vault.try_lamports_mut()? = 0;
        **ctx.accounts.signer.try_lamports_mut()? += amount;
        Ok(())
    }
}

#[derive(Accounts)]
pub struct VaultAction<'info> {
    #[account(mut)]
    pub signer: Signer<'info>,
    #[account(mut)]
    pub vault: AccountInfo<'info>,
    pub system_program: Program<'info, System>,
}

#[error_code]
pub enum VaultError {
    #[msg("Invalid amount")]
    InvalidAmount,
}

Page Layout:

  • Header: Fixed top bar with "Solana Learn" logo, navigation, and profile icon.

  • Main Content:

    • Left Panel (50%): Explanation of vault logic.

    • Right Panel (50%): Code editor with this code.

  • Footer: Link to Anchor Examples.

Visuals:

  • Code Editor: Rust syntax highlighting.

  • Diagram: Arrows showing SOL flow (signer → vault, vault → signer).

Interactivity:

  • Edit code with real-time feedback; "Run Code" to simulate.

Last updated