name
stringlengths 5
231
| severity
stringclasses 3
values | description
stringlengths 107
68.2k
| recommendation
stringlengths 12
8.75k
⌀ | impact
stringlengths 3
11.2k
⌀ | function
stringlengths 15
64.6k
|
---|---|---|---|---|---|
RocketDAONodeTrustedUpgrade - inconsistent upgrade blacklist | medium | `upgradeContract` defines a hardcoded list of contracts that cannot be upgraded because they manage their own settings (statevars) or they hold value in the system.\\nthe list is hardcoded and cannot be extended when new contracts are added via `addcontract`. E.g. what if another contract holding value is added to the system? This would require an upgrade of the upgrade contract to update the whitelist (gas hungry, significant risk of losing access to the upgrade mechanisms if a bug is being introduced).\\na contract named `rocketPoolToken` is blacklisted from being upgradeable but the system registers no contract called `rocketPoolToken`. This may be an oversight or artifact of a previous iteration of the code. However, it may allow a malicious group of nodes to add a contract that is not yet in the system which cannot be removed anymore as there is no `removeContract` functionality and `upgradeContract` to override the malicious contract will fail due to the blacklist.\\nNote that upgrading `RocketTokenRPL` requires an account balance migration as contracts in the system may hold value in `RPL` (e.g. a lot in AuctionManager) that may vanish after an upgrade. The contract is not exempt from upgrading. A migration may not be easy to perform as the system cannot be paused to e.g. snapshot balances.\\n```\\nfunction \\_upgradeContract(string memory \\_name, address \\_contractAddress, string memory \\_contractAbi) internal {\\n // Check contract being upgraded\\n bytes32 nameHash = keccak256(abi.encodePacked(\\_name));\\n require(nameHash != keccak256(abi.encodePacked("rocketVault")), "Cannot upgrade the vault");\\n require(nameHash != keccak256(abi.encodePacked("rocketPoolToken")), "Cannot upgrade token contracts");\\n require(nameHash != keccak256(abi.encodePacked("rocketTokenRETH")), "Cannot upgrade token contracts");\\n require(nameHash != keccak256(abi.encodePacked("rocketTokenNETH")), "Cannot upgrade token contracts");\\n require(nameHash != keccak256(abi.encodePacked("casperDeposit")), "Cannot upgrade the casper deposit contract");\\n // Get old contract address & check contract exists\\n```\\n | Consider implementing a whitelist of contracts that are allowed to be upgraded instead of a more error-prone blacklist of contracts that cannot be upgraded.\\nProvide documentation that outlines what contracts are upgradeable and why.\\nCreate a process to verify the blacklist before deploying/operating the system.\\nPlan for migration paths when upgrading contracts in the system\\nAny proposal that reaches the upgrade contract must be scrutinized for potential malicious activity (e.g. as any registered contract can directly modify storage or may contain subtle backdoors. Upgrading without performing a thorough security inspection may easily put the DAO at risk) | null | ```\\nfunction \\_upgradeContract(string memory \\_name, address \\_contractAddress, string memory \\_contractAbi) internal {\\n // Check contract being upgraded\\n bytes32 nameHash = keccak256(abi.encodePacked(\\_name));\\n require(nameHash != keccak256(abi.encodePacked("rocketVault")), "Cannot upgrade the vault");\\n require(nameHash != keccak256(abi.encodePacked("rocketPoolToken")), "Cannot upgrade token contracts");\\n require(nameHash != keccak256(abi.encodePacked("rocketTokenRETH")), "Cannot upgrade token contracts");\\n require(nameHash != keccak256(abi.encodePacked("rocketTokenNETH")), "Cannot upgrade token contracts");\\n require(nameHash != keccak256(abi.encodePacked("casperDeposit")), "Cannot upgrade the casper deposit contract");\\n // Get old contract address & check contract exists\\n```\\n |
RocketMinipoolStatus - DAO Membership changes can result in votes getting stuck | medium | Changes in the DAO's trusted node members are reflected in the `RocketDAONodeTrusted.getMemberCount()` function. When compared with the vote on consensus threshold, a DAO-driven decision is made, e.g., when updating token price feeds and changing Minipool states.\\nEspecially in the early phase of the DAO, the functions below can get stuck as execution is restricted to DAO members who have not voted yet. Consider the following scenario:\\nThe DAO consists of five members\\nTwo members vote to make a Minipool withdrawable\\nThe other three members are inactive, the community votes, and they get kicked from the DAO\\nThe two remaining members have no way to change the Minipool state now. All method calls to trigger the state update fails because the members have already voted before.\\nNote: votes of members that are kicked/leave are still count towards the quorum!\\nSetting a Minipool into the withdrawable state:\\n```\\nRocketDAONodeTrustedInterface rocketDAONodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted"));\\nif (calcBase.mul(submissionCount).div(rocketDAONodeTrusted.getMemberCount()) >= rocketDAOProtocolSettingsNetwork.getNodeConsensusThreshold()) {\\n setMinipoolWithdrawable(\\_minipoolAddress, \\_stakingStartBalance, \\_stakingEndBalance);\\n}\\n```\\n\\nSubmitting a block's network balances:\\n```\\nRocketDAONodeTrustedInterface rocketDAONodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted"));\\nif (calcBase.mul(submissionCount).div(rocketDAONodeTrusted.getMemberCount()) >= rocketDAOProtocolSettingsNetwork.getNodeConsensusThreshold()) {\\n updateBalances(\\_block, \\_totalEth, \\_stakingEth, \\_rethSupply);\\n}\\n```\\n\\nSubmitting a block's RPL price information:\\n```\\nRocketDAONodeTrustedInterface rocketDAONodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted"));\\nif (calcBase.mul(submissionCount).div(rocketDAONodeTrusted.getMemberCount()) >= rocketDAOProtocolSettingsNetwork.getNodeConsensusThreshold()) {\\n updatePrices(\\_block, \\_rplPrice);\\n}\\n```\\n | Resolution\\nThis issue has been fixed in PR https://github.com/ConsenSys/rocketpool-audit-2021-03/issues/204 by introducing a public method that allows anyone to manually trigger a DAO consensus threshold check and a subsequent balance update in case the issue's example scenario occurs.\\nThe conditional check and update of price feed information, Minipool state transition, etc., should be externalized into a separate public function. This function is also called internally in the existing code. In case the DAO gets into the scenario above, anyone can call the function to trigger a reevaluation of the condition with updated membership numbers and thus get the process unstuck. | null | ```\\nRocketDAONodeTrustedInterface rocketDAONodeTrusted = RocketDAONodeTrustedInterface(getContractAddress("rocketDAONodeTrusted"));\\nif (calcBase.mul(submissionCount).div(rocketDAONodeTrusted.getMemberCount()) >= rocketDAOProtocolSettingsNetwork.getNodeConsensusThreshold()) {\\n setMinipoolWithdrawable(\\_minipoolAddress, \\_stakingStartBalance, \\_stakingEndBalance);\\n}\\n```\\n |
Trusted/Oracle-Nodes can vote multiple times for different outcomes | medium | Trusted/oracle nodes submit various ETH2 observations to the RocketPool contracts. When 51% of nodes submitted the same observation, the result is stored in the contract. However, while it is recorded that a node already voted for a specific minipool (being withdrawable & balance) or block (price/balance), a re-submission with different parameters for the same minipool/block is not rejected.\\nSince the oracle values should be distinct, clear, and there can only be one valid value, it should not be allowed for trusted nodes to change their mind voting for multiple different outcomes within one block or one minipool\\n`RocketMinipoolStatus` - a trusted node can submit multiple different results for one minipool\\nNote that `setBool(keccak256(abi.encodePacked("minipool.withdrawable.submitted.node", msg.sender, _minipoolAddress)), true);` is recorded but never checked. (as for the other two instances)\\n```\\n// Get submission keys\\nbytes32 nodeSubmissionKey = keccak256(abi.encodePacked("minipool.withdrawable.submitted.node", msg.sender, \\_minipoolAddress, \\_stakingStartBalance, \\_stakingEndBalance));\\nbytes32 submissionCountKey = keccak256(abi.encodePacked("minipool.withdrawable.submitted.count", \\_minipoolAddress, \\_stakingStartBalance, \\_stakingEndBalance));\\n// Check & update node submission status\\nrequire(!getBool(nodeSubmissionKey), "Duplicate submission from node");\\nsetBool(nodeSubmissionKey, true);\\nsetBool(keccak256(abi.encodePacked("minipool.withdrawable.submitted.node", msg.sender, \\_minipoolAddress)), true);\\n// Increment submission count\\nuint256 submissionCount = getUint(submissionCountKey).add(1);\\nsetUint(submissionCountKey, submissionCount);\\n```\\n\\n`RocketNetworkBalances` - a trusted node can submit multiple different results for the balances at a specific block\\n```\\n// Get submission keys\\nbytes32 nodeSubmissionKey = keccak256(abi.encodePacked("network.balances.submitted.node", msg.sender, \\_block, \\_totalEth, \\_stakingEth, \\_rethSupply));\\nbytes32 submissionCountKey = keccak256(abi.encodePacked("network.balances.submitted.count", \\_block, \\_totalEth, \\_stakingEth, \\_rethSupply));\\n// Check & update node submission status\\nrequire(!getBool(nodeSubmissionKey), "Duplicate submission from node");\\nsetBool(nodeSubmissionKey, true);\\nsetBool(keccak256(abi.encodePacked("network.balances.submitted.node", msg.sender, \\_block)), true);\\n// Increment submission count\\nuint256 submissionCount = getUint(submissionCountKey).add(1);\\nsetUint(submissionCountKey, submissionCount);\\n// Emit balances submitted event\\nemit BalancesSubmitted(msg.sender, \\_block, \\_totalEth, \\_stakingEth, \\_rethSupply, block.timestamp);\\n// Check submission count & update network balances\\n```\\n\\n`RocketNetworkPrices` - a trusted node can submit multiple different results for the price at a specific block\\n```\\n// Get submission keys\\nbytes32 nodeSubmissionKey = keccak256(abi.encodePacked("network.prices.submitted.node", msg.sender, \\_block, \\_rplPrice));\\nbytes32 submissionCountKey = keccak256(abi.encodePacked("network.prices.submitted.count", \\_block, \\_rplPrice));\\n// Check & update node submission status\\nrequire(!getBool(nodeSubmissionKey), "Duplicate submission from node");\\nsetBool(nodeSubmissionKey, true);\\nsetBool(keccak256(abi.encodePacked("network.prices.submitted.node", msg.sender, \\_block)), true);\\n// Increment submission count\\nuint256 submissionCount = getUint(submissionCountKey).add(1);\\nsetUint(submissionCountKey, submissionCount);\\n// Emit prices submitted event\\nemit PricesSubmitted(msg.sender, \\_block, \\_rplPrice, block.timestamp);\\n// Check submission count & update network prices\\n```\\n | Only allow one vote per minipool/block. Don't give nodes the possibility to vote multiple times for different outcomes. | null | ```\\n// Get submission keys\\nbytes32 nodeSubmissionKey = keccak256(abi.encodePacked("minipool.withdrawable.submitted.node", msg.sender, \\_minipoolAddress, \\_stakingStartBalance, \\_stakingEndBalance));\\nbytes32 submissionCountKey = keccak256(abi.encodePacked("minipool.withdrawable.submitted.count", \\_minipoolAddress, \\_stakingStartBalance, \\_stakingEndBalance));\\n// Check & update node submission status\\nrequire(!getBool(nodeSubmissionKey), "Duplicate submission from node");\\nsetBool(nodeSubmissionKey, true);\\nsetBool(keccak256(abi.encodePacked("minipool.withdrawable.submitted.node", msg.sender, \\_minipoolAddress)), true);\\n// Increment submission count\\nuint256 submissionCount = getUint(submissionCountKey).add(1);\\nsetUint(submissionCountKey, submissionCount);\\n```\\n |
RocketTokenNETH - Pot. discrepancy between minted tokens and deposited collateral | medium | The `nETH` token is paid to node operators when minipool becomes withdrawable. `nETH` is supposed to be backed by `ETH` 1:1. However, in most cases, this will not be the case.\\nThe `nETH` minting and deposition of collateral happens in two different stages of a minipool. `nETH` is minted in the minipool state transition from `Staking` to `Withdrawable` when the trusted/oracle nodes find consensus on the fact that the minipool became withdrawable (submitWinipoolWithdrawable).\\n```\\nif (calcBase.mul(submissionCount).div(rocketDAONodeTrusted.getMemberCount()) >= rocketDAOProtocolSettingsNetwork.getNodeConsensusThreshold()) {\\n setMinipoolWithdrawable(\\_minipoolAddress, \\_stakingStartBalance, \\_stakingEndBalance);\\n}\\n```\\n\\nWhen consensus is found on the state of the `minipool`, `nETH` tokens are minted to the `minipool` address according to the withdrawal amount observed by the trusted/oracle nodes. At this stage, `ETH` backing the newly minted `nETH` was not yet provided.\\n```\\nuint256 nodeAmount = getMinipoolNodeRewardAmount(\\n minipool.getNodeFee(),\\n userDepositBalance,\\n minipool.getStakingStartBalance(),\\n minipool.getStakingEndBalance()\\n);\\n// Mint nETH to minipool contract\\nif (nodeAmount > 0) { rocketTokenNETH.mint(nodeAmount, \\_minipoolAddress); }\\n```\\n\\nThe `nETH` token contract now holds more `nETH.totalsupply` than actual `ETH` collateral. It is out of sync with the `ETH` reserve and therefore becomes undercollateralized. This should generally be avoided as the security guarantees that for every `nETH` someone deposited, `ETH` does not hold. However, the newly minted `nETH` is locked to the `minipoolAddress`, and the minipool has no means of redeeming the `nETH` for `ETH` directly (via nETH.burn()).\\nThe transition from Withdrawable to `Destroyed` the actual collateral for the previously minted `nETH` (still locked to minipoolAddress) is provided by the `Eth2` withdrawal contract. There is no specification for the withdrawal contract as of now. Still, it is assumed that some entity triggers the payout for the `Eth2` rewards on the withdrawal contract, which sends the amount of `ETH` to the configured withdrawal address (the minipoolAddress).\\nThe `minipool.receive()` function receives the `ETH`\\n```\\nreceive() external payable {\\n (bool success, bytes memory data) = getContractAddress("rocketMinipoolDelegate").delegatecall(abi.encodeWithSignature("receiveValidatorBalance()"));\\n if (!success) { revert(getRevertMessage(data)); }\\n}\\n```\\n\\nand forwards it to `minipooldelegate.receiveValidatorBalance`\\n```\\nrequire(msg.sender == rocketDAOProtocolSettingsNetworkInterface.getSystemWithdrawalContractAddress(), "The minipool's validator balance can only be sent by the eth1 system withdrawal contract");\\n// Set validator balance withdrawn status\\nvalidatorBalanceWithdrawn = true;\\n// Process validator withdrawal for minipool\\nrocketNetworkWithdrawal.processWithdrawal{value: msg.value}();\\n```\\n\\nWhich calculates the `nodeAmount` based on the `ETH` received and submits it as collateral to back the previously minted `nodeAmount` of `nETH`.\\n```\\nuint256 totalShare = rocketMinipoolManager.getMinipoolWithdrawalTotalBalance(msg.sender);\\nuint256 nodeShare = rocketMinipoolManager.getMinipoolWithdrawalNodeBalance(msg.sender);\\nuint256 userShare = totalShare.sub(nodeShare);\\n// Get withdrawal amounts based on shares\\nuint256 nodeAmount = 0;\\nuint256 userAmount = 0;\\nif (totalShare > 0) {\\n nodeAmount = msg.value.mul(nodeShare).div(totalShare);\\n userAmount = msg.value.mul(userShare).div(totalShare);\\n}\\n// Set withdrawal processed status\\nrocketMinipoolManager.setMinipoolWithdrawalProcessed(msg.sender);\\n// Transfer node balance to nETH contract\\nif (nodeAmount > 0) { rocketTokenNETH.depositRewards{value: nodeAmount}(); }\\n// Transfer user balance to rETH contract or deposit pool\\n```\\n\\nLooking at how the `nodeAmount` of `nETH` that was minted was calculated and comparing it to how `nodeAmount` of `ETH` is calculated, we can observe the following:\\nthe `nodeAmount` of `nETH` minted is an absolute number of tokens based on the rewards observed by the trusted/oracle nodes. the `nodeAmount` is stored in the storage and later used to calculate the collateral deposit in a later step.\\nthe `nodeAmount` calculated when depositing the collateral is first assumed to be a `nodeShare` (line 47), while it is actually an absolute number. the `nodeShare` is then turned into a `nodeAmount` relative to the `ETH` supplied to the contract.\\nDue to rounding errors, this might not always exactly match the `nETH` minted (see https://github.com/ConsenSys/rocketpool-audit-2021-03/issues/26).\\nThe collateral calculation is based on the `ETH` value provided to the contract. If this value does not exactly match what was reported by the oracle/trusted nodes when minting `nETH`, less/more collateral will be provided.\\nNote: excess collateral will be locked in the `nETH` contract as it is unaccounted for in the `nETH` token contract and therefore cannot be redeemed.\\nNote: providing less collateral will go unnoticed and mess up the 1:1 `nETH:ETH` peg. In the worst case, there will be less `nETH` than `ETH`. Not everybody will be able to redeem their `ETH`.\\nNote: keep in mind that the `receive()` function might be subject to gas restrictions depending on the implementation of the withdrawal contract (.call() vs. .transfer())\\nThe `nETH` minted is initially uncollateralized and locked to the `minipoolAddress`, which cannot directly redeem it for `ETH`. The next step (next stage) is collateralized with the staking rewards (which, as noted, might not always completely add up to the minted nETH). At the last step in `withdraw()`, the `nETH` is transferred to the `withdrawalAddress` of the minipool.\\n```\\nuint256 nethBalance = rocketTokenNETH.balanceOf(address(this));\\nif (nethBalance > 0) {\\n // Get node withdrawal address\\n RocketNodeManagerInterface rocketNodeManager = RocketNodeManagerInterface(getContractAddress("rocketNodeManager"));\\n address nodeWithdrawalAddress = rocketNodeManager.getNodeWithdrawalAddress(nodeAddress);\\n // Transfer\\n require(rocketTokenNETH.transfer(nodeWithdrawalAddress, nethBalance), "nETH balance was not successfully transferred to node operator");\\n // Emit nETH withdrawn event\\n emit NethWithdrawn(nodeWithdrawalAddress, nethBalance, block.timestamp);\\n}\\n```\\n\\nSince the `nETH` initially minted can never take part in the `nETH` token market (as it is locked to the minipool address, which can only transfer it to the withdrawal address in the last step), the question arises why it is actually minted early in the lifecycle of the minipool. At the same time, it could as well be just directly minted to `withdrawalAddress` when providing the right amount of collateral in the last step of the minipool lifecycle. Furthermore, if `nETH` is minted at this stage, it should be questioned why `nETH` is actually needed when you can directly forward the `nodeAmount` to the `withdrawalAddress` instead of minting an intermediary token that is pegged 1:1 to `ETH`.\\nFor reference, `depositRewards` (providing collateral) and `mint` are not connected at all, hence the risk of `nETH` being an undercollateralized token.\\n```\\nfunction depositRewards() override external payable onlyLatestContract("rocketNetworkWithdrawal", msg.sender) {\\n // Emit ether deposited event\\n emit EtherDeposited(msg.sender, msg.value, block.timestamp);\\n}\\n\\n// Mint nETH\\n// Only accepts calls from the RocketMinipoolStatus contract\\nfunction mint(uint256 \\_amount, address \\_to) override external onlyLatestContract("rocketMinipoolStatus", msg.sender) {\\n // Check amount\\n require(\\_amount > 0, "Invalid token mint amount");\\n // Update balance & supply\\n \\_mint(\\_to, \\_amount);\\n // Emit tokens minted event\\n emit TokensMinted(\\_to, \\_amount, block.timestamp);\\n}\\n```\\n | It looks like `nETH` might not be needed at all, and it should be discussed if the added complexity of having a potentially out-of-sync `nETH` token contract is necessary and otherwise remove it from the contract system as the `nodeAmount` of `ETH` can directly be paid out to the `withdrawalAddress` in the `receiveValidatorBalance` or `withdraw` transitions.\\nIf `nETH` cannot be removed, consider minting `nodeAmount` of `nETH` directly to `withdrawalAddress` on `withdraw` instead of first minting uncollateralized tokens. This will also reduce the gas footprint of the Minipool.\\nEnsure that the initial `nodeAmount` calculation matches the minted `nETH` and deposited to the contract as collateral (absolute amount vs. fraction).\\nEnforce that `nETH` requires collateral to be provided when minting tokens. | null | ```\\nif (calcBase.mul(submissionCount).div(rocketDAONodeTrusted.getMemberCount()) >= rocketDAOProtocolSettingsNetwork.getNodeConsensusThreshold()) {\\n setMinipoolWithdrawable(\\_minipoolAddress, \\_stakingStartBalance, \\_stakingEndBalance);\\n}\\n```\\n |
RocketMiniPoolDelegate - on destroy() leftover ETH is sent to RocketVault where it cannot be recovered | medium | When destroying the `MiniPool`, leftover `ETH` is sent to the `RocketVault`. Since `RocketVault` has no means to recover “unaccounted” `ETH` (not deposited via depositEther), funds forcefully sent to the vault will end up being locked.\\n```\\n// Destroy the minipool\\nfunction destroy() private {\\n // Destroy minipool\\n RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));\\n rocketMinipoolManager.destroyMinipool();\\n // Self destruct & send any remaining ETH to vault\\n selfdestruct(payable(getContractAddress("rocketVault")));\\n}\\n```\\n | Implement means to recover and reuse `ETH` that was forcefully sent to the contract by `MiniPool` instances. | null | ```\\n// Destroy the minipool\\nfunction destroy() private {\\n // Destroy minipool\\n RocketMinipoolManagerInterface rocketMinipoolManager = RocketMinipoolManagerInterface(getContractAddress("rocketMinipoolManager"));\\n rocketMinipoolManager.destroyMinipool();\\n // Self destruct & send any remaining ETH to vault\\n selfdestruct(payable(getContractAddress("rocketVault")));\\n}\\n```\\n |
RocketDAO - personally identifiable member information (PII) stored on-chain Acknowledged | medium | Like a DAO user's e-mail address, PII is stored on-chain and can, therefore, be accessed by anyone. This may allow de-pseudonymize users (and correlate Ethereum addresses to user email addresses) and be used for spamming or targeted phishing campaigns putting the DAO users at risk.\\nrocketpool-go-2.5-Tokenomics/dao/trustednode/dao.go:L173-L183\\n```\\n// Return\\nreturn MemberDetails{\\n Address: memberAddress,\\n Exists: exists,\\n ID: id,\\n Email: email,\\n JoinedBlock: joinedBlock,\\n LastProposalBlock: lastProposalBlock,\\n RPLBondAmount: rplBondAmount,\\n UnbondedValidatorCount: unbondedValidatorCount,\\n}, nil\\n```\\n\\n```\\nfunction getMemberEmail(address \\_nodeAddress) override public view returns (string memory) {\\n return getString(keccak256(abi.encodePacked(daoNameSpace, "member.email", \\_nodeAddress))); \\n}\\n```\\n | Avoid storing PII on-chain where it is readily available for anyone. | null | ```\\n// Return\\nreturn MemberDetails{\\n Address: memberAddress,\\n Exists: exists,\\n ID: id,\\n Email: email,\\n JoinedBlock: joinedBlock,\\n LastProposalBlock: lastProposalBlock,\\n RPLBondAmount: rplBondAmount,\\n UnbondedValidatorCount: unbondedValidatorCount,\\n}, nil\\n```\\n |
RocketPoolMinipool - should check for address(0x0) | medium | The two implementations for `getContractAddress()` in `Minipool/Delegate` are not checking whether the requested contract's address was ever set before. If it were never set, the method would return `address(0x0)`, which would silently make all delegatecalls succeed without executing any code. In contrast, `RocketBase.getContractAddress()` fails if the requested contract is not known.\\nIt should be noted that this can happen if `rocketMinipoolDelegate` is not set in global storage, or it was cleared afterward, or if `_rocketStorageAddress` points to a contract that implements a non-throwing fallback function (may not even be storage at all).\\nMissing checks\\n```\\nfunction getContractAddress(string memory \\_contractName) private view returns (address) {\\n return rocketStorage.getAddress(keccak256(abi.encodePacked("contract.address", \\_contractName)));\\n}\\n```\\n\\n```\\nfunction getContractAddress(string memory \\_contractName) private view returns (address) {\\n return rocketStorage.getAddress(keccak256(abi.encodePacked("contract.address", \\_contractName)));\\n}\\n```\\n\\nChecks implemented\\n```\\nfunction getContractAddress(string memory \\_contractName) internal view returns (address) {\\n // Get the current contract address\\n address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", \\_contractName)));\\n // Check it\\n require(contractAddress != address(0x0), "Contract not found");\\n // Return\\n return contractAddress;\\n}\\n```\\n | Resolution\\nAddressed in branch `rp3.0-updates` (rocket-pool/[email protected]b424ca1) by changing requiring that the contract address is not `0x0`.\\nSimilar to `RocketBase.getContractAddress()` require that the contract is set. | null | ```\\nfunction getContractAddress(string memory \\_contractName) private view returns (address) {\\n return rocketStorage.getAddress(keccak256(abi.encodePacked("contract.address", \\_contractName)));\\n}\\n```\\n |
RocketDAONodeTrustedAction - ambiguous event emitted in actionChallengeDecide | low | `actionChallengeDecide` succeeds and emits `challengeSuccess=False` in case the challenged node defeats the challenge. It also emits the same event if another node calls `actionChallengeDecided` before the refute window passed. This ambiguity may make a defeated challenge indistinguishable from a challenge that was attempted to be decided too early (unless the component listening for the event also checks the refute window).\\n```\\n // Allow the challenged member to refute the challenge at anytime. If the window has passed and the challenge node does not run this method, any member can decide the challenge and eject the absent member\\n // Is it the node being challenged?\\n if(\\_nodeAddress == msg.sender) {\\n // Challenge is defeated, node has responded\\n deleteUint(keccak256(abi.encodePacked(daoNameSpace, "member.challenged.block", \\_nodeAddress)));\\n }else{\\n // The challenge refute window has passed, the member can be ejected now\\n if(getUint(keccak256(abi.encodePacked(daoNameSpace, "member.challenged.block", \\_nodeAddress))).add(rocketDAONodeTrustedSettingsMembers.getChallengeWindow()) < block.number) {\\n // Node has been challenged and failed to respond in the given window, remove them as a member and their bond is burned\\n \\_memberRemove(\\_nodeAddress);\\n // Challenge was successful\\n challengeSuccess = true;\\n }\\n }\\n // Log it\\n emit ActionChallengeDecided(\\_nodeAddress, msg.sender, challengeSuccess, block.timestamp);\\n}\\n```\\n | Avoid ambiguities when emitting events. Consider throwing an exception in the else branch if the refute window has not passed yet (minimal gas savings; it's clear that the call failed; other components can rely on the event only being emitted if there was a decision. | null | ```\\n // Allow the challenged member to refute the challenge at anytime. If the window has passed and the challenge node does not run this method, any member can decide the challenge and eject the absent member\\n // Is it the node being challenged?\\n if(\\_nodeAddress == msg.sender) {\\n // Challenge is defeated, node has responded\\n deleteUint(keccak256(abi.encodePacked(daoNameSpace, "member.challenged.block", \\_nodeAddress)));\\n }else{\\n // The challenge refute window has passed, the member can be ejected now\\n if(getUint(keccak256(abi.encodePacked(daoNameSpace, "member.challenged.block", \\_nodeAddress))).add(rocketDAONodeTrustedSettingsMembers.getChallengeWindow()) < block.number) {\\n // Node has been challenged and failed to respond in the given window, remove them as a member and their bond is burned\\n \\_memberRemove(\\_nodeAddress);\\n // Challenge was successful\\n challengeSuccess = true;\\n }\\n }\\n // Log it\\n emit ActionChallengeDecided(\\_nodeAddress, msg.sender, challengeSuccess, block.timestamp);\\n}\\n```\\n |
RocketDAOProtocolProposals, RocketDAONodeTrustedProposals - unused enum ProposalType | low | The enum `ProposalType` is defined but never used.\\n```\\nenum ProposalType {\\n Invite, // Invite a registered node to join the trusted node DAO\\n Leave, // Leave the DAO\\n Replace, // Replace a current trusted node with a new registered node, they take over their bond\\n Kick, // Kick a member from the DAO with optional penalty applied to their RPL deposit\\n Setting // Change a DAO setting (Quorum threshold, RPL deposit size, voting periods etc)\\n}\\n```\\n\\n```\\nenum ProposalType {\\n Setting // Change a DAO setting (Node operator min/max fees, inflation rate etc)\\n}\\n```\\n | Remove unnecessary code. | null | ```\\nenum ProposalType {\\n Invite, // Invite a registered node to join the trusted node DAO\\n Leave, // Leave the DAO\\n Replace, // Replace a current trusted node with a new registered node, they take over their bond\\n Kick, // Kick a member from the DAO with optional penalty applied to their RPL deposit\\n Setting // Change a DAO setting (Quorum threshold, RPL deposit size, voting periods etc)\\n}\\n```\\n |
RocketDaoNodeTrusted - Unused events | low | The `MemberJoined` `MemberLeave` events are not used within `RocketDaoNodeTrusted`.\\n```\\n// Events\\nevent MemberJoined(address indexed \\_nodeAddress, uint256 \\_rplBondAmount, uint256 time); \\nevent MemberLeave(address indexed \\_nodeAddress, uint256 \\_rplBondAmount, uint256 time);\\n```\\n | Consider removing the events. Note: `RocketDAONodeTrustedAction` is emitting `ActionJoin` and `ActionLeave` event.s | null | ```\\n// Events\\nevent MemberJoined(address indexed \\_nodeAddress, uint256 \\_rplBondAmount, uint256 time); \\nevent MemberLeave(address indexed \\_nodeAddress, uint256 \\_rplBondAmount, uint256 time);\\n```\\n |
RocketDAOProposal - expired, and defeated proposals can be canceled | low | The `RocketDAOProposal.getState` function defaults a proposal's state to `ProposalState.Defeated`. While this fallback can be considered secure, the remaining code does not perform checks that prevent defeated proposals from changing their state. As such, a user can transition a proposal that is `Expired` or `Defeated` to `Cancelled` by using the `RocketDAOProposal.cancel` function. This can be used to deceive users and potentially bias future votes.\\nThe method emits an event that might trigger other components to perform actions.\\n```\\n} else {\\n // Check the votes, was it defeated?\\n // if (votesFor <= votesAgainst || votesFor < getVotesRequired(\\_proposalID))\\n return ProposalState.Defeated;\\n}\\n```\\n\\n```\\nfunction cancel(address \\_member, uint256 \\_proposalID) override public onlyDAOContract(getDAO(\\_proposalID)) {\\n // Firstly make sure this proposal that hasn't already been executed\\n require(getState(\\_proposalID) != ProposalState.Executed, "Proposal has already been executed");\\n // Make sure this proposal hasn't already been successful\\n require(getState(\\_proposalID) != ProposalState.Succeeded, "Proposal has already succeeded");\\n // Only allow the proposer to cancel\\n require(getProposer(\\_proposalID) == \\_member, "Proposal can only be cancelled by the proposer");\\n // Set as cancelled now\\n setBool(keccak256(abi.encodePacked(daoProposalNameSpace, "cancelled", \\_proposalID)), true);\\n // Log it\\n emit ProposalCancelled(\\_proposalID, \\_member, block.timestamp);\\n}\\n```\\n | Preserve the true outcome. Do not allow to cancel proposals that are already in an end-state like `canceled`, `expired`, `defeated`. | null | ```\\n} else {\\n // Check the votes, was it defeated?\\n // if (votesFor <= votesAgainst || votesFor < getVotesRequired(\\_proposalID))\\n return ProposalState.Defeated;\\n}\\n```\\n |
RocketDAOProposal - preserve the proposals correct state after expiration | low | The state of proposals is resolved to give a preference to a proposal being `expired` over the actual result which may be `defeated`. The preference for a proposal's status is checked in order: `cancelled? -> executed? -> `expired`? -> succeeded? -> pending? -> active? -> `defeated` (default)`\\n```\\nif (getCancelled(\\_proposalID)) {\\n // Cancelled by the proposer?\\n return ProposalState.Cancelled;\\n // Has it been executed?\\n} else if (getExecuted(\\_proposalID)) {\\n return ProposalState.Executed;\\n // Has it expired?\\n} else if (block.number >= getExpires(\\_proposalID)) {\\n return ProposalState.Expired;\\n // Vote was successful, is now awaiting execution\\n} else if (votesFor >= getVotesRequired(\\_proposalID)) {\\n return ProposalState.Succeeded;\\n // Is the proposal pending? Eg. waiting to be voted on\\n} else if (block.number <= getStart(\\_proposalID)) {\\n return ProposalState.Pending;\\n // The proposal is active and can be voted on\\n} else if (block.number <= getEnd(\\_proposalID)) {\\n return ProposalState.Active;\\n} else {\\n // Check the votes, was it defeated?\\n // if (votesFor <= votesAgainst || votesFor < getVotesRequired(\\_proposalID))\\n return ProposalState.Defeated;\\n}\\n```\\n | consider checking for `voteAgainst` explicitly and return `defeated` instead of `expired` if a proposal was `defeated` and is queried after expiration. Preserve the actual proposal result. | null | ```\\nif (getCancelled(\\_proposalID)) {\\n // Cancelled by the proposer?\\n return ProposalState.Cancelled;\\n // Has it been executed?\\n} else if (getExecuted(\\_proposalID)) {\\n return ProposalState.Executed;\\n // Has it expired?\\n} else if (block.number >= getExpires(\\_proposalID)) {\\n return ProposalState.Expired;\\n // Vote was successful, is now awaiting execution\\n} else if (votesFor >= getVotesRequired(\\_proposalID)) {\\n return ProposalState.Succeeded;\\n // Is the proposal pending? Eg. waiting to be voted on\\n} else if (block.number <= getStart(\\_proposalID)) {\\n return ProposalState.Pending;\\n // The proposal is active and can be voted on\\n} else if (block.number <= getEnd(\\_proposalID)) {\\n return ProposalState.Active;\\n} else {\\n // Check the votes, was it defeated?\\n // if (votesFor <= votesAgainst || votesFor < getVotesRequired(\\_proposalID))\\n return ProposalState.Defeated;\\n}\\n```\\n |
RocketRewardsPool - registerClaimer should check if a node is already disabled before decrementing rewards.pool.claim.interval.claimers.total.next | low | The other branch in `registerClaimer` does not check whether the provided `_claimerAddress` is already disabled (or invalid). This might lead to inconsistencies where `rewards.pool.claim.interval.claimers.total.next` is decremented because the caller provided an already deactivated address.\\nThis issue is flagged as `minor` since we have not found an exploitable version of this issue in the current codebase. However, we recommend safeguarding the implementation instead of relying on the caller to provide sane parameters. Registered Nodes cannot unregister, and Trusted Nodes are unregistered when they leave.\\n```\\nfunction registerClaimer(address \\_claimerAddress, bool \\_enabled) override external onlyClaimContract {\\n // The name of the claiming contract\\n string memory contractName = getContractName(msg.sender);\\n // Record the block they are registering at\\n uint256 registeredBlock = 0;\\n // How many users are to be included in next interval\\n uint256 claimersIntervalTotalUpdate = getClaimingContractUserTotalNext(contractName);\\n // Ok register\\n if(\\_enabled) {\\n // Make sure they are not already registered\\n require(getClaimingContractUserRegisteredBlock(contractName, \\_claimerAddress) == 0, "Claimer is already registered");\\n // Update block number\\n registeredBlock = block.number;\\n // Update the total registered claimers for next interval\\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.add(1));\\n }else{\\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.sub(1));\\n }\\n // Save the registered block\\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.block", contractName, \\_claimerAddress)), registeredBlock);\\n}\\n```\\n | Ensure that `getClaimingContractUserRegisteredBlock(contractName, _claimerAddress)` returns `!=0` before decrementing the `.total.next`. | null | ```\\nfunction registerClaimer(address \\_claimerAddress, bool \\_enabled) override external onlyClaimContract {\\n // The name of the claiming contract\\n string memory contractName = getContractName(msg.sender);\\n // Record the block they are registering at\\n uint256 registeredBlock = 0;\\n // How many users are to be included in next interval\\n uint256 claimersIntervalTotalUpdate = getClaimingContractUserTotalNext(contractName);\\n // Ok register\\n if(\\_enabled) {\\n // Make sure they are not already registered\\n require(getClaimingContractUserRegisteredBlock(contractName, \\_claimerAddress) == 0, "Claimer is already registered");\\n // Update block number\\n registeredBlock = block.number;\\n // Update the total registered claimers for next interval\\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.add(1));\\n }else{\\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.interval.claimers.total.next", contractName)), claimersIntervalTotalUpdate.sub(1));\\n }\\n // Save the registered block\\n setUint(keccak256(abi.encodePacked("rewards.pool.claim.contract.registered.block", contractName, \\_claimerAddress)), registeredBlock);\\n}\\n```\\n |
RocketNetworkPrices - Price feed update lacks block number sanity check | low | Trusted nodes submit the RPL price feed. The function is called specifying a block number and the corresponding RPL price for that block. If a DAO vote goes through for that block-price combination, it is written to storage. In the unlikely scenario that a vote confirms a very high block number such as `uint(-1)`, all future price updates will fail due to the `require` check below.\\nThis issue becomes less likely the more active members the DAO has. Thus, it's considered a minor issue that mainly affects the initial bootstrapping process.\\n```\\n// Check block\\nrequire(\\_block > getPricesBlock(), "Network prices for an equal or higher block are set");\\n```\\n | The function's `_block` parameter should be checked to prevent large block numbers from being submitted. This check could, e.g., specify that node operators are only allowed to submit price updates for a maximum of x blocks ahead of `block.number`. | null | ```\\n// Check block\\nrequire(\\_block > getPricesBlock(), "Network prices for an equal or higher block are set");\\n```\\n |
RocketDepositPool - Potential gasDoS in assignDeposits Acknowledged | low | `assignDeposits` seems to be a gas heavy function, with many external calls in general, and few of them are inside the for loop itself. By default, `rocketDAOProtocolSettingsDeposit.getMaximumDepositAssignments()` returns `2`, which is not a security concern. Through a DAO vote, the settings key `deposit.assign.maximum` can be set to a value that exhausts the block gas limit and effectively deactivates the deposit assignment process.\\n```\\nfor (uint256 i = 0; i < rocketDAOProtocolSettingsDeposit.getMaximumDepositAssignments(); ++i) {\\n // Get & check next available minipool capacity\\n```\\n | The `rocketDAOProtocolSettingsDeposit.getMaximumDepositAssignments()` return value could be cached outside the loop. Additionally, a check should be added that prevents unreasonably high values. | null | ```\\nfor (uint256 i = 0; i < rocketDAOProtocolSettingsDeposit.getMaximumDepositAssignments(); ++i) {\\n // Get & check next available minipool capacity\\n```\\n |
RocketNetworkWithdrawal - ETH dust lockup due to rounding errors | low | There's a potential `ETH` dust lockup when processing a withdrawal due to rounding errors when performing a division.\\n```\\nuint256 totalShare = rocketMinipoolManager.getMinipoolWithdrawalTotalBalance(msg.sender);\\nuint256 nodeShare = rocketMinipoolManager.getMinipoolWithdrawalNodeBalance(msg.sender);\\nuint256 userShare = totalShare.sub(nodeShare);\\n// Get withdrawal amounts based on shares\\nuint256 nodeAmount = 0;\\nuint256 userAmount = 0;\\nif (totalShare > 0) {\\n nodeAmount = msg.value.mul(nodeShare).div(totalShare);\\n userAmount = msg.value.mul(userShare).div(totalShare);\\n}\\n```\\n | Calculate `userAmount` as `msg.value - nodeAmount` instead. This should also save some gas. | null | ```\\nuint256 totalShare = rocketMinipoolManager.getMinipoolWithdrawalTotalBalance(msg.sender);\\nuint256 nodeShare = rocketMinipoolManager.getMinipoolWithdrawalNodeBalance(msg.sender);\\nuint256 userShare = totalShare.sub(nodeShare);\\n// Get withdrawal amounts based on shares\\nuint256 nodeAmount = 0;\\nuint256 userAmount = 0;\\nif (totalShare > 0) {\\n nodeAmount = msg.value.mul(nodeShare).div(totalShare);\\n userAmount = msg.value.mul(userShare).div(totalShare);\\n}\\n```\\n |
RocketAuctionManager - calcBase should be declared constant | low | Declaring the same constant value `calcBase` multiple times as local variables to some methods in `RocketAuctionManager` carries the risk that if that value is ever updated, one of the value assignments might be missed. It is therefore highly recommended to reduce duplicate code and declare the value as a public constant. This way, it is clear that the same `calcBase` is used throughout the contract, and there is a single point of change in case it ever needs to be changed.\\n```\\nfunction getLotPriceByTotalBids(uint256 \\_index) override public view returns (uint256) {\\n uint256 calcBase = 1 ether;\\n return calcBase.mul(getLotTotalBidAmount(\\_index)).div(getLotTotalRPLAmount(\\_index));\\n}\\n```\\n\\n```\\nfunction getLotClaimedRPLAmount(uint256 \\_index) override public view returns (uint256) {\\n uint256 calcBase = 1 ether;\\n return calcBase.mul(getLotTotalBidAmount(\\_index)).div(getLotCurrentPrice(\\_index));\\n}\\n```\\n\\n```\\n// Calculation base value\\nuint256 calcBase = 1 ether;\\n```\\n\\n```\\nuint256 bidAmount = msg.value;\\nuint256 calcBase = 1 ether;\\n```\\n\\n```\\n// Calculate RPL claim amount\\nuint256 calcBase = 1 ether;\\nuint256 rplAmount = calcBase.mul(bidAmount).div(currentPrice);\\n```\\n | Consider declaring `calcBase` as a private const state var instead of re-declaring it with the same value in multiple, multiple functions. Constant, literal state vars are replaced in a preprocessing step and do not require significant additional gas when accessed than normal state vars. | null | ```\\nfunction getLotPriceByTotalBids(uint256 \\_index) override public view returns (uint256) {\\n uint256 calcBase = 1 ether;\\n return calcBase.mul(getLotTotalBidAmount(\\_index)).div(getLotTotalRPLAmount(\\_index));\\n}\\n```\\n |
RocketDAO* - daoNamespace is missing a trailing dot; should be declared constant/immutable | low | `string private daoNameSpace = 'dao.trustednodes'` is missing a trailing dot, or else there's no separator when concatenating the namespace with the vars.\\nrequests `dao.trustednodesmember.index` instead of `dao.trustednodes.member.index`\\n```\\nfunction getMemberAt(uint256 \\_index) override public view returns (address) {\\n AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));\\n return addressSetStorage.getItem(keccak256(abi.encodePacked(daoNameSpace, "member.index")), \\_index);\\n}\\n```\\n\\n```\\n// The namespace for any data stored in the trusted node DAO (do not change)\\nstring private daoNameSpace = 'dao.trustednodes';\\n```\\n\\n```\\n// Calculate using this as the base\\nuint256 private calcBase = 1 ether;\\n\\n// The namespace for any data stored in the trusted node DAO (do not change)\\nstring private daoNameSpace = 'dao.trustednodes';\\n```\\n\\n```\\n// The namespace for any data stored in the network DAO (do not change)\\nstring private daoNameSpace = 'dao.protocol';\\n```\\n | Remove the `daoNameSpace` and add the prefix to the respective variables directly. | null | ```\\nfunction getMemberAt(uint256 \\_index) override public view returns (address) {\\n AddressSetStorageInterface addressSetStorage = AddressSetStorageInterface(getContractAddress("addressSetStorage"));\\n return addressSetStorage.getItem(keccak256(abi.encodePacked(daoNameSpace, "member.index")), \\_index);\\n}\\n```\\n |
RocketVault - consider rejecting zero amount deposit/withdrawal requests | low | Consider disallowing zero amount token transfers unless the system requires this to work. In most cases, zero amount token transfers will emit an event (that potentially triggers off-chain components). In some cases, they allow the caller without holding any balance to call back to themselves (pot. reentrancy) or the caller provided token address.\\n`depositEther` allows to deposit zero ETH\\nemits `EtherDeposited`\\n`withdrawEther` allows to withdraw zero ETH\\ncalls back to `withdrawer` (msg.sender)!\\nemits `EtherWithdrawn`\\n(depositToken checks for amount >0)\\n`withdrawToken` allows zero amount token withdrawals\\ncalls into user provided (actually a network contract) tokenAddress)\\nemits `TokenWithdrawn`\\n`transferToken` allows zero amount token transfers\\nemits `TokenTransfer`\\n```\\nfunction depositEther() override external payable onlyLatestNetworkContract {\\n // Get contract key\\n bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender)));\\n // Update contract balance\\n etherBalances[contractKey] = etherBalances[contractKey].add(msg.value);\\n // Emit ether deposited event\\n emit EtherDeposited(contractKey, msg.value, block.timestamp);\\n}\\n```\\n | Zero amount transfers are no-operation calls in most cases and should be avoided. However, as all vault actions are authenticated (to registered system contracts), the risk of something going wrong is rather low. Nevertheless, it is recommended to deny zero amount transfers to avoid running code unnecessarily (gas consumption), emitting unnecessary events, or potentially call back to callers/token address for ineffective transfers. | null | ```\\nfunction depositEther() override external payable onlyLatestNetworkContract {\\n // Get contract key\\n bytes32 contractKey = keccak256(abi.encodePacked(getContractName(msg.sender)));\\n // Update contract balance\\n etherBalances[contractKey] = etherBalances[contractKey].add(msg.value);\\n // Emit ether deposited event\\n emit EtherDeposited(contractKey, msg.value, block.timestamp);\\n}\\n```\\n |
RocketVault - methods returning static return values and unchecked return parameters | low | The `Token*` methods in `RocketVault` either throw or return `true`, but they can never return `false`. If the method fails, it will always throw. Therefore, it is questionable if the static return value is needed at all. Furthermore, callees are in most cases not checking the return value of\\nstatic return value `true`\\n```\\n// Emit token transfer\\nemit TokenDeposited(contractKey, \\_tokenAddress, \\_amount, block.timestamp);\\n// Done\\nreturn true;\\n```\\n\\n```\\nemit TokenWithdrawn(contractKey, \\_tokenAddress, \\_amount, block.timestamp);\\n// Done\\nreturn true;\\n```\\n\\n```\\n// Emit token withdrawn event\\nemit TokenTransfer(contractKeyFrom, contractKeyTo, \\_tokenAddress, \\_amount, block.timestamp);\\n// Done\\nreturn true;\\n```\\n\\nreturn value not checked\\n```\\nrocketVault.depositToken("rocketNodeStaking", rplTokenAddress, \\_amount);\\n// Update RPL stake amounts & node RPL staked block\\n```\\n\\n```\\nrocketVault.withdrawToken(msg.sender, getContractAddress("rocketTokenRPL"), rplAmount);\\n```\\n\\n```\\nrocketVault.withdrawToken(msg.sender, getContractAddress("rocketTokenRPL"), \\_amount);\\n```\\n\\n```\\nrocketVault.transferToken("rocketAuctionManager", getContractAddress("rocketTokenRPL"), rplSlashAmount);\\n```\\n | Define a clear interface for these functions. Remove the static return value in favor of having the method throw on failure (which is already the current behavior). | null | ```\\n// Emit token transfer\\nemit TokenDeposited(contractKey, \\_tokenAddress, \\_amount, block.timestamp);\\n// Done\\nreturn true;\\n```\\n |
RocketMinipoolDelegate - enforce that the delegate contract cannot be called directly | low | This contract is not meant to be consumed directly and will only be delegate called from `Minipool`. Being able to call it directly might even create the problem that, in the worst case, someone might be able to `selfdestruct` the contract rendering all other contracts that link to it dysfunctional. This might even not be easily detectable because `delegatecall` to an EOA will act as a NOP.\\nThe access control checks on the methods currently prevent methods from being called directly on the delegate. They require state variables to be set correctly, or the delegate is registered as a valid minipool in the system. Both conditions are improbable to be fulfilled, hence, mitigation any security risk. However, it looks like this is more of a side-effect than a design decision, and we would recommend not explicitly stating that the delegate contract cannot be used directly.\\n```\\nconstructor(address \\_rocketStorageAddress) {\\n // Initialise RocketStorage\\n require(\\_rocketStorageAddress != address(0x0), "Invalid storage address");\\n rocketStorage = RocketStorageInterface(\\_rocketStorageAddress);\\n}\\n```\\n | Resolution\\nAddressed in branch `rp3.0-updates` (rocket-pool/[email protected]b424ca1) by removing the constructor and therefore the initialization code from the RocketMinipoolDelegate contract. The contract cannot be used directly anymore as all relevant methods are decorated `onlyInitialised` and there is no way to initialize it in the implementation directly.\\nRemove the initialization from the constructor in the delegate contract. Consider adding a flag that indicates that the delegate contract is initialized and only set in the Minipool contract and not in the logic contract (delegate). On calls, check that the contract is initialized. | null | ```\\nconstructor(address \\_rocketStorageAddress) {\\n // Initialise RocketStorage\\n require(\\_rocketStorageAddress != address(0x0), "Invalid storage address");\\n rocketStorage = RocketStorageInterface(\\_rocketStorageAddress);\\n}\\n```\\n |
Re-entrancy issue for ERC1155 | high | ERC1155 tokens have callback functions on some of the transfers, like `safeTransferFrom`, `safeBatchTransferFrom`. During these transfers, the `IERC1155ReceiverUpgradeable(to).onERC1155Received` function is called in the `to` address.\\nFor example, `safeTransferFrom` is used in the `LiquidityMining` contract:\\n```\\nfunction distributeAllNFT() external {\\n require(block.timestamp > getEndLMTime(),\\n "2 weeks after liquidity mining time has not expired");\\n require(!isNFTDistributed, "NFT is already distributed");\\n\\n for (uint256 i = 0; i < leaderboard.length; i++) {\\n address[] memory \\_groupLeaders = groupsLeaders[leaderboard[i]];\\n\\n for (uint256 j = 0; j < \\_groupLeaders.length; j++) {\\n \\_sendNFT(j, \\_groupLeaders[j]);\\n }\\n }\\n\\n for (uint256 i = 0; i < topUsers.length; i++) {\\n address \\_currentAddress = topUsers[i];\\n LMNFT.safeTransferFrom(address(this), \\_currentAddress, 1, 1, "");\\n emit NFTSent(\\_currentAddress, 1);\\n }\\n\\n isNFTDistributed = true;\\n}\\n```\\n\\nDuring that transfer, the `distributeAllNFT` function can be called again and again. So multiple transfers will be done for each user.\\nIn addition to that, any receiver of the tokens can revert the transfer. If that happens, nobody will be able to receive their tokens. | Add a reentrancy guard.\\nAvoid transferring tokens for different receivers in a single transaction. | null | ```\\nfunction distributeAllNFT() external {\\n require(block.timestamp > getEndLMTime(),\\n "2 weeks after liquidity mining time has not expired");\\n require(!isNFTDistributed, "NFT is already distributed");\\n\\n for (uint256 i = 0; i < leaderboard.length; i++) {\\n address[] memory \\_groupLeaders = groupsLeaders[leaderboard[i]];\\n\\n for (uint256 j = 0; j < \\_groupLeaders.length; j++) {\\n \\_sendNFT(j, \\_groupLeaders[j]);\\n }\\n }\\n\\n for (uint256 i = 0; i < topUsers.length; i++) {\\n address \\_currentAddress = topUsers[i];\\n LMNFT.safeTransferFrom(address(this), \\_currentAddress, 1, 1, "");\\n emit NFTSent(\\_currentAddress, 1);\\n }\\n\\n isNFTDistributed = true;\\n}\\n```\\n |
Winning pods can be frontrun with large deposits | high | `Pod.depositTo()` grants users shares of the pod pool in exchange for `tokenAmount` of `token`.\\n```\\nfunction depositTo(address to, uint256 tokenAmount)\\n external\\n override\\n returns (uint256)\\n{\\n require(tokenAmount > 0, "Pod:invalid-amount");\\n\\n // Allocate Shares from Deposit To Amount\\n uint256 shares = \\_deposit(to, tokenAmount);\\n\\n // Transfer Token Transfer Message Sender\\n IERC20Upgradeable(token).transferFrom(\\n msg.sender,\\n address(this),\\n tokenAmount\\n );\\n\\n // Emit Deposited\\n emit Deposited(to, tokenAmount, shares);\\n\\n // Return Shares Minted\\n return shares;\\n}\\n```\\n\\nThe winner of a prize pool is typically determined by an off-chain random number generator, which requires a request to first be made on-chain. The result of this RNG request can be seen in the mempool and frontrun. In this case, an attacker could identify a winning `Pod` contract and make a large deposit, diluting existing user shares and claiming the entire prize. | The modifier `pauseDepositsDuringAwarding` is included in the `Pod` contract but is unused.\\n```\\nmodifier pauseDepositsDuringAwarding() {\\n require(\\n !IPrizeStrategyMinimal(\\_prizePool.prizeStrategy()).isRngRequested(),\\n "Cannot deposit while prize is being awarded"\\n );\\n \\_;\\n}\\n```\\n\\nAdd this modifier to the `depositTo()` function along with corresponding test cases. | null | ```\\nfunction depositTo(address to, uint256 tokenAmount)\\n external\\n override\\n returns (uint256)\\n{\\n require(tokenAmount > 0, "Pod:invalid-amount");\\n\\n // Allocate Shares from Deposit To Amount\\n uint256 shares = \\_deposit(to, tokenAmount);\\n\\n // Transfer Token Transfer Message Sender\\n IERC20Upgradeable(token).transferFrom(\\n msg.sender,\\n address(this),\\n tokenAmount\\n );\\n\\n // Emit Deposited\\n emit Deposited(to, tokenAmount, shares);\\n\\n // Return Shares Minted\\n return shares;\\n}\\n```\\n |
TokenDrop: Unprotected initialize() function | high | The `TokenDrop.initialize()` function is unprotected and can be called multiple times.\\n```\\nfunction initialize(address \\_measure, address \\_asset) external {\\n measure = IERC20Upgradeable(\\_measure);\\n asset = IERC20Upgradeable(\\_asset);\\n\\n // Set Factory Deployer\\n factory = msg.sender;\\n}\\n```\\n\\nAmong other attacks, this would allow an attacker to re-initialize any `TokenDrop` with the same `asset` and a malicious `measure` token. By manipulating the balance of a user in this malicious `measure` token, the entire `asset` token balance of the `TokenDrop` contract could be drained. | Add the `initializer` modifier to the `initialize()` function and include an explicit test that every initialization function in the system can be called once and only once. | null | ```\\nfunction initialize(address \\_measure, address \\_asset) external {\\n measure = IERC20Upgradeable(\\_measure);\\n asset = IERC20Upgradeable(\\_asset);\\n\\n // Set Factory Deployer\\n factory = msg.sender;\\n}\\n```\\n |
Pod: Re-entrancy during deposit or withdrawal can lead to stealing funds | high | During the deposit, the token transfer is made after the Pod shares are minted:\\n```\\nuint256 shares = \\_deposit(to, tokenAmount);\\n\\n// Transfer Token Transfer Message Sender\\nIERC20Upgradeable(token).transferFrom(\\n msg.sender,\\n address(this),\\n tokenAmount\\n);\\n```\\n\\nThat means that if the `token` allows re-entrancy, the attacker can deposit one more time inside the `token` transfer. If that happens, the second call will mint more tokens than it is supposed to, because the first `token` transfer will still not be finished. By doing so with big amounts, it's possible to drain the pod. | Add re-entrancy guard to the external functions. | null | ```\\nuint256 shares = \\_deposit(to, tokenAmount);\\n\\n// Transfer Token Transfer Message Sender\\nIERC20Upgradeable(token).transferFrom(\\n msg.sender,\\n address(this),\\n tokenAmount\\n);\\n```\\n |
TokenDrop: Re-entrancy in the claim function can cause to draining funds | high | If the `asset` token is making a call before the `transfer` to the `receiver` or to any other 3-d party contract (like it's happening in the `Pod` token using the `_beforeTokenTransfer` function), the attacker can call the `drop` function inside the `transfer` call here:\\n```\\nfunction claim(address user) external returns (uint256) {\\n drop();\\n \\_captureNewTokensForUser(user);\\n uint256 balance = userStates[user].balance;\\n userStates[user].balance = 0;\\n totalUnclaimed = uint256(totalUnclaimed).sub(balance).toUint112();\\n\\n // Transfer asset/reward token to user\\n asset.transfer(user, balance);\\n\\n // Emit Claimed\\n emit Claimed(user, balance);\\n\\n return balance;\\n}\\n```\\n\\nBecause the `totalUnclaimed` is already changed, but the current balance is not, the `drop` function will consider the funds from the unfinished transfer as the new tokens. These tokens will be virtually redistributed to everyone.\\nAfter that, the transfer will still happen, and further calls of the `drop()` function will fail because the following line will revert:\\n`uint256 newTokens = assetTotalSupply.sub(totalUnclaimed);`\\nThat also means that any transfers of the `Pod` token will fail because they all are calling the `drop` function. The `TokenDrop` will “unfreeze” only if someone transfers enough tokens to the `TokenDrop` contract.\\nThe severity of this issue is hard to evaluate because, at the moment, there's not a lot of tokens that allow this kind of re-entrancy. | Simply adding re-entrancy guard to the `drop` and the `claim` function won't help because the `drop` function is called from the `claim`. For that, the transfer can be moved to a separate function, and this function can have the re-entrancy guard as well as the `drop` function.\\nAlso, it's better to make sure that `_beforeTokenTransfer` will not revert to prevent the token from being frozen. | null | ```\\nfunction claim(address user) external returns (uint256) {\\n drop();\\n \\_captureNewTokensForUser(user);\\n uint256 balance = userStates[user].balance;\\n userStates[user].balance = 0;\\n totalUnclaimed = uint256(totalUnclaimed).sub(balance).toUint112();\\n\\n // Transfer asset/reward token to user\\n asset.transfer(user, balance);\\n\\n // Emit Claimed\\n emit Claimed(user, balance);\\n\\n return balance;\\n}\\n```\\n |
Pod: Having multiple token drops is inconsistent | medium | The `Pod` contract had the `drop` storage field and mapping of different TokenDrops `(token => TokenDrop)`. When adding a new `TokenDrop` in the mapping, the `drop` field is also changed to the added _tokenDrop:\\n```\\nfunction setTokenDrop(address \\_token, address \\_tokenDrop)\\n external\\n returns (bool)\\n{\\n require(\\n msg.sender == factory || msg.sender == owner(),\\n "Pod:unauthorized-set-token-drop"\\n );\\n\\n // Check if target<>tokenDrop mapping exists\\n require(\\n drops[\\_token] == TokenDrop(0),\\n "Pod:target-tokendrop-mapping-exists"\\n );\\n\\n // Set TokenDrop Referance\\n drop = TokenDrop(\\_tokenDrop);\\n\\n // Set target<>tokenDrop mapping\\n drops[\\_token] = drop;\\n\\n return true;\\n}\\n```\\n\\nOn the other hand, the `measure` token and the `asset` token of the `drop` are strictly defined by the Pod contract. They cannot be changed, so all `TokenDrops` are supposed to have the same `asset` and `measure` tokens. So it is useless to have different `TokenDrops`. | The mapping seems to be unused, and only one `TokenDrop` will normally be in the system. If that code is not used, it should be deleted. | null | ```\\nfunction setTokenDrop(address \\_token, address \\_tokenDrop)\\n external\\n returns (bool)\\n{\\n require(\\n msg.sender == factory || msg.sender == owner(),\\n "Pod:unauthorized-set-token-drop"\\n );\\n\\n // Check if target<>tokenDrop mapping exists\\n require(\\n drops[\\_token] == TokenDrop(0),\\n "Pod:target-tokendrop-mapping-exists"\\n );\\n\\n // Set TokenDrop Referance\\n drop = TokenDrop(\\_tokenDrop);\\n\\n // Set target<>tokenDrop mapping\\n drops[\\_token] = drop;\\n\\n return true;\\n}\\n```\\n |
Pod: Fees are not limited by a user during the withdrawal | medium | When withdrawing from the Pod, the shares are burned, and the deposit is removed from the Pod. If there are not enough deposit tokens in the contract, the remaining tokens are withdrawn from the pool contract:\\n```\\nif (amount > currentBalance) {\\n // Calculate Withdrawl Amount\\n uint256 \\_withdraw = amount.sub(currentBalance);\\n\\n // Withdraw from Prize Pool\\n uint256 exitFee = \\_withdrawFromPool(\\_withdraw);\\n\\n // Add Exit Fee to Withdrawl Amount\\n amount = amount.sub(exitFee);\\n}\\n```\\n\\nThese tokens are withdrawn with a fee from the pool, which is not controlled or limited by the user. | Allow users to pass a `maxFee` parameter to control fees. | null | ```\\nif (amount > currentBalance) {\\n // Calculate Withdrawl Amount\\n uint256 \\_withdraw = amount.sub(currentBalance);\\n\\n // Withdraw from Prize Pool\\n uint256 exitFee = \\_withdrawFromPool(\\_withdraw);\\n\\n // Add Exit Fee to Withdrawl Amount\\n amount = amount.sub(exitFee);\\n}\\n```\\n |
Pod.setManager() checks validity of wrong address | low | The function `Pod.setManager()` allows the `owner` of the Pod contract to change the Pod's `manager`. It checks that the value of the existing `manager` in storage is nonzero. This is presumably intended to ensure that the `owner` has provided a valid `newManager` parameter in calldata.\\nThe current check will always pass once the contract is initialized with a nonzero `manager`. But, the contract can currently be initialized with a `manager` of `IPodManager(address(0))`. In this case, the check would prevent the `manager` from ever being updated.\\n```\\nfunction setManager(IPodManager newManager)\\n public\\n virtual\\n onlyOwner\\n returns (bool)\\n{\\n // Require Valid Address\\n require(address(manager) != address(0), "Pod:invalid-manager-address");\\n```\\n | Change the check to:\\n```\\nrequire(address(newManager) != address(0), "Pod:invalid-manager-address");\\n```\\n\\nMore generally, attempt to define validity criteria for all input values that are as strict as possible. Consider preventing zero inputs or inputs that might conflict with other addresses in the smart contract system altogether, including in contract initialization functions. | null | ```\\nfunction setManager(IPodManager newManager)\\n public\\n virtual\\n onlyOwner\\n returns (bool)\\n{\\n // Require Valid Address\\n require(address(manager) != address(0), "Pod:invalid-manager-address");\\n```\\n |
Reuse of CHAINID from contract deployment | low | The internal function `_validateWithdrawSignature()` is used to check whether a sponsored token withdrawal is approved by the owner of the stealth address that received the tokens. Among other data, the chain ID is signed over to prevent replay of signatures on other EVM-compatible chains.\\n```\\nfunction \\_validateWithdrawSignature(\\n address \\_stealthAddr,\\n address \\_acceptor,\\n address \\_tokenAddr,\\n address \\_sponsor,\\n uint256 \\_sponsorFee,\\n IUmbraHookReceiver \\_hook,\\n bytes memory \\_data,\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s\\n) internal view {\\n bytes32 \\_digest =\\n keccak256(\\n abi.encodePacked(\\n "\\x19Ethereum Signed Message:\\n32",\\n keccak256(abi.encode(chainId, version, \\_acceptor, \\_tokenAddr, \\_sponsor, \\_sponsorFee, address(\\_hook), \\_data))\\n )\\n );\\n\\n address \\_recoveredAddress = ecrecover(\\_digest, \\_v, \\_r, \\_s);\\n require(\\_recoveredAddress != address(0) && \\_recoveredAddress == \\_stealthAddr, "Umbra: Invalid Signature");\\n}\\n```\\n\\nHowever, this chain ID is set as an immutable value in the contract constructor. In the case of a future contentious hard fork of the Ethereum network, the same `Umbra` contract would exist on both of the resulting chains. One of these two chains would be expected to change the network's chain ID, but the `Umbra` contracts would not be aware of this change. As a result, signatures to the `Umbra` contract on either chain would be replayable on the other chain.\\nThis is a common pattern in contracts that implement EIP-712 signatures. Presumably, the motivation in most cases for committing to the chain ID at deployment time is to avoid recomputing the EIP-712 domain separator for every signature verification. In this case, the chain ID is a direct input to the generation of the signed digest, so this should not be a concern. | Replace the use of the `chainId` immutable value with the `CHAINID` opcode in `_validateWithdrawSignature()`. Note that `CHAINID` is only available using Solidity's inline assembly, so this would need to be accessed in the same way as it is currently accessed in the contract's constructor:\\n```\\nuint256 \\_chainId;\\n\\nassembly {\\n \\_chainId := chainid()\\n}\\n```\\n | null | ```\\nfunction \\_validateWithdrawSignature(\\n address \\_stealthAddr,\\n address \\_acceptor,\\n address \\_tokenAddr,\\n address \\_sponsor,\\n uint256 \\_sponsorFee,\\n IUmbraHookReceiver \\_hook,\\n bytes memory \\_data,\\n uint8 \\_v,\\n bytes32 \\_r,\\n bytes32 \\_s\\n) internal view {\\n bytes32 \\_digest =\\n keccak256(\\n abi.encodePacked(\\n "\\x19Ethereum Signed Message:\\n32",\\n keccak256(abi.encode(chainId, version, \\_acceptor, \\_tokenAddr, \\_sponsor, \\_sponsorFee, address(\\_hook), \\_data))\\n )\\n );\\n\\n address \\_recoveredAddress = ecrecover(\\_digest, \\_v, \\_r, \\_s);\\n require(\\_recoveredAddress != address(0) && \\_recoveredAddress == \\_stealthAddr, "Umbra: Invalid Signature");\\n}\\n```\\n |
Random task execution | high | In a scenario where user takes a flash loan, `_parseFLAndExecute()` gives the flash loan wrapper contract (FLAaveV2, FLDyDx) the permission to execute functions on behalf of the user's `DSProxy`. This execution permission is revoked only after the entire recipe execution is finished, which means that in case that any of the external calls along the recipe execution is malicious, it might call `executeAction()` back and inject any task it wishes (e.g. take user's funds out, drain approved tokens, etc)\\n```\\nfunction executeOperation(\\n address[] memory \\_assets,\\n uint256[] memory \\_amounts,\\n uint256[] memory \\_fees,\\n address \\_initiator,\\n bytes memory \\_params\\n) public returns (bool) {\\n require(msg.sender == AAVE\\_LENDING\\_POOL, ERR\\_ONLY\\_AAVE\\_CALLER);\\n require(\\_initiator == address(this), ERR\\_SAME\\_CALLER);\\n\\n (Task memory currTask, address proxy) = abi.decode(\\_params, (Task, address));\\n\\n // Send FL amounts to user proxy\\n for (uint256 i = 0; i < \\_assets.length; ++i) {\\n \\_assets[i].withdrawTokens(proxy, \\_amounts[i]);\\n }\\n\\n address payable taskExecutor = payable(registry.getAddr(TASK\\_EXECUTOR\\_ID));\\n\\n // call Action execution\\n IDSProxy(proxy).execute{value: address(this).balance}(\\n taskExecutor,\\n abi.encodeWithSelector(CALLBACK\\_SELECTOR, currTask, bytes32(\\_amounts[0] + \\_fees[0]))\\n );\\n\\n // return FL\\n for (uint256 i = 0; i < \\_assets.length; i++) {\\n \\_assets[i].approveToken(address(AAVE\\_LENDING\\_POOL), \\_amounts[i] + \\_fees[i]);\\n }\\n\\n return true;\\n}\\n```\\n | A reentrancy guard (mutex) that covers the entire content of FLAaveV2.executeOperation/FLDyDx.callFunction should be used to prevent such attack. | null | ```\\nfunction executeOperation(\\n address[] memory \\_assets,\\n uint256[] memory \\_amounts,\\n uint256[] memory \\_fees,\\n address \\_initiator,\\n bytes memory \\_params\\n) public returns (bool) {\\n require(msg.sender == AAVE\\_LENDING\\_POOL, ERR\\_ONLY\\_AAVE\\_CALLER);\\n require(\\_initiator == address(this), ERR\\_SAME\\_CALLER);\\n\\n (Task memory currTask, address proxy) = abi.decode(\\_params, (Task, address));\\n\\n // Send FL amounts to user proxy\\n for (uint256 i = 0; i < \\_assets.length; ++i) {\\n \\_assets[i].withdrawTokens(proxy, \\_amounts[i]);\\n }\\n\\n address payable taskExecutor = payable(registry.getAddr(TASK\\_EXECUTOR\\_ID));\\n\\n // call Action execution\\n IDSProxy(proxy).execute{value: address(this).balance}(\\n taskExecutor,\\n abi.encodeWithSelector(CALLBACK\\_SELECTOR, currTask, bytes32(\\_amounts[0] + \\_fees[0]))\\n );\\n\\n // return FL\\n for (uint256 i = 0; i < \\_assets.length; i++) {\\n \\_assets[i].approveToken(address(AAVE\\_LENDING\\_POOL), \\_amounts[i] + \\_fees[i]);\\n }\\n\\n return true;\\n}\\n```\\n |
Tokens with more than 18 decimal points will cause issues | high | It is assumed that the maximum number of decimals for each token is 18. However uncommon, but it is possible to have tokens with more than 18 decimals, as an Example YAMv2 has 24 decimals. This can result in broken code flow and unpredictable outcomes (e.g. an underflow will result with really high rates).\\n```\\n function getSellRate(address \\_srcAddr, address \\_destAddr, uint \\_srcAmount, bytes memory) public override view returns (uint rate) {\\n (rate, ) = KyberNetworkProxyInterface(KYBER\\_INTERFACE)\\n .getExpectedRate(IERC20(\\_srcAddr), IERC20(\\_destAddr), \\_srcAmount);\\n\\n // multiply with decimal difference in src token\\n rate = rate \\* (10\\*\\*(18 - getDecimals(\\_srcAddr)));\\n // divide with decimal difference in dest token\\n rate = rate / (10\\*\\*(18 - getDecimals(\\_destAddr)));\\n }\\n```\\n | Make sure the code won't fail in case the token's decimals is more than 18. | null | ```\\n function getSellRate(address \\_srcAddr, address \\_destAddr, uint \\_srcAmount, bytes memory) public override view returns (uint rate) {\\n (rate, ) = KyberNetworkProxyInterface(KYBER\\_INTERFACE)\\n .getExpectedRate(IERC20(\\_srcAddr), IERC20(\\_destAddr), \\_srcAmount);\\n\\n // multiply with decimal difference in src token\\n rate = rate \\* (10\\*\\*(18 - getDecimals(\\_srcAddr)));\\n // divide with decimal difference in dest token\\n rate = rate / (10\\*\\*(18 - getDecimals(\\_destAddr)));\\n }\\n```\\n |
Error codes of Compound's Comptroller.enterMarket, Comptroller.exitMarket are not checked | high | Compound's `enterMarket/exitMarket` functions return an error code instead of reverting in case of failure. DeFi Saver smart contracts never check for the error codes returned from Compound smart contracts, although the code flow might revert due to unavailability of the CTokens, however early on checks for Compound errors are suggested.\\n```\\nfunction enterMarket(address \\_cTokenAddr) public {\\n address[] memory markets = new address[](1);\\n markets[0] = \\_cTokenAddr;\\n\\n IComptroller(COMPTROLLER\\_ADDR).enterMarkets(markets);\\n}\\n\\n/// @notice Exits the Compound market\\n/// @param \\_cTokenAddr CToken address of the token\\nfunction exitMarket(address \\_cTokenAddr) public {\\n IComptroller(COMPTROLLER\\_ADDR).exitMarket(\\_cTokenAddr);\\n}\\n```\\n | Caller contract should revert in case the error code is not 0. | null | ```\\nfunction enterMarket(address \\_cTokenAddr) public {\\n address[] memory markets = new address[](1);\\n markets[0] = \\_cTokenAddr;\\n\\n IComptroller(COMPTROLLER\\_ADDR).enterMarkets(markets);\\n}\\n\\n/// @notice Exits the Compound market\\n/// @param \\_cTokenAddr CToken address of the token\\nfunction exitMarket(address \\_cTokenAddr) public {\\n IComptroller(COMPTROLLER\\_ADDR).exitMarket(\\_cTokenAddr);\\n}\\n```\\n |
Reversed order of parameters in allowance function call | medium | When trying to pull the maximum amount of tokens from an approver to the allowed spender, the parameters that are used for the `allowance` function call are not in the same order that is used later in the call to `safeTransferFrom`.\\n```\\nfunction pullTokens(\\n address \\_token,\\n address \\_from,\\n uint256 \\_amount\\n) internal returns (uint256) {\\n // handle max uint amount\\n if (\\_amount == type(uint256).max) {\\n uint256 allowance = IERC20(\\_token).allowance(address(this), \\_from);\\n uint256 balance = getBalance(\\_token, \\_from);\\n\\n \\_amount = (balance > allowance) ? allowance : balance;\\n }\\n\\n if (\\_from != address(0) && \\_from != address(this) && \\_token != ETH\\_ADDR && \\_amount != 0) {\\n IERC20(\\_token).safeTransferFrom(\\_from, address(this), \\_amount);\\n }\\n\\n return \\_amount;\\n}\\n```\\n | Reverse the order of parameters in `allowance` function call to fit the order that is in the `safeTransferFrom` function call. | null | ```\\nfunction pullTokens(\\n address \\_token,\\n address \\_from,\\n uint256 \\_amount\\n) internal returns (uint256) {\\n // handle max uint amount\\n if (\\_amount == type(uint256).max) {\\n uint256 allowance = IERC20(\\_token).allowance(address(this), \\_from);\\n uint256 balance = getBalance(\\_token, \\_from);\\n\\n \\_amount = (balance > allowance) ? allowance : balance;\\n }\\n\\n if (\\_from != address(0) && \\_from != address(this) && \\_token != ETH\\_ADDR && \\_amount != 0) {\\n IERC20(\\_token).safeTransferFrom(\\_from, address(this), \\_amount);\\n }\\n\\n return \\_amount;\\n}\\n```\\n |
Kyber getRates code is unclear | low | `getSellRate` can be converted into one function to get the rates, which then for buy or sell can swap input and output tokens\\n`getBuyRate` uses a 3% slippage that is not documented.\\n```\\n function getSellRate(address \\_srcAddr, address \\_destAddr, uint \\_srcAmount, bytes memory) public override view returns (uint rate) {\\n (rate, ) = KyberNetworkProxyInterface(KYBER\\_INTERFACE)\\n .getExpectedRate(IERC20(\\_srcAddr), IERC20(\\_destAddr), \\_srcAmount);\\n\\n // multiply with decimal difference in src token\\n rate = rate \\* (10\\*\\*(18 - getDecimals(\\_srcAddr)));\\n // divide with decimal difference in dest token\\n rate = rate / (10\\*\\*(18 - getDecimals(\\_destAddr)));\\n }\\n\\n /// @notice Return a rate for which we can buy an amount of tokens\\n /// @param \\_srcAddr From token\\n /// @param \\_destAddr To token\\n /// @param \\_destAmount To amount\\n /// @return rate Rate\\n function getBuyRate(address \\_srcAddr, address \\_destAddr, uint \\_destAmount, bytes memory \\_additionalData) public override view returns (uint rate) {\\n uint256 srcRate = getSellRate(\\_destAddr, \\_srcAddr, \\_destAmount, \\_additionalData);\\n uint256 srcAmount = wmul(srcRate, \\_destAmount);\\n\\n rate = getSellRate(\\_srcAddr, \\_destAddr, srcAmount, \\_additionalData);\\n\\n // increase rate by 3% too account for inaccuracy between sell/buy conversion\\n rate = rate + (rate / 30);\\n }\\n```\\n | Refactoring the code to separate getting rate functionality with `getSellRate` and `getBuyRate`. Explicitly document any assumptions in the code ( slippage, etc) | null | ```\\n function getSellRate(address \\_srcAddr, address \\_destAddr, uint \\_srcAmount, bytes memory) public override view returns (uint rate) {\\n (rate, ) = KyberNetworkProxyInterface(KYBER\\_INTERFACE)\\n .getExpectedRate(IERC20(\\_srcAddr), IERC20(\\_destAddr), \\_srcAmount);\\n\\n // multiply with decimal difference in src token\\n rate = rate \\* (10\\*\\*(18 - getDecimals(\\_srcAddr)));\\n // divide with decimal difference in dest token\\n rate = rate / (10\\*\\*(18 - getDecimals(\\_destAddr)));\\n }\\n\\n /// @notice Return a rate for which we can buy an amount of tokens\\n /// @param \\_srcAddr From token\\n /// @param \\_destAddr To token\\n /// @param \\_destAmount To amount\\n /// @return rate Rate\\n function getBuyRate(address \\_srcAddr, address \\_destAddr, uint \\_destAmount, bytes memory \\_additionalData) public override view returns (uint rate) {\\n uint256 srcRate = getSellRate(\\_destAddr, \\_srcAddr, \\_destAmount, \\_additionalData);\\n uint256 srcAmount = wmul(srcRate, \\_destAmount);\\n\\n rate = getSellRate(\\_srcAddr, \\_destAddr, srcAmount, \\_additionalData);\\n\\n // increase rate by 3% too account for inaccuracy between sell/buy conversion\\n rate = rate + (rate / 30);\\n }\\n```\\n |
Return values not used for DFSExchangeCore.onChainSwap | low | Return values from `DFSExchangeCore.onChainSwap` are not used.\\n```\\nfunction \\_sell(ExchangeData memory exData) internal returns (address, uint256) {\\n uint256 amountWithoutFee = exData.srcAmount;\\n address wrapper = exData.offchainData.wrapper;\\n bool offChainSwapSuccess;\\n\\n uint256 destBalanceBefore = exData.destAddr.getBalance(address(this));\\n\\n // Takes DFS exchange fee\\n exData.srcAmount -= getFee(\\n exData.srcAmount,\\n exData.user,\\n exData.srcAddr,\\n exData.dfsFeeDivider\\n );\\n\\n // Try 0x first and then fallback on specific wrapper\\n if (exData.offchainData.price > 0) {\\n (offChainSwapSuccess, ) = offChainSwap(exData, ExchangeActionType.SELL);\\n }\\n\\n // fallback to desired wrapper if 0x failed\\n if (!offChainSwapSuccess) {\\n onChainSwap(exData, ExchangeActionType.SELL);\\n wrapper = exData.wrapper;\\n }\\n\\n uint256 destBalanceAfter = exData.destAddr.getBalance(address(this));\\n uint256 amountBought = sub(destBalanceAfter, destBalanceBefore);\\n\\n // check slippage\\n require(amountBought >= wmul(exData.minPrice, exData.srcAmount), ERR\\_SLIPPAGE\\_HIT);\\n\\n // revert back exData changes to keep it consistent\\n exData.srcAmount = amountWithoutFee;\\n\\n return (wrapper, amountBought);\\n}\\n```\\n\\n```\\nfunction \\_buy(ExchangeData memory exData) internal returns (address, uint256) {\\n require(exData.destAmount != 0, ERR\\_DEST\\_AMOUNT\\_MISSING);\\n\\n uint256 amountWithoutFee = exData.srcAmount;\\n address wrapper = exData.offchainData.wrapper;\\n bool offChainSwapSuccess;\\n\\n uint256 destBalanceBefore = exData.destAddr.getBalance(address(this));\\n\\n // Takes DFS exchange fee\\n exData.srcAmount -= getFee(\\n exData.srcAmount,\\n exData.user,\\n exData.srcAddr,\\n exData.dfsFeeDivider\\n );\\n\\n // Try 0x first and then fallback on specific wrapper\\n if (exData.offchainData.price > 0) {\\n (offChainSwapSuccess, ) = offChainSwap(exData, ExchangeActionType.BUY);\\n }\\n\\n // fallback to desired wrapper if 0x failed\\n if (!offChainSwapSuccess) {\\n onChainSwap(exData, ExchangeActionType.BUY);\\n wrapper = exData.wrapper;\\n }\\n\\n uint256 destBalanceAfter = exData.destAddr.getBalance(address(this));\\n uint256 amountBought = sub(destBalanceAfter, destBalanceBefore);\\n\\n // check slippage\\n require(amountBought >= exData.destAmount, ERR\\_SLIPPAGE\\_HIT);\\n\\n // revert back exData changes to keep it consistent\\n exData.srcAmount = amountWithoutFee;\\n\\n return (wrapper, amountBought);\\n}\\n```\\n | The return value can be used for verification of the swap or used in the event data. | null | ```\\nfunction \\_sell(ExchangeData memory exData) internal returns (address, uint256) {\\n uint256 amountWithoutFee = exData.srcAmount;\\n address wrapper = exData.offchainData.wrapper;\\n bool offChainSwapSuccess;\\n\\n uint256 destBalanceBefore = exData.destAddr.getBalance(address(this));\\n\\n // Takes DFS exchange fee\\n exData.srcAmount -= getFee(\\n exData.srcAmount,\\n exData.user,\\n exData.srcAddr,\\n exData.dfsFeeDivider\\n );\\n\\n // Try 0x first and then fallback on specific wrapper\\n if (exData.offchainData.price > 0) {\\n (offChainSwapSuccess, ) = offChainSwap(exData, ExchangeActionType.SELL);\\n }\\n\\n // fallback to desired wrapper if 0x failed\\n if (!offChainSwapSuccess) {\\n onChainSwap(exData, ExchangeActionType.SELL);\\n wrapper = exData.wrapper;\\n }\\n\\n uint256 destBalanceAfter = exData.destAddr.getBalance(address(this));\\n uint256 amountBought = sub(destBalanceAfter, destBalanceBefore);\\n\\n // check slippage\\n require(amountBought >= wmul(exData.minPrice, exData.srcAmount), ERR\\_SLIPPAGE\\_HIT);\\n\\n // revert back exData changes to keep it consistent\\n exData.srcAmount = amountWithoutFee;\\n\\n return (wrapper, amountBought);\\n}\\n```\\n |
Return value is not used for TokenUtils.withdrawTokens | low | The return value of `TokenUtils.withdrawTokens` which represents the actual amount of tokens that were transferred is never used throughout the repository. This might cause discrepancy in the case where the original value of `_amount` was `type(uint256).max`.\\n```\\nfunction \\_borrow(\\n address \\_market,\\n address \\_tokenAddr,\\n uint256 \\_amount,\\n uint256 \\_rateMode,\\n address \\_to,\\n address \\_onBehalf\\n) internal returns (uint256) {\\n ILendingPoolV2 lendingPool = getLendingPool(\\_market);\\n\\n // defaults to onBehalf of proxy\\n if (\\_onBehalf == address(0)) {\\n \\_onBehalf = address(this);\\n }\\n\\n lendingPool.borrow(\\_tokenAddr, \\_amount, \\_rateMode, AAVE\\_REFERRAL\\_CODE, \\_onBehalf);\\n\\n \\_tokenAddr.withdrawTokens(\\_to, \\_amount);\\n\\n logger.Log(\\n address(this),\\n msg.sender,\\n "AaveBorrow",\\n abi.encode(\\_market, \\_tokenAddr, \\_amount, \\_rateMode, \\_to, \\_onBehalf)\\n );\\n\\n return \\_amount;\\n}\\n```\\n\\n```\\nfunction withdrawTokens(\\n address \\_token,\\n address \\_to,\\n uint256 \\_amount\\n) internal returns (uint256) {\\n if (\\_amount == type(uint256).max) {\\n \\_amount = getBalance(\\_token, address(this));\\n }\\n```\\n | The return value can be used to validate the withdrawal or used in the event emitted. | null | ```\\nfunction \\_borrow(\\n address \\_market,\\n address \\_tokenAddr,\\n uint256 \\_amount,\\n uint256 \\_rateMode,\\n address \\_to,\\n address \\_onBehalf\\n) internal returns (uint256) {\\n ILendingPoolV2 lendingPool = getLendingPool(\\_market);\\n\\n // defaults to onBehalf of proxy\\n if (\\_onBehalf == address(0)) {\\n \\_onBehalf = address(this);\\n }\\n\\n lendingPool.borrow(\\_tokenAddr, \\_amount, \\_rateMode, AAVE\\_REFERRAL\\_CODE, \\_onBehalf);\\n\\n \\_tokenAddr.withdrawTokens(\\_to, \\_amount);\\n\\n logger.Log(\\n address(this),\\n msg.sender,\\n "AaveBorrow",\\n abi.encode(\\_market, \\_tokenAddr, \\_amount, \\_rateMode, \\_to, \\_onBehalf)\\n );\\n\\n return \\_amount;\\n}\\n```\\n |
Anyone is able to mint NFTs by calling mintNFTsForLM | high | The contract `LiquidityMiningNFT` has the method `mintNFTsForLM`.\\n```\\nfunction mintNFTsForLM(address \\_liquidiyMiningAddr) external {\\n uint256[] memory \\_ids = new uint256[](NFT\\_TYPES\\_COUNT);\\n uint256[] memory \\_amounts = new uint256[](NFT\\_TYPES\\_COUNT);\\n\\n \\_ids[0] = 1;\\n \\_amounts[0] = 5;\\n\\n \\_ids[1] = 2;\\n \\_amounts[1] = 1 \\* LEADERBOARD\\_SIZE;\\n\\n \\_ids[2] = 3;\\n \\_amounts[2] = 3 \\* LEADERBOARD\\_SIZE;\\n\\n \\_ids[3] = 4;\\n \\_amounts[3] = 6 \\* LEADERBOARD\\_SIZE;\\n\\n \\_mintBatch(\\_liquidiyMiningAddr, \\_ids, \\_amounts, "");\\n}\\n```\\n\\nHowever, this contract does not have any kind of special permissions to limit who is able to mint tokens.\\nAn attacker could call `LiquidityMiningNFT.mintNFTsForLM(0xhackerAddress)` to mint tokens for their address and sell them on the marketplace. They are also allowed to mint as many tokens as they want by calling the method multiple times. | Add some permissions to limit only some actors to mint tokens. | null | ```\\nfunction mintNFTsForLM(address \\_liquidiyMiningAddr) external {\\n uint256[] memory \\_ids = new uint256[](NFT\\_TYPES\\_COUNT);\\n uint256[] memory \\_amounts = new uint256[](NFT\\_TYPES\\_COUNT);\\n\\n \\_ids[0] = 1;\\n \\_amounts[0] = 5;\\n\\n \\_ids[1] = 2;\\n \\_amounts[1] = 1 \\* LEADERBOARD\\_SIZE;\\n\\n \\_ids[2] = 3;\\n \\_amounts[2] = 3 \\* LEADERBOARD\\_SIZE;\\n\\n \\_ids[3] = 4;\\n \\_amounts[3] = 6 \\* LEADERBOARD\\_SIZE;\\n\\n \\_mintBatch(\\_liquidiyMiningAddr, \\_ids, \\_amounts, "");\\n}\\n```\\n |
A liquidity provider can withdraw all his funds anytime | high | Since some users provide liquidity to sell the insurance policies, it is important that these providers cannot withdraw their funds when the security breach happens and the policyholders are submitting claims. The liquidity providers can only request their funds first and withdraw them later (in a week).\\n```\\nfunction requestWithdrawal(uint256 \\_tokensToWithdraw) external override {\\n WithdrawalStatus \\_status = getWithdrawalStatus(msg.sender);\\n\\n require(\\_status == WithdrawalStatus.NONE || \\_status == WithdrawalStatus.EXPIRED,\\n "PB: Can't request withdrawal");\\n\\n uint256 \\_daiTokensToWithdraw = \\_tokensToWithdraw.mul(getDAIToDAIxRatio()).div(PERCENTAGE\\_100);\\n uint256 \\_availableDaiBalance = balanceOf(msg.sender).mul(getDAIToDAIxRatio()).div(PERCENTAGE\\_100);\\n\\n if (block.timestamp < liquidityMining.getEndLMTime().add(neededTimeAfterLM)) {\\n \\_availableDaiBalance = \\_availableDaiBalance.sub(liquidityFromLM[msg.sender]);\\n }\\n\\n require(totalLiquidity >= totalCoverTokens.add(\\_daiTokensToWithdraw),\\n "PB: Not enough liquidity");\\n\\n require(\\_availableDaiBalance >= \\_daiTokensToWithdraw, "PB: Wrong announced amount");\\n\\n WithdrawalInfo memory \\_newWithdrawalInfo;\\n \\_newWithdrawalInfo.amount = \\_tokensToWithdraw;\\n \\_newWithdrawalInfo.readyToWithdrawDate = block.timestamp.add(withdrawalPeriod);\\n\\n withdrawalsInfo[msg.sender] = \\_newWithdrawalInfo;\\n emit RequestWithdraw(msg.sender, \\_tokensToWithdraw, \\_newWithdrawalInfo.readyToWithdrawDate);\\n}\\n```\\n\\n```\\nfunction withdrawLiquidity() external override {\\n require(getWithdrawalStatus(msg.sender) == WithdrawalStatus.READY,\\n "PB: Withdrawal is not ready");\\n\\n uint256 \\_tokensToWithdraw = withdrawalsInfo[msg.sender].amount;\\n uint256 \\_daiTokensToWithdraw = \\_tokensToWithdraw.mul(getDAIToDAIxRatio()).div(PERCENTAGE\\_100);\\n\\n if (withdrawalQueue.length != 0 || totalLiquidity.sub(\\_daiTokensToWithdraw) < totalCoverTokens) {\\n withdrawalQueue.push(msg.sender);\\n } else {\\n \\_withdrawLiquidity(msg.sender, \\_tokensToWithdraw);\\n }\\n}\\n```\\n\\nThere is a restriction in `requestWithdrawal` that requires the liquidity provider to have enough funds at the moment of request:\\n```\\nrequire(totalLiquidity >= totalCoverTokens.add(\\_daiTokensToWithdraw),\\n "PB: Not enough liquidity");\\n\\nrequire(\\_availableDaiBalance >= \\_daiTokensToWithdraw, "PB: Wrong announced amount");\\n```\\n\\nBut after the request is created, these funds can then be transferred to another address. When the request is created, the provider should wait for 7 days, and then there will be 2 days to withdraw the requested amount:\\n```\\nwithdrawalPeriod = 1 weeks;\\nwithdrawalExpirePeriod = 2 days;\\n```\\n\\nThe attacker would have 4 addresses that will send the pool tokens to each other and request withdrawal of the full amount one by one every 2 days. So at least one of the addresses can withdraw all of the funds at any point in time. If the liquidity provider needs to withdraw funds immediately, he should transfer all funds to that address and execute the withdrawal. | Resolution\\nThe funds are now locked when the withdrawal is requested, so funds cannot be transferred after the request, and this bug cannot be exploited anymore.\\nOne of the solutions would be to block the DAIx tokens from being transferred after the withdrawal request. | null | ```\\nfunction requestWithdrawal(uint256 \\_tokensToWithdraw) external override {\\n WithdrawalStatus \\_status = getWithdrawalStatus(msg.sender);\\n\\n require(\\_status == WithdrawalStatus.NONE || \\_status == WithdrawalStatus.EXPIRED,\\n "PB: Can't request withdrawal");\\n\\n uint256 \\_daiTokensToWithdraw = \\_tokensToWithdraw.mul(getDAIToDAIxRatio()).div(PERCENTAGE\\_100);\\n uint256 \\_availableDaiBalance = balanceOf(msg.sender).mul(getDAIToDAIxRatio()).div(PERCENTAGE\\_100);\\n\\n if (block.timestamp < liquidityMining.getEndLMTime().add(neededTimeAfterLM)) {\\n \\_availableDaiBalance = \\_availableDaiBalance.sub(liquidityFromLM[msg.sender]);\\n }\\n\\n require(totalLiquidity >= totalCoverTokens.add(\\_daiTokensToWithdraw),\\n "PB: Not enough liquidity");\\n\\n require(\\_availableDaiBalance >= \\_daiTokensToWithdraw, "PB: Wrong announced amount");\\n\\n WithdrawalInfo memory \\_newWithdrawalInfo;\\n \\_newWithdrawalInfo.amount = \\_tokensToWithdraw;\\n \\_newWithdrawalInfo.readyToWithdrawDate = block.timestamp.add(withdrawalPeriod);\\n\\n withdrawalsInfo[msg.sender] = \\_newWithdrawalInfo;\\n emit RequestWithdraw(msg.sender, \\_tokensToWithdraw, \\_newWithdrawalInfo.readyToWithdrawDate);\\n}\\n```\\n |
The buyPolicyFor/addLiquidityFor should transfer funds from msg.sender | high | When calling the buyPolicyFor/addLiquidityFor functions, are called with the parameter _policyHolderAddr/_liquidityHolderAddr who is going to be the beneficiary in buying policy/adding liquidity:\\n```\\nfunction buyPolicyFor(\\n address \\_policyHolderAddr,\\n uint256 \\_epochsNumber,\\n uint256 \\_coverTokens \\n) external override {\\n \\_buyPolicyFor(\\_policyHolderAddr, \\_epochsNumber, \\_coverTokens);\\n}\\n```\\n\\n```\\nfunction addLiquidityFor(address \\_liquidityHolderAddr, uint256 \\_liquidityAmount) external override {\\n \\_addLiquidityFor(\\_liquidityHolderAddr, \\_liquidityAmount, false);\\n}\\n```\\n\\nDuring the execution, the funds for the policy/liquidity are transferred from the _policyHolderAddr/_liquidityHolderAddr, while it's usually expected that they should be transferred from `msg.sender`. Because of that, anyone can call a function on behalf of a user that gave the allowance to the `PolicyBook`.\\nFor example, a user(victim) wants to add some DAI to the liquidity pool and gives allowance to the `PolicyBook`. After that, the user should call `addLiquidity`, but the attacker can front-run this transaction and buy a policy on behalf of the victim instead.\\nAlso, there is a curious edge case that makes this issue Critical: _policyHolderAddr/_liquidityHolderAddr parameters can be equal to the address of the `PolicyBook` contract. That may lead to multiple different dangerous attack vectors. | Make sure that nobody can transfer funds on behalf of the users if it's not intended. | null | ```\\nfunction buyPolicyFor(\\n address \\_policyHolderAddr,\\n uint256 \\_epochsNumber,\\n uint256 \\_coverTokens \\n) external override {\\n \\_buyPolicyFor(\\_policyHolderAddr, \\_epochsNumber, \\_coverTokens);\\n}\\n```\\n |
LiquidityMining can't accept single ERC1155 tokens | high | The contract `LiquidityMining` is also defined as an `ERC1155Receiver`\\n```\\ncontract LiquidityMining is ILiquidityMining, ERC1155Receiver, Ownable {\\n```\\n\\nThe finalized EIP-1155 standard states that a contract which acts as an EIP-1155 Receiver must implement all the functions in the `ERC1155TokenReceiver` interface to be able to accept transfers.\\nThese are indeed implemented here:\\n```\\nfunction onERC1155Received(\\n```\\n\\n```\\nfunction onERC1155BatchReceived(\\n```\\n\\nThe standard states that they will be called and they MUST return a specific `byte4` value, otherwise the transfer will fail.\\nHowever one of the methods returns an incorrect value. This seems to an error generated by a copy/paste action.\\n```\\nfunction onERC1155Received(\\n address operator,\\n address from,\\n uint256 id,\\n uint256 value,\\n bytes memory data\\n)\\n external\\n pure\\n override\\n returns(bytes4)\\n{\\n return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));\\n}\\n```\\n\\nThe value returned is equal to\\n`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"));`\\nBut it should be\\n`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`.\\nOn top of this, the contract MUST implement the ERC-165 standard to correctly respond to `supportsInterface`. | Change the return value of `onERC1155Received` to be equal to `0xf23a6e61` which represents `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`.\\nAlso, make sure to implement `supportsInterface` to signify support of `ERC1155TokenReceiver` to accept transfers.\\nAdd tests to check the functionality is correct and make sure these kinds of bugs do not exist in the future.\\nMake sure to read the EIP-1155 and EIP-165 standards in detail and implement them correctly. | null | ```\\ncontract LiquidityMining is ILiquidityMining, ERC1155Receiver, Ownable {\\n```\\n |
DAI is assumed to have the same price as DAIx in the staking contract | high | When a liquidity provider stakes tokens to the `BMIDAIStaking` contract, the equal amount of DAI and DAIx are transferred from the pool contract.\\n```\\nfunction \\_stakeDAIx(address \\_user, uint256 \\_amount, address \\_policyBookAddr) internal {\\n require (\\_amount > 0, "BMIDAIStaking: Can't stake zero tokens");\\n\\n PolicyBook \\_policyBook = PolicyBook(\\_policyBookAddr);\\n // transfer DAI from PolicyBook to yield generator\\n daiToken.transferFrom(\\_policyBookAddr, address(defiYieldGenerator), \\_amount); \\n\\n // transfer bmiDAIx from user to staking\\n \\_policyBook.transferFrom(\\_user, address(this), \\_amount); \\n\\n \\_mintNFT(\\_user, \\_amount, \\_policyBook);\\n}\\n```\\n | Only the corresponding amount of DAI should be transferred to the pool. | null | ```\\nfunction \\_stakeDAIx(address \\_user, uint256 \\_amount, address \\_policyBookAddr) internal {\\n require (\\_amount > 0, "BMIDAIStaking: Can't stake zero tokens");\\n\\n PolicyBook \\_policyBook = PolicyBook(\\_policyBookAddr);\\n // transfer DAI from PolicyBook to yield generator\\n daiToken.transferFrom(\\_policyBookAddr, address(defiYieldGenerator), \\_amount); \\n\\n // transfer bmiDAIx from user to staking\\n \\_policyBook.transferFrom(\\_user, address(this), \\_amount); \\n\\n \\_mintNFT(\\_user, \\_amount, \\_policyBook);\\n}\\n```\\n |
_updateWithdrawalQueue can run out of gas | high | When there's not enough collateral to withdraw liquidity from a policy book, the withdrawal request is added to a queue. The queue is supposed to be processed and cleared once there are enough funds for that. The only way to do so is the `_updateWithdrawalQueue` function that is caller when new liquidity is added:\\n```\\nfunction \\_updateWithdrawalQueue() internal {\\n uint256 \\_availableLiquidity = totalLiquidity.sub(totalCoverTokens);\\n uint256 \\_countToRemoveFromQueue;\\n\\n for (uint256 i = 0; i < withdrawalQueue.length; i++) { \\n uint256 \\_tokensToWithdraw = withdrawalsInfo[withdrawalQueue[i]].amount;\\n uint256 \\_amountInDai = \\_tokensToWithdraw.mul(getDAIToDAIxRatio()).div(PERCENTAGE\\_100);\\n\\n if (balanceOf(withdrawalQueue[i]) < \\_tokensToWithdraw) {\\n \\_countToRemoveFromQueue++;\\n continue;\\n }\\n\\n if (\\_availableLiquidity >= \\_amountInDai) {\\n \\_withdrawLiquidity(withdrawalQueue[i], \\_tokensToWithdraw);\\n \\_availableLiquidity = \\_availableLiquidity.sub(\\_amountInDai);\\n \\_countToRemoveFromQueue++;\\n } else {\\n break;\\n }\\n }\\n\\n \\_removeFromQueue(\\_countToRemoveFromQueue);\\n}\\n```\\n\\nThe problem is that this function can only process all queue until the pool run out of available funds or the whole queue is going to be processed. If the queue is big enough, this process can be stuck. | Pass the parameter to the `_updateWithdrawalQueue` that defines how many requests to process in the queue per one call. | null | ```\\nfunction \\_updateWithdrawalQueue() internal {\\n uint256 \\_availableLiquidity = totalLiquidity.sub(totalCoverTokens);\\n uint256 \\_countToRemoveFromQueue;\\n\\n for (uint256 i = 0; i < withdrawalQueue.length; i++) { \\n uint256 \\_tokensToWithdraw = withdrawalsInfo[withdrawalQueue[i]].amount;\\n uint256 \\_amountInDai = \\_tokensToWithdraw.mul(getDAIToDAIxRatio()).div(PERCENTAGE\\_100);\\n\\n if (balanceOf(withdrawalQueue[i]) < \\_tokensToWithdraw) {\\n \\_countToRemoveFromQueue++;\\n continue;\\n }\\n\\n if (\\_availableLiquidity >= \\_amountInDai) {\\n \\_withdrawLiquidity(withdrawalQueue[i], \\_tokensToWithdraw);\\n \\_availableLiquidity = \\_availableLiquidity.sub(\\_amountInDai);\\n \\_countToRemoveFromQueue++;\\n } else {\\n break;\\n }\\n }\\n\\n \\_removeFromQueue(\\_countToRemoveFromQueue);\\n}\\n```\\n |
The PolicyBook should make DAI transfers inside the contract | medium | The `PolicyBook` contract gives full allowance over DAI tokens to the other contracts:\\n```\\nfunction approveAllDaiTokensForStakingAndVotingAndTransferOwnership() internal {\\n daiToken.approve(address(bmiDaiStaking), MAX\\_INT); \\n daiToken.approve(address(claimVoting), MAX\\_INT); \\n\\n transferOwnership(address(bmiDaiStaking));\\n}\\n```\\n\\nThat behavior is dangerous because it's hard to keep track of and control the contract's DAI balance. And it's also hard to track in the code where the balance of the `PolicyBook` can be changed from. | It's better to perform all the transfers inside the `PolicyBook` contract. So if the `bmiDaiStaking` and the `claimVoting` contracts need DAI tokens from the `PolicyBook`, they should call some function of the `PolicyBook` to perform transfers. | null | ```\\nfunction approveAllDaiTokensForStakingAndVotingAndTransferOwnership() internal {\\n daiToken.approve(address(bmiDaiStaking), MAX\\_INT); \\n daiToken.approve(address(claimVoting), MAX\\_INT); \\n\\n transferOwnership(address(bmiDaiStaking));\\n}\\n```\\n |
The totalCoverTokens is only updated when the policy is bought | medium | The `totalCoverTokens` value represents the amount of collateral that needs to be locked in the policy book. It should be changed either by buying a new policy or when an old policy expires. The problem is that when the old policy expires, this value is not updated; it is only updated when someone buys a policy by calling the `_updateEpochsInfo` function:\\n```\\nfunction \\_updateEpochsInfo() internal {\\n uint256 \\_totalEpochTime = block.timestamp.sub(epochStartTime);\\n uint256 \\_countOfPassedEpoch = \\_totalEpochTime.div(epochDuration);\\n\\n uint256 \\_lastEpochUpdate = currentEpochNumber;\\n currentEpochNumber = \\_countOfPassedEpoch.add(1);\\n\\n for (uint256 i = \\_lastEpochUpdate; i < currentEpochNumber; i++) {\\n totalCoverTokens = totalCoverTokens.sub(epochAmounts[i]);\\n delete epochAmounts[i];\\n }\\n}\\n```\\n\\nUsers waiting to withdraw liquidity should wait for someone to buy the policy to update the `totalCoverTokens`. | Resolution\\nThe `updateEpochsInfo` function is now public and can be called by anyone.\\nMake sure it's possible to call the `_updateEpochsInfo` function without buying a new policy. | null | ```\\nfunction \\_updateEpochsInfo() internal {\\n uint256 \\_totalEpochTime = block.timestamp.sub(epochStartTime);\\n uint256 \\_countOfPassedEpoch = \\_totalEpochTime.div(epochDuration);\\n\\n uint256 \\_lastEpochUpdate = currentEpochNumber;\\n currentEpochNumber = \\_countOfPassedEpoch.add(1);\\n\\n for (uint256 i = \\_lastEpochUpdate; i < currentEpochNumber; i++) {\\n totalCoverTokens = totalCoverTokens.sub(epochAmounts[i]);\\n delete epochAmounts[i];\\n }\\n}\\n```\\n |
Unbounded loops in LiquidityMining | medium | There are some methods that have unbounded loops and will fail when enough items exist in the arrays.\\n```\\nfor (uint256 i = 0; i < \\_teamsNumber; i++) {\\n```\\n\\n```\\nfor (uint256 i = 0; i < \\_membersNumber; i++) {\\n```\\n\\n```\\nfor (uint256 i = 0; i < \\_usersNumber; i++) {\\n```\\n\\nThese methods will fail when lots of items will be added to them. | Consider adding limits (from, to) when requesting the items. | null | ```\\nfor (uint256 i = 0; i < \\_teamsNumber; i++) {\\n```\\n |
The _removeFromQueue is very gas greedy | medium | The `_removeFromQueue` function is supposed to remove `_countToRemove` elements from the queue:\\n```\\nfunction \\_removeFromQueue(uint256 \\_countToRemove) internal {\\n for (uint256 i = 0; i < \\_countToRemove; i++) {\\n delete withdrawalsInfo[withdrawalQueue[i]];\\n } \\n\\n if (\\_countToRemove == withdrawalQueue.length) {\\n delete withdrawalQueue;\\n } else {\\n uint256 \\_remainingArrLength = withdrawalQueue.length.sub(\\_countToRemove);\\n address[] memory \\_remainingArr = new address[](\\_remainingArrLength);\\n\\n for (uint256 i = 0; i < \\_remainingArrLength; i++) {\\n \\_remainingArr[i] = withdrawalQueue[i.add(\\_countToRemove)];\\n }\\n\\n withdrawalQueue = \\_remainingArr;\\n }\\n}\\n```\\n\\nThis function uses too much gas, which makes it easier to make attacks on the system. Even if only one request is removed and executed, this function rewrites all the requests to the storage. | The data structure should be changed so this function shouldn't rewrite the requests that did not change. For example, it can be a mapping `(unit => address)` with 2 indexes `(start, end)` that are only increasing. | null | ```\\nfunction \\_removeFromQueue(uint256 \\_countToRemove) internal {\\n for (uint256 i = 0; i < \\_countToRemove; i++) {\\n delete withdrawalsInfo[withdrawalQueue[i]];\\n } \\n\\n if (\\_countToRemove == withdrawalQueue.length) {\\n delete withdrawalQueue;\\n } else {\\n uint256 \\_remainingArrLength = withdrawalQueue.length.sub(\\_countToRemove);\\n address[] memory \\_remainingArr = new address[](\\_remainingArrLength);\\n\\n for (uint256 i = 0; i < \\_remainingArrLength; i++) {\\n \\_remainingArr[i] = withdrawalQueue[i.add(\\_countToRemove)];\\n }\\n\\n withdrawalQueue = \\_remainingArr;\\n }\\n}\\n```\\n |
Withdrawal with zero amount is possible | medium | When creating a withdrawal request, the amount of tokens to withdraw is passed as a parameter:\\n```\\nfunction requestWithdrawal(uint256 \\_tokensToWithdraw) external override {\\n```\\n\\nThe problem is that this parameter can be zero, and the function will be successfully executed. Moreover, this request can then be added to the queue, and the actual withdrawal will also be executed with zero value. Addresses that never added any liquidity could spam the system with these requests. | Do not allow withdrawals of zero tokens. | null | ```\\nfunction requestWithdrawal(uint256 \\_tokensToWithdraw) external override {\\n```\\n |
The withdrawal queue is only updated when the liquidity is added | medium | Sometimes when the amount of liquidity is not much higher than the number of tokens locked for the collateral, it's impossible to withdraw liquidity. For a user that wants to withdraw liquidity, a withdrawal request is created. If the request can't be executed, it's added to the withdrawal queue, and the user needs to wait until there's enough collateral for withdrawal. There are potentially 2 ways to achieve that: either someone adds more liquidity or some existing policies expire.\\nCurrently, the queue can only be cleared when the internal `_updateWithdrawalQueue` function is called. And it is only called in one place while adding liquidity:\\n```\\nfunction \\_addLiquidityFor(address \\_liquidityHolderAddr, uint256 \\_liquidityAmount, bool \\_isLM) internal {\\n daiToken.transferFrom(\\_liquidityHolderAddr, address(this), \\_liquidityAmount); \\n \\n uint256 \\_amountToMint = \\_liquidityAmount.mul(PERCENTAGE\\_100).div(getDAIToDAIxRatio());\\n totalLiquidity = totalLiquidity.add(\\_liquidityAmount);\\n \\_mintERC20(\\_liquidityHolderAddr, \\_amountToMint);\\n\\n if (\\_isLM) {\\n liquidityFromLM[\\_liquidityHolderAddr] = liquidityFromLM[\\_liquidityHolderAddr].add(\\_liquidityAmount);\\n }\\n\\n \\_updateWithdrawalQueue();\\n\\n emit AddLiquidity(\\_liquidityHolderAddr, \\_liquidityAmount, totalLiquidity);\\n}\\n```\\n | It would be better if the queue could be processed when some policies expire without adding new liquidity. For example, there may be an external function that allows users to process the queue. | null | ```\\nfunction \\_addLiquidityFor(address \\_liquidityHolderAddr, uint256 \\_liquidityAmount, bool \\_isLM) internal {\\n daiToken.transferFrom(\\_liquidityHolderAddr, address(this), \\_liquidityAmount); \\n \\n uint256 \\_amountToMint = \\_liquidityAmount.mul(PERCENTAGE\\_100).div(getDAIToDAIxRatio());\\n totalLiquidity = totalLiquidity.add(\\_liquidityAmount);\\n \\_mintERC20(\\_liquidityHolderAddr, \\_amountToMint);\\n\\n if (\\_isLM) {\\n liquidityFromLM[\\_liquidityHolderAddr] = liquidityFromLM[\\_liquidityHolderAddr].add(\\_liquidityAmount);\\n }\\n\\n \\_updateWithdrawalQueue();\\n\\n emit AddLiquidity(\\_liquidityHolderAddr, \\_liquidityAmount, totalLiquidity);\\n}\\n```\\n |
Optimize gas usage when checking max length of arrays | low | There are a few cases where some arrays have to be limited to a number of items.\\nAnd the max size is enforced by removing the last item if the array reached max size + 1.\\n```\\nif (leaderboard.length == MAX\\_LEADERBOARD\\_SIZE.add(1)) {\\n leaderboard.pop();\\n}\\n```\\n\\n```\\nif (topUsers.length == MAX\\_TOP\\_USERS\\_SIZE.add(1)) {\\n topUsers.pop();\\n}\\n```\\n\\n```\\nif (\\_addresses.length == MAX\\_GROUP\\_LEADERS\\_SIZE.add(1)) {\\n groupsLeaders[\\_referralLink].pop();\\n}\\n```\\n\\nA simpler and cheaper way to check if an item should be removed is to change the condition to\\n```\\nif (limitedSizedArray.length > MAX\\_DEFINED\\_SIZE\\_FOR\\_ARRAY) {\\n limitedSizedArray.pop();\\n}\\n```\\n\\nThis check does not need or do a SafeMath call (which is more expensive), and because of the limited number of items, as well as a practical impossibility to add enough items to overflow the limit, makes it a preferred way to check the maximum limit. | Rewrite the checks and remove SafeMath operations, as well as the addition by 1 and change the check to a “greater than” verification. | null | ```\\nif (leaderboard.length == MAX\\_LEADERBOARD\\_SIZE.add(1)) {\\n leaderboard.pop();\\n}\\n```\\n |
Methods return values that are never used | low | When a user calls `investDAI` these 3 methods are called internally:\\n```\\n\\_updateTopUsers();\\n\\_updateLeaderboard(\\_userTeamInfo.teamAddr);\\n\\_updateGroupLeaders(\\_userTeamInfo.teamAddr);\\n```\\n\\nEach method returns a boolean, but the value is never used. It is also unclear what the value should represent. | Remove the returned variable or use it in method `investDAI`. | null | ```\\n\\_updateTopUsers();\\n\\_updateLeaderboard(\\_userTeamInfo.teamAddr);\\n\\_updateGroupLeaders(\\_userTeamInfo.teamAddr);\\n```\\n |
Save some gas when looping over state arrays | low | There are a few loops over state arrays in `LiquidutyMining`.\\n```\\nfor (uint256 i = 0; i < leaderboard.length; i++) {\\n```\\n\\n```\\nfor (uint256 i = 0; i < topUsers.length; i++) {\\n```\\n\\nConsider caching the length in a local variable to reduce gas costs.\\nSimilar to\\n```\\nuint256 \\_usersNumber = allUsers.length;\\n```\\n\\n```\\nfor (uint256 i = 0; i < \\_usersNumber; i++) {\\n```\\n | Reduce gas cost by caching array state length in a local variable. | null | ```\\nfor (uint256 i = 0; i < leaderboard.length; i++) {\\n```\\n |
Optimize gas costs when handling liquidity start and end times | low | When the `LiquidityMining` contract is deployed, `startLiquidityMiningTime` saves the current block timestamp.\\n```\\nstartLiquidityMiningTime = block.timestamp; \\n```\\n\\nThis value is never changed.\\nThere also exists an end limit calculated by `getEndLMTime`.\\n```\\nfunction getEndLMTime() public view override returns (uint256) {\\n return startLiquidityMiningTime.add(2 weeks);\\n}\\n```\\n\\nThis value is also fixed, once the start was defined.\\nNone of the values change after the contract was deployed. This is why you can use the immutable feature provided by Solidity.\\nIt will reduce costs significantly.\\n```\\ncontract A {\\n uint public immutable start;\\n uint public immutable end;\\n \\n constructor() {\\n start = block.timestamp;\\n end = block.timestamp + 2 weeks;\\n }\\n}\\n```\\n\\nThis contract defines 2 variables: `start` and `end` and their value is fixed on deploy and cannot be changed.\\nIt does not need to use `SafeMath` because there's no risk of overflowing.\\nSetting `public` on both variables creates getters, and calling `A.start()` and `A.end()` returns the respective values.\\nHaving set as immutable does not request EVM storage and makes them very cheap to access. | Use Solidity's immutable feature to reduce gas costs and rename variables for consistency.\\nUse the example for inspiration. | null | ```\\nstartLiquidityMiningTime = block.timestamp; \\n```\\n |
Computing the quote should be done for a positive amount of tokens | low | When a policy is bought, a quote is requested from the `PolicyQuote` contract.\\n```\\nfunction \\_buyPolicyFor(\\n address \\_policyHolderAddr,\\n uint256 \\_epochsNumber,\\n uint256 \\_coverTokens\\n) internal {\\n```\\n\\n```\\nuint256 \\_totalPrice = policyQuote.getQuote(\\_totalSeconds, \\_coverTokens, address(this));\\n```\\n\\nThe `getQuote` call is then forwarded to an internal function\\n```\\nfunction getQuote(uint256 \\_durationSeconds, uint256 \\_tokens, address \\_policyBookAddr)\\n external view override returns (uint256 \\_daiTokens)\\n{\\n \\_daiTokens = \\_getQuote(\\_durationSeconds, \\_tokens, \\_policyBookAddr);\\n}\\n```\\n\\n```\\nfunction \\_getQuote(uint256 \\_durationSeconds, uint256 \\_tokens, address \\_policyBookAddr)\\n internal view returns (uint256)\\n{\\n```\\n\\nThere are some basic checks that make sure the total covered tokens with the requested quote do not exceed the total liquidity. On top of that check, it makes sure the total liquidity is positive.\\n```\\nrequire(\\_totalCoverTokens.add(\\_tokens) <= \\_totalLiquidity, "PolicyBook: Requiring more than there exists");\\nrequire(\\_totalLiquidity > 0, "PolicyBook: The pool is empty");\\n```\\n\\nBut there is no check for the number of quoted tokens. It should also be positive. | Add an additional check for the number of quoted tokens to be positive. The check could fail or return 0, depending on your use case.\\nIf you add a check for the number of quoted tokens to be positive, the check for `_totalLiquidity` to be positive becomes obsolete and can be removed. | null | ```\\nfunction \\_buyPolicyFor(\\n address \\_policyHolderAddr,\\n uint256 \\_epochsNumber,\\n uint256 \\_coverTokens\\n) internal {\\n```\\n |
Anyone can win all the funds from the LiquidityMining without investing any DAI | high | When a user decides to `investDAI` in the `LiquidityMining` contract, the policy book address is passed as a parameter:\\n```\\nfunction investDAI(uint256 \\_tokensAmount, address \\_policyBookAddr) external override {\\n```\\n\\nBut this parameter is never checked and only used at the end of the function:\\n```\\nIPolicyBook(\\_policyBookAddr).addLiquidityFromLM(msg.sender, \\_tokensAmount);\\n```\\n\\nThe attacker can pass the address of a simple multisig that will process this transaction successfully without doing anything. And pretend to invest a lot of DAI without actually doing that to win all the rewards in the `LiquidityMining` contract. | Check that the pool address is valid. | null | ```\\nfunction investDAI(uint256 \\_tokensAmount, address \\_policyBookAddr) external override {\\n```\\n |
Liquidity withdrawal can be blocked | high | The main problem in that issue is that the liquidity provider may face many potential issues when withdrawing the liquidity. Under some circumstances, a normal user will never be able to withdraw the liquidity. This issue consists of multiple factors that are interconnected and share the same solution.\\nThere are no partial withdrawals when in the queue. When the withdrawal request is added to the queue, it can only be processed fully:\\n```\\naddress \\_currentAddr = withdrawalQueue.head();\\nuint256 \\_tokensToWithdraw = withdrawalsInfo[\\_currentAddr].withdrawalAmount;\\n \\nuint256 \\_amountInDAI = convertDAIXtoDAI(\\_tokensToWithdraw);\\n \\nif (\\_availableLiquidity < \\_amountInDAI) {\\n break;\\n}\\n```\\n\\nBut when the request is not in the queue, it can still be processed partially, and the rest of the locked tokens will wait in the queue.\\n```\\n} else if (\\_availableLiquidity < convertDAIXtoDAI(\\_tokensToWithdraw)) {\\n uint256 \\_availableDAIxTokens = convertDAIToDAIx(\\_availableLiquidity);\\n uint256 \\_currentWithdrawalAmount = \\_tokensToWithdraw.sub(\\_availableDAIxTokens);\\n withdrawalsInfo[\\_msgSender()].withdrawalAmount = \\_currentWithdrawalAmount;\\n \\n aggregatedQueueAmount = aggregatedQueueAmount.add(\\_currentWithdrawalAmount);\\n withdrawalQueue.push(\\_msgSender());\\n \\n \\_withdrawLiquidity(\\_msgSender(), \\_availableDAIxTokens);\\n} else {\\n```\\n\\nIf there's a huge request in the queue, it can become a bottleneck that does not allow others to withdraw even if there is enough free liquidity.\\nWithdrawals can be blocked forever by the bots.\\nThe withdrawal can only be requested if there are enough free funds in the contract. But once these funds appear, the bots can instantly buy a policy, and for the normal users, it will be impossible to request the withdrawal. Even when a withdrawal is requested and then in the queue, the same problem appears at that stage.\\nThe policy can be bought even if there are pending withdrawals in the queue. | One of the solutions would be to implement the following changes, but the team should thoroughly consider them:\\nAllow people to request the withdrawal even if there is not enough liquidity at the moment.\\nDo not allow people to buy policies if there are pending withdrawals in the queue and cannot be executed.\\n(Optional) Even when the queue is empty, do not allow people to buy policies if there is not enough liquidity for the pending requests (that are not yet in the queue).\\n(Optional if the points above are implemented) Allow partial executions of the withdrawals in the queue. | null | ```\\naddress \\_currentAddr = withdrawalQueue.head();\\nuint256 \\_tokensToWithdraw = withdrawalsInfo[\\_currentAddr].withdrawalAmount;\\n \\nuint256 \\_amountInDAI = convertDAIXtoDAI(\\_tokensToWithdraw);\\n \\nif (\\_availableLiquidity < \\_amountInDAI) {\\n break;\\n}\\n```\\n |
The totalCoverTokens can be decreased before the claim is committed | high | The `totalCoverTokens` is decreased right after the policy duration ends (_endEpochNumber). When that happens, the liquidity providers can withdraw their funds:\\n```\\npolicyHolders[\\_msgSender()] = PolicyHolder(\\_coverTokens, currentEpochNumber,\\n \\_endEpochNumber, \\_totalPrice, \\_reinsurancePrice);\\n\\nepochAmounts[\\_endEpochNumber] = epochAmounts[\\_endEpochNumber].add(\\_coverTokens);\\n```\\n\\n```\\nuint256 \\_countOfPassedEpoch = block.timestamp.sub(epochStartTime).div(EPOCH\\_DURATION);\\n\\nnewTotalCoverTokens = totalCoverTokens;\\nlastEpochUpdate = currentEpochNumber;\\nnewEpochNumber = \\_countOfPassedEpoch.add(1);\\n\\nfor (uint256 i = lastEpochUpdate; i < newEpochNumber; i++) {\\n newTotalCoverTokens = newTotalCoverTokens.sub(epochAmounts[i]); \\n}\\n```\\n\\nOn the other hand, the claim can be created while the policy is still “active”. And is considered active until one week after the policy expired:\\n```\\nfunction isPolicyActive(address \\_userAddr, address \\_policyBookAddr) public override view returns (bool) {\\n PolicyInfo storage \\_currentInfo = policyInfos[\\_userAddr][\\_policyBookAddr];\\n\\n if (\\_currentInfo.endTime == 0) {\\n return false;\\n }\\n\\n return \\_currentInfo.endTime.add(STILL\\_CLAIMABLE\\_FOR) > block.timestamp;\\n}\\n```\\n\\nBy the time when the claim is created + voted, the liquidity provider can potentially withdraw all of their funds already, and the claim will fail. | Make sure that there will always be enough funds for the claim. | null | ```\\npolicyHolders[\\_msgSender()] = PolicyHolder(\\_coverTokens, currentEpochNumber,\\n \\_endEpochNumber, \\_totalPrice, \\_reinsurancePrice);\\n\\nepochAmounts[\\_endEpochNumber] = epochAmounts[\\_endEpochNumber].add(\\_coverTokens);\\n```\\n |
The totalCoverTokens is not decreased after the claim happened | high | When the claim happens and the policy is removed, the `totalCoverTokens` should be decreased instantly, that's why the scheduled reduction value is removed:\\n```\\nPolicyHolder storage holder = policyHolders[claimer];\\n\\nepochAmounts[holder.endEpochNumber] = epochAmounts[holder.endEpochNumber].sub(holder.coverTokens);\\ntotalLiquidity = totalLiquidity.sub(claimAmount);\\n\\ndaiToken.transfer(claimer, claimAmount);\\n \\ndelete policyHolders[claimer];\\npolicyRegistry.removePolicy(claimer);\\n```\\n\\nBut the `totalCoverTokens` is not changed and will have the coverage from the removed policy forever. | Decrease the `totalCoverTokens` inside the `commitClaim` function. | null | ```\\nPolicyHolder storage holder = policyHolders[claimer];\\n\\nepochAmounts[holder.endEpochNumber] = epochAmounts[holder.endEpochNumber].sub(holder.coverTokens);\\ntotalLiquidity = totalLiquidity.sub(claimAmount);\\n\\ndaiToken.transfer(claimer, claimAmount);\\n \\ndelete policyHolders[claimer];\\npolicyRegistry.removePolicy(claimer);\\n```\\n |
The Queue remove function does not remove the item completely | high | When removing an item in a queue, the following function is used:\\n```\\nfunction remove(UniqueAddressQueue storage baseQueue, address addrToRemove) internal returns (bool) {\\n if (!contains(baseQueue, addrToRemove)) {\\n return false;\\n }\\n\\n if (baseQueue.HEAD == addrToRemove) {\\n return removeFirst(baseQueue);\\n }\\n\\n if (baseQueue.TAIL == addrToRemove) {\\n return removeLast(baseQueue);\\n }\\n\\n address prevAddr = baseQueue.queue[addrToRemove].prev;\\n address nextAddr = baseQueue.queue[addrToRemove].next;\\n baseQueue.queue[prevAddr].next = nextAddr;\\n baseQueue.queue[nextAddr].prev = prevAddr;\\n baseQueue.queueLength--;\\n\\n return true;\\n}\\n```\\n\\nAs the result, the `baseQueue.queue[addrToRemove]` is not deleted, so the `contains` function will still return `True` after the removal. | Remove the element from the queue completely. | null | ```\\nfunction remove(UniqueAddressQueue storage baseQueue, address addrToRemove) internal returns (bool) {\\n if (!contains(baseQueue, addrToRemove)) {\\n return false;\\n }\\n\\n if (baseQueue.HEAD == addrToRemove) {\\n return removeFirst(baseQueue);\\n }\\n\\n if (baseQueue.TAIL == addrToRemove) {\\n return removeLast(baseQueue);\\n }\\n\\n address prevAddr = baseQueue.queue[addrToRemove].prev;\\n address nextAddr = baseQueue.queue[addrToRemove].next;\\n baseQueue.queue[prevAddr].next = nextAddr;\\n baseQueue.queue[nextAddr].prev = prevAddr;\\n baseQueue.queueLength--;\\n\\n return true;\\n}\\n```\\n |
Optimization issue | medium | The codebase is huge, and there are still a lot of places where these complications and gas efficiency can be improved.\\n`_updateTopUsers`, `_updateGroupLeaders`, `_updateLeaderboard` are having a similar mechanism of adding users to a sorted set which makes more storage operations than needed:\\n```\\nuint256 \\_tmpIndex = \\_currentIndex - 1;\\nuint256 \\_currentUserAmount = usersTeamInfo[msg.sender].stakedAmount;\\n \\nwhile (\\_currentUserAmount > usersTeamInfo[topUsers[\\_tmpIndex]].stakedAmount) {\\n address \\_tmpAddr = topUsers[\\_tmpIndex];\\n topUsers[\\_tmpIndex] = msg.sender;\\n topUsers[\\_tmpIndex + 1] = \\_tmpAddr;\\n \\n if (\\_tmpIndex == 0) {\\n break;\\n }\\n \\n \\_tmpIndex--;\\n}\\n```\\n\\nInstead of doing 2 operations per item that is lower than the new_item, same can be done with one operation: while `topUsers[_tmpIndex]` is lower than the new itemtopUsers[_tmpIndex + 1] = `topUsers[_tmpIndex]`.\\ncreating the Queue library looks like overkill `for` the intended task. It is only used `for` the withdrawal queue in the PolicyBook. The structure stores and processes extra data, which is unnecessary and more expensive. A larger codebase also has a higher chance of introducing a bug (and it happened here https://github.com/ConsenSys/bridge-mutual-audit-2021-03/issues/25). It's usually better to have a simpler and optimized version like described here issue 5.14.\\nThere are a few `for` loops that are using `uint8` iterators. It's unnecessary and can be even more expensive because, under the hood, it's additionally converted to `uint256` all the time. In general, shrinking data to `uint8` makes sense to optimize storage slots, but that's not the case here.\\nThe value that is calculated in a loop can be obtained simpler by just having a 1-line formula:\\n```\\nfunction \\_getAvailableMonthForReward(address \\_userAddr) internal view returns (uint256) {\\n uint256 \\_oneMonth = 30 days;\\n uint256 \\_startRewardTime = getEndLMTime();\\n \\n uint256 \\_countOfRewardedMonth = countsOfRewardedMonth[usersTeamInfo[\\_userAddr].teamAddr][\\_userAddr];\\n uint256 \\_numberOfMonthForReward;\\n \\n for (uint256 i = \\_countOfRewardedMonth; i < MAX\\_MONTH\\_TO\\_GET\\_REWARD; i++) {\\n if (block.timestamp > \\_startRewardTime.add(\\_oneMonth.mul(i))) {\\n \\_numberOfMonthForReward++;\\n } else {\\n break;\\n }\\n }\\n \\n return \\_numberOfMonthForReward;\\n}\\n```\\n\\nThe mapping is using 2 keys, but the first key is strictly defined by the second one, so there's no need for it:\\n```\\n// Referral link => Address => count of rewarded month\\nmapping (address => mapping (address => uint256)) public countsOfRewardedMonth;\\n```\\n\\nThere are a lot of structures in the code with duplicated and unnecessary data, for example:\\n```\\nstruct UserTeamInfo {\\n string teamName;\\n address teamAddr;\\n \\n uint256 stakedAmount;\\n bool isNFTDistributed;\\n}\\n```\\n\\nHere the structure is created for every team member, duplicating the team name for each member. | Optimize and simplify the code. | null | ```\\nuint256 \\_tmpIndex = \\_currentIndex - 1;\\nuint256 \\_currentUserAmount = usersTeamInfo[msg.sender].stakedAmount;\\n \\nwhile (\\_currentUserAmount > usersTeamInfo[topUsers[\\_tmpIndex]].stakedAmount) {\\n address \\_tmpAddr = topUsers[\\_tmpIndex];\\n topUsers[\\_tmpIndex] = msg.sender;\\n topUsers[\\_tmpIndex + 1] = \\_tmpAddr;\\n \\n if (\\_tmpIndex == 0) {\\n break;\\n }\\n \\n \\_tmpIndex--;\\n}\\n```\\n |
The aggregatedQueueAmount value is used inconsistently | medium | The `aggregatedQueueAmount` variable represents the cumulative DAIx amount in the queue that is waiting for the withdrawal. When requesting the withdrawal, this value is used as the amount of DAI that needs to be withdrawn, which may be significantly different:\\n```\\nrequire(totalLiquidity >= totalCoverTokens.add(aggregatedQueueAmount).add(\\_daiTokensToWithdraw),\\n "PB: Not enough available liquidity");\\n```\\n\\nThat may lead to allowing the withdrawal request even if it shouldn't be allowed and the opposite. | Convert `aggregatedQueueAmount` to DAI in the `_requestWithdrawal`. | null | ```\\nrequire(totalLiquidity >= totalCoverTokens.add(aggregatedQueueAmount).add(\\_daiTokensToWithdraw),\\n "PB: Not enough available liquidity");\\n```\\n |
The claim can only be done once | medium | When the claim happens, the policy is removed afterward:\\n```\\nfunction commitClaim(address claimer, uint256 claimAmount)\\n external \\n override\\n onlyClaimVoting\\n updateBMIDAIXStakingReward\\n{\\n PolicyHolder storage holder = policyHolders[claimer];\\n\\n epochAmounts[holder.endEpochNumber] = epochAmounts[holder.endEpochNumber].sub(holder.coverTokens);\\n totalLiquidity = totalLiquidity.sub(claimAmount);\\n \\n daiToken.transfer(claimer, claimAmount);\\n \\n delete policyHolders[claimer];\\n policyRegistry.removePolicy(claimer);\\n}\\n```\\n\\nIf the claim amount is much lower than the coverage, the users are incentivized not to submit it and wait until the end of the coverage period to accumulate all the claims into one. | Allow the policyholders to submit multiple claims until the `coverTokens` is not reached. | null | ```\\nfunction commitClaim(address claimer, uint256 claimAmount)\\n external \\n override\\n onlyClaimVoting\\n updateBMIDAIXStakingReward\\n{\\n PolicyHolder storage holder = policyHolders[claimer];\\n\\n epochAmounts[holder.endEpochNumber] = epochAmounts[holder.endEpochNumber].sub(holder.coverTokens);\\n totalLiquidity = totalLiquidity.sub(claimAmount);\\n \\n daiToken.transfer(claimer, claimAmount);\\n \\n delete policyHolders[claimer];\\n policyRegistry.removePolicy(claimer);\\n}\\n```\\n |
iETH.exchangeRateStored may not be accurate when invoked from external contracts | high | `iETH.exchangeRateStored` returns the exchange rate of the contract as a function of the current cash of the contract. In the case of `iETH`, current cash is calculated as the contract's ETH balance minus msg.value:\\n```\\n/\\*\\*\\n \\* @dev Gets balance of this contract in terms of the underlying\\n \\*/\\nfunction \\_getCurrentCash() internal view override returns (uint256) {\\n return address(this).balance.sub(msg.value);\\n}\\n```\\n\\n`msg.value` is subtracted because the majority of `iETH` methods are payable, and `msg.value` is implicitly added to a contract's balance before execution begins. If `msg.value` were not subtracted, the value sent with a call could be used to inflate the contract's exchange rate artificially.\\nAs part of execution, `iETH` makes calls to the `Controller`, which performs important checks using (among other things) the stored exchange rate. When `exchangeRateStored` is invoked from the `Controller`, the call context has a `msg.value` of 0. However, the `msg.value` sent by the initial `iETH` execution is still included in the contract's balance. This means that the `Controller` receives an exchange rate inflated by the initial call's `msg.value`.\\nThis problem occurs in multiple locations in the Controller:\\n`beforeMint` uses the exchange rate to ensure the supply capacity of the market is not reached. In this case, inflation would prevent the entire supply capacity of the market from being utilized:\\n```\\n// Check the iToken's supply capacity, -1 means no limit\\nuint256 \\_totalSupplyUnderlying =\\n IERC20Upgradeable(\\_iToken).totalSupply().rmul(\\n IiToken(\\_iToken).exchangeRateStored()\\n );\\nrequire(\\n \\_totalSupplyUnderlying.add(\\_mintAmount) <= \\_market.supplyCapacity,\\n "Token supply capacity reached"\\n);\\n```\\n\\n`beforeLiquidateBorrow` uses the exchange rate via `calcAccountEquity` to calculate the value of the borrower's collateral. In this case, inflation would increase the account's equity, which could prevent the liquidator from liquidating:\\n```\\n(, uint256 \\_shortfall, , ) = calcAccountEquity(\\_borrower);\\n\\nrequire(\\_shortfall > 0, "Account does not have shortfall");\\n```\\n | Resolution\\nThis issue was addressed in commit `9876e3a` by using a modifier to track the current `msg.value` of payable functions.\\nRather than having the `Controller` query the `iETH.exchangeRateStored`, the exchange rate could be passed-in to `Controller` methods as a parameter.\\nEnsure no other components in the system rely on `iETH.exchangeRateStored` after being called from `iETH`. | null | ```\\n/\\*\\*\\n \\* @dev Gets balance of this contract in terms of the underlying\\n \\*/\\nfunction \\_getCurrentCash() internal view override returns (uint256) {\\n return address(this).balance.sub(msg.value);\\n}\\n```\\n |
Unbounded loop in Controller.calcAccountEquity allows DoS on liquidation | high | `Controller.calcAccountEquity` calculates the relative value of a user's supplied collateral and their active borrow positions. Users may mark an arbitrary number of assets as collateral, and may borrow from an arbitrary number of assets. In order to calculate the value of both of these positions, this method performs two loops.\\nFirst, to calculate the sum of the value of a user's collateral:\\n```\\n// Calculate value of all collaterals\\n// collateralValuePerToken = underlyingPrice \\* exchangeRate \\* collateralFactor\\n// collateralValue = balance \\* collateralValuePerToken\\n// sumCollateral += collateralValue\\nuint256 \\_len = \\_accountData.collaterals.length();\\nfor (uint256 i = 0; i < \\_len; i++) {\\n IiToken \\_token = IiToken(\\_accountData.collaterals.at(i));\\n```\\n\\nSecond, to calculate the sum of the value of a user's borrow positions:\\n```\\n// Calculate all borrowed value\\n// borrowValue = underlyingPrice \\* underlyingBorrowed / borrowFactor\\n// sumBorrowed += borrowValue\\n\\_len = \\_accountData.borrowed.length();\\nfor (uint256 i = 0; i < \\_len; i++) {\\n IiToken \\_token = IiToken(\\_accountData.borrowed.at(i));\\n```\\n\\nFrom dForce, we learned that 200 or more assets would be supported by the Controller. This means that a user with active collateral and borrow positions on all 200 supported assets could force any `calcAccountEquity` action to perform some 400 iterations of these loops, each with several expensive external calls.\\nBy modifying dForce's unit test suite, we showed that an attacker could force the cost of `calcAccountEquity` above the block gas limit. This would prevent all of the following actions, as each relies on calcAccountEquity:\\n`iToken.transfer` and `iToken.transferFrom`\\n`iToken.redeem` and `iToken.redeemUnderlying`\\n`iToken.borrow`\\n`iToken.liquidateBorrow` and `iToken.seize`\\nThe following actions would still be possible:\\n`iToken.mint`\\n`iToken.repayBorrow` and `iToken.repayBorrowBehalf`\\nAs a result, an attacker may abuse the unbounded looping in `calcAccountEquity` to prevent the liquidation of underwater positions. We provided dForce with a PoC here: gist. | There are many possible ways to address this issue. Some ideas have been outlined below, and it may be that a combination of these ideas is the best approach:\\nIn general, cap the number of markets and borrowed assets a user may have: The primary cause of the DoS is that the number of collateral and borrow positions held by a user is only restricted by the number of supported assets. The PoC provided above showed that somewhere around 150 collateral positions and 150 borrow positions, the gas costs of `calcAccountEquity` use most of the gas in a block. Given that gas prices often spike along with turbulent market conditions and that liquidations are far more likely in turbulent market conditions, a cap on active markets / borrows should be much lower than 150 each so as to keep the cost of liquidations as low as possible.\\ndForce should perform their own gas cost estimates to determine a cap, and choose a safe, low value. Estimates should be performed on the high-level `liquidateBorrow` method, so as to simulate an actual liquidation event. Additionally, estimates should factor in a changing block gas limit, and the possibility of opcode gas costs changing in future forks. It may be wise to make this cap configurable, so that the limits may be adjusted for future conditions. | null | ```\\n// Calculate value of all collaterals\\n// collateralValuePerToken = underlyingPrice \\* exchangeRate \\* collateralFactor\\n// collateralValue = balance \\* collateralValuePerToken\\n// sumCollateral += collateralValue\\nuint256 \\_len = \\_accountData.collaterals.length();\\nfor (uint256 i = 0; i < \\_len; i++) {\\n IiToken \\_token = IiToken(\\_accountData.collaterals.at(i));\\n```\\n |
Fix utilization rate computation and respect reserves when lending | medium | The utilization rate `UR` of an asset forms the basis for interest calculations and is defined as `borrows / ( borrows + cash - reserves)`.\\n```\\n/\\*\\*\\n \\* @notice Calculate the utilization rate: `\\_borrows / (\\_cash + \\_borrows - \\_reserves)`\\n \\* @param \\_cash Asset balance\\n \\* @param \\_borrows Asset borrows\\n \\* @param \\_reserves Asset reserves\\n \\* @return Asset utilization [0, 1e18]\\n \\*/\\nfunction utilizationRate(\\n uint256 \\_cash,\\n uint256 \\_borrows,\\n uint256 \\_reserves\\n) internal pure returns (uint256) {\\n // Utilization rate is 0 when there are no borrows\\n if (\\_borrows == 0) return 0;\\n\\n return \\_borrows.mul(BASE).div(\\_cash.add(\\_borrows).sub(\\_reserves));\\n}\\n```\\n\\nThe implicit assumption here is that `reserves` <= cash; in this case — and if we define `UR` as `0` for `borrows == 0` — we have `0` <= `UR` <=1. We can view `cash` - `reserves` as “available cash”. However, the system does not guarantee that `reserves` never exceeds `cash`. If `reserves` > `cash` (and borrows + `cash` - `reserves` > 0), the formula for `UR` above gives a utilization rate above `1`. This doesn't make much sense conceptually and has undesirable technical consequences; an especially severe one is analyzed in issue 4.4. | If `reserves > cash` — or, in other words, available cash is negative — this means part of the `reserves` have been borrowed, which ideally shouldn't happen in the first place. However, the `reserves` grow automatically over time, so it might be difficult to avoid this entirely. We recommend (1) avoiding this situation whenever it is possible and (2) fixing the `UR` computation such that it deals more gracefully with this scenario. More specifically:\\nLoan amounts should not be checked to be smaller than or equal to `cash` but `cash - reserves` (which might be negative). Note that the current check against `cash` happens more or less implicitly because the transfer just fails for insufficient `cash`.\\nMake the utilization rate computation return `1` if `reserves > cash` (unless borrows == `0`, in which case return `0` as is already the case).\\nRemark\\nInternally, the utilization rate and other fractional values are scaled by `1e18`. The discussion above has a more conceptual than technical perspective, so we used unscaled numbers. When making changes to the code, care must be taken to apply the scaling. | null | ```\\n/\\*\\*\\n \\* @notice Calculate the utilization rate: `\\_borrows / (\\_cash + \\_borrows - \\_reserves)`\\n \\* @param \\_cash Asset balance\\n \\* @param \\_borrows Asset borrows\\n \\* @param \\_reserves Asset reserves\\n \\* @return Asset utilization [0, 1e18]\\n \\*/\\nfunction utilizationRate(\\n uint256 \\_cash,\\n uint256 \\_borrows,\\n uint256 \\_reserves\\n) internal pure returns (uint256) {\\n // Utilization rate is 0 when there are no borrows\\n if (\\_borrows == 0) return 0;\\n\\n return \\_borrows.mul(BASE).div(\\_cash.add(\\_borrows).sub(\\_reserves));\\n}\\n```\\n |
If Base._updateInterest fails, the entire system will halt | medium | Before executing most methods, the `iETH` and `iToken` contracts update interest accumulated on borrows via the method `Base._updateInterest`. This method uses the contract's interest rate model to calculate the borrow interest rate. If the calculated value is above `maxBorrowRate` (0.001e18), the method will revert:\\n```\\nfunction \\_updateInterest() internal virtual override {\\n InterestLocalVars memory \\_vars;\\n \\_vars.currentCash = \\_getCurrentCash();\\n \\_vars.totalBorrows = totalBorrows;\\n \\_vars.totalReserves = totalReserves;\\n\\n // Gets the current borrow interest rate.\\n \\_vars.borrowRate = interestRateModel.getBorrowRate(\\n \\_vars.currentCash,\\n \\_vars.totalBorrows,\\n \\_vars.totalReserves\\n );\\n require(\\n \\_vars.borrowRate <= maxBorrowRate,\\n "\\_updateInterest: Borrow rate is too high!"\\n );\\n```\\n\\nIf this method reverts, the entire contract may halt and be unrecoverable. The only ways to change the values used to calculate this interest rate lie in methods that must first call `Base._updateInterest`. In this case, those methods would fail.\\nOne other potential avenue for recovery exists: the Owner role may update the interest rate calculation contract via TokenAdmin._setInterestRateModel:\\n```\\n/\\*\\*\\n \\* @dev Sets a new interest rate model.\\n \\* @param \\_newInterestRateModel The new interest rate model.\\n \\*/\\nfunction \\_setInterestRateModel(\\n IInterestRateModelInterface \\_newInterestRateModel\\n) external virtual onlyOwner settleInterest {\\n // Gets current interest rate model.\\n IInterestRateModelInterface \\_oldInterestRateModel = interestRateModel;\\n\\n // Ensures the input address is the interest model contract.\\n require(\\n \\_newInterestRateModel.isInterestRateModel(),\\n "\\_setInterestRateModel: This is not the rate model contract!"\\n );\\n\\n // Set to the new interest rate model.\\n interestRateModel = \\_newInterestRateModel;\\n```\\n\\nHowever, this method also calls `Base._updateInterest` before completing the upgrade, so it would fail as well.\\nWe used interest rate parameters taken from dForce's unit tests to determine whether any of the interest rate models could return a borrow rate that would cause this failure. The default `InterestRateModel` is deployed using these values:\\n```\\nbaseInterestPerBlock: 0\\ninterestPerBlock: 5.074e10\\nhighInterestPerBlock: 4.756e11\\nhigh: 0.75e18\\n```\\n\\nPlugging these values in to their borrow rate calculations, we determined that the utilization rate of the contract would need to be `2103e18` in order to reach the max borrow rate and trigger a failure. Plugging this in to the formula for utilization rate, we derived the following ratio:\\n`reserves >= (2102/2103)*borrows + cash`\\nWith the given interest rate parameters, if token reserves, total borrows, and underlying cash meet the above ratio, the interest rate model would return a borrow rate above the maximum, leading to the failure conditions described above. | Note that the examples above depend on the specific interest rate parameters configured by dForce. In general, with reasonable interest rate parameters and a reasonable reserve ratio, it seems unlikely that the maximum borrow rate will be reached. Consider implementing the following changes as a precaution:\\nAs utilization rate should be between `0` and `1` (scaled by 1e18), prevent utilization rate calculations from returning anything above `1e18`. See issue 4.3 for a more thorough discussion of this topic.\\nRemove the `settleInterest` modifier from TokenAdmin._setInterestRateModel: In a worst case scenario, this will allow the Owner role to update the interest rate model without triggering the failure in `Base._updateInterest`. | null | ```\\nfunction \\_updateInterest() internal virtual override {\\n InterestLocalVars memory \\_vars;\\n \\_vars.currentCash = \\_getCurrentCash();\\n \\_vars.totalBorrows = totalBorrows;\\n \\_vars.totalReserves = totalReserves;\\n\\n // Gets the current borrow interest rate.\\n \\_vars.borrowRate = interestRateModel.getBorrowRate(\\n \\_vars.currentCash,\\n \\_vars.totalBorrows,\\n \\_vars.totalReserves\\n );\\n require(\\n \\_vars.borrowRate <= maxBorrowRate,\\n "\\_updateInterest: Borrow rate is too high!"\\n );\\n```\\n |
RewardDistributor requirement prevents transition of Owner role to smart contract | medium | From dForce, we learned that the eventual plan for the system Owner role is to use a smart contract (a multisig or DAO). However, a requirement in `RewardDistributor` would prevent the `onlyOwner` method `_setDistributionFactors` from working in this case.\\n`_setDistributionFactors` calls `updateDistributionSpeed`, which requires that the caller is an EOA:\\n```\\n/\\*\\*\\n \\* @notice Update each iToken's distribution speed according to current global speed\\n \\* @dev Only EOA can call this function\\n \\*/\\nfunction updateDistributionSpeed() public override {\\n require(msg.sender == tx.origin, "only EOA can update speeds");\\n require(!paused, "Can not update speeds when paused");\\n\\n // Do the actual update\\n \\_updateDistributionSpeed();\\n}\\n```\\n\\nIn the event the Owner role is a smart contract, this statement would necessitate a complicated upgrade to restore full functionality. | Rather than invoking `updateDistributionSpeed`, have `_setDistributionFactors` directly call the internal helper `_updateDistributionSpeed`, which does not require the caller is an EOA. | null | ```\\n/\\*\\*\\n \\* @notice Update each iToken's distribution speed according to current global speed\\n \\* @dev Only EOA can call this function\\n \\*/\\nfunction updateDistributionSpeed() public override {\\n require(msg.sender == tx.origin, "only EOA can update speeds");\\n require(!paused, "Can not update speeds when paused");\\n\\n // Do the actual update\\n \\_updateDistributionSpeed();\\n}\\n```\\n |
MSDController._withdrawReserves does not update interest before withdrawal | medium | `MSDController._withdrawReserves` allows the Owner to mint the difference between an MSD asset's accumulated debt and earnings:\\n```\\nfunction \\_withdrawReserves(address \\_token, uint256 \\_amount)\\n external\\n onlyOwner\\n onlyMSD(\\_token)\\n{\\n (uint256 \\_equity, ) = calcEquity(\\_token);\\n\\n require(\\_equity >= \\_amount, "Token do not have enough reserve");\\n\\n // Increase the token debt\\n msdTokenData[\\_token].debt = msdTokenData[\\_token].debt.add(\\_amount);\\n\\n // Directly mint the token to owner\\n MSD(\\_token).mint(owner, \\_amount);\\n```\\n\\nDebt and earnings are updated each time the asset's `iMSD` and `MSDS` contracts are used for the first time in a given block. Because `_withdrawReserves` does not force an update to these values, it is possible for the withdrawal amount to be calculated using stale values. | Ensure `_withdrawReserves` invokes `iMSD.updateInterest()` and `MSDS.updateInterest()`. | null | ```\\nfunction \\_withdrawReserves(address \\_token, uint256 \\_amount)\\n external\\n onlyOwner\\n onlyMSD(\\_token)\\n{\\n (uint256 \\_equity, ) = calcEquity(\\_token);\\n\\n require(\\_equity >= \\_amount, "Token do not have enough reserve");\\n\\n // Increase the token debt\\n msdTokenData[\\_token].debt = msdTokenData[\\_token].debt.add(\\_amount);\\n\\n // Directly mint the token to owner\\n MSD(\\_token).mint(owner, \\_amount);\\n```\\n |
permit functions use deployment-time instead of execution-time chain ID | low | The contracts `Base`, `MSD`, and `MSDS` each have an EIP-2612-style `permit` function that supports approvals with EIP-712 signatures. We focus this discussion on the `Base` contract, but the same applies to `MSD` and `MSDS`.\\nWhen the contract is initialized, the chain ID is queried (with the `CHAINID` opcode) and becomes part of the `DOMAIN_SEPARATOR` — a hash of several values which (presumably) don't change over the lifetime of the contract and that can therefore be computed only once, when the contract is deployed.\\n```\\nfunction \\_initialize(\\n string memory \\_name,\\n string memory \\_symbol,\\n uint8 \\_decimals,\\n IControllerInterface \\_controller,\\n IInterestRateModelInterface \\_interestRateModel\\n) internal virtual {\\n controller = \\_controller;\\n interestRateModel = \\_interestRateModel;\\n accrualBlockNumber = block.number;\\n borrowIndex = BASE;\\n flashloanFeeRatio = 0.0008e18;\\n protocolFeeRatio = 0.25e18;\\n \\_\\_Ownable\\_init();\\n \\_\\_ERC20\\_init(\\_name, \\_symbol, \\_decimals);\\n \\_\\_ReentrancyGuard\\_init();\\n\\n uint256 chainId;\\n\\n assembly {\\n chainId := chainid()\\n }\\n DOMAIN\\_SEPARATOR = keccak256(\\n abi.encode(\\n keccak256(\\n "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"\\n ),\\n keccak256(bytes(\\_name)),\\n keccak256(bytes("1")),\\n chainId,\\n address(this)\\n )\\n );\\n}\\n```\\n\\nThe `DOMAIN_SEPARATOR` is supposed to prevent replay attacks by providing context for the signature; it is hashed into the digest to be signed.\\n```\\nbytes32 \\_digest =\\n keccak256(\\n abi.encodePacked(\\n "\\x19\\x01",\\n DOMAIN\\_SEPARATOR,\\n keccak256(\\n abi.encode(\\n PERMIT\\_TYPEHASH,\\n \\_owner,\\n \\_spender,\\n \\_value,\\n \\_currentNonce,\\n \\_deadline\\n )\\n )\\n )\\n );\\naddress \\_recoveredAddress = ecrecover(\\_digest, \\_v, \\_r, \\_s);\\nrequire(\\n \\_recoveredAddress != address(0) && \\_recoveredAddress == \\_owner,\\n "permit: INVALID\\_SIGNATURE!"\\n);\\n```\\n\\nThe chain ID is not necessarily constant, though. In the event of a chain split, only one of the resulting chains gets to keep the original chain ID and the other will have to use a new one. With the current pattern, a signature will be valid on both chains; if the `DOMAIN_SEPARATOR` is recomputed for every verification, a signature will only be valid on the chain that keeps the original ID — which is probably the intended behavior.\\nRemark\\nThe reason why the not necessarily constant chain ID is part of the supposedly constant `DOMAIN_SEPARATOR` is that EIP-712 predates the introduction of the `CHAINID` opcode. Originally, it was not possible to query the chain ID via opcode, so it had to be supplied to the constructor of a contract by the deployment script. | An obvious fix is to compute the `DOMAIN_SEPARATOR` dynamically in `permit`. However, since a chain split is a relatively unlikely event, it makes sense to compute the `DOMAIN_SEPARATOR` at deployment/initialization time and then check in `permit` whether the current chain ID equals the one that went into the `DOMAIN_SEPARATOR`. If that is true, we proceed as before. If the chain ID has changed, we could (1) just revert, or (2) recompute the `DOMAIN_SEPARATOR` with the new chain ID. Solution (1) is probably the easiest and most straightforward to implement, but it should be noted that it makes the `permit` functionality of this contract completely unusable on the new chain. | null | ```\\nfunction \\_initialize(\\n string memory \\_name,\\n string memory \\_symbol,\\n uint8 \\_decimals,\\n IControllerInterface \\_controller,\\n IInterestRateModelInterface \\_interestRateModel\\n) internal virtual {\\n controller = \\_controller;\\n interestRateModel = \\_interestRateModel;\\n accrualBlockNumber = block.number;\\n borrowIndex = BASE;\\n flashloanFeeRatio = 0.0008e18;\\n protocolFeeRatio = 0.25e18;\\n \\_\\_Ownable\\_init();\\n \\_\\_ERC20\\_init(\\_name, \\_symbol, \\_decimals);\\n \\_\\_ReentrancyGuard\\_init();\\n\\n uint256 chainId;\\n\\n assembly {\\n chainId := chainid()\\n }\\n DOMAIN\\_SEPARATOR = keccak256(\\n abi.encode(\\n keccak256(\\n "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"\\n ),\\n keccak256(bytes(\\_name)),\\n keccak256(bytes("1")),\\n chainId,\\n address(this)\\n )\\n );\\n}\\n```\\n |
iETH.receive() does not support contracts executing during their constructor | low | `iETH.receive()` requires that the caller is a contract:\\n```\\n/\\*\\*\\n \\* @notice receive ETH, used for flashloan repay.\\n \\*/\\nreceive() external payable {\\n require(\\n msg.sender.isContract(),\\n "receive: Only can call from a contract!"\\n );\\n}\\n```\\n\\nThis method uses the `extcodesize` of an account to check that the account belongs to a contract. However, contracts currently executing their constructor will have an `extcodesize` of 0, and will not be able to use this method.\\nThis is unlikely to cause significant issues, but dForce may want to consider supporting this edge case. | Use `msg.sender != tx.origin` as a more reliable method to detect use by a contract. | null | ```\\n/\\*\\*\\n \\* @notice receive ETH, used for flashloan repay.\\n \\*/\\nreceive() external payable {\\n require(\\n msg.sender.isContract(),\\n "receive: Only can call from a contract!"\\n );\\n}\\n```\\n |
Token approvals can be stolen in DAOfiV1Router01.addLiquidity() | high | `DAOfiV1Router01.addLiquidity()` creates the desired pair contract if it does not already exist, then transfers tokens into the pair and calls `DAOfiV1Pair.deposit()`. There is no validation of the address to transfer tokens from, so an attacker could pass in any address with nonzero token approvals to `DAOfiV1Router`. This could be used to add liquidity to a pair contract for which the attacker is the `pairOwner`, allowing the stolen funds to be retrieved using `DAOfiV1Pair.withdraw()`.\\n```\\nfunction addLiquidity(\\n LiquidityParams calldata lp,\\n uint deadline\\n) external override ensure(deadline) returns (uint256 amountBase) {\\n if (IDAOfiV1Factory(factory).getPair(\\n lp.tokenBase,\\n lp.tokenQuote,\\n lp.slopeNumerator,\\n lp.n,\\n lp.fee\\n ) == address(0)) {\\n IDAOfiV1Factory(factory).createPair(\\n address(this),\\n lp.tokenBase,\\n lp.tokenQuote,\\n msg.sender,\\n lp.slopeNumerator,\\n lp.n,\\n lp.fee\\n );\\n }\\n address pair = DAOfiV1Library.pairFor(\\n factory, lp.tokenBase, lp.tokenQuote, lp.slopeNumerator, lp.n, lp.fee\\n );\\n\\n TransferHelper.safeTransferFrom(lp.tokenBase, lp.sender, pair, lp.amountBase);\\n TransferHelper.safeTransferFrom(lp.tokenQuote, lp.sender, pair, lp.amountQuote);\\n amountBase = IDAOfiV1Pair(pair).deposit(lp.to);\\n}\\n```\\n | Transfer tokens from `msg.sender` instead of `lp.sender`. | null | ```\\nfunction addLiquidity(\\n LiquidityParams calldata lp,\\n uint deadline\\n) external override ensure(deadline) returns (uint256 amountBase) {\\n if (IDAOfiV1Factory(factory).getPair(\\n lp.tokenBase,\\n lp.tokenQuote,\\n lp.slopeNumerator,\\n lp.n,\\n lp.fee\\n ) == address(0)) {\\n IDAOfiV1Factory(factory).createPair(\\n address(this),\\n lp.tokenBase,\\n lp.tokenQuote,\\n msg.sender,\\n lp.slopeNumerator,\\n lp.n,\\n lp.fee\\n );\\n }\\n address pair = DAOfiV1Library.pairFor(\\n factory, lp.tokenBase, lp.tokenQuote, lp.slopeNumerator, lp.n, lp.fee\\n );\\n\\n TransferHelper.safeTransferFrom(lp.tokenBase, lp.sender, pair, lp.amountBase);\\n TransferHelper.safeTransferFrom(lp.tokenQuote, lp.sender, pair, lp.amountQuote);\\n amountBase = IDAOfiV1Pair(pair).deposit(lp.to);\\n}\\n```\\n |
The deposit of a new pair can be stolen | high | To create a new pair, a user is expected to call the same `addLiquidity()` (or the addLiquidityETH()) function of the router contract seen above:\\n```\\nfunction addLiquidity(\\n LiquidityParams calldata lp,\\n uint deadline\\n) external override ensure(deadline) returns (uint256 amountBase) {\\n if (IDAOfiV1Factory(factory).getPair(\\n lp.tokenBase,\\n lp.tokenQuote,\\n lp.slopeNumerator,\\n lp.n,\\n lp.fee\\n ) == address(0)) {\\n IDAOfiV1Factory(factory).createPair(\\n address(this),\\n lp.tokenBase,\\n lp.tokenQuote,\\n msg.sender,\\n lp.slopeNumerator,\\n lp.n,\\n lp.fee\\n );\\n }\\n address pair = DAOfiV1Library.pairFor(\\n factory, lp.tokenBase, lp.tokenQuote, lp.slopeNumerator, lp.n, lp.fee\\n );\\n\\n TransferHelper.safeTransferFrom(lp.tokenBase, lp.sender, pair, lp.amountBase);\\n TransferHelper.safeTransferFrom(lp.tokenQuote, lp.sender, pair, lp.amountQuote);\\n amountBase = IDAOfiV1Pair(pair).deposit(lp.to);\\n}\\n```\\n\\nThis function checks if the pair already exists and creates a new one if it does not. After that, the first and only deposit is made to that pair.\\nThe attacker can front-run that call and create a pair with the same parameters (thus, with the same address) by calling the `createPair` function of the `DAOfiV1Factory` contract. By calling that function directly, the attacker does not have to make the deposit when creating a new pair. The initial user will make this deposit, whose funds can now be withdrawn by the attacker. | There are a few factors/bugs that allowed this attack. All or some of them should be fixed:\\nThe `createPair` function of the `DAOfiV1Factory` contract can be called directly by anyone without depositing with any `router` address as the parameter. The solution could be to allow only the `router` to create a pair.\\nThe `addLiquidity` function checks that the pair does not exist yet. If the pair exists already, a deposit should only be made by the owner of the pair. But in general, a new pair shouldn't be deployed without depositing in the same transaction.\\nThe pair's address does not depend on the owner/creator. It might make sense to add that information to the salt. | null | ```\\nfunction addLiquidity(\\n LiquidityParams calldata lp,\\n uint deadline\\n) external override ensure(deadline) returns (uint256 amountBase) {\\n if (IDAOfiV1Factory(factory).getPair(\\n lp.tokenBase,\\n lp.tokenQuote,\\n lp.slopeNumerator,\\n lp.n,\\n lp.fee\\n ) == address(0)) {\\n IDAOfiV1Factory(factory).createPair(\\n address(this),\\n lp.tokenBase,\\n lp.tokenQuote,\\n msg.sender,\\n lp.slopeNumerator,\\n lp.n,\\n lp.fee\\n );\\n }\\n address pair = DAOfiV1Library.pairFor(\\n factory, lp.tokenBase, lp.tokenQuote, lp.slopeNumerator, lp.n, lp.fee\\n );\\n\\n TransferHelper.safeTransferFrom(lp.tokenBase, lp.sender, pair, lp.amountBase);\\n TransferHelper.safeTransferFrom(lp.tokenQuote, lp.sender, pair, lp.amountQuote);\\n amountBase = IDAOfiV1Pair(pair).deposit(lp.to);\\n}\\n```\\n |
Incorrect token decimal conversions can lead to loss of funds | high | The `_convert()` function in `DAOfiV1Pair` is used to accommodate tokens with varying `decimals()` values. There are three cases in which it implicitly returns 0 for any `amount`, the most notable of which is when `token.decimals() == resolution`.\\nAs a result of this, `getQuoteOut()` reverts any time either `baseToken` or `quoteToken` have `decimals == INTERNAL_DECIMALS` (currently hardcoded to 8).\\n`getBaseOut()` also reverts in most cases when either `baseToken` or `quoteToken` have `decimals() == INTERNAL_DECIMALS`. The exception is when `getBaseOut()` is called while `supply` is 0, as is the case in `deposit()`. This causes `getBaseOut()` to succeed, returning an incorrect value.\\nThe result of this is that no swaps can be performed in one of these pools, and the `deposit()` function will return an incorrect `amountBaseOut` of `baseToken` to the depositor, the balance of which can then be withdrawn by the `pairOwner`.\\n```\\nfunction \\_convert(address token, uint256 amount, uint8 resolution, bool to) private view returns (uint256 converted) {\\n uint8 decimals = IERC20(token).decimals();\\n uint256 diff = 0;\\n uint256 factor = 0;\\n converted = 0;\\n if (decimals > resolution) {\\n diff = uint256(decimals.sub(resolution));\\n factor = 10 \\*\\* diff;\\n if (to && amount >= factor) {\\n converted = amount.div(factor);\\n } else if (!to) {\\n converted = amount.mul(factor);\\n }\\n } else if (decimals < resolution) {\\n diff = uint256(resolution.sub(decimals));\\n factor = 10 \\*\\* diff;\\n if (to) {\\n converted = amount.mul(factor);\\n } else if (!to && amount >= factor) {\\n converted = amount.div(factor);\\n }\\n }\\n}\\n```\\n | The `_convert()` function should return `amount` when `token.decimals() == resolution`. Additionally, implicit return values should be avoided whenever possible, especially in functions that implement complex mathematical operations.\\n`BancorFormula.power(baseN, baseD, _, _)` does not support `baseN < baseD`, and checks should be added to ensure that any call to the `BancorFormula` conforms to the expected input ranges. | null | ```\\nfunction \\_convert(address token, uint256 amount, uint8 resolution, bool to) private view returns (uint256 converted) {\\n uint8 decimals = IERC20(token).decimals();\\n uint256 diff = 0;\\n uint256 factor = 0;\\n converted = 0;\\n if (decimals > resolution) {\\n diff = uint256(decimals.sub(resolution));\\n factor = 10 \\*\\* diff;\\n if (to && amount >= factor) {\\n converted = amount.div(factor);\\n } else if (!to) {\\n converted = amount.mul(factor);\\n }\\n } else if (decimals < resolution) {\\n diff = uint256(resolution.sub(decimals));\\n factor = 10 \\*\\* diff;\\n if (to) {\\n converted = amount.mul(factor);\\n } else if (!to && amount >= factor) {\\n converted = amount.div(factor);\\n }\\n }\\n}\\n```\\n |
The swapExactTokensForETH checks the wrong return value | high | The following lines are intended to check that the amount of tokens received from a swap is greater than the minimum amount expected from this swap (sp.amountOut):\\n```\\nuint amountOut = IWETH10(WETH).balanceOf(address(this));\\nrequire(\\n IWETH10(sp.tokenOut).balanceOf(address(this)).sub(balanceBefore) >= sp.amountOut,\\n 'DAOfiV1Router: INSUFFICIENT\\_OUTPUT\\_AMOUNT'\\n);\\n```\\n\\nInstead, it calculates the difference between the initial receiver's balance and the balance of the router. | Check the intended value. | null | ```\\nuint amountOut = IWETH10(WETH).balanceOf(address(this));\\nrequire(\\n IWETH10(sp.tokenOut).balanceOf(address(this)).sub(balanceBefore) >= sp.amountOut,\\n 'DAOfiV1Router: INSUFFICIENT\\_OUTPUT\\_AMOUNT'\\n);\\n```\\n |
DAOfiV1Pair.deposit() accepts deposits of zero, blocking the pool | medium | `DAOfiV1Pair.deposit()` is used to deposit liquidity into the pool. Only a single deposit can be made, so no liquidity can ever be added to a pool where `deposited == true`. The `deposit()` function does not check for a nonzero deposit amount in either token, so a malicious user that does not hold any of the `baseToken` or `quoteToken` can lock the pool by calling `deposit()` without first transferring any funds to the pool.\\n```\\nfunction deposit(address to) external override lock returns (uint256 amountBaseOut) {\\n require(msg.sender == router, 'DAOfiV1: FORBIDDEN\\_DEPOSIT');\\n require(deposited == false, 'DAOfiV1: DOUBLE\\_DEPOSIT');\\n reserveBase = IERC20(baseToken).balanceOf(address(this));\\n reserveQuote = IERC20(quoteToken).balanceOf(address(this));\\n // this function is locked and the contract can not reset reserves\\n deposited = true;\\n if (reserveQuote > 0) {\\n // set initial supply from reserveQuote\\n supply = amountBaseOut = getBaseOut(reserveQuote);\\n if (amountBaseOut > 0) {\\n \\_safeTransfer(baseToken, to, amountBaseOut);\\n reserveBase = reserveBase.sub(amountBaseOut);\\n }\\n }\\n emit Deposit(msg.sender, reserveBase, reserveQuote, amountBaseOut, to);\\n}\\n```\\n | Require a minimum deposit amount in both `baseToken` and `quoteToken`, and do not rely on any assumptions about the distribution of `baseToken` as part of the security model. | null | ```\\nfunction deposit(address to) external override lock returns (uint256 amountBaseOut) {\\n require(msg.sender == router, 'DAOfiV1: FORBIDDEN\\_DEPOSIT');\\n require(deposited == false, 'DAOfiV1: DOUBLE\\_DEPOSIT');\\n reserveBase = IERC20(baseToken).balanceOf(address(this));\\n reserveQuote = IERC20(quoteToken).balanceOf(address(this));\\n // this function is locked and the contract can not reset reserves\\n deposited = true;\\n if (reserveQuote > 0) {\\n // set initial supply from reserveQuote\\n supply = amountBaseOut = getBaseOut(reserveQuote);\\n if (amountBaseOut > 0) {\\n \\_safeTransfer(baseToken, to, amountBaseOut);\\n reserveBase = reserveBase.sub(amountBaseOut);\\n }\\n }\\n emit Deposit(msg.sender, reserveBase, reserveQuote, amountBaseOut, to);\\n}\\n```\\n |
Restricting DAOfiV1Pair functions to calls from router makes DAOfiV1Router01 security critical | medium | The `DAOfiV1Pair` functions `deposit()`, `withdraw()`, and `swap()` are all restricted to calls from the router in order to avoid losses from user error. However, this means that any unidentified issue in the Router could render all pair contracts unusable, potentially locking the pair owner's funds.\\nAdditionally, `DAOfiV1Factory.createPair()` allows any nonzero address to be provided as the `router`, so pairs can be initialized with a malicious `router` that users would be forced to interact with to utilize the pair contract.\\n```\\nfunction deposit(address to) external override lock returns (uint256 amountBaseOut) {\\n require(msg.sender == router, 'DAOfiV1: FORBIDDEN\\_DEPOSIT');\\n```\\n\\n```\\nfunction withdraw(address to) external override lock returns (uint256 amountBase, uint256 amountQuote) {\\n require(msg.sender == router, 'DAOfiV1: FORBIDDEN\\_WITHDRAW');\\n```\\n\\n```\\nfunction swap(address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOut, address to) external override lock {\\n require(msg.sender == router, 'DAOfiV1: FORBIDDEN\\_SWAP');\\n```\\n | Do not restrict `DAOfiV1Pair` functions to calls from `router`, but encourage users to use a trusted `router` to avoid losses from user error. If this restriction is kept, consider including the `router` address in the deployment salt for the pair or hardcoding the address of a trusted `router` in `DAOfiV1Factory` instead of taking the `router` as a parameter to `createPair()`. | null | ```\\nfunction deposit(address to) external override lock returns (uint256 amountBaseOut) {\\n require(msg.sender == router, 'DAOfiV1: FORBIDDEN\\_DEPOSIT');\\n```\\n |
Pair contracts can be easily blocked | low | The parameters used to define a unique pair are the `baseToken`, `quoteToken`, `slopeNumerator`, `n`, and `fee`. There is only one accepted value for `n`, and there are eleven accepted values for `fee`. This makes the number of possible “interesting” pools for each token pair somewhat limited, and pools can be easily blocked by front-running deployments and depositing zero liquidity or immediately withdrawing deposited liquidity. Because liquidity can only be added once, these pools are permanently blocked.\\nThe existing mitigation for this issue is to create a new pool with slightly different parameters. This creates significant cost for the creator of a pair, forces them to deploy a pair with sub-optimal parameters, and could potentially block all interesting pools for a token pair.\\nThe salt used to determine unique pair contracts in DAOfiV1Factory.createPair():\\n```\\nrequire(getPair(baseToken, quoteToken, slopeNumerator, n, fee) == address(0), 'DAOfiV1: PAIR\\_EXISTS'); // single check is sufficient\\nbytes memory bytecode = type(DAOfiV1Pair).creationCode;\\nbytes32 salt = keccak256(abi.encodePacked(baseToken, quoteToken, slopeNumerator, n, fee));\\nassembly {\\n pair := create2(0, add(bytecode, 32), mload(bytecode), salt)\\n}\\nIDAOfiV1Pair(pair).initialize(router, baseToken, quoteToken, pairOwner, slopeNumerator, n, fee);\\npairs[salt] = pair;\\n```\\n | Consider adding additional parameters to the salt that defines a unique pair, such as the `pairOwner`. Modifying the parameters included in the salt can also be used to partially mitigate other security concerns raised in this report. | null | ```\\nrequire(getPair(baseToken, quoteToken, slopeNumerator, n, fee) == address(0), 'DAOfiV1: PAIR\\_EXISTS'); // single check is sufficient\\nbytes memory bytecode = type(DAOfiV1Pair).creationCode;\\nbytes32 salt = keccak256(abi.encodePacked(baseToken, quoteToken, slopeNumerator, n, fee));\\nassembly {\\n pair := create2(0, add(bytecode, 32), mload(bytecode), salt)\\n}\\nIDAOfiV1Pair(pair).initialize(router, baseToken, quoteToken, pairOwner, slopeNumerator, n, fee);\\npairs[salt] = pair;\\n```\\n |
DAOfiV1Router01.removeLiquidityETH() does not support tokens with no return value | low | While the rest of the system uses the `safeTransfer*` pattern, allowing tokens that do not return a boolean value on `transfer()` or `transferFrom()`, `DAOfiV1Router01.removeLiquidityETH()` throws and consumes all remaining gas if the base token does not return `true`.\\nNote that the deposit in this case can still be withdrawn without unwrapping the Eth using `removeLiquidity()`.\\n```\\nfunction removeLiquidityETH(\\n LiquidityParams calldata lp,\\n uint deadline\\n) external override ensure(deadline) returns (uint amountToken, uint amountETH) {\\n IDAOfiV1Pair pair = IDAOfiV1Pair(DAOfiV1Library.pairFor(factory, lp.tokenBase, WETH, lp.slopeNumerator, lp.n, lp.fee));\\n require(msg.sender == pair.pairOwner(), 'DAOfiV1Router: FORBIDDEN');\\n (amountToken, amountETH) = pair.withdraw(address(this));\\n assert(IERC20(lp.tokenBase).transfer(lp.to, amountToken));\\n IWETH10(WETH).withdraw(amountETH);\\n TransferHelper.safeTransferETH(lp.to, amountETH);\\n}\\n```\\n | Be consistent with the use of `safeTransfer*`, and do not use `assert()` in cases where the condition can be false. | null | ```\\nfunction removeLiquidityETH(\\n LiquidityParams calldata lp,\\n uint deadline\\n) external override ensure(deadline) returns (uint amountToken, uint amountETH) {\\n IDAOfiV1Pair pair = IDAOfiV1Pair(DAOfiV1Library.pairFor(factory, lp.tokenBase, WETH, lp.slopeNumerator, lp.n, lp.fee));\\n require(msg.sender == pair.pairOwner(), 'DAOfiV1Router: FORBIDDEN');\\n (amountToken, amountETH) = pair.withdraw(address(this));\\n assert(IERC20(lp.tokenBase).transfer(lp.to, amountToken));\\n IWETH10(WETH).withdraw(amountETH);\\n TransferHelper.safeTransferETH(lp.to, amountETH);\\n}\\n```\\n |
Users can withdraw their funds immediately when they are over-leveraged | high | `Accounts.withdraw` makes two checks before processing a withdrawal.\\nFirst, the method checks that the amount requested for withdrawal is not larger than the user's balance for the asset in question:\\n```\\nfunction withdraw(address \\_accountAddr, address \\_token, uint256 \\_amount) external onlyAuthorized returns(uint256) {\\n\\n // Check if withdraw amount is less than user's balance\\n require(\\_amount <= getDepositBalanceCurrent(\\_token, \\_accountAddr), "Insufficient balance.");\\n uint256 borrowLTV = globalConfig.tokenInfoRegistry().getBorrowLTV(\\_token);\\n```\\n\\nSecond, the method checks that the withdrawal will not over-leverage the user. The amount to be withdrawn is subtracted from the user's current “borrow power” at the current price. If the user's total value borrowed exceeds this new borrow power, the method fails, as the user no longer has sufficient collateral to support their borrow positions. However, this `require` is only checked if a user is not already over-leveraged:\\n```\\n// This if condition is to deal with the withdraw of collateral token in liquidation.\\n// As the amount if borrowed asset is already large than the borrow power, we don't\\n// have to check the condition here.\\nif(getBorrowETH(\\_accountAddr) <= getBorrowPower(\\_accountAddr))\\n require(\\n getBorrowETH(\\_accountAddr) <= getBorrowPower(\\_accountAddr).sub(\\n \\_amount.mul(globalConfig.tokenInfoRegistry().priceFromAddress(\\_token))\\n .mul(borrowLTV).div(Utils.getDivisor(address(globalConfig), \\_token)).div(100)\\n ), "Insufficient collateral when withdraw.");\\n```\\n\\nIf the user has already borrowed more than their “borrow power” allows, they are allowed to withdraw regardless. This case may arise in several circumstances; the most common being price fluctuation. | Disallow withdrawals if the user is already over-leveraged.\\nFrom the comment included in the code sample above, this condition is included to support the `liquidate` method, but its inclusion creates an attack vector that may allow users to withdraw when they should not be able to do so. Consider adding an additional method to support `liquidate`, so that users may not exit without repaying debts. | null | ```\\nfunction withdraw(address \\_accountAddr, address \\_token, uint256 \\_amount) external onlyAuthorized returns(uint256) {\\n\\n // Check if withdraw amount is less than user's balance\\n require(\\_amount <= getDepositBalanceCurrent(\\_token, \\_accountAddr), "Insufficient balance.");\\n uint256 borrowLTV = globalConfig.tokenInfoRegistry().getBorrowLTV(\\_token);\\n```\\n |
Users can borrow funds, deposit them, then borrow more Won't Fix | high | Users may deposit and borrow funds denominated in any asset supported by the `TokenRegistry`. Each time a user deposits or borrows a token, they earn FIN according to the difference in deposit / borrow rate indices maintained by `Bank`.\\nBorrowing funds\\nWhen users borrow funds, they may only borrow up to a certain amount: the user's “borrow power.” As long as the user is not requesting to borrow an amount that would cause their resulting borrowed asset value to exceed their available borrow power, the borrow is successful and the user receives the assets immediately. A user's borrow power is calculated in the following function:\\n```\\n/\\*\\*\\n \\* Calculate an account's borrow power based on token's LTV\\n \\*/\\nfunction getBorrowPower(address \\_borrower) public view returns (uint256 power) {\\n for(uint8 i = 0; i < globalConfig.tokenInfoRegistry().getCoinLength(); i++) {\\n if (isUserHasDeposits(\\_borrower, i)) {\\n address token = globalConfig.tokenInfoRegistry().addressFromIndex(i);\\n uint divisor = INT\\_UNIT;\\n if(token != ETH\\_ADDR) {\\n divisor = 10\\*\\*uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(token));\\n }\\n // globalConfig.bank().newRateIndexCheckpoint(token);\\n power = power.add(getDepositBalanceCurrent(token, \\_borrower)\\n .mul(globalConfig.tokenInfoRegistry().priceFromIndex(i))\\n .mul(globalConfig.tokenInfoRegistry().getBorrowLTV(token)).div(100)\\n .div(divisor)\\n );\\n }\\n }\\n return power;\\n}\\n```\\n\\nFor each asset, borrow power is calculated from the user's deposit size, multiplied by the current chainlink price, multiplied and that asset's “borrow LTV.”\\nDepositing borrowed funds\\nAfter a user borrows tokens, they can then deposit those tokens, increasing their deposit balance for that asset. As a result, their borrow power increases, which allows the user to borrow again.\\nBy continuing to borrow, deposit, and borrow again, the user can repeatedly borrow assets. Essentially, this creates positions for the user where the collateral for their massive borrow position is entirely made up of borrowed assets.\\nConclusion\\nThere are several potential side-effects of this behavior.\\nFirst, as described in https://github.com/ConsenSys/definer-audit-2021-02/issues/3, the system is comprised of many different tokens, each of which is subject to price fluctuation. By borrowing and depositing repeatedly, a user may establish positions across all supported tokens. At this point, if price fluctuations cause the user's account to cross the liquidation threshold, their positions can be liquidated.\\nLiquidation is a complicated function of the protocol, but in essence, the liquidator purchases a target's collateral at a discount, and the resulting sale balances the account somewhat. However, when a user repeatedly deposits borrowed tokens, their collateral is made up of borrowed tokens: the system's liquidity! As a result, this may allow an attacker to intentionally create a massively over-leveraged account on purpose, liquidate it, and exit with a chunk of the system liquidity.\\nAnother potential problem with this behavior is FIN token mining. When users borrow and deposit, they earn FIN according to the size of the deposit / borrow, and the difference in deposit / borrow rate indices since the last deposit / borrow. By repeatedly depositing / borrowing, users are able to artificially deposit and borrow far more often than normal, which may allow them to generate FIN tokens at will. This additional strategy may make attacks like the one described above much more economically feasible. | Due to the limited time available during this engagement, these possibilities and potential mitigations were not fully explored. Definer is encouraged to investigate this behavior more carefully. | null | ```\\n/\\*\\*\\n \\* Calculate an account's borrow power based on token's LTV\\n \\*/\\nfunction getBorrowPower(address \\_borrower) public view returns (uint256 power) {\\n for(uint8 i = 0; i < globalConfig.tokenInfoRegistry().getCoinLength(); i++) {\\n if (isUserHasDeposits(\\_borrower, i)) {\\n address token = globalConfig.tokenInfoRegistry().addressFromIndex(i);\\n uint divisor = INT\\_UNIT;\\n if(token != ETH\\_ADDR) {\\n divisor = 10\\*\\*uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(token));\\n }\\n // globalConfig.bank().newRateIndexCheckpoint(token);\\n power = power.add(getDepositBalanceCurrent(token, \\_borrower)\\n .mul(globalConfig.tokenInfoRegistry().priceFromIndex(i))\\n .mul(globalConfig.tokenInfoRegistry().getBorrowLTV(token)).div(100)\\n .div(divisor)\\n );\\n }\\n }\\n return power;\\n}\\n```\\n |
Stale Oracle prices might affect the rates | high | It's possible that due to network congestion or other reasons, the price that the ChainLink oracle returns is old and not up to date. This is more extreme in lesser known tokens that have fewer ChainLink Price feeds to update the price frequently. The codebase as is, relies on `chainLink().getLatestAnswer()` and does not check the timestamp of the price.\\n```\\n function priceFromAddress(address tokenAddress) public view returns(uint256) {\\n if(Utils.\\_isETH(address(globalConfig), tokenAddress)) {\\n return 1e18;\\n }\\n return uint256(globalConfig.chainLink().getLatestAnswer(tokenAddress));\\n }\\n```\\n | Do a sanity check on the price returned from the oracle. If the price is older than a threshold, revert or handle in other means. | null | ```\\n function priceFromAddress(address tokenAddress) public view returns(uint256) {\\n if(Utils.\\_isETH(address(globalConfig), tokenAddress)) {\\n return 1e18;\\n }\\n return uint256(globalConfig.chainLink().getLatestAnswer(tokenAddress));\\n }\\n```\\n |
Overcomplicated unit conversions | medium | There are many instances of unit conversion in the system that are implemented in a confusing way. This could result in mistakes in the conversion and possibly failure in correct accounting. It's been seen in the ecosystem that these type of complicated unit conversions could result in calculation mistake and loss of funds.\\nHere are a few examples:\\n```\\n function getBorrowRatePerBlock(address \\_token) public view returns(uint) {\\n if(!globalConfig.tokenInfoRegistry().isSupportedOnCompound(\\_token))\\n // If the token is NOT supported by the third party, borrowing rate = 3% + U \\* 15%.\\n return getCapitalUtilizationRatio(\\_token).mul(globalConfig.rateCurveSlope()).div(INT\\_UNIT).add(globalConfig.rateCurveConstant()).div(BLOCKS\\_PER\\_YEAR);\\n\\n // if the token is suppored in third party, borrowing rate = Compound Supply Rate \\* 0.4 + Compound Borrow Rate \\* 0.6\\n return (compoundPool[\\_token].depositRatePerBlock).mul(globalConfig.compoundSupplyRateWeights()).\\n add((compoundPool[\\_token].borrowRatePerBlock).mul(globalConfig.compoundBorrowRateWeights())).div(10);\\n }\\n```\\n\\n```\\n compoundPool[\\_token].depositRatePerBlock = cTokenExchangeRate.mul(UNIT).div(lastCTokenExchangeRate[cToken])\\n .sub(UNIT).div(blockNumber.sub(lastCheckpoint[\\_token]));\\n```\\n\\n```\\n return lastDepositeRateIndex.mul(getBlockNumber().sub(lcp).mul(depositRatePerBlock).add(INT\\_UNIT)).div(INT\\_UNIT);\\n```\\n | Simplify the unit conversions in the system. This can be done either by using a function wrapper for units to convert all values to the same unit before including them in any calculation or by better documenting every line of unit conversion | null | ```\\n function getBorrowRatePerBlock(address \\_token) public view returns(uint) {\\n if(!globalConfig.tokenInfoRegistry().isSupportedOnCompound(\\_token))\\n // If the token is NOT supported by the third party, borrowing rate = 3% + U \\* 15%.\\n return getCapitalUtilizationRatio(\\_token).mul(globalConfig.rateCurveSlope()).div(INT\\_UNIT).add(globalConfig.rateCurveConstant()).div(BLOCKS\\_PER\\_YEAR);\\n\\n // if the token is suppored in third party, borrowing rate = Compound Supply Rate \\* 0.4 + Compound Borrow Rate \\* 0.6\\n return (compoundPool[\\_token].depositRatePerBlock).mul(globalConfig.compoundSupplyRateWeights()).\\n add((compoundPool[\\_token].borrowRatePerBlock).mul(globalConfig.compoundBorrowRateWeights())).div(10);\\n }\\n```\\n |
Commented out code in the codebase | medium | There are many instances of code lines (and functions) that are commented out in the code base. Having commented out code increases the cognitive load on an already complex system. Also, it hides the important parts of the system that should get the proper attention, but that attention gets to be diluted.\\nThe main problem is that commented code adds confusion with no real benefit. Code should be code, and comments should be comments.\\nHere's a few examples of such lines of code, note that there are more.\\n```\\n struct LiquidationVars {\\n // address token;\\n // uint256 tokenPrice;\\n // uint256 coinValue;\\n uint256 borrowerCollateralValue;\\n // uint256 tokenAmount;\\n // uint256 tokenDivisor;\\n uint256 msgTotalBorrow;\\n```\\n\\n```\\n if(token != ETH\\_ADDR) {\\n divisor = 10\\*\\*uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(token));\\n }\\n // globalConfig.bank().newRateIndexCheckpoint(token);\\n power = power.add(getDepositBalanceCurrent(token, \\_borrower)\\n```\\n\\nMany usage of `console.log()` and also the commented import on most of the contracts\\n```\\n // require(\\n // totalBorrow.mul(100) <= totalCollateral.mul(liquidationDiscountRatio),\\n // "Collateral is not sufficient to be liquidated."\\n // );\\n```\\n\\n```\\n // function \\_isETH(address \\_token) public view returns (bool) {\\n // return globalConfig.constants().ETH\\_ADDR() == \\_token;\\n // }\\n\\n // function getDivisor(address \\_token) public view returns (uint256) {\\n // if(\\_isETH(\\_token)) return INT\\_UNIT;\\n // return 10 \\*\\* uint256(getTokenDecimals(\\_token));\\n // }\\n```\\n\\n```\\n // require(\\_borrowLTV != 0, "Borrow LTV is zero");\\n require(\\_borrowLTV < SCALE, "Borrow LTV must be less than Scale");\\n // require(liquidationThreshold > \\_borrowLTV, "Liquidation threshold must be greater than Borrow LTV");\\n```\\n | In many of the above examples, it's not clear if the commented code is for testing or obsolete code (e.g. in the last example, can _borrowLTV ==0?) . All these instances should be reviewed and the system should be fully tested for all edge cases after the code changes. | null | ```\\n struct LiquidationVars {\\n // address token;\\n // uint256 tokenPrice;\\n // uint256 coinValue;\\n uint256 borrowerCollateralValue;\\n // uint256 tokenAmount;\\n // uint256 tokenDivisor;\\n uint256 msgTotalBorrow;\\n```\\n |
Emergency withdrawal code present | medium | Code and functionality for emergency stop and withdrawal is present in this code base.\\n```\\n // ============================================\\n // EMERGENCY WITHDRAWAL FUNCTIONS\\n // Needs to be removed when final version deployed\\n // ============================================\\n function emergencyWithdraw(GlobalConfig globalConfig, address \\_token) public {\\n address cToken = globalConfig.tokenInfoRegistry().getCToken(\\_token);\\n// rest of code\\n```\\n\\n```\\n function emergencyWithdraw(address \\_token) external onlyEmergencyAddress {\\n SavingLib.emergencyWithdraw(globalConfig, \\_token);\\n }\\n```\\n\\n```\\n// rest of code\\n address payable public constant EMERGENCY\\_ADDR = 0xc04158f7dB6F9c9fFbD5593236a1a3D69F92167c;\\n// rest of code\\n```\\n | To remove the emergency code and fully test all the affected contracts. | null | ```\\n // ============================================\\n // EMERGENCY WITHDRAWAL FUNCTIONS\\n // Needs to be removed when final version deployed\\n // ============================================\\n function emergencyWithdraw(GlobalConfig globalConfig, address \\_token) public {\\n address cToken = globalConfig.tokenInfoRegistry().getCToken(\\_token);\\n// rest of code\\n```\\n |
Accounts contains expensive looping | medium | `Accounts.getBorrowETH` performs multiple external calls to `GlobalConfig` and `TokenRegistry` within a for loop:\\n```\\nfunction getBorrowETH(\\n address \\_accountAddr\\n) public view returns (uint256 borrowETH) {\\n uint tokenNum = globalConfig.tokenInfoRegistry().getCoinLength();\\n //console.log("tokenNum", tokenNum);\\n for(uint i = 0; i < tokenNum; i++) {\\n if(isUserHasBorrows(\\_accountAddr, uint8(i))) {\\n address tokenAddress = globalConfig.tokenInfoRegistry().addressFromIndex(i);\\n uint divisor = INT\\_UNIT;\\n if(tokenAddress != ETH\\_ADDR) {\\n divisor = 10 \\*\\* uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(tokenAddress));\\n }\\n borrowETH = borrowETH.add(getBorrowBalanceCurrent(tokenAddress, \\_accountAddr).mul(globalConfig.tokenInfoRegistry().priceFromIndex(i)).div(divisor));\\n }\\n }\\n return borrowETH;\\n}\\n```\\n\\nThe loop also makes additional external calls and delegatecalls from:\\nTokenRegistry.priceFromIndex:\\n```\\nfunction priceFromIndex(uint index) public view returns(uint256) {\\n require(index < tokens.length, "coinIndex must be smaller than the coins length.");\\n address tokenAddress = tokens[index];\\n // Temp fix\\n if(Utils.\\_isETH(address(globalConfig), tokenAddress)) {\\n return 1e18;\\n }\\n return uint256(globalConfig.chainLink().getLatestAnswer(tokenAddress));\\n}\\n```\\n\\nAccounts.getBorrowBalanceCurrent:\\n```\\nfunction getBorrowBalanceCurrent(\\n address \\_token,\\n address \\_accountAddr\\n) public view returns (uint256 borrowBalance) {\\n AccountTokenLib.TokenInfo storage tokenInfo = accounts[\\_accountAddr].tokenInfos[\\_token];\\n uint accruedRate;\\n if(tokenInfo.getBorrowPrincipal() == 0) {\\n return 0;\\n } else {\\n if(globalConfig.bank().borrowRateIndex(\\_token, tokenInfo.getLastBorrowBlock()) == 0) {\\n accruedRate = INT\\_UNIT;\\n } else {\\n accruedRate = globalConfig.bank().borrowRateIndexNow(\\_token)\\n .mul(INT\\_UNIT)\\n .div(globalConfig.bank().borrowRateIndex(\\_token, tokenInfo.getLastBorrowBlock()));\\n }\\n return tokenInfo.getBorrowBalance(accruedRate);\\n }\\n}\\n```\\n\\nIn a worst case scenario, each iteration may perform a maximum of 25+ calls/delegatecalls. Assuming a maximum `tokenNum` of 128 (TokenRegistry.MAX_TOKENS), the gas cost for this method may reach upwards of 2 million for external calls alone.\\nGiven that this figure would only be a portion of the total transaction gas cost, `getBorrowETH` may represent a DoS risk within the `Accounts` contract. | Avoid for loops unless absolutely necessary\\nWhere possible, consolidate multiple subsequent calls to the same contract to a single call, and store the results of calls in local variables for re-use. For example,\\nInstead of this:\\n```\\nuint tokenNum = globalConfig.tokenInfoRegistry().getCoinLength();\\nfor(uint i = 0; i < tokenNum; i++) {\\n if(isUserHasBorrows(\\_accountAddr, uint8(i))) {\\n address tokenAddress = globalConfig.tokenInfoRegistry().addressFromIndex(i);\\n uint divisor = INT\\_UNIT;\\n if(tokenAddress != ETH\\_ADDR) {\\n divisor = 10 \\*\\* uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(tokenAddress));\\n }\\n borrowETH = borrowETH.add(getBorrowBalanceCurrent(tokenAddress, \\_accountAddr).mul(globalConfig.tokenInfoRegistry().priceFromIndex(i)).div(divisor));\\n }\\n}\\n```\\n\\nModify `TokenRegistry` to support a single call, and cache intermediate results like this:\\n```\\nTokenRegistry registry = globalConfig.tokenInfoRegistry();\\nuint tokenNum = registry.getCoinLength();\\nfor(uint i = 0; i < tokenNum; i++) {\\n if(isUserHasBorrows(\\_accountAddr, uint8(i))) {\\n // here, getPriceFromIndex(i) performs all of the steps as the code above, but with only 1 ext call\\n borrowETH = borrowETH.add(getBorrowBalanceCurrent(tokenAddress, \\_accountAddr).mul(registry.getPriceFromIndex(i)).div(divisor));\\n }\\n}\\n```\\n | null | ```\\nfunction getBorrowETH(\\n address \\_accountAddr\\n) public view returns (uint256 borrowETH) {\\n uint tokenNum = globalConfig.tokenInfoRegistry().getCoinLength();\\n //console.log("tokenNum", tokenNum);\\n for(uint i = 0; i < tokenNum; i++) {\\n if(isUserHasBorrows(\\_accountAddr, uint8(i))) {\\n address tokenAddress = globalConfig.tokenInfoRegistry().addressFromIndex(i);\\n uint divisor = INT\\_UNIT;\\n if(tokenAddress != ETH\\_ADDR) {\\n divisor = 10 \\*\\* uint256(globalConfig.tokenInfoRegistry().getTokenDecimals(tokenAddress));\\n }\\n borrowETH = borrowETH.add(getBorrowBalanceCurrent(tokenAddress, \\_accountAddr).mul(globalConfig.tokenInfoRegistry().priceFromIndex(i)).div(divisor));\\n }\\n }\\n return borrowETH;\\n}\\n```\\n |
Naming inconsistency | low | There are some inconsistencies in the naming of some functions with what they do.\\n```\\n function getCoinLength() public view returns (uint256 length) { //@audit-info coin vs token\\n return tokens.length;\\n }\\n```\\n | Review the code for the naming inconsistencies. | null | ```\\n function getCoinLength() public view returns (uint256 length) { //@audit-info coin vs token\\n return tokens.length;\\n }\\n```\\n |
TokenFaucet refill can have an unexpected outcome | medium | The `TokenFaucet` contract can only disburse tokens to the users if it has enough balance. When the contract is running out of tokens, it stops dripping.\\n```\\nuint256 assetTotalSupply = asset.balanceOf(address(this));\\nuint256 availableTotalSupply = assetTotalSupply.sub(totalUnclaimed);\\nuint256 newSeconds = currentTimestamp.sub(lastDripTimestamp);\\nuint256 nextExchangeRateMantissa = exchangeRateMantissa;\\nuint256 newTokens;\\nuint256 measureTotalSupply = measure.totalSupply();\\n\\nif (measureTotalSupply > 0 && availableTotalSupply > 0 && newSeconds > 0) {\\n newTokens = newSeconds.mul(dripRatePerSecond);\\n if (newTokens > availableTotalSupply) {\\n newTokens = availableTotalSupply;\\n }\\n uint256 indexDeltaMantissa = measureTotalSupply > 0 ? FixedPoint.calculateMantissa(newTokens, measureTotalSupply) : 0;\\n nextExchangeRateMantissa = nextExchangeRateMantissa.add(indexDeltaMantissa);\\n\\n emit Dripped(\\n newTokens\\n );\\n}\\n```\\n\\nThe owners of the faucet can decide to refill the contract so it can disburse tokens again. If there's been a lot of time since the faucet was drained, the `lastDripTimestamp` value can be far behind the `currentTimestamp`. In that case, the users can instantly withdraw some amount (up to all the balance) right after the refill. | To avoid uncertainty, it's essential to call the `drip` function before the refill. If this call is made in a separate transaction, the owner should make sure that this transaction was successfully mined before sending tokens for the refill. | null | ```\\nuint256 assetTotalSupply = asset.balanceOf(address(this));\\nuint256 availableTotalSupply = assetTotalSupply.sub(totalUnclaimed);\\nuint256 newSeconds = currentTimestamp.sub(lastDripTimestamp);\\nuint256 nextExchangeRateMantissa = exchangeRateMantissa;\\nuint256 newTokens;\\nuint256 measureTotalSupply = measure.totalSupply();\\n\\nif (measureTotalSupply > 0 && availableTotalSupply > 0 && newSeconds > 0) {\\n newTokens = newSeconds.mul(dripRatePerSecond);\\n if (newTokens > availableTotalSupply) {\\n newTokens = availableTotalSupply;\\n }\\n uint256 indexDeltaMantissa = measureTotalSupply > 0 ? FixedPoint.calculateMantissa(newTokens, measureTotalSupply) : 0;\\n nextExchangeRateMantissa = nextExchangeRateMantissa.add(indexDeltaMantissa);\\n\\n emit Dripped(\\n newTokens\\n );\\n}\\n```\\n |
Gas Optimization on transfers | low | In TokenFaucet, on every transfer `_captureNewTokensForUser` is called twice. This function does a few calculations and writes the latest UserState to the storage. However, if `lastExchangeRateMantissa == exchangeRateMantissa`, or in other words, two transfers happen in the same block, there are no changes in the newToken amounts, so there is an extra storage store with the same values.\\n`deltaExchangeRateMantissa` will be 0 in case two transfers ( no matter from or to) are in the same block for a user.\\n```\\n uint256 deltaExchangeRateMantissa = uint256(exchangeRateMantissa).sub(userState.lastExchangeRateMantissa);\\n uint128 newTokens = FixedPoint.multiplyUintByMantissa(userMeasureBalance, deltaExchangeRateMantissa).toUint128();\\n userStates[user] = UserState({\\n lastExchangeRateMantissa: exchangeRateMantissa,\\n balance: uint256(userState.balance).add(newTokens).toUint128()\\n });\\n```\\n | Return without storage update if `lastExchangeRateMantissa == exchangeRateMantissa`, or by another method if `deltaExchangeRateMantissa == 0`. This reduces the gas cost for active users (high number of transfers that might be in the same block) | null | ```\\n uint256 deltaExchangeRateMantissa = uint256(exchangeRateMantissa).sub(userState.lastExchangeRateMantissa);\\n uint128 newTokens = FixedPoint.multiplyUintByMantissa(userMeasureBalance, deltaExchangeRateMantissa).toUint128();\\n userStates[user] = UserState({\\n lastExchangeRateMantissa: exchangeRateMantissa,\\n balance: uint256(userState.balance).add(newTokens).toUint128()\\n });\\n```\\n |
Handle transfer tokens where from == to | low | In TokenFaucet, when calling `beforeTokenTransfer` it should also be optimized when `to == from`. This is to prevent any possible issues with internal accounting and token drip calculations.\\n```\\n// rest of code\\n if (token == address(measure) && from != address(0)) { //add && from != to\\n drip();\\n// rest of code\\n```\\n | As ERC20 standard, `from == to` can be allowed but check in `beforeTokenTransfer` that if `to == from`, then do not call `_captureNewTokensForUser(from);` again. | null | ```\\n// rest of code\\n if (token == address(measure) && from != address(0)) { //add && from != to\\n drip();\\n// rest of code\\n```\\n |
Redundant/Duplicate checks | low | There are a few checks (require) in TokenFaucet that are redundant and/or checked twice.\\n```\\n require(\\_dripRatePerSecond > 0, "TokenFaucet/dripRate-gt-zero");\\n asset = \\_asset;\\n measure = \\_measure;\\n setDripRatePerSecond(\\_dripRatePerSecond);\\n```\\n\\n```\\n function setDripRatePerSecond(uint256 \\_dripRatePerSecond) public onlyOwner {\\n require(\\_dripRatePerSecond > 0, "TokenFaucet/dripRate-gt-zero");\\n```\\n\\n\\n```\\n function drip() public returns (uint256) {\\n uint256 currentTimestamp = \\_currentTime();\\n\\n // this should only run once per block.\\n if (lastDripTimestamp == uint32(currentTimestamp)) {\\n return 0;\\n }\\n// rest of code\\n uint256 newSeconds = currentTimestamp.sub(lastDripTimestamp);\\n// rest of code\\n if (measureTotalSupply > 0 && availableTotalSupply > 0 && newSeconds > 0) {\\n// rest of code\\n uint256 indexDeltaMantissa = measureTotalSupply > 0 ? FixedPoint.calculateMantissa(newTokens, measureTotalSupply) : 0; \\n```\\n | Remove the redundant checks to reduce the code size and complexity. | null | ```\\n require(\\_dripRatePerSecond > 0, "TokenFaucet/dripRate-gt-zero");\\n asset = \\_asset;\\n measure = \\_measure;\\n setDripRatePerSecond(\\_dripRatePerSecond);\\n```\\n |
GenesisGroup.commit overwrites previously-committed values | high | `commit` allows anyone to `commit` purchased FGEN to a swap that will occur once the genesis group is launched. This commitment may be performed on behalf of other users, as long as the calling account has sufficient allowance:\\n```\\nfunction commit(address from, address to, uint amount) external override onlyGenesisPeriod {\\n burnFrom(from, amount);\\n\\n committedFGEN[to] = amount;\\n totalCommittedFGEN += amount;\\n\\n emit Commit(from, to, amount);\\n}\\n```\\n\\nThe `amount` stored in the recipient's `committedFGEN` balance overwrites any previously-committed value. Additionally, this also allows anyone to commit an `amount` of “0” to any account, deleting their commitment entirely. | Ensure the committed amount is added to the existing commitment. | null | ```\\nfunction commit(address from, address to, uint amount) external override onlyGenesisPeriod {\\n burnFrom(from, amount);\\n\\n committedFGEN[to] = amount;\\n totalCommittedFGEN += amount;\\n\\n emit Commit(from, to, amount);\\n}\\n```\\n |
UniswapIncentive overflow on pre-transfer hooks | high | Before a token transfer is performed, `Fei` performs some combination of mint/burn operations via UniswapIncentive.incentivize:\\n```\\nfunction incentivize(\\n address sender,\\n address receiver, \\n address operator,\\n uint amountIn\\n) external override onlyFei {\\n updateOracle();\\n\\n if (isPair(sender)) {\\n incentivizeBuy(receiver, amountIn);\\n }\\n\\n if (isPair(receiver)) {\\n require(isSellAllowlisted(sender) || isSellAllowlisted(operator), "UniswapIncentive: Blocked Fei sender or operator");\\n incentivizeSell(sender, amountIn);\\n }\\n}\\n```\\n\\nBoth `incentivizeBuy` and `incentivizeSell` calculate buy/sell incentives using overflow-prone math, then mint / burn from the target according to the results. This may have unintended consequences, like allowing a caller to mint tokens before transferring them, or burn tokens from their recipient.\\n`incentivizeBuy` calls `getBuyIncentive` to calculate the final minted value:\\n```\\nfunction incentivizeBuy(address target, uint amountIn) internal ifMinterSelf {\\n if (isExemptAddress(target)) {\\n return;\\n }\\n\\n (uint incentive, uint32 weight,\\n Decimal.D256 memory initialDeviation,\\n Decimal.D256 memory finalDeviation) = getBuyIncentive(amountIn);\\n\\n updateTimeWeight(initialDeviation, finalDeviation, weight);\\n if (incentive != 0) {\\n fei().mint(target, incentive); \\n }\\n}\\n```\\n\\n`getBuyIncentive` calculates price deviations after casting `amount` to an `int256`, which may overflow:\\n```\\nfunction getBuyIncentive(uint amount) public view override returns(\\n uint incentive,\\n uint32 weight,\\n Decimal.D256 memory initialDeviation,\\n Decimal.D256 memory finalDeviation\\n) {\\n (initialDeviation, finalDeviation) = getPriceDeviations(-1 \\* int256(amount));\\n```\\n | Resolution\\nThis was addressed in fei-protocol/fei-protocol-core#15.\\nEnsure casts in `getBuyIncentive` and `getSellPenalty` do not overflow. | null | ```\\nfunction incentivize(\\n address sender,\\n address receiver, \\n address operator,\\n uint amountIn\\n) external override onlyFei {\\n updateOracle();\\n\\n if (isPair(sender)) {\\n incentivizeBuy(receiver, amountIn);\\n }\\n\\n if (isPair(receiver)) {\\n require(isSellAllowlisted(sender) || isSellAllowlisted(operator), "UniswapIncentive: Blocked Fei sender or operator");\\n incentivizeSell(sender, amountIn);\\n }\\n}\\n```\\n |
BondingCurve allows users to acquire FEI before launch | medium | `BondingCurve.allocate` allocates the protocol's held PCV, then calls `_incentivize`, which rewards the caller with FEI if a certain amount of time has passed:\\n```\\n/// @notice if window has passed, reward caller and reset window\\nfunction \\_incentivize() internal virtual {\\n if (isTimeEnded()) {\\n \\_initTimed(); // reset window\\n fei().mint(msg.sender, incentiveAmount);\\n }\\n}\\n```\\n\\n`allocate` can be called before genesis launch, as long as the contract holds some nonzero PCV. By force-sending the contract 1 wei, anyone can bypass the majority of checks and actions in `allocate`, and mint themselves FEI each time the timer expires. | Prevent `allocate` from being called before genesis launch. | null | ```\\n/// @notice if window has passed, reward caller and reset window\\nfunction \\_incentivize() internal virtual {\\n if (isTimeEnded()) {\\n \\_initTimed(); // reset window\\n fei().mint(msg.sender, incentiveAmount);\\n }\\n}\\n```\\n |
Overflow/underflow protection | medium | Having overflow/underflow vulnerabilities is very common for smart contracts. It is usually mitigated by using `SafeMath` or using solidity version ^0.8 (after solidity 0.8 arithmetical operations already have default overflow/underflow protection).\\nIn this code, many arithmetical operations are used without the ‘safe' version. The reasoning behind it is that all the values are derived from the actual ETH values, so they can't overflow.\\nOn the other hand, some operations can't be checked for overflow/underflow without going much deeper into the codebase that is out of scope:\\n```\\nuint totalGenesisTribe = tribeBalance() - totalCommittedTribe;\\n```\\n | Resolution\\nThis was partially addressed in fei-protocol/fei-protocol-core#17 by using `SafeMath` for the specific example given in the description.\\nIn our opinion, it is still safer to have these operations in a safe mode. So we recommend using `SafeMath` or solidity version ^0.8 compiler. | null | ```\\nuint totalGenesisTribe = tribeBalance() - totalCommittedTribe;\\n```\\n |
Unchecked return value for IWETH.transfer call | medium | In `EthUniswapPCVController`, there is a call to `IWETH.transfer` that does not check the return value:\\n```\\nweth.transfer(address(pair), amount);\\n```\\n\\nIt is usually good to add a require-statement that checks the return value or to use something like safeTransfer; unless one is sure the given token reverts in case of a failure. | Consider adding a require-statement or using `safeTransfer`. | null | ```\\nweth.transfer(address(pair), amount);\\n```\\n |
GenesisGroup.emergencyExit remains functional after launch | medium | `emergencyExit` is intended as an escape mechanism for users in the event the genesis `launch` method fails or is frozen. `emergencyExit` becomes callable 3 days after `launch` is callable. These two methods are intended to be mutually-exclusive, but are not: either method remains callable after a successful call to the other.\\nThis may result in accounting edge cases. In particular, `emergencyExit` fails to decrease `totalCommittedFGEN` by the exiting user's commitment:\\n```\\nburnFrom(from, amountFGEN);\\ncommittedFGEN[from] = 0;\\n\\npayable(to).transfer(total);\\n```\\n\\nAs a result, calling launch after a user performs an exit will incorrectly calculate the amount of FEI to swap:\\n```\\nuint amountFei = feiBalance() \\* totalCommittedFGEN / (totalSupply() + totalCommittedFGEN);\\nif (amountFei != 0) {\\n totalCommittedTribe = ido.swapFei(amountFei);\\n}\\n```\\n | Ensure `launch` cannot be called if `emergencyExit` has been called\\nEnsure `emergencyExit` cannot be called if `launch` has been called\\nIn `emergencyExit`, reduce `totalCommittedFGEN` by the exiting user's committed amount | null | ```\\nburnFrom(from, amountFGEN);\\ncommittedFGEN[from] = 0;\\n\\npayable(to).transfer(total);\\n```\\n |
Unchecked return value for transferFrom calls | medium | There are two `transferFrom` calls that do not check the return value (some tokens signal failure by returning false):\\n```\\nstakedToken.transferFrom(from, address(this), amount);\\n```\\n\\n```\\nfei().transferFrom(msg.sender, address(pair), amountFei);\\n```\\n\\nIt is usually good to add a require-statement that checks the return value or to use something like safeTransferFrom; unless one is sure the given token reverts in case of a failure. | Consider adding a require-statement or using `safeTransferFrom`. | null | ```\\nstakedToken.transferFrom(from, address(this), amount);\\n```\\n |
Pool: claiming to the pool itself causes accounting issues | low | ```\\nfunction \\_claim(address from, address to) internal returns (uint256) {\\n (uint256 amountReward, uint256 amountPool) = redeemableReward(from);\\n require(amountPool != 0, "Pool: User has no redeemable pool tokens");\\n\\n \\_burnFrom(from, amountPool);\\n \\_incrementClaimed(amountReward);\\n\\n rewardToken.transfer(to, amountReward);\\n return amountReward;\\n}\\n```\\n\\nIf the destination address `to` is the pool itself, the pool will burn tokens and increment the amount of tokens claimed, then transfer the reward tokens `to` itself. | Resolution\\nThis was addressed in fei-protocol/fei-protocol-core#57\\nPrevent claims from specifying the pool as a destination. | null | ```\\nfunction \\_claim(address from, address to) internal returns (uint256) {\\n (uint256 amountReward, uint256 amountPool) = redeemableReward(from);\\n require(amountPool != 0, "Pool: User has no redeemable pool tokens");\\n\\n \\_burnFrom(from, amountPool);\\n \\_incrementClaimed(amountReward);\\n\\n rewardToken.transfer(to, amountReward);\\n return amountReward;\\n}\\n```\\n |
Assertions that can fail | low | In `UniswapSingleEthRouter` there are two assert-statements that may fail:\\n```\\nassert(msg.sender == address(WETH)); // only accept ETH via fallback from the WETH contract\\n```\\n\\n```\\nassert(IWETH(WETH).transfer(address(PAIR), amountIn));\\n```\\n\\nSince they do some sort of input validation it might be good to replace them with require-statements. I would only use asserts for checks that should never fail and failure would constitute a bug in the code. | Consider replacing the assert-statements with require-statements. An additional benefit is that this will not result in consuming all the gas in case of a violation. | null | ```\\nassert(msg.sender == address(WETH)); // only accept ETH via fallback from the WETH contract\\n```\\n |
Simplify API of GenesisGroup.purchase | low | The API of `GenesisGroup.purchase` could be simplified by not including the `value` parameter that is required to be equivalent to msg.value:\\n```\\nrequire(msg.value == value, "GenesisGroup: value mismatch");\\n```\\n\\nUsing `msg.value` might make the API more explicit and avoid requiring `msg.value == value`. It can also save some gas due to fewer inputs and fewer checks. | Consider dropping the `value` parameter and changing the code to use `msg.value` instead. | null | ```\\nrequire(msg.value == value, "GenesisGroup: value mismatch");\\n```\\n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.