Search code examples
nearprotocol

Why doesn't my NEAR smart-contract function return an object (AssemblyScript)?


I have a function in my smart contract that looks like this

index.ts

class MsgCode {
  msg: string;
  code: i32;
}

@nearBindgen
export class Contract {
  getFoo(): MsgCode {
    return {code: 0, msg: 'foo'};
  }
  getBar(): string {
    return 'bar'
  }
}

When I call this function through the near-api-js library like this, I'm not receiving anything from the result

contract = await new Contract(account, CONTRACT_NAME, {
  viewMethods: ['getFoo', 'getBar'],
});

const getData = () => {
  return contract.getFoo().then(res => console.log(res)); // prints nothing. Expect to print {msg:'foo', code:0}
  return contract.getBar().then(res => console.log(res)); // prints bar
};

I'm expecting getFoo() to return {msg:'foo', code:0} when I call it on the client, but I receive nothing. What am I doing wrong?


Solution

  • The class type that we want to return from our function also needs to use the @nearBindgen annotation. Otherwise, it won't be serialized. https://docs.near.org/docs/develop/contracts/as/intro#models-define-new-types

    @nearBindgen // Added annotation
    class MsgCode {
      msg: string;
      code: i32;
    }