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

ReentryProtection.sol Switching between 1, 2 instead of increasing lockCounter is more gas efficient #202

Open
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

The current implementation of ReentryProtection will increase lockCounter by one every time it's used.

https://github.com/code-423n4/2021-12-amun/blob/98f6e2ff91f5fcebc0489f5871183566feaec307/contracts/basket/contracts/facets/shared/Reentry/ReentryProtection.sol#L7-L18

modifier noReentry {
    // Use counter to only write to storage once
    LibReentryProtectionStorage.RPStorage storage s =
        LibReentryProtectionStorage.rpStorage();
    s.lockCounter++;
    uint256 lockValue = s.lockCounter;
    _;
    require(
        lockValue == s.lockCounter,
        "ReentryProtectionFacet.noReentry: reentry detected"
    );
}

A more gas efficient implementation would be switching between 1, 2.

By storing the original value once again, a refund is triggered (https://eips.ethereum.org/EIPS/eip-2200).

See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/86bd4d73896afcb35a205456e361436701823c7a/contracts/security/ReentrancyGuard.sol#L29-L33

Recommendation

Change to:

modifier noReentry {
    // Use counter to only write to storage once
    LibReentryProtectionStorage.RPStorage storage s =
        LibReentryProtectionStorage.rpStorage();
    s.lockCounter = 2;
    _;
    require(
        s.lockCounter == 2,
        "ReentryProtectionFacet.noReentry: reentry detected"
    );
    s.lockCounter = 1;
}
@code423n4 code423n4 added bug Something isn't working G (Gas Optimization) labels Dec 19, 2021
code423n4 added a commit that referenced this issue Dec 19, 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)
Projects
None yet
Development

No branches or pull requests

1 participant