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 unnecessary storage read can save gas #112

Closed
code423n4 opened this issue Oct 27, 2021 · 0 comments
Closed

Avoid unnecessary storage read can save gas #112

code423n4 opened this issue Oct 27, 2021 · 0 comments
Labels
bug Something isn't working G (Gas Optimization) sponsor confirmed Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity")

Comments

@code423n4
Copy link
Contributor

Handle

WatchPug

Vulnerability details

https://github.com/code-423n4/2021-10-mochi/blob/8458209a52565875d8b2cefcb611c477cefb9253/projects/mochi-core/contracts/vault/MochiVault.sol#L85-L111

function accrueDebt(uint256 _id) public {
    // global debt for vault
    // first, increase gloabal debt;
    uint256 currentIndex = liveDebtIndex();
    uint256 increased = (debts * currentIndex) / debtIndex - debts;
    debts += increased;
    claimable += int256(increased);
    // update global debtIndex
    debtIndex = currentIndex;
    lastAccrued = block.timestamp;
    // individual debt
    if (_id != type(uint256).max && details[_id].debtIndex < debtIndex) {
        require(details[_id].status != Status.Invalid, "invalid");
        if (details[_id].debt != 0) {
            uint256 increasedDebt = (details[_id].debt * debtIndex) /
                details[_id].debtIndex -
                details[_id].debt;
            uint256 discountedDebt = increasedDebt.multiply(
                engine.discountProfile().discount(engine.nft().ownerOf(_id))
            );
            debts -= discountedDebt;
            claimable -= int256(discountedDebt);
            details[_id].debt += (increasedDebt - discountedDebt);
        }
        details[_id].debtIndex = debtIndex;
    }
}

At L93, debtIndex is set as currentIndex, therefore, at L96, L99, and L109 storage variable debtIndex can be changed to local variable currentIndex to avoid unnecessary storage read to save some gas.

@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels Oct 27, 2021
code423n4 added a commit that referenced this issue Oct 27, 2021
@r2moon r2moon added the sponsor confirmed Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity") label Oct 29, 2021
@leekt leekt closed this as completed Nov 16, 2021
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) sponsor confirmed Sponsor agrees this is a problem and intends to fix it (OK to use w/ "disagree with severity")
Projects
None yet
Development

No branches or pull requests

3 participants