Thunder Loan

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

deposit() charges a phantom fee on plain deposits with no matching inflow, inflating exchangeRate and causing later LPs to lose funds

Root + Impact

Description

  • ThunderLoan.deposit() mints shares to the depositor at the current exchangeRate, then additionally calls getCalculatedFee(token, amount) and assetToken.updateExchangeRate(calculatedFee) to credit a "fee" into the exchange rate - but deposit() only ever transfers in amount. Nobody ever transfers the extra fee tokens into the AssetToken contract for a plain deposit.

  • AssetToken.updateExchangeRate()'s formula newRate = oldRate * (totalSupply + fee) / totalSupply assumes the fee portion of the numerator is backed by real assets. That assumption only holds in the flashloan() path, where the fee must arrive in the same transaction or the whole call reverts via the ending-balance check. In the deposit() path this precondition does not hold, so exchangeRate is inflated with nothing backing it.

  • The result: totalSupply * exchangeRate (what the protocol owes all LPs) systematically drifts above token.balanceOf(address(assetToken)) (what the protocol actually holds) - with zero attacker and zero oracle manipulation required. Two ordinary, honest deposit() calls back-to-back already produce a real deficit, and an earlier LP who redeems first extracts more than they put in, leaving a later, fully honest LP unable to redeem the full value of their own shares (redeem() reverts - real fund loss / DoS, not just a bad number).

  • This is also independently weaponizable: since calculatedFee is derived from OracleUpgradeable.getPriceInWeth()'s live spot price (manipulable in a single transaction via MockTSwapPool-style AMMs), an attacker can spike the price, deposit to mint a hugely inflated exchange-rate bump, restore the price, then redeem a small fraction of their new shares for far more underlying than they put in - directly at the expense of existing LPs' principal.

  • Confirms this is a known-bad pattern: src/upgradedProtocol/ThunderLoanUpgraded.sol::deposit() has already removed the getCalculatedFee/updateExchangeRate calls entirely, while flashloan()/repay() logic is otherwise unchanged - strong evidence the fee-on-deposit call was recognized internally as wrong.

function deposit(IERC20 token, uint256 amount) external revertIfZero(amount) revertIfNotAllowedToken(token) {
AssetToken assetToken = s_tokenToAssetToken[token];
uint256 calculatedFee = getCalculatedFee(token, amount);
uint256 mintAmount = (amount * assetToken.EXCHANGE_RATE_PRECISION()) / assetToken.getExchangeRate();
emit Deposit(msg.sender, token, amount);
assetToken.mint(msg.sender, mintAmount);
@> assetToken.updateExchangeRate(calculatedFee);
token.safeTransferFrom(msg.sender, address(assetToken), amount);
}
// AssetToken.sol
function updateExchangeRate(uint256 fee) external onlyThunderLoan {
uint256 newExchangeRate =
@> s_exchangeRate * (totalSupply() + fee) / totalSupply();
if (newExchangeRate <= s_exchangeRate) {
revert AssetToken__ExhangeRateCanOnlyIncrease(s_exchangeRate, newExchangeRate);
}
s_exchangeRate = newExchangeRate;
emit ExchangeRateUpdated(s_exchangeRate);
}

Risk

Likelihood:

  • Reason 1 // No attacker, no timing, and no oracle manipulation is needed - two consecutive, fully honest deposit() calls at a constant, non-manipulated price already produce the deficit, as shown in the PoC below.

  • Reason 2 // The deficit is monotonic and compounds with every subsequent deposit, so it is not a one-off edge case but a systemic, guaranteed drift toward insolvency the longer the pool is used normally.

Impact:

  • Impact 1 // Honest LPs' redeemable principal is put at direct risk: a later, fully honest depositor's redeem() reverts because the vault's real balance no longer covers what the exchange rate says they are owed.

  • Impact 2 // Combined with oracle-price manipulation, an attacker can weaponize the same bug to extract real underlying value from existing LPs' principal in a single transaction.

Proof of Concept

Ran with forge test --match-path "test/PoC_1.t.sol" -vvv: [PASS] test_PassiveDriftCausesInsolvency() (gas: 785549). Key logs: after LP_1 deposits 1000 tokenA, real balance = 1000e18 but owed-to-LPs already = 1003e18 (a 3e18 phantom fee credited from a single honest deposit). After LP_2 also deposits 1000 tokenA, real balance = 2000e18 but owed-to-LPs = 2006.009e18 (deficit 6.009e18) - and the oracle price (MockTSwapPool) never changed the entire time. LP_1 then redeems first and receives 1004.5e18 (more than their 1000e18 principal). LP_2, a purely honest, later depositor, is entitled to 1001.5e18 but the vault only has 995.5e18 left - LP_2's redeem() call reverts (vm.expectRevert() assertion passes), proving a real fund-loss/DoS, not a cosmetic accounting artifact. Full regression suite: 19/19 passing, no regressions.

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import { Test, console } from "forge-std/Test.sol";
import { BaseTest, ThunderLoan } from "./unit/BaseTest.t.sol";
import { AssetToken } from "../src/protocol/AssetToken.sol";
contract PoC_1 is BaseTest {
address LP_1 = makeAddr("LP_1");
address LP_2 = makeAddr("LP_2");
uint256 constant LP1_DEPOSIT = 1000e18;
uint256 constant LP2_DEPOSIT = 1000e18;
AssetToken assetToken;
function setUp() public override {
super.setUp();
assetToken = thunderLoan.setAllowedToken(tokenA, true);
}
function test_PassiveDriftCausesInsolvency() public {
tokenA.mint(LP_1, LP1_DEPOSIT);
vm.startPrank(LP_1);
tokenA.approve(address(thunderLoan), LP1_DEPOSIT);
thunderLoan.deposit(tokenA, LP1_DEPOSIT);
vm.stopPrank();
uint256 realBalanceAfterLP1 = tokenA.balanceOf(address(assetToken));
assertEq(realBalanceAfterLP1, LP1_DEPOSIT, "real balance should equal LP1's deposit only");
uint256 owedAfterLP1 = (assetToken.totalSupply() * assetToken.getExchangeRate()) / assetToken.EXCHANGE_RATE_PRECISION();
assertGt(owedAfterLP1, realBalanceAfterLP1, "protocol already owes more than it holds after a single honest deposit");
tokenA.mint(LP_2, LP2_DEPOSIT);
vm.startPrank(LP_2);
tokenA.approve(address(thunderLoan), LP2_DEPOSIT);
thunderLoan.deposit(tokenA, LP2_DEPOSIT);
vm.stopPrank();
uint256 realBalanceAfterLP2 = tokenA.balanceOf(address(assetToken));
uint256 owedAfterLP2 = (assetToken.totalSupply() * assetToken.getExchangeRate()) / assetToken.EXCHANGE_RATE_PRECISION();
assertEq(realBalanceAfterLP2, LP1_DEPOSIT + LP2_DEPOSIT, "real balance is just the sum of deposits");
assertGt(owedAfterLP2, realBalanceAfterLP2, "deficit persists/grows with each honest deposit");
uint256 lp1Shares = assetToken.balanceOf(LP_1);
vm.prank(LP_1);
thunderLoan.redeem(tokenA, lp1Shares);
assertGt(tokenA.balanceOf(LP_1), LP1_DEPOSIT, "LP1 extracts more than it ever deposited");
uint256 lp2Shares = assetToken.balanceOf(LP_2);
uint256 remainingRealBalance = tokenA.balanceOf(address(assetToken));
uint256 lp2Entitlement = (lp2Shares * assetToken.getExchangeRate()) / assetToken.EXCHANGE_RATE_PRECISION();
assertGt(lp2Entitlement, remainingRealBalance, "LP2 is owed more than what remains in the vault");
vm.prank(LP_2);
vm.expectRevert();
thunderLoan.redeem(tokenA, lp2Shares);
}
}

Recommended Mitigation

function deposit(IERC20 token, uint256 amount) external revertIfZero(amount) revertIfNotAllowedToken(token) {
AssetToken assetToken = s_tokenToAssetToken[token];
- uint256 calculatedFee = getCalculatedFee(token, amount);
uint256 mintAmount = (amount * assetToken.EXCHANGE_RATE_PRECISION()) / assetToken.getExchangeRate();
emit Deposit(msg.sender, token, amount);
assetToken.mint(msg.sender, mintAmount);
- assetToken.updateExchangeRate(calculatedFee);
token.safeTransferFrom(msg.sender, address(assetToken), amount);
}

Remove the getCalculatedFee/updateExchangeRate calls from deposit() entirely - deposits should mint shares 1:1 at the current exchange rate with no fee credited, matching what ThunderLoanUpgraded.sol::deposit() already does. updateExchangeRate should only ever be invoked from a path where the extra funds are guaranteed to have arrived in the same transaction (i.e. inside flashloan(), after the ending-balance check passes). Add an invariant test asserting assetToken.totalSupply() * assetToken.getExchangeRate() / EXCHANGE_RATE_PRECISION() <= token.balanceOf(address(assetToken)) holds after every state-changing call, as a CI guard against reintroducing this class of bug.

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!