foundry icon indicating copy to clipboard operation
foundry copied to clipboard

Foundry incorrectly asseses gas costs when using proxy

Open novaknole opened this issue 7 months ago • 3 comments

Component

Forge

Have you ensured that all of these are up to date?

  • [X] Foundry
  • [X] Foundryup

What version of Foundry are you on?

forge 0.2.0 (f479e94 2024-06-01T00:19:17.421178000Z)

What command(s) is the bug in?

forge test

Operating System

macOS (Apple Silicon)

Describe the bug

Assume the following contract:

contract Nice is UUPSUpgradeable {
    function test(
        IDAO.Action[] calldata _actions,
        uint256 _allowFailureMap,
        bytes calldata _metadata
    ) public {
        console.log(gasleft());
    }
}

There're 2 scenarios and the problem/bug happens only when Nice is deployed with proxy.

Nice nice = new Nice();
Nice proxy = Nice(createProxyAndCall(address(nice), bytes("")));

Then, inside the tests, I do:

// This prints 373000
(bool success, ) = address(proxy).call{gas: 380000}(
    abi.encodeWithSelector(Nice.test.selector, new IDAO.Action[](0), 0, "dummy")
);
// This prints 412375
(bool success, ) = address(proxy).call{gas: 420000}(
    abi.encodeWithSelector(Nice.test.selector, new IDAO.Action[](0), 0, "dummy")
);

What this means is before getting to gasleft():

  • it spent 380000 - 373000 = 7000 in first case
  • in 2nd case, it spent 420000 - 412375=7625.

Why did it spend different amounts ? The only thing changed was gaslimit in the .call. Also, this difference only happens when the Nice is deployed through proxy. If it's deployed with new directly, we don't got the problem.

The reason I ended up with this issue is I want to achieve the following:

  1. figure out what the gas costs for the function is, so that I can call it with estimatedGas - 1000. So I need the estimatedGas. I calculate it with console.log(vm.lastCallGas().gasTotalUsed);, but when I call the function with the gasLimit of the same amount of gasTotalUsed, the call fails and asks me to send more than +1500 gas.

novaknole avatar Jun 28 '24 11:06 novaknole