code-423n4 / 2022-05-cudos-findings

1 stars 0 forks source link

Gas Optimizations #169

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

Gas Optimization for Cudos (May-05) by PeritoFlores

[G-01] Avoid initializing integers to 0

Initializing integers to zero consumes gas an is unnecessary. This is important as many of those function are called inside a loop .

https://github.com/code-423n4/2022-05-cudos/blob/de39cf3cd1f1e1cf211819b06d4acf6a043acda0/solidity/contracts/Gravity.sol#L54

https://github.com/code-423n4/2022-05-cudos/blob/de39cf3cd1f1e1cf211819b06d4acf6a043acda0/solidity/contracts/Gravity.sol#L54

https://github.com/code-423n4/2022-05-cudos/blob/de39cf3cd1f1e1cf211819b06d4acf6a043acda0/solidity/contracts/Gravity.sol#L231

https://github.com/code-423n4/2022-05-cudos/blob/de39cf3cd1f1e1cf211819b06d4acf6a043acda0/solidity/contracts/Gravity.sol#L233

https://github.com/code-423n4/2022-05-cudos/blob/de39cf3cd1f1e1cf211819b06d4acf6a043acda0/solidity/contracts/Gravity.sol#L263

https://github.com/code-423n4/2022-05-cudos/blob/de39cf3cd1f1e1cf211819b06d4acf6a043acda0/solidity/contracts/Gravity.sol#L453

https://github.com/code-423n4/2022-05-cudos/blob/de39cf3cd1f1e1cf211819b06d4acf6a043acda0/solidity/contracts/Gravity.sol#L568

https://github.com/code-423n4/2022-05-cudos/blob/de39cf3cd1f1e1cf211819b06d4acf6a043acda0/solidity/contracts/Gravity.sol#L579

[G-02] Optimize code at checkValidatorSignatures

In the function checkValidatorSignatures at some part of your code you can revert just inside the loop to avoid calculating twice cumulativePower > _powerThreshold

   // Break early to avoid wasting gas
    if (cumulativePower > _powerThreshold) {
      break;
    }
  }
}
// Check that there was enough power
require(
  cumulativePower > _powerThreshold,
  "Submitted validator set signatures do not have enough power."
);
// Success
}

Recommended

Modify break for

 revert("Submitted validator set signatures do not have enough power.")

[G-03] Remove Safe Math library and some usages

​ As you are using solidity >= 0.8 it is not necessary to use SafeMath so you can remove

Recommended

Remove

import "@openzeppelin/contracts/math/SafeMath.sol";

using SafeMath for uint256;

Replace

[-] totalFee = totalFee.add(_fees[i]);  #L455
[+] totalFee = totalFee + _fees[i];  

The following line is repeated at #L349, 465, 585, 601, 621

[-] state_lastEventNonce = state_lastEventNonce.add(1); 

[+] state_lastEventNonce++;
V-Staykov commented 2 years ago

[G-02] Is a good catch, but the solution is not right. When cumulativePower > _powerThreshold we expect the function to pass and not revert. The revert should only happen when the loop finishes and still the cumulitivePower has not reached the threshold.