Direct theft of any user funds, whether at-rest or in-motion, other than unclaimed yield
Description
Brief/Intro
In a sandwich attack, the attacker mints just 1 wei share for 1 wei long token deposit then donate higher than the victim's deposit amount to the Staking.sol vault before the victim's deposit is executed.
This inflates the totalAssets() before the victim's deposit is executed and by the time the victim's deposit is executed, zero shares is minted to the victim due to rounding from inflated to totalAssets() (the denominator in shares calculation).
After the victim's deposit, the attacker calls emergencyWithdraw(...) immediately and since there is just 1 wei of shares available on Staking.sol, the attacker uses this 1 wei of shares token to withdraw the totalAssets (this is plus the victim's asset).
And a 10 percent penalty is charged from the emergencyWithdraw(...) which makes the attack profitable because the attacker makes at least 80% profit.
Vulnerability Details
The Staking.sol is vulnerable to an inflation attack because:
The totalAssets(...) function from the inherited ERC4626 uses the ERC20 balanceOf(address(this)) to track the total assets.
Staking.sol allows minting of zero shares.
balanceOf(address(this)) can be manipulated by anyone by directly transferring Long token to the Staking.sol increasing the totalAssets() value which is used as denominator in calculating shares minted. But before inflating total asset, the attacker mints 1 wei shares token which will be used to withdraw the victim's asset plus the attacker's donated asset.
Impact Details
Theft of first depositor's asset through inflation attack.
Recommendation
Consider tracking total assets with a storage variable instead of relying on ERC20.balanceOf(...) which can be manipulated.
Also consider not allowing minting of zero shares for deposits.
Proof of Concept
1
Setup & context
Copy and paste the test below to the staking.test.ts file in the 'Staking features' test suite, then run yarn test.
This demonstrates how an attacker can frontrun first deposit by first minting 1 wei of shares, then inflate the total asset by direct donation before the victim's deposit tx is executed resulting in zero shares minted to the victim due to rounding. Then attacker uses 1 wei shares to withdraw the attacker and the victim's assets.