code-423n4 / 2022-09-artgobblers-findings

0 stars 0 forks source link

Gas Optimizations #402

Closed code423n4 closed 1 year ago

code423n4 commented 2 years ago

Gas Optimizations Report for Art Gobblers contest

Overview

During the audit, 8 gas issues were found.

Title Instance Count
G-1 Postfix increment and decrement 9
G-2 <>.length in loops 2
G-3 Initializing variables with default value 5
G-4 > 0 is more expensive than =! 0 2
G-5 x += y is more expensive than x = x + y 6
G-6 Public is more expensive than private for constants 8
G-7 Custom errors may be used 33
G-8 Elements that are smaller than 32 bytes (256 bits) may increase gas usage 9

Gas Optimizations Findings (8)

G-1. Postfix increment and decrement

Description

Prefix increment and decrement cost less gas than postfix.

Instances
Recommendation

Consider using prefix increment and decrement where it is relevant.

#

G-2. <>.length in loops

Description

Reading the length of an array at each iteration of the loop consumes extra gas.

Instances
Recommendation

Store the length of an array in a variable before the loop, and use it.

#

G-3. Initializing variables with default value

Description

It costs gas to initialize integer variables with 0 or bool variables with false but it is not necessary.

Instances
Recommendation

Remove initialization for default values.
For example: for (uint256 i; i < array.length; ++i) {

#

G-4. > 0 is more expensive than =! 0

Instances
Recommendation

Use =! 0 instead of > 0, where possible.

#

G-5. x += y is more expensive than x = x + y

Instances
Recommendation

Use x = x + y instead of x += y. Use x = x - y instead of x -= y.

#

G-6. Public is more expensive than private for constants

Instances
Recommendation

Use private constants instead of public, where possible.

#

G-7. Custom errors may be used

Description

Custom errors from Solidity 0.8.4 are cheaper than revert strings.

Instances

ZERO_ADDRESS

WRONG_FROM

INVALID_RECIPIENT

UNSAFE_RECIPIENT

NOT_AUTHORIZED

NOT_MINTED

ALREADY_MINTED

LENGTH_MISMATCH

Recommendation

For example, change:

require(getGobblerData[id].owner == msg.sender, "WRONG_FROM");

to:

error WrongFrom();
...
if (getGobblerData[id].owner != msg.sender) revert WrongFrom();

#

G-8. Elements that are smaller than 32 bytes (256 bits) may increase gas usage

Description

According to docs, when using elements that are smaller than 32 bytes, your contract’s gas usage may be higher. This is because the EVM operates on 32 bytes at a time. Therefore, if the element is smaller than that, the EVM must use more operations in order to reduce the size of the element from 32 bytes to the desired size.

Instances
Recommendation

Use a larger size where needed.

GalloDaSballo commented 2 years ago

Less than 100 gas