Phuture Finance contest - defsec's results

Crypto index platform, that simplifies your investments through automated, themed index products.

General Information

Platform: Code4rena

Start Date: 19/04/2022

Pot Size: $30,000 USDC

Total HM: 10

Participants: 43

Period: 3 days

Judges: moose-code, JasoonS

Total Solo HM: 7

Id: 90

League: ETH

Phuture Finance

Findings Distribution

Researcher Performance

Rank: 10/43

Findings: 3

Award: $523.37

🌟 Selected for report: 0

🚀 Solo Findings: 0

Findings Information

Awards

22.0499 USDC - $22.05

Labels

bug
duplicate
2 (Med Risk)

External Links

Lines of code

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

Vulnerability details

Impact

The refreshedAssetPerBaseInUQ function in the contract ChainlinkPriceOracle.sol fetches the asset price from a Chainlink aggregator using the latestRoundData function. However, there are no checks on roundID nor timeStamp, resulting in stale prices. The oracle wrapper calls out to a chainlink oracle receiving the latestRoundData(). It then checks freshness by verifying that the answer is indeed for the last known round. The returned updatedAt timestamp is not checked.

If there is a problem with chainlink starting a new round and finding consensus on the new value for the oracle (e.g. chainlink nodes abandon the oracle, chain congestion, vulnerability/attacks on the chainlink system) consumers of this contract may continue using outdated stale data (if oracles are unable to submit no new round is started)

Proof of Concept

  1. Navigate to the following contract.

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

  1. Stale prices could put funds at risk. According to Chainlink's documentation, This function does not error if no answer has been reached but returns 0, causing an incorrect price fed to the PriceOracle. The external Chainlink oracle, which provides index price information to the system, introduces risk inherent to any dependency on third-party data sources. For example, the oracle could fall behind or otherwise fail to be maintained, resulting in outdated data being fed to the index price calculations of the AMM. Oracle reliance has historically resulted in crippled on-chain systems, and complications that lead to these outcomes can arise from things as simple as network congestion.

Medium Severity Issue From The FEI Protocol : https://consensys.net/diligence/audits/2021/09/fei-protocol-v2-phase-1/#chainlinkoraclewrapper-latestrounddata-might-return-stale-results

Tools Used

Code Review

Consider to add checks on the return data with proper revert messages if the price is stale or the round is incomplete, for example:

(uint80 roundID, int256 price, , uint256 timeStamp, uint80 answeredInRound) = ETH_CHAINLINK.latestRoundData(); require(price > 0, "Chainlink price <= 0"); require(answeredInRound >= roundID, "..."); require(timeStamp != 0, "...");

Consider checking the oracle responses updatedAt value after calling out to chainlinkOracle.latestRoundData() verifying that the result is within an allowed margin of freshness.

#0 - olivermehr

2022-05-02T20:02:28Z

Duplicate of #1

Awards

359.1979 USDC - $359.20

Labels

bug
QA (Quality Assurance)

External Links

C4-001 :Use safeTransfer/safeTransferFrom consistently instead of transfer/transferFrom

Impact - LOW

Impact

It is good to add a require() statement that checks the return value of token transfers or to use something like OpenZeppelin’s safeTransfer/safeTransferFrom unless one is sure the given token reverts in case of a failure. Failure to do so will cause silent failures of transfers and affect token accounting in contract.

Reference: This similar medium-severity finding from Consensys Diligence Audit of Fei Protocol: https://consensys.net/diligence/audits/2021/01/fei-protocol/#unchecked-return-value-for-iweth-transfer-call

Proof of Concept

  1. Navigate to the following contract.

  2. transfer/transferFrom functions are used instead of safe transfer/transferFrom on the following contracts.

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

Tools Used

Code Review

Consider using safeTransfer/safeTransferFrom or require() consistently.

C4-002 : Use of Block.timestamp

Impact - Non-Critical

Block timestamps have historically been used for a variety of applications, such as entropy for random numbers (see the Entropy Illusion for further details), locking funds for periods of time, and various state-changing conditional statements that are time-dependent. Miners have the ability to adjust timestamps slightly, which can prove to be dangerous if block timestamps are used incorrectly in smart contracts.

Proof of Concept

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

Tools Used

Manual Code Review

Block timestamps should not be used for entropy or generating random numbers—i.e., they should not be the deciding factor (either directly or through some derivation) for winning a game or changing an important state.

Time-sensitive logic is sometimes required; e.g., for unlocking contracts (time-locking), completing an ICO after a few weeks, or enforcing expiry dates. It is sometimes recommended to use block.number and an average block time to estimate times; with a 10 second block time, 1 week equates to approximately, 60480 blocks. Thus, specifying a block number at which to change a contract state can be more secure, as miners are unable to easily manipulate the block number.

C4-003 : Missing events for only functions that change critical parameters

Impact - Non critical

The afunctions that change critical parameters should emit events. Events allow capturing the changed parameters so that off-chain tools/interfaces can register such changes with timelocks that allow users to evaluate them and consider if they would like to engage/exit based on how they perceive the changes as affecting the trustworthiness of the protocol or profitability of the implemented financial services. The alternative of directly querying on-chain contract state for such changes is not considered practical for most users/usages.

Missing events and timelocks do not promote transparency and if such changes immediately affect users’ perception of fairness or trustworthiness, they could exit the protocol causing a reduction in liquidity which could negatively impact protocol TVL and reputation.

Proof of Concept

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

See similar High-severity H03 finding OpenZeppelin’s Audit of Audius (https://blog.openzeppelin.com/audius-contracts-audit/#high) and Medium-severity M01 finding OpenZeppelin’s Audit of UMA Phase 4 (https://blog.openzeppelin.com/uma-audit-phase-4/)

Tools Used

None

Add events to all functions that change critical parameters.

C4-004 : # DoS With Block Gas Limit

Impact - Non-Critical

When smart contracts are deployed or functions inside them are called, the execution of these actions always requires a certain amount of gas, based of how much computation is needed to complete them. The Ethereum network specifies a block gas limit and the sum of all transactions included in a block can not exceed the threshold.

Programming patterns that are harmless in centralized applications can lead to Denial of Service conditions in smart contracts when the cost of executing a function exceeds the block gas limit. Modifying an array of unknown size, that increases in size over time, can lead to such a Denial of Service condition.

Proof of Concept

  1. Follow the functions shown below.
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

Caution is advised when you expect to have large arrays that grow over time. Actions that require looping across the entire data structure should be avoided.

If you absolutely must loop over an array of unknown size, then you should plan for it to potentially take multiple blocks, and therefore require multiple transactions.

C4-005 : Critical changes should use two-step procedure

Impact - NON CRITICAL

The critical procedures should be two step process.

Proof of Concept

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

Tools Used

Code Review

Lack of two-step procedure for critical operations leaves them error-prone. Consider adding two step procedure on the critical functions.

C4-006 : Front-runnable Initializers

Impact - LOW

All contract initializers were missing access controls, allowing any user to initialize the contract. By front-running the contract deployers to initialize the contract, the incorrect parameters may be supplied, leaving the contract needing to be redeployed.

Proof of Concept

  1. Navigate to the following contracts.
./contracts/TrackedIndex.sol:25: function initialize( ./contracts/UniswapV2PriceOracle.sol:13:/// @dev Oracle works through base asset which is set in initialize function ./contracts/ManagedIndex.sol:27: function initialize(address[] calldata _assets, uint8[] calldata _weights) external { ./contracts/vToken.sol:55: function initialize(address _asset, address _registry) external override initializer { ./contracts/TopNMarketCapIndex.sol:37: function initialize( ./contracts/ChainlinkPriceOracle.sol:17:/// @dev Oracle works through base asset which is set in initialize function ./contracts/interfaces/IvToken.sol:18: function initialize(address _asset, address _registry) external;
  1. initialize functions does not have access control. They are vulnerable to front-running.

Tools Used

Manual Code Review

While the code that can be run in contract constructors is limited, setting the owner in the contract's constructor to the msg.sender and adding the onlyOwner modifier to all initializers would be a sufficient level of access control.

C4-007 : Incompatibility With Rebasing/Deflationary/Inflationary tokens

Impact - LOW

PrePo protocol do not appear to support rebasing/deflationary/inflationary tokens whose balance changes during transfers or over time. The necessary checks include at least verifying the amount of tokens transferred to contracts before and after the actual transfer to infer any fees/interest.

Proof of Concept

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

Tools Used

Manual Code Review

  • Ensure that to check previous balance/after balance equals to amount for any rebasing/inflation/deflation
  • Add support in contracts for such tokens before accepting user-supplied tokens
  • Consider supporting deflationary / rebasing / etc tokens by extra checking the balances before/after or strictly inform your users not to use such tokens if they don't want to lose them.

C4-008 : # Unlocked Pragma

Impact

In the contracts, floating pragmas are used. Contracts should be deployed with the same compiler version and flags that they have been tested with thoroughly. Locking the pragma helps to ensure that contracts do not accidentally get deployed using, for example, an outdated compiler version that might introduce bugs that affect the contract system negatively.

## Proof of Concept

https://swcregistry.io/docs/SWC-103

./contracts/UniswapV2PathPriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/IndexLayout.sol:3:pragma solidity >=0.8.7; ./contracts/TrackedIndexReweightingLogic.sol:3:pragma solidity >=0.8.7; ./contracts/BaseIndex.sol:3:pragma solidity >=0.8.7; ./contracts/TrackedIndex.sol:3:pragma solidity >=0.8.7; ./contracts/libraries/FixedPoint112.sol:3:pragma solidity >=0.8.7; ./contracts/libraries/BP.sol:3:pragma solidity >=0.8.7; ./contracts/libraries/NAV.sol:3:pragma solidity >=0.8.7; ./contracts/libraries/FullMath.sol:2:pragma solidity >=0.8.4 <0.9.0; ./contracts/libraries/AUMCalculationLibrary.sol:3:pragma solidity >=0.8.7; ./contracts/libraries/IndexLibrary.sol:3:pragma solidity >=0.8.7; ./contracts/TopNMarketCapReweightingLogic.sol:3:pragma solidity >=0.8.7; ./contracts/ManagedIndexReweightingLogic.sol:3:pragma solidity >=0.8.7; ./contracts/UniswapV2PriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/ManagedIndex.sol:3:pragma solidity >=0.8.7; ./contracts/IndexLogic.sol:3:pragma solidity >=0.8.7; ./contracts/PhuturePriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/vToken.sol:3:pragma solidity >=0.8.7; ./contracts/TopNMarketCapIndex.sol:3:pragma solidity >=0.8.7; ./contracts/ChainlinkPriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IIndexRegistry.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IAnatomyUpdater.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IManagedIndexReweightingLogic.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IvTokenFactory.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IChainlinkPriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IPriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/external/IChainLinkFeed.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/external/IWETH.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IFeePool.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IUniswapV2PathPriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IUniswapV2PriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IManagedIndex.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IReweightableIndex.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IPhuturePriceOracle.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IIndexLayout.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/ITopNMarketCapIndexFactory.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/ITopNMarketCapCategories.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IOrderer.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IIndexLogic.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IIndex.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IvToken.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/ITopNMarketCapIndexReweightingLogic.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/IIndexFactory.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/ITrackedIndexReweightingLogic.sol:3:pragma solidity >=0.8.7; ./contracts/interfaces/INameRegistry.sol:3:pragma solidity >=0.8.7; ./contracts/PhutureIndex.sol:3:pragma solidity >=0.8.7;

Tools Used

Manual code review

Lock the pragma version: delete pragma solidity 0.8.10 in favor of pragma solidity 0.8.10

C4-009 : # Missing zero-address check in the setter functions and initiliazers

Impact

Missing checks for zero-addresses may lead to infunctional protocol, if the variable addresses are updated incorrectly.

Proof of Concept

  1. Navigate to the following contracts.
./contracts/TrackedIndex.sol:25: function initialize( ./contracts/UniswapV2PriceOracle.sol:13:/// @dev Oracle works through base asset which is set in initialize function ./contracts/ManagedIndex.sol:27: function initialize(address[] calldata _assets, uint8[] calldata _weights) external { ./contracts/vToken.sol:55: function initialize(address _asset, address _registry) external override initializer { ./contracts/TopNMarketCapIndex.sol:37: function initialize( ./contracts/ChainlinkPriceOracle.sol:17:/// @dev Oracle works through base asset which is set in initialize function ./contracts/interfaces/IvToken.sol:18: function initialize(address _asset, address _registry) external; https://github.com/code-423n4/2022-04-phuture/blob/47cd226c80842585542599a3b56cc2a26b519d8a/contracts/UniswapV2PathPriceOracle.sol#L23

Tools Used

Code Review

Consider adding zero-address checks in the discussed constructors: require(newAddr != address(0));.

C4-010 : # Lack of setter function for the oracle

Impact

On the UniswapV2PathPriceOracle contract, there is not setter function on the oracles addresses. This can cause misfunctionality on the uniswap oracle contract.

Proof of Concept

  1. Navigate to "https://github.com/code-423n4/2022-04-phuture/blob/47cd226c80842585542599a3b56cc2a26b519d8a/contracts/UniswapV2PathPriceOracle.sol#L28" contract.
  2. Oracle addresses are set on the constructor.
  3. Setter function is missing on the contract. Misdeployed contract can cause failure of oracle integration.

Tools Used

None

Consider to add setter function for oracles addresses.

#0 - moose-code

2022-05-23T12:59:36Z

Couple things don't make sense "PrePo protocol do not appear to support rebasing/deflationary/inflationary tokens " "Lock the pragma version: delete pragma solidity 0.8.10 in favor of pragma solidity 0.8.10"

But overall a solid report!

Awards

142.1175 USDC - $142.12

Labels

bug
G (Gas Optimization)

External Links

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

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

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

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

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

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

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

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

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

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

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

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

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
AuditHub

A portfolio for auditors, a security profile for protocols, a hub for web3 security.

Built bymalatrax © 2024

Auditors

Browse

Contests

Browse

Get in touch

ContactTwitter