Thunder Loan

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

Storage collision between ThunderLoan and ThunderLoanUpgraded inflates the flash loan fee from 0.3% to 100% after upgrade

Root + Impact

Description

The upgrade target reorders storage. ThunderLoan declares s_feePrecision before s_flashLoanFee, while ThunderLoanUpgraded removes s_feePrecision and replaces it with a constant. Constants are embedded in bytecode and occupy no storage slot, so every variable declared after it shifts up by one slot.

// src/protocol/ThunderLoan.sol
mapping(IERC20 => AssetToken) public s_tokenToAssetToken; // slot N+0
@> uint256 private s_feePrecision; // slot N+1
uint256 private s_flashLoanFee; // slot N+2
mapping(IERC20 token => bool) private s_currentlyFlashLoaning; // slot N+3
// src/upgradedProtocol/ThunderLoanUpgraded.sol
mapping(IERC20 => AssetToken) public s_tokenToAssetToken; // slot N+0
@> uint256 private s_flashLoanFee; // slot N+1 - reads old s_feePrecision
@> uint256 public constant FEE_PRECISION = 1e18; // constants occupy NO slot
mapping(IERC20 token => bool) private s_currentlyFlashLoaning; // slot N+2 - reads old fee slot

A proxy keeps its storage across an upgrade while the implementation's variable-to-slot mapping is recompiled from the new source. After the upgrade, s_flashLoanFee therefore reads the slot that used to hold s_feePrecision (1e18), and s_currentlyFlashLoaning reads the slot that used to hold the fee.

Risk

Likelihood: High

This is not an edge case but the intended deployment path. The protocol documentation states: "We are planning to upgrade from the current ThunderLoan contract to the ThunderLoanUpgraded contract." Performing that documented upgrade triggers the bug with certainty.

Impact: High

The flash loan fee becomes 100% of the borrowed value the instant the upgrade executes, because s_flashLoanFee and FEE_PRECISION both equal 1e18, so fee = value * 1e18 / 1e18 = value. Every flash loan then demands repaying double the borrowed amount, breaking the protocol's core function for all users.

On a proxy this is unrecoverable without a further upgrade, and the corrupted s_currentlyFlashLoaning slot additionally breaks repay().

Proof of Concept

Deploy behind an ERC1967Proxy, record the fee, perform the documented upgrade, read the fee again.

function test_Finding3_UpgradeCorruptsFlashLoanFee() public {
uint256 feeBefore = thunderLoan.getFee(); // 3e15 (0.3%)
uint256 precisionBefore = thunderLoan.getFeePrecision(); // 1e18
​
ThunderLoanUpgraded upgraded = new ThunderLoanUpgraded();
thunderLoan.upgradeToAndCall(address(upgraded), "");
​
uint256 feeAfter = ThunderLoanUpgraded(address(proxy)).getFee();
​
assertEq(feeBefore, 3e15);
assertEq(precisionBefore, 1e18);
assertEq(feeAfter, precisionBefore); // the fee now reads the OLD feePrecision slot
}
​
function test_Finding3_FeeBecomesOneHundredPercent() public {
ThunderLoanUpgraded upgraded = new ThunderLoanUpgraded();
thunderLoan.upgradeToAndCall(address(upgraded), "");
​
ThunderLoanUpgraded tl = ThunderLoanUpgraded(address(proxy));
tl.setAllowedToken(IERC20(address(tokenA)), true);
​
uint256 borrow = 10e18;
uint256 fee = tl.getCalculatedFee(IERC20(address(tokenA)), borrow);
​
assertEq(fee, borrow); // the fee equals 100% of the borrowed amount
}

Both tests pass. Result:

BEFORE upgrade - s_flashLoanFee : 3000000000000000 (3e15 = 0.3%)
BEFORE upgrade - s_feePrecision : 1000000000000000000 (1e18)
AFTER upgrade - s_flashLoanFee : 1000000000000000000 (the old precision value)
fee inflated by factor: 333
​
borrow amount: 10000000000000000000 (10 tokens)
fee charged : 10000000000000000000 (10 tokens = 100%)

Recommended Mitigation

Never remove or reorder existing storage variables in an upgradeable contract. The proxy's storage is fixed at the layout of the first implementation, so a later implementation must preserve that layout exactly: variables may only be appended at the end, and any variable that is no longer used must keep its slot occupied by a placeholder rather than being deleted.

Replacing a storage variable with a constant is the specific trap here, because a constant looks like a declaration in the same position but consumes no slot, silently shifting everything below it.

mapping(IERC20 => AssetToken) public s_tokenToAssetToken;
- uint256 public constant FEE_PRECISION = 1e18;
+ uint256 private __deprecated_feePrecision; // keep the slot occupied
uint256 private s_flashLoanFee;
mapping(IERC20 token => bool) private s_currentlyFlashLoaning;

Declare FEE_PRECISION as a constant elsewhere in the contract body (after all storage variables), and add an automated storage-layout check to CI, such as the OpenZeppelin Upgrades plugin, so a layout-incompatible upgrade cannot be deployed.

Updates

Lead Judging Commences

ai-first-flight-judge Lead Judge 15 days 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!