Yul: The Gas Difference Between Regular Revert, Revert in Assembly and Revert in Assembly Using Bytes32
It is imperative to return clear error messages in all programming as it helps to segmentise where your code went wrong. In solidity, most error cases will cause a revert in the execution but there are scenarios where it will not. Especially if you are coding in Yul, a lot of error handling has to be done manually.?
There are many logical methods to reduce the need for error handling if you structure your codes well. This post I am going to compare the gas difference between 3 kinds of revert in Solidity.
1. Regular Revert
function RegularError() external pure {
// This is the simplest way to revert and therefore no explanation
// is needed.
revert("0x1");
}
Contract (without optimisation) gas cost: 114588
2. Revert in Assembly
function AssemblyError() external pure {
assembly {
mstore(0x80, shl(0xe5, 0x461bcd))
// Above is the method name for Error(String)
// shl is to further save the gas by not storing the entire keccak256
// method name. I may explain this in another post.
mstore(0x84, 0x20)
mstore(0xa4, 0x3)
mstore(0xc4, "0x1")
// The above is the standard way to put string into the memory and
// call it. 0xa4 is the length of the string, expand or contract it
// according to your next memory storage.
revert(0x80, 0x64)
// This is the revert method in Yul. First parameter is the position
// of the return message, the second parameter is the total size
// of the return message.
}
}
Contract (without optimisation) gas cost: 103030
领英推荐
3. Revert in Assembly Using Bytes32
error Err(bytes32);
// This need to be defined in your contract as a custom error
function BytesAssemblyError() external pure {
assembly {
mstore(0x0, shl(0xe0, 0x5b4fb734))
// The 4 bytes keccak256 for the above custom error
mstore(0x4, 0x1)
// Can directly return hexadecimal
revert(0x0, 0x24)
// The size of the revert message is significantly shorter.
}
}
Contract (without optimisation) gas cost: 93474
As clear as it is, the 3rd method is cheaper and cleaner. You may prefer error message in string or any other data type. How you going to identify the error codes is that you will need a table to keep track of.
For example:
0x1 = "Some error"
0x2 = "Some other error"
0x3 = "So on and so forth"
It is more prudent to store your error messages on somewhere you can manage rather than wasting gas fee in the opcode.