Writing a smart contract in Kotlin

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 smart contract code

// nodejs process object
external val process: dynamic

fun atoi(v: String?): Int {
    return try {
        v?.toInt() ?: 0
    } catch (e: NumberFormatException) {
        0
    }
}

fun errorln(message: Any?) {
    process.stderr.write(message)
    process.stderr.write("\n")
}

fun main() {
    val args = process.argv.slice(2) as Array<String>
    
    // THIS SAMPLE ONLY SUPPORTS THE "register" FUNCTION
    if (args.size == 2 && args[0] == "register") {
        
        // GET THE CURRENT USER'S NAME
        // OR DEFAULT TO "unknown" IF THIS IS THE FIRST CALL
        val previousName = process.env.DB_USER_CURRENT ?: "unknown"
        
        // GET THE TOTAL USER COUNT
        val totalUserCount = atoi(process.env.DB_TOTALUSERS as? String)
        
        // WRITE PREVIOUS USER NAME TO STDOUT
        println("OUT=prevname: $previousName")
        
        // UPDATE CURRENT USER NAME BY WRITING IT TO DB
        println("DBW=USER_CURRENT=${args[1]}")
        
        // STORE USER NAME UNDER A STORAGE SLOT FOR PERSISTENCE (CURRENT GETS OVERWRITTEN ON EACH CALL)
        println("DBW=USER_${totalUserCount}=${args[1]}")
        
        // INCREMENT THE TOTAL USER COUNT
        println("DBW=TOTALUSERS=${totalUserCount+1}")
        process.exit(0)
    }
    
    if (args.size >= 2) {
        errorln("Wrong CMD: ${args[0]}")
        process.exit(1)
    }
    
    errorln("Wrong args!")
    process.exit(1)
}

Save the smart contract

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

Compiling a smart contract in Kotlin

Last updated