From d7025e261a98aeedfed53d7014bab6acbeb7deb6 Mon Sep 17 00:00:00 2001 From: Piotr Dyraga Date: Fri, 21 Aug 2020 15:11:23 +0200 Subject: [PATCH 1/2] Refactored the loop in RNG.bitsRequired The loop should work exactly the same as before except that we avoid the comparison of bits >= 0 which is always true because bits is an uint. --- contracts/RNG.sol | 28 ++++++++++++++-------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/contracts/RNG.sol b/contracts/RNG.sol index 611216d0..7ccd724f 100644 --- a/contracts/RNG.sol +++ b/contracts/RNG.sol @@ -135,22 +135,22 @@ library RNG { /// @return uint The smallest number of bits /// that can contain the number `range-1`. function bitsRequired(uint256 range) internal pure returns (uint256) { - uint256 bits; // Start at 19 to be faster for large ranges - for (bits = (POSITION_BITS - 1); bits >= 0; bits--) { - // Left shift by `bits`, - // so we have a 1 in the (bits + 1)th least significant bit - // and 0 in other bits. - // If this number is equal or greater than `range`, - // the range [0, range-1] fits in `bits` bits. - // - // Because we loop from high bits to low bits, - // we find the highest number of bits that doesn't fit the range, - // and return that number + 1. - if (1 << bits < range) { - break; - } + uint256 bits = POSITION_BITS - 1; + + // Left shift by `bits`, + // so we have a 1 in the (bits + 1)th least significant bit + // and 0 in other bits. + // If this number is equal or greater than `range`, + // the range [0, range-1] fits in `bits` bits. + // + // Because we loop from high bits to low bits, + // we find the highest number of bits that doesn't fit the range, + // and return that number + 1. + while (1 << bits >= range) { + bits--; } + return bits + 1; } From 5588f317e55a113b75ede5b8feab70d00be0af0e Mon Sep 17 00:00:00 2001 From: Piotr Dyraga Date: Fri, 21 Aug 2020 15:13:20 +0200 Subject: [PATCH 2/2] Initialize the index in RNG.getIndex function Initializing the index does not change how the function works and, in fact, index when not initialized is initialized to the default - 0 value. We can however make this code a little cleaner and Slither happier. --- contracts/RNG.sol | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/contracts/RNG.sol b/contracts/RNG.sol index 7ccd724f..e4272cd7 100644 --- a/contracts/RNG.sol +++ b/contracts/RNG.sol @@ -197,7 +197,7 @@ library RNG { { uint256 bits = bitsRequired(range); bool found = false; - uint256 index; + uint256 index = 0; bytes32 newState = state; while (!found) { index = truncate(bits, uint256(newState));