Created
March 21, 2023 20:32
-
-
Save KONFeature/d35e7278b37443ff286a0d3b73acad36 to your computer and use it in GitHub Desktop.
Sample revert gas usage test
This file contains 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: GNU GPLv3 | |
pragma solidity 0.8.17; | |
import {PRBTest} from "@prb/test/PRBTest.sol"; | |
contract RevertWithString { | |
function sampleRevert(uint256 amount) external pure { | |
require(amount > 10, "Not enough amount"); | |
} | |
} | |
contract RevertWithError { | |
error NotEnoughAmount(); | |
function sampleRevert(uint256 amount) external pure { | |
if (amount < 10) revert NotEnoughAmount(); | |
} | |
} | |
contract RevertWithErrorAssembly { | |
/// @dev 'bytes4(keccak256("NotEnoughAmount()"))' | |
uint256 private constant _NOT_ENOUGH_AMOUNT_SELECTOR = 0xe008b5f9; | |
function sampleRevert(uint256 amount) external pure { | |
assembly { | |
if lt(amount, 10) { | |
mstore(0x00, _NOT_ENOUGH_AMOUNT_SELECTOR) | |
revert(0x1c, 0x04) | |
} | |
} | |
} | |
} | |
/// Testing revert gas cost handling | |
contract RevertGasUsageTest is PRBTest { | |
RevertWithString testStringContract; | |
RevertWithError testErrorContract; | |
RevertWithErrorAssembly testErrorAssemblyContract; | |
function setUp() public { | |
testStringContract = new RevertWithString(); | |
testErrorContract = new RevertWithError(); | |
testErrorAssemblyContract = new RevertWithErrorAssembly(); | |
} | |
function testFail_RevertWithString() public view { | |
testStringContract.sampleRevert(1); | |
} | |
function testFail_RevertWithError() public view { | |
testErrorContract.sampleRevert(1); | |
} | |
function testFail_RevertWithErrorAssembly() public view { | |
testErrorAssemblyContract.sampleRevert(1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment