Skip to content

Instantly share code, notes, and snippets.

@PaulRBerg
Last active March 13, 2023 20:24
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PaulRBerg/23bb1e7b04a43aa5376974d9f7a6aa1c to your computer and use it in GitHub Desktop.
Save PaulRBerg/23bb1e7b04a43aa5376974d9f7a6aa1c to your computer and use it in GitHub Desktop.
Test that fuzzes ordered arrays in Solidity
// 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