nearprotocol / NEARStudio

IDE for building smart contracts on NEAR Protocol
https://studio.nearprotocol.com
MIT License
67 stars 18 forks source link

redundant functions in Token Smart Contract sample #231

Open amgando opened 4 years ago

amgando commented 4 years ago

The current code for the contract (in assembly/main.ts) has 2 similar (redundant) functions: getBalance and balanceOf. also collections is not used.

in keeping with the standard interface, including the method order, the template code should be changed to the following:

note, the methods have been re-ordered to be in line with the ERC-20 standard here

//@nearfile
import { context, storage, logging, PersistentMap } from "near-runtime-ts";

// --- contract code goes below

let balances = new PersistentMap<string, u64>("b:");
let approves = new PersistentMap<string, u64>("a:");

let TOTAL_SUPPLY: u64 = 1000000;

export function totalSupply(): string {
  return TOTAL_SUPPLY.toString();
}

export function balanceOf(tokenOwner: string): u64 {
  logging.log("balanceOf: " + tokenOwner);
  if (!balances.contains(tokenOwner)) {
    return 0;
  }
  let result = balances.getSome(tokenOwner);
  return result;
}

export function transfer(to: string, tokens: u64): boolean {
  logging.log("transfer from: " + context.sender + " to: " + to + " tokens: " + tokens.toString());
  let fromAmount = balanceOf(context.sender);
  assert(fromAmount >= tokens, "not enough tokens on account");
  balances.set(context.sender, fromAmount - tokens);
  balances.set(to, balanceOf(to) + tokens);
  return true;
}

export function transferFrom(from: string, to: string, tokens: u64): boolean {
  let fromAmount = balanceOf(from);
  assert(fromAmount >= tokens, "not enough tokens on account");
  let approvedAmount = allowance(from, to);
  assert(tokens <= approvedAmount, "not enough tokens approved to transfer");
  balances.set(from, fromAmount - tokens);
  balances.set(to, balanceOf(to) + tokens);
  return true;
}

export function approve(spender: string, tokens: u64): boolean {
  logging.log("approve: " + spender + " tokens: " + tokens.toString());
  approves.set(context.sender + ":" + spender, tokens);
  return true;
}

export function allowance(tokenOwner: string, spender: string): u64 {
  const key = tokenOwner + ":" + spender;
  if (!approves.contains(key)) {
    return 0;
  }
  return approves.getSome(key);
}

// utility function to prevent the token from being "launched" more than once
export function init(initialOwner: string): void {
  logging.log("initialOwner: " + initialOwner);
  assert(storage.get<string>("init") == null, "Already initialized token supply");
  balances.set(initialOwner, TOTAL_SUPPLY);
  storage.set<string>("init", "done");
}