3

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

3 Answers 3

6

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) }
}
0
5

you can make use of abi.encodePacked function

 function random() private view returns(uint){
     uint source = block.difficulty + now;
     return uint(keccak256(abi.encodePacked(source)));
   }
1
  • 2
    This answer should've been marked!
    – Ender
    Nov 26, 2019 at 3:45
2

Both of the current answers are excessive

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

Also you should not be using block.difficulty or block.timestamp as a source of randomness as they are exploitable by miners. Consider using Chainlink's VRF instead

1
  • 1
    The question request a solution for solc 0.5, in that version your code doesn't compile.
    – Ismael
    Aug 31, 2021 at 6:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.