[Ethereum] Invalid implicit conversion from uint256 to bytes memory requested

contract-developmentremixsolidity

I am trying to create a simple random function but it gives me an error. I can't figure out what I do wrong. Solidity 0.5.0;

   function random() private view returns(uint){
        uint source = block.difficulty + now;
        return uint(keccak256(source));
    }

TypeError: Invalid type for argument in function call. Invalid
implicit conversion from uint256 to bytes memory requested. This
function requires a single bytes argument. Use abi.encodePacked(…)
to obtain the pre-0.5.0 behaviour or abi.encode(…) to use ABI
encoding.
return uint(keccak256(source));

Best Answer

You are getting this error because you are trying to take the keccack256 hash of a uint, which you cannot do, according to the docs. What you must do instead is convert the uint to a bytes.

The code you want is as follows:

function random() private returns(uint){
    uint source = block.difficulty + now;
    bytes memory source_b = toBytes(source);
    return uint(keccak256(source_b));
}

function toBytes(uint256 x) public returns (bytes memory b) {
    b = new bytes(32);
    assembly { mstore(add(b, 32), x) }
}
Related Topic