9

I'm working on a proxy contract that will perform calls as follows:

bool success;
bytes memory returndata;
(success, returndata) = _to.call.value(_value)(_data);
require(success);

this works great, except that, if the call reverts with an error message, this function will simply reverts, hiding the reason string.

How can I retrieve the reason string (I assume in the returndata) and use if to revert properly

3 Answers 3

3

You can do it very concisely:

(bool success, bytes memory result) = addr.delegatecall(data);
if (success == false) {
    assembly {
      revert(add(result,32),mload(result))
    }
}
12

The following code performs a delegate call, and if the delegate call reverts, the transaction is reverted with the reason given by the delegate call.

(bool success, bytes memory result) = address(_impl).delegatecall(signature);
if (success == false) {
    assembly {
        let ptr := mload(0x40)
        let size := returndatasize()
        returndatacopy(ptr, 0, size)
        revert(ptr, size)
    }
}
return result;
3
  • 1
    with solidity 0.5.5
    – Thykof
    Aug 27, 2020 at 6:49
  • 3
    Thanks, work with solc 0.7 ! *returndatasize()
    – Xavier59
    Nov 14, 2020 at 22:16
  • This should be the accepted answer. May 18, 2022 at 3:12
11

It is simpler than you think:

require(success, string (returndata));

See documentation for details. You may also forward raw bytes, but you will need to use assembly.

3
  • I tryed require(success, returndata); and started looking into assembly when it failled to compile ... thanks for proving how stupid I am :P
    – Amxx
    Apr 1, 2019 at 14:52
  • 2
    I get Error: Returned error: VM Exception while processing transaction: revert�y� )ERC721: owner query for nonexistent token -- Reason given:y )ERC721: owner query for nonexistent token. There may be a encoding error, maybe removing the 32 first bytes (the length of returndata)? (with solidity 0.5.5)
    – Thykof
    Aug 21, 2020 at 10:39
  • Incorrect answer, string (returndata) returns the empty string if success is false. See the correct answer by @Thykof. May 18, 2022 at 3:13

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.