20,000 USDC
View results
Submission Details
Severity: gas
Valid

Removing an unnecessary check for gas savings

Gas Issue Details

The Staking::update() will be invoked every time the following functions are executed.

  • Staking::update() -- the function itself

  • Staking::updateFor()

  • Staking::deposit()

  • Staking::withdraw()

  • Staking::claim()

The "if (_diff > 0) { ... }" condition check in the update() is unnecessary since the _diff variable will always be more than 0 due to the outer "if (_balance > balance) { ... }" condition check.

function update() public {
uint256 totalSupply = TKN.balanceOf(address(this));
if (totalSupply > 0) {
uint256 _balance = WETH.balanceOf(address(this));
if (_balance > balance) {
uint256 _diff = _balance - balance;
@> if (_diff > 0) {
uint256 _ratio = _diff * 1e18 / totalSupply;
if (_ratio > 0) {
index = index + _ratio;
balance = _balance;
}
@> }
}
}
}

https://github.com/Cyfrin/2023-07-beedle/blob/658e046bda8b010a5b82d2d85e824f3823602d27/src/Staking.sol#L67

Gas Improvements

I recommend removing the "if (_diff > 0) { ... }" condition check for gas savings, as shown below.

function update() public {
uint256 totalSupply = TKN.balanceOf(address(this));
if (totalSupply > 0) {
uint256 _balance = WETH.balanceOf(address(this));
if (_balance > balance) {
uint256 _diff = _balance - balance;
- if (_diff > 0) {
uint256 _ratio = _diff * 1e18 / totalSupply;
if (_ratio > 0) {
index = index + _ratio;
balance = _balance;
}
- }
}
}
}

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.