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)) {
                        "AccessControl: 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:

: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