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 #2

Open
code423n4 opened this issue Mar 29, 2022 · 1 comment
Open

Gas Optimizations #2

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

Comments

@code423n4
Copy link
Contributor

Title: Unnecessary cast
Severity: Gas

    Request PooledCreditLine.sol.request - unnecessary casting Request(_request)

Title: Public functions to external
Severity: GAS

The following functions could be set external to save gas and improve code quality.
External call cost is less expensive than of public functions.

    PooledCreditLine.sol, getPrincipal

Title: Use unchecked to save gas for certain additive calculations that cannot overflow
Severity: GAS

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

    twitterVerifier.sol (L#126) - require(block.timestamp < _timestamp + signValidity, 'RS3'); 
    PooledCreditLine.sol (L#683) - uint256 _endsAt = block.timestamp + _request.collectionPeriod + _request.duration;
    PooledCreditLine.sol (L#684) - _clc.startsAt = block.timestamp + _request.collectionPeriod;

Title: Prefix increments are cheaper than postfix increments
Severity: GAS

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:

    just change to unchecked: LenderPool.sol, i, 670

Title: Consider inline the following functions to save gas
Severity: 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.)


    PooledCreditLine.sol, _calculateInterest, { return (_principal.mul(_borrowRate).mul(_timeElapsed).div(YEAR_IN_SECONDS).div(SCALING_FACTOR)); }

Title: Caching array length can save gas
Severity: 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++) { ... }


    LenderPool.sol, ids, 670

Title: Upgrade pragma to at least 0.8.4
Severity: GAS

Using newer compiler versions and the optimizer gives gas optimizations
and additional safety checks are available for free.

The advantages of versions 0.8.* over <0.8.0 are:

    1. Safemath by default from 0.8.0 (can be more gas efficient than library based safemath.)
    2. Low level inliner : from 0.8.2, leads to cheaper runtime gas. Especially relevant when the contract has small functions. For example, OpenZeppelin libraries typically have a lot of small helper functions and if they are not inlined, they cost an additional 20 to 40 gas because of 2 extra jump instructions and additional stack operations needed for function calls.
    3. Optimizer improvements in packed structs: Before 0.8.3, storing packed structs, in some cases used an additional storage read operation. After EIP-2929, if the slot was already cold, this means unnecessary stack operations and extra deploy time costs. However, if the slot was already warm, this means additional cost of 100 gas alongside the same unnecessary stack operations and extra deploy time costs.
    4. Custom errors from 0.8.4, leads to cheaper deploy time cost and run time cost. Note: the run time cost is only relevant when the revert condition is met. In short, replace revert strings by custom errors.

    LenderPool.sol
    PooledCreditLine.sol
    twitterVerifier.sol

Title: Unnecessary functions
Severity: GAS

The following functions are not used at all. Therefore you can remove them to save deployment gas and improve code clearness.


    LenderPool.sol, _beforeTokenTransfer

Title: Inline one time use functions
Severity: GAS

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

    PooledCreditLine.sol, _notifyRequest
    PooledCreditLine.sol, _borrow
    PooledCreditLine.sol, _withdrawBorrowAmount
    LenderPool.sol, _rebalanceInterestWithdrawn
    PooledCreditLine.sol, updateStateOnPrincipalChange
    PooledCreditLine.sol, _limitBorrowedInUSD
    PooledCreditLine.sol, _repay
    PooledCreditLine.sol, _createRequest

Title: Use calldata instead of memory
Severity: GAS

Use calldata instead of memory for function parameters
In some cases, having function arguments in calldata instead of
memory is more optimal.

    twitterVerifier.initialize (_version)
    twitterVerifier.registerSelf (_tweetId)
    twitterVerifier.initialize (_name)

Title: Cache powers of 10 used several times
Severity: GAS

You calculate the power of 10 every time you use it instead of caching it once as a constant variable and using it instead.
Fix the following code lines:

PooledCreditLine.sol, 389 : You should cache the used power of 10 as constant state variable since it's used several times (6): uint256 _poolsizeInUSD = _borrowLimit.mul(_ratioOfPrices).div(10**_decimals);

PooledCreditLine.sol, 1246 : You should cache the used power of 10 as constant state variable since it's used several times (6): 10**_decimals

PooledCreditLine.sol, 825 : You should cache the used power of 10 as constant state variable since it's used several times (6): .mul(10**_decimals)

PooledCreditLine.sol, 394 : You should cache the used power of 10 as constant state variable since it's used several times (6): uint256 _minBorrowLimitInUSD = _minBorrowAmount.mul(_ratioOfPrices).div(10**_decimals);

PooledCreditLine.sol, 1259 : You should cache the used power of 10 as constant state variable since it's used several times (6): uint256 _collateralTokens = (_borrowTokens.mul(_ratioOfPrices).div(10**_decimals));

PooledCreditLine.sol, 943 : You should cache the used power of 10 as constant state variable since it's used several times (6): _maxPossible = _totalCollateralToken.mul(_ratioOfPrices).div(_collateralRatio).mul(SCALING_FACTOR).div(10**_decimals);

Title: Unnecessary Reentrancy Guards
Severity: GAS

Where there is onlyOwner or Initializer modifer, the reentrancy gaurd isn't
necessary (unless you don't trust the owner or the deployer, which will lead to full security breakdown of the project and we believe this is not the case)
This is a list we found of such occurrences:

    PooledCreditLine.sol no need both nonReentrant and onlyOwner modifiers in terminate

Title: Internal functions to private
Severity: GAS

The following functions could be set private to save gas and improve code quality:

    LenderPool.sol, _beforeTokenTransfer
    LenderPool.sol, _withdrawInterest
    PooledCreditLine.sol, _equivalentCollateral
    LenderPool.sol, _withdrawLiquidity
    LenderPool.sol, _updateStartFeeFraction
    PooledCreditLine.sol, _withdrawBorrowAmount
    LenderPool.sol, _calculatePrincipalWithdrawable
    LenderPool.sol, _withdrawLiquidation
    PooledCreditLine.sol, _updateProtocolFeeFraction
    PooledCreditLine.sol, isWithinLimits
    PooledCreditLine.sol, _updatePriceOracle
    PooledCreditLine.sol, _withdrawCollateral
    PooledCreditLine.sol, _transferCollateral
    LenderPool.sol, _calculateInterestToWithdraw
    PooledCreditLine.sol, _updateProtocolFeeCollector
    PooledCreditLine.sol, _updateVerification
    LenderPool.sol, _accept
    PooledCreditLine.sol, _notifyRequest
    PooledCreditLine.sol, _updateSavingsAccount
    PooledCreditLine.sol, _borrow
    LenderPool.sol, _rebalanceInterestWithdrawn
    PooledCreditLine.sol, updateStateOnPrincipalChange
    PooledCreditLine.sol, _calculateInterest
    PooledCreditLine.sol, _limitBorrowedInUSD
    PooledCreditLine.sol, _repay
    PooledCreditLine.sol, _updateStrategyRegistry
    PooledCreditLine.sol, _createRequest
@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels Mar 29, 2022
code423n4 added a commit that referenced this issue Mar 29, 2022
@ritik99
Copy link
Collaborator

ritik99 commented Apr 12, 2022

Issues 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13 are valid/acknowledged suggestions.

Unclear/invalid issues:

  1. ("Unnecessary cast") is unclear
  2. ("Unnecessary functions") _beforeTokenTransfer is called during token transfers

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