Solana dApp Scaffold

repository·main·Indexed 23 days ago

https://github.com/solana-labs/dapp-scaffold

A Next.js-based starter template for bootstrapping Solana dApps. It includes essential features such as wallet integration, state management, and Web3.js examples. The scaffold provides pre-built components and hooks for managing network configuration, automatic wallet connection, SOL balance tracking, and sending both legacy and versioned transactions.

Tokens
2.2K
Snippets
2
Records
19
Agent score
83%

What's inside solana-labs-dapp-scaffold

  1. Core features included in the scaffold

    main

    The scaffold provides a baseline for Solana dApps, including:

    • Wallet Integration: Support for auto-connect and refresh.
    • State Management: Integrated stores and context.
    • Web3.js Examples: Demonstrations of using Web3.js, including transactions with a connection provider.
    • Navigation: Sample navigation and page changes to demonstrate state persistence.
    • Styling: Clean, simple, and responsive styling.
    • Notifications: (Optional) Example implementation of a notification system.
  2. Understand the project structure

    main

    The scaffold follows a specific directory pattern to organize reusable code and views. While structures may vary, the Next.js scaffold typically uses the following organization:

    • public: Publicly hosted files.
    • src/components: Reusable UI components.
    • src/contexts: Reusable React contexts for passing data through the component tree.
    • src/hooks: Custom React hooks for state or lifecycle features.
    • src/models: Reusable data structures.
    • src/pages: Next.js pages that host metadata and the intended View.
    • src/stores: State management stores.
    • src/styles: Global and reusable styles.
    • src/utils: Reusable utility functions.
    • src/views: The actual views of the project containing main content and components.
  3. Manage user SOL balance with useUserSOLBalanceStore

    main

    The HomeView utilizes useUserSOLBalanceStore to manage and display the user's SOL balance.

    To update the balance for a specific wallet, you can call getUserSOLBalance(publicKey, connection). The current balance can be accessed via the balance selector.

    Note: This store relies on the publicKey from @solana/wallet-adapter-react and the connection from @solana/wallet-adapter-react to perform the fetch.

  4. Sign a message using a Solana wallet

    main

    To sign a message in a Solana dApp, use the signMessage function provided by the @solana/wallet-adapter-react useWallet hook.

    Implementation Steps:

    1. Check Connection: Ensure publicKey is not null.
    2. Check Support: Ensure signMessage is defined (not all wallets support message signing).
    3. Encode Message: Convert your message string into a Uint8Array using TextEncoder.
    4. Sign: Await the signMessage(message) call.
    5. Verify (Optional but recommended): Use @noble/ed25519 to verify that the signature matches the message and the public key.

    Note: The signature returned is a byte array. You can encode it to a Base58 string using bs58 for display or transaction IDs.

  5. Send a Versioned Transaction (v0) using @solana/web3.js

    main

    To send a versioned transaction (specifically Version 0) in a Solana dApp, you must follow a specific workflow:

    1. Prepare Instructions: Define your instructions (e.g., SystemProgram.transfer).
    2. Fetch Blockhash: Retrieve the latest blockhash using connection.getLatestBlockhash().
    3. Create TransactionMessage: Use new TransactionMessage with the payerKey, recentBlockhash, and instructions, then call .compileToV0Message() to generate a V0 message.
    4. Initialize VersionedTransaction: Pass the compiled message into new VersionedTransaction(messageV0).
    5. Send via Wallet: Use the sendTransaction method from the wallet adapter to sign and broadcast the transaction.
    6. Confirm: Await confirmation using connection.confirmTransaction with the signature and the blockhash object used during creation.

    This pattern is essential for transactions that require address lookup tables (ALTs) or other V0 features.

  6. Request a SOL airdrop in a React component

    main

    To request a SOL airdrop, you can use the connection.requestAirdrop method from @solana/web3.js. This requires a connected wallet's publicKey. After requesting the airdrop, you should fetch the latest blockhash and use connection.confirmTransaction to ensure the transaction is processed.

    In this scaffold, it is recommended to trigger a balance refresh (e.g., via getUserSOLBalance) after a successful airdrop to keep the UI in sync.

  7. Send a Versioned Transaction using useWallet and useConnection

    main
    To send a transaction in a Solana dApp using the scaffold's patterns, you should use the useConnection and useWallet hooks from @solana/wallet-adapter-react. The process involves creating instructions (e.g., via SystemProgram.transfer), fetching the latest blockhash, compiling a TransactionMessage into a legacy message, wrapping it in a VersionedTransaction, and finally calling sendTransaction from the wallet context. Always await the transaction confirmation using connection.confirmTransaction to ensure the transaction is processed.
  8. Use the ContextProvider to wrap your application

    main

    The ContextProvider component is the root provider for the application's state. It orchestrates the initialization of network configuration, auto-connection logic, and Solana wallet connectivity. To enable all scaffolded features (network switching, wallet connection, and auto-connection), wrap your application's top-level component with ContextProvider.

    It internally manages the following providers in a specific hierarchy:

    1. NetworkConfigurationProvider: Manages the selected Solana cluster.
    2. AutoConnectProvider: Handles automatic wallet reconnection.
    3. WalletContextProvider: Configures the ConnectionProvider (with the correct cluster endpoint), WalletProvider (with available wallets and error handling), and the WalletModalProvider for the UI.
  9. Use the BasicsView component for dApp demonstrations

    main

    The BasicsView component is a React functional component (FC) that serves as a demonstration view for core dApp functionalities. It aggregates several key interaction components into a single layout, making it useful for testing or showcasing basic Solana wallet interactions like signing messages and sending transactions.

    It includes the following components:

    • SignMessage: For testing wallet signature capabilities.
    • SendTransaction: For sending legacy transactions.
    • SendVersionedTransaction: For sending versioned transactions.

    Note: This component is intended to be used within a React application that has the necessary Solana provider context configured.

  10. Use the useAutoConnect hook to manage automatic wallet connection

    main

    The useAutoConnect hook provides access to the AutoConnectContextState, allowing you to read and update the user's preference for automatic wallet connection. This preference is persisted in local storage via the autoConnect boolean value.

    To use this hook, ensure your component tree is wrapped in the AutoConnectProvider.