code-423n4 / 2022-04-phuture-findings

0 stars 0 forks source link

Gas Optimizations #69

Open code423n4 opened 2 years ago

code423n4 commented 2 years ago

C4-001: Revert String Size Optimization

Impact

Shortening revert strings to fit in 32 bytes will decrease deploy time gas and will decrease runtime gas when the revert condition has been met.

Revert strings that are longer than 32 bytes require at least one additional mstore, along with additional overhead for computing memory offset, etc.

Proof of Concept

Revert strings > 32 bytes are here:

https://github.com/code-423n4/2022-04-phuture/blob/main/contracts/UniswapV2PriceOracle.sol#L46

Tools Used

Manual Review

Recommended Mitigation Steps

Shorten the revert strings to fit in 32 bytes. That will affect gas optimization.

C4-002 : Adding unchecked directive can save gas

Impact

For the arithmetic operations that will never over/underflow, using the unchecked directive (Solidity v0.8 has default overflow/underflow checks) can save some gas from the unnecessary internal over/underflow checks.

Proof of Concept

  contracts/BaseIndex.sol::48 => if (data.length == 0) {
  contracts/BaseIndex.sol::64 => if (data.length == 0) {
  contracts/BaseIndex.sol::77 => _weights = new uint8[](_assets.length);
  contracts/BaseIndex.sol::78 => for (uint i; i < _assets.length; ++i) {
  contracts/IndexLogic.sol::39 => for (uint i; i < assets.length(); ++i) {
  contracts/IndexLogic.sol::60 => for (uint i; i < inactiveAssets.length(); ++i) {
  contracts/IndexLogic.sol::99 => uint length = assets.length();
  contracts/IndexLogic.sol::102 => for (uint i; i < length; ++i) {
  contracts/IndexLogic.sol::125 => for (uint i; i < length + inactiveAssets.length(); ++i) {
  contracts/IndexLogic.sol::126 => address asset = i < length ? assets.at(i) : inactiveAssets.at(i - length);
  contracts/ManagedIndex.sol::30 => for (uint i; i < _assets.length; ++i) {
  contracts/ManagedIndex.sol::53 => if (data.length == 0) {
  contracts/ManagedIndexReweightingLogic.sol::30 => _updatedAssets.length > 1 &&
  contracts/ManagedIndexReweightingLogic.sol::31 => _updatedWeights.length == _updatedAssets.length &&
  contracts/ManagedIndexReweightingLogic.sol::32 => _updatedAssets.length <= IIndexRegistry(registry).maxComponents(),
  contracts/ManagedIndexReweightingLogic.sol::38 => for (uint i; i < assets.length(); ++i) {
  contracts/ManagedIndexReweightingLogic.sol::50 => for (uint i; i < _updatedAssets.length; ++i) {
  contracts/ManagedIndexReweightingLogic.sol::96 => for (uint i; i < _inactiveAssets.length; ++i) {
  contracts/TopNMarketCapIndex.sol::48 => for (uint i; i < _assets.length; ++i) {
  contracts/TopNMarketCapIndex.sol::49 => uint _i = _assets.length - 1 - i;
  contracts/TopNMarketCapIndex.sol::73 => if (data.length == 0) {
  contracts/TopNMarketCapReweightingLogic.sol::37 => for (uint i; i < assets.length(); ++i) {
  contracts/TopNMarketCapReweightingLogic.sol::104 => for (uint i; i < _inactiveAssets.length; ++i) {
  contracts/TrackedIndex.sol::35 => for (uint i; i < _assets.length; ++i) {
  contracts/TrackedIndex.sol::62 => if (data.length == 0) {
  contracts/TrackedIndexReweightingLogic.sol::37 => for (uint i; i < assets.length(); ++i) {
  contracts/TrackedIndexReweightingLogic.sol::66 => for (uint i; i < assets.length(); ++i) {
  contracts/UniswapV2PathPriceOracle.sol::24 => require(_path.length >= 2, "UniswapV2PathPriceOracle: PATH");
  contracts/UniswapV2PathPriceOracle.sol::25 => require(_oracles.length == _path.length - 1, "UniswapV2PathPriceOracle: ORACLES");
  contracts/UniswapV2PathPriceOracle.sol::34 => for (uint i = 0; i < path.length - 1; i++) {
  contracts/UniswapV2PathPriceOracle.sol::49 => for (uint i = 0; i < path.length - 1; i++) {

Tools Used

None

Recommended Mitigation Steps

Consider applying unchecked arithmetic where overflow/underflow is not possible. Example can be seen from below.

Unchecked{i++};

C4-003 : Cache array length in for loops can save gas

Impact

Reading array length at each iteration of the loop takes 6 gas (3 for mload and 3 to place memory_offset) in the stack.

Caching the array length in the stack saves around 3 gas per iteration.

Proof of Concept

  1. Navigate to the following smart contract line.
  contracts/TrackedIndexReweightingLogic.sol::37 => for (uint i; i < assets.length(); ++i) {
  contracts/TrackedIndexReweightingLogic.sol::66 => for (uint i; i < assets.length(); ++i) {
  contracts/UniswapV2PathPriceOracle.sol::24 => require(_path.length >= 2, "UniswapV2PathPriceOracle: PATH");
  contracts/UniswapV2PathPriceOracle.sol::25 => require(_oracles.length == _path.length - 1, "UniswapV2PathPriceOracle: ORACLES");
  contracts/UniswapV2PathPriceOracle.sol::34 => for (uint i = 0; i < path.length - 1; i++) {
  contracts/UniswapV2PathPriceOracle.sol::49 => for (uint i = 0; i < path.length - 1; i++) {
contracts/ManagedIndexReweightingLogic.sol::31 => _updatedWeights.length == _updatedAssets.length &&
  contracts/ManagedIndexReweightingLogic.sol::32 => _updatedAssets.length <= IIndexRegistry(registry).maxComponents(),
  contracts/ManagedIndexReweightingLogic.sol::38 => for (uint i; i < assets.length(); ++i) {
  contracts/ManagedIndexReweightingLogic.sol::50 => for (uint i; i < _updatedAssets.length; ++i) {
  contracts/ManagedIndexReweightingLogic.sol::96 => for (uint i; i < _inactiveAssets.length; ++i) {

Tools Used

None

Recommended Mitigation Steps

Consider to cache array length.

C4-004 : Non-strict inequalities are cheaper than strict ones

Impact

Strict inequalities add a check of non equality which costs around 3 gas.

Proof of Concept

  contracts/BaseIndex.sol::78 => for (uint i; i < _assets.length; ++i) {
  contracts/IndexLogic.sol::39 => for (uint i; i < assets.length(); ++i) {
  contracts/IndexLogic.sol::60 => for (uint i; i < inactiveAssets.length(); ++i) {
  contracts/IndexLogic.sol::99 => uint length = assets.length();
  contracts/IndexLogic.sol::102 => for (uint i; i < length; ++i) {
  contracts/IndexLogic.sol::125 => for (uint i; i < length + inactiveAssets.length(); ++i) {
  contracts/IndexLogic.sol::126 => address asset = i < length ? assets.at(i) : inactiveAssets.at(i - length);
  contracts/ManagedIndex.sol::30 => for (uint i; i < _assets.length; ++i) {
  contracts/ManagedIndex.sol::53 => if (data.length == 0) {
  contracts/ManagedIndexReweightingLogic.sol::30 => _updatedAssets.length > 1 &&
  contracts/ManagedIndexReweightingLogic.sol::31 => _updatedWeights.length == _updatedAssets.length &&
  contracts/ManagedIndexReweightingLogic.sol::32 => _updatedAssets.length <= IIndexRegistry(registry).maxComponents(),
  contracts/ManagedIndexReweightingLogic.sol::38 => for (uint i; i < assets.length(); ++i) {
  contracts/ManagedIndexReweightingLogic.sol::50 => for (uint i; i < _updatedAssets.length; ++i) {
  contracts/ManagedIndexReweightingLogic.sol::96 => for (uint i; i < _inactiveAssets.length; ++i) {
  contracts/TopNMarketCapIndex.sol::48 => for (uint i; i < _assets.length; ++i) {
  contracts/TopNMarketCapIndex.sol::49 => uint _i = _assets.length - 1 - i;
  contracts/TopNMarketCapIndex.sol::73 => if (data.length == 0) {
  contracts/TopNMarketCapReweightingLogic.sol::37 => for (uint i; i < assets.length(); ++i) {
  contracts/TopNMarketCapReweightingLogic.sol::104 => for (uint i; i < _inactiveAssets.length; ++i) {
  contracts/TrackedIndex.sol::35 => for (uint i; i < _assets.length; ++i) {
  contracts/TrackedIndex.sol::62 => if (data.length == 0) {
  contracts/TrackedIndexReweightingLogic.sol::37 => for (uint i; i < assets.length(); ++i) {
  contracts/TrackedIndexReweightingLogic.sol::66 => for (uint i; i < assets.length(); ++i) {
  contracts/UniswapV2PathPriceOracle.sol::24 => require(_path.length >= 2, "UniswapV2PathPriceOracle: PATH");
  contracts/UniswapV2PathPriceOracle.sol::25 => require(_oracles.length == _path.length - 1, "UniswapV2PathPriceOracle: ORACLES");
  contracts/UniswapV2PathPriceOracle.sol::34 => for (uint i = 0; i < path.length - 1; i++) {
  contracts/UniswapV2PathPriceOracle.sol::49 => for (uint i = 0; i < path.length - 1; i++) {

Tools Used

Code Review

Recommended Mitigation Steps

Use >= or <= instead of > and < when possible.

C4-005: Use of constant keccak variables results in extra hashing (and so gas).

Impact

That would Increase gas costs on all privileged operations.

Proof of Concept

The following role variables are marked as constant.

 contracts/BaseIndex.sol::25 => bytes32 internal constant INDEX_MANAGER_ROLE = keccak256("INDEX_MANAGER_ROLE");
  contracts/ChainlinkPriceOracle.sol::29 => bytes32 private constant ASSET_MANAGER_ROLE = keccak256("ASSET_MANAGER_ROLE");
  contracts/IndexLogic.sol::25 => bytes32 internal constant ASSET_ROLE = keccak256("ASSET_ROLE");
  contracts/IndexLogic.sol::27 => bytes32 internal constant SKIPPED_ASSET_ROLE = keccak256("SKIPPED_ASSET_ROLE");
  contracts/ManagedIndex.sol::20 => REWEIGHT_INDEX_ROLE = keccak256(abi.encodePacked("REWEIGHT_PERMISSION", address(this)));
  contracts/ManagedIndexReweightingLogic.sol::25 => bytes32 internal constant ASSET_ROLE = keccak256("ASSET_ROLE");
  contracts/PhuturePriceOracle.sol::21 => bytes32 private constant ASSET_MANAGER_ROLE = keccak256("ASSET_MANAGER_ROLE");
  contracts/TopNMarketCapIndex.sol::18 => bytes32 internal constant ORDERER_ROLE = keccak256("ORDERER_ROLE");
  contracts/TopNMarketCapReweightingLogic.sol::27 => bytes32 internal constant ASSET_ROLE = keccak256("ASSET_ROLE");
  contracts/TrackedIndex.sol::17 => bytes32 internal constant ORDERER_ROLE = keccak256("ORDERER_ROLE");
  contracts/TrackedIndexReweightingLogic.sol::25 => bytes32 internal constant ASSET_ROLE = keccak256("ASSET_ROLE");
  contracts/vToken.sol::27 => bytes32 private constant INDEX_ROLE = keccak256("INDEX_ROLE");
  contracts/vToken.sol::29 => bytes32 private constant ORACLE_ROLE = keccak256("ORACLE_ROLE");
  contracts/vToken.sol::31 => bytes32 private constant ORDERER_ROLE = keccak256("ORDERER_ROLE");
  contracts/vToken.sol::33 => bytes32 private constant RESERVE_MANAGER_ROLE = keccak256("RESERVE_MANAGER_ROLE");

This results in the keccak operation being performed whenever the variable is used, increasing gas costs relative to just storing the output hash. Changing to immutable will only perform hashing on contract deployment which will save gas.

See: ethereum/solidity#9232 (https://github.com/ethereum/solidity/issues/9232#issuecomment-646131646)

Tools Used

Code Review

Recommended Mitigation Steps

Consider to change the variable to be immutable rather than constant.

C4-006 : Check if amount > 0 before token transfer can save gas

Impact

Since _amount can be 0. Checking if (_amount != 0) before the transfer can potentially save an external call and the unnecessary gas cost of a 0 token transfer.

Proof of Concept

  contracts/IndexLogic.sol::139 => vToken.transfer(address(vToken), accountBalance);
  contracts/vToken.sol::210 => _NAV.transfer(_from, _to, _amount);

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider checking amount != 0.

C4-007 : There is no need to assign default values to variables

Impact - Gas Optimization

When a variable is declared solidity assigns the default value. In case the contract assigns the value again, it costs extra gas.

Example: uint x = 0 costs more gas than uint x without having any different functionality.

Proof of Concept

  contracts/UniswapV2PathPriceOracle.sol::34 => for (uint i = 0; i < path.length - 1; i++) {
  contracts/UniswapV2PathPriceOracle.sol::49 => for (uint i = 0; i < path.length - 1; i++) {

Tools Used

Code Review

Recommended Mitigation Steps

uint x = 0 costs more gas than uint x without having any different functionality.

C4-008 : Use Shift Right/Left instead of Division/Multiplication if possible

Impact

A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.

While the DIV opcode uses 5 gas, the SHR opcode only uses 3 gas. Furthermore, Solidity's division operation also includes a division-by-0 prevention which is bypassed using shifting.

Proof of Concept

  1. Navigate to the following smart contract line.
  contracts/libraries/FullMath.sol::92 => inv *= 2 - denominator * inv; // inverse mod 2**8
  contracts/libraries/FullMath.sol::97 => inv *= 2 - denominator * inv; // inverse mod 2**256

Tools Used

None

Recommended Mitigation Steps

A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.

C4-009: > 0 can be replaced with != 0 for gas optimization

Impact

!= 0 is a cheaper operation compared to > 0, when dealing with uint.

Proof of Concept

  1. Navigate to the following contracts.
  contracts/ChainlinkPriceOracle.sol::86 => require(basePrice > 0 && quotePrice > 0, "ChainlinkPriceOracle: NEGATIVE");
  contracts/IndexLogic.sol::76 => require(lastAssetBalanceInBase > 0, "Index: INSUFFICIENT_AMOUNT");
  contracts/IndexLogic.sol::86 => if (fee > 0) {
  contracts/IndexLogic.sol::98 => require(value > 0, "Index: INSUFFICIENT_AMOUNT");
  contracts/IndexLogic.sol::114 => if (fee > 0) {
  contracts/IndexLogic.sol::141 => if (lastOrderId > 0) {
  contracts/ManagedIndexReweightingLogic.sol::56 => if (i > 0) {
  contracts/ManagedIndexReweightingLogic.sol::61 => if (newWeight > 0) {
  contracts/ManagedIndexReweightingLogic.sol::98 => if (shares > 0) {
  contracts/PhutureIndex.sol::56 => if (timePassed > 0) {
  contracts/PhutureIndex.sol::64 => if (fee > 0) {
  contracts/TopNMarketCapIndex.sol::56 => if (weight > 0) {
  contracts/TopNMarketCapReweightingLogic.sol::58 => if (shares > 0) {
  contracts/TopNMarketCapReweightingLogic.sol::79 => if (weight > 0) {
  contracts/TopNMarketCapReweightingLogic.sol::106 => if (shares > 0) {
  contracts/libraries/FullMath.sol::35 => require(denominator > 0);
  contracts/libraries/FullMath.sol::122 => if (mulmod(a, b, denominator) > 0) {
  contracts/libraries/IndexLibrary.sol::29 => require(_assetPerBaseInUQ > 0, "IndexLibrary: ORACLE");
  contracts/libraries/NAV.sol::49 => require(shares > 0, "NAV: INSUFFICIENT_AMOUNT");
  contracts/libraries/NAV.sol::59 => require(amount > 0, "NAV: INSUFFICIENT_SHARES_BURNED");
  contracts/vToken.sol::160 => if (_totalSupply > 0) {

Tools Used

Code Review

Recommended Mitigation Steps

Use "!=0" instead of ">0" for the gas optimization.

C4-0010 : Free gas savings for using solidity 0.8.10+

Impact

Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks are available for free.

Proof of Concept

All Contracts

Solidity 0.8.10 has a useful change which reduced gas costs of external calls which expect a return value: https://blog.soliditylang.org/2021/11/09/solidity-0.8.10-release-announcement/

Code Generator: Skip existence check for external contract if return data is expected. In this case, the ABI decoder will revert if the contract does not exist

All Contracts

Tools Used

None

Recommended Mitigation Steps

Consider to upgrade pragma to at least 0.8.10.

C4-0011 : ++i is more gas efficient than i++ in loops forwarding

Impact

++i is more gas efficient than i++ in loops forwarding.

Proof of Concept

  1. Navigate to the following contracts.
  contracts/UniswapV2PathPriceOracle.sol::34 => for (uint i = 0; i < path.length - 1; i++) {
  contracts/UniswapV2PathPriceOracle.sol::49 => for (uint i = 0; i < path.length - 1; i++) {

Tools Used

Code Review

Recommended Mitigation Steps

It is recommend to use unchecked{++i} and change i declaration to uint256.

C4-0012 : Using operator && used more gas

Impact

Using double require instead of operator && can save more gas.

Proof of Concept

  1. Navigate to the following contracts.
https://github.com/code-423n4/2022-04-phuture/blob/47cd226c80842585542599a3b56cc2a26b519d8a/contracts/ManagedIndexReweightingLogic.sol#L30

Tools Used

Code Review

Recommended Mitigation Steps

Example


using &&:

function check(uint x)public view{
    require(x == 0 && x < 1 );
}
// gas cost 21630

using double require:

    require(x == 0 );
    require( x < 1);
    }
}
// gas cost 21622