You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// SPDX-License-Identifier: MITpragma solidity^0.8.23;
import"@openzeppelin/contracts/utils/Strings.sol";
import"forge-std/Test.sol";
// run from base project directory with:// forge test --match-contract ErrorTest -vvvcontractErrorRaiser {
error SecondError();
error ThirdError();
function generateError(uint8input) externalpure {
if(input ==0) revert("First error");
revertSecondError();
}
}
contractErrorTestisTest {
using Stringsforstring;
ErrorRaiser errorRaiser;
function setUp() public {
errorRaiser =newErrorRaiser();
targetContract(address(this));
bytes4[] memory selectors =newbytes4[](1);
selectors[0] =this.fake_handler.selector;
targetSelector(FuzzSelector({addr: address(this), selectors: selectors}));
}
function invariant_always_true() publicpure {
assert(true);
}
function fake_handler(uint8input) public {
try errorRaiser.generateError(input) {}
// handle `require` text-based errorscatchError(stringmemoryerr) {
string[] memory allowedErrors =newstring[](1);
allowedErrors[0] ="First error";
_assertTextErrorsAllowed(err, allowedErrors);
}
// handle custom errorscatch(bytesmemoryerr) {
bytes4[] memory allowedErrors =newbytes4[](1);
allowedErrors[0] = ErrorRaiser.SecondError.selector;
_assertCustomErrorsAllowed(err, allowedErrors);
}
}
// used to filter for allowed text errors during functions// if a function fails with an error that is not allowed,// this can indicate a potential DoS attack vectorevent UnexpectedTextError(string);
function _assertTextErrorsAllowed(stringmemoryerr, string[] memoryallowedErrors) private {
bool allowed;
uint256 allowedErrorsLength = allowedErrors.length;
for (uint256 i; i < allowedErrorsLength;) {
if (err.equal(allowedErrors[i])) {
allowed =true;
break;
}
unchecked {++i;}
}
if(!allowed) {
emitUnexpectedTextError(err);
assert(false);
}
}
// used to filter for allowed custom errors during functions// if a function fails with an error that is not allowed,// this can indicate a potential DoS attack vectorevent UnexpectedCustomError(bytes);
function _assertCustomErrorsAllowed(bytesmemoryerr, bytes4[] memoryallowedErrors) private {
bool allowed;
bytes4 errorSelector =bytes4(err);
uint256 allowedErrorsLength = allowedErrors.length;
for (uint256 i; i < allowedErrorsLength;) {
if (errorSelector == allowedErrors[i]) {
allowed =true;
break;
}
unchecked {++i;}
}
if(!allowed) {
emitUnexpectedCustomError(err);
assert(false);
}
}
}
The text was updated successfully, but these errors were encountered:
Code example for foundry (thanks to DevDacian)
The text was updated successfully, but these errors were encountered: