I have enums that I use in many contracts of one project. Sometimes, they need to be mapped to a uint256. Their uint256 values do not relate to their positions in the enum list, so I can't just cast the enums to uint256.

Currently, I have a library with functions converting between enums and uint256 values:

function enumToUint(Foo _foo) returns (uint256) {
    if(_foo == Foo.apple) {
            return 45245;
    if(_foo == Foo.banana) {
            return 557857585;
    if(_foo == Foo.clementine) {
            return 1352;
    // ...

function uintToEnum(uint256 _bar) returns (Foo) {
    if(_bar == 45245) {
        return Foo.apple;
    // ...

This solution not only is super ugly but I also think that it is burning gas unnecessarily because to get to Foo.zucchini, the EVM needs to walk through the entire Foo alphabet (there are a lot of enum values).

The elephant in the room is to use two Solidity mappings in my contracts. However, there are several problems with this:

  • I'd need to either duplicate the mapping everywhere, leading to an updating nightmare, or use inheritance simply for a contract knowing this mapping (seems really ugly).
  • This mapping would be part of the bytecode of all contracts of the project. Some of these contracts should be really small because they need to be deployed many times. Avoiding duplicated definitions is why I think that the mapping should be defined in a library.
  • I need to use the mapping in other libraries. Right now, this is not a problem because I can use library functions in other libraries. But if I misuse a contract as a library for my definition, I'd have to get that contract's address into the other libraries. The only way to do this I see is passing the contract's address to every library function that needs the mapping.

How can this problem be solved (somewhat) elegantly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.