0

I am trying to test an enum value from a test. This is simplified version of the contract:

pragma solidity >=0.5.0 <0.7.0;

contract Foo {

  enum State {
    StateA,
    StateB
  }

  State internal state;

  function getState()
    public view
    returns (State)
  {
    return state;
  }
}

Now running the test just like this:

contract("Foo", async accounts => {
  it("requires a project to create", async () => {
    let instance = await Foo.new()
    console.log(await instance.getState())
  })
})

I am getting output like this

BN { negative: 0, words: [ 1, <1 empty item> ], length: 1, red: null }

I've read that enums are still not supported from the ABI but shouldn't this then just return the index? What is BN? negative? red?

1 Answer 1

1

Enums are returned as uint256.

BN means big number, it is a javascript object that wraps an arbitrary precision integer, it is used to wrap uint256.

When it prints some values like words, red, negative, etc. it is javascript that is trying to show some internal data that is not useful unless you develop BN package.

You get more info if you convert to string before printing to console

console.log((await instance.getState()).toString())
4
  • 1
    Better yet IMO, always prefer toFixed over toString. It is insignificant for the specific case at hand, but for BigNumber instances representing large values, toString converts to a scientific notation string, which can be an issue later on in the execution of your application/test (for example, when comparing with the expected result, or when converting back to a BigNumber instance, which could be different from the original result due to the precision-loss embedded in scientific notation). Commented May 21, 2019 at 8:56
  • Took a bit but I figured out the BigNumber thing, too. Using Number(await instance.getState()) seems to do the trick. Thanks for the help.
    – tcurdt
    Commented May 21, 2019 at 9:36
  • 1
    @tcurdt: Watch out from this type of conversion in general. Number.MAX_SAFE_INTEGER is 2 ** 53 - 1, so converting any BigNumber which represents a value higher than that may result in a different value. Commented May 21, 2019 at 10:21
  • @goodvibration It's a bit awkward having to drop down to this level on the tests anyway - but I guess that's the current of state of things for enums. It would probably better to compare two BigNumbers but for the tests it's not that critical. But thanks for the pointer!
    – tcurdt
    Commented May 21, 2019 at 10:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.