Solnet C# SDK for Solana

repository·master·Indexed 18 days ago

https://github.com/bmresearch/solnet

A comprehensive C# SDK for Solana designed for the .NET ecosystem. Solnet provides full coverage for JSON RPC and Streaming RPC APIs, support for wallets and keystores (compatible with Phantom and solana-keygen), and integration with SPL programs including Token, Memo, Compute Budget, and Address Lookup Table programs.

Tokens
7K
Snippets
14
Records
21
Agent score
61%

What's inside Solnet

  1. Overview of Solnet features and supported programs

    master

    Solnet provides a comprehensive C# SDK for Solana development with the following capabilities:

    Core Features

    • RPC Support: Full coverage of JSON RPC and Streaming JSON RPC APIs.
    • Wallet/Keystore: Compatible with Phantom and solana-keygen.
    • Encoding/Decoding: Supports base64 and wire format for transactions and messages.
    • Token Management: TokenWallet object for sending SPL tokens and JIT provisioning of Associated Token Accounts.
    • Instruction Decompilation.

    Supported Programs

    Native Programs

    • System Program
    • Stake Program

    Solana Program Library (SPL)

    • Compute Budget Program
    • Account Compression Program
    • Governance Program
    • StakePool Program
    • Address Lookup Table Program
    • Memo Program
    • Token Program
    • Token Swap Program
    • Associated Token Account Program
    • Name Service Program
    • Shared Memory Program
  2. Overview of Solnet features and capabilities

    master

    Solnet is a .NET integration library for Solana that implements the full Solana JSON RPC API. It supports development across Desktop, Web (ASP.NET, Blazor WebAssembly), and Mobile (MAUI, Xamarin, Avalonia) using a shared codebase.

    Key Capabilities:

    • RPC Support: Full coverage of both HTTP and Streaming (WebSocket) JSON RPC APIs.
    • Wallet & Security: Support for Wallets, Accounts, and Keystores (compatible with sollet and solana-keygen).
    • Program Support:
      • Native Programs: System Program.
      • SPL (Solana Program Library): Memo Program, Token Program, Associated Token Account Program, Name Service Program, and Shared Memory Program.
  3. Use Solnet.KeyStore for managing encrypted wallets

    master

    The Solnet.KeyStore assembly provides utilities to save, restore, encrypt, and decrypt wallets. It supports two main formats:

    1. Web3 Secret Storage Definition: Generates an encrypted JSON keystore file that requires a password for decryption.
    2. Simple Keystore: A simpler implementation capable of restoring keys generated by the solana-keygen CLI tool.
  4. Use Solnet.Wallet for wallet initialization and signing

    master
    The Solnet.Wallet assembly provides constructs for initializing wallets following Bip32 or Bip39 standards. Wallets created this way are compatible with keys generated via the solana-keygen CLI tool and Sollet.io. This library also provides the necessary tools to sign data from a given account.
  5. Use Solnet.Rpc for Solana node communication

    master

    The Solnet.Rpc assembly provides the abstractions required to communicate with Solana nodes via HTTP or WebSockets. It includes all necessary models for RPC calls and features a base Transaction builder that can be used to implement custom programs.

    Note: Solnet.Rpc depends on Solnet.Wallet to support transaction signing.

  6. Quickstart: Fetch balance and send a memo

    master

    This minimal example demonstrates how to initialize an RPC client, create a wallet, fetch a balance, and construct/send a transaction containing a memo instruction using the TransactionBuilder and ComputeBudgetProgram.

    using Solnet.Rpc;
    using Solnet.Rpc.Builders;
    using Solnet.Rpc.Types;
    using Solnet.Programs;
    using Solnet.Wallet;
    
    var rpc = ClientFactory.GetClient(Cluster.MainNet);
    var wallet = new Wallet();
    var from = wallet.GetAccount(0);
    
    // Get balance
    var bal = rpc.GetBalance(from.PublicKey);
    Console.WriteLine($"Balance: {bal.Result.Value} lamports");
    
    // Send a simple memo transaction
    var blockhash = rpc.GetLatestBlockHash();
    var tx = new TransactionBuilder()
        .SetRecentBlockHash(blockhash.Result.Value.Blockhash)
        .SetFeePayer(from)
        .AddInstruction(ComputeBudgetProgram.SetComputeUnitLimit(30000))
        .AddInstruction(ComputeBudgetProgram.SetComputeUnitPrice(1000000))
        .AddInstruction(MemoProgram.NewMemo(from, "Hello from Solnet"))
        .Build(from);
    
    var sig = rpc.SendTransaction(tx);
    Console.WriteLine($"tx: {sig.Result}");
  7. Create, Initialize, and Mint Tokens

    master

    To create a new token, you must perform a sequence of instructions: create the mint account, initialize it, create a token account for the owner, initialize that account, and finally mint tokens to it.

    Required Steps:

    1. Rent Exemption: Use rpcClient.GetMinimumBalanceForRentExemption for both TokenProgram.TokenAccountDataSize and TokenProgram.MintAccountDataSize.
    2. Create Mint: SystemProgram.CreateAccount with TokenProgram.ProgramIdKey.
    3. Initialize Mint: TokenProgram.InitializeMint.
    4. Create Token Account: SystemProgram.CreateAccount for the owner's token account.
    5. Initialize Token Account: TokenProgram.InitializeAccount.
    6. Mint: TokenProgram.MintTo to move supply into the account.
    var wallet = new Wallet(MnemonicWords);
    var blockHash = rpcClient.GetLatestBlockHash();
    var minBalanceForExemptionAcc = rpcClient.GetMinimumBalanceForRentExemption(TokenProgram.TokenAccountDataSize).Result;
    var minBalanceForExemptionMint = rpcClient.GetMinimumBalanceForRentExemption(TokenProgram.MintAccountDataSize).Result;
    
    var mintAccount = wallet.GetAccount(21);
    var ownerAccount = wallet.GetAccount(10);
    var initialAccount = wallet.GetAccount(22);
    
    var tx = new TransactionBuilder()
        .SetRecentBlockHash(blockHash.Result.Value.Blockhash)
        .SetFeePayer(ownerAccount)
        .AddInstruction(ComputeBudgetProgram.SetComputeUnitLimit(30000))
        .AddInstruction(ComputeBudgetProgram.SetComputeUnitPrice(1000000))
        .AddInstruction(SystemProgram.CreateAccount(
            ownerAccount,
            mintAccount,
            minBalanceForExemptionMint,
            TokenProgram.MintAccountDataSize,
            TokenProgram.ProgramIdKey))
        .AddInstruction(TokenProgram.InitializeMint(
            mintAccount.PublicKey,
            2,
            ownerAccount.PublicKey,
            ownerAccount.PublicKey))
        .AddInstruction(SystemProgram.CreateAccount(
            ownerAccount,
            initialAccount,
            minBalanceForExemptionAcc,
            TokenProgram.TokenAccountDataSize,
            TokenProgram.ProgramIdKey))
        .AddInstruction(TokenProgram.InitializeAccount(
            initialAccount.PublicKey,
            mintAccount.PublicKey,
            ownerAccount.PublicKey))
        .AddInstruction(TokenProgram.MintTo(
            mintAccount.PublicKey,
            initialAccount.PublicKey,
            25000,
            ownerAccount))
        .AddInstruction(MemoProgram.NewMemo(initialAccount, "Hello from Sol.Net"))
        .Build(new List<Account>{ ownerAccount, mintAccount, initialAccount });
  8. Install Solnet via dotnet CLI or NuGet

    master

    To integrate Solnet into your .NET project, you can use the dotnet CLI or the Visual Studio NuGet Package Manager. Solnet provides full coverage of the Solana JSON RPC API (both HTTP and WebSocket) and is compatible with .NET 5.0 or higher.

    For CLI users, add the core RPC package using:

    dotnet add Solnet.Rpc

    For Visual Studio users, search for Solnet in the NuGet Package Manager and install the required packages.

  9. Securely store keys with KeyStore

    master

    The Solnet.KeyStore project allows for secure storage of keys, seeds, and mnemonics using the Web3 Secret Storage Definition.

    • SecretKeyStoreService: Use EncryptAndGenerateDefaultKeyStoreAsJson to encrypt data and generate a JSON string. Use KeyStore.DecryptKeyStoreFromJson to recover the data using the correct password.
    • SolanaKeyStoreService: Use RestoreKeystore to read keys generated by the solana-keygen CLI tool from a file path using a passphrase.
    // Secret KeyStore Service
    var secretKeyStoreService = new SecretKeyStoreService();
    var jsonString = secretKeyStoreService.EncryptAndGenerateDefaultKeyStoreAsJson(password, data, address);
    
    try
    {
        var decrypted = KeyStore.DecryptKeyStoreFromJson(password, jsonString);
    }
    catch (Exception)
    {
        Console.WriteLine("Invalid password!");
    }
    
    // Solana KeyStore Service
    var solanaKeyStoreService = new SolanaKeyStoreService();
    var wallet = solanaKeyStoreService.RestoreKeystore(filePath, passphrase);
  10. Initialize Wallets and Accounts

    master

    Solnet provides several ways to initialize accounts and wallets depending on your source material (secret keys, mnemonics, or derivation paths).

    • From Secret Key: Use Account.FromSecretKey(string) to create an account directly from a byte array string.
    • Phantom-compatible Wallet: Initialize a Wallet with a mnemonic and a WordList. Use wallet.GetAccount(index) to derive specific accounts. By default, this follows Phantom's derivation pattern.
    • solana-keygen compatible Wallet: Initialize a Wallet using SeedMode.Bip39 and a passphrase. Use the .Account property to access the account, as solana-keygen uses a fixed derivation path.
    • New Wallet: Generate a new mnemonic using the Mnemonic class and pass it to a new Wallet instance.
    // Initialize a keypair from a secret key
    var account = Account.FromSecretKey("");
    
    // Initialize a wallet (Phantom-compatible by default)
    var wallet = new Wallet("mnemonic words ...", WordList.English);
    var account = wallet.GetAccount(10);
    
    // Initialize a wallet compatible with solana-keygen
    var wallet = new Wallet("mnemonic words ...", WordList.English, "passphrase", SeedMode.Bip39);
    var account = wallet.Account;
    
    // Generating new wallets
    var newMnemonic = new Mnemonic(WordList.English, WordCount.Twelve);
    var wallet = new Wallet(newMnemonic);
  11. Install Solnet packages via .NET CLI

    master

    Solnet is modular. Install only the packages required for your specific use case using the .NET CLI:

    • RPC client and streaming: Solana.Rpc, Solana.Programs
    • Wallets and keys: Solana.Wallet
    • Token helpers: Solana.Extensions
    • Keystore utilities: Solana.Keystore
    # Rpc client and streaming
     dotnet add package Solana.Rpc
     dotnet add package Solana.Programs
    
    # Wallets and keys
     dotnet add package Solana.Wallet
    
    # Token helpers
     dotnet add package Solana.Extensions
    
    # Keystore utilities
     dotnet add package Solana.Keystore