DEV Community

Cover image for Building a Solana Wallet Backend with .NET (Part 1)
Lucky Israel
Lucky Israel

Posted on

2

Building a Solana Wallet Backend with .NET (Part 1)

Welcome & allow me be your guide you through building a Solana wallet backend using C# and .NET, no too much talk! Let's dive in. We’ll start with wallet creation, recovery, and balance retrieval functionality. This will be the first part of our Solana wallet series.

Prerequisites

  • Visual Studio or any preferred IDE.
  • .NET SDK installed.
  • Basic understanding of Solana and blockchain technology.
  • NuGet package: Solnett.

First let us organise our folder structure, (feel free to call the project anything you want, for me? I will call mine Solark: "Sol for Solana" and "Ark for the strength of Noah's Ark")

SolarkAPI/
Controllers/
WalletController.cs
Services/
WalletService.cs
Program.cs

Step 1: Setting Up the Project
Create a new ASP.NET Core Web API project:

dotnet new webapi -n SolarkAPI
cd SolarkAPI

Install the Solana SDK:

dotnet add package Solnett

Step 2: Implementing Wallet Functionality
We will create the WalletService to handle wallet operations.

using Solnet.Wallet;
using Solnet.Rpc;
using Solnet.Rpc.Builders;
using Solnet.Wallet.Bip39;

namespace SolarkAPI.Services
{
    public class WalletService
    {
        public Wallet CreateNewWallet()
        {
            var mnemonic = new Mnemonic(WordList.English, WordCount.Twelve);
            return new Wallet(mnemonic);
        }

        public Wallet RecoverWallet(string mnemonicPhrase)
        {
            var mnemonic = new Mnemonic(mnemonicPhrase);
            return new Wallet(mnemonic);
        }

        public async Task<ulong> GetWalletBalanceAsync(string publicKey)
        {
            var rpcClient = ClientFactory.GetClient(Cluster.DevNet);
            var balanceResult = await rpcClient.GetBalanceAsync(publicKey);

            if (balanceResult.WasSuccessful)
                return balanceResult.Result.Value;

            throw new Exception($"Failed to fetch balance: {balanceResult.Reason}");
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Note: you can choose the amount of strings you want your mnemonic phrase to be, i like Twelve because it short

Step 3: Setting Up the Wallet Controller
We will expose wallet functionalities through RESTful API endpoints.

using Microsoft.AspNetCore.Mvc;
using Solark.Services;

[ApiController]
[Route("api/wallet")]
public class WalletController : ControllerBase
{
    private readonly WalletService _walletService;

    public WalletController()
    {
        _walletService = new WalletService();
    }

    [HttpGet("new")]
    public IActionResult CreateWallet()
    {
        var wallet = _walletService.CreateNewWallet();
        return Ok(new
        {
            Mnemonic = wallet.Mnemonic,
            PublicKey = wallet.Account.PublicKey.Key
        });
    }

    [HttpPost("recover")]
    public IActionResult RecoverWallet([FromBody] string mnemonic)
    {
        try
        {
            var wallet = _walletService.RecoverWallet(mnemonic);
            return Ok(new { PublicKey = wallet.Account.PublicKey.Key });
        }
        catch (Exception ex)
        {
            return BadRequest(new { Error = ex.Message });
        }
    }

    [HttpGet("balance/{publicKey}")]
    public async Task<IActionResult> GetBalance(string publicKey)
    {
        try
        {
            var balance = await _walletService.GetWalletBalanceAsync(publicKey);
            return Ok(new { Balance = balance });
        }
        catch (Exception ex)
        {
            return BadRequest(new { Error = ex.Message });
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Note this is just a basic setup, for creating a wallet, mnemonic phrase & recovery and Remember to add your service & map controller to your programs.cs file so your can view your endpoints on swagger.

Step 4: Testing your new API
Run the API and test the endpoints using Swagger or any tool you're comfortable with.

Endpoints:

  1. Create a new wallet: GET /api/wallet/new
  2. Recover a wallet: POST /api/wallet/recover
  3. Get wallet balance: GET /api/wallet/balance/{publicKey}

Example Output

Create Wallet:
{
"Mnemonic": "abandon abandon abandon ...",
"PublicKey": "B63V..."
}

Recover Wallet
{
"PublicKey": "B63V..."
}

Get Balance:
{
"Balance": 50000000
}

Congratulations, you have successfully created an API to generate a Solana wallet address along with its own mnemonic phrase, you can recover a wallet and also get the balance of that wallet with these endpoints.

For out next part, I'll be writing on making transactions, verifying transaction status & viewing transaction details.

Stay tuned for more Solana & .Net contents.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (1)

Collapse
 
jhon_woo_3ad4abccae5e936d profile image
Jhon Woo

Thank you for the very valuable information!
I look forward to the second part and also hope for the following ones.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay