Thunder Loan

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

ThunderLoanUpgraded storage layout mismatch corrupts the flash loan fee after upgrade

Root + Impact

Description

ThunderLoan is deployed behind an ERC1967/UUPS proxy, and the README explicitly places the planned upgrade to ThunderLoanUpgraded in scope. During a UUPS upgrade, the proxy keeps the same storage while only the implementation code changes, so the upgraded implementation must preserve the original storage layout.

ThunderLoanUpgraded removes the stored s_feePrecision variable from the original layout and replaces it with a constant. This shifts s_flashLoanFee from slot 204 to slot 203 in the upgraded implementation. As a result, after upgrade, ThunderLoanUpgraded.getFee() reads the old s_feePrecision value (1e18) as the flash-loan fee instead of the actual configured fee (3e15 by default, or any owner-updated value).

// src/protocol/ThunderLoan.sol
mapping(IERC20 => AssetToken) public s_tokenToAssetToken;
// The fee in WEI, it should have 18 decimals. Each flash loan takes a flat fee of the token price.
@> uint256 private s_feePrecision;
@> uint256 private s_flashLoanFee; // 0.3% ETH fee
@> mapping(IERC20 token => bool currentlyFlashLoaning) private s_currentlyFlashLoaning;

Risk

Likelihood:

  • This occurs during the documented upgrade path from ThunderLoan to ThunderLoanUpgraded, because the proxy storage is retained and the upgraded implementation reads s_flashLoanFee from the old s_feePrecision slot.

  • The issue occurs deterministically for initialized deployments because ThunderLoan.initialize() stores s_feePrecision = 1e18 in the slot that the upgraded implementation later interprets as s_flashLoanFee.

Impact:

  • The flash-loan fee is corrupted after upgrade. In the PoC, a pre-upgrade fee of 5e15 becomes 1e18, changing the fee to 100%.

  • Borrowers can be charged drastically incorrect fees or flash-loan functionality can become unusable. The storage shift also changes the base slot of s_currentlyFlashLoaning, creating additional upgrade-state corruption risk for the repayment guard.

Proof of Concept

Add the following test file:

// SPDX-License-Identifier: MIT
pragma solidity 0.8.20;
import { AssetToken } from "../src/protocol/AssetToken.sol";
import { ThunderLoanUpgraded } from "../src/upgradedProtocol/ThunderLoanUpgraded.sol";
import { BaseTest } from "./unit/BaseTest.t.sol";
contract I06UpgradeStoragePreservesObligationsTest is BaseTest {
uint256 private constant DEPOSIT_AMOUNT = 1_000e18;
uint256 private constant CUSTOM_FLASH_LOAN_FEE = 5e15;
uint256 private constant OLD_FEE_PRECISION_SLOT = 203;
uint256 private constant OLD_FLASH_LOAN_FEE_SLOT = 204;
address private liquidityProvider = address(0xA11CE);
function test_I06_01_upgradePreservesFlashLoanFeeConfig() public {
thunderLoan.setAllowedToken(tokenA, true);
tokenA.mint(liquidityProvider, DEPOSIT_AMOUNT);
vm.startPrank(liquidityProvider);
tokenA.approve(address(thunderLoan), DEPOSIT_AMOUNT);
thunderLoan.deposit(tokenA, DEPOSIT_AMOUNT);
vm.stopPrank();
thunderLoan.updateFlashLoanFee(CUSTOM_FLASH_LOAN_FEE);
uint256 preUpgradeFee = thunderLoan.getFee();
uint256 preUpgradeFeePrecision = thunderLoan.getFeePrecision();
uint256 oldFeePrecisionSlotValue =
uint256(vm.load(address(thunderLoan), bytes32(uint256(OLD_FEE_PRECISION_SLOT))));
uint256 oldFlashLoanFeeSlotValue =
uint256(vm.load(address(thunderLoan), bytes32(uint256(OLD_FLASH_LOAN_FEE_SLOT))));
AssetToken preUpgradeAssetToken = thunderLoan.getAssetFromToken(tokenA);
assertEq(preUpgradeFee, CUSTOM_FLASH_LOAN_FEE, "setup: custom fee not set");
assertEq(preUpgradeFeePrecision, 1e18, "setup: old fee precision not initialized");
assertEq(oldFeePrecisionSlotValue, preUpgradeFeePrecision, "setup: unexpected old precision slot");
assertEq(oldFlashLoanFeeSlotValue, preUpgradeFee, "setup: unexpected old fee slot");
ThunderLoanUpgraded upgradedImplementation = new ThunderLoanUpgraded();
thunderLoan.upgradeTo(address(upgradedImplementation));
ThunderLoanUpgraded upgradedThunderLoan = ThunderLoanUpgraded(address(thunderLoan));
assertEq(address(upgradedThunderLoan.getAssetFromToken(tokenA)), address(preUpgradeAssetToken));
assertEq(upgradedThunderLoan.getFee(), preUpgradeFee, "flash loan fee changed across upgrade");
}
}

Run:

forge test --match-contract I06UpgradeStoragePreservesObligationsTest --match-test test_I06_01_upgradePreservesFlashLoanFeeConfig -vvv

Result:

[FAIL: flash loan fee changed across upgrade: 1000000000000000000 != 5000000000000000]

The test confirms that before upgrade, old slot 203 contains s_feePrecision == 1e18 and old slot 204 contains s_flashLoanFee == 5e15. After upgrade, getFee() returns 1e18, proving the upgraded implementation reads the old precision slot as the fee.

Recommended Mitigation

Preserve the original storage layout in ThunderLoanUpgraded. Do not remove or reorder existing state variables in upgradeable contracts. Keep the old s_feePrecision slot, or migrate through an explicit versioned storage/migration design.

contract ThunderLoanUpgraded is Initializable, OwnableUpgradeable, UUPSUpgradeable, OracleUpgradeable {
mapping(IERC20 => AssetToken) public s_tokenToAssetToken;
- uint256 private s_flashLoanFee; // 0.3% ETH fee
- uint256 public constant FEE_PRECISION = 1e18;
+ uint256 private s_feePrecision;
+ uint256 private s_flashLoanFee; // 0.3% ETH fee
mapping(IERC20 token => bool currentlyFlashLoaning) private s_currentlyFlashLoaning;
function getCalculatedFee(IERC20 token, uint256 amount) public view returns (uint256 fee) {
- uint256 valueOfBorrowedToken = (amount * getPriceInWeth(address(token))) / FEE_PRECISION;
- fee = (valueOfBorrowedToken * s_flashLoanFee) / FEE_PRECISION;
+ uint256 valueOfBorrowedToken = (amount * getPriceInWeth(address(token))) / s_feePrecision;
+ fee = (valueOfBorrowedToken * s_flashLoanFee) / s_feePrecision;
}
function updateFlashLoanFee(uint256 newFee) external onlyOwner {
- if (newFee > FEE_PRECISION) {
+ if (newFee > s_feePrecision) {
revert ThunderLoan__BadNewFee();
}
s_flashLoanFee = newFee;
}
}

Also add an upgrade regression test that initializes the original implementation, mutates non-default storage values, upgrades, and asserts all user-facing config and accounting values are preserved.

Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge 1 day ago
Submission Judgement Published
Validated
Assigned finding tags:

[H-01] Storage Collision during upgrade

## Description The thunderloanupgrade.sol storage layout is not compatible with the storage layout of thunderloan.sol which will cause storage collision and mismatch of variable to different data. ## Vulnerability Details Thunderloan.sol at slot 1,2 and 3 holds s_feePrecision, s_flashLoanFee and s_currentlyFlashLoaning, respectively, but the ThunderLoanUpgraded at slot 1 and 2 holds s_flashLoanFee, s_currentlyFlashLoaning respectively. the s_feePrecision from the thunderloan.sol was changed to a constant variable which will no longer be assessed from the state variable. This will cause the location at which the upgraded version will be pointing to for some significant state variables like s_flashLoanFee to be wrong because s_flashLoanFee is now pointing to the slot of the s_feePrecision in the thunderloan.sol and when this fee is used to compute the fee for flashloan it will return a fee amount greater than the intention of the developer. s_currentlyFlashLoaning might not really be affected as it is back to default when a flashloan is completed but still to be noted that the value at that slot can be cleared to be on a safer side. ## Impact 1. Fee is miscalculated for flashloan 1. users pay same amount of what they borrowed as fee ## POC 2 ``` function testFlashLoanAfterUpgrade() public setAllowedToken hasDeposits { //upgrade thunderloan upgradeThunderloan(); uint256 amountToBorrow = AMOUNT * 10; console.log("amount flashloaned", amountToBorrow); uint256 calculatedFee = thunderLoan.getCalculatedFee( tokenA, amountToBorrow ); AssetToken assetToken = thunderLoan.getAssetFromToken(tokenA); vm.startPrank(user); tokenA.mint(address(mockFlashLoanReceiver), amountToBorrow); thunderLoan.flashloan( address(mockFlashLoanReceiver), tokenA, amountToBorrow, "" ); vm.stopPrank(); console.log("feepaid", calculatedFee); assertEq(amountToBorrow, calculatedFee); } ``` Add the code above to thunderloantest.t.sol and run `forge test --mt testFlashLoanAfterUpgrade -vv` to test for the second poc ## Recommendations The team should should make sure the the fee is pointing to the correct location as intended by the developer: a suggestion recommendation is for the team to get the feeValue from the previous implementation, clear the values that will not be needed again and after upgrade reset the fee back to its previous value from the implementation. ##POC for recommendation ``` // function upgradeThunderloanFixed() internal { thunderLoanUpgraded = new ThunderLoanUpgraded(); //getting the current fee; uint fee = thunderLoan.getFee(); // clear the fee as thunderLoan.updateFlashLoanFee(0); // upgrade to the new implementation thunderLoan.upgradeTo(address(thunderLoanUpgraded)); //wrapped the abi thunderLoanUpgraded = ThunderLoanUpgraded(address(proxy)); // set the fee back to the correct value thunderLoanUpgraded.updateFlashLoanFee(fee); } function testSlotValuesFixedfterUpgrade() public setAllowedToken { AssetToken asset = thunderLoan.getAssetFromToken(tokenA); uint precision = thunderLoan.getFeePrecision(); uint fee = thunderLoan.getFee(); bool isflanshloaning = thunderLoan.isCurrentlyFlashLoaning(tokenA); /// 4 slots before upgrade console.log("????SLOTS VALUE BEFORE UPGRADE????"); console.log("slot 0 for s_tokenToAssetToken =>", address(asset)); console.log("slot 1 for s_feePrecision =>", precision); console.log("slot 2 for s_flashLoanFee =>", fee); console.log("slot 3 for s_currentlyFlashLoaning =>", isflanshloaning); //upgrade function upgradeThunderloanFixed(); //// after upgrade they are only 3 valid slot left because precision is now set to constant AssetToken assetUpgrade = thunderLoan.getAssetFromToken(tokenA); uint feeUpgrade = thunderLoan.getFee(); bool isflanshloaningUpgrade = thunderLoan.isCurrentlyFlashLoaning( tokenA ); console.log("????SLOTS VALUE After UPGRADE????"); console.log("slot 0 for s_tokenToAssetToken =>", address(assetUpgrade)); console.log("slot 1 for s_flashLoanFee =>", feeUpgrade); console.log( "slot 2 for s_currentlyFlashLoaning =>", isflanshloaningUpgrade ); assertEq(address(asset), address(assetUpgrade)); //asserting precision value before upgrade to be what fee takes after upgrades assertEq(fee, feeUpgrade); // #POC assertEq(isflanshloaning, isflanshloaningUpgrade); } ``` Add the code above to thunderloantest.t.sol and run with `forge test --mt testSlotValuesFixedfterUpgrade -vv`. it can also be tested with `testFlashLoanAfterUpgrade function` and see the fee properly calculated for flashloan

Support

FAQs

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

Give us feedback!