code-423n4 / 2021-11-badgerzaps-findings

0 stars 0 forks source link

Gas optimization: Use else if for mutually exclusive conditions #76

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Handle

gzeon

Vulnerability details

Impact

Use else if for mutually exclusive conditions to save gas

Proof of Concept

https://github.com/Badger-Finance/ibbtc/blob/d8b95e8d145eb196ba20033267a9ba43a17be02c/contracts/Zap.sol#L125 can be rewritten into

function _addLiquidity(ICurveFi pool, uint amount, uint numTokens, uint idx) internal {
        if (numTokens == 2) {
            uint[2] memory amounts;
            amounts[idx] = amount;
            pool.add_liquidity(amounts, 0);
        }

        else if (numTokens == 3) {
            uint[3] memory amounts;
            amounts[idx] = amount;
            pool.add_liquidity(amounts, 0);
        }

        else if (numTokens == 4) {
            uint[4] memory amounts;
            amounts[idx] = amount;
            pool.add_liquidity(amounts, 0);
        }
    }
GalloDaSballo commented 2 years ago

Would like to see proof to this statement, why does it save gas?

0xleastwood commented 2 years ago

I imagine gas savings could be generated on this one by limiting the number of comparisons the function makes. If an earlier branch is entered, subsequent branches are not executed and the function will instead return.