1

having this issue of using enum as interface in other contract: will appreciate your help...

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.9;

interface interEnum {
    enum SIDE {
        buy,
        sell
    }
}

contract B is interEnum {

    function bEnum(SIDE side) external {
        // do something with here
    }
}

contract A {
    B b;
    enum NUM {
        buy,
        sell
    }
    function bEnum(NUM num) external {
        // i cant pass in an enum from here.
        // invalid explicit conversion from uint256 to Enum when i tried it this way
        // b.bEnum(uint256(num);

        // b
        // invalid explicit conversion from enum to enum....
        // b.bEnum(num);

    }
}

2 Answers 2

2
+50

I fiddled and cleaned up a bit so the Type is declared in one place only (DRY).

You can convert an enum to a number but you have to go through intermediary conversions to get there. Since there are only two members in the enum, it fits in a uint8 so that conversion is possible. You have to go there first before you can convert to a uint256.

In most cases, you will hardly ever convert between enums and numbers. Numbers generally imply some sort of gradient while enums make things more readable when you want hard-coded categories or states.

In any case, this compiles and works as expected.

// SPDX-License-Identifier: GPL-3.0

pragma solidity 0.8.9;

library Types {

    enum Side {
        buy,
        sell
    }
}

contract B {

    event TookSide(string side);

    function bEnum(Types.Side side) external {
        // Do something with it here
        if(side == Types.Side.buy) emit TookSide("buy");
        if(side == Types.Side.sell) emit TookSide("sell");
    }
}

contract A {

    B b;

    constructor(address _b) {
        b = B(_b);
    }

    function takeSide(Types.Side side) external returns(uint thing) {
        b.bEnum(side);
        thing = uint256(uint8(side));
    }
}
[
    {
        "from": "0xd9145CCE52D386f254917e481eB44e9943F39138",
        "topic": "0x39053e506755f3eaf8479a64ca6444658a68a5886c5992c63649ab2d3cd476d8",
        "event": "TookSide",
        "args": {
            "0": "sell",
            "side": "sell"
        }
    }
]

Hope it helps.

1

Solidity does not allow implicit conversion from A.NUM to interEnum.SIDE, nor will it allow an explicit conversion like b.bEnum(SIDE(num)). Since your b.bEnum() takes SIDE as a param, you should pass the param of type interEnum.SIDE only.

contract A is interEnum {
    B b;

    function bEnum(SIDE num) external {
       b.bEnum(num);
    }
}

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.