wise-foundation / lending-audit

5 stars 4 forks source link

[MHR-06C] Potentially Inefficient Array Shift Operation #76

Open vm06007 opened 1 year ago

vm06007 commented 1 year ago

MHR-06C: Potentially Inefficient Array Shift Operation

Type Severity Location
Gas Optimization MainHelper.sol:L575-L577

Description:

The referenced ternary condition is meant to assign the last element of the array to the index of the element being removed, however, this will be done inefficiently so when the index being removed is the endPosition.

Example:

while (index < length) {

    if (_getPositionTokenByIndex(_nftId, index) != _poolToken) {
        index += 1;
        continue;
    }

    address poolToken = _getPositionTokenByIndex(
        _nftId,
        endPosition
    );

    isLending
        ? positionLendingTokenData[_nftId][index] = poolToken
        : positionBorrowTokenData[_nftId][index] = poolToken;

    _deleteLastPositionData(
        _nftId,
        _poolToken
    );

    break;
}

Recommendation:

We advise the code to immediately invoke _deleteLastPositionData if the index is equal to the endPosition without fetching the position token by index nor assigning it at the index, greatly reducing the worst-case gas cost of the function.

vm06007 commented 1 year ago

Resolved based on suggestion from auditor in https://github.com/wise-foundation/lending-audit/pull/75