Solana Cookbook

repository·master·Indexed 20 days ago

https://github.com/solana-developers/solana-cookbook

A repository of practical, 'grab and go' code snippets and guides for implementing Solana-specific programming patterns. It is organized into Core Concepts, Guides, and References to help developers—including those new to blockchain—quickly find and implement common patterns.

Tokens
68.8K
Snippets
236
Records
375
Agent score
71%

What's inside solana-cookbook

  1. Introduction to Gaming on Solana

    master

    Solana is optimized for web3 gaming due to its 400ms block time and fast confirmations, making it suitable for real-time genres like strategy games, city builders, and turn-based games. Developers can leverage Solana to enable asset ownership via NFTs, build in-game economies, create composable game programs, and facilitate player competition for assets.

    Integration Strategies

    There are several ways to integrate Solana into your gaming experience:

    • Digital Collectibles: Use NFTs to represent in-game items or characters.
    • In-game Economy: Use tokens for in-app purchases or micro-payments.
    • Authentication: Use the player's wallet to authenticate them within the game.
    • Rewards: Run tournaments and pay out crypto rewards to players.
    • On-chain Gaming: Develop the game logic entirely on-chain to reward players at every step.

    Supported Development Environments

    You can build games using various technologies and SDKs:

    • Web/Mobile: Javascript with Canvas, or Flutter.
    • Game Engines: Use specialized Solana Game SDKs for Unity or Unreal Engine (e.g., FoundationKit for Unreal).
  2. Overview of the Solana Cookbook

    master
    The Solana Cookbook is a collection of small, digestible code snippets designed for developers—including those with no prior blockchain or Solana experience—to quickly find and implement common patterns. It is organized into 'topics' containing documentation and corresponding code implementations.
  3. Understand the Solana Cookbook structure

    master

    The Solana Cookbook is organized into three primary sections to help developers navigate different types of information:

    • Core Concepts: Explains the fundamental building blocks of Solana necessary for development.
    • Guides: Provides small, focused guides regarding various development tools.
    • References: Contains frequently used code snippets and technical references.
  4. What is a Durable Nonce and when to use it

    master

    Standard Solana transactions rely on a RecentBlockhash, which expires after approximately 150 blocks. If a transaction is not broadcast within this window, it will be rejected.

    A Durable Nonce provides a way to use a 'never expiring' recent blockhash. To use this mechanism, your transaction must satisfy two requirements:

    1. Use a nonce stored in a nonce account as the recent blockhash.
    2. Include a nonce advance operation as the first instruction in the transaction.
  5. Overview of Solana program testing and debugging tools

    master

    There are three primary ways to test and debug Solana BPF programs, each serving different needs:

    1. solana-program-test: Uses a basic local runtime. This is ideal for interactive debugging (e.g., setting breakpoints in VS Code) because it allows you to step through code.
    2. solana-validator: Uses solana-test-validator to provide a more reliable testing environment on a local validator node. While you can run these from an editor, breakpoints within the program itself will be ignored.
    3. solana-test-validator CLI: Runs from the command line to load your program and handle transactions from Rust applications or JavaScript/TypeScript clients using web3.js.

    Best Practice: Use the msg! macro extensively during early development to output logs. Once behavior is stable, remove them, as msg! consumes compute units and can cause programs to fail if they exceed the budget.

  6. What are Program Derived Addresses (PDAs) and how to generate them

    master

    A Program Derived Address (PDA) differs from a standard address in two ways:

    1. It is off the ed25519 curve.
    2. Programs use the program itself to sign for the account instead of a private key.

    Note: While the address is derived from a Program ID, it does not automatically mean the PDA is owned by that program. You can initialize a PDA as a Token Account owned by the Token Program.

    To generate a PDA, use findProgramAddress. This function appends an extra byte (starting from 255 down to 0) to your seeds until it finds a public key that falls off the ed25519 curve. Providing the same Program ID and seeds will always yield the same result.

    // Refer to @/code/accounts/program-derived-address/derived-a-pda/find-program-address.en.ts for implementation
  7. Limit returned data per account with `dataSlice`

    master

    The dataSlice parameter does not reduce the number of accounts returned, but it limits the amount of data returned for each account. This is useful when you need to find accounts (e.g., counting holders) but do not need to read their full state.

    Parameters:

    • offset (number): The number of bytes into the account data to begin returning.
    • length (number): The number of bytes of account data to return.
  8. Understand the core concepts of Solana Programs

    master

    In Solana, Programs (often called smart contracts) are the foundation for on-chain activity. Unlike many other blockchains, Solana strictly separates code from data.

    Key characteristics:

    • Statelessness: Programs themselves do not store state. All data used by a program is stored in separate Accounts.
    • Execution: Programs are owned by a BPF Loader and executed by the Solana Runtime.
    • Storage: A program exists within an Account marked as executable.
    • Entry Point: Every program has a single entry point (typically process_instruction) that receives three mandatory parameters:
      • program_id: The pubkey of the program.
      • accounts: An array of accounts involved in the instruction.
      • instruction_data: A byte array containing the instruction parameters.
  9. Use Recent Blockhashes to prevent replay attacks

    master

    Every transaction must reference a recent blockhash before being sent to the cluster. The blockhash serves two primary purposes:

    1. Preventing Duplication: It helps prevent replay attacks.
    2. Expiration: It allows the network to discard old transactions. A transaction is considered valid for a maximum of approximately 150 blocks or roughly 1 minute and 19 seconds.
  10. Implement account mapping using a single account with a BTreeMap

    master

    An alternative to PDAs is to store a data structure like a BTreeMap within a single account. The account address itself can be either a PDA or a standard Keypair public key.

    Limitations

    • Initialization: You must explicitly initialize the account before inserting key-value pairs.
    • Address Management: You must store the address of this mapping account somewhere to reference it for future updates.
    • Size Constraints: Solana accounts have a maximum size of 10MB, which limits the number of key-value pairs a single BTreeMap can hold.
  11. Distinguish between Native Programs and SPL Programs

    master

    Solana programs are categorized into two main types:

    1. Native Programs: These provide fundamental infrastructure required to run validators. The most prominent example is the System Program, which manages account creation and SOL transfers between accounts.
    2. Solana Program Library (SPL) Programs: These support a wide range of on-chain activities such as token creation, swapping, lending, stake pools, and on-chain name services.
      • The SPL Token Program can be invoked directly via the CLI.
      • Other programs, like the Associated Token Account Program, are typically used as part of custom program logic.