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
|
---|---|---|---|---|---|
[Out of Scope] ReferralFeeReceiver - anyone can steal all the funds that belong to ReferralFeeReceiver Unverified | high | Note: This issue was raised in components that were being affected by the scope reduction as outlined in the section “Scope” and are, therefore, only shallowly validated. Nevertheless, we find it important to communicate such potential findings and ask the client to further investigate.\\nThe `ReferralFeeReceiver` receives pool shares when users `swap()` tokens in the pool. A `ReferralFeeReceiver` may be used with multiple pools and, therefore, be a lucrative target as it is holding pool shares.\\nAny token or `ETH` that belongs to the `ReferralFeeReceiver` is at risk and can be drained by any user by providing a custom `mooniswap` pool contract that references existing token holdings.\\nIt should be noted that none of the functions in `ReferralFeeReceiver` verify that the user-provided `mooniswap` pool address was actually deployed by the linked `MooniswapFactory`. The factory provides certain security guarantees about `mooniswap` pool contracts (e.g. valid `mooniswap` contract, token deduplication, tokenA!=tokenB, enforced token sorting, …), however, since the `ReferralFeeReceiver` does not verify the user-provided `mooniswap` address they are left unchecked.\\nAdditional Notes\\n`freezeEpoch` - (callable by anyone) performs a `pool.withdraw()` with the `minAmounts` check being disabled. This may allow someone to call this function at a time where the contract actually gets a bad deal.\\n`trade` - (callable by anyone) can intentionally be used to perform bad trades (front-runnable)\\n`trade` - (callable by anyone) appears to implement inconsistent behavior when sending out `availableBalance`. `ETH` is sent to `tx.origin` (the caller) while tokens are sent to the user-provided `mooniswap` address.\\n```\\nif (path[0].isETH()) {\\n tx.origin.transfer(availableBalance); // solhint-disable-line avoid-tx-origin\\n} else {\\n path[0].safeTransfer(address(mooniswap), availableBalance);\\n}\\n```\\n\\nmultiple methods - since `mooniswap` is a user-provided address there are a lot of opportunities to reenter the contract. Consider adding reentrancy guards as another security layer (e.g. `claimCurrentEpoch` and others).\\nmultiple methods - do not validate the amount of tokens that are returned, causing an evm assertion due to out of bounds index access.\\n```\\nIERC20[] memory tokens = mooniswap.getTokens();\\nuint256 token0Balance = tokens[0].uniBalanceOf(address(this));\\nuint256 token1Balance = tokens[1].uniBalanceOf(address(this));\\n```\\n\\nin `GovernanceFeeReceiver` anyone can intentionally force unwrapping of pool tokens or perform swaps in the worst time possible. e.g. The checks for `withdraw(..., minAmounts)` is disabled.\\n```\\nfunction unwrapLPTokens(Mooniswap mooniswap) external validSpread(mooniswap) {\\n mooniswap.withdraw(mooniswap.balanceOf(address(this)), new uint256[](0));\\n}\\n\\nfunction swap(IERC20[] memory path) external validPath(path) {\\n (uint256 amount,) = \\_maxAmountForSwap(path, path[0].uniBalanceOf(address(this)));\\n uint256 result = \\_swap(path, amount, payable(address(rewards)));\\n rewards.notifyRewardAmount(result);\\n}\\n```\\n\\nA malicious user can drain all token by calling `claimFrozenEpoch` with a custom contract as `mooniswap` that returns a token address the `ReferralFeeReceiver` contracts holds token from in `IERC20[] memory tokens = mooniswap.getTokens();`. A subsequent call to `_transferTokenShare()` will then send out any amount of token requested by the attacker to the attacker-controlled address (msg.sender).\\nLet's assume the following scenario:\\n`ReferralFeeReceiver` holds `DAI` token and we want to steal them.\\nAn attacker may be able to drain the contract from `DAI` token via `claimFrozenToken` if\\nthey control the `mooniswap` address argument and provide a malicious contract\\n`user.share[mooniswap][firstUnprocessedEpoch] > 0` - this can be arbitrarily set in `updateReward`\\n`token.epochBalance[currentEpoch].token0Balance > 0` - this can be manipulated in `freezeEpoch` by providing a malicious `mooniswap` contract\\nthey own a worthless `ERC20` token e.g. named `ATTK`\\nThe following steps outline the attack:\\nThe attacker calls into `updateReward` to set `user.share[mooniswap][currentEpoch]` to a value that is greater than zero to make sure that `share` in `claimFrozenEpoch` takes the `_transferTokenShare` path.\\n```\\nfunction updateReward(address referral, uint256 amount) external override {\\n Mooniswap mooniswap = Mooniswap(msg.sender);\\n TokenInfo storage token = tokenInfo[mooniswap];\\n UserInfo storage user = userInfo[referral];\\n uint256 currentEpoch = token.currentEpoch;\\n\\n // Add new reward to current epoch\\n user.share[mooniswap][currentEpoch] = user.share[mooniswap][currentEpoch].add(amount);\\n token.epochBalance[currentEpoch].totalSupply = token.epochBalance[currentEpoch].totalSupply.add(amount);\\n\\n // Collect all processed epochs and advance user token epoch\\n \\_collectProcessedEpochs(user, token, mooniswap, currentEpoch);\\n}\\n```\\n\\nThe attacker then calls `freezeEpoch()` providing the malicious `mooniswap` contract address controlled by the attacker.\\nThe malicious contract returns token that is controlled by the attacker (e.g. ATTK) in a call to `mooniswap.getTokens();`\\nThe contract then stores the current balance of the attacker-controlled token in `token0Balance/token1Balance`. Note that the token being returned here by the malicious contract can be different from the one we're checking out in the last step (balance manipulation via `ATTK`, checkout of `DAI` in the last step).\\nThen the contract calls out to the malicious `mooniswap` contract. This gives the malicious contract an easy opportunity to send some attacker-controlled token (ATTK) to the `ReferralFeeReceiver` in order to freely manipulate the frozen tokenbalances (tokens[0].uniBalanceOf(address(this)).sub(token0Balance);).\\nNote that the used token addresses are never stored anywhere. The balances recorded here are for an attacker-controlled token (ATTK), not the actual one that we're about to steal (e.g. DAI)\\nThe token balances are now set-up for checkout in the last step (claimFrozenEpoch).\\n```\\nfunction freezeEpoch(Mooniswap mooniswap) external validSpread(mooniswap) {\\n TokenInfo storage token = tokenInfo[mooniswap];\\n uint256 currentEpoch = token.currentEpoch;\\n require(token.firstUnprocessedEpoch == currentEpoch, "Previous epoch is not finalized");\\n\\n IERC20[] memory tokens = mooniswap.getTokens();\\n uint256 token0Balance = tokens[0].uniBalanceOf(address(this));\\n uint256 token1Balance = tokens[1].uniBalanceOf(address(this));\\n mooniswap.withdraw(mooniswap.balanceOf(address(this)), new uint256[](0));\\n token.epochBalance[currentEpoch].token0Balance = tokens[0].uniBalanceOf(address(this)).sub(token0Balance);\\n token.epochBalance[currentEpoch].token1Balance = tokens[1].uniBalanceOf(address(this)).sub(token1Balance);\\n token.currentEpoch = currentEpoch.add(1);\\n}\\n```\\n\\nA call to `claimFrozenEpoch` checks-out the previously frozen token balance.\\nThe `claim > 0` requirement was fulfilled in step 1.\\nThe token balance was prepared for the attacker-controlled token (ATTK) in step 2, but we're now checking out `DAI`.\\nWhen the contract calls out to the attackers `mooniswap` contract the call to `IERC20[] memory tokens = mooniswap.getTokens();` returns the address of the token to be stolen (e.g. DAI) instead of the attacker-controlled token (ATTK) that was used to set-up the balance records.\\nSubsequently, the valuable target tokens (DAI) are sent out to the caller in `_transferTokenShare`.\\n```\\nif (share > 0) {\\n EpochBalance storage epochBalance = token.epochBalance[firstUnprocessedEpoch];\\n uint256 totalSupply = epochBalance.totalSupply;\\n user.share[mooniswap][firstUnprocessedEpoch] = 0;\\n epochBalance.totalSupply = totalSupply.sub(share);\\n\\n IERC20[] memory tokens = mooniswap.getTokens();\\n epochBalance.token0Balance = \\_transferTokenShare(tokens[0], epochBalance.token0Balance, share, totalSupply);\\n epochBalance.token1Balance = \\_transferTokenShare(tokens[1], epochBalance.token1Balance, share, totalSupply);\\n epochBalance.inchBalance = \\_transferTokenShare(inchToken, epochBalance.inchBalance, share, totalSupply);\\n```\\n | Resolution\\nAccording to the client, this issue is addressed in 1inch-exchange/1inch-liquidity-protocol#2 and the reentrancy in `FeeReceiver` in 1inch-exchange/[email protected]e9c6a03\\n(This fix is as reported by the developer team, but has not been verified by Diligence).\\nEnforce that the user-provided `mooniswap` contract was actually deployed by the linked factory. Other contracts cannot be trusted. Consider implementing token sorting and de-duplication (tokenA!=tokenB) in the pool contract constructor as well. Consider employing a reentrancy guard to safeguard the contract from reentrancy attacks.\\nImprove testing. The methods mentioned here are not covered at all. Improve documentation and provide a specification that outlines how this contract is supposed to be used.\\nReview the “additional notes” provided with this issue. | null | ```\\nif (path[0].isETH()) {\\n tx.origin.transfer(availableBalance); // solhint-disable-line avoid-tx-origin\\n} else {\\n path[0].safeTransfer(address(mooniswap), availableBalance);\\n}\\n```\\n |
GovernanceMothership - notifyFor allows to arbitrarily create new or override other users stake in governance modules Unverified | high | The `notify*` methods are called to update linked governance modules when an accounts stake changes in the Mothership. The linked modules then update their own balances of the user to accurately reflect the account's real stake in the Mothership.\\nBesides `notify` there's also a method named `notifyFor` which is publicly accessible. It is assumed that the method should be used similar to `notify` to force an update for another account's balance.\\nHowever, invoking the method forces an update in the linked modules for the provided address, but takes `balanceOf(msg.sender)` instead of `balanceOf(account)`. This allows malicious actors to:\\nArbitrarily change other accounts stake in linked governance modules (e.g. zeroing stake, increasing stake) based on the callers stake in the mothership\\nDuplicate stake out of thin air to arbitrary addresses (e.g. staking in mothership once and calling `notifyFor` many other account addresses)\\npublicly accessible method allows forcing stake updates for arbitrary users\\n```\\nfunction notifyFor(address account) external {\\n \\_notifyFor(account, balanceOf(msg.sender));\\n}\\n```\\n\\nthe method calls the linked governance modules\\n```\\nfunction \\_notifyFor(address account, uint256 balance) private {\\n uint256 modulesLength = \\_modules.length();\\n for (uint256 i = 0; i < modulesLength; ++i) {\\n IGovernanceModule(\\_modules.at(i)).notifyStakeChanged(account, balance);\\n }\\n}\\n```\\n\\nwhich will arbitrarily `mint` or `burn` stake in the `BalanceAccounting` of `Factory` or `Reward` (or other linked governance modules)\\n```\\nfunction notifyStakeChanged(address account, uint256 newBalance) external override onlyMothership {\\n \\_notifyStakeChanged(account, newBalance);\\n}\\n```\\n\\n```\\nfunction \\_notifyStakeChanged(address account, uint256 newBalance) internal override {\\n uint256 balance = balanceOf(account);\\n if (newBalance > balance) {\\n \\_mint(account, newBalance.sub(balance));\\n } else if (newBalance < balance) {\\n \\_burn(account, balance.sub(newBalance));\\n } else {\\n return;\\n }\\n uint256 newTotalSupply = totalSupply();\\n\\n \\_defaultFee.updateBalance(account, \\_defaultFee.votes[account], balance, newBalance, newTotalSupply, \\_DEFAULT\\_FEE, \\_emitDefaultFeeVoteUpdate);\\n \\_defaultSlippageFee.updateBalance(account, \\_defaultSlippageFee.votes[account], balance, newBalance, newTotalSupply, \\_DEFAULT\\_SLIPPAGE\\_FEE, \\_emitDefaultSlippageFeeVoteUpdate);\\n \\_defaultDecayPeriod.updateBalance(account, \\_defaultDecayPeriod.votes[account], balance, newBalance, newTotalSupply, \\_DEFAULT\\_DECAY\\_PERIOD, \\_emitDefaultDecayPeriodVoteUpdate);\\n \\_referralShare.updateBalance(account, \\_referralShare.votes[account], balance, newBalance, newTotalSupply, \\_DEFAULT\\_REFERRAL\\_SHARE, \\_emitReferralShareVoteUpdate);\\n \\_governanceShare.updateBalance(account, \\_governanceShare.votes[account], balance, newBalance, newTotalSupply, \\_DEFAULT\\_GOVERNANCE\\_SHARE, \\_emitGovernanceShareVoteUpdate);\\n}\\n```\\n\\n```\\nfunction \\_notifyStakeChanged(address account, uint256 newBalance) internal override updateReward(account) {\\n uint256 balance = balanceOf(account);\\n if (newBalance > balance) {\\n \\_mint(account, newBalance.sub(balance));\\n } else if (newBalance < balance) {\\n \\_burn(account, balance.sub(newBalance));\\n }\\n}\\n```\\n | Remove `notifyFor` or change it to take the balance of the correct account `_notifyFor(account, balanceOf(msg.sender))`.\\nIt is questionable whether the public `notify*()` family of methods is actually needed as stake should only change - and thus an update of linked modules should only be required - if an account calls `stake()` or `unstake()`. It should therefore be considered to remove `notify()`, `notifyFor` and `batchNotifyFor`. | null | ```\\nfunction notifyFor(address account) external {\\n \\_notifyFor(account, balanceOf(msg.sender));\\n}\\n```\\n |
The uniTransferFrom function can potentially be used with invalid params Unverified | medium | The system is using the `UniERC20` contract to incapsulate transfers of both ERC-20 tokens and ETH. This contract has `uniTransferFrom` function that can be used for any ERC-20 or ETH:\\n```\\nfunction uniTransferFrom(IERC20 token, address payable from, address to, uint256 amount) internal {\\n if (amount > 0) {\\n if (isETH(token)) {\\n require(msg.value >= amount, "UniERC20: not enough value");\\n if (msg.value > amount) {\\n // Return remainder if exist\\n from.transfer(msg.value.sub(amount));\\n }\\n } else {\\n token.safeTransferFrom(from, to, amount);\\n }\\n }\\n}\\n```\\n\\nIn case if the function is called for the normal ERC-20 token, everything works as expected. The tokens are transferred `from` the `from` address `to` the `to` address. If the token is ETH - the transfer is expected `to` be `from` the `msg.sender` `to` `this` contract. Even if the `to` and `from` parameters are different.\\nThis issue's severity is not high because the function is always called with the proper parameters in the current codebase. | Resolution\\nAccording to the client, this issue is addressed in 1inch-exchange/[email protected]d0ffb6f.\\n(This fix is as reported by the developer team, but has not been verified by Diligence).\\nMake sure that the `uniTransferFrom` function is always called with expected parameters. | null | ```\\nfunction uniTransferFrom(IERC20 token, address payable from, address to, uint256 amount) internal {\\n if (amount > 0) {\\n if (isETH(token)) {\\n require(msg.value >= amount, "UniERC20: not enough value");\\n if (msg.value > amount) {\\n // Return remainder if exist\\n from.transfer(msg.value.sub(amount));\\n }\\n } else {\\n token.safeTransferFrom(from, to, amount);\\n }\\n }\\n}\\n```\\n |
MooniswapGovernance - votingpower is not accurately reflected when minting pool tokens Unverified | medium | When a user provides liquidity to the pool, pool-tokens are minted. The minting event triggers the `_beforeTokenTransfer` callback in `MooniswapGovernance` which updates voting power reflecting the newly minted stake for the user.\\nThere seems to be a copy-paste error in the way `balanceTo` is determined that sets `balanceTo` to zero if new token were minted (from==address(0)). This means, that in a later call to `_updateOnTransfer` only the newly minted amount is considered when adjusting voting power.\\nIf tokens are newly minted `from==address(0)` and therefore `balanceTo -> 0`.\\n```\\nfunction \\_beforeTokenTransfer(address from, address to, uint256 amount) internal override {\\n uint256 balanceFrom = (from != address(0)) ? balanceOf(from) : 0;\\n uint256 balanceTo = (from != address(0)) ? balanceOf(to) : 0;\\n uint256 newTotalSupply = totalSupply()\\n .add(from == address(0) ? amount : 0)\\n .sub(to == address(0) ? amount : 0);\\n\\n ParamsHelper memory params = ParamsHelper({\\n from: from,\\n to: to,\\n amount: amount,\\n balanceFrom: balanceFrom,\\n balanceTo: balanceTo,\\n newTotalSupply: newTotalSupply\\n });\\n```\\n\\nnow, `balanceTo` is zero which would adjust voting power to `amount` instead of the user's actual balance + the newly minted token.\\n```\\nif (params.to != address(0)) {\\n votingData.updateBalance(params.to, voteTo, params.balanceTo, params.balanceTo.add(params.amount), params.newTotalSupply, defaultValue, emitEvent);\\n}\\n```\\n | `balanceTo` should be zero when burning (to == address(0)) and `balanceOf(to)` when minting.\\ne.g. like this:\\n```\\nuint256 balanceTo = (to != address(0)) ? balanceOf(to) : 0;\\n```\\n | null | ```\\nfunction \\_beforeTokenTransfer(address from, address to, uint256 amount) internal override {\\n uint256 balanceFrom = (from != address(0)) ? balanceOf(from) : 0;\\n uint256 balanceTo = (from != address(0)) ? balanceOf(to) : 0;\\n uint256 newTotalSupply = totalSupply()\\n .add(from == address(0) ? amount : 0)\\n .sub(to == address(0) ? amount : 0);\\n\\n ParamsHelper memory params = ParamsHelper({\\n from: from,\\n to: to,\\n amount: amount,\\n balanceFrom: balanceFrom,\\n balanceTo: balanceTo,\\n newTotalSupply: newTotalSupply\\n });\\n```\\n |
MooniswapGovernance - _beforeTokenTransfer should not update voting power on transfers to self Unverified | medium | Mooniswap governance is based on the liquidity voting system that is also employed by the mothership or for factory governance. In contrast to traditional voting systems where users vote for discrete values, the liquidity voting system derives a continuous weighted averaged “consensus” value from all the votes. Thus it is required that whenever stake changes in the system, all the parameters that can be voted upon are updated with the new weights for a specific user.\\nThe Mooniswap pool is governed by liquidity providers and liquidity tokens are the stake that gives voting rights in `MooniswapGovernance`. Thus whenever liquidity tokens are transferred to another address, stake and voting values need to be updated. This is handled by `MooniswapGovernance._beforeTokenTransfer()`.\\nIn the special case where someone triggers a token transfer where the `from` address equals the `to` address, effectively sending the token `to` themselves, no update on voting power should be performed. Instead, voting power is first updated with `balance - amount` and then with `balance + amount` which in the worst case means it is updating first `to` a zero balance and then `to` 2x the balance.\\nUltimately this should not have an effect on the overall outcome but is unnecessary and wasting gas.\\n`beforeTokenTransfer` callback in `Mooniswap` does not check for the NOP case where `from==to`\\n```\\nfunction \\_beforeTokenTransfer(address from, address to, uint256 amount) internal override {\\n uint256 balanceFrom = (from != address(0)) ? balanceOf(from) : 0;\\n uint256 balanceTo = (from != address(0)) ? balanceOf(to) : 0;\\n uint256 newTotalSupply = totalSupply()\\n .add(from == address(0) ? amount : 0)\\n .sub(to == address(0) ? amount : 0);\\n\\n ParamsHelper memory params = ParamsHelper({\\n from: from,\\n to: to,\\n amount: amount,\\n balanceFrom: balanceFrom,\\n balanceTo: balanceTo,\\n newTotalSupply: newTotalSupply\\n });\\n\\n \\_updateOnTransfer(params, mooniswapFactoryGovernance.defaultFee, \\_emitFeeVoteUpdate, \\_fee);\\n \\_updateOnTransfer(params, mooniswapFactoryGovernance.defaultSlippageFee, \\_emitSlippageFeeVoteUpdate, \\_slippageFee);\\n \\_updateOnTransfer(params, mooniswapFactoryGovernance.defaultDecayPeriod, \\_emitDecayPeriodVoteUpdate, \\_decayPeriod);\\n}\\n```\\n\\nwhich leads to `updateBalance` being called on the same address twice, first with `currentBalance - amountTransferred` and then with `currentBalance + amountTransferred`.\\n```\\nif (params.from != address(0)) {\\n votingData.updateBalance(params.from, voteFrom, params.balanceFrom, params.balanceFrom.sub(params.amount), params.newTotalSupply, defaultValue, emitEvent);\\n}\\n\\nif (params.to != address(0)) {\\n votingData.updateBalance(params.to, voteTo, params.balanceTo, params.balanceTo.add(params.amount), params.newTotalSupply, defaultValue, emitEvent);\\n}\\n```\\n | Do not update voting power on LP token transfers where `from == to`. | null | ```\\nfunction \\_beforeTokenTransfer(address from, address to, uint256 amount) internal override {\\n uint256 balanceFrom = (from != address(0)) ? balanceOf(from) : 0;\\n uint256 balanceTo = (from != address(0)) ? balanceOf(to) : 0;\\n uint256 newTotalSupply = totalSupply()\\n .add(from == address(0) ? amount : 0)\\n .sub(to == address(0) ? amount : 0);\\n\\n ParamsHelper memory params = ParamsHelper({\\n from: from,\\n to: to,\\n amount: amount,\\n balanceFrom: balanceFrom,\\n balanceTo: balanceTo,\\n newTotalSupply: newTotalSupply\\n });\\n\\n \\_updateOnTransfer(params, mooniswapFactoryGovernance.defaultFee, \\_emitFeeVoteUpdate, \\_fee);\\n \\_updateOnTransfer(params, mooniswapFactoryGovernance.defaultSlippageFee, \\_emitSlippageFeeVoteUpdate, \\_slippageFee);\\n \\_updateOnTransfer(params, mooniswapFactoryGovernance.defaultDecayPeriod, \\_emitDecayPeriodVoteUpdate, \\_decayPeriod);\\n}\\n```\\n |
Unpredictable behavior for users due to admin front running or general bad timing | medium | In a number of cases, administrators of contracts can update or upgrade things in the system without warning. This has the potential to violate a security goal of the system.\\nSpecifically, privileged roles could use front running to make malicious changes just ahead of incoming transactions, or purely accidental negative effects could occur due to the unfortunate timing of changes.\\nIn general users of the system should have assurances about the behavior of the action they're about to take.\\nMooniswapFactoryGovernance - Admin opportunity to lock `swapFor` with a referral when setting an invalid `referralFeeReceiver`\\n`setReferralFeeReceiver` and `setGovernanceFeeReceiver` takes effect immediately.\\n```\\nfunction setReferralFeeReceiver(address newReferralFeeReceiver) external onlyOwner {\\n referralFeeReceiver = newReferralFeeReceiver;\\n emit ReferralFeeReceiverUpdate(newReferralFeeReceiver);\\n}\\n```\\n\\n`setReferralFeeReceiver` can be used to set an invalid receiver address (or one that reverts on every call) effectively rendering `Mooniswap.swapFor` unusable if a referral was specified in the swap.\\n```\\nif (referral != address(0)) {\\n referralShare = invIncrease.mul(referralShare).div(\\_FEE\\_DENOMINATOR);\\n if (referralShare > 0) {\\n if (referralFeeReceiver != address(0)) {\\n \\_mint(referralFeeReceiver, referralShare);\\n IReferralFeeReceiver(referralFeeReceiver).updateReward(referral, referralShare);\\n```\\n\\nLocking staked token\\nAt any point in time and without prior notice to users an admin may accidentally or intentionally add a broken governance sub-module to the system that blocks all users from unstaking their `1INCH` token. An admin can recover from this by removing the broken sub-module, however, with malicious intent tokens may be locked forever.\\nSince `1INCH` token gives voting power in the system, tokens are considered to hold value for other users and may be traded on exchanges. This raises concerns if tokens can be locked in a contract by one actor.\\nAn admin adds an invalid address or a malicious sub-module to the governance contract that always `reverts` on calls to `notifyStakeChanged`.\\n```\\nfunction addModule(address module) external onlyOwner {\\n require(\\_modules.add(module), "Module already registered");\\n emit AddModule(module);\\n}\\n```\\n\\n```\\nfunction \\_notifyFor(address account, uint256 balance) private {\\n uint256 modulesLength = \\_modules.length();\\n for (uint256 i = 0; i < modulesLength; ++i) {\\n IGovernanceModule(\\_modules.at(i)).notifyStakeChanged(account, balance);\\n }\\n}\\n```\\n\\nAdmin front-running to prevent user stake sync\\nAn admin may front-run users while staking in an attempt to prevent submodules from being notified of the stake update. This is unlikely to happen as it incurs costs for the attacker (front-back-running) to normal users but may be an interesting attack scenario to exclude a whale's stake from voting.\\nFor example, an admin may front-run `stake()` or `notoify*()` by briefly removing all governance submodules from the mothership and re-adding them after the users call succeeded. The stake-update will not be propagated to the sub-modules. A user may only detect this when they are voting (if they had no stake before) or when they actually check their stake. Such an attack might likely stay unnoticed unless someone listens for `addmodule` `removemodule` events on the contract.\\nAn admin front-runs a transaction by removing all modules and re-adding them afterwards to prevent the stake from propagating to the submodules.\\n```\\nfunction removeModule(address module) external onlyOwner {\\n require(\\_modules.remove(module), "Module was not registered");\\n emit RemoveModule(module);\\n}\\n```\\n\\nAdmin front-running to prevent unstake from propagating\\nAn admin may choose to front-run their own `unstake()`, temporarily removing all governance sub-modules, preventing `unstake()` from syncing the action to sub-modules while still getting their previously staked tokens out. The governance sub-modules can be re-added right after unstaking. Due to double-accounting of the stake (in governance and in every sub-module) their stake will still be exercisable in the sub-module even though it was removed from the mothership. Users can only prevent this by manually calling a state-sync on the affected account(s). | The underlying issue is that users of the system can't be sure what the behavior of a function call will be, and this is because the behavior can change at any time.\\nWe recommend giving the user advance notice of changes with a time lock. For example, make all system-parameter and upgrades require two steps with a mandatory time window between them. The first step merely broadcasts to users that a particular change is coming, and the second step commits that change after a suitable waiting period. This allows users that do not accept the change to withdraw immediately.\\nFurthermore, users should be guaranteed to be able to redeem their staked tokens. An entity - even though trusted - in the system should not be able to lock tokens indefinitely. | null | ```\\nfunction setReferralFeeReceiver(address newReferralFeeReceiver) external onlyOwner {\\n referralFeeReceiver = newReferralFeeReceiver;\\n emit ReferralFeeReceiverUpdate(newReferralFeeReceiver);\\n}\\n```\\n |
The owner can borrow token0/token1 in the rescueFunds | low | If some random tokens/funds are accidentally transferred to the pool, the `owner` can call the `rescueFunds` function to withdraw any funds manually:\\n```\\nfunction rescueFunds(IERC20 token, uint256 amount) external nonReentrant onlyOwner {\\n uint256 balance0 = token0.uniBalanceOf(address(this));\\n uint256 balance1 = token1.uniBalanceOf(address(this));\\n\\n token.uniTransfer(msg.sender, amount);\\n\\n require(token0.uniBalanceOf(address(this)) >= balance0, "Mooniswap: access denied");\\n require(token1.uniBalanceOf(address(this)) >= balance1, "Mooniswap: access denied");\\n require(balanceOf(address(this)) >= \\_BASE\\_SUPPLY, "Mooniswap: access denied");\\n}\\n```\\n\\nThere's no restriction on which funds the `owner` can try to withdraw and which token to call. It's theoretically possible to transfer pool tokens and then return them to the contract (e.g. in the case of ERC-777). That action would be similar to a free flash loan. | Explicitly check that the `token` is not equal to any of the pool tokens. | null | ```\\nfunction rescueFunds(IERC20 token, uint256 amount) external nonReentrant onlyOwner {\\n uint256 balance0 = token0.uniBalanceOf(address(this));\\n uint256 balance1 = token1.uniBalanceOf(address(this));\\n\\n token.uniTransfer(msg.sender, amount);\\n\\n require(token0.uniBalanceOf(address(this)) >= balance0, "Mooniswap: access denied");\\n require(token1.uniBalanceOf(address(this)) >= balance1, "Mooniswap: access denied");\\n require(balanceOf(address(this)) >= \\_BASE\\_SUPPLY, "Mooniswap: access denied");\\n}\\n```\\n |
Ether temporarily held during transactions can be stolen via reentrancy | high | The exchange proxy typically holds no ether balance, but it can temporarily hold a balance during a transaction. This balance is vulnerable to theft if the following conditions are met:\\nNo check at the end of the transaction reverts if ether goes missing,\\nreentrancy is possible during the transaction, and\\na mechanism exists to spend ether held by the exchange proxy.\\nWe found one example where these conditions are met, but it's possible that more exist.\\nExample\\n`MetaTransactionsFeature.executeMetaTransaction()` accepts ether, which is used to pay protocol fees. It's possible for less than the full amount in `msg.value` to be consumed, which is why the function uses the `refundsAttachedEth` modifier to return any remaining ether to the caller:\\n```\\n/// @dev Refunds up to `msg.value` leftover ETH at the end of the call.\\nmodifier refundsAttachedEth() {\\n \\_;\\n uint256 remainingBalance =\\n LibSafeMathV06.min256(msg.value, address(this).balance);\\n if (remainingBalance > 0) {\\n msg.sender.transfer(remainingBalance);\\n }\\n}\\n```\\n\\nNotice that this modifier just returns the remaining ether balance (up to msg.value). It does not check for a specific amount of remaining ether. This meets condition (1) above.\\nIt's impossible to reenter the system with a second metatransaction because `executeMetaTransaction()` uses the modifier `nonReentrant`, but there's nothing preventing reentrancy via a different feature. We can achieve reentrancy by trading a token that uses callbacks (e.g. ERC777's hooks) during transfers. This meets condition (2).\\nTo find a full exploit, we also need a way to extract the ether held by the exchange proxy. `LiquidityProviderFeature.sellToLiquidityProvider()` provides such a mechanism. By passing `ETH_TOKEN_ADDRESS` as the `inputToken` and an address in the attacker's control as the `provider`, an attacker can transfer out any ether held by the exchange proxy. Note that `sellToLiquidityProvider()` can transfer any amount of ether, not limited to the amount sent via msg.value:\\n```\\nif (inputToken == ETH\\_TOKEN\\_ADDRESS) {\\n provider.transfer(sellAmount);\\n```\\n\\nThis meets condition (3).\\nThe full steps to exploit this vulnerability are as follows:\\nA maker/attacker signs a trade where one of the tokens will invoke a callback during the trade.\\nA taker signs a metatransaction to take this trade.\\nA relayer sends in the metatransaction, providing more ether than is necessary to pay the protocol fee. (It's unclear how likely this situation is.)\\nDuring the token callback, the attacker invokes `LiquidityProviderFeature.sellToLiquidityProvider()` to transfer the excess ether to their account.\\nThe metatransaction feature returns the remaining ether balance, which is now zero. | In general, we recommend using strict accounting of ether throughout the system. If there's ever a temporary balance, it should be accurately resolved at the end of the transaction, after any potential reentrancy opportunities.\\nFor the example we specifically found, we recommend doing strict accounting in the metatransactions feature. This means features called via a metatransaction would need to return how much ether was consumed. The metatransactions feature could then refund exactly `msg.value - <consumed ether>`. The transaction should be reverted if this fails because it means ether went missing during the transaction.\\nWe also recommend limiting `sellToLiquidityProvider()` to only transfer up to `msg.value`. This is a form of defense in depth in case other vectors for a similar attack exist. | null | ```\\n/// @dev Refunds up to `msg.value` leftover ETH at the end of the call.\\nmodifier refundsAttachedEth() {\\n \\_;\\n uint256 remainingBalance =\\n LibSafeMathV06.min256(msg.value, address(this).balance);\\n if (remainingBalance > 0) {\\n msg.sender.transfer(remainingBalance);\\n }\\n}\\n```\\n |
UniswapFeature: Non-static call to ERC20.allowance() | low | In the case where a token is possibly “greedy” (consumes all gas on failure), `UniswapFeature` makes a call to the token's `allowance()` function to check whether the user has provided a token allowance to the protocol proxy or to the `AllowanceTarget`. This call is made using `call()`, potentially allowing state-changing operations to take place before control of the execution returns to `UniswapFeature`.\\n```\\n// `token.allowance()``\\nmstore(0xB00, ALLOWANCE\\_CALL\\_SELECTOR\\_32)\\nmstore(0xB04, caller())\\nmstore(0xB24, address())\\nlet success := call(gas(), token, 0, 0xB00, 0x44, 0xC00, 0x20)\\n```\\n | Replace the `call()` with a `staticcall()`. | null | ```\\n// `token.allowance()``\\nmstore(0xB00, ALLOWANCE\\_CALL\\_SELECTOR\\_32)\\nmstore(0xB04, caller())\\nmstore(0xB24, address())\\nlet success := call(gas(), token, 0, 0xB00, 0x44, 0xC00, 0x20)\\n```\\n |
UniswapFeature: Unchecked returndatasize in low-level external calls | low | `UniswapFeature` makes a number of external calls from low-level assembly code. Two of these calls rely on the `CALL` opcode to copy the returndata to memory without checking that the call returned the expected amount of data. Because the `CALL` opcode does not zero memory if the call returns less data than expected, this can lead to usage of dirty memory under the assumption that it is data returned from the most recent call.\\nCall to `UniswapV2Pair.getReserves()`\\n```\\n// Call pair.getReserves(), store the results at `0xC00`\\nmstore(0xB00, UNISWAP\\_PAIR\\_RESERVES\\_CALL\\_SELECTOR\\_32)\\nif iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) {\\n bubbleRevert()\\n}\\n```\\n\\nCall to `ERC20.allowance()`\\n```\\n// Check if we have enough direct allowance by calling\\n// `token.allowance()``\\nmstore(0xB00, ALLOWANCE\\_CALL\\_SELECTOR\\_32)\\nmstore(0xB04, caller())\\nmstore(0xB24, address())\\nlet success := call(gas(), token, 0, 0xB00, 0x44, 0xC00, 0x20)\\n```\\n | Instead of providing a memory range for `call()` to write returndata to, explicitly check `returndatasize()` after the call is made and then copy the data into memory using `returndatacopy()`.\\n```\\nif lt(returndatasize(), EXPECTED\\_SIZE) {\\n revert(0, 0) \\n}\\nreturndatacopy(0xC00, 0x00, EXPECTED\\_SIZE)\\n```\\n | null | ```\\n// Call pair.getReserves(), store the results at `0xC00`\\nmstore(0xB00, UNISWAP\\_PAIR\\_RESERVES\\_CALL\\_SELECTOR\\_32)\\nif iszero(staticcall(gas(), pair, 0xB00, 0x4, 0xC00, 0x40)) {\\n bubbleRevert()\\n}\\n```\\n |
PeriodicPrizeStrategy - RNG failure can lock user funds | high | To prevent manipulation of the `SortitionSumTree` after a requested random number enters the mempool, users are unable to withdraw funds while the strategy contract waits on a random number request between execution of `startAward()` and `completeAward()`.\\nIf an rng request fails, however, there is no way to exit this locked state. After an rng request times out, only `startAward()` can be called, which will make another rng request and re-enter the same locked state. The rng provider can also not be updated while the contract is in this state. If the rng provider fails permanently, user funds are permanently locked.\\n`requireNotLocked()` prevents transfers, deposits, or withdrawals when there is a pending award.\\n```\\nfunction beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external override onlyPrizePool {\\n if (controlledToken == address(ticket)) {\\n \\_requireNotLocked();\\n }\\n```\\n\\n```\\nfunction \\_requireNotLocked() internal view {\\n uint256 currentBlock = \\_currentBlock();\\n require(rngRequest.lockBlock == 0 || currentBlock < rngRequest.lockBlock, "PeriodicPrizeStrategy/rng-in-flight");\\n}\\n```\\n\\n`setRngService()` reverts if there is a pending or timed-out rng request\\n```\\nfunction setRngService(RNGInterface rngService) external onlyOwner {\\n require(!isRngRequested(), "PeriodicPrizeStrategy/rng-in-flight");\\n```\\n | Instead of forcing the pending award phase to be re-entered in the event of an rng request time-out, provide an `exitAwardPhase()` function that ends the award phase without paying out the award. This will at least allow users to withdraw their funds in the event of a catastrophic failure of the rng service. It may also be prudent to allow the rng service to be updated in the event of an rng request time out. | null | ```\\nfunction beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external override onlyPrizePool {\\n if (controlledToken == address(ticket)) {\\n \\_requireNotLocked();\\n }\\n```\\n |
LootBox - Unprotected selfdestruct in proxy implementation | high | When the `LootBoxController` is deployed, it also deploys an instance of `LootBox`. When someone calls `LootBoxController.plunder()` or `LootBoxController.executeCall()` the controller actually deploys a temporary proxy contract to a deterministic address using `create2`, then calls out to it to collect the loot.\\nThe `LootBox` implementation contract is completely unprotected, exposing all its functionality to any actor on the blockchain. The most critical functionality is actually the `LootBox.destroy()` method that calls `selfdestruct()` on the implementation contract.\\nTherefore, an unauthenticated user can `selfdestruct` the `LootBox` proxy implementation and cause the complete system to become dysfunctional. As an effect, none of the AirDrops that were delivered based on this contract will be redeemable (Note: `create2` deploy address is calculated from the current contract address and salt). Funds may be lost.\\n```\\nconstructor () public {\\n lootBoxActionInstance = new LootBox();\\n lootBoxActionBytecode = MinimalProxyLibrary.minimalProxy(address(lootBoxActionInstance));\\n}\\n```\\n\\n```\\n/// @notice Destroys this contract using `selfdestruct`\\n/// @param to The address to send remaining Ether to\\nfunction destroy(address payable to) external {\\n selfdestruct(to);\\n}\\n```\\n\\nnot in scope but listed for completeness\\n```\\ncontract CounterfactualAction {\\n function depositTo(address payable user, PrizePool prizePool, address output, address referrer) external {\\n IERC20 token = IERC20(prizePool.token());\\n uint256 amount = token.balanceOf(address(this));\\n token.approve(address(prizePool), amount);\\n prizePool.depositTo(user, amount, output, referrer);\\n selfdestruct(user);\\n }\\n\\n function cancel(address payable user, PrizePool prizePool) external {\\n IERC20 token = IERC20(prizePool.token());\\n token.transfer(user, token.balanceOf(address(this)));\\n selfdestruct(user);\\n }\\n```\\n | Enforce that only the deployer of the contract can call functionality in the contract. Make sure that nobody can destroy the implementation of proxy contracts. | null | ```\\nconstructor () public {\\n lootBoxActionInstance = new LootBox();\\n lootBoxActionBytecode = MinimalProxyLibrary.minimalProxy(address(lootBoxActionInstance));\\n}\\n```\\n |
PeriodicPriceStrategy - trustedForwarder can impersonate any msg.sender | high | The `trustedForwarder` undermines the trust assumptions in the system. For example, one would assume that the access control modifier `onlyPrizePool` would only allow the configured `PrizePool` to call certain methods. However, in reality, the `trustedForwarder` can assume this position as well. The same is true for the `onlyOwnerOrListener` modifier. One would assume `msg.sender` must either be `periodicPrizeStrategyListener` or `owner` (the initial deployer) while the `trustedForwarder` can assume any of the administrative roles.\\nThe centralization of power to allow one account to impersonate other components and roles (owner, `listener`, prizePool) in the system is a concern by itself and may give users pause when deciding whether to trust the contract system. The fact that the `trustedForwarder` can spoof events for any `msg.sender` may also make it hard to keep an accurate log trail of events in case of a security incident.\\nNote: The same functionality seems to be used in `ControlledToken` and other contracts which allows the `trustedForwarder` to assume any tokenholder in `ERC20UpgradeSafe`. There is practically no guarantee to `ControlledToken` holders.\\nNote: The trustedForwarder/msgSender() pattern is used in multiple contracts, many of which are not in the scope of this assessment.\\naccess control modifiers that can be impersonated\\n```\\nmodifier onlyPrizePool() {\\n require(\\_msgSender() == address(prizePool), "PeriodicPrizeStrategy/only-prize-pool");\\n \\_;\\n}\\n```\\n\\n```\\nmodifier onlyOwnerOrListener() {\\n require(\\_msgSender() == owner() || \\_msgSender() == address(periodicPrizeStrategyListener), "PeriodicPrizeStrategy/only-owner-or-listener");\\n \\_;\\n}\\n```\\n\\nevent `msg.sender` that can be spoofed because the actual `msg.sender` can be `trustedForwarder`\\n```\\nemit PrizePoolOpened(\\_msgSender(), prizePeriodStartedAt);\\n```\\n\\n```\\nemit PrizePoolAwardStarted(\\_msgSender(), address(prizePool), requestId, lockBlock);\\n```\\n\\n```\\nemit PrizePoolAwarded(\\_msgSender(), randomNumber);\\nemit PrizePoolOpened(\\_msgSender(), prizePeriodStartedAt);\\n```\\n\\n`_msgSender()` implementation allows the `trustedForwarder` to impersonate any `msg.sender` address\\n```\\n/// @dev Provides information about the current execution context for GSN Meta-Txs.\\n/// @return The payable address of the message sender\\nfunction \\_msgSender()\\n internal\\n override(BaseRelayRecipient, ContextUpgradeSafe)\\n virtual\\n view\\n returns (address payable)\\n{\\n return BaseRelayRecipient.\\_msgSender();\\n}\\n```\\n | Remove the `trustedForwarder` or restrict the type of actions the forwarder can perform and don't allow it to impersonate other components in the system. Make sure users understand the trust assumptions and who has what powers in the system. Make sure to keep an accurate log trail of who performed which action on whom's behalf. | null | ```\\nmodifier onlyPrizePool() {\\n require(\\_msgSender() == address(prizePool), "PeriodicPrizeStrategy/only-prize-pool");\\n \\_;\\n}\\n```\\n |
Unpredictable behavior for users due to admin front running or general bad timing | high | In a number of cases, administrators of contracts can update or upgrade things in the system without warning. This has the potential to violate a security goal of the system.\\nSpecifically, privileged roles could use front running to make malicious changes just ahead of incoming transactions, or purely accidental negative effects could occur due to unfortunate timing of changes.\\nIn general users of the system should have assurances about the behavior of the action they're about to take.\\nAn administrator (deployer) of `MultipleWinners` can change the number of winners in the system without warning. This has the potential to violate a security goal of the system.\\nadmin can change the number of winners during a prize-draw period\\n```\\nfunction setNumberOfWinners(uint256 count) external onlyOwner {\\n \\_\\_numberOfWinners = count;\\n\\n emit NumberOfWinnersSet(count);\\n}\\n```\\n\\n`PeriodicPriceStrategy` - admin may switch-out RNG service at any time (when RNG is not in inflight or timed-out)\\n```\\nfunction setRngService(RNGInterface rngService) external onlyOwner {\\n require(!isRngRequested(), "PeriodicPrizeStrategy/rng-in-flight");\\n\\n rng = rngService;\\n emit RngServiceUpdated(address(rngService));\\n}\\n```\\n\\n`PeriodicPriceStrategy` - admin can effectively disable the rng request timeout by setting a high value during a prize-draw (e.g. to indefinitely block payouts)\\n```\\nfunction setRngRequestTimeout(uint32 \\_rngRequestTimeout) external onlyOwner {\\n \\_setRngRequestTimeout(\\_rngRequestTimeout);\\n}\\n```\\n\\n`PeriodicPriceStrategy` - admin may set new tokenListener which might intentionally block token-transfers\\n```\\nfunction setTokenListener(TokenListenerInterface \\_tokenListener) external onlyOwner {\\n tokenListener = \\_tokenListener;\\n\\n emit TokenListenerUpdated(address(tokenListener));\\n}\\n```\\n\\n```\\nfunction setPeriodicPrizeStrategyListener(address \\_periodicPrizeStrategyListener) external onlyOwner {\\n periodicPrizeStrategyListener = PeriodicPrizeStrategyListener(\\_periodicPrizeStrategyListener);\\n\\n emit PeriodicPrizeStrategyListenerSet(\\_periodicPrizeStrategyListener);\\n}\\n```\\n\\nout of scope but mentioned as a relevant example: `PrizePool` owner can set new `PrizeStrategy` at any time\\n```\\n/// @notice Sets the prize strategy of the prize pool. Only callable by the owner.\\n/// @param \\_prizeStrategy The new prize strategy\\nfunction setPrizeStrategy(address \\_prizeStrategy) external override onlyOwner {\\n \\_setPrizeStrategy(TokenListenerInterface(\\_prizeStrategy));\\n}\\n```\\n\\na malicious admin may remove all external ERC20/ERC721 token awards prior to the user claiming them (admin front-running opportunity)\\n```\\nfunction removeExternalErc20Award(address \\_externalErc20, address \\_prevExternalErc20) external onlyOwner {\\n externalErc20s.removeAddress(\\_prevExternalErc20, \\_externalErc20);\\n emit ExternalErc20AwardRemoved(\\_externalErc20);\\n}\\n```\\n\\n```\\nfunction removeExternalErc721Award(address \\_externalErc721, address \\_prevExternalErc721) external onlyOwner {\\n externalErc721s.removeAddress(\\_prevExternalErc721, \\_externalErc721);\\n delete externalErc721TokenIds[\\_externalErc721];\\n emit ExternalErc721AwardRemoved(\\_externalErc721);\\n}\\n```\\n\\nthe `PeriodicPrizeStrategy` `owner` (also see concerns outlined in issue 5.4) can transfer external ERC20 at any time to avoid them being awarded to users. there is no guarantee to the user.\\n```\\nfunction transferExternalERC20(\\n address to,\\n address externalToken,\\n uint256 amount\\n)\\n external\\n onlyOwner\\n{\\n prizePool.transferExternalERC20(to, externalToken, amount);\\n}\\n```\\n | The underlying issue is that users of the system can't be sure what the behavior of a function call will be, and this is because the behavior can change at any time.\\nWe recommend giving the user advance notice of changes with a time lock. For example, make all system-parameter and upgrades require two steps with a mandatory time window between them. The first step merely broadcasts to users that a particular change is coming, and the second step commits that change after a suitable waiting period. This allows users that do not accept the change to withdraw immediately. | null | ```\\nfunction setNumberOfWinners(uint256 count) external onlyOwner {\\n \\_\\_numberOfWinners = count;\\n\\n emit NumberOfWinnersSet(count);\\n}\\n```\\n |
PeriodicPriceStrategy - addExternalErc721Award duplicate or invalid tokenIds may block award phase | medium | The prize-strategy owner (or a listener) can add `ERC721` token awards by calling `addExternalErc721Award` providing the `ERC721` token address and a list of `tokenIds` owned by the prizePool.\\nThe method does not check if duplicate `tokenIds` or `tokenIds` that are not owned by the contract are provided. This may cause an exception when `_awardExternalErc721s` calls `prizePool.awardExternalERC721` to transfer an invalid or previously transferred token, blocking the award phase.\\nNote: An admin can recover from this situation by removing and re-adding the `ERC721` token from the awards list.\\nadding `tokenIds`\\n```\\n/// @notice Adds an external ERC721 token as an additional prize that can be awarded\\n/// @dev Only the Prize-Strategy owner/creator can assign external tokens,\\n/// and they must be approved by the Prize-Pool\\n/// NOTE: The NFT must already be owned by the Prize-Pool\\n/// @param \\_externalErc721 The address of an ERC721 token to be awarded\\n/// @param \\_tokenIds An array of token IDs of the ERC721 to be awarded\\nfunction addExternalErc721Award(address \\_externalErc721, uint256[] calldata \\_tokenIds) external onlyOwnerOrListener {\\n // require(\\_externalErc721.isContract(), "PeriodicPrizeStrategy/external-erc721-not-contract");\\n require(prizePool.canAwardExternal(\\_externalErc721), "PeriodicPrizeStrategy/cannot-award-external");\\n \\n if (!externalErc721s.contains(\\_externalErc721)) {\\n externalErc721s.addAddress(\\_externalErc721);\\n }\\n\\n for (uint256 i = 0; i < \\_tokenIds.length; i++) {\\n uint256 tokenId = \\_tokenIds[i];\\n require(IERC721(\\_externalErc721).ownerOf(tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token");\\n externalErc721TokenIds[\\_externalErc721].push(tokenId);\\n }\\n\\n emit ExternalErc721AwardAdded(\\_externalErc721, \\_tokenIds);\\n}\\n```\\n\\nawarding tokens\\n```\\n/// @notice Awards all external ERC721 tokens to the given user.\\n/// The external tokens must be held by the PrizePool contract.\\n/// @dev The list of ERC721s is reset after every award\\n/// @param winner The user to transfer the tokens to\\nfunction \\_awardExternalErc721s(address winner) internal {\\n address currentToken = externalErc721s.start();\\n while (currentToken != address(0) && currentToken != externalErc721s.end()) {\\n uint256 balance = IERC721(currentToken).balanceOf(address(prizePool));\\n if (balance > 0) {\\n prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[currentToken]);\\n delete externalErc721TokenIds[currentToken];\\n }\\n currentToken = externalErc721s.next(currentToken);\\n }\\n externalErc721s.clearAll();\\n}\\n```\\n\\ntransferring the tokens\\n```\\n/// @notice Called by the prize strategy to award external ERC721 prizes\\n/// @dev Used to award any arbitrary NFTs held by the Prize Pool\\n/// @param to The address of the winner that receives the award\\n/// @param externalToken The address of the external NFT token being awarded\\n/// @param tokenIds An array of NFT Token IDs to be transferred\\nfunction awardExternalERC721(\\n address to,\\n address externalToken,\\n uint256[] calldata tokenIds\\n)\\n external override\\n onlyPrizeStrategy\\n{\\n require(\\_canAwardExternal(externalToken), "PrizePool/invalid-external-token");\\n\\n if (tokenIds.length == 0) {\\n return;\\n }\\n\\n for (uint256 i = 0; i < tokenIds.length; i++) {\\n IERC721(externalToken).transferFrom(address(this), to, tokenIds[i]);\\n }\\n\\n emit AwardedExternalERC721(to, externalToken, tokenIds);\\n}\\n```\\n | Ensure that no duplicate token-ids were provided or skip over token-ids that are not owned by prize-pool (anymore). | null | ```\\n/// @notice Adds an external ERC721 token as an additional prize that can be awarded\\n/// @dev Only the Prize-Strategy owner/creator can assign external tokens,\\n/// and they must be approved by the Prize-Pool\\n/// NOTE: The NFT must already be owned by the Prize-Pool\\n/// @param \\_externalErc721 The address of an ERC721 token to be awarded\\n/// @param \\_tokenIds An array of token IDs of the ERC721 to be awarded\\nfunction addExternalErc721Award(address \\_externalErc721, uint256[] calldata \\_tokenIds) external onlyOwnerOrListener {\\n // require(\\_externalErc721.isContract(), "PeriodicPrizeStrategy/external-erc721-not-contract");\\n require(prizePool.canAwardExternal(\\_externalErc721), "PeriodicPrizeStrategy/cannot-award-external");\\n \\n if (!externalErc721s.contains(\\_externalErc721)) {\\n externalErc721s.addAddress(\\_externalErc721);\\n }\\n\\n for (uint256 i = 0; i < \\_tokenIds.length; i++) {\\n uint256 tokenId = \\_tokenIds[i];\\n require(IERC721(\\_externalErc721).ownerOf(tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token");\\n externalErc721TokenIds[\\_externalErc721].push(tokenId);\\n }\\n\\n emit ExternalErc721AwardAdded(\\_externalErc721, \\_tokenIds);\\n}\\n```\\n |
PeriodicPrizeStrategy - Token with callback related warnings (ERC777 a.o.) | medium | This issue is highly dependent on the configuration of the system. If an admin decides to allow callback enabled token (e.g. `ERC20` compliant `ERC777` or other ERC721/ERC20 extensions) as awards then one recipient may be able to\\nblock the payout for everyone by forcing a revert in the callback when accepting token awards\\nuse the callback to siphon gas, mint gas token, or similar activities\\npotentially re-enter the `PrizeStrategy` contract in an attempt to manipulate the payout (e.g. by immediately withdrawing from the pool to manipulate the 2nd ticket.draw())\\n```\\nfunction \\_awardExternalErc721s(address winner) internal {\\n address currentToken = externalErc721s.start();\\n while (currentToken != address(0) && currentToken != externalErc721s.end()) {\\n uint256 balance = IERC721(currentToken).balanceOf(address(prizePool));\\n if (balance > 0) {\\n prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[currentToken]);\\n delete externalErc721TokenIds[currentToken];\\n }\\n currentToken = externalErc721s.next(currentToken);\\n }\\n externalErc721s.clearAll();\\n}\\n```\\n | It is highly recommended to not allow tokens with callback functionality into the system. Document and/or implement safeguards that disallow the use of callback enabled tokens. Consider implementing means for the “other winners” to withdraw their share of the rewards independently from others. | null | ```\\nfunction \\_awardExternalErc721s(address winner) internal {\\n address currentToken = externalErc721s.start();\\n while (currentToken != address(0) && currentToken != externalErc721s.end()) {\\n uint256 balance = IERC721(currentToken).balanceOf(address(prizePool));\\n if (balance > 0) {\\n prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[currentToken]);\\n delete externalErc721TokenIds[currentToken];\\n }\\n currentToken = externalErc721s.next(currentToken);\\n }\\n externalErc721s.clearAll();\\n}\\n```\\n |
PeriodicPrizeStrategy - unbounded external tokens linked list may be used to force a gas DoS | medium | The size of the linked list of ERC20/ERC721 token awards is not limited. This fact may be exploited by an administrative account by adding an excessive number of external token addresses.\\nThe winning user might want to claim their win by calling `completeAward()` which fails in one of the `_distribute() -> _awardAllExternalTokens() -> _awardExternalErc20s/_awardExternalErc721s` while loops if too many token addresses are configured and gas consumption hits the block gas limit (or it just gets too expensive for the user to call).\\nNote: an admin can recover from this situation by removing items from the list.\\n```\\n/// @notice Adds an external ERC20 token type as an additional prize that can be awarded\\n/// @dev Only the Prize-Strategy owner/creator can assign external tokens,\\n/// and they must be approved by the Prize-Pool\\n/// @param \\_externalErc20 The address of an ERC20 token to be awarded\\nfunction addExternalErc20Award(address \\_externalErc20) external onlyOwnerOrListener {\\n \\_addExternalErc20Award(\\_externalErc20);\\n}\\n\\nfunction \\_addExternalErc20Award(address \\_externalErc20) internal {\\n require(prizePool.canAwardExternal(\\_externalErc20), "PeriodicPrizeStrategy/cannot-award-external");\\n externalErc20s.addAddress(\\_externalErc20);\\n emit ExternalErc20AwardAdded(\\_externalErc20);\\n}\\n```\\n\\n```\\n/// @param newAddress The address to shift to the front of the list\\nfunction addAddress(Mapping storage self, address newAddress) internal {\\n require(newAddress != SENTINEL && newAddress != address(0), "Invalid address");\\n require(self.addressMap[newAddress] == address(0), "Already added");\\n self.addressMap[newAddress] = self.addressMap[SENTINEL];\\n self.addressMap[SENTINEL] = newAddress;\\n self.count = self.count + 1;\\n}\\n```\\n\\nawarding the tokens loops through the linked list of configured tokens\\n```\\n/// @notice Awards all external ERC721 tokens to the given user.\\n/// The external tokens must be held by the PrizePool contract.\\n/// @dev The list of ERC721s is reset after every award\\n/// @param winner The user to transfer the tokens to\\nfunction \\_awardExternalErc721s(address winner) internal {\\n address currentToken = externalErc721s.start();\\n while (currentToken != address(0) && currentToken != externalErc721s.end()) {\\n uint256 balance = IERC721(currentToken).balanceOf(address(prizePool));\\n if (balance > 0) {\\n prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[currentToken]);\\n delete externalErc721TokenIds[currentToken];\\n }\\n currentToken = externalErc721s.next(currentToken);\\n }\\n externalErc721s.clearAll();\\n}\\n```\\n | Limit the number of tokens an admin can add. Consider implementing an interface that allows the user to claim tokens one-by-one or in user-configured batches. | null | ```\\n/// @notice Adds an external ERC20 token type as an additional prize that can be awarded\\n/// @dev Only the Prize-Strategy owner/creator can assign external tokens,\\n/// and they must be approved by the Prize-Pool\\n/// @param \\_externalErc20 The address of an ERC20 token to be awarded\\nfunction addExternalErc20Award(address \\_externalErc20) external onlyOwnerOrListener {\\n \\_addExternalErc20Award(\\_externalErc20);\\n}\\n\\nfunction \\_addExternalErc20Award(address \\_externalErc20) internal {\\n require(prizePool.canAwardExternal(\\_externalErc20), "PeriodicPrizeStrategy/cannot-award-external");\\n externalErc20s.addAddress(\\_externalErc20);\\n emit ExternalErc20AwardAdded(\\_externalErc20);\\n}\\n```\\n |
MultipleWinners - setNumberOfWinners does not enforce count>0 | medium | The constructor of `MultipleWinners` enforces that the argument `_numberOfWinners > 0` while `setNumberOfWinners` does not. A careless or malicious admin might set `__numberOfWinners` to zero to cause the `distribute()` method to throw and not pay out any winners.\\nenforced in the constructor\\n```\\nrequire(\\_numberOfWinners > 0, "MultipleWinners/num-gt-zero");\\n```\\n\\nnot enforced when updating the value at a later stage\\n```\\nfunction setNumberOfWinners(uint256 count) external onlyOwner {\\n \\_\\_numberOfWinners = count;\\n\\n emit NumberOfWinnersSet(count);\\n}\\n```\\n | Require that `numberOfWinners > 0`. | null | ```\\nrequire(\\_numberOfWinners > 0, "MultipleWinners/num-gt-zero");\\n```\\n |
LootBox - plunder should disallow plundering to address(0) | medium | Anyone can call `LootboxController.plunder()` to plunder on behalf of a `tokenId` owner. If a `LootBox` received an AirDrop but no `NFT` was issued to an owner (yet) this might open up an opportunity for a malicious actor to call `plunder()` in an attempt to burn the ETH and any airdropped tokens that allow transfers to `address(0)`.\\nNote:\\nDepending on the token implementation, transfers may or may not revert if the `toAddress == address(0)`, while burning the `ETH` will succeed.\\nThis might allow anyone to forcefully burn received `ETH` that would otherwise be available to the future beneficiary\\nIf the airdrop and transfer of `LootBox` ownership are not done within one transaction, this might open up a front-running window that allows a third party to burn air-dropped `ETH` before it can be claimed by the `owner`.\\nconsider one component issues the airdrop in one transaction (or block) and setting the `owner` in a later transaction (or block). The `owner` is unset for a short duration of time which might allow anyone to burn `ETH` held by the `LootBox` proxy instance.\\n`plunder()` receiving the `owner` of an `ERC721.tokenId`\\n```\\nfunction plunder(\\n address erc721,\\n uint256 tokenId,\\n IERC20[] calldata erc20s,\\n LootBox.WithdrawERC721[] calldata erc721s,\\n LootBox.WithdrawERC1155[] calldata erc1155s\\n) external {\\n address payable owner = payable(IERC721(erc721).ownerOf(tokenId));\\n```\\n\\nThe modified `ERC721` returns `address(0)` if the owner is not known\\n```\\n \\* @dev See {IERC721-ownerOf}.\\n \\*/\\nfunction ownerOf(uint256 tokenId) public view override returns (address) {\\n return \\_tokenOwners[tokenId];\\n}\\n```\\n\\nWhile `withdraw[ERC20|ERC721|ERC1155]` fail with `to == address(0)`, `transferEther()` succeeds and burns the eth by sending it to `address(0)`\\n```\\nfunction plunder(\\n IERC20[] memory erc20,\\n WithdrawERC721[] memory erc721,\\n WithdrawERC1155[] memory erc1155,\\n address payable to\\n) external {\\n \\_withdrawERC20(erc20, to);\\n \\_withdrawERC721(erc721, to);\\n \\_withdrawERC1155(erc1155, to);\\n transferEther(to, address(this).balance);\\n}\\n```\\n | Require that the destination address `to` in `plunder()` and `transferEther()` is not `address(0)`. | null | ```\\nfunction plunder(\\n address erc721,\\n uint256 tokenId,\\n IERC20[] calldata erc20s,\\n LootBox.WithdrawERC721[] calldata erc721s,\\n LootBox.WithdrawERC1155[] calldata erc1155s\\n) external {\\n address payable owner = payable(IERC721(erc721).ownerOf(tokenId));\\n```\\n |
PeriodicPrizeStrategy - Inconsistent behavior between award-phase modifiers and view functions | low | The logic in the `canStartAward()` function is inconsistent with that of the `requireCanStartAward` modifier, and the logic in the `canCompleteAward()` function is inconsistent with that of the `requireCanCompleteAward` modifier. Neither of these view functions appear to be used elsewhere in the codebase, but the similarities between the function names and the corresponding modifiers is highly misleading.\\n`canStartAward()` is inconsistent with `requireCanStartAward`\\n```\\nfunction canStartAward() external view returns (bool) {\\n return \\_isPrizePeriodOver() && !isRngRequested();\\n}\\n```\\n\\n```\\nmodifier requireCanStartAward() {\\n require(\\_isPrizePeriodOver(), "PeriodicPrizeStrategy/prize-period-not-over");\\n require(!isRngRequested() || isRngTimedOut(), "PeriodicPrizeStrategy/rng-already-requested");\\n \\_;\\n}\\n```\\n\\n`canCompleteAward()` is inconsistent with `requireCanCompleteAward`\\n```\\nfunction canCompleteAward() external view returns (bool) {\\n return isRngRequested() && isRngCompleted();\\n}\\n```\\n\\n```\\nmodifier requireCanCompleteAward() {\\n require(\\_isPrizePeriodOver(), "PeriodicPrizeStrategy/prize-period-not-over");\\n require(isRngRequested(), "PeriodicPrizeStrategy/rng-not-requested");\\n require(isRngCompleted(), "PeriodicPrizeStrategy/rng-not-complete");\\n \\_;\\n}\\n```\\n | Make the logic consistent between the view functions and the modifiers of the same name or remove the functions. | null | ```\\nfunction canStartAward() external view returns (bool) {\\n return \\_isPrizePeriodOver() && !isRngRequested();\\n}\\n```\\n |
MultipleWinners - Awards can be guaranteed with a set number of tickets | low | Because additional award drawings are distributed at a constant interval in the `SortitionSumTree` by `MultipleWinners._distribute()`, any user that holds a number of tickets `>= floor(totalSupply / __numberOfWinners)` can guarantee at least one award regardless of the initial drawing.\\nMultipleWinners._distribute():\\n```\\nuint256 ticketSplit = totalSupply.div(\\_\\_numberOfWinners);\\nuint256 nextRandom = randomNumber.add(ticketSplit);\\n// the other winners receive their prizeShares\\nfor (uint256 winnerCount = 1; winnerCount < \\_\\_numberOfWinners; winnerCount++) {\\n winners[winnerCount] = ticket.draw(nextRandom);\\n nextRandom = nextRandom.add(ticketSplit);\\n}\\n```\\n | Do not distribute awards at fixed intervals from the initial drawing, but instead randomize the additional drawings as well. | null | ```\\nuint256 ticketSplit = totalSupply.div(\\_\\_numberOfWinners);\\nuint256 nextRandom = randomNumber.add(ticketSplit);\\n// the other winners receive their prizeShares\\nfor (uint256 winnerCount = 1; winnerCount < \\_\\_numberOfWinners; winnerCount++) {\\n winners[winnerCount] = ticket.draw(nextRandom);\\n nextRandom = nextRandom.add(ticketSplit);\\n}\\n```\\n |
MultipleWinners - Inconsistent behavior compared to SingleRandomWinner | low | The `MultipleWinners` strategy carries out award distribution to the zero address if `ticket.draw()` returns `address(0)` (indicating an error condition) while `SingleRandomWinner` does not.\\n`SingleRandomWinner` silently skips award distribution if `ticket.draw()` returns `address(0)`.\\n```\\ncontract SingleRandomWinner is PeriodicPrizeStrategy {\\n function \\_distribute(uint256 randomNumber) internal override {\\n uint256 prize = prizePool.captureAwardBalance();\\n address winner = ticket.draw(randomNumber);\\n if (winner != address(0)) {\\n \\_awardTickets(winner, prize);\\n \\_awardAllExternalTokens(winner);\\n }\\n }\\n}\\n```\\n\\n`MultipleWinners` still attempts to distribute awards if `ticket.draw()` returns `address(0)`. This may or may not succeed depending on the implementation of the tokens included in the `externalErc20s` and `externalErc721s` linked lists.\\n```\\nfunction \\_distribute(uint256 randomNumber) internal override {\\n uint256 prize = prizePool.captureAwardBalance();\\n\\n // main winner gets all external tokens\\n address mainWinner = ticket.draw(randomNumber);\\n \\_awardAllExternalTokens(mainWinner);\\n\\n address[] memory winners = new address[](\\_\\_numberOfWinners);\\n winners[0] = mainWinner;\\n```\\n | Implement consistent behavior. Avoid hiding error conditions and consider throwing an exception instead. | null | ```\\ncontract SingleRandomWinner is PeriodicPrizeStrategy {\\n function \\_distribute(uint256 randomNumber) internal override {\\n uint256 prize = prizePool.captureAwardBalance();\\n address winner = ticket.draw(randomNumber);\\n if (winner != address(0)) {\\n \\_awardTickets(winner, prize);\\n \\_awardAllExternalTokens(winner);\\n }\\n }\\n}\\n```\\n |
Initialize implementations for proxy contracts and protect initialization methods | low | Any situation where the implementation of proxy contracts can be initialized by third parties should be avoided. This can be the case if the `initialize` function is unprotected or not initialized immediately after deployment. Since the implementation contract is not meant to be used directly without a proxy delegate-calling to it, it is recommended to protect the initialization method of the implementation by initializing on deployment.\\nThis affects all proxy implementations (the delegatecall target contract) deployed in the system.\\nThe implementation for `MultipleWinners` is not initialized. Even though not directly used by the system it may be initialized by a third party.\\n```\\nconstructor () public {\\n instance = new MultipleWinners();\\n}\\n```\\n\\nThe deployed `ERC721Contract` is not initialized.\\n```\\nconstructor () public {\\n erc721ControlledInstance = new ERC721Controlled();\\n erc721ControlledBytecode = MinimalProxyLibrary.minimalProxy(address(erc721ControlledInstance));\\n}\\n```\\n\\nThe deployed `LootBox` is not initialized.\\n```\\nconstructor () public {\\n lootBoxActionInstance = new LootBox();\\n lootBoxActionBytecode = MinimalProxyLibrary.minimalProxy(address(lootBoxActionInstance));\\n}\\n```\\n | Initialize unprotected implementation contracts in the implementation's constructor. Protect initialization methods from being called by unauthorized parties or ensure that deployment of the proxy and initialization is performed in the same transaction. | null | ```\\nconstructor () public {\\n instance = new MultipleWinners();\\n}\\n```\\n |
LootBox - transferEther should be internal | low | `LootBox.transferEther()` can be `internal` as it is only called from `LootBox.plunder()` and the LootBox(proxy) instances are generally very short-living (created and destroyed within one transaction).\\n```\\nfunction transferEther(address payable to, uint256 amount) public {\\n to.transfer(amount);\\n\\n emit TransferredEther(to, amount);\\n}\\n```\\n | Restrict transferEther()'s visibility to `internal`. | null | ```\\nfunction transferEther(address payable to, uint256 amount) public {\\n to.transfer(amount);\\n\\n emit TransferredEther(to, amount);\\n}\\n```\\n |
LootBox - executeCalls can be misused to relay calls | low | `LootBox` is deployed with `LootBoxController` and serves as the implementation for individual `create2` lootbox proxy contracts. None of the methods of the `LootBox` implementation contract are access restricted. A malicious actor may therefore use the `executeCalls()` method to relay arbitrary calls to other contracts on the blockchain in an attempt to disguise the origin or misuse the reputation of the `LootBox` contract (as it belongs to the PoolTogether project).\\nNote: allows non-value and value calls (deposits can be forces via selfdestruct)\\n```\\nfunction executeCalls(Call[] calldata calls) external returns (bytes[] memory) {\\n bytes[] memory response = new bytes[](calls.length);\\n for (uint256 i = 0; i < calls.length; i++) {\\n response[i] = \\_executeCall(calls[i].to, calls[i].value, calls[i].data);\\n }\\n return response;\\n}\\n```\\n | Restrict access to call forwarding functionality to trusted entities. Consider implementing the `Ownable` pattern allowing access to functionality to the owner only. | null | ```\\nfunction executeCalls(Call[] calldata calls) external returns (bytes[] memory) {\\n bytes[] memory response = new bytes[](calls.length);\\n for (uint256 i = 0; i < calls.length; i++) {\\n response[i] = \\_executeCall(calls[i].to, calls[i].value, calls[i].data);\\n }\\n return response;\\n}\\n```\\n |
ERC20 tokens with no return value will fail to transfer | high | Although the ERC20 standard suggests that a transfer should return `true` on success, many tokens are non-compliant in this regard.\\nIn that case, the `.transfer()` call here will revert even if the transfer is successful, because solidity will check that the RETURNDATASIZE matches the ERC20 interface.\\n```\\nif (!instance.transfer(getSendAddress(), forwarderBalance)) {\\n revert('Could not gather ERC20');\\n}\\n```\\n | Consider using OpenZeppelin's SafeERC20. | null | ```\\nif (!instance.transfer(getSendAddress(), forwarderBalance)) {\\n revert('Could not gather ERC20');\\n}\\n```\\n |
Delegated transactions can be executed for multiple accounts | high | The `Gateway` contract allows users to create meta transactions triggered by the system's backend. To do so, one of the owners of the account should sign the message in the following format:\\n```\\naddress sender = \\_hashPrimaryTypedData(\\n \\_hashTypedData(\\n nonce,\\n to,\\n data\\n )\\n).recoverAddress(senderSignature);\\n```\\n\\nThe message includes a nonce, destination address, and call data. The problem is that this message does not include the `account` address. So if the `sender` is the owner of multiple accounts, this meta transaction can be called for multiple accounts. | Resolution\\nComment from the client: The issue has been solved\\nAdd the `account` field in the signed message or make sure that any address can be the owner of only one `account`. | null | ```\\naddress sender = \\_hashPrimaryTypedData(\\n \\_hashTypedData(\\n nonce,\\n to,\\n data\\n )\\n).recoverAddress(senderSignature);\\n```\\n |
Removing an owner does not work in PersonalAccountRegistry | high | An owner of a personal account can be added/removed by other owners. When removing the owner, only `removedAtBlockNumber` value is updated. `accounts[account].owners[owner].added` remains true:\\n```\\naccounts[account].owners[owner].removedAtBlockNumber = block.number;\\n\\nemit AccountOwnerRemoved(\\n account,\\n owner\\n);\\n```\\n\\nBut when the account is checked whether this account is the owner, only `accounts[account].owners[owner].added` is actually checked:\\n```\\nfunction \\_verifySender(\\n address account\\n)\\n private\\n returns (address)\\n{\\n address sender = \\_getContextSender();\\n\\n if (!accounts[account].owners[sender].added) {\\n require(\\n accounts[account].salt == 0\\n );\\n\\n bytes32 salt = keccak256(\\n abi.encodePacked(sender)\\n );\\n\\n require(\\n account == \\_computeAccountAddress(salt)\\n );\\n\\n accounts[account].salt = salt;\\n accounts[account].owners[sender].added = true;\\n\\n emit AccountOwnerAdded(\\n account,\\n sender\\n );\\n }\\n\\n return sender;\\n}\\n```\\n\\nSo the owner will never be removed, because `accounts[account].owners[owner].added` will always be `true. | Properly check if the account is still the owner in the `_verifySender` function. | null | ```\\naccounts[account].owners[owner].removedAtBlockNumber = block.number;\\n\\nemit AccountOwnerRemoved(\\n account,\\n owner\\n);\\n```\\n |
The withdrawal mechanism is overcomplicated | medium | To withdraw the funds, anyone who has the account in `PaymentRegistry` should call the `withdrawDeposit` function and go through the withdrawal process. After the lockdown period (30 days), the user will withdraw all the funds from the account.\\n```\\nfunction withdrawDeposit(\\n address token\\n)\\n external\\n{\\n address owner = \\_getContextAccount();\\n uint256 lockedUntil = deposits[owner].withdrawalLockedUntil[token];\\n\\n /\\* solhint-disable not-rely-on-time \\*/\\n\\n if (lockedUntil != 0 && lockedUntil <= now) {\\n deposits[owner].withdrawalLockedUntil[token] = 0;\\n\\n address depositAccount = deposits[owner].account;\\n uint256 depositValue;\\n\\n if (token == address(0)) {\\n depositValue = depositAccount.balance;\\n } else {\\n depositValue = ERC20Token(token).balanceOf(depositAccount);\\n }\\n\\n \\_transferFromDeposit(\\n depositAccount,\\n owner,\\n token,\\n depositValue\\n );\\n\\n emit DepositWithdrawn(\\n depositAccount,\\n owner,\\n token,\\n depositValue\\n );\\n } else {\\n \\_deployDepositAccount(owner);\\n\\n lockedUntil = now.add(depositWithdrawalLockPeriod);\\n\\n deposits[owner].withdrawalLockedUntil[token] = lockedUntil;\\n\\n emit DepositWithdrawalRequested(\\n deposits[owner].account,\\n owner,\\n token,\\n lockedUntil\\n );\\n }\\n /\\* solhint-enable not-rely-on-time \\*/\\n}\\n```\\n\\nDuring that period, everyone who has a channel with the user is forced to commit their channels or lose money from that channel. When doing so, every user will reset the initial lockdown period and the withdrawer should start the process again.\\n```\\nif (deposits[sender].withdrawalLockedUntil[token] > 0) {\\n deposits[sender].withdrawalLockedUntil[token] = 0;\\n```\\n\\nThere is no way for the withdrawer to close the channel by himself. If the withdrawer has N channels, it's theoretically possible to wait for up to N*(30 days) period and make N+2 transactions. | There may be some minor recommendations on how to improve that without major changes:\\nWhen committing a payment channel, do not reset the lockdown period to zero. Two better option would be either not change it at all or extend to `now + depositWithdrawalLockPeriod` | null | ```\\nfunction withdrawDeposit(\\n address token\\n)\\n external\\n{\\n address owner = \\_getContextAccount();\\n uint256 lockedUntil = deposits[owner].withdrawalLockedUntil[token];\\n\\n /\\* solhint-disable not-rely-on-time \\*/\\n\\n if (lockedUntil != 0 && lockedUntil <= now) {\\n deposits[owner].withdrawalLockedUntil[token] = 0;\\n\\n address depositAccount = deposits[owner].account;\\n uint256 depositValue;\\n\\n if (token == address(0)) {\\n depositValue = depositAccount.balance;\\n } else {\\n depositValue = ERC20Token(token).balanceOf(depositAccount);\\n }\\n\\n \\_transferFromDeposit(\\n depositAccount,\\n owner,\\n token,\\n depositValue\\n );\\n\\n emit DepositWithdrawn(\\n depositAccount,\\n owner,\\n token,\\n depositValue\\n );\\n } else {\\n \\_deployDepositAccount(owner);\\n\\n lockedUntil = now.add(depositWithdrawalLockPeriod);\\n\\n deposits[owner].withdrawalLockedUntil[token] = lockedUntil;\\n\\n emit DepositWithdrawalRequested(\\n deposits[owner].account,\\n owner,\\n token,\\n lockedUntil\\n );\\n }\\n /\\* solhint-enable not-rely-on-time \\*/\\n}\\n```\\n |
The lockdown period shouldn't be extended when called multiple times | low | In order to withdraw a deposit from the `PaymentRegistry`, the account owner should call the `withdrawDeposit` function and wait for `depositWithdrawalLockPeriod` (30 days) before actually transferring all the tokens from the account.\\nThe issue is that if the withdrawer accidentally calls it for the second time before these 30 days pass, the waiting period gets extended for 30 days again.\\n```\\nif (lockedUntil != 0 && lockedUntil <= now) {\\n deposits[owner].withdrawalLockedUntil[token] = 0;\\n\\n address depositAccount = deposits[owner].account;\\n uint256 depositValue;\\n\\n if (token == address(0)) {\\n depositValue = depositAccount.balance;\\n } else {\\n depositValue = ERC20Token(token).balanceOf(depositAccount);\\n }\\n\\n \\_transferFromDeposit(\\n depositAccount,\\n owner,\\n token,\\n depositValue\\n );\\n\\n emit DepositWithdrawn(\\n depositAccount,\\n owner,\\n token,\\n depositValue\\n );\\n} else {\\n \\_deployDepositAccount(owner);\\n\\n lockedUntil = now.add(depositWithdrawalLockPeriod);\\n```\\n | Resolution\\nComment from the client: The issue has been solved\\nOnly extend the waiting period when a withdrawal is requested for the first time. | null | ```\\nif (lockedUntil != 0 && lockedUntil <= now) {\\n deposits[owner].withdrawalLockedUntil[token] = 0;\\n\\n address depositAccount = deposits[owner].account;\\n uint256 depositValue;\\n\\n if (token == address(0)) {\\n depositValue = depositAccount.balance;\\n } else {\\n depositValue = ERC20Token(token).balanceOf(depositAccount);\\n }\\n\\n \\_transferFromDeposit(\\n depositAccount,\\n owner,\\n token,\\n depositValue\\n );\\n\\n emit DepositWithdrawn(\\n depositAccount,\\n owner,\\n token,\\n depositValue\\n );\\n} else {\\n \\_deployDepositAccount(owner);\\n\\n lockedUntil = now.add(depositWithdrawalLockPeriod);\\n```\\n |
Gateway can call any contract Acknowledged | low | Resolution\\nComment from the client: That's right Gateway can call any contract, we want to keep it open for any external contract.\\nThe `Gateway` contract is used as a gateway for meta transactions and batched transactions. It can currently call any contract, while is only intended to call specific contracts in the system that implemented `GatewayRecipient` interface:\\n```\\n for (uint256 i = 0; i < data.length; i++) {\\n require(\\n to[i] != address(0)\\n );\\n\\n // solhint-disable-next-line avoid-low-level-calls\\n (succeeded,) = to[i].call(abi.encodePacked(data[i], account, sender));\\n\\n require(\\n succeeded\\n );\\n }\\n}\\n```\\n\\nThere are currently no restrictions for `to` value. | Make sure, only intended contracts can be called by the `Gateway` : `PersonalAccountRegistry`, `PaymentRegistry`, `ENSController`. | null | ```\\n for (uint256 i = 0; i < data.length; i++) {\\n require(\\n to[i] != address(0)\\n );\\n\\n // solhint-disable-next-line avoid-low-level-calls\\n (succeeded,) = to[i].call(abi.encodePacked(data[i], account, sender));\\n\\n require(\\n succeeded\\n );\\n }\\n}\\n```\\n |
Remove unused code | low | ```\\n return \\_deployAccount(\\n salt,\\n 0\\n );\\n}\\n\\nfunction \\_deployAccount(\\n bytes32 salt,\\n uint256 value\\n)\\n internal\\n returns (address)\\n{\\n return address(new Account{salt: salt, value: value}());\\n}\\n```\\n | It is recommended to remove this value as there are no use cases for it at the moment, however if it is planned to be used in the future, it should be well documented in the code to prevent confusion. | null | ```\\n return \\_deployAccount(\\n salt,\\n 0\\n );\\n}\\n\\nfunction \\_deployAccount(\\n bytes32 salt,\\n uint256 value\\n)\\n internal\\n returns (address)\\n{\\n return address(new Account{salt: salt, value: value}());\\n}\\n```\\n |
Every node gets a full validator's bounty | high | Resolution\\nThis issue is addressed in Bug/skale 3273 formula fix 435 and SKALE-3273 Fix BountyV2 populating error 438.\\nThe main change is related to how bounties are calculated for each validator. Below are a few notes on these pull requests:\\n`nodesByValidator` mapping is no longer used in the codebase and the non-zero values are deleted when `calculateBounty()` is called for a specific validator. The mapping is kept in the code for compatible storage layout in upgradable proxies.\\nSome functions such as `populate()` was developed for the transition to the upgraded contracts (rewrite `_effectiveDelegatedSum` values based on the new calculation formula). This function is not part of this review and will be removed in the future updates.\\nUnlike the old architecture, `nodesByValidator[validatorId]` is no longer used within the system to calculate `_effectiveDelegatedSum` and bounties. This is replaced by using overall staked amount and duration.\\nIf a validator does not claim their bounty during a month, it is considered as a misbehave and her bounty goes to the bounty pool for the next month.\\nTo get the bounty, every node calls the `getBounty` function of the `SkaleManager` contract. This function can be called once per month. The size of the bounty is defined in the `BountyV2` contract in the `_calculateMaximumBountyAmount` function:\\n```\\nreturn epochPoolSize\\n .add(\\_bountyWasPaidInCurrentEpoch)\\n .mul(\\n delegationController.getAndUpdateEffectiveDelegatedToValidator(\\n nodes.getValidatorId(nodeIndex),\\n currentMonth\\n )\\n )\\n .div(effectiveDelegatedSum);\\n```\\n\\nThe problem is that this amount actually represents the amount that should be paid to the validator of that node. But each node will get this amount. Additionally, the amount of validator's bounty should also correspond to the number of active nodes, while this formula only uses the amount of delegated funds. | Every node should get only their parts of the bounty. | null | ```\\nreturn epochPoolSize\\n .add(\\_bountyWasPaidInCurrentEpoch)\\n .mul(\\n delegationController.getAndUpdateEffectiveDelegatedToValidator(\\n nodes.getValidatorId(nodeIndex),\\n currentMonth\\n )\\n )\\n .div(effectiveDelegatedSum);\\n```\\n |
A node exit prevents some other nodes from exiting for some period Pending | medium | When a node wants to exit, the `nodeExit` function should be called as many times, as there are schains in the node. Each time one schain is getting removed from the node. During every call, all the active schains are getting frozen for 12 hours.\\n```\\nfunction freezeSchains(uint nodeIndex) external allow("SkaleManager") {\\n SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));\\n bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex);\\n for (uint i = 0; i < schains.length; i++) {\\n Rotation memory rotation = rotations[schains[i]];\\n if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) {\\n continue;\\n }\\n string memory schainName = schainsInternal.getSchainName(schains[i]);\\n string memory revertMessage = "Node cannot rotate on Schain ";\\n revertMessage = revertMessage.strConcat(schainName);\\n revertMessage = revertMessage.strConcat(", occupied by Node ");\\n revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str());\\n string memory dkgRevert = "DKG process did not finish on schain ";\\n ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));\\n require(\\n skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))),\\n dkgRevert.strConcat(schainName));\\n require(rotation.freezeUntil < now, revertMessage);\\n \\_startRotation(schains[i], nodeIndex);\\n }\\n}\\n```\\n\\nBecause of that, no other node that is running one of these schains can exit during that period. In the worst-case scenario, one malicious node has 128 Schains and calls `nodeExit` every 12 hours. That means that some nodes will not be able to exit for 64 days. | Make node exiting process less synchronous. | null | ```\\nfunction freezeSchains(uint nodeIndex) external allow("SkaleManager") {\\n SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal"));\\n bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex);\\n for (uint i = 0; i < schains.length; i++) {\\n Rotation memory rotation = rotations[schains[i]];\\n if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) {\\n continue;\\n }\\n string memory schainName = schainsInternal.getSchainName(schains[i]);\\n string memory revertMessage = "Node cannot rotate on Schain ";\\n revertMessage = revertMessage.strConcat(schainName);\\n revertMessage = revertMessage.strConcat(", occupied by Node ");\\n revertMessage = revertMessage.strConcat(rotation.nodeIndex.uint2str());\\n string memory dkgRevert = "DKG process did not finish on schain ";\\n ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG"));\\n require(\\n skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))),\\n dkgRevert.strConcat(schainName));\\n require(rotation.freezeUntil < now, revertMessage);\\n \\_startRotation(schains[i], nodeIndex);\\n }\\n}\\n```\\n |
Removing a node require multiple transactions and may be very expensive Pending | medium | When removing a node from the network, the owner should redistribute all the schains that are currently on that node to the other nodes. To do so, the validator should call the `nodeExit` function of the `SkaleManager` contract. In this function, only one schain is going to be removed from the node. So the node would have to call the `nodeExit` function as many times as there are schains in the node. Every call iterates over every potential node that can be used as a replacement (like in https://github.com/ConsenSys/skale-network-audit-2020-10/issues/3).\\nIn addition to that, the first call will iterate over all schains in the node, make 4 SSTORE operations and external calls for each schain:\\n```\\nfunction \\_startRotation(bytes32 schainIndex, uint nodeIndex) private {\\n ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));\\n rotations[schainIndex].nodeIndex = nodeIndex;\\n rotations[schainIndex].newNodeIndex = nodeIndex;\\n rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay());\\n waitForNewNode[schainIndex] = true;\\n}\\n```\\n\\nThis may hit the block gas limit even easier than issue 5.4.\\nIf the first transaction does not hit the block's gas limit, the maximum price of deleting a node would be BLOCK_GAS_COST * 128. At the moment, it's around $50,000. | Optimize the process of deleting a node, so it can't hit the gas limit in one transaction, and the overall price should be cheaper. | null | ```\\nfunction \\_startRotation(bytes32 schainIndex, uint nodeIndex) private {\\n ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder"));\\n rotations[schainIndex].nodeIndex = nodeIndex;\\n rotations[schainIndex].newNodeIndex = nodeIndex;\\n rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay());\\n waitForNewNode[schainIndex] = true;\\n}\\n```\\n |
Adding a new schain may potentially hit the gas limit Pending | medium | When adding a new schain, a group of random 16 nodes is randomly selected to run that schain. In order to do so, the `_generateGroup` function iterates over all the nodes that can be used for that purpose:\\n```\\nfunction \\_generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) {\\n Nodes nodes = Nodes(contractManager.getContract("Nodes"));\\n uint8 space = schains[schainId].partOfNode;\\n nodesInGroup = new uint[](numberOfNodes);\\n\\n uint[] memory possibleNodes = isEnoughNodes(schainId);\\n require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain");\\n uint ignoringTail = 0;\\n uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId)));\\n for (uint i = 0; i < nodesInGroup.length; ++i) {\\n uint index = random % (possibleNodes.length.sub(ignoringTail));\\n uint node = possibleNodes[index];\\n nodesInGroup[i] = node;\\n \\_swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1));\\n ++ignoringTail;\\n\\n \\_exceptionsForGroups[schainId][node] = true;\\n addSchainForNode(node, schainId);\\n require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node");\\n }\\n```\\n\\nIf the total number of nodes exceeds around a few thousands, adding a schain may hit the block gas limit. | Avoid iterating over all nodes when selecting a random node for a schain. | null | ```\\nfunction \\_generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) {\\n Nodes nodes = Nodes(contractManager.getContract("Nodes"));\\n uint8 space = schains[schainId].partOfNode;\\n nodesInGroup = new uint[](numberOfNodes);\\n\\n uint[] memory possibleNodes = isEnoughNodes(schainId);\\n require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain");\\n uint ignoringTail = 0;\\n uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId)));\\n for (uint i = 0; i < nodesInGroup.length; ++i) {\\n uint index = random % (possibleNodes.length.sub(ignoringTail));\\n uint node = possibleNodes[index];\\n nodesInGroup[i] = node;\\n \\_swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1));\\n ++ignoringTail;\\n\\n \\_exceptionsForGroups[schainId][node] = true;\\n addSchainForNode(node, schainId);\\n require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node");\\n }\\n```\\n |
Re-entrancy attacks with ERC-777 | low | Some tokens may allow users to perform re-entrancy while calling the `transferFrom` function. For example, it would be possible for an attacker to “borrow” a large amount of ERC-777 tokens from the lending pool by re-entering the `deposit` function from within `transferFrom`.\\n```\\nfunction deposit(\\n address asset,\\n uint256 amount,\\n address onBehalfOf,\\n uint16 referralCode\\n) external override {\\n \\_whenNotPaused();\\n ReserveLogic.ReserveData storage reserve = \\_reserves[asset];\\n\\n ValidationLogic.validateDeposit(reserve, amount);\\n\\n address aToken = reserve.aTokenAddress;\\n\\n reserve.updateState();\\n reserve.updateInterestRates(asset, aToken, amount, 0);\\n\\n bool isFirstDeposit = IAToken(aToken).balanceOf(onBehalfOf) == 0;\\n if (isFirstDeposit) {\\n \\_usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true);\\n }\\n\\n IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex);\\n\\n //transfer to the aToken contract\\n IERC20(asset).safeTransferFrom(msg.sender, aToken, amount);\\n\\n emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode);\\n}\\n```\\n\\nBecause the `safeTransferFrom` call is happening at the end of the `deposit` function, the `deposit` will be fully processed before the tokens are actually transferred.\\nSo at the beginning of the transfer, the attacker can re-enter the call to withdraw their deposit. The withdrawal will succeed even though the attacker's tokens have not yet been transferred to the lending pool. Essentially, the attacker is granted a flash-loan but without paying fees.\\nAdditionally, after these calls, interest rates will be skewed because interest rate update relies on the actual current balance.\\nRemediation\\nDo not whitelist ERC-777 or other re-entrable tokens to prevent this kind of attack. | Resolution\\nThe issue was partially mitigated in `deposit` function by minting AToken before the transfer of the `deposit` token. | null | ```\\nfunction deposit(\\n address asset,\\n uint256 amount,\\n address onBehalfOf,\\n uint16 referralCode\\n) external override {\\n \\_whenNotPaused();\\n ReserveLogic.ReserveData storage reserve = \\_reserves[asset];\\n\\n ValidationLogic.validateDeposit(reserve, amount);\\n\\n address aToken = reserve.aTokenAddress;\\n\\n reserve.updateState();\\n reserve.updateInterestRates(asset, aToken, amount, 0);\\n\\n bool isFirstDeposit = IAToken(aToken).balanceOf(onBehalfOf) == 0;\\n if (isFirstDeposit) {\\n \\_usersConfig[onBehalfOf].setUsingAsCollateral(reserve.id, true);\\n }\\n\\n IAToken(aToken).mint(onBehalfOf, amount, reserve.liquidityIndex);\\n\\n //transfer to the aToken contract\\n IERC20(asset).safeTransferFrom(msg.sender, aToken, amount);\\n\\n emit Deposit(asset, msg.sender, onBehalfOf, amount, referralCode);\\n}\\n```\\n |
Attacker can abuse swapLiquidity function to drain users' funds | medium | The `swapLiquidity` function allows liquidity providers to atomically swap their collateral. The function takes a receiverAddressargument that normally points to an `ISwapAdapter` implementation trusted by the user.\\n```\\nvars.fromReserveAToken.burn(\\n msg.sender,\\n receiverAddress,\\n amountToSwap,\\n fromReserve.liquidityIndex\\n);\\n// Notifies the receiver to proceed, sending as param the underlying already transferred\\nISwapAdapter(receiverAddress).executeOperation(\\n fromAsset,\\n toAsset,\\n amountToSwap,\\n address(this),\\n params\\n);\\n\\nvars.amountToReceive = IERC20(toAsset).balanceOf(receiverAddress);\\nif (vars.amountToReceive != 0) {\\n IERC20(toAsset).transferFrom(\\n receiverAddress,\\n address(vars.toReserveAToken),\\n vars.amountToReceive\\n );\\n\\n if (vars.toReserveAToken.balanceOf(msg.sender) == 0) {\\n \\_usersConfig[msg.sender].setUsingAsCollateral(toReserve.id, true);\\n }\\n\\n vars.toReserveAToken.mint(msg.sender, vars.amountToReceive, toReserve.liquidityIndex);\\n```\\n\\nHowever, since an attacker can pass any address as the `receiverAddress`, they can arbitrarily transfer funds from other contracts that have given allowances to the `LendingPool` contract (for example, another ISwapAdapter).\\nThe `amountToSwap` is defined by the caller and can be very small. The attacker gets the difference between `IERC20(toAsset).balanceOf(receiverAddress)` value of `toAsset` and the `amountToSwap` of `fromToken`.\\nRemediation\\nEnsure that no funds can be stolen from contracts that have granted allowances to the `LendingPool` contract. | Resolution\\nSolved by removing `swapLiquidity` functionality. | null | ```\\nvars.fromReserveAToken.burn(\\n msg.sender,\\n receiverAddress,\\n amountToSwap,\\n fromReserve.liquidityIndex\\n);\\n// Notifies the receiver to proceed, sending as param the underlying already transferred\\nISwapAdapter(receiverAddress).executeOperation(\\n fromAsset,\\n toAsset,\\n amountToSwap,\\n address(this),\\n params\\n);\\n\\nvars.amountToReceive = IERC20(toAsset).balanceOf(receiverAddress);\\nif (vars.amountToReceive != 0) {\\n IERC20(toAsset).transferFrom(\\n receiverAddress,\\n address(vars.toReserveAToken),\\n vars.amountToReceive\\n );\\n\\n if (vars.toReserveAToken.balanceOf(msg.sender) == 0) {\\n \\_usersConfig[msg.sender].setUsingAsCollateral(toReserve.id, true);\\n }\\n\\n vars.toReserveAToken.mint(msg.sender, vars.amountToReceive, toReserve.liquidityIndex);\\n```\\n |
VotingMachine - tryToMoveToValidating can lock up proposals | high | After a vote was received, the proposal can move to a validating state if any of the votes pass the proposal's `precReq` value, referred to as the minimum threshold.\\n```\\ntryToMoveToValidating(\\_proposalId);\\n```\\n\\nInside the method `tryToMoveToValidating` each of the vote options are checked to see if they pass `precReq`. In case that happens, the proposal goes into the next stage, specifically `Validating`.\\n```\\n/// @notice Function to move to Validating the proposal in the case the last vote action\\n/// was done before the required votingBlocksDuration passed\\n/// @param \\_proposalId The id of the proposal\\nfunction tryToMoveToValidating(uint256 \\_proposalId) public {\\n Proposal storage \\_proposal = proposals[\\_proposalId];\\n require(\\_proposal.proposalStatus == ProposalStatus.Voting, "VOTING\\_STATUS\\_REQUIRED");\\n if (\\_proposal.currentStatusInitBlock.add(\\_proposal.votingBlocksDuration) <= block.number) {\\n for (uint256 i = 0; i <= COUNT\\_CHOICES; i++) {\\n if (\\_proposal.votes[i] > \\_proposal.precReq) {\\n internalMoveToValidating(\\_proposalId);\\n }\\n }\\n }\\n}\\n```\\n\\nThe method `internalMoveToValidating` checks the proposal's status to be `Voting` and proceeds to moving the proposal into `Validating` state.\\n```\\n/// @notice Internal function to change proposalStatus from Voting to Validating\\n/// @param \\_proposalId The id of the proposal\\nfunction internalMoveToValidating(uint256 \\_proposalId) internal {\\n Proposal storage \\_proposal = proposals[\\_proposalId];\\n require(\\_proposal.proposalStatus == ProposalStatus.Voting, "ONLY\\_ON\\_VOTING\\_STATUS");\\n \\_proposal.proposalStatus = ProposalStatus.Validating;\\n \\_proposal.currentStatusInitBlock = block.number;\\n emit StatusChangeToValidating(\\_proposalId);\\n}\\n```\\n\\nThe problem appears if multiple vote options go past the minimum threshold. This is because the loop does not stop after the first found option and the loop will fail when the method `internalMoveToValidating` is called a second time.\\n```\\nfor (uint256 i = 0; i <= COUNT\\_CHOICES; i++) {\\n if (\\_proposal.votes[i] > \\_proposal.precReq) {\\n internalMoveToValidating(\\_proposalId);\\n }\\n}\\n```\\n\\nThe method `internalMoveToValidating` fails the second time because the first time it is called, the proposal goes into the `Validating` state and the second time it is called, the require check fails.\\n```\\nrequire(\\_proposal.proposalStatus == ProposalStatus.Voting, "ONLY\\_ON\\_VOTING\\_STATUS");\\n\\_proposal.proposalStatus = ProposalStatus.Validating;\\n```\\n\\nThis can lead to proposal lock-ups if there are enough votes to at least one option that pass the minimum threshold. | After moving to the `Validating` state return successfully.\\n```\\nfunction tryToMoveToValidating(uint256 \\_proposalId) public {\\n Proposal storage \\_proposal = proposals[\\_proposalId];\\n require(\\_proposal.proposalStatus == ProposalStatus.Voting, "VOTING\\_STATUS\\_REQUIRED");\\n if (\\_proposal.currentStatusInitBlock.add(\\_proposal.votingBlocksDuration) <= block.number) {\\n for (uint256 i = 0; i <= COUNT\\_CHOICES; i++) {\\n if (\\_proposal.votes[i] > \\_proposal.precReq) {\\n internalMoveToValidating(\\_proposalId);\\n return; // <- this was added\\n }\\n }\\n }\\n}\\n```\\n\\nAn additional change can be done to `internalMoveToValidating` because it is called only in `tryToMoveToValidating` and the parent method already does the check.\\n```\\n/// @notice Internal function to change proposalStatus from Voting to Validating\\n/// @param \\_proposalId The id of the proposal\\nfunction internalMoveToValidating(uint256 \\_proposalId) internal {\\n Proposal storage \\_proposal = proposals[\\_proposalId];\\n // The line below can be removed\\n // require(\\_proposal.proposalStatus == ProposalStatus.Voting, "ONLY\\_ON\\_VOTING\\_STATUS");\\n \\_proposal.proposalStatus = ProposalStatus.Validating;\\n \\_proposal.currentStatusInitBlock = block.number;\\n emit StatusChangeToValidating(\\_proposalId);\\n}\\n```\\n | null | ```\\ntryToMoveToValidating(\\_proposalId);\\n```\\n |
VotingMachine - verifyNonce should only allow the next nonce | high | When a relayer calls `submitVoteByRelayer` they also need to provide a nonce. This nonce is cryptographicly checked against the provided signature. It is also checked again to be higher than the previous nonce saved for that voter.\\n```\\n/// @notice Verifies the nonce of a voter on a proposal\\n/// @param \\_proposalId The id of the proposal\\n/// @param \\_voter The address of the voter\\n/// @param \\_relayerNonce The nonce submitted by the relayer\\nfunction verifyNonce(uint256 \\_proposalId, address \\_voter, uint256 \\_relayerNonce) public view {\\n Proposal storage \\_proposal = proposals[\\_proposalId];\\n require(\\_proposal.voters[\\_voter].nonce < \\_relayerNonce, "INVALID\\_NONCE");\\n}\\n```\\n\\nWhen the vote is saved, the previous nonce is incremented.\\n```\\nvoter.nonce = voter.nonce.add(1);\\n```\\n\\nThis leaves the opportunity to use the same signature to vote multiple times, as long as the provided nonce is higher than the incremented nonce. | The check should be more restrictive and make sure the consecutive nonce was provided.\\n```\\nrequire(\\_proposal.voters[\\_voter].nonce + 1 == \\_relayerNonce, "INVALID\\_NONCE");\\n```\\n | null | ```\\n/// @notice Verifies the nonce of a voter on a proposal\\n/// @param \\_proposalId The id of the proposal\\n/// @param \\_voter The address of the voter\\n/// @param \\_relayerNonce The nonce submitted by the relayer\\nfunction verifyNonce(uint256 \\_proposalId, address \\_voter, uint256 \\_relayerNonce) public view {\\n Proposal storage \\_proposal = proposals[\\_proposalId];\\n require(\\_proposal.voters[\\_voter].nonce < \\_relayerNonce, "INVALID\\_NONCE");\\n}\\n```\\n |
VoteMachine - Cancelling vote does not increase the nonce | low | A vote can be cancelled by calling `cancelVoteByRelayer` with the proposal ID, nonce, voter's address, signature and a hash of the sent params.\\nThe parameters are hashed and checked against the signature correctly.\\nThe nonce is part of these parameters and it is checked to be valid.\\n```\\nrequire(\\_proposal.voters[\\_voter].nonce < \\_relayerNonce, "INVALID\\_NONCE");\\n```\\n\\nOnce the vote is cancelled, the data is cleared but the nonce is not increased.\\n```\\nif (\\_cachedVoter.balance > 0) {\\n \\_proposal.votes[\\_cachedVoter.vote] = \\_proposal.votes[\\_cachedVoter.vote].sub(\\_cachedVoter.balance.mul(\\_cachedVoter.weight));\\n \\_proposal.totalVotes = \\_proposal.totalVotes.sub(1);\\n voter.weight = 0;\\n voter.balance = 0;\\n voter.vote = 0;\\n voter.asset = address(0);\\n emit VoteCancelled(\\n \\_proposalId,\\n \\_voter,\\n \\_cachedVoter.vote,\\n \\_cachedVoter.asset,\\n \\_cachedVoter.weight,\\n \\_cachedVoter.balance,\\n uint256(\\_proposal.proposalStatus)\\n );\\n}\\n```\\n\\nThis means that in the future, the same signature can be used as long as the nonce is still higher than the current one. | Considering the recommendation from issue https://github.com/ConsenSys/aave-governance-dao-audit-2020-01/issues/4 is implemented, the nonce should also increase when the vote is cancelled. Otherwise the same signature can be replayed again. | null | ```\\nrequire(\\_proposal.voters[\\_voter].nonce < \\_relayerNonce, "INVALID\\_NONCE");\\n```\\n |
Possible lock ups with SafeMath multiplication Acknowledged | low | In some cases using SafeMath can lead to a situation where a contract is locked up due to an unavoidable overflow.\\nIt is theoretically possible that both the `internalSubmitVote()` and `internalCancelVote()` functions could become unusable by voters with a high enough balance, if the asset weighting is set extremely high.\\nThis line in `internalSubmitVote()` could overflow if the voter's balance and the asset weight were sufficiently high:\\n```\\nuint256 \\_votingPower = \\_voterAssetBalance.mul(\\_assetWeight);\\n```\\n\\nA similar situation occurs in internalCancelVote():\\n```\\n\\_proposal.votes[\\_cachedVoter.vote] = \\_proposal.votes[\\_cachedVoter.vote].sub(\\_cachedVoter.balance.mul(\\_cachedVoter.weight));\\n\\_proposal.totalVotes = \\_proposal.totalVotes.sub(1);\\n```\\n | This could be protected against by setting a maximum value for asset weights. In practice it is very unlikely to occur in this situation, but it could be introduced at some point in the future. | null | ```\\nuint256 \\_votingPower = \\_voterAssetBalance.mul(\\_assetWeight);\\n```\\n |
Reentrancy vulnerability in MetaSwap.swap() | high | `MetaSwap.swap()` should have a reentrancy guard.\\nThe adapters use this general process:\\nCollect the from token (or ether) from the user.\\nExecute the trade.\\nTransfer the contract's balance of tokens (from and to) and ether to the user.\\nIf an attacker is able to reenter `swap()` before step 3, they can execute their own trade using the same tokens and get all the tokens for themselves.\\nThis is partially mitigated by the check against `amountTo` in `CommonAdapter`, but note that the `amountTo` typically allows for slippage, so it may still leave room for an attacker to siphon off some amount while still returning the required minimum to the user.\\n```\\n// Transfer remaining balance of tokenTo to sender\\nif (address(tokenTo) != Constants.ETH) {\\n uint256 balance = tokenTo.balanceOf(address(this));\\n require(balance >= amountTo, "INSUFFICIENT\\_AMOUNT");\\n \\_transfer(tokenTo, balance, recipient);\\n} else {\\n```\\n\\nAs an example of how this could be exploited, 0x supports an “EIP1271Wallet” signature type, which invokes an external contract to check whether a trade is allowed. A malicious maker might front run the swap to reduce their inventory. This way, the taker is sending more of the taker asset than necessary to `MetaSwap`. The excess can be stolen by the maker during the EIP1271 call. | Use a simple reentrancy guard, such as OpenZeppelin's `ReentrancyGuard` to prevent reentrancy in `MetaSwap.swap()`. It might seem more obvious to put this check in `Spender.swap()`, but the `Spender` contract intentionally does not use any storage to avoid interference between different adapters. | null | ```\\n// Transfer remaining balance of tokenTo to sender\\nif (address(tokenTo) != Constants.ETH) {\\n uint256 balance = tokenTo.balanceOf(address(this));\\n require(balance >= amountTo, "INSUFFICIENT\\_AMOUNT");\\n \\_transfer(tokenTo, balance, recipient);\\n} else {\\n```\\n |
Simplify fee calculation in WethAdapter | low | `WethAdapter` does some arithmetic to keep track of how much ether is being provided as a fee versus as funds that should be transferred into WETH:\\n```\\n// Some aggregators require ETH fees\\nuint256 fee = msg.value;\\n\\nif (address(tokenFrom) == Constants.ETH) {\\n // If tokenFrom is ETH, msg.value = fee + amountFrom (total fee could be 0)\\n require(amountFrom <= fee, "MSG\\_VAL\\_INSUFFICIENT");\\n fee -= amountFrom;\\n // Can't deal with ETH, convert to WETH\\n IWETH weth = getWETH();\\n weth.deposit{value: amountFrom}();\\n \\_approveSpender(weth, spender, amountFrom);\\n} else {\\n // Otherwise capture tokens from sender\\n // tokenFrom.safeTransferFrom(recipient, address(this), amountFrom);\\n \\_approveSpender(tokenFrom, spender, amountFrom);\\n}\\n\\n// Perform the swap\\naggregator.functionCallWithValue(abi.encodePacked(method, data), fee);\\n```\\n\\nThis code can be simplified by using `address(this).balance` instead. | Resolution\\nConsenSys/[email protected]93bf5c6.\\nConsider something like the following code instead:\\n```\\nif (address(tokenFrom) == Constants.ETH) {\\n getWETH().deposit{value: amountFrom}(); // will revert if the contract has an insufficient balance\\n \\_approveSpender(weth, spender, amountFrom);\\n} else {\\n tokenFrom.safeTransferFrom(recipient, address(this), amountFrom);\\n \\_approveSpender(tokenFrom, spender, amountFrom);\\n}\\n\\n// Send the remaining balance as the fee.\\naggregator.functionCallWithValue(abi.encodePacked(method, data), address(this).balance);\\n```\\n\\nAside from being a little simpler, this way of writing the code makes it obvious that the full balance is being properly consumed. Part is traded, and the rest is sent as a fee. | null | ```\\n// Some aggregators require ETH fees\\nuint256 fee = msg.value;\\n\\nif (address(tokenFrom) == Constants.ETH) {\\n // If tokenFrom is ETH, msg.value = fee + amountFrom (total fee could be 0)\\n require(amountFrom <= fee, "MSG\\_VAL\\_INSUFFICIENT");\\n fee -= amountFrom;\\n // Can't deal with ETH, convert to WETH\\n IWETH weth = getWETH();\\n weth.deposit{value: amountFrom}();\\n \\_approveSpender(weth, spender, amountFrom);\\n} else {\\n // Otherwise capture tokens from sender\\n // tokenFrom.safeTransferFrom(recipient, address(this), amountFrom);\\n \\_approveSpender(tokenFrom, spender, amountFrom);\\n}\\n\\n// Perform the swap\\naggregator.functionCallWithValue(abi.encodePacked(method, data), fee);\\n```\\n |
Consider checking adapter existence in MetaSwap | low | `MetaSwap` doesn't check that an adapter exists before calling into Spender:\\n```\\nfunction swap(\\n string calldata aggregatorId,\\n IERC20 tokenFrom,\\n uint256 amount,\\n bytes calldata data\\n) external payable whenNotPaused nonReentrant {\\n Adapter storage adapter = adapters[aggregatorId];\\n\\n if (address(tokenFrom) != Constants.ETH) {\\n tokenFrom.safeTransferFrom(msg.sender, address(spender), amount);\\n }\\n\\n spender.swap{value: msg.value}(\\n adapter.addr,\\n```\\n\\nThen `Spender` performs the check and reverts if it receives `address(0)`.\\n```\\nfunction swap(address adapter, bytes calldata data) external payable {\\n require(adapter != address(0), "ADAPTER\\_NOT\\_SUPPORTED");\\n```\\n\\nIt can be difficult to decide where to put a check like this, especially when the operation spans multiple contracts. Arguments can be made for either choice (or even duplicating the check), but as a general rule it's a good idea to avoid passing invalid parameters internally. Checking for adapter existence in `MetaSwap.swap()` is a natural place to do input validation, and it means `Spender` can have a simpler model where it trusts its inputs (which always come from MetaSwap). | Drop the check from `Spender.swap()` and perform the check instead in `MetaSwap.swap()`. | null | ```\\nfunction swap(\\n string calldata aggregatorId,\\n IERC20 tokenFrom,\\n uint256 amount,\\n bytes calldata data\\n) external payable whenNotPaused nonReentrant {\\n Adapter storage adapter = adapters[aggregatorId];\\n\\n if (address(tokenFrom) != Constants.ETH) {\\n tokenFrom.safeTransferFrom(msg.sender, address(spender), amount);\\n }\\n\\n spender.swap{value: msg.value}(\\n adapter.addr,\\n```\\n |
Swap fees can be bypassed using redeemMasset | high | Part of the value proposition for liquidity providers is earning fees incurred for swapping between assets. However, traders can perform fee-less swaps by providing liquidity in one bAsset, followed by calling `redeemMasset()` to convert the resulting mAssets back into a proportional amount of bAssets. Since removing liquidity via `redeemMasset()` does not incur a fee this is equivalent to doing a swap with zero fees.\\nAs a very simple example, assuming a pool with 2 bAssets (say, DAI and USDT), it would be possible to swap 10 DAI to USDT as follows:\\nAdd 20 DAI to the pool, receive 20 mUSD\\ncall redeemMasset() to redeem 10 DAI and 10 USDT\\nThe boolean argument `applyFee` is set to `false` in _redeemMasset:\\n```\\n\\_settleRedemption(\\_recipient, \\_mAssetQuantity, props.bAssets, bAssetQuantities, props.indexes, props.integrators, false);\\n```\\n | Resolution\\nThis issue was reported independently via the bug bounty program and was fixed early during the audit. The fix has already been deployed on mainnet using the upgrade mechanism\\nCharge a small redemption fee in `redeemMasset()`. | null | ```\\n\\_settleRedemption(\\_recipient, \\_mAssetQuantity, props.bAssets, bAssetQuantities, props.indexes, props.integrators, false);\\n```\\n |
Users can collect interest from SavingsContract by only staking mTokens momentarily | high | The SAVE contract allows users to deposit mAssets in return for lending yield and swap fees. When depositing mAsset, users receive a “credit” tokens at the momentary credit/mAsset exchange rate which is updated at every deposit. However, the smart contract enforces a minimum timeframe of 30 minutes in which the interest rate will not be updated. A user who deposits shortly before the end of the timeframe will receive credits at the stale interest rate and can immediately trigger and update of the rate and withdraw at the updated (more favorable) rate after the 30 minutes window. As a result, it would be possible for users to benefit from interest payouts by only staking mAssets momentarily and using them for other purposes the rest of the time.\\n```\\n// 1. Only collect interest if it has been 30 mins\\nuint256 timeSinceLastCollection = now.sub(previousCollection);\\nif(timeSinceLastCollection > THIRTY\\_MINUTES) {\\n```\\n | Remove the 30 minutes window such that every deposit also updates the exchange rate between credits and tokens. Note that this issue was reported independently during the bug bounty program and a fix is currently being worked on. | null | ```\\n// 1. Only collect interest if it has been 30 mins\\nuint256 timeSinceLastCollection = now.sub(previousCollection);\\nif(timeSinceLastCollection > THIRTY\\_MINUTES) {\\n```\\n |
Internal accounting of vault balance may diverge from actual token balance in lending pool Won't Fix | medium | It is possible that the vault balance for a given bAsset is greater than the corresponding balance in the lending pool. This violates one of the correctness properties stated in the audit brief. Our Harvey fuzzer was able to generate a transaction that mints a small amount (0xf500) of mAsset. Due to the way that the lending pool integration (Compound in this case) updates the vault balance it ends up greater than the available balance in the lending pool.\\nMore specifically, the integration contract assumes that the amount deposited into the pool is equal to the amount received by the mAsset contract for the case where no transaction fees are charged for token transfers:\\n```\\nquantityDeposited = \\_amount;\\n\\nif(\\_isTokenFeeCharged) {\\n // If we charge a fee, account for it\\n uint256 prevBal = \\_checkBalance(cToken);\\n require(cToken.mint(\\_amount) == 0, "cToken mint failed");\\n uint256 newBal = \\_checkBalance(cToken);\\n quantityDeposited = \\_min(quantityDeposited, newBal.sub(prevBal));\\n} else {\\n // Else just execute the mint\\n require(cToken.mint(\\_amount) == 0, "cToken mint failed");\\n}\\n\\nemit Deposit(\\_bAsset, address(cToken), quantityDeposited);\\n```\\n\\nFor illustration, consider the following scenario: assume your current balance in a lending pool is 0. When you deposit some amount X into the lending pool your balance after the deposit may be less than X (even if the underlying token does not charge transfer fees). One reason for this is rounding, but, in theory, a lending pool could also charge fees, etc.\\nThe vault balance is updated in function `Masset._mintTo` based on the amount returned by the integration.\\n```\\nbasketManager.increaseVaultBalance(bInfo.index, integrator, quantityDeposited);\\n```\\n\\n```\\nuint256 deposited = IPlatformIntegration(\\_integrator).deposit(\\_bAsset, quantityTransferred, \\_erc20TransferFeeCharged);\\n```\\n\\nThis violation of the correctness property is temporary since the vault balance is readjusted when interest is collected. However, the time frame of ca. 30 minutes between interest collections (may be longer if no continuous interest is distributed) means that it may be violated for substantial periods of time.\\n```\\nuint256 balance = IPlatformIntegration(integrations[i]).checkBalance(b.addr);\\nuint256 oldVaultBalance = b.vaultBalance;\\n\\n// accumulate interest (ratioed bAsset)\\nif(balance > oldVaultBalance && b.status == BassetStatus.Normal) {\\n // Update balance\\n basket.bassets[i].vaultBalance = balance;\\n```\\n\\nThe regular updates due to interest collection should ensure that the difference stays relatively small. However, note that the following scenarios is feasible: assuming there is 0 DAI in the basket, a user mints X mUSD by depositing X DAI. While the interest collection hasn't been triggered yet, the user tries to redeem X mUSD for DAI. This may fail since the amount of DAI in the lending pool is smaller than X. | It seems like this issue could be fixed by using the balance increase from the lending pool to update the vault balance (much like for the scenario where transfer fees are charged) instead of using the amount received. | null | ```\\nquantityDeposited = \\_amount;\\n\\nif(\\_isTokenFeeCharged) {\\n // If we charge a fee, account for it\\n uint256 prevBal = \\_checkBalance(cToken);\\n require(cToken.mint(\\_amount) == 0, "cToken mint failed");\\n uint256 newBal = \\_checkBalance(cToken);\\n quantityDeposited = \\_min(quantityDeposited, newBal.sub(prevBal));\\n} else {\\n // Else just execute the mint\\n require(cToken.mint(\\_amount) == 0, "cToken mint failed");\\n}\\n\\nemit Deposit(\\_bAsset, address(cToken), quantityDeposited);\\n```\\n |
Missing validation in Masset._redeemTo Acknowledged | medium | In function `_redeemTo` the collateralisation ratio is not taken into account unlike in _redeemMasset:\\n```\\nuint256 colRatio = StableMath.min(props.colRatio, StableMath.getFullScale());\\n\\n// Ensure payout is related to the collateralised mAsset quantity\\nuint256 collateralisedMassetQuantity = \\_mAssetQuantity.mulTruncate(colRatio);\\n```\\n\\nIt seems like `_redeemTo` should not be executed if the collateralisation ratio is below 100%. However, the contracts (that is, `Masset` and ForgeValidator) themselves don't seem to enforce this explicitly. Instead, the governor needs to ensure that the collateralisation ratio is only set to a value below 100% when the basket is not “healthy” (for instance, if it is considered “failed”). Failing to ensure this may allow an attacker to redeem a disproportionate amount of assets. Note that the functionality for setting the collateralisation ratio is not currently implemented in the audited code. | Consider enforcing the intended use of `_redeemTo` more explicitly. For instance, it might be possible to introduce additional input validation by requiring that the collateralisation ratio is not below 100%. | null | ```\\nuint256 colRatio = StableMath.min(props.colRatio, StableMath.getFullScale());\\n\\n// Ensure payout is related to the collateralised mAsset quantity\\nuint256 collateralisedMassetQuantity = \\_mAssetQuantity.mulTruncate(colRatio);\\n```\\n |
Removing a bAsset might leave some tokens stuck in the vault Acknowledged | low | In function `_removeBasset` there is existing validation to make sure only “empty” vaults are removed:\\n```\\nrequire(bAsset.vaultBalance == 0, "bAsset vault must be empty");\\n```\\n\\nHowever, this is not necessarily sufficient since the lending pool balance may be higher than the vault balance. The reason is that the vault balance is usually slightly out-of-date due to the 30 minutes time span between interest collections. Consider the scenario: (1) a user swaps out an asset 29 minutes after the last interest collection to reduce its vault balance from 100 USD to 0, and (2) the governor subsequently remove the asset. During those 29 minutes the asset was collecting interest (according to the lending pool the balance was higher than 100 USD at the time of the swap) that is now “stuck” in the vault. | Consider adding additional input validation (for instance, by requiring that the lending pool balance to be 0) or triggering a swap directly when removing an asset from the basket. | null | ```\\nrequire(bAsset.vaultBalance == 0, "bAsset vault must be empty");\\n```\\n |
Unused parameter in BasketManager._addBasset Won't Fix | low | It seems like the `_measurementMultiple` parameter is always `StableMath.getRatioScale()` (1e8). There is also some range validation code that seems unnecessary if the parameter is always 1e8.\\n```\\nrequire(\\_measurementMultiple >= 1e6 && \\_measurementMultiple <= 1e10, "MM out of range");\\n```\\n | Consider removing the parameter and the input validation to improve the readability of the code. | null | ```\\nrequire(\\_measurementMultiple >= 1e6 && \\_measurementMultiple <= 1e10, "MM out of range");\\n```\\n |
Assumptions are made about interest distribution Won't Fix | low | There is a mechanism that prevents interest collection if the extrapolated APY exceeds a threshold (MAX_APY).\\n```\\nrequire(extrapolatedAPY < MAX\\_APY, "Interest protected from inflating past maxAPY");\\n```\\n\\nThe extrapolation seems to assume that the interest is payed out frequently and continuously. It seems like a less frequent payout (for instance, once a month/year) could be rejected since the extrapolation considers the interest since the last time that `collectAndDistributeInterest` was called (potentially without interest being collected). | Consider revisiting or documenting this assumption. For instance, one could consider extrapolating between the current time and the last time that (non-zero) interest was actually collected. | null | ```\\nrequire(extrapolatedAPY < MAX\\_APY, "Interest protected from inflating past maxAPY");\\n```\\n |
Assumptions are made about Aave and Compound integrations Acknowledged | low | The code makes several assumptions about the Aave and Compound integrations. A malicious or malfunctioning integration (or lending pool) might violate those assumptions. This might lead to unintended behavior in the system. Below are three such assumptions:\\nfunction `checkBalance` reverts if the token hasn't been added:\\n```\\nIPlatformIntegration(\\_integration).checkBalance(\\_bAsset);\\n```\\n\\nfunction `withdraw` is trusted to not fail when it shouldn't:\\n```\\nIPlatformIntegration(\\_integrators[i]).withdraw(\\_recipient, bAsset, q, \\_bAssets[i].isTransferFeeCharged);\\n```\\n\\nthe mapping from mAssets to pTokens is fixed:\\n```\\nrequire(bAssetToPToken[\\_bAsset] == address(0), "pToken already set");\\n```\\n\\nThe first assumption could be avoided by adding a designated function to check if the token was added.\\nThe second assumption is more difficult to avoid, but should be considered when adding new integrations. The system needs to trust the lending pools to work properly; for instance, if the lending pool would blacklist the integration contract the system may behave in unintended ways.\\nThe third assumption could be avoided, but it comes at a cost. | Consider revisiting or avoiding these assumptions. For any assumptions that are there by design it would be good to document them to facilitate future changes. One should also be careful to avoid coupling between external systems. For instance, if withdrawing from Aave fails this should not prevent withdrawing from Compound. | null | ```\\nIPlatformIntegration(\\_integration).checkBalance(\\_bAsset);\\n```\\n |
Assumptions are made about bAssets Acknowledged | low | The code makes several assumptions about the bAssets that can be used. A malicious or malfunctioning asset contract might violate those assumptions. This might lead to unintended behavior in the system. Below there are several such assumptions:\\nDecimals of a bAsset are constant where the decimals are used to derive the asset's ratio:\\n```\\nuint256 bAsset\\_decimals = CommonHelpers.getDecimals(\\_bAsset);\\n```\\n\\nDecimals must be in a range from 4 to 18:\\n```\\nrequire(decimals >= 4 && decimals <= 18, "Token must have sufficient decimal places");\\n```\\n\\nThe governor is able to foresee when transfer fees are charged (which needs to be called if anything changes); in theory, assets could be much more flexible in when transfer fees are charged (for instance, during certain periods or for certain users)\\n```\\nfunction setTransferFeesFlag(address \\_bAsset, bool \\_flag)\\n```\\n\\nIt seems like some of these assumptions could be avoided, but there might be a cost. For instance, one could retrieve the decimals directly instead of “caching” them and one could always enable the setting where transfer fees may be charged. | Consider revisiting or avoiding these assumptions. For any assumptions that are there by design it would be good to document them to facilitate future changes. | null | ```\\nuint256 bAsset\\_decimals = CommonHelpers.getDecimals(\\_bAsset);\\n```\\n |
Unused field in ForgePropsMulti struct Won't Fix | low | The `ForgePropsMulti` struct defines the field `isValid` which always seems to be true:\\n```\\n/\\*\\* @dev All details needed to Forge with multiple bAssets \\*/\\nstruct ForgePropsMulti {\\n bool isValid; // Flag to signify that forge bAssets have passed validity check\\n Basset[] bAssets;\\n address[] integrators;\\n uint8[] indexes;\\n}\\n```\\n\\nIf it is indeed always true, one could remove the following line:\\n```\\nif(!props.isValid) return 0;\\n```\\n | If the field is indeed always true please consider removing it to simplify the code. | null | ```\\n/\\*\\* @dev All details needed to Forge with multiple bAssets \\*/\\nstruct ForgePropsMulti {\\n bool isValid; // Flag to signify that forge bAssets have passed validity check\\n Basset[] bAssets;\\n address[] integrators;\\n uint8[] indexes;\\n}\\n```\\n |
BassetStatus enum defines multiple unused states Won't Fix | low | The `BassetStatus` enum defines several values that do not seem to be assigned in the code:\\nDefault (different from “Normal”?)\\nBlacklisted\\nLiquidating\\nLiquidated\\nFailed\\n```\\n/\\*\\* @dev Status of the Basset - has it broken its peg? \\*/\\nenum BassetStatus {\\n Default,\\n Normal,\\n BrokenBelowPeg,\\n BrokenAbovePeg,\\n Blacklisted,\\n Liquidating,\\n Liquidated,\\n Failed\\n}\\n```\\n\\nSince some of these are used in the code there might be some dead code that can be removed as a result. For example:\\n```\\n\\_bAsset.status == BassetStatus.Liquidating ||\\n\\_bAsset.status == BassetStatus.Blacklisted\\n```\\n | If those values are indeed never used please consider removing them to simplify the code. | null | ```\\n/\\*\\* @dev Status of the Basset - has it broken its peg? \\*/\\nenum BassetStatus {\\n Default,\\n Normal,\\n BrokenBelowPeg,\\n BrokenAbovePeg,\\n Blacklisted,\\n Liquidating,\\n Liquidated,\\n Failed\\n}\\n```\\n |
Potential gas savings by terminating early Acknowledged | low | If a function invocation is bound to revert, one should try to revert as soon as possible to save gas. In `ForgeValidator.validateRedemption` it is possible to terminate more early:\\n```\\nif(atLeastOneBecameOverweight) return (false, "bAssets must remain below max weight", false);\\n```\\n | Consider moving the require-statement a few lines up (for instance, after assigning to atLeastOneBecameOverweight). | null | ```\\nif(atLeastOneBecameOverweight) return (false, "bAssets must remain below max weight", false);\\n```\\n |
Discrepancy between code and comments | low | There is a discrepancy between the code at:\\n```\\nrequire(weightSum >= 1e18 && weightSum <= 4e18, "Basket weight must be >= 100 && <= 400%");\\n```\\n\\nAnd the comment at:\\n```\\n\\* @dev Throws if the total Basket weight does not sum to 100\\n```\\n | Update the code or the comment to be consistent. | null | ```\\nrequire(weightSum >= 1e18 && weightSum <= 4e18, "Basket weight must be >= 100 && <= 400%");\\n```\\n |
Loss of the liquidity pool is not equally distributed | high | All stakeholders in the liquidity pool should be able to withdraw the same amount as they staked plus a share of fees that the converter earned during their staking period.\\n```\\n IPoolTokensContainer(anchor).burn(\\_poolToken, msg.sender, \\_amount);\\n\\n // calculate how much liquidity to remove\\n // if the entire supply is liquidated, the entire staked amount should be sent, otherwise\\n // the price is based on the ratio between the pool token supply and the staked balance\\n uint256 reserveAmount = 0;\\n if (\\_amount == initialPoolSupply)\\n reserveAmount = balance;\\n else\\n reserveAmount = \\_amount.mul(balance).div(initialPoolSupply);\\n\\n // sync the reserve balance / staked balance\\n reserves[reserveToken].balance = reserves[reserveToken].balance.sub(reserveAmount);\\n uint256 newStakedBalance = stakedBalances[reserveToken].sub(reserveAmount);\\n stakedBalances[reserveToken] = newStakedBalance;\\n```\\n\\nThe problem is that sometimes there might not be enough funds in reserve (for example, due to this issue https://github.com/ConsenSys/bancor-audit-2020-06/issues/4). So the first ones who withdraw their stakes receive all the tokens they own. But the last stakeholders might not be able to get their funds back because the pool is empty already.\\nSo under some circumstances, there is a chance that users can lose all of their staked funds.\\nThis issue also has the opposite side: if the liquidity pool makes an extra profit, the stakers do not owe this profit and cannot withdraw it. | Resolution\\nThe issue was addressed by adding a new fee mechanism called ‘adjusted fees'. This mechanism aims to decrease the deficit of the reserves over time. If there is a deficit of reserves, it is usually present on the secondary token side, because there is a strong incentive to bring the primary token to the balanced state. Roughly speaking, the idea is that if the secondary token has a deficit in reserves, there are additional fees for trading that token. These fees are not distributed across the liquidity providers like the regular fees. Instead, they are just populating the reserve, decreasing the existing deficit.\\nLoss is still not distributed across the liquidity providers, and there is a possibility that there are not enough funds for everyone to withdraw them. In the case of a run on reserves, LPs will be able to withdraw funds on a first-come-first-serve basis.\\nDistribute losses evenly across the liquidity providers. | null | ```\\n IPoolTokensContainer(anchor).burn(\\_poolToken, msg.sender, \\_amount);\\n\\n // calculate how much liquidity to remove\\n // if the entire supply is liquidated, the entire staked amount should be sent, otherwise\\n // the price is based on the ratio between the pool token supply and the staked balance\\n uint256 reserveAmount = 0;\\n if (\\_amount == initialPoolSupply)\\n reserveAmount = balance;\\n else\\n reserveAmount = \\_amount.mul(balance).div(initialPoolSupply);\\n\\n // sync the reserve balance / staked balance\\n reserves[reserveToken].balance = reserves[reserveToken].balance.sub(reserveAmount);\\n uint256 newStakedBalance = stakedBalances[reserveToken].sub(reserveAmount);\\n stakedBalances[reserveToken] = newStakedBalance;\\n```\\n |
Use of external calls with a fixed amount of gas Won't Fix | medium | The converter smart contract uses the Solidity transfer() function to transfer Ether.\\n.transfer() and .send() forward exactly 2,300 gas to the recipient. The goal of this hardcoded gas stipend was to prevent reentrancy vulnerabilities, but this only makes sense under the assumption that gas costs are constant. Recently EIP 1884 was included in the Istanbul hard fork. One of the changes included in EIP 1884 is an increase to the gas cost of the SLOAD operation, causing a contract's fallback function to cost more than 2300 gas.\\n```\\n\\_to.transfer(address(this).balance);\\n```\\n\\n```\\nif (\\_targetToken == ETH\\_RESERVE\\_ADDRESS)\\n```\\n\\n```\\nmsg.sender.transfer(reserveAmount);\\n```\\n | Resolution\\nIt was decided to accept this minor risk as the usage of .call() might introduce other unexpected behavior.\\nIt's recommended to stop using .transfer() and .send() and instead use .call(). Note that .call() does nothing to mitigate reentrancy attacks, so other precautions must be taken. To prevent reentrancy attacks, it is recommended that you use the checks-effects-interactions pattern. | null | ```\\n\\_to.transfer(address(this).balance);\\n```\\n |
Use of assert statement for input validation | low | Solidity assertion should only be used to assert invariants, i.e. statements that are expected to always hold if the code behaves correctly. Note that all available gas is consumed when an assert-style exception occurs.\\nIt appears that assert() is used in one location within the test scope to catch invalid user inputs:\\n```\\nassert(amount < targetReserveBalance);\\n```\\n | Using `require()` instead of `assert()`. | null | ```\\nassert(amount < targetReserveBalance);\\n```\\n |
Certain functions lack input validation routines | high | The functions should first check if the passed arguments are valid first. The checks-effects-interactions pattern should be implemented throughout the code.\\nThese checks should include, but not be limited to:\\n`uint` should be larger than `0` when `0` is considered invalid\\n`uint` should be within constraints\\n`int` should be positive in some cases\\nlength of arrays should match if more arrays are sent as arguments\\naddresses should not be `0x0`\\nThe function `includeAsset` does not do any checks before changing the contract state.\\n```\\nfunction includeAsset (address \\_numeraire, address \\_nAssim, address \\_reserve, address \\_rAssim, uint256 \\_weight) public onlyOwner {\\n shell.includeAsset(\\_numeraire, \\_nAssim, \\_reserve, \\_rAssim, \\_weight);\\n}\\n```\\n\\nThe internal function called by the public method `includeAsset` again doesn't check any of the data.\\n```\\nfunction includeAsset (Shells.Shell storage shell, address \\_numeraire, address \\_numeraireAssim, address \\_reserve, address \\_reserveAssim, uint256 \\_weight) internal {\\n\\n Assimilators.Assimilator storage \\_numeraireAssimilator = shell.assimilators[\\_numeraire];\\n\\n \\_numeraireAssimilator.addr = \\_numeraireAssim;\\n\\n \\_numeraireAssimilator.ix = uint8(shell.numeraires.length);\\n\\n shell.numeraires.push(\\_numeraireAssimilator);\\n\\n Assimilators.Assimilator storage \\_reserveAssimilator = shell.assimilators[\\_reserve];\\n\\n \\_reserveAssimilator.addr = \\_reserveAssim;\\n\\n \\_reserveAssimilator.ix = uint8(shell.reserves.length);\\n\\n shell.reserves.push(\\_reserveAssimilator);\\n\\n shell.weights.push(\\_weight.divu(1e18).add(uint256(1).divu(1e18)));\\n\\n}\\n```\\n\\nSimilar with `includeAssimilator`.\\n```\\nfunction includeAssimilator (address \\_numeraire, address \\_derivative, address \\_assimilator) public onlyOwner {\\n shell.includeAssimilator(\\_numeraire, \\_derivative, \\_assimilator);\\n}\\n```\\n\\nAgain no checks are done in any function.\\n```\\nfunction includeAssimilator (Shells.Shell storage shell, address \\_numeraire, address \\_derivative, address \\_assimilator) internal {\\n\\n Assimilators.Assimilator storage \\_numeraireAssim = shell.assimilators[\\_numeraire];\\n\\n shell.assimilators[\\_derivative] = Assimilators.Assimilator(\\_assimilator, \\_numeraireAssim.ix);\\n // shell.assimilators[\\_derivative] = Assimilators.Assimilator(\\_assimilator, \\_numeraireAssim.ix, 0, 0);\\n\\n}\\n```\\n\\nNot only does the administrator functions not have any checks, but also user facing functions do not check the arguments.\\nFor example `swapByOrigin` does not check any of the arguments if you consider it calls `MainnetDaiToDaiAssimilator`.\\n```\\nfunction swapByOrigin (address \\_o, address \\_t, uint256 \\_oAmt, uint256 \\_mTAmt, uint256 \\_dline) public notFrozen returns (uint256 tAmt\\_) {\\n\\n return transferByOrigin(\\_o, \\_t, \\_dline, \\_mTAmt, \\_oAmt, msg.sender);\\n\\n}\\n```\\n\\nIt calls `transferByOrigin` and we simplify this example and consider we have `_o.ix == _t.ix`\\n```\\nfunction transferByOrigin (address \\_origin, address \\_target, uint256 \\_dline, uint256 \\_mTAmt, uint256 \\_oAmt, address \\_rcpnt) public notFrozen nonReentrant returns (uint256 tAmt\\_) {\\n\\n Assimilators.Assimilator memory \\_o = shell.assimilators[\\_origin];\\n Assimilators.Assimilator memory \\_t = shell.assimilators[\\_target];\\n\\n // TODO: how to include min target amount\\n if (\\_o.ix == \\_t.ix) return \\_t.addr.outputNumeraire(\\_rcpnt, \\_o.addr.intakeRaw(\\_oAmt));\\n```\\n\\nIn which case it can call 2 functions on an assimilatior such as `MainnetDaiToDaiAssimilator`.\\nThe first called function is `intakeRaw`.\\n```\\n// transfers raw amonut of dai in, wraps it in cDai, returns numeraire amount\\nfunction intakeRaw (uint256 \\_amount) public returns (int128 amount\\_, int128 balance\\_) {\\n\\n dai.transferFrom(msg.sender, address(this), \\_amount);\\n\\n amount\\_ = \\_amount.divu(1e18);\\n\\n}\\n```\\n\\nAnd its result is used in `outputNumeraire` that again does not have any checks.\\n```\\n// takes numeraire amount of dai, unwraps corresponding amount of cDai, transfers that out, returns numeraire amount\\nfunction outputNumeraire (address \\_dst, int128 \\_amount) public returns (uint256 amount\\_) {\\n\\n amount\\_ = \\_amount.mulu(1e18);\\n\\n dai.transfer(\\_dst, amount\\_);\\n\\n return amount\\_;\\n\\n}\\n```\\n | Resolution\\nComment from the development team:\\nNow all functions in the Orchestrator revert on incorrect arguments.\\nAll functions in Loihi in general revert on incorrect arguments.\\nImplement the `checks-effects-interactions` as a pattern to write code. Add tests that check if all of the arguments have been validated.\\nConsider checking arguments as an important part of writing code and developing the system. | null | ```\\nfunction includeAsset (address \\_numeraire, address \\_nAssim, address \\_reserve, address \\_rAssim, uint256 \\_weight) public onlyOwner {\\n shell.includeAsset(\\_numeraire, \\_nAssim, \\_reserve, \\_rAssim, \\_weight);\\n}\\n```\\n |
Remove Loihi methods that can be used as backdoors by the administrator | high | There are several functions in `Loihi` that give extreme powers to the shell administrator. The most dangerous set of those is the ones granting the capability to add assimilators.\\nSince assimilators are essentially a proxy architecture to delegate code to several different implementations of the same interface, the administrator could, intentionally or unintentionally, deploy malicious or faulty code in the implementation of an assimilator. This means that the administrator is essentially totally trusted to not run code that, for example, drains the whole pool or locks up the users' and LPs' tokens.\\nIn addition to these, the function `safeApprove` allows the administrator to move any of the tokens the contract holds to any address regardless of the balances any of the users have.\\nThis can also be used by the owner as a backdoor to completely drain the contract.\\n```\\nfunction safeApprove(address \\_token, address \\_spender, uint256 \\_value) public onlyOwner {\\n\\n (bool success, bytes memory returndata) = \\_token.call(abi.encodeWithSignature("approve(address,uint256)", \\_spender, \\_value));\\n\\n require(success, "SafeERC20: low-level call failed");\\n\\n}\\n```\\n | Remove the `safeApprove` function and, instead, use a trustless escape-hatch mechanism like the one suggested in issue 6.1.\\nFor the assimilator addition functions, our recommendation is that they are made completely internal, only callable in the constructor, at deploy time.\\nEven though this is not a big structural change (in fact, it reduces the attack surface), it is, indeed, a feature loss. However, this is the only way to make each shell a time-invariant system.\\nThis would not only increase Shell's security but also would greatly improve the trust the users have in the protocol since, after deployment, the code is now static and auditable. | null | ```\\nfunction safeApprove(address \\_token, address \\_spender, uint256 \\_value) public onlyOwner {\\n\\n (bool success, bytes memory returndata) = \\_token.call(abi.encodeWithSignature("approve(address,uint256)", \\_spender, \\_value));\\n\\n require(success, "SafeERC20: low-level call failed");\\n\\n}\\n```\\n |
Assimilators should implement an interface | high | The Assimilators are one of the core components within the application. They are used to move the tokens and can be thought of as a “middleware” between the Shell Protocol application and any other supported tokens.\\nThe methods attached to the assimilators are called throughout the application and they are a critical component of the whole system. Because of this fact, it is extremely important that they behave correctly.\\nA suggestion to restrict the possibility of errors when implementing them and when using them is to make all of the assimilators implement a unique specific interface. This way, any deviation would be immediately observed, right when the compilation happens.\\nConsider this example. The user calls `swapByOrigin`.\\n```\\nfunction swapByOrigin (address \\_o, address \\_t, uint256 \\_oAmt, uint256 \\_mTAmt, uint256 \\_dline) public notFrozen returns (uint256 tAmt\\_) {\\n\\n return transferByOrigin(\\_o, \\_t, \\_dline, \\_mTAmt, \\_oAmt, msg.sender);\\n\\n}\\n```\\n\\nWhich calls `transferByOrigin`. In `transferByOrigin`, if the origin index matches the target index, a different execution branch is activated.\\n```\\nif (\\_o.ix == \\_t.ix) return \\_t.addr.outputNumeraire(\\_rcpnt, \\_o.addr.intakeRaw(\\_oAmt));\\n```\\n\\nIn this case we need the output of `_o.addr.intakeRaw(_oAmt)`.\\nIf we pick a random assimilator and check the implementation, we see the function `intakeRaw` needs to return the transferred amount.\\n```\\n// takes raw cdai amount, transfers it in, calculates corresponding numeraire amount and returns it\\nfunction intakeRaw (uint256 \\_amount) public returns (int128 amount\\_) {\\n\\n bool success = cdai.transferFrom(msg.sender, address(this), \\_amount);\\n\\n if (!success) revert("CDai/transferFrom-failed");\\n\\n uint256 \\_rate = cdai.exchangeRateStored();\\n\\n \\_amount = ( \\_amount \\* \\_rate ) / 1e18;\\n\\n cdai.redeemUnderlying(\\_amount);\\n\\n amount\\_ = \\_amount.divu(1e18);\\n\\n}\\n```\\n\\nHowever, with other implementations, the returns do not match. In the case of `MainnetDaiToDaiAssimilator`, it returns 2 values, which will make the `Loihi` contract work in this case but can misbehave in other cases, or even fail.\\n```\\n// transfers raw amonut of dai in, wraps it in cDai, returns numeraire amount\\nfunction intakeRaw (uint256 \\_amount) public returns (int128 amount\\_, int128 balance\\_) {\\n\\n dai.transferFrom(msg.sender, address(this), \\_amount);\\n\\n amount\\_ = \\_amount.divu(1e18);\\n\\n}\\n```\\n\\nMaking all the assimilators implement one unique interface will enforce the functions to look the same from the outside. | Create a unique interface for the assimilators and make all the contracts implement that interface. | null | ```\\nfunction swapByOrigin (address \\_o, address \\_t, uint256 \\_oAmt, uint256 \\_mTAmt, uint256 \\_dline) public notFrozen returns (uint256 tAmt\\_) {\\n\\n return transferByOrigin(\\_o, \\_t, \\_dline, \\_mTAmt, \\_oAmt, msg.sender);\\n\\n}\\n```\\n |
Assimilators do not conform to the ERC20 specification | medium | The assimilators in the codebase make heavy usage of both the `transfer` and `transferFrom` methods in the ERC20 standard.\\nQuoting the relevant parts of the specification of the standard:\\nTransfers _value amount of tokens to address _to, and MUST fire the Transfer event. The function SHOULD throw if the message caller's account balance does not have enough tokens to spend.\\nThe transferFrom method is used for a withdraw workflow, allowing contracts to transfer tokens on your behalf. This can be used for example to allow a contract to transfer tokens on your behalf and/or to charge fees in sub-currencies. The function SHOULD throw unless the _from account has deliberately authorized the sender of the message via some mechanism.\\nWe can see that, even though it is suggested that ERC20-compliant tokens do `throw` on the lack of authorization from the sender or lack of funds to complete the transfer, the standard does not enforce it.\\nThis means that, in order to make the system both more resilient and future-proof, code in each implementation of current and future assimilators should check for the return value of both `transfer` and `transferFrom` call instead of just relying on the external contract to revert execution.\\nThe extent of this issue is only mitigated by the fact that new assets are only added by the shell administrator and could, therefore, be audited prior to their addition.\\nNon-exhaustive Examples\\n```\\ndai.transferFrom(msg.sender, address(this), \\_amount);\\n```\\n\\n```\\ndai.transfer(\\_dst, \\_amount);\\n```\\n | Add a check for the return boolean of the function.\\nExample:\\n`require(dai.transferFrom(msg.sender, address(this), _amount) == true);` | null | ```\\ndai.transferFrom(msg.sender, address(this), \\_amount);\\n```\\n |
Access to assimilators does not check for existence and allows delegation to the zeroth address | medium | For every method that allows to selectively withdraw, deposit, or swap tokens in `Loihi`, the user is allowed to specify addresses for the assimilators of said tokens (by inputting the addresses of the tokens themselves).\\nThe shell then performs a lookup on a mapping called `assimilators` inside its main structure and uses the result of that lookup to delegate call the assimilator deployed by the shell administrator.\\nHowever, there are no checks for prior instantiation of a specific, supported token, effectively meaning that we can do a lookup on an all-zeroed-out member of that mapping and delegate call execution to the zeroth address.\\nFor example, the 32 bytes expected as a result of this call:\\n```\\nfunction viewNumeraireAmount (address \\_assim, uint256 \\_amt) internal returns (int128 amt\\_) {\\n\\n // amount\\_ = IAssimilator(\\_assim).viewNumeraireAmount(\\_amt); // for production\\n\\n bytes memory data = abi.encodeWithSelector(iAsmltr.viewNumeraireAmount.selector, \\_amt); // for development\\n\\n amt\\_ = abi.decode(\\_assim.delegate(data), (int128)); // for development\\n\\n}\\n```\\n\\nThis is definitely an insufficient check since the interface for the assimilators might change in the future to include functions that have no return values. | Check for the prior instantiation of assimilators by including the following requirement:\\n`require(shell.assimilators[<TOKEN_ADDRESS>].ix != 0);`\\nIn all the functions that access the `assimilators` mapping and change the indexes to be 1-based instead pf 0-based. | null | ```\\nfunction viewNumeraireAmount (address \\_assim, uint256 \\_amt) internal returns (int128 amt\\_) {\\n\\n // amount\\_ = IAssimilator(\\_assim).viewNumeraireAmount(\\_amt); // for production\\n\\n bytes memory data = abi.encodeWithSelector(iAsmltr.viewNumeraireAmount.selector, \\_amt); // for development\\n\\n amt\\_ = abi.decode(\\_assim.delegate(data), (int128)); // for development\\n\\n}\\n```\\n |
Math library's fork has problematic changes | medium | The math library ABDK Libraries for Solidity was forked and modified to add a few `unsafe_*` functions.\\n`unsafe_add`\\n`unsafe_sub`\\n`unsafe_mul`\\n`unsafe_div`\\n`unsafe_abs`\\nThe problem which was introduced is that `unsafe_add` ironically is not really unsafe, it is as safe as the original `add` function. It is, in fact, identical to the safe `add` function.\\n```\\n/\\*\\*\\n \\* Calculate x + y. Revert on overflow.\\n \\*\\n \\* @param x signed 64.64-bit fixed point number\\n \\* @param y signed 64.64-bit fixed point number\\n \\* @return signed 64.64-bit fixed point number\\n \\*/\\nfunction add (int128 x, int128 y) internal pure returns (int128) {\\n int256 result = int256(x) + y;\\n require (result >= MIN\\_64x64 && result <= MAX\\_64x64);\\n return int128 (result);\\n}\\n```\\n\\n```\\n/\\*\\*\\n \\* Calculate x + y. Revert on overflow.\\n \\*\\n \\* @param x signed 64.64-bit fixed point number\\n \\* @param y signed 64.64-bit fixed point number\\n \\* @return signed 64.64-bit fixed point number\\n \\*/\\nfunction unsafe\\_add (int128 x, int128 y) internal pure returns (int128) {\\n int256 result = int256(x) + y;\\n require (result >= MIN\\_64x64 && result <= MAX\\_64x64);\\n return int128 (result);\\n}\\n```\\n\\nFortunately, `unsafe_add` is not used anywhere in the code.\\nHowever, `unsafe_abs` was changed from this:\\n```\\n/\\*\\*\\n \\* Calculate |x|. Revert on overflow.\\n \\*\\n \\* @param x signed 64.64-bit fixed point number\\n \\* @return signed 64.64-bit fixed point number\\n \\*/\\nfunction abs (int128 x) internal pure returns (int128) {\\n require (x != MIN\\_64x64);\\n return x < 0 ? -x : x;\\n}\\n```\\n\\nTo this:\\n```\\n/\\*\\*\\n \\* Calculate |x|. Revert on overflow.\\n \\*\\n \\* @param x signed 64.64-bit fixed point number\\n \\* @return signed 64.64-bit fixed point number\\n \\*/\\nfunction unsafe\\_abs (int128 x) internal pure returns (int128) {\\n return x < 0 ? -x : x;\\n}\\n```\\n\\nThe check that was removed, is actually an important check:\\n```\\nrequire (x != MIN\\_64x64);\\n```\\n\\n```\\nint128 private constant MIN\\_64x64 = -0x80000000000000000000000000000000;\\n```\\n\\nThe problem is that for an `int128` variable that is equal to `-0x80000000000000000000000000000000`, there is no absolute value within the constraints of `int128`.\\nStarting from int128 `n` = `-0x80000000000000000000000000000000`, the absolute value should be int128 `abs_n` = -n, however `abs_n` is equal to the initial value of `n`. The final value of `abs_n` is still `-0x80000000000000000000000000000000`. It's still not a positive or zero value. The operation `0 - n` wraps back to the same initial value. | Remove unused `unsafe_*` functions and try to find other ways of doing unsafe math (if it is fundamentally important) without changing existing, trusted, already audited code. | null | ```\\n/\\*\\*\\n \\* Calculate x + y. Revert on overflow.\\n \\*\\n \\* @param x signed 64.64-bit fixed point number\\n \\* @param y signed 64.64-bit fixed point number\\n \\* @return signed 64.64-bit fixed point number\\n \\*/\\nfunction add (int128 x, int128 y) internal pure returns (int128) {\\n int256 result = int256(x) + y;\\n require (result >= MIN\\_64x64 && result <= MAX\\_64x64);\\n return int128 (result);\\n}\\n```\\n |
Use one file for each contract or library | medium | The repository contains a lot of contracts and libraries that are added in the same file as another contract or library.\\nOrganizing the code in this manner makes it hard to navigate, develop and audit. It is a best practice to have each contract or library in its own file. The file also needs to bear the name of the hosted contract or library.\\n```\\nlibrary SafeERC20Arithmetic {\\n```\\n\\n```\\nlibrary Shells {\\n```\\n\\n```\\ncontract ERC20Approve {\\n function approve (address spender, uint256 amount) public returns (bool);\\n}\\n```\\n\\n```\\ncontract Loihi is LoihiRoot {\\n```\\n\\n```\\nlibrary Delegate {\\n```\\n\\n```\\nlibrary Assimilators {\\n```\\n | Split up contracts and libraries in single files. | null | ```\\nlibrary SafeERC20Arithmetic {\\n```\\n |
Remove debugging code from the repository | medium | Throughout the repository, there is source code from the development stage that was used for debugging the functionality and was not removed.\\nThis should not be present in the source code and even if they are used while functionality is developed, they should be removed after the functionality was implemented.\\n```\\nevent log(bytes32);\\nevent log\\_int(bytes32, int256);\\nevent log\\_ints(bytes32, int256[]);\\nevent log\\_uint(bytes32, uint256);\\nevent log\\_uints(bytes32, uint256[]);\\n```\\n\\n```\\nevent log(bytes32);\\nevent log\\_uint(bytes32, uint256);\\nevent log\\_int(bytes32, int256);\\n```\\n\\n```\\nevent log(bytes32);\\nevent log\\_int(bytes32, int128);\\nevent log\\_int(bytes32, int);\\nevent log\\_uint(bytes32, uint);\\nevent log\\_addr(bytes32, address);\\n```\\n\\n```\\nevent log(bytes32);\\n```\\n\\n```\\nevent log(bytes32);\\nevent log\\_int(bytes32, int256);\\nevent log\\_ints(bytes32, int256[]);\\nevent log\\_uint(bytes32, uint256);\\nevent log\\_uints(bytes32, uint256[]);\\n```\\n\\n```\\nevent log\\_int(bytes32, int);\\nevent log\\_ints(bytes32, int128[]);\\nevent log\\_uint(bytes32, uint);\\nevent log\\_uints(bytes32, uint[]);\\nevent log\\_addrs(bytes32, address[]);\\n```\\n\\n```\\nevent log\\_uint(bytes32, uint256);\\nevent log\\_int(bytes32, int256);\\n```\\n\\n```\\nevent log\\_uint(bytes32, uint256);\\n```\\n\\n```\\nshell.testHalts = true;\\n```\\n\\n```\\nfunction setTestHalts (bool \\_testOrNotToTest) public {\\n\\n shell.testHalts = \\_testOrNotToTest;\\n\\n}\\n```\\n\\n```\\nbool testHalts;\\n```\\n | Remove the debug functionality at the end of the development cycle of each functionality. | null | ```\\nevent log(bytes32);\\nevent log\\_int(bytes32, int256);\\nevent log\\_ints(bytes32, int256[]);\\nevent log\\_uint(bytes32, uint256);\\nevent log\\_uints(bytes32, uint256[]);\\n```\\n |
Remove commented out code from the repository | medium | 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.\\nThere is no code that is important enough to be left commented out in a repository. Git branching should take care of having different code versions or diffs should show what was before.\\nIf there is commented out code, this also has to be maintained; it will be out of date if other parts of the system are changed, and the tests will not pick that up.\\nThe main problem is that commented code adds confusion with no real benefit. Code should be code, and comments should be comments.\\nCommented out code should be removed or dealt with in a separate branch that is later included in the master branch.\\n```\\nfunction viewRawAmount (address \\_assim, int128 \\_amt) internal returns (uint256 amount\\_) {\\n\\n // amount\\_ = IAssimilator(\\_assim).viewRawAmount(\\_amt); // for production\\n\\n bytes memory data = abi.encodeWithSelector(iAsmltr.viewRawAmount.selector, \\_amt.abs()); // for development\\n\\n amount\\_ = abi.decode(\\_assim.delegate(data), (uint256)); // for development\\n\\n}\\n```\\n\\n```\\nfunction viewNumeraireAmount (address \\_assim, uint256 \\_amt) internal returns (int128 amt\\_) {\\n\\n // amount\\_ = IAssimilator(\\_assim).viewNumeraireAmount(\\_amt); // for production\\n\\n bytes memory data = abi.encodeWithSelector(iAsmltr.viewNumeraireAmount.selector, \\_amt); // for development\\n\\n amt\\_ = abi.decode(\\_assim.delegate(data), (int128)); // for development\\n\\n}\\n```\\n\\n```\\nfunction viewNumeraireAmount (address \\_assim, uint256 \\_amt) internal returns (int128 amt\\_) {\\n\\n // amount\\_ = IAssimilator(\\_assim).viewNumeraireAmount(\\_amt); // for production\\n\\n bytes memory data = abi.encodeWithSelector(iAsmltr.viewNumeraireAmount.selector, \\_amt); // for development\\n\\n amt\\_ = abi.decode(\\_assim.delegate(data), (int128)); // for development\\n\\n}\\n```\\n\\n```\\nfunction includeAssimilator (Shells.Shell storage shell, address \\_numeraire, address \\_derivative, address \\_assimilator) internal {\\n\\n Assimilators.Assimilator storage \\_numeraireAssim = shell.assimilators[\\_numeraire];\\n\\n shell.assimilators[\\_derivative] = Assimilators.Assimilator(\\_assimilator, \\_numeraireAssim.ix);\\n // shell.assimilators[\\_derivative] = Assimilators.Assimilator(\\_assimilator, \\_numeraireAssim.ix, 0, 0);\\n\\n}\\n```\\n\\n```\\nfunction transfer (address \\_recipient, uint256 \\_amount) public nonReentrant returns (bool) {\\n // return shell.transfer(\\_recipient, \\_amount);\\n}\\n\\nfunction transferFrom (address \\_sender, address \\_recipient, uint256 \\_amount) public nonReentrant returns (bool) {\\n // return shell.transferFrom(\\_sender, \\_recipient, \\_amount);\\n}\\n\\nfunction approve (address \\_spender, uint256 \\_amount) public nonReentrant returns (bool success\\_) {\\n // return shell.approve(\\_spender, \\_amount);\\n}\\n\\nfunction increaseAllowance(address \\_spender, uint256 \\_addedValue) public returns (bool success\\_) {\\n // return shell.increaseAllowance(\\_spender, \\_addedValue);\\n}\\n\\nfunction decreaseAllowance(address \\_spender, uint256 \\_subtractedValue) public returns (bool success\\_) {\\n // return shell.decreaseAllowance(\\_spender, \\_subtractedValue);\\n}\\n\\nfunction balanceOf (address \\_account) public view returns (uint256) {\\n // return shell.balances[\\_account];\\n}\\n```\\n\\n```\\n// function test\\_s1\\_selectiveDeposit\\_noSlippage\\_balanced\\_10DAI\\_10USDC\\_10USDT\\_2p5SUSD\\_NO\\_HACK () public logs\\_gas {\\n\\n// uint256 newShells = super.noSlippage\\_balanced\\_10DAI\\_10USDC\\_10USDT\\_2p5SUSD();\\n\\n// assertEq(newShells, 32499999216641686631);\\n\\n// }\\n\\n// function test\\_s1\\_selectiveDeposit\\_noSlippage\\_balanced\\_10DAI\\_10USDC\\_10USDT\\_2p5SUSD\\_HACK () public logs\\_gas {\\n\\n// uint256 newShells = super.noSlippage\\_balanced\\_10DAI\\_10USDC\\_10USDT\\_2p5SUSD\\_HACK();\\n\\n// assertEq(newShells, 32499999216641686631);\\n\\n// }\\n```\\n\\n```\\n// function noSlippage\\_balanced\\_10DAI\\_10USDC\\_10USDT\\_2p5SUSD\\_HACK () public returns (uint256 shellsMinted\\_) {\\n\\n// uint256 startingShells = l.proportionalDeposit(300e18);\\n\\n// uint256 gas = gasleft();\\n\\n// shellsMinted\\_ = l.depositHack(\\n// address(dai), 10e18,\\n// address(usdc), 10e6,\\n// address(usdt), 10e6,\\n// address(susd), 2.5e18\\n// );\\n\\n// emit log\\_uint("gas for deposit", gas - gasleft());\\n\\n\\n// }\\n```\\n | Remove all the commented out code or transform it into comments. | null | ```\\nfunction viewRawAmount (address \\_assim, int128 \\_amt) internal returns (uint256 amount\\_) {\\n\\n // amount\\_ = IAssimilator(\\_assim).viewRawAmount(\\_amt); // for production\\n\\n bytes memory data = abi.encodeWithSelector(iAsmltr.viewRawAmount.selector, \\_amt.abs()); // for development\\n\\n amount\\_ = abi.decode(\\_assim.delegate(data), (uint256)); // for development\\n\\n}\\n```\\n |
Should check if the asset already exists when adding a new asset | medium | The public function `includeAsset`\\n```\\nfunction includeAsset (address \\_numeraire, address \\_nAssim, address \\_reserve, address \\_rAssim, uint256 \\_weight) public onlyOwner {\\n shell.includeAsset(\\_numeraire, \\_nAssim, \\_reserve, \\_rAssim, \\_weight);\\n}\\n```\\n\\nCalls the internal `includeAsset` implementation\\n```\\nfunction includeAsset (Shells.Shell storage shell, address \\_numeraire, address \\_numeraireAssim, address \\_reserve, address \\_reserveAssim, uint256 \\_weight) internal {\\n```\\n\\nBut there is no check to see if the asset already exists in the list. Because the check was not done, `shell.numeraires` can contain multiple identical instances.\\n```\\nshell.numeraires.push(\\_numeraireAssimilator);\\n```\\n | Check if the `_numeraire` already exists before invoking `includeAsset`. | null | ```\\nfunction includeAsset (address \\_numeraire, address \\_nAssim, address \\_reserve, address \\_rAssim, uint256 \\_weight) public onlyOwner {\\n shell.includeAsset(\\_numeraire, \\_nAssim, \\_reserve, \\_rAssim, \\_weight);\\n}\\n```\\n |
Check return values for both internal and external calls | low | There are some cases where functions which return values are called throughout the source code but the return values are not processed, nor checked.\\nThe returns should in principle be handled and checked for validity to provide more robustness to the code.\\nThe function `intakeNumeraire` receives a number of tokens and returns how many tokens were transferred to the contract.\\n```\\n// transfers numeraire amount of dai in, wraps it in cDai, returns raw amount\\nfunction intakeNumeraire (int128 \\_amount) public returns (uint256 amount\\_) {\\n\\n // truncate stray decimals caused by conversion\\n amount\\_ = \\_amount.mulu(1e18) / 1e3 \\* 1e3;\\n\\n dai.transferFrom(msg.sender, address(this), amount\\_);\\n\\n}\\n```\\n\\nSimilarly, the function `outputNumeraire` receives a destination address and an amount of token for withdrawal and returns a number of transferred tokens to the specified address.\\n```\\n// takes numeraire amount of dai, unwraps corresponding amount of cDai, transfers that out, returns numeraire amount\\nfunction outputNumeraire (address \\_dst, int128 \\_amount) public returns (uint256 amount\\_) {\\n\\n amount\\_ = \\_amount.mulu(1e18);\\n\\n dai.transfer(\\_dst, amount\\_);\\n\\n return amount\\_;\\n\\n}\\n```\\n\\nHowever, the results are not handled in the main contract.\\n```\\nshell.numeraires[i].addr.intakeNumeraire(\\_shells.mul(shell.weights[i]));\\n```\\n\\n```\\nshell.numeraires[i].addr.intakeNumeraire(\\_oBals[i].mul(\\_multiplier));\\n```\\n\\n```\\nshell.reserves[i].addr.outputNumeraire(msg.sender, \\_oBals[i].mul(\\_multiplier));\\n```\\n\\nA sanity check can be done to make sure that more than 0 tokens were transferred to the contract.\\n```\\nunit intakeAmount = shell.numeraires[i].addr.intakeNumeraire(\\_shells.mul(shell.weights[i]));\\nrequire(intakeAmount > 0, "Must intake a positive number of tokens");\\n```\\n | Handle all return values everywhere returns exist and add checks to make sure an expected value was returned.\\nIf the return values are never used, consider not returning them at all. | null | ```\\n// transfers numeraire amount of dai in, wraps it in cDai, returns raw amount\\nfunction intakeNumeraire (int128 \\_amount) public returns (uint256 amount\\_) {\\n\\n // truncate stray decimals caused by conversion\\n amount\\_ = \\_amount.mulu(1e18) / 1e3 \\* 1e3;\\n\\n dai.transferFrom(msg.sender, address(this), amount\\_);\\n\\n}\\n```\\n |
Interfaces do not need to be implemented for the compiler to access their selectors. | low | ```\\nIAssimilator constant iAsmltr = IAssimilator(address(0));\\n```\\n\\nThis pattern is unneeded since you can reference selectors by using the imported interface directly without any implementation. It hinders both gas costs and readability of the code. | ```\\nbytes memory data = abi.encodeWithSelector(iAsmltr.viewNumeraireAmount.selector, \\_amt); // for development\\n```\\n\\nuse the expression:\\n`IAssimilator.viewRawAmount.selector` | null | ```\\nIAssimilator constant iAsmltr = IAssimilator(address(0));\\n```\\n |
Use consistent interfaces for functions in the same group | low | This library has 2 functions.\\n`add` which receives 2 arguments, `x` and `y`.\\n```\\nfunction add(uint x, uint y) internal pure returns (uint z) {\\n require((z = x + y) >= x, "add-overflow");\\n}\\n```\\n\\n`sub` which receives 3 arguments `x`, `y` and `_errorMessage`.\\n```\\nfunction sub(uint x, uint y, string memory \\_errorMessage) internal pure returns (uint z) {\\n require((z = x - y) <= x, \\_errorMessage);\\n}\\n```\\n\\nIn order to reduce the cognitive load on the auditors and developers alike, somehow-related functions should have coherent logic and interfaces. Both of the functions either need to have 2 arguments, with an implied error message passed to `require`, or both functions need to have 3 arguments, with an error message that can be specified. | Update the functions to be coherent with other related functions. | null | ```\\nfunction add(uint x, uint y) internal pure returns (uint z) {\\n require((z = x + y) >= x, "add-overflow");\\n}\\n```\\n |
Consider emitting an event when changing the frozen state of the contract | low | The function `freeze` allows the owner to `freeze` and unfreeze the contract.\\n```\\nfunction freeze (bool \\_freeze) public onlyOwner {\\n frozen = \\_freeze;\\n}\\n```\\n\\nThe common pattern when doing actions important for the outside of the blockchain is to emit an event when the action is successful.\\nIt's probably a good idea to emit an event stating the contract was frozen or unfrozen. | Create an event that displays the current state of the contract.\\n```\\nevent Frozen(bool frozen);\\n```\\n\\nAnd emit the event when `frozen` is called.\\n```\\nfunction freeze (bool \\_freeze) public onlyOwner {\\n frozen = \\_freeze;\\n emit Frozen(\\_freeze);\\n}\\n```\\n | null | ```\\nfunction freeze (bool \\_freeze) public onlyOwner {\\n frozen = \\_freeze;\\n}\\n```\\n |
Function supportsInterface can be restricted to pure | low | The function `supportsInterface` returns a `bool` stating that the contract supports one of the defined interfaces.\\n```\\nfunction supportsInterface (bytes4 interfaceID) public returns (bool) {\\n return interfaceID == ERC20ID || interfaceID == ERC165ID;\\n}\\n```\\n\\nThe function does not access or change the state of the contract, this is why it can be restricted to `pure`. | Restrict the function definition to `pure`.\\n```\\nfunction supportsInterface (bytes4 interfaceID) public pure returns (bool) {\\n```\\n | null | ```\\nfunction supportsInterface (bytes4 interfaceID) public returns (bool) {\\n return interfaceID == ERC20ID || interfaceID == ERC165ID;\\n}\\n```\\n |
Use more consistent function naming (includeAssimilator / excludeAdapter) | low | The function `includeAssimilator` adds a new assimilator to the list\\n```\\nshell.assimilators[\\_derivative] = Assimilators.Assimilator(\\_assimilator, \\_numeraireAssim.ix);\\n```\\n\\nThe function `excludeAdapter` removes the specified assimilator from the list\\n```\\ndelete shell.assimilators[\\_assimilator];\\n```\\n | Consider renaming the function `excludeAdapter` to `removeAssimilator` and moving the logic of adding and removing in the same source file. | null | ```\\nshell.assimilators[\\_derivative] = Assimilators.Assimilator(\\_assimilator, \\_numeraireAssim.ix);\\n```\\n |
Eliminate assembly code by using ABI decode | high | There are several locations where assembly code is used to access and decode byte arrays (including uses inside loops). Even though assembly code was used for gas optimization, it reduces the readability (and future updatability) of the code.\\n```\\nassembly {\\n flag := mload(add(\\_data, 32))\\n}\\nif (flag == CHANGE\\_PARTITION\\_FLAG) {\\n assembly {\\n toPartition := mload(add(\\_data, 64))\\n```\\n\\n```\\nassembly {\\n toPartition := mload(add(\\_data, 64))\\n```\\n\\n```\\nfor (uint256 i = 116; i <= \\_operatorData.length; i = i + 32) {\\n bytes32 temp;\\n assembly {\\n temp := mload(add(\\_operatorData, i))\\n }\\n proof[index] = temp;\\n index++;\\n}\\n```\\n | As discussed in the mid-audit meeting, it is a good solution to use ABI decode since all uses of assembly simply access 32-byte chunks of data from user input. This should eliminate all assembly code and make the code significantly more clean. In addition, it might allow for more compact encoding in some cases (for instance, by eliminating or reducing the size of the flags).\\nThis suggestion can be also applied to Merkle Root verifications/calculation code, which can reduce the for loops and complexity of these functions. | null | ```\\nassembly {\\n flag := mload(add(\\_data, 32))\\n}\\nif (flag == CHANGE\\_PARTITION\\_FLAG) {\\n assembly {\\n toPartition := mload(add(\\_data, 64))\\n```\\n |
Ignored return value for transferFrom call | high | When burning swap tokens the return value of the `transferFrom` call is ignored. Depending on the token's implementation this could allow an attacker to mint an arbitrary amount of Amp tokens.\\nNote that the severity of this issue could have been Critical if Flexa token was any arbitrarily tokens. We quickly verified that Flexa token implementation would revert if the amount exceeds the allowance, however it might not be the case for other token implementations.\\n```\\nswapToken.transferFrom(\\_from, swapTokenGraveyard, amount);\\n```\\n | The code should be changed like this:\\n```\\nrequire(swapToken.transferFrom(_from, swapTokenGraveyard, amount));\\n```\\n | null | ```\\nswapToken.transferFrom(\\_from, swapTokenGraveyard, amount);\\n```\\n |
Potentially insufficient validation for operator transfers | medium | For operator transfers, the current validation does not require the sender to be an operator (as long as the transferred value does not exceed the allowance):\\n```\\nrequire(\\n \\_isOperatorForPartition(\\_partition, msg.sender, \\_from) ||\\n (\\_value <= \\_allowedByPartition[\\_partition][\\_from][msg.sender]),\\n EC\\_53\\_INSUFFICIENT\\_ALLOWANCE\\n);\\n```\\n\\nIt is unclear if this is the intention `or` whether the logical `or` should be a logical `and`. | Resolution\\nremoving `operatorTransferByPartition` and simplifying the interfaces to only `tranferByPartition`\\nThis removes the existing tranferByPartition, converting operatorTransferByPartition to it. The reason for this is to make the client interface simpler, where there is one method to transfer by partition, and that method can be called by either a sender wanting to transfer from their own address, or an operator wanting to transfer from a different token holder address. We found that it was redundant to have multiple methods, and the client convenience wasn't worth the confusion.\\nConfirm that the code matches the intention. If so, consider documenting the behavior (for instance, by changing the name of function `operatorTransferByPartition`. | null | ```\\nrequire(\\n \\_isOperatorForPartition(\\_partition, msg.sender, \\_from) ||\\n (\\_value <= \\_allowedByPartition[\\_partition][\\_from][msg.sender]),\\n EC\\_53\\_INSUFFICIENT\\_ALLOWANCE\\n);\\n```\\n |
Potentially missing nonce check Acknowledged | medium | When executing withdrawals in the collateral manager the per-address withdrawal nonce is simply updated without checking that the new nonce is one greater than the previous one (see Examples). It seems like without such a check it might be easy to make mistakes and causing issues with ordering of withdrawals.\\n```\\naddressToWithdrawalNonce[\\_partition][supplier] = withdrawalRootNonce;\\n```\\n\\n```\\naddressToWithdrawalNonce[\\_partition][supplier] = maxWithdrawalRootNonce;\\n```\\n\\n```\\nmaxWithdrawalRootNonce = \\_nonce;\\n```\\n | Consider adding more validation and sanity checks for nonces on per-address withdrawals. | null | ```\\naddressToWithdrawalNonce[\\_partition][supplier] = withdrawalRootNonce;\\n```\\n |
Unbounded loop when validating Merkle proofs | medium | It seems like the loop for validating Merkle proofs is unbounded. If possible it would be good to have an upper bound to prevent DoS-like attacks. It seems like the depth of the tree, and thus, the length of the proof could be bounded.\\nThis could also simplify the decoding and make it more robust. For instance, in `_decodeWithdrawalOperatorData` it is unclear what happens if the data length is not a multiple of 32. It seems like it might result in out-of-bound reads.\\n```\\nuint256 proofNb = (\\_operatorData.length - 84) / 32;\\nbytes32[] memory proof = new bytes32[](proofNb);\\nuint256 index = 0;\\nfor (uint256 i = 116; i <= \\_operatorData.length; i = i + 32) {\\n bytes32 temp;\\n assembly {\\n temp := mload(add(\\_operatorData, i))\\n }\\n proof[index] = temp;\\n index++;\\n}\\n```\\n | Consider enforcing a bound on the length of Merkle proofs.\\nAlso note that if similar mitigation method as issue 5.1 is used, this method can be replaced by a simpler function using ABI Decode, which does not have any unbounded issues as the sizes of the hashes are fixed (or can be indicated in the passed objects) | null | ```\\nuint256 proofNb = (\\_operatorData.length - 84) / 32;\\nbytes32[] memory proof = new bytes32[](proofNb);\\nuint256 index = 0;\\nfor (uint256 i = 116; i <= \\_operatorData.length; i = i + 32) {\\n bytes32 temp;\\n assembly {\\n temp := mload(add(\\_operatorData, i))\\n }\\n proof[index] = temp;\\n index++;\\n}\\n```\\n |
Mitigation for possible reentrancy in token transfers | medium | ERC777 adds significant features to the token implementation, however there are some known risks associated with this token, such as possible reentrancy attack vector. Given that the Amp token uses hooks to communicate to Collateral manager, it seems that the environment is trusted and safe. However, a minor modification to the implementation can result in safer implementation of the token transfer.\\n```\\nrequire(\\n \\_balanceOfByPartition[\\_from][\\_fromPartition] >= \\_value,\\n EC\\_52\\_INSUFFICIENT\\_BALANCE\\n);\\n\\nbytes32 toPartition = \\_fromPartition;\\nif (\\_data.length >= 64) {\\n toPartition = \\_getDestinationPartition(\\_fromPartition, \\_data);\\n}\\n\\n\\_callPreTransferHooks(\\n \\_fromPartition,\\n \\_operator,\\n \\_from,\\n \\_to,\\n \\_value,\\n \\_data,\\n \\_operatorData\\n);\\n\\n\\_removeTokenFromPartition(\\_from, \\_fromPartition, \\_value);\\n\\_transfer(\\_from, \\_to, \\_value);\\n\\_addTokenToPartition(\\_to, toPartition, \\_value);\\n\\n\\_callPostTransferHooks(\\n toPartition,\\n```\\n | It is suggested to move any condition check that is checking the balance to after the external call. However `_callPostTransferHooks` needs to be called after the state changes, so the suggested mitigation here is to move the require at line 1152 to after `_callPreTransferHooks()` function (e.g. line 1171). | null | ```\\nrequire(\\n \\_balanceOfByPartition[\\_from][\\_fromPartition] >= \\_value,\\n EC\\_52\\_INSUFFICIENT\\_BALANCE\\n);\\n\\nbytes32 toPartition = \\_fromPartition;\\nif (\\_data.length >= 64) {\\n toPartition = \\_getDestinationPartition(\\_fromPartition, \\_data);\\n}\\n\\n\\_callPreTransferHooks(\\n \\_fromPartition,\\n \\_operator,\\n \\_from,\\n \\_to,\\n \\_value,\\n \\_data,\\n \\_operatorData\\n);\\n\\n\\_removeTokenFromPartition(\\_from, \\_fromPartition, \\_value);\\n\\_transfer(\\_from, \\_to, \\_value);\\n\\_addTokenToPartition(\\_to, toPartition, \\_value);\\n\\n\\_callPostTransferHooks(\\n toPartition,\\n```\\n |
Potentially inconsistent input validation | medium | There are some functions that might require additional input validation (similar to other functions):\\nAmp.transferWithData: `require(_isOperator(msg.sender, _from), EC_58_INVALID_OPERATOR);` like in\\n```\\nrequire(\\_isOperator(msg.sender, \\_from), EC\\_58\\_INVALID\\_OPERATOR);\\n```\\n\\nAmp.authorizeOperatorByPartition: `require(_operator != msg.sender);` like in\\n```\\nrequire(\\_operator != msg.sender);\\n```\\n\\nAmp.revokeOperatorByPartition: `require(_operator != msg.sender);` like in\\n```\\nrequire(\\_operator != msg.sender);\\n```\\n | Consider adding additional input validation. | null | ```\\nrequire(\\_isOperator(msg.sender, \\_from), EC\\_58\\_INVALID\\_OPERATOR);\\n```\\n |
ERC20 compatibility of Amp token using defaultPartition | medium | It is somewhat unclear how the Amp token ensures ERC20 compatibility. While the `default` partition is used in some places (for instance, in function balanceOf) there are also separate fields for (aggregated) balances/allowances. This seems to introduce some redundancy and raises certain questions about when which fields are relevant.\\n`_allowed` is used in function `allowance` instead of `_allowedByPartition` with the default partition\\nAn `Approval` event should be emitted when approving the default partition\\n```\\nemit ApprovalByPartition(\\_partition, \\_tokenHolder, \\_spender, \\_amount);\\n```\\n\\n`increaseAllowance()` vs. `increaseAllowanceByPartition()` | After the mid-audit discussion, it was clear that the general `balanceOf` method (with no partition) is not needed and can be replaced with a `balanceOf` function that returns balance of the default partition, similarly for allowance, the general `increaseAllowance` function can simply call `increaseAllowanceByPartition` using default partition (same for decreaseAllowance). | null | ```\\nemit ApprovalByPartition(\\_partition, \\_tokenHolder, \\_spender, \\_amount);\\n```\\n |
Additional validation for canReceive | low | For `FlexaCollateralManager.tokensReceived` there is validation to ensure that only the Amp calls the function. In contrast, there is no such validation for `canReceive` and it is unclear if this is the intention.\\n```\\nrequire(msg.sender == amp, "Invalid sender");\\n```\\n | Consider adding a conjunct `msg.sender == amp` in function `_canReceive`.\\n```\\nfunction \\_canReceive(address \\_to, bytes32 \\_destinationPartition) internal view returns (bool) {\\n return \\_to == address(this) && partitions[\\_destinationPartition];\\n}\\n```\\n | null | ```\\nrequire(msg.sender == amp, "Invalid sender");\\n```\\n |
Discrepancy between code and comments | low | There are some discrepancies between (uncommented) code and the documentations comment:\\n```\\n// Indicate token verifies Amp, ERC777 and ERC20 interfaces\\nERC1820Implementer.\\_setInterface(AMP\\_INTERFACE\\_NAME);\\nERC1820Implementer.\\_setInterface(ERC20\\_INTERFACE\\_NAME);\\n// ERC1820Implementer.\\_setInterface(ERC777\\_INTERFACE\\_NAME);\\n```\\n\\n```\\n/\\*\\*\\n \\* @notice Indicates a supply refund was executed\\n \\* @param supplier Address whose refund authorization was executed\\n \\* @param partition Partition from which the tokens were transferred\\n \\* @param amount Amount of tokens transferred\\n \\*/\\nevent SupplyRefund(\\n address indexed supplier,\\n bytes32 indexed partition,\\n uint256 amount,\\n uint256 indexed nonce\\n);\\n```\\n | Consider updating either the code or the comment. | null | ```\\n// Indicate token verifies Amp, ERC777 and ERC20 interfaces\\nERC1820Implementer.\\_setInterface(AMP\\_INTERFACE\\_NAME);\\nERC1820Implementer.\\_setInterface(ERC20\\_INTERFACE\\_NAME);\\n// ERC1820Implementer.\\_setInterface(ERC777\\_INTERFACE\\_NAME);\\n```\\n |
Several fields could potentially be private Acknowledged | low | Several fields in `Amp` could possibly be private:\\nswapToken:\\n```\\nISwapToken public swapToken;\\n```\\n\\nswapTokenGraveyard:\\n```\\naddress public constant swapTokenGraveyard = 0x000000000000000000000000000000000000dEaD;\\n```\\n\\ncollateralManagers:\\n```\\naddress[] public collateralManagers;\\n```\\n\\npartitionStrategies:\\n```\\nbytes4[] public partitionStrategies;\\n```\\n\\nThe same hold for several fields in `FlexaCollateralManager`. For instance:\\npartitions:\\n```\\nmapping(bytes32 => bool) public partitions;\\n```\\n\\nnonceToSupply:\\n```\\nmapping(uint256 => Supply) public nonceToSupply;\\n```\\n\\nwithdrawalRootToNonce:\\n```\\nmapping(bytes32 => uint256) public withdrawalRootToNonce;\\n```\\n | Double-check that you really want to expose those fields. | null | ```\\nISwapToken public swapToken;\\n```\\n |
Several fields could be declared immutable Acknowledged | low | Several fields could be declared immutable to make clear that they never change after construction:\\nAmp._name:\\n```\\nstring internal \\_name;\\n```\\n\\nAmp._symbol:\\n```\\nstring internal \\_symbol;\\n```\\n\\nAmp.swapToken:\\n```\\nISwapToken public swapToken;\\n```\\n\\nFlexaCollateralManager.amp:\\n```\\naddress public amp;\\n```\\n | Use the `immutable` annotation in Solidity (see Immutable). | null | ```\\nstring internal \\_name;\\n```\\n |
A reverting fallback function will lock up all payouts | high | ```\\nfunction \\_transferETH(address \\_recipient, uint256 \\_amount) private {\\n (bool success, ) = \\_recipient.call{value: \\_amount}(\\n abi.encodeWithSignature("")\\n );\\n require(success, "Transfer Failed");\\n}\\n```\\n\\nThe `_payment()` function processes a list of transfers to settle the transactions in an `ExchangeBox`. If any of the recipients of an Eth transfer is a smart contract that reverts, then the entire payout will fail and will be unrecoverable. | Implement a queuing mechanism to allow buyers/sellers to initiate the withdrawal on their own using a ‘pull-over-push pattern.'\\nIgnore a failed transfer and leave the responsibility up to users to receive them properly. | null | ```\\nfunction \\_transferETH(address \\_recipient, uint256 \\_amount) private {\\n (bool success, ) = \\_recipient.call{value: \\_amount}(\\n abi.encodeWithSignature("")\\n );\\n require(success, "Transfer Failed");\\n}\\n```\\n |
Force traders to mint gas token | high | Attack scenario:\\nAlice makes a large trade via the Fairswap_iDOLvsEth exchange. This will tie up her iDOL until the box is executed.\\nMallory makes a small trades to buy ETH immediately afterwards, the trades are routed through an attack contract.\\nAlice needs to execute the box to get her iDOL out.\\nBecause the gas amount is unlimited, when you Mallory's ETH is paid out to her attack contract, mint a lot of GasToken.\\nIf Alice has $100 worth of ETH tied up in the exchange, you can basically ransom her for $99 of gas token or else she'll never see her funds again.\\n```\\nfunction \\_transferETH(address \\_recipient, uint256 \\_amount) private {\\n```\\n | When sending ETH, a pull-payment model is generally preferable.\\nThis would require setting up a queue, allowing users to call a function to initiate a withdrawal. | null | ```\\nfunction \\_transferETH(address \\_recipient, uint256 \\_amount) private {\\n```\\n |
Missing Proper Access Control | high | Some functions do not have proper access control and are `public`, meaning that anyone can call them. This will result in system take over depending on how critical those functionalities are.\\n```\\n \\*/\\nfunction setIDOLContract(address contractAddress) public {\\n require(address(\\_IDOLContract) == address(0), "IDOL contract is already registered");\\n \\_setStableCoinContract(contractAddress);\\n}\\n```\\n | Make the `setIDOLContract()` function `internal` and call it from the constructor, or only allow the `deployer` to set the value. | null | ```\\n \\*/\\nfunction setIDOLContract(address contractAddress) public {\\n require(address(\\_IDOLContract) == address(0), "IDOL contract is already registered");\\n \\_setStableCoinContract(contractAddress);\\n}\\n```\\n |
Code is not production-ready | high | Similar to other discussed issues, several areas of the code suggest that the system is not production-ready. This results in narrow test scenarios that do not cover production code flow.\\nisNotStartedAuction\\ninAcceptingBidsPeriod\\ninRevealingValuationPeriod\\ninReceivingBidsPeriod\\n```\\n/\\*\\n// Indicates any auction has never held for a specified BondID\\nfunction isNotStartedAuction(bytes32 auctionID) public virtual override returns (bool) {\\n uint256 closingTime = \\_auctionClosingTime[auctionID];\\n return closingTime == 0;\\n}\\n\\n// Indicates if the auctionID is in bid acceptance status\\nfunction inAcceptingBidsPeriod(bytes32 auctionID) public virtual override returns (bool) {\\n uint256 closingTime = \\_auctionClosingTime[auctionID];\\n```\\n\\n```\\n// TEST\\nfunction isNotStartedAuction(bytes32 auctionID)\\n public\\n virtual\\n override\\n returns (bool)\\n{\\n return true;\\n}\\n\\n// TEST\\nfunction inAcceptingBidsPeriod(bytes32 auctionID)\\n```\\n\\nThese commented-out functions contain essential functionality for the Auction contract. For example, `inRevealingValuationPeriod` is used to allow revealing of the bid price publicly:\\n```\\nrequire(\\n inRevealingValuationPeriod(auctionID),\\n "it is not the time to reveal the value of bids"\\n);\\n```\\n | Remove the test functions and use the production code for testing. The tests must have full coverage of the production code to be considered complete. | null | ```\\n/\\*\\n// Indicates any auction has never held for a specified BondID\\nfunction isNotStartedAuction(bytes32 auctionID) public virtual override returns (bool) {\\n uint256 closingTime = \\_auctionClosingTime[auctionID];\\n return closingTime == 0;\\n}\\n\\n// Indicates if the auctionID is in bid acceptance status\\nfunction inAcceptingBidsPeriod(bytes32 auctionID) public virtual override returns (bool) {\\n uint256 closingTime = \\_auctionClosingTime[auctionID];\\n```\\n |
Unreachable code due to checked conditions | medium | ```\\nfunction revealBid(\\n bytes32 auctionID,\\n uint256 price,\\n uint256 targetSBTAmount,\\n uint256 random\\n) public override {\\n require(\\n inRevealingValuationPeriod(auctionID),\\n "it is not the time to reveal the value of bids"\\n );\\n```\\n\\nHowever, later in the same function, code exists to introduce “Penalties for revealing too early.” This checks to see if the function was called before closing, which should not be possible given the previous check.\\n```\\n/\\*\\*\\n \\* @dev Penalties for revealing too early.\\n \\* Some participants may not follow the rule and publicate their bid information before the reveal process.\\n \\* In such a case, the bid price is overwritten by the bid with the strike price (slightly unfavored price).\\n \\*/\\nuint256 bidPrice = price;\\n\\n/\\*\\*\\n \\* @dev FOR TEST CODE RUNNING: The following if statement in L533 should be replaced by the comment out\\n \\*/\\nif (inAcceptingBidsPeriod(auctionID)) {\\n // if (false) {\\n (, , uint256 solidStrikePriceE4, ) = \\_getBondFromAuctionID(auctionID);\\n bidPrice = \\_exchangeSBT2IDOL(solidStrikePriceE4.mul(10\\*\\*18));\\n}\\n```\\n | Resolution\\nComment from Lien Protocol:\\nDouble-check the logic in these functions. If revealing should be allowed (but penalized in the earlier stage), the first check should be changed. However, based on our understanding, the first check is correct, and the second check for early reveal is redundant and should be removed. | null | ```\\nfunction revealBid(\\n bytes32 auctionID,\\n uint256 price,\\n uint256 targetSBTAmount,\\n uint256 random\\n) public override {\\n require(\\n inRevealingValuationPeriod(auctionID),\\n "it is not the time to reveal the value of bids"\\n );\\n```\\n |
Fairswap: inconsistent checks on _executionOrder() | low | The `_executionOrder()` function should only be called under specific conditions. However, these conditions are not always consistently defined.\\n```\\nif (nextBoxNumber > 1 && nextBoxNumber > nextExecuteBoxNumber) {\\n```\\n\\n```\\nif (nextBoxNumber > 1 && nextBoxNumber > nextExecuteBoxNumber) {\\n```\\n\\n```\\nif (nextBoxNumber > 1 && nextBoxNumber >= nextExecuteBoxNumber) {\\n```\\n | Resolution\\nComment from Lien Protocol:\\nReduce duplicate code by defining an internal function to perform this check. A clear, descriptive name will help to clarify the intention. | null | ```\\nif (nextBoxNumber > 1 && nextBoxNumber > nextExecuteBoxNumber) {\\n```\\n |
Inconsistency in DecimalSafeMath implementations | low | There are two different implementations of `DecimalSafeMath` in the 3 FairSwap repositories.\\n```\\nlibrary DecimalSafeMath {\\n function decimalDiv(uint256 a, uint256 b)internal pure returns (uint256) {\\n // assert(b > 0); // Solidity automatically throws when dividing by 0\\n uint256 a\\_ = a \\* 1000000000000000000;\\n uint256 c = a\\_ / b;\\n // assert(a == b \\* c + a % b); // There is no case in which this doesn't hold\\n return c;\\n }\\n```\\n\\n```\\nlibrary DecimalSafeMath {\\n\\n function decimalDiv(uint256 a, uint256 b)internal pure returns (uint256) {\\n // assert(b > 0); // Solidity automatically throws when dividing by 0\\n \\n uint256 c = (a \\* 1000000000000000000) / b;\\n // assert(a == b \\* c + a % b); // There is no case in which this doesn't hold\\n return c;\\n }\\n```\\n | Try removing duplicate code/libraries and using a better inheritance model to include one file in all FairSwaps. | null | ```\\nlibrary DecimalSafeMath {\\n function decimalDiv(uint256 a, uint256 b)internal pure returns (uint256) {\\n // assert(b > 0); // Solidity automatically throws when dividing by 0\\n uint256 a\\_ = a \\* 1000000000000000000;\\n uint256 c = a\\_ / b;\\n // assert(a == b \\* c + a % b); // There is no case in which this doesn't hold\\n return c;\\n }\\n```\\n |
Exchange - CancelOrder has no effect Pending | high | The exchange provides means for the `trader` or `broker` to cancel the order. The `cancelOrder` method, however, only stores the hash of the canceled order in mapping but the mapping is never checked. It is therefore effectively impossible for a `trader` to cancel an order.\\n```\\nfunction cancelOrder(LibOrder.Order memory order) public {\\n require(msg.sender == order.trader || msg.sender == order.broker, "invalid caller");\\n\\n bytes32 orderHash = order.getOrderHash();\\n cancelled[orderHash] = true;\\n\\n emit Cancel(orderHash);\\n}\\n```\\n | `matchOrders*` or `validateOrderParam` should check if `cancelled[orderHash] == true` and abort fulfilling the order.\\nVerify the order params (Signature) before accepting it as canceled. | null | ```\\nfunction cancelOrder(LibOrder.Order memory order) public {\\n require(msg.sender == order.trader || msg.sender == order.broker, "invalid caller");\\n\\n bytes32 orderHash = order.getOrderHash();\\n cancelled[orderHash] = true;\\n\\n emit Cancel(orderHash);\\n}\\n```\\n |
Perpetual - withdraw should only be available in NORMAL state Pending | high | According to the specification `withdraw` can only be called in `NORMAL` state. However, the implementation allows it to be called in `NORMAL` and `SETTLED` mode.\\nWithdraw only checks for `!SETTLING` state which resolves to `NORMAL` and `SETTLED`.\\n```\\nfunction withdraw(uint256 amount) public {\\n withdrawFromAccount(msg.sender, amount);\\n}\\n```\\n\\n```\\nfunction withdrawFromAccount(address payable guy, uint256 amount) private {\\n require(guy != address(0), "invalid guy");\\n require(status != LibTypes.Status.SETTLING, "wrong perpetual status");\\n\\n uint256 currentMarkPrice = markPrice();\\n require(isSafeWithPrice(guy, currentMarkPrice), "unsafe before withdraw");\\n remargin(guy, currentMarkPrice);\\n address broker = currentBroker(guy);\\n bool forced = broker == address(amm.perpetualProxy()) || broker == address(0);\\n withdraw(guy, amount, forced);\\n\\n require(isSafeWithPrice(guy, currentMarkPrice), "unsafe after withdraw");\\n require(availableMarginWithPrice(guy, currentMarkPrice) >= 0, "withdraw margin");\\n}\\n```\\n\\nIn contrast, `withdrawFor` requires the state to be NORMAL:\\n```\\nfunction withdrawFor(address payable guy, uint256 amount) public onlyWhitelisted {\\n require(status == LibTypes.Status.NORMAL, "wrong perpetual status");\\n withdrawFromAccount(guy, amount);\\n}\\n```\\n | Resolution\\nThis issue was resolved by requiring `status == LibTypes.Status.NORMAL`.\\n`withdraw` should only be available in the `NORMAL` operation mode. | null | ```\\nfunction withdraw(uint256 amount) public {\\n withdrawFromAccount(msg.sender, amount);\\n}\\n```\\n |
Perpetual - withdrawFromInsuranceFund should check wadAmount instead of rawAmount Pending | high | `withdrawFromInsurance` checks that enough funds are in the insurance fund before allowing withdrawal by an admin by checking the provided `rawAmount` <= insuranceFundBalance.toUint256(). `rawAmount` is the `ETH` (18 digit precision) or collateral token amount (can be less than 18 digit precision) to be withdrawn while `insuranceFundBalance` is a WAD-denominated value (18 digit precision).\\nThe check does not hold if the configured collateral has different precision and may have unwanted consequences, e.g. the withdrawal of more funds than expected.\\nNote: there is another check for `insuranceFundBalance` staying positive after the potential external call to collateral.\\n```\\nfunction withdrawFromInsuranceFund(uint256 rawAmount) public onlyWhitelistAdmin {\\n require(rawAmount > 0, "invalid amount");\\n require(insuranceFundBalance > 0, "insufficient funds");\\n require(rawAmount <= insuranceFundBalance.toUint256(), "insufficient funds");\\n\\n int256 wadAmount = toWad(rawAmount);\\n insuranceFundBalance = insuranceFundBalance.sub(wadAmount);\\n withdrawFromProtocol(msg.sender, rawAmount);\\n\\n require(insuranceFundBalance >= 0, "negtive insurance fund");\\n\\n emit UpdateInsuranceFund(insuranceFundBalance);\\n}\\n```\\n\\nWhen looking at the test-cases there seems to be a misconception about what unit of amount `withdrawFromInsuranceFund` is taking. For example, the insurance fund withdrawal and deposit are not tested for collateral that specifies a precision that is not 18. The test-cases falsely assume that the input to `withdrawFromInsuranceFund` is a WAD value, while it is taking the collateral's `rawAmount` which is then converted to a WAD number.\\ncode/test/test_perpetual.js:L471-L473\\n```\\nawait perpetual.withdrawFromInsuranceFund(toWad(10.111));\\nfund = await perpetual.insuranceFundBalance();\\nassert.equal(fund.toString(), 0);\\n```\\n | Check that `require(wadAmount <= insuranceFundBalance.toUint256(), "insufficient funds");`, add a test-suite testing the insurance fund with collaterals with different precision and update existing tests that properly provide the expected input to `withdraFromInsurance`. | null | ```\\nfunction withdrawFromInsuranceFund(uint256 rawAmount) public onlyWhitelistAdmin {\\n require(rawAmount > 0, "invalid amount");\\n require(insuranceFundBalance > 0, "insufficient funds");\\n require(rawAmount <= insuranceFundBalance.toUint256(), "insufficient funds");\\n\\n int256 wadAmount = toWad(rawAmount);\\n insuranceFundBalance = insuranceFundBalance.sub(wadAmount);\\n withdrawFromProtocol(msg.sender, rawAmount);\\n\\n require(insuranceFundBalance >= 0, "negtive insurance fund");\\n\\n emit UpdateInsuranceFund(insuranceFundBalance);\\n}\\n```\\n |
Perpetual - liquidateFrom should not have public visibility Pending | high | `Perpetual.liquidate` is used to liquidate an account that is “unsafe,” determined by the relative sizes of `marginBalanceWithPrice` and maintenanceMarginWithPrice:\\n```\\n// safe for liquidation\\nfunction isSafeWithPrice(address guy, uint256 currentMarkPrice) public returns (bool) {\\n return\\n marginBalanceWithPrice(guy, currentMarkPrice) >=\\n maintenanceMarginWithPrice(guy, currentMarkPrice).toInt256();\\n}\\n```\\n\\n`Perpetual.liquidate` allows the caller to assume the liquidated account's position, as well as a small amount of “penalty collateral.” The steps to liquidate are, roughly:\\nClose the liquidated account's position\\nPerform a trade on the liquidated assets with the liquidator acting as counter-party\\nGrant the liquidator a portion of the liquidated assets as a reward. An additional portion is added to the insurance fund.\\nHandle any losses\\nWe found several issues in Perpetual.liquidate:\\n`liquidateFrom` has `public` visibility:\\n```\\nfunction liquidateFrom(address from, address guy, uint256 maxAmount) public returns (uint256, uint256) {\\n```\\n\\nGiven that `liquidate` only calls `liquidateFrom` after checking the current contract's status, this oversight allows anyone to call `liquidateFrom` during the `SETTLED` stage:\\n```\\nfunction liquidate(address guy, uint256 maxAmount) public returns (uint256, uint256) {\\n require(status != LibTypes.Status.SETTLED, "wrong perpetual status");\\n return liquidateFrom(msg.sender, guy, maxAmount);\\n}\\n```\\n\\nAdditionally, directly calling `liquidateFrom` allows anyone to liquidate on behalf of other users, forcing other accounts to assume liquidated positions.\\nFinally, neither `liquidate` nor `liquidateFrom` check that the liquidated account and liquidator are the same. Though the liquidation accounting process is hard to follow, we believe this is unintended and could lead to large errors in internal contract accounting. | Make `liquidateFrom` an `internal` function\\nIn `liquidate` or `liquidateFrom`, check that `msg.sender != guy` | null | ```\\n// safe for liquidation\\nfunction isSafeWithPrice(address guy, uint256 currentMarkPrice) public returns (bool) {\\n return\\n marginBalanceWithPrice(guy, currentMarkPrice) >=\\n maintenanceMarginWithPrice(guy, currentMarkPrice).toInt256();\\n}\\n```\\n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.