JairusSW / as-json

The only JSON library you'll need for AssemblyScript. SIMD enabled
MIT License
79 stars 15 forks source link

unreachable code error while using JSON #82

Closed spino17 closed 4 months ago

spino17 commented 4 months ago

I am trying out below code:


import { JSON } from "json-as/assembly";

@json
class TokenMetaData {
  id: u64;
  name: string;
  uri: string;

  constructor(id: u64, name: string, uri: string) {
    this.id = id;
    this.name = name;
    this.uri = uri;
  }
}

@json
class NonFungibleToken {
  owner: string;
  counter: u64;
  tokens: Map<u64, TokenMetaData>;
  owners: Map<u64, string>;
  balances: Map<string, u64[]>;

  constructor() {
    this.owner = "";
    this.counter = 0;
    this.tokens = new Map();
    this.owners = new Map();
    this.balances = new Map();
  }
}

export function mint(): void {
  let state = JSON.parse<NonFungibleToken>(
    '"{"owner":"","counter":0,"tokens":{},"owners":{},"balances":{}}"'
  );
  // let state = new NonFungibleToken();

  if (!state.balances.has("bhavya")) {
    state.balances.set("bhavya", []);
  }
}

Which is giving me

Error: RuntimeError: unreachable

but when I change it to


import { JSON } from "json-as/assembly";

@json
class TokenMetaData {
  id: u64;
  name: string;
  uri: string;

  constructor(id: u64, name: string, uri: string) {
    this.id = id;
    this.name = name;
    this.uri = uri;
  }
}

@json
class NonFungibleToken {
  owner: string;
  counter: u64;
  tokens: Map<u64, TokenMetaData>;
  owners: Map<u64, string>;
  balances: Map<string, u64[]>;

  constructor() {
    this.owner = "";
    this.counter = 0;
    this.tokens = new Map();
    this.owners = new Map();
    this.balances = new Map();
  }
}

export function mint(): void {
  //let state = JSON.parse<NonFungibleToken>(
  //  '"{"owner":"","counter":0,"tokens":{},"owners":{},"balances":{}}"'
  //);
  let state = new NonFungibleToken();

  if (!state.balances.has("yamini")) {
    state.balances.set("yamini", []);
  }
}

it is working fine.

JairusSW commented 4 months ago

Thanks for the better example I'll fix this tonight

spino17 commented 4 months ago

Thanks @JairusSW for the response. Let me know if you need anything else from my end.

JairusSW commented 4 months ago

Just a note, I'd reccomend using default values with json-as. Its designed to work well with them. Your also using new Map() instead, you need to provide strong type annotations so use new Map<K,V>() instead

JairusSW commented 4 months ago

Can you try now? Fix live on json-as@0.9.9

spino17 commented 4 months ago

yeah, now it is working perfectly! thanks @JairusSW for fixing it