Last active
March 13, 2023 20:24
-
-
Save PaulRBerg/23bb1e7b04a43aa5376974d9f7a6aa1c to your computer and use it in GitHub Desktop.
Test that fuzzes ordered arrays in Solidity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: UNLICENSED | |
pragma solidity >=0.8.18; | |
import { Test } from "forge-std/Test.sol"; | |
import { arange } from "solidity-generators/Generators.sol"; | |
contract MyTest is Test { | |
function testFuzz_OrderedArr(uint256[] memory arr) internal view { | |
vm.assume(arr.length != 0); | |
// Precompute the first element so that we don't bump into an underflow below. | |
arr[0] = PREDEFINED_VALUE; | |
// Return here if there's only one segment to not run into division by zero. | |
uint256 len = arr.length; | |
if (len == 1) { | |
return; | |
} | |
// Generate `len` elements linearly spaced between `arr[0]` and max uint256. | |
uint256 max = type(uint256).max; | |
uint256 step = (max - arr[0]) / (len - 1); | |
arr = arange(arr[0], max, step); | |
// Fuzz the elements in a way that preserves their order in the array, using `bound`. | |
uint40 halfStep = step / 2; | |
for (uint256 i = 1; i < len; ++i) { | |
arr[i] = bound(arr[i], arr[i] - halfStep, arr[i] + halfStep); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment