Skip to content

Latest commit

 

History

History
75 lines (62 loc) · 2.99 KB

File metadata and controls

75 lines (62 loc) · 2.99 KB
title Flow Control & Contract Structure
actions
checkAnswer
hints
material
editor
language startingCode answer
c#
public static void Main (string alienName) { uint xna = FindXna (RandomNumber ()); Alien someAlien = new Alien { Xna = xna, AlienName = alienName, }; Runtime.Notify (alienName, "created"); } public static void GenerateAlien (string alienName, byte[] owner) { }
public static object Main (string method, params object[] args) { switch (method) { case "generateAlien": return GenerateAlien ((string) args[0], (byte[]) args[1]); default: return false; } } public static BigInteger GenerateAlien (string alienName, byte[] owner) { uint xna = FindXna (RandomNumber ()); Alien someAlien = new Alien { Xna = xna, AlienName = alienName }; Runtime.Notify (alienName, "created"); return true; }

As we have seen in Lesson 1, Chapter 9, a contract on the Neo network functions as a list of methods that can be called by other programs or clients. A common practice is to use the main method as the entry point, and use the first parameter for users to specify which method they want to call. Below is an example of the main method for a DNS smart contract.

public static object Main (string method, params object[] args) {
    switch (method) {
    case "query":
            return Query ((string) args[0]);
    case "register":
            return Register ((string) args[0], (byte[]) args[1]);
    case "delete":
            return Delete ((string) args[0]);
    default:
            return false;
    }
}

Aside from the first parameter, which takes a string variable, the main methods takes an array of objects as parameters, which get cast into specified data types at method calls.

Note that byte[] is the most commonly used data type for verifying account and encryption. In the case of Register (), the args[1] parameter is the address of an account.

The main method uses a switch-case statement to cycle through method calls, and returns a boolean value of false if no matching statement is found.

Instructions

  • Create a public, static, GenerateAlien () method. Its return type is BigInteger. Its first parameter is a string called alienName. Second parameter is byte[] called owner.
  • Move the body of Main () to the new GenerateAlien () method.
  • Add return 1; at the end of the method. This is a placeholder.
  • Use switch statement to check the value of method variable.
    • In the case that it is generateAlien, return a call to GenerateAlien method.
    • In the default case, return false.
    • In the method call, cast the first argument as string, cast the second argument as byte[]