code-423n4 / 2022-10-zksync-findings

3 stars 0 forks source link

Gas Optimizations #334

Closed code423n4 closed 1 year ago

code423n4 commented 1 year ago

Gas Optimizations Report for zkSync v2 contest

Overview

During the audit, 4 gas issues were found.
Total savings ~1500+.

Title Instance Count Saved
G-1 Use calldata instead of memory for read-only arguments 19 1140
G-2 Use unchecked blocks for incrementing i 4 140
G-3 Use inline function for internal function called once 8 240
G-4 Elements that are smaller than 32 bytes (256 bits) may increase gas usage 12

Gas Optimizations Findings(4)

G-1. Use calldata instead of memory for read-only arguments

Description

Since Solidity v0.6.9, memory and calldata are allowed in all functions regardless of their visibility type (See "Calldata Variables" section here).
When function arguments should not be modified, it is cheaper to use calldata.

Instances
Recommendation

Consider using calldata where possible.

Saved

This saves at least 60 gas per iteration.
So, ~60*19 = 1140 #

G-2. Use unchecked blocks for incrementing i

Description

In Solidity 0.8+, there’s a default overflow and underflow check on unsigned integers. In the loops, "i" will not overflow because the loop will run out of gas before that.

Instances
Recommendation

Change:

for (uint256 i; i < n; ++i) {
 // ...
}

to:

for (uint256 i; i < n;) { 
 // ...
 unchecked { ++i; }
}
Saved

This saves ~30-40 gas per iteration.
So, ~35*4 = 140 #

G-3. Use inline function for internal function called once

Description

Function calls need two extra JUMP instructions and other stack operations.

Instances
Saved

This saves ~20-40.
So, ~30*8 = 240 #

G-4. 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

Consider using a larger size where needed.

GalloDaSballo commented 1 year ago

G-1 | Use calldata instead of memory for read-only arguments | 19 | 1140 Most will not compile, ignoring

G-2 | Use unchecked blocks for incrementing i | 4 | 140 200

G-3 | Use inline function for internal function called once | 8 | 240 8*24 192

392

c4-judge commented 1 year ago

GalloDaSballo marked the issue as grade-c