Writing a smart contract in C# (C-Sharp)

Sample contract functionality

The sample contract serves as a demonstration of general QVM logic.

It is capable of:

  • registering users into the database

  • storing the last registered user's name in the database

  • echoing the previous user's name to STDOUT

  • incrementing the total registered user count

  • storing above counter in the database

Sample code

using System;

public class Contract
{
    private static String getEnv(String key, String deft) {
        String? val = Environment.GetEnvironmentVariable(key);
        if (val == null || val.Length == 0) {
            return deft;
        }
        return val;
    }

    private static int atoi(String val) {
        try
        {
            return Int32.Parse(val);
        }
        catch (FormatException)
        {
            return 0;
        }
    }

    public static int Main(String[] args)
    {
        // THIS SAMPLE ONLY SUPPORTS THE "register" FUNCTION
        if (args.Length == 2 && args[0] == "register") {
           // GET THE CURRENT USER'S NAME OR DEFAULT TO "unknown" IF THIS IS THE FIRST CALL
           String? previousName = getEnv("DB_USER_CURRENT", "unknown");
           // GET THE TOTAL USER COUNT
           int totalUserCount = atoi(getEnv("DB_TOTALUSERS", "0"));
           // WRITE PREVIOUS USER NAME TO STDOUT
           Console.Out.WriteLine($"OUT=prevname: {previousName}");
           // UPDATE CURRENT USER NAME BY WRITING IT TO DB
           Console.Out.WriteLine($"DBW=USER_CURRENT={args[1]}");
           // STORE USER NAME UNDER A STORAGE SLOT FOR PERSISTENCE (CURRENT GETS OVERWRITTEN ON EACH CALL)
           Console.Out.WriteLine($"DBW=USER_{totalUserCount}={args[1]}");
           // INCREMENT THE TOTAL USER COUNT
           Console.Out.WriteLine($"DBW=TOTALUSERS={totalUserCount+1}");
           return 0;
        }
        if (args.Length >= 1) {
            Console.Error.WriteLine("Wrong CMD: " + args[0]);
            return 1;
        }
        Console.Error.WriteLine("Wrong args!");
        return 1;
    }
}

Save the contract

Open a text editor and save above sample contract as main.cs file.

Compiling a smart contract in C# (C-Sharp)

Last updated