You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Arithmetics: ++i costs less gas compared to i++ or i += 1
5
4
Arithmetics: Use != 0 instead of > 0 for unsigned integers in require statements
1
5
Arithmetics: Use Shift Right/Left instead of Division/Multiplication if possible
2
6
Visibility: Consider declaring constants as non-public to save gas
4
7
Duplicated require() checks should be refactored to a modifier or function
1
8
Errors: Use custom errors instead of revert strings
36
9
State variables should be cached in stack variables rather than re-reading them from storage
1
10
<x> += <y> costs more gas than <x> = <x> + <y> for state variables
2
11
Using bool for storage incurs overhead
5
12
Usage of uints/ints smaller than 32 bytes (256 bits) incurs overhead
17
13
Not using the named return variables when a function returns, wastes deployment gas
4
14
Multiple accesses of a mapping/array should use a local variable cache
4
Total: 97 instances over 14 issues
For-loops: Index initialized with default value
Uninitialized uint variables are assigned with a default value of 0.
Thus, in for-loops, explicitly initializing an index with 0 costs unnecesary gas. For example, the following code:
for(uint256i=0;i<length;++i){
can be written without explicitly setting the index to 0:
for(uint256i;i<length;++i){
There are 7 instances of this issue:
src/Pages.sol:
251: for (uint256 i =0; i < numPages; i++) _mint(community, ++lastMintedPageId);
src/ArtGobblers.sol:
432: for (uint256 i =0; i < cost; ++i) {
592: for (uint256 i =0; i < numGobblers; ++i) {
src/utils/GobblerReserve.sol:
37: for (uint256 i =0; i < ids.length; i++) {
src/utils/token/GobblersERC721.sol:
186: for (uint256 i =0; i < amount; ++i) {
src/utils/token/GobblersERC1155B.sol:
114: for (uint256 i =0; i < owners.length; ++i) {
173: for (uint256 i =0; i < amount; ++i) {
For-Loops: Cache array length outside of loops
Reading an array's length at each iteration has the following gas overheads:
storage arrays incur a Gwarmaccess (100 gas)
memory arrays use mload (3 gas)
calldata arrays use calldataload (3 gas)
Caching the length changes each of these to a DUP<N> (3 gas), and gets rid of the extra DUP<N> needed to store the stack offset. This would save around 3 gas per iteration.
For example:
for(uint256i;i<arr.length;++i){}
can be changed to:
uint256len=arr.length;for(uint256i;i<len;++i){}
There are 2 instances of this issue:
src/utils/GobblerReserve.sol:
37: for (uint256 i =0; i < ids.length; i++) {
src/utils/token/GobblersERC1155B.sol:
114: for (uint256 i =0; i < owners.length; ++i) {
Arithmetics: ++i costs less gas compared to i++ or i += 1
++i costs less gas compared to i++ or i += 1 for unsigned integers, as pre-increment is cheaper (about 5 gas per iteration). This statement is true even with the optimizer enabled.
i++ increments i and returns the initial value of i. Which means:
uinti=1;i++;// == 1 but i == 2
But ++i returns the actual incremented value:
uinti=1;++i;// == 2 and i == 2 too, so no need for a temporary variable
In the first case, the compiler has to create a temporary variable (when used) for returning 1 instead of 2, thus it costs more gas.
The same logic applies for --i and i--.
There are 5 instances of this issue:
src/Pages.sol:
251: for (uint256 i =0; i < numPages; i++) _mint(community, ++lastMintedPageId);
src/ArtGobblers.sol:
464: legendaryGobblerAuctionData.numSold +=1; // Increment the # of legendaries sold.906: getUserData[from].gobblersOwned -=1;
913: getUserData[to].gobblersOwned +=1;
src/utils/GobblerReserve.sol:
37: for (uint256 i =0; i < ids.length; i++) {
Arithmetics: Use != 0 instead of > 0 for unsigned integers in require statements
A variable of type uint will never go below 0. Thus, checking != 0 rather than > 0 is sufficient, which would save 6 gas per instance.
Arithmetics: Use Shift Right/Left instead of Division/Multiplication if possible
A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.
While the MUL and DIV opcodes use 5 gas, the SHL and SHR opcodes only uses 3 gas. Furthermore, Solidity's division operation also includes a division-by-0 prevention which is bypassed using shifting.
Visibility: Consider declaring constants as non-public to save gas
If a constant is not used outside of its contract, declaring its visibility as private or internal instead of public can save gas. If needed, the value can be read from the verified contract source code.
Gas savings occur as the compiler does not have to create non-payable getter functions for deployment calldata and add another entry to the method ID table.
Duplicated require() checks should be refactored to a modifier or function
If a require() statement that is used to validate function parameters or global variables is present across multiple functions in a contract, it should be rewritten into modifier if possible. This would help to reduce code deployment size, which saves gas, and improve code readability.
Starting from Solidity v0.8.4, there is a convenient and gas-efficient way to explain to users why an operation failed through the use of custom errors. Until now, you could already use strings to give more information about failures (e.g., revert("Insufficient funds.");), but they are rather expensive, especially when it comes to deploy cost, and it is difficult to use dynamic information in them.
Custom errors reduce runtime gas costs as they save about 50 gas each time they are hit by avoiding having to allocate and store the revert string. Furthermore, not definiting error strings also help to reduce deployment gas costs.
State variables should be cached in stack variables rather than re-reading them from storage
If a state variable is read from storage multiple times in a function, it should be cached in a stack variable.
Caching of a state variable replaces each Gwarmaccess (100 gas) with a much cheaper stack read. Other less obvious fixes/optimizations include having local memory caches of state variable structs, or having local caches of state variable contracts/addresses.
There is 1 instance of this issue: numMintedFromGoo in legendaryGobblerPrice():
Declaring storage variables as bool is more expensive compared to uint256, as explained here:
Booleans are more expensive than uint256 or any type that takes up a full word because each write operation emits an extra SLOAD to first read the slot's contents, replace the bits taken up by the boolean, and then write back. This is the compiler's defense against contract upgrades and pointer aliasing, and it cannot be disabled.
Use uint256(1) and uint256(2) rather than true/false to avoid a Gwarmaccess (100 gas) for the extra SLOAD, and to avoid Gsset (20000 gas) when changing from 'false' to 'true', after having been 'true' in the past.
There are 5 instances of this issue:
src/ArtGobblers.sol:
149: mapping(address=>bool) public hasClaimedMintlistGobbler;
src/utils/token/PagesERC721.sol:
70: mapping(address=>mapping(address=>bool)) internal _isApprovedForAll;
src/utils/token/GobblersERC721.sol:
77: mapping(address=>mapping(address=>bool)) public isApprovedForAll;
src/utils/token/GobblersERC1155B.sol:
37: mapping(address=>mapping(address=>bool)) public isApprovedForAll;
lib/solmate/src/tokens/ERC721.sol:
51: mapping(address=>mapping(address=>bool)) public isApprovedForAll;
Usage of uints/ints smaller than 32 bytes (256 bits) incurs overhead
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.
However, this does not apply to storage values as using reduced-size types might be beneficial to pack multiple elements into a single storage slot. Thus, where appropriate, use uint256/int256 and downcast when needed.
Not using the named return variables when a function returns, wastes deployment gas
There are 4 instances of this issue:
src/utils/token/PagesERC721.sol:
73: if (operator ==address(artGobblers)) returntrue; // Skip approvals for the ArtGobblers contract.75: return _isApprovedForAll[owner][operator];
src/utils/token/GobblersERC1155B.sol:
56: return getGobblerData[id].owner;
src/utils/rand/ChainlinkV1RandProvider.sol:
69: returnrequestRandomness(chainlinkKeyHash, chainlinkFee);
Multiple accesses of a mapping/array should use a local variable cache
If a mapping/array is read with the same key/index multiple times in a function, it should be cached in a stack variable.
Caching a mapping's value in a local storage variable when the value is accessed multiple times, saves ~42 gas per access due to not having to recalculate the key's keccak256 hash (Gkeccak256 - 30 gas) and that calculation's associated stack operations. Caching an array's struct avoids recalculating the array offsets into memory.
There are 4 instances of this issue: getGobblerData[id] in mintLegendaryGobbler():
Gas Optimizations
++i
costs less gas compared toi++
ori += 1
!= 0
instead of> 0
for unsigned integers inrequire
statementsrequire()
checks should be refactored to a modifier or function<x> += <y>
costs more gas than<x> = <x> + <y>
for state variablesbool
for storage incurs overheaduints
/ints
smaller than 32 bytes (256 bits) incurs overheadTotal: 97 instances over 14 issues
For-loops: Index initialized with default value
Uninitialized
uint
variables are assigned with a default value of0
.Thus, in for-loops, explicitly initializing an index with
0
costs unnecesary gas. For example, the following code:can be written without explicitly setting the index to
0
:There are 7 instances of this issue:
For-Loops: Cache array length outside of loops
Reading an array's length at each iteration has the following gas overheads:
mload
(3 gas)calldataload
(3 gas)Caching the length changes each of these to a
DUP<N>
(3 gas), and gets rid of the extraDUP<N>
needed to store the stack offset. This would save around 3 gas per iteration.For example:
can be changed to:
There are 2 instances of this issue:
Arithmetics:
++i
costs less gas compared toi++
ori += 1
++i
costs less gas compared toi++
ori += 1
for unsigned integers, as pre-increment is cheaper (about 5 gas per iteration). This statement is true even with the optimizer enabled.i++
incrementsi
and returns the initial value ofi
. Which means:But
++i
returns the actual incremented value:In the first case, the compiler has to create a temporary variable (when used) for returning
1
instead of2
, thus it costs more gas.The same logic applies for
--i
andi--
.There are 5 instances of this issue:
Arithmetics: Use
!= 0
instead of> 0
for unsigned integers inrequire
statementsA variable of type
uint
will never go below 0. Thus, checking!= 0
rather than> 0
is sufficient, which would save 6 gas per instance.There is 1 instance of this issue:
Arithmetics: Use Shift Right/Left instead of Division/Multiplication if possible
A division/multiplication by any number
x
being a power of 2 can be calculated by shiftinglog2(x)
to the right/left.While the
MUL
andDIV
opcodes use 5 gas, theSHL
andSHR
opcodes only uses 3 gas. Furthermore, Solidity's division operation also includes a division-by-0 prevention which is bypassed using shifting.For example, the following code:
can be changed to:
There are 2 instances of this issue:
Visibility: Consider declaring constants as non-public to save gas
If a constant is not used outside of its contract, declaring its visibility as
private
orinternal
instead ofpublic
can save gas. If needed, the value can be read from the verified contract source code.Gas savings occur as the compiler does not have to create non-payable getter functions for deployment calldata and add another entry to the method ID table.
There are 4 instances of this issue:
Duplicated
require()
checks should be refactored to a modifier or functionIf a
require()
statement that is used to validate function parameters or global variables is present across multiple functions in a contract, it should be rewritten into modifier if possible. This would help to reduce code deployment size, which saves gas, and improve code readability.There is 1 instance of this issue:
Instance #3:
Errors: Use custom errors instead of revert strings
Since Solidity v0.8.4, custom errors can be used rather than
require
statements.Taken from Custom Errors in Solidity:
Custom errors reduce runtime gas costs as they save about 50 gas each time they are hit by avoiding having to allocate and store the revert string. Furthermore, not definiting error strings also help to reduce deployment gas costs.
There are 36 instances of this issue:
State variables should be cached in stack variables rather than re-reading them from storage
If a state variable is read from storage multiple times in a function, it should be cached in a stack variable.
Caching of a state variable replaces each Gwarmaccess (100 gas) with a much cheaper stack read. Other less obvious fixes/optimizations include having local memory caches of state variable structs, or having local caches of state variable contracts/addresses.
There is 1 instance of this issue:
numMintedFromGoo
inlegendaryGobblerPrice()
:<x> += <y>
costs more gas than<x> = <x> + <y>
for state variablesThe above also applies to state variables that use
-=
.There are 2 instances of this issue:
Using
bool
for storage incurs overheadDeclaring storage variables as
bool
is more expensive compared touint256
, as explained here:Use
uint256(1)
anduint256(2)
rather than true/false to avoid a Gwarmaccess (100 gas) for the extraSLOAD
, and to avoid Gsset (20000 gas) when changing from 'false' to 'true', after having been 'true' in the past.There are 5 instances of this issue:
Usage of
uints
/ints
smaller than 32 bytes (256 bits) incurs overheadAs seen from here:
However, this does not apply to storage values as using reduced-size types might be beneficial to pack multiple elements into a single storage slot. Thus, where appropriate, use
uint256
/int256
and downcast when needed.There are 17 instances of this issue:
Not using the named return variables when a function returns, wastes deployment gas
There are 4 instances of this issue:
Multiple accesses of a mapping/array should use a local variable cache
If a mapping/array is read with the same key/index multiple times in a function, it should be cached in a stack variable.
Caching a mapping's value in a local
storage
variable when the value is accessed multiple times, saves ~42 gas per access due to not having to recalculate the key's keccak256 hash (Gkeccak256 - 30 gas) and that calculation's associated stack operations. Caching an array's struct avoids recalculating the array offsets into memory.There are 4 instances of this issue:
getGobblerData[id]
inmintLegendaryGobbler()
:getGobblerData[currentId]
inrevealGobblers()
:getUserData[user]
ingooBalance()
:getGobblerData[id]
intransferFrom()
:The text was updated successfully, but these errors were encountered: