Created
February 5, 2025 16:16
-
-
Save 0xPhaze/ea2d61ef3b050243c908ce4bd1966c3b to your computer and use it in GitHub Desktop.
Solidity: Binary search minimum upper gas limit
This file contains hidden or 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.25; | |
import {Test, console2 as console} from "forge-std/Test.sol"; | |
contract ABCTest is Test { | |
event VaultAuxiliary1(address, string, bytes); | |
function test_xxx() public { | |
binarySearchMinUpperGasLimit(this.process, 100_000_000); | |
} | |
function binarySearchMinUpperGasLimit(function() external fun, uint256 upper) internal { | |
uint256 gas; | |
uint256 lower; | |
while (true) { | |
gas = (upper - lower) / 2 + lower; | |
if (gas == lower) { | |
break; | |
} | |
try fun{gas: gas}() { | |
upper = gas; | |
} catch { | |
lower = gas; | |
} | |
} | |
console.log("gas", upper); | |
} | |
function process() public { | |
consumeGas(100_000); | |
// try catch an inner call | |
try this.innerCall("eventKey", "eventData") {} catch {} | |
// outer call continues with 1/64 of remaining gas | |
uint256 tmp; | |
assembly { | |
tmp := sload(0) | |
} | |
tmp += 1; // just so the compiler doesn't optimize `tmp` load | |
} | |
function innerCall(string calldata eventKey, bytes calldata eventData) external { | |
emit VaultAuxiliary1(msg.sender, eventKey, eventData); | |
} | |
function consumeGas(uint256 val) internal pure { | |
assembly { | |
mstore(val, 0) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment