0

I am testing the Foundry Fuzzing feature. Therefore I created this simple contract:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract Vault {
bool public s_locked;
uint private s_password;

constructor(uint password) {
    s_locked = true;
    s_password = password;
}

function unlock(uint password) external {
    if (s_password == password) {
        s_locked = false;
    }
}
}

And here its test:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.18;

import "forge-std/Test.sol";
import "forge-std/console.sol";
import "../src/Vault.sol";

contract VaultFuzzTest is Test {

Vault public vault;

function setUp() public {
    vault = new Vault(5);
}

function testFuzz_password(uint x) public {
  vault.unlock(x);
  assertEq(vault.s_locked(), true);
}
}

When I run it, the test is passing successfully, however it shouldn't when the password is equal to 5. See output:

Test result: ok. 1 passed; 0 failed; 0 skipped; finished in 10.94ms
  Ran 1 test suites: 1 tests passed, 0 failed, 0 skipped (1 total tests)

That is why I was wondering, is Foundry just trying random 256 values (I assume all 256 values are big numbers) and if it doesn't find 5 among them, it just returns success. If so, is there a way I can fuzz my contract with more than 256 values, so eventually I get my test fail?

What else I have tried: adding vm.assume(x<10);

function testFuzz_password(uint x) public {
  vm.assume(x<10);
  vault.unlock(x);
  assertEq(vault.s_locked(), true);
}

Now when I run my test it fails:

Failing tests:
Encountered 1 failing test in test/Vault.t.sol:VaultFuzzTest
[FAIL. Reason: Assertion failed. Counterexamplecalldata=0x0ce2d6010000000000000000000000000000000000000000000000000000000000000005, args=[5]] testFuzz_password(uint256) (runs: 6, μ: 13283, ~: 13283)

  Encountered a total of 1 failing tests, 0 tests succeeded

When I put a constraint where the password is assumed to be <10, then the fuzzing works as expected and throws an error.

Therefore I wanted to ask someone with more experience with Foundry to explain me how it works and should I increase the runs in order to achieve the same behaviour but without using vm.assume(x<10);

1 Answer 1

2

Ok, I found how to increase fuzz runs: Inside the foundry.toml Add this

[fuzz]
runs = 1000000

But I don't know whether that is correct solution.

1
  • This is. The fuzzer tries semi-random variables as input, sort of like a brute-force attempting to crack the code. So the more runs, the better. Jul 29, 2023 at 19:50

Your Answer

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

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