[Ethereum] convert enum members to string

contract-debuggingcontract-designcontract-developmentsolidity

I am trying to play around enums in solidity, during which I came across following questions–

  1. Is it possible convert enum members to string??

I am trying to get enum members and convert them to string, It always returns integer ie. position of member,
following is the code snippet

contract c{
    enum Numbers {zero,one,two,three,four}

    Numbers number;

    function getFirstNumber(){
         number=Numbers.zero; //works fine
         uint num=uint(Numbers.zero);//works fine
         string stringNum=string(Numbers.zero);// throws error
    }
}

is it possible to convert them to strings, by using any other approach.

  1. Is it possible to get enum members by using index??

Can we get enum member by using the index / position of the member in enum
following is the code snippet I am trying.

contract c{
    enum Numbers {zero,one,two,three,four}

    Numbers number;
    function getByIndex(int position){
         number=Numbers.zero; //works fine

         //tried somthings like
         number=Numbers[0];//throws error
         number=Numbers.get(position);// throws error
    }
}

Is this possible to get them using position

  1. Is it possible to check existence of members using string??

I need to check that the provided string exist in the enum, following is the code snippet I am trying

contract c{
    enum Numbers {zero,one,two,three,four}

    Numbers number;
    function checkIfExist(string member) returns(bool exists){

         //tried somthings like

         for(uint i=0;i<Number.length;i++){
            if(string(Number[i]==member){ //throws error
                return true;
            }
            else{
                exists=false;
            }
         }

         //also tried
         uint flag=Number.member;//throws error
         if(flag>0){
              return true;
         }
    }
}

is it possible to do this by any approach

Best Answer

The compiled code doesn't know anything about the names of the enum elements. You can prove this by arbitrarily changing their names and compiling with solc --bin, and you'll see that they make no difference to the compiled code. So no, you can't get them by calling the contract.

You could of course add a separate mapping to the contract hard-coding that if asked for "two" it should return Numbers.two and vice versa, but you'd have to pay gas to carry this extra data when you deployed the contract.

The simplest thing is usually just to maintain a copy of the enum mapping wherever you need to call it, eg if you access the contract from a JavaScript DApp, keep a copy of the enum mappings in your JavaScript.

Related Topic