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
Update to `managerFeeBPS` applied to pending tokens yet to be claimed
medium
A manager (malicious or not) can update the `managerFeeBPS` by calling `ArrakisV2.setManagerFeeBPS()`. The newly-updated `managerFeeBPS` will be retroactively applied to the pending fees yet to be claimed by the `ArrakisV2` contract.\\nWhenever UniV3 fees are collected (via `burn()` or rebalance()), the manager fees are applied to the received pending tokens.\\n```\\nfunction _applyFees(uint256 fee0_, uint256 fee1_) internal {\\n uint16 mManagerFeeBPS = managerFeeBPS;\\n managerBalance0 += (fee0_ * mManagerFeeBPS) / hundredPercent;\\n managerBalance1 += (fee1_ * mManagerFeeBPS) / hundredPercent;\\n}\\n```\\n\\nSince the manager can update the `managerFeeBPS` whenever, this calculation can be altered to take up to 100% of the pending fees in favor of the manager.\\n```\\nfunction setManagerFeeBPS(uint16 managerFeeBPS_) external onlyManager {\\n require(managerFeeBPS_ <= 10000, "MFO");\\n managerFeeBPS = managerFeeBPS_;\\n emit LogSetManagerFeeBPS(managerFeeBPS_);\\n}\\n```\\n
Fees should be collected at the start of execution within the `setManagerFeeBPS()` function. This effectively checkpoints the fees properly, prior to updating the `managerFeeBPS` variable.
Manager's ability to intentionally or accidently steal pending fees owed to stakers
```\\nfunction _applyFees(uint256 fee0_, uint256 fee1_) internal {\\n uint16 mManagerFeeBPS = managerFeeBPS;\\n managerBalance0 += (fee0_ * mManagerFeeBPS) / hundredPercent;\\n managerBalance1 += (fee1_ * mManagerFeeBPS) / hundredPercent;\\n}\\n```\\n
Wrong calculation of `tickCumulatives` due to hardcoded pool fees
high
Wrong calculation of `tickCumulatives` due to hardcoded pool fees\\nReal Wagmi is using a hardcoded `500` fee to calculate the `amountOut` to check for slippage and revert if it was to high, or got less funds back than expected.\\n```\\n IUniswapV3Pool(underlyingTrustedPools[500].poolAddress)\\n```\\n\\nThere are several problems with the hardcoding of the `500` as the fee.\\nNot all tokens have `500` fee pools\\nThe swapping takes place in pools that don't have a `500` fee\\nThe `500` pool fee is not the optimal to fetch the `tickCumulatives` due to low volume\\nSpecially as they are deploying in so many secondary chains like Kava, this will be a big problem pretty much in every transaction over there.\\nIf any of those scenarios is given, `tickCumulatives` will be incorrectly calculated and it will set an incorrect slippage return.
Consider allowing the fees as an input and consider not even picking low TVL pools with no transations
Incorrect slippage calculation will increase the risk of `rebalanceAll()` rebalance getting rekt.
```\\n IUniswapV3Pool(underlyingTrustedPools[500].poolAddress)\\n```\\n
No slippage protection when withdrawing and providing liquidity in rebalanceAll
high
When `rebalanceAll` is called, the liquidity is first withdrawn from the pools and then deposited to new positions. However, there is no slippage protection for these operations.\\nIn the `rebalanceAll` function, it first withdraws all liquidity from the pools and deposits all liquidity to new positions.\\n```\\n _withdraw(_totalSupply, _totalSupply);\\n```\\n\\n```\\n _deposit(reserve0, reserve1, _totalSupply, slots);\\n```\\n\\nHowever, there are no parameters for `amount0Min` and `amount1Min`, which are used to prevent slippage. These parameters should be checked to create slippage protections.\\nActually, they are implemented in the `deposit` and `withdraw` functions, but just not in the rebalanceAll function.
Implement slippage protection in rebalanceAll as suggested to avoid loss to the protocol.
The withdraw and provide liquidity operations in rebalanceAll are exposed to high slippage and could result in a loss for LPs of multipool.
```\\n _withdraw(_totalSupply, _totalSupply);\\n```\\n
Usage of `slot0` is extremely easy to manipulate
high
Usage of `slot0` is extremely easy to manipulate\\nReal Wagmi is using `slot0` to calculate several variables in their codebase:\\nslot0 is the most recent data point and is therefore extremely easy to manipulate.\\nMultipool directly uses the token values returned by `getAmountsForLiquidity`\\n```\\n (uint256 amount0, uint256 amount1) = LiquidityAmounts.getAmountsForLiquidity(\\n slots[i].currentSqrtRatioX96,\\n TickMath.getSqrtRatioAtTick(position.lowerTick),\\n TickMath.getSqrtRatioAtTick(position.upperTick),\\n liquidity\\n );\\n```\\n\\nto calculate the reserves.\\n```\\n reserve0 += amount0;\\n reserve1 += amount1;\\n```\\n
To make any calculation use a TWAP instead of slot0.
Pool lp value can be manipulated and cause other users to receive less lp tokens.
```\\n (uint256 amount0, uint256 amount1) = LiquidityAmounts.getAmountsForLiquidity(\\n slots[i].currentSqrtRatioX96,\\n TickMath.getSqrtRatioAtTick(position.lowerTick),\\n TickMath.getSqrtRatioAtTick(position.upperTick),\\n liquidity\\n );\\n```\\n
The `_estimateWithdrawalLp` function might return a very large value, result in users losing significant incentives or being unable to withdraw from the Dispatcher contract
high
The `_estimateWithdrawalLp` function might return a very large value, result in users losing significant incentives or being unable to withdraw from the Dispatcher contract\\nIn Dispatcher contract, `_estimateWithdrawalLp` function returns the value of shares amount based on the average of ratios `amount0 / reserve0` and `amount1 / reserve1`.\\n```\\nfunction _estimateWithdrawalLp(\\n uint256 reserve0,\\n uint256 reserve1,\\n uint256 _totalSupply,\\n uint256 amount0,\\n uint256 amount1\\n) private pure returns (uint256 shareAmount) {\\n shareAmount =\\n ((amount0 * _totalSupply) / reserve0 + (amount1 * _totalSupply) / reserve1) /\\n 2;\\n}\\n```\\n\\nFrom `Dispatcher.withdraw` and `Dispatcher.deposit` function, amount0 and amount1 will be the accumulated fees of users\\n```\\nuint256 lpAmount;\\n{\\n (uint256 fee0, uint256 fee1) = _calcFees(feesGrow, user);\\n lpAmount = _estimateWithdrawalLp(reserve0, reserve1, _totalSupply, fee0, fee1);\\n}\\nuser.shares -= lpAmount;\\n_withdrawFee(pool, lpAmount, reserve0, reserve1, _totalSupply, deviationBP);\\n```\\n\\nHowever, it is important to note that the values of reserve0 and reserve1 can fluctuate significantly. This is because the positions of the Multipool in UniSwapV3 pools (concentrated) are unstable on-chain, and they can change substantially as the state of the pools changes. As a result, the `_estimateWithdrawalLp` function might return a large value even for a small fee amount. This could potentially lead to reverting due to underflow in the deposit function (in cases where lpAmount > user.shares), or it could result in withdrawing a larger amount of Multipool LP than initially expected.\\nScenario:\\nTotal supply of Multipool is 1e18, and Alice has 1e16 (1%) LP amounts which deposited into Dispatcher contract.\\nAlice accrued fees = 200 USDC and 100 USDT\\nThe reserves of Multipool are 100,000 USDC and 100,000 USDT, `_estimateWithdrawalLp` of Alice fees will be `(0.2% + 0.1%) / 2 * totalSupply` = `0.15% * totalSupply` = 1.5e15 LP amounts\\nHowever, in some cases, UniSwapV3 pools may experience fluctuations, reserves of Multipool are 10,000 USDC and 190,000 USDT, `_estimateWithdrawalLp` of Alice fees will be `(2% + 0.052%) / 2 * totalSupply` = `1.026% * totalSupply` = 1.026e16 LP amounts This result is greater than LP amounts of Alice (1e16), leading to reverting by underflow in deposit/withdraw function of Dispatcher contract.
Shouldn't use the average ratio for calculation in_estimateWithdrawalLp function
Users may face 2 potential issues when interacting with the Dispatcher contract.\\nThey might be unable to deposit/withdraw\\nSecondly, users could potentially lose significant incentives when depositing or withdrawing due to unexpected withdrawals of LP amounts for their fees.
```\\nfunction _estimateWithdrawalLp(\\n uint256 reserve0,\\n uint256 reserve1,\\n uint256 _totalSupply,\\n uint256 amount0,\\n uint256 amount1\\n) private pure returns (uint256 shareAmount) {\\n shareAmount =\\n ((amount0 * _totalSupply) / reserve0 + (amount1 * _totalSupply) / reserve1) /\\n 2;\\n}\\n```\\n
The deposit - withdraw - trade transaction lack of expiration timestamp check (DeadLine check)
medium
The deposit - withdraw - trade transaction lack of expiration timestamp check (DeadLine check)\\nthe protocol missing the DEADLINE check at all in logic.\\nthis is actually how uniswap implemented the Deadline, this protocol also need deadline check like this logic\\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 point is the deadline check\\n```\\nmodifier ensure(uint deadline) {\\n require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');\\n _;\\n}\\n```\\n\\nThe deadline check ensure that the transaction can be executed on time and the expired transaction revert.
consider adding deadline check like in the functions like withdraw and deposit and all operations the point is the deadline check\\n```\\nmodifier ensure(uint deadline) {\\n require(deadline >= block.timestamp, 'UniswapV2Router: EXPIRED');\\n _;\\n}\\n```\\n
The 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.
```\\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
Lenders lose interests and pay deposit fees due to no slippage control
medium
When a lender deposits quote tokens below the minimum of LUP(Lowest Utilization Price) and HTP(Highest Threshold Price), the deposits will not earn interest and will also be charged deposit fees, according to docs. When a lender deposits to a bucket, they are vulnerable to pool LUP slippage which might cause them to lose funds due to fee charges against their will.\\nA lender would call `addQuoteToken()` to deposit. This function only allows entering expiration time for transaction settlement, but there is no slippage protection.\\n```\\n//Pool.sol\\n function addQuoteToken(\\n uint256 amount_,\\n uint256 index_,\\n uint256 expiry_\\n ) external override nonReentrant returns (uint256 bucketLP_) {\\n _revertAfterExpiry(expiry_);\\n PoolState memory poolState = _accruePoolInterest();\\n // round to token precision\\n amount_ = _roundToScale(amount_, poolState.quoteTokenScale);\\n uint256 newLup;\\n (bucketLP_, newLup) = LenderActions.addQuoteToken(\\n buckets,\\n deposits,\\n poolState,\\n AddQuoteParams({\\n amount: amount_,\\n index: index_\\n })\\n );\\n // rest of code\\n```\\n\\nIn LenderActions.sol, `addQuoteToken()` takes current `DepositsState` in storage and current `poolState_.debt` in storage to calculate spot LUP prior to deposit. And this LUP is compared with user input bucket `index_` to determine if the lender will be punished with deposit fees. The deposit amount is then written to storage.\\n```\\n//LenderActions.sol\\n function addQuoteToken(\\n mapping(uint256 => Bucket) storage buckets_,\\n DepositsState storage deposits_,\\n PoolState calldata poolState_,\\n AddQuoteParams calldata params_\\n ) external returns (uint256 bucketLP_, uint256 lup_) {\\n // rest of code\\n // charge unutilized deposit fee where appropriate\\n |> uint256 lupIndex = Deposits.findIndexOfSum(deposits_, poolState_.debt);\\n bool depositBelowLup = lupIndex != 0 && params_.index > lupIndex;\\n if (depositBelowLup) {\\n addedAmount = Maths.wmul(addedAmount, Maths.WAD - _depositFeeRate(poolState_.rate));\\n }\\n// rest of code\\n Deposits.unscaledAdd(deposits_, params_.index, unscaledAmount);\\n// rest of code\\n```\\n\\nIt should be noted that current `deposits_` and `poolState_.debt` can be different from when the user invoked the transaction, which will result in a different LUP spot price unforeseen by the lender to determine deposit fees. Even though lenders can input a reasonable expiration time `expirty_`, this will only prevent stale transactions to be executed and not offer any slippage control.\\nWhen there are many lenders depositing around the same time, LUP spot price can be increased and if the user transaction settles after a whale lender which moves the LUP spot price up significantly, the user might get accidentally punished for depositing below LUP. Or there could also be malicious lenders trying to ensure their transactions settle at a favorable LUP/HTP and front-run the user transaction, in which case the user transaction might still settle after the malicious lender and potentially get charged for fees.
Add slippage protection in Pool.sol `addQuoteToken()`. A lender can enable slippage protection, which will enable comparing deposit `index_` with `lupIndex` in LenderActions.sol.
Lenders might get charged deposit fees due to slippage against their will with or without MEV attacks, lenders might also lose on interest by depositing below HTP.
```\\n//Pool.sol\\n function addQuoteToken(\\n uint256 amount_,\\n uint256 index_,\\n uint256 expiry_\\n ) external override nonReentrant returns (uint256 bucketLP_) {\\n _revertAfterExpiry(expiry_);\\n PoolState memory poolState = _accruePoolInterest();\\n // round to token precision\\n amount_ = _roundToScale(amount_, poolState.quoteTokenScale);\\n uint256 newLup;\\n (bucketLP_, newLup) = LenderActions.addQuoteToken(\\n buckets,\\n deposits,\\n poolState,\\n AddQuoteParams({\\n amount: amount_,\\n index: index_\\n })\\n );\\n // rest of code\\n```\\n
BalancedVault.sol: loss of funds + global settlement flywheel / user settlement flywheels getting out of sync
high
When an epoch has become "stale", the `BalancedVault` will treat any new deposits and redemptions in this epoch as "pending". This means they won't get processed by the global settlement flywheel in the next epoch but one epoch later than that.\\nDue to the fact that anyone can push a pending deposit or redemption of a user further ahead by making an arbitrarily small deposit in the "intermediate epoch" (i.e. the epoch between when the user creates the pending deposit / redemption and the epoch when it is scheduled to be processed by the global settlement flywheel), the user can experience a DOS.\\nWorse than that, by pushing the pending deposit / pending redemption further ahead, the global settlement flywheel and the user settlement flywheel get out of sync.\\nAlso users can experience a loss of funds.\\nSo far so good. The global settlement flywheel and the user settlement flywheel are in sync and will process the pending deposit in epoch `3`.\\nNow here's the issue. A malicious user2 or user1 unknowingly (depending on the specific scenario) calls `deposit` for user1 again in the current epoch `2` once it has become `stale` (it's possible to `deposit` an arbitrarily small amount). By doing so we set `_pendingEpochs[user1] = context.epoch + 1 = 3`, thereby pushing the processing of the `deposit` in the user settlement flywheel one epoch ahead.\\nIt's important to understand that the initial deposit will still be processed in epoch `3` in the global settlement flywheel, it's just being pushed ahead in the user settlement flywheel.\\nThereby the global settlement flywheel and user settlement flywheel are out of sync now.\\nAn example for a loss of funds that can occur as a result of this issue is when the PnL from epoch `3` to epoch `4` is positive. Thereby the user1 will get less shares than he is entitled to.\\nSimilarly it is possible to push pending redemptions ahead, thereby the `_totalUnclaimed` amount would be increased by an amount that is different from the amount that `_unclaimed[account]` is increased by.\\nComing back to the case with the pending deposit, I wrote a test that you can add to BalancedVaultMulti.test.ts:\\n```\\nit('pending deposit pushed by 1 epoch causing shares difference', async () => {\\n const smallDeposit = utils.parseEther('1000')\\n const smallestDeposit = utils.parseEther('0.000001')\\n\\n await updateOracleEth() // epoch now stale\\n // make a pending deposit\\n await vault.connect(user).deposit(smallDeposit, user.address)\\n await updateOracleBtc()\\n await vault.sync()\\n\\n await updateOracleEth() // epoch now stale\\n /* \\n user2 deposits for user1, thereby pushing the pending deposit ahead and causing the \\n global settlement flywheel and user settlement flywheel to get out of sync\\n */\\n await vault.connect(user2).deposit(smallestDeposit, user.address)\\n await updateOracleBtc()\\n await vault.sync()\\n\\n await updateOracle()\\n // pending deposit for user1 is now processed in the user settlement flywheel\\n await vault.syncAccount(user.address)\\n\\n const totalSupply = await vault.totalSupply()\\n const balanceUser1 = await vault.balanceOf(user.address)\\n const balanceUser2 = await vault.balanceOf(user2.address)\\n\\n /*\\n totalSupply is bigger than the amount of shares of both users together\\n this is because user1 loses out on some shares that he is entitled to\\n -> loss of funds\\n */\\n console.log(totalSupply);\\n console.log(balanceUser1.add(balanceUser2));\\n\\n})\\n```\\n\\nThe impact that is generated by having one pending deposit that is off by one epoch is small. However over time this would evolve into a chaotic situation, where the state of the Vault is significantly corrupted.
My recommendation is to implement a queue for pending deposits / pending redemptions of a user. Pending deposits / redemptions can then be processed independently (without new pending deposits / redemptions affecting when existing ones are processed).\\nPossibly there is a simpler solution which might involve restricting the ability to make deposits to the user himself and only allowing one pending deposit / redemption to exist at a time.\\nThe solution to implement depends on how flexible the sponsor wants the deposit / redemption functionality to be.
The biggest impact comes from the global settlement flywheel and user settlement flywheel getting out of sync. As shown above, this can lead to a direct loss of funds for the user (e.g. the amount of shares he gets for a deposit are calculated with the wrong context).\\nApart from the direct impact for a single user, there is a subtler impact which can be more severe in the long term. Important invariants are violated:\\nSum of user balances is equal to the total supply\\nSum of unclaimed user assets is equal to total unclaimed assets\\nThereby the impact is not limited to a single user but affects the calculations for all users.\\nLess important but still noteworthy is that users that deposit into the Vault are partially exposed to PnL in the underlying products. The Vault does not employ a fully delta-neutral strategy. Therefore by experiencing a larger delay until the pending deposit / redemption is processed, users incur the risk of negative PnL.
```\\nit('pending deposit pushed by 1 epoch causing shares difference', async () => {\\n const smallDeposit = utils.parseEther('1000')\\n const smallestDeposit = utils.parseEther('0.000001')\\n\\n await updateOracleEth() // epoch now stale\\n // make a pending deposit\\n await vault.connect(user).deposit(smallDeposit, user.address)\\n await updateOracleBtc()\\n await vault.sync()\\n\\n await updateOracleEth() // epoch now stale\\n /* \\n user2 deposits for user1, thereby pushing the pending deposit ahead and causing the \\n global settlement flywheel and user settlement flywheel to get out of sync\\n */\\n await vault.connect(user2).deposit(smallestDeposit, user.address)\\n await updateOracleBtc()\\n await vault.sync()\\n\\n await updateOracle()\\n // pending deposit for user1 is now processed in the user settlement flywheel\\n await vault.syncAccount(user.address)\\n\\n const totalSupply = await vault.totalSupply()\\n const balanceUser1 = await vault.balanceOf(user.address)\\n const balanceUser2 = await vault.balanceOf(user2.address)\\n\\n /*\\n totalSupply is bigger than the amount of shares of both users together\\n this is because user1 loses out on some shares that he is entitled to\\n -> loss of funds\\n */\\n console.log(totalSupply);\\n console.log(balanceUser1.add(balanceUser2));\\n\\n})\\n```\\n
ChainlinkAggregator: binary search for roundId does not work correctly and Oracle can even end up temporarily DOSed
medium
When a phase switchover occurs, it can be necessary that phases need to be searched for a `roundId` with a timestamp as close as possible but bigger than `targetTimestamp`.\\nFinding the `roundId` with the closest possible timestamp is necessary according to the sponsor to minimize the delay of position changes:\\n\\nThe binary search algorithm is not able to find this best `roundId` which thereby causes unintended position changes.\\nAlso it can occur that the `ChainlinkAggregator` library is unable to find a valid `roundId` at all (as opposed to only not finding the "best").\\nThis would cause the Oracle to be temporarily DOSed until there are more valid rounds.\\nLet's say in a phase there's only one valid round (roundId=1) and the timestamp for this round is greater than `targetTimestamp`\\nWe would expect the `roundId` that the binary search finds to be `roundId=1`.\\nThe binary search loop is executed with `minRoundId=1` and `maxRoundId=1001`.\\nAll the above conditions can easily occur in reality, they represent the basic scenario under which this algorithm executes.\\n`minRoundId` and `maxRoundId` change like this in the iterations of the loop:\\n```\\nminRoundId=1\\nmaxRoundId=1001\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=501\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=251\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=126\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=63\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=32\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=16\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=8\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=4\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=2\\n\\nNow the loop terminates because\\nminRoundId + 1 !< maxRoundId\\n```\\n\\nSince we assumed that `roundId=2` is invalid, the function returns `0` (maxTimestamp=type(uint256).max):\\nIn the case that `latestRound.roundId` is equal to the `roundId=1` (i.e. same phase and same round id which could not be found) there would be no other valid rounds that the `ChainlinkAggregator` can find which causes a temporary DOS.
I recommend to add a check if `minRoundId` is a valid solution for the binary search. If it is, `minRoundId` should be used to return the result instead of maxRoundId:\\n```\\n // If the found timestamp is not greater than target timestamp or no max was found, then the desired round does\\n // not exist in this phase\\n// Remove the line below\\n if (maxTimestamp <= targetTimestamp || maxTimestamp == type(uint256).max) return 0;\\n// Add the line below\\n if ((minTimestamp <= targetTimestamp || minTimestamp == type(uint256).max) && (maxTimestamp <= targetTimestamp || maxTimestamp == type(uint256).max)) return 0;\\n \\n// Add the line below\\n if (minTimestamp > targetTimestamp) {\\n// Add the line below\\n return _aggregatorRoundIdToProxyRoundId(phaseId, uint80(minRoundId));\\n// Add the line below\\n }\\n return _aggregatorRoundIdToProxyRoundId(phaseId, uint80(maxRoundId));\\n }\\n```\\n\\nAfter applying the changes, the binary search only returns `0` if both `minRoundId` and `maxRoundId` are not a valid result.\\nIf this line is passed we know that either of both is valid and we can use `minRoundId` if it is the better result.
As explained above this would result in sub-optimal and unintended position changes in the best case. In the worst-case the Oracle can be temporarily DOSed, unable to find a valid `roundId`.\\nThis means that users cannot interact with the perennial protocol because the Oracle cannot be synced. So they cannot close losing trades which is a loss of funds.
```\\nminRoundId=1\\nmaxRoundId=1001\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=501\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=251\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=126\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=63\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=32\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=16\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=8\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=4\\n\\n-> \\n\\nminRoundId=1\\nmaxRoundId=2\\n\\nNow the loop terminates because\\nminRoundId + 1 !< maxRoundId\\n```\\n
BalancedVault.sol: Early depositor can manipulate exchange rate and steal funds
medium
The first depositor can mint a very small number of shares, then donate assets to the Vault. Thereby he manipulates the exchange rate and later depositors lose funds due to rounding down in the number of shares they receive.\\nThe currently deployed Vaults already hold funds and will merely be upgraded to V2. However as Perennial expands there will surely be the need for more Vaults which enables this issue to occur.\\nYou can add the following test to `BalancedVaultMulti.test.ts`. Make sure to have the `dsu` variable available in the test since by default this variable is not exposed to the tests.\\nThe test is self-explanatory and contains the necessary comments:\\n```\\nit('exchange rate manipulation', async () => {\\n const smallDeposit = utils.parseEther('1')\\n const smallestDeposit = utils.parseEther('0.000000000000000001')\\n\\n // make a deposit with the attacker. Deposit 1 Wei to mint 1 Wei of shares\\n await vault.connect(user).deposit(smallestDeposit, user.address)\\n await updateOracle();\\n await vault.sync()\\n\\n console.log(await vault.totalSupply());\\n\\n // donating assets to Vault\\n await dsu.connect(user).transfer(vault.address, utils.parseEther('1'))\\n\\n console.log(await vault.totalAssets());\\n\\n // make a deposit with the victim. Due to rounding the victim will end up with 0 shares\\n await updateOracle();\\n await vault.sync()\\n await vault.connect(user2).deposit(smallDeposit, user2.address)\\n await updateOracle();\\n await vault.sync()\\n\\n console.log(await vault.totalAssets());\\n console.log(await vault.totalSupply());\\n // the amount of shares the victim receives is rounded down to 0\\n console.log(await vault.balanceOf(user2.address));\\n\\n /*\\n at this point there are 2000000000000000001 Wei of assets in the Vault and only 1 Wei of shares\\n which is owned by the attacker.\\n This means the attacker has stolen all funds from the victim.\\n */\\n })\\n```\\n
This issue can be mitigated by requiring a minimum deposit of assets. Thereby the attacker cannot manipulate the exchange rate to be so low as to enable this attack.
The attacker can steal funds from later depositors.
```\\nit('exchange rate manipulation', async () => {\\n const smallDeposit = utils.parseEther('1')\\n const smallestDeposit = utils.parseEther('0.000000000000000001')\\n\\n // make a deposit with the attacker. Deposit 1 Wei to mint 1 Wei of shares\\n await vault.connect(user).deposit(smallestDeposit, user.address)\\n await updateOracle();\\n await vault.sync()\\n\\n console.log(await vault.totalSupply());\\n\\n // donating assets to Vault\\n await dsu.connect(user).transfer(vault.address, utils.parseEther('1'))\\n\\n console.log(await vault.totalAssets());\\n\\n // make a deposit with the victim. Due to rounding the victim will end up with 0 shares\\n await updateOracle();\\n await vault.sync()\\n await vault.connect(user2).deposit(smallDeposit, user2.address)\\n await updateOracle();\\n await vault.sync()\\n\\n console.log(await vault.totalAssets());\\n console.log(await vault.totalSupply());\\n // the amount of shares the victim receives is rounded down to 0\\n console.log(await vault.balanceOf(user2.address));\\n\\n /*\\n at this point there are 2000000000000000001 Wei of assets in the Vault and only 1 Wei of shares\\n which is owned by the attacker.\\n This means the attacker has stolen all funds from the victim.\\n */\\n })\\n```\\n
User would liquidate his account to sidestep `takerInvariant` modifier
medium
A single user could open a massive maker position, using the maximum leverage possible(and possibly reach the maker limit), and when a lot of takers open take positions, maker would liquidate his position, effectively bypassing the taker invariant and losing nothing apart from position fees. This would cause takers to be charged extremely high funding fees(at the maxRate), and takers that are not actively monitoring their positions will be greatly affected.\\nIn the closeMakeFor function, there is a modifier called `takerInvariant`.\\n```\\nfunction closeMakeFor(\\n address account,\\n UFixed18 amount\\n )\\n public\\n nonReentrant\\n notPaused\\n onlyAccountOrMultiInvoker(account)\\n settleForAccount(account)\\n takerInvariant\\n closeInvariant(account)\\n liquidationInvariant(account)\\n {\\n _closeMake(account, amount);\\n }\\n```\\n\\nThis modifier prevents makers from closing their positions if it would make the global maker open positions to fall below the global taker open positions. A malicious maker can easily sidestep this by liquidating his own account. Liquidating an account pays the liquidator a fee from the account's collateral, and then forcefully closes all open maker and taker positions for that account.\\n```\\nfunction closeAll(address account) external onlyCollateral notClosed settleForAccount(account) {\\n AccountPosition storage accountPosition = _positions[account];\\n Position memory p = accountPosition.position.next(_positions[account].pre);\\n\\n // Close all positions\\n _closeMake(account, p.maker);\\n _closeTake(account, p.taker);\\n\\n // Mark liquidation to lock position\\n accountPosition.liquidation = true; \\n }\\n```\\n\\nThis would make the open maker positions to drop significantly below the open taker position, and greatly increase the funding fee and utilization ratio.\\nATTACK SCENARIO\\nA new Product(ETH-Long) is launched on arbitrum with the following configurations:\\n20x max leverage(5% maintenance)\\nmakerFee = 0\\ntakerFee = 0.015\\nliquidationFee = 20%\\nminRate = 4%\\nmaxRate = 120%\\ntargetRate = 12%\\ntargetUtilization = 80%\\nmakerLimit = 4000 Eth\\nETH price = 1750 USD\\nColl Token = USDC\\nmax liquidity(USD) = 4000*1750 = $7,000,000\\nWhale initially supplies 350k USDC of collateral(~200ETH), and opens a maker position of 3000ETH($5.25mn), at 15x leverage.\\nAfter 2 weeks of activity, global open maker position goes up to 3429ETH($6mn), and because fundingFee is low, people are incentivized to open taker positions, so global open taker position gets to 2743ETH($4.8mn) at 80% utilization. Now, rate of fundingFee is 12%\\nNow, Whale should only be able to close up to 686ETH($1.2mn) of his maker position using the `closeMakeFor` function because of the `takerInvariant` modifier.\\nWhale decides to withdraw 87.5k USDC(~50ETH), bringing his total collateral to 262.5k USDC, and his leverage to 20x(which is the max leverage)\\nIf price of ETH temporarily goes up to 1755 USD, totalMaintenance=3000 * 1755 * 5% = $263250. Because his totalCollateral is 262500 USDC(which is less than totalMaintenance), his account becomes liquidatable.\\nWhale liquidates his account, he receives liquidationFee*totalMaintenance = 20% * 263250 = 52650USDC, and his maker position of 3000ETH gets closed. Now, he can withdraw his remaining collateral(262500-52650=209850)USDC because he has no open positions.\\nGlobal taker position is now 2743ETH($4.8mn), and global maker position is 429ETH($750k)\\nWhale has succeeded in bypassing the takerInvaraiant modifier, which was to prevent him from closing his maker position if it would make global maker position less than global taker position.\\nConsequently,\\nFunding fees would now be very high(120%), so the currently open taker positions will be greatly penalized, and takers who are not actively monitoring their position could lose a lot.\\nWhale would want to gain from the high funding fees, so he would open a maker position that would still keep the global maker position less than the global taker position(e.g. collateral of 232750USDC at 15x leverage, open position = ~2000ETH($3.5mn)) so that taker positions will keep getting charged at the funding fee maxRate.
Consider implementing any of these:\\nProtocol should receive a share of liquidation fee: This would disincentivize users from wanting to liquidate their own accounts, and they would want to keep their positions healthy and over-collateralized\\nLet there be a maker limit on each account: In addition to the global maker limit, there should be maker limit for each account which may be capped at 5% of global maker limit. This would decentralize liquidity provisioning.
Issue User would liquidate his account to sidestep `takerInvariant` modifier\\nUser will close his maker position when he shouldn't be allowed to, and it would cause open taker positions to be greatly impacted. And those who are not actively monitoring their open taker positions will suffer loss due to high funding fees.
```\\nfunction closeMakeFor(\\n address account,\\n UFixed18 amount\\n )\\n public\\n nonReentrant\\n notPaused\\n onlyAccountOrMultiInvoker(account)\\n settleForAccount(account)\\n takerInvariant\\n closeInvariant(account)\\n liquidationInvariant(account)\\n {\\n _closeMake(account, amount);\\n }\\n```\\n
Accounts will not be liquidated when they are meant to.
medium
In the case that the totalMaintenance*liquidationFee is higher than the account's totalCollateral, liquidators are paid the totalCollateral. I think one of the reasons for this is to avoid the case where liquidating an account would attempt to debit fees that is greater than the collateral balance The problem is that, the value of totalCollateral used as fee is slightly higher value than the current collateral balance, which means that in such cases, attempts to liquidate the account would revert due to underflow errors.\\nHere is the `liquidate` function:\\n```\\nfunction liquidate(\\n address account,\\n IProduct product\\n ) external nonReentrant notPaused isProduct(product) settleForAccount(account, product) {\\n if (product.isLiquidating(account)) revert CollateralAccountLiquidatingError(account);\\n\\n UFixed18 totalMaintenance = product.maintenance(account); maintenance?\\n UFixed18 totalCollateral = collateral(account, product); \\n\\n if (!totalMaintenance.gt(totalCollateral))\\n revert CollateralCantLiquidate(totalMaintenance, totalCollateral);\\n\\n product.closeAll(account);\\n\\n // claim fee\\n UFixed18 liquidationFee = controller().liquidationFee();\\n \\n UFixed18 collateralForFee = UFixed18Lib.max(totalMaintenance, controller().minCollateral()); \\n UFixed18 fee = UFixed18Lib.min(totalCollateral, collateralForFee.mul(liquidationFee)); \\n\\n _products[product].debitAccount(account, fee); \\n token.push(msg.sender, fee);\\n\\n emit Liquidation(account, product, msg.sender, fee);\\n }\\n```\\n\\n`fee=min(totalCollateral,collateralForFee*liquidationFee)` But the PROBLEM is, the value of `totalCollateral` is fetched before calling `product.closeAll`, and `product.closeAll` debits the closePosition fee from the collateral balance. So there is an attempt to debit `totalCollateral`, when the current collateral balance of the account is totalCollateral-closePositionFees This allows the following:\\nThere is an ETH-long market with following configs:\\nmaintenance=5%\\nminCollateral=100USDC\\nliquidationFee=20%\\nETH price=$1000\\nUser uses 500USDC to open $10000(10ETH) position\\nPrice of ETH spikes up to $6000\\nRequired maintenance= 60000*5%=$3000 which is higher than account's collateral balance(500USDC), therefore account should be liquidated\\nA watcher attempts to liquidate the account which does the following:\\ntotalCollateral=500USDC\\n`product.closeAll` closes the position and debits a makerFee of 10USDC\\ncurrent collateral balance=490USDC\\ncollateralForFee=totalMaintenance=$3000\\nfee=min(500,3000*20%)=500\\n`_products[product].debitAccount(account,fee)` attempts to subtract 500 from 490 which would revert due to underflow\\naccount does not get liquidated\\nNow, User is not liquidated even when he is using 500USD to control a $60000 position at 120x leverage(whereas, maxLeverage=20x)\\nNOTE: This would happen when the market token's price increases by (1/liquidationFee)x. In the above example, price of ETH increased by 6x (from 1000USD to 6000USD) which is greater than 5(1/20%)
`totalCollateral` that would be paid to liquidator should be refetched after `product.closeAll` is called to get the current collateral balance after closePositionFees have been debited.
A User's position will not be liquidated even when his collateral balance falls WELL below the required maintenance. I believe this is of HIGH impact because this scenario is very likely to happen, and when it does, the protocol will be greatly affected because a lot of users will be trading abnormally high leveraged positions without getting liquidated.
```\\nfunction liquidate(\\n address account,\\n IProduct product\\n ) external nonReentrant notPaused isProduct(product) settleForAccount(account, product) {\\n if (product.isLiquidating(account)) revert CollateralAccountLiquidatingError(account);\\n\\n UFixed18 totalMaintenance = product.maintenance(account); maintenance?\\n UFixed18 totalCollateral = collateral(account, product); \\n\\n if (!totalMaintenance.gt(totalCollateral))\\n revert CollateralCantLiquidate(totalMaintenance, totalCollateral);\\n\\n product.closeAll(account);\\n\\n // claim fee\\n UFixed18 liquidationFee = controller().liquidationFee();\\n \\n UFixed18 collateralForFee = UFixed18Lib.max(totalMaintenance, controller().minCollateral()); \\n UFixed18 fee = UFixed18Lib.min(totalCollateral, collateralForFee.mul(liquidationFee)); \\n\\n _products[product].debitAccount(account, fee); \\n token.push(msg.sender, fee);\\n\\n emit Liquidation(account, product, msg.sender, fee);\\n }\\n```\\n
`BalancedVault` doesn't consider potential break in one of the markets
medium
In case of critical failure of any of the underlying markets, making it permanently impossible to close position and withdraw collateral all funds deposited to balanced Vault will be lost, including funds deposited to other markets.\\nAs Markets and Vaults on Perennial are intented to be created in a permissionless manner and integrate with external price feeds, it cannot be ruled out that any Market will enter a state of catastrophic failure at a point in the future (i.e. oracle used stops functioning and Market admin keys are compromised, so it cannot be changed), resulting in permanent inability to process closing positions and withdrawing collateral.\\n`BalancedVault` does not consider this case, exposing all funds deposited to a multi-market Vault to an increased risk, as it is not implementing a possibility for users to withdraw deposited funds through a partial emergency withdrawal from other markets, even at a price of losing the claim to locked funds in case it becomes available in the future. This risk is not mentioned in the documentation.\\nProof of Concept\\nConsider a Vault with 2 markets: ETH/USD and ARB/USD.\\nAlice deposits to Vault, her funds are split between 2 markets\\nARB/USD market undergoes a fatal failure resulting in `maxAmount` returned from `_maxRedeemAtEpoch` to be 0\\nAlice cannot start withdrawal process as this line in `redeem` reverts:\\n```\\n if (shares.gt(_maxRedeemAtEpoch(context, accountContext, account))) revert BalancedVaultRedemptionLimitExceeded();\\n```\\n
Implement a partial/emergency withdrawal or acknowledge the risk clearly in Vault's documentation.
Users funds are exposed to increased risk compared to depositing to each market individually and in case of failure of any of the markets all funds are lost. User has no possibility to consciously cut losses and withdraw funds from Markets other than the failed one.
```\\n if (shares.gt(_maxRedeemAtEpoch(context, accountContext, account))) revert BalancedVaultRedemptionLimitExceeded();\\n```\\n
eMode implementation is completely broken
high
Enabling eMode allows assets of the same class to be borrowed at much higher a much higher LTV. The issue is that the current implementation makes the incorrect calls to the Aave V3 pool making so that the pool can never take advantage of this higher LTV.\\nAaveLeverageStrategyExtension.sol#L1095-L1109\\n```\\nfunction _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) {\\n \\n // Retrieve collateral factor and liquidation threshold for the collateral asset in precise units (1e16 = 1%)\\n ( , uint256 maxLtvRaw, uint256 liquidationThresholdRaw, , , , , , ,) = strategy.aaveProtocolDataProvider.getReserveConfigurationData(address(strategy.collateralAsset));\\n\\n // Normalize LTV and liquidation threshold to precise units. LTV is measured in 4 decimals in Aave which is why we must multiply by 1e14\\n // for example ETH has an LTV value of 8000 which represents 80%\\n if (_isLever) {\\n uint256 netBorrowLimit = _actionInfo.collateralValue\\n .preciseMul(maxLtvRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return netBorrowLimit\\n .sub(_actionInfo.borrowValue)\\n .preciseDiv(_actionInfo.collateralPrice);\\n```\\n\\nWhen calculating the max borrow/repay allowed, the contract uses the getReserveConfigurationData subcall to the pool.\\nAaveProtocolDataProvider.sol#L77-L100\\n```\\nfunction getReserveConfigurationData(\\n address asset\\n)\\n external\\n view\\n override\\n returns (\\n // rest of code\\n )\\n{\\n DataTypes.ReserveConfigurationMap memory configuration = IPool(ADDRESSES_PROVIDER.getPool())\\n .getConfiguration(asset);\\n\\n (ltv, liquidationThreshold, liquidationBonus, decimals, reserveFactor, ) = configuration\\n .getParams();\\n```\\n\\nThe issue with using getReserveConfigurationData is that it always returns the default settings of the pool. It never returns the adjusted eMode settings. This means that no matter the eMode status of the set token, it will never be able to borrow to that limit due to calling the incorrect function.\\nIt is also worth considering that the set token as well as other integrated modules configurations/settings would assume this higher LTV. Due to this mismatch, the set token would almost guaranteed be misconfigured which would lead to highly dangerous/erratic behavior from both the set and it's integrated modules. Due to this I believe that a high severity is appropriate.
Pull the adjusted eMode settings rather than the base pool settings
Usage of eMode, a core function of the contracts, is completely unusable causing erratic/dangerous behavior
```\\nfunction _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) {\\n \\n // Retrieve collateral factor and liquidation threshold for the collateral asset in precise units (1e16 = 1%)\\n ( , uint256 maxLtvRaw, uint256 liquidationThresholdRaw, , , , , , ,) = strategy.aaveProtocolDataProvider.getReserveConfigurationData(address(strategy.collateralAsset));\\n\\n // Normalize LTV and liquidation threshold to precise units. LTV is measured in 4 decimals in Aave which is why we must multiply by 1e14\\n // for example ETH has an LTV value of 8000 which represents 80%\\n if (_isLever) {\\n uint256 netBorrowLimit = _actionInfo.collateralValue\\n .preciseMul(maxLtvRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return netBorrowLimit\\n .sub(_actionInfo.borrowValue)\\n .preciseDiv(_actionInfo.collateralPrice);\\n```\\n
_calculateMaxBorrowCollateral calculates repay incorrectly and can lead to set token liquidation
high
When calculating the amount to repay, `_calculateMaxBorrowCollateral` incorrectly applies `unutilizedLeveragePercentage` when calculating `netRepayLimit`. The result is that if the `borrowValue` ever exceeds `liquidationThreshold * (1 - unutilizedLeveragPercentage)` then all attempts to repay will revert.\\nAaveLeverageStrategyExtension.sol#L1110-L1118\\n```\\n } else {\\n uint256 netRepayLimit = _actionInfo.collateralValue\\n .preciseMul(liquidationThresholdRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return _actionInfo.collateralBalance\\n .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))\\n .preciseDiv(netRepayLimit);\\n }\\n```\\n\\nWhen calculating `netRepayLimit`, `_calculateMaxBorrowCollateral` uses the `liquidationThreshold` adjusted by `unutilizedLeveragePercentage`. It then subtracts the borrow value from this limit. This is problematic because if the current `borrowValue` of the set token exceeds `liquidationThreshold` * (1 - unutilizedLeveragPercentage) then this line will revert making it impossible to make any kind of repayment. Once no repayment is possible the set token can't rebalance and will be liquidated.
Don't adjust the max value by `unutilizedLeveragPercentage`
Once the leverage exceeds a certain point the set token can no longer rebalance
```\\n } else {\\n uint256 netRepayLimit = _actionInfo.collateralValue\\n .preciseMul(liquidationThresholdRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return _actionInfo.collateralBalance\\n .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))\\n .preciseDiv(netRepayLimit);\\n }\\n```\\n
setIncentiveSettings would be halt during a rebalance operation that gets stuck due to supply cap is reached at Aave
medium
setIncentiveSettings would be halt during a rebalance operation that gets stuck due to supply cap is reached at Aave\\nrebalance implement a cap of tradeSize and if the need to rebalance require taking more assets than the maxTradeSize, then `twapLeverageRatio` would be set to the targeted leverage. `twapLeverageRatio` == 0 is required during rebalance.\\nConsider:\\nlever is needed during rebalance, the strategy require to borrow more ETH and sell to wstETH during the 1st call of rebalance the protocol cache the new `twapLeverageRatio` However wstETH market in Aave reach supply cap. rebalance/iterateRebalance comes to a halt. `twapLeverageRatio` remains caching the targeted leverage\\nsetIncentiveSettings requires a condition in which no rebalance is in progress. With the above case, setIncentiveSettings can be halted for an extended period of time until the wstETH market falls under supply cap.\\nWorth-noting, at the time of writing this issue, the wstETH market at Aave has been at supply cap\\nIn this case, malicious actor who already has a position in wstETH can do the following:\\ndeposit into the setToken, trigger a rebalance.\\nmalicious trader withdraw his/her position in Aave wstETH market so there opens up vacancy for supply again.\\nprotocol owner see supply vacancy, call rebalance in order to lever as required. Now twapLeverageRatio is set to new value since multiple trades are needed\\nmalicious trader now re-supply the wstETH market at Aave so it reaches supply cap again.\\nthe protocol gets stuck with a non-zero twapLeverageRatio, `setIncentiveSettings` can not be called.\\n```\\n function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress {\\n incentive = _newIncentiveSettings;\\n\\n _validateNonExchangeSettings(methodology, execution, incentive);\\n\\n emit IncentiveSettingsUpdated(\\n incentive.etherReward,\\n incentive.incentivizedLeverageRatio,\\n incentive.incentivizedSlippageTolerance,\\n incentive.incentivizedTwapCooldownPeriod\\n );\\n }\\n```\\n
Add some checks on whether the supply cap of an Aave market is reached during a rebalance. If so, allows a re-set of twapLeverageRatio
setIncentiveSettings would be halt.
```\\n function setIncentiveSettings(IncentiveSettings memory _newIncentiveSettings) external onlyOperator noRebalanceInProgress {\\n incentive = _newIncentiveSettings;\\n\\n _validateNonExchangeSettings(methodology, execution, incentive);\\n\\n emit IncentiveSettingsUpdated(\\n incentive.etherReward,\\n incentive.incentivizedLeverageRatio,\\n incentive.incentivizedSlippageTolerance,\\n incentive.incentivizedTwapCooldownPeriod\\n );\\n }\\n```\\n
Protocol doesn't completely protect itself from `LTV = 0` tokens
medium
The AaveLeverageStrategyExtension does not completely protect against tokens with a Loan-to-Value (LTV) of 0. Tokens with an LTV of 0 in Aave V3 pose significant risks, as they cannot be used as collateral to borrow upon a breaking withdraw. Moreover, LTVs of assets could be set to 0, even though they currently aren't, it could create substantial problems with potential disruption of multiple functionalities. This bug could cause a Denial-of-Service (DoS) situation in some cases, and has a potential to impact the borrowing logic in the protocol, leading to an unintentionally large perceived borrowing limit.\\nWhen an AToken has LTV = 0, Aave restricts the usage of certain operations. Specifically, if a user owns at least one AToken as collateral with an LTV = 0, certain operations could revert:\\nWithdraw: If the asset being withdrawn is collateral and the user is borrowing something, the operation will revert if the withdrawn collateral is an AToken with LTV > 0.\\nTransfer: If the asset being transferred is an AToken with LTV > 0 and the sender is using the asset as collateral and is borrowing something, the operation will revert.\\nSet the reserve of an AToken as non-collateral: If the AToken being set as non-collateral is an AToken with LTV > 0, the operation will revert.\\nTake a look at AaveLeverageStrategyExtension.sol#L1050-L1119\\n```\\n /**\\n * Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units.\\n *\\n * return uint256 Chunked rebalance notional in collateral units\\n * return uint256 Total rebalance notional in collateral units\\n */\\n function _calculateChunkRebalanceNotional(\\n LeverageInfo memory _leverageInfo,\\n uint256 _newLeverageRatio,\\n bool _isLever\\n )\\n internal\\n view\\n returns (uint256, uint256)\\n {\\n // Calculate absolute value of difference between new and current leverage ratio\\n uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio);\\n\\n uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance);\\n\\n uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever);\\n\\n uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize);\\n\\n return (chunkRebalanceNotional, totalRebalanceNotional);\\n }\\n\\n /**\\n * Calculate the max borrow / repay amount allowed in base units for lever / delever. This is due to overcollateralization requirements on\\n * assets deposited in lending protocols for borrowing.\\n *\\n * For lever, max borrow is calculated as:\\n * (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals\\n *\\n * For delever, max repay is calculated as:\\n * Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD\\n *\\n * Net borrow limit for levering is calculated as:\\n * The collateral value in USD * Aave collateral factor * (1 - unutilized leverage %)\\n *\\n * Net repay limit for delevering is calculated as:\\n * The collateral value in USD * Aave liquiditon threshold * (1 - unutilized leverage %)\\n *\\n * return uint256 Max borrow notional denominated in collateral asset\\n */\\n function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) {\\n\\n // Retrieve collateral factor and liquidation threshold for the collateral asset in precise units (1e16 = 1%)\\n ( , uint256 maxLtvRaw, uint256 liquidationThresholdRaw, , , , , , ,) = strategy.aaveProtocolDataProvider.getReserveConfigurationData(address(strategy.collateralAsset));\\n\\n // Normalize LTV and liquidation threshold to precise units. LTV is measured in 4 decimals in Aave which is why we must multiply by 1e14\\n // for example ETH has an LTV value of 8000 which represents 80%\\n if (_isLever) {\\n uint256 netBorrowLimit = _actionInfo.collateralValue\\n .preciseMul(maxLtvRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return netBorrowLimit\\n .sub(_actionInfo.borrowValue)\\n .preciseDiv(_actionInfo.collateralPrice);\\n } else {\\n uint256 netRepayLimit = _actionInfo.collateralValue\\n .preciseMul(liquidationThresholdRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return _actionInfo.collateralBalance\\n .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))\\n .preciseDiv(netRepayLimit);\\n }\\n }\\n```\\n\\nApart from the aforementioned issue with `LTV = 0` tokens, there's another issue with the `_calculateMaxBorrowCollateral()` function. When `LTV = 0`, `maxLtvRaw` also equals 0, leading to a `netBorrowLimit` of 0. When the borrowing value is subtracted from this, it results in an underflow, causing the borrowing limit to appear incredibly large. This essentially breaks the borrowing logic of the protocol.
The protocol should consider implementing additional protections against tokens with an LTV of 0.
This bug could potentially disrupt the entire borrowing logic within the protocol by inflating the perceived borrowing limit. This could lead to users borrowing an unlimited amount of assets due to the underflow error. In extreme cases, this could lead to a potential loss of user funds or even a complete protocol shutdown, thus impacting user trust and the overall functionality of the protocol.
```\\n /**\\n * Calculate total notional rebalance quantity and chunked rebalance quantity in collateral units.\\n *\\n * return uint256 Chunked rebalance notional in collateral units\\n * return uint256 Total rebalance notional in collateral units\\n */\\n function _calculateChunkRebalanceNotional(\\n LeverageInfo memory _leverageInfo,\\n uint256 _newLeverageRatio,\\n bool _isLever\\n )\\n internal\\n view\\n returns (uint256, uint256)\\n {\\n // Calculate absolute value of difference between new and current leverage ratio\\n uint256 leverageRatioDifference = _isLever ? _newLeverageRatio.sub(_leverageInfo.currentLeverageRatio) : _leverageInfo.currentLeverageRatio.sub(_newLeverageRatio);\\n\\n uint256 totalRebalanceNotional = leverageRatioDifference.preciseDiv(_leverageInfo.currentLeverageRatio).preciseMul(_leverageInfo.action.collateralBalance);\\n\\n uint256 maxBorrow = _calculateMaxBorrowCollateral(_leverageInfo.action, _isLever);\\n\\n uint256 chunkRebalanceNotional = Math.min(Math.min(maxBorrow, totalRebalanceNotional), _leverageInfo.twapMaxTradeSize);\\n\\n return (chunkRebalanceNotional, totalRebalanceNotional);\\n }\\n\\n /**\\n * Calculate the max borrow / repay amount allowed in base units for lever / delever. This is due to overcollateralization requirements on\\n * assets deposited in lending protocols for borrowing.\\n *\\n * For lever, max borrow is calculated as:\\n * (Net borrow limit in USD - existing borrow value in USD) / collateral asset price adjusted for decimals\\n *\\n * For delever, max repay is calculated as:\\n * Collateral balance in base units * (net borrow limit in USD - existing borrow value in USD) / net borrow limit in USD\\n *\\n * Net borrow limit for levering is calculated as:\\n * The collateral value in USD * Aave collateral factor * (1 - unutilized leverage %)\\n *\\n * Net repay limit for delevering is calculated as:\\n * The collateral value in USD * Aave liquiditon threshold * (1 - unutilized leverage %)\\n *\\n * return uint256 Max borrow notional denominated in collateral asset\\n */\\n function _calculateMaxBorrowCollateral(ActionInfo memory _actionInfo, bool _isLever) internal view returns(uint256) {\\n\\n // Retrieve collateral factor and liquidation threshold for the collateral asset in precise units (1e16 = 1%)\\n ( , uint256 maxLtvRaw, uint256 liquidationThresholdRaw, , , , , , ,) = strategy.aaveProtocolDataProvider.getReserveConfigurationData(address(strategy.collateralAsset));\\n\\n // Normalize LTV and liquidation threshold to precise units. LTV is measured in 4 decimals in Aave which is why we must multiply by 1e14\\n // for example ETH has an LTV value of 8000 which represents 80%\\n if (_isLever) {\\n uint256 netBorrowLimit = _actionInfo.collateralValue\\n .preciseMul(maxLtvRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return netBorrowLimit\\n .sub(_actionInfo.borrowValue)\\n .preciseDiv(_actionInfo.collateralPrice);\\n } else {\\n uint256 netRepayLimit = _actionInfo.collateralValue\\n .preciseMul(liquidationThresholdRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return _actionInfo.collateralBalance\\n .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue))\\n .preciseDiv(netRepayLimit);\\n }\\n }\\n```\\n
no validation to ensure the arbitrum sequencer is down
medium
There is no validation to ensure sequencer is down\\n```\\n int256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();\\n rebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10 ** strategy.collateralDecimalAdjustment);\\n int256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();\\n rebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10 ** strategy.borrowDecimalAdjustment);\\n```\\n\\nUsing 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.
recommend to add checks to ensure the sequencer is not down.
when sequencer is down, stale price is used for oracle and the borrow value and collateral value is calculated and the protocol can be forced to rebalance in a loss position
```\\n int256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();\\n rebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10 ** strategy.collateralDecimalAdjustment);\\n int256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();\\n rebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10 ** strategy.borrowDecimalAdjustment);\\n```\\n
Relying solely on oracle base slippage parameters can cause significant loss due to sandwich attacks
medium
AaveLeverageStrategyExtension relies solely on oracle price data when determining the slippage parameter during a rebalance. This is problematic as chainlink oracles, especially mainnet, have upwards of 2% threshold before triggering a price update. If swapping between volatile assets, the errors will compound causing even bigger variation. These variations can be exploited via sandwich attacks.\\nAaveLeverageStrategyExtension.sol#L1147-L1152\\n```\\nfunction _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) {\\n return _collateralRebalanceUnits\\n .preciseMul(_actionInfo.collateralPrice)\\n .preciseDiv(_actionInfo.borrowPrice)\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));\\n}\\n```\\n\\nWhen determining the minimum return from the swap, _calculateMinRepayUnits directly uses oracle data to determine the final output. The differences between the true value and the oracle value can be systematically exploited via sandwich attacks. Given the leverage nature of the module, these losses can cause significant loss to the pool.
The solution to this is straight forward. Allow keepers to specify their own slippage value. Instead of using an oracle slippage parameter, validate that the specified slippage value is within a margin of the oracle. This gives the best of both world. It allows for tighter and more reactive slippage controls while still preventing outright abuse in the event that the trusted keeper is compromised.
Purely oracle derived slippage parameters will lead to significant and unnecessary losses
```\\nfunction _calculateMinRepayUnits(uint256 _collateralRebalanceUnits, uint256 _slippageTolerance, ActionInfo memory _actionInfo) internal pure returns (uint256) {\\n return _collateralRebalanceUnits\\n .preciseMul(_actionInfo.collateralPrice)\\n .preciseDiv(_actionInfo.borrowPrice)\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(_slippageTolerance));\\n}\\n```\\n
Chainlink price feed is `deprecated`, not sufficiently validated and can return `stale` prices.
medium
The function `_createActionInfo()` uses Chainlink's deprecated latestAnswer function, this function also does not guarantee that the price returned by the Chainlink price feed is not stale and there is no additional checks to ensure that the return values are valid.\\nThe internal function `_createActionInfo()` uses calls `strategy.collateralPriceOracle.latestAnswer()` and `strategy.borrowPriceOracle.latestAnswer()` that uses Chainlink's deprecated latestAnswer() to get the latest price. However, there is no check for if the return value is a stale data.\\n```\\nfunction _createActionInfo() internal view returns(ActionInfo memory) {\\n ActionInfo memory rebalanceInfo;\\n\\n // Calculate prices from chainlink. Chainlink returns prices with 8 decimal places, but we need 36 - underlyingDecimals decimal places.\\n // This is so that when the underlying amount is multiplied by the received price, the collateral valuation is normalized to 36 decimals.\\n // To perform this adjustment, we multiply by 10^(36 - 8 - underlyingDecimals)\\n int256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();\\n rebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10 ** strategy.collateralDecimalAdjustment);\\n int256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();\\n rebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10 ** strategy.borrowDecimalAdjustment);\\n// More Code// rest of code.\\n}\\n \\n```\\n
The `latestRoundData` function should be used instead of the deprecated `latestAnswer` function and add sufficient checks to ensure that the pricefeed is not stale.\\n```\\n(uint80 roundId, int256 assetChainlinkPriceInt, , uint256 updatedAt, uint80 answeredInRound) = IPrice(_chainlinkFeed).latestRoundData();\\n require(answeredInRound >= roundId, "price is stale");\\n require(updatedAt > 0, "round is incomplete");\\n```\\n
The function `_createActionInfo()` is used to return important values used throughout the contract, the staleness of the chainlinklink return values will lead to wrong calculation of the collateral and borrow prices and other unexpected behavior.
```\\nfunction _createActionInfo() internal view returns(ActionInfo memory) {\\n ActionInfo memory rebalanceInfo;\\n\\n // Calculate prices from chainlink. Chainlink returns prices with 8 decimal places, but we need 36 - underlyingDecimals decimal places.\\n // This is so that when the underlying amount is multiplied by the received price, the collateral valuation is normalized to 36 decimals.\\n // To perform this adjustment, we multiply by 10^(36 - 8 - underlyingDecimals)\\n int256 rawCollateralPrice = strategy.collateralPriceOracle.latestAnswer();\\n rebalanceInfo.collateralPrice = rawCollateralPrice.toUint256().mul(10 ** strategy.collateralDecimalAdjustment);\\n int256 rawBorrowPrice = strategy.borrowPriceOracle.latestAnswer();\\n rebalanceInfo.borrowPrice = rawBorrowPrice.toUint256().mul(10 ** strategy.borrowDecimalAdjustment);\\n// More Code// rest of code.\\n}\\n \\n```\\n
The protocol does not compatible with token such as USDT because of the Approval Face Protection
medium
The protocol does not compatible with token such as USDT because of the Approval Face Protection\\nthe protocol is intended to interact with any ERC20 token and USDT is a common one\\nQ: Which ERC20 tokens do you expect will interact with the smart contracts? The protocol expects to interact with any ERC20.\\nIndividual SetToken's should only interact with ERC20 chosen by the SetToken manager.\\nwhen doing the deleverage\\nfirst, we construct the deleverInfo\\n```\\nActionInfo memory deleverInfo = _createAndValidateActionInfo(\\n _setToken,\\n _collateralAsset,\\n _repayAsset,\\n _redeemQuantityUnits,\\n _minRepayQuantityUnits,\\n _tradeAdapterName,\\n false\\n );\\n```\\n\\nthen we withdraw from the lending pool, execute trade and repay the borrow token\\n```\\n_withdraw(deleverInfo.setToken, deleverInfo.lendingPool, _collateralAsset, deleverInfo.notionalSendQuantity);\\n\\n uint256 postTradeReceiveQuantity = _executeTrade(deleverInfo, _collateralAsset, _repayAsset, _tradeData);\\n\\n uint256 protocolFee = _accrueProtocolFee(_setToken, _repayAsset, postTradeReceiveQuantity);\\n\\n uint256 repayQuantity = postTradeReceiveQuantity.sub(protocolFee);\\n\\n _repayBorrow(deleverInfo.setToken, deleverInfo.lendingPool, _repayAsset, repayQuantity);\\n```\\n\\nthis is calling _repayBorrow\\n```\\n/**\\n * @dev Invoke repay from SetToken using AaveV2 library. Burns DebtTokens for SetToken.\\n */\\nfunction _repayBorrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal {\\n _setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity);\\n _setToken.invokeRepay(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE);\\n}\\n```\\n\\nthe trade received (quantity - the protocol fee) is used to repay the debt\\nbut the required debt to be required is the (borrowed amount + the interest rate)\\nsuppose the only debt that needs to be repayed is 1000 USDT\\ntrade received (quantity - the protocol) fee is 20000 USDT\\nonly 1000 USDT is used to repay the debt\\nbecause when repaying, the paybackAmount is only the debt amount\\n```\\nuint256 paybackAmount = params.interestRateMode == DataTypes.InterestRateMode.STABLE\\n ? stableDebt\\n : variableDebt;\\n```\\n\\nthen when burning the variable debt token\\n```\\nreserveCache.nextScaledVariableDebt = IVariableDebtToken(\\n reserveCache.variableDebtTokenAddress\\n ).burn(params.onBehalfOf, paybackAmount, reserveCache.nextVariableBorrowIndex);\\n```\\n\\nonly the "payback amount", which is 1000 USDT is transferred to pay the debt,\\nthe excessive leftover amount is (20000 USDT - 1000 USDT) = 19000 USDT\\nbut if we lookback into the repayBack function\\n```\\n/**\\n * @dev Invoke repay from SetToken using AaveV2 library. Burns DebtTokens for SetToken.\\n */\\nfunction _repayBorrow(ISetToken _setToken, ILendingPool _lendingPool, IERC20 _asset, uint256 _notionalQuantity) internal {\\n _setToken.invokeApprove(address(_asset), address(_lendingPool), _notionalQuantity);\\n _setToken.invokeRepay(_lendingPool, address(_asset), _notionalQuantity, BORROW_RATE_MODE);\\n}\\n```\\n\\nthe approved amount is 20000 USDT, but only 1000 USDT approval limit is used, we have 19000 USDT approval limit left\\naccording to\\nSome tokens (e.g. OpenZeppelin) will revert if trying to approve the zero address to spend tokens (i.e. a call to approve(address(0), amt)).\\nIntegrators may need to add special cases to handle this logic if working with such a token.\\nUSDT is such token that subject to approval race condition, without approving 0 first, the second approve after first repay will revert
Approval 0 first
second and following repay borrow will revert if the ERC20 token is subject to approval race condition
```\\nActionInfo memory deleverInfo = _createAndValidateActionInfo(\\n _setToken,\\n _collateralAsset,\\n _repayAsset,\\n _redeemQuantityUnits,\\n _minRepayQuantityUnits,\\n _tradeAdapterName,\\n false\\n );\\n```\\n
Operator is blocked when sequencer is down on Arbitrum
medium
When the sequencer is down on Arbitrum state changes can still happen on L2 by passing them from L1 through the Delayed Inbox.\\nUsers can still interact with the Index protocol but due to how Arbitrum address aliasing functions the operator will be blocked from calling onlyOperator().\\nThe `msg.sender` of a transaction from the Delayed Inbox is aliased:\\n```\\nL2_Alias = L1_Contract_Address + 0x1111000000000000000000000000000000001111\\n```\\n\\nAll functions with the `onlyOperator()` modifier are therefore blocked when the sequencer is down.\\nThe issue exists for all modifiers that are only callable by specific EOAs. But the operator of the Aave3LeverageStrategyExtension is the main security risk.
Change the `onlyOperator()` to check if the address is the aliased address of the operator.
The operator has roles that are vital for the safety of the protocol. Re-balancing and issuing/redeeming can still be done when the sequencer is down it is therefore important that the operator call the necessary functions to operate the protocol when the sequencer is down.\\n`disengage()` is an important safety function that the operator should always have access especially when the protocol is still in accessible to other users. Changing methodology and adding/removing exchanges are also important for the safety of the protocol.
```\\nL2_Alias = L1_Contract_Address + 0x1111000000000000000000000000000000001111\\n```\\n
Oracle Price miss matched when E-mode uses single oracle
medium
AAVE3 can turn on single oracle use on any E-mode category. When that is done collateral and the borrowed assets will be valued based on a single oracle price. When this is done the prices used in AaveLeverageStrategyExtension can differ from those used internally in AAVE3.\\nThis can lead to an increased risk of liquidation and failures to re-balance properly.\\nThere is currently no accounting for single oracle use in the AaveLeverageStragyExtension, if AAVE3 turns it on the extension will simply continue using its current oracles without accounting for the different prices.\\nWhen re-balancing the following code calculate the netBorrowLimit/netRepayLimit:\\n```\\n if (_isLever) {\\n uint256 netBorrowLimit = _actionInfo.collateralValue\\n .preciseMul(maxLtvRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return netBorrowLimit\\n .sub(_actionInfo.borrowValue)\\n .preciseDiv(_actionInfo.collateralPrice);\\n } else {\\n uint256 netRepayLimit = _actionInfo.collateralValue\\n .preciseMul(liquidationThresholdRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return _actionInfo.collateralBalance\\n .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue)) \\n .preciseDiv(netRepayLimit);\\n \\n```\\n\\nThe `_actionInfo.collateralValue` and `_adminInfo.borrowValue` are `_getAndValidateLeverageInfo()` where they are both retrieved based on the current set chainlink oracle.\\nWhen E-mode uses a single oracle price a de-pegging of one of the assets will lead to incorrect values of `netBorrowLimit` and `netRepayLimit` depending on which asset is de-pegging.\\n`collateralValue` or `borrowValue` can be either larger or smaller than how they are valued internally in AAVE3.
Aave3LeverageStrategyExtension should take single oracle usage into account. `_calcualteMaxBorrowCollateral` should check if there is a discrepancy and adjust such that the `execute.unutilizedLeveragePercentage` safety parameter is honored.
When Levering\\nIf `collateralValue` is to valued higher than internally in AAVE3 OR If `borrowValue` is to valued lower than internally in AAVE3:\\nThe `netBorrowLimit` is larger than it should be we are essentially going to overriding `execute.unutilizedLeveragePercentage` and attempting to borrow more than we should.\\nIf `collateralValue` is valued lower than internally in AAVE3 OR If `borrowValue` is to valued higher than internally in AAVE3:\\nThe `netBorrowLimit` is smaller than it should be, we are not borrowing as much as we should. Levering up takes longer.\\nWhen Delevering\\nIf `collateralValue` is to valued higher than internally in AAVE3 OR If `borrowValue` is to valued lower than internally in AAVE3:\\nWe will withdraw more collateral and repay more than specified by `execution.unutilizedLeveragePercentage`.\\nIf `collateralValue` is valued lower than internally in AAVE3 OR If `borrowValue` is to valued higher than internally in AAVE3:\\nWe withdraw less and repay less debt than we should. This means that both `ripcord()` and `disengage()` are not functioning as they, they will not delever as fast they should. We can look at it as `execution.unutilizedLeveragePercentage` not being throttled.\\nThe above consequences show that important functionality is not working as expected. "overriding" `execution.unutilizedLeveragePercentage` is a serious safety concern.
```\\n if (_isLever) {\\n uint256 netBorrowLimit = _actionInfo.collateralValue\\n .preciseMul(maxLtvRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return netBorrowLimit\\n .sub(_actionInfo.borrowValue)\\n .preciseDiv(_actionInfo.collateralPrice);\\n } else {\\n uint256 netRepayLimit = _actionInfo.collateralValue\\n .preciseMul(liquidationThresholdRaw.mul(10 ** 14))\\n .preciseMul(PreciseUnitMath.preciseUnit().sub(execution.unutilizedLeveragePercentage));\\n\\n return _actionInfo.collateralBalance\\n .preciseMul(netRepayLimit.sub(_actionInfo.borrowValue)) \\n .preciseDiv(netRepayLimit);\\n \\n```\\n
In case the portfolio makes a loss, the total reserves and reserve ratio will be inflated.
medium
The pool balance is transferred to the portfolio for investment, for example sending USDT to Curve/Aave/Balancer etc. to generate yield. However, there are risks associated with those protocols such as smart contract risks. In case a loss happens, it will not be reflected in the pool balance and the total reserve and reserve ratio will be inflated.\\nThe assets in the pool can be sent to the portfolio account to invest and earn yield. The amount of assets in the insurance pool and Unitas pool is tracked by the `_balance` variable. This amount is used to calculate the total reserve and total collateral, which then are used to calculate the reserve ratio.\\n```\\n uint256 tokenReserve = _getBalance(token);\\n uint256 tokenCollateral = IInsurancePool(insurancePool).getCollateral(token);\\n```\\n\\nWhen there is a loss to the portfolio, there is no way to write down the `_balance` variable. This leads to an overstatement of the total reserve and reserve ratio.
Add function to allow admin to write off the `_balance` in case of investment lost. Example:\\n```\\nfunction writeOff(address token, uint256 amount) external onlyGuardian {\\n\\n uint256 currentBalance = IERC20(token).balanceOf(address(this));\\n\\n // Require that the amount to write off is less than or equal to the current balance\\n require(amount <= currentBalance, "Amount exceeds balance");\\n _balance[token] -= amount;\\n\\n emit WriteOff(token, amount);\\n}\\n```\\n
Overstatement of the total reserve and reserve ratio can increase the risk for the protocol because of undercollateralization of assets.
```\\n uint256 tokenReserve = _getBalance(token);\\n uint256 tokenCollateral = IInsurancePool(insurancePool).getCollateral(token);\\n```\\n
USD1 is priced as $1 instead of being pegged to USDT
medium
The system treats 1 USD1 = $1 instead of 1 USD1 = 1 USDT which allows arbitrage opportunities.\\nTo swap from one token to another Unitas first get's the price of the quote token and then calculates the swap result. Given that we want to swap 1 USD1 for USDT, we have USDT as the quote token:\\n```\\n address priceQuoteToken = _getPriceQuoteToken(tokenIn, tokenOut);\\n price = oracle.getLatestPrice(priceQuoteToken);\\n _checkPrice(priceQuoteToken, price);\\n\\n feeNumerator = isBuy ? pair.buyFee : pair.sellFee;\\n feeToken = IERC20Token(priceQuoteToken == tokenIn ? tokenOut : tokenIn);\\n\\n SwapRequest memory request;\\n request.tokenIn = tokenIn;\\n request.tokenOut = tokenOut;\\n request.amountType = amountType;\\n request.amount = amount;\\n request.feeNumerator = feeNumerator;\\n request.feeBase = tokenManager.SWAP_FEE_BASE();\\n request.feeToken = address(feeToken);\\n request.price = price;\\n request.priceBase = 10 ** oracle.decimals();\\n request.quoteToken = priceQuoteToken;\\n\\n (amountIn, amountOut, fee) = _calculateSwapResult(request);\\n```\\n\\nSince `amountType == AmountType.In`, it executes _calculateSwapResultByAmountIn():\\n```\\n // When tokenOut is feeToken, subtracts the fee after converting the amount\\n amountOut = _convert(\\n request.tokenIn,\\n request.tokenOut,\\n amountIn,\\n MathUpgradeable.Rounding.Down,\\n request.price,\\n request.priceBase,\\n request.quoteToken\\n );\\n fee = _getFeeByAmountWithFee(amountOut, request.feeNumerator, request.feeBase);\\n amountOut -= fee;\\n```\\n\\nGiven that the price is 0.99e18, i.e. 1 USDT is worth $0.99, it calculates the amount of USDT we should receive as:\\n```\\n function _convertByFromPrice(\\n address fromToken,\\n address toToken,\\n uint256 fromAmount,\\n MathUpgradeable.Rounding rounding,\\n uint256 price,\\n uint256 priceBase\\n ) internal view virtual returns (uint256) {\\n uint256 fromBase = 10 ** IERC20Metadata(fromToken).decimals();\\n uint256 toBase = 10 ** IERC20Metadata(toToken).decimals();\\n\\n return fromAmount.mulDiv(price * toBase, priceBase * fromBase, rounding);\\n }\\n```\\n\\nGiven that:\\ntoBase = 10**6 = 1e6 (USDT has 6 decimals)\\nfromBase = 10**18 = 1e18 (USD1 has 18 decimals)\\npriceBase = 1e18\\nprice = 0.99e18 (1 USDT = $0.99)\\nfromAmount = 1e18 (we swap 1 USD1) we get: $1e18 * 0.99e18 * 1e6 / (1e18 * 1e18) = 0.99e6$\\nSo by redeeming 1 USD1 I only get back 0.99 USDT. The other way around, trading USDT for USD1, would get you 1.01 USD1 for 1 USDT: $1e6 * 1e18 * 1e18 / (0.99e18 * 1e6) = 1.01e18$\\nThe contract values USD1 at exactly $1 while USDT's price is variable. But, in reality, USD1 is not pegged to $1. It's pegged to USDT the only underlying asset.\\nThat allows us to do the following:\\nWith USDT back to $1 we get: $1.003009e+23 * 1e18 * 1e6 / (1e18 * 1e18) = 100300.9e6$\\nThat's a profit of 300 USDT. The profit is taken from other users of the protocol who deposited USDT to get access to the other stablecoins.
1 USDT should always be 1 USD1. You treat 1 USD1 as $1 but that's not the case.
An attacker can abuse the price variation of USDT to buy USD1 for cheap.
```\\n address priceQuoteToken = _getPriceQuoteToken(tokenIn, tokenOut);\\n price = oracle.getLatestPrice(priceQuoteToken);\\n _checkPrice(priceQuoteToken, price);\\n\\n feeNumerator = isBuy ? pair.buyFee : pair.sellFee;\\n feeToken = IERC20Token(priceQuoteToken == tokenIn ? tokenOut : tokenIn);\\n\\n SwapRequest memory request;\\n request.tokenIn = tokenIn;\\n request.tokenOut = tokenOut;\\n request.amountType = amountType;\\n request.amount = amount;\\n request.feeNumerator = feeNumerator;\\n request.feeBase = tokenManager.SWAP_FEE_BASE();\\n request.feeToken = address(feeToken);\\n request.price = price;\\n request.priceBase = 10 ** oracle.decimals();\\n request.quoteToken = priceQuoteToken;\\n\\n (amountIn, amountOut, fee) = _calculateSwapResult(request);\\n```\\n
Users may not be able to fully redeem USD1 into USDT even when reserve ratio is above 100%
medium
Users may not be able to fully redeem USDT even when reserve ratio is above 100%, because of portfolio being taken into the account for calculation.\\nReserve ratio shows how many liabilities is covered by reserves, a reserve ratio above 100% guarantees protocol has enough USDT to redeem, the way of calculating reserve ratio is `Reserve Ratio = allReserves / liabilities` and is implemented in Unitas#_getReserveStatus(...) function:\\n```\\n reserveRatio = ScalingUtils.scaleByBases(\\n allReserves * valueBase / liabilities,\\n valueBase,\\n tokenManager.RESERVE_RATIO_BASE()\\n );\\n```\\n\\n`allReserves` is the sum of the balance of Unitas and InsurancePool, calculated in Unitas#_getTotalReservesAndCollaterals() function:\\n```\\n for (uint256 i; i < tokenCount; i++) {\\n address token = tokenManager.tokenByIndex(tokenTypeValue, i);\\n uint256 tokenReserve = _getBalance(token);\\n uint256 tokenCollateral = IInsurancePool(insurancePool).getCollateral(token);\\n\\n\\n if (tokenReserve > 0 || tokenCollateral > 0) {\\n uint256 price = oracle.getLatestPrice(token);\\n\\n\\n reserves += _convert(\\n token,\\n baseToken,\\n tokenReserve,\\n MathUpgradeable.Rounding.Down,\\n price,\\n priceBase,\\n token\\n );\\n\\n\\n collaterals += _convert(\\n token,\\n baseToken,\\n tokenCollateral,\\n MathUpgradeable.Rounding.Down,\\n price,\\n priceBase,\\n token\\n );\\n }\\n }\\n```\\n\\n`liabilities` is the total value of USD1 and USDEMC tokens, calculated in Unitas#_getTotalLiabilities() function:\\n```\\n for (uint256 i; i < tokenCount; i++) {\\n address token = tokenManager.tokenByIndex(tokenTypeValue, i);\\n uint256 tokenSupply = IERC20Token(token).totalSupply();\\n\\n\\n if (token == baseToken) {\\n // Adds up directly when the token is USD1\\n liabilities += tokenSupply;\\n } else if (tokenSupply > 0) {\\n uint256 price = oracle.getLatestPrice(token);\\n\\n\\n liabilities += _convert(\\n token,\\n baseToken,\\n tokenSupply,\\n MathUpgradeable.Rounding.Down,\\n price,\\n priceBase,\\n token\\n );\\n }\\n }\\n```\\n\\nSome amount of USDT in both Unitas and InsurancePool is `portfolio`, which represents the current amount of assets used for strategic investments, it is worth noting that after sending `portfolio`, `balance` remains the same, which means `portfolio` is taken into account in the calculation of reserve ratio.\\nThis is problematic because `portfolio` is not available when user redeems, and user may not be able to fully redeem for USDT even when protocols says there is sufficient reserve ratio.\\nLet's assume :\\nUnitas's balance is 10000 USD and its portfolio is 2000 USD, avaliable balance is 8000 USD InsurancePool's balance is 3000 USD and its portfolio is 600 USD, available balance is 2400 USD AllReserves value is 13000 USD Liabilities (USDEMC) value is 10000 USD Reserve Ratio is (10000 + 3000) / 10000 = 130%.\\nLater on, USDEMC appreciates upto 10% and we can get:\\nAllReserves value is still 13000 USD Liabilities (USDEMC) value is 11000 USD Reserve Ratio is (10000 + 3000) / 11000 = 118%.\\nThe available balance in Unitas is 8000 USD so there is 3000 USD in short, it needs to be obtain from InsurancePool, however, the available balance in InsurancePool is 2400 USD, transaction will be reverted and users cannot redeem.\\nThere would also be an extreme situation when reserve ratio is above 100% but there is no available `balance` in protocol because all the `balance` is `portfolio` (this is possible when InsurancePool is drained out), users cannot redeem any USDT in this case.
Portfolio should not be taken into account for the calculation of reserve ratio.\\n```\\n function _getTotalReservesAndCollaterals() internal view returns (uint256 reserves, uint256 collaterals) {\\n // rest of code\\n// Remove the line below\\n uint256 tokenReserve = _getBalance(token);\\n// Add the line below\\n uint256 tokenReserve = _getBalance(token) // Remove the line below\\n _getPortfolio(token);\\n// Remove the line below\\n uint256 tokenCollateral = IInsurancePool(insurancePool).getCollateral(token);\\n// Add the line below\\n uint256 tokenCollateral = IInsurancePool(insurancePool).getCollateral(token) // Remove the line below\\n IInsurancePool(insurancePool).getPortfolio(token);\\n // rest of code\\n }\\n```\\n
Users may not be able to fully redeem USD1 into USDT even when reserve ratio is above 100%, this defeats the purpose of reserve ratio and breaks the promise of the protocol, users may be mislead and lose funds.
```\\n reserveRatio = ScalingUtils.scaleByBases(\\n allReserves * valueBase / liabilities,\\n valueBase,\\n tokenManager.RESERVE_RATIO_BASE()\\n );\\n```\\n
If any stable depegs, oracle will fail, disabling swaps
medium
If any stable depegs, oracle will fail, disabling swaps\\nWhen swapping, the price of the asset/stable is fetched from OracleX. After fetching the price, the deviation is checked in the `_checkPrice` function.\\nIf the price of an asset/stable depegs, the following require will fail:\\n```\\n _require(minPrice <= price && price <= maxPrice, Errors.PRICE_INVALID);\\n```\\n\\nDue to the fail in the deviation, any swapping activity will be disabled by default and transactions will not go through
Use a secondary oracle when the first one fails and wrap the code in a try catch and store the last fetched price in a variable
Core functionality of the protocol will fail to work if any token they fetch depegs and its price goes outside the bounds.
```\\n _require(minPrice <= price && price <= maxPrice, Errors.PRICE_INVALID);\\n```\\n
supplyNativeToken will strand ETH in contract if called after ACTION_DEFER_LIQUIDITY_CHECK
high
supplyNativeToken deposits msg.value to the WETH contract. This is very problematic if it is called after ACTION_DEFER_LIQUIDITY_CHECK. Since onDeferredLiqudityCheck creates a new context msg.value will be 0 and no ETH will actually be deposited for the user, causing funds to be stranded in the contract.\\nTxBuilderExtension.sol#L252-L256\\n```\\nfunction supplyNativeToken(address user) internal nonReentrant {\\n WethInterface(weth).deposit{value: msg.value}();\\n IERC20(weth).safeIncreaseAllowance(address(ironBank), msg.value);\\n ironBank.supply(address(this), user, weth, msg.value);\\n}\\n```\\n\\nsupplyNativeToken uses the context sensitive msg.value to determine how much ETH to send to convert to WETH. After ACTION_DEFER_LIQUIDITY_CHECK is called, it enters a new context in which msg.value is always 0. We can outline the execution path to see where this happens:\\n`execute > executeInteral > deferLiquidityCheck > ironBank.deferLiquidityCheck > onDeferredLiquidityCheck (new context) > executeInternal > supplyNativeToken`\\nWhen IronBank makes it's callback to TxBuilderExtension it creates a new context. Since the ETH is not sent along to this new context, msg.value will always be 0. Which will result in no ETH being deposited and the sent ether is left in the contract.\\nAlthough these funds can be recovered by the admin, it may can easily cause the user to be unfairly liquidated in the meantime since a (potentially significant) portion of their collateral hasn't been deposited. Additionally in conjunction with my other submission on ownable not being initialized correctly, the funds would be completely unrecoverable due to lack of owner.
msg.value should be cached at the beginning of the function to preserve it across contexts
User funds are indefinitely (potentially permanently) stuck in the contract. Users may be unfairly liquidated due to their collateral not depositing.
```\\nfunction supplyNativeToken(address user) internal nonReentrant {\\n WethInterface(weth).deposit{value: msg.value}();\\n IERC20(weth).safeIncreaseAllowance(address(ironBank), msg.value);\\n ironBank.supply(address(this), user, weth, msg.value);\\n}\\n```\\n
PriceOracle.getPrice doesn't check for stale price
medium
PriceOracle.getPrice doesn't check for stale price. As result protocol can make decisions based on not up to date prices, which can cause loses.\\n```\\n function getPriceFromChainlink(address base, address quote) internal view returns (uint256) {\\n (, int256 price,,,) = registry.latestRoundData(base, quote);\\n require(price > 0, "invalid price");\\n\\n // Extend the decimals to 1e18.\\n return uint256(price) * 10 ** (18 - uint256(registry.decimals(base, quote)));\\n }\\n```\\n\\nThis function doesn't check that prices are up to date. Because of that it's possible that price is not outdated which can cause financial loses for protocol.
You need to check that price is not outdated by checking round timestamp.
Protocol can face bad debt.
```\\n function getPriceFromChainlink(address base, address quote) internal view returns (uint256) {\\n (, int256 price,,,) = registry.latestRoundData(base, quote);\\n require(price > 0, "invalid price");\\n\\n // Extend the decimals to 1e18.\\n return uint256(price) * 10 ** (18 - uint256(registry.decimals(base, quote)));\\n }\\n```\\n
PriceOracle will use the wrong price if the Chainlink registry returns price outside min/max range
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.\\nNote there is only a check for `price` to be non-negative, and not within an acceptable range.\\n```\\nfunction getPriceFromChainlink(address base, address quote) internal view returns (uint256) {\\n (, int256 price,,,) = registry.latestRoundData(base, quote);\\n require(price > 0, "invalid price");\\n\\n // Extend the decimals to 1e18.\\n return uint256(price) * 10 ** (18 - uint256(registry.decimals(base, quote)));\\n}\\n```\\n\\nA similar issue is seen here.
Implement the proper check for each asset. It must revert in the case of bad price.\\n```\\nfunction getPriceFromChainlink(address base, address quote) internal view returns (uint256) {\\n (, int256 price,,,) = registry.latestRoundData(base, quote);\\n require(price >= minPrice && price <= maxPrice, "invalid price"); // @audit use the proper minPrice and maxPrice for each asset\\n\\n // Extend the decimals to 1e18.\\n return uint256(price) * 10 ** (18 - uint256(registry.decimals(base, quote)));\\n}\\n```\\n
The wrong price may be returned in the event of a market crash. An adversary will then be able to borrow against the wrong price and incur bad debt to the protocol.
```\\nfunction getPriceFromChainlink(address base, address quote) internal view returns (uint256) {\\n (, int256 price,,,) = registry.latestRoundData(base, quote);\\n require(price > 0, "invalid price");\\n\\n // Extend the decimals to 1e18.\\n return uint256(price) * 10 ** (18 - uint256(registry.decimals(base, quote)));\\n}\\n```\\n
Wrong Price will be Returned When Asset is PToken for WstETH
medium
Iron Bank allows a PToken market to be created for an underlying asset in addition to a lending market. PTokens can be counted as user collaterals and their price is fetched based on their underlying tokens. However, wrong price will return when PToken's underlying asset is WstETH.\\nRetrieving price for WstETH is a 2 step process. WstETH needs to be converted to stETH first, then converted to ETH/USD. This is properly implemented when the market is WstETH through checking `if (asset==wsteth)`. But when PToken market is created for WstETH, this check will by bypassed because PToken contract address will be different from wsteth address.\\nPToken market price is set through `_setAggregators()` in PriceOracle.sol where base and quote token address are set and tested before writing into `aggregators` array. And note that quote token address can either be ETH or USD. When asset price is accessed through `getPrice()`, if the input asset is not `wsteth` address, `aggregators` is directly pulled to get chainlink price denominated in ETH or USD.\\n```\\n//PriceOracle.sol\\n//_setAggregators()\\n require(\\n aggrs[i].quote == Denominations.ETH ||\\n aggrs[i].quote == Denominations.USD,\\n "unsupported quote"\\n );\\n```\\n\\n```\\n//PriceOracle.sol\\n function getPrice(address asset) external view returns (uint256) {\\n if (asset == wsteth) {\\n uint256 stEthPrice = getPriceFromChainlink(\\n steth,\\n Denominations.USD\\n );\\n uint256 stEthPerToken = WstEthInterface(wsteth).stEthPerToken();\\n uint256 wstEthPrice = (stEthPrice * stEthPerToken) / 1e18;\\n return getNormalizedPrice(wstEthPrice, asset);\\n }\\n AggregatorInfo memory aggregatorInfo = aggregators[asset];\\n uint256 price = getPriceFromChainlink(\\n aggregatorInfo.base,\\n aggregatorInfo.quote\\n );\\n // rest of code\\n```\\n\\nThis creates a problem for PToken for WstETH, because `if (asset==wsteth)` will be bypassed and chainlink aggregator price will be returned. And chainlink doesn't have a direct price quote of WstETH/ETH or WstETH/USD, only WstETH/stETH or stETH/USD. This means most likely aggregator price for stETH/USD will be returned as price for WstETH.\\nSince stETH is a rebasing token, and WstETH:stETH is not 1 to 1, this will create a wrong valuation for users holding PToken for WstETH as collaterals.
In `getPrice()`, consider adding another check whether the asset is PToken and its underlying asset is WstETH. If true, use the same bypass for pricing.
Since users holding PToken for WstETH will have wrong valuation, this potentially creates opportunities for malicious over-borrowing or unfair liquidations, putting the protocol at risk.
```\\n//PriceOracle.sol\\n//_setAggregators()\\n require(\\n aggrs[i].quote == Denominations.ETH ||\\n aggrs[i].quote == Denominations.USD,\\n "unsupported quote"\\n );\\n```\\n
Limit swap orders can be used to get a free look into the future
high
Users can cancel their limit swap orders to get a free look into prices in future blocks\\nThis is a part of the same issue that was described in the last contest. The sponsor fixed the bug for `LimitDecrease` and `StopLossDecrease`, but not for `LimitSwap`.\\nAny swap limit order submitted in block range N can't be executed until block range N+2, because the block range is forced to be after the submitted block range, and keepers can't execute until the price has been archived, which necessarily won't be until after block range N+1. Consider what happens when half of the oracle's block ranges are off from the other half, e.g.:\\n```\\n 1 2 3 4 5 6 7 8 9 < block number\\nO1: A B B B B C C C D\\nA A B B B B C C C\\n^^ grouped oracle block ranges\\n```\\n\\nAt block 1, oracles in both groups (O1 and O2) are in the same block range A, and someone submits a large swap limit order (N). At block 6, oracles in O1 are in N+2, but oracles in O2 are still in N+1. This means that the swap limit order will execute at the median price of block 5 (since the earliest group to have archive prices at block 6 for N+1 will be O1) and market swap order submitted at block 6 in the other direction will execute at the median price of block 6 since O2 will be the first group to archive a price range that will contain block 6. By the end of block 5, the price for O1 is known, and the price that O2 will get at block 6 can be predicted with high probability (e.g. if the price has just gapped a few cents), so a trader will know whether the two orders will create a profit or not. If a profit is expected, they'll submit the market order at block 6. If a loss is expected, they'll cancel the swap limit order from block 1, and only have to cover gas fees.\\nEssentially the logic is that limit swap orders will use earlier prices, and market orders (with swaps) will use later prices, and since oracle block ranges aren't fixed, an attacker is able to know both prices before having their orders executed, and use large order sizes to capitalize on small price differences.
Issue Limit swap orders can be used to get a free look into the future\\nAll orders should follow the same block range rules
There is a lot of work involved in calculating statistics about block ranges for oracles and their processing time/queues, and ensuring one gets the prices essentially when the keepers do, but this is likely less work than co-located high frequency traders in traditional finance have to do, and if there's a risk free profit to be made, they'll put in the work to do it every single time, at the expense of all other traders.
```\\n 1 2 3 4 5 6 7 8 9 < block number\\nO1: A B B B B C C C D\\nA A B B B B C C C\\n^^ grouped oracle block ranges\\n```\\n
User can loose funds in case if swapping in DecreaseOrderUtils.processOrder will fail
medium
When user executes decrease order, then he provides `order.minOutputAmount` value, that should protect his from loses. This value is provided with hope that swapping that will take some fees will be executed. But in case if swapping will fail, then this `order.minOutputAmount` value will be smaller then user would like to receive in case when swapping didn't occur. Because of that user can receive less output amount.\\n`DecreaseOrderUtils.processOrder` function executed decrease order and returns order execution result which contains information about output tokens and amounts that user should receive.\\n```\\n try params.contracts.swapHandler.swap(\\n SwapUtils.SwapParams(\\n params.contracts.dataStore,\\n params.contracts.eventEmitter,\\n params.contracts.oracle,\\n Bank(payable(order.market())),\\n params.key,\\n result.outputToken,\\n result.outputAmount,\\n params.swapPathMarkets,\\n 0,\\n order.receiver(),\\n order.uiFeeReceiver(),\\n order.shouldUnwrapNativeToken()\\n )\\n ) returns (address tokenOut, uint256 swapOutputAmount) {\\n `(\\n params.contracts.oracle,\\n tokenOut,\\n swapOutputAmount,\\n order.minOutputAmount()\\n );\\n } catch (bytes memory reasonBytes) {\\n (string memory reason, /* bool hasRevertMessage */) = ErrorUtils.getRevertMessage(reasonBytes);\\n\\n _handleSwapError(\\n params.contracts.oracle,\\n order,\\n result,\\n reason,\\n reasonBytes\\n );\\n }\\n }\\n```\\n\\n```\\n null(\\n Oracle oracle,\\n Order.Props memory order,\\n DecreasePositionUtils.DecreasePositionResult memory result,\\n string memory reason,\\n bytes memory reasonBytes\\n ) internal {\\n emit SwapUtils.SwapReverted(reason, reasonBytes);\\n\\n _validateOutputAmount(\\n oracle,\\n result.outputToken,\\n result.outputAmount,\\n order.minOutputAmount()\\n );\\n\\n MarketToken(payable(order.market())).transferOut(\\n result.outputToken,\\n order.receiver(),\\n result.outputAmount,\\n order.shouldUnwrapNativeToken()\\n );\\n }\\n```\\n\\nAs you can see in this case `_validateOutputAmount` function will be called as well, but it will be called with `result.outputAmount` this time, which is amount provided by decreasing of position.\\nNow i will describe the problem. In case if user wants to swap his token, he knows that he needs to pay fees to the market pools and that this swap will eat some amount of output. So in case if `result.outputAmount` is 100$ worth of tokenA, it's fine if user will provide slippage as 3% if he has long swap path, so his slippage is 97$. But in case when swap will fail, then now this slippage of 97$ is incorrect as user didn't do swapping and he should receiev exactly 100$ worth of tokenA.\\nAlso i should note here, that it's easy to make swap fail for keeper, it's enough for him to just not provide any asset price, so swap reverts. So keeper can benefit on this slippage issue.
Issue User can loose funds in case if swapping in DecreaseOrderUtils.processOrder will fail\\nMaybe it's needed to have another slippage param, that should be used in case of no swapping.
User can be frontruned to receive less amount in case of swapping error.
```\\n try params.contracts.swapHandler.swap(\\n SwapUtils.SwapParams(\\n params.contracts.dataStore,\\n params.contracts.eventEmitter,\\n params.contracts.oracle,\\n Bank(payable(order.market())),\\n params.key,\\n result.outputToken,\\n result.outputAmount,\\n params.swapPathMarkets,\\n 0,\\n order.receiver(),\\n order.uiFeeReceiver(),\\n order.shouldUnwrapNativeToken()\\n )\\n ) returns (address tokenOut, uint256 swapOutputAmount) {\\n `(\\n params.contracts.oracle,\\n tokenOut,\\n swapOutputAmount,\\n order.minOutputAmount()\\n );\\n } catch (bytes memory reasonBytes) {\\n (string memory reason, /* bool hasRevertMessage */) = ErrorUtils.getRevertMessage(reasonBytes);\\n\\n _handleSwapError(\\n params.contracts.oracle,\\n order,\\n result,\\n reason,\\n reasonBytes\\n );\\n }\\n }\\n```\\n
MarketUtils.getFundingAmountPerSizeDelta() has a rounding logical error.
medium
`MarketUtils.getFundingAmountPerSizeDelta()` has a rounding logical error. The main problem is the divisor always use a roundupDivision regardless of the input `roundUp` rounding mode. Actually the correct use should be: the divisor should use the opposite of `roundup` to achieve the same logic of rounding.\\n`MarketUtils.getFundingAmountPerSizeDelta()` is used to calculate the `FundingAmountPerSizeDelta` with a roundup input mode parameter.\\nThis function is used for example by the IncreaseLimit order via flow `OrderHandler.executeOrder() -> _executeOrder() -> OrderUtils.executeOrder() -> processOrder() -> IncreaseOrderUtils.processOrder() -> IncreasePositionUtils.increasePosition() -> PositionUtils.updateFundingAndBorrowingState() -> MarketUtils.updateFundingAmoutPerSize() -> getFundingAmountPerSizeDelta()`.\\nHowever, the main problem is the divisor always use a roundupDivision regardless of the input `roundUp` rounding mode. Actually the correct use should be: the divisor should use the opposite of `roundup` to achieve the same logic of rounding.\\nMy POC code confirms my finding: given fundingAmount = 2e15, openInterest = 1e15+1, and roundup = true, the correct answer should be: 1999999999999998000000000000001999999999999999. However, the implementation returns the wrong solution of : 1000000000000000000000000000000000000000000000. The reason is that the divisor uses a roundup and gets a divisor of 2, as a result, the final result is actually rounded down rather than rounding up!\\n```\\nfunction testGetFundingAmountPerSizeDelta() public{\\n uint result = MarketUtils.getFundingAmountPerSizeDelta(2e15, 1e15+1, true);\\n console2.log("result: %d", result);\\n uint256 correctResult = 2e15 * 1e15 * 1e30 + 1e15; // this is a real round up\\n correctResult = correctResult/(1e15+1);\\n console2.log("correctResult: %d", correctResult);\\n assertTrue(result == 1e15 * 1e30);\\n }\\n```\\n
Change the rounding mode of the divisor to the opposite of the input `roundup` mode. Or, the solution can be just as follows:\\n```\\nfunction getFundingAmountPerSizeDelta(\\n uint256 fundingAmount,\\n uint256 openInterest,\\n bool roundUp\\n ) internal pure returns (uint256) {\\n if (fundingAmount == 0 || openInterest == 0) { return 0; }\\n \\n \\n\\n // how many units in openInterest\\n// Remove the line below\\n uint256 divisor = Calc.roundUpDivision(openInterest, Precision.FLOAT_PRECISION_SQRT);\\n\\n// Remove the line below\\n return Precision.toFactor(fundingAmount, divisor, roundUp);\\n// Add the line below\\n return Precision.toFactor(fundingAmount*Precision.FLOAT_PRECISION_SQRT, openInterest, roundUp\\n }\\n```\\n
MarketUtils.getFundingAmountPerSizeDelta() has a rounding logical error, sometimes, when roundup = true, the result, instead of rounding up, it becomes a rounding down!
```\\nfunction testGetFundingAmountPerSizeDelta() public{\\n uint result = MarketUtils.getFundingAmountPerSizeDelta(2e15, 1e15+1, true);\\n console2.log("result: %d", result);\\n uint256 correctResult = 2e15 * 1e15 * 1e30 + 1e15; // this is a real round up\\n correctResult = correctResult/(1e15+1);\\n console2.log("correctResult: %d", correctResult);\\n assertTrue(result == 1e15 * 1e30);\\n }\\n```\\n
PositionUtils.validatePosition() uses ``isIncrease`` instead of ``false`` when calling isPositionLiquidatable(), making it not work properly for the case of ``isIncrease = true``.
medium
`PositionUtils.validatePosition()` uses `isIncrease` instead of `false` when calling `isPositionLiquidatable()`, making it not work properly for the case of `isIncrease` = true. The main problem is that when calling `isPositionLiquidatable()`, we should always consider decreasing the position since we are proposing a liquidation trade (which is a decrease in position). Therefore, it should not use `isIncrease` for the input parameter for `isPositionLiquidatable()`. We should always use `false` instead.\\n`PositionUtils.validatePosition()` is called to validate whether a position is valid in both collateral size and position size, and in addition, to check if the position is liquidable:\\nIt calls function `isPositionLiquidatable()` to check if a position is liquidable. However, it passes the `isIncrease` to function `isPositionLiquidatable()` as an argument. Actually, the `false` value should always be used for calling function `isPositionLiquidatable()` since a liquidation is always a decrease position operation. A position is liquidable or not has nothing to do with exiting trade operations and only depend on the parameters of the position per se.\\nCurrent implementation has a problem for an increase order: Given a Increase order, for example, increase a position by $200, when `PositionUtils.validatePosition()` is called, which is after the position has been increased, we should not consider another $200 increase in `isPositionLiquidatable()` again as part of the price impact calculation. This is double-accouting for price impact calculation, one during the position increasing process, and another in the position validation process. On the other hand, if we use `false` here, then we are considering a decrease order (since a liquidation is a decrease order) and evaluate the hypothetical price impact if the position will be liquidated.\\nOur POC code confirms my finding: intially, we don't have any positions, after executing a LimitIncrease order, the priceImpactUsd is evaluaed as follows (notice initialDiffUsd = 0):\\nPositionPricingUtils.getPriceImpactUsd started... openInterestParams.longOpenInterest: 0 openInterestParams.shortOpenInterest: 0 initialDiffUsd: 0 nextDiffUsd: 1123456700000000000000000000000 positiveImpactFactor: 50000000000000000000000 negativeImpactFactor: 100000000000000000000000 positiveImpactUsd: 0 negativeImpactUsd: 63107747838744499100000 deltaDiffUsd: 63107747838744499100000 priceImpactUsd: -63107747838744499100000 PositionPricingUtils.getPriceImpactUsd() completed. Initial priceImpactUsd: -63107747838744499100000 Capped priceImpactUsd: -63107747838744499100000\\nThen, during validation, when `PositionUtils.validatePosition()` is called, the double accouting occurs, notice the `nextDiffUsd` is doubled, as if the limitOrder was executed for another time!\\nPositionPricingUtils.getPriceImpactUsd started... openInterestParams.longOpenInterest: 1123456700000000000000000000000 openInterestParams.shortOpenInterest: 0 initialDiffUsd: 1123456700000000000000000000000 nextDiffUsd: 2246913400000000000000000000000 impactFactor: 100000000000000000000000 impactExponentFactor: 2000000000000000000000000000000 deltaDiffUsd: 189323243516233497450000 priceImpactUsd: -189323243516233497450000 priceImpactUsd: -189323243516233497450000 adjusted 2: priceImpactUsd: 0\\nThe POC code is as follows, pay attention to the `testLimit()` and the execution of `createLimitIncreaseOrder()`. Please comment out the checks for signature, timestamp and block number for oracle price in the source code to run the testing smoothly without revert.\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport "forge-std/Test.sol";\\nimport "../contracts/role/RoleStore.sol";\\nimport "../contracts/router/ExchangeRouter.sol";\\nimport "../contracts/data/DataStore.sol";\\nimport "../contracts/referral/ReferralStorage.sol";\\n\\nimport "../contracts/token/IWNT.sol";\\nimport "../contracts/token/WNT.sol";\\nimport "../contracts/token/SOLToken.sol";\\nimport "../contracts/token/USDC.sol";\\nimport "../contracts/token/tokenA.sol";\\nimport "../contracts/token/tokenB.sol";\\nimport "../contracts/token/tokenC.sol";\\n\\nimport "../contracts/market/MarketFactory.sol";\\nimport "../contracts/deposit/DepositUtils.sol";\\nimport "../contracts/oracle/OracleUtils.sol";\\nimport "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";\\nimport "../contracts/withdrawal/WithdrawalUtils.sol";\\nimport "../contracts/order/Order.sol";\\nimport "../contracts/order/BaseOrderUtils.sol";\\nimport "../contracts/price/Price.sol";\\nimport "../contracts/utils/Debug.sol";\\nimport "../contracts/position/Position.sol";\\nimport "../contracts/exchange/LiquidationHandler.sol";\\nimport "../contracts/utils/Calc.sol";\\nimport "@openzeppelin/contracts/utils/math/SignedMath.sol";\\nimport "@openzeppelin/contracts/utils/math/SafeCast.sol";\\n\\n\\ncontract CounterTest is Test, Debug{\\n using SignedMath for int256;\\n using SafeCast for uint256;\\n\\n\\n WNT _wnt; \\n USDC _usdc;\\n SOLToken _sol;\\n tokenA _tokenA;\\n tokenB _tokenB;\\n tokenC _tokenC;\\n\\n RoleStore _roleStore;\\n Router _router;\\n DataStore _dataStore;\\n EventEmitter _eventEmitter;\\n DepositVault _depositVault;\\n OracleStore _oracleStore; \\n Oracle _oracle;\\n DepositHandler _depositHandler;\\n WithdrawalVault _withdrawalVault;\\n WithdrawalHandler _withdrawalHandler;\\n OrderHandler _orderHandler;\\n SwapHandler _swapHandler;\\n LiquidationHandler _liquidationHandler;\\n ReferralStorage _referralStorage;\\n OrderVault _orderVault;\\n ExchangeRouter _erouter;\\n MarketFactory _marketFactory;\\n Market.Props _marketProps1;\\n Market.Props _marketPropsAB;\\n Market.Props _marketPropsBC;\\n Market.Props _marketPropsCwnt;\\n \\n \\n address depositor1;\\n address depositor2;\\n address depositor3;\\n address uiFeeReceiver = address(333);\\n\\n\\n function testGetFundingAmountPerSizeDelta() public{\\n uint result = MarketUtils.getFundingAmountPerSizeDelta(2e15, 1e15+1, true);\\n console2.log("result: %d", result);\\n uint256 correctResult = 2e15 * 1e15 * 1e30 + 1e15; // this is a real round up\\n correctResult = correctResult/(1e15+1);\\n console2.log("correctResult: %d", correctResult);\\n assertTrue(result == 1e15 * 1e30);\\n }\\n\\n \\n\\n function setUp() public {\\n _wnt = new WNT();\\n _usdc = new USDC();\\n _sol = new SOLToken();\\n _tokenA = new tokenA();\\n _tokenB = new tokenB();\\n _tokenC = new tokenC();\\n \\n\\n\\n _roleStore = new RoleStore();\\n _router = new Router(_roleStore);\\n _dataStore = new DataStore(_roleStore);\\n \\n _eventEmitter= new EventEmitter(_roleStore);\\n _depositVault = new DepositVault(_roleStore, _dataStore);\\n _oracleStore = new OracleStore(_roleStore, _eventEmitter);\\n _oracle = new Oracle(_roleStore, _oracleStore);\\n console2.logString("_oracle:"); console2.logAddress(address(_oracle));\\n \\n _depositHandler = new DepositHandler(_roleStore, _dataStore, _eventEmitter, _depositVault, _oracle);\\n console2.logString("_depositHandler:"); console2.logAddress(address(_depositHandler));\\n \\n\\n _withdrawalVault = new WithdrawalVault(_roleStore, _dataStore);\\n _withdrawalHandler = new WithdrawalHandler(_roleStore, _dataStore, _eventEmitter, _withdrawalVault, _oracle);\\n \\n \\n _swapHandler = new SwapHandler(_roleStore);\\n _orderVault = new OrderVault(_roleStore, _dataStore);\\n _referralStorage = new ReferralStorage();\\n\\n\\n \\n _orderHandler = new OrderHandler(_roleStore, _dataStore, _eventEmitter, _orderVault, _oracle, _swapHandler, _referralStorage); \\n _erouter = new ExchangeRouter(_router, _roleStore, _dataStore, _eventEmitter, _depositHandler, _withdrawalHandler, _orderHandler);\\n console2.logString("_erouter:"); console2.logAddress(address(_erouter));\\n _liquidationHandler = new LiquidationHandler(_roleStore, _dataStore, _eventEmitter, _orderVault, _oracle, _swapHandler, _referralStorage);\\n \\n _referralStorage.setHandler(address(_orderHandler), true); \\n\\n /* set myself as the controller so that I can set the address of WNT (wrapped native token contracdt) */\\n _roleStore.grantRole(address(this), Role.CONTROLLER);\\n _roleStore.grantRole(address(this), Role.MARKET_KEEPER);\\n \\n _dataStore.setUint(Keys.MAX_SWAP_PATH_LENGTH, 5); // at most 5 markets in the path\\n \\n _dataStore.setAddress(Keys.WNT, address(_wnt));\\n\\n /* set the token transfer gas limit for wnt as 3200 */\\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_wnt)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_usdc)), 32000); \\n \\n\\n /* create a market (SQL, WNT, ETH, USDC) */\\n _marketFactory = new MarketFactory(_roleStore, _dataStore, _eventEmitter);\\n console2.logString("_marketFactory:"); console2.logAddress(address(_marketFactory));\\n _roleStore.grantRole(address(_marketFactory), Role.CONTROLLER); // to save a market's props\\n _roleStore.grantRole(address(_erouter), Role.CONTROLLER); \\n _roleStore.grantRole(address(_depositHandler), Role.CONTROLLER); \\n _roleStore.grantRole(address(_withdrawalHandler), Role.CONTROLLER); \\n _roleStore.grantRole(address(_swapHandler), Role.CONTROLLER);\\n _roleStore.grantRole(address(_orderHandler), Role.CONTROLLER); \\n _roleStore.grantRole(address(_liquidationHandler), Role.CONTROLLER); \\n _roleStore.grantRole(address(_oracleStore), Role.CONTROLLER); // so it can call EventEmitter\\n _roleStore.grantRole(address(_oracle), Role.CONTROLLER); // so it can call EventEmitter\\n _roleStore.grantRole(address(this), Role.ORDER_KEEPER);\\n _roleStore.grantRole(address(this), Role.LIQUIDATION_KEEPER);\\n\\n \\n _marketProps1 = _marketFactory.createMarket(address(_sol), address(_wnt), address(_usdc), keccak256(abi.encode("sol-wnt-usdc"))); \\n _marketPropsAB = _marketFactory.createMarket(address(0), address(_tokenA), address(_tokenB), keccak256(abi.encode("swap-tokenA-tokenB"))); \\n _marketPropsBC = _marketFactory.createMarket(address(0), address(_tokenB), address(_tokenC), keccak256(abi.encode("swap-tokenB-tokenC"))); \\n _marketPropsCwnt = _marketFactory.createMarket(address(0), address(_tokenC), address(_wnt), keccak256(abi.encode("swap-tokenC-wnt"))); \\n \\n \\n _dataStore.setUint(Keys.minCollateralFactorForOpenInterestMultiplierKey(_marketProps1.marketToken, true), 1e25);\\n _dataStore.setUint(Keys.minCollateralFactorForOpenInterestMultiplierKey(_marketProps1.marketToken, false), 1e25);\\n \\n // see fees for the market\\n _dataStore.setUint(Keys.swapFeeFactorKey(_marketProps1.marketToken), 0.05e30); // 5%\\n _dataStore.setUint(Keys.SWAP_FEE_RECEIVER_FACTOR, 0.5e30);\\n _dataStore.setUint(Keys.positionFeeFactorKey(_marketProps1.marketToken), 0.00001234e30); // 2%\\n _dataStore.setUint(Keys.POSITION_FEE_RECEIVER_FACTOR, 0.15e30);\\n _dataStore.setUint(Keys.MAX_UI_FEE_FACTOR, 0.01e30);\\n _dataStore.setUint(Keys.uiFeeFactorKey(uiFeeReceiver), 0.01e30); // only when this is set, one can receive ui fee, so stealing is not easy\\n _dataStore.setInt(Keys.poolAmountAdjustmentKey(_marketProps1.marketToken, _marketProps1.longToken), 1);\\n _dataStore.setInt(Keys.poolAmountAdjustmentKey(_marketProps1.marketToken, _marketProps1.shortToken), 1);\\n _dataStore.setUint(Keys.swapImpactExponentFactorKey(_marketProps1.marketToken), 10e28);\\n _dataStore.setUint(Keys.swapImpactFactorKey(_marketProps1.marketToken, true), 0.99e30);\\n _dataStore.setUint(Keys.swapImpactFactorKey(_marketProps1.marketToken, false), 0.99e30);\\n\\n \\n \\n \\n // set gas limit to transfer a token\\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_sol)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_wnt)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_usdc)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_tokenA)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_tokenB)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_tokenC)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_marketProps1.marketToken)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_marketPropsAB.marketToken)), 32000);\\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_marketPropsBC.marketToken)), 32000);\\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_marketPropsCwnt.marketToken)), 32000);\\n\\n\\n /* Configure the system parameters/limits here */\\n _dataStore.setUint(Keys.MAX_CALLBACK_GAS_LIMIT, 10000);\\n _dataStore.setUint(Keys.EXECUTION_GAS_FEE_BASE_AMOUNT, 100);\\n _dataStore.setUint(Keys.MAX_ORACLE_PRICE_AGE, 2 hours);\\n _dataStore.setUint(Keys.MIN_ORACLE_BLOCK_CONFIRMATIONS, 3);\\n _dataStore.setUint(Keys.MIN_COLLATERAL_USD, 1e30); // just require $1 as min collateral usd\\n _dataStore.setUint(Keys.reserveFactorKey(_marketProps1.marketToken, true), 5e29); // 50%\\n _dataStore.setUint(Keys.reserveFactorKey(_marketProps1.marketToken, false), 5e29);\\n _dataStore.setUint(Keys.fundingExponentFactorKey(_marketProps1.marketToken), 1.1e30); // 2 in 30 decimals like a square, cube, etc\\n _dataStore.setUint(Keys.fundingFactorKey(_marketProps1.marketToken), 0.0000001e30);\\n _dataStore.setUint(Keys.borrowingFactorKey(_marketProps1.marketToken, true), 0.87e30);\\n _dataStore.setUint(Keys.borrowingFactorKey(_marketProps1.marketToken, false), 0.96e30);\\n _dataStore.setUint(Keys.borrowingExponentFactorKey(_marketProps1.marketToken, true), 2.1e30);\\n _dataStore.setUint(Keys.borrowingExponentFactorKey(_marketProps1.marketToken, false), 2.3e30);\\n _dataStore.setUint(Keys.positionImpactExponentFactorKey(_marketProps1.marketToken), 2e30);\\n _dataStore.setUint(Keys.positionImpactFactorKey(_marketProps1.marketToken, true), 5e22); \\n _dataStore.setUint(Keys.positionImpactFactorKey(_marketProps1.marketToken, false), 1e23);\\n\\n // set the limit of market tokens\\n\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketProps1.marketToken, _marketProps1.longToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketProps1.marketToken, _marketProps1.shortToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsAB.marketToken, _marketPropsAB.longToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsAB.marketToken, _marketPropsAB.shortToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsBC.marketToken, _marketPropsBC.longToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsBC.marketToken, _marketPropsBC.shortToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsCwnt.marketToken, _marketPropsCwnt.longToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsCwnt.marketToken, _marketPropsCwnt.shortToken), 1000e18);\\n \\n \\n // set max open interest for each market\\n _dataStore.setUint(Keys.maxOpenInterestKey(_marketProps1.marketToken, true), 1e39); // 1B $ \\n _dataStore.setUint(Keys.maxOpenInterestKey(_marketProps1.marketToken, false), 1e39); // 1B $\\n\\n _dataStore.setUint(Keys.maxPnlFactorKey(Keys.MAX_PNL_FACTOR_FOR_WITHDRAWALS, _marketProps1.marketToken, true), 10**29); // maxPnlFactor = 10% for long\\n _dataStore.setUint(Keys.maxPnlFactorKey(Keys.MAX_PNL_FACTOR_FOR_WITHDRAWALS, _marketProps1.marketToken, false), 10**29); // maxPnlFactor = 10% for short\\n // _dataStore.setBool(Keys.cancelDepositFeatureDisabledKey(address(_depositHandler)), true);\\n _dataStore.setBool(Keys.cancelOrderFeatureDisabledKey(address(_orderHandler), uint256(Order.OrderType.MarketIncrease)), true);\\n\\n addFourSigners();\\n address(_wnt).call{value: 10000e18}("");\\n depositor1 = address(0x801);\\n depositor2 = address(0x802);\\n depositor3 = address(0x803);\\n\\n // make sure each depositor has some tokens.\\n _wnt.transfer(depositor1, 1000e18);\\n _wnt.transfer(depositor2, 1000e18);\\n _wnt.transfer(depositor3, 1000e18); \\n _usdc.transfer(depositor1, 1000e18);\\n _usdc.transfer(depositor2, 1000e18);\\n _usdc.transfer(depositor3, 1000e18);\\n _tokenA.transfer(depositor1, 1000e18);\\n _tokenB.transfer(depositor1, 1000e18);\\n _tokenC.transfer(depositor1, 1000e18); \\n\\n printAllTokens(); \\n }\\n\\n error Unauthorized(string);\\n // error Error(string);\\n\\n\\nfunction testLimit() public{\\n OracleUtils.SetPricesParams memory priceParams = createSetPricesParams();\\n \\n vm.roll(block.number+2); // block 3\\n\\n \\n bytes32 key = createDepositNoSwap(_marketProps1, depositor1, 90e18, true); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n uint mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n key = createDepositNoSwap(_marketProps1, depositor1, 100e18, false); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n console2.log("Experiment 1 is completed."); \\n \\n // console2.log("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");\\n \\n key = createMarketSwapOrder(depositor1, address(_wnt), 1e15); // create a deposit at block 3 which is within range (2, 6) \\n _orderHandler.executeOrder(key, priceParams); \\n console2.log("Experiment 2 is completed."); \\n \\n\\n console2.log("\\n\\n depositor 1 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor1, _marketProps1.marketToken, _marketProps1.longToken, 20e18, 1001e30, 106000000000000, true); // \\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor1, _marketProps1.marketToken, _marketProps1.longToken, true);\\n console2.log("Experiment 3 is completed."); \\n \\n \\n\\n console2.log("\\n\\n depositor 2 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.longToken, 110e18, 13e30, 101000000000000, false); // 110 usdc as collateral\\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.longToken, false);\\n console2.log("Experiment 4 is completed."); \\n \\n\\n\\n console2.log("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");\\n vm.warp(2 days);\\n setIndexTokenPrice(priceParams, 98, 100); // send 20e18 USDC, increase $13.123 in a long position with trigger price 101\\n key = createLimitIncreaseOrder(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 23e18, 1.1234567e30, 101000000000000, true); // collateral token, usdsize, price\\n console2.log("a LimitIncrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("Experiment 5 is completed.\\n"); \\n \\n\\n // depositor3 creates a LimitDecrease order\\n /*\\n setIndexTokenPrice(priceParams, 120, 125);\\n key = createLimitDecreaseOrder(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 7e18, 58e30, 120000000000000, 120000000000000, true); // retrieve $50? collateral token, usdsize, acceptible price\\n console2.log("a LimitIncrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams); \\n console2.log("Experiment 7 for is completed."); \\n */\\n}\\n\\nfunction testMarketDecrease() public{\\n \\n OracleUtils.SetPricesParams memory priceParams = createSetPricesParams();\\n \\n vm.roll(block.number+2); // block 3\\n\\n \\n bytes32 key = createDepositNoSwap(_marketProps1, depositor1, 90e18, true); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n uint mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n key = createDepositNoSwap(_marketProps1, depositor1, 100e18, false); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n console2.log("Experiment 1 is completed."); \\n \\n \\n \\n \\n console2.log("\\n\\n depositor 2 deposit into marketProps1");\\n key = createDepositNoSwap(_marketProps1, depositor2, 100e18, true);\\n _depositHandler.executeDeposit(key, priceParams);\\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor2);\\n printPoolsAmounts();\\n console2.log("Experiment 2 is completed."); \\n \\n \\n console2.log("\\n\\n depositor 1 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor1, _marketProps1.marketToken, _marketProps1.longToken, 20e18, 1e25, 106000000000000, true); // \\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor1, _marketProps1.marketToken, _marketProps1.longToken, true);\\n console2.log("Experiment 3 is completed."); \\n \\n \\n\\n console2.log("\\n\\n depositor 2 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.longToken, 110e18, 1e25, 101000000000000, false); // 110 usdc as collateral\\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.longToken, false);\\n console2.log("Experiment 4 is completed."); \\n \\n console2.log("********************************************");\\n\\n // deposit 2 will execute a marketDecreaseOrder now\\n key = createMarketDecreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.longToken, 70000000000000, 5e23, false) ; // decrease by 5%\\n console2.log("a market desced order created with key: ");\\n console2.logBytes32(key);\\n console2.log("\\nExecuting the order// rest of code"); \\n setIndexTokenPrice(priceParams, 60, 65); // we have a profit for a short position\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.longToken, false);\\n console2.log("Experiment 5 is completed."); \\n\\n printAllTokens();\\n} \\n\\n \\n\\nfunction testLiquidation() public{\\n // blockrange (2, 6)\\n OracleUtils.SetPricesParams memory priceParams = createSetPricesParams();\\n \\n vm.roll(block.number+2); // block 3\\n\\n \\n bytes32 key = createDepositNoSwap(_marketProps1, depositor1, 90e18, true); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n uint mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n key = createDepositNoSwap(_marketProps1, depositor1, 100e18, false); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n console2.log("Experiment 1 is completed."); \\n \\n \\n \\n \\n console2.log("\\n\\n depositor 2 deposit into marketProps1");\\n key = createDepositNoSwap(_marketProps1, depositor2, 100e18, true);\\n _depositHandler.executeDeposit(key, priceParams);\\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor2);\\n printPoolsAmounts();\\n console2.log("Experiment 2 is completed."); \\n \\n \\n console2.log("\\n\\n depositor 1 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor1, _marketProps1.marketToken, _marketProps1.longToken, 10e18, 1e25, 106000000000000, true);\\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor1, _marketProps1.marketToken, _marketProps1.longToken, true);\\n console2.log("Experiment 3 is completed."); \\n \\n \\n\\n console2.log("\\n\\n depositor 2 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.shortToken, 100e18, 1e25, 101000000000000, false);\\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.shortToken, false);\\n console2.log("Experiment 4 is completed."); \\n \\n \\n\\n // deposit 2 will execute a marketDecreaseOrder now\\n key = createMarketDecreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.shortToken, 106000000000000, 5e23, false) ; // decrease by 5%\\n console2.log("a market desced order created with key: ");\\n console2.logBytes32(key);\\n console2.log("\\nExecuting the order// rest of code"); \\n setIndexTokenPrice(priceParams, 84, 90);\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.shortToken, false);\\n console2.log("Experiment 5 is completed."); \\n \\n \\n\\n \\n // depositor3 will execute a LimitIncrease Order now\\n key = createMarketIncreaseOrder(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 20e18, 200e30, 101000000000000, true); // collateral token, usdsize, price\\n console2.log("a LimitIncrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("Experiment 6 is completed.\\n"); \\n \\n\\n // depositor3 creates a LimitDecrease order\\n setIndexTokenPrice(priceParams, 120, 125);\\n key = createLimitDecreaseOrder(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 7e18, 58e30, 120000000000000, 120000000000000, true); // retrieve $50? collateral token, usdsize, acceptible price\\n console2.log("a LimitIncrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams); \\n console2.log("Experiment 7 for is completed."); \\n \\n // depositor3 creates a stopLossDecrease order\\n setIndexTokenPrice(priceParams, 97, 99);\\n key = createStopLossDecrease(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 7e18, 58e30, 95000000000000, 92000000000000, true); // retrieve $50? collateral token, usdsize, acceptible price\\n console2.log("a StopLossDecrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n // Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams);\\n console2.log("Experiment 8 is completed."); \\n \\n \\n console2.log("\\n\\n*************************************************\\n\\n");\\n\\n\\n // depositor3 creates a Liquidation order\\n setIndexTokenPrice(priceParams, 75, 75);\\n console2.log("Liquidate a position// rest of code");\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n _liquidationHandler.executeLiquidation(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true, priceParams);\\n console2.log("Experiment 9 is completed."); \\n \\n\\n // printPoolsAmounts();\\n printAllTokens();\\n\\n \\n \\n \\n}\\n\\nfunction printAllTokens() startedCompleted("printAllTokens") public\\n{\\n console2.log("\\nTokens used in this test:");\\n console2.log("_wnt: "); console2.logAddress(address(_wnt));\\n console2.log("_usdc: "); console2.logAddress(address(_usdc));\\n console2.log("_sol: "); console2.logAddress(address(_sol));\\n console2.log("_tokenA: "); console2.logAddress(address(_tokenA));\\n console2.log("_tokenB: "); console2.logAddress(address(_tokenB));\\n console2.log("_tokenC: "); console2.logAddress(address(_tokenC));\\n console2.logString("test contract address:"); console2.logAddress(address(this));\\n \\n console2.log("_marketProps1 market token: "); console2.logAddress(address(_marketProps1.marketToken));\\n console2.log("_marketPropsAB market token: "); console2.logAddress(address(_marketPropsAB.marketToken));\\n console2.log("_marketPropsBC market token: "); console2.logAddress(address(_marketPropsBC.marketToken));\\n console2.log("_marketProps1Cwnt market token: "); console2.logAddress(address(_marketPropsCwnt.marketToken));\\n console2.log("\\n");\\n \\n \\n}\\n\\n\\nfunction printMarketTokenAmount() public \\n{ console2.log("Market token address: ");\\n console2.logAddress(address(_marketProps1.marketToken));\\n console2.log("depositor1 market token amount: %d", IERC20(_marketProps1.marketToken).balanceOf(depositor1));\\n console2.log("depositor2 market token amount: %d", IERC20(_marketProps1.marketToken).balanceOf(depositor2));\\n console2.log("depositor3 market token amount: %d", IERC20(_marketProps1.marketToken).balanceOf(depositor3));\\n}\\n\\nfunction printLongShortTokens(address account) public\\n{\\n console2.log("balance for "); console2.logAddress(account);\\n console2.log("_wnt balance:", _wnt.balanceOf(account));\\n console2.log("usdc balance:", _usdc.balanceOf(account));\\n}\\n\\n\\n\\n\\nfunction addFourSigners() private {\\n _oracleStore.addSigner(address(901));\\n _oracleStore.addSigner(address(902)); \\n _oracleStore.addSigner(address(903)); \\n _oracleStore.addSigner(address(904)); \\n}\\n\\n\\nfunction setIndexTokenPrice(OracleUtils.SetPricesParams memory priceParams, uint256 minP, uint256 maxP) public\\n{\\n uint256 mask1 = ~uint256(type(uint96).max); // (32*3 of 1's)\\n console2.logBytes32(bytes32(mask1));\\n\\n uint256 minPrice = minP;\\n minPrice = minPrice << 32 | minP;\\n minPrice = minPrice << 32 | minP;\\n\\n uint256 maxPrice = maxP;\\n maxPrice = maxPrice << 32 | maxP;\\n maxPrice = maxPrice << 32 | maxP;\\n\\n priceParams.compactedMinPrices[0] = (priceParams.compactedMinPrices[0] & mask1) | minPrice;\\n priceParams.compactedMaxPrices[0] = (priceParams.compactedMaxPrices[0] & mask1) | maxPrice;\\n}\\n\\n\\nfunction createSetPricesParams() public returns (OracleUtils.SetPricesParams memory) {\\n uint256 signerInfo = 3; // signer 904\\n signerInfo = signerInfo << 16 | 2; // signer 903\\n signerInfo = signerInfo << 16 | 1; // signer 902\\n signerInfo = signerInfo << 16 | 3; // number of singers\\n // will read out as 902, 903, 904 from the lowest first\\n\\n // the number of tokens, 6\\n address[] memory tokens = new address[](6);\\n tokens[0] = address(_sol);\\n tokens[1] = address(_wnt);\\n tokens[2] = address(_usdc);\\n tokens[3] = address(_tokenA);\\n tokens[4] = address(_tokenB);\\n tokens[5] = address(_tokenC);\\n\\n // must be equal to the number of tokens 6, 64 for each one, so 64*6. 64*4 for one element, so need two elements \\n uint256[] memory compactedMinOracleBlockNumbers = new uint256[](2);\\n compactedMinOracleBlockNumbers[0] = block.number+1;\\n compactedMinOracleBlockNumbers[0] = compactedMinOracleBlockNumbers[0] << 64 | block.number+1;\\n compactedMinOracleBlockNumbers[0] = compactedMinOracleBlockNumbers[0] << 64 | block.number+1;\\n compactedMinOracleBlockNumbers[0] = compactedMinOracleBlockNumbers[0] << 64 | block.number+1;\\n\\n compactedMinOracleBlockNumbers[1] = block.number+1;\\n compactedMinOracleBlockNumbers[1] = compactedMinOracleBlockNumbers[0] << 64 | block.number+1;\\n \\n // must be equal to the number of tokens 6, 64 for each one, so 64*6. 64*4 for one element, so need two elements \\n \\n uint256[] memory compactedMaxOracleBlockNumbers = new uint256[](2);\\n compactedMaxOracleBlockNumbers[0] = block.number+5; \\n compactedMaxOracleBlockNumbers[0] = compactedMaxOracleBlockNumbers[0] << 64 | block.number+5;\\n compactedMaxOracleBlockNumbers[0] = compactedMaxOracleBlockNumbers[0] << 64 | block.number+5; \\n compactedMaxOracleBlockNumbers[0] = compactedMaxOracleBlockNumbers[0] << 64 | block.number+5; \\n\\n compactedMaxOracleBlockNumbers[1] = block.number+5; \\n compactedMaxOracleBlockNumbers[1] = compactedMaxOracleBlockNumbers[0] << 64 | block.number+5;\\n\\n // must be equal to the number of tokens 6, 64 for each one, so 64*6. 64*4 for one element, so need two elements \\n uint256[] memory compactedOracleTimestamps = new uint256[](2);\\n compactedOracleTimestamps[0] = 9;\\n compactedOracleTimestamps[0] = compactedOracleTimestamps[0] << 64 | 8;\\n compactedOracleTimestamps[0] = compactedOracleTimestamps[0] << 64 | 7;\\n compactedOracleTimestamps[0] = compactedOracleTimestamps[0] << 64 | 7;\\n \\n compactedOracleTimestamps[1] = 9;\\n compactedOracleTimestamps[1] = compactedOracleTimestamps[0] << 64 | 8;\\n \\n\\n // must be equal to the number of tokens, 8 for each, so 8*6= 48, only need one element\\n uint256[] memory compactedDecimals = new uint256[](1);\\n compactedDecimals[0] = 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n \\n \\n // three signers, 6 tokens, so we have 3*6 = 18 entries, each entry takes 32 bits, so each 8 entries takes one element, we need 3 elements\\n // price table:\\n // SOL: 100 101 102\\n // wnt: 200 201 203\\n // USDC 1 1 1\\n // tokenA 100 101 102\\n // tokenB 200 202 204\\n // tokenC 400 404 408\\n\\n uint256[] memory compactedMinPrices = new uint256[](3);\\n compactedMinPrices[2] = 408; \\n compactedMinPrices[2] = compactedMinPrices[2] << 32 | 404;\\n\\n compactedMinPrices[1] = 400;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 204;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 202;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 200;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 102;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 101;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 100;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 1;\\n \\n compactedMinPrices[0] = 1;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 1;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 203;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 201;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 200;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 102;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 101;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 100;\\n \\n // three signers, 6 tokens, so we have 3*6 = 18 entries, each entry takes 8 bits, so we just need one element\\n\\n uint256[] memory compactedMinPricesIndexes = new uint256[](1);\\n compactedMinPricesIndexes[0] = 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0; \\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0; \\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0; \\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0; \\n \\n // three signers, 6 tokens, so we have 3*6 = 18 entries, each entry takes 32 bits, so each 8 entries takes one element, we need 3 elements\\n // price table:\\n // SOL: 105 106 107\\n // wnt: 205 206 208\\n // USDC 1 1 1\\n // tokenA 105 106 107\\n // tokenB 205 207 209\\n // tokenC 405 409 413\\n uint256[] memory compactedMaxPrices = new uint256[](3);\\n compactedMaxPrices[2] = 413;\\n compactedMaxPrices[2] = compactedMaxPrices[2] << 32 | 409;\\n \\n compactedMaxPrices[1] = 405;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 209;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 207;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 205;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 107;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 106;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 105;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 1;\\n\\n compactedMaxPrices[0] = 1;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 1;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 208;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 206; \\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 205; \\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 107;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 106;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 105;\\n \\n \\n // three signers, 6 tokens, so we have 3*6 = 18 entries, each entry takes 8 bits, so we just need one element\\n\\n uint256[] memory compactedMaxPricesIndexes = new uint256[](1);\\n compactedMaxPricesIndexes[0] = 1; \\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n \\n // 3 signers and 6 tokens, so we need 3*6 signatures\\n bytes[] memory signatures = new bytes[](18);\\n for(uint i; i<18; i++){\\n signatures[i] = abi.encode("SIGNATURE");\\n }\\n address[] memory priceFeedTokens;\\n\\n OracleUtils.SetPricesParams memory priceParams = OracleUtils.SetPricesParams(\\n signerInfo,\\n tokens,\\n compactedMinOracleBlockNumbers,\\n compactedMaxOracleBlockNumbers,\\n compactedOracleTimestamps,\\n compactedDecimals,\\n compactedMinPrices, \\n compactedMinPricesIndexes,\\n compactedMaxPrices, \\n compactedMaxPricesIndexes, \\n signatures, \\n priceFeedTokens\\n );\\n return priceParams;\\n}\\n\\n/* \\n* The current index token price (85, 90), a trader sets a trigger price to 100 and then acceptabiel price to 95.\\n* He like to long the index token. \\n* 1. Pick the primary price 90 since we long, so choose the max\\n* 2. Make sure 90 < 100, and pick (90, 100) as the custom price since we long\\n* 3. Choose price 95 since 95 is within the range, and it is the highest acceptible price. Choosing 90 \\n* will be in favor of the trader\\n* \\n*/\\n\\nfunction createMarketSwapOrder(address account, address inputToken, uint256 inAmount) public returns(bytes32)\\n{ \\n address[] memory swapPath = new address[](1);\\n swapPath[0] = _marketProps1.marketToken;\\n // swapPath[0] = _marketPropsAB.marketToken;\\n // swapPath[1] = _marketPropsBC.marketToken;\\n // swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account; // the account is the receiver\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = account; // set myself as the ui receiver\\n // params.addresses.market = marketToken;\\n params.addresses.initialCollateralToken = inputToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n // params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n params.numbers.initialCollateralDeltaAmount = inAmount ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(inputToken).transfer(address(_orderVault), inAmount); // this is the real amount\\n\\n\\n // params.numbers.triggerPrice = triggerPrice;\\n // params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n // params.numbers.initialCollateralDeltaAmount = inAmount;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.MarketSwap;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n // params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n}\\n\\n\\n\\nfunction createLiquidationOrder(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint triggerPrice, uint256 acceptablePrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = triggerPrice;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.Liquidation;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\nfunction createStopLossDecrease(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint triggerPrice, uint256 acceptablePrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = triggerPrice;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.StopLossDecrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\nfunction createLimitDecreaseOrder(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint triggerPrice, uint256 acceptablePrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = triggerPrice;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.LimitDecrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\nfunction createLimitIncreaseOrder(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint triggerPrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = triggerPrice; // used for limit order\\n params.numbers.acceptablePrice = 121000000000000; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.LimitIncrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\n\\nfunction createMarketDecreaseOrder(address account, address marketToken, address collateralToken, uint256 acceptablePrice, uint256 sizeInUsd, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeInUsd; // how much dollar to decrease, will convert into amt of tokens to decrease in long/short based on the execution price\\n params.numbers.initialCollateralDeltaAmount = 13e18; // this is actually useless, will be overidden by real transfer amount\\n // vm.prank(account); \\n // IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = 0;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 10e18; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.MarketDecrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\nfunction createMarketIncreaseOrder(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint acceptablePrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = 0;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.MarketIncrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\nfunction createWithdraw(address withdrawor, uint marketTokenAmount) public returns (bytes32)\\n{\\n address[] memory longTokenSwapPath;\\n address[] memory shortTokenSwapPath;\\n\\n console.log("createWithdraw with withdrawor: ");\\n console.logAddress(withdrawor);\\n vm.prank(withdrawor); \\n _wnt.transfer(address(_withdrawalVault), 3200); // execution fee\\n\\n vm.prank(withdrawor);\\n ERC20(_marketProps1.marketToken).transfer(address(_withdrawalVault), marketTokenAmount);\\n\\n WithdrawalUtils.CreateWithdrawalParams memory params = WithdrawalUtils.CreateWithdrawalParams(\\n withdrawor, // receiver\\n address(0), // call back function\\n uiFeeReceiver, // uiFeeReceiver\\n _marketProps1.marketToken, // which market token to withdraw\\n longTokenSwapPath,\\n shortTokenSwapPath,\\n 123, // minLongTokenAmount\\n 134, // minShortTokenAmount\\n false, // shouldUnwrapNativeToken\\n 3200, // execution fee\\n 3200 // callback gas limit\\n );\\n\\n vm.prank(withdrawor);\\n bytes32 key = _erouter.createWithdrawal(params);\\n return key;\\n}\\n\\n\\nfunction createDepositNoSwap(Market.Props memory marketProps, address depositor, uint amount, bool isLong) public returns (bytes32){\\n address[] memory longTokenSwapPath;\\n address[] memory shortTokenSwapPath;\\n\\n console.log("createDeposit with depositor: ");\\n console.logAddress(depositor);\\n\\n vm.prank(depositor);\\n _wnt.transfer(address(_depositVault), 3200); // execution fee\\n if(isLong){\\n console2.log("000000000000000000");\\n vm.prank(depositor);\\n IERC20(marketProps.longToken).transfer(address(_depositVault), amount); \\n console2.log("bbbbbbbbbbbbbbbbbbbbbb");\\n }\\n else {\\n console2.log("111111111111111111111111");\\n console2.log("deposit balance: %d, %d", IERC20(marketProps.shortToken).balanceOf(depositor), amount);\\n vm.prank(depositor);\\n IERC20(marketProps.shortToken).transfer(address(_depositVault), amount);\\n console2.log("qqqqqqqqqqqqqqqqqq");\\n }\\n \\n\\n DepositUtils.CreateDepositParams memory params = DepositUtils.CreateDepositParams(\\n depositor,\\n address(0),\\n uiFeeReceiver,\\n marketProps.marketToken,\\n marketProps.longToken,\\n marketProps.shortToken,\\n longTokenSwapPath,\\n shortTokenSwapPath,\\n 100000, // minMarketTokens\\n true,\\n 3200, // execution fee\\n 3200 // call back gas limit\\n );\\n\\n console2.log("aaaaaaaaaaaaaaaaaaaaaaaaa");\\n vm.prank(depositor);\\n bytes32 key1 = _erouter.createDeposit(params);\\n\\n return key1;\\n}\\n\\n/*\\nfunction testCancelDeposit() public \\n{\\n address[] memory longTokenSwapPath;\\n address[] memory shortTokenSwapPath;\\n\\n address(_wnt).call{value: 100e8}("");\\n _wnt.transfer(address(_depositVault), 1e6);\\n DepositUtils.CreateDepositParams memory params = DepositUtils.CreateDepositParams(\\n msg.sender,\\n address(0),\\n address(111),\\n _marketProps1.marketToken,\\n _marketProps1.longToken,\\n _marketProps1.shortToken,\\n longTokenSwapPath,\\n shortTokenSwapPath,\\n 100000, // minMarketTokens\\n true,\\n 3200, // execution fee\\n 3200 // call back gas limit\\n );\\n\\n bytes32 key1 = _erouter.createDeposit(params);\\n\\n console.log("WNT balance of address(222) before cancelllation: %s", _wnt.balanceOf(address(222)));\\n console.log("WNT balance of address(this) before cancelllation: %s", _wnt.balanceOf(address(this))); \\n\\n _roleStore.grantRole(address(222), Role.CONTROLLER); // to save a market's props\\n vm.prank(address(222));\\n _depositHandler.cancelDeposit(key1);\\n console.log("WNT balance of address(222) after cancelllation: %s", _wnt.balanceOf(address(222)));\\n console.log("WNT balance of address(this) after cancelllation: %s", _wnt.balanceOf(address(this))); \\n}\\n*/\\n\\nfunction testERC165() public{\\n bool yes = _wnt.supportsInterface(type(IWNT).interfaceId);\\n console2.log("wnt suppports deposit?");\\n console2.logBool(yes);\\n vm.expectRevert();\\n yes = IERC165(address(_sol)).supportsInterface(type(IWNT).interfaceId);\\n console2.logBool(yes);\\n\\n if(ERC165Checker.supportsERC165(address(_wnt))){\\n console2.log("_wnt supports ERC165");\\n }\\n if(ERC165Checker.supportsERC165(address(_sol))){\\n console2.log("_sol supports ERC165");\\n }\\n}\\n\\n function justError() external {\\n // revert Unauthorized("abcdefg"); // 973d02cb\\n // revert("abcdefg"); // 0x08c379a, Error selector\\n // require(false, "abcdefg"); // 0x08ce79a, Error selector\\n assert(3 == 4); // Panic: 0x4e487b71\\n }\\n\\n function testErrorMessage() public{\\n\\n try this.justError(){} \\n catch (bytes memory reasonBytes) {\\n (string memory msg, bool ok ) = ErrorUtils.getRevertMessage(reasonBytes);\\n console2.log("Error Message: "); console2.logString(msg);\\n console2.log("error?"); console2.logBool(ok);\\n } \\n }\\n\\n \\n function printAddresses() public{\\n console2.log("_orderVault:"); console2.logAddress(address(_orderVault));\\n console2.log("marketToken:"); console2.logAddress(address(_marketProps1.marketToken));\\n } \\n\\n function printPoolsAmounts() public{\\n console2.log("\\n The summary of pool amounts: ");\\n \\n uint256 amount = MarketUtils.getPoolAmount(_dataStore, _marketProps1, _marketProps1.longToken);\\n console2.log("Market: _marketProps1, token: long/nwt, amount: %d", amount);\\n amount = MarketUtils.getPoolAmount(_dataStore, _marketProps1, _marketProps1.shortToken);\\n console2.log("Market: _marketProps1, token: short/USDC, amount: %d", amount);\\n \\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsAB, _marketPropsAB.longToken);\\n console2.log("Market: _marketPropsAB, token: long/A, amount: %d", amount);\\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsAB, _marketPropsAB.shortToken);\\n console2.log("Market: _marketPropsAB, token: short/B, amount: %d", amount);\\n \\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsBC, _marketPropsBC.longToken);\\n console2.log("Market: _marketPropsBC, token: long/B, amount:%d", amount);\\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsBC, _marketPropsBC.shortToken);\\n console2.log("Market: _marketPropsBC, token: short/C, amount: %d", amount);\\n \\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsCwnt, _marketPropsCwnt.longToken);\\n console2.log("Market: _marketPropsCwnt, token: long/C, amount: %d", amount);\\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsCwnt, _marketPropsCwnt.shortToken);\\n console2.log("Market: _marketPropsCwnt, token: short/wnt, amount: %d", amount);\\n \\n\\n console2.log("\\n");\\n }\\n \\n}\\n```\\n
Pass false always to isPositionLiquidatable():\\n```\\n function validatePosition(\\n DataStore dataStore,\\n IReferralStorage referralStorage,\\n Position.Props memory position,\\n Market.Props memory market,\\n MarketUtils.MarketPrices memory prices,\\n bool isIncrease,\\n bool shouldValidateMinPositionSize,\\n bool shouldValidateMinCollateralUsd\\n ) public view {\\n if (position.sizeInUsd() == 0 || position.sizeInTokens() == 0) {\\n revert Errors.InvalidPositionSizeValues(position.sizeInUsd(), position.sizeInTokens());\\n }\\n\\n MarketUtils.validateEnabledMarket(dataStore, market.marketToken);\\n MarketUtils.validateMarketCollateralToken(market, position.collateralToken());\\n\\n if (shouldValidateMinPositionSize) {\\n uint256 minPositionSizeUsd = dataStore.getUint(Keys.MIN_POSITION_SIZE_USD);\\n if (position.sizeInUsd() < minPositionSizeUsd) {\\n revert Errors.MinPositionSize(position.sizeInUsd(), minPositionSizeUsd);\\n }\\n }\\n\\n if (isPositionLiquidatable(\\n dataStore,\\n referralStorage,\\n position,\\n market,\\n prices,\\n// Remove the line below\\n isIncrease,\\n// Add the line below\\n false,\\n shouldValidateMinCollateralUsd\\n )) {\\n revert Errors.LiquidatablePosition();\\n }\\n }\\n```\\n
PositionUtils.validatePosition() uses `isIncrease` instead of `false` when calling isPositionLiquidatable(), making it not work properly for the case of `isIncrease` = true. A liquidation should always be considered as a decrease order in terms of evaluating price impact.
```\\n// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport "forge-std/Test.sol";\\nimport "../contracts/role/RoleStore.sol";\\nimport "../contracts/router/ExchangeRouter.sol";\\nimport "../contracts/data/DataStore.sol";\\nimport "../contracts/referral/ReferralStorage.sol";\\n\\nimport "../contracts/token/IWNT.sol";\\nimport "../contracts/token/WNT.sol";\\nimport "../contracts/token/SOLToken.sol";\\nimport "../contracts/token/USDC.sol";\\nimport "../contracts/token/tokenA.sol";\\nimport "../contracts/token/tokenB.sol";\\nimport "../contracts/token/tokenC.sol";\\n\\nimport "../contracts/market/MarketFactory.sol";\\nimport "../contracts/deposit/DepositUtils.sol";\\nimport "../contracts/oracle/OracleUtils.sol";\\nimport "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";\\nimport "../contracts/withdrawal/WithdrawalUtils.sol";\\nimport "../contracts/order/Order.sol";\\nimport "../contracts/order/BaseOrderUtils.sol";\\nimport "../contracts/price/Price.sol";\\nimport "../contracts/utils/Debug.sol";\\nimport "../contracts/position/Position.sol";\\nimport "../contracts/exchange/LiquidationHandler.sol";\\nimport "../contracts/utils/Calc.sol";\\nimport "@openzeppelin/contracts/utils/math/SignedMath.sol";\\nimport "@openzeppelin/contracts/utils/math/SafeCast.sol";\\n\\n\\ncontract CounterTest is Test, Debug{\\n using SignedMath for int256;\\n using SafeCast for uint256;\\n\\n\\n WNT _wnt; \\n USDC _usdc;\\n SOLToken _sol;\\n tokenA _tokenA;\\n tokenB _tokenB;\\n tokenC _tokenC;\\n\\n RoleStore _roleStore;\\n Router _router;\\n DataStore _dataStore;\\n EventEmitter _eventEmitter;\\n DepositVault _depositVault;\\n OracleStore _oracleStore; \\n Oracle _oracle;\\n DepositHandler _depositHandler;\\n WithdrawalVault _withdrawalVault;\\n WithdrawalHandler _withdrawalHandler;\\n OrderHandler _orderHandler;\\n SwapHandler _swapHandler;\\n LiquidationHandler _liquidationHandler;\\n ReferralStorage _referralStorage;\\n OrderVault _orderVault;\\n ExchangeRouter _erouter;\\n MarketFactory _marketFactory;\\n Market.Props _marketProps1;\\n Market.Props _marketPropsAB;\\n Market.Props _marketPropsBC;\\n Market.Props _marketPropsCwnt;\\n \\n \\n address depositor1;\\n address depositor2;\\n address depositor3;\\n address uiFeeReceiver = address(333);\\n\\n\\n function testGetFundingAmountPerSizeDelta() public{\\n uint result = MarketUtils.getFundingAmountPerSizeDelta(2e15, 1e15+1, true);\\n console2.log("result: %d", result);\\n uint256 correctResult = 2e15 * 1e15 * 1e30 + 1e15; // this is a real round up\\n correctResult = correctResult/(1e15+1);\\n console2.log("correctResult: %d", correctResult);\\n assertTrue(result == 1e15 * 1e30);\\n }\\n\\n \\n\\n function setUp() public {\\n _wnt = new WNT();\\n _usdc = new USDC();\\n _sol = new SOLToken();\\n _tokenA = new tokenA();\\n _tokenB = new tokenB();\\n _tokenC = new tokenC();\\n \\n\\n\\n _roleStore = new RoleStore();\\n _router = new Router(_roleStore);\\n _dataStore = new DataStore(_roleStore);\\n \\n _eventEmitter= new EventEmitter(_roleStore);\\n _depositVault = new DepositVault(_roleStore, _dataStore);\\n _oracleStore = new OracleStore(_roleStore, _eventEmitter);\\n _oracle = new Oracle(_roleStore, _oracleStore);\\n console2.logString("_oracle:"); console2.logAddress(address(_oracle));\\n \\n _depositHandler = new DepositHandler(_roleStore, _dataStore, _eventEmitter, _depositVault, _oracle);\\n console2.logString("_depositHandler:"); console2.logAddress(address(_depositHandler));\\n \\n\\n _withdrawalVault = new WithdrawalVault(_roleStore, _dataStore);\\n _withdrawalHandler = new WithdrawalHandler(_roleStore, _dataStore, _eventEmitter, _withdrawalVault, _oracle);\\n \\n \\n _swapHandler = new SwapHandler(_roleStore);\\n _orderVault = new OrderVault(_roleStore, _dataStore);\\n _referralStorage = new ReferralStorage();\\n\\n\\n \\n _orderHandler = new OrderHandler(_roleStore, _dataStore, _eventEmitter, _orderVault, _oracle, _swapHandler, _referralStorage); \\n _erouter = new ExchangeRouter(_router, _roleStore, _dataStore, _eventEmitter, _depositHandler, _withdrawalHandler, _orderHandler);\\n console2.logString("_erouter:"); console2.logAddress(address(_erouter));\\n _liquidationHandler = new LiquidationHandler(_roleStore, _dataStore, _eventEmitter, _orderVault, _oracle, _swapHandler, _referralStorage);\\n \\n _referralStorage.setHandler(address(_orderHandler), true); \\n\\n /* set myself as the controller so that I can set the address of WNT (wrapped native token contracdt) */\\n _roleStore.grantRole(address(this), Role.CONTROLLER);\\n _roleStore.grantRole(address(this), Role.MARKET_KEEPER);\\n \\n _dataStore.setUint(Keys.MAX_SWAP_PATH_LENGTH, 5); // at most 5 markets in the path\\n \\n _dataStore.setAddress(Keys.WNT, address(_wnt));\\n\\n /* set the token transfer gas limit for wnt as 3200 */\\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_wnt)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_usdc)), 32000); \\n \\n\\n /* create a market (SQL, WNT, ETH, USDC) */\\n _marketFactory = new MarketFactory(_roleStore, _dataStore, _eventEmitter);\\n console2.logString("_marketFactory:"); console2.logAddress(address(_marketFactory));\\n _roleStore.grantRole(address(_marketFactory), Role.CONTROLLER); // to save a market's props\\n _roleStore.grantRole(address(_erouter), Role.CONTROLLER); \\n _roleStore.grantRole(address(_depositHandler), Role.CONTROLLER); \\n _roleStore.grantRole(address(_withdrawalHandler), Role.CONTROLLER); \\n _roleStore.grantRole(address(_swapHandler), Role.CONTROLLER);\\n _roleStore.grantRole(address(_orderHandler), Role.CONTROLLER); \\n _roleStore.grantRole(address(_liquidationHandler), Role.CONTROLLER); \\n _roleStore.grantRole(address(_oracleStore), Role.CONTROLLER); // so it can call EventEmitter\\n _roleStore.grantRole(address(_oracle), Role.CONTROLLER); // so it can call EventEmitter\\n _roleStore.grantRole(address(this), Role.ORDER_KEEPER);\\n _roleStore.grantRole(address(this), Role.LIQUIDATION_KEEPER);\\n\\n \\n _marketProps1 = _marketFactory.createMarket(address(_sol), address(_wnt), address(_usdc), keccak256(abi.encode("sol-wnt-usdc"))); \\n _marketPropsAB = _marketFactory.createMarket(address(0), address(_tokenA), address(_tokenB), keccak256(abi.encode("swap-tokenA-tokenB"))); \\n _marketPropsBC = _marketFactory.createMarket(address(0), address(_tokenB), address(_tokenC), keccak256(abi.encode("swap-tokenB-tokenC"))); \\n _marketPropsCwnt = _marketFactory.createMarket(address(0), address(_tokenC), address(_wnt), keccak256(abi.encode("swap-tokenC-wnt"))); \\n \\n \\n _dataStore.setUint(Keys.minCollateralFactorForOpenInterestMultiplierKey(_marketProps1.marketToken, true), 1e25);\\n _dataStore.setUint(Keys.minCollateralFactorForOpenInterestMultiplierKey(_marketProps1.marketToken, false), 1e25);\\n \\n // see fees for the market\\n _dataStore.setUint(Keys.swapFeeFactorKey(_marketProps1.marketToken), 0.05e30); // 5%\\n _dataStore.setUint(Keys.SWAP_FEE_RECEIVER_FACTOR, 0.5e30);\\n _dataStore.setUint(Keys.positionFeeFactorKey(_marketProps1.marketToken), 0.00001234e30); // 2%\\n _dataStore.setUint(Keys.POSITION_FEE_RECEIVER_FACTOR, 0.15e30);\\n _dataStore.setUint(Keys.MAX_UI_FEE_FACTOR, 0.01e30);\\n _dataStore.setUint(Keys.uiFeeFactorKey(uiFeeReceiver), 0.01e30); // only when this is set, one can receive ui fee, so stealing is not easy\\n _dataStore.setInt(Keys.poolAmountAdjustmentKey(_marketProps1.marketToken, _marketProps1.longToken), 1);\\n _dataStore.setInt(Keys.poolAmountAdjustmentKey(_marketProps1.marketToken, _marketProps1.shortToken), 1);\\n _dataStore.setUint(Keys.swapImpactExponentFactorKey(_marketProps1.marketToken), 10e28);\\n _dataStore.setUint(Keys.swapImpactFactorKey(_marketProps1.marketToken, true), 0.99e30);\\n _dataStore.setUint(Keys.swapImpactFactorKey(_marketProps1.marketToken, false), 0.99e30);\\n\\n \\n \\n \\n // set gas limit to transfer a token\\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_sol)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_wnt)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_usdc)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_tokenA)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_tokenB)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_tokenC)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_marketProps1.marketToken)), 32000); \\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_marketPropsAB.marketToken)), 32000);\\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_marketPropsBC.marketToken)), 32000);\\n _dataStore.setUint(Keys.tokenTransferGasLimit(address(_marketPropsCwnt.marketToken)), 32000);\\n\\n\\n /* Configure the system parameters/limits here */\\n _dataStore.setUint(Keys.MAX_CALLBACK_GAS_LIMIT, 10000);\\n _dataStore.setUint(Keys.EXECUTION_GAS_FEE_BASE_AMOUNT, 100);\\n _dataStore.setUint(Keys.MAX_ORACLE_PRICE_AGE, 2 hours);\\n _dataStore.setUint(Keys.MIN_ORACLE_BLOCK_CONFIRMATIONS, 3);\\n _dataStore.setUint(Keys.MIN_COLLATERAL_USD, 1e30); // just require $1 as min collateral usd\\n _dataStore.setUint(Keys.reserveFactorKey(_marketProps1.marketToken, true), 5e29); // 50%\\n _dataStore.setUint(Keys.reserveFactorKey(_marketProps1.marketToken, false), 5e29);\\n _dataStore.setUint(Keys.fundingExponentFactorKey(_marketProps1.marketToken), 1.1e30); // 2 in 30 decimals like a square, cube, etc\\n _dataStore.setUint(Keys.fundingFactorKey(_marketProps1.marketToken), 0.0000001e30);\\n _dataStore.setUint(Keys.borrowingFactorKey(_marketProps1.marketToken, true), 0.87e30);\\n _dataStore.setUint(Keys.borrowingFactorKey(_marketProps1.marketToken, false), 0.96e30);\\n _dataStore.setUint(Keys.borrowingExponentFactorKey(_marketProps1.marketToken, true), 2.1e30);\\n _dataStore.setUint(Keys.borrowingExponentFactorKey(_marketProps1.marketToken, false), 2.3e30);\\n _dataStore.setUint(Keys.positionImpactExponentFactorKey(_marketProps1.marketToken), 2e30);\\n _dataStore.setUint(Keys.positionImpactFactorKey(_marketProps1.marketToken, true), 5e22); \\n _dataStore.setUint(Keys.positionImpactFactorKey(_marketProps1.marketToken, false), 1e23);\\n\\n // set the limit of market tokens\\n\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketProps1.marketToken, _marketProps1.longToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketProps1.marketToken, _marketProps1.shortToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsAB.marketToken, _marketPropsAB.longToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsAB.marketToken, _marketPropsAB.shortToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsBC.marketToken, _marketPropsBC.longToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsBC.marketToken, _marketPropsBC.shortToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsCwnt.marketToken, _marketPropsCwnt.longToken), 1000e18);\\n _dataStore.setUint(Keys.maxPoolAmountKey(_marketPropsCwnt.marketToken, _marketPropsCwnt.shortToken), 1000e18);\\n \\n \\n // set max open interest for each market\\n _dataStore.setUint(Keys.maxOpenInterestKey(_marketProps1.marketToken, true), 1e39); // 1B $ \\n _dataStore.setUint(Keys.maxOpenInterestKey(_marketProps1.marketToken, false), 1e39); // 1B $\\n\\n _dataStore.setUint(Keys.maxPnlFactorKey(Keys.MAX_PNL_FACTOR_FOR_WITHDRAWALS, _marketProps1.marketToken, true), 10**29); // maxPnlFactor = 10% for long\\n _dataStore.setUint(Keys.maxPnlFactorKey(Keys.MAX_PNL_FACTOR_FOR_WITHDRAWALS, _marketProps1.marketToken, false), 10**29); // maxPnlFactor = 10% for short\\n // _dataStore.setBool(Keys.cancelDepositFeatureDisabledKey(address(_depositHandler)), true);\\n _dataStore.setBool(Keys.cancelOrderFeatureDisabledKey(address(_orderHandler), uint256(Order.OrderType.MarketIncrease)), true);\\n\\n addFourSigners();\\n address(_wnt).call{value: 10000e18}("");\\n depositor1 = address(0x801);\\n depositor2 = address(0x802);\\n depositor3 = address(0x803);\\n\\n // make sure each depositor has some tokens.\\n _wnt.transfer(depositor1, 1000e18);\\n _wnt.transfer(depositor2, 1000e18);\\n _wnt.transfer(depositor3, 1000e18); \\n _usdc.transfer(depositor1, 1000e18);\\n _usdc.transfer(depositor2, 1000e18);\\n _usdc.transfer(depositor3, 1000e18);\\n _tokenA.transfer(depositor1, 1000e18);\\n _tokenB.transfer(depositor1, 1000e18);\\n _tokenC.transfer(depositor1, 1000e18); \\n\\n printAllTokens(); \\n }\\n\\n error Unauthorized(string);\\n // error Error(string);\\n\\n\\nfunction testLimit() public{\\n OracleUtils.SetPricesParams memory priceParams = createSetPricesParams();\\n \\n vm.roll(block.number+2); // block 3\\n\\n \\n bytes32 key = createDepositNoSwap(_marketProps1, depositor1, 90e18, true); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n uint mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n key = createDepositNoSwap(_marketProps1, depositor1, 100e18, false); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n console2.log("Experiment 1 is completed."); \\n \\n // console2.log("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");\\n \\n key = createMarketSwapOrder(depositor1, address(_wnt), 1e15); // create a deposit at block 3 which is within range (2, 6) \\n _orderHandler.executeOrder(key, priceParams); \\n console2.log("Experiment 2 is completed."); \\n \\n\\n console2.log("\\n\\n depositor 1 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor1, _marketProps1.marketToken, _marketProps1.longToken, 20e18, 1001e30, 106000000000000, true); // \\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor1, _marketProps1.marketToken, _marketProps1.longToken, true);\\n console2.log("Experiment 3 is completed."); \\n \\n \\n\\n console2.log("\\n\\n depositor 2 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.longToken, 110e18, 13e30, 101000000000000, false); // 110 usdc as collateral\\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.longToken, false);\\n console2.log("Experiment 4 is completed."); \\n \\n\\n\\n console2.log("PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP");\\n vm.warp(2 days);\\n setIndexTokenPrice(priceParams, 98, 100); // send 20e18 USDC, increase $13.123 in a long position with trigger price 101\\n key = createLimitIncreaseOrder(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 23e18, 1.1234567e30, 101000000000000, true); // collateral token, usdsize, price\\n console2.log("a LimitIncrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("Experiment 5 is completed.\\n"); \\n \\n\\n // depositor3 creates a LimitDecrease order\\n /*\\n setIndexTokenPrice(priceParams, 120, 125);\\n key = createLimitDecreaseOrder(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 7e18, 58e30, 120000000000000, 120000000000000, true); // retrieve $50? collateral token, usdsize, acceptible price\\n console2.log("a LimitIncrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams); \\n console2.log("Experiment 7 for is completed."); \\n */\\n}\\n\\nfunction testMarketDecrease() public{\\n \\n OracleUtils.SetPricesParams memory priceParams = createSetPricesParams();\\n \\n vm.roll(block.number+2); // block 3\\n\\n \\n bytes32 key = createDepositNoSwap(_marketProps1, depositor1, 90e18, true); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n uint mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n key = createDepositNoSwap(_marketProps1, depositor1, 100e18, false); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n console2.log("Experiment 1 is completed."); \\n \\n \\n \\n \\n console2.log("\\n\\n depositor 2 deposit into marketProps1");\\n key = createDepositNoSwap(_marketProps1, depositor2, 100e18, true);\\n _depositHandler.executeDeposit(key, priceParams);\\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor2);\\n printPoolsAmounts();\\n console2.log("Experiment 2 is completed."); \\n \\n \\n console2.log("\\n\\n depositor 1 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor1, _marketProps1.marketToken, _marketProps1.longToken, 20e18, 1e25, 106000000000000, true); // \\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor1, _marketProps1.marketToken, _marketProps1.longToken, true);\\n console2.log("Experiment 3 is completed."); \\n \\n \\n\\n console2.log("\\n\\n depositor 2 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.longToken, 110e18, 1e25, 101000000000000, false); // 110 usdc as collateral\\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.longToken, false);\\n console2.log("Experiment 4 is completed."); \\n \\n console2.log("********************************************");\\n\\n // deposit 2 will execute a marketDecreaseOrder now\\n key = createMarketDecreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.longToken, 70000000000000, 5e23, false) ; // decrease by 5%\\n console2.log("a market desced order created with key: ");\\n console2.logBytes32(key);\\n console2.log("\\nExecuting the order// rest of code"); \\n setIndexTokenPrice(priceParams, 60, 65); // we have a profit for a short position\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.longToken, false);\\n console2.log("Experiment 5 is completed."); \\n\\n printAllTokens();\\n} \\n\\n \\n\\nfunction testLiquidation() public{\\n // blockrange (2, 6)\\n OracleUtils.SetPricesParams memory priceParams = createSetPricesParams();\\n \\n vm.roll(block.number+2); // block 3\\n\\n \\n bytes32 key = createDepositNoSwap(_marketProps1, depositor1, 90e18, true); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n uint mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n key = createDepositNoSwap(_marketProps1, depositor1, 100e18, false); // create a deposit at block 3 which is within range (2, 6) \\n _depositHandler.executeDeposit(key, priceParams); \\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor1);\\n console2.log("Experiment 1 is completed."); \\n \\n \\n \\n \\n console2.log("\\n\\n depositor 2 deposit into marketProps1");\\n key = createDepositNoSwap(_marketProps1, depositor2, 100e18, true);\\n _depositHandler.executeDeposit(key, priceParams);\\n mintedMarketTokens = IERC20(_marketProps1.marketToken).balanceOf(depositor2);\\n printPoolsAmounts();\\n console2.log("Experiment 2 is completed."); \\n \\n \\n console2.log("\\n\\n depositor 1 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor1, _marketProps1.marketToken, _marketProps1.longToken, 10e18, 1e25, 106000000000000, true);\\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor1, _marketProps1.marketToken, _marketProps1.longToken, true);\\n console2.log("Experiment 3 is completed."); \\n \\n \\n\\n console2.log("\\n\\n depositor 2 createMarketIncreaseOrder");\\n key = createMarketIncreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.shortToken, 100e18, 1e25, 101000000000000, false);\\n console2.log("\\nExecuting the order// rest of code");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.shortToken, false);\\n console2.log("Experiment 4 is completed."); \\n \\n \\n\\n // deposit 2 will execute a marketDecreaseOrder now\\n key = createMarketDecreaseOrder(depositor2, _marketProps1.marketToken, _marketProps1.shortToken, 106000000000000, 5e23, false) ; // decrease by 5%\\n console2.log("a market desced order created with key: ");\\n console2.logBytes32(key);\\n console2.log("\\nExecuting the order// rest of code"); \\n setIndexTokenPrice(priceParams, 84, 90);\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor2, _marketProps1.marketToken, _marketProps1.shortToken, false);\\n console2.log("Experiment 5 is completed."); \\n \\n \\n\\n \\n // depositor3 will execute a LimitIncrease Order now\\n key = createMarketIncreaseOrder(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 20e18, 200e30, 101000000000000, true); // collateral token, usdsize, price\\n console2.log("a LimitIncrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("Experiment 6 is completed.\\n"); \\n \\n\\n // depositor3 creates a LimitDecrease order\\n setIndexTokenPrice(priceParams, 120, 125);\\n key = createLimitDecreaseOrder(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 7e18, 58e30, 120000000000000, 120000000000000, true); // retrieve $50? collateral token, usdsize, acceptible price\\n console2.log("a LimitIncrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams); \\n console2.log("Experiment 7 for is completed."); \\n \\n // depositor3 creates a stopLossDecrease order\\n setIndexTokenPrice(priceParams, 97, 99);\\n key = createStopLossDecrease(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, 7e18, 58e30, 95000000000000, 92000000000000, true); // retrieve $50? collateral token, usdsize, acceptible price\\n console2.log("a StopLossDecrease order created by depositor3 with key: ");\\n console2.logBytes32(key);\\n // Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n\\n console2.log("\\n\\nExecuting the order, exiting moment// rest of code\\n\\n");\\n _orderHandler.executeOrder(key, priceParams);\\n console2.log("Experiment 8 is completed."); \\n \\n \\n console2.log("\\n\\n*************************************************\\n\\n");\\n\\n\\n // depositor3 creates a Liquidation order\\n setIndexTokenPrice(priceParams, 75, 75);\\n console2.log("Liquidate a position// rest of code");\\n Position.printPosition(_dataStore, depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true);\\n _liquidationHandler.executeLiquidation(depositor3, _marketProps1.marketToken, _marketProps1.shortToken, true, priceParams);\\n console2.log("Experiment 9 is completed."); \\n \\n\\n // printPoolsAmounts();\\n printAllTokens();\\n\\n \\n \\n \\n}\\n\\nfunction printAllTokens() startedCompleted("printAllTokens") public\\n{\\n console2.log("\\nTokens used in this test:");\\n console2.log("_wnt: "); console2.logAddress(address(_wnt));\\n console2.log("_usdc: "); console2.logAddress(address(_usdc));\\n console2.log("_sol: "); console2.logAddress(address(_sol));\\n console2.log("_tokenA: "); console2.logAddress(address(_tokenA));\\n console2.log("_tokenB: "); console2.logAddress(address(_tokenB));\\n console2.log("_tokenC: "); console2.logAddress(address(_tokenC));\\n console2.logString("test contract address:"); console2.logAddress(address(this));\\n \\n console2.log("_marketProps1 market token: "); console2.logAddress(address(_marketProps1.marketToken));\\n console2.log("_marketPropsAB market token: "); console2.logAddress(address(_marketPropsAB.marketToken));\\n console2.log("_marketPropsBC market token: "); console2.logAddress(address(_marketPropsBC.marketToken));\\n console2.log("_marketProps1Cwnt market token: "); console2.logAddress(address(_marketPropsCwnt.marketToken));\\n console2.log("\\n");\\n \\n \\n}\\n\\n\\nfunction printMarketTokenAmount() public \\n{ console2.log("Market token address: ");\\n console2.logAddress(address(_marketProps1.marketToken));\\n console2.log("depositor1 market token amount: %d", IERC20(_marketProps1.marketToken).balanceOf(depositor1));\\n console2.log("depositor2 market token amount: %d", IERC20(_marketProps1.marketToken).balanceOf(depositor2));\\n console2.log("depositor3 market token amount: %d", IERC20(_marketProps1.marketToken).balanceOf(depositor3));\\n}\\n\\nfunction printLongShortTokens(address account) public\\n{\\n console2.log("balance for "); console2.logAddress(account);\\n console2.log("_wnt balance:", _wnt.balanceOf(account));\\n console2.log("usdc balance:", _usdc.balanceOf(account));\\n}\\n\\n\\n\\n\\nfunction addFourSigners() private {\\n _oracleStore.addSigner(address(901));\\n _oracleStore.addSigner(address(902)); \\n _oracleStore.addSigner(address(903)); \\n _oracleStore.addSigner(address(904)); \\n}\\n\\n\\nfunction setIndexTokenPrice(OracleUtils.SetPricesParams memory priceParams, uint256 minP, uint256 maxP) public\\n{\\n uint256 mask1 = ~uint256(type(uint96).max); // (32*3 of 1's)\\n console2.logBytes32(bytes32(mask1));\\n\\n uint256 minPrice = minP;\\n minPrice = minPrice << 32 | minP;\\n minPrice = minPrice << 32 | minP;\\n\\n uint256 maxPrice = maxP;\\n maxPrice = maxPrice << 32 | maxP;\\n maxPrice = maxPrice << 32 | maxP;\\n\\n priceParams.compactedMinPrices[0] = (priceParams.compactedMinPrices[0] & mask1) | minPrice;\\n priceParams.compactedMaxPrices[0] = (priceParams.compactedMaxPrices[0] & mask1) | maxPrice;\\n}\\n\\n\\nfunction createSetPricesParams() public returns (OracleUtils.SetPricesParams memory) {\\n uint256 signerInfo = 3; // signer 904\\n signerInfo = signerInfo << 16 | 2; // signer 903\\n signerInfo = signerInfo << 16 | 1; // signer 902\\n signerInfo = signerInfo << 16 | 3; // number of singers\\n // will read out as 902, 903, 904 from the lowest first\\n\\n // the number of tokens, 6\\n address[] memory tokens = new address[](6);\\n tokens[0] = address(_sol);\\n tokens[1] = address(_wnt);\\n tokens[2] = address(_usdc);\\n tokens[3] = address(_tokenA);\\n tokens[4] = address(_tokenB);\\n tokens[5] = address(_tokenC);\\n\\n // must be equal to the number of tokens 6, 64 for each one, so 64*6. 64*4 for one element, so need two elements \\n uint256[] memory compactedMinOracleBlockNumbers = new uint256[](2);\\n compactedMinOracleBlockNumbers[0] = block.number+1;\\n compactedMinOracleBlockNumbers[0] = compactedMinOracleBlockNumbers[0] << 64 | block.number+1;\\n compactedMinOracleBlockNumbers[0] = compactedMinOracleBlockNumbers[0] << 64 | block.number+1;\\n compactedMinOracleBlockNumbers[0] = compactedMinOracleBlockNumbers[0] << 64 | block.number+1;\\n\\n compactedMinOracleBlockNumbers[1] = block.number+1;\\n compactedMinOracleBlockNumbers[1] = compactedMinOracleBlockNumbers[0] << 64 | block.number+1;\\n \\n // must be equal to the number of tokens 6, 64 for each one, so 64*6. 64*4 for one element, so need two elements \\n \\n uint256[] memory compactedMaxOracleBlockNumbers = new uint256[](2);\\n compactedMaxOracleBlockNumbers[0] = block.number+5; \\n compactedMaxOracleBlockNumbers[0] = compactedMaxOracleBlockNumbers[0] << 64 | block.number+5;\\n compactedMaxOracleBlockNumbers[0] = compactedMaxOracleBlockNumbers[0] << 64 | block.number+5; \\n compactedMaxOracleBlockNumbers[0] = compactedMaxOracleBlockNumbers[0] << 64 | block.number+5; \\n\\n compactedMaxOracleBlockNumbers[1] = block.number+5; \\n compactedMaxOracleBlockNumbers[1] = compactedMaxOracleBlockNumbers[0] << 64 | block.number+5;\\n\\n // must be equal to the number of tokens 6, 64 for each one, so 64*6. 64*4 for one element, so need two elements \\n uint256[] memory compactedOracleTimestamps = new uint256[](2);\\n compactedOracleTimestamps[0] = 9;\\n compactedOracleTimestamps[0] = compactedOracleTimestamps[0] << 64 | 8;\\n compactedOracleTimestamps[0] = compactedOracleTimestamps[0] << 64 | 7;\\n compactedOracleTimestamps[0] = compactedOracleTimestamps[0] << 64 | 7;\\n \\n compactedOracleTimestamps[1] = 9;\\n compactedOracleTimestamps[1] = compactedOracleTimestamps[0] << 64 | 8;\\n \\n\\n // must be equal to the number of tokens, 8 for each, so 8*6= 48, only need one element\\n uint256[] memory compactedDecimals = new uint256[](1);\\n compactedDecimals[0] = 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n compactedDecimals[0] = compactedDecimals[0] << 8 | 12;\\n \\n \\n // three signers, 6 tokens, so we have 3*6 = 18 entries, each entry takes 32 bits, so each 8 entries takes one element, we need 3 elements\\n // price table:\\n // SOL: 100 101 102\\n // wnt: 200 201 203\\n // USDC 1 1 1\\n // tokenA 100 101 102\\n // tokenB 200 202 204\\n // tokenC 400 404 408\\n\\n uint256[] memory compactedMinPrices = new uint256[](3);\\n compactedMinPrices[2] = 408; \\n compactedMinPrices[2] = compactedMinPrices[2] << 32 | 404;\\n\\n compactedMinPrices[1] = 400;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 204;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 202;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 200;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 102;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 101;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 100;\\n compactedMinPrices[1] = compactedMinPrices[1] << 32 | 1;\\n \\n compactedMinPrices[0] = 1;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 1;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 203;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 201;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 200;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 102;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 101;\\n compactedMinPrices[0] = compactedMinPrices[0] << 32 | 100;\\n \\n // three signers, 6 tokens, so we have 3*6 = 18 entries, each entry takes 8 bits, so we just need one element\\n\\n uint256[] memory compactedMinPricesIndexes = new uint256[](1);\\n compactedMinPricesIndexes[0] = 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0; \\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0; \\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0; \\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 1;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 2;\\n compactedMinPricesIndexes[0] = compactedMinPricesIndexes[0] << 8 | 0; \\n \\n // three signers, 6 tokens, so we have 3*6 = 18 entries, each entry takes 32 bits, so each 8 entries takes one element, we need 3 elements\\n // price table:\\n // SOL: 105 106 107\\n // wnt: 205 206 208\\n // USDC 1 1 1\\n // tokenA 105 106 107\\n // tokenB 205 207 209\\n // tokenC 405 409 413\\n uint256[] memory compactedMaxPrices = new uint256[](3);\\n compactedMaxPrices[2] = 413;\\n compactedMaxPrices[2] = compactedMaxPrices[2] << 32 | 409;\\n \\n compactedMaxPrices[1] = 405;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 209;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 207;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 205;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 107;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 106;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 105;\\n compactedMaxPrices[1] = compactedMaxPrices[1] << 32 | 1;\\n\\n compactedMaxPrices[0] = 1;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 1;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 208;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 206; \\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 205; \\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 107;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 106;\\n compactedMaxPrices[0] = compactedMaxPrices[0] << 32 | 105;\\n \\n \\n // three signers, 6 tokens, so we have 3*6 = 18 entries, each entry takes 8 bits, so we just need one element\\n\\n uint256[] memory compactedMaxPricesIndexes = new uint256[](1);\\n compactedMaxPricesIndexes[0] = 1; \\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 1;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 2;\\n compactedMaxPricesIndexes[0] = compactedMaxPricesIndexes[0] << 8 | 0;\\n \\n // 3 signers and 6 tokens, so we need 3*6 signatures\\n bytes[] memory signatures = new bytes[](18);\\n for(uint i; i<18; i++){\\n signatures[i] = abi.encode("SIGNATURE");\\n }\\n address[] memory priceFeedTokens;\\n\\n OracleUtils.SetPricesParams memory priceParams = OracleUtils.SetPricesParams(\\n signerInfo,\\n tokens,\\n compactedMinOracleBlockNumbers,\\n compactedMaxOracleBlockNumbers,\\n compactedOracleTimestamps,\\n compactedDecimals,\\n compactedMinPrices, \\n compactedMinPricesIndexes,\\n compactedMaxPrices, \\n compactedMaxPricesIndexes, \\n signatures, \\n priceFeedTokens\\n );\\n return priceParams;\\n}\\n\\n/* \\n* The current index token price (85, 90), a trader sets a trigger price to 100 and then acceptabiel price to 95.\\n* He like to long the index token. \\n* 1. Pick the primary price 90 since we long, so choose the max\\n* 2. Make sure 90 < 100, and pick (90, 100) as the custom price since we long\\n* 3. Choose price 95 since 95 is within the range, and it is the highest acceptible price. Choosing 90 \\n* will be in favor of the trader\\n* \\n*/\\n\\nfunction createMarketSwapOrder(address account, address inputToken, uint256 inAmount) public returns(bytes32)\\n{ \\n address[] memory swapPath = new address[](1);\\n swapPath[0] = _marketProps1.marketToken;\\n // swapPath[0] = _marketPropsAB.marketToken;\\n // swapPath[1] = _marketPropsBC.marketToken;\\n // swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account; // the account is the receiver\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = account; // set myself as the ui receiver\\n // params.addresses.market = marketToken;\\n params.addresses.initialCollateralToken = inputToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n // params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n params.numbers.initialCollateralDeltaAmount = inAmount ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(inputToken).transfer(address(_orderVault), inAmount); // this is the real amount\\n\\n\\n // params.numbers.triggerPrice = triggerPrice;\\n // params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n // params.numbers.initialCollateralDeltaAmount = inAmount;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.MarketSwap;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n // params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n}\\n\\n\\n\\nfunction createLiquidationOrder(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint triggerPrice, uint256 acceptablePrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = triggerPrice;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.Liquidation;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\nfunction createStopLossDecrease(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint triggerPrice, uint256 acceptablePrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = triggerPrice;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.StopLossDecrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\nfunction createLimitDecreaseOrder(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint triggerPrice, uint256 acceptablePrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = triggerPrice;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.LimitDecrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\nfunction createLimitIncreaseOrder(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint triggerPrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = triggerPrice; // used for limit order\\n params.numbers.acceptablePrice = 121000000000000; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.LimitIncrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\n\\nfunction createMarketDecreaseOrder(address account, address marketToken, address collateralToken, uint256 acceptablePrice, uint256 sizeInUsd, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeInUsd; // how much dollar to decrease, will convert into amt of tokens to decrease in long/short based on the execution price\\n params.numbers.initialCollateralDeltaAmount = 13e18; // this is actually useless, will be overidden by real transfer amount\\n // vm.prank(account); \\n // IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = 0;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 10e18; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.MarketDecrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\nfunction createMarketIncreaseOrder(address account, address marketToken, address collateralToken, uint256 collateralAmount, uint sizeDeltaUsd, uint acceptablePrice, bool isLong) public returns(bytes32)\\n{\\n address[] memory swapPath;\\n \\n //address[] memory swapPath = new address[](3);\\n //swapPath[0] = _marketPropsAB.marketToken;\\n //swapPath[1] = _marketPropsBC.marketToken;\\n //swapPath[2] = _marketPropsCwnt.marketToken;\\n\\n \\n vm.prank(account); \\n _wnt.transfer(address(_orderVault), 3200); // execution fee\\n\\n\\n BaseOrderUtils.CreateOrderParams memory params;\\n params.addresses.receiver = account;\\n params.addresses.callbackContract = address(0);\\n params.addresses.uiFeeReceiver = uiFeeReceiver;\\n params.addresses.market = marketToken; // final market\\n params.addresses.initialCollateralToken = collateralToken; // initial token\\n params.addresses.swapPath = swapPath;\\n\\n params.numbers.sizeDeltaUsd = sizeDeltaUsd;\\n // params.numbers.initialCollateralDeltaAmount = ; // this is actually useless, will be overidden by real transfer amount\\n vm.prank(account); \\n IERC20(collateralToken).transfer(address(_orderVault), collateralAmount); // this is the real amount\\n\\n\\n params.numbers.triggerPrice = 0;\\n params.numbers.acceptablePrice = acceptablePrice; // I can buy with this price or lower effective spread control \\n params.numbers.executionFee = 3200;\\n params.numbers.callbackGasLimit = 3200;\\n params.numbers.minOutputAmount = 100; // use the control the final collateral amount, not for the position size delta, which is indirectly controlled by acceptable price\\n\\n params.orderType = Order.OrderType.MarketIncrease;\\n params.decreasePositionSwapType = Order.DecreasePositionSwapType.NoSwap;\\n params.isLong = isLong;\\n params.shouldUnwrapNativeToken = false;\\n params.referralCode = keccak256(abi.encode("MY REFERRAL"));\\n\\n vm.prank(account);\\n bytes32 key = _erouter.createOrder(params);\\n return key;\\n} \\n\\n\\n\\nfunction createWithdraw(address withdrawor, uint marketTokenAmount) public returns (bytes32)\\n{\\n address[] memory longTokenSwapPath;\\n address[] memory shortTokenSwapPath;\\n\\n console.log("createWithdraw with withdrawor: ");\\n console.logAddress(withdrawor);\\n vm.prank(withdrawor); \\n _wnt.transfer(address(_withdrawalVault), 3200); // execution fee\\n\\n vm.prank(withdrawor);\\n ERC20(_marketProps1.marketToken).transfer(address(_withdrawalVault), marketTokenAmount);\\n\\n WithdrawalUtils.CreateWithdrawalParams memory params = WithdrawalUtils.CreateWithdrawalParams(\\n withdrawor, // receiver\\n address(0), // call back function\\n uiFeeReceiver, // uiFeeReceiver\\n _marketProps1.marketToken, // which market token to withdraw\\n longTokenSwapPath,\\n shortTokenSwapPath,\\n 123, // minLongTokenAmount\\n 134, // minShortTokenAmount\\n false, // shouldUnwrapNativeToken\\n 3200, // execution fee\\n 3200 // callback gas limit\\n );\\n\\n vm.prank(withdrawor);\\n bytes32 key = _erouter.createWithdrawal(params);\\n return key;\\n}\\n\\n\\nfunction createDepositNoSwap(Market.Props memory marketProps, address depositor, uint amount, bool isLong) public returns (bytes32){\\n address[] memory longTokenSwapPath;\\n address[] memory shortTokenSwapPath;\\n\\n console.log("createDeposit with depositor: ");\\n console.logAddress(depositor);\\n\\n vm.prank(depositor);\\n _wnt.transfer(address(_depositVault), 3200); // execution fee\\n if(isLong){\\n console2.log("000000000000000000");\\n vm.prank(depositor);\\n IERC20(marketProps.longToken).transfer(address(_depositVault), amount); \\n console2.log("bbbbbbbbbbbbbbbbbbbbbb");\\n }\\n else {\\n console2.log("111111111111111111111111");\\n console2.log("deposit balance: %d, %d", IERC20(marketProps.shortToken).balanceOf(depositor), amount);\\n vm.prank(depositor);\\n IERC20(marketProps.shortToken).transfer(address(_depositVault), amount);\\n console2.log("qqqqqqqqqqqqqqqqqq");\\n }\\n \\n\\n DepositUtils.CreateDepositParams memory params = DepositUtils.CreateDepositParams(\\n depositor,\\n address(0),\\n uiFeeReceiver,\\n marketProps.marketToken,\\n marketProps.longToken,\\n marketProps.shortToken,\\n longTokenSwapPath,\\n shortTokenSwapPath,\\n 100000, // minMarketTokens\\n true,\\n 3200, // execution fee\\n 3200 // call back gas limit\\n );\\n\\n console2.log("aaaaaaaaaaaaaaaaaaaaaaaaa");\\n vm.prank(depositor);\\n bytes32 key1 = _erouter.createDeposit(params);\\n\\n return key1;\\n}\\n\\n/*\\nfunction testCancelDeposit() public \\n{\\n address[] memory longTokenSwapPath;\\n address[] memory shortTokenSwapPath;\\n\\n address(_wnt).call{value: 100e8}("");\\n _wnt.transfer(address(_depositVault), 1e6);\\n DepositUtils.CreateDepositParams memory params = DepositUtils.CreateDepositParams(\\n msg.sender,\\n address(0),\\n address(111),\\n _marketProps1.marketToken,\\n _marketProps1.longToken,\\n _marketProps1.shortToken,\\n longTokenSwapPath,\\n shortTokenSwapPath,\\n 100000, // minMarketTokens\\n true,\\n 3200, // execution fee\\n 3200 // call back gas limit\\n );\\n\\n bytes32 key1 = _erouter.createDeposit(params);\\n\\n console.log("WNT balance of address(222) before cancelllation: %s", _wnt.balanceOf(address(222)));\\n console.log("WNT balance of address(this) before cancelllation: %s", _wnt.balanceOf(address(this))); \\n\\n _roleStore.grantRole(address(222), Role.CONTROLLER); // to save a market's props\\n vm.prank(address(222));\\n _depositHandler.cancelDeposit(key1);\\n console.log("WNT balance of address(222) after cancelllation: %s", _wnt.balanceOf(address(222)));\\n console.log("WNT balance of address(this) after cancelllation: %s", _wnt.balanceOf(address(this))); \\n}\\n*/\\n\\nfunction testERC165() public{\\n bool yes = _wnt.supportsInterface(type(IWNT).interfaceId);\\n console2.log("wnt suppports deposit?");\\n console2.logBool(yes);\\n vm.expectRevert();\\n yes = IERC165(address(_sol)).supportsInterface(type(IWNT).interfaceId);\\n console2.logBool(yes);\\n\\n if(ERC165Checker.supportsERC165(address(_wnt))){\\n console2.log("_wnt supports ERC165");\\n }\\n if(ERC165Checker.supportsERC165(address(_sol))){\\n console2.log("_sol supports ERC165");\\n }\\n}\\n\\n function justError() external {\\n // revert Unauthorized("abcdefg"); // 973d02cb\\n // revert("abcdefg"); // 0x08c379a, Error selector\\n // require(false, "abcdefg"); // 0x08ce79a, Error selector\\n assert(3 == 4); // Panic: 0x4e487b71\\n }\\n\\n function testErrorMessage() public{\\n\\n try this.justError(){} \\n catch (bytes memory reasonBytes) {\\n (string memory msg, bool ok ) = ErrorUtils.getRevertMessage(reasonBytes);\\n console2.log("Error Message: "); console2.logString(msg);\\n console2.log("error?"); console2.logBool(ok);\\n } \\n }\\n\\n \\n function printAddresses() public{\\n console2.log("_orderVault:"); console2.logAddress(address(_orderVault));\\n console2.log("marketToken:"); console2.logAddress(address(_marketProps1.marketToken));\\n } \\n\\n function printPoolsAmounts() public{\\n console2.log("\\n The summary of pool amounts: ");\\n \\n uint256 amount = MarketUtils.getPoolAmount(_dataStore, _marketProps1, _marketProps1.longToken);\\n console2.log("Market: _marketProps1, token: long/nwt, amount: %d", amount);\\n amount = MarketUtils.getPoolAmount(_dataStore, _marketProps1, _marketProps1.shortToken);\\n console2.log("Market: _marketProps1, token: short/USDC, amount: %d", amount);\\n \\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsAB, _marketPropsAB.longToken);\\n console2.log("Market: _marketPropsAB, token: long/A, amount: %d", amount);\\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsAB, _marketPropsAB.shortToken);\\n console2.log("Market: _marketPropsAB, token: short/B, amount: %d", amount);\\n \\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsBC, _marketPropsBC.longToken);\\n console2.log("Market: _marketPropsBC, token: long/B, amount:%d", amount);\\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsBC, _marketPropsBC.shortToken);\\n console2.log("Market: _marketPropsBC, token: short/C, amount: %d", amount);\\n \\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsCwnt, _marketPropsCwnt.longToken);\\n console2.log("Market: _marketPropsCwnt, token: long/C, amount: %d", amount);\\n amount = MarketUtils.getPoolAmount(_dataStore, _marketPropsCwnt, _marketPropsCwnt.shortToken);\\n console2.log("Market: _marketPropsCwnt, token: short/wnt, amount: %d", amount);\\n \\n\\n console2.log("\\n");\\n }\\n \\n}\\n```\\n
short side of getReservedUsd does not work for market that has the same collateral token
medium
short side of getReservedUsd does not work for market that has the same collateral token\\nConsider the case of ETH / USD market with both long and short collateral token as ETH.\\nthe available amount to be reserved (ETH) would CHANGE with the price of ETH.\\n```\\n function getReservedUsd(\\n DataStore dataStore,\\n Market.Props memory market,\\n MarketPrices memory prices,\\n bool isLong\\n ) internal view returns (uint256) {\\n uint256 reservedUsd;\\n if (isLong) {\\n // for longs calculate the reserved USD based on the open interest and current indexTokenPrice\\n // this works well for e.g. an ETH / USD market with long collateral token as WETH\\n // the available amount to be reserved would scale with the price of ETH\\n // this also works for e.g. a SOL / USD market with long collateral token as WETH\\n // if the price of SOL increases more than the price of ETH, additional amounts would be\\n // automatically reserved\\n uint256 openInterestInTokens = getOpenInterestInTokens(dataStore, market, isLong);\\n reservedUsd = openInterestInTokens * prices.indexTokenPrice.max;\\n } else {\\n // for shorts use the open interest as the reserved USD value\\n // this works well for e.g. an ETH / USD market with short collateral token as USDC\\n // the available amount to be reserved would not change with the price of ETH\\n reservedUsd = getOpenInterest(dataStore, market, isLong);\\n }\\n\\n return reservedUsd;\\n }\\n```\\n
Consider apply both long and short calculations of reserveUsd with relation to the indexTokenPrice.
reservedUsd does not work when long and short collateral tokens are the same.
```\\n function getReservedUsd(\\n DataStore dataStore,\\n Market.Props memory market,\\n MarketPrices memory prices,\\n bool isLong\\n ) internal view returns (uint256) {\\n uint256 reservedUsd;\\n if (isLong) {\\n // for longs calculate the reserved USD based on the open interest and current indexTokenPrice\\n // this works well for e.g. an ETH / USD market with long collateral token as WETH\\n // the available amount to be reserved would scale with the price of ETH\\n // this also works for e.g. a SOL / USD market with long collateral token as WETH\\n // if the price of SOL increases more than the price of ETH, additional amounts would be\\n // automatically reserved\\n uint256 openInterestInTokens = getOpenInterestInTokens(dataStore, market, isLong);\\n reservedUsd = openInterestInTokens * prices.indexTokenPrice.max;\\n } else {\\n // for shorts use the open interest as the reserved USD value\\n // this works well for e.g. an ETH / USD market with short collateral token as USDC\\n // the available amount to be reserved would not change with the price of ETH\\n reservedUsd = getOpenInterest(dataStore, market, isLong);\\n }\\n\\n return reservedUsd;\\n }\\n```\\n
Keepers can steal additional execution fee from users
medium
The implementation of `payExecutionFee()` didn't take EIP-150 into consideration, a malicious keeper can exploit it to drain out all execution fee users have paid, regardless of the actual execution cost.\\nThe issue arises on `L55` of `payExecutionFee()`, as it's an `external` function, callingpayExecutionFee() is subject to EIP-150. Only `63/64` gas is passed to the `GasUtils` sub-contract(external library), and the remaing `1/64` gas is reserved in the caller contract which will be refunded to keeper(msg.sender) after the execution of the whole transaction. But calculation of `gasUsed` includes this portion of the cost as well.\\n```\\nFile: contracts\\gas\\GasUtils.sol\\n function payExecutionFee(\\n DataStore dataStore,\\n EventEmitter eventEmitter,\\n StrictBank bank,\\n uint256 executionFee,\\n uint256 startingGas,\\n address keeper,\\n address user\\n ) external { // @audit external call is subject to EIP// Remove the line below\\n150\\n// Remove the line below\\n uint256 gasUsed = startingGas // Remove the line below\\n gasleft();\\n// Add the line below\\n uint256 gasUsed = startingGas // Remove the line below\\n gasleft() * 64 / 63; // @audit the correct formula\\n uint256 executionFeeForKeeper = adjustGasUsage(dataStore, gasUsed) * tx.gasprice;\\n\\n if (executionFeeForKeeper > executionFee) {\\n executionFeeForKeeper = executionFee;\\n }\\n\\n bank.transferOutNativeToken(\\n keeper,\\n executionFeeForKeeper\\n );\\n\\n emitKeeperExecutionFee(eventEmitter, keeper, executionFeeForKeeper);\\n\\n uint256 refundFeeAmount = executionFee // Remove the line below\\n executionFeeForKeeper;\\n if (refundFeeAmount == 0) {\\n return;\\n }\\n\\n bank.transferOutNativeToken(\\n user,\\n refundFeeAmount\\n );\\n\\n emitExecutionFeeRefund(eventEmitter, user, refundFeeAmount);\\n }\\n```\\n\\nA malicious keeper can exploit this issue to drain out all execution fee, regardless of the actual execution cost. Let's take `executeDeposit()` operation as an example to show how it works:\\n```\\nFile: contracts\\exchange\\DepositHandler.sol\\n function executeDeposit(\\n bytes32 key,\\n OracleUtils.SetPricesParams calldata oracleParams\\n ) external\\n globalNonReentrant\\n onlyOrderKeeper\\n withOraclePrices(oracle, dataStore, eventEmitter, oracleParams)\\n {\\n uint256 startingGas = gasleft();\\n\\n try this._executeDeposit(\\n key,\\n oracleParams,\\n msg.sender\\n ) {\\n } catch (bytes memory reasonBytes) {\\n// rest of code\\n }\\n }\\n\\nFile: contracts\\exchange\\DepositHandler.sol\\n function _executeDeposit(\\n bytes32 key,\\n OracleUtils.SetPricesParams memory oracleParams,\\n address keeper\\n ) external onlySelf {\\n uint256 startingGas = gasleft();\\n// rest of code\\n\\n ExecuteDepositUtils.executeDeposit(params);\\n }\\n\\n\\nFile: contracts\\deposit\\ExecuteDepositUtils.sol\\n function executeDeposit(ExecuteDepositParams memory params) external {\\n// rest of code\\n\\n GasUtils.payExecutionFee(\\n params.dataStore,\\n params.eventEmitter,\\n params.depositVault,\\n deposit.executionFee(),\\n params.startingGas,\\n params.keeper,\\n deposit.account()\\n );\\n }\\n\\nFile: contracts\\gas\\GasUtils.sol\\n function payExecutionFee(\\n DataStore dataStore,\\n EventEmitter eventEmitter,\\n StrictBank bank,\\n uint256 executionFee,\\n uint256 startingGas,\\n address keeper,\\n address user\\n ) external {\\n uint256 gasUsed = startingGas - gasleft();\\n uint256 executionFeeForKeeper = adjustGasUsage(dataStore, gasUsed) * tx.gasprice;\\n\\n if (executionFeeForKeeper > executionFee) {\\n executionFeeForKeeper = executionFee;\\n }\\n\\n bank.transferOutNativeToken(\\n keeper,\\n executionFeeForKeeper\\n );\\n\\n emitKeeperExecutionFee(eventEmitter, keeper, executionFeeForKeeper);\\n\\n uint256 refundFeeAmount = executionFee - executionFeeForKeeper;\\n if (refundFeeAmount == 0) {\\n return;\\n }\\n\\n bank.transferOutNativeToken(\\n user,\\n refundFeeAmount\\n );\\n\\n emitExecutionFeeRefund(eventEmitter, user, refundFeeAmount);\\n }\\n\\nFile: contracts\\gas\\GasUtils.sol\\n function adjustGasUsage(DataStore dataStore, uint256 gasUsed) internal view returns (uint256) {\\n// rest of code\\n uint256 baseGasLimit = dataStore.getUint(Keys.EXECUTION_GAS_FEE_BASE_AMOUNT);\\n// rest of code\\n uint256 multiplierFactor = dataStore.getUint(Keys.EXECUTION_GAS_FEE_MULTIPLIER_FACTOR);\\n uint256 gasLimit = baseGasLimit + Precision.applyFactor(gasUsed, multiplierFactor);\\n return gasLimit;\\n }\\n```\\n\\nTo simplify the problem, given\\n```\\nEXECUTION_GAS_FEE_BASE_AMOUNT = 0\\nEXECUTION_GAS_FEE_MULTIPLIER_FACTOR = 1\\nexecutionFeeUserHasPaid = 200K Gwei\\ntx.gasprice = 1 Gwei\\nactualUsedGas = 100K\\n```\\n\\n`actualUsedGas` is the gas cost since startingGas(L146 of DepositHandler.sol) but before calling payExecutionFee()(L221 of ExecuteDepositUtils.sol)\\nLet's say, the keeper sets `tx.gaslimit` to make\\n```\\nstartingGas = 164K\\n```\\n\\nThen the calculation of `gasUsed`, L55 of `GasUtils.sol`, would be\\n```\\nuint256 gasUsed = startingGas - gasleft() = 164K - (164K - 100K) * 63 / 64 = 101K\\n```\\n\\nand\\n```\\nexecutionFeeForKeeper = 101K * tx.gasprice = 101K * 1 Gwei = 101K Gwei\\nrefundFeeForUser = 200K - 101K = 99K Gwei\\n```\\n\\nAs setting of `tx.gaslimit` doesn't affect the actual gas cost of the whole transaction, the excess gas will be refunded to `msg.sender`. Now, the keeper increases `tx.gaslimit` to make `startingGas = 6500K`, the calculation of `gasUsed` would be\\n```\\nuint256 gasUsed = startingGas - gasleft() = 6500K - (6500K - 100K) * 63 / 64 = 200K\\n```\\n\\nand\\n```\\nexecutionFeeForKeeper = 200K * tx.gasprice = 200K * 1 Gwei = 200K Gwei\\nrefundFeeForUser = 200K - 200K = 0 Gwei\\n```\\n\\nWe can see the keeper successfully drain out all execution fee, the user gets nothing refunded.
The description in `Vulnerability Detail` section has been simplified. In fact, `gasleft` value should be adjusted after each external call during the whole call stack, not just in `payExecutionFee()`.
Keepers can steal additional execution fee from users.
```\\nFile: contracts\\gas\\GasUtils.sol\\n function payExecutionFee(\\n DataStore dataStore,\\n EventEmitter eventEmitter,\\n StrictBank bank,\\n uint256 executionFee,\\n uint256 startingGas,\\n address keeper,\\n address user\\n ) external { // @audit external call is subject to EIP// Remove the line below\\n150\\n// Remove the line below\\n uint256 gasUsed = startingGas // Remove the line below\\n gasleft();\\n// Add the line below\\n uint256 gasUsed = startingGas // Remove the line below\\n gasleft() * 64 / 63; // @audit the correct formula\\n uint256 executionFeeForKeeper = adjustGasUsage(dataStore, gasUsed) * tx.gasprice;\\n\\n if (executionFeeForKeeper > executionFee) {\\n executionFeeForKeeper = executionFee;\\n }\\n\\n bank.transferOutNativeToken(\\n keeper,\\n executionFeeForKeeper\\n );\\n\\n emitKeeperExecutionFee(eventEmitter, keeper, executionFeeForKeeper);\\n\\n uint256 refundFeeAmount = executionFee // Remove the line below\\n executionFeeForKeeper;\\n if (refundFeeAmount == 0) {\\n return;\\n }\\n\\n bank.transferOutNativeToken(\\n user,\\n refundFeeAmount\\n );\\n\\n emitExecutionFeeRefund(eventEmitter, user, refundFeeAmount);\\n }\\n```\\n
An Oracle Signer can never be removed even if he becomes malicious
medium
The call flow of removeOracleSIgner incorrectly compares the hash of ("removeOracleSigner", account) with the hash of ("addOracleSigner", account) for validating that an action is actually initiated. This validation always fails because the hashes can never match.\\nThe process of removing oracle signers is 2 stage. First function `signalRemoveOracleSigner` is called by the TimelockAdmin which stores a time-delayed timestamp corresponding to the keccak256 hash of ("removeOracleSigner", account) - a bytes32 value called actionKey in the pendingActions mapping.\\nThen the Admin needs to call function `removeOracleSignerAfterSignal` but this function calls `_addOracleSignerActionKey` instead of `_removeOracleSignerActionKey` for calculating the bytes32 action key value. Now the actionKey is calculated as keccak256 hash of ("addOracleSigner", account) and this hash is used for checking if this action is actually pending by ensuring its timestamp is not zero inside the `_validateAction` function called via `_validateAndClearAction` function at Line 122. The hash of ("removeOracleSigner", account) can never match hash of ("addOracleSigner", account) and thus this validation will fail.\\n```\\n function removeOracleSignerAfterSignal(address account) external onlyTimelockAdmin nonReentrant {\\n bytes32 actionKey = _addOracleSignerActionKey(account);\\n _validateAndClearAction(actionKey, "removeOracleSigner");\\n\\n oracleStore.removeSigner(account);\\n\\n EventUtils.EventLogData memory eventData;\\n eventData.addressItems.initItems(1);\\n eventData.addressItems.setItem(0, "account", account);\\n eventEmitter.emitEventLog1(\\n "RemoveOracleSigner",\\n actionKey,\\n eventData\\n );\\n }\\n```\\n
Replace the call to _addOracleSignerActionKey at Line 118 by call to _removeOracleSignerActionKey
The process of removing an Oracle Signer will always revert and this breaks an important safety measure if a certain oracle signer becomes malicious the TimelockAdmin could do nothing(these functions are meant for this). Hence, important functionality is permanently broken.
```\\n function removeOracleSignerAfterSignal(address account) external onlyTimelockAdmin nonReentrant {\\n bytes32 actionKey = _addOracleSignerActionKey(account);\\n _validateAndClearAction(actionKey, "removeOracleSigner");\\n\\n oracleStore.removeSigner(account);\\n\\n EventUtils.EventLogData memory eventData;\\n eventData.addressItems.initItems(1);\\n eventData.addressItems.setItem(0, "account", account);\\n eventEmitter.emitEventLog1(\\n "RemoveOracleSigner",\\n actionKey,\\n eventData\\n );\\n }\\n```\\n
Stale inflationMultiplier in L1ECOBridge
high
`L1ECOBridge::inflationMultiplier` is updated through `L1ECOBridge::rebase` on Ethereum, and it is used in `_initiateERC20Deposit` and `finalizeERC20Withdrawal` to convert between token amount and `_gonsAmount`. However, if `rebase` is not called in a timely manner, the `inflationMultiplier` value can be stale and inconsistent with the value of L1 ECO token during transfer, leading to incorrect token amounts in deposit and withdraw.\\nThe `inflationMultiplier` value is updated in `rebase` with an independent transaction on L1 as shown below:\\n```\\n function rebase(uint32 _l2Gas) external {\\n inflationMultiplier = IECO(l1Eco).getPastLinearInflation(block.number);\\n```\\n\\nHowever, in both `_initiateERC20Deposit`, `transferFrom` is called before the `inflationMultiplier` is used, which can lead to inconsistent results if `rebase` is not called on time for the `inflationMultiplier` to be updated. The code snippet for `_initiateERC20Deposit` is as follows:\\n```\\n IECO(_l1Token).transferFrom(_from, address(this), _amount);\\n _amount = _amount * inflationMultiplier;\\n```\\n\\n`finalizeERC20Withdrawal` has the same problem.\\n```\\n uint256 _amount = _gonsAmount / inflationMultiplier;\\n bytes memory _ecoTransferMessage = abi.encodeWithSelector(IERC20.transfer.selector,_to,_amount);\\n```\\n\\nThe same problem does not exist in L2ECOBridge. Because the L2 rebase function updates inflationMultiplier and rebase l2Eco token synchronously.\\n```\\n function rebase(uint256 _inflationMultiplier)\\n external\\n virtual\\n onlyFromCrossDomainAccount(l1TokenBridge)\\n validRebaseMultiplier(_inflationMultiplier)\\n {\\n inflationMultiplier = _inflationMultiplier;\\n l2Eco.rebase(_inflationMultiplier);\\n emit RebaseInitiated(_inflationMultiplier);\\n }\\n```\\n
Calling `IECO(l1Eco).getPastLinearInflation(block.number)` instead of using `inflationMultiplier`.
The attacker can steal tokens with this.\\nHe can deposit to L1 bridge when he observes a stale larger value and he will receive more tokens on L2.
```\\n function rebase(uint32 _l2Gas) external {\\n inflationMultiplier = IECO(l1Eco).getPastLinearInflation(block.number);\\n```\\n
Malicious actor cause rebase to an old inflation multiplier
high
The protocol has a rebasing mechanism that allows to sync the inflation multiplier between both L1 and L2 chains. The call to rebase is permissionless (anyone can trigger it). Insufficant checks allow a malicious actor to rebase to an old value.\\n```\\n function rebase(uint32 _l2Gas) external {\\n inflationMultiplier = IECO(l1Eco).getPastLinearInflation(\\n block.number\\n );\\n\\n bytes memory message = abi.encodeWithSelector(\\n IL2ECOBridge.rebase.selector,\\n inflationMultiplier\\n );\\n\\n sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);\\n }\\n```\\n\\nA malicious actor can call this function a large amount of times to queue messages on `L2CrossDomainMessenger`. Since it is expensive to execute so much messages from `L2CrossDomainMessenger` (especially if the malicious actor sets `_l2Gas` to a high value) there will be a rebase message that will not be relayed through `L2CrossDomainMessenger` (or in failedMessages array).\\nSome time passes and other legitimate rebase transactions get executed.\\nOne day the malicious actor can execute one of his old rebase messages and set the value to the old value. The attacker will debalance the scales between L1 and L2 and can profit from it.
When sending a rebase from L1, include in the message the L1 block number. In L2 rebase, validate that the new rebase block number is above previous block number
debalance the scales between L1 and L2 ECO token
```\\n function rebase(uint32 _l2Gas) external {\\n inflationMultiplier = IECO(l1Eco).getPastLinearInflation(\\n block.number\\n );\\n\\n bytes memory message = abi.encodeWithSelector(\\n IL2ECOBridge.rebase.selector,\\n inflationMultiplier\\n );\\n\\n sendCrossDomainMessage(l2TokenBridge, _l2Gas, message);\\n }\\n```\\n
`StableOracleDAI` calculates `getPriceUSD` with inverted base/rate tokens for Chainlink price
high
`StableOracleDAI::getPriceUSD()` calculates the average price between the Uniswap pool price for a pair and the Chainlink feed as part of its result.\\nThe problem is that it uses `WETH/DAI` as the base/rate tokens for the pool, and `DAI/ETH` for the Chainlink feed, which is the opposite.\\nThis will incur in a huge price difference that will impact on the amount of USSD tokens being minted, while requesting the price from this oracle.\\nIn `StableOracleDAI::getPrice()` the `price` from the Chainlink feed `priceFeedDAIETH` returns the `price` as DAI/ETH.\\nThis can be checked on Etherscan and the Chainlink Feeds Page.\\nAlso note the comment on the code is misleading, as it is refering to another pair:\\nchainlink price data is 8 decimals for WETH/USD\\n```\\n/// constructor\\n priceFeedDAIETH = AggregatorV3Interface(\\n 0x773616E4d11A78F511299002da57A0a94577F1f4\\n );\\n\\n/// getPrice()\\n // chainlink price data is 8 decimals for WETH/USD, so multiply by 10 decimals to get 18 decimal fractional\\n //(uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound) = priceFeedDAIETH.latestRoundData();\\n (, int256 price, , , ) = priceFeedDAIETH.latestRoundData();\\n```\\n\\nLink to code\\nOn the other hand, the price coming from the Uniswap pool `DAIWethPrice` returns the price as `WETH/DAI`.\\nNote that the relation WETH/DAI is given by the orders of the token addresses passed as arguments, being the first the base token, and the second the quote token.\\nAlso note that the variable name `DAIWethPrice` is misleading as well as the base/rate are the opposite (although this doesn't affect the code).\\n```\\n uint256 DAIWethPrice = DAIEthOracle.quoteSpecificPoolsWithTimePeriod(\\n 1000000000000000000, // 1 Eth\\n 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, // WETH (base token) // @audit\\n 0x6B175474E89094C44Da98b954EedeAC495271d0F, // DAI (quote token) // @audit\\n pools, // DAI/WETH pool uni v3\\n 600 // period\\n );\\n```\\n\\nLink to code\\nFinally, both values are used to calculate an average price of in `((DAIWethPrice + uint256(price) * 1e10) / 2)`.\\nBut as seen, one has price in `DAI/ETH` and the other one in `WETH/DAI`, which leads to an incorrect result.\\n```\\n return\\n (wethPriceUSD * 1e18) /\\n ((DAIWethPrice + uint256(price) * 1e10) / 2);\\n```\\n\\nLink to code\\nThe average will be lower in this case, and the resulting price higher.\\nThis will be used by `USSD::mintForToken()` for calculating the amount of tokens to mint for the user, and thus giving them much more than they should.\\nAlso worth mentioning that `USSDRebalancer::rebalance()` also relies on the result of this price calculation and will make it perform trades with incorrect values.
Calculate the inverse of the `price` returned by the Chainlink feed so that it can be averaged with the pool `price`, making sure that both use the correct `WETH/DAI` and `ETH/DAI` base/rate tokens.
Users will receive far more USSD tokens than they should when they call `mintForToken()`, ruining the token value.\\nWhen performed the `USSDRebalancer::rebalance()`, all the calculations will be broken for the DAI oracle, leading to incorrect pool trades due to the error in `getPrice()`
```\\n/// constructor\\n priceFeedDAIETH = AggregatorV3Interface(\\n 0x773616E4d11A78F511299002da57A0a94577F1f4\\n );\\n\\n/// getPrice()\\n // chainlink price data is 8 decimals for WETH/USD, so multiply by 10 decimals to get 18 decimal fractional\\n //(uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound) = priceFeedDAIETH.latestRoundData();\\n (, int256 price, , , ) = priceFeedDAIETH.latestRoundData();\\n```\\n
`USSDRebalancer.sol#SellUSSDBuyCollateral` the check of whether collateral is DAI is wrong
high
The `SellUSSDBuyCollateral` function use `||` instand of `&&` to check whether the collateral is DAI. It is wrong and may cause `SellUSSDBuyCollateral` function revert.\\n```\\n196 for (uint256 i = 0; i < collateral.length; i++) {\\n197 uint256 collateralval = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * 1e18 / (10**IERC20MetadataUpgradeable(collateral[i].token).decimals()) * collateral[i].oracle.getPriceUSD() / 1e18;\\n198 if (collateralval * 1e18 / ownval < collateral[i].ratios[flutter]) {\\n199 if (collateral[i].token != uniPool.token0() || collateral[i].token != uniPool.token1()) {\\n200 // don't touch DAI if it's needed to be bought (it's already bought)\\n201 IUSSD(USSD).UniV3SwapInput(collateral[i].pathbuy, daibought/portions);\\n202 }\\n203 }\\n204 }\\n```\\n\\nLine 199 should use `&&` instand of `||` to ensure that the token is not DAI. If the token is DAI, the `UniV3SwapInput` function will revert because that DAI's `pathbuy` is empty.
```\\n for (uint256 i = 0; i < collateral.length; i// Add the line below\\n// Add the line below\\n) {\\n uint256 collateralval = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * 1e18 / (10**IERC20MetadataUpgradeable(collateral[i].token).decimals()) * collateral[i].oracle.getPriceUSD() / 1e18;\\n if (collateralval * 1e18 / ownval < collateral[i].ratios[flutter]) {\\n// Remove the line below\\n if (collateral[i].token != uniPool.token0() || collateral[i].token != uniPool.token1()) {\\n// Add the line below\\n if (collateral[i].token != uniPool.token0() && collateral[i].token != uniPool.token1()) {\\n // don't touch DAI if it's needed to be bought (it's already bought)\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathbuy, daibought/portions);\\n }\\n }\\n }\\n```\\n
The `SellUSSDBuyCollateral` will revert and USSD will become unstable.
```\\n196 for (uint256 i = 0; i < collateral.length; i++) {\\n197 uint256 collateralval = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * 1e18 / (10**IERC20MetadataUpgradeable(collateral[i].token).decimals()) * collateral[i].oracle.getPriceUSD() / 1e18;\\n198 if (collateralval * 1e18 / ownval < collateral[i].ratios[flutter]) {\\n199 if (collateral[i].token != uniPool.token0() || collateral[i].token != uniPool.token1()) {\\n200 // don't touch DAI if it's needed to be bought (it's already bought)\\n201 IUSSD(USSD).UniV3SwapInput(collateral[i].pathbuy, daibought/portions);\\n202 }\\n203 }\\n204 }\\n```\\n
The getOwnValuation() function contains errors in the price calculation
high
The getOwnValuation() function in the provided code has incorrect price calculation logic when token0() or token1() is equal to USSD. The error leads to inaccurate price calculations.\\nThe `USSDRebalancer.getOwnValuation()` function calculates the price based on the sqrtPriceX96 value obtained from the uniPool.slot0() function. The calculation depends on whether token0() is equal to USSD or not. If token0() is equal to USSD, the price calculation is performed as follows:\\n```\\n price = uint(sqrtPriceX96)*(uint(sqrtPriceX96))/(1e6) (96 * 2);\\n```\\n\\nHowever,there is an error in the price calculation logic. The calculation should be:\\n```\\nprice = uint(sqrtPriceX96) * uint(sqrtPriceX96) * 1e6 (96 * 2);\\n```\\n\\nIf token0() is not equal to USSD, the price calculation is slightly different:\\n```\\n price = uint(sqrtPriceX96)*(uint(sqrtPriceX96))*(1e18 /* 1e12 + 1e6 decimal representation */) (96 * 2);\\n // flip the fraction\\n price = (1e24 / price) / 1e12;\\n```\\n\\nThe calculation should be:\\n```\\n price = uint(sqrtPriceX96)*(uint(sqrtPriceX96))*(1e6 /* 1e12 + 1e6 decimal representation */) (96 * 2);\\n // flip the fraction\\n price = (1e24 / price) / 1e12;\\n```\\n
When token0() is USSD, the correct calculation should be uint(sqrtPriceX96) * uint(sqrtPriceX96) * 1e6 >> (96 * 2). When token1() is USSD, the correct calculation should be\\n```\\nprice = uint(sqrtPriceX96)*(uint(sqrtPriceX96))*(1e6 /* 1e12 + 1e6 decimal representation */) (96 * 2);\\n // flip the fraction\\n price = (1e24 / price) / 1e12;\\n```\\n
The incorrect price calculation in the getOwnValuation() function can lead to significant impact on the valuation of assets in the UniSwap V3 pool. The inaccurate prices can result in incorrect asset valuations, which may affect trading decisions, liquidity provision, and overall financial calculations based on the UniSwap V3 pool.
```\\n price = uint(sqrtPriceX96)*(uint(sqrtPriceX96))/(1e6) (96 * 2);\\n```\\n
The price from `StableOracleDAI` is returned with the incorrect number of decimals
high
The price returned from the `getPriceUSD` function of the `StableOracleDAI` is scaled up by `1e10`, which results in 28 decimals instead of the intended 18.\\nIn `StableOracleDAI` the `getPriceUSD` function is defined as follows...\\n```\\n function getPriceUSD() external view override returns (uint256) {\\n address[] memory pools = new address[](1);\\n pools[0] = 0x60594a405d53811d3BC4766596EFD80fd545A270;\\n uint256 DAIWethPrice = DAIEthOracle.quoteSpecificPoolsWithTimePeriod(\\n 1000000000000000000, // 1 Eth\\n 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, // WETH (base token)\\n 0x6B175474E89094C44Da98b954EedeAC495271d0F, // DAI (quote token)\\n pools, // DAI/WETH pool uni v3\\n 600 // period\\n );\\n\\n uint256 wethPriceUSD = ethOracle.getPriceUSD();\\n\\n // chainlink price data is 8 decimals for WETH/USD, so multiply by 10 decimals to get 18 decimal fractional\\n //(uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound) = priceFeedDAIETH.latestRoundData();\\n (, int256 price,,,) = priceFeedDAIETH.latestRoundData();\\n\\n return (wethPriceUSD * 1e18) / ((DAIWethPrice + uint256(price) * 1e10) / 2);\\n }\\n```\\n\\nThe assumption is made that the `DAIWethPrice` is 8 decimals, and is therefore multiplied by `1e10` in the return statement to scale it up to 18 decimals.\\nThe other price feeds used in the protocol are indeed received with decimals, however, the Chainlink DAI/ETH price feed returns a value with 18 decimals as can be seen on their site.
Remove the `* 1e10` from the return statement.\\n```\\n// Remove the line below\\n return (wethPriceUSD * 1e18) / ((DAIWethPrice // Add the line below\\n uint256(price) * 1e10) / 2);\\n// Add the line below\\n return (wethPriceUSD * 1e18) / (DAIWethPrice // Add the line below\\n uint256(price) / 2);\\n```\\n
This means that the price returned from the `getPriceUSD` function is scaled up by `1e10`, which results in 28 decimals instead of the intended 18, drastically overvaluing the DAI/USD price.\\nThis will result in the USSD token price being a tiny fraction of what it is intended to be. Instead of being pegged to $1, it will be pegged to $0.0000000001, completely defeating the purpose of the protocol.\\nFor example, if a user calls `USSD.mintForToken`, supplying DAI, they'll be able to mint `1e10` times more USSD than intended.
```\\n function getPriceUSD() external view override returns (uint256) {\\n address[] memory pools = new address[](1);\\n pools[0] = 0x60594a405d53811d3BC4766596EFD80fd545A270;\\n uint256 DAIWethPrice = DAIEthOracle.quoteSpecificPoolsWithTimePeriod(\\n 1000000000000000000, // 1 Eth\\n 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, // WETH (base token)\\n 0x6B175474E89094C44Da98b954EedeAC495271d0F, // DAI (quote token)\\n pools, // DAI/WETH pool uni v3\\n 600 // period\\n );\\n\\n uint256 wethPriceUSD = ethOracle.getPriceUSD();\\n\\n // chainlink price data is 8 decimals for WETH/USD, so multiply by 10 decimals to get 18 decimal fractional\\n //(uint80 roundID, int256 price, uint256 startedAt, uint256 timeStamp, uint80 answeredInRound) = priceFeedDAIETH.latestRoundData();\\n (, int256 price,,,) = priceFeedDAIETH.latestRoundData();\\n\\n return (wethPriceUSD * 1e18) / ((DAIWethPrice + uint256(price) * 1e10) / 2);\\n }\\n```\\n
Wrong computation of the amountToSellUnit variable
high
The variable `amountToSellUnits` is computed wrongly in the code which will lead to an incorrect amount of collateral to be sold.\\nThe `BuyUSSDSellCollateral()` function is used to sell collateral during a peg-down recovery event. The computation of the amount to sell is computed using the following formula:\\n```\\n// @audit-issue Wrong computation\\nuint256 amountToSellUnits = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * ((amountToBuyLeftUSD * 1e18 / collateralval) / 1e18) / 1e18;\\n```\\n\\nThe idea is to sell an amount which is equivalent (in USD) to the ratio of `amountToBuyLeftUSD / collateralval`. Flattening the equation it ends up as:\\n```\\nuint256 amountToSellUnits = (collateralBalance * amountToBuyLeftUSD * 1e18) / (collateralval * 1e18 * 1e18);\\n\\n// Reducing the equation\\nuint256 amountToSellUnits = (collateralBalance * amountToBuyLeftUSD) / (collateralval * 1e18);\\n```\\n\\n`amountToBuyLeftUSD` and `collateralval` already have 18 decimals so their decimals get cancelled together which will lead the last 1e18 factor as not necessary.
Issue Wrong computation of the amountToSellUnit variable\\nDelete the last 1e18 factor
The contract will sell an incorrect amount of collateral during a peg-down recovery event.
```\\n// @audit-issue Wrong computation\\nuint256 amountToSellUnits = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * ((amountToBuyLeftUSD * 1e18 / collateralval) / 1e18) / 1e18;\\n```\\n
Calls to Oracles don't check for stale prices
medium
Calls to Oracles don't check for stale prices.\\nNone of the oracle calls check for stale prices, for example StableOracleDAI.getPriceUSD():\\n```\\n(, int256 price, , , ) = priceFeedDAIETH.latestRoundData();\\n\\nreturn\\n (wethPriceUSD * 1e18) /\\n ((DAIWethPrice + uint256(price) * 1e10) / 2);\\n```\\n
Read the `updatedAt` parameter from the calls to `latestRoundData()` and verify that it isn't older than a set amount, eg:\\n```\\nif (updatedAt < block.timestamp - 60 * 60 /* 1 hour */) {\\n revert("stale price feed");\\n}\\n```\\n
Oracle price feeds can become stale due to a variety of reasons. Using a stale price will result in incorrect calculations in most of the key functionality of USSD & USSDRebalancer contracts.
```\\n(, int256 price, , , ) = priceFeedDAIETH.latestRoundData();\\n\\nreturn\\n (wethPriceUSD * 1e18) /\\n ((DAIWethPrice + uint256(price) * 1e10) / 2);\\n```\\n
rebalance process incase of selling the collateral, could revert because of underflow calculation
medium
rebalance process, will try to sell the collateral in case of peg-down. However, the process can revert because the calculation can underflow.\\nInside `rebalance()` call, if `BuyUSSDSellCollateral()` is triggered, it will try to sell the current collateral to `baseAsset`. The asset that will be sold (amountToSellUnits) first calculated. Then swap it to `baseAsset` via uniswap. However, when subtracting `amountToBuyLeftUSD`, it with result of `(IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore)`. There is no guarantee `amountToBuyLeftUSD` always bigger than `(IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore)`.\\nThis causing the call could revert in case `(IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore)` > `amountToBuyLeftUSD`.\\nThere are two branch where `amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore)` is performed :\\nIncase `collateralval > amountToBuyLeftUSD`\\n`collateralval` is calculated using oracle price, thus the result of swap not guaranteed to reflect the proportion of `amountToBuyLefUSD` against `collateralval` ratio, and could result in returning `baseAsset` larger than expected. And potentially `(IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore)` > `amountToBuyLeftUSD`\\n```\\n uint256 collateralval = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * 1e18 / (10**IERC20MetadataUpgradeable(collateral[i].token).decimals()) * collateral[i].oracle.getPriceUSD() / 1e18;\\n if (collateralval > amountToBuyLeftUSD) {\\n // sell a portion of collateral and exit\\n if (collateral[i].pathsell.length > 0) {\\n uint256 amountBefore = IERC20Upgradeable(baseAsset).balanceOf(USSD);\\n uint256 amountToSellUnits = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * ((amountToBuyLeftUSD * 1e18 / collateralval) / 1e18) / 1e18;\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathsell, amountToSellUnits);\\n amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n DAItosell += (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n } else {\\n```\\n\\nIncase `collateralval < amountToBuyLeftUSD`\\nThis also can't guarantee `(IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore)` < `amountToBuyLeftUSD`.\\n```\\n if (collateralval >= amountToBuyLeftUSD / 20) {\\n uint256 amountBefore = IERC20Upgradeable(baseAsset).balanceOf(USSD);\\n // sell all collateral and move to next one\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathsell, IERC20Upgradeable(collateral[i].token).balanceOf(USSD));\\n amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n DAItosell += (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n }\\n```\\n
Check if `(IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore)` > `amountToBuyLeftUSD`, in that case, just set `amountToBuyLeftUSD` to 0.\\n```\\n // rest of code\\n uint baseAssetChange = IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n if (baseAssetChange > amountToBuyLeftUSD) {\\n amountToBuyLeftUSD = 0;\\n } else {\\n amountToBuyLeftUSD -= baseAssetChange;\\n }\\n DAItosell += baseAssetChange;\\n // rest of code\\n```\\n
Rebalance process can revert caused by underflow calculation.
```\\n uint256 collateralval = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * 1e18 / (10**IERC20MetadataUpgradeable(collateral[i].token).decimals()) * collateral[i].oracle.getPriceUSD() / 1e18;\\n if (collateralval > amountToBuyLeftUSD) {\\n // sell a portion of collateral and exit\\n if (collateral[i].pathsell.length > 0) {\\n uint256 amountBefore = IERC20Upgradeable(baseAsset).balanceOf(USSD);\\n uint256 amountToSellUnits = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * ((amountToBuyLeftUSD * 1e18 / collateralval) / 1e18) / 1e18;\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathsell, amountToSellUnits);\\n amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n DAItosell += (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n } else {\\n```\\n
StableOracleWBTC use BTC/USD chainlink oracle to price WBTC which is problematic if WBTC depegs
medium
The StableOracleWBTC contract utilizes a BTC/USD Chainlink oracle to determine the price of WBTC. However, this approach can lead to potential issues if WBTC were to depeg from BTC. In such a scenario, WBTC would no longer maintain an equivalent value to BTC. This can result in significant problems, including borrowing against a devalued asset and the accumulation of bad debt. Given that the protocol continues to value WBTC based on BTC/USD, the issuance of bad loans would persist, exacerbating the overall level of bad debt.\\nImportant to note that this is like a 2 in 1 report as the same idea could work on the StableOracleWBGL contract too.\\nThe vulnerability lies in the reliance on a single BTC/USD Chainlink oracle to obtain the price of WBTC. If the bridge connecting WBTC to BTC becomes compromised and WBTC depegs, WBTC may depeg from BTC. Consequently, WBTC's value would no longer be equivalent to BTC, potentially rendering it worthless (hopefully this never happens). The use of the BTC/USD oracle to price WBTC poses risks to the protocol and its users.\\nThe following code snippet represents the relevant section of the StableOracleWBTC contract responsible for retrieving the price of WBTC using the BTC/USD Chainlink oracle:\\n```\\ncontract StableOracleWBTC is IStableOracle {\\n AggregatorV3Interface priceFeed;\\n\\n constructor() {\\n priceFeed = AggregatorV3Interface(\\n 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419\\n\\n );\\n }\\n\\n function getPriceUSD() external view override returns (uint256) {\\n (, int256 price, , , ) = priceFeed.latestRoundData();\\n // chainlink price data is 8 decimals for WBTC/USD\\n return uint256(price) * 1e10;\\n }\\n}\\n```\\n\\nNB: key to note that the above pricefeed is set to the wrong aggregator, the correct one is this: `0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599`
To mitigate the vulnerability mentioned above, it is strongly recommended to implement a double oracle setup for WBTC pricing. This setup would involve integrating both the BTC/USD Chainlink oracle and an additional on-chain liquidity-based oracle, such as UniV3 TWAP.\\nThe double oracle setup serves two primary purposes. Firstly, it reduces the risk of price manipulation by relying on the Chainlink oracle, which ensures accurate pricing for WBTC. Secondly, incorporating an on-chain liquidity-based oracle acts as a safeguard against WBTC depegging. By monitoring the price derived from the liquidity-based oracle and comparing it to the Chainlink oracle's price, borrowing activities can be halted if the threshold deviation (e.g., 2% lower) is breached.\\nAdopting a double oracle setup enhances the protocol's stability and minimizes the risks associated with WBTC depegging. It ensures accurate valuation, reduces the accumulation of bad debt, and safeguards the protocol and its users
Should the WBTC bridge become compromised or WBTC depeg from BTC, the protocol would face severe consequences. The protocol would be burdened with a substantial amount of bad debt stemming from outstanding loans secured by WBTC. Additionally, due to the protocol's reliance on the BTC/USD oracle, the issuance of loans against WBTC would persist even if its value has significantly deteriorated. This would lead to an escalation in bad debt, negatively impacting the protocol's financial stability and overall performance.
```\\ncontract StableOracleWBTC is IStableOracle {\\n AggregatorV3Interface priceFeed;\\n\\n constructor() {\\n priceFeed = AggregatorV3Interface(\\n 0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419\\n\\n );\\n }\\n\\n function getPriceUSD() external view override returns (uint256) {\\n (, int256 price, , , ) = priceFeed.latestRoundData();\\n // chainlink price data is 8 decimals for WBTC/USD\\n return uint256(price) * 1e10;\\n }\\n}\\n```\\n
Inaccurate collateral factor calculation due to missing collateral asset
medium
The function `collateralFactor()` in the smart contract calculates the collateral factor for the protocol but fails to account for the removal of certain collateral assets. As a result, the total value of the removed collateral assets is not included in the calculation, leading to an inaccurate collateral factor.\\nThe `collateralFactor()` function calculates the current collateral factor for the protocol. It iterates through each collateral asset in the system and calculates the total value of all collateral assets in USD.\\nFor each collateral asset, the function retrieves its balance and converts it to a USD value by multiplying it with the asset's price in USD obtained from the corresponding oracle. The balance is adjusted for the decimal precision of the asset. These USD values are accumulated to calculate the totalAssetsUSD.\\n```\\n function collateralFactor() public view override returns (uint256) {\\n uint256 totalAssetsUSD = 0;\\n for (uint256 i = 0; i < collateral.length; i++) {\\n totalAssetsUSD +=\\n (((IERC20Upgradeable(collateral[i].token).balanceOf(\\n address(this)\\n ) * 1e18) /\\n (10 **\\n IERC20MetadataUpgradeable(collateral[i].token)\\n .decimals())) *\\n collateral[i].oracle.getPriceUSD()) /\\n 1e18;\\n }\\n\\n return (totalAssetsUSD * 1e6) / totalSupply();\\n }\\n```\\n\\nHowever, when a collateral asset is removed from the collateral list, the `collateralFactor` function fails to account for its absence. This results in an inaccurate calculation of the collateral factor. Specifically, the totalAssetsUSD variable does not include the value of the removed collateral asset, leading to an underestimation of the total collateral value. The function `SellUSSDBuyCollateral()` in the smart contract is used for rebalancing. However, it relies on the `collateralFactor` calculation, which has been found to be inaccurate. The `collateralFactor` calculation does not accurately assess the portions of collateral assets to be bought or sold during rebalancing. This discrepancy can lead to incorrect rebalancing decisions and potentially impact the stability and performance of the protocol.\\n```\\n function removeCollateral(uint256 _index) public onlyControl {\\n collateral[_index] = collateral[collateral.length - 1];\\n collateral.pop();\\n }\\n```\\n
Ensure accurate calculations and maintain the integrity of the collateral factor metric in the protocol's risk management system.
As a consequence, the reported collateral factor may be lower than it should be, potentially affecting the risk assessment and stability of the protocol.
```\\n function collateralFactor() public view override returns (uint256) {\\n uint256 totalAssetsUSD = 0;\\n for (uint256 i = 0; i < collateral.length; i++) {\\n totalAssetsUSD +=\\n (((IERC20Upgradeable(collateral[i].token).balanceOf(\\n address(this)\\n ) * 1e18) /\\n (10 **\\n IERC20MetadataUpgradeable(collateral[i].token)\\n .decimals())) *\\n collateral[i].oracle.getPriceUSD()) /\\n 1e18;\\n }\\n\\n return (totalAssetsUSD * 1e6) / totalSupply();\\n }\\n```\\n
Inconsistency handling of DAI as collateral in the BuyUSSDSellCollateral function
medium
DAI is the base asset of the `USSD.sol` contract, when a rebalacing needs to occur during a peg-down recovery, collateral is sold for DAI, which then is used to buy USSD in the DAI / USSD uniswap pool. Hence, when DAI is the collateral, this is not sold because there no existe a path to sell DAI for DAI.\\nThe above behavior is handled when collateral is about to be sold for DAI, see the comment `no need to swap DAI` (link to the code):\\n```\\nif (collateralval > amountToBuyLeftUSD) {\\n // sell a portion of collateral and exit\\n if (collateral[i].pathsell.length > 0) {\\n uint256 amountBefore = IERC20Upgradeable(baseAsset).balanceOf(USSD);\\n uint256 amountToSellUnits = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * ((amountToBuyLeftUSD * 1e18 / collateralval) / 1e18) / 1e18;\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathsell, amountToSellUnits);\\n amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n DAItosell += (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n } \\n else {\\n // no need to swap DAI\\n DAItosell = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * amountToBuyLeftUSD / collateralval;\\n }\\n}\\n\\nelse {\\n // @audit-issue Not handling the case where this is DAI as is done above.\\n // sell all or skip (if collateral is too little, 5% treshold)\\n if (collateralval >= amountToBuyLeftUSD / 20) {\\n uint256 amountBefore = IERC20Upgradeable(baseAsset).balanceOf(USSD);\\n // sell all collateral and move to next one\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathsell, IERC20Upgradeable(collateral[i].token).balanceOf(USSD));\\n amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n DAItosell += (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n }\\n}\\n```\\n\\nThe problem is in the `else branch` of the first if statement `collateralval > amountToBuyLeftUSD`, which lacks the check `if (collateral[i].pathsell.length > 0)`
Handle the case as is the done on the if branch of collateralval > amountToBuyLeftUSD:\\n```\\nif (collateral[i].pathsell.length > 0) {\\n // Sell collateral for DAI\\n}\\nelse {\\n // No need to swap DAI\\n}\\n```\\n
A re-balancing on a peg-down recovery will fail if the `collateralval` of DAI is less than `amountToBuyLeftUSD` but greater than `amountToBuyLeftUSD / 20` since the DAI collateral does not have a sell path.
```\\nif (collateralval > amountToBuyLeftUSD) {\\n // sell a portion of collateral and exit\\n if (collateral[i].pathsell.length > 0) {\\n uint256 amountBefore = IERC20Upgradeable(baseAsset).balanceOf(USSD);\\n uint256 amountToSellUnits = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * ((amountToBuyLeftUSD * 1e18 / collateralval) / 1e18) / 1e18;\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathsell, amountToSellUnits);\\n amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n DAItosell += (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n } \\n else {\\n // no need to swap DAI\\n DAItosell = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * amountToBuyLeftUSD / collateralval;\\n }\\n}\\n\\nelse {\\n // @audit-issue Not handling the case where this is DAI as is done above.\\n // sell all or skip (if collateral is too little, 5% treshold)\\n if (collateralval >= amountToBuyLeftUSD / 20) {\\n uint256 amountBefore = IERC20Upgradeable(baseAsset).balanceOf(USSD);\\n // sell all collateral and move to next one\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathsell, IERC20Upgradeable(collateral[i].token).balanceOf(USSD));\\n amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n DAItosell += (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore);\\n }\\n}\\n```\\n
Risk of Incorrect Asset Pricing by StableOracle in Case of Underlying Aggregator Reaching minAnswer
medium
Chainlink aggregators have a built-in circuit breaker to prevent the price of an asset from deviating outside a predefined price range. This circuit breaker may cause the oracle to persistently return the minPrice instead of the actual asset price in the event of a significant price drop, as witnessed during the LUNA crash.\\nStableOracleDAI.sol, StableOracleWBTC.sol, and StableOracleWETH.sol utilize the ChainlinkFeedRegistry to fetch 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 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 extracts the linked aggregator and requests round data from it. If an asset's price falls below the minPrice, the protocol continues to value the token at the minPrice rather than its real value. This discrepancy could have the protocol end up minting drastically larger amount of stableCoinAmount as well as returning a much bigger collateral factor.\\nFor instance, if TokenA's minPrice is $1 and its price falls to $0.10, the aggregator continues to report $1, rendering the related function calls to entail a value that is ten times the actual value.\\nIt's important to note that while Chainlink oracles form part of the OracleAggregator system and the use of a combination of oracles could potentially prevent such a situation, there's still a risk. Secondary oracles, such as Band, could potentially be exploited by a malicious user who can DDOS relayers to prevent price updates. Once the price becomes stale, the Chainlink oracle's price would be the sole reference, posing a significant risk.
StableOracle should cross-check the returned answer against the minPrice/maxPrice and revert if the answer is outside of these bounds:\\n```\\n (, int256 price, , uint256 updatedAt, ) = registry.latestRoundData(\\n token,\\n USD\\n );\\n \\n if (price >= maxPrice or price <= minPrice) revert();\\n```\\n\\nThis ensures that a false price will not be returned if the underlying asset's value hits the minPrice.
In the event of an asset crash (like LUNA), the protocol can be manipulated to handle calls 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 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
`BuyUSSDSellCollateral()` always sells 0 amount if need to sell part of collateral
medium
Due to rounding error there is misbehaviour in `BuyUSSDSellCollateral()` function. It results in selling 0 amount of collateral.\\nSuppose the only collateral in protocol is 1 WBTC; 1 WBTC costs 30_000 USD; UniV3Pool DAI/ USSD has following liquidity: (3000e6 USSD, 2000e18 DAI) And also USSD is underpriced so call rebalance:\\n```\\n function rebalance() override public {\\n uint256 ownval = getOwnValuation(); // it low enough to dive into if statement (see line below) \\n (uint256 USSDamount, uint256 DAIamount) = getSupplyProportion(); // (3000e6 USSD, 2000e18 DAI)\\n if (ownval < 1e6 - threshold) {\\n // peg-down recovery\\n BuyUSSDSellCollateral((USSDamount - DAIamount / 1e12)/2); // 500 * 1e6 = (3000e6 - 2000e18 / 1e12) / 2\\n```\\n\\nTake a look into BuyUSSDSellCollateral (follow comments):\\n```\\n function BuyUSSDSellCollateral(uint256 amountToBuy) internal { // 500e6\\n CollateralInfo[] memory collateral = IUSSD(USSD).collateralList();\\n //uint amountToBuyLeftUSD = amountToBuy * 1e12 * 1e6 / getOwnValuation();\\n uint amountToBuyLeftUSD = amountToBuy * 1e12; // 500e18\\n uint DAItosell = 0;\\n // Sell collateral in order of collateral array\\n for (uint256 i = 0; i < collateral.length; i++) {\\n // 30_000e18 = 1e8 * 1e18 / 10**8 * 30_000e18 / 1e18\\n uint256 collateralval = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * 1e18 / (10**IERC20MetadataUpgradeable(collateral[i].token).decimals()) * collateral[i].oracle.getPriceUSD() / 1e18;\\n if (collateralval > amountToBuyLeftUSD) {\\n // sell a portion of collateral and exit\\n if (collateral[i].pathsell.length > 0) {\\n uint256 amountBefore = IERC20Upgradeable(baseAsset).balanceOf(USSD); // 0\\n // amountToSellUnits = 1e8 * ((500e18 * 1e18 / 30_000e18) / 1e18) / 1e18 = 1e8 * (0) / 1e18 = 0\\n uint256 amountToSellUnits = IERC20Upgradeable(collateral[i].token).balanceOf(USSD) * ((amountToBuyLeftUSD * 1e18 / collateralval) / 1e18) / 1e18;\\n // and finally executes trade of 0 WBTC\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathsell, amountToSellUnits);\\n amountToBuyLeftUSD -= (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore); // 0 = 0 - 0\\n DAItosell += (IERC20Upgradeable(baseAsset).balanceOf(USSD) - amountBefore); // 0 += 0\\n // rest of code\\n```\\n\\nSo protocol will not buy DAI and will not sell DAI for USSD in UniswapV3Pool to support peg of USSD to DAI
Refactor formula of amountToSellUnits\\n```\\n// uint256 amountToSellUnits = (decimals of collateral) * (DAI amount to get for sell) / (price of 1 token of collateral)\\nuint256 amountToSellUnits = collateral[i].token).decimals() * amountToBuyLeftUSD / collateral[i].oracle.getPriceUSD()\\n```\\n
Protocol is not able of partial selling of collateral for token. It block algorithmic pegging of USSD to DAI
```\\n function rebalance() override public {\\n uint256 ownval = getOwnValuation(); // it low enough to dive into if statement (see line below) \\n (uint256 USSDamount, uint256 DAIamount) = getSupplyProportion(); // (3000e6 USSD, 2000e18 DAI)\\n if (ownval < 1e6 - threshold) {\\n // peg-down recovery\\n BuyUSSDSellCollateral((USSDamount - DAIamount / 1e12)/2); // 500 * 1e6 = (3000e6 - 2000e18 / 1e12) / 2\\n```\\n
If collateral factor is high enough, flutter ends up being out of bounds
medium
In `USSDRebalancer` contract, function `SellUSSDBuyCollateral` will revert everytime a rebalance calls it, provided the collateral factor is greater than all the elements of the `flutterRatios` array.\\nFunction `SellUSSDBuyCollateral` calculates `flutter` as the lowest index of the `flutterRatios` array for which the collateral factor is smaller than the `flutter` ratio.\\n```\\nuint256 cf = IUSSD(USSD).collateralFactor();\\nuint256 flutter = 0;\\nfor (flutter = 0; flutter < flutterRatios.length; flutter++) {\\n if (cf < flutterRatios[flutter]) {\\n break;\\n }\\n}\\n```\\n\\nThe problem arises when, if collateral factor is greater than all flutter values, after the loop `flutter = flutterRatios.length`.\\nThis `flutter` value is used afterwards here:\\n```\\n// rest of code\\nif (collateralval * 1e18 / ownval < collateral[i].ratios[flutter]) {\\n portions++;\\n}\\n// rest of code\\n```\\n\\nAnd here:\\n```\\n// rest of code\\nif (collateralval * 1e18 / ownval < collateral[i].ratios[flutter]) {\\n if (collateral[i].token != uniPool.token0() || collateral[i].token != uniPool.token1()) {\\n // don't touch DAI if it's needed to be bought (it's already bought)\\n IUSSD(USSD).UniV3SwapInput(collateral[i].pathbuy, daibought/portions);\\n }\\n}\\n// rest of code\\n```\\n\\nAs we can see in the tests of the project, the flutterRatios array and the collateral `ratios` array are set to be of the same length, so if flutter = flutterRatios.length, any call to that index in the `ratios` array will revert with an index out of bounds.
When checking `collateral[i].ratios[flutter]` always check first that flutter is `< flutterRatios.length`.
High, when the collateral factor reaches certain level, a rebalance that calls `SellUSSDBuyCollateral` will always revert.
```\\nuint256 cf = IUSSD(USSD).collateralFactor();\\nuint256 flutter = 0;\\nfor (flutter = 0; flutter < flutterRatios.length; flutter++) {\\n if (cf < flutterRatios[flutter]) {\\n break;\\n }\\n}\\n```\\n
claimCOMPAndTransfer() COMP may be locked into the contract
high
Malicious users can keep front-run `claimCOMPAndTransfer()` to trigger `COMPTROLLER.claimComp()` first, causing `netBalance` in `claimCOMPAndTransfer()` to be 0 all the time, resulting in `COMP` not being transferred out and locked in the contract\\n`claimCOMPAndTransfer()` use for "Claims COMP incentives earned and transfers to the treasury manager contract" The code is as follows:\\n```\\n function claimCOMPAndTransfer(address[] calldata cTokens)\\n external\\n override\\n onlyManagerContract\\n nonReentrant\\n returns (uint256)\\n {\\n uint256 balanceBefore = COMP.balanceOf(address(this));\\n COMPTROLLER.claimComp(address(this), cTokens);\\n uint256 balanceAfter = COMP.balanceOf(address(this));\\n\\n // NOTE: the onlyManagerContract modifier prevents a transfer to address(0) here\\n uint256 netBalance = balanceAfter.sub(balanceBefore); //<-------@only transfer out `netBalance`\\n if (netBalance > 0) {\\n COMP.safeTransfer(msg.sender, netBalance);\\n }\\n\\n // NOTE: TreasuryManager contract will emit a COMPHarvested event\\n return netBalance;\\n```\\n\\nFrom the above code, we can see that this method only turns out the difference value `netBalance` But `COMPTROLLER.claimComp()` can be called by anyone, if there is a malicious user front-run this transcation to triggers `COMPTROLLER.claimComp()` first This will cause thenetBalance to be 0 all the time, resulting in `COMP` not being transferred out and being locked in the contract.\\nThe following code is from `Comptroller.sol`\\n```\\n function claimComp(address holder, CToken[] memory cTokens) public { //<----------anyone can call it\\n address[] memory holders = new address[](1);\\n holders[0] = holder;\\n claimComp(holders, cTokens, true, true);\\n }\\n```\\n
Transfer all balances, not using `netBalance`
`COMP` may be locked into the contract
```\\n function claimCOMPAndTransfer(address[] calldata cTokens)\\n external\\n override\\n onlyManagerContract\\n nonReentrant\\n returns (uint256)\\n {\\n uint256 balanceBefore = COMP.balanceOf(address(this));\\n COMPTROLLER.claimComp(address(this), cTokens);\\n uint256 balanceAfter = COMP.balanceOf(address(this));\\n\\n // NOTE: the onlyManagerContract modifier prevents a transfer to address(0) here\\n uint256 netBalance = balanceAfter.sub(balanceBefore); //<-------@only transfer out `netBalance`\\n if (netBalance > 0) {\\n COMP.safeTransfer(msg.sender, netBalance);\\n }\\n\\n // NOTE: TreasuryManager contract will emit a COMPHarvested event\\n return netBalance;\\n```\\n
repayAccountPrimeDebtAtSettlement() user lost residual cash
high
in `repayAccountPrimeDebtAtSettlement()` Incorrect calculation of `primeCashRefund` value (always == 0) Resulting in the loss of the user's residual cash\\nwhen settle Vault Account will execute settleVaultAccount()->repayAccountPrimeDebtAtSettlement() In the `repayAccountPrimeDebtAtSettlement()` method the residual amount will be refunded to the user The code is as follows.\\n```\\n function repayAccountPrimeDebtAtSettlement(\\n PrimeRate memory pr,\\n VaultStateStorage storage primeVaultState,\\n uint16 currencyId,\\n address vault,\\n address account,\\n int256 accountPrimeCash,\\n int256 accountPrimeStorageValue\\n ) internal returns (int256 finalPrimeDebtStorageValue, bool didTransfer) {\\n// rest of code\\n\\n if (netPrimeDebtRepaid < accountPrimeStorageValue) {\\n // If the net debt change is greater than the debt held by the account, then only\\n // decrease the total prime debt by what is held by the account. The residual amount\\n // will be refunded to the account via a direct transfer.\\n netPrimeDebtChange = accountPrimeStorageValue;\\n finalPrimeDebtStorageValue = 0;\\n\\n int256 primeCashRefund = pr.convertFromUnderlying(\\n pr.convertDebtStorageToUnderlying(netPrimeDebtChange.sub(accountPrimeStorageValue)) //<--------@audit always ==0\\n );\\n TokenHandler.withdrawPrimeCash(\\n account, currencyId, primeCashRefund, pr, false // ETH will be transferred natively\\n );\\n didTransfer = true;\\n } else {\\n```\\n\\nFrom the above code we can see that there is a spelling error\\nnetPrimeDebtChange = accountPrimeStorageValue;\\nprimeCashRefund = netPrimeDebtChange.sub(accountPrimeStorageValue) so primeCashRefund always ==0\\nshould be `primeCashRefund = netPrimeDebtRepaid - accountPrimeStorageValue`
```\\n function repayAccountPrimeDebtAtSettlement(\\n PrimeRate memory pr,\\n VaultStateStorage storage primeVaultState,\\n uint16 currencyId,\\n address vault,\\n address account,\\n int256 accountPrimeCash,\\n int256 accountPrimeStorageValue\\n ) internal returns (int256 finalPrimeDebtStorageValue, bool didTransfer) {\\n// rest of code\\n\\n if (netPrimeDebtRepaid < accountPrimeStorageValue) {\\n // If the net debt change is greater than the debt held by the account, then only\\n // decrease the total prime debt by what is held by the account. The residual amount\\n // will be refunded to the account via a direct transfer.\\n netPrimeDebtChange = accountPrimeStorageValue;\\n finalPrimeDebtStorageValue = 0;\\n\\n int256 primeCashRefund = pr.convertFromUnderlying(\\n- pr.convertDebtStorageToUnderlying(netPrimeDebtChange.sub(accountPrimeStorageValue))\\n+ pr.convertDebtStorageToUnderlying(netPrimeDebtRepaid.sub(accountPrimeStorageValue)) \\n );\\n TokenHandler.withdrawPrimeCash(\\n account, currencyId, primeCashRefund, pr, false // ETH will be transferred natively\\n );\\n didTransfer = true;\\n } else {\\n```\\n
`primeCashRefund` always == 0 , user lost residual cash
```\\n function repayAccountPrimeDebtAtSettlement(\\n PrimeRate memory pr,\\n VaultStateStorage storage primeVaultState,\\n uint16 currencyId,\\n address vault,\\n address account,\\n int256 accountPrimeCash,\\n int256 accountPrimeStorageValue\\n ) internal returns (int256 finalPrimeDebtStorageValue, bool didTransfer) {\\n// rest of code\\n\\n if (netPrimeDebtRepaid < accountPrimeStorageValue) {\\n // If the net debt change is greater than the debt held by the account, then only\\n // decrease the total prime debt by what is held by the account. The residual amount\\n // will be refunded to the account via a direct transfer.\\n netPrimeDebtChange = accountPrimeStorageValue;\\n finalPrimeDebtStorageValue = 0;\\n\\n int256 primeCashRefund = pr.convertFromUnderlying(\\n pr.convertDebtStorageToUnderlying(netPrimeDebtChange.sub(accountPrimeStorageValue)) //<--------@audit always ==0\\n );\\n TokenHandler.withdrawPrimeCash(\\n account, currencyId, primeCashRefund, pr, false // ETH will be transferred natively\\n );\\n didTransfer = true;\\n } else {\\n```\\n
`VaultAccountSecondaryDebtShareStorage.maturity` will be cleared prematurely
high
`VaultAccountSecondaryDebtShareStorage.maturity` will be cleared prematurely during liquidation\\nIf both the `accountDebtOne` and `accountDebtTwo` of secondary currencies are zero, Notional will consider both debt shares to be cleared to zero, and the maturity will be cleared as well as shown below.\\n```\\nFile: VaultSecondaryBorrow.sol\\n function _setAccountMaturity(\\n VaultAccountSecondaryDebtShareStorage storage accountStorage,\\n int256 accountDebtOne,\\n int256 accountDebtTwo,\\n uint40 maturity\\n ) private {\\n if (accountDebtOne == 0 && accountDebtTwo == 0) {\\n // If both debt shares are cleared to zero, clear the maturity as well.\\n accountStorage.maturity = 0;\\n } else {\\n // In all other cases, set the account to the designated maturity\\n accountStorage.maturity = maturity;\\n }\\n }\\n```\\n\\n`VaultLiquidationAction.deleverageAccount` function\\nWithin the `VaultLiquidationAction.deleverageAccount` function, it will call the `_reduceAccountDebt` function.\\nReferring to the `_reduceAccountDebt` function below. Assume that the `currencyIndex` reference to a secondary currency. In this case, the else logic in Line 251 will be executed. An important point to take note of that is critical to understand this bug is that only ONE of the prime rates will be set as it assumes that the other prime rate will not be used (Refer to Line 252 - 255). However, this assumption is incorrect.\\nAssume that the `currencyIndex` is `1`. Then `netUnderlyingDebtOne` parameter will be set to a non-zero value (depositUnderlyingInternal) at Line 261 while `netUnderlyingDebtTwo` parameter will be set to zero at Line 262. This is because, in Line 263 of the `_reduceAccountDebt` function, the `pr[0]` will be set to the prime rate, while the `pr[1]` will be zero or empty. It will then proceed to call the `VaultSecondaryBorrow.updateAccountSecondaryDebt`\\n```\\nFile: VaultLiquidationAction.sol\\n function _reduceAccountDebt(\\n VaultConfig memory vaultConfig,\\n VaultState memory vaultState,\\n VaultAccount memory vaultAccount,\\n PrimeRate memory primeRate,\\n uint256 currencyIndex,\\n int256 depositUnderlyingInternal,\\n bool checkMinBorrow\\n ) private {\\n if (currencyIndex == 0) {\\n vaultAccount.updateAccountDebt(vaultState, depositUnderlyingInternal, 0);\\n vaultState.setVaultState(vaultConfig);\\n } else {\\n // Only set one of the prime rates, the other prime rate is not used since\\n // the net debt amount is set to zero\\n PrimeRate[2] memory pr;\\n pr[currencyIndex - 1] = primeRate;\\n\\n VaultSecondaryBorrow.updateAccountSecondaryDebt(\\n vaultConfig,\\n vaultAccount.account,\\n vaultAccount.maturity,\\n currencyIndex == 1 ? depositUnderlyingInternal : 0,\\n currencyIndex == 2 ? depositUnderlyingInternal : 0,\\n pr,\\n checkMinBorrow\\n );\\n }\\n }\\n```\\n\\nWithin the `updateAccountSecondaryDebt` function, at Line 272, assume that `accountStorage.accountDebtTwo` is `100`. However, since `pr[1]` is not initialized, the `VaultStateLib.readDebtStorageToUnderlying` will return a zero value and set the `accountDebtTwo` to zero.\\nAssume that the liquidator calls the `deleverageAccount` function to clear all the debt of the `currencyIndex` secondary currency. Line 274 will be executed, and `accountDebtOne` will be set to zero.\\nNote that at this point, both `accountDebtOne` and `accountDebtTwo` are zero. At Line 301, the `_setAccountMaturity` will set the `accountStorage.maturity = 0` , which clears the vault account's maturity.\\nAn important point here is that the liquidator did not clear the `accountDebtTwo`. Yet, `accountDebtTwo` became zero in memory during the execution and caused Notional to wrongly assume that both debt shares had been cleared to zero.\\n```\\nFile: VaultSecondaryBorrow.sol\\n function updateAccountSecondaryDebt(\\n VaultConfig memory vaultConfig,\\n address account,\\n uint256 maturity,\\n int256 netUnderlyingDebtOne,\\n int256 netUnderlyingDebtTwo,\\n PrimeRate[2] memory pr,\\n bool checkMinBorrow\\n ) internal {\\n VaultAccountSecondaryDebtShareStorage storage accountStorage = \\n LibStorage.getVaultAccountSecondaryDebtShare()[account][vaultConfig.vault];\\n // Check maturity\\n uint256 accountMaturity = accountStorage.maturity;\\n require(accountMaturity == maturity || accountMaturity == 0);\\n \\n int256 accountDebtOne = VaultStateLib.readDebtStorageToUnderlying(pr[0], maturity, accountStorage.accountDebtOne); \\n int256 accountDebtTwo = VaultStateLib.readDebtStorageToUnderlying(pr[1], maturity, accountStorage.accountDebtTwo);\\n if (netUnderlyingDebtOne != 0) {\\n accountDebtOne = accountDebtOne.add(netUnderlyingDebtOne);\\n\\n _updateTotalSecondaryDebt(\\n vaultConfig, account, vaultConfig.secondaryBorrowCurrencies[0], maturity, netUnderlyingDebtOne, pr[0]\\n );\\n\\n accountStorage.accountDebtOne = VaultStateLib.calculateDebtStorage(pr[0], maturity, accountDebtOne)\\n .neg().toUint().toUint80();\\n }\\n\\n if (netUnderlyingDebtTwo != 0) {\\n accountDebtTwo = accountDebtTwo.add(netUnderlyingDebtTwo);\\n\\n _updateTotalSecondaryDebt(\\n vaultConfig, account, vaultConfig.secondaryBorrowCurrencies[1], maturity, netUnderlyingDebtTwo, pr[1]\\n );\\n\\n accountStorage.accountDebtTwo = VaultStateLib.calculateDebtStorage(pr[1], maturity, accountDebtTwo)\\n .neg().toUint().toUint80();\\n }\\n\\n if (checkMinBorrow) {\\n // No overflow on negation due to overflow checks above\\n require(accountDebtOne == 0 || vaultConfig.minAccountSecondaryBorrow[0] <= -accountDebtOne, "min borrow");\\n require(accountDebtTwo == 0 || vaultConfig.minAccountSecondaryBorrow[1] <= -accountDebtTwo, "min borrow");\\n }\\n\\n _setAccountMaturity(accountStorage, accountDebtOne, accountDebtTwo, maturity.toUint40());\\n }\\n```\\n\\nThe final state will be `VaultAccountSecondaryDebtShareStorage` as follows:\\n`maturity` and `accountDebtOne` are zero\\n`accountDebtTwo` = 100\\n```\\nstruct VaultAccountSecondaryDebtShareStorage {\\n // Maturity for the account's secondary borrows. This is stored separately from\\n // the vault account maturity to ensure that we have access to the proper state\\n // during a roll borrow position. It should never be allowed to deviate from the\\n // vaultAccount.maturity value (unless it is cleared to zero).\\n uint40 maturity;\\n // Account debt for the first secondary currency in either fCash or pCash denomination\\n uint80 accountDebtOne;\\n // Account debt for the second secondary currency in either fCash or pCash denomination\\n uint80 accountDebtTwo;\\n}\\n```\\n\\nFirstly, it does not make sense to have `accountDebtTwo` but no `maturity` in storage, which also means the vault account data is corrupted. Secondly, when `maturity` is zero, it also means that the vault account did not borrow anything from Notional. Lastly, many vault logic would break since it relies on the `maturity` value.\\n`VaultLiquidationAction.liquidateVaultCashBalance` function\\nThe root cause lies in the implementation of the `_reduceAccountDebt` function. Since `liquidateVaultCashBalance` function calls the `_reduceAccountDebt` function to reduce the debt of the vault account being liquidated, the same issue will occur here.
Fetch the prime rate of both secondary currencies because they are both needed within the `updateAccountSecondaryDebt` function when converting debt storage to underlying.\\n```\\n function _reduceAccountDebt(\\n VaultConfig memory vaultConfig,\\n VaultState memory vaultState,\\n VaultAccount memory vaultAccount,\\n PrimeRate memory primeRate,\\n uint256 currencyIndex,\\n int256 depositUnderlyingInternal,\\n bool checkMinBorrow\\n ) private {\\n if (currencyIndex == 0) {\\n vaultAccount.updateAccountDebt(vaultState, depositUnderlyingInternal, 0);\\n vaultState.setVaultState(vaultConfig);\\n } else {\\n // Only set one of the prime rates, the other prime rate is not used since\\n // the net debt amount is set to zero\\n PrimeRate[2] memory pr;\\n// Remove the line below\\n pr[currencyIndex // Remove the line below\\n 1] = primeRate;\\n// Add the line below\\n pr = VaultSecondaryBorrow.getSecondaryPrimeRateStateful(vaultConfig);\\n\\n VaultSecondaryBorrow.updateAccountSecondaryDebt(\\n vaultConfig,\\n vaultAccount.account,\\n vaultAccount.maturity,\\n currencyIndex == 1 ? depositUnderlyingInternal : 0,\\n currencyIndex == 2 ? depositUnderlyingInternal : 0,\\n pr,\\n checkMinBorrow\\n );\\n }\\n }\\n```\\n
Any vault logic that relies on the VaultAccountSecondaryDebtShareStorage's maturity value would break since it has been cleared (set to zero). For instance, a vault account cannot be settled anymore as the following `settleSecondaryBorrow` function will always revert. Since `storedMaturity == 0` but `accountDebtTwo` is not zero, Line 399 below will always revert.\\nAs a result, a vault account with secondary currency debt cannot be settled. This also means that the vault account cannot exit since a vault account needs to be settled before exiting, causing users' assets to be stuck within the protocol.\\n```\\nFile: VaultSecondaryBorrow.sol\\n function settleSecondaryBorrow(VaultConfig memory vaultConfig, address account) internal returns (bool) {\\n if (!vaultConfig.hasSecondaryBorrows()) return false;\\n\\n VaultAccountSecondaryDebtShareStorage storage accountStorage = \\n LibStorage.getVaultAccountSecondaryDebtShare()[account][vaultConfig.vault];\\n uint256 storedMaturity = accountStorage.maturity;\\n\\n // NOTE: we can read account debt directly since prime cash maturities never enter this block of code.\\n int256 accountDebtOne = -int256(uint256(accountStorage.accountDebtOne));\\n int256 accountDebtTwo = -int256(uint256(accountStorage.accountDebtTwo));\\n \\n if (storedMaturity == 0) {\\n // Handles edge condition where an account is holding vault shares past maturity without\\n // any debt position.\\n require(accountDebtOne == 0 && accountDebtTwo == 0); \\n } else {\\n```\\n\\nIn addition, the vault account data is corrupted as there is a secondary debt without maturity, which might affect internal accounting and tracking.
```\\nFile: VaultSecondaryBorrow.sol\\n function _setAccountMaturity(\\n VaultAccountSecondaryDebtShareStorage storage accountStorage,\\n int256 accountDebtOne,\\n int256 accountDebtTwo,\\n uint40 maturity\\n ) private {\\n if (accountDebtOne == 0 && accountDebtTwo == 0) {\\n // If both debt shares are cleared to zero, clear the maturity as well.\\n accountStorage.maturity = 0;\\n } else {\\n // In all other cases, set the account to the designated maturity\\n accountStorage.maturity = maturity;\\n }\\n }\\n```\\n
StrategyVault can perform a full exit without repaying all secondary debt
high
StrategyVault can perform a full exit without repaying all secondary debt, leaving bad debt with the protocol.\\nNoted from the codebase's comment that:\\nVaults can borrow up to the capacity using the `borrowSecondaryCurrencyToVault` and `repaySecondaryCurrencyToVault` methods. Vaults that use a secondary currency must ALWAYS repay the secondary debt during redemption and handle accounting for the secondary currency themselves.\\nThus, when the StrategyVault-side performs a full exit for a vault account, Notional-side does not check that all secondary debts of that vault account are cleared (= zero) and will simply trust StrategyVault-side has already handled them properly.\\nLine 271 below shows that only validates the primary debt but not the secondary debt during a full exit.\\n```\\nFile: VaultAccountAction.sol\\n if (vaultAccount.accountDebtUnderlying == 0 && vaultAccount.vaultShares == 0) {\\n // If the account has no position in the vault at this point, set the maturity to zero as well\\n vaultAccount.maturity = 0;\\n }\\n vaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: true});\\n\\n // It's possible that the user redeems more vault shares than they lend (it is not always the case\\n // that they will be increasing their collateral ratio here, so we check that this is the case). No\\n // need to check if the account has exited in full (maturity == 0).\\n if (vaultAccount.maturity != 0) {\\n IVaultAccountHealth(address(this)).checkVaultAccountCollateralRatio(vault, account);\\n }\\n```\\n
Consider checking that all secondary debts of a vault account are cleared before executing a full exit.\\n```\\n// Add the line below\\n int256 accountDebtOne;\\n// Add the line below\\n int256 accountDebtTwo;\\n\\n// Add the line below\\n if (vaultConfig.hasSecondaryBorrows()) {\\n// Add the line below\\n (/* */, accountDebtOne, accountDebtTwo) = VaultSecondaryBorrow.getAccountSecondaryDebt(vaultConfig, account, pr);\\n// Add the line below\\n }\\n\\n// Remove the line below\\n if (vaultAccount.accountDebtUnderlying == 0 && vaultAccount.vaultShares == 0) {\\n// Add the line below\\n if (vaultAccount.accountDebtUnderlying == 0 && vaultAccount.vaultShares == 0 && accountDebtOne == 0 && accountDebtTwo == 0) {\\n // If the account has no position in the vault at this point, set the maturity to zero as well\\n vaultAccount.maturity = 0;\\n}\\nvaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: true});\\n```\\n
Leveraged vaults are designed to be as isolated as possible to mitigate the risk to the Notional protocol and its users. However, the above implementation seems to break this principle. As such, if there is a vulnerability in the leverage vault that allows someone to exploit this issue and bypass the repayment of the secondary debt, the protocol will be left with a bad debt which affects the insolvency of the protocol.
```\\nFile: VaultAccountAction.sol\\n if (vaultAccount.accountDebtUnderlying == 0 && vaultAccount.vaultShares == 0) {\\n // If the account has no position in the vault at this point, set the maturity to zero as well\\n vaultAccount.maturity = 0;\\n }\\n vaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: true});\\n\\n // It's possible that the user redeems more vault shares than they lend (it is not always the case\\n // that they will be increasing their collateral ratio here, so we check that this is the case). No\\n // need to check if the account has exited in full (maturity == 0).\\n if (vaultAccount.maturity != 0) {\\n IVaultAccountHealth(address(this)).checkVaultAccountCollateralRatio(vault, account);\\n }\\n```\\n
Unable to transfer fee reserve assets to treasury
high
Transferring fee reserve assets to the treasury manager contract will result in a revert, leading to a loss of rewards for NOTE stakers.\\n```\\nFile: TreasuryAction.sol\\n /// @notice redeems and transfers tokens to the treasury manager contract\\n function _redeemAndTransfer(uint16 currencyId, int256 primeCashRedeemAmount) private returns (uint256) {\\n PrimeRate memory primeRate = PrimeRateLib.buildPrimeRateStateful(currencyId);\\n int256 actualTransferExternal = TokenHandler.withdrawPrimeCash(\\n treasuryManagerContract,\\n currencyId,\\n primeCashRedeemAmount.neg(),\\n primeRate,\\n true // if ETH, transfers it as WETH\\n );\\n\\n require(actualTransferExternal > 0);\\n return uint256(actualTransferExternal);\\n }\\n```\\n\\nThe value returned by the `TokenHandler.withdrawPrimeCash` function is always less than or equal to zero. Thus, the condition `actualTransferExternal > 0` will always be false, and the `_redeemAndTransfer` function will always revert.\\nThe `transferReserveToTreasury` function depends on `_redeemAndTransfer` function. Thus, it is not possible to transfer any asset to the treasury manager contract.
Negate the value returned by the `TokenHandler.withdrawPrimeCash` function.\\n```\\n int256 actualTransferExternal = TokenHandler.withdrawPrimeCash(\\n treasuryManagerContract,\\n currencyId,\\n primeCashRedeemAmount.neg(),\\n primeRate,\\n true // if ETH, transfers it as WETH\\n// Remove the line below\\n );\\n// Add the line below\\n ).neg();\\n```\\n
The fee collected by Notional is stored in the Fee Reserve. The fee reserve assets will be transferred to Notional's Treasury to be invested into the sNOTE pool. Without the ability to do so, the NOTE stakers will not receive their rewards.
```\\nFile: TreasuryAction.sol\\n /// @notice redeems and transfers tokens to the treasury manager contract\\n function _redeemAndTransfer(uint16 currencyId, int256 primeCashRedeemAmount) private returns (uint256) {\\n PrimeRate memory primeRate = PrimeRateLib.buildPrimeRateStateful(currencyId);\\n int256 actualTransferExternal = TokenHandler.withdrawPrimeCash(\\n treasuryManagerContract,\\n currencyId,\\n primeCashRedeemAmount.neg(),\\n primeRate,\\n true // if ETH, transfers it as WETH\\n );\\n\\n require(actualTransferExternal > 0);\\n return uint256(actualTransferExternal);\\n }\\n```\\n
Excess funds withdrawn from the money market
high
Excessive amounts of assets are being withdrawn from the money market.\\n```\\nFile: TokenHandler.sol\\n function _redeemMoneyMarketIfRequired(\\n uint16 currencyId,\\n Token memory underlying,\\n uint256 withdrawAmountExternal\\n ) private {\\n // If there is sufficient balance of the underlying to withdraw from the contract\\n // immediately, just return.\\n mapping(address => uint256) storage store = LibStorage.getStoredTokenBalances();\\n uint256 currentBalance = store[underlying.tokenAddress];\\n if (withdrawAmountExternal <= currentBalance) return;\\n\\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\\n // Redemption data returns an array of contract calls to make from the Notional proxy (which\\n // is holding all of the money market tokens).\\n (RedeemData[] memory data) = oracle.getRedemptionCalldata(withdrawAmountExternal);\\n\\n // This is the total expected underlying that we should redeem after all redemption calls\\n // are executed.\\n uint256 totalUnderlyingRedeemed = executeMoneyMarketRedemptions(underlying, data);\\n\\n // Ensure that we have sufficient funds before we exit\\n require(withdrawAmountExternal <= currentBalance.add(totalUnderlyingRedeemed)); // dev: insufficient redeem\\n }\\n```\\n\\nIf the `currentBalance` is `999,900` USDC and the `withdrawAmountExternal` is `1,000,000` USDC, then there is insufficient balance in the contract, and additional funds need to be withdrawn from the money market (e.g. Compound).\\nSince the contract already has `999,900` USDC, only an additional `100` USDC needs to be withdrawn from the money market to fulfill the withdrawal request of `1,000,000` USDC\\nHowever, instead of withdrawing `100` USDC from the money market, Notional withdraw `1,000,000` USDC from the market as per the `oracle.getRedemptionCalldata(withdrawAmountExternal)` function. As a result, an excess of `990,000` USDC is being withdrawn from the money market
Consider withdrawing only the shortfall amount from the money market.\\n```\\n// Remove the line below\\n (RedeemData[] memory data) = oracle.getRedemptionCalldata(withdrawAmountExternal);\\n// Add the line below\\n (RedeemData[] memory data) = oracle.getRedemptionCalldata(withdrawAmountExternal // Remove the line below\\n currentBalance);\\n```\\n
This led to an excessive amount of assets idling in Notional and not generating any returns or interest in the money market, which led to a loss of assets for the users as they would receive a lower interest rate than expected and incur opportunity loss.\\nAttackers could potentially abuse this to pull the funds Notional invested in the money market leading to griefing and loss of returns/interest for the protocol.
```\\nFile: TokenHandler.sol\\n function _redeemMoneyMarketIfRequired(\\n uint16 currencyId,\\n Token memory underlying,\\n uint256 withdrawAmountExternal\\n ) private {\\n // If there is sufficient balance of the underlying to withdraw from the contract\\n // immediately, just return.\\n mapping(address => uint256) storage store = LibStorage.getStoredTokenBalances();\\n uint256 currentBalance = store[underlying.tokenAddress];\\n if (withdrawAmountExternal <= currentBalance) return;\\n\\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\\n // Redemption data returns an array of contract calls to make from the Notional proxy (which\\n // is holding all of the money market tokens).\\n (RedeemData[] memory data) = oracle.getRedemptionCalldata(withdrawAmountExternal);\\n\\n // This is the total expected underlying that we should redeem after all redemption calls\\n // are executed.\\n uint256 totalUnderlyingRedeemed = executeMoneyMarketRedemptions(underlying, data);\\n\\n // Ensure that we have sufficient funds before we exit\\n require(withdrawAmountExternal <= currentBalance.add(totalUnderlyingRedeemed)); // dev: insufficient redeem\\n }\\n```\\n
Possible to liquidate past the debt outstanding above the min borrow without liquidating the entire debt outstanding
high
It is possible to liquidate past the debt outstanding above the min borrow without liquidating the entire debt outstanding. Thus, leaving accounts with small debt that are not profitable to unwind if it needs to liquidate.\\n```\\nFile: VaultValuation.sol\\n // NOTE: deposit amount is always positive in this method\\n if (depositUnderlyingInternal < maxLiquidatorDepositLocal) {\\n // If liquidating past the debt outstanding above the min borrow, then the entire\\n // debt outstanding must be liquidated.\\n\\n // (debtOutstanding - depositAmountUnderlying) is the post liquidation debt. As an\\n // edge condition, when debt outstanding is discounted to present value, the account\\n // may be liquidated to zero while their debt outstanding is still greater than the\\n // min borrow size (which is normally enforced in notional terms -- i.e. non present\\n // value). Resolving this would require additional complexity for not much gain. An\\n // account within 20% of the minBorrowSize in a vault that has fCash discounting enabled\\n // may experience a full liquidation as a result.\\n require(\\n h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\\n "Must Liquidate All Debt"\\n );\\n```\\n\\n`depositUnderlyingInternal` is always a positive value (Refer to comment on Line 250) that represents the amount of underlying deposited by the liquidator\\n`h.debtOutstanding[currencyIndex]` is always a negative value representing debt outstanding of a specific currency in a vault account\\n`minBorrowSize` is always a positive value that represents the minimal borrow size of a specific currency (It is stored as uint32 in storage)\\nIf liquidating past the debt outstanding above the min borrow, then the entire debt outstanding must be liquidated.\\nAssume the following scenario:\\n`depositUnderlyingInternal` = `70 USDC`\\n`h.debtOutstanding[currencyIndex]` = `-100 USDC`\\n`minBorrowSize` = `50 USDC`\\nIf the liquidation is successful, the vault account should be left with `-30 USDC` debt outstanding because `70 USDC` has been paid off by the liquidator. However, this should not happen under normal circumstances because the debt outstanding (-30) does not meet the minimal borrow size of `50 USDC` and the liquidation should revert/fail.\\nThe following piece of validation logic attempts to ensure that all outstanding debt is liquidated if post-liquidation debt does not meet the minimal borrowing size.\\n```\\nrequire(\\n h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\\n "Must Liquidate All Debt"\\n);\\n```\\n\\nPlugging in the values from our scenario to verify if the code will revert if the debt outstanding does not meet the minimal borrow size.\\n```\\nrequire(\\n (-100 USDC - 70 USDC) < 50 USDC\\n);\\n===>\\nrequire(\\n (-170 USDC) < 50 USDC\\n);\\n===>\\nrequire(true) // no revert\\n```\\n\\nThe above shows that it is possible for someone to liquidate past the debt outstanding above the min borrow without liquidating the entire debt outstanding. This shows that the math formula in the code is incorrect and not working as intended.
Update the formula to as follows:\\n```\\nrequire(\\n// Remove the line below\\n h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\\n// Add the line below\\n h.debtOutstanding[currencyIndex].neg().sub(depositUnderlyingInternal) > minBorrowSize,\\n "Must Liquidate All Debt"\\n);\\n```\\n\\nPlugging in the values from our scenario again to verify if the code will revert if the debt outstanding does not meet the minimal borrow size.\\n```\\nrequire(\\n ((-100 USDC).neg() - 70 USDC) > 50 USDC\\n);\\n===>\\nrequire(\\n (100 USDC - 70 USDC) > 50 USDC\\n);\\n===>\\nrequire(\\n (30 USDC) > 50 USDC\\n);\\n===>\\nrequire(false) // revert\\n```\\n\\nThe above will trigger a revert as expected when the debt outstanding does not meet the minimal borrow size.
A liquidation can bring an account below the minimum debt. Accounts smaller than the minimum debt are not profitable to unwind if it needs to liquidate (Reference)\\nAs a result, liquidators are not incentivized to liquidate those undercollateralized positions. This might leave the protocol with bad debts, potentially leading to insolvency if the bad debts accumulate.
```\\nFile: VaultValuation.sol\\n // NOTE: deposit amount is always positive in this method\\n if (depositUnderlyingInternal < maxLiquidatorDepositLocal) {\\n // If liquidating past the debt outstanding above the min borrow, then the entire\\n // debt outstanding must be liquidated.\\n\\n // (debtOutstanding - depositAmountUnderlying) is the post liquidation debt. As an\\n // edge condition, when debt outstanding is discounted to present value, the account\\n // may be liquidated to zero while their debt outstanding is still greater than the\\n // min borrow size (which is normally enforced in notional terms -- i.e. non present\\n // value). Resolving this would require additional complexity for not much gain. An\\n // account within 20% of the minBorrowSize in a vault that has fCash discounting enabled\\n // may experience a full liquidation as a result.\\n require(\\n h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\\n "Must Liquidate All Debt"\\n );\\n```\\n
Vaults can avoid liquidations by not letting their vault account be settled
high
Vault liquidations will leave un-matured accounts with cash holdings which are then used to offset account debt during vault account settlements. As it stands, any excess cash received via interest accrual will be transferred back to the vault account directly. If a primary or secondary borrow currency is `ETH`, then this excess cash will be transferred natively. Consequently, the recipient may intentionally revert, causing account settlement to fail.\\nThe issue arises in the `VaultAccount.repayAccountPrimeDebtAtSettlement()` function. If there is any excess cash due to interest accrual, then this amount will be refunded to the vault account. Native `ETH` is not wrapped when it should be wrapped, allowing the recipient to take control over the flow of execution.\\n```\\nFile: VaultAccount.sol\\n function repayAccountPrimeDebtAtSettlement(\\n PrimeRate memory pr,\\n VaultStateStorage storage primeVaultState,\\n uint16 currencyId,\\n address vault,\\n address account,\\n int256 accountPrimeCash,\\n int256 accountPrimeStorageValue\\n ) internal returns (int256 finalPrimeDebtStorageValue, bool didTransfer) {\\n didTransfer = false;\\n finalPrimeDebtStorageValue = accountPrimeStorageValue;\\n \\n if (accountPrimeCash > 0) {\\n // netPrimeDebtRepaid is a negative number\\n int256 netPrimeDebtRepaid = pr.convertUnderlyingToDebtStorage(\\n pr.convertToUnderlying(accountPrimeCash).neg()\\n );\\n\\n int256 netPrimeDebtChange;\\n if (netPrimeDebtRepaid < accountPrimeStorageValue) {\\n // If the net debt change is greater than the debt held by the account, then only\\n // decrease the total prime debt by what is held by the account. The residual amount\\n // will be refunded to the account via a direct transfer.\\n netPrimeDebtChange = accountPrimeStorageValue;\\n finalPrimeDebtStorageValue = 0;\\n\\n int256 primeCashRefund = pr.convertFromUnderlying(\\n pr.convertDebtStorageToUnderlying(netPrimeDebtChange.sub(accountPrimeStorageValue))\\n );\\n TokenHandler.withdrawPrimeCash(\\n account, currencyId, primeCashRefund, pr, false // ETH will be transferred natively\\n );\\n didTransfer = true;\\n } else {\\n // In this case, part of the account's debt is repaid.\\n netPrimeDebtChange = netPrimeDebtRepaid;\\n finalPrimeDebtStorageValue = accountPrimeStorageValue.sub(netPrimeDebtRepaid);\\n }\\n\\n // Updates the global prime debt figure and events are emitted via the vault.\\n pr.updateTotalPrimeDebt(vault, currencyId, netPrimeDebtChange);\\n\\n // Updates the state on the prime vault storage directly.\\n int256 totalPrimeDebt = int256(uint256(primeVaultState.totalDebt));\\n int256 newTotalDebt = totalPrimeDebt.add(netPrimeDebtChange);\\n // Set the total debt to the storage value\\n primeVaultState.totalDebt = newTotalDebt.toUint().toUint80();\\n }\\n }\\n```\\n\\nAs seen here, a `withdrawWrappedNativeToken` is used to signify when a native `ETH` transfer will be wrapped before sending an amount. In the case of vault settlement, this is always sent to `false`.\\n```\\nFile: TokenHandler.sol\\n function withdrawPrimeCash(\\n address account,\\n uint16 currencyId,\\n int256 primeCashToWithdraw,\\n PrimeRate memory primeRate,\\n bool withdrawWrappedNativeToken\\n ) internal returns (int256 netTransferExternal) {\\n if (primeCashToWithdraw == 0) return 0;\\n require(primeCashToWithdraw < 0);\\n\\n Token memory underlying = getUnderlyingToken(currencyId);\\n netTransferExternal = convertToExternal(\\n underlying, \\n primeRate.convertToUnderlying(primeCashToWithdraw) \\n );\\n\\n // Overflow not possible due to int256\\n uint256 withdrawAmount = uint256(netTransferExternal.neg());\\n _redeemMoneyMarketIfRequired(currencyId, underlying, withdrawAmount);\\n\\n if (underlying.tokenType == TokenType.Ether) {\\n GenericToken.transferNativeTokenOut(account, withdrawAmount, withdrawWrappedNativeToken);\\n } else {\\n GenericToken.safeTransferOut(underlying.tokenAddress, account, withdrawAmount);\\n }\\n\\n _postTransferPrimeCashUpdate(account, currencyId, netTransferExternal, underlying, primeRate);\\n }\\n```\\n\\nIt's likely that the vault account is considered solvent in this case, but due to the inability to trade between currencies, it is not possible to use excess cash in one currency to offset debt in another.
Consider wrapping `ETH` under all circumstances. This will prevent vault accounts from intentionally reverting and preventing their account from being settled.
Liquidations require vaults to be settled if `block.timestamp` is past the maturity date, hence, it is not possible to deleverage vault accounts, leading to bad debt accrual.
```\\nFile: VaultAccount.sol\\n function repayAccountPrimeDebtAtSettlement(\\n PrimeRate memory pr,\\n VaultStateStorage storage primeVaultState,\\n uint16 currencyId,\\n address vault,\\n address account,\\n int256 accountPrimeCash,\\n int256 accountPrimeStorageValue\\n ) internal returns (int256 finalPrimeDebtStorageValue, bool didTransfer) {\\n didTransfer = false;\\n finalPrimeDebtStorageValue = accountPrimeStorageValue;\\n \\n if (accountPrimeCash > 0) {\\n // netPrimeDebtRepaid is a negative number\\n int256 netPrimeDebtRepaid = pr.convertUnderlyingToDebtStorage(\\n pr.convertToUnderlying(accountPrimeCash).neg()\\n );\\n\\n int256 netPrimeDebtChange;\\n if (netPrimeDebtRepaid < accountPrimeStorageValue) {\\n // If the net debt change is greater than the debt held by the account, then only\\n // decrease the total prime debt by what is held by the account. The residual amount\\n // will be refunded to the account via a direct transfer.\\n netPrimeDebtChange = accountPrimeStorageValue;\\n finalPrimeDebtStorageValue = 0;\\n\\n int256 primeCashRefund = pr.convertFromUnderlying(\\n pr.convertDebtStorageToUnderlying(netPrimeDebtChange.sub(accountPrimeStorageValue))\\n );\\n TokenHandler.withdrawPrimeCash(\\n account, currencyId, primeCashRefund, pr, false // ETH will be transferred natively\\n );\\n didTransfer = true;\\n } else {\\n // In this case, part of the account's debt is repaid.\\n netPrimeDebtChange = netPrimeDebtRepaid;\\n finalPrimeDebtStorageValue = accountPrimeStorageValue.sub(netPrimeDebtRepaid);\\n }\\n\\n // Updates the global prime debt figure and events are emitted via the vault.\\n pr.updateTotalPrimeDebt(vault, currencyId, netPrimeDebtChange);\\n\\n // Updates the state on the prime vault storage directly.\\n int256 totalPrimeDebt = int256(uint256(primeVaultState.totalDebt));\\n int256 newTotalDebt = totalPrimeDebt.add(netPrimeDebtChange);\\n // Set the total debt to the storage value\\n primeVaultState.totalDebt = newTotalDebt.toUint().toUint80();\\n }\\n }\\n```\\n
Possible to create vault positions ineligible for liquidation
high
Users can self-liquidate their secondary debt holdings in such a way that it is no longer possible to deleverage their vault account as `checkMinBorrow` will fail post-maturity.\\nWhen deleveraging a vault account, the liquidator will pay down account debt directly and the account will not accrue any cash. Under most circumstances, it is not possible to put an account's debt below its minimum borrow size.\\nHowever, there are two exceptions to this:\\nLiquidators purchasing cash from a vault account. This only applies to non-prime vault accounts.\\nA vault account is being settled and `checkMinBorrow` is skipped to ensure an account can always be settled.\\n```\\nFile: VaultLiquidationAction.sol\\n function deleverageAccount(\\n address account,\\n address vault,\\n address liquidator,\\n uint16 currencyIndex,\\n int256 depositUnderlyingInternal\\n ) external payable nonReentrant override returns (\\n uint256 vaultSharesToLiquidator,\\n int256 depositAmountPrimeCash\\n ) {\\n require(currencyIndex < 3);\\n (\\n VaultConfig memory vaultConfig,\\n VaultAccount memory vaultAccount,\\n VaultState memory vaultState\\n ) = _authenticateDeleverage(account, vault, liquidator);\\n\\n PrimeRate memory pr;\\n // Currency Index is validated in this method\\n (\\n depositUnderlyingInternal,\\n vaultSharesToLiquidator,\\n pr\\n ) = IVaultAccountHealth(address(this)).calculateDepositAmountInDeleverage(\\n currencyIndex, vaultAccount, vaultConfig, vaultState, depositUnderlyingInternal\\n );\\n\\n uint16 currencyId = vaultConfig.borrowCurrencyId;\\n if (currencyIndex == 1) currencyId = vaultConfig.secondaryBorrowCurrencies[0];\\n else if (currencyIndex == 2) currencyId = vaultConfig.secondaryBorrowCurrencies[1];\\n\\n Token memory token = TokenHandler.getUnderlyingToken(currencyId);\\n // Excess ETH is returned to the liquidator natively\\n (/* */, depositAmountPrimeCash) = TokenHandler.depositUnderlyingExternal(\\n liquidator, currencyId, token.convertToExternal(depositUnderlyingInternal), pr, false \\n );\\n\\n // Do not skip the min borrow check here\\n vaultAccount.vaultShares = vaultAccount.vaultShares.sub(vaultSharesToLiquidator);\\n if (vaultAccount.maturity == Constants.PRIME_CASH_VAULT_MATURITY) {\\n // Vault account will not incur a cash balance if they are in the prime cash maturity, their debts\\n // will be paid down directly.\\n _reduceAccountDebt(\\n vaultConfig, vaultState, vaultAccount, pr, currencyIndex, depositUnderlyingInternal, true\\n );\\n depositAmountPrimeCash = 0;\\n }\\n\\n // Check min borrow in this liquidation method, the deleverage calculation should adhere to the min borrow\\n vaultAccount.setVaultAccountForLiquidation(vaultConfig, currencyIndex, depositAmountPrimeCash, true);\\n\\n emit VaultDeleverageAccount(vault, account, currencyId, vaultSharesToLiquidator, depositAmountPrimeCash);\\n emit VaultLiquidatorProfit(vault, account, liquidator, vaultSharesToLiquidator, true);\\n\\n _transferVaultSharesToLiquidator(\\n liquidator, vaultConfig, vaultSharesToLiquidator, vaultAccount.maturity\\n );\\n\\n Emitter.emitVaultDeleverage(\\n liquidator, account, vault, currencyId, vaultState.maturity,\\n depositAmountPrimeCash, vaultSharesToLiquidator\\n );\\n }\\n```\\n\\n`currencyIndex` represents which currency is being liquidated and `depositUnderlyingInternal` the amount of debt being reduced. Only one currency's debt can be updated here.\\n```\\nFile: VaultLiquidationAction.sol\\n function _reduceAccountDebt(\\n VaultConfig memory vaultConfig,\\n VaultState memory vaultState,\\n VaultAccount memory vaultAccount,\\n PrimeRate memory primeRate,\\n uint256 currencyIndex,\\n int256 depositUnderlyingInternal,\\n bool checkMinBorrow\\n ) private {\\n if (currencyIndex == 0) {\\n vaultAccount.updateAccountDebt(vaultState, depositUnderlyingInternal, 0);\\n vaultState.setVaultState(vaultConfig);\\n } else {\\n // Only set one of the prime rates, the other prime rate is not used since\\n // the net debt amount is set to zero\\n PrimeRate[2] memory pr;\\n pr[currencyIndex - 1] = primeRate;\\n\\n VaultSecondaryBorrow.updateAccountSecondaryDebt(\\n vaultConfig,\\n vaultAccount.account,\\n vaultAccount.maturity,\\n currencyIndex == 1 ? depositUnderlyingInternal : 0,\\n currencyIndex == 2 ? depositUnderlyingInternal : 0,\\n pr,\\n checkMinBorrow\\n );\\n }\\n }\\n```\\n\\nIn the case of vault settlement, through self-liquidation, users can setup their debt and cash holdings post-settlement, such that both `accountDebtOne` and `accountDebtTwo` are non-zero and less than `vaultConfig.minAccountSecondaryBorrow`. The objective would be to have zero primary debt and `Y` secondary debt and `X` secondary cash. Post-settlement, cash is used to offset debt (Y - `X` < minAccountSecondaryBorrow) and due to the lack of `checkMinBorrow` in `VaultAccountAction.settleVaultAccount()`, both secondary currencies can have debt holdings below the minimum amount.\\nNow when `deleverageAccount()` is called on a prime vault account, debts are paid down directly. However, if we are only able to pay down one secondary currency at a time, `checkMinBorrow` will fail in `VaultSecondaryBorrow.updateAccountSecondaryDebt()` because both debts are checked.\\n```\\nFile: VaultSecondaryBorrow.sol\\n if (checkMinBorrow) {\\n // No overflow on negation due to overflow checks above\\n require(accountDebtOne == 0 || vaultConfig.minAccountSecondaryBorrow[0] <= -accountDebtOne, "min borrow");\\n require(accountDebtTwo == 0 || vaultConfig.minAccountSecondaryBorrow[1] <= -accountDebtTwo, "min borrow");\\n }\\n```\\n\\nNo prime fees accrue on secondary debt, hence, this debt will never reach a point where it is above the minimum borrow amount.
Either allow for multiple currencies to be liquidated or ensure that `checkMinBorrow` is performed only on the currency which is being liquidated.
Malicious actors can generate vault accounts which cannot be liquidated. Through opening numerous vault positions, Notional can rack up significant exposure and accrue bad debt as a result.
```\\nFile: VaultLiquidationAction.sol\\n function deleverageAccount(\\n address account,\\n address vault,\\n address liquidator,\\n uint16 currencyIndex,\\n int256 depositUnderlyingInternal\\n ) external payable nonReentrant override returns (\\n uint256 vaultSharesToLiquidator,\\n int256 depositAmountPrimeCash\\n ) {\\n require(currencyIndex < 3);\\n (\\n VaultConfig memory vaultConfig,\\n VaultAccount memory vaultAccount,\\n VaultState memory vaultState\\n ) = _authenticateDeleverage(account, vault, liquidator);\\n\\n PrimeRate memory pr;\\n // Currency Index is validated in this method\\n (\\n depositUnderlyingInternal,\\n vaultSharesToLiquidator,\\n pr\\n ) = IVaultAccountHealth(address(this)).calculateDepositAmountInDeleverage(\\n currencyIndex, vaultAccount, vaultConfig, vaultState, depositUnderlyingInternal\\n );\\n\\n uint16 currencyId = vaultConfig.borrowCurrencyId;\\n if (currencyIndex == 1) currencyId = vaultConfig.secondaryBorrowCurrencies[0];\\n else if (currencyIndex == 2) currencyId = vaultConfig.secondaryBorrowCurrencies[1];\\n\\n Token memory token = TokenHandler.getUnderlyingToken(currencyId);\\n // Excess ETH is returned to the liquidator natively\\n (/* */, depositAmountPrimeCash) = TokenHandler.depositUnderlyingExternal(\\n liquidator, currencyId, token.convertToExternal(depositUnderlyingInternal), pr, false \\n );\\n\\n // Do not skip the min borrow check here\\n vaultAccount.vaultShares = vaultAccount.vaultShares.sub(vaultSharesToLiquidator);\\n if (vaultAccount.maturity == Constants.PRIME_CASH_VAULT_MATURITY) {\\n // Vault account will not incur a cash balance if they are in the prime cash maturity, their debts\\n // will be paid down directly.\\n _reduceAccountDebt(\\n vaultConfig, vaultState, vaultAccount, pr, currencyIndex, depositUnderlyingInternal, true\\n );\\n depositAmountPrimeCash = 0;\\n }\\n\\n // Check min borrow in this liquidation method, the deleverage calculation should adhere to the min borrow\\n vaultAccount.setVaultAccountForLiquidation(vaultConfig, currencyIndex, depositAmountPrimeCash, true);\\n\\n emit VaultDeleverageAccount(vault, account, currencyId, vaultSharesToLiquidator, depositAmountPrimeCash);\\n emit VaultLiquidatorProfit(vault, account, liquidator, vaultSharesToLiquidator, true);\\n\\n _transferVaultSharesToLiquidator(\\n liquidator, vaultConfig, vaultSharesToLiquidator, vaultAccount.maturity\\n );\\n\\n Emitter.emitVaultDeleverage(\\n liquidator, account, vault, currencyId, vaultState.maturity,\\n depositAmountPrimeCash, vaultSharesToLiquidator\\n );\\n }\\n```\\n
Partial liquidations are not possible
high
Due to an incorrect implementation of `VaultValuation.getLiquidationFactors()`, Notional requires that a liquidator reduces an account's debt below `minBorrowSize`. This does not allow liquidators to partially liquidate a vault account into a healthy position and opens up the protocol to an edge case where an account is always ineligible for liquidation.\\nWhile `VaultValuation.getLiquidationFactors()` might allow for the resultant outstanding debt to be below the minimum borrow amount and non-zero, `deleverageAccount()` will revert due to `checkMinBorrow` being set to `true`. Therefore, the only option is for liquidators to wipe the outstanding debt entirely but users can set up their vault accounts such that that `maxLiquidatorDepositLocal` is less than each of the vault currency's outstanding debt.\\n```\\nFile: VaultValuation.sol\\n int256 maxLiquidatorDepositLocal = _calculateDeleverageAmount(\\n vaultConfig,\\n h.vaultShareValueUnderlying,\\n h.totalDebtOutstandingInPrimary.neg(),\\n h.debtOutstanding[currencyIndex].neg(),\\n minBorrowSize,\\n exchangeRate,\\n er.rateDecimals\\n );\\n\\n // NOTE: deposit amount is always positive in this method\\n if (depositUnderlyingInternal < maxLiquidatorDepositLocal) {\\n // If liquidating past the debt outstanding above the min borrow, then the entire\\n // debt outstanding must be liquidated.\\n\\n // (debtOutstanding - depositAmountUnderlying) is the post liquidation debt. As an\\n // edge condition, when debt outstanding is discounted to present value, the account\\n // may be liquidated to zero while their debt outstanding is still greater than the\\n // min borrow size (which is normally enforced in notional terms -- i.e. non present\\n // value). Resolving this would require additional complexity for not much gain. An\\n // account within 20% of the minBorrowSize in a vault that has fCash discounting enabled\\n // may experience a full liquidation as a result.\\n require(\\n h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\\n "Must Liquidate All Debt"\\n );\\n } else {\\n // If the deposit amount is greater than maxLiquidatorDeposit then limit it to the max\\n // amount here.\\n depositUnderlyingInternal = maxLiquidatorDepositLocal;\\n }\\n```\\n\\nIf `depositUnderlyingInternal >= maxLiquidatorDepositLocal`, then the liquidator's deposit is capped to `maxLiquidatorDepositLocal`. However, `maxLiquidatorDepositLocal` may put the vault account's outstanding debt below the minimum borrow amount but not to zero.\\nHowever, because it is not possible to partially liquidate the account's debt, we reach a deadlock where it isn't possible to liquidate all outstanding debt and it also isn't possible to liquidate debt partially. So even though it may be possible to liquidate an account into a healthy position, the current implementation doesn't always allow for this to be true.
`VaultValuation.getLiquidationFactors()` must be updated to allow for partial liquidations.\\n```\\nFile: VaultValuation.sol\\n if (depositUnderlyingInternal < maxLiquidatorDepositLocal) {\\n // If liquidating past the debt outstanding above the min borrow, then the entire\\n // debt outstanding must be liquidated.\\n\\n // (debtOutstanding - depositAmountUnderlying) is the post liquidation debt. As an\\n // edge condition, when debt outstanding is discounted to present value, the account\\n // may be liquidated to zero while their debt outstanding is still greater than the\\n // min borrow size (which is normally enforced in notional terms -- i.e. non present\\n // value). Resolving this would require additional complexity for not much gain. An\\n // account within 20% of the minBorrowSize in a vault that has fCash discounting enabled\\n // may experience a full liquidation as a result.\\n require(\\n h.debtOutstanding[currencyIndex].neg().sub(depositUnderlyingInternal) >= minBorrowSize,\\n || h.debtOutstanding[currencyIndex].neg().sub(depositUnderlyingInternal) == 0\\n "Must Liquidate All Debt"\\n );\\n } else {\\n // If the deposit amount is greater than maxLiquidatorDeposit then limit it to the max\\n // amount here.\\n depositUnderlyingInternal = maxLiquidatorDepositLocal;\\n }\\n```\\n
Certain vault positions will never be eligible for liquidation and hence Notional may be left with bad debt. Liquidity providers will lose funds as they must cover the shortfall for undercollateralised positions.
```\\nFile: VaultValuation.sol\\n int256 maxLiquidatorDepositLocal = _calculateDeleverageAmount(\\n vaultConfig,\\n h.vaultShareValueUnderlying,\\n h.totalDebtOutstandingInPrimary.neg(),\\n h.debtOutstanding[currencyIndex].neg(),\\n minBorrowSize,\\n exchangeRate,\\n er.rateDecimals\\n );\\n\\n // NOTE: deposit amount is always positive in this method\\n if (depositUnderlyingInternal < maxLiquidatorDepositLocal) {\\n // If liquidating past the debt outstanding above the min borrow, then the entire\\n // debt outstanding must be liquidated.\\n\\n // (debtOutstanding - depositAmountUnderlying) is the post liquidation debt. As an\\n // edge condition, when debt outstanding is discounted to present value, the account\\n // may be liquidated to zero while their debt outstanding is still greater than the\\n // min borrow size (which is normally enforced in notional terms -- i.e. non present\\n // value). Resolving this would require additional complexity for not much gain. An\\n // account within 20% of the minBorrowSize in a vault that has fCash discounting enabled\\n // may experience a full liquidation as a result.\\n require(\\n h.debtOutstanding[currencyIndex].sub(depositUnderlyingInternal) < minBorrowSize,\\n "Must Liquidate All Debt"\\n );\\n } else {\\n // If the deposit amount is greater than maxLiquidatorDeposit then limit it to the max\\n // amount here.\\n depositUnderlyingInternal = maxLiquidatorDepositLocal;\\n }\\n```\\n
Vault accounts with excess cash can avoid being settled
high
If excess cash was transferred out from an account during account settlement, then the protocol will check the account's collateral ratio and revert if the position is unhealthy. Because it may not be possible to settle a vault account, liquidators cannot reduce account debt by purchasing vault shares because `_authenticateDeleverage()` will check to see if a vault has matured.\\nConsidering an account's health is determined by a combination of its outstanding debt, cash holdings and the total underlying value of its vault shares, transferring out excess cash may actually put an account in an unhealthy position.\\n```\\nFile: VaultAccountAction.sol\\n function settleVaultAccount(address account, address vault) external override nonReentrant {\\n requireValidAccount(account);\\n require(account != vault);\\n\\n VaultConfig memory vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\\n VaultAccount memory vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\\n \\n // Require that the account settled, otherwise we may leave the account in an unintended\\n // state in this method because we allow it to skip the min borrow check in the next line.\\n (bool didSettle, bool didTransfer) = vaultAccount.settleVaultAccount(vaultConfig);\\n require(didSettle, "No Settle");\\n\\n vaultAccount.accruePrimeCashFeesToDebt(vaultConfig);\\n\\n // Skip Min Borrow Check so that accounts can always be settled\\n vaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: false});\\n\\n if (didTransfer) {\\n // If the vault did a transfer (i.e. withdrew cash) we have to check their collateral ratio. There\\n // is an edge condition where a vault with secondary borrows has an emergency exit. During that process\\n // an account will be left some cash balance in both currencies. It may have excess cash in one and\\n // insufficient cash in the other. A withdraw of the excess in one side will cause the vault account to\\n // be insolvent if we do not run this check. If this scenario indeed does occur, the vault itself must\\n // be upgraded in order to facilitate orderly exits for all of the accounts since they will be prevented\\n // from settling.\\n IVaultAccountHealth(address(this)).checkVaultAccountCollateralRatio(vault, account);\\n }\\n }\\n```\\n\\nIt is important to note that all vault liquidation actions require a vault to first be settled. Hence, through self-liquidation, sophisticated vault accounts can have excess cash in one currency and significant debt holdings in the vault's other currencies.\\n```\\nFile: VaultLiquidationAction.sol\\n function _authenticateDeleverage(\\n address account,\\n address vault,\\n address liquidator\\n ) private returns (\\n VaultConfig memory vaultConfig,\\n VaultAccount memory vaultAccount,\\n VaultState memory vaultState\\n ) {\\n // Do not allow invalid accounts to liquidate\\n requireValidAccount(liquidator);\\n require(liquidator != vault);\\n\\n // Cannot liquidate self, if a vault needs to deleverage itself as a whole it has other methods \\n // in VaultAction to do so.\\n require(account != msg.sender);\\n require(account != liquidator);\\n\\n vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\\n require(vaultConfig.getFlag(VaultConfiguration.DISABLE_DELEVERAGE) == false);\\n\\n // Authorization rules for deleveraging\\n if (vaultConfig.getFlag(VaultConfiguration.ONLY_VAULT_DELEVERAGE)) {\\n require(msg.sender == vault);\\n } else {\\n require(msg.sender == liquidator);\\n }\\n\\n vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\\n\\n // Vault accounts that are not settled must be settled first by calling settleVaultAccount\\n // before liquidation. settleVaultAccount is not permissioned so anyone may settle the account.\\n require(block.timestamp < vaultAccount.maturity, "Must Settle");\\n\\n if (vaultAccount.maturity == Constants.PRIME_CASH_VAULT_MATURITY) {\\n // Returns the updated prime vault state\\n vaultState = vaultAccount.accruePrimeCashFeesToDebtInLiquidation(vaultConfig);\\n } else {\\n vaultState = VaultStateLib.getVaultState(vaultConfig, vaultAccount.maturity);\\n }\\n }\\n```\\n\\nConsider the following example:\\nAlice has a valid borrow position in the vault which is considered risky. She has a small bit of secondary cash but most of her debt is primary currency denominated. Generally speaking her vault is healthy. Upon settlement, the small bit of excess secondary cash is transferred out and her vault is undercollateralised and eligible for liquidation. However, we are deadlocked because it is not possible to settle the vault because `checkVaultAccountCollateralRatio()` will fail, and it's not possible to purchase the excess cash and offset the debt directly via `liquidateVaultCashBalance()` or `deleverageAccount()` because `_authenticateDeleverage()` will revert if a vault has not yet been settled.
Consider adding a liquidation method which settles a vault account and allows for a liquidator to purchase vault shares, offsetting outstanding debt, before performing collateral ratio checks.
Vault accounts can create positions which will never be eligible for liquidation and the protocol may accrue bad debt.
```\\nFile: VaultAccountAction.sol\\n function settleVaultAccount(address account, address vault) external override nonReentrant {\\n requireValidAccount(account);\\n require(account != vault);\\n\\n VaultConfig memory vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\\n VaultAccount memory vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\\n \\n // Require that the account settled, otherwise we may leave the account in an unintended\\n // state in this method because we allow it to skip the min borrow check in the next line.\\n (bool didSettle, bool didTransfer) = vaultAccount.settleVaultAccount(vaultConfig);\\n require(didSettle, "No Settle");\\n\\n vaultAccount.accruePrimeCashFeesToDebt(vaultConfig);\\n\\n // Skip Min Borrow Check so that accounts can always be settled\\n vaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: false});\\n\\n if (didTransfer) {\\n // If the vault did a transfer (i.e. withdrew cash) we have to check their collateral ratio. There\\n // is an edge condition where a vault with secondary borrows has an emergency exit. During that process\\n // an account will be left some cash balance in both currencies. It may have excess cash in one and\\n // insufficient cash in the other. A withdraw of the excess in one side will cause the vault account to\\n // be insolvent if we do not run this check. If this scenario indeed does occur, the vault itself must\\n // be upgraded in order to facilitate orderly exits for all of the accounts since they will be prevented\\n // from settling.\\n IVaultAccountHealth(address(this)).checkVaultAccountCollateralRatio(vault, account);\\n }\\n }\\n```\\n
convertFromStorage() fails to use rounding-up when converting a negative storedCashBalance into signedPrimeSupplyValue.
medium
`convertFromStorage()` fails to use rounding-up when converting a negative `storedCashBalance` into `signedPrimeSupplyValue`.\\n`convertFromStorage()` is used to convert `storedCashBalance` into `signedPrimeSupplyValue`. When `storedCashBalance` is negative, it represents a debt - positive prime cash owed.\\nUnfortunately, when converting a negative `storedCashBalance` into `signedPrimeSupplyValue`, the following division will apply a rounding-down (near zero) mode, leading to a user to owe less than it is supposed to be.\\n```\\nreturn storedCashBalance.mul(pr.debtFactor).div(pr.supplyFactor);\\n```\\n\\nThis is not acceptable. Typically, rounding should be in favor of the protocol, not in favor of the user to prevent draining of the protocol and losing funds of the protocol.\\nThe following POC shows a rounding-down will happen for a negative value division. The result of the following test is -3.\\n```\\nfunction testMod() public {\\n \\n int256 result = -14;\\n result = result / 4;\\n console2.logInt(result);\\n }\\n```\\n
Use rounding-up instead.\\n```\\nfunction convertFromStorage(\\n PrimeRate memory pr,\\n int256 storedCashBalance\\n ) internal pure returns (int256 signedPrimeSupplyValue) {\\n if (storedCashBalance >= 0) {\\n return storedCashBalance;\\n } else {\\n // Convert negative stored cash balance to signed prime supply value\\n // signedPrimeSupply = (negativePrimeDebt * debtFactor) / supplyFactor\\n\\n // cashBalance is stored as int88, debt factor is uint80 * uint80 so there\\n // is no chance of phantom overflow (88 // Add the line below\\n 80 // Add the line below\\n 80 = 248) on mul\\n// Remove the line below\\n return storedCashBalance.mul(pr.debtFactor).div(pr.supplyFactor);\\n// Add the line below\\n return (storedCashBalance.mul(pr.debtFactor).sub(pr.supplyFactor// Remove the line below\\n1)).div(pr.supplyFactor);\\n }\\n }\\n```\\n
`convertFromStorage()` fails to use rounding-up when converting a negative `storedCashBalance` into `signedPrimeSupplyValue`. The protocol is losing some dusts amount, but it can be accumulative or a vulnerability that can be exploited.
```\\nreturn storedCashBalance.mul(pr.debtFactor).div(pr.supplyFactor);\\n```\\n
Cannot permissionless settle the vault account if the user use a blacklisted account
medium
Cannot permissionless settle the vault account if the user use a blacklisted account\\nIn VaultAccoutnAction.sol, one of the critical function is\\n```\\n /// @notice Settles a matured vault account by transforming it from an fCash maturity into\\n /// a prime cash account. This method is not authenticated, anyone can settle a vault account\\n /// without permission. Generally speaking, this action is economically equivalent no matter\\n /// when it is called. In some edge conditions when the vault is holding prime cash, it is\\n /// advantageous for the vault account to have this called sooner. All vault account actions\\n /// will first settle the vault account before taking any further actions.\\n /// @param account the address to settle\\n /// @param vault the vault the account is in\\n function settleVaultAccount(address account, address vault) external override nonReentrant {\\n requireValidAccount(account);\\n require(account != vault);\\n\\n VaultConfig memory vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\\n VaultAccount memory vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\\n \\n // Require that the account settled, otherwise we may leave the account in an unintended\\n // state in this method because we allow it to skip the min borrow check in the next line.\\n (bool didSettle, bool didTransfer) = vaultAccount.settleVaultAccount(vaultConfig);\\n require(didSettle, "No Settle");\\n\\n vaultAccount.accruePrimeCashFeesToDebt(vaultConfig);\\n\\n // Skip Min Borrow Check so that accounts can always be settled\\n vaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: false});\\n\\n if (didTransfer) {\\n // If the vault did a transfer (i.e. withdrew cash) we have to check their collateral ratio. There\\n // is an edge condition where a vault with secondary borrows has an emergency exit. During that process\\n // an account will be left some cash balance in both currencies. It may have excess cash in one and\\n // insufficient cash in the other. A withdraw of the excess in one side will cause the vault account to\\n // be insolvent if we do not run this check. If this scenario indeed does occur, the vault itself must\\n // be upgraded in order to facilitate orderly exits for all of the accounts since they will be prevented\\n // from settling.\\n IVaultAccountHealth(address(this)).checkVaultAccountCollateralRatio(vault, account);\\n }\\n }\\n```\\n\\nas the comment suggests, this function should be called permissionless\\nand the comment is, which means there should not be able to permissionless reject account settlement\\n```\\n/// will first settle the vault account before taking any further actions.\\n```\\n\\nthis is calling\\n```\\n (bool didSettle, bool didTransfer) = vaultAccount.settleVaultAccount(vaultConfig);\\n```\\n\\nwhich calls\\n```\\n /// @notice Settles a matured vault account by transforming it from an fCash maturity into\\n /// a prime cash account. This method is not authenticated, anyone can settle a vault account\\n /// without permission. Generally speaking, this action is economically equivalent no matter\\n /// when it is called. In some edge conditions when the vault is holding prime cash, it is\\n /// advantageous for the vault account to have this called sooner. All vault account actions\\n /// will first settle the vault account before taking any further actions.\\n /// @param account the address to settle\\n /// @param vault the vault the account is in\\n function settleVaultAccount(address account, address vault) external override nonReentrant {\\n requireValidAccount(account);\\n require(account != vault);\\n\\n VaultConfig memory vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\\n VaultAccount memory vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\\n \\n // Require that the account settled, otherwise we may leave the account in an unintended\\n // state in this method because we allow it to skip the min borrow check in the next line.\\n (bool didSettle, bool didTransfer) = vaultAccount.settleVaultAccount(vaultConfig);\\n require(didSettle, "No Settle");\\n```\\n\\nbasically this calls\\n```\\n // Calculates the net settled cash if there is any temp cash balance that is net off\\n // against the settled prime debt.\\n bool didTransferPrimary;\\n (accountPrimeStorageValue, didTransferPrimary) = repayAccountPrimeDebtAtSettlement(\\n vaultConfig.primeRate,\\n primeVaultState,\\n vaultConfig.borrowCurrencyId,\\n vaultConfig.vault,\\n vaultAccount.account,\\n vaultAccount.tempCashBalance,\\n accountPrimeStorageValue\\n );\\n```\\n\\ncalling\\n```\\n function repayAccountPrimeDebtAtSettlement(\\n PrimeRate memory pr,\\n VaultStateStorage storage primeVaultState,\\n uint16 currencyId,\\n address vault,\\n address account,\\n int256 accountPrimeCash,\\n int256 accountPrimeStorageValue\\n ) internal returns (int256 finalPrimeDebtStorageValue, bool didTransfer) {\\n didTransfer = false;\\n finalPrimeDebtStorageValue = accountPrimeStorageValue;\\n \\n if (accountPrimeCash > 0) {\\n // netPrimeDebtRepaid is a negative number\\n int256 netPrimeDebtRepaid = pr.convertUnderlyingToDebtStorage(\\n pr.convertToUnderlying(accountPrimeCash).neg()\\n );\\n\\n int256 netPrimeDebtChange;\\n if (netPrimeDebtRepaid < accountPrimeStorageValue) {\\n // If the net debt change is greater than the debt held by the account, then only\\n // decrease the total prime debt by what is held by the account. The residual amount\\n // will be refunded to the account via a direct transfer.\\n netPrimeDebtChange = accountPrimeStorageValue;\\n finalPrimeDebtStorageValue = 0;\\n\\n int256 primeCashRefund = pr.convertFromUnderlying(\\n pr.convertDebtStorageToUnderlying(netPrimeDebtChange.sub(accountPrimeStorageValue))\\n );\\n TokenHandler.withdrawPrimeCash(\\n account, currencyId, primeCashRefund, pr, false // ETH will be transferred natively\\n );\\n didTransfer = true;\\n } else {\\n // In this case, part of the account's debt is repaid.\\n netPrimeDebtChange = netPrimeDebtRepaid;\\n finalPrimeDebtStorageValue = accountPrimeStorageValue.sub(netPrimeDebtRepaid);\\n }\\n```\\n\\nthe token withdrawal logic above try to push ETH to accout\\n```\\nTokenHandler.withdrawPrimeCash(\\n account, currencyId, primeCashRefund, pr, false // ETH will be transferred natively\\n);\\n```\\n\\nthis is calling\\n```\\n function withdrawPrimeCash(\\n address account,\\n uint16 currencyId,\\n int256 primeCashToWithdraw,\\n PrimeRate memory primeRate,\\n bool withdrawWrappedNativeToken\\n ) internal returns (int256 netTransferExternal) {\\n if (primeCashToWithdraw == 0) return 0;\\n require(primeCashToWithdraw < 0);\\n\\n Token memory underlying = getUnderlyingToken(currencyId);\\n netTransferExternal = convertToExternal(\\n underlying, \\n primeRate.convertToUnderlying(primeCashToWithdraw) \\n );\\n\\n // Overflow not possible due to int256\\n uint256 withdrawAmount = uint256(netTransferExternal.neg());\\n _redeemMoneyMarketIfRequired(currencyId, underlying, withdrawAmount);\\n\\n if (underlying.tokenType == TokenType.Ether) {\\n GenericToken.transferNativeTokenOut(account, withdrawAmount, withdrawWrappedNativeToken);\\n } else {\\n GenericToken.safeTransferOut(underlying.tokenAddress, account, withdrawAmount);\\n }\\n\\n _postTransferPrimeCashUpdate(account, currencyId, netTransferExternal, underlying, primeRate);\\n }\\n```\\n\\nnote the function call\\n```\\nif (underlying.tokenType == TokenType.Ether) {\\n GenericToken.transferNativeTokenOut(account, withdrawAmount, withdrawWrappedNativeToken);\\n} else {\\n GenericToken.safeTransferOut(underlying.tokenAddress, account, withdrawAmount);\\n}\\n```\\n\\nif the token type is not ETHER,\\nwe are transfer the underlying ERC20 token to the account\\n```\\nGenericToken.safeTransferOut(underlying.tokenAddress, account, withdrawAmount);\\n```\\n\\nthe token in-scoped is\\n```\\nERC20: Any Non-Rebasing token. ex. USDC, DAI, USDT (future), wstETH, WETH, WBTC, FRAX, CRV, etc.\\n```\\n\\nUSDC is common token that has blacklisted\\nif the account is blacklisted, the transfer would revert and the account cannot be settled!
maybe let admin bypass the withdrawPrimeCash and force settle the account to not let settlement block further action!
what are the impact,\\nper comment\\n```\\n/// will first settle the vault account before taking any further actions.\\n```\\n\\nif that is too vague, I can list three, there are more!\\nthere are certain action that need to be done after the vault settlement, for example, liqudation require the vault settlement first\\nthere are case that require force vault settlement, actually one example is notional need to force the settle the vault during migration! (this is just the case to show user should be able to permissionless reject settlement)
```\\n /// @notice Settles a matured vault account by transforming it from an fCash maturity into\\n /// a prime cash account. This method is not authenticated, anyone can settle a vault account\\n /// without permission. Generally speaking, this action is economically equivalent no matter\\n /// when it is called. In some edge conditions when the vault is holding prime cash, it is\\n /// advantageous for the vault account to have this called sooner. All vault account actions\\n /// will first settle the vault account before taking any further actions.\\n /// @param account the address to settle\\n /// @param vault the vault the account is in\\n function settleVaultAccount(address account, address vault) external override nonReentrant {\\n requireValidAccount(account);\\n require(account != vault);\\n\\n VaultConfig memory vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\\n VaultAccount memory vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\\n \\n // Require that the account settled, otherwise we may leave the account in an unintended\\n // state in this method because we allow it to skip the min borrow check in the next line.\\n (bool didSettle, bool didTransfer) = vaultAccount.settleVaultAccount(vaultConfig);\\n require(didSettle, "No Settle");\\n\\n vaultAccount.accruePrimeCashFeesToDebt(vaultConfig);\\n\\n // Skip Min Borrow Check so that accounts can always be settled\\n vaultAccount.setVaultAccount({vaultConfig: vaultConfig, checkMinBorrow: false});\\n\\n if (didTransfer) {\\n // If the vault did a transfer (i.e. withdrew cash) we have to check their collateral ratio. There\\n // is an edge condition where a vault with secondary borrows has an emergency exit. During that process\\n // an account will be left some cash balance in both currencies. It may have excess cash in one and\\n // insufficient cash in the other. A withdraw of the excess in one side will cause the vault account to\\n // be insolvent if we do not run this check. If this scenario indeed does occur, the vault itself must\\n // be upgraded in order to facilitate orderly exits for all of the accounts since they will be prevented\\n // from settling.\\n IVaultAccountHealth(address(this)).checkVaultAccountCollateralRatio(vault, account);\\n }\\n }\\n```\\n
getAccountPrimeDebtBalance() always return 0
medium
Spelling errors that result in `getAccountPrimeDebtBalance()` Always return 0\\n`getAccountPrimeDebtBalance()` use for Show current debt\\n```\\n function getAccountPrimeDebtBalance(uint16 currencyId, address account) external view override returns (\\n int256 debtBalance\\n ) {\\n mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();\\n BalanceStorage storage balanceStorage = store[account][currencyId];\\n int256 cashBalance = balanceStorage.cashBalance;\\n\\n // Only return cash balances less than zero\\n debtBalance = cashBalance < 0 ? debtBalance : 0; //<------@audit wrong, Always return 0\\n }\\n```\\n\\nIn the above code we can see that due to a spelling error, `debtBalance` always ==0 should use `debtBalance = cashBalance < 0 ? cashBalance : 0;`
```\\n function getAccountPrimeDebtBalance(uint16 currencyId, address account) external view override returns (\\n int256 debtBalance\\n ) {\\n mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();\\n BalanceStorage storage balanceStorage = store[account][currencyId];\\n int256 cashBalance = balanceStorage.cashBalance;\\n\\n // Only return cash balances less than zero\\n- debtBalance = cashBalance < 0 ? debtBalance : 0;\\n+ debtBalance = cashBalance < 0 ? cashBalance : 0;\\n }\\n```\\n
`getAccountPrimeDebtBalance()` is the external method to check the debt If a third party integrates with notional protocol, this method will be used to determine whether the user has debt or not and handle it accordingly, which may lead to serious errors in the third party's business
```\\n function getAccountPrimeDebtBalance(uint16 currencyId, address account) external view override returns (\\n int256 debtBalance\\n ) {\\n mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();\\n BalanceStorage storage balanceStorage = store[account][currencyId];\\n int256 cashBalance = balanceStorage.cashBalance;\\n\\n // Only return cash balances less than zero\\n debtBalance = cashBalance < 0 ? debtBalance : 0; //<------@audit wrong, Always return 0\\n }\\n```\\n
A single external protocol can DOS rebalancing process
medium
A failure in an external money market can DOS the entire rebalance process in Notional.\\n```\\nFile: ProportionalRebalancingStrategy.sol\\n function calculateRebalance(\\n IPrimeCashHoldingsOracle oracle,\\n uint8[] calldata rebalancingTargets\\n ) external view override onlyNotional returns (RebalancingData memory rebalancingData) {\\n address[] memory holdings = oracle.holdings();\\n..SNIP..\\n for (uint256 i; i < holdings.length;) {\\n address holding = holdings[i];\\n uint256 targetAmount = totalValue * rebalancingTargets[i] / uint256(Constants.PERCENTAGE_DECIMALS);\\n uint256 currentAmount = values[i];\\n\\n redeemHoldings[i] = holding;\\n depositHoldings[i] = holding;\\n..SNIP..\\n }\\n\\n rebalancingData.redeemData = oracle.getRedemptionCalldataForRebalancing(redeemHoldings, redeemAmounts);\\n rebalancingData.depositData = oracle.getDepositCalldataForRebalancing(depositHoldings, depositAmounts);\\n }\\n```\\n\\nDuring a rebalance, the `ProportionalRebalancingStrategy` will loop through all the holdings and perform a deposit or redemption against the external market of the holdings.\\nAssume that Notional integrates with four (4) external money markets (Aave V2, Aave V3, Compound V3, Morpho). In this case, whenever a rebalance is executed, Notional will interact with all four external money markets.\\n```\\nFile: TreasuryAction.sol\\n function _executeDeposits(Token memory underlyingToken, DepositData[] memory deposits) private {\\n..SNIP..\\n for (uint256 j; j < depositData.targets.length; ++j) {\\n // This will revert if the individual call reverts.\\n GenericToken.executeLowLevelCall(\\n depositData.targets[j], \\n depositData.msgValue[j], \\n depositData.callData[j]\\n );\\n }\\n```\\n\\n```\\nFile: TokenHandler.sol\\n function executeMoneyMarketRedemptions(\\n..SNIP..\\n for (uint256 j; j < data.targets.length; j++) {\\n // This will revert if the individual call reverts.\\n GenericToken.executeLowLevelCall(data.targets[j], 0, data.callData[j]);\\n }\\n```\\n\\nHowever, as long as one external money market reverts, the entire rebalance process will be reverted and Notional would not be able to rebalance its underlying assets.\\nThe call to the external money market can revert due to many reasons, which include the following:\\nChanges in the external protocol's interfaces (e.g. function signatures modified or functions added or removed)\\nThe external protocol is paused\\nThe external protocol has been compromised\\nThe external protocol suffers from an upgrade failure causing an error in the new contract code.
Consider implementing a more resilient rebalancing process that allows for failures in individual external money markets. For instance, Notional could catch reverts from individual money markets and continue the rebalancing process with the remaining markets.
Notional would not be able to rebalance its underlying holding if one of the external money markets causes a revert. The probability of this issue occurring increases whenever Notional integrates with a new external money market\\nThe key feature of Notional V3 is to allow its Treasury Manager to rebalance underlying holdings into various other money market protocols.\\nThis makes Notional more resilient to issues in external protocols and future-proofs the protocol. If rebalancing does not work, Notional will be unable to move its fund out of a vulnerable external market, potentially draining protocol funds if this is not mitigated.\\nAnother purpose of rebalancing is to allow Notional to allocate Notional V3's capital to new opportunities or protocols that provide a good return. If rebalancing does not work, the protocol and its users will lose out on the gain from the investment.\\nOn the other hand, if an external monkey market that Notional invested in is consistently underperforming or yielding negative returns, Notional will perform a rebalance to reallocate its funds to a better market. However, if rebalancing does not work, they will be stuck with a suboptimal asset allocation, and the protocol and its users will incur losses.
```\\nFile: ProportionalRebalancingStrategy.sol\\n function calculateRebalance(\\n IPrimeCashHoldingsOracle oracle,\\n uint8[] calldata rebalancingTargets\\n ) external view override onlyNotional returns (RebalancingData memory rebalancingData) {\\n address[] memory holdings = oracle.holdings();\\n..SNIP..\\n for (uint256 i; i < holdings.length;) {\\n address holding = holdings[i];\\n uint256 targetAmount = totalValue * rebalancingTargets[i] / uint256(Constants.PERCENTAGE_DECIMALS);\\n uint256 currentAmount = values[i];\\n\\n redeemHoldings[i] = holding;\\n depositHoldings[i] = holding;\\n..SNIP..\\n }\\n\\n rebalancingData.redeemData = oracle.getRedemptionCalldataForRebalancing(redeemHoldings, redeemAmounts);\\n rebalancingData.depositData = oracle.getDepositCalldataForRebalancing(depositHoldings, depositAmounts);\\n }\\n```\\n
Inadequate slippage control
medium
The current slippage control mechanism checks a user's acceptable interest rate limit against the post-trade rate, which could result in trades proceeding at rates exceeding the user's defined limit.\\n```\\nFile: InterestRateCurve.sol\\n function _getNetCashAmountsUnderlying(\\n InterestRateParameters memory irParams,\\n MarketParameters memory market,\\n CashGroupParameters memory cashGroup,\\n int256 totalCashUnderlying,\\n int256 fCashToAccount,\\n uint256 timeToMaturity\\n ) private pure returns (int256 postFeeCashToAccount, int256 netUnderlyingToMarket, int256 cashToReserve) {\\n uint256 utilization = getfCashUtilization(fCashToAccount, market.totalfCash, totalCashUnderlying);\\n // Do not allow utilization to go above 100 on trading\\n if (utilization > uint256(Constants.RATE_PRECISION)) return (0, 0, 0);\\n uint256 preFeeInterestRate = getInterestRate(irParams, utilization);\\n\\n int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(\\n getfCashExchangeRate(preFeeInterestRate, timeToMaturity)\\n ).neg();\\n\\n uint256 postFeeInterestRate = getPostFeeInterestRate(irParams, preFeeInterestRate, fCashToAccount < 0);\\n postFeeCashToAccount = fCashToAccount.divInRatePrecision(\\n getfCashExchangeRate(postFeeInterestRate, timeToMaturity)\\n ).neg();\\n```\\n\\nWhen executing a fCash trade, the interest rate is computed based on the utilization of the current market (Refer to Line 432). The `postFeeInterestRate` is then computed based on the `preFeeCashToAccount` and trading fee, and this rate will be used to derive the exchange rate needed to convert `fCashToAccount` to the net prime cash (postFeeCashToAccount).\\nNote that the interest rate used for the trade is `postFeeInterestRate`, and `postFeeCashToAccount` is the amount of cash credit or debit to an account.\\nIf there is any slippage control in place, the slippage should be checked against the `postFeeInterestRate` or `postFeeCashToAccount`. As such, there are two approaches to implementing slippage controls:\\n1st Approach - The current interest rate is `2%`. User sets their acceptable interest rate limit at 3% when the user submits the trade transaction. The user's tolerance is `1%`. From the time the trade is initiated to when it's executed, the rate (postFeeInterestRate) rises to 5%, the transaction should revert due to the increased slippage beyond the user's tolerance.\\n2nd Approach - If a user sets the minimum trade return of 1000 cash, but the return is only 900 cash (postFeeCashToAccount) when the trade is executed, the transaction should revert as it exceeded the user's slippage tolerance\\nNote: When users submit a trade transaction, the transaction is held in the mempool for a period of time before executing, and thus the market condition and interest rate might change during this period, and slippage control is used to protect users from these fluctuations.\\nHowever, within the codebase, it was observed that the slippage was not checked against the `postFeeInterestRate` or `postFeeCashToAccount`.\\n```\\nFile: InterestRateCurve.sol\\n // returns the net cash amounts to apply to each of the three relevant balances.\\n (\\n int256 netUnderlyingToAccount,\\n int256 netUnderlyingToMarket,\\n int256 netUnderlyingToReserve\\n ) = _getNetCashAmountsUnderlying(\\n irParams,\\n market,\\n cashGroup,\\n totalCashUnderlying,\\n fCashToAccount,\\n timeToMaturity\\n );\\n..SNIP..\\n {\\n // Do not allow utilization to go above 100 on trading, calculate the utilization after\\n // the trade has taken effect, meaning that fCash changes and cash changes are applied to\\n // the market totals.\\n market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);\\n totalCashUnderlying = totalCashUnderlying.add(netUnderlyingToMarket);\\n\\n uint256 utilization = getfCashUtilization(0, market.totalfCash, totalCashUnderlying);\\n if (utilization > uint256(Constants.RATE_PRECISION)) return (0, 0);\\n\\n uint256 newPreFeeImpliedRate = getInterestRate(irParams, utilization);\\n..SNIP..\\n // Saves the preFeeInterestRate and fCash\\n market.lastImpliedRate = newPreFeeImpliedRate;\\n }\\n```\\n\\nAfter computing the net prime cash (postFeeCashToAccount == netUnderlyingToAccount) at Line 373 above, it updates the `market.totalfCash` and `totalCashUnderlying`. Line 395 computes the `utilization` after the trade happens, and uses the latest `utilization` to compute the new interest rate after the trade and save it within the `market.lastImpliedRate`\\n```\\nFile: TradingAction.sol\\n function _executeLendBorrowTrade(\\n..SNIP..\\n cashAmount = market.executeTrade(\\n account,\\n cashGroup,\\n fCashAmount,\\n market.maturity.sub(blockTime),\\n marketIndex\\n );\\n\\n uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));\\n if (rateLimit != 0) {\\n if (tradeType == TradeActionType.Borrow) {\\n // Do not allow borrows over the rate limit\\n require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");\\n } else {\\n // Do not allow lends under the rate limit\\n require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");\\n }\\n }\\n }\\n```\\n\\nThe trade is executed at Line 256 above. After the trade is executed, it will check for the slippage at Line 264-273 above.\\nLet $IR_1$ be the interest rate used during the trade (postFeeInterestRate), $IR_2$ be the interest rate after the trade (market.lastImpliedRate), and $IR_U$ be the user's acceptable interest rate limit (rateLimit).\\nBased on the current slippage control implementation, $IR_U$ is checked against $IR_2$. Since the purpose of having slippage control in DeFi trade is to protect users from unexpected and unfavorable price changes during the execution of a trade, $IR_1$ should be used instead.\\nAssume that at the time of executing a trade (TradeActionType.Borrow), $IR_1$ spikes up and exceeds $IR_U$. However, since the slippage control checks $IR_U$ against $IR_2$, which may have resettled to $IR_U$ or lower, the transaction proceeds despite exceeding the user's acceptable rate limit. So, the transaction succeeds without a revert.\\nThis issue will exacerbate when executing large trades relative to pool liquidity.
Consider updating the slippage control to compare the user's acceptable interest rate limit (rateLimit) against the interest rate used during the trade execution (postFeeInterestRate).
The existing slippage control does not provide the desired protection against unexpected interest rate fluctuations during the transaction. As a result, users might be borrowing at a higher cost or lending at a lower return than they intended, leading to losses.
```\\nFile: InterestRateCurve.sol\\n function _getNetCashAmountsUnderlying(\\n InterestRateParameters memory irParams,\\n MarketParameters memory market,\\n CashGroupParameters memory cashGroup,\\n int256 totalCashUnderlying,\\n int256 fCashToAccount,\\n uint256 timeToMaturity\\n ) private pure returns (int256 postFeeCashToAccount, int256 netUnderlyingToMarket, int256 cashToReserve) {\\n uint256 utilization = getfCashUtilization(fCashToAccount, market.totalfCash, totalCashUnderlying);\\n // Do not allow utilization to go above 100 on trading\\n if (utilization > uint256(Constants.RATE_PRECISION)) return (0, 0, 0);\\n uint256 preFeeInterestRate = getInterestRate(irParams, utilization);\\n\\n int256 preFeeCashToAccount = fCashToAccount.divInRatePrecision(\\n getfCashExchangeRate(preFeeInterestRate, timeToMaturity)\\n ).neg();\\n\\n uint256 postFeeInterestRate = getPostFeeInterestRate(irParams, preFeeInterestRate, fCashToAccount < 0);\\n postFeeCashToAccount = fCashToAccount.divInRatePrecision(\\n getfCashExchangeRate(postFeeInterestRate, timeToMaturity)\\n ).neg();\\n```\\n
Inconsistent use of `VAULT_ACCOUNT_MIN_TIME` in vault implementation
medium
There is a considerable difference in implementation behaviour when a vault has yet to mature compared to after vault settlement.\\nThere is some questionable functionality with the following `require` statement:\\n```\\nFile: VaultAccountAction.sol\\n require(vaultAccount.lastUpdateBlockTime + Constants.VAULT_ACCOUNT_MIN_TIME <= block.timestamp)\\n```\\n\\nThe `lastUpdateBlockTime` variable is updated in two cases:\\nA user enters a vault position, updating the vault state; including `lastUpdateBlockTime`. This is a proactive measure to prevent users from quickly entering and exiting the vault.\\nThe vault has matured and as a result, each time vault fees are assessed for a given vault account, `lastUpdateBlockTime` is updated to `block.timestamp` after calculating the pro-rated fee for the prime cash vault.\\nTherefore, before a vault has matured, it is not possible to quickly enter and exit a vault. But after `Constants.VAULT_ACCOUNT_MIN_TIME` has passed, the user can exit the vault as many times as they like. However, the same does not hold true once a vault has matured. Each time a user exits the vault, they must wait `Constants.VAULT_ACCOUNT_MIN_TIME` time again to re-exit. This seems like inconsistent behaviour.
It might be worth adding an exception to `VaultConfiguration.settleAccountOrAccruePrimeCashFees()` so that when vault fees are calculated, `lastUpdatedBlockTime` is not updated to `block.timestamp`.
The `exitVault()` function will ultimately affect prime and non-prime vault users differently. It makes sense for the codebase to be written in such a way that functions execute in-line with user expectations.
```\\nFile: VaultAccountAction.sol\\n require(vaultAccount.lastUpdateBlockTime + Constants.VAULT_ACCOUNT_MIN_TIME <= block.timestamp)\\n```\\n
Return data from the external call not verified during deposit and redemption
medium
The deposit and redemption functions did not verify the return data from the external call, which might cause the contract to wrongly assume that the deposit/redemption went well although the action has actually failed in the background.\\n```\\nFile: GenericToken.sol\\n function executeLowLevelCall(\\n address target,\\n uint256 msgValue,\\n bytes memory callData\\n ) internal {\\n (bool status, bytes memory returnData) = target.call{value: msgValue}(callData);\\n require(status, checkRevertMessage(returnData));\\n }\\n```\\n\\nWhen the external call within the `GenericToken.executeLowLevelCall` function reverts, the `status` returned from the `.call` will be `false`. In this case, Line 69 above will revert.\\n```\\nFile: TreasuryAction.sol\\n for (uint256 j; j < depositData.targets.length; ++j) {\\n // This will revert if the individual call reverts.\\n GenericToken.executeLowLevelCall(\\n depositData.targets[j], \\n depositData.msgValue[j], \\n depositData.callData[j]\\n );\\n }\\n```\\n\\nFor deposit and redeem, Notional assumes that all money markets will revert if the deposit/mint and redeem/burn has an error. Thus, it does not verify the return data from the external call. Refer to the comment in Line 317 above.\\nHowever, this is not always true due to the following reasons:\\nSome money markets might not revert when errors occur but instead return `false (0)`. In this case, the current codebase will wrongly assume that the deposit/redemption went well although the action has failed.\\nCompound might upgrade its contracts to return errors instead of reverting in the future.
Consider checking the `returnData` to ensure that the external money market returns a successful response after deposit and redemption.\\nNote that the successful response returned from various money markets might be different. Some protocols return `1` on a successful action, while Compound return zero (NO_ERROR).
The gist of prime cash is to integrate with multiple markets. Thus, the codebase should be written in a manner that can handle multiple markets. Otherwise, the contract will wrongly assume that the deposit/redemption went well although the action has actually failed in the background, which might potentially lead to some edge cases where assets are sent to the users even though the redemption fails.
```\\nFile: GenericToken.sol\\n function executeLowLevelCall(\\n address target,\\n uint256 msgValue,\\n bytes memory callData\\n ) internal {\\n (bool status, bytes memory returnData) = target.call{value: msgValue}(callData);\\n require(status, checkRevertMessage(returnData));\\n }\\n```\\n
Treasury rebalance will fail due to interest accrual
medium
If Compound has updated their interest rate model, then Notional will calculate the before total underlying token balance without accruing interest. If this exceeds `Constants.REBALANCING_UNDERLYING_DELTA`, then rebalance execution will revert.\\nThe `TreasuryAction._executeRebalance()` function will revert on a specific edge case where `oracle.getTotalUnderlyingValueStateful()` does not accrue interest before calculating the value of the treasury's `cToken` holdings.\\n```\\nFile: TreasuryAction.sol\\n function _executeRebalance(uint16 currencyId) private {\\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\\n uint8[] memory rebalancingTargets = _getRebalancingTargets(currencyId, oracle.holdings());\\n (RebalancingData memory data) = REBALANCING_STRATEGY.calculateRebalance(oracle, rebalancingTargets);\\n\\n (/* */, uint256 totalUnderlyingValueBefore) = oracle.getTotalUnderlyingValueStateful();\\n\\n // Process redemptions first\\n Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\\n TokenHandler.executeMoneyMarketRedemptions(underlyingToken, data.redeemData);\\n\\n // Process deposits\\n _executeDeposits(underlyingToken, data.depositData);\\n\\n (/* */, uint256 totalUnderlyingValueAfter) = oracle.getTotalUnderlyingValueStateful();\\n\\n int256 underlyingDelta = totalUnderlyingValueBefore.toInt().sub(totalUnderlyingValueAfter.toInt());\\n require(underlyingDelta.abs() < Constants.REBALANCING_UNDERLYING_DELTA);\\n }\\n```\\n\\n`cTokenAggregator.getExchangeRateView()` returns the exchange rate which is used to calculate the underlying value of `cToken` holdings in two ways:\\nIf the interest rate model is unchanged, then we correctly accrue interest by calculating it without mutating state.\\nIf the interest rate model HAS changed, then we query `cToken.exchangeRateStored()` which DOES NOT accrue interest.\\n```\\nFile: cTokenAggregator.sol\\n function getExchangeRateView() external view override returns (int256) {\\n // Return stored exchange rate if interest rate model is updated.\\n // This prevents the function from returning incorrect exchange rates\\n uint256 exchangeRate = cToken.interestRateModel() == INTEREST_RATE_MODEL\\n ? _viewExchangeRate()\\n : cToken.exchangeRateStored();\\n _checkExchangeRate(exchangeRate);\\n\\n return int256(exchangeRate);\\n }\\n```\\n\\nTherefore, if the interest rate model has changed, `totalUnderlyingValueBefore` will not include any accrued interest and `totalUnderlyingValueAfter` will include all accrued interest. As a result, it is likely that the delta between these two amounts will exceed `Constants.REBALANCING_UNDERLYING_DELTA`, causing the rebalance to ultimately revert.\\nIt does not really make sense to not accrue interest if the interest rate model has changed unless we want to avoid any drastic changes to Notional's underlying protocol. Then we may want to explicitly revert here instead of allowing the rebalance function to still execute.
Ensure this is well-understand and consider accruing interest under any circumstance. Alternatively, if we do not wish to accrue interest when the interest rate model has changed, then we need to make sure that `underlyingDelta` does not include this amount as `TreasuryAction._executeDeposits()` will ultimately update the vault's position in Compound.
The treasury manager is unable to rebalance currencies across protocols and therefore it is likely that most funds become under-utilised as a result.
```\\nFile: TreasuryAction.sol\\n function _executeRebalance(uint16 currencyId) private {\\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\\n uint8[] memory rebalancingTargets = _getRebalancingTargets(currencyId, oracle.holdings());\\n (RebalancingData memory data) = REBALANCING_STRATEGY.calculateRebalance(oracle, rebalancingTargets);\\n\\n (/* */, uint256 totalUnderlyingValueBefore) = oracle.getTotalUnderlyingValueStateful();\\n\\n // Process redemptions first\\n Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\\n TokenHandler.executeMoneyMarketRedemptions(underlyingToken, data.redeemData);\\n\\n // Process deposits\\n _executeDeposits(underlyingToken, data.depositData);\\n\\n (/* */, uint256 totalUnderlyingValueAfter) = oracle.getTotalUnderlyingValueStateful();\\n\\n int256 underlyingDelta = totalUnderlyingValueBefore.toInt().sub(totalUnderlyingValueAfter.toInt());\\n require(underlyingDelta.abs() < Constants.REBALANCING_UNDERLYING_DELTA);\\n }\\n```\\n
Debt cannot be repaid without redeeming vault share
medium
Debt cannot be repaid without redeeming the vault share. As such, users have to redeem a certain amount of vault shares/strategy tokens at the current market price to work around this issue, which deprives users of potential gains from their vault shares if they maintain ownership until the end.\\n```\\nFile: VaultAccountAction.sol\\n function exitVault(\\n address account,\\n address vault,\\n address receiver,\\n uint256 vaultSharesToRedeem,\\n uint256 lendAmount,\\n uint32 minLendRate,\\n bytes calldata exitVaultData\\n ) external payable override nonReentrant returns (uint256 underlyingToReceiver) {\\n..SNIP..\\n // If insufficient strategy tokens are redeemed (or if it is set to zero), then\\n // redeem with debt repayment will recover the repayment from the account's wallet\\n // directly.\\n underlyingToReceiver = underlyingToReceiver.add(vaultConfig.redeemWithDebtRepayment(\\n vaultAccount, receiver, vaultSharesToRedeem, exitVaultData\\n ));\\n```\\n\\nThere is a valid scenario where users want to repay debt without redeeming their vault shares/strategy tokens (mentioned in the comments above "or if it is set to zero" at Line 251-263). In this case, the users will call `exitVault` with `vaultSharesToRedeem` parameter set to zero. The entire debt to be repaid will then be recovered directly from the account's wallet.\\nFollowing is the function trace of the VaultAccountAction.exitVault:\\n```\\nVaultAccountAction.exitVault\\n└─VaultConfiguration.redeemWithDebtRepayment\\n └─VaultConfiguration._redeem\\n └─IStrategyVault.redeemFromNotional\\n └─MetaStable2TokenAuraVault._redeemFromNotional\\n └─MetaStable2TokenAuraHelper.redeem\\n └─Balancer2TokenPoolUtils._redeem\\n └─StrategyUtils._redeemStrategyTokens\\n```\\n\\n```\\nFile: StrategyUtils.sol\\n function _redeemStrategyTokens(\\n StrategyContext memory strategyContext,\\n uint256 strategyTokens\\n ) internal returns (uint256 poolClaim) {\\n poolClaim = _convertStrategyTokensToPoolClaim(strategyContext, strategyTokens);\\n\\n if (poolClaim == 0) {\\n revert Errors.ZeroPoolClaim();\\n }\\n```\\n\\nThe problem is that if the vault shares/strategy tokens to be redeemed are zero, the `poolClaim` will be zero and cause a revert within the `StrategyUtils._redeemStrategyTokens` function call. Thus, users who want to repay debt without redeeming their vault shares/strategy tokens will be unable to do so.
Within the `VaultConfiguration.redeemWithDebtRepayment` function, skip the vault share redemption if `vaultShares` is zero. In this case, the `amountTransferred` will be zero, and the subsequent code will attempt to recover the entire `underlyingExternalToRepay` amount directly from account's wallet.\\n```\\nfunction redeemWithDebtRepayment(\\n VaultConfig memory vaultConfig,\\n VaultAccount memory vaultAccount,\\n address receiver,\\n uint256 vaultShares,\\n bytes calldata data\\n) internal returns (uint256 underlyingToReceiver) {\\n uint256 amountTransferred;\\n uint256 underlyingExternalToRepay;\\n {\\n..SNIP..\\n// Add the line below\\n if (vaultShares > 0) {\\n // Repayment checks operate entirely on the underlyingExternalToRepay, the amount of\\n // prime cash raised is irrelevant here since tempCashBalance is cleared to zero as\\n // long as sufficient underlying has been returned to the protocol.\\n (amountTransferred, underlyingToReceiver, /* primeCashRaised */) = _redeem(\\n vaultConfig,\\n underlyingToken,\\n vaultAccount.account,\\n receiver,\\n vaultShares,\\n vaultAccount.maturity,\\n underlyingExternalToRepay,\\n data\\n ); \\n// Add the line below\\n }\\n..Recover any unpaid debt amount from the account directly..\\n..SNIP..\\n```\\n\\nAlternatively, update the `StrategyUtils._redeemStrategyTokens` function to handle zero vault share appropriately. However, note that the revert at Line 154 is added as part of mitigation to the "minting zero-share" bug in the past audit. Therefore, any changes to this part of the code must ensure that the "minting zero-share" bug is not being re-introduced. Removing the code at 153-155 might result in the user's vault share being "burned" but no assets in return under certain conditions.\\n```\\nFile: StrategyUtils.sol\\n function _redeemStrategyTokens(\\n StrategyContext memory strategyContext,\\n uint256 strategyTokens\\n ) internal returns (uint256 poolClaim) {\\n poolClaim = _convertStrategyTokensToPoolClaim(strategyContext, strategyTokens);\\n\\n if (poolClaim == 0) {\\n revert Errors.ZeroPoolClaim();\\n }\\n```\\n
Users cannot repay debt without redeeming their vault shares/strategy tokens. To do so, they have to redeem a certain amount of vault shares/strategy tokens at the current market price to work around this issue so that `poolClaim > 0`, which deprives users of potential gains from their vault shares if they maintain ownership until the end.
```\\nFile: VaultAccountAction.sol\\n function exitVault(\\n address account,\\n address vault,\\n address receiver,\\n uint256 vaultSharesToRedeem,\\n uint256 lendAmount,\\n uint32 minLendRate,\\n bytes calldata exitVaultData\\n ) external payable override nonReentrant returns (uint256 underlyingToReceiver) {\\n..SNIP..\\n // If insufficient strategy tokens are redeemed (or if it is set to zero), then\\n // redeem with debt repayment will recover the repayment from the account's wallet\\n // directly.\\n underlyingToReceiver = underlyingToReceiver.add(vaultConfig.redeemWithDebtRepayment(\\n vaultAccount, receiver, vaultSharesToRedeem, exitVaultData\\n ));\\n```\\n
Vault account might not be able to exit after liquidation
medium
The vault exit might fail after a liquidation event, leading to users being unable to main their positions.\\nAssume that a large portion of the vault account gets liquidated which results in a large amount of cash deposited into the vault account's cash balance. In addition, interest will also start accruing within the vault account's cash balance.\\nLet $x$ be the `primaryCash` of a vault account after a liquidation event and interest accrual.\\nThe owner of the vault account decided to exit the vault by calling `exitVault`. Within the `exitVault` function, the `vaultAccount.tempCashBalance` will be set to $x$.\\nNext, the `lendToExitVault` function is called. Assume that the cost in prime cash terms to lend an offsetting fCash position is $-y$ (primeCashCostToLend). The `updateAccountDebt` function will be called, and the `vaultAccount.tempCashBalance` will be updated to $x + (-y) \\Rightarrow x - y$. If $x > y$, then the new `vaultAccount.tempCashBalance` will be more than zero.\\nSubsequently, the `redeemWithDebtRepayment` function will be called. However, since `vaultAccount.tempCashBalance` is larger than zero, the transaction will revert, and the owner cannot exit the vault.\\n```\\nFile: VaultConfiguration.sol\\n if (vaultAccount.tempCashBalance < 0) {\\n int256 x = vaultConfig.primeRate.convertToUnderlying(vaultAccount.tempCashBalance).neg();\\n underlyingExternalToRepay = underlyingToken.convertToUnderlyingExternalWithAdjustment(x).toUint();\\n } else {\\n // Otherwise require that cash balance is zero. Cannot have a positive cash balance in this method\\n require(vaultAccount.tempCashBalance == 0);\\n }\\n```\\n
Consider refunding the excess positive `vaultAccount.tempCashBalance` to the users so that `vaultAccount.tempCashBalance` will be cleared (set to zero) before calling the `redeemWithDebtRepayment` function.
The owner of the vault account would not be able to exit the vault to main their position. As such, their assets are stuck within the protocol.
```\\nFile: VaultConfiguration.sol\\n if (vaultAccount.tempCashBalance < 0) {\\n int256 x = vaultConfig.primeRate.convertToUnderlying(vaultAccount.tempCashBalance).neg();\\n underlyingExternalToRepay = underlyingToken.convertToUnderlyingExternalWithAdjustment(x).toUint();\\n } else {\\n // Otherwise require that cash balance is zero. Cannot have a positive cash balance in this method\\n require(vaultAccount.tempCashBalance == 0);\\n }\\n```\\n
Rebalance process reverts due to zero amount deposit and redemption
medium
Depositing or redeeming zero amount against certain external money markets will cause the rebalancing process to revert.\\nFor a specific holding (e.g. cToken), the `redeemAmounts` and `depositAmounts` are mutually exclusive. So if the `redeemAmounts` for a specific holding is non-zero, the `depositAmounts` will be zero and vice-versa. This is because of the if-else block at Lines 48-56 below. Only `redeemAmounts` or `depositAmounts` of a specific holding can be initialized, but not both.\\n```\\nFile: ProportionalRebalancingStrategy.sol\\n for (uint256 i; i < holdings.length;) {\\n address holding = holdings[i];\\n uint256 targetAmount = totalValue * rebalancingTargets[i] / uint256(Constants.PERCENTAGE_DECIMALS);\\n uint256 currentAmount = values[i];\\n\\n redeemHoldings[i] = holding;\\n depositHoldings[i] = holding;\\n\\n if (targetAmount < currentAmount) {\\n unchecked {\\n redeemAmounts[i] = currentAmount - targetAmount;\\n }\\n } else if (currentAmount < targetAmount) {\\n unchecked {\\n depositAmounts[i] = targetAmount - currentAmount;\\n }\\n }\\n\\n unchecked {\\n ++i;\\n }\\n }\\n```\\n\\nFor each holding, the following codes always deposit or redeem a zero value. For example, cETH holding, if the `redeemAmounts` is 100 ETH, the `depositAmounts` will be zero. (because of the if-else block). Therefore, `getDepositCalldataForRebalancing` function will be executed and attempt to deposit zero amount to Compound.\\n```\\nFile: ProportionalRebalancingStrategy.sol\\n rebalancingData.redeemData = oracle.getRedemptionCalldataForRebalancing(redeemHoldings, redeemAmounts);\\n rebalancingData.depositData = oracle.getDepositCalldataForRebalancing(depositHoldings, depositAmounts);\\n```\\n\\nThe problem is that the deposit/mint or redeem/burn function of certain external money markets will revert if the amount is zero. Notional is considering integrating with a few external monkey markets and one of them is AAVE.\\nIn this case, when Notional `deposit` zero amount to AAVE or `redeem` zero amount from AAVE, it causes the rebalancing process to revert because of the `onlyAmountGreaterThanZero` modifier on the AAVE's `deposit` and `redeem` function.\\n```\\nfunction deposit(address _reserve, uint256 _amount, uint16 _referralCode)\\n external\\n payable\\n nonReentrant\\n onlyActiveReserve(_reserve)\\n onlyUnfreezedReserve(_reserve)\\n onlyAmountGreaterThanZero(_amount)\\n{\\n```\\n\\n```\\nfunction redeemUnderlying(\\n address _reserve,\\n address payable _user,\\n uint256 _amount,\\n uint256 _aTokenBalanceAfterRedeem\\n)\\n external\\n nonReentrant\\n onlyOverlyingAToken(_reserve)\\n onlyActiveReserve(_reserve)\\n onlyAmountGreaterThanZero(_amount)\\n{\\n```\\n\\nThe above issue is not only limited to AAVE and might also happen in other external markets.
Consider implementing validation to ensure the contract does not deposit zero amount to or redeem zero amount from the external market.\\nFollowing is the pseudocode for the potential fixes that could be implemented within the `_getDepositCalldataForRebalancing` of the holding contract to mitigate this issue. The same should be done for redemption.\\n```\\nfunction _getDepositCalldataForRebalancing(\\n address[] calldata holdings, \\n uint256[] calldata depositAmounts\\n) internal view virtual override returns (\\n DepositData[] memory depositData\\n) {\\n require(holdings.length == NUM_ASSET_TOKENS);\\n for (int i = 0; i < holdings.length; i++) {\\n if (depositAmounts[i] > 0) {\\n // populate the depositData[i] with the deposit calldata to external money market>\\n }\\n }\\n}\\n```\\n\\nThe above solution will return an empty calldata if the deposit amount is zero for a specific holding.\\nWithin the `_executeDeposits` function, skip the `depositData` if it has not been initialized.\\n```\\nfunction _executeDeposits(Token memory underlyingToken, DepositData[] memory deposits) private {\\n uint256 totalUnderlyingDepositAmount;\\n\\n for (uint256 i; i < deposits.length; i++) {\\n DepositData memory depositData = deposits[i];\\n // if depositData is not initialized, skip to the next one\\n```\\n
Notional would not be able to rebalance its underlying holding. The key feature of Notional V3 is to allow its Treasury Manager to rebalance underlying holdings into various other money market protocols.\\nThis makes Notional more resilient to issues in external protocols and future-proofs the protocol. If rebalancing does not work, Notional will be unable to move its fund out of a vulnerable external market, potentially draining protocol funds if this is not mitigated.\\nAnother purpose of rebalancing is to allow Notional to allocate Notional V3's capital to new opportunities or protocols that provide a good return. If rebalancing does not work, the protocol and its users will lose out on the gain from the investment.\\nOn the other hand, if an external monkey market that Notional invested in is consistently underperforming or yielding negative returns, Notional will perform a rebalance to reallocate its funds to a better market. However, if rebalancing does not work, they will be stuck with a suboptimal asset allocation, and the protocol and its users will incur losses.
```\\nFile: ProportionalRebalancingStrategy.sol\\n for (uint256 i; i < holdings.length;) {\\n address holding = holdings[i];\\n uint256 targetAmount = totalValue * rebalancingTargets[i] / uint256(Constants.PERCENTAGE_DECIMALS);\\n uint256 currentAmount = values[i];\\n\\n redeemHoldings[i] = holding;\\n depositHoldings[i] = holding;\\n\\n if (targetAmount < currentAmount) {\\n unchecked {\\n redeemAmounts[i] = currentAmount - targetAmount;\\n }\\n } else if (currentAmount < targetAmount) {\\n unchecked {\\n depositAmounts[i] = targetAmount - currentAmount;\\n }\\n }\\n\\n unchecked {\\n ++i;\\n }\\n }\\n```\\n
Inaccurate settlement reserve accounting
medium
The off-chain accounting of fCash debt or prime cash in the settlement reserve will be inaccurate due to an error when handling the conversion between signed and unsigned integers.\\nEvents will be emitted to reconcile off-chain accounting for the edge condition when leveraged vaults lend at zero interest. This event will be emitted if there is fCash debt or prime cash in the settlement reserve.\\nIn an event where `s.fCashDebtHeldInSettlementReserve > 0` and `s.primeCashHeldInSettlementReserve <= 0`, no event will be emitted. As a result, the off-chain accounting of fCash debt or prime cash in the settlement reserve will be off.\\nThe reason is that since `fCashDebtInReserve` is the negation of `s.fCashDebtHeldInSettlementReserve`, which is an unsigned integer, `fCashDebtInReserve` will always be less than or equal to 0. Therefore, `fCashDebtInReserve` > 0 will always be false and is an unsatisfiable condition.\\n```\\nFile: PrimeRateLib.sol\\n // This is purely done to fully reconcile off chain accounting with the edge condition where\\n // leveraged vaults lend at zero interest.\\n int256 fCashDebtInReserve = -int256(s.fCashDebtHeldInSettlementReserve);\\n int256 primeCashInReserve = int256(s.primeCashHeldInSettlementReserve);\\n if (fCashDebtInReserve > 0 || primeCashInReserve > 0) {\\n int256 settledPrimeCash = convertFromUnderlying(settlementRate, fCashDebtInReserve);\\n int256 excessCash;\\n if (primeCashInReserve > settledPrimeCash) {\\n excessCash = primeCashInReserve - settledPrimeCash;\\n BalanceHandler.incrementFeeToReserve(currencyId, excessCash);\\n } \\n\\n Emitter.emitSettlefCashDebtInReserve(\\n currencyId, maturity, fCashDebtInReserve, settledPrimeCash, excessCash\\n );\\n }\\n```\\n
It is recommended to implement the following fix:\\n```\\n// Remove the line below\\n int256 fCashDebtInReserve = // Remove the line below\\nint256(s.fCashDebtHeldInSettlementReserve);\\n// Add the line below\\n int256 fCashDebtInReserve = int256(s.fCashDebtHeldInSettlementReserve);\\n```\\n
The off-chain accounting of fCash debt or prime cash in the settlement reserve will be inaccurate. Users who rely on inaccurate accounting information to conduct any form of financial transaction will expose themselves to unintended financial risks and make ill-informed decisions.
```\\nFile: PrimeRateLib.sol\\n // This is purely done to fully reconcile off chain accounting with the edge condition where\\n // leveraged vaults lend at zero interest.\\n int256 fCashDebtInReserve = -int256(s.fCashDebtHeldInSettlementReserve);\\n int256 primeCashInReserve = int256(s.primeCashHeldInSettlementReserve);\\n if (fCashDebtInReserve > 0 || primeCashInReserve > 0) {\\n int256 settledPrimeCash = convertFromUnderlying(settlementRate, fCashDebtInReserve);\\n int256 excessCash;\\n if (primeCashInReserve > settledPrimeCash) {\\n excessCash = primeCashInReserve - settledPrimeCash;\\n BalanceHandler.incrementFeeToReserve(currencyId, excessCash);\\n } \\n\\n Emitter.emitSettlefCashDebtInReserve(\\n currencyId, maturity, fCashDebtInReserve, settledPrimeCash, excessCash\\n );\\n }\\n```\\n
Rebalance stops working when more holdings are added
medium
Notional would not be able to rebalance its underlying holding when more holdings are added.\\n```\\nFile: TreasuryAction.sol\\n function _executeRebalance(uint16 currencyId) private {\\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\\n uint8[] memory rebalancingTargets = _getRebalancingTargets(currencyId, oracle.holdings());\\n (RebalancingData memory data) = REBALANCING_STRATEGY.calculateRebalance(oracle, rebalancingTargets);\\n\\n (/* */, uint256 totalUnderlyingValueBefore) = oracle.getTotalUnderlyingValueStateful();\\n\\n // Process redemptions first\\n Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\\n TokenHandler.executeMoneyMarketRedemptions(underlyingToken, data.redeemData);\\n\\n // Process deposits\\n _executeDeposits(underlyingToken, data.depositData);\\n\\n (/* */, uint256 totalUnderlyingValueAfter) = oracle.getTotalUnderlyingValueStateful();\\n\\n int256 underlyingDelta = totalUnderlyingValueBefore.toInt().sub(totalUnderlyingValueAfter.toInt());\\n require(underlyingDelta.abs() < Constants.REBALANCING_UNDERLYING_DELTA);\\n }\\n```\\n\\nIf the underlying delta is equal to or larger than the acceptable delta, the rebalancing process will fail and revert as per Line 301 above.\\n`Constants.REBALANCING_UNDERLYING_DELTA` is currently hardcoded to $0.0001$. There is only 1 holding (cToken) in the current code base, so $0.0001$ might be the optimal acceptable delta.\\nLet $c$ be the underlying delta for cToken holding. Then, $0 <= c < 0.0001$.\\nHowever, as more external markets are added to Notional, the number of holdings will increase, and the rounding errors could accumulate. Let $a$ and $m$ be the underlying delta for aToken and morpho token respectively. Then $0 <= (c + a + m) < 0.0001$.\\nThe accumulated rounding error or underlying delta $(c + a + m)$ could be equal to or larger than $0.0001$ and cause the `_executeRebalance` function always to revert. As a result, Notional would not be able to rebalance its underlying holding.
If the acceptable underlying delta for one holding (cToken) is $\\approx0.0001$, the acceptable underlying delta for three holdings should be $\\approx0.0003$ to factor in the accumulated rounding error or underlying delta.\\nInstead of hardcoding the `REBALANCING_UNDERLYING_DELTA`, consider allowing the governance to adjust this acceptable underlying delta to accommodate more holdings in the future and to adapt to potential changes in market conditions.
Notional would not be able to rebalance its underlying holding. The key feature of Notional V3 is to allow its Treasury Manager to rebalance underlying holdings into various other money market protocols.\\nThis makes Notional more resilient to issues in external protocols and future-proofs the protocol. If rebalancing does not work, Notional will be unable to move its fund out of a vulnerable external market, potentially draining protocol funds if this is not mitigated.\\nAnother purpose of rebalancing is to allow Notional to allocate Notional V3's capital to new opportunities or protocols that provide a good return. If rebalancing does not work, the protocol and its users will lose out on the gain from the investment.\\nOn the other hand, if an external monkey market that Notional invested in is consistently underperforming or yielding negative returns, Notional will perform a rebalance to reallocate its funds to a better market. However, if rebalancing does not work, they will be stuck with a suboptimal asset allocation, and the protocol and its users will incur losses.
```\\nFile: TreasuryAction.sol\\n function _executeRebalance(uint16 currencyId) private {\\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\\n uint8[] memory rebalancingTargets = _getRebalancingTargets(currencyId, oracle.holdings());\\n (RebalancingData memory data) = REBALANCING_STRATEGY.calculateRebalance(oracle, rebalancingTargets);\\n\\n (/* */, uint256 totalUnderlyingValueBefore) = oracle.getTotalUnderlyingValueStateful();\\n\\n // Process redemptions first\\n Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\\n TokenHandler.executeMoneyMarketRedemptions(underlyingToken, data.redeemData);\\n\\n // Process deposits\\n _executeDeposits(underlyingToken, data.depositData);\\n\\n (/* */, uint256 totalUnderlyingValueAfter) = oracle.getTotalUnderlyingValueStateful();\\n\\n int256 underlyingDelta = totalUnderlyingValueBefore.toInt().sub(totalUnderlyingValueAfter.toInt());\\n require(underlyingDelta.abs() < Constants.REBALANCING_UNDERLYING_DELTA);\\n }\\n```\\n
Underlying delta is calculated on internal token balance
medium
The underlying delta is calculated on the internal token balance, which might cause inconsistency with tokens of varying decimals.\\n```\\nFile: TreasuryAction.sol\\n function _executeRebalance(uint16 currencyId) private {\\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\\n uint8[] memory rebalancingTargets = _getRebalancingTargets(currencyId, oracle.holdings());\\n (RebalancingData memory data) = REBALANCING_STRATEGY.calculateRebalance(oracle, rebalancingTargets);\\n\\n (/* */, uint256 totalUnderlyingValueBefore) = oracle.getTotalUnderlyingValueStateful();\\n\\n // Process redemptions first\\n Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\\n TokenHandler.executeMoneyMarketRedemptions(underlyingToken, data.redeemData);\\n\\n // Process deposits\\n _executeDeposits(underlyingToken, data.depositData);\\n\\n (/* */, uint256 totalUnderlyingValueAfter) = oracle.getTotalUnderlyingValueStateful();\\n\\n int256 underlyingDelta = totalUnderlyingValueBefore.toInt().sub(totalUnderlyingValueAfter.toInt());\\n require(underlyingDelta.abs() < Constants.REBALANCING_UNDERLYING_DELTA);\\n }\\n```\\n\\nThe `underlyingDelta` is denominated in internal token precision (1e8) and is computed by taking the difference between `totalUnderlyingValueBefore` and `totalUnderlyingValueAfter` in Line 300 above.\\nNext, the `underlyingDelta` is compared against the `Constants.REBALANCING_UNDERLYING_DELTA` (10_000=0.0001) to ensure that the rebalance did not exceed the acceptable delta threshold.\\nHowever, the same `Constants.REBALANCING_UNDERLYING_DELTA` is used across all tokens such as ETH, DAI, and USDC. As a result, the delta will not be consistent with tokens of varying decimals.
Consider using the external token balance and scale `Constants.REBALANCING_UNDERLYING_DELTA` to the token's decimals.
Using the internal token precision (1e8) might result in an over-sensitive trigger for tokens with fewer decimals (e.g. 1e6) as they are scaled up and an under-sensitive one for tokens with more decimals (e.g. 1e18) as they are scaled down, leading to inconsistency across different tokens when checking against the `Constants.REBALANCING_UNDERLYING_DELTA`.\\nThis also means that the over-sensitive one will trigger a revert more easily and vice versa.
```\\nFile: TreasuryAction.sol\\n function _executeRebalance(uint16 currencyId) private {\\n IPrimeCashHoldingsOracle oracle = PrimeCashExchangeRate.getPrimeCashHoldingsOracle(currencyId);\\n uint8[] memory rebalancingTargets = _getRebalancingTargets(currencyId, oracle.holdings());\\n (RebalancingData memory data) = REBALANCING_STRATEGY.calculateRebalance(oracle, rebalancingTargets);\\n\\n (/* */, uint256 totalUnderlyingValueBefore) = oracle.getTotalUnderlyingValueStateful();\\n\\n // Process redemptions first\\n Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);\\n TokenHandler.executeMoneyMarketRedemptions(underlyingToken, data.redeemData);\\n\\n // Process deposits\\n _executeDeposits(underlyingToken, data.depositData);\\n\\n (/* */, uint256 totalUnderlyingValueAfter) = oracle.getTotalUnderlyingValueStateful();\\n\\n int256 underlyingDelta = totalUnderlyingValueBefore.toInt().sub(totalUnderlyingValueAfter.toInt());\\n require(underlyingDelta.abs() < Constants.REBALANCING_UNDERLYING_DELTA);\\n }\\n```\\n
Secondary debt dust balances are not truncated
medium
Dust balances in primary debt are truncated toward zero. However, this truncation was not performed against secondary debts.\\n```\\nFile: VaultAccount.sol\\n function updateAccountDebt(\\n..SNIP..\\n // Truncate dust balances towards zero\\n if (0 < vaultState.totalDebtUnderlying && vaultState.totalDebtUnderlying < 10) vaultState.totalDebtUnderlying = 0;\\n..SNIP..\\n }\\n```\\n\\n`vaultState.totalDebtUnderlying` is primarily used to track the total debt of primary currency. Within the `updateAccountDebt` function, any dust balance in the `vaultState.totalDebtUnderlying` is truncated towards zero at the end of the function as shown above.\\n```\\nFile: VaultSecondaryBorrow.sol\\n function _updateTotalSecondaryDebt(\\n VaultConfig memory vaultConfig,\\n address account,\\n uint16 currencyId,\\n uint256 maturity,\\n int256 netUnderlyingDebt,\\n PrimeRate memory pr\\n ) private {\\n VaultStateStorage storage balance = LibStorage.getVaultSecondaryBorrow()\\n [vaultConfig.vault][maturity][currencyId];\\n int256 totalDebtUnderlying = VaultStateLib.readDebtStorageToUnderlying(pr, maturity, balance.totalDebt);\\n \\n // Set the new debt underlying to storage\\n totalDebtUnderlying = totalDebtUnderlying.add(netUnderlyingDebt);\\n VaultStateLib.setTotalDebtStorage(\\n balance, pr, vaultConfig, currencyId, maturity, totalDebtUnderlying, false // not settled\\n );\\n```\\n\\nHowever, this approach was not consistently applied when handling dust balance in secondary debt within the `_updateTotalSecondaryDebt` function. Within the `_updateTotalSecondaryDebt` function, the dust balance in secondary debts is not truncated.
Consider truncating dust balance in secondary debt within the `_updateTotalSecondaryDebt` function similar to what has been done for primary debt.
The inconsistency in handling dust balances in primary and secondary debt could potentially lead to discrepancies in debt accounting within the protocol, accumulation of dust, and result in unforeseen consequences.
```\\nFile: VaultAccount.sol\\n function updateAccountDebt(\\n..SNIP..\\n // Truncate dust balances towards zero\\n if (0 < vaultState.totalDebtUnderlying && vaultState.totalDebtUnderlying < 10) vaultState.totalDebtUnderlying = 0;\\n..SNIP..\\n }\\n```\\n
No minimum borrow size check against secondary debts
medium
Secondary debts were not checked against the minimum borrow size during exit, which could lead to accounts with insufficient debt becoming insolvent and the protocol incurring bad debts.\\n```\\nFile: VaultAccount.sol\\n function _setVaultAccount(\\n..SNIP..\\n // An account must maintain a minimum borrow size in order to enter the vault. If the account\\n // wants to exit under the minimum borrow size it must fully exit so that we do not have dust\\n // accounts that become insolvent.\\n if (\\n vaultAccount.accountDebtUnderlying.neg() < vaultConfig.minAccountBorrowSize &&\\n // During local currency liquidation and settlement, the min borrow check is skipped\\n checkMinBorrow\\n ) {\\n // NOTE: use 1 to represent the minimum amount of vault shares due to rounding in the\\n // vaultSharesToLiquidator calculation\\n require(vaultAccount.accountDebtUnderlying == 0 || vaultAccount.vaultShares <= 1, "Min Borrow");\\n }\\n```\\n\\nA vault account has one primary debt (accountDebtUnderlying) and one or more secondary debts (accountDebtOne and accountDebtTwo).\\nWhen a vault account exits the vault, Notional will check that its primary debt (accountDebtUnderlying) meets the minimum borrow size requirement. If a vault account wants to exit under the minimum borrow size it must fully exit so that we do not have dust accounts that become insolvent. This check is being performed in Line 140 above.\\nHowever, this check is not performed against the secondary debts. As a result, it is possible that the secondary debts fall below the minimum borrow size after exiting.
Consider performing a similar check against the secondary debts (accountDebtOne and accountDebtTwo) within the `_setVaultAccount` function to ensure they do not fall below the minimum borrow size.
Vault accounts with debt below the minimum borrow size are at risk of becoming insolvent, leaving the protocol with bad debts.
```\\nFile: VaultAccount.sol\\n function _setVaultAccount(\\n..SNIP..\\n // An account must maintain a minimum borrow size in order to enter the vault. If the account\\n // wants to exit under the minimum borrow size it must fully exit so that we do not have dust\\n // accounts that become insolvent.\\n if (\\n vaultAccount.accountDebtUnderlying.neg() < vaultConfig.minAccountBorrowSize &&\\n // During local currency liquidation and settlement, the min borrow check is skipped\\n checkMinBorrow\\n ) {\\n // NOTE: use 1 to represent the minimum amount of vault shares due to rounding in the\\n // vaultSharesToLiquidator calculation\\n require(vaultAccount.accountDebtUnderlying == 0 || vaultAccount.vaultShares <= 1, "Min Borrow");\\n }\\n```\\n
It may be possible to liquidate on behalf of another account
medium
If the caller of any liquidation action is the vault itself, there is no validation of the `liquidator` parameter and therefore, any arbitrary account may act as the `liquidator` if they have approved any amount of funds for the `VaultLiquidationAction.sol` contract.\\nWhile the vault implementation itself should most likely handle proper validation of the parameters provided to actions enabled by the vault, the majority of important validation should be done within the Notional protocol. The base implementation for vaults does not seem to sanitise `liquidator` and hence users could deleverage accounts on behalf of a `liquidator` which has approved Notional's contracts.\\n```\\nFile: VaultLiquidationAction.sol\\n function _authenticateDeleverage(\\n address account,\\n address vault,\\n address liquidator\\n ) private returns (\\n VaultConfig memory vaultConfig,\\n VaultAccount memory vaultAccount,\\n VaultState memory vaultState\\n ) {\\n // Do not allow invalid accounts to liquidate\\n requireValidAccount(liquidator);\\n require(liquidator != vault);\\n\\n // Cannot liquidate self, if a vault needs to deleverage itself as a whole it has other methods \\n // in VaultAction to do so.\\n require(account != msg.sender);\\n require(account != liquidator);\\n\\n vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\\n require(vaultConfig.getFlag(VaultConfiguration.DISABLE_DELEVERAGE) == false);\\n\\n // Authorization rules for deleveraging\\n if (vaultConfig.getFlag(VaultConfiguration.ONLY_VAULT_DELEVERAGE)) {\\n require(msg.sender == vault);\\n } else {\\n require(msg.sender == liquidator);\\n }\\n\\n vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\\n\\n // Vault accounts that are not settled must be settled first by calling settleVaultAccount\\n // before liquidation. settleVaultAccount is not permissioned so anyone may settle the account.\\n require(block.timestamp < vaultAccount.maturity, "Must Settle");\\n\\n if (vaultAccount.maturity == Constants.PRIME_CASH_VAULT_MATURITY) {\\n // Returns the updated prime vault state\\n vaultState = vaultAccount.accruePrimeCashFeesToDebtInLiquidation(vaultConfig);\\n } else {\\n vaultState = VaultStateLib.getVaultState(vaultConfig, vaultAccount.maturity);\\n }\\n }\\n```\\n
Make the necessary changes to `BaseStrategyVault.sol` or `_authenticateDeleverage()`, whichever is preferred.
A user may be forced to liquidate an account they do not wish to purchase vault shares for.
```\\nFile: VaultLiquidationAction.sol\\n function _authenticateDeleverage(\\n address account,\\n address vault,\\n address liquidator\\n ) private returns (\\n VaultConfig memory vaultConfig,\\n VaultAccount memory vaultAccount,\\n VaultState memory vaultState\\n ) {\\n // Do not allow invalid accounts to liquidate\\n requireValidAccount(liquidator);\\n require(liquidator != vault);\\n\\n // Cannot liquidate self, if a vault needs to deleverage itself as a whole it has other methods \\n // in VaultAction to do so.\\n require(account != msg.sender);\\n require(account != liquidator);\\n\\n vaultConfig = VaultConfiguration.getVaultConfigStateful(vault);\\n require(vaultConfig.getFlag(VaultConfiguration.DISABLE_DELEVERAGE) == false);\\n\\n // Authorization rules for deleveraging\\n if (vaultConfig.getFlag(VaultConfiguration.ONLY_VAULT_DELEVERAGE)) {\\n require(msg.sender == vault);\\n } else {\\n require(msg.sender == liquidator);\\n }\\n\\n vaultAccount = VaultAccountLib.getVaultAccount(account, vaultConfig);\\n\\n // Vault accounts that are not settled must be settled first by calling settleVaultAccount\\n // before liquidation. settleVaultAccount is not permissioned so anyone may settle the account.\\n require(block.timestamp < vaultAccount.maturity, "Must Settle");\\n\\n if (vaultAccount.maturity == Constants.PRIME_CASH_VAULT_MATURITY) {\\n // Returns the updated prime vault state\\n vaultState = vaultAccount.accruePrimeCashFeesToDebtInLiquidation(vaultConfig);\\n } else {\\n vaultState = VaultStateLib.getVaultState(vaultConfig, vaultAccount.maturity);\\n }\\n }\\n```\\n
MarginTrading.sol: Missing flash loan initiator check allows attacker to open trades, close trades and steal funds
high
The `MarginTrading.executeOperation` function is called when a flash loan is made (and it can only be called by the lendingPool).\\nThe wrong assumption by the protocol is that the flash loan can only be initiated by the `MarginTrading` contract itself.\\nHowever this is not true. A flash loan can be initiated for any `receiverAddress`.\\n\\nSo an attacker can execute a flash loan with the `MarginTrading` contract as `receiverAddress`. Also the funds that are needed to pay back the flash loan are pulled from the `receiverAddress` and NOT from the initiator:\\nThis means the attacker can close a position or repay a position in the `MarginTrading` contract.\\nBy crafting a malicious swap, the attacker can even steal funds.\\nLet's assume there is an ongoing trade in a `MarginTrading` contract:\\n```\\ndaiAToken balance = 30000\\nwethDebtToken balance = 10\\n\\nThe price of WETH when the trade was opened was ~ 3000 DAI\\n```\\n\\nIn order to profit from this the attacker does the following (not considering fees for simplicity):\\nTake a flash loan of 30000 DAI with `MarginTrading` as `receiverAddress` with `mode=0` (flash loan is paid back in the same transaction)\\nPrice of WETH has dropped to 2000 DAI. The attacker uses a malicious swap contract that pockets 10000 DAI for the attacker and swaps the remaining 20000 DAI to 10 WETH (the attacker can freely choose the swap contract in the `_params` of the flash loan).\\nThe 10 WETH debt is repaid\\nWithdraw 30000 DAI from Aave to pay back the flash loan
The fix is straightforward:\\n```\\ndiff --git a/dodo-margin-trading-contracts/contracts/marginTrading/MarginTrading.sol b/dodo-margin-trading-contracts/contracts/marginTrading/MarginTrading.sol\\nindex f68c1f3..5b4b485 100644\\n--- a/dodo-margin-trading-contracts/contracts/marginTrading/MarginTrading.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/dodo-margin-trading-contracts/contracts/marginTrading/MarginTrading.sol\\n@@ -125,6 // Add the line below\\n125,7 @@ contract MarginTrading is OwnableUpgradeable, IMarginTrading, IFlashLoanReceiver\\n address _initiator,\\n bytes calldata _params\\n ) external override onlyLendingPool returns (bool) {\\n// Add the line below\\n require(_initiator == address(this));\\n //decode params exe swap and deposit\\n {\\n```\\n\\nThis ensures that the flash loan has been initiated by the `MarginTrading.executeFlashLoans` function which is the intended initiator.
The attacker can close trades, partially close trades and even steal funds.\\n(Note: It's not possible for the attacker to open trades because he cannot incur debt on behalf of the `MarginTrading` contract)
```\\ndaiAToken balance = 30000\\nwethDebtToken balance = 10\\n\\nThe price of WETH when the trade was opened was ~ 3000 DAI\\n```\\n
MarginTrading.sol: The whole balance and not just the traded funds are deposited into Aave when a trade is opened
medium
It's expected by the protocol that funds can be in the `MarginTrading` contract without being deposited into Aave as margin.\\nWe can see this by looking at the `MarginTradingFactory.depositMarginTradingETH` and `MarginTradingFactory.depositMarginTradingERC20` functions.\\nIf the user sets `margin=false` as the parameter, the funds are only sent to the `MarginTrading` contract but NOT deposited into Aave.\\nSo clearly there is the expectation for funds to be in the `MarginTrading` contract that should not be deposited into Aave.\\nThis becomes an issue when a trade is opened.\\nLet's look at the `MarginTrading._openTrade` function that is called when a trade is opened:\\nThe whole balance of the token will be deposited into Aave:\\n```\\n_tradeAmounts[i] = IERC20(_tradeAssets[i]).balanceOf(address(this)); \\n_lendingPoolDeposit(_tradeAssets[i], _tradeAmounts[i], 1); \\n```\\n\\nNot just those funds that have been acquired by the swap. This means that funds that should stay in the `MarginTrading` contract might also be deposited as margin.
It is necessary to differentiate the funds that are acquired by the swap and those funds that were there before and should stay in the contract:\\n```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/dodo// Remove the line below\\nmargin// Remove the line below\\ntrading// Remove the line below\\ncontracts/contracts/marginTrading/MarginTrading.sol b/dodo// Remove the line below\\nmargin// Remove the line below\\ntrading// Remove the line below\\ncontracts/contracts/marginTrading/MarginTrading.sol\\nindex f68c1f3..42f96cf 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/dodo// Remove the line below\\nmargin// Remove the line below\\ntrading// Remove the line below\\ncontracts/contracts/marginTrading/MarginTrading.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/dodo// Remove the line below\\nmargin// Remove the line below\\ntrading// Remove the line below\\ncontracts/contracts/marginTrading/MarginTrading.sol\\n@@ // Remove the line below\\n261,6 // Add the line below\\n261,10 @@ contract MarginTrading is OwnableUpgradeable, IMarginTrading, IFlashLoanReceiver\\n bytes memory _swapParams,\\n address[] memory _tradeAssets\\n ) internal {\\n// Add the line below\\n int256[] memory _amountsBefore = new uint256[](_tradeAssets.length);\\n// Add the line below\\n for (uint256 i = 0; i < _tradeAssets.length; i// Add the line below\\n// Add the line below\\n) {\\n// Add the line below\\n _amountsBefore[i] = IERC20(_tradeAssets[i]).balanceOf(address(this));\\n// Add the line below\\n }\\n if (_swapParams.length > 0) {\\n // approve to swap route\\n for (uint256 i = 0; i < _swapApproveToken.length; i// Add the line below\\n// Add the line below\\n) {\\n@@ // Remove the line below\\n272,8 // Add the line below\\n276,10 @@ contract MarginTrading is OwnableUpgradeable, IMarginTrading, IFlashLoanReceiver\\n }\\n uint256[] memory _tradeAmounts = new uint256[](_tradeAssets.length);\\n for (uint256 i = 0; i < _tradeAssets.length; i// Add the line below\\n// Add the line below\\n) {\\n// Remove the line below\\n _tradeAmounts[i] = IERC20(_tradeAssets[i]).balanceOf(address(this));\\n// Remove the line below\\n _lendingPoolDeposit(_tradeAssets[i], _tradeAmounts[i], 1);\\n// Add the line below\\n if (_amountsBefore[i] < IERC20(_tradeAssets[i]).balanceOf(address(this))) {\\n// Add the line below\\n _tradeAmounts[i] = IERC20(_tradeAssets[i]).balanceOf(address(this)) // Remove the line below\\n _amountsBefore[i];\\n// Add the line below\\n _lendingPoolDeposit(_tradeAssets[i], _tradeAmounts[i], 1);\\n// Add the line below\\n }\\n }\\n emit OpenPosition(_swapAddress, _swapApproveToken, _tradeAssets, _tradeAmounts);\\n }\\n```\\n\\nIf funds that were in the contract prior to the swap should be deposited there is the separate `MarginTrading.lendingPoolDeposit` function to achieve this.
When opening a trade funds can be deposited into Aave unintentionally. Thereby the funds act as margin and the trade can incur a larger loss than expected.
```\\n_tradeAmounts[i] = IERC20(_tradeAssets[i]).balanceOf(address(this)); \\n_lendingPoolDeposit(_tradeAssets[i], _tradeAmounts[i], 1); \\n```\\n
AuraSpell#openPositionFarm fails to return all rewards to user
high
When a user adds to an existing position on AuraSpell, the contract burns their current position and remints them a new one. The issues is that WAuraPool will send all reward tokens to the contract but it only sends Aura back to the user, causing all other rewards to be lost.\\n```\\n for (uint i = 0; i < rewardTokens.length; i++) {\\n IERC20Upgradeable(rewardTokens[i]).safeTransfer(\\n msg.sender,\\n rewards[i]\\n );\\n }\\n```\\n\\nInside WAuraPools#burn reward tokens are sent to the user.\\n```\\n IBank.Position memory pos = bank.getCurrentPositionInfo();\\n if (pos.collateralSize > 0) {\\n (uint256 pid, ) = wAuraPools.decodeId(pos.collId);\\n if (param.farmingPoolId != pid)\\n revert Errors.INCORRECT_PID(param.farmingPoolId);\\n if (pos.collToken != address(wAuraPools))\\n revert Errors.INCORRECT_COLTOKEN(pos.collToken);\\n bank.takeCollateral(pos.collateralSize);\\n wAuraPools.burn(pos.collId, pos.collateralSize);\\n _doRefundRewards(AURA);\\n }\\n```\\n\\nWe see above that the contract only refunds Aura to the user causing all other extra reward tokens received by the contract to be lost to the user.
WAuraPool returns the reward tokens it sends. Use this list to refund all tokens to the user
User will lose all extra reward tokens from their original position
```\\n for (uint i = 0; i < rewardTokens.length; i++) {\\n IERC20Upgradeable(rewardTokens[i]).safeTransfer(\\n msg.sender,\\n rewards[i]\\n );\\n }\\n```\\n
ShortLongSpell#openPosition uses the wrong balanceOf when determining how much collateral to put
high
The _doPutCollateral subcall in ShortLongSpell#openPosition uses the balance of the uToken rather than the vault resulting in the vault tokens being left in the contract which will be stolen.\\n```\\n address vault = strategies[param.strategyId].vault;\\n _doPutCollateral(\\n vault,\\n IERC20Upgradeable(ISoftVault(vault).uToken()).balanceOf(\\n address(this)\\n )\\n );\\n```\\n\\nWhen putting the collateral the contract is putting vault but it uses the balance of the uToken instead of the balance of the vault.
Use the balanceOf vault rather than vault.uToken
Vault tokens will be left in contract and stolen
```\\n address vault = strategies[param.strategyId].vault;\\n _doPutCollateral(\\n vault,\\n IERC20Upgradeable(ISoftVault(vault).uToken()).balanceOf(\\n address(this)\\n )\\n );\\n```\\n
BalancerPairOracle#getPrice will revert due to division by zero in some cases
medium
`BalancerPairOracle#getPrice` internally calls `computeFairReserves`, which returns fair reserve amounts given spot reserves, weights, and fair prices. When the parameter `resA` passed to `computeFairReserves` is smaller than `resB`, division by 0 will occur.\\nIn `BalancerPairOracle#getPrice`, resA and resB passed to `computeFairReserves` are the balance of TokenA and TokenB of the pool respectively. It is common for the balance of TokenB to be greater than the balance of TokenA.\\n```\\nfunction computeFairReserves(\\n uint256 resA,\\n uint256 resB,\\n uint256 wA,\\n uint256 wB,\\n uint256 pxA,\\n uint256 pxB\\n ) internal pure returns (uint256 fairResA, uint256 fairResB) {\\n // rest of code\\n //@audit r0 = 0 when resA < resB.\\n-> uint256 r0 = resA / resB;\\n uint256 r1 = (wA * pxB) / (wB * pxA);\\n // fairResA = resA * (r1 / r0) ^ wB\\n // fairResB = resB * (r0 / r1) ^ wA\\n if (r0 > r1) {\\n uint256 ratio = r1 / r0;\\n fairResA = resA * (ratio ** wB);\\n fairResB = resB / (ratio ** wA);\\n } else {\\n-> uint256 ratio = r0 / r1; // radio = 0 when r0 = 0\\n-> fairResA = resA / (ratio ** wB); // revert divided by 0\\n fairResB = resB * (ratio ** wA);\\n }\\n }\\n```\\n\\nAnother case is when the decimals of tokenA is smaller than the decimals of tokenB, such as usdc(e6)-weth(e18).
```\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/blueberry// Remove the line below\\ncore/contracts/oracle/BalancerPairOracle.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/blueberry// Remove the line below\\ncore/contracts/oracle/BalancerPairOracle.sol\\n@@ // Remove the line below\\n50,7 // Add the line below\\n50,7 @@ contract BalancerPairOracle is UsingBaseOracle, IBaseOracle {\\n // // Remove the line below\\n// Remove the line below\\n> fairResA / r1^wB = constant product\\n // // Remove the line below\\n// Remove the line below\\n> fairResA = resA^wA * resB^wB * r1^wB\\n // // Remove the line below\\n// Remove the line below\\n> fairResA = resA * (resB/resA)^wB * r1^wB = resA * (r1/r0)^wB\\n// Remove the line below\\n uint256 r0 = resA / resB;\\n// Add the line below\\n uint256 r0 = resA * 10**(decimalsB) / resB;\\n uint256 r1 = (wA * pxB) / (wB * pxA);\\n // fairResA = resA * (r1 / r0) ^ wB\\n // fairResB = resB * (r0 / r1) ^ wA\\n```\\n
All functions that subcall `BalancerPairOracle#getPrice` will be affected.
```\\nfunction computeFairReserves(\\n uint256 resA,\\n uint256 resB,\\n uint256 wA,\\n uint256 wB,\\n uint256 pxA,\\n uint256 pxB\\n ) internal pure returns (uint256 fairResA, uint256 fairResB) {\\n // rest of code\\n //@audit r0 = 0 when resA < resB.\\n-> uint256 r0 = resA / resB;\\n uint256 r1 = (wA * pxB) / (wB * pxA);\\n // fairResA = resA * (r1 / r0) ^ wB\\n // fairResB = resB * (r0 / r1) ^ wA\\n if (r0 > r1) {\\n uint256 ratio = r1 / r0;\\n fairResA = resA * (ratio ** wB);\\n fairResB = resB / (ratio ** wA);\\n } else {\\n-> uint256 ratio = r0 / r1; // radio = 0 when r0 = 0\\n-> fairResA = resA / (ratio ** wB); // revert divided by 0\\n fairResB = resB * (ratio ** wA);\\n }\\n }\\n```\\n
Updating the feeManger on config will cause desync between bank and vaults
medium
When the bank is initialized it caches the current config.feeManager. This is problematic since feeManger can be updated in config. Since it is precached the address in bank will not be updated leading to a desync between contracts the always pull the freshest value for feeManger and bank.\\n```\\n feeManager = config_.feeManager();\\n```\\n\\nAbove we see that feeManger is cached during initialization.\\n```\\n withdrawAmount = config.feeManager().doCutVaultWithdrawFee(\\n address(uToken),\\n shareAmount\\n );\\n```\\n\\nThis is in direct conflict with other contracts the always use the freshest value. This is problematic for a few reasons. The desync will lead to inconsistent fees across the ecosystem either charging users too many fees or not enough.
BlueBerryBank should always use config.feeManger instead of caching it.
After update users will experience inconsistent fees across the ecosystem
```\\n feeManager = config_.feeManager();\\n```\\n
ShortLongSpell#openPosition attempts to burn wrong token
medium
ShortLongSpell#openPosition attempts to burn vault.uToken when it should be using vault instead. The result is that ShortLongSpell#openPosition will be completely nonfunctional when the user is adding to their position\\n```\\n address burnToken = address(ISoftVault(strategy.vault).uToken());\\n if (collSize > 0) {\\n if (posCollToken != address(wrapper))\\n revert Errors.INCORRECT_COLTOKEN(posCollToken);\\n bank.takeCollateral(collSize);\\n wrapper.burn(burnToken, collSize);\\n _doRefund(burnToken);\\n }\\n```\\n\\nWe see above that the contract attempts to withdraw vault.uToken from the wrapper.\\n```\\n _doPutCollateral(\\n vault,\\n IERC20Upgradeable(ISoftVault(vault).uToken()).balanceOf(\\n address(this)\\n )\\n );\\n```\\n\\nThis is in direct conflict with the collateral that is actually deposited which is vault. This will cause the function to always revert when adding to an existing position.
Burn token should be vault rather than vault.uToken
ShortLongSpell#openPosition will be completely nonfunctional when the user is adding to their position
```\\n address burnToken = address(ISoftVault(strategy.vault).uToken());\\n if (collSize > 0) {\\n if (posCollToken != address(wrapper))\\n revert Errors.INCORRECT_COLTOKEN(posCollToken);\\n bank.takeCollateral(collSize);\\n wrapper.burn(burnToken, collSize);\\n _doRefund(burnToken);\\n }\\n```\\n
All allowances to DepositStableCoinToDealer and GeneralRepay can be stolen due to unsafe call
high
DepositStableCoinToDealer.sol and GeneralRepay.sol are helper contracts that allow a user to swap and enter JOJODealer and JUSDBank respectively. The issue is that the call is unsafe allowing the contract to call the token contracts directly and transfer tokens from anyone who has approved the contract.\\n```\\n IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);\\n (address approveTarget, address swapTarget, bytes memory data) = abi\\n .decode(param, (address, address, bytes));\\n // if usdt\\n IERC20(asset).approve(approveTarget, 0);\\n IERC20(asset).approve(approveTarget, amount);\\n (bool success, ) = swapTarget.call(data);\\n if (success == false) {\\n assembly {\\n let ptr := mload(0x40)\\n let size := returndatasize()\\n returndatacopy(ptr, 0, size)\\n revert(ptr, size)\\n }\\n }\\n```\\n\\nWe can see above that the call is totally unprotected allowing a user to make any call to any contract. This can be abused by calling the token contract and using the allowances of others. The attack would go as follows:\\nUser A approves the contract for 100 USDT\\nUser B sees this approval and calls depositStableCoin with the swap target as the USDT contract with themselves as the receiver\\nThis transfers all of user A USDT to them
Only allow users to call certain whitelisted contracts.
All allowances can be stolen
```\\n IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);\\n (address approveTarget, address swapTarget, bytes memory data) = abi\\n .decode(param, (address, address, bytes));\\n // if usdt\\n IERC20(asset).approve(approveTarget, 0);\\n IERC20(asset).approve(approveTarget, amount);\\n (bool success, ) = swapTarget.call(data);\\n if (success == false) {\\n assembly {\\n let ptr := mload(0x40)\\n let size := returndatasize()\\n returndatacopy(ptr, 0, size)\\n revert(ptr, size)\\n }\\n }\\n```\\n
JUSD borrow fee rate is less than it should be
medium
The borrow fee rate calculation is wrong causing the protocol to take less fees than it should.\\nThe borrowFeeRate is calculated through getTRate():\\n```\\n function getTRate() public view returns (uint256) {\\n uint256 timeDifference = block.timestamp - uint256(lastUpdateTimestamp);\\n return\\n t0Rate +\\n (borrowFeeRate * timeDifference) /\\n JOJOConstant.SECONDS_PER_YEAR;\\n }\\n```\\n\\n`t0Rate` is initialized as `1e18` in the test contracts:\\n```\\n constructor(\\n uint256 _maxReservesNum,\\n address _insurance,\\n address _JUSD,\\n address _JOJODealer,\\n uint256 _maxPerAccountBorrowAmount,\\n uint256 _maxTotalBorrowAmount,\\n uint256 _borrowFeeRate,\\n address _primaryAsset\\n ) {\\n // // rest of code\\n t0Rate = JOJOConstant.ONE;\\n }\\n```\\n\\n`SECONDS_PER_YEAR` is equal to `365 days` which is 60 * 60 * 24 * 365 = 31536000:\\n```\\nlibrary JOJOConstant {\\n uint256 public constant SECONDS_PER_YEAR = 365 days;\\n}\\n```\\n\\nAs time passes, `getTRate()` value will increase. When a user borrows JUSD the contract doesn't save the actual amount of JUSD they borrow, `tAmount`. Instead, it saves the current "value" of it, t0Amount:\\n```\\n function _borrow(\\n DataTypes.UserInfo storage user,\\n bool isDepositToJOJO,\\n address to,\\n uint256 tAmount,\\n address from\\n ) internal {\\n uint256 tRate = getTRate();\\n // tAmount % tRate ? tAmount / tRate + 1 : tAmount % tRate\\n uint256 t0Amount = tAmount.decimalRemainder(tRate)\\n ? tAmount.decimalDiv(tRate)\\n : tAmount.decimalDiv(tRate) + 1;\\n user.t0BorrowBalance += t0Amount;\\n```\\n\\nWhen you repay the JUSD, the same calculation is done again to decrease the borrowed amount. Meaning, as time passes, you have to repay more JUSD.\\nLet's say that JUSDBank was live for a year with a borrowing fee rate of 10% (1e17). `getTRate()` would then return: $1e18 + 1e17 * 31536000 / 31536000 = 1.1e18$\\nIf the user now borrows 1 JUSD we get: $1e6 * 1e18 / 1.1e18 ~= 909091$ for `t0Amount`. That's not the expected 10% decrease. Instead, it's about 9.1%.
Change formula to: `t0Amount = tAmount - tAmount.decimalMul(tRate)` where `t0Rate` is initialized with `0` instead of `1e18`.
Users are able to borrow JUSD for cheaper than expected
```\\n function getTRate() public view returns (uint256) {\\n uint256 timeDifference = block.timestamp - uint256(lastUpdateTimestamp);\\n return\\n t0Rate +\\n (borrowFeeRate * timeDifference) /\\n JOJOConstant.SECONDS_PER_YEAR;\\n }\\n```\\n
Subaccount#execute lacks payable
medium
`Subaccount#execute` lacks `payable`. If `value` in `Subaccount#execute` is not zero, it could always revert.\\n`Subaccount#execute` lacks `payable`. The caller cannot send the value.\\n```\\nfunction execute(address to, bytes calldata data, uint256 value) external onlyOwner returns (bytes memory){\\n require(to != address(0));\\n-> (bool success, bytes memory returnData) = to.call{value: value}(data);\\n if (!success) {\\n assembly {\\n let ptr := mload(0x40)\\n let size := returndatasize()\\n returndatacopy(ptr, 0, size)\\n revert(ptr, size)\\n }\\n }\\n emit ExecuteTransaction(owner, address(this), to, data, value);\\n return returnData;\\n }\\n```\\n\\nThe `Subaccount` contract does not implement receive() `payable` or fallback() `payable`, so it is unable to receive value (eth) . Therefore, `Subaccount#execute` needs to add `payable`.
Add a receive() external `payable` to the contract or `execute()` to add a `payable` modifier.
`Subaccount#execute` cannot work if `value` != 0.
```\\nfunction execute(address to, bytes calldata data, uint256 value) external onlyOwner returns (bytes memory){\\n require(to != address(0));\\n-> (bool success, bytes memory returnData) = to.call{value: value}(data);\\n if (!success) {\\n assembly {\\n let ptr := mload(0x40)\\n let size := returndatasize()\\n returndatacopy(ptr, 0, size)\\n revert(ptr, size)\\n }\\n }\\n emit ExecuteTransaction(owner, address(this), to, data, value);\\n return returnData;\\n }\\n```\\n
It's possible to reset primaryCredit and secondaryCredit for insurance account
medium
When because of negative credit after liquidations of another accounts, insurance address doesn't pass `isSafe` check, then malicious user can call JOJOExternal.handleBadDebt and reset both primaryCredit and secondaryCredit for insurance account.\\n`insurance` account is handled by JOJO team. Team is responsible to top up this account in order to cover losses. When bad debt is handled, then its negative credit value is added to the `insurance` account. Because of that it's possible that primaryCredit of `insurance` account is negative and `Liquidation._isSafe(state, insurance) == false`.\\n```\\n function handleBadDebt(Types.State storage state, address liquidatedTrader)\\n external\\n {\\n if (\\n state.openPositions[liquidatedTrader].length == 0 &&\\n !Liquidation._isSafe(state, liquidatedTrader)\\n ) {\\n int256 primaryCredit = state.primaryCredit[liquidatedTrader];\\n uint256 secondaryCredit = state.secondaryCredit[liquidatedTrader];\\n state.primaryCredit[state.insurance] += primaryCredit;\\n state.secondaryCredit[state.insurance] += secondaryCredit;\\n state.primaryCredit[liquidatedTrader] = 0;\\n state.secondaryCredit[liquidatedTrader] = 0;\\n emit HandleBadDebt(\\n liquidatedTrader,\\n primaryCredit,\\n secondaryCredit\\n );\\n }\\n }\\n```\\n\\nSo it's possible for anyone to call `handleBadDebt` for `insurance` address, once its primaryCredit is negative and `Liquidation._isSafe(state, insurance) == false`. This will reset both primaryCredit and secondaryCredit variables to 0 and break `insurance` calculations.
Do not allow `handleBadDebt` call with insurance address.
Insurance primaryCredit and secondaryCredit variables are reset.
```\\n function handleBadDebt(Types.State storage state, address liquidatedTrader)\\n external\\n {\\n if (\\n state.openPositions[liquidatedTrader].length == 0 &&\\n !Liquidation._isSafe(state, liquidatedTrader)\\n ) {\\n int256 primaryCredit = state.primaryCredit[liquidatedTrader];\\n uint256 secondaryCredit = state.secondaryCredit[liquidatedTrader];\\n state.primaryCredit[state.insurance] += primaryCredit;\\n state.secondaryCredit[state.insurance] += secondaryCredit;\\n state.primaryCredit[liquidatedTrader] = 0;\\n state.secondaryCredit[liquidatedTrader] = 0;\\n emit HandleBadDebt(\\n liquidatedTrader,\\n primaryCredit,\\n secondaryCredit\\n );\\n }\\n }\\n```\\n
When the `JUSDBank.withdraw()` is to another internal account the `ReserveInfo.isDepositAllowed` is not validated
medium
The internal withdraw does not validate if the collateral reserve has activated/deactivated the isDepositAllowed variable\\nThe JUSDBank.withdraw() function has a param called isInternal that helps to indicate if the withdraw amount is internal between accounts or not. When the withdraw is internal the `ReserveInfo.isDepositAllowed` is not validated.\\n```\\nFile: JUSDBank.sol\\n function _withdraw(\\n uint256 amount,\\n address collateral,\\n address to,\\n address from,\\n bool isInternal\\n ) internal {\\n// rest of code\\n// rest of code\\n if (isInternal) {\\n DataTypes.UserInfo storage toAccount = userInfo[to];\\n _addCollateralIfNotExists(toAccount, collateral);\\n toAccount.depositBalance[collateral] += amount;\\n require(\\n toAccount.depositBalance[collateral] <=\\n reserve.maxDepositAmountPerAccount,\\n JUSDErrors.EXCEED_THE_MAX_DEPOSIT_AMOUNT_PER_ACCOUNT\\n );\\n// rest of code\\n// rest of code\\n```\\n\\nIn the other hand, the `isDepositAllowed` is validated in the deposit function in the `code line 255` but the withdraw to internal account is not validated.\\n```\\nFile: JUSDBank.sol\\n function _deposit(\\n DataTypes.ReserveInfo storage reserve,\\n DataTypes.UserInfo storage user,\\n uint256 amount,\\n address collateral,\\n address to,\\n address from\\n ) internal {\\n require(reserve.isDepositAllowed, JUSDErrors.RESERVE_NOT_ALLOW_DEPOSIT);\\n```\\n\\nAdditionally, the `ReserveInfo.isDepositAllowed` can be modified via the JUSDOperation.delistReserve() function. So any collateral's deposits can be deactivated at any time.\\n```\\nFile: JUSDOperation.sol\\n function delistReserve(address collateral) external onlyOwner {\\n DataTypes.ReserveInfo storage reserve = reserveInfo[collateral];\\n reserve.isBorrowAllowed = false;\\n reserve.isDepositAllowed = false;\\n reserve.isFinalLiquidation = true;\\n emit RemoveReserve(collateral);\\n }\\n```\\n
Add a `Reserve.isDepositAllowed` validation when the withdrawal is to another internal account.\\n```\\nFile: JUSDBank.sol\\n function _withdraw(\\n uint256 amount,\\n address collateral,\\n address to,\\n address from,\\n bool isInternal\\n ) internal {\\n// rest of code\\n// rest of code\\n if (isInternal) {\\n// Add the line below\\n// Add the line below\\n require(reserve.isDepositAllowed, JUSDErrors.RESERVE_NOT_ALLOW_DEPOSIT);\\n DataTypes.UserInfo storage toAccount = userInfo[to];\\n _addCollateralIfNotExists(toAccount, collateral);\\n toAccount.depositBalance[collateral] // Add the line below\\n= amount;\\n require(\\n toAccount.depositBalance[collateral] <=\\n reserve.maxDepositAmountPerAccount,\\n JUSDErrors.EXCEED_THE_MAX_DEPOSIT_AMOUNT_PER_ACCOUNT\\n );\\n// rest of code\\n// rest of code\\n```\\n
The collateral's reserve can get deposits via the internal withdraw even when the `Reserve.isDepositAllowed` is turned off making the `Reserve.isDepositAllowed` useless because the collateral deposits can be via `internal withdrawals`.
```\\nFile: JUSDBank.sol\\n function _withdraw(\\n uint256 amount,\\n address collateral,\\n address to,\\n address from,\\n bool isInternal\\n ) internal {\\n// rest of code\\n// rest of code\\n if (isInternal) {\\n DataTypes.UserInfo storage toAccount = userInfo[to];\\n _addCollateralIfNotExists(toAccount, collateral);\\n toAccount.depositBalance[collateral] += amount;\\n require(\\n toAccount.depositBalance[collateral] <=\\n reserve.maxDepositAmountPerAccount,\\n JUSDErrors.EXCEED_THE_MAX_DEPOSIT_AMOUNT_PER_ACCOUNT\\n );\\n// rest of code\\n// rest of code\\n```\\n
Lack of burn mechanism for JUSD repayments causes oversupply of JUSD
medium
`JUSDBank.repay()` allow users to repay their JUSD debt and interest by transfering in JUSD tokens. Without a burn mechanism, it will cause an oversupply of JUSD that is no longer backed by any collateral.\\n`JUSDBank` receives JUSD tokens for the repayment of debt and interest. However, there are no means to burn these tokens, causing JUSD balance in `JUSDBank` to keep increasing.\\nThat will lead to an oversupply of JUSD that is not backed by any collateral. And the oversupply of JUSD will increase significantly during market due to mass repayments from liquidation.\\n```\\n function _repay(\\n DataTypes.UserInfo storage user,\\n address payer,\\n address to,\\n uint256 amount,\\n uint256 tRate\\n ) internal returns (uint256) {\\n require(amount != 0, JUSDErrors.REPAY_AMOUNT_IS_ZERO);\\n uint256 JUSDBorrowed = user.t0BorrowBalance.decimalMul(tRate);\\n uint256 tBorrowAmount;\\n uint256 t0Amount;\\n if (JUSDBorrowed <= amount) {\\n tBorrowAmount = JUSDBorrowed;\\n t0Amount = user.t0BorrowBalance;\\n } else {\\n tBorrowAmount = amount;\\n t0Amount = amount.decimalDiv(tRate);\\n }\\n IERC20(JUSD).safeTransferFrom(payer, address(this), tBorrowAmount);\\n user.t0BorrowBalance -= t0Amount;\\n t0TotalBorrowAmount -= t0Amount;\\n emit Repay(payer, to, tBorrowAmount);\\n return tBorrowAmount;\\n }\\n```\\n
Instead of transfering to the JUSDBank upon repayment, consider adding a burn mechanism to reduce the supply of JUSD so that it will be adjusted automatically.
To maintain its stability, JUSD must always be backed by more than 1 USD worth of collateral.\\nWhen there is oversupply of JUSD that is not backed by any collateral, it affects JUSD stability and possibly lead to a depeg event.
```\\n function _repay(\\n DataTypes.UserInfo storage user,\\n address payer,\\n address to,\\n uint256 amount,\\n uint256 tRate\\n ) internal returns (uint256) {\\n require(amount != 0, JUSDErrors.REPAY_AMOUNT_IS_ZERO);\\n uint256 JUSDBorrowed = user.t0BorrowBalance.decimalMul(tRate);\\n uint256 tBorrowAmount;\\n uint256 t0Amount;\\n if (JUSDBorrowed <= amount) {\\n tBorrowAmount = JUSDBorrowed;\\n t0Amount = user.t0BorrowBalance;\\n } else {\\n tBorrowAmount = amount;\\n t0Amount = amount.decimalDiv(tRate);\\n }\\n IERC20(JUSD).safeTransferFrom(payer, address(this), tBorrowAmount);\\n user.t0BorrowBalance -= t0Amount;\\n t0TotalBorrowAmount -= t0Amount;\\n emit Repay(payer, to, tBorrowAmount);\\n return tBorrowAmount;\\n }\\n```\\n
UniswapPriceAdaptor fails after updating impact
medium
The `impact` variable can have a maximum value of `uint32` (=4.294.967.295) after updating. This is too low and will cause the `UniswapPriceAdaptor#getMarkPrice()` function to revert.\\nWhen initialized, the `impact` variable is a `uint256`. However, in the `updateImpact` function, the newImpact is a `uint32`.\\n```\\n function updateImpact(uint32 newImpact) external onlyOwner {\\n emit UpdateImpact(impact, newImpact);\\n impact = newImpact;\\n }\\n```\\n\\nThe new `impact` variable will be too small because in the getMarkPrice() function, we need diff * 1e18 / JOJOPriceFeed <= impact:\\n```\\n require(diff * 1e18 / JOJOPriceFeed <= impact, "deviation is too big");\\n```\\n\\nThe result of `diff * 1e18 / JOJOPriceFeed <= impact` is a number with e18 power. It is very likely that it is larger than the `impact` variable which is a `uint32`. The function getMarkPrice() will revert.
Change the newImpact argument from uint32 to uint256.\\n```\\n// Remove the line below\\n function updateImpact(uint32 newImpact) external onlyOwner {\\n// Add the line below\\n function updateImpact(uint256 newImpact) external onlyOwner { \\n emit UpdateImpact(impact, newImpact);\\n impact = newImpact;\\n }\\n```\\n
The UniswapPriceAdaptor will malfunction and not return the price from Uniswap Oracle.
```\\n function updateImpact(uint32 newImpact) external onlyOwner {\\n emit UpdateImpact(impact, newImpact);\\n impact = newImpact;\\n }\\n```\\n
In over liquidation, if the liquidatee has USDC-denominated assets for sale, the liquidator can buy the assets with USDC to avoid paying USDC to the liquidatee
medium
In over liquidation, if the liquidatee has USDC-denominated assets for sale, the liquidator can buy the assets with USDC to avoid paying USDC to the liquidatee\\nIn JUSDBank contract, if the liquidator wants to liquidate more collateral than the borrowings of the liquidatee, the liquidator can pay additional USDC to get the liquidatee's collateral.\\n```\\n } else {\\n // actualJUSD = actualCollateral * priceOff\\n // = JUSDBorrowed * priceOff / priceOff * (1-insuranceFeeRate)\\n // = JUSDBorrowed / (1-insuranceFeeRate)\\n // insuranceFee = actualJUSD * insuranceFeeRate\\n // = actualCollateral * priceOff * insuranceFeeRate\\n // = JUSDBorrowed * insuranceFeeRate / (1- insuranceFeeRate)\\n liquidateData.actualCollateral = JUSDBorrowed\\n .decimalDiv(priceOff)\\n .decimalDiv(JOJOConstant.ONE - reserve.insuranceFeeRate);\\n liquidateData.insuranceFee = JUSDBorrowed\\n .decimalMul(reserve.insuranceFeeRate)\\n .decimalDiv(JOJOConstant.ONE - reserve.insuranceFeeRate);\\n liquidateData.actualLiquidatedT0 = liquidatedInfo.t0BorrowBalance;\\n liquidateData.actualLiquidated = JUSDBorrowed;\\n }\\n\\n liquidateData.liquidatedRemainUSDC = (amount -\\n liquidateData.actualCollateral).decimalMul(price);\\n```\\n\\nThe liquidator needs to pay USDC in the callback and the JUSDBank contract will require the final USDC balance of the liquidatee to increase.\\n```\\n require(\\n IERC20(primaryAsset).balanceOf(liquidated) -\\n primaryLiquidatedAmount >=\\n liquidateData.liquidatedRemainUSDC,\\n JUSDErrors.LIQUIDATED_AMOUNT_NOT_ENOUGH\\n );\\n```\\n\\nIf the liquidatee has USDC-denominated assets for sale, the liquidator can purchase the assets with USDC in the callback, so that the liquidatee's USDC balance will increase and the liquidator will not need to send USDC to the liquidatee to pass the check in the JUSDBank contract.
Consider banning over liquidation
In case of over liquidation, the liquidator does not need to pay additional USDC to the liquidatee
```\\n } else {\\n // actualJUSD = actualCollateral * priceOff\\n // = JUSDBorrowed * priceOff / priceOff * (1-insuranceFeeRate)\\n // = JUSDBorrowed / (1-insuranceFeeRate)\\n // insuranceFee = actualJUSD * insuranceFeeRate\\n // = actualCollateral * priceOff * insuranceFeeRate\\n // = JUSDBorrowed * insuranceFeeRate / (1- insuranceFeeRate)\\n liquidateData.actualCollateral = JUSDBorrowed\\n .decimalDiv(priceOff)\\n .decimalDiv(JOJOConstant.ONE - reserve.insuranceFeeRate);\\n liquidateData.insuranceFee = JUSDBorrowed\\n .decimalMul(reserve.insuranceFeeRate)\\n .decimalDiv(JOJOConstant.ONE - reserve.insuranceFeeRate);\\n liquidateData.actualLiquidatedT0 = liquidatedInfo.t0BorrowBalance;\\n liquidateData.actualLiquidated = JUSDBorrowed;\\n }\\n\\n liquidateData.liquidatedRemainUSDC = (amount -\\n liquidateData.actualCollateral).decimalMul(price);\\n```\\n
FlashLoanLiquidate.JOJOFlashLoan has no slippage control when swapping USDC
medium
FlashLoanLiquidate.JOJOFlashLoan has no slippage control when swapping USDC\\nIn both GeneralRepay.repayJUSD and FlashLoanRepay.JOJOFlashLoan, the user-supplied minReceive parameter is used for slippage control when swapping USDC.\\n```\\n function JOJOFlashLoan(\\n address asset,\\n uint256 amount,\\n address to,\\n bytes calldata param\\n ) external {\\n (address approveTarget, address swapTarget, uint256 minReceive, bytes memory data) = abi\\n .decode(param, (address, address, uint256, bytes));\\n IERC20(asset).approve(approveTarget, amount);\\n (bool success, ) = swapTarget.call(data);\\n if (success == false) {\\n assembly {\\n let ptr := mload(0x40)\\n let size := returndatasize()\\n returndatacopy(ptr, 0, size)\\n revert(ptr, size)\\n }\\n }\\n uint256 USDCAmount = IERC20(USDC).balanceOf(address(this));\\n require(USDCAmount >= minReceive, "receive amount is too small");\\n// rest of code\\n function repayJUSD(\\n address asset,\\n uint256 amount,\\n address to,\\n bytes memory param\\n ) external {\\n IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);\\n uint256 minReceive;\\n if (asset != USDC) {\\n (address approveTarget, address swapTarget, uint256 minAmount, bytes memory data) = abi\\n .decode(param, (address, address, uint256, bytes));\\n IERC20(asset).approve(approveTarget, amount);\\n (bool success, ) = swapTarget.call(data);\\n if (success == false) {\\n assembly {\\n let ptr := mload(0x40)\\n let size := returndatasize()\\n returndatacopy(ptr, 0, size)\\n revert(ptr, size)\\n }\\n }\\n minReceive = minAmount;\\n }\\n\\n uint256 USDCAmount = IERC20(USDC).balanceOf(address(this));\\n require(USDCAmount >= minReceive, "receive amount is too small");\\n```\\n\\nHowever, this is not done in FlashLoanLiquidate.JOJOFlashLoan, and the lack of slippage control may expose the user to sandwich attacks when swapping USDC.
Consider making FlashLoanLiquidate.JOJOFlashLoan use the minReceive parameter for slippage control when swapping USDC.
The lack of slippage control may expose the user to sandwich attacks when swapping USDC.
```\\n function JOJOFlashLoan(\\n address asset,\\n uint256 amount,\\n address to,\\n bytes calldata param\\n ) external {\\n (address approveTarget, address swapTarget, uint256 minReceive, bytes memory data) = abi\\n .decode(param, (address, address, uint256, bytes));\\n IERC20(asset).approve(approveTarget, amount);\\n (bool success, ) = swapTarget.call(data);\\n if (success == false) {\\n assembly {\\n let ptr := mload(0x40)\\n let size := returndatasize()\\n returndatacopy(ptr, 0, size)\\n revert(ptr, size)\\n }\\n }\\n uint256 USDCAmount = IERC20(USDC).balanceOf(address(this));\\n require(USDCAmount >= minReceive, "receive amount is too small");\\n// rest of code\\n function repayJUSD(\\n address asset,\\n uint256 amount,\\n address to,\\n bytes memory param\\n ) external {\\n IERC20(asset).safeTransferFrom(msg.sender, address(this), amount);\\n uint256 minReceive;\\n if (asset != USDC) {\\n (address approveTarget, address swapTarget, uint256 minAmount, bytes memory data) = abi\\n .decode(param, (address, address, uint256, bytes));\\n IERC20(asset).approve(approveTarget, amount);\\n (bool success, ) = swapTarget.call(data);\\n if (success == false) {\\n assembly {\\n let ptr := mload(0x40)\\n let size := returndatasize()\\n returndatacopy(ptr, 0, size)\\n revert(ptr, size)\\n }\\n }\\n minReceive = minAmount;\\n }\\n\\n uint256 USDCAmount = IERC20(USDC).balanceOf(address(this));\\n require(USDCAmount >= minReceive, "receive amount is too small");\\n```\\n
JUSDBank users can bypass individual collateral borrow limits
medium
JUSDBank imposes individual borrow caps on each collateral. The issue is that this can be bypassed due to the fact that withdraw and borrow use different methods to determine if an account is safe.\\n```\\n function borrow(\\n uint256 amount,\\n address to,\\n bool isDepositToJOJO\\n ) external override nonReentrant nonFlashLoanReentrant{\\n // t0BorrowedAmount = borrowedAmount / getT0Rate\\n DataTypes.UserInfo storage user = userInfo[msg.sender];\\n _borrow(user, isDepositToJOJO, to, amount, msg.sender);\\n require(\\n _isAccountSafeAfterBorrow(user, getTRate()),\\n JUSDErrors.AFTER_BORROW_ACCOUNT_IS_NOT_SAFE\\n );\\n }\\n```\\n\\nWhen borrowing the contract calls _isAccountSafeAfterBorrow. This imposes a max borrow on each collateral type that guarantees that the user cannot borrow more than the max for each collateral type. The issues is that withdraw doesn't impose this cap. This allows a user to bypass this cap as shown in the example below.\\nExample: Assume WETH and WBTC both have a cap of 10,000 borrow. The user deposits $30,000 WETH and takes a flashloand for $30,000 WBTC. Now they deposit both and borrow 20,000 JUSD. They then withdraw all their WBTC to repay the flashloan and now they have borrowed 20,000 against $30000 in WETH
Always use _isAccountSafeAfterBorrow
Deposit caps can be easily surpassed creating systematic risk for the system
```\\n function borrow(\\n uint256 amount,\\n address to,\\n bool isDepositToJOJO\\n ) external override nonReentrant nonFlashLoanReentrant{\\n // t0BorrowedAmount = borrowedAmount / getT0Rate\\n DataTypes.UserInfo storage user = userInfo[msg.sender];\\n _borrow(user, isDepositToJOJO, to, amount, msg.sender);\\n require(\\n _isAccountSafeAfterBorrow(user, getTRate()),\\n JUSDErrors.AFTER_BORROW_ACCOUNT_IS_NOT_SAFE\\n );\\n }\\n```\\n
GeneralRepay#repayJUSD returns excess USDC to `to` address rather than msg.sender
medium
When using GeneralRepay#repayJUSD `to` repay a position on JUSDBank, any excess tokens are sent `to` the `to` address. While this is fine for users that are repaying their own debt this is not good when repaying for another user. Additionally, specifying an excess `to` repay is basically a requirement when attempting `to` pay off the entire balance of an account. This combination of factors will make it very likely that funds will be refunded incorrectly.\\n```\\n IERC20(USDC).approve(jusdExchange, borrowBalance);\\n IJUSDExchange(jusdExchange).buyJUSD(borrowBalance, address(this));\\n IERC20(USDC).safeTransfer(to, USDCAmount - borrowBalance);\\n JUSDAmount = borrowBalance;\\n }\\n```\\n\\nAs seen above, when there is an excess amount of USDC, it is transferred `to` the `to` address which is the recipient of the repay. When `to` != msg.sender all excess will be sent `to` the recipient of the repay rather than being refunded `to` the caller.
Either send the excess back to the caller or allow them to specify where the refund goes
Refund is sent to the wrong address if to != msg.sender
```\\n IERC20(USDC).approve(jusdExchange, borrowBalance);\\n IJUSDExchange(jusdExchange).buyJUSD(borrowBalance, address(this));\\n IERC20(USDC).safeTransfer(to, USDCAmount - borrowBalance);\\n JUSDAmount = borrowBalance;\\n }\\n```\\n
Certain ERC20 token does not return bool from approve and transfer and transaction revert
medium
Certain ERC20 token does not return bool from approve and transfer and transaction revert\\nAccording to\\nSome tokens do not return a bool on ERC20 methods and use IERC20 token interface will revert transaction\\nCertain ERC20 token does not return bool from approve and transfer and transaction revert\\n```\\n function setApprovalForERC20(\\n IERC20 erc20Contract,\\n address to,\\n uint256 amount\\n ) external onlyClubOwner {\\n erc20Contract.approve(to, amount);\\n }\\n```\\n\\nand\\n```\\nfunction transferERC20(\\n IERC20 erc20Contract,\\n address to,\\n uint256 amount\\n) external onlyClubOwner {\\n erc20Contract.transfer(to, amount);\\n}\\n```\\n\\nthe transfer / approve can fail slienlty
Issue Certain ERC20 token does not return bool from approve and transfer and transaction revert\\nUse Openzeppelin SafeTransfer / SafeApprove
Some tokens do not return a bool on ERC20 methods and use IERC20 token interface will revert transaction
```\\n function setApprovalForERC20(\\n IERC20 erc20Contract,\\n address to,\\n uint256 amount\\n ) external onlyClubOwner {\\n erc20Contract.approve(to, amount);\\n }\\n```\\n