Solidity custom error a way to save gas? pt.2
Okay! Here we are again talking about how to save gas using solidity custom error. In my last post on custom errror, we saw how to use the custom error in our code and how easy it is.
Today, it just a short comparison to see how gas efficient custom error is. We will be comparing it with require statement.
The above shows that 23591 gas was used when we implemented custom error.
Now, let us see the gas that will be used when we use the require statement.
Here, we can see that 23642 gas was used in this transaction. It may not look like a lot of difference but it will surely be useful when you have a lot of code and you are looking for a lot of means to save gas.
Now, require statement is quite popular… But I think I’m inlove with custom errors.
Alright, you might want to know what require statement is…
The require statements specify the conditions that must be met before the function may be executed, i.e. the requirements that must be met before the code can be executed. It takes a single argument and evaluates it into a boolean value; also it offers a custom string message choice. If false, an exception can be thrown and the operation is stopped. The caller receives the unused gas, and also the state is reset to its initial state. The following are some examples of when a specific sort of exception is thrown:
- When using an index that is too large or negative to access an array.
- When .transfer() method fails.
- When a value is modulo or divided by zero.
- When the public getter method is used to send ethers to the contract.
- When converting a large or negative value to an enum.
- When an external function is the target of a codeless contract.
- When a function’s zero-initialized variable is called.
- When a contract is made using the new keyword and the process fails to complete correctly.
- When an assert is used in conjunction with a condition that returns false.
- When a message-initiated function fails to complete successfully.
- When the function require() is called with false arguments, it returns false.
You can see an example of how the require statement was used in the image above.
What do you think?
Don’t forget to add your thoughts in the comment section and turn on the notification.