Solidity Foundry – Resolving Foundry Tests Failure with EvmError: Revert Counterexample When Calling Transfer

foundrysolidity

I'm getting an error when trying to test my treasury:

[FAIL. Reason: EvmError: Revert Counterexample: calldata=0x959f692800000000000000000000000000000000000000000000000000000000000000d300000000000000000000000000000000000000000000000000000000000016fc, args=[211, 5884]]

It's failing on this function on the treasury:

function withdrawNative(uint256 amount) external {
    userAccounts[msg.sender].balances[NATIVE_ADDRESS] -= amount;
    payable(msg.sender).transfer(amount);
}

My foundry test looks like so:

function testPartialNativeWithdraw(uint256 amount1, uint256 amount2) public {
    vm.assume(amount1 <= 10 ether);
    vm.assume(amount1 > 0);
    vm.assume(amount2 <= 10 ether);
    vm.assume(amount2 > 0);

    address payable user1 = payable(address(1));
    vm.deal(user1, 20 ether);
    
    _deposit(user1, amount1 + amount2);

    uint256 userBalance = address(user1).balance;

    vm.startPrank(user1);
    treasury.withdrawNative(amount1);
    
    assertEq(address(treasury).balance, amount2);
    assertEq(treasury.getNativeBalance(user1), amount2);
    assertEq(user1.balance, userBalance + amount1);
    
    treasury.withdrawNative(amount2);
    assertEq(treasury.getNativeBalance(user1), 0);
    assertEq(address(treasury).balance, 0);
    vm.stopPrank();

}

I removed all the code to identify the problem line which is:

payable(msg.sender).transfer(amount);

My guess is this occurs because I faked user accounts? and theres not code deployed at that address. Perhaps I need to impersonate an user differently

Best Answer

Address 0x01 contains a precompiled contract, and the reason you can't send ether to it is because it doesn't have a receive function.

https://book.getfoundry.sh/misc/precompile-registry

When you changed it to vm.addr(1), you are no longer using address 0x01, but an address derived from private key "1".

So, it is always better not to use low number addresses but to generate them with the foundry utilities like makeAddr() and vm.addr(), like you did.