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
Permissioned rebalancing functions leading to loss of assets
medium
Permissioned rebalancing functions that could only be accessed by admin could lead to a loss of assets.\\nPer the contest's README page, it stated that the admin/owner is "RESTRICTED". Thus, any finding showing that the owner/admin can steal a user's funds, cause loss of funds or harm to the users, or cause the user's ...
To prevent the above scenario, the minimum `targetBufferPercentage` should be set to a higher percentage such as 5 or 10%, and the `requestWithdrawal` function should be made permissionless, so that even if the rebalancer does not do its job, anyone else can still initiate the rebalancing process to replenish the adapt...
Loss of assets for the victim.
```\\nFile: BaseLSTAdapter.sol\\n function setRebalancer(address _rebalancer) external onlyOwner {\\n rebalancer = _rebalancer;\\n }\\n```\\n
Unable to deposit to Tranche/Adaptor under certain conditions
medium
Minting of PT and YT is the core feature of the protocol. Without the ability to mint PT and YT, the protocol would not operate.\\nThe user cannot deposit into the Tranche to issue new PT + YT under certain conditions.\\nThe comment in Line 133 below mentioned that the `stakeAmount` can be zero.\\nThe reason is that wh...
Short-circuit the `_stake` function by returning zero value immediately if the `stakeAmount` is zero.\\nFile: StEtherAdapter.sol\\n```\\nfunction _stake(uint256 stakeAmount) internal override returns (uint256) {\\n// Add the line below\\n if (stakeAmount == 0) return 0; \\n uint256 stakeLimit = STETH.getCurrentStakeLim...
Minting of PT and YT is the core feature of the protocol. Without the ability to mint PT and YT, the protocol would not operate. The user cannot deposit into the Tranche to issue new PT + YT under certain conditions. Breaking of core protocol/contract functionality.
```\\nFile: BaseLSTAdapter.sol\\n function prefundedDeposit() external nonReentrant returns (uint256, uint256) {\\n..SNIP..\\n uint256 stakeAmount;\\n unchecked {\\n stakeAmount = availableEth + queueEthCache - targetBufferEth; // non-zero, no underflow\\n }\\n // If the stake ...
Napier pool owner can unfairly increase protocol fees on swaps to earn more revenue
medium
Currently there is no limit to how often a `poolOwner` can update fees which can be abused to earn more fees by charging users higher swap fees than they expect.\\nThe `NapierPool::setFeeParameter` function allows the `poolOwner` to set the `protocolFeePercent` at any point to a maximum value of 100%. The `poolOwner` i...
Introduce a delay in fee updates to ensure users receive the fees they expect.
A malicious `poolOwner` could change the protocol swap fees unfairly for users by front-running swaps and increasing fees to higher values on unsuspecting users. An example scenario is:\\nThe `poolOwner` sets swap fees to 1% to attract users\\nThe `poolOwner` front runs all swaps and changes the swap fees to the maximu...
```\\n function test_protocol_owner_frontRuns_swaps_with_higher_fees() public whenMaturityNotPassed {\\n // pre-condition\\n vm.warp(maturity - 30 days);\\n deal(address(pts[0]), alice, type(uint96).max, false); // ensure alice has enough pt\\n uint256 preBaseLptSupply = tricrypto.totalSuppl...
Benign esfrxETH holders incur more loss than expected
medium
Malicious esfrxETH holders can avoid "pro-rated" loss and have the remaining esfrxETH holders incur all the loss due to the fee charged by FRAX during unstaking. As a result, the rest of the esfrxETH holders incur more losses than expected compared to if malicious esfrxETH holders had not used this trick in the first p...
The best way to discourage users from withdrawing their assets and depositing them back to take advantage of a particular event is to impose a fee upon depositing and withdrawing.
The rest of the esfrxETH holders incur more losses than expected compared to if malicious esfrxETH holders had not used this trick in the first place.
```\\nFile: SFrxETHAdapter.sol\\n/// @title SFrxETHAdapter - esfrxETH\\n/// @dev Important security note:\\n/// 1. The vault share price (esfrxETH / WETH) increases as sfrxETH accrues staking rewards.\\n/// However, the share price decreases when frxETH (sfrxETH) is withdrawn.\\n/// Withdrawals are processed by the Fra...
Lack of slippage control for `issue` function
medium
The lack of slippage control for `issue` function can lead to a loss of assets for the affected users.\\nDuring the issuance, the user will deposit underlying assets (e.g., ETH) to the Tranche contract, and the Tranche contract will forward them to the Adaptor contract for depositing at Line 208 below. The number of sh...
Implement a slippage control that allows the users to revert if the amount of PT/YT they received is less than the amount they expected.
Loss of assets for the affected users.
```\\nFile: Tranche.sol\\n function issue(\\n address to,\\n uint256 underlyingAmount\\n ) external nonReentrant whenNotPaused notExpired returns (uint256 issued) {\\n..SNIP..\\n // Transfer underlying from user to adapter and deposit it into adapter to get target token\\n _underlying....
Users unable to withdraw their funds due to FRAX admin action
medium
FRAX admin action can lead to the fund of Naiper protocol and its users being stuck, resulting in users being unable to withdraw their assets.\\nPer the contest page, the admins of the protocols that Napier integrates with are considered "RESTRICTED". This means that any issue related to FRAX's admin action that could ...
Ensure that the protocol team and its users are aware of the risks of such an event and develop a contingency plan to manage it.
The fund of Naiper protocol and its users will be stuck, resulting in users being unable to withdraw their assets.
```\\nFile: SFrxETHAdapter.sol\\n function claimWithdrawal() external override {\\n uint256 _requestId = requestId;\\n uint256 _withdrawalQueueEth = withdrawalQueueEth;\\n if (_requestId == 0) revert NoPendingWithdrawal();\\n\\n /// WRITE ///\\n delete withdrawalQueueEth;\\n ...
Users are unable to collect their yield if tranche is paused
medium
Users are unable to collect their yield if Tranche is paused, resulting in a loss of assets for the victims.\\nPer the contest's README page, it stated that the admin/owner is "RESTRICTED". Thus, any finding showing that the owner/admin can steal a user's funds, cause loss of funds or harm to the users, or cause the us...
Consider allowing the users to collect yield even when the system is paused.
Users are unable to collect their yield if Tranche is paused, resulting in a loss of assets for the victims.
```\\nFile: Tranche.sol\\n /// @notice Pause issue, collect and updateUnclaimedYield\\n /// @dev only callable by management\\n function pause() external onlyManagement {\\n _pause();\\n }\\n\\n /// @notice Unpause issue, collect and updateUnclaimedYield\\n /// @dev only callable by management\...
`swapUnderlyingForYt` revert due to rounding issues
medium
The core function (swapUnderlyingForYt) of the Router will revert due to rounding issues. Users who intend to swap underlying assets to YT tokens via the Router will be unable to do so.\\nThe `swapUnderlyingForYt` allows users to swap underlying assets to a specific number of YT tokens they desire.\\n```\\nFile: Napier...
The buffer does not appear to be the correct approach to manage this rounding error. One could increase the buffer from 0.01% to 1% and solve the issue in the above example, but a different or larger number might cause a rounding error to surface again. Also, a larger buffer means that many unnecessary PTs will be issu...
The core function (swapUnderlyingForYt) of the Router will break. Users who intend to swap underlying assets to YT tokens via the Router will not be able to do so.
```\\nFile: NapierRouter.sol\\n function swapUnderlyingForYt(\\n address pool,\\n uint256 index,\\n uint256 ytOutDesired,\\n uint256 underlyingInMax,\\n address recipient,\\n uint256 deadline\\n ) external payable override nonReentrant checkDeadline(deadline) returns (uin...
FRAX admin can adjust fee rate to harm Napier and its users
medium
FRAX admin can adjust fee rates to harm Napier and its users, preventing Napier users from withdrawing.\\nPer the contest page, the admins of the protocols that Napier integrates with are considered "RESTRICTED". This means that any issue related to FRAX's admin action that could negatively affect Napier protocol/users...
Ensure that the protocol team and its users are aware of the risks of such an event and develop a contingency plan to manage it.
Users unable to withdraw their assets. Loss of assets for the victim.
```\\nFile: FraxEtherRedemptionQueue.sol\\n /// @notice Sets the fee for redeeming\\n /// @param _newFee New redemption fee given in percentage terms, using 1e6 precision\\n function setRedemptionFee(uint64 _newFee) external {\\n _requireSenderIsTimelock();\\n if (_newFee > FEE_PRECISION) revert ...
SFrxETHAdapter redemptionQueue waiting period can DOS adapter functions
medium
The waiting period between `rebalancer` address making a withdrawal request and the withdrawn funds being ready to claim from `FraxEtherRedemptionQueue` is extremely long which can lead to a significant period of time where some of the protocol's functions are either unusable or work in a diminished capacity.\\nIn Frax...
Consider adding a function allowing the rebalancer call `earlyBurnRedemptionTicketNft()` in `FraxEtherRedemptionQueue.sol` when there is a necessity. This will allow an immediate withdrawal for a fee of 0.5%; see function here
If the `SFrxETHAdapter` experiences a large net redemption, bringing `bufferEth` significantly below `targetBufferEth`, the rebalancer can be required to make a withdrawal request in order to replenish the buffer. However, this will be an ineffective action given the current, 15 Day waiting period. During the waiting p...
```\\n function prefundedRedeem(address recipient) external virtual returns (uint256, uint256) {\\n // SOME CODE\\n\\n // If the buffer is insufficient, shares cannot be redeemed immediately\\n // Need to wait for the withdrawal to be completed and the buffer to be refilled.\\n> if (assets >...
`AccountV1#flashActionByCreditor` can be used to drain assets from account without withdrawing
high
`AccountV1#flashActionByCreditor` is designed to allow atomic flash actions moving funds from the `owner` of the account. By making the account own itself, these arbitrary calls can be used to transfer `ERC721` assets directly out of the account. The assets being transferred from the account will still show as deposite...
The root cause of this issue is that the account can own itself. The fix is simple, make the account unable to own itself by causing transferOwnership to revert if `owner == address(this)`
Account can take out completely uncollateralized loans, causing massive losses to all lending pools.
```\\n1) Deposit ERC721\\n2) Set creditor to malicious designed creditor\\n3) Transfer the account to itself\\n4) flashActionByCreditor to transfer ERC721\\n 4a) account owns itself so _transferFromOwner allows transfers from account\\n 4b) Account is now empty but still thinks is has ERC721\\n5) Use malicious de...
Reentrancy in flashAction() allows draining liquidity pools
high
It is possible to drain a liquidity pool/creditor if the pool's asset is an ERC777 token by triggering a reentrancy flow using flash actions.\\nThe following vulnerability describes a complex flow that allows draining any liquidity pool where the underlying asset is an ERC777 token. Before diving into the vulnerability...
This attack is possible because the `getCollateralValue()` function returns a 0 collateral value due to the `minUsdValue` mentioned before not being reached after executing the bid. The Liquidator's `_settleAuction()` function then believes the collateral held in the account is 0.\\nIn order to mitigate the issue, cons...
The impact for this vulnerability is high. All funds deposited in creditors with ERC777 tokens as the underlying asset can be drained.
```\\n// Liquidator.sol\\n\\nfunction bid(address account, uint256[] memory askedAssetAmounts, bool endAuction_) external nonReentrant {\\n AuctionInformation storage auctionInformation_ = auctionInformation[account];\\n if (!auctionInformation_.inAuction) revert LiquidatorErrors.NotForSale();\\n\\n ...
Caching Uniswap position liquidity allows borrowing using undercollateralized Uni positions
high
It is possible to fake the amount of liquidity held in a Uniswap V3 position, making the protocol believe the Uniswap position has more liquidity than the actual liquidity deposited in the position. This makes it possible to borrow using undercollateralized Uniswap positions.\\nWhen depositing into an account, the `dep...
There are several ways to mitigate this issue. One possible option is to perform the transfer of assets when depositing at the same time that the asset is processed, instead of first processing the assets (and storing the Uniswap liquidity) and then transferring them. Another option is to perform a liquidity check afte...
High. The protocol will always believe that there is liquidity deposited in the Uniswap position while in reality the position is empty. This allows for undercollateralized borrows, essentially enabling the protocol to be drained if the attack is performed utilizing several uniswap positions.
```\\n// AccountV1.sol\\n\\nfunction _deposit(\\n address[] memory assetAddresses,\\n uint256[] memory assetIds,\\n uint256[] memory assetAmounts,\\n address from\\n ) internal {\\n // If no Creditor is set, batchProcessDeposit only checks if the assets can be priced.\\n // ...
Stargate `STG` rewards are accounted incorrectly by `StakedStargateAM.sol`
medium
Stargate LP_STAKING_TIME contract clears and sends rewards to the caller every time `deposit()` is called but StakedStargateAM does not take it into account.\\nWhen either mint() or increaseLiquidity() are called the `assetState[asset].lastRewardGlobal` variable is not reset to `0` even though the rewards have been tra...
Adjust the `assetState[asset].lastRewardGlobal` correctly or since every action (mint(), `burn()`, `increaseLiquidity()`, `decreaseliquidity()`, claimReward()) will have the effect of withdrawing all the current rewards it's possible to change the function _getRewardBalances() to use the amount returned by _getCurrentR...
Users will not be able to take any action on their positions until `currentRewardGlobal` is greater or equal to `assetState_.lastRewardGlobal`. After that they will be able to perform actions but their position will account for less rewards than it should because a total amount of `assetState_.lastRewardGlobal` rewards...
```\\nuint256 currentRewardGlobal = _getCurrentReward(positionState_.asset);\\nuint256 deltaReward = currentRewardGlobal - assetState_.lastRewardGlobal; ❌\\n```\\n
`CREATE2` address collision against an Account will allow complete draining of lending pools
medium
The factory function `createAccount()` creates a new account contract for the user using `CREATE2`. We show that a meet-in-the-middle attack at finding an address collision against an undeployed account is possible. Furthermore, such an attack allows draining of all funds from the lending pool.\\nThe attack consists of...
The mitigation method is to prevent controlling over the deployed account address (or at least severely limit that). Some techniques may be:\\nDo not allow a user-supplied `salt`, as well as do not use the user address as a determining factor for the `salt`.\\nUse the vanilla contract creation with `CREATE`, as opposed...
Complete draining of a lending pool if an address collision is found.\\nWith the advancement of computing hardware, the cost of an attack has been shown to be just a few million dollars, and that the current Bitcoin network hashrate allows about $2^{80}$ in about half an hour. The cost of the attack may be offsetted wi...
```\\naccount = address(\\n new Proxy{ salt: keccak256(abi.encodePacked(salt, tx.origin)) }(\\n versionInformation[accountVersion].implementation\\n )\\n);\\n```\\n
Utilisation Can Be Manipulated Far Above 100%
medium
The utilisation of the protocol can be manipulated far above 100% via token donation. It is easiest to set this up on an empty pool. This can be used to manipulate the interest to above 10000% per minute to steal from future depositors.\\nThe utilisation is basically assets_borrowed / assets_loaned. A higher utilisatio...
Add a utilisation cap of 100%. Many other lending protocols implement this mitigation.
An early depositor can steal funds from future depositors through utilisation/interest rate manipulation.
```\\nRunning 1 test for test/scenario/BorrowAndRepay.scenario.t.sol:BorrowAndRepay_Scenario_Test\\n[PASS] testScenario_Poc() (gas: 799155)\\nLogs:\\n 100 initial pool balance. This is also the amount deposited into tranche\\n warp 2 minutes into future\\n mint was used rather than deposit to ensure no rounding erro...
`LendingPool#flashAction` is broken when trying to refinance position across `LendingPools` due to improper access control
medium
When refinancing an account, `LendingPool#flashAction` is used to facilitate the transfer. However due to access restrictions on `updateActionTimestampByCreditor`, the call made from the new creditor will revert, blocking any account transfers. This completely breaks refinancing across lenders which is a core functiona...
`Account#updateActionTimestampByCreditor()` should be callable by BOTH the current and pending creditor
Refinancing is impossible
```\\nIAccount(account).updateActionTimestampByCreditor();\\n\\nasset.safeTransfer(actionTarget, amountBorrowed);\\n\\n{\\n uint256 accountVersion = IAccount(account).flashActionByCreditor(actionTarget, actionData);\\n if (!isValidVersion[accountVersion]) revert LendingPoolErrors.InvalidVersion();\\n}\\n```\\n
Malicious keepers can manipulate the price when executing an order
high
Malicious keepers can manipulate the price when executing an order by selecting a price in favor of either the LPs or long traders, leading to a loss of assets to the victim's party.\\nWhen the keeper executes an order, it was understood from the protocol team that the protocol expects that the keeper must also update ...
Ensure that the keepers must update the Pyth price when executing an order. Perform additional checks against the `priceUpdateData` submitted by the keepers to ensure that it is not empty and `priceId` within the `PriceInfo` matches the price ID of the collateral (rETH), so as to prevent malicious keeper from bypassing...
Loss of assets as shown in the scenario above.
```\\nFile: DelayedOrder.sol\\n function executeOrder(\\n address account,\\n bytes[] calldata priceUpdateData\\n )\\n external\\n payable\\n nonReentrant\\n whenNotPaused\\n updatePythPrice(vault, msg.sender, priceUpdateData)\\n orderInvariantChecks(vault)\...
Losses of some long traders can eat into the margins of others
medium
The losses of some long traders can eat into the margins of others, resulting in those affected long traders being unable to withdraw their margin and profits, leading to a loss of assets for the long traders.\\nAt $T0$, the current price of ETH is $1000 and assume the following state:\\nAlice's Long Position 1 Bob's L...
The following are the two issues identified earlier and the recommended fixes:\\nIssue 1\\nLet's review Alice's Long Position 1: Her position's settled margin is -1 ETH. When the settled margin is -ve then the LPs have to bear the cost of loss per the comment here. However, in this case, we can see that it is Bob (long...
Loss of assets for the long traders as the losses of some long traders can eat into the margins of others, resulting in those affected long traders being unable to withdraw their margin and profits.
```\\npriceShift = current price - last price\\npriceShift = $600 - $1000 = -$400\\n\\nprofitLossTotal = (globalPosition.sizeOpenedTotal * priceShift) / current price\\nprofitLossTotal = (12 ETH * -$400) / $600\\nprofitLossTotal = -8 ETH\\n```\\n
The transfer lock for leveraged position orders can be bypassed
high
The leveraged positions can be closed either through `DelayedOrder` or through the `LimitOrder`. Once the order is announced via `DelayedOrder.announceLeverageClose` or `LimitOrder.announceLimitOrder` function the LeverageModule's `lock` function is called to prevent given token to be transferred. This mechanism can be...
It is recommended to prevent announcing order either through `DelayedOrder.announceLeverageClose` or `LimitOrder.announceLimitOrder` if the leveraged position is already locked.
The attacker can sell the leveraged position with a close order opened, execute the order afterward, and steal the underlying collateral.
```\\nfunction testExploitTransferOut() public {\\n uint256 collateralPrice = 1000e8;\\n\\n vm.startPrank(alice);\\n\\n uint256 balance = WETH.balanceOf(alice);\\n console2.log("alice balance", balance);\\n \\n (uint256 minFillPrice, ) = oracleModProxy.getPrice();\\n\\n // Announce order through de...
A malicious user can bypass limit order trading fees via cross-function re-entrancy
high
A malicious user can bypass limit order trading fees via cross-function re-entrancy, since `_safeMint` makes an external call to the user before updating state.\\nIn the `LeverageModule` contract, the `_mint` function calls `_safeMint`, which makes an external call `to` the receiver of the NFT (the `to` address).\\n\\n...
To fix this specific issue, the following change is sufficient:\\n```\\n// Remove the line below\\n_newTokenId = _mint(_account); \\n\\nvault.setPosition( \\n FlatcoinStructs.Position({\\n lastPrice: entryPrice,\\n marginDeposited: announcedOpen.margin,\\n additionalSize: announcedOpen.additiona...
A malicious user can bypass the trading fees for a limit order, via cross-function re-entrancy. These trading fees were supposed to be paid to the LPs by increasing `stableCollateralTotal`, but due to limit orders being able to bypass trading fees (albeit during the same transaction as opening the position), LPs are no...
```\\nuint256 tradeFee = ILeverageModule(vault.moduleAddress(FlatcoinModuleKeys._LEVERAGE_MODULE_KEY)).getTradeFee(\\n vault.getPosition(tokenId).additionalSize\\n);\\n```\\n
Incorrect handling of PnL during liquidation
high
The incorrect handling of PnL during liquidation led to an error in the protocol's accounting mechanism, which might result in various issues, such as the loss of assets and the stable collateral total being inflated.\\nFirst Example\\nAssume a long position with the following state:\\nMargin Deposited = +20\\nAccrued ...
To remediate the issue, the `profitLossTotal` should be excluded within the `updateGlobalPositionData` function during liquidation.\\n```\\n// Remove the line below\\n profitLossTotal = PerpMath._profitLossTotal(// rest of code)\\n\\n// Remove the line below\\n newMarginDepositedTotal = globalPositions.marginDepositedT...
The following is a list of potential impacts of this issue:\\nFirst Example: LPs incur unnecessary losses during liquidation, which would be avoidable if the calculations were correctly implemented from the start.\\nSecond Example: An error in the protocol's accounting mechanism led to an inflated increase in the LPs' ...
```\\nsettleFundingFees() = Short/LP need to pay Long 100\\n\\nmarginDepositedTotal = marginDepositedTotal + funding fee\\nmarginDepositedTotal = y + (-100) = (y - 100)\\n\\nstableCollateralTotal = x + (-(-100)) = (x + 100)\\n```\\n
Asymmetry in profit and loss (PnL) calculations
high
An asymmetry arises in profit and loss (PnL) calculations due to relative price changes. This discrepancy emerges when adjustments to a position lead to differing PnL outcomes despite equivalent absolute price shifts in rETH, leading to loss of assets.\\nScenario 1\\nAssume at $T0$, the price of rETH is $1000. Bob open...
Consider tracking the PnL in dollar value/term to ensure consistency between the rETH and dollar representations of gains and losses.\\nAppendix\\nCompared to SNX V2, it is not vulnerable to this issue. The reason is that in SNX V2 when it computes the PnL, it does not "scale" down the result by the price. The PnL in S...
Loss of assets, as demonstrated in the second scenario in the first example above. The tracking of profit and loss, which is the key component within the protocol, both on the position level and global level, is broken.
```\\nPnL = Position Size * Price Shift / Current Price\\nPnL = Position Size * (Current Price - Last Price) / Current Price\\nPnL = 40 rETH * ($2000 - $1000) / $2000\\nPnL = $40000 / $2000 = 20 rETH\\n```\\n
Incorrect price used when updating the global position data
high
Incorrect price used when updating the global position data leading to a loss of assets for LPs.\\nNear the end of the liquidation process, the `updateGlobalPositionData` function at Line 159 will be executed to update the global position data. However, when executing the `updateGlobalPositionData` function, the code s...
Use the current price instead of liquidated position's last price when update the global position data\\n```\\n(uint256 currentPrice, ) = IOracleModule(vault.moduleAddress(FlatcoinModuleKeys._ORACLE_MODULE_KEY)).getPrice();\\n..SNIP..\\nvault.updateGlobalPositionData({\\n// Remove the line below\\n price: position.l...
Loss of assets for the LP as mentioned in the above section.
```\\nFile: LiquidationModule.sol\\n /// @notice Function to liquidate a position.\\n /// @dev One could directly call this method instead of `liquidate(uint256, bytes[])` if they don't want to update the Pyth price.\\n /// @param tokenId The token ID of the leverage position.\\n function liquidate(uint256 ...
Long trader's deposited margin can be wiped out
high
Long Trader's deposited margin can be wiped out due to a logic error, leading to a loss of assets.\\n```\\nFile: FlatcoinVault.sol\\n function settleFundingFees() public returns (int256 _fundingFees) {\\n..SNIP..\\n // Calculate the funding fees accrued to the longs.\\n // This will be used to adjust t...
If the intention is to ensure that `_globalPositions.marginDepositedTotal` will never become negative, consider summing up $(X + Y)$ first and determine if the result is less than zero. If yes, set the `_globalPositions.marginDepositedTotal` to zero.\\nThe following is the pseudocode:\\n```\\nnewMarginTotal = globalPos...
Loss of assets for the long traders as mentioned above.
```\\nFile: FlatcoinVault.sol\\n function settleFundingFees() public returns (int256 _fundingFees) {\\n..SNIP..\\n // Calculate the funding fees accrued to the longs.\\n // This will be used to adjust the global margin and collateral amounts.\\n _fundingFees = PerpMath._accruedFundingTotalByLong...
Fees are ignored when checks skew max in Stable Withdrawal / Leverage Open / Leverage Adjust
medium
Fees are ignored when checks skew max in Stable Withdrawal / Leverage Open / Leverage Adjust.\\nWhen user withdrawal from the stable LP, vault total stable collateral is updated:\\n```\\n vault.updateStableCollateralTotal(-int256(_amountOut));\\n```\\n\\nThen _withdrawFee is calculated and checkSkewMax(...) func...
Include withdrawal fee / trade fee when check skew max.
Protocol may wrongly prevent a Stable Withdrawal / Leverage Open / Leverage Adjust even if the execution is essentially safe.
```\\n vault.updateStableCollateralTotal(-int256(_amountOut));\\n```\\n
In LeverageModule.executeOpen/executeAdjust, vault.checkSkewMax should be called after updating the global position data
medium
```\\nFile: flatcoin-v1\\src\\LeverageModule.sol\\n function executeOpen(\\n address _account,\\n address _keeper,\\n FlatcoinStructs.Order calldata _order\\n ) external whenNotPaused onlyAuthorizedModule returns (uint256 _newTokenId) {\\n// rest of code// rest of code\\n101:-> vault.ch...
```\\nFile: flatcoin-v1\\src\\LeverageModule.sol\\n function executeOpen(\\n address _account,\\n address _keeper,\\n FlatcoinStructs.Order calldata _order\\n ) external whenNotPaused onlyAuthorizedModule returns (uint256 _newTokenId) {\\n// rest of code// rest of code\\n101:--- vault.ch...
The `stableCollateralTotal` used by `checkSkewMax` is the value of the total profit that has not yet been settled, which is old value. In this way, when the price of collateral rises, it will cause the system to be more skewed towards the long side.
```\\nFile: flatcoin-v1\\src\\LeverageModule.sol\\n function executeOpen(\\n address _account,\\n address _keeper,\\n FlatcoinStructs.Order calldata _order\\n ) external whenNotPaused onlyAuthorizedModule returns (uint256 _newTokenId) {\\n// rest of code// rest of code\\n101:-> vault.ch...
Oracle will not failover as expected during liquidation
medium
Oracle will not failover as expected during liquidation. If the liquidation cannot be executed due to the revert described in the following scenario, underwater positions and bad debt accumulate in the protocol, threatening the solvency of the protocol.\\nThe liquidators have the option to update the Pyth price during ...
Consider implementing a feature to allow the protocol team to disable the price deviation check so that the protocol team can disable it in the event that Pyth network is down for an extended period of time.
The liquidation mechanism is the core component of the protocol and is important to the solvency of the protocol. If the liquidation cannot be executed due to the revert described in the above scenario, underwater positions and bad debt accumulate in the protocol threaten the solvency of the protocol.
```\\nFile: LiquidationModule.sol\\n function liquidate(\\n uint256 tokenID,\\n bytes[] calldata priceUpdateData\\n ) external payable whenNotPaused updatePythPrice(vault, msg.sender, priceUpdateData) {\\n liquidate(tokenID);\\n }\\n\\n /// @notice Function to liquidate a position.\\n ...
Large amounts of points can be minted virtually without any cost
medium
Large amounts of points can be minted virtually without any cost. The points are intended to be used to exchange something of value. A malicious user could abuse this to obtain a large number of points, which could obtain excessive value and create unfairness among other protocol users.\\nWhen depositing stable collate...
One approach that could mitigate this risk is also to impose withdraw fee for the final/last withdrawal so that no one could abuse this exception to perform any attack that was once not profitable due to the need to pay withdraw fee.\\nIn addition, consider deducting the points once a position is closed or reduced in s...
Large amounts of points can be minted virtually without any cost. The points are intended to be used to exchange something of value. A malicious user could abuse this to obtain a large number of points, which could obtain excessive value from the protocol and create unfairness among other protocol users.
```\\nFile: StableModule.sol\\n function executeWithdraw(\\n address _account,\\n uint64 _executableAtTime,\\n FlatcoinStructs.AnnouncedStableWithdraw calldata _announcedWithdraw\\n ) external whenNotPaused onlyAuthorizedModule returns (uint256 _amountOut, uint256 _withdrawFee) {\\n ui...
Vault Inflation Attack
medium
Malicious users can perform an inflation attack against the vault to steal the assets of the victim.\\nA malicious user can perform a donation to execute a classic first depositor/ERC4626 inflation Attack against the FlatCoin vault. The general process of this attack is well-known, and a detailed explanation of this at...
A `MIN_LIQUIDITY` amount of shares needs to exist within the vault to guard against a common inflation attack.\\nHowever, the current approach of only checking if the `totalSupply() < MIN_LIQUIDITY` is not sufficient, and could be bypassed by making use of the withdraw function.\\nA more robust approach to ensuring tha...
Malicous users could steal the assets of the victim.
```\\nFile: StableModule.sol\\n function executeDeposit(\\n address _account,\\n uint64 _executableAtTime,\\n FlatcoinStructs.AnnouncedStableDeposit calldata _announcedDeposit\\n ) external whenNotPaused onlyAuthorizedModule returns (uint256 _liquidityMinted) {\\n uint256 depositAmount...
Long traders unable to withdraw their assets
medium
Whenever the protocol reaches a state where the long trader's profit is larger than LP's stable collateral total, the protocol will be bricked. As a result, the margin deposited and gain of the long traders can no longer be withdrawn and the LPs cannot withdraw their collateral, leading to a loss of assets for the user...
Currently, when the loss of the LP is more than the existing `stableCollateralTotal`, the loss will be capped at zero, and it will not go negative. In the above example, the `stableCollateralTotal` is 50, and the loss is 51. Thus, the `stableCollateralTotal` is set to zero instead of -1.\\nThe loss of LP and the gain o...
Loss of assets for the users. Since the protocol is bricked due to revert, the long traders are unable to withdraw their deposited margin and gain and the LPs cannot withdraw their collateral.
```\\nFile: InvariantChecks.sol\\n /// @dev Returns the difference between actual total collateral balance in the vault vs tracked collateral\\n /// Tracked collateral should be updated when depositing to stable LP (stableCollateralTotal) or\\n /// opening leveraged positions (marginDepositedTotal).\...
Oracle can return different prices in same transaction
medium
The Pyth network oracle contract allows to submit and read two different prices in the same transaction. This can be used to create arbitrage opportunities that can make a profit with no risk at the expense of users on the other side of the trade.\\n`OracleModule.sol` uses Pyth network as the primary source of price fe...
```\\nFile: OracleModule.sol\\n FlatcoinStructs.OffchainOracle public offchainOracle; // Offchain Pyth network oracle\\n\\n// Add the line below\\n uint256 public lastOffchainUpdate;\\n\\n (// rest of code)\\n\\n function updatePythPrice(address sender, bytes[] calldata priceUpdateData) external payable nonR...
Different oracle prices can be fetched in the same transaction, which can be used to create arbitrage opportunities that can make a profit with no risk at the expense of users on the other side of the trade.
```\\nadjustmentSize * (secondPrice - firstPrice) - (adjustmentSize * tradeFees * 2)\\n```\\n
OperationalStaking may not possess enough CQT for the last withdrawal
medium
Both `_sharesToTokens` and `_tokensToShares` round down instead of rounding off against the user. This can result in users withdrawing few weis more than they should, which in turn would make the last CQT transfer from the contract revert due to insufficient balance.\\nWhen users `stake`, the shares they will receive i...
`_sharesToTokens` and `_tokensToShares`, instead of rounding down, should always round off against the user.
Victim's transactions will keep reverting unless they figure out that they need to decrease their withdrawal amount.
```\\n function _tokensToShares(\\n uint128 amount,\\n uint128 rate\\n ) internal view returns (uint128) {\\n return uint128((uint256(amount) * DIVIDER) / uint256(rate));\\n }\\n```\\n
Frontrunning validator freeze to withdraw tokens
medium
Covalent implements a freeze mechanism to disable malicious Validators, this allows the protocol to block all interactions with a validator when he behaves maliciously. Covalent also implements a timelock to ensure tokens are only withdraw after a certain amount of time. After the cooldown ends, tokens can always be wi...
Implement a check if validator is frozen on `transferUnstakedOut()` and `recoverUnstaking()`, and revert transaction if true.\\nIf freezing all unstakings is undesirable (e.g. not freezing honest unstakes), the sponsor may consider storing the unstake timestamp as well:\\nStore the unstaking block number for each unsta...
Malicious validators can front run freeze to withdraw tokens.
```\\n require(!v.frozen, "Validator is frozen");\\n```\\n
`validatorMaxStake` can be bypassed by using `setValidatorAddress()`
medium
`setValidatorAddress()` allows a validator to migrate to a new address of their choice. However, the current logic only stacks up the old address' stake to the new one, never checking `validatorMaxStake`.\\nThe current logic for `setValidatorAddress()` is as follow:\\n```\\nfunction setValidatorAddress(uint128 validato...
Check that the new address's total stake does not exceed `validatorMaxStake` before proceeding with the migration.
Breaking an important invariant of the protocol.\\nAllowing any validator to bypass the max stake amount. In turn allows them to earn an unfair amount of validator rewards in the process.\\nAllows a validator to unfairly increase their max delegator amount, as an effect of increasing `(validator stake) * maxCapMultipli...
```\\nfunction setValidatorAddress(uint128 validatorId, address newAddress) external whenNotPaused {\\n // // rest of code\\n v.stakings[newAddress].shares += v.stakings[msg.sender].shares;\\n v.stakings[newAddress].staked += v.stakings[msg.sender].staked;\\n delete v.stakings[msg.sender];\\n // // rest ...
Nobody can cast for any proposal
medium
```\\nFile: bophades\\src\\external\\governance\\GovernorBravoDelegate.sol\\n function castVoteInternal(\\n address voter,\\n uint256 proposalId,\\n uint8 support\\n ) internal returns (uint256) {\\n// rest of code// rest of code\\n // Get the user's votes at the start of the proposal ...
```\\nFile: bophades\\src\\external\\governance\\GovernorBravoDelegate.sol\\n uint256 originalVotes = gohm.getPriorVotes(voter, proposal.startBlock);\\n446:- uint256 currentVotes = gohm.getPriorVotes(voter, block.number);\\n446:+ uint256 currentVotes = gohm.getPriorVotes(voter, block.number - 1);\\...
Nobody can cast for any proposal. Not being able to vote means the entire governance contract will be useless. Core functionality is broken.
```\\nFile: bophades\\src\\external\\governance\\GovernorBravoDelegate.sol\\n function castVoteInternal(\\n address voter,\\n uint256 proposalId,\\n uint8 support\\n ) internal returns (uint256) {\\n// rest of code// rest of code\\n // Get the user's votes at the start of the proposal ...
User can get free entries if the price of any whitelisted ERC20 token is greater than the round's `valuePerEntry`
high
Lack of explicit separation between ERC20 and ERC721 deposits allows users to gain free entries for any round given there exists a whitelisted ERC20 token with price greater than the round's `valuePerEntry`.\\n```\\n if (isCurrencyAllowed[tokenAddress] != 1) {\\n revert InvalidCollecti...
Whitelist tokens using both the token address and the token type (ERC20/ERC721).
Users can get an arbitrary number of entries into rounds for free (which should generally allow them to significantly increase their chances of winning). In the case the winner is a free depositor, they will end up with the same profit as if they participated normally since they have to pay the fee over the total value...
```\\n if (isCurrencyAllowed[tokenAddress] != 1) {\\n revert InvalidCollection();\\n }\\n```\\n
Users can deposit "0" ether to any round
high
The main invariant to determine the winner is that the indexes must be in ascending order with no repetitions. Therefore, depositing "0" is strictly prohibited as it does not increase the index. However, there is a method by which a user can easily deposit "0" ether to any round without any extra costs than gas.\\nAs s...
Add the following check inside the depositETHIntoMultipleRounds function\\n```\\nif (depositAmount == 0) {\\n revert InvalidValue();\\n }\\n```\\n
High, since it will alter the games winner selection and it is very cheap to perform the attack.
```\\nfor (uint256 i; i < numberOfRounds; ++i) {\\n uint256 roundId = _unsafeAdd(startingRoundId, i);\\n Round storage round = rounds[roundId];\\n uint256 roundValuePerEntry = round.valuePerEntry;\\n if (roundValuePerEntry == 0) {\\n (, , roundValuePerEntry) = ...
The number of deposits in a round can be larger than MAXIMUM_NUMBER_OF_DEPOSITS_PER_ROUND
medium
The number of deposits in a round can be larger than MAXIMUM_NUMBER_OF_DEPOSITS_PER_ROUND, because there is no such check in depositETHIntoMultipleRounds() function or rolloverETH() function.\\ndepositETHIntoMultipleRounds() function is called to deposit ETH into multiple rounds, so it's possible that the number of dep...
Add check in _depositETH() function which is called by both depositETHIntoMultipleRounds() function and rolloverETH() function to ensure the deposit number cannot be larger than MAXIMUM_NUMBER_OF_DEPOSITS_PER_ROUND:\\n```\\n uint256 roundDepositCount = round.deposits.length;\\n\\n// Add the line below\\n i...
This issue break the invariant that the number of deposits in a round can be larger than MAXIMUM_NUMBER_OF_DEPOSITS_PER_ROUND.
```\\n if (\\n _shouldDrawWinner(\\n startingRound.numberOfParticipants,\\n startingRound.maximumNumberOfParticipants,\\n startingRound.deposits.length\\n )\\n ) {\\n _drawWinner(startingRound, startingRoundId);\\n }\\n``...
Low precision is used when checking spot price deviation
medium
Low precision is used when checking spot price deviation, which might lead to potential manipulation or create the potential for an MEV opportunity due to valuation discrepancy.\\nAssume the following:\\nThe max deviation is set to 1%\\n`nTokenOracleValue` is 1,000,000,000\\n`nTokenSpotValue` is 980,000,001\\n```\\nFil...
Consider increasing the precision.\\nFor instance, increasing the precision from `Constants.PERCENTAGE_DECIMALS` (100) to 1e8 would have caught the issue mentioned earlier in the report even after the rounding down.\\n```\\nnTokenOracleValue.sub(nTokenSpotValue).abs().mul(1e8).div(nTokenOracleValue);\\n((nTokenOracleVa...
The purpose of the deviation check is to ensure that the spot market value is not manipulated. If the deviation check is not accurate, it might lead to potential manipulation or create the potential for an MEV opportunity due to valuation discrepancy.
```\\nFile: Constants.sol\\n // Basis for percentages\\n int256 internal constant PERCENTAGE_DECIMALS = 100;\\n```\\n
The use of spot data when discounting is subjected to manipulation
medium
The use of spot data when discounting is subjected to manipulation. As a result, malicious users could receive more cash than expected during redemption by performing manipulation. Since this is a zero-sum, the attacker's gain is the protocol loss.\\nWhen redeeming wfCash before maturity, the `_sellfCash` function will...
Avoid using spot data when computing the amount of assets that the user is entitled to during redemption. Consider using a TWAP/Time-lagged oracle to guard against potential manipulation.
Malicious users could receive more cash than expected during redemption by performing manipulation. Since this is a zero-sum, the attacker's gain is the protocol loss.
```\\nFile: wfCashLogic.sol\\n /// @dev Sells an fCash share back on the Notional AMM\\n function _sellfCash(\\n address receiver,\\n uint256 fCashToSell,\\n uint32 maxImpliedRate\\n ) private returns (uint256 tokensTransferred) {\\n (IERC20 token, bool isETH) = getToken(true); \\n ...
External lending can exceed the threshold
medium
Due to an incorrect calculation of the max lending amount, external lending can exceed the external withdrawal threshold. If this restriction/threshold is not adhered to, users or various core functionalities within the protocol will have issues redeeming or withdrawing their prime cash.\\nThe following is the extract ...
To ensure that a deposit does not exceed the threshold, the following formula should be used to determine the maximum deposit amount:\\nLet's denote:\\n$T$ as the externalWithdrawThreshold $L$ as the currentExternalUnderlyingLend $W$ as the externalUnderlyingAvailableForWithdraw $D$ as the Deposit (the variable we want...
To ensure the redeemability of Notional's funds on external lending markets, Notional requires there to be redeemable funds on the external lending market that are a multiple of the funds that Notional has lent on that market itself.\\nIf this restriction is not adhered to, users or various core functionalities within ...
```\\n700/1300 = 0.5384615385 (53%).\\n```\\n
Rebalance will be delayed due to revert
medium
The rebalancing of unhealthy currencies will be delayed due to a revert, resulting in an excess of liquidity being lent out in the external market. This might affect the liquidity of the protocol, potentially resulting in withdrawal or liquidation having issues executed due to insufficient liquidity.\\nAssume that Noti...
If one of the currencies becomes healthy when the rebalance TX is executed, consider skipping this currency and move on to execute the rebalance on the rest of the currencies that are still unhealthy.\\n```\\nfunction _rebalanceCurrency(uint16 currencyId, bool useCooldownCheck) private { \\n RebalancingContextStorage m...
The rebalancing of unhealthy currencies will be delayed, resulting in an excess of liquidity being lent out to the external market. This might affect the liquidity of the protocol, potentially resulting in withdrawal or liquidation having issues executed due to insufficient liquidity.
```\\nFile: TreasuryAction.sol\\n function _rebalanceCurrency(uint16 currencyId, bool useCooldownCheck) private { \\n RebalancingContextStorage memory context = LibStorage.getRebalancingContext()[currencyId]; \\n // Accrues interest up to the current block before any rebalancing is executed\\n I...
Rebalance might be skipped even if the external lending is unhealthy
medium
The deviation between the target and current lending amount (offTargetPercentage) will be underestimated due to incorrect calculation. As a result, a rebalancing might be skipped even if the existing external lending is unhealthy.\\nThe formula used within the `_isExternalLendingUnhealthy` function below calculating th...
Consider calculating the off-target percentages as a ratio of the difference to the target:\\n$$ offTargetPercentage = \\frac{\\mid currentExternalUnderlyingLend - targetAmount \\mid}{targetAmount} \\times 100% $$
The deviation between the target and current lending amount (offTargetPercentage) will be underestimated by approximately half the majority of the time. As a result, a rebalance intended to remediate the unhealthy external lending might be skipped since the code incorrectly assumes that it has not hit the off-target pe...
```\\noffTargetPercentage = abs(90 - 100) / (100 + 90) = 10 / 190 = 0.0526 = 5.26%\\n```\\n
All funds can be stolen from JOJODealer
high
`Funding._withdraw()` makes arbitrary call with user specified params. User can for example make ERC20 to himself and steal funds.\\nUser can specify parameters `param` and `to` when withdraws:\\n```\\n function executeWithdraw(address from, address to, bool isInternal, bytes memory param) external nonReentrant {\\n...
Don't make arbitrary call with user specified params
All funds can be stolen from JOJODealer
```\\n function executeWithdraw(address from, address to, bool isInternal, bytes memory param) external nonReentrant {\\n Funding.executeWithdraw(state, from, to, isInternal, param);\\n }\\n```\\n
FundingRateArbitrage contract can be drained due to rounding error
high
In the `requestWithdraw`, rounding in the wrong direction is done which can lead to contract being drained.\\nIn the `requestWithdraw` function in `FundingRateArbitrage`, we find the following lines of code:\\n```\\njusdOutside[msg.sender] -= repayJUSDAmount;\\nuint256 index = getIndex();\\nuint256 lockedEarnUSDCAmount...
Round up instead of down
All JUSD in the contract can be drained
```\\njusdOutside[msg.sender] -= repayJUSDAmount;\\nuint256 index = getIndex();\\nuint256 lockedEarnUSDCAmount = jusdOutside[msg.sender].decimalDiv(index);\\nrequire(\\n earnUSDCBalance[msg.sender] >= lockedEarnUSDCAmount, "lockedEarnUSDCAmount is bigger than earnUSDCBalance"\\n);\\nwithdrawEarnUSDCAmount = earnUSD...
`JUSDBankStorage::getTRate()`,`JUSDBankStorage::accrueRate()` are calculated differently, and the data calculation is biased, Causes the `JUSDBank` contract funciton result to be incorrect
medium
```\\n function accrueRate() public {\\n uint256 currentTimestamp = block.timestamp;\\n if (currentTimestamp == lastUpdateTimestamp) {\\n return;\\n }\\n uint256 timeDifference = block.timestamp - uint256(lastUpdateTimestamp);\\n tRate = tRate.decimalMul((timeDifference...
Use the same calculation formula:\\n```\\n function accrueRate() public {\\n uint256 currentTimestamp = block.timestamp;\\n if (currentTimestamp == lastUpdateTimestamp) {\\n return;\\n }\\n uint256 timeDifference = block.timestamp // Remove the line below\\n uint256(lastUpdateT...
Causes the `JUSDBank` contract funciton result to be incorrect
```\\n function accrueRate() public {\\n uint256 currentTimestamp = block.timestamp;\\n if (currentTimestamp == lastUpdateTimestamp) {\\n return;\\n }\\n uint256 timeDifference = block.timestamp - uint256(lastUpdateTimestamp);\\n tRate = tRate.decimalMul((timeDifference...
Funding#requestWithdraw uses incorrect withdraw address
medium
When requesting a withdraw, `msg.sender` is used in place of the `from` address. This means that withdraws cannot be initiated on behalf of other users. This will break integrations that depend on this functionality leading to irretrievable funds.\\nFunding.sol#L69-L82\\n```\\nfunction requestWithdraw(\\n Types.Stat...
Change all occurrences of `msg.sender` in stage changes to `from` instead.
Requesting withdraws for other users is broken and strands funds
```\\nfunction requestWithdraw(\\n Types.State storage state,\\n address from,\\n uint256 primaryAmount,\\n uint256 secondaryAmount\\n)\\n external\\n{\\n require(isWithdrawValid(state, msg.sender, from, primaryAmount, secondaryAmount), Errors.WITHDRAW_INVALID);\\n state.pendingPrimaryWithdraw[msg....
FundRateArbitrage is vulnerable to inflation attacks
medium
When index is calculated, it is figured by dividing the net value of the contract (including USDC held) by the current supply of earnUSDC. Through deposit and donation this ratio can be inflated. Then when others deposit, their deposit can be taken almost completely via rounding.\\nFundingRateArbitrage.sol#L98-L104\\n`...
Use a virtual offset as suggested by OZ for their ERC4626 contracts
Subsequent user deposits can be stolen
```\\nfunction getIndex() public view returns (uint256) {\\n if (totalEarnUSDCBalance == 0) {\\n return 1e18;\\n } else {\\n return SignedDecimalMath.decimalDiv(getNetValue(), totalEarnUSDCBalance);\\n }\\n}\\n```\\n
Lender transactions can be front-run, leading to lost funds
high
Users can mint wfCash tokens via `mintViaUnderlying` by passing a variable `minImpliedRate` to guard against trade slippage. If the market interest is lower than expected by the user, the transaction will revert due to slippage protection. However, if the user mints a share larger than maxFCash, the `minImpliedRate` ch...
add a check inside `_mintInternal`\\n```\\n if (maxFCash < fCashAmount) {\\n// Add the line below\\n require(minImpliedRate ==0,"Trade failed, slippage"); \\n // NOTE: lending at zero\\n uint256 fCashAmountExternal = fCashAmount * precision / uint256(Constants.INTERNAL_T...
lender lost of funds
```\\n function mintViaUnderlying(\\n uint256 depositAmountExternal,\\n uint88 fCashAmount,\\n address receiver,\\n uint32 minImpliedRate//@audit when lendAmount bigger than maxFCash lack of minRate protect.\\n ) external override {\\n (/* */, uint256 maxFCash) = getTotalFCashAv...
Residual ETH will not be sent back to users during the minting of wfCash
high
Residual ETH will not be sent back to users, resulting in a loss of assets.\\nAt Line 67, residual ETH within the `depositUnderlyingToken` function will be sent as Native ETH back to the `msg.sender`, which is this wfCash Wrapper contract.\\n```\\nFile: wfCashLogic.sol\\n function _mintInternal(\\n..SNIP..\\n ...
If the underlying is ETH, measure the Native ETH balance before and after the `depositUnderlyingToken` is executed. Forward any residual Native ETH to the users, if any.
Loss of assets as the residual ETH is not sent to the users.
```\\nFile: wfCashLogic.sol\\n function _mintInternal(\\n..SNIP..\\n if (maxFCash < fCashAmount) {\\n // NOTE: lending at zero\\n uint256 fCashAmountExternal = fCashAmount * precision / uint256(Constants.INTERNAL_TOKEN_PRECISION); \\n require(fCashAmountExternal <= depositAmou...
Residual ETH not sent back when `batchBalanceAndTradeAction` executed
high
Residual ETH was not sent back when `batchBalanceAndTradeAction` function was executed, resulting in a loss of assets.\\nPer the comment at Line 122 below, when there is residual ETH, native ETH will be sent from Notional V3 to the wrapper contract. In addition, per the comment at Line 109, it is often the case to have...
If the underlying is ETH, measure the Native ETH balance before and after the `batchBalanceAndTradeAction` is executed. Forward any residual Native ETH to the users, if any.
Loss of assets as the residual ETH is not sent to the users.
```\\nFile: wfCashLogic.sol\\n function _lendLegacy(\\nFile: wfCashLogic.sol\\n // If deposit amount external is in excess of the cost to purchase fCash amount (often the case),\\n // then we need to return the difference between postTradeCash - preTradeCash. This is done because\\n // the encod...
_isExternalLendingUnhealthy() using stale factors
medium
In `checkRebalance()` -> _isExternalLendingUnhealthy() -> getTargetExternalLendingAmount(factors) using stale `factors` will lead to inaccurate `targetAmount`, which in turn will cause `checkRebalance()` that should have been rebalance to not execute.\\nrebalancingBot uses `checkRebalance()` to return the `currencyIds ...
```\\n function _isExternalLendingUnhealthy(\\n uint16 currencyId,\\n IPrimeCashHoldingsOracle oracle,\\n PrimeRate memory pr\\n ) internal view returns (bool isExternalLendingUnhealthy, OracleData memory oracleData, uint256 targetAmount) {\\n// rest of code\\n\\n// Remove the line below\\n ...
Due to the incorrect `targetAmount`, it may cause the `currencyId` that should have been re-executed `Rebalance` to not execute `rebalance`, increasing the risk of the protocol.
```\\n function _isExternalLendingUnhealthy(\\n uint16 currencyId,\\n IPrimeCashHoldingsOracle oracle,\\n PrimeRate memory pr\\n ) internal view returns (bool isExternalLendingUnhealthy, OracleData memory oracleData, uint256 targetAmount) {\\n// rest of code\\n\\n PrimeCashFactors memory...
recover() using the standard transfer may not be able to retrieve some tokens
medium
in `SecondaryRewarder.recover()` Using the standard `IERC20.transfer()` If `REWARD_TOKEN` is like `USDT`, it will not be able to transfer out, because this kind of `token` does not return `bool` This will cause it to always `revert`\\n`SecondaryRewarder.recover()` use for\\nAllows the Notional owner to recover any toke...
```\\n function recover(address token, uint256 amount) external onlyOwner {\\n if (Constants.ETH_ADDRESS == token) {\\n (bool status,) = msg.sender.call{value: amount}("");\\n require(status);\\n } else {\\n// Remove the line below\\n IERC20(token).transfer(msg.sender, am...
If `REWARD_TOKEN` is like `USDT`, it will not be able to transfer out.
```\\n function recover(address token, uint256 amount) external onlyOwner {\\n if (Constants.ETH_ADDRESS == token) {\\n (bool status,) = msg.sender.call{value: amount}("");\\n require(status);\\n } else {\\n IERC20(token).transfer(msg.sender, amount);\\n }\\n }\...
Malicious users could block liquidation or perform DOS
medium
The current implementation uses a "push" approach where reward tokens are sent to the recipient during every update, which introduces additional attack surfaces that the attackers can exploit. An attacker could intentionally affect the outcome of the transfer to gain a certain advantage or carry out certain attack.\\nT...
The current implementation uses a "push" approach where reward tokens are sent to the recipient during every update, which introduces additional attack surfaces that the attackers can exploit.\\nConsider adopting a pull method for users to claim their rewards instead so that the transfer of reward tokens is disconnecte...
Many of the core functionalities of the protocol will be affected by the revert. Specifically, the `BalancerHandler._finalize` has the most impact as this function is called by almost every critical functionality of the protocol, including deposit, withdrawal, and liquidation.\\nThe worst-case scenario is that maliciou...
```\\nFile: SecondaryRewarder.sol\\n function _claimRewards(address account, uint256 nTokenBalanceBefore, uint256 nTokenBalanceAfter) private { \\n uint256 rewardToClaim = _calculateRewardToClaim(account, nTokenBalanceBefore, accumulatedRewardPerNToken); \\n\\n // Precision here is:\\n // nToke...
Unexpected behavior when calling certain ERC4626 functions
medium
Unexpected behavior could occur when certain ERC4626 functions are called during the time windows when the fCash has matured but is not yet settled.\\nWhen the fCash has matured, the global settlement does not automatically get executed. The global settlement will only be executed when the first account attempts to set...
Document the unexpected behavior of the affected functions that could occur during the time windows when the fCash has matured but is not yet settled so that anyone who calls these functions is aware of them.
The `totalAssets()` function is utilized by key ERC4626 functions within the wrapper, such as the following functions. The side effects of this issue are documented below:\\n`convertToAssets` (Impact = returned value is always zero assets regardless of the inputs)\\n`convertToAssets` > `previewRedeem` (Impact = returne...
```\\nFile: wfCashBase.sol\\n function _getMaturedCashValue(uint256 fCashAmount) internal view returns (uint256) { \\n if (!hasMatured()) return 0; \\n // If the fCash has matured we use the cash balance instead.\\n (uint16 currencyId, uint40 maturity) = getDecodedID(); \\n PrimeRate memo...
getOracleData() maxExternalDeposit not accurate
medium
in `getOracleData()` The calculation of `maxExternalDeposit` lacks consideration for `reserve.accruedToTreasury`. This leads to `maxExternalDeposit` being too large, causing `Treasury.rebalance()` to fail.\\nin `getOracleData()`\\n```\\n function getOracleData() external view override returns (OracleData memory orac...
subtract `uint256(reserve.accruedToTreasury)).rayMul(reserveCache.nextLiquidityIndex)`
An overly large `maxExternalDeposit` may cause `rebalance()` to be unable to execute.
```\\n function getOracleData() external view override returns (OracleData memory oracleData) {\\n// rest of code\\n (/* */, uint256 supplyCap) = IPoolDataProvider(POOL_DATA_PROVIDER).getReserveCaps(underlying);\\n // Supply caps are returned as whole token values\\n supplyCap = supplyCap * UNDE...
getTargetExternalLendingAmount() when targetUtilization == 0 no check whether enough externalUnderlyingAvailableForWithdraw
medium
in `getTargetExternalLendingAmount()` When `targetUtilization == 0`, it directly returns `targetAmount=0`. It lacks the judgment of whether there is enough `externalUnderlyingAvailableForWithdraw`. This may cause `_rebalanceCurrency()` to `revert` due to insufficient balance for `withdraw`.\\nwhen `setRebalancingTarget...
Remove `targetUtilization == 0` directly returning 0.\\nThe subsequent logic of the method can handle `targetUtilization == 0` normally and will not cause an error.\\n```\\n function getTargetExternalLendingAmount(\\n Token memory underlyingToken,\\n PrimeCashFactors memory factors,\\n Rebalanci...
A too small `targetAmount` may cause AAVE withdraw to fail, thereby causing the inability to `setRebalancingTargets()` to fail.
```\\n function getTargetExternalLendingAmount(\\n Token memory underlyingToken,\\n PrimeCashFactors memory factors,\\n RebalancingTargetData memory rebalancingTargetData,\\n OracleData memory oracleData,\\n PrimeRate memory pr\\n ) internal pure returns (uint256 targetAmount) {...
getTargetExternalLendingAmount() targetAmount may far less than the correct value
medium
When calculating `ExternalLending.getTargetExternalLendingAmount()`, it restricts `targetAmount` greater than `oracleData.maxExternalDeposit`. However, it does not take into account that `oracleData.maxExternalDeposit` includes the protocol deposit `currentExternalUnderlyingLend` This may result in the returned quantit...
Only when `targetAmount > currentExternalUnderlyingLend` is a deposit needed, it should be considered that it cannot exceed `oracleData.maxExternalDeposit`\\n```\\n function getTargetExternalLendingAmount(\\n Token memory underlyingToken,\\n PrimeCashFactors memory factors,\\n RebalancingTargetD...
A too small `targetAmount` will cause the withdrawal of deposits that should not be withdrawn, damaging the interests of the protocol.
```\\n function getTargetExternalLendingAmount(\\n Token memory underlyingToken,\\n PrimeCashFactors memory factors,\\n RebalancingTargetData memory rebalancingTargetData,\\n OracleData memory oracleData,\\n PrimeRate memory pr\\n ) internal pure returns (uint256 targetAmount) {...
`wfCashERC4626`
medium
The `wfCash` vault is credited less prime cash than the `wfCash` it mints to the depositor when its underlying asset is a fee-on-transfer token. This leads to the vault being insolvent because it has issued more shares than can be redeemed.\\n```\\n if (maxFCash < fCashAmount) {\\n // NOTE: lending at zero\\n...
Consider adding the following:\\nA flag in `wfCashERC4626` that signals that the vault's asset is a fee-on-transfer token.\\nIn `wfCashERC4626._previewMint()` and `wfCashERC46262._previewDeposit`, all calculations related to `assets` should account for the transfer fee of the token.
Although the example used to display the vulnerability is for the case of lending at 0% interest, the issue exists for minting any amount of shares.\\nThe `wfCashERC4626` vault will become insolvent and unable to buy back all shares. The larger the total amount deposited, the larger the deficit. The deficit is equal to...
```\\n if (maxFCash < fCashAmount) {\\n // NOTE: lending at zero\\n uint256 fCashAmountExternal = fCashAmount * precision / uint256(Constants.INTERNAL_TOKEN_PRECISION);\\n require(fCashAmountExternal <= depositAmountExternal);\\n\\n // NOTE: Residual (depositAmountExternal - fCashAmountEx...
`ExternalLending`
medium
When the Treasury rebalances and has to redeem aTokens from AaveV3, it checks that the actual amount withdrawn is greater than or equal to the set `withdrawAmount`. This check will always fail for fee-on-transfer tokens since the `withdrawAmount` does not account for the transfer fee.\\n```\\n address[] memory t...
When computing for the `withdrawAmount / data.expectedUnderlying`, it should account for the transfer fees. The pseudocode for the computation may look like so:\\n```\\nwithdrawAmount = currentAmount - targetAmount\\nif (underlyingToken.hasTransferFee) {\\n withdrawAmount = withdrawAmount / (100% - underlyingToken.tra...
```\\n uint256 withdrawAmount = uint256(netTransferExternal.neg());\\n ExternalLending.redeemMoneyMarketIfRequired(currencyId, underlying, withdrawAmount);\\n```\\n\\nThis means that these tokens can only be deposited into AaveV3 but can never redeemed. This can lead to insolvency of the protocol.
```\\n address[] memory targets = new address[](UNDERLYING_IS_ETH ? 2 : 1);\\n bytes[] memory callData = new bytes[](UNDERLYING_IS_ETH ? 2 : 1);\\n targets[0] = LENDING_POOL;\\n callData[0] = abi.encodeWithSelector(\\n ILendingPool.withdraw.selector, underlyingToken, withdrawAmoun...
`StakingRewardsManager::topUp(...)` Misallocates Funds to `StakingRewards` Contracts
high
The `StakingRewardsManager::topUp(...)` contract exhibits an issue where the specified `StakingRewards` contracts are not topped up at the correct indices, resulting in an incorrect distribution to different contracts.\\nThe `StakingRewardsManager::topUp(...)` function is designed to top up multiple `StakingRewards` co...
It is recommended to do the following changes:\\n```\\n function topUp(\\n address source,\\n uint256[] memory indices\\n ) external onlyRole(EXECUTOR_ROLE) {\\n for (uint i = 0; i < indices.length; i// Add the line below\\n// Add the line below\\n) {\\n // get staking contract and...
The consequence of this vulnerability is that rewards will be distributed to the incorrect staking contract, leading to potential misallocation and unintended outcomes
```\\n function topUp(\\n address source,\\n uint256[] memory indices\\n ) external onlyRole(EXECUTOR_ROLE) {\\n for (uint i = 0; i < indices.length; i++) {\\n // get staking contract and config\\n StakingRewards staking = stakingContracts[i];\\n StakingConfig...
Wrong parameter when retrieving causes a complete DoS of the protocol
high
A wrong parameter in the `_retrieve()` prevents the protocol from properly interacting with Sablier, causing a Denial of Service in all functions calling `_retrieve()`.\\nThe `CouncilMember` contract is designed to interact with a Sablier stream. As time passes, the Sablier stream will unlock more TELCOIN tokens which ...
In order to fix the vulnerability, the proper address needs to be passed when calling `withdrawMax()`.\\nNote that the actual stream address is currently NOT stored in `CouncilMember.sol`, so it will need to be stored (my example shows a new `actualStream` variable)\\n```\\nfunction _retrieve() internal {\\n // ...
High. ALL withdrawals from the Sablier stream will revert, effectively causing a DoS in the _retrieve() function. Because the _retrieve() function is called in all the main protocol functions, this vulnerability essentially prevents the protocol from ever functioning correctly.\\nProof of Concept\\n```\\n// SPDX-Licens...
```\\n// CouncilMember.sol\\n\\nfunction _retrieve() internal {\\n // rest of code\\n // Execute the withdrawal from the _target, which might be a Sablier stream or another protocol\\n _stream.execute(\\n _target,\\n abi.encodeWithSelector(\\n ISablierV2ProxyTar...
CouncilMember:burn renders the contract inoperable after the first execution
high
The CouncilMember contract suffers from a critical vulnerability that misaligns the balances array after a successful burn, rendering the contract inoperable.\\nThe root cause of the vulnerability is that the `burn` function incorrectly manages the `balances` array, shortening it by one each time an ERC721 token is bur...
It is recommended to avoid popping out balances to keep alignment with uniquely minted tokenId. Alternatively, consider migrating to ERC1155, which inherently manages a built-in balance for each NFT.
The severity of the vulnerability is high due to the high likelihood of occurence and the critical impacts on the contract's operability and token holders' ability to interact with their assets.
```\\n// File: telcoin-audit/contracts/sablier/core/CouncilMember.sol\\n function burn(\\n // rest of code\\n balances.pop(); // <= FOUND: balances.length decreases, while latest minted nft withold its unique tokenId\\n _burn(tokenId);\\n }\\n```\\n
Users can fully drain the `TrufVesting` contract
high
Due to flaw in the logic in `claimable` any arbitrary user can drain all the funds within the contract.\\nA user's claimable is calculated in the following way:\\nUp until start time it is 0.\\nBetween start time and cliff time it's equal to `initialRelease`.\\nAfter cliff time, it linearly increases until the full per...
change the if check to the following\\n```\\n if (startTime > block.timestamp) {\\n if (initialRelease > userVesting.claimed) {\\n return initialRelease - userVesting.claimed;\\n }\\n else { return 0; } \\n }\\n```\\n\\nPoC\\n```\\n function test_cliffVesting...
Any user can drain the contract
```\\n function claimable(uint256 categoryId, uint256 vestingId, address user)\\n public\\n view\\n returns (uint256 claimableAmount)\\n {\\n UserVesting memory userVesting = userVestings[categoryId][vestingId][user];\\n\\n VestingInfo memory info = vestingInfos[categoryId][vest...
`cancelVesting` will potentially not give users unclaimed, vested funds, even if giveUnclaimed = true
high
The purpose of `cancelVesting` is to cancel a vesting grant and potentially give users unclaimed but vested funds in the event that `giveUnclaimed = true`. However, due to a bug, in the event that the user had staked / locked funds, they will potentially not received the unclaimed / vested funds even if `giveUnclaimed ...
Change `userVesting.locked = 0;` to `userVestings[categoryId][vestingId][user].locked = 0;`
When `cancelVesting` is called, a user may not receive their unclaimed, vested funds.
```\\nfunction cancelVesting(uint256 categoryId, uint256 vestingId, address user, bool giveUnclaimed)\\n external\\n onlyOwner\\n{\\n UserVesting memory userVesting = userVestings[categoryId][vestingId][user];\\n\\n if (userVesting.amount == 0) {\\n revert UserVestingDoesNotExists...
When migrating the owner users will lose their rewards
medium
When a user migrates the owner due to a lost private key, the rewards belonging to the previous owner remain recorded in their account and cannot be claimed, resulting in the loss of user rewards.\\nAccording to the documentation, `migrateUser()` is used when a user loses their private key to migrate the old vesting ow...
When migrating the owner, the rewards belonging to the previous owner should be transferred to the new owner.
The user's rewards are lost
```\\n /**\\n * @notice Migrate owner of vesting. Used when user lost his private key\\n * @dev Only admin can migrate users vesting\\n * @param categoryId Category id\\n * @param vestingId Vesting id\\n * @param prevUser previous user address\\n * @param newUser new user address\\n */\\n...
Ended locks can be extended
medium
When a lock period ends, it can be extended. If the new extension 'end' is earlier than the current block.timestamp, the user will have a lock that can be unstaked at any time."\\nWhen the lock period ends, the owner of the expired lock can extend it to set a new lock end that is earlier than the current block.timestam...
Do not let extension of locks that are already ended.
The owner of the lock will achieve points that he can unlock anytime. This is clearly a gaming of the system and shouldn't be acceptable behaviour. A locker having a "lock" that can be unstaked anytime will be unfair for the other lockers. Considering this, I'll label this as high.
```\\nfunction test_ExtendLock_AlreadyEnded() external {\\n uint256 amount = 100e18;\\n uint256 duration = 5 days;\\n\\n _stake(amount, duration, alice, alice);\\n\\n // 5 days later, lock is ended for Alice\\n skip(5 days + 1);\\n\\n (,, uint128 _ends,,) = veTRUF.lockups(alice...
OlympusPrice.v2.sol#storePrice: The moving average prices are used recursively for the calculation of the moving average price.
high
The moving average prices should be calculated by only oracle feed prices. But now, they are calculated by not only oracle feed prices but also moving average price recursively.\\nThat is, the `storePrice` function uses the current price obtained from the `_getCurrentPrice` function to update the moving average price. ...
When updating the current price and cumulative observations in the `storePrice` function, it should use the oracle price feeds and not include the moving average prices. So, instead of using the `asset.useMovingAverage` state variable in the `_getCurrentPrice` function, we can add a `useMovingAverage` parameter as the ...
Now the moving average prices are used recursively for the calculation of the moving average price. Then, the moving average prices become more smoothed than the intention of the administrator. That is, even when the actual price fluctuations are large, the price fluctuations of `_getCurrentPrice` function will become ...
```\\n function storePrice(address asset_) public override permissioned {\\n Asset storage asset = _assetData[asset_];\\n\\n // Check if asset is approved\\n if (!asset.approved) revert PRICE_AssetNotApproved(asset_);\\n\\n // Get the current price for the asset\\n (uint256 price, uint4...
Incorrect ProtocolOwnedLiquidityOhm calculation due to inclusion of other user's reserves
high
ProtocolOwnedLiquidityOhm for Bunni can include the liquidity deposited by other users which is not protocol owned\\nThe protocol owned liquidity in Bunni is calculated as the sum of reserves of all the BunniTokens\\n```\\n function getProtocolOwnedLiquidityOhm() external view override returns (uint256) {\\n\\n ...
Guard the deposit function in BunniHub or compute the liquidity using shares belonging to the protocol
Incorrect assumption of the protocol owned liquidity and hence the supply. An attacker can inflate the liquidity reserves The wider system relies on the supply calculation to be correct in order to perform actions of economical impact
```\\n function getProtocolOwnedLiquidityOhm() external view override returns (uint256) {\\n\\n uint256 len = bunniTokens.length;\\n uint256 total;\\n for (uint256 i; i < len; ) {\\n TokenData storage tokenData = bunniTokens[i];\\n BunniLens lens = tokenData.lens;\\n ...
Incorrect StablePool BPT price calculation
high
Incorrect StablePool BPT price calculation as rate's are not considered\\nThe price of a stable pool BPT is computed as:\\nminimum price among the pool tokens obtained via feeds * return value of `getRate()`\\nThis method is used referring to an old documentation of Balancer\\n```\\n function getStablePoolTokenPrice...
For pools having rate providers, divide prices by rate before choosing the minimum
Incorrect calculation of bpt price. Has possibility to be over and under valued.
```\\n function getStablePoolTokenPrice(\\n address,\\n uint8 outputDecimals_,\\n bytes calldata params_\\n ) external view returns (uint256) {\\n // Prevent overflow\\n if (outputDecimals_ > BASE_10_MAX_EXPONENT)\\n revert Balancer_OutputDecimalsOutOfBounds(outputDec...
Inconsistency in BunniToken Price Calculation
medium
The deviation check (_validateReserves()) from BunniPrice.sol considers both position reserves and uncollected fees when validating the deviation with TWAP, while the final price calculation (_getTotalValue()) only accounts for position reserves, excluding uncollected fees.\\nThe same is applied to BunniSupply.sol wher...
Align the methodology used in both the deviation check and the final price computation. This could involve either including the uncollected fees in both calculations or excluding them in both.\\nIt's ok for BunniSupply as there are 2 functions handling both reserves and reserves+fees but change deviation check process ...
`_getTotalValue()` from BunniPrice.sol and `getProtocolOwnedLiquidityReserves()` from BunniSupply.sol have both ratio computation that includes uncollected fees to compare with TWAP ratio, potentially overestimating the total value compared to what these functions are aim to, which is returning only the reserves or LP ...
```\\n### BunniPrice.sol and BunniSupply.sol : \\n function _validateReserves( BunniKey memory key_,BunniLens lens_,uint16 twapMaxDeviationBps_,uint32 twapObservationWindow_) internal view \\n {\\n uint256 reservesTokenRatio = BunniHelper.getReservesRatio(key_, lens_);\\n uint256 twapTokenRatio ...
Price can be miscalculated.
medium
In `SimplePriceFeedStrategy.sol#getMedianPrice` function, when the length of `nonZeroPrices` is 2 and they are deviated it returns first non-zero value, not median value.\\n`SimplePriceFeedStrategy.sol#getMedianPriceIfDeviation` is as follows.\\n```\\n function getMedianPriceIfDeviation(\\n uint256[] memory p...
First, `SimplePriceFeedStrategy.sol#getMedianPriceIfDeviation` function has to be rewritten as follows.\\n```\\n function getMedianPriceIfDeviation(\\n uint256[] memory prices_,\\n bytes memory params_\\n ) public pure returns (uint256) {\\n // Misconfiguration\\n if (prices_.length < ...
When the length of `nonZeroPrices` is 2 and they are deviated, it returns first non-zero value, not median value. It causes wrong calculation error.
```\\n function getMedianPriceIfDeviation(\\n uint256[] memory prices_,\\n bytes memory params_\\n ) public pure returns (uint256) {\\n // Misconfiguration\\n if (prices_.length < 3) revert SimpleStrategy_PriceCountInvalid(prices_.length, 3);\\n\\n237 uint256[] memory nonZeroPrices...
Price calculation can be manipulated by intentionally reverting some of price feeds.
medium
Price calculation module iterates through available price feeds for the requested asset, gather prices of non-revert price feeds and then apply strategy on available prices to calculate final asset price. By abusing this functionality, an attacker can let some price feeds revert to get advantage from any manipulated pr...
For the cases above that price feeds being intentionally reverted, the price calculation itself also should revert without just ignoring it.
Attackers can disable some of price feeds as they want with ease, they can get advantage of one manipulated price feed.
```\\n// Get the current price of the lookup token in terms of the quote token\\n(, int24 currentTick, , , , , bool unlocked) = params.pool.slot0();\\n\\n// Check for re-entrancy\\nif (unlocked == false) revert UniswapV3_PoolReentrancy(address(params.pool));\\n```\\n
getReservesByCategory() when useSubmodules =true and submoduleReservesSelector=bytes4(0) will revert
medium
in `getReservesByCategory()` Lack of check `data.submoduleReservesSelector!=""` when call `submodule.staticcall(abi.encodeWithSelector(data.submoduleReservesSelector));` will revert\\nwhen `_addCategory()` if `useSubmodules==true`, `submoduleMetricSelector` must not empty and `submoduleReservesSelector` can empty (byte...
```\\n function getReservesByCategory(\\n Category category_\\n ) external view override returns (Reserves[] memory) {\\n// rest of code\\n\\n\\n CategoryData memory data = categoryData[category_];\\n uint256 categorySubmodSources;\\n // If category requires data from submodules, count...
some category can't get `Reserves`
```\\n _addCategory(toCategory("protocol-owned-treasury"), true, 0xb600c5e2, 0x00000000); // getProtocolOwnedTreasuryOhm()`\\n```\\n
Balancer LP valuation methodologies use the incorrect supply metric
medium
In various Balancer LP valuations, totalSupply() is used to determine the total LP supply. However this is not the appropriate method for determining the supply. Instead getActualSupply should be used instead. Depending on the which pool implementation and how much LP is deployed, the valuation can be much too high or ...
Use a try-catch block to always query getActualSupply on each pool to make sure supported pools use the correct metric.
Pool LP can be grossly under/over valued
```\\nuint256 balTotalSupply = pool.balancerPool.totalSupply();\\nuint256[] memory balances = new uint256[](_vaultTokens.length);\\n// Calculate the proportion of the pool balances owned by the polManager\\nif (balTotalSupply != 0) {\\n // Calculate the amount of OHM in the pool owned by the polManager\\n // We h...
Possible incorrect price for tokens in Balancer stable pool due to amplification parameter update
medium
Incorrect price calculation of tokens in StablePools if amplification factor is being updated\\nThe amplification parameter used to calculate the invariant can be in a state of update. In such a case, the current amplification parameter can differ from the amplificaiton parameter at the time of the last invariant calcu...
Use the latest amplification factor by callling the `getAmplificationParameter` function
In case the amplification parameter of a pool is being updated by the admin, wrong price will be calculated.
```\\n function getTokenPriceFromStablePool(\\n address lookupToken_,\\n uint8 outputDecimals_,\\n bytes calldata params_\\n ) external view returns (uint256) {\\n\\n // rest of code..\\n\\n try pool.getLastInvariant() returns (uint256, uint256 ampFactor)...
Incorrect deviation calculation in isDeviatingWithBpsCheck function
medium
The current implementation of the `isDeviatingWithBpsCheck` function in the codebase leads to inaccurate deviation calculations, potentially allowing deviations beyond the specified limits.\\nThe function `isDeviatingWithBpsCheck` checks if the deviation between two values exceeds a defined threshold. This function inc...
To accurately measure deviation, the isDeviating function should be revised to calculate the deviation based on the mean value: `| spot value - twap value | / twap value`.
This miscalculation allows for greater deviations than intended, increasing the vulnerability to price manipulation and inaccuracies in Oracle price reporting.
```\\n function isDeviatingWithBpsCheck(\\n uint256 value0_,\\n uint256 value1_,\\n uint256 deviationBps_,\\n uint256 deviationMax_\\n ) internal pure returns (bool) {\\n if (deviationBps_ > deviationMax_)\\n revert Deviation_InvalidDeviationBps(deviationBps_, deviati...
Pool can be drained if there are no LP_FEES
high
The pool can be depleted because swaps allow the withdrawal of the entire balance, resulting in a reserve of 0 for a specific asset. When an asset's balance reaches 0, the PMMPricing algorithm incorrectly estimates the calculation of output amounts. Consequently, the entire pool can be exploited using a flash loan by d...
Do not allow the pools balance to be 0 or do not let LP_FEE to be 0 in anytime.
Pool can be drained, funds are lost. Hence, high. Though, this can only happen when there are no "LP_FEES". However, when we check the default settings of the deployment, we see here that the LP_FEE is set to 0. So, it is ok to assume that the LP_FEES can be 0.
```\\nfunction test_poolCanBeDrained() public {\\n // @review 99959990000000000000000 this amount makes the reserve 0\\n // run a fuzz test, to get the logs easily I will just use this value as constant but I found it via fuzzing\\n // selling this amount to the pool will make the quote token reser...
Adjusting "_I_" will create a sandwich opportunity because of price changes
medium
Adjusting the value of "I" directly influences the price. This can be exploited by a MEV bot, simply by trading just before the "adjustPrice" function and exiting right after the price change. The profit gained from this operation essentially represents potential losses for the liquidity providers who supplied liquidit...
Acknowledge the issue and use private RPC's to eliminate front-running or slowly ramp up the "I" so that the arbitrage opportunity is fair
null
```\\nfunction test_Adjusting_I_CanBeFrontrunned() external {\\n vm.startPrank(tapir);\\n\\n // Buy shares with tapir, 10 - 10\\n dai.safeTransfer(address(gsp), 10 * 1e18);\\n usdc.transfer(address(gsp), 10 * 1e6);\\n gsp.buyShares(tapir);\\n\\n // print some stuff\\n c...
First depositor can lock the quote target value to zero
medium
When the initial deposit occurs, it is possible for the quote target to be set to 0. This situation significantly impacts other LPs as well. Even if subsequent LPs deposit substantial amounts, the quote target remains at 0 due to multiplication with this zero value. 0 QUOTE_TARGET value will impact the swaps that pool ...
According to the quote tokens decimals, multiply the quote token balance with the proper decimal scalor.
Since the quote target is important and used when pool deciding the swap math I will label this as high.
```\\n if (totalSupply == 0) {\\n // case 1. initial supply\\n // The shares will be minted to user\\n shares = quoteBalance < DecimalMath.mulFloor(baseBalance, _I_)\\n ? DecimalMath.divFloor(quoteBalance, _I_)\\n : baseBalance;\\n // The target ...
Share Price Inflation by First LP-er, Enabling DOS Attacks on Subsequent buyShares with Up to 1001x the Attacking Cost
medium
The smart contract contains a critical vulnerability that allows a malicious actor to manipulate the share price during the initialization of the liquidity pool, potentially leading to a DOS attack on subsequent buyShares operations.\\nThe root cause of the vulnerability lies in the initialization process of the liquid...
A mechanism should be implemented to handle the case of zero totalSupply during initialization. A potential solution is inspired by Uniswap V2 Core Code, which sends the first 1001 LP tokens to the zero address. This way, it's extremely costly to inflate the share price as much as 1001 times on the first deposit.\\n```...
The impact of this vulnerability is severe, as it allows an attacker to conduct DOS attacks on buyShares with a low attacking cost (retrievable for further attacks via sellShares). This significantly impairs the core functionality of the protocol, potentially preventing further LP operations and hindering the protocol'...
```\\n// Findings are labeled with '<= FOUND'\\n// File: dodo-gassaving-pool/contracts/GasSavingPool/impl/GSPFunding.sol\\n function buyShares(address to)\\n // rest of code\\n // case 1. initial supply\\n // The shares will be minted to user\\n shares = quoteBalance < DecimalMath...
Attacker can force pause the Auction contract.
medium
In certain situations (e.g founders have ownership percentage greater than 51) an attacker can potentially exploit the `try catch` within the `Auction._CreateAuction()` function to arbitrarily pause the auction contract.\\nConsider the code from `Auction._CreateAuction()` function, which is called by `Auction.settleCur...
Consider better handling the possible errors from `Token.mint()`, like shown below:\\n```\\n function _createAuction() private returns (bool) {\\n // Get the next token available for bidding\\n try token.mint() returns (uint256 tokenId) {\\n //CODE OMMITED\\n } catch (bytes memory err) {\\n ...
Should the conditions mentioned above be met, an attacker can arbitrarily pause the auction contract, effectively interrupting the DAO auction process. This pause persists until owners takes subsequent actions to unpause the contract. The attacker can exploit this vulnerability repeatedly.
```\\nfunction _createAuction() private returns (bool) {\\n // Get the next token available for bidding\\n try token.mint() returns (uint256 tokenId) {\\n // Store the token id\\n auction.tokenId = tokenId;\\n\\n // Cache the current timestamp\\n uint256 startTime = block.timestamp;\\n\\n // Used to store the auct...
MerkleReserveMinter minting methodology is incompatible with current governance structure and can lead to migrated DAOs being hijacked immediately
medium
MerkleReserveMinter allows large number of tokens to be minted instantaneously which is incompatible with the current governance structure which relies on tokens being minted individually and time locked after minting by the auction. By minting and creating a proposal in the same block a user is able to create a propos...
Token should be changed to use a checkpoint based total supply, similar to how balances are handled. Quorum should be based on that instead of the current supply.
DOA can be completely hijacked
```\\nunchecked {\\n for (uint256 i = 0; i < claimCount; ++i) {\\n // Load claim in memory\\n MerkleClaim memory claim = claims[I];\\n\\n // Requires one proof per tokenId to handle cases where users want to partially claim\\n if (!MerkleProof.verify(claim.merkleProof, settings.merkleRoot...
when reservedUntilTokenId > 100 first funder loss 1% NFT
high
The incorrect use of `baseTokenId = reservedUntilTokenId` may result in the first `tokenRecipient[]` being invalid, thus preventing the founder from obtaining this portion of the NFT.\\nThe current protocol adds a parameter `reservedUntilTokenId` for reserving `Token`. This parameter will be used as the starting `baseT...
A better is that the baseTokenId always starts from 0.\\n```\\n function _addFounders(IManager.FounderParams[] calldata _founders, uint256 reservedUntilTokenId) internal {\\n// rest of code\\n\\n // Used to store the base token id the founder will recieve\\n// Remove the line below\\n ui...
when reservedUntilTokenId > 100 first funder loss 1% NFT
```\\n function _addFounders(IManager.FounderParams[] calldata _founders, uint256 reservedUntilTokenId) internal {\\n// rest of code\\n\\n // Used to store the base token id the founder will recieve\\n uint256 baseTokenId = reservedUntilTokenId;\\n\\n // For each token to v...
Adversary can permanently brick auctions due to precision error in Auction#_computeTotalRewards
high
When batch depositing to ProtocolRewards, the msg.value is expected to match the sum of the amounts array EXACTLY. The issue is that due to precision loss in Auction#_computeTotalRewards this call can be engineered to always revert which completely bricks the auction process.\\nProtocolRewards.sol#L55-L65\\n```\\n f...
Instead of setting totalRewards with the sum of the percentages, increment it by each fee calculated. This way they will always match no matter what.
Auctions are completely bricked
```\\n for (uint256 i; i < numRecipients; ) {\\n expectedTotalValue += amounts[i];\\n\\n unchecked {\\n ++i;\\n }\\n }\\n\\n if (msg.value != expectedTotalValue) {\\n revert INVALID_DEPOSIT();\\n }\\n```\\n
Lowering the gauge weight can disrupt accounting, potentially leading to both excessive fund distribution and a loss of funds.
high
Similar issues were found by users 0xDetermination and bart1e in the Canto veRWA audit, which uses a similar gauge controller type.\\nWhen the _change_gauge_weight function is called, the `points_weight[addr][next_time].bias` andtime_weight[addr] are updated - the slope is not.\\n```\\ndef _change_gauge_weight(addr: ad...
Disable weight reduction, or only allow reset to 0.
The way rewards are calculated is broken, leading to an uneven distribution of rewards, with some users receiving too much and others receiving nothing.
```\\ndef _change_gauge_weight(addr: address, weight: uint256):\\n # Change gauge weight\\n # Only needed when testing in reality\\n gauge_type: int128 = self.gauge_types_[addr] - 1\\n old_gauge_weight: uint256 = self._get_weight(addr)\\n type_weight: uint256 = self._get_type_weight(gauge_type)\\n old...
Tokens that are both bribes and StakeDao gauge rewards will cause loss of funds
high
When SdtStakingPositionService is pulling rewards and bribes from buffer, the buffer will return a list of tokens and amounts owed. This list is used to set the rewards eligible for distribution. Since this list is never check for duplicate tokens, a shared bribe and reward token would cause the token to show up twice ...
Either sdtBuffer or SdtStakingPositionService should be updated to combine duplicate token entries and prevent overwriting.
Tokens that are both bribes and rewards will be cause tokens to be lost forever
```\\n ICommonStruct.TokenAmount[] memory bribeTokens = _sdtBlackHole.pullSdStakingBribes(\\n processor,\\n _processorRewardsPercentage\\n );\\n\\n uint256 rewardAmount = _gaugeAsset.reward_count();\\n\\n ICommonStruct.TokenAmount[] memory tokenAmounts = new ICommonStruct.TokenAmount[](\\n ...
Delegation Limitation in Voting Power Management
medium
MgCVG Voting power delegation system is constrained by 2 hard limits, first on the number of tokens delegated to one user (maxTokenIdsDelegated = 25) and second on the number of delegatees for one token ( maxMgDelegatees = 5). Once this limit is reached for a token, the token owner cannot modify the delegation percenta...
Issue Delegation Limitation in Voting Power Management\\nSeparate functions for new delegations and updates : Implement logic that differentiates between adding a new delegatee and updating an existing delegation to allow updates to existing delegations even if the maximum number of delegatees is reached
In some cases it is impossible to update percentage delegated or to remove only one delegated percentage then forcing users to remove all their voting power delegatations, taking the risk that someone is faster then them to delegate to their old delegated users and reach threshold for delegation, making impossible for ...
```\\nfunction delegateMgCvg(uint256 _tokenId, address _to, uint96 _percentage) external onlyTokenOwner(_tokenId) {\\n require(_percentage <= 100, "INVALID_PERCENTAGE");\\n\\n uint256 _delegateesLength = delegatedMgCvg[_tokenId].length;\\n require(_delegateesLength < maxMgDelegatees, "TOO_MUCH_DELEGATEES");\\n...
cvgControlTower and veCVG lock timing will be different and lead to yield loss scenarios
medium
When creating a locked CVG position, there are two more or less independent locks that are created. The first is in lockingPositionService and the other is in veCVG. LockingPositionService operates on cycles (which are not finite length) while veCVG always rounds down to the absolute nearest week. The disparity between...
I would recommend against using block.timestamp for CVG cycles, instead using an absolute measurement like veCVG uses.
Unlock DOS that cause loss of yield to the user
```\\n(1,400,000 + 2 * 604,800) / 604,800 = 4\\n\\n4 * 604,800 = 2,419,200\\n```\\n
SdtRewardReceiver#_withdrawRewards has incorrect slippage protection and withdraws can be sandwiched
medium
The _min_dy parameter of poolCvgSDT.exchange is set via the poolCvgSDT.get_dy method. The problem with this is that get_dy is a relative output that is executed at runtime. This means that no matter the state of the pool, this slippage check will never work.\\nSdtRewardReceiver.sol#L229-L236\\n```\\n if (isMint)...
Allow the user to set _min_dy directly so they can guarantee they get the amount they want
SDT rewards will be sandwiched and can lose the entire balance
```\\n if (isMint) {\\n /// @dev Mint cvgSdt 1:1 via CvgToke contract\\n cvgSdt.mint(receiver, rewardAmount);\\n } else {\\n ICrvPoolPlain _poolCvgSDT = poolCvgSDT;\\n /// @dev Only swap if the returned amount in CvgSdt is gretear than the amount rewarded in SDT...
Division difference can result in a revert when claiming treasury yield and excess rewards to some users
medium
Different ordering of calculations are used to compute `ysTotal` in different situations. This causes the totalShares tracked to be less than the claimable amount of shares\\n`ysTotal` is calculated differently when adding to `totalSuppliesTracking` and when computing `balanceOfYsCvgAt`. When adding to `totalSuppliesTr...
Perform the same calculation in both places\\n```\\n+++ uint256 _ysTotal = (_extension.endCycle - _extension.cycleId)* ((_extension.cvgLocked * _lockingPosition.ysPercentage) / MAX_PERCENTAGE) / MAX_LOCK;\\n--- uint256 ysTotal = (((endCycle - startCycle) * amount * ysPercentage) / MAX_PERCENTAGE...
This breaks the shares accounting of the treasury rewards. Some user's will get more than the actual intended rewards while the last withdrawals will result in a revert
```\\n uint256 cvgLockAmount = (amount * ysPercentage) / MAX_PERCENTAGE;\\n uint256 ysTotal = (lockDuration * cvgLockAmount) / MAX_LOCK;\\n```\\n
Different spot prices used during the comparison
high
The spot prices used during the comparison are different, which might result in the trade proceeding even if the pool is manipulated, leading to a loss of assets.\\n```\\nFile: BalancerComposableAuraVault.sol\\n function _checkPriceAndCalculateValue() internal view override returns (uint256) {\\n (uint256[] m...
Consider verifying if the comment of the `StableMath._calcSpotPrice` function is aligned with its implementation with the Balancer team.\\nIn addition, the `StableMath._calcSpotPrice` function is no longer used or found within the current version of Balancer's composable pool. Thus, there is no guarantee that the math ...
If the spot price is incorrect, it might potentially fail to detect the pool has been manipulated or result in unintended reverts due to false positives. In the worst-case scenario, the trade proceeds to execute against the manipulated pool, leading to a loss of assets.
```\\nFile: BalancerComposableAuraVault.sol\\n function _checkPriceAndCalculateValue() internal view override returns (uint256) {\\n (uint256[] memory balances, uint256[] memory spotPrices) = SPOT_PRICE.getComposableSpotPrices(\\n BALANCER_POOL_ID,\\n address(BALANCER_POOL_TOKEN),\\n ...
BPT LP Token could be sold off during re-investment
medium
BPT LP Token could be sold off during the re-investment process. BPT LP Tokens must not be sold to external DEXs under any circumstance because:\\nThey are used to redeem the underlying assets from the pool when someone exits the vault\\nThe BPTs represent the total value of the vault\\nWithin the `ConvexStakingMixin._...
Ensure that the LP tokens cannot be sold off during re-investment.\\n```\\nfunction _isInvalidRewardToken(address token) internal override view returns (bool) {\\n return (\\n token == TOKEN_1 ||\\n token == TOKEN_2 ||\\n token == TOKEN_3 ||\\n token == TOKEN_4 ||\\n token == TOKEN...
LP tokens (BPT) might be accidentally or maliciously sold off by the bots during the re-investment process. BPT LP Tokens must not be sold to external DEXs under any circumstance because:\\nThey are used to redeem the underlying assets from the pool when someone exits the vault\\nThe BPTs represent the total value of t...
```\\nFile: ConvexStakingMixin.sol\\n function _isInvalidRewardToken(address token) internal override view returns (bool) {\\n return (\\n token == TOKEN_1 ||\\n token == TOKEN_2 ||\\n token == address(CURVE_POOL_TOKEN) ||\\n token == address(CONVEX_REWARD_POOL) ||\...
Fewer than expected LP tokens if the pool is imbalanced during vault restoration
high
The vault restoration function intends to perform a proportional deposit. If the pool is imbalanced due to unexpected circumstances, performing a proportional deposit is not optimal. This results in fewer pool tokens in return due to sub-optimal trade, eventually leading to a loss for the vault shareholder.\\nPer the c...
Consider providing the callers the option to deposit the reward tokens in a "non-proportional" manner if a pool becomes imbalanced. For instance, the function could allow the caller to swap the withdrawn tokens in external DEXs within the `restoreVault` function to achieve the most optimal proportion to minimize the pe...
There is no guarantee that a pool will always be balanced. Historically, there have been multiple instances where the largest curve pool (stETH/ETH) has become imbalanced (Reference #1 and #2).\\nIf the pool is imbalanced due to unexpected circumstances, performing a proportional deposit is not optimal, leading to the ...
```\\nFile: SingleSidedLPVaultBase.sol\\n /// @notice Restores withdrawn tokens from emergencyExit back into the vault proportionally.\\n /// Unlocks the vault after restoration so that normal functionality is restored.\\n /// @param minPoolClaim slippage limit to prevent front running\\n function restoreVa...
Rounding differences when computing the invariant
high
The invariant is used to compute the spot price to verify if the pool has been manipulated before executing certain key vault actions (e.g. reinvest rewards). If the inputted invariant is inaccurate, the spot price computed might not be accurate and might not match the actual spot price of the Balancer Pool. In the wor...
To avoid any discrepancy in the result, ensure that the StableMath library used by Balancer's Composable Pool and Notional's leverage vault are aligned, and the implementation of the StableMath functions is the same between them.
The invariant is used to compute the spot price to verify if the pool has been manipulated before executing certain key vault actions (e.g. reinvest rewards). If the inputted invariant is inaccurate, the spot price computed might not be accurate and might not match the actual spot price of the Balancer Pool. In the wor...
```\\nFile: StableMath.sol\\n function _calculateInvariant(\\n uint256 amplificationParameter,\\n uint256[] memory balances,\\n bool roundUp\\n ) internal pure returns (uint256) {\\n /**********************************************************************************************\\n ...
Incorrect scaling of the spot price
high
The incorrect scaling of the spot price leads to the incorrect spot price, which is later compared with the oracle price.\\nIf the spot price is incorrect, it might potentially fail to detect the pool has been manipulated or result in unintended reverts due to false positives. In the worst-case scenario, the trade proc...
The spot price returned from `StableMath._calcSpotPrice` is denominated in 1e18 (POOL_PRECISION) since the inputted balances are normalized to 18 decimals. The scaling factors are used to normalize a balance to 18 decimals. By dividing or scaling down the spot price by the scaling factor, the native spot price will be ...
The spot price is used to verify if the pool has been manipulated before executing certain key vault actions (e.g. reinvest rewards).\\nIf the spot price is incorrect, it might potentially result in the following:\\nFailure to detect the pool has been manipulated, resulting in the trade to execute against the manipulat...
```\\nFile: BalancerComposableAuraVault.sol\\n function _checkPriceAndCalculateValue() internal view override returns (uint256) {\\n (uint256[] memory balances, uint256[] memory spotPrices) = SPOT_PRICE.getComposableSpotPrices(\\n BALANCER_POOL_ID,\\n address(BALANCER_POOL_TOKEN),\\n ...
Incorrect Spot Price
high
Multiple discrepancies between the implementation of Leverage Vault's `_calcSpotPrice` function and SDK were observed, which indicate that the computed spot price is incorrect.\\nIf the spot price is incorrect, it might potentially fail to detect the pool has been manipulated. In the worst-case scenario, the trade proc...
Given multiple discrepancies between the implementation of Leverage Vault's `_calcSpotPrice` function and SDK and due to the lack of information on the web, it is recommended to reach out to the Balancer's protocol team to identify the actual formula used to determine a spot price of any two tokens within a composable ...
The spot price is used to verify if the pool has been manipulated before executing certain key vault actions (e.g. reinvest rewards). If the spot price is incorrect, it might potentially fail to detect the pool has been manipulated or result in unintended reverts due to false positives. In the worst-case scenario, the ...
```\\nFile: BalancerSpotPrice.sol\\n function _calculateStableMathSpotPrice(\\n..SNIP..\\n // Apply scale factors\\n uint256 secondary = balances[index2] * scalingFactors[index2] / BALANCER_PRECISION;\\n\\n uint256 invariant = StableMath._calculateInvariant(\\n ampParam, StableMath._b...
Incorrect invariant used for Balancer's composable pools
high
Only two balances instead of all balances were used when computing the invariant for Balancer's composable pools, which is incorrect. As a result, pool manipulation might not be detected. This could lead to the transaction being executed on the manipulated pool, resulting in a loss of assets.\\n```\\nFile: BalancerSpot...
Review if there is any specific reason for passing in only the balance of two tokens when computing the invariant. Otherwise, the balance of all tokens (except BPT) should be used to compute the invariant.\\nIn addition, it is recommended to include additional tests to ensure that the computed spot price is aligned wit...
An incorrect invariant will lead to an incorrect spot price being computed. The spot price is used within the `_checkPriceAndCalculateValue` function that is intended to revert if the spot price on the pool is not within some deviation tolerance of the implied oracle price to prevent any pool manipulation. As a result,...
```\\nFile: BalancerSpotPrice.sol\\n function _calculateStableMathSpotPrice(\\n..SNIP..\\n // Apply scale factors\\n uint256 secondary = balances[index2] * scalingFactors[index2] / BALANCER_PRECISION;\\n\\n uint256 invariant = StableMath._calculateInvariant(\\n ampParam, StableMath._b...
Unable to reinvest if the reward token equals one of the pool tokens
high
If the reward token is the same as one of the pool tokens, the protocol would not be able to reinvest such a reward token. Thus leading to a loss of assets for the vault shareholders.\\nDuring the reinvestment process, the `reinvestReward` function will be executed once for each reward token. The length of the `trades`...
Consider tracking the number of pool tokens received during an emergency exit, and segregate these tokens with the reward tokens. For instance, the vault has 3000 CVX, 1000 of them are received during the emergency exit, while the rest are reward tokens emitted from Convex/Aura. In this case, the protocol can sell all ...
The reinvestment of reward tokens is a critical component of the vault. The value per vault share increases when reward tokens are sold for the pool tokens and reinvested back into the Curve/Balancer pool to obtain more LP tokens. If this feature does not work as intended, it will lead to a loss of assets for the vault...
```\\nFile: SingleSidedLPVaultBase.sol\\n function reinvestReward(\\n SingleSidedRewardTradeParams[] calldata trades,\\n uint256 minPoolClaim\\n ) external whenNotLocked onlyRole(REWARD_REINVESTMENT_ROLE) returns (\\n address rewardToken,\\n uint256 amountSold,\\n uint256 poolCl...