Let us build a simple yet powerful API that allows you to check any Solana wallet's balance using .NET 8 and the Solnett library. We'll create a minimal API with proper error handling, documentation, and clean architecture.
Prerequisites
Before we begin, make sure you have:
- .NET 8 SDK installed
 - Your favorite code editor (Visual Studio, VS Code, etc.)
 - Basic understanding of C# and RESTful APIs
 - Basic knowledge of Solana blockchain concepts
 
Setting Up the Project
First, create a new web API project:
dotnet new web -n SolanaBalanceChecker
cd SolanaBalanceChecker
Next, let us install the required NuGet packages:
dotnet add package Solnet.Rpc
dotnet add package Solnet.Wallet
dotnet add package Microsoft.AspNetCore.OpenApi
dotnet add package Swashbuckle.AspNetCore
Understanding the Code
Let's break down our solution into key components:
1. Setting up the Dependencies
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Add Solana RPC client as a singleton
builder.Services.AddSingleton<IRpcClient>(sp => 
    ClientFactory.GetClient(Cluster.MainNet)
);
What are we doing here?
- We're creating a minimal API application
 - Adding Swagger support for API documentation
 - Registering Solnet's RPC client as a singleton service
 - Configuring it to use Solana's MainNet (you can change this to TestNet or DevNet)
 
2. Creating the Balance Endpoint
app.MapGet("/balance/{walletAddress}", async (string walletAddress, IRpcClient rpcClient) =>
{
    try
    {
        // Validate wallet address format
        if (!Solnet.Wallet.PublicKey.IsValid(walletAddress))
        {
            return Results.BadRequest("Invalid Solana wallet address");
        }
        // Create public key from address
        var publicKey = new Solnet.Wallet.PublicKey(walletAddress);
        // Get the balance
        var balance = await rpcClient.GetBalanceAsync(publicKey);
Notes:
- We create a GET endpoint that accepts a wallet address as a parameter
 - The address is validated using Solnet's built-in validator
 - We convert the address string to a PublicKey object
 - The RPC client is injected automatically thanks to dependency injection
 
3. Processing the Balance
if (balance.WasSuccessful)
{
    // Convert lamports to SOL (1 SOL = 1,000,000,000 lamports)
    decimal solBalance = balance.Result.Value / 1000000000m;
    return Results.Ok(new
    {
        Address = walletAddress,
        BalanceInSol = solBalance,
        BalanceInLamports = balance.Result.Value
    });
}
Important Details:
- Solana balances are returned in lamports (1 SOL = 1,000,000,000 lamports)
 - We convert the balance to SOL for better readability
 - We return both SOL and lamports values for flexibility
 - The response is automatically serialized to JSON
 
At the end, your get request should look like this:
app.MapGet("/balance/{walletAddress}", async (string walletAddress, IRpcClient rpcClient) =>
{
    try
    {
        // Validate wallet address format
        if (!Solnet.Wallet.PublicKey.IsValid(walletAddress))
        {
            return Results.BadRequest("Invalid Solana wallet address");
        }
        // Create public key from address
        var publicKey = new Solnet.Wallet.PublicKey(walletAddress);
        // Get the balance
        var balance = await rpcClient.GetBalanceAsync(publicKey);
        if (balance.WasSuccessful)
        {
            // Convert lamports to SOL (1 SOL = 1,000,000,000 lamports)
            decimal solBalance = balance.Result.Value / 1000000000m;
            return Results.Ok(new
            {
                Address = walletAddress,
                BalanceInSol = solBalance,
                BalanceInLamports = balance.Result.Value
            });
        }
        else
        {
            return Results.Problem(
                detail: balance.Reason,
                statusCode: 500
            );
        }
    }
    catch (Exception ex)
    {
        return Results.Problem(
            detail: ex.Message,
            statusCode: 500
        );
    }
})
.WithName("GetBalance")
.WithOpenApi();
Test your API
- Run your application:
 
dotnet run or dotnet watch run
- Open your browser and navigate to:
 
https://localhost:5001/swagger
- Try it out with a real Solana wallet address:
 
GET /balance/7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU
Example Response:
{
    "address": "7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU",
    "balanceInSol": 1.5,
    "balanceInLamports": 1500000000
}
Error Handling
catch (Exception ex)
{
    return Results.Problem(
        detail: ex.Message,
        statusCode: 500
    );
}
You'll receive clean error messages depending on the error:
- Invalid wallet addresses
 - Network connection issues
 - RPC errors
 
Conclusion
Congrtatulation now have a working Solana wallet balance checker API built with .NET!.
              
    
Top comments (0)