Writing a smart contract in Python

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

import os
import sys

def getenv(key, deft):
    return os.getenv(key) or deft

def get_int_env(key, deft):
    try:
        return int(getenv(key, ""))
    except Exception:
        return deft

def stdout_writeln(s):
    sys.stdout.write(s + "\n")

def stderr_writeln(s):
    sys.stderr.write(s + "\n")

def contract(argv):
    
    # THIS SAMPLE ONLY SUPPORTS THE "register" FUNCTION
    if len(argv) == 3 and argv[1] == "register":
        
        # GET THE CURRENT USER'S NAME OR DEFAULT TO "unknown" IF THIS IS THE FIRST CALL
        previous_name = getenv("DB_USER_CURRENT", "unknown")
        
        # GET THE TOTAL USER COUNT
        total_user_count = get_int_env("DB_TOTALUSERS", 0)
        
        # WRITE PREVIOUS USER NAME TO STDOUT
        stdout_writeln("OUT=prevname: " + previous_name)

        # UPDATE CURRENT USER NAME BY WRITING IT TO DB
        stdout_writeln("DBW=USER_CURRENT=" + argv[2])

        # STORE USER NAME UNDER A STORAGE SLOT FOR PERSISTENCE (CURRENT GETS OVERWRITTEN ON EACH CALL)
        stdout_writeln("DBW=USER_%d=%s" % (total_user_count, argv[2]))

        # INCREMENT THE TOTAL USER COUNT
        stdout_writeln("DBW=TOTALUSERS=%d" % (total_user_count+1))

        # CONTRACT RAN SUCCESSFULLY, EXIT WITH ZERO CODE
        sys.exit(0)

    # WRONG INVOCATION
    if len(argv) >= 2:
        stderr_writeln("Wrong CMD: %s" % argv[1])
        sys.exit(1)

    stderr_writeln("Wrong argv!")
    sys.exit(1)


if __name__ == '__main__':
    contract(sys.argv)

Save the smart contract

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

Compiling a smart contract in Python

Last updated