Skip to main content

Revert String Size

Description

When a Solidity contract executes a revert operation, it can optionally include a string that describes the reason for the revert. However, including long revert strings can be expensive in terms of gas usage. By shortening the revert strings to fit within 32 bytes, we can reduce the amount of gas used during deployment and runtime when the revert condition is met.

Revert strings that are longer than 32 bytes require at least one additional mstore, along with additional overhead to calculate memory offset, which can significantly increase gas usage. Therefore, it is recommended to keep revert strings as short as possible.

Example Code

Consider the following contract that uses a long revert string:

contract RevertExample {
function doSomething(uint256 x) external {
require(x > 10, "The input value must be greater than 10 for this function to work");
// some code here
}
}

In the above example, the revert string is longer than 32 bytes, which can lead to increased gas usage. To optimize this, we can shorten the revert string to fit within 32 bytes:

contract RevertExample {
function doSomething(uint256 x) external {
require(x > 10, "Invalid input");
// some code here
}
}

Recommendation

To optimize gas usage in your Solidity contract, it is recommended to keep revert strings as short as possible and to ensure that they fit within 32 bytes. You can use abbreviations or simplified error messages to keep the string length short. By doing so, you can reduce the amount of gas used during deployment and runtime when the revert condition is met.