Thunder Loan

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

ThunderLoan -> ThunderLoanUpgraded storage collision: s_flashLoanFee reads stale s_feePrecision, fee becomes 100%

Description

Normal behavior: after the README-planned upgrade to ThunderLoanUpgraded, flash loans should keep charging the initialized 0.3% fee.

The issue: V1 declares s_feePrecision as a STORAGE variable (ThunderLoan.sol:96) while V2 replaces it with a CONSTANT (ThunderLoanUpgraded.sol:97, no slot). Verified with forge inspect storage-layout (OZ v4.9.6, including inherited __gap reservations): V1 has s_tokenToAssetToken at slot 202, s_feePrecision at slot 203, s_flashLoanFee at slot 204; V2 shifts s_flashLoanFee UP into slot 203 (and s_currentlyFlashLoaning into slot 204). After upgrade, s_flashLoanFee reads V1's stale slot-203 value (s_feePrecision = 1e18). The flash-loan fee becomes 1e18/1e18 = 100% of the borrowed value.

// V1 (ThunderLoan.sol) // forge inspect: slot 203 / 204 (after inherited OZ slots + __gap)
uint256 private s_feePrecision; // slot 203 = 1e18
uint256 private s_flashLoanFee; // slot 204 = 3e15
// V2 (ThunderLoanUpgraded.sol)
@> uint256 private s_flashLoanFee; // now slot 203 -> reads stale 1e18
uint256 public constant FEE_PRECISION = 1e18; // constant: no slot, predecessor never cleared

Additionally, V2's initialize() is a plain initializer (not reinitializer(2)), so the corrupted fee cannot be repaired by re-initialization; only a manual updateFlashLoanFee() by the owner fixes it.

Risk

Likelihood: High.

  • Reason 1: The upgrade is the documented, expected owner action (README states the planned upgrade); executing it correctly triggers the corruption with no admin mistake involved.

  • Reason 2: The corruption is silent — nothing reverts at upgrade time; the first borrower discovers it live.

Impact:

  • Impact 1: Flash loans are effectively bricked — repaying requires 2x principal, so every honest borrower's transaction reverts (core protocol functionality down until manual owner repair).

  • Impact 2: Any borrower who pre-computed a 0.3% fee and gets front-run with the upgraded fee loses up to the full principal difference; fee accounting is persistently corrupted (100% vs 0.3%).

(No attacker profit vector: the overcharge accrues to LPs, not to an attacker — hence Medium per the impact tree, not High.)

Proof of Concept

Foundry test: test/poc/PocStorageCollision.t.sol (PoC file added under test/poc/ in the contest repo; deploys V1 behind ERC1967Proxy, initializes, then owner upgradeTo(V2)):

fee before upgrade (0.3% expected): 300000000000000000 (0.3e18 = 0.3% of 100e18)
fee after upgrade (100% = brick): 100000000000000000000 (100e18 = 100% of 100e18)

Actual vs expected: fee inflates ~333x purely from a correct upgrade; expected unchanged 0.3%.

Recommended Mitigation

Keep storage append-only across upgrades; never delete or reorder live slot variables (turn s_feePrecision into a constant only via a new-name variable or leave the slot reserved), and verify layouts before upgrading:

// V2
- uint256 private s_flashLoanFee;
- uint256 public constant FEE_PRECISION = 1e18;
+ uint256 private s_feePrecision_DEPRECATED; // slot 203 kept for layout compatibility
+ uint256 private s_flashLoanFee; // stays at slot 204
+ uint256 public constant FEE_PRECISION = 1e18;

and add reinitializer-based repair:

- function initialize(address tswapAddress) external initializer {
+ function initializeV2() external reinitializer(2) {
+ s_flashLoanFee = 3e15; // restore intended fee after upgrade
+ }

Process fix: run forge inspect ThunderLoan storage-layout vs forge inspect ThunderLoanUpgraded storage-layout in CI and block the upgrade on any divergence.Root + Impact

Description

  • Describe the normal behavior in one or more sentences

  • Explain the specific issue or problem in one or more sentences

// Root cause in the codebase with @> marks to highlight the relevant section

Risk

Likelihood:

  • Reason 1 // Describe WHEN this will occur (avoid using "if" statements)

  • Reason 2

Impact:

  • Impact 1

  • Impact 2

Proof of Concept

Recommended Mitigation

- remove this code
+ add this code
Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge about 1 hour 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!