Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gas Optimizations #155

Open
code423n4 opened this issue Aug 15, 2022 · 1 comment
Open

Gas Optimizations #155

code423n4 opened this issue Aug 15, 2022 · 1 comment
Labels
bug Something isn't working G (Gas Optimization)

Comments

@code423n4
Copy link
Contributor

State variables that could be set immutable

In the following files there are state variables that could be set immutable to save gas.

Code instances:

    versionNFTCollection in NFTCollectionFactory.sol
    paymentAddress in NFTDropCollection.sol

Unused state variables

Unused state variables are gas consuming at deployment (since they are located in storage) and are
a bad code practice. Removing those variables will decrease deployment gas cost and improve code quality.
This is a full list of all the unused storage variables we found in your code base.

Code instances:

    AdminRole.sol, __gap
    OZAccessControlUpgradeable.sol, __gap
    NFTDropMarketFixedPriceSale.sol, __gap
    MarketSharedCore.sol, __gap
    WETH9.sol, symbol
    SendValueWithFallbackWithdraw.sol, __gap_was_pendingWithdrawals
    WETH9.sol, name
    Gap10000.sol, __gap
    WETH9.sol, decimals
    NFTDropMarketCore.sol, __gap
    CollateralManagement.sol, __gap
    FoundationTreasuryNode.sol, __gap_was_treasury

Unused declared local variables

Unused local variables are gas consuming, since the initial value assignment costs gas. And are
a bad code practice. Removing those variables will decrease the gas cost and improve code quality.
This is a full list of all the unused storage variables we found in your code base.

Code instance:

    OZERC165Checker.sol, supportsERC165InterfaceUnchecked, encodedParams

Unnecessary array boundaries check when loading an array element twice

There are places in the code (especially in for-each loops) that loads the same array element more than once. 
In such cases, only one array boundaries check should take place, and the rest are unnecessary.
Therefore, this array element should be cached in a local variable and then be loaded
again using this local variable, skipping the redundant second array boundaries check: 

Code instance:

    PercentSplitETH.sol.getShares - double load of _shares[i]

Caching array length can save gas

Caching the array length is more gas efficient.
This is because access to a local variable in solidity is more efficient than query storage / calldata / memory.
We recommend to change from:

for (uint256 i=0; i<array.length; i++) { ... }

to:

uint len = array.length  
for (uint256 i=0; i<len; i++) { ... }

Code instances:

    PercentSplitETH.sol, shares, 320
    PercentSplitETH.sol, _shares, 115

Prefix increments are cheaper than postfix increments

Prefix increments are cheaper than postfix increments.
Further more, using unchecked {++x} is even more gas efficient, and the gas saving accumulates every iteration and can make a real change
There is no risk of overflow caused by increamenting the iteration index in for loops (the ++i in for (uint256 i = 0; i < numIterations; ++i)).
But increments perform overflow checks that are not necessary in this case.
These functions use not using prefix increments (++x) or not using the unchecked keyword:

Code instances:

    just change to unchecked: PercentSplitETH.sol, i, 320
    just change to unchecked: PercentSplitETH.sol, i, 115

Unnecessary index init

In for loops you initialize the index to start from 0, but it already initialized to 0 in default and this assignment cost gas.
It is more clear and gas efficient to declare without assigning 0 and will have the same meaning:

Code instances:

    PercentSplitETH.sol, 320
    PercentSplitETH.sol, 115

Storage double reading. Could save SLOAD

Reading a storage variable is gas costly (SLOAD). In cases of multiple read of a storage variable in the same scope, caching the first read (i.e saving as a local variable) can save gas and decrease the
overall gas uses. The following is a list of functions and the storage variables that you read twice:

Code instance:

    PercentSplitETH.sol: BASIS_POINTS is read twice in initialize

Unnecessary default assignment

Unnecessary default assignments, you can just declare and it will save gas and have the same meaning.

Code instance:

    BasicERC721WithoutOwnerOfRevert.sol (L#18) : uint256 private id = 0; 

Use bytes32 instead of string to save gas whenever possible

Use bytes32 instead of string to save gas whenever possible.
String is a dynamic data structure and therefore is more gas consuming then bytes32.

Code instances:

    FETH.sol (L135), string public constant symbol = "FETH"; 
    WETH9.sol (L6), string public name = "Wrapped Ether";
    WETH9.sol (L7), string public symbol = "WETH";
    FETH.sol (L130), string public constant name = "Foundation ETH"; 

Short the following require messages

The following require messages are of length more than 32 and we think are short enough to short
them into exactly 32 characters such that it will be placed in one slot of memory and the require
function will cost less gas.
The list:

Code instances:

    Solidity file: BasicERC721.sol, In line 263, Require message length to shorten: 37, The message: ERC721: transfer from incorrect owner
    Solidity file: PercentSplitETH.sol, In line 148, Require message length to shorten: 35, The message: Split: Total amount must equal 100%
    Solidity file: NFTDropCollection.sol, In line 130, Require message length to shorten: 40, The message: NFTDropCollection: `_symbol` must be set
    Solidity file: NFTDropCollection.sol, In line 179, Require message length to shorten: 38, The message: NFTDropCollection: Exceeds max tokenId
    Solidity file: NFTCollection.sol, In line 263, Require message length to shorten: 35, The message: NFTCollection: tokenCID is required
    Solidity file: NFTDropCollection.sol, In line 238, Require message length to shorten: 39, The message: NFTDropCollection: use `reveal` instead
    Solidity file: NFTCollection.sol, In line 264, Require message length to shorten: 37, The message: NFTCollection: NFT was already minted
    Solidity file: PercentSplitETH.sol, In line 191, Require message length to shorten: 33, The message: Split: ERC20 tokens must be split
    Solidity file: PercentSplitETH.sol, In line 136, Require message length to shorten: 35, The message: Split: Share must be less than 100%
    Solidity file: NFTCollectionFactory.sol, In line 262, Require message length to shorten: 40, The message: NFTCollectionFactory: Symbol is required
    Solidity file: BasicERC721.sol, In line 59, Require message length to shorten: 33, The message: ERC721: approval to current owner
    Solidity file: BasicERC721.sol, In line 264, Require message length to shorten: 36, The message: ERC721: transfer to the zero address

Use != 0 instead of > 0

Using != 0 is slightly cheaper than > 0. (see code-423n4/2021-12-maple-findings#75 for similar issue)

Code instances:

    NFTDropMarketFixedPriceSale.sol, 183: change 'balance > 0' to 'balance != 0'
    WETH9.sol, 55: change 'balance > 0' to 'balance != 0'
    WETH9.sol, 29: change 'balance > 0' to 'balance != 0'
    LockedBalance.sol, 113: change 'balance > 0' to 'balance != 0'
    NFTDropCollection.sol, 131: change '_maxTokenId > 0' to '_maxTokenId != 0'

Use unchecked to save gas for certain additive calculations that cannot overflow

You can use unchecked in the following calculations since there is no risk to overflow:

Code instances:

    FETH.sol (L#572) - expiration = lockupDuration + block.timestamp.ceilDiv(lockupInterval) * lockupInterval;
    FETH.sol (L#765) - if (escrow.expiration >= block.timestamp && escrow.totalAmount != 0) { ++lockedCount;

Consider inline the following functions to save gas

You can inline the following functions instead of writing a specific function to save gas.
(see https://github.com/code-423n4/2021-11-nested-findings/issues/167 for a similar issue.)

Code instances

    OZAccessControlUpgradeable.sol, getRoleMemberCount, { return _roles[role].members.length(); }
    BasicERC721.sol, _exists, { return _owners[tokenId] != address(0); }
    OZAccessControlUpgradeable.sol, getRoleMember, { return _roles[role].members.at(index); }
    OZAccessControlUpgradeable.sol, hasRole, { return _roles[role].members.contains(account); }
    NFTCollectionFactory.sol, _getSalt, { return keccak256(abi.encodePacked(creator, nonce)); }
    AddressLibrary.sol, callAndReturnContractAddress, { return callAndReturnContractAddress(call.target, call.callData); }

Inline one time use functions

The following functions are used exactly once. Therefore you can inline them and save gas and improve code clearness.

Code instances:

    NFTDropCollection.sol, _burn
    MarketSharedCore.sol, _getSellerOf
    NFTCollection.sol, _burn
    OZAccessControlUpgradeable.sol, _revokeRole
    SequentialMintCollection.sol, _burn
    ArrayLibrary.sol, capLength
    BasicERC721.sol, _safeTransfer

Change if -> revert pattern to require

Change if -> revert pattern to 'require' to save gas and improve code quality,
if (some_condition) {
revert(revert_message)
}

to: require(!some_condition, revert_message)

In the following locations:

Code instance:

    BasicERC721.sol, 303
@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels Aug 15, 2022
code423n4 added a commit that referenced this issue Aug 15, 2022
@HardlyDifficult
Copy link
Collaborator

State variables that could be set immutable

Invalid. versionNFTCollection increments with each new template. paymentAddress is set in the initializer for each proxy individually.

Unused state variables

Invalid - these gaps are here to help preserve upgrade compatibility and to leave room for changes in future upgrades.

Unused declared local variables

Invalid, that is called.

Unnecessary array boundaries check when loading an array element twice

Potentially valid but that file was out of scope for this contest.

Cache Array Length Outside of Loop

May be theoretically valid, but won't fix. I tested this: gas-reporter and our gas-stories suite is reporting a small regression using this technique. It also hurts readability a bit so we wouldn't want to include it unless it was a clear win.

++i costs less than i++

Agree and will fix.

Don't initialize variables with default values.

Invalid. This optimization technique is no longer applicable with the current version of Solidity.

Storage double reading. Could save SLOAD

Invalid. Constants do not use SLOAD

Use bytes32 instead of string to save gas whenever possible

FETH and mocks are out of scope.

Use short error messages

Agree but won't fix. We use up to 64 bytes, aiming to respect the incremental cost but 32 bytes is a bit too short to provide descriptive error messages for our u

Use != 0 instead of > 0

Invalid. We tested the recommendation and got the following results:

createNFTDropCollection gas reporter results:
  using > 0 (current):
    - 319246  ·     319578  ·      319361
  using != 0 (recommendation):
    -  319252  ·     319584  ·      319367
  impact: +6 gas

unchecked

FETH is out of scope

Consider inline the following functions to save gas
Inline one time use functions

This may save a bit of gas, but occasionally helpers improve readability.

Change if -> revert pattern to require

Invalid - the code instance is a mock file.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working G (Gas Optimization)
Projects
None yet
Development

No branches or pull requests

2 participants