Invalid implicit conversion from uint256 to bytes memory requested

by Filip Laurentiu   Last Updated March 14, 2019 19:28 PM

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));



Answers 1


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) }
}
shane
shane
March 14, 2019 19:20 PM

Related Questions


Contract working on Remix but not with truffle

Updated December 04, 2017 03:28 AM

I need help with a crowdfunding contract

Updated July 27, 2017 13:28 PM

How to interact with Smart Contracts (for test)

Updated August 10, 2017 10:28 AM


Testing for Reentrancy attacks in remix

Updated October 21, 2017 13:28 PM