Skip to content
Business logic Audit finding Advanced

Reserving a listing checkpoints the collection's `compoundFactor` at an intermediary higher compound factor

When a listing is reserved, the collection's compoundFactor is checkpointed while the CollectionToken total supply is temporarily reduced, leading to an inflated utilization rate and a higher interest rate for the new protected listing. This causes borrowers to accrue more interest than they should.

Sentryx Follow

Originally disclosed on Sherlock

Source: https://github.com/sherlock-audit/2024-08-flayer-judging/issues/533

Found by

Sentryx

Summary

When a listing is reserved (Listings#reserve()) there are multiple CollectionToken operations that affect its totalSupply that take place in the following order: transfer → transfer → burn → mint → transfer → burn. After the function ends execution the totalSupply of the CollectionToken itself remains unchanged compared to before the call to the function, but in the middle of its execution a protected listing is created and its compound factor is checkpointed at an intermediary state of the CollectionToken's total supply (between the first burn and the mint) that will later affect the rate of interest accrual on the loan itself in harm to all borrowers of NFTs in that collection causing them to actually accrue more interest on the loan.

Root Cause

To be able to understand the issue, we must inspect what CollectionToken operations are performed throughout the execution of the reserve() function and at which point exactly the protected listing's compoundFactor is checkpointed.

(Will comment out the irrelevant parts of the function for brevity) https://github.com/sherlock-audit/2024-08-flayer/blob/main/flayer/src/contracts/Listings.sol#L690-L759

Solidity
    function reserve(address _collection, uint _tokenId, uint _collateral) public nonReentrant lockerNotPaused {
        // ...
        
        if (oldListing.owner != address(0)) {
            // We can process a tax refund for the existing listing if it isn't a liquidation
            if (!_isLiquidation[_collection][_tokenId]) {
                // 1st transfer
→               (uint _fees,) = _resolveListingTax(oldListing, _collection, true);
                if (_fees != 0) {
                    emit ListingFeeCaptured(_collection, _tokenId, _fees);
                }
            }
            
            // ...
            
            if (listingPrice > listingFloorPrice) {
                unchecked {
                    // 2nd transfer
→                   collectionToken.transferFrom(msg.sender, oldListing.owner, listingPrice - listingFloorPrice);
                }
            }
            
            // ...
        }

        // 1st burn
→       collectionToken.burnFrom(msg.sender, _collateral * 10 ** collectionToken.denomination());

        // ...

        // the protected listing is recorded in storage with the just-checkpointed compoundFactor
        // then: mint + transfer
→       protectedListings.createListings(createProtectedListing);

        // 2nd burn
→       collectionToken.burn((1 ether - _collateral) * 10 ** collectionToken.denomination());

        // ...
    }

Due to the loan's compoundFactor being checkpointed before the second burn of 1 ether - _collateral CollectionTokens (and before listingCount[listing.collection] is incremented) , the totalSupply will be temporarily decreased which will make the collection's utilization ratio go up a notch due to the way it's derived and this will eventually be reflected in the checkpointed compoundFactor for the current block and respectively for the loan as well.

https://github.com/sherlock-audit/2024-08-flayer/blob/main/flayer/src/contracts/ProtectedListings.sol#L117-L156

Solidity
    function createListings(CreateListing[] calldata _createListings) public nonReentrant lockerNotPaused {
        // ...
        
        for (uint i; i < _createListings.length; ++i) {
            // ...
            
            if (checkpointIndex == 0) {
                // @audit Checkpoint the temporarily altered `compoundFactor` due to the temporary
                // change in the CollectionToken's `totalSupply`.
→               checkpointIndex = _createCheckpoint(listing.collection);
                assembly { tstore(checkpointKey, checkpointIndex) }
            }

            // ...
            
            // @audit Store the listing with a pointer to the index of the inacurate checkpoint above
→           tokensReceived = _mapListings(listing, tokensIdsLength, checkpointIndex) * 10 ** locker.collectionToken(listing.collection).denomination();

            // Register our listing type
            unchecked {
                listingCount[listing.collection] += tokensIdsLength;
            }

            // ...
        }
    }

https://github.com/sherlock-audit/2024-08-flayer/blob/main/flayer/src/contracts/ProtectedListings.sol#L530-L571

Solidity
    function _createCheckpoint(address _collection) internal returns (uint index_) {
→       Checkpoint memory checkpoint = _currentCheckpoint(_collection);

        // ...
        
        collectionCheckpoints[_collection].push(checkpoint);
    }

_currentCheckpoint() will fetch the current utilization ratio which is temporarily higher and will calculate the current checkpoint's compoundedFactor with it (which the newly created loan will reference thereafter).

https://github.com/sherlock-audit/2024-08-flayer/blob/main/flayer/src/contracts/ProtectedListings.sol#L580-L596

Solidity
    function _currentCheckpoint(address _collection) internal view returns (Checkpoint memory checkpoint_) {
        // ...
→       (, uint _utilizationRate) = utilizationRate(_collection);

        // ...
        
        checkpoint_ = Checkpoint({
→           compoundedFactor: locker.taxCalculator().calculateCompoundedFactor({
                _previousCompoundedFactor: previousCheckpoint.compoundedFactor,
                _utilizationRate: _utilizationRate,
                _timePeriod: block.timestamp - previousCheckpoint.timestamp
            }),
            timestamp: block.timestamp
        });
    }

https://github.com/sherlock-audit/2024-08-flayer/blob/main/flayer/src/contracts/ProtectedListings.sol#L261-L276

Solidity
    function utilizationRate(address _collection) public view virtual returns (uint listingsOfType_, uint utilizationRate_) {
        listingsOfType_ = listingCount[_collection];
        // ...
        if (listingsOfType_ != 0) {
            // ...
→           uint totalSupply = collectionToken.totalSupply();
            if (totalSupply != 0) {
→               utilizationRate_ = (listingsOfType_ * 1e36 * 10 ** collectionToken.denomination()) / totalSupply;
            }
        }
    }

Internal pre-conditions

None

External pre-conditions

None

Attack Path

No attack required.

Impact

Knowing how a collection's utilization rate is calculated we can clearly see the impact it'll have on the checkpointed compounded factor for a block:

$utilizationRate = \dfrac{collection\ protected\ listings\ count\ *\ 1e36\ *\ 10^{denomination}}{CT\ total\ supply}$

The less CollectionToken (CT) total supply, the higher the utilization rate for a constant collection's protected listings count. The higher the utilization rate, the higher the compoundedFactor will be for the current checkpoint and for the protected position created (the loan).

$compoundedFactor = \dfrac{previousCompoundFactor\ *\ (1e18 + (perSecondRate\ / 1000 * \_timePeriod))}{1e18}$ Where: $perSecondRate = \dfrac{interestRate * 1e18}{365 * 24 * 60 * 60}$

$interestRate = 200 + \dfrac{utilizationRate * 600}{0.8e18}$ – When utilizationRate ≤ 0.8e18 (UTILIZATION_KINK) OR $interestRate = (\dfrac{(utilizationRate - 200) * (100 - 8)}{1e18 - 200} + 8) * 100$ – When utilizationRate > 0.8e18 (UTILIZATION_KINK)

As a result (and with the help of another issue that has a different root cause and a fix which is submitted separately) the loan will end up checkpointing a temporarily higher compoundedFactor and thus will compound more interest in the future than it's correct to. It's important to know that no matter how many times createCheckpoint() is called after the call to reserve(), the compoundFactor for the current block's checkpoint will remain as. But even without that, there is no guarantee that even if it worked correctly, there'd by any calls that'd record a new checkpoint for that collection.

PoC

  1. Bob lists an NFT for sale. The duration and the floorMultiple of the listing are irrelevant in this case.
  2. John sees the NFT and wants to reserve it, putting up $0.9e18$ amount of CollectionTokens as _collateral.
  3. The _collateral is burned.
  4. The collection's compoundFactor for the current block is checkpointed.

Let's say there is only one protected listing prior to John's call to reserve() and its owner has put up $0.5e18$ CollectionTokens as collateral.

$old\ collection\ token\ total\ supply = 5e18$ $collection\ protected\ listings\ count = 1$

We can now calculate the utilization rate the way it's calculated right now:

$utilizationRate = \dfrac{collection\ protected\ listings\ count\ * 1e36 * 10^{denomination}}{CT\ total\ supply}$

$utilizationRate = \dfrac{1*1e36*10^0}{5e18 - 0.9e18}$ (assuming denomination is 0)

$utilizationRate = \dfrac{1e36}{4.1e18} = 243902439024390243$

We can now proceed to calculate the wrong compounded factor:

$compoundedFactor = \dfrac{previousCompoundFactor\ *\ (1e18 + (perSecondRate\ / 1000 * \_timePeriod))}{1e18}$

Where: $previousCompoundFactor = 1e18$ $interestRate = 200 + \dfrac{utilizationRate * 600}{0.8e18} = 200 + \dfrac{243902439024390243 * 600}{0.8e18} = 382$ (3.82 %)

$perSecondRate = \dfrac{interestRate * 1e18}{365 * 24 * 60 * 60} = \dfrac{382 * 1e18}{31 536 000} = 12113140537798$ $timePeriod = 432000\ (5\ days)$ (last checkpoint was made 5 days ago)

$compoundedFactor = \dfrac{1e18 * (1e18 + (12113140537798 / 1000 * 432000))}{1e18}$

$compoundedFactor = \dfrac{1e18 * 1005232876711984000}{1e18} = 1005232876711984000$ (This will be the final compound factor for the checkpoint for the current block)

The correct utilization rate however, should be calculated with a current collection token total supply of $5e18$ at the time when reserve() is called, which will result in: $utilizationRate = \dfrac{collection\ protected\ listings\ count\ *\ 1e36\ *\ 10^{denomination}}{CT\ total\ supply} = \dfrac{1 * 1e36}{5e18} = 200000000000000000$

The difference with the wrong utilization rate is $43902439024390243$ or ~$0.439e18$ which is ~18% smaller than the wrongly computed utilization rate).

From then on the interest rate will be lower and thus the final and correct compounded factor comes out at $1004794520547808000$ (will not repeat the formulas for brevity) which is around 0.05% smaller than the wrongly recorded compounded factor. The % might not be big but remember that this error will be bigger with the longer time period between the two checkpoints and will be compounding with every call to reserve().

  1. A protected listing is created for the reserved NFT, referencing the current checkpoint.
  2. When the collection's compoundFactor is checkpointed the next time, the final compoundFactor product will be times greater due to the now incremented collection's protected listings count and the increased (back to the value before the reserve was made) total supply of CollectionTokens.

Lets say after another 5 days the createCheckpoint() method is called for that collection without any changes in the CollectionToken total supply or the collection's protected listings count. The math will remain mostly the same with little updates and we will first run the math with the wrongly computed $previousCompoundedFactor$ and then will compare it to the correct one.

$collection\ token\ total\ supply = 5e18$ (because the burned _collateral amount of CollectionTokens has been essentially minted to the ProtectedListings contract hence as we said reserve() does not affect the total supply after the function is executed). $collection\ protected\ listings\ count = 2$ (now 1 more due to the created protected listing) $previousCompoundedFactor = 1005232876711984000$ (the wrong one, as we derived it a bit earlier) $utilizationRate = \dfrac{collection\ protected\ listings\ count\ *\ 1e36\ *\ 10^{denomination}}{CT\ total\ supply}$

$utilizationRate = \dfrac{2 * 1e36 * 10^0}{5e18} = \dfrac{2e36}{5e18} = 0.4e18$

$interestRate = 200 + \dfrac{utilizationRate * 600}{0.8e18} = 200 + \dfrac{0.4e18 * 600}{0.8e18} = 500$ (5 %) $perSecondRate = \dfrac{interestRate * 1e18}{365 * 24 * 60 * 60} = \dfrac{500 * 1e18}{31 536 000} = 15854895991882$ $timePeriod = 432000\ (5\ days)$ (the previous checkpoint was made 5 days ago)

$compoundedFactor = \dfrac{1005232876711984000 * (1e18 + (15854895991882 / 1000 * 432000)}{1e18}$

$compoundedFactor = \dfrac{1005232876711984000 * 1006849315068112000}{1e18} = 1012118033401408964$ or 0.68% accrued interest for that collection for the past 5 days.

Now let's run the math but compounding on top of the correct compound factor:

$compoundedFactor = \dfrac{1004794520547808000 * 1006849315068112000}{1e18} = 1011676674797752473$ or 0.21% of interest should've been accrued for that collection for the past 5 days, instead of 0.68% which in this case is 3 times bigger.

Mitigation

Just burn the _collateral amount after the protected listing is created. This way the compoundedFactor will be calculated and checkpointed properly.

Diff
diff --git a/flayer/src/contracts/Listings.sol b/flayer/src/contracts/Listings.sol
index eb39e7a..c8eac4d 100644
--- a/flayer/src/contracts/Listings.sol
+++ b/flayer/src/contracts/Listings.sol
@@ -725,10 +725,6 @@ contract Listings is IListings, Ownable, ReentrancyGuard, TokenEscrow {
             unchecked { listingCount[_collection] -= 1; }
         }
 
-        // Burn the tokens that the user provided as collateral, as we will have it minted
-        // from {ProtectedListings}.
-        collectionToken.burnFrom(msg.sender, _collateral * 10 ** collectionToken.denomination());
-
         // We can now pull in the tokens from the Locker
         locker.withdrawToken(_collection, _tokenId, address(this));
         IERC721(_collection).approve(address(protectedListings), _tokenId);
@@ -750,6 +746,10 @@ contract Listings is IListings, Ownable, ReentrancyGuard, TokenEscrow {
         // Create our listing, receiving the ERC20 into this contract
         protectedListings.createListings(createProtectedListing);
 
+        // Burn the tokens that the user provided as collateral, as we will have it minted
+        // from {ProtectedListings}.
+        collectionToken.burnFrom(msg.sender, _collateral * 10 ** collectionToken.denomination());
+
         // We should now have received the non-collateral assets, which we will burn in
         // addition to the amount that the user sent us.
         collectionToken.burn((1 ether - _collateral) * 10 ** collectionToken.denomination());

The original report as published on Sherlock, by Sentryx. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

How it worked

Root cause

The compoundFactor is checkpointed before the second burn of CollectionTokens, so the total supply is temporarily lower, inflating the utilization rate used in the checkpoint.

What the attacker needed

None

The fix

The _collateral should be burned after the protected listing is created, so the checkpoint uses the correct total supply.

How it was found

  1. Bob lists an NFT for sale.
  2. John calls reserve() with _collateral of 0.9e18 CollectionTokens.
  3. The _collateral is burned, reducing total supply.
  4. The collection's compoundFactor is checkpointed with the reduced total supply.
  5. A protected listing is created referencing that checkpoint.
  6. Later checkpoints compound on the inflated factor, increasing interest.

Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.

Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.

When you reserve an NFT, the system calculates an interest rate based on how many tokens are locked up. During the reservation, the total number of tokens temporarily drops, making it look like more of the collection is borrowed than it really is. This makes the interest rate higher for that loan, so the borrower pays more interest over time.

What is Business logic?

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.

More by Sentryx

View all

2 more disclosed reports, best first.

More from Flayer

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Business logic flaws

The lesson behind this report.

The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.