0

I am trying to figure out what the most gas efficient way to return an error to a user when a transaction reverts is.

The easiest way to do this is with require.

function niceFail() public view  returns(string memory) {
    require(false, "Readable message");
    return test;}

I have read that what require does is compile into something like this:

error Fail(string);
function cheapFail() public view {
    if (false) {
        revert Fail("Readable Message");
    }
}

But they don't behave the same way. If I deploy these functions in remix, one will return a message, and the other will not. Obviously, require does more than I have been led to believe. What is the difference?

EDIT: That code was a bad example. Here, consider this contract:

contract ErrorTest{
error CustomError(string m);
function revertWithError() public {
    0x5B38Da6a701c568545dCfcB03FcB875f56beddC4.call{value: 0}("");
    revert CustomError("this is a custom error revert ");
}
function revertWithErrorViewFunction() public view {
    revert CustomError("this is a custom error revert on a view function");
}
function revertWithRequireView() public view {
    require(0==1, "this is a view function revert with require");
}
function revertWithRequire() public {
    0x5B38Da6a701c568545dCfcB03FcB875f56beddC4.call{value: 0}("");
    require(0 == 1, "this is a state modifying function with a revert with require");
}

}

And here, in remix:

enter image description here

Notice with require, we get the message. With revert Error("message"), we do not.

2
  • If you want to use revert with a message, do revert("message"). I don't know the exact mechanics, but I believe a raw revert saves a little gas over a require.
    – Bruce
    Mar 9, 2023 at 0:55
  • It does, but then you don't actually get the message back ... require is clearly doing something else.
    – Chev_603
    Mar 9, 2023 at 2:39

2 Answers 2

0

Both revert Fail("Readable Message"); and revert("message") are valid.

I think the main issue is the check condition, the revert is never called:

if (false) {
  revert Fail("Readable Message");
}

Should use if(true) instead. Or just don't use any condition.

2
  • I think maybe this is just a bad example then, I never actually ran this code, let me edit the question
    – Chev_603
    Mar 10, 2023 at 23:51
  • Please see updated question
    – Chev_603
    Mar 11, 2023 at 0:07
0

I think you want to do if(true) revert("message") to cause a revert properly. if(false) is skipping the revert lines

1
  • Please see updated question
    – Chev_603
    Mar 11, 2023 at 0:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.