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

Avoid repeated arithmetic operations in for loop can save gas #205

Open
code423n4 opened this issue Dec 19, 2021 · 0 comments
Open

Avoid repeated arithmetic operations in for loop can save gas #205

code423n4 opened this issue Dec 19, 2021 · 0 comments
Labels
bug Something isn't working G (Gas Optimization)

Comments

@code423n4
Copy link
Contributor

Handle

WatchPug

Vulnerability details

https://github.com/code-423n4/2021-12-amun/blob/98f6e2ff91f5fcebc0489f5871183566feaec307/contracts/basket/contracts/facets/Basket/BasketFacet.sol#L158-L168

uint256 feeAmount = _amount.mul(bs.entryFee).div(10**18);

for (uint256 i; i < bs.tokens.length; i++) {
    IERC20 token = bs.tokens[i];
    uint256 tokenAmount =
        balance(address(token)).mul(_amount.add(feeAmount)).div(
            totalSupply
        );
    require(tokenAmount != 0, "AMOUNT_TOO_SMALL");
    token.safeTransferFrom(msg.sender, address(this), tokenAmount);
}

_amount.add(feeAmount) is being recalculated each in the for loop, which is unnecessary.

https://github.com/code-423n4/2021-12-amun/blob/98f6e2ff91f5fcebc0489f5871183566feaec307/contracts/basket/contracts/facets/Basket/BasketFacet.sol#L200-L213

uint256 feeAmount = _amount.mul(bs.exitFee).div(10**18);

for (uint256 i; i < bs.tokens.length; i++) {
    IERC20 token = bs.tokens[i];
    uint256 tokenBalance = balance(address(token));
    // redeem less tokens if there is an exit fee
    uint256 tokenAmount =
        tokenBalance.mul(_amount.sub(feeAmount)).div(totalSupply);
    require(
        tokenBalance.sub(tokenAmount) >= MIN_AMOUNT,
        "TOKEN_BALANCE_TOO_LOW"
    );
    token.safeTransfer(msg.sender, tokenAmount);
}

_amount.sub(feeAmount) is being recalculated each in the for loop, which is unnecessary and gas consuming.

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

1 participant