code-423n4 / 2021-10-union-findings

0 stars 0 forks source link

Cache array length in for loops can save gas #60

Open code423n4 opened 3 years ago

code423n4 commented 3 years ago

Handle

WatchPug

Vulnerability details

Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack.

Caching the array length in the stack saves around 3 gas per iteration.

Instances include:

https://github.com/code-423n4/2021-10-union/blob/4176c366986e6d1a6b3f6ec0079ba547b040ac0f/contracts/user/SumOfTrust.sol#L44-L44

https://github.com/code-423n4/2021-10-union/blob/4176c366986e6d1a6b3f6ec0079ba547b040ac0f/contracts/user/SumOfTrust.sol#L32-L44

function getLockedAmount(
    LockedInfo[] memory array,
    address account,
    uint256 amount,
    bool isIncrease
) public pure override returns (uint256) {
    if (array.length == 0) return 0;

    uint256 remaining = amount;
    uint256 newLockedAmount;
    if (isIncrease) {
        array = _sortArray(array, true);
        for (uint256 i = 0; i < array.length; i++) {

https://github.com/code-423n4/2021-10-union/blob/4176c366986e6d1a6b3f6ec0079ba547b040ac0f/contracts/user/SumOfTrust.sol#L19-L22

function getCreditLimit(uint256[] memory vouchs) public view override returns (uint256) {
        if (vouchs.length >= effectiveNumber) {
            uint256 limit;
            for (uint256 i = 0; i < vouchs.length; i++) {

https://github.com/code-423n4/2021-10-union/blob/4176c366986e6d1a6b3f6ec0079ba547b040ac0f/contracts/user/UserManager.sol#L688-L694

    function repayLoanOverdue(
        address account,
        address token,
        uint256 lastRepay
    ) external override whenNotPaused onlyMarketOrAdmin {
        address[] memory stakerAddresses = getStakerAddresses(account);
        for (uint256 i = 0; i < stakerAddresses.length; i++) {

https://github.com/code-423n4/2021-10-union/blob/4176c366986e6d1a6b3f6ec0079ba547b040ac0f/contracts/asset/AssetManager.sol#L307-L309

function addAdapter(address adapterAddress) external override onlyAdmin {
        bool isExist = false;
        for (uint256 i = 0; i < moneyMarkets.length; i++) {

And more.

GalloDaSballo commented 3 years ago

Agree with the finding, caching length saves 3 gas