Solana Foundation Program Examples
repository·main·Indexed 23 days ago
https://github.com/solana-foundation/program-examplesA 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.
What's inside solana-foundation-program-examples
- The Token Fundraiser example demonstrates how to implement a fundraising mechanism for SPL Tokens using the Anchor framework. It allows a user to create a fundraiser account by specifying a target amount and the specific token mint they wish to collect.
Overview of World Cup Webapp features
mainThe 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.
Overview of available Solana program examples
mainThis repository provides a collection of onchain program examples categorized into Basics and Tokens. Each example is typically provided in multiple flavors:
anchor,pinocchio, andnative.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
reallocto 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.
Overview of the World Cup bracket prediction game
mainThe 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_scorefunction 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:
init_config: Initialize game configuration.submit_bracket: Entrants submit their 32-game predictions.lock: Lock the bracket submissions.post_result/post_goals: Admin oracle records match outcomes.refresh_score: Permissionless function that tallies scores on-chain.finalize: Finalize the game state.claim: Winners claim the pot.
Overview of Token Extension MetaData Pointer NFT
mainThis project demonstrates how to create an NFT using the Solana Token-2022 program extensions, specifically utilizing the
metadata_pointerextension.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.
Overview of the Favorites Anchor program
mainThe Favorites program is a basic Anchor application designed to demonstrate how to use Program Derived Addresses (PDAs) to store user-specific data. It utilizes Anchor's built-in account checks to enforce security, ensuring that users can only modify their own data and cannot access or overwrite the data of others.Use the Counter example program
mainThe Counter program is a basic example that demonstrates how to create a counter and increment its value. The program is designed such that any user (any public key) can increment any existing counter.Create an account using SBPF
mainThecreate-account-asm-programis an example program built using sbpf. SBPF is a toolchain used to create Solana programs via assembly/low-level instructions rather than high-level frameworks like Anchor or Native Rust.Use the Solana Program cNFT Transfer example
mainThis 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.tsdemonstrates how to use the program in conjunction with Address Lookup Tables (ALTs).
Understand the Anchor Escrow program
mainThe 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.
How to use Solana Program cNFT utils
mainThis 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/actuatepattern. You can validate constraints using anaccess_controlmacro, 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.
Transfer SOL between system accounts
mainThis 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
nativeandanchor), 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/// CHECKattribute to satisfy the account validation requirements for an uninitialized account being used in a context where its ownership is being verified.