| title |
Implementing tokensOf () |
| actions |
|
| material |
| editor |
| language |
startingCode |
answer |
c# |
public class AlienFinder : SmartContract {
...
public static string name () => "Alien";
public static string symbol () => "ALI";
public static BigInteger totalSupply () => getCounter ();
public static byte decimals () => 0;
public static BigInteger balanceOf (byte[] addr) {
if (addr.Length != 20)
throw new InvalidOperationException ("The parameter owner should be a 20-byte address");
BigInteger balance = 0;
byte[] value = Storage.Get(addr);
if (value != null)
balance = value.ToBigInteger();
return balance;
}
public static byte[] ownerOf (byte[] id) {
Alien a = Query (id);
if (a != null) return a.Owner;
return null;
}
public static Alien[] tokensOf (byte[] owner) {
if (owner.Length != 20)
throw new InvalidOperationException ("The parameter owner should be a 20-byte address");
// Implement (1) here
int balance =
Alien[] tokens =
int idx =
// Implement (2) here
for () {
Alien token
}
return tokens;
}
}
|
public class AlienFinder : SmartContract {
...
public static string name () => "Alien";
public static string symbol () => "ALI";
public static BigInteger totalSupply () => getCounter ();
public static byte decimals () => 0;
public static BigInteger balanceOf (byte[] addr) {
if (addr.Length != 20)
throw new InvalidOperationException ("The parameter owner should be a 20-byte address");
BigInteger balance = 0;
byte[] value = Storage.Get(addr);
if (value != null)
balance = value.ToBigInteger();
return balance;
}
public static byte[] ownerOf (byte[] id) {
Alien a = Query (id);
if (a != null) return a.Owner;
return null;
}
public static Alien[] tokensOf (byte[] owner) {
if (owner.Length != 20)
throw new InvalidOperationException ("The parameter owner should be a 20-byte address");
int balance = (int) balanceOf (owner);
Alien[] tokens = new Alien[balance + 1];
int idx = 0;
for (BigInteger id = 1; id <= totalSupply (); id = id + 1) {
Alien token = Query (id.ToByteArray ());
if (token != null && token.Owner == owner) {
tokens[idx] = token;
idx = idx + 1;
}
}
return tokens;
}
}
|
|
|
Now that each alien has a designated owner, it is now possible to write a method that returns all aliens of a given owner: tokensOf (). Our method will take an owner address in byte[] as parameter, and returns an array of Alien objects which belong to the address.
-
Initialize variables
balance is the current balance of the given owner
tokens is an array with length (balance + 1)
idx is a pointer for tokens that indicates where a new Alien should be added. It starts at 0.
-
Iterate through all tokens, find tokens that beloneg to the owner
- Declare a for statement. Set a
BigInteger named id that begins at 1, and increments by 1 as long as it is not greater than the total supply.
- Read the next token using id.
- If
token is not null and belongs to owner, add it to tokens at idx position. Increment idx.