12

When using web3, calling a function that returns an enum type converts it to a uint. Initially I assumed that enums are converted incrementally: 0,1,2,3.... However what I received was a hexadecimal. How is it converted, and how do you parse it?

For example:

contract Foo {
   enum Letter {A, B, C}
   function say(uint index) returns (Letter) {
       if(index == 0) return Letter.A;
       if(index == 1) return Letter.B;
       if(index == 2) return Letter.C;
       throw;
   }
}

If you call Foo.say.call(1) you get a hex number (0x3ad324...). How would I check if it was Letter.A or 'Letter.B` that was returned?

latrasis
  • 313
  • 1
  • 2
  • 7

2 Answers2

17

Enum values are numbered in the order they're defined, starting at 0. So, Letter.A will be 0, Letter.B will be 1, and so forth. There's currently no means to cast an enum value to its name; that information isn't retained at runtime.

Nick Johnson
  • 8,144
  • 1
  • 28
  • 35
  • I thought this was the case as well! However what I got from web3 were hashes, not incremental numbers. – latrasis May 20 '16 at 15:11
  • 1
    @latrasis You haven't included any web3 code in your question, so I can only speculate. Perhaps you're sending a transaction instead of making a local call, in which case you're getting back a transaction hash? – Nick Johnson May 20 '16 at 15:24
  • I just realized I forgot to add constant, you were right, thank you! – latrasis May 21 '16 at 20:34
  • for those reading this in 2020's, note that the statement ""there's currently no means to cast an enum value to its name" hasn't been true since at least November 2016. See @BinGoGoBin's answer below. – GGizmos Dec 22 '21 at 03:45
8

About Enums, being described below:

Enums are one way to create a user-defined type in Solidity. They are explicitly convertible to and from all integer types but implicit conversion is not allowed. The explicit conversion from integer checks at runtime that the value lies inside the range of the enum and causes a Panic error otherwise. Enums require at least one member

Enum values are numbered in the order they're defined, starting at 0. If you want to get the value of an enum, use uint(enum_variable).

pragma solidity ^0.4.4;

contract SimpleEnum {

enum VirtualTrade {DEFAULT,ONE,TWO} VirtualTrade vt;

function SimpleEnum(){
    vt = VirtualTrade.DEFAULT;
}

function setValues(uint _value) { require(uint(VirtualTrade.TWO) >= _value); vt = VirtualTrade(_value); }

function getValue() constant returns (uint){ return uint(vt); }

}

Hope it helps~

Pang
  • 299
  • 1
  • 3
  • 7
BinGoBinBin
  • 2,161
  • 13
  • 17