Writing a smart contract in Java

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

public class contract {
    
    static public void main(String[] args) {
        
        // THIS SAMPLE ONLY SUPPORTS THE "register" FUNCTION
        if (args.length == 2 && args[0].equals("register")) {
            
            // GET THE CURRENT USER'S NAME
            String previousName = System.getenv("DB_USER_CURRENT");
            
            // OR DEFAULT TO "unknown" IF THIS IS THE FIRST CALL
            if (previousName == null || previousName.length() == 0) {
                previousName = "unknown";
            }
            
            // GET THE TOTAL USER COUNT
            int totalUserCount = envAtoi("DB_TOTALUSERS");
            
            // WRITE PREVIOUS USER NAME TO STDOUT
            System.out.println("OUT=prevname: " + previousName);
            
            // UPDATE CURRENT USER NAME BY WRITING IT TO DB
            System.out.println("DBW=USER_CURRENT=" + args[1]);
            
            // STORE USER NAME UNDER A STORAGE SLOT FOR PERSISTENCE (CURRENT GETS OVERWRITTEN ON EACH CALL)
            System.out.println("DBW=USER_" + totalUserCount + "=" + args[1]);
            
            // INCREMENT THE TOTAL USER COUNT
            System.out.println("DBW=TOTALUSERS=" + (totalUserCount+1));
            return;
        }
        
        // ENSURE PROPER INPUT
        if (args.length >= 1) {
            System.err.println("Wrong CMD: " + args[0]);
            System.exit(1);
        }
        
        System.err.println("Wrong args!");
        System.exit(1);
    };

    static int envAtoi(String env) {
        String val = System.getenv(env);
        if (val == null || val.length() == 0) {
            return 0;
        }
        try {
            return Integer.valueOf(val);
        } catch (Exception e) {
            return 0;
        }
    };
};

Save the contract

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

Last updated