Solana Foundation Program Examples

repository·main·Indexed 23 days ago

https://github.com/solana-foundation/program-examples

A repository of Solana onchain program examples implemented in Anchor, Pinocchio, and Native Rust. It covers various programming patterns including security checks, account closure, Counter and Favorites program implementations, Cross-Program Invocation (CPI), Program Derived Addresses (PDAs), and account creation using SBPF.

Tokens
102.7K
Snippets
269
Records
426
Agent score
81%

What's inside solana-foundation-program-examples

  1. Overview of World Cup Webapp features

    main

    The World Cup Webapp is a generic Solana app shell designed to interface with the World Cup on-chain program. Key capabilities include:

    • Wallet Connection: Integration with Solana wallets (tested with Phantom) featuring real-time SOL and token balance displays.
    • Cluster Switching: Ability to switch between localnet, devnet, testnet, mainnet, or a custom RPC endpoint.
    • Program Deploy & Status: Tools to deploy and inspect the on-chain program (intended for development use).
    • Token Management: Functionality to add, select, and view balances for various tokens.
    • Dev Faucet: Request SOL/USDC airdrops for local testing (this feature is hidden on mainnet).
    • Theme Support: Toggle between dark and light modes.
  2. Overview of available Solana program examples

    main

    This repository provides a collection of onchain program examples categorized into Basics and Tokens. Each example is typically provided in multiple flavors: anchor, pinocchio, and native.

    Basics

    • Hello world: Minimal program that logs a greeting.
    • Account-data: Storing and retrieving data using Solana accounts.
    • Counter: Storing global state in an account that increments on call.
    • Favorites: Saving per-user state where users can only update their own data.
    • Checking Instruction Accounts: Validating that provided accounts meet specific criteria.
    • Closing Accounts: Closing an account and reclaiming Lamports.
    • Creating Accounts: Creating new accounts and calculating minimum rent.
    • Cross program invocations: Invoking one program from another.
    • PDA rent-payer: Using a Program Derived Address (PDA) to pay rent for new accounts.
    • Processing instructions: Using instruction parameters in handlers.
    • Storing date in program derived addresses: Managing state via PDAs.
    • Handling accounts that expand in size: Using realloc to manage changing state sizes.
    • Laying out larger programs: Organizing large-scale onchain programs.
    • Transferring SOL: Sending SOL between accounts.

    Tokens

    • Creating tokens: Creating a token with a symbol and icon.
    • NFT operations: Managing collections, minting, and verifying NFTs via Metaplex.
    • Transferring Tokens: Minting and transferring tokens between accounts.
    • Escrow: Implementing a decentralized asset swap between two users.
    • Fundraising with SPL Tokens: Creating a fundraiser account with a target mint and goal.
    • Minting with PDA authority: Using a PDA as a mint authority within a program.
    • Automated Market Maker (AMM): Creating liquidity pools for asset trading.
    • External delegate token master: Controlling transfers via external secp256k1 signatures.
  3. Overview of the World Cup bracket prediction game

    main

    The World Cup bracket prediction game is a Solana-based application where entrants pay a fixed fee to submit a 32-game bracket. The game uses consistency checks for submissions and an admin oracle to record results. A permissionless refresh_score function processes brackets into a provable on-chain tally. To ensure a single winner, the ranking logic follows a strict hierarchy: total score, then goal-closeness, then earliest submission time.

    Game Lifecycle:

    1. init_config: Initialize game configuration.
    2. submit_bracket: Entrants submit their 32-game predictions.
    3. lock: Lock the bracket submissions.
    4. post_result / post_goals: Admin oracle records match outcomes.
    5. refresh_score: Permissionless function that tallies scores on-chain.
    6. finalize: Finalize the game state.
    7. claim: Winners claim the pot.
  4. Overview of Token Extension MetaData Pointer NFT

    main

    This project demonstrates how to create an NFT using the Solana Token-2022 program extensions, specifically utilizing the metadata_pointer extension.

    This approach allows for on-chain key-value stores within the metadata, which is particularly useful for games to save character states (e.g., level, XP, current weapon, or collected items) directly on-chain. These metadata fields can eventually be used by marketplaces for filtering and ordering NFTs based on in-game progress.

  5. Use the Solana Program cNFT Transfer example

    main

    This example demonstrates how to interact with Metaplex compressed NFTs (cNFTs) within a Solana Anchor program. The core functionality allows for transferring cNFTs to a Program Derived Address (PDA) acting as a 'vault' and subsequently withdrawing them using program instructions.

    Key Functionality

    • Vault Mechanism: A PDA account serves as a vault where cNFTs can be sent manually and then withdrawn via program instructions.
    • Withdrawal Instructions:
      • A simple transfer instruction to withdraw a single cNFT.
      • An instruction to withdraw two cNFTs simultaneously.

    Project Structure

    • programs/: Contains the Anchor program source code.
    • tests/: Contains client-side tests.
    • tests/scripts/: Contains TypeScript Node scripts for running tests individually. Specifically, withdrawWithLookup.ts demonstrates how to use the program in conjunction with Address Lookup Tables (ALTs).
  6. Understand the Anchor Escrow program

    main

    The Anchor Escrow program enables a secure, trustless swap between two users. It allows a 'maker' to offer a specific amount of one token (Token A) in exchange for a specific amount of another token (Token B) from a 'taker'.

    Key features:

    • Trustless Swapping: The program acts as a trusted intermediary, ensuring tokens are only released when both parties meet the specified exchange conditions.
    • Direct Transactions: Users transact directly with each other through the program, ensuring they receive 100% of the desired tokens without intermediary fees.
    • Security: Prevents scenarios where one party takes the offered tokens without fulfilling their side of the swap.
  7. How to use Solana Program cNFT utils

    main

    This repository provides example code for interacting with Metaplex compressed NFTs (cNFTs) within Solana Anchor programs. It demonstrates how to implement custom logic by performing Cross-Program Invocations (CPI) to the Bubblegum minting instruction.

    Core Functionality

    • mint: Mints a cNFT to a collection via CPI to Bubblegum. This instruction can also be used to initialize program-specific Program Derived Addresses (PDAs).
    • verify: A utility function used to verify that the owner of a cNFT actually executed the specific program instruction. This is intended for use in future program-specific logic.

    Key Components

    • Programs: Uses a validate/actuate pattern. You can validate constraints using an access_control macro, which is useful when combined with cNFT verification logic.
    • Tests:
      • setup.ts: Used to initialize a collection and its underlying Merkle tree(s).
      • tests.ts: Used for running individual minting and verification tests.
  8. Transfer SOL between system accounts

    main

    This example demonstrates the fundamental process of transferring SOL between two system accounts (accounts owned by the System Program). While this example focuses on system accounts, the concept of transferring SOL can be applied to various account types on Solana.

    Note on Account Initialization: In the provided test implementations (both native and anchor), a brand new keypair is generated. Transferring SOL to a new keypair's address initializes it as a default system account. In the Anchor implementation, this requires a /// CHECK attribute to satisfy the account validation requirements for an uninitialized account being used in a context where its ownership is being verified.