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
[M-1]
high
Seller's funds may remain locked in the protocol, because of revert on 0 transfer tokens. In the README.md file is stated that the protocol uses every token with ERC20 Metadata and decimals between 6-18, which includes some revert on 0 transfer tokens, so this should be considered as valid issue!\\nin the `AuctionHouse...
Check if the `prefundingRefund > 0` like this:\\n```\\n function claimProceeds(\\n uint96 lotId_,\\n bytes calldata callbackData_\\n ) external override nonReentrant {\\n // Validation\\n _isLotValid(lotId_);\\n\\n // Call auction module to validate and update data\\n (uin...
The seller's funds remain locked in the system and he will never be able to get them back.
```\\n uint96 prefundingRefund = routing.funding + payoutSent_ - sold_;\\n unchecked {\\n routing.funding -= prefundingRefund;\\n }\\n Transfer.transfer(\\n routing.baseToken,\\n _getAddressGivenCallbackBaseTokenFlag(routing.callbacks, routing.seller),\\n ...
Module's gas yield can never be claimed and all yield will be lost
high
Module's gas yield can never be claimed\\nThe protocol is meant to be deployed on blast, meaning that the gas and ether balance accrue yield.\\nBy default these yield settings for both ETH and GAS yields are set to VOID as default, meaning that unless we configure the yield mode to claimable, we will be unable to recie...
change the following in BlastGas contract, this will set the gas yield of the modules to claimable in the constructor and allowing the auction house to claim gas yield.\\n```\\ninterface IBlast {\\n function configureGovernor(address governor_) external;\\n function configureClaimableGas() external; \\n}\\n\\nabstr...
Gas yields will never acrue and the yield will forever be lost
```\\n constructor(address auctionHouse_) LinearVesting(auctionHouse_) BlastGas(auctionHouse_) {}\\n```\\n
Auction creators have the ability to lock bidders' funds.
high
`Auction creators` have the ability to cancel an `auction` before it starts. However, once the `auction` begins, they should not be allowed to cancel it. During the `auction`, `bidders` can place `bids` and send `quote` tokens to the `auction` house. After the `auction` concludes, `bidders` can either receive `base` to...
```\\nfunction _revertIfLotConcluded(uint96 lotId_) internal view virtual {\\n- if (lotData[lotId_].conclusion < uint48(block.timestamp)) {\\n+ if (lotData[lotId_].conclusion <= uint48(block.timestamp)) {\\n revert Auction_MarketNotActive(lotId_);\\n }\\n\\n // Capacity is sold-out, or cancelled\\n...
Users' funds can be locked.
```\\nfunction cancelAuction(uint96 lotId_) external override onlyInternal {\\n _revertIfLotConcluded(lotId_);\\n}\\n```\\n
Bidders can not claim their bids if the auction creator claims the proceeds.
high
Before the batch `auction` begins, the `auction` creator should `prefund` `base` tokens to the `auction` house. During the `auction`, `bidders` transfer `quote` tokens to the `auction` house. After the `auction` settles,\\n`Bidders` can claim their `bids` and either to receive `base` tokens or `retrieve` their `quote` ...
Allow `bidders` to claim their `bids` even when the `auction status` is `Claimed`.
Users' funds could be locked.
```\\nfunction _claimProceeds(uint96 lotId_)\\n internal\\n override\\n returns (uint96 purchased, uint96 sold, uint96 payoutSent)\\n{\\n auctionData[lotId_].status = Auction.Status.Claimed;\\n}\\n```\\n
Bidders' funds may become locked due to inconsistent price order checks in MaxPriorityQueue and the _claimBid function.
high
In the `MaxPriorityQueue`, `bids` are ordered by decreasing `price`. We calculate the `marginal price`, `marginal bid ID`, and determine the `auction winners`. When a `bidder` wants to claim, we verify that the `bid price` of this `bidder` exceeds the `marginal price`. However, there's minor inconsistency: certain `bid...
In the `MaxPriorityQueue`, we should check the price: `Math.mulDivUp(q, 10 ** baseDecimal, b)`.
null
```\\nfunction _isLess(Queue storage self, uint256 i, uint256 j) private view returns (bool) {\\n uint64 iId = self.bidIdList[i];\\n uint64 jId = self.bidIdList[j];\\n Bid memory bidI = self.idToBidMap[iId];\\n Bid memory bidJ = self.idToBidMap[jId];\\n uint256 relI = uint256(bidI.amountIn) * uint256(bid...
Overflow in curate() function, results in permanently stuck funds
high
The `Axis-Finance` protocol has a curate() function that can be used to set a certain fee to a curator set by the seller for a certain auction. Typically, a curator is providing some service to an auction seller to help the sale succeed. This could be doing diligence on the project and `vouching` for them, or something...
Either remove the unchecked block\\n```\\nunchecked {\\n routing.funding += curatorFeePayout;\\n}\\n```\\n\\nso that when overflow occurs, the transaction will revert, or better yet also change the funding variable type from `uint96` to `uint256` this way sellers can create big enough auctions, and provide sufficient...
If there is an overflow occurs in the curate() function, a big portion of the tokens will be stuck in the `Axis-Finance` protocol forever, as there is no way for them to be withdrawn, either by an admin function, or by canceling the auction (if an auction has started, only FPAM auctions can be canceled), as the amount ...
```\\n struct Routing {\\n // rest of code\\n uint96 funding; \\n // rest of code\\n }\\n```\\n
It is possible to DoS batch auctions by submitting invalid AltBn128 points when bidding
high
Bidders can submit invalid points for the AltBn128 elliptic curve. The invalid points will make the decrypting process always revert, effectively DoSing the auction process, and locking funds forever in the protocol.\\nAxis finance supports a sealed-auction type of auctions, which is achieved in the Encrypted Marginal ...
Ensure that the x and y coordinates are smaller than the field modulus inside the `ECIES.sol` `isValid()` function, adding the `p.x < FIELD_MODULUS && p.y < FIELD_MODULUS` check so that invalid points can't be submitted:\\n```\\n// ECIES.sol\\n\\nfunction isValid(Point memory p) public pure returns (bool) { \\n// Remov...
High. A malicious bidder can effectively DoS the decryption process, which will prevent all actions in the protocol from being executed. This attack will make all the bids and prefunded auction funds remain stuck forever in the contract, because all the functions related to the post-concluded auction steps expect the b...
```\\n// EMPAM.sol\\n\\nfunction _bid(\\n uint96 lotId_, \\n address bidder_,\\n address referrer_,\\n uint96 amount_,\\n bytes calldata auctionData_\\n ) internal override returns (uint64 bidId) {\\n // Decode auction data \\n (uint256 encryptedAmountOut, Point memor...
Downcasting to uint96 can cause assets to be lost for some tokens
high
Downcasting to uint96 can cause assets to be lost for some tokens\\nAfter summing the individual bid amounts, the total bid amount is downcasted to uint96 without any checks\\n```\\n settlement_.totalIn = uint96(result.totalAmountIn);\\n```\\n\\nuint96 can be overflowed for multiple well traded tokens:\\nEg:...
Use a higher type or warn the user's of the limitations on the auction sizes
The auctioner will suffer extreme loss in situations where the auctions bring in >uint96 amount of tokens
```\\n settlement_.totalIn = uint96(result.totalAmountIn);\\n```\\n
Incorrect `prefundingRefund` calculation will disallow claiming
high
Incorrect `prefundingRefund` calculation will lead to underflow and hence disallowing claiming\\nThe `prefundingRefund` variable calculation inside the `claimProceeds` function is incorrect\\n```\\n function claimProceeds(\\n uint96 lotId_,\\n bytes calldata callbackData_\\n ) external override nonR...
Change the calculation to:\\n```\\nuint96 prefundingRefund = capacity - sold_ + curatorFeesAdjustment (how much was prefunded initially - how much will be sent out based on capacity - sold)\\n```\\n
Claim proceeds function is broken. Sellers won't be able to receive the proceedings
```\\n function claimProceeds(\\n uint96 lotId_,\\n bytes calldata callbackData_\\n ) external override nonReentrant {\\n \\n // rest of code\\n\\n (uint96 purchased_, uint96 sold_, uint96 payoutSent_) =\\n _getModuleForId(lotId_).claimProceeds(lotId_);\\n\\n /...
If pfBidder gets blacklisted the settlement process would be broken and every other bidders and the seller would lose their funds
medium
During batch auction settlement, the bidder whos bid was partially filled gets the refund amount in quote tokens and his payout in base immediately. In case if quote or base is a token with blacklisted functionality (e.g. USDC) and bidder's account gets blacklisted after the bid was submitted, the settlement would be b...
Separate the payout and refunding logic for pfBidder from the settlement process.
Loss of funds
```\\n // Check if there was a partial fill and handle the payout + refund\\n if (settlement.pfBidder != address(0)) {\\n // Allocate quote and protocol fees for bid\\n _allocateQuoteFees(\\n feeData.protocolFee,\\n feeData.referr...
Unsold tokens from a FPAM auction, will be stuck in the protocol, after the auction concludes
medium
The `Axis-Finance` protocol allows sellers to create two types of auctions: FPAM & EMPAM. An FPAM auction allows sellers to set a price, and a maxPayout, as well as create a prefunded auction. The seller of a FPAM auction can cancel it while it is still active by calling the cancel function which in turn calls the canc...
Implement a function, that allows sellers to withdraw the amount left for a prefunded FPAM auction they have created, once the auction has concluded.
If a prefunded FPAM auction concludes and there are still tokens, not bought from the users, they will be stuck in the `Axis-Finance` protocol.
```\\n function _revertIfLotConcluded(uint96 lotId_) internal view virtual {\\n // Beyond the conclusion time\\n if (lotData[lotId_].conclusion < uint48(block.timestamp)) {\\n revert Auction_MarketNotActive(lotId_);\\n }\\n\\n // Capacity is sold-out, or cancelled\\n if ...
User's can be grieved by not submitting the private key
medium
User's can be grieved by not submitting the private key\\nBids cannot be refunded once the auction concludes. And bids cannot be claimed until the auction has been settled. Similarly a EMPAM auction cannot be cancelled once started.\\n```\\n function claimBids(\\n uint96 lotId_,\\n uint64[] calldata bi...
Acknowledge the risk involved for the seller and bidder
User's will not be able to claim their assets in case the private key holder doesn't submit the key for decryption
```\\n function claimBids(\\n uint96 lotId_,\\n uint64[] calldata bidIds_\\n )\\n external\\n override\\n onlyInternal\\n returns (BidClaim[] memory bidClaims, bytes memory auctionOutput)\\n {\\n // Standard validation\\n _revertIfLotInvalid(lotId_);\\n ...
Bidder's payout claim could fail due to validation checks in LinearVesting
medium
Bidder's payout claim will fail due to validation checks in LinearVesting after the expiry timestamp\\nBidder's payout are sent by internally calling the `_sendPayout` function. In case the payout is a derivative which has already expired, this will revert due to the validation check of `block.timestmap < expiry` prese...
Allow to mint tokens even after expiry of the vesting token / deploy the derivative token first itself and when making the payout, transfer the base token directly incase the expiry time is passed
Bidder's won't be able claim payouts from auction after the derivative expiry timestamp
```\\n function _sendPayout(\\n address recipient_,\\n uint256 payoutAmount_,\\n Routing memory routingParams_,\\n bytes memory\\n ) internal {\\n \\n if (fromVeecode(derivativeReference) == bytes7("")) {\\n Transfer.transfer(baseToken, recipient_, payoutAmount...
Inaccurate value is used for partial fill quote amount when calculating fees
medium
Inaccurate value is used for partial fill quote amount when calculating fees which can cause reward claiming / payment withdrawal to revert\\nThe fees of an auction is managed as follows:\\nWhenever a bidder claims their payout, calculate the amount of quote tokens that should be collected as fees (instead of giving th...
Use `bidAmount - pfRefund` as the quote token input amount value instead of computing the current way
Rewards might not be collectible or seller might not be able to claim the proceeds due to lack of tokens
```\\n function claimBids(uint96 lotId_, uint64[] calldata bidIds_) external override nonReentrant {\\n \\n // rest of code.\\n\\n for (uint256 i = 0; i < bidClaimsLen; i++) {\\n Auction.BidClaim memory bidClaim = bidClaims[i];\\n\\n if (bidClaim.payout > 0) {\\n ...
Settlement of batch auction can exceed the gas limit
medium
Settlement of batch auction can exceed the gas limit, making it impossible to settle the auction.\\nWhen a batch auction (EMPAM) is settled, to calculate the lot marginal price, the contract iterates over all bids until the capacity is reached or a bid below the minimum price is found.\\nAs some of the operations perfo...
An easy way to tackle the issue would be to change the `_MIN_BID_PERCENT` value from 10 (0.01%) to 1000 (1%) in the `EMPAM.sol` contract, which would limit the number of iterations to 100.\\nA more appropriate solution, if it is not acceptable to increase the min bid percent, would be to change the settlement logic so ...
Settlement of batch auction will revert, causing sellers and bidders to lose their funds.
```\\n// Remove the line below\\n uint24 internal constant _MIN_BID_PERCENT = 1000; // 1%\\n// Add the line below\\n uint24 internal constant _MIN_BID_PERCENT = 100; // 0.1%\\n```\\n
An earner can still continue earning even after being removed from the approved list.
medium
An earner can still continue earning even after being removed from the approved list.\\nA `M` holder is eligible to earn the `Earner Rate` when they are approved by TTG. The approved `M` holder can call `startEarning()` then begin to earn the `Earner Rate`. They also can `stopEarning()` to quit earning.\\nHowever, when...
Introduce a method that allows anyone to stop the disapproved earner from earning:\\n```\\n function stopEarning(address account_) external {\\n if (_isApprovedEarner(account_)) revert IsApprovedEarner();\\n _stopEarning(account_);\\n }\\n```\\n
The earnings of eligible users could potentially be diluted.\\nThe `excessOwedM` to ZERO vault holders could be diluted
```\\n function rate() external view returns (uint256) {\\n uint256 safeEarnerRate_ = getSafeEarnerRate(\\n IMinterGateway(minterGateway).totalActiveOwedM(),\\n IMToken(mToken).totalEarningSupply(),\\n IMinterGateway(minterGateway).minterRate()\\n );\\n\\n return...
Malicious minters can repeatedly penalize their undercollateralized accounts in a short peroid of time, which can result in disfunctioning of critical protocol functions, such as `mintM`.
medium
Malicious minters can exploit the `updateCollateral()` function to repeatedly penalize their undercollateralized accounts in a short peroid of time. This can make the `principalOfTotalActiveOwedM` to reach `uint112.max` limit, disfunctioning some critical functions, such as `mintM`.\\nThe `updateCollateral()` function ...
Consider only imposing penalty for undercollateralization for each update interval.
The direct impact is that `principalOfTotalActiveOwedM` will hit `uint112.max` limit. All related protocol features would be disfunctioned, the most important one being `mintM`, since the function would revert if `principalOfTotalActiveOwedM` hits `uint112.max` limit.\\n```\\n unchecked {\\n uint256 n...
```\\n penalty: 1 94536959275 94536000000\\n penalty: 2 95482328867 95481360000\\n penalty: 3 96437152156 96436173600\\n penalty: 4 97401523678 97400535336\\n penalty: 5 98375538914 98374540689\\n penalty: 6 99359294302 99358286095\\n penalty: 7 100352887244 100351868955\\n penalty: 8 101356416116 101355387644\...
Validator threshold can be bypassed: a single compromised validator can update minter's state to historical state
medium
The `updateCollateralValidatorThreshold` specifies the minimum number of validators needed to confirm the validity of `updateCollateral` data. However, just one compromised validator is enough to alter a minter's collateral status. In particular, this vulnerability allows the compromised validator to set the minter's s...
Use the maximum timestamp of all validators instead of minimum, or take the threshold-last minimum instead of the most minimum.
As shown in the proof of concept, the minter can use the extra collateral to mint M tokens for free.\\nOne may claim that during minting, the `collateralOf()` function checks for `block.timestamp < collateralExpiryTimestampOf(minter_)`, however, since during deployment `updateCollateralInterval` is set to 86400, that g...
```\\n minTimestamp_ = _verifyValidatorSignatures(\\n msg.sender,\\n collateral_,\\n retrievalIds_,\\n metadataHash_,\\n validators_,\\n timestamps_,\\n signatures_\\n );\\n // rest of code\\n _updateCollateral(msg....
Liquidation bonus scales exponentially instead of linearly.
medium
Liquidation bonus scales exponentially instead of linearly.\\nLet's look at the code of `getLiquidationBonus`\\n```\\n function getLiquidationBonus(\\n address token,\\n uint256 borrowedAmount,\\n uint256 times\\n ) public view returns (uint256 liquidationBonus) {\\n // Retrieve liquid...
make liquidation bonus simply a % of totalBorrowed
Loss of funds
```\\n function getLiquidationBonus(\\n address token,\\n uint256 borrowedAmount,\\n uint256 times\\n ) public view returns (uint256 liquidationBonus) {\\n // Retrieve liquidation bonus for the given token\\n Liquidation memory liq = liquidationBonusForToken[token];\\n un...
When the amout of token acquired by a flash loan exceeds the expected value, the callback function will fail.
medium
When the amout of token acquired by a flash loan exceeds the expected value, the callback function will fail.\\nThe function `wagmiLeverageFlashCallback` is used to handle the repayment operation after flash loan. After obtaining enough saleToken, it uses `_v3SwapExact` to convert the saleToken into holdToken. We know ...
In the function `_excuteCallback`, the amount of token finally obtained by the user through flash loan should be the the balance difference during the flash loan period.
DOS
```\\n// Swap tokens to repay the flash loan\\nuint256 holdTokenAmtIn = _v3SwapExact(\\n v3SwapExactParams({\\n isExactInput: false,\\n fee: decodedData.fee,\\n tokenIn: decodedData.holdToken,\\n tokenOut: decodedData.saleToken,\\n amount: amountToPay\\n })\\n);\\ndecodedData.ho...
Highest bidder can withdraw his collateral due to a missing check in _cancelAllBids
high
A bidder with the highest bid cannot cancel his bid since this would break the auction. A check to ensure this was implemented in `_cancelBid`.\\nHowever, this check was not implemented in `_cancelAllBids`, allowing the highest bidder to withdraw his collateral and win the auction for free.\\nThe highest bidder should ...
Implement the require check from _cancelBid to _cancelAllBids.
A malicious user can win an auction for free.\\nAdditionally, either the oldBidder or some other user in the future will suffer the loss.\\nIf this is repeated multiple times, it will drain the contract balance and all users will lose their locked collateral.
```\\n require(\\n bidder != l.highestBids[tokenId][round].bidder,\\n 'EnglishPeriodicAuction: Cannot cancel bid if highest bidder'\\n );\\n```\\n
User Can Vote Even When They Have 0 Locked Mento (Edge Case)
medium
There exists an edge case where the user will be withdrawing his entire locked MENTO amount and even then will be able to vote , this is depicted by a PoC to make things clearer.\\nThe flow to receiving voting power can be understood in simple terms as follows ->\\nUsers locks his MENTO and chooses a delegate-> receive...
When the entire amount is withdrawn adjust the logic to remove the corresponding lines for the delegator.
User still able to vote even when the entire locked amount is withdrawn.
```\\nfunction getAvailableForWithdraw(address account) public view returns (uint96) {\\n uint96 value = accounts[account].amount;\\n if (!stopped) {\\n uint32 currentBlock = getBlockNumber();\\n uint32 time = roundTimestamp(currentBlock);\\n uint96 bias = accounts[account].locked.actualValue(time,...
Auction fails if the 'Honorarium Rate' is 0%
medium
The Honorarium Rate is the required percentage of a winning Auction Pitch bid that the Steward makes to the Creator Circle at the beginning of each Stewardship Cycle.\\n`$$ Winning Bid * Honorarium Rate = Periodic Honorarium $$`\\nTo mimic the dynamics of private ownership, the Creator Circle may choose a 0% Honorarium...
Alter EnglishPeriodicAuctionInternal.sol::L#330 as follows :\\n```\\n// Remove the line below\\n totalCollateralAmount > bidAmount,\\n// Add the line below\\n totalCollateralAmount >= bidAmount, \\n```\\n
The protocol becomes dysfunctional in such a scenario as users as DOS'd from placing a bid.
```\\nuint256 totalCollateralAmount = bid.collateralAmount + collateralAmount;\\n```\\n
Currently auctioned NFTs can be transferred to a different address in a specific edge case
medium
Currently auctioned NFTs can be transferred to a different address in a specific edge case, leading to theft of funds.\\nThe protocol assumes that an NFT cannot change owner while it's being auctioned, this is generally the case but there is an exception, an NFT can change owner via mintToken() while an auction is ongo...
Don't allow `tokenInitialPeriodStartTime[]` to be set at a timestamp beforel.initialPeriodStartTime.
Malicious initial bidder can potentially steal ETH from the protocol in an edge case. If the `ADD_TOKEN_TO_COLLECTION_ROLE` is also malicious, it's possible to drain the protocol.
```\\nl.availableCollateral[oldBidder] += l.highestBids[tokenId][currentAuctionRound].bidAmount;\\n```\\n
Tax refund is calculated based on the wrong amount
high
Tax refund is calculated based on the wrong amount\\nAfter the private period has finished, users can claim a tax refund, based on their max tax free allocation.\\n```\\n (s.share, left) = _claim(s);\\n require(left > 0, "TokenSale: Nothing to claim");\\n uint256 refundTaxAmount;\\n if (s.ta...
change the code to the following:\\n```\\n refundTaxAmount = ((left + taxFreeAllc) * tax) / POINT_BASE;\\n```\\n
Users are not refunded enough tax
```\\n (s.share, left) = _claim(s);\\n require(left > 0, "TokenSale: Nothing to claim");\\n uint256 refundTaxAmount;\\n if (s.taxAmount > 0) {\\n uint256 tax = userTaxRate(s.amount, msg.sender);\\n uint256 taxFreeAllc = _maxTaxfreeAllocation(msg.sender) * PCT_BASE;\\n ...
Vesting contract cannot work with ETH, although it's supposed to.
medium
Vesting contract cannot work with native token, although it's supposed to.\\nWithin the claim function, we can see that if `token` is set to address(1), the contract should operate with ETH\\n```\\n function claim() external {\\n address sender = msg.sender;\\n\\n UserDetails storage s = userdetails[se...
make the following check\\n```\\n if (address(token) != address(1)) token.safeTransferFrom(distributionWallet, address(this), amount);\\n```\\n
Vesting contract is unusable with ETH
```\\n function claim() external {\\n address sender = msg.sender;\\n\\n UserDetails storage s = userdetails[sender];\\n require(s.userDeposit != 0, "No Deposit");\\n require(s.index != vestingPoints.length, "already claimed");\\n uint256 pctAmount;\\n uint256 i = s.index;\\...
If token does not oversell, users cannot claim tax refund on their tax free allocation.
high
Users may not be able to claim tax refund\\nWithin TokenSale, upon depositing users, users have to pay tax. Then, users can receive a tax-free allocation - meaning they'll be refunded the tax they've paid on part of their deposit.\\nThe problem is that due to a unnecessary require check, users cannot claim their tax re...
Remove the require check
loss of funds
```\\n function claim() external {\\n checkingEpoch();\\n require(\\n uint8(epoch) > 1 && !admin.blockClaim(address(this)),\\n "TokenSale: Not time or not allowed"\\n );\\n\\n Staked storage s = stakes[msg.sender];\\n require(s.amount != 0, "TokenSale: No Deposit...
Reentrancy in Vesting.sol:claim() will allow users to drain the contract due to executing .call() on user's address before setting s.index = uint128(i)
high
Reentrancy in Vesting.sol:claim() will allow users to drain the contract due to executing .call() on user's address before setting s.index = uint128(I)\\nHere is the Vesting.sol:claim() function:\\n```\\nfunction claim() external {\\n address sender = msg.sender;\\n\\n UserDetails storage s = userdetails[...
Here is the recommended fix:\\n```\\nif (pctAmount != 0) {\\n// Add the line below\\n s.index = uint128(i);\\n if (address(token) == address(1)) {\\n (bool sent, ) = payable(sender).call{value: pctAmount}("");\\n require(sent, "Failed to send BNB to receiver");\\n ...
Reentrancy in Vesting.sol:claim() will allow users to drain the contract
```\\nfunction claim() external {\\n address sender = msg.sender;\\n\\n UserDetails storage s = userdetails[sender];\\n require(s.userDeposit != 0, "No Deposit");\\n require(s.index != vestingPoints.length, "already claimed");\\n uint256 pctAmount;\\n uint256 i = s.index;\\n ...
Blocklisted investors can still claim USDC in `TokenSale.sol`
medium
A wrong argument is passed when checking if a user is blacklisted for claiming in `TokenSale.claim()`. Because the check is insufficient, blocked users can claim their USDC.\\n`Admin.setClaimBlock()` blocks users from claiming. The function accepts the address of the user to be blocked and adds it to the `blockClaim` m...
Pass the address of the user.\\n```\\n require(\\n// Remove the line below\\n uint8(epoch) > 1 && !admin.blockClaim(address(this)),\\n// Add the line below\\n uint8(epoch) > 1 && !admin.blockClaim(msg.sender)),\\n "TokenSale: Not time or not allowed"\\n );\\n```\\n
The whole functionality for blocking claims doesn't work properly.
```\\n /**\\n @dev Whitelist users\\n @param _address Address of User\\n */\\n function setClaimBlock(address _address) external onlyRole(OPERATOR) {\\n blockClaim[_address] = true;\\n }\\n```\\n
Max allocations can be bypassed with multiple addresses because of guaranteed allocations
medium
`TokenSale._processPrivate()` ensures that a user cannot deposit more than their allocation amount. However, each address can deposit up to at least `maxAllocations`. This can be leveraged by a malicious user by using different addresses to claim all tokens without even staking.\\nThe idea of the protocol is to give ev...
A possible solution may be to modify `calculateMaxAllocation` in the following way:\\n```\\n function calculateMaxAllocation(address _sender) public returns (uint256) {\\n uint256 userMaxAllc = _maxTierAllc(_sender);\\n// Add the line below\\n if (userMaxAllc == 0) return 0;\\n\\n if (userMaxAll...
Buying all allocations without staking. This also violates a key property that only ION holders can deposit.
```\\n if (userTier == 0 && giftedTierAllc == 0) {\\n return 0;\\n }\\n```\\n
Potential damages due to incorrect implementation of the ````ZIP```` algorithm
medium
`WooracleV2_2.fallback()` is used to post zipped token price and state data to the contract for sake of gas saving. However, the first 4 bytes of zipped data are not reserved to distinguish the `ZIP` call and other normal call's function selector. This would cause `ZIP` calls to be accidentally interpreted as any other...
```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/WooPoolV2/contracts/wooracle/WooracleV2_2.sol b/WooPoolV2/contracts/wooracle/WooracleV2_2.sol\\nindex 9e66c63..4a9138f 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/WooPoolV2/contracts/wooracle/Wooracle...
This bug would result in unintended exceptions and potential damages such as:\\nCollision with normal price post functions might cause users' trades executed on incorrect price and suffer losses.\\nCollision with any view function might cause price post to fail silently and hold on trade processing until next submissio...
```\\nfallback () external [payable];\\nfallback (bytes calldata _input) external [payable] returns (bytes memory _output);\\n```\\n
Price manipulation by swapping any ````baseToken```` with itself
medium
`WooPPV2.swap()` doesn't forbid the case that `fromToken == toToken == baseToken`, attackers can make any baseToken's price unboundedly drifting away by swapping with self.\\nThe issue arises due to incorrect logic in WooPPV2._swapBaseToBase():\\nFirstly, we can see the situation that `fromToken == toToken == baseToken...
```\\n2024-03-woofi-swap\\WooPoolV2> git diff\\ndiff --git a/WooPoolV2/contracts/WooPPV2.sol b/WooPoolV2/contracts/WooPPV2.sol\\nindex e7a6ae8..9440089 100644\\n--- a/WooPoolV2/contracts/WooPPV2.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/WooPoolV2/contracts/WooPPV2.sol\\n@@ -520,6 ...
null
```\\nFile: contracts\\WooPPV2.sol\\n function _swapBaseToBase(\\n// rest of code\\n ) private nonReentrant whenNotPaused returns (uint256 base2Amount) {\\n require(baseToken1 != address(0) && baseToken1 != quoteToken, "WooPPV2: !baseToken1");\\n require(baseToken2 != address(0) && baseToken2 != quo...
WooFi oracle can fail to validate its price with Chainlink price feed
medium
The price precision that the WooOracle uses is 8. However, if the quote token is an expensive token or the base token is a very cheap token, then the price will be too less in decimals and even "0" in some cases. This will lead to inefficient trades or inability to compare the woofi price with chainlink price due to ch...
Precision of "8" is not enough on most of the cases. I'd suggest return the oracle price in "18" decimals to get more room on rounding.
Oracle will fail to do a validation of its price with the chainlink price.
```\\nfunction _cloPriceInQuote(address _fromToken, address _toToken)\\n internal\\n view\\n returns (uint256 refPrice, uint256 refTimestamp)\\n {\\n address baseOracle = clOracles[_fromToken].oracle;\\n if (baseOracle == address(0)) {\\n return (0, 0);\\n }\\n ...
Swaps can happen without changing the price for the next trade due to gamma = 0
medium
When a swap happens in WoofiPool the price is updated accordingly respect to such value "gamma". However, there are some cases where the swap results to a "gamma" value of "0" which will not change the new price for the next trade.\\nThis is how the quote token received and new price is calculated when given amount of ...
if the "gamma" is "0", then revert.
As by design, the price should change after every trade irrelevant of the amount that is being traded. Also, in a cheap network the attack can be quite realistic. Hence, I'll label this as medium.
```\\nfunction _calcQuoteAmountSellBase(\\n address baseToken,\\n uint256 baseAmount,\\n IWooracleV2.State memory state\\n ) private view returns (uint256 quoteAmount, uint256 newPrice) {\\n require(state.woFeasible, "WooPPV2: !ORACLE_FEASIBLE");\\n\\n DecimalInfo memory decs = dec...
In the function _handleERC20Received, the fee was incorrectly charged
medium
In the function _handleERC20Received, the fee was incorrectly charged.\\nIn the contract, when external swap occurs, a portion of the fee will be charged. However, in function _handleERC20Received, the fee is also charged in internal swap.\\n```\\n} else {\\n // Deduct the external swap fee\\n uint256 fee = (brid...
Apply fee calculation only to external swaps.\\n```\\nfunction _handleERC20Received(\\n uint256 refId,\\n address to,\\n address toToken,\\n address bridgedToken,\\n uint256 bridgedAmount,\\n uint256 minToAmount,\\n Dst1inch memory dst1inch\\n) internal {\\n address msgSender = _msgSender();\\n\...
Internal swaps are incorrectly charged, and fees are not refunded when internal swap fail.
```\\n} else {\\n // Deduct the external swap fee\\n uint256 fee = (bridgedAmount * dstExternalFeeRate) / FEE_BASE;\\n bridgedAmount -= fee; // @@audit: fee should not be applied to internal swap \\n\\n TransferHelper.safeApprove(bridgedToken, address(wooRouter), bridgedAmount);\\n if (dst1inch.swapRout...
Claim functions don't validate if the epoch is settled
high
Both claim functions fail to validate if the epoch for the request has been already settled, leading to loss of funds when claiming requests for the current epoch. The issue is worsened as `claimAndRequestDeposit()` can be used to claim a deposit on behalf of any account, allowing an attacker to wipe other's requests.\...
Check that the epoch associated with the request is not the current epoch.\\n```\\n function _claimDeposit(\\n address owner,\\n address receiver\\n )\\n internal\\n returns (uint256 shares)\\n {\\n// Add the line below\\n uint256 lastRequestId = lastDepositRequestId[owner];\\...
CRITICAL. Requests can be wiped by executing the claim in an unsettled epoch, leading to loss of funds. The issue can also be triggered for any arbitrary account by using `claimAndRequestDeposit()`.
```\\nfunction _claimDeposit(\\n address owner,\\n address receiver\\n)\\n internal\\n returns (uint256 shares)\\n{\\n shares = previewClaimDeposit(owner);\\n\\n uint256 lastRequestId = lastDepositRequestId[owner];\\n uint256 assets = epochs[lastRequestId].depositRequestBalance[owner];\\n epochs...
Calling `requestRedeem` with `_msgSender() != owner` will lead to user's shares being locked in the vault forever
high
The `requestRedeem` function in `AsyncSynthVault.sol` can be invoked by a user on behalf of another user, referred to as 'owner', provided that the user has been granted sufficient allowance by the 'owner'. However, this action results in a complete loss of balance.\\nThe `_createRedeemRequest` function contains a disc...
Modify `_createRedeemRequest` as follows :\\n```\\n// Remove the line below\\n lastRedeemRequestId[owner] = epochId;\\n// Add the line below\\n lastRedeemRequestid[receiver] = epochId;\\n```\\n
The shares are locked in the vault forever with no method for recovery by the user or the 'owner'.
```\\nfunction test_poc() external {\\n // set token balances\\n deal(vaultTested.asset(), user1.addr, 20); // owner\\n\\n vm.startPrank(user1.addr);\\n IERC20Metadata(vaultTested.asset()).approve(address(vaultTested), 20);\\n // owner deposits tokens when vault is open and receives v...
Exchange rate is calculated incorrectly when the vault is closed, potentially leading to funds being stolen
high
The exchange ratio between shares and assets is calculated incorrectly when the vault is closed. This can cause accounting inconsistencies, funds being stolen and users being unable to redeem shares.\\nThe functions AsyncSynthVault::_convertToAssets and AsyncSynthVault::_convertToShares both add `1` to the epoch cached...
In the functions AsyncSynthVault::_convertToAssets and AsyncSynthVault::_convertToShares:\\nReturn `0` if `requestId == 0`\\nDon't add `1` to the two cached variables\\nIt's also a good idea to perform the initial bootstrapping deposit in the initialize function (as suggested in another finding) and require that the va...
When the ratio between shares and assets is not 1:1 the protocol calculates the exchange rate between assets and shares inconsitently. This is an issue by itself and can lead to loss of funds and users not being able to claim shares. It can also be taken advantage of by an attacker to steal shares from the claimable si...
```\\n// rest of code\\nuint256 totalAssetsSnapshotForDeposit = _lastSavedBalance + 1;\\nuint256 totalSupplySnapshotForDeposit = totalSupply + 1;\\n// rest of code\\nuint256 totalAssetsSnapshotForRedeem = _lastSavedBalance + pendingDeposit + 1;\\nuint256 totalSupplySnapshotForRedeem = totalSupply + sharesToMint + 1;\\n...
The `_zapIn` function may unexpectedly revert due to the incorrect implementation of `_transferTokenInAndApprove`
medium
The `_transferTokenInAndApprove` function should approve the `router` on behalf of the VaultZapper contract. However, it checks the allowance from `msgSender` to the `router`, rather than the VaultZapper. This potentially results in the VaultZapper not approving the `router` and causing unexpected reverting.\\nThe allo...
Fix the issue:\\n```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/asynchronous// Remove the line below\\nvault/src/VaultZapper.sol b/asynchronous// Remove the line below\\nvault/src/VaultZapper.sol\\nindex 9943535..9cf6df9 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove th...
This issue could lead to transaction reverting when users interact with the contract normally, thereby affecting the contract's regular functionality.
```\\n function _transferTokenInAndApprove(\\n address router,\\n IERC20 tokenIn,\\n uint256 amount\\n )\\n internal\\n {\\n tokenIn.safeTransferFrom(_msgSender(), address(this), amount);\\n//@ The check of allowance is useless, we should check the allowance from address(this...
Unupdated totalBorrow After BigBang Liquidation
high
During the liquidation process, BigBang only reduces the user's `userBorrowPart[user]`, but fails to update the global `totalBorrow`. Consequently, all subsequent debt calculations are incorrect.\\nCurrently, the implementation relies on the `BBLiquidation._updateBorrowAndCollateralShare()` method to calculate user deb...
```\\n function _liquidateUser(\\n address user,\\n uint256 maxBorrowPart,\\n IMarketLiquidatorReceiver _liquidatorReceiver,\\n bytes calldata _liquidatorReceiverData,\\n uint256 _exchangeRate,\\n uint256 minLiquidationBonus\\n ) private {\\n uint256 callerReward =...
The lack of an update to `totalBorrow` during liquidation leads to inaccuracies in subsequent loan-related calculations. For instance, this affects interest accumulation and the amount of interest due.
```\\n function _liquidateUser(\\n address user,\\n uint256 maxBorrowPart,\\n IMarketLiquidatorReceiver _liquidatorReceiver,\\n bytes calldata _liquidatorReceiverData,\\n uint256 _exchangeRate,\\n uint256 minLiquidationBonus\\n ) private {\\n uint256 callerReward =...
`_computeClosingFactor` function will return incorrect values, lower than needed, because it uses `collateralizationRate` to calculate the denominator
high
`_computeClosingFactor` is used to calculate the required borrow amount that should be liquidated to make the user's position solvent. However, this function uses `collateralizationRate` (defaulting to 75%) to calculate the liquidated amount, while the threshold to be liquidatable is `liquidationCollateralizationRate` ...
Use `liquidationCollateralizationRate` instead of `collateralizationRate` to calculate the denominator in `_computeClosingFactor`
This issue will result in the user still being liquidatable after a partial liquidation because it liquidates a lower amount than needed. Therefore, the user will never be solvent again after they are undercollateralized until their position is fully liquidated. This may lead to the user being liquidated more than expe...
```\\n//borrowPart and collateralPartInAsset should already be scaled due to the exchange rate computation\\nuint256 liquidationStartsAt =\\n (collateralPartInAsset * _liquidationCollateralizationRate) / (10 ** ratesPrecision);///80% collateral value in asset in default\\n\\nif (borrowPart < liquidationStartsAt) ret...
All ETH can be stolen during rebalancing for `mTOFTs` that hold native
high
Rebalancing of ETH transfers the ETH to the destination `mTOFT` without calling `sgRecieve` which leaves the ETH hanging inside the `mTOFT` contract. This can be exploited to steal all the ETH.\\nRebalancing of `mTOFTs` that hold native tokens is done through the `routerETH` contract inside the `Balancer.sol` contract....
```\\nfunction swapETHAndCall(\\n uint16 _dstChainId, // destination Stargate chainId\\n address payable _refundAddress, // refund additional messageFee to this address\\n bytes calldata _toAddress, // the receiver of the destination ETH\\n SwapAmount memory _swapAmount, // the amount and th...
All ETH can be stolen during rebalancing for mTOFTs that hold native tokens.
```\\n## Balancer.sol\\n\\nif (address(this).balance < _amount) revert ExceedsBalance();\\n uint256 valueAmount = msg.value + _amount;\\n routerETH.swapETH{value: valueAmount}(\\n _dstChainId,\\n payable(this),\\n abi.encodePacked(connectedOFTs[_oft][_dstChainId].dstOft),\...
exerciseOptionsReceiver() Lack of Ownership Check for oTAP, Allowing Anyone to Use oTAPTokenID
high
In UsdoOptionReceiverModule.exerciseOptionsReceiver(): For this method to execute successfully, the `owner` of the `oTAPTokenID` needs to approve it to `address(usdo)`. Once approved, anyone can front-run execute `exerciseOptionsReceiver()` and utilize this authorization.\\nIn `USDO.lzCompose()`, it is possible to spec...
add check `_options.from` is owner or be approved\\n```\\n function exerciseOptionsReceiver(address srcChainSender, bytes memory _data) public payable {\\n\\n// rest of code\\n uint256 bBefore = balanceOf(address(this));\\n// Add the line below\\n address oTap = ITapiocaOptionBroker(_options.tar...
The `exerciseOptionsReceiver()` function lacks ownership checks for `oTAP`, allowing anyone to use `oTAPTokenID`.
```\\n function exerciseOptionsReceiver(address srcChainSender, bytes memory _data) public payable {\\n// rest of code\\n ITapiocaOptionBroker(_options.target).exerciseOption(\\n _options.oTAPTokenID,\\n address(this), //payment token\\n _options.tapAmount\\n ...
Wrong parameter in remote transfer makes it possible to steal all USDO balance from users
high
Setting a wrong parameter when performing remote transfers enables an attack flow where USDO can be stolen from users.\\nThe following bug describes a way to leverage Tapioca's remote transfers in order to drain any user's USDO balance. Before diving into the issue, a bit of background regarding compose calls is requir...
Change the parameter passed in the `_internalRemoteransferSendPacket()` call so that the sender in the compose call built inside it is actually the real source chain sender. This will make it be kept along all the possible recursive calls that might take place:\\n```\\nfunction _remoteTransferReceiver(address _srcChain...
High. An attacker can drain any USDO holder's balance and transfer it to themselves.
```\\n// TapiocaOmnichainReceiver.sol\\nfunction lzCompose( \\n address _from,\\n bytes32 _guid,\\n bytes calldata _message,\\n address, //executor\\n bytes calldata //extra Data\\n ) external payable override {\\n // rest of code\\n \\n // Decode LZ compose messag...
Recursive _lzCompose() call can be leveraged to steal all generated USDO fees
high
It is possible to steal all generated USDO fees by leveraging the recursive _lzCompose() call triggered in compose calls.\\nThe `USDOFlashloanHelper` contract allows users to take USDO flash loans. When a user takes a flash loan some fees will be enforced and transferred to the USDO contract:\\n```\\n// USDOFlashloanHe...
Ensure that the `_lzCompose()` call triggered when a `_nextMsg` exists keeps a consistent source chain sender address, instead of hardcoding it to `address(this)` :\\n```\\n// TapiocaOmnichainReceiver.sol\\n\\nfunction _lzCompose(address srcChainSender_, bytes32 _guid, bytes memory oftComposeMsg_) internal {\\n \\n ...
High, all fees generated by the USDO contract can be effectively stolen by the attacker
```\\n// USDOFlashloanHelper.sol\\nfunction flashLoan(IERC3156FlashBorrower receiver, address token, uint256 amount, bytes calldata data)\\n external\\n override\\n returns (bool)\\n {\\n \\n // rest of code\\n\\n IERC20(address(usdo)).safeTransferFrom(address(receiver), address(...
Unprotected `executeModule` function allows to steal the tokens
high
The `executeModule` function allows anyone to execute any module with any params. That allows attacker to execute operations on behalf of other users.\\nHere is the `executeModule` function:\\nAll its parameters are controlled by the caller and anyone can be the caller. Anyone can execute any module on behalf of any us...
The `executeModule` function should inspect and validate the `_data` parameter to make sure that the caller is the same address as the user who executes the operations.
HIGH - Anyone can steal others' tokens from their markets.
```\\nbUsdo.executeModule(\\n IUsdo.Module.UsdoMarketReceiver, \\n abi.encodeWithSelector(\\n UsdoMarketReceiverModule.removeAssetReceiver.selector, \\n marketMsg_), \\n false);\\n```\\n
Pending allowances can be exploited
high
Pending allowances can be exploited in multiple places in the codebase.\\n`TOFT::marketRemoveCollateralReceiver` has the following flow:\\nIt calls `removeCollateral` ona a market with the following parameters: `from = msg_user`, `to = msg_.removeParams.magnetar`.\\nInside the `SGLCollateral::removeCollateral` `_allowe...
There are multiple instances of issues with dangling allowances in the protocol. Review all the allowance flows and make sure it can't be exploited.
The impact of this vulnerability is that any pending allowances from any user can immediately be exploited to steal the collateral/borrowed amount.
```\\nfunction approveBorrow(address spender, uint256 amount) external returns (bool) {\\n _approveBorrow(msg.sender, spender, amount);\\n return true;\\n }\\n```\\n
Incorrect `tapOft` Amounts Will Be Sent to Desired Chains on Certain Conditions
medium
TOFTOptionsReceiverModule::exerciseOptionsReceiver module, is responsible for facilitating users' token exercises between `mTOFT` and `tapOFT` tokens across different chains. In a `msg-type` where the user wishes to receive the `tapOFT` tokens on a different chain, the module attempts to ensure the amount sent to the u...
update the lz send param `amountLD` to the new computed `amountToSend` before sending the packet\\nI.e :\\n```\\nmsg_.lzSendParams.sendParam.amountLD = amountToSend;\\n```\\n\\nNote that the issue should also be fixed in Tapioca-Bar as well
The user will always receive an incorrect amount of `tapOFT` in the desired chain whenever `amountLD` is greater than `tapAmount`
```\\n uint256 amountToSend = _send.amountLD > _options.tapAmount ? _options.tapAmount : _send.amountLD;\\n if (_send.minAmountLD > amountToSend) {\\n _send.minAmountLD = amountToSend;\\n }\\n```\\n
Underflow Vulnerability in `Market::_allowedBorrow` Function: Oversight with Pearlmit Allowance Handling
medium
The protocol permits users to authorize spenders using the MarketERC20::approveBorrow function, and also includes support for allowances granted through the `Pearlmit` contract. However, an oversight in the _allowedBorrow function leads to an underflow issue when spenders utilize `Pearlmit` allowances, rendering them u...
After ensuring that the user has got the approval, return when permission from `Pearlmit` is used:\\n```\\n function _allowedBorrow(address from, uint256 share) internal virtual override {\\n if (from != msg.sender) {\\n // TODO review risk of using this\\n (uint256 pearlmitAllowed,) = p...
Although giving a spender allowance via `Pearlmit` will appear to be supported, the spender cannot carry out any borrowing action in the Market.
```\\n function _allowedBorrow(address from, uint256 share) internal virtual override {\\n if (from != msg.sender) {\\n // TODO review risk of using this\\n (uint256 pearlmitAllowed,) = penrose.pearlmit().allowance(from, msg.sender, address(yieldBox), collateralId);\\n require...
The repaying action in `BBLeverage.sellCollateral` function pulls YieldBox shares of asset from wrong address
medium
The `sellCollateral` function is used to sell a user's collateral to obtain YieldBox shares of the asset and repay the user's loan. However, in the BBLeverage contract, it calls `_repay` with the `from` parameter set to the user, even though the asset shares have already been collected by this contract beforehand.\\nIn...
Should fix as following:\\n```\\nif (memoryData.shareOwed <= memoryData.shareOut) {\\n _repay(address(this), from, memoryData.partOwed);\\n} else {\\n //repay as much as we can\\n uint256 partOut = totalBorrow.toBase(amountOut, false);\\n _repay(address(this), from, partOut);\\n}\\n```\\n
Mistakenly pulling user funds while the received asset shares remain stuck in the contract will result in losses for users who have sufficient allowance and balance when using the `BBLeverage.sellCollateral` functionality.
```\\nif (memoryData.shareOwed <= memoryData.shareOut) {\\n _repay(from, from, memoryData.partOwed);\\n} else {\\n //repay as much as we can\\n uint256 partOut = totalBorrow.toBase(amountOut, false);\\n _repay(from, from, partOut);\\n}\\n```\\n
`leverageAmount` is incorrect in `SGLLeverage.sellCollateral` function due to calculation based on the new states of YieldBox after withdrawal
medium
See vulnerability detail\\n`SGLLeverage.sellCollateral` function attempts to remove the user's collateral in shares of YieldBox, then withdraws those collateral shares to collect collateral tokens. Subsequently, the received collateral tokens can be used to swap for asset tokens.\\nHowever, the `leverageAmount` variabl...
`leverageAmount` should be obtained from the return value of YieldBox.withdraw:\\n```\\n(uint256 leverageAmount, ) = yieldBox.withdraw(collateralId, address(this), address(leverageExecutor), 0, calldata_.share);\\n```\\n
Because `leverageAmount` can be higher than the actual withdrawn collateral tokens, `leverageExecutor.getAsset()` will revert due to not having enough tokens in the contract to pull. This results in a DOS of `sellCollateral`, break this functionality.
```\\nyieldBox.withdraw(collateralId, address(this), address(leverageExecutor), 0, calldata_.share);\\nuint256 leverageAmount = yieldBox.toAmount(collateralId, calldata_.share, false);\\n\\namountOut = leverageExecutor.getAsset(\\n assetId, address(collateral), address(asset), leverageAmount, calldata_.from, calldat...
mTOFTReceiver MSG_XCHAIN_LEND_XCHAIN_LOCK unable to execute
medium
In `mTOFTReceiver._toftCustomComposeReceiver(uint16 _msgType)` If `_msgType` is processed normally, the method must return `true`, if it returns `false`, it will trigger `revert InvalidMsgType()` But when `_msgType == MSG_XCHAIN_LEND_XCHAIN_LOCK` is executed normally, it does not correctly return `true` This causes thi...
```\\ncontract mTOFTReceiver is BaseTOFTReceiver {\\n constructor(TOFTInitStruct memory _data) BaseTOFTReceiver(_data) {}\\n\\n function _toftCustomComposeReceiver(uint16 _msgType, address, bytes memory _toeComposeMsg)\\n internal\\n override\\n returns (bool success)\\n {\\n if (_m...
`_msgType == MSG_XCHAIN_LEND_XCHAIN_LOCK` `TOFTOptionsReceiver.mintLendXChainSGLXChainLockAndParticipateReceiver()` unable to execute successfully
```\\n function _lzCompose(address srcChainSender_, bytes32 _guid, bytes memory oftComposeMsg_) internal {\\n // Decode OFT compose message.\\n (uint16 msgType_,,, bytes memory tapComposeMsg_, bytes memory nextMsg_) =\\n TapiocaOmnichainEngineCodec.decodeToeComposeMsg(oftComposeMsg_);\\n\\n ...
Multiple contracts cannot be paused
medium
For safety, tapioca has added `whenNotPaused` restrictions to multiple contracts But there is no method provided to modify the `_paused` state If a security event occurs, it cannot be paused at all\\nTake `mTOFT.sol` as an example, multiple methods are `whenNotPaused`\\n```\\n function executeModule(ITOFT.Module _mo...
```\\n// Add the line below\\n function pause() external onlyOwner{\\n// Add the line below\\n _pause();\\n// Add the line below\\n }\\n\\n// Add the line below\\n function unpause() external onlyOwner{\\n// Add the line below\\n _unpause();\\n// Add the line below\\n }\\n```\\n
Due to the inability to modify `_paused`, it poses a security risk
```\\n function executeModule(ITOFT.Module _module, bytes memory _data, bool _forwardRevert)\\n external\\n payable\\n whenNotPaused\\n returns (bytes memory returnData)\\n {\\n// rest of code\\n function sendPacket(LZSendParam calldata _lzSendParam, bytes calldata _composeMsg)\\n ...
Composing approval with other messages is subject to DoS
medium
`TOFT::sendPacket` function allows the caller to specify multiple messages that are executed on the destination chain. On the receiving side the `lzCompose` function in `TOFT` contract can be DoS-ed by front-running the approval message and causing the `lzCompose` to revert. As `lzCompose` is supposed to process severa...
`TOFT::sendPacket` should do extra checks to ensure if the message contains approvals, it should not allow packing several messages.
When user is granting approvals and wants to execute any other message in the same `lzCompose` call, the attacker can deny the user from executing the other message by front-running the approval message and causing the `lzCompose` to revert. The impact is lost fee paid on the sending chain for executing the subsequent ...
```\\n function sendPacket(LZSendParam calldata _lzSendParam, bytes calldata _composeMsg)\\n public\\n payable\\n whenNotPaused // @audit Pausing is not implemented yet.\\n returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt)\\n {\\n (msgReceipt, oftReceipt...
StargateRouter cannot send payloads and rebalancing of ERC20s is broken
medium
The `Balancer.sol` contract can't perform the rebalancing of ERC20s across chains as the Stargate router is not able to send any payload and will immediately revert the transaction if a payload is included. In this instance payload is hardcoded to `"0x"`.\\n`Balancer.sol` contract has a `rebalance` function that is sup...
Use the `StargateComposer` instead of the `StargateRouter` if sending payloads.
Rebalancing of `mTOFTs` across chains is broken and as it is one of the main functionalities of the protocol, this is a high-severity issue.
```\\n## Balancer.sol\\n\\n router.swap{value: msg.value}(\\n _dstChainId,\\n _srcPoolId,\\n _dstPoolId,\\n payable(this),\\n _amount,\\n _computeMinAmount(_amount, _slippage),\\n IStargateRouterBase.lzTxObj({dstGasForCall: 0, dstNativeAmount: 0, dstNativeAddr: "0x0"}...
`mTOFT` can be forced to receive the wrong ERC20 leading to token lockup
medium
Due to Stargate's functionality of swapping one token on the source chain to another token on the destination chain, it is possible to force `mTOFT` to receive the wrong ERC20 token leading to token lockup.\\nTo give an example, a user can:\\nProvide USDC on Ethereum and receive USDT on Avalanche.\\nProvide USDC on Ava...
The `initConnectedOFT` function should enforce the poolIds for the src and dst chains.The rebalance function should just fetch these saved values and use them.\\n```\\n \\n@@ // Remove the line below\\n164,14 // Add the line below\\n176,12 @@ contract Balancer is Ownable {\\n * @param _dstChainId the destination L...
The impact of this vulnerability is critical. It allows for locking up wrong tokens inside the mTOFT contract causing irreversible loss of funds.
```\\n## Balancer.sol\\n\\nfunction _sendToken(\\n address payable _oft,\\n uint256 _amount,\\n uint16 _dstChainId,\\n uint256 _slippage,\\n> bytes memory _data\\n ) private {\\n address erc20 = ITOFT(_oft).erc20();\\n if (IERC20Metadata(erc20).balanceOf(address(this)...
Gas parameters for Stargate swap are hardcoded leading to stuck messages
medium
The `dstGasForCall` for transferring erc20s through Stargate is hardcoded to 0 in the `Balancer` contract leading to `sgReceive` not being called during Stargate swap. As a consequence, the `sgReceive` has to be manually called to clear the `cachedSwapLookup` mapping, but this can be DoSed due to the fact that the `mTO...
The `dstGasForCall` shouldn't be hardcoded to 0. It should be a configurable value that is set by the admin of the `Balancer` contract.\\nTake into account that this value will be different for different chains.\\nThe recommended solution is:\\n```\\n contract Balancer is Ownable {\\n using SafeERC20 for IERC20;\\n...
Hardcoding the `dstGasCall` to 0 in conjuction with not checking the `sgReceive` parameters opens up the possibility of a long-term DoS attack.
```\\n function swap(\\n uint16 _chainId,\\n uint256 _srcPoolId,\\n uint256 _dstPoolId,\\n address payable _refundAddress,\\n Pool.CreditObj memory _c,\\n Pool.SwapObj memory _s,\\n IStargateRouter.lzTxObj memory _lzTxParams, \\n bytes calldata _to,\\n b...
`getCollateral` and `getAsset` functions of the AssetTotsDaiLeverageExecutor contract decode data incorrectly
medium
See vulnerability detail\\nIn AssetTotsDaiLeverageExecutor contract, `getCollateral` function decodes the data before passing it to `_swapAndTransferToSender` function.\\n```\\nSLeverageSwapData memory swapData = abi.decode(data, (SLeverageSwapData));\\nuint256 daiAmount =\\n _swapAndTransferToSender(false, assetAdd...
The AssetTotsDaiLeverageExecutor contract should pass data directly to `_swapAndTransferToSender`, similar to the SimpleLeverageExecutor contract
`getCollateral` and `getAsset` of AssetTotsDaiLeverageExecutor will not work as intended due to incorrectly decoding data.
```\\nSLeverageSwapData memory swapData = abi.decode(data, (SLeverageSwapData));\\nuint256 daiAmount =\\n _swapAndTransferToSender(false, assetAddress, daiAddress, assetAmountIn, swapData.swapperData);\\n```\\n
Balancer using safeApprove may lead to revert.
medium
When executing `Balancer._routerSwap()`, the `oz` `safeApprove` function is used to set an allowance. Due to the presence of the `convertRate` in the `router`, `Balancer._routerSwap()` rounds down the incoming quantity. This behavior may result in the allowance not being fully use, causing a subsequent execution of `oz...
```\\n function _routerSwap(\\n uint16 _dstChainId,\\n uint256 _srcPoolId,\\n uint256 _dstPoolId,\\n uint256 _amount,\\n uint256 _slippage,\\n address payable _oft,\\n address _erc20\\n ) private {\\n bytes memory _dst = abi.encodePacked(connectedOFTs[_oft][...
Unused allowance may lead to failure in subsequent `_routerSwap()` executions.
```\\n function _routerSwap(\\n uint16 _dstChainId,\\n uint256 _srcPoolId,\\n uint256 _dstPoolId,\\n uint256 _amount,\\n uint256 _slippage,\\n address payable _oft,\\n address _erc20\\n ) private {\\n bytes memory _dst = abi.encodePacked(connectedOFTs[_oft][...
buyCollateral() does not work properly
medium
The `BBLeverage.buyCollateral()` function does not work as expected.\\nThe implementation of `BBLeverage.buyCollateral()` is as follows:\\n```\\n function buyCollateral(address from, uint256 borrowAmount, uint256 supplyAmount, bytes calldata data)\\n external\\n optionNotPaused(PauseType.LeverageBuy)\\...
```\\n function buyCollateral(address from, uint256 borrowAmount, uint256 supplyAmount, bytes calldata data)\\n external\\n optionNotPaused(PauseType.LeverageBuy)\\n solvent(from, false)\\n notSelf(from)\\n returns (uint256 amountOut)\\n {\\n// rest of code.\\n\\n {\\n ...
`buyCollateral()` does not work properly.
```\\n function buyCollateral(address from, uint256 borrowAmount, uint256 supplyAmount, bytes calldata data)\\n external\\n optionNotPaused(PauseType.LeverageBuy)\\n solvent(from, false)\\n notSelf(from)\\n returns (uint256 amountOut)\\n {\\n if (address(leverageExecutor)...
DoS in BBLeverage and SGLLeverage due to using wrong leverage executor interface
medium
A DoS takes place due to utilizing a wrong interface in the leverage modules.\\n`BBLeverage.sol` and `SGLLeverage.sol` use a wrong interface to interact with the `leverageExecutor` contract. This will make the `sellCollateral()` and `buyCollateral()` functions always fail and render the `BBLeverage.sol` and `SGLLeverag...
Update the interface used in BBLeverage.sol and SGLLeverage.sol and pass the proper parameters so that calls can succeed.
High. Calls to the leverage modules will always fail, rendering these features unusable.
```\\n// BBLeverage.sol\\n\\nfunction buyCollateral(address from, uint256 borrowAmount, uint256 supplyAmount, bytes calldata data) \\n external\\n optionNotPaused(PauseType.LeverageBuy)\\n solvent(from, false)\\n notSelf(from) \\n returns (uint256 amountOut) \\n { \\n // re...
Variable opening fee will always be wrongly computed if collateral is not a stablecoin
medium
Borrowing fees will be computed wrongly because of a combination of hardcoded values and a wrongly implemented setter function.\\nTapioca applies a linearly scaling creation fee to open a new CDP in Big Bang markets. This is done via the internal `_computeVariableOpeningFee()` function every time a new borrow is perfor...
The mitigation for this is straightforward. Change the `setMinAndMaxMintRange()` function so that `_max` is enforced to be smaller than _min:\\n```\\n// BigBang.sol\\n\\nfunction setMinAndMaxMintRange(uint256 _min, uint256 _max) external onlyOwner {\\n emit UpdateMinMaxMintRange(minMintFeeStart, _min, maxMintFee...
Medium. Although this looks like a bug that doesn't have a big impact in the protocol, it actually does. The fees will always be wrongly applied for collaterals different from stablecoins, and applying these kind of fees when borrowing is one of the core mechanisms to keep USDO peg, as described in Tapioca's documentat...
```\\n// BBLendingCommon.sol\\n\\nfunction _computeVariableOpeningFee(uint256 amount) internal returns (uint256) {\\n if (amount == 0) return 0; \\n \\n //get asset <> USDC price ( USDO <> USDC ) \\n (bool updated, uint256 _exchangeRate) = assetOracle.get(oracleData); \\n if (!updated) rever...
Not properly tracking debt accrual leads mintOpenInterestDebt() to lose twTap rewards
medium
Debt accrual is tracked wrongly, making the expected twTap rewards to be potentially lost.\\nPenrose's `mintOpenInterestDebt()` function allows USDO to be minted and distributed as a reward to twTap holders based on the current USDO open interest.\\nIn order to mint and distribute rewards, `mintOpenInterestDebt()` will...
One of the possible fixes for this issue is to track debt with a storage variable. Every time a repay is performed, the difference between elastic and base could be accrued to the variable, and such variable could be decremented when the fees distributions are performed. This makes it easier to compute the actual rewar...
Medium. The fees to be distributed in twTap are likely to always be wrong, making one of the core governance functionalities (locking TAP in order to participate in Tapioca's governance) be broken given that fee distributions (and thus the incentives to participate in governance) won't be correct.
```\\nfunction mintOpenInterestDebt(address twTap) external onlyOwner { \\n uint256 usdoSupply = usdoToken.totalSupply();\\n\\n // nothing to mint when there's no activity\\n if (usdoSupply > 0) { \\n // re-compute latest debt\\n uint256 totalUsdoDebt = computeTotalDebt(); \...
USDO's MSG_TAP_EXERCISE compose messages where exercised options must be withdrawn to another chain will always fail due to wrongly requiring sendParam's to address to be whitelisted in the Cluster
medium
Wrongly checking for the sendParam's `to` address `to` be whitelisted when bridging exercised options will make such calls always fail.\\nOne of the compose messages allowed in USDO is `MSG_TAP_EXERCISE`. This type of message will trigger UsdoOptionReceiverModule's `exerciseOptionsReceiver()` function, which allows use...
Remove the whitelist check against the `msg_.lzSendParams.sendParam.to` param inexerciseOptionsReceiver():\\n```\\n// UsdoOptionReceiverModule.sol\\n\\nfunction exerciseOptionsReceiver(address srcChainSender, bytes memory _data) public payable {\\n // Decode received message.\\n ExerciseOptionsMsg memory ...
High. The functionality of exercising options and bridging them in the same transaction is one of the wide range of core functionalities that should be completely functional in Tapioca. However, this functionality will always fail due to the mentioned issue, forcing users to only be able to exercise options in the same...
```\\n// UsdoOptionReceiverModule.sol\\n\\nfunction exerciseOptionsReceiver(address srcChainSender, bytes memory _data) public payable {\\n // Decode received message.\\n ExerciseOptionsMsg memory msg_ = UsdoMsgCodec.decodeExerciseOptionsMsg(_data);\\n \\n _checkWhitelistStatus(msg_.optionsData.ta...
Withdrawing to other chain when exercising options won't work as expected, leading to DoS
medium
Withdrawing to another chain when exercising options will always fail because the implemented functionality does not bridge the tokens exercised in the option, and tries to perform a regular cross-chain call instead.\\nTapioca incorporates a DAO Share Options (DSO) program where users can lock USDO in order to obtain T...
If users decide to bridge their exercised tapOft, the sendPacket() function incorporated in the tapOft contract should be used instead of UsdoOptionReceiverModule's internal _sendPacket() function, so that the actual bridged asset is the tapOft and not the USDO.
High. As demonstrated, two critical outcomes might affect the user:\\n`tapOft` funds will remain stuck forever in the USDO contract and USDO will be incorrectly burnt from `msg.sender`\\nThe core functionality of exercising and bridging options always reverts and effectively causes a DoS.
```\\n// UsdoOptionReceiverModule.sol\\n\\nfunction exerciseOptionsReceiver(address srcChainSender, bytes memory _data) public payable {\\n \\n // rest of code \\n \\n ITapiocaOptionBroker(_options.target).exerciseOption(\\n _options.oTAPTokenID,\\n address(this), //pay...
Not considering fees when wrapping mtOFTs leads to DoS in leverage executors
medium
When wrapping mtOFTs in leverage executors, fees are not considered, making calls always revert because the obtained assets amount is always smaller than expected.\\nTapioca will allow tOFTs and mtOFTs to act as collateral in some of Tapioca's markets, as described by the documentation. Although regular tOFTs don't har...
Consider the fees applied when wrapping assets by following OFT's API, and store the returned value by `wrap()`. For example, `_handleToftWrapToSender()` could return an integer with the actual amount obtained after wrapping:\\n```\\n// BaseLeverageExecutor.sol\\n\\nfunction _handleToftWrapToSender(bool sendBack, addre...
High. The core functionality of leverage won't work if the tokens are mtOFT tokens.
```\\n// mTOFT.sol\\n\\nfunction wrap(address _fromAddress, address _toAddress, uint256 _amount)\\n external\\n payable \\n whenNotPaused\\n nonReentrant\\n returns (uint256 minted)\\n {\\n // rest of code\\n \\n uint256 feeAmount = _checkAndExtractFees(_amount);\...
Secondary Big Bang market rates can be manipulated due to not triggering penrose.reAccrueBigBangMarkets(); when leveraging
medium
Secondary market rates can still be manipulated via leverage executors because `penrose.reAccrueBigBangMarkets()` is never called in the leverage module.\\nThe attack described in Tapioca's C4 audit 1561 issue and also described in Spearbit's audit 5.2.16 issue is still possible utilizing the leverage modules.\\nAs a s...
It is recommended to trigger Penrose's reAccrueBigBangMarkets() function when interacting with Big Bang's leverage modules, so that the issue can be fully mitigated.
Medium. A previously found issue is still present in the codebase which allows secondary Big Bang markets interest rates to be manipulated, allowing the attacker to perform profitable strategies and potentially affecting users.
```\\n// Penrose.sol\\n\\nfunction reAccrueBigBangMarkets() external notPaused {\\n if (msg.sender == bigBangEthMarket) {\\n _reAccrueMarkets(false);\\n } \\n }\\n \\n function _reAccrueMarkets(bool includeMainMarket) private {\\n uint256 len = allBigBangMarkets.length;\\n addr...
`TOFTMarketReceiverModule::marketBorrowReceiver` flow is broken
medium
The `TOFTMarketReceiverModule::marketBorrowReceiver` flow is broken and will revert when the Magnetar contract tries to transfer the ERC1155 tokens to the Market contract.\\n`TOFTMarketReceiverModule::marketBorrowReceiver` flow is broken.\\nLet's examine it more closely:\\nAfter checking the whitelisting status for the...
Review all the allowance mechanisms and ensure that they are correct.
The `TOFTMarketReceiverModule::marketBorrowReceiver` flow is broken and will revert when the Magnetar contract tries to transfer the ERC1155 tokens to the Market contract. There are also other instances of similar issues.
```\\n function _extractTokens(address _from, address _token, uint256 _amount) internal returns (uint256) {\\n uint256 balanceBefore = IERC20(_token).balanceOf(address(this));\\n // IERC20(_token).safeTransferFrom(_from, address(this), _amount);\\n pearlmit.transferFromERC20(_from, address(this)...
Blacklisted accounts can still transact.
medium
Accounts that have been blacklisted by the `BLACKLISTER_ROLE` continue to transact normally.\\nCurrently, the only real effect of blacklisting an account is the seizure of `Stablecoin` funds:\\n```\\n/**\\n * @notice Overrides Blacklist function to transfer balance of a blacklisted user to the caller.\\n * @dev This fu...
ERC20s that enforce blacklists normally prevent a sanctioned address from being able to transact:\\n📄 Stablecoin.sol\\n```\\n// Add the line below\\n error Blacklisted(address account);\\n\\n// Add the line below\\nfunction _update(address from, address to, uint256 value) internal virtual override {\\n// Add the line ...
Medium, as this the failure of a manually administered security feature.
```\\n/**\\n * @notice Overrides Blacklist function to transfer balance of a blacklisted user to the caller.\\n * @dev This function is called internally when an account is blacklisted.\\n * @param user The blacklisted user whose balance will be transferred.\\n */\\nfunction _onceBlacklisted(address user) internal over...
Setting the strategy cap to "0" does not update the total shares held or the withdrawal queue
high
Removing or setting the strategy cap to 0 will not decrease the shares held in the system. Additionally, it will not update the withdrawal queue, which means users can request withdrawals, and the withdrawals will exceed the allocated amount when rebalance occurs.\\nLet's go over the issue with an example:\\nAssume the...
Update the withdrawal queue when the operator registry admin changes the EigenLayer shares amount by either removing an operator or setting its strategy cap to "0".
High, because the users withdrawals will never go through in rebalancing because of double counting of the same share withdrawals.
```\\nfunction setOperatorStrategyCap(\\n RioLRTOperatorRegistryStorageV1.StorageV1 storage s,\\n uint8 operatorId,\\n IRioLRTOperatorRegistry.StrategyShareCap memory newShareCap\\n ) internal {\\n . \\n // @review this "if" will be executed\\n -> if (currentShareDetails.cap...
swapValidatorDetails incorrectly writes keys to memory, resulting in permanently locked beacon chain deposits
high
When loading BLS public keys from storage to memory, the keys are partly overwritten with zero bytes. This ultimately causes allocations of these malformed public keys to permanently lock deposited ETH in the beacon chain deposit contract.\\nValidatorDetails.swapValidatorDetails is used by RioLRTOperatorRegistry.report...
We can solve this by simply mstoring `_part2` prior to mstoring `_part1`, allowing the mstore of `_part1` to overwrite the zero bytes from _part2:\\n```\\nmstore(add(key1, 0x30), shr(128, _part2)) // Store bytes 16..47\\nmstore(add(key1, 0x20), _part1) // Store bytes 0..31\\n```\\n\\nNote that the above change must be ...
Whenever we swapValidatorDetails using reportOutOfOrderValidatorExits, both sets of validators will have broken public keys and when allocated to will cause ETH to be permanently locked in the beacon deposit contract.\\nWe can see how this manifests in allocateETHDeposits where we retrieve the public keys for allocatio...
```\\n// Swap the position of the validators starting from the `fromIndex` with the validators that were next in line to be exited.\\nVALIDATOR_DETAILS_POSITION.swapValidatorDetails(operatorId, fromIndex, validators.exited, validatorCount);\\n```\\n
`reportOutOfOrderValidatorExits` does not updates the heap order
high
When an operator's validator exits without a withdrawal request, the owner can invoke the `reportOutOfOrderValidatorExits` function to increase the `exited` portion of the operator validators. However, this action does not update the heap. Consequently, during subsequent allocation or deallocation processes, the heap m...
update the utilization in the reportOutOfOrderValidatorExits function
Heap can be mixed, withdrawals and deposits can fail, hence I will label this as high.
```\\nfunction getOperatorUtilizationHeapForETH(RioLRTOperatorRegistryStorageV1.StorageV1 storage s)\\n internal\\n view\\n returns (OperatorUtilizationHeap.Data memory heap)\\n {\\n uint8 numActiveOperators = s.activeOperatorCount;\\n if (numActiveOperators == 0) return OperatorUt...
Heap is incorrectly stores the removed operator ID which can lead to division by zero in deposit/withdrawal flow
high
An operator's strategy can be reset by the owner calling `setOperatorStrategyCaps` to "0". This action sets the utilization to "0" and removes the operator from the heap. Consequently, this means that the operator has unwound all its strategy shares and can no longer receive any more deposits. However, due to how the h...
When removing from the heap also remove the last element from the heap.\\nI am not sure of this, but this might work\\n```\\nfunction _remove(Data memory self, uint8 i) internal pure {\\n self.operators[i] = self.operators[--self.count];\\n }\\n```\\n
Core logic broken, withdrawal/deposits can not be performed.
```\\nfunction setOperatorStrategyCap(\\n RioLRTOperatorRegistryStorageV1.StorageV1 storage s,\\n uint8 operatorId,\\n IRioLRTOperatorRegistry.StrategyShareCap memory newShareCap\\n ) internal {\\n .\\n OperatorUtilizationHeap.Data memory utilizationHeap = s.getOperatorUtilizationH...
Ether can stuck when an operators validators are removed due to an user front-running
medium
When a full withdrawal occurs in the EigenPod, the excess amount can remain idle within the EigenPod and can only be swept by calling a function in the delegator contract of a specific operator. However, in cases where the owner removes all validators for emergencies or any other reason, a user can frontrun the transac...
Make an emergency function which owner can scrape the excess eth regardless of `MIN_EXCESS_FULL_WITHDRAWAL_ETH_FOR_SCRAPE`
Owner needs to set the caps again to recover the 1 ether. However, the validators are removed for a reason and adding operators again would probably be not intended since it was a shutdown. Hence, I'll label this as medium.
```\\nif (validatorDetails.cap > 0 && newValidatorCap == 0) {\\n // If there are active deposits, queue the operator for strategy exit.\\n if (activeDeposits > 0) {\\n -> operatorDetails.queueOperatorStrategyExit(operatorId, BEACON_CHAIN_STRATEGY);\\n .\\n ...
A part of ETH rewards can be stolen by sandwiching `claimDelayedWithdrawals()`
medium
Rewards can be stolen by sandwiching the call to EigenLayer::DelayedWithdrawalRouter::claimDelayedWithdrawals().\\nThe protocol handles ETH rewards by sending them to the rewards distributor. There are at least 3 flows that end-up sending funds there:\\nWhen the function RioLRTOperatorDelegator::scrapeNonBeaconChainETH...
When requesting withdrawals via RioLRTCoordinator::requestWithdrawal() don't distribute the rewards received in the current epoch.
Rewards can be stolen by sandwiching the call to EigenLayer::DelayedWithdrawalRouter::claimDelayedWithdrawals(), however this requires a bigger investment in funds the higher the protocol TVL.
```\\nreceive() external payable {\\n (bool success,) = address(rewardDistributor()).call{value: msg.value}('');\\n require(success);\\n}\\n```\\n
The protocol can't receive rewards because of low gas limits on ETH transfers
medium
The hardcoded gas limit of the Asset::transferETH() function, used to transfer ETH in the protocol, is too low and will result unwanted reverts.\\nETH transfers in the protocol are always done via Asset::transferETH(), which performs a low-level call with an hardcoded gas limit of 10_000:\\n```\\n(bool success,) = reci...
Remove the hardcoded `10_000` gas limit in Asset::transferETH(), at least on ETH transfers where the destination is a protocol controlled contract.
The protocol is unable to receive rewards and the funds will be stucked.
```\\n(bool success,) = recipient.call{value: amount, gas: 10_000}('');\\nif (!success) {revert ETH_TRANSFER_FAILED();}\\n```\\n
Stakers can avoid validator penalties
medium
Stakers can frontrun validators penalties and slashing events with a withdrawal request in order to avoid the loss, this is possible if the deposit pool has enough liquidity available.\\nValidators can lose part of their deposit via penalties or slashing events:\\nIn case of penalties Eigenlayer can be notified of the ...
When RioLRTCoordinator::rebalance() is called and penalties or slashing events happened during the epoch being settled, distribute the correct amount of penalties to all the `LRTTokens` withdrawn in the current epoch, including the ones that requested the withdrawal before the drop.
Stakers can avoid validator penalties and slashing events if there's enough liquidity in the deposit pool.
```\\nimport {IRioLRTOperatorRegistry} from 'contracts/interfaces/IRioLRTOperatorRegistry.sol';\\nimport {RioLRTOperatorDelegator} from 'contracts/restaking/RioLRTOperatorDelegator.sol';\\nimport {CredentialsProofs, BeaconWithdrawal} from 'test/utils/beacon-chain/MockBeaconChain.sol';\\n```\\n
All operators can have ETH deposits regardless of the cap setted for them leading to miscalculated TVL
medium
Some operators might not be eligible for using some strategies in the LRT's underlying tokens. However, in default every operator can have ETH deposits which would impact the TVL/Exchange rate of the LRT regardless of they have a cap or not.\\nFirst, let's examine how an operator can have ETH deposit\\nAn operator can ...
put a check on `verifyWithdrawalCredentials` that is not possible to call the function if the operator is not actively participating in the BEACON_CHAIN_STRATEGY.
Miscalculation of total ether holdings of an LRT. Withdrawals can fail because the calculated ether is not existed in the heap but the TVL says there are ether to withdraw from the LRT.
```\\nfunction getTVLForAsset(address asset) public view returns (uint256) {\\n uint256 balance = getTotalBalanceForAsset(asset);\\n if (asset == ETH_ADDRESS) {\\n return balance;\\n }\\n return convertToUnitOfAccountFromAsset(asset, balance);\\n }\\n\\n function getTotalBal...
`requestWithdrawal` doesn't estimate accurately the available shares for withdrawals
medium
The `requestWithdrawal` function inaccurately estimates the available shares for withdrawals by including funds stored in the deposit pool into the already deposited EigenLayer shares. This can potentially lead to blocking withdrawals or users receiving less funds for their shares.\\nFor a user to withdraw funds from t...
There is no straightforward way to handle this issue as the asset held by the deposit pool can't be converted into shares while they were not deposited into EigenLayer. The code should be reviewed to address this issue.
The `requestWithdrawal` function inaccurately estimates the available shares for withdrawals, potentially resulting in blocking withdrawals or users receiving less funds for their shares.
```\\nuint256 availableShares = assetRegistry().convertToSharesFromAsset(asset, assetRegistry().getTotalBalanceForAsset(asset));\\n```\\n
Slashing penalty is unfairly paid by a subset of users if a deficit is accumulated.
medium
If a deficit is accumulated in the EigenPodManager due to slashing when ETH is being withdrawn the slashing payment will be taken from the first cohort to complete a withdrawal.\\nA deficit can happen in `podOwnerShares[podOwner]` in the EigenPodManager in the EigenLayer protocol. This can happen if validators are slas...
A potential solution to deal with this is to check if a deficit exists in `settleEpochFromEigenLayer()`. If it exists functionality has to be added that spreads the cost of the penalty fairly among all LRT holders.
If a deficit is accumulated the first cohort to settle will pay for the entire amount. If they can not cover it fully, they will receive 0 and the following cohort will pay for the rest.
```\\n uint256 balanceBefore = asset.getSelfBalance();\\n\\n address[] memory assets = asset.toArray();\\n bytes32[] memory roots = new bytes32[](queuedWithdrawalCount);\\n\\n IDelegationManager.Withdrawal memory queuedWithdrawal;\\n for (uint256 i; i < queuedWithdrawalCount; ++i) {\\...
ETH withdrawers do not earn yield while waiting for a withdrawal
medium
In the Rio doc we can read the following\\n"Users will continue to earn yield as they wait for their withdrawal request to be processed."\\nThis is not true for withdrawals in ETH since they will simply receive an equivalent to the `sharesOWed` calculated when requesting a withdrawal.\\nWhen `requestWithdrawal()` is ca...
Account for the accumulate rewards during the withdrawal period that belongs to the deposit pool. This can be calculated based on data in DelayedWithdrawalRouter on Eigenlayer.
Since a portion of the staking reward belongs to the LRT holders and since the docs mentions that yield is accumulated while in the queue It is fair to assume that withdrawing users have a proportional claim to the yield.\\nAs shown above this is not true, users withdrawing in ETH do no earn any rewards when withdrawin...
```\\nsharesOwed = convertToSharesFromRestakingTokens(asset, amountIn);\\n```\\n
The sign of delta hedge amount can be reversed by malicious user due to incorrect condition in `FinanceIGDelta.deltaHedgeAmount`
high
When delta hedge amount is calculated after the trade, the final check is to account for sqrt computation error and ensure the exchanged amount of side token doesn't exceed amount of side tokens the vault has. The issue is that this check is incorrect: it compares absolute value of the delta hedge amount, but always se...
The check should be done only when `tokensToSwap` is positive:\\n```\\n // due to sqrt computation error, sideTokens to sell may be very few more than available\\n- if (SignedMath.abs(tokensToSwap) > params.sideTokensAmount) {\\n+ if (tokensToSwap > 0 && SignedMath.abs(tokensToSwap) > params.sideToke...
Malicious user can steal all vault funds, and/or the vault LPs will incur losses higher than uniswap LPs or vault will be unable to payoff the traders due to incorrect hedged amount.\\nProof Of Concept\\nCopy to attack.t.sol:\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.15;\\n\\nimport {Test} f...
```\\n // due to sqrt computation error, sideTokens to sell may be very few more than available\\n if (SignedMath.abs(tokensToSwap) > params.sideTokensAmount) {\\n if (SignedMath.abs(tokensToSwap) - params.sideTokensAmount < params.sideTokensAmount / 10000) {\\n tokensToSwap = SignedMath.revabs(...
Position Manager providing the wrong strike when storing user's position data
medium
When users mint position using `PositionManager`, users can provide strike that want to be used for the trade. However, if the provided strike data is not exactly the same with IG's current strike, the minted position's will be permanently stuck inside the PositionManager's contract.\\nWhen `mint` is called inside `Pos...
When storing user position data inside PositionManager, query IG's current price and use it instead.\\n```\\n function mint(\\n IPositionManager.MintParams calldata params\\n ) external override returns (uint256 tokenId, uint256 premium) {\\n // // rest of code\\n\\n if (params.tokenId == 0) ...
If the provided strike data does not match IG's current strike price, the user's minted position using `PositionManager` will be stuck and cannot be burned. This happens because when burn is called and `position.strike` is provided, it will revert as it cannot find the corresponding positions inside IG contract.\\nThis...
```\\n function mint(\\n IPositionManager.MintParams calldata params\\n ) external override returns (uint256 tokenId, uint256 premium) {\\n IDVP dvp = IDVP(params.dvpAddr);\\n\\n if (params.tokenId != 0) {\\n tokenId = params.tokenId;\\n ManagedPosition storage position ...
Whenever swapPrice > oraclePrice, minting via PositionManager will revert, due to not enough funds being obtained from user.
medium
In `PositionManager::mint()`, `obtainedPremium` is calculated in a different way to the actual premium needed, and this will lead to a revert, denying service to users.\\nIn `PositionManager::mint()`, the PM gets `obtainedPremium` from DVP::premium():\\n```\\n(obtainedPremium, ) = dvp.premium(params.strike, params.noti...
When calculating `obtainedPremium`, consider also using the premium from `swapPrice` if it is greater than the premium calculated from `oraclePrice`.
Whenever `swapPrice > oraclePrice`, minting positions via the PositionManager will revert. This is a denial of service to users and this disruption of core protocol functionality can last extended periods of time.
```\\n(obtainedPremium, ) = dvp.premium(params.strike, params.notionalUp, params.notionalDown);\\n```\\n
Transferring ERC20 Vault tokens to another address and then withdrawing from the vault breaks `totalDeposit` accounting which is tied to deposit addresses
medium
Vault inherits from the ERC20, so it has transfer functions to transfer vault shares. However, `totalDeposit` accounting is tied to addresses of users who deposited with the assumption that the same user will withdraw those shares. This means that any vault tokens transfer and then withdrawal from either user breaks th...
Either disallow transferring of vault shares or track vault assets instead of deposits. Alternatively, re-design the withdrawal system (for example, throw out cumulative deposit calculation and simply calculate total assets and total shares and when withdrawing - reduce `totalDeposit` by the sharesWithdrawn / totalShar...
Important security measure of vault max deposit limit can be bypassed, potentially losing funds for the users when the admin doesn't want to accept large amounts for various reasons (like testing something).\\nIt's possible to lock vault from deposits by inflating the `totalDeposit` without vault having actual assets, ...
```\\ncontract Vault is IVault, ERC20, EpochControls, AccessControl, Pausable {\\n```\\n
PositionManager will revert when trying to return back to user excess of the premium transferred from the user when minting position
medium
`PositionManager.mint` calculates preliminary premium to be paid for buying the option and transfers it from the user. The actual premium paid may differ, and if it's smaller, excess is returned back to user. However, it is returned using the safeTransferFrom:\\n```\\n if (obtainedPremium > premium) {\\n base...
Consider using `safeTransfer` instead of `safeTransferFrom` when transferring token from self.
User is unable to open positions via `PositionManager` in certain situations as all such transactions will revert, breaking important protocol functionality and potentially losing user funds / profit due to failure to open position.
```\\n if (obtainedPremium > premium) {\\n baseToken.safeTransferFrom(address(this), msg.sender, obtainedPremium - premium);\\n }\\n```\\n
FeeManager `receiveFee` and `trackVaultFee` functions allow anyone to call it with user-provided dvp/vault address and add any arbitrary feeAmount to any address, breaking fees accounting and temporarily bricking DVP smart contract
medium
`FeeManager` uses `trackVaultFee` function to account vault fees. The problem is that this function can be called by any smart contract implementing `vault()` function (there are no address or role authentication), thus malicious user can break all vault fees accounting by randomly inflating existing vault's fees, maki...
Consider adding a whitelist of addresses which can call these functions.
Malicious users can break all fee and vault fee accounting by inflating existing vaults or user addresses fees earned without actually paying these fees, making it hard/impossible for admins to determine the actual fees earned from each vault or dvp. Moreover, malicious user can temporarily brick DVP smart contract by ...
```\\n function trackVaultFee(address vault, uint256 feeAmount) external {\\n // Check sender:\\n IDVP dvp = IDVP(msg.sender);\\n if (vault != dvp.vault()) {\\n revert WrongVault();\\n }\\n\\n vaultFeeAmounts[vault] += feeAmount;\\n\\n emit TransferVaultFee(vault,...
Trading out of the money options has delta = 0 which breaks protocol assumptions of traders profit being fully hedged and can result in a loss of funds to LPs
medium
Smilee protocol fully hedges all traders pnl by re-balancing the vault between base and side tokens after each trade. This is the assumption about this from the docs:\\nIn the other words, any profit for traders is taken from the hedge and not from the vault Liquidity Providers funds. LP payoff must be at least the und...
The issue seems to be from the approximation of the delta for OTM options. Statistically, long-term, the issue shouldn't be a problem as the long-term expectation is positive for the LPs profit due to it. However, short-term, the traders profit can create issues, and this seems to be the protocol's core assumption. Pos...
In some specific trading conditions (IG Bear liquidity used close to 100% if price < strike, or IG Bull liquidity used close to 100% if price > strike), all or most of the traders pnl is not hedged and thus becomes loss or profit of the LPs, breaking the core protocol assumptions about hedging and in extreme cases can ...
```\\n /**\\n Δ_bull = (1 / θ) * F\\n F = {\\n@@@ * 0 if (S < K)\\n * (1 - √(K / Kb)) / K if (S > Kb)\\n * 1 / K - 1 / √(S * K) if (K < S < Kb)\\n }\\n */\\n function bullDelta(uint256 k, uint256 kB, uint256 s, uint256 theta) internal pu...
If the vault's side token balance is 0 or a tiny amount, then most if not all IG Bear trades will revert due to incorrect check of computation error during delta hedge amount calculation
medium
When delta hedge amount is calculated in `FinanceIGDelta.deltaHedgeAmount`, the last step is to verify that delta hedge amount to sell is slightly more than vault's side token due to computation error. The check is the following:\\n```\\n if (SignedMath.abs(tokensToSwap) > params.sideTokensAmount) {\\n if (Si...
Possibly check both relative (sideToken / 10000) and absolute (e.g. 1000 or side token UNIT / 10000) value. Alternatively, always limit side token to sell amount to max of side token balance when hedging (but needs additional research if that might create issues).
Almost all IG Bear trades will revert in certain situations, leading to core protocol function being unavailable and potentially loss of funds to the users who expected to do these trades.\\nProof Of Concept\\nCopy to attack.t.sol:\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.15;\\n\\nimport {T...
```\\n if (SignedMath.abs(tokensToSwap) > params.sideTokensAmount) {\\n if (SignedMath.abs(tokensToSwap) - params.sideTokensAmount < params.sideTokensAmount / 10000) {\\n tokensToSwap = SignedMath.revabs(params.sideTokensAmount, true);\\n }\\n }\\n```\\n
Mint and sales can be dossed due to lack of safeApprove to 0
medium
The lack of approval to 0 to the dvp contract, and the fee managers during DVP mints and sales will cause that subsequent transactions involving approval of these contracts to spend the basetoken will fail, breaking their functionality.\\nWhen DVPs are to be minted and sold through the PositionManager, the `mint` and `...
Approve first to 0;\\nUpdate the OpenZeppelin version to the latest and use the `forceApprove` functions instead;\\nRefactor the functions to allow for direct transfer of base tokens to the DVP and FeeManager contracts directly.
This causes that after the first approval for the baseToken has been given, subsequent approvals will fail causing the functions to fail.
```\\n function safeApprove(\\n IERC20 token,\\n address spender,\\n uint256 value\\n ) internal {\\n // safeApprove should only be called when setting an initial allowance,\\n // or when resetting it to zero. To increase and decrease it, use\\n // 'safeIncreaseAllowance'...
User wrapped tokens get stuck in master router because of incorrect calculation
medium
Swapping exact tokens for ETH swaps underlying token amount, not wrapped token amount and this causes wrapped tokens to get stuck in the contract.\\nIn the protocol the `JalaMasterRouter` is used to swap tokens with less than 18 decimals. It is achieved by wrapping the underlying tokens and interacting with the `JalaRo...
In `JalaMasterRouter::swapExactTokensForETH()` multiply the `amountIn` by decimal off set of the token:\\n```\\n function swapExactTokensForETH(\\n address originTokenAddress,\\n uint256 amountIn,\\n uint256 amountOutMin,\\n address[] calldata path,\\n address to,\\n uint256...
User wrapped tokens get stuck in router contract. The can be stolen by someone performing a `swapExactTokensForTokens()` because it uses the whole balance of the contract when swapping: `IERC20(wrappedTokenIn).balanceOf(address(this))`\\n```\\n amounts = IJalaRouter02(router).swapExactTokensForTokens(\\n ...
```\\n function testswapExactTokensForETHStuckTokens() public {\\n address wrappedTokenA = IChilizWrapperFactory(wrapperFactory).wrappedTokenFor(address(tokenA));\\n\\n tokenA.approve(address(wrapperFactory), type(uint256).max);\\n wrapperFactory.wrap(address(this), address(tokenA), 100);\\n\\n ...
JalaPair potential permanent DoS due to overflow
medium
In the `JalaPair::_update` function, overflow is intentionally desired in the calculations for `timeElapsed` and `priceCumulative`. This is forked from the UniswapV2 source code, and it's meant and known to overflow. UniswapV2 was developed using Solidity 0.6.6, where arithmetic operations overflow and underflow by def...
Use the `unchecked` block to ensure everything overflows as expected
This issue could potentially lead to permanent denial of service for a pool. All the core functionalities such as `mint`, `burn`, or `swap` would be broken. Consequently, all funds would be locked within the contract.\\nI think issue with High impact and a Low probability (merely due to the extended timeframe for the e...
```\\nuint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired\\nif (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {\\n // * never overflows, and + overflow is desired\\n price0CumulativeLast += uint256(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;\\n price1Cumulat...
Fees aren't distributed properly for positions with multiple lenders, causing loss of funds for lenders
high
Fees distributed are calculated according to a lender's amount lent divided by the total amount lent, which causes more recent lenders to steal fees from older lenders.\\n```\\n uint256 feesAmt = FullMath.mulDiv(feesOwed, cache.holdTokenDebt, borrowedAmount); //fees owed multiplied by the individual amou...
A potential fix is to harvest fees in the borrow() function; the scenario above will no longer be possible.
Loss of funds for lenders, potential for borrowers to steal fees.
```\\n uint256 feesAmt = FullMath.mulDiv(feesOwed, cache.holdTokenDebt, borrowedAmount); //fees owed multiplied by the individual amount lent, divided by the total amount lent\\n // rest of code\\n loansFeesInfo[creditor][cache.holdToken] += feesAmt;\\n harves...
Entrance fees are distributed wrongly in loans with multiple lenders
medium
Entrance fees are distributed improperly, some lenders are likely to lose some portion of their entrance fees. Also, calling `updateHoldTokenEntranceFee()` can cause improper entrance fee distribution in loans with multiple lenders.\\nNote that entrance fees are added to the borrower's `feesOwed` when borrowing:\\n```\...
Could add the entrance fee directly to the lender's fees balance instead of adding it to feesOwed, and then track the entrance fee in the loan data to be used in min fee enforcement calculations.
Lenders are likely to lose entrance fees.
```\\n borrowing.feesOwed += entranceFee;\\n```\\n
A borrower eligible for liquidation can pay an improperly large amount of fees, and may be unfairly liquidated
medium
If a borrower is partially liquidated and then increases the collateral balance to avoid further liquidation, they will pay an improperly large amount of fees and can be unfairly liquidated.\\n```\\n (collateralBalance, currentFees) = _calculateCollateralBalance(\\n borrowing.borrowedAmount,\\...
Update `accLoanRatePerSeconds` for incomplete emergency liquidations.
The borrower may pay too many fees, and it's also possible to unfairly liquidate the position.
```\\n (collateralBalance, currentFees) = _calculateCollateralBalance(\\n borrowing.borrowedAmount,\\n borrowing.accLoanRatePerSeconds,\\n borrowing.dailyRateCollateralBalance,\\n accLoanRatePerSeconds\\n );\\n // rest of code\...
All yield could be drained if users set any ````> 0```` allowance to others
high
`Tranche.redeemWithYT()` is not well implemented, all yield could be drained if users set any `> 0` allowance to others.\\nThe issue arises on L283, all `accruedInTarget` is sent out, this will not work while users have allowances to others. Let's say, alice has `1000 YT` (yield token) which has generated `100 TT` (tar...
```\\ndiff // Remove the line below\\n// Remove the line below\\ngit a/napier// Remove the line below\\nv1/src/Tranche.sol b/napier// Remove the line below\\nv1/src/Tranche.sol\\nindex 62d9562..65db5c6 100644\\n// Remove the line below\\n// Remove the line below\\n// Remove the line below\\n a/napier// Remove the line ...
Users lost all unclaimed and unaccrued yield
```\\nFile: src\\Tranche.sol\\n function redeemWithYT(address from, address to, uint256 pyAmount) external nonReentrant returns (uint256) {\\n// rest of code\\n accruedInTarget += _computeAccruedInterestInTarget(\\n _gscales.maxscale,\\n _lscale,\\n// rest of code\\n _yt.balan...
LP Tokens always valued at 3 PTs
high
LP Tokens are always valued at 3 PTs. As a result, users of the AMM pool might receive fewer assets/PTs than expected. The AMM pool might be unfairly arbitraged, resulting in a loss for the pool's LPs.\\nThe Napier AMM pool facilitates trade between underlying assets and PTs. The PTs in the pool are represented by the ...
Naiper and Pendle share the same core math for their AMM pool.\\nIn Pendle, the AMM stores the PTs and SY (Standard Yield Token). When performing any operation (e.g., deposit, swap), the SY will be converted to the underlying assets based on SY's current rate before performing any math operation. If it is a SY (wstETH)...
Users of the AMM pool might receive fewer assets/PTs than expected. The AMM pool might be unfairly arbitraged, resulting in a loss for the pool's LPs.
```\\nFile: PoolMath.sol\\n int256 internal constant N_COINS = 3;\\n..SNIP..\\n function swapExactBaseLpTokenForUnderlying(PoolState memory pool, uint256 exactBaseLptIn)\\n internal\\n..SNIP..\\n // Note: Here we are multiplying by N_COINS because the swap formula is defined in terms of the amou...
Victim's fund can be stolen due to rounding error and exchange rate manipulation
high
Victim's funds can be stolen by malicious users by exploiting the rounding error and through exchange rate manipulation.\\nThe LST Adaptor attempts to guard against the well-known vault inflation attack by reverting the TX when the amount of shares minted is rounded down to zero in Line 78 below.\\n```\\nFile: BaseLSTA...
Following are some of the measures that could help to prevent such an attack:\\nMint a certain amount of shares to zero address (dead address) during contract deployment (similar to what has been implemented in Uniswap V2)\\nAvoid using the `balanceOf` so that malicious users cannot transfer directly to the contract to...
Loss of assets for the victim.
```\\nFile: BaseLSTAdapter.sol\\n function prefundedDeposit() external nonReentrant returns (uint256, uint256) {\\n uint256 bufferEthCache = bufferEth; // cache storage reads\\n uint256 queueEthCache = withdrawalQueueEth; // cache storage reads\\n uint256 assets = IWETH9(WETH).balanceOf(address(...
Anyone can convert someone's unclaimed yield to PT + YT
medium
Anyone can convert someone's unclaimed yield to PT + YT, leading to a loss of assets for the victim.\\nAssume that Alice has accumulated 100 Target Tokens in her account's unclaimed yields. She is only interested in holding the Target token (e.g., she is might be long Target token). She intends to collect those Target ...
Consider not allowing anyone to issue PY+YT on behalf of someone's account.
Loss of assets for the victim.
```\\nFile: Tranche.sol\\n function issue(\\n address to,\\n uint256 underlyingAmount\\n ) external nonReentrant whenNotPaused notExpired returns (uint256 issued) {\\n..SNIP..\\n lscales[to] = _maxscale;\\n delete unclaimedYields[to];\\n\\n uint256 yBal = _yt.balanceOf(to);\\n ...
`withdraw` function does not comply with ERC5095
medium
The `withdraw` function of Tranche/PT does not comply with ERC5095 as it does not return the exact amount of underlying assets requested by the users.\\nQ: Is the code/contract expected to comply with any EIPs? Are there specific assumptions around adhering to those EIPs that Watsons should be aware of? EIP20 and IERC5...
Update the `withdraw` function to send exactly `underlyingAmount` number of underlying tokens to the caller so that the Tranche will be aligned with the ERC5095 specification.
The tranche/PT does not align with the ERC5095 specification.
```\\nFile: Tranche.sol\\n function withdraw(\\n uint256 underlyingAmount,\\n address to,\\n address from\\n ) external override nonReentrant expired returns (uint256) {\\n GlobalScales memory _gscales = gscales;\\n uint256 cscale = _updateGlobalScalesCache(_gscales);\\n\\n ...