toHexString failing to convert bytes memory to bytes20/bytes32

Hey OZ community,

My code will not compile with the errors below. I also tried using string(abi.encodePacked(account)) but that threw encoding issues.

TypeError: Explicit type conversion not allowed from "bytes memory" to "bytes20".
   --> contracts/layerzero-wrapper/acl/OmniteAccessControl.sol:113:56:
    |
113 |             return Strings.toHexString(uint256(uint160(bytes20(account))));
    |                                                        ^^^^^^^^^^^^^^^^


TypeError: Explicit type conversion not allowed from "bytes memory" to "bytes32".
   --> contracts/layerzero-wrapper/acl/OmniteAccessControl.sol:115:48:
    |
115 |             return Strings.toHexString(uint256(bytes32(account)));

:1234: Code to reproduce

    function _checkRole(bytes32 role, bytes memory account) internal view {
        if (!hasRole(role, account)) {
            revert(
                string(
                    abi.encodePacked(
                        "AccessControl: account ",
                        toHexString(account),
                        " is missing role ",
                        Strings.toHexString(uint256(role), 32)
                    )
                )
            );
        }
    }

    function toHexString(bytes memory account) internal pure returns(string memory) {
        if (account.length == 20) { // all eth based addresses
            return Strings.toHexString(uint256(uint160(bytes20(account))));
        } else if (account.length <= 32) { // most of other addresses if not all of them
            return Strings.toHexString(uint256(bytes32(account)));
        }
        return string(account); // not supported, just return raw bytes (shouldn't happen)
    }

Failed TX hash here: https://rinkeby.etherscan.io/tx/0x5d16af66c326d8d18afa84b429eaa09fb98d48f4b4a4fce519282bd5e5e29b4d

:computer: Environment

npx hardhat compile

Solidity doesn't allow converting a bytes memory value to a bytes20 or bytes32 value. You're probably going to have to use assembly for this.

You can also open an issue to request a function toHexString that works with bytes.

1 Like