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
Rank: 10/43
Findings: 3
Award: $523.37
🌟 Selected for report: 0
🚀 Solo Findings: 0
22.0499 USDC - $22.05
https://github.com/code-423n4/2022-04-phuture/blob/main/contracts/ChainlinkPriceOracle.sol#L83
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)
https://github.com/code-423n4/2022-04-phuture/blob/main/contracts/ChainlinkPriceOracle.sol#L83
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
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
🌟 Selected for report: IllIllI
Also found by: 0v3rf10w, 0xDjango, 0xkatana, Dravee, Kenshin, Tadashi, TerrierLover, abhinavmir, defsec, ellahi, fatima_naz, foobar, gzeon, hyh, joestakey, kebabsec, kenta, minhquanym, oyc_109, rayn, robee, sseefried, xpriment626, z3s
359.1979 USDC - $359.20
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
Navigate to the following contract.
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);
Code Review
Consider using safeTransfer/safeTransferFrom or require() consistently.
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.
https://github.com/code-423n4/2022-04-phuture/blob/47cd226c80842585542599a3b56cc2a26b519d8a/contracts/PhutureIndex.sol#L55
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.
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.
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/)
None
Add events to all functions that change critical parameters.
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.
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++) {
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.
The critical procedures should be two step process.
https://github.com/code-423n4/2022-04-phuture/blob/47cd226c80842585542599a3b56cc2a26b519d8a/contracts/PhuturePriceOracle.sol#L55
Code Review
Lack of two-step procedure for critical operations leaves them error-prone. Consider adding two step procedure on the critical functions.
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.
./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;
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.
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.
https://github.com/code-423n4/2022-04-phuture/blob/47cd226c80842585542599a3b56cc2a26b519d8a/contracts/vToken.sol#L210
Manual Code Review
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.
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;
Manual code review
Lock the pragma version: delete pragma solidity 0.8.10 in favor of pragma solidity 0.8.10
Missing checks for zero-addresses may lead to infunctional protocol, if the variable addresses are updated incorrectly.
./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
Code Review
Consider adding zero-address checks in the discussed constructors: require(newAddr != address(0));.
On the UniswapV2PathPriceOracle contract, there is not setter function on the oracles addresses. This can cause misfunctionality on the uniswap oracle contract.
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!
🌟 Selected for report: IllIllI
Also found by: 0v3rf10w, 0xDjango, 0xNazgul, 0xkatana, Dravee, Kenshin, MaratCerby, Tadashi, TerrierLover, Tomio, TrungOre, defsec, ellahi, fatherOfBlocks, fatima_naz, gzeon, joestakey, kenta, minhquanym, oyc_109, rayn, rfa, robee, simon135, slywaters, windhustler, z3s
142.1175 USDC - $142.12
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.
Revert strings > 32 bytes are here:
https://github.com/code-423n4/2022-04-phuture/blob/main/contracts/UniswapV2PriceOracle.sol#L46
Manual Review
Shorten the revert strings to fit in 32 bytes. That will affect gas optimization.
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.
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++) {
None
Consider applying unchecked arithmetic where overflow/underflow is not possible. Example can be seen from below.
Unchecked{i++};
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.
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) {
None
Consider to cache array length.
Strict inequalities add a check of non equality which costs around 3 gas.
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++) {
Code Review
Use >= or <= instead of > and < when possible.
That would Increase gas costs on all privileged operations.
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)
Code Review
Consider to change the variable to be immutable rather than constant.
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.
contracts/IndexLogic.sol::139 => vToken.transfer(address(vToken), accountBalance); contracts/vToken.sol::210 => _NAV.transfer(_from, _to, _amount);
All Contracts
None
Consider checking amount != 0.
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.
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++) {
Code Review
uint x = 0 costs more gas than uint x without having any different functionality.
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.
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
None
A division/multiplication by any number x being a power of 2 can be calculated by shifting log2(x) to the right/left.
> 0 can be replaced with != 0 for gas optimization
!= 0
is a cheaper operation compared to > 0
, when dealing with uint.
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) {
Code Review
Use "!=0" instead of ">0" for the gas optimization.
Using newer compiler versions and the optimizer gives gas optimizations and additional safety checks are available for free.
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
None
Consider to upgrade pragma to at least 0.8.10.
++i is more gas efficient than i++ in loops forwarding.
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++) {
Code Review
It is recommend to use unchecked{++i} and change i declaration to uint256.
Using double require instead of operator && can save more gas.
https://github.com/code-423n4/2022-04-phuture/blob/47cd226c80842585542599a3b56cc2a26b519d8a/contracts/ManagedIndexReweightingLogic.sol#L30
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