Thunder Loan

AI First Flight #7
Beginner FriendlyFoundryDeFiOracle
EXP
View results
Submission Details
Severity: high
Valid

[H-03] Erroneous updateExchangeRate on deposit() Causes Protocol Insolvency and Locks LP Funds

Description

In ThunderLoan.sol:153-154, deposit() calls assetToken.updateExchangeRate(calculatedFee):

// File: src/protocol/ThunderLoan.sol                                                   
    function deposit(IERC20 token, uint256 amount) external revertIfZero(amount)        

revertIfNotAllowedToken(token) {
AssetToken assetToken = s_tokenToAssetToken[token];
uint256 exchangeRate = assetToken.getExchangeRate();
uint256 mintAmount = (amount * assetToken.EXCHANGE_RATE_PRECISION()) /
exchangeRate;
emit Deposit(msg.sender, token, amount);
assetToken.mint(msg.sender, mintAmount);
@> uint256 calculatedFee = getCalculatedFee(token, amount);
@> assetToken.updateExchangeRate(calculatedFee);
token.safeTransferFrom(msg.sender, address(assetToken), amount);
}

However, a depositor only transfers amount of the underlying token—no fee is paid into the
protocol during deposit. Invoking updateExchangeRate(calculatedFee) inflates
s_exchangeRate without adding corresponding backing assets to the contract.

When liquidity providers attempt to redeem their AssetToken shares via redeem():

uint256 amountUnderlying = (amountOfAssetToken * exchangeRate) / assetToken.            

EXCHANGE_RATE_PRECISION();
assetToken.transferUnderlyingTo(msg.sender, amountUnderlying);

The contract does not hold sufficient tokens to satisfy the inflated redemption amount. If
there is a sole liquidity provider, they can never redeem their full balance and their
funds become permanently trapped. If multiple providers exist, early redeemers siphon
other users' capital until the pool is insolvent.

Risk

Likelihood: High

Impact: High

Proof of Concept

function test_WRRE_DepositInflatesExchangeRateCausingInsolvency() public {              
    ERC20Mock cleanToken = new ERC20Mock();                                             
    mockPoolFactory.createPool(address(cleanToken));                                    
                                                                                        
    vm.prank(thunderLoan.owner());                                                      
    AssetToken cleanAsset = thunderLoan.setAllowedToken(cleanToken, true);              
                                                                                        
    address soleLP = address(789);                                                      
    uint256 depositAmt = 100e18;                                                        
    cleanToken.mint(soleLP, depositAmt);                                                
                                                                                        
    vm.startPrank(soleLP);                                                              
    cleanToken.approve(address(thunderLoan), depositAmt);                               
    thunderLoan.deposit(cleanToken, depositAmt);                                        
                                                                                        
    // Exchange rate artificially inflated from 1e18 to 1.003e18 without any fee        

received
assertEq(cleanAsset.getExchangeRate(), 1003000000000000000);

    // LP attempts to redeem their full deposit                                         
    uint256 lpShares = cleanAsset.balanceOf(soleLP);                                    
    // Reverts with ERC20 transfer amount exceeds balance because contract only holds   

100e18 tokens
vm.expectRevert();
thunderLoan.redeem(cleanToken, lpShares);
vm.stopPrank();
}

Recommended Mitigation

Remove the updateExchangeRate invocation from deposit(). The exchange rate should only be
updated when actual flash loan fees are collected:

--- a/src/protocol/ThunderLoan.sol                                                      
+++ b/src/protocol/ThunderLoan.sol                                                      
@@ -150,8 +150,6 @@ contract ThunderLoan is Initializable, OwnableUpgradeable,          

UUPSUpgradeable, Ora
uint256 mintAmount = (amount * assetToken.EXCHANGE_RATE_PRECISION()) /
exchangeRate;
emit Deposit(msg.sender, token, amount);
assetToken.mint(msg.sender, mintAmount);
- uint256 calculatedFee = getCalculatedFee(token, amount);
- assetToken.updateExchangeRate(calculatedFee);
token.safeTransferFrom(msg.sender, address(assetToken), amount);

Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge about 2 hours ago
Submission Judgement Published
Validated
Assigned finding tags:

[H-02] Updating exchange rate on token deposit will inflate asset token's exchange rate faster than expected

# Summary Exchange rate for asset token is updated on deposit. This means users can deposit (which will increase exchange rate), and then immediately withdraw more underlying tokens than they deposited. # Details Per documentation: > Liquidity providers can deposit assets into ThunderLoan and be given AssetTokens in return. **These AssetTokens gain interest over time depending on how often people take out flash loans!** Asset tokens gain interest when people take out flash loans with the underlying tokens. In current version of ThunderLoan, exchange rate is also updated when user deposits underlying tokens. This does not match with documentation and will end up causing exchange rate to increase on deposit. This will allow anyone who deposits to immediately withdraw and get more tokens back than they deposited. Underlying of any asset token can be completely drained in this manner. # Filename `src/protocol/ThunderLoan.sol` # Permalinks https://github.com/Cyfrin/2023-11-Thunder-Loan/blob/8539c83865eb0d6149e4d70f37a35d9e72ac7404/src/protocol/ThunderLoan.sol#L153-L154 # Impact Users can deposit and immediately withdraw more funds. Since exchange rate is increased on deposit, they will withdraw more funds then they deposited without any flash loans being taken at all. # Recommendations It is recommended to not update exchange rate on deposits and updated it only when flash loans are taken, as per documentation. ```diff function deposit(IERC20 token, uint256 amount) external revertIfZero(amount) revertIfNotAllowedToken(token) { AssetToken assetToken = s_tokenToAssetToken[token]; uint256 exchangeRate = assetToken.getExchangeRate(); uint256 mintAmount = (amount * assetToken.EXCHANGE_RATE_PRECISION()) / exchangeRate; emit Deposit(msg.sender, token, amount); assetToken.mint(msg.sender, mintAmount); - uint256 calculatedFee = getCalculatedFee(token, amount); - assetToken.updateExchangeRate(calculatedFee); token.safeTransferFrom(msg.sender, address(assetToken), amount); } ``` # POC ```solidity function testExchangeRateUpdatedOnDeposit() public setAllowedToken { tokenA.mint(liquidityProvider, AMOUNT); tokenA.mint(user, AMOUNT); // deposit some tokenA into ThunderLoan vm.startPrank(liquidityProvider); tokenA.approve(address(thunderLoan), AMOUNT); thunderLoan.deposit(tokenA, AMOUNT); vm.stopPrank(); // another user also makes a deposit vm.startPrank(user); tokenA.approve(address(thunderLoan), AMOUNT); thunderLoan.deposit(tokenA, AMOUNT); vm.stopPrank(); AssetToken assetToken = thunderLoan.getAssetFromToken(tokenA); // after a deposit, asset token's exchange rate has aleady increased // this is only supposed to happen when users take flash loans with underlying assertGt(assetToken.getExchangeRate(), 1 * assetToken.EXCHANGE_RATE_PRECISION()); // now liquidityProvider withdraws and gets more back because exchange // rate is increased but no flash loans were taken out yet // repeatedly doing this could drain all underlying for any asset token vm.startPrank(liquidityProvider); thunderLoan.redeem(tokenA, assetToken.balanceOf(liquidityProvider)); vm.stopPrank(); assertGt(tokenA.balanceOf(liquidityProvider), AMOUNT); } ```

Support

FAQs

Can't find an answer? Chat with us on Discord, Twitter or Linkedin.

Give us feedback!