Vault's savedTotalUnderlying tracks withdrawn funds incorrectly
The Vault contract's pullFunds() function reduces the savedTotalUnderlying variable by the requested withdrawal amount before the actual withdrawal occurs, and even when no withdrawal is made due to the minimumPull threshold. This causes savedTotalUnderlying to be understated, leading to incorrect allocation calculations and reduced investment efficiency.
Source: https://github.com/sherlock-audit/2023-01-derby-judging/issues/363
Found by
Ch_301, atrixs, chaduke, hyh, rvierdiiev, spyrosonic10
Summary
Vault's pullFunds() updates total underlying funds outside Vault variable, savedTotalUnderlying, preliminary with the amount requested, not with the amount obtained.
Vulnerability Detail
pullFunds() reduces savedTotalUnderlying before calling for protocol withdrawal, with amount requested for withdrawal, not with amount that was actually withdrawn. Also, when amountToWithdraw < minimumPull the minimumPull is removed from savedTotalUnderlying despite no withdrawal is made in this case.
As amount requested tends to be bigger than amount withdrawn, the result is savedTotalUnderlying being understated this way. This effect will accumulate over time.
Impact
Net impact is ongoing Vault misbalancing by artificially reducing allocations to the underlying DeFi pools as understated savedTotalUnderlying means less funds are deemed to be available for each Provider.
This will reduce the effective investment sizes vs desired and diminish the results realized as some funds will remain systemically dormant (not used as calcUnderlyingIncBalance() is reported lower than real).
This is the protocol wide loss for the depositors.
Code Snippet
savedTotalUnderlying -= amountToWithdraw is performed before withdrawFromProtocol() was called:
/// @notice Withdraw from protocols on shortage in Vault
/// @dev Keeps on withdrawing until the Vault balance > _value
/// @param _value The total value of vaultCurrency an user is trying to withdraw.
/// @param _value The (value - current underlying value of this vault) is withdrawn from the underlying protocols.
function pullFunds(uint256 _value) internal {
uint256 latestID = controller.latestProtocolId(vaultNumber);
for (uint i = 0; i < latestID; i++) {
if (currentAllocations[i] == 0) continue;
uint256 shortage = _value - vaultCurrency.balanceOf(address(this));
uint256 balanceProtocol = balanceUnderlying(i);
uint256 amountToWithdraw = shortage > balanceProtocol ? balanceProtocol : shortage;
>> savedTotalUnderlying -= amountToWithdraw;
if (amountToWithdraw < minimumPull) break;
withdrawFromProtocol(i, amountToWithdraw);
if (_value <= vaultCurrency.balanceOf(address(this))) break;
}
}
But actual amount withdrawn from protocol differs from the amount requested:
function withdrawFromProtocol(uint256 _protocolNum, uint256 _amount) internal {
if (_amount <= 0) return;
IController.ProtocolInfoS memory protocol = controller.getProtocolInfo(
vaultNumber,
_protocolNum
);
_amount = (_amount * protocol.uScale) / uScale;
uint256 shares = IProvider(protocol.provider).calcShares(_amount, protocol.LPToken);
uint256 balance = IProvider(protocol.provider).balance(address(this), protocol.LPToken);
if (shares == 0) return;
>> if (balance < shares) shares = balance;
IERC20(protocol.LPToken).safeIncreaseAllowance(protocol.provider, shares);
>> uint256 amountReceived = IProvider(protocol.provider).withdraw(
shares,
protocol.LPToken,
protocol.underlying
);
if (protocol.underlying != address(vaultCurrency)) {
>> _amount = Swap.swapStableCoins(
Swap.SwapInOut(amountReceived, protocol.underlying, address(vaultCurrency)),
controller.underlyingUScale(protocol.underlying),
uScale,
controller.getCurveParams(protocol.underlying, address(vaultCurrency))
);
}
}
This happens because of:
- shares balance restriction
- underlying funds availability within Provider
- swapping to
vaultCurrencyis market dependent and is not deterministic
As this is substantial degree of randomness it can be assumed that withdrawFromProtocol() typically returns somewhat different amount than it was requested.
savedTotalUnderlying is then used by calcUnderlyingIncBalance():
/// @notice Helper to return underlying balance plus totalUnderlying - liquidty for the vault
/// @return underlying totalUnderlying - liquidityVault
function calcUnderlyingIncBalance() internal view returns (uint256) {
>> uint256 totalUnderlyingInclVaultBalance = savedTotalUnderlying +
getVaultBalance() -
reservedFunds;
uint256 liquidityVault = (totalUnderlyingInclVaultBalance * liquidityPerc) / 100;
return totalUnderlyingInclVaultBalance - liquidityVault;
}
Which defines the allocation during Vault rebalancing:
function rebalance() external nonReentrant {
require(state == State.RebalanceVault, stateError);
require(deltaAllocationsReceived, "!Delta allocations");
rebalancingPeriod++;
claimTokens();
settleDeltaAllocation();
>> uint256 underlyingIncBalance = calcUnderlyingIncBalance();
uint256[] memory protocolToDeposit = rebalanceCheckProtocols(underlyingIncBalance);
executeDeposits(protocolToDeposit);
setTotalUnderlying();
if (reservedFunds > vaultCurrency.balanceOf(address(this))) pullFunds(reservedFunds);
state = State.SendRewardsPerToken;
deltaAllocationsReceived = false;
}
Tool used
Manual Review
Recommendation
Consider returning the amount realized in withdrawFromProtocol():
/// @notice Withdraw amount from underlying protocol
/// @dev shares = amount / PricePerShare
/// @param _protocolNum Protocol number linked to an underlying protocol e.g compound_usdc_01
/// @param _amount in VaultCurrency to withdraw
- function withdrawFromProtocol(uint256 _protocolNum, uint256 _amount) internal {
+ function withdrawFromProtocol(uint256 _protocolNum, uint256 _amount) internal returns (uint256 amountReceived) {
if (_amount <= 0) return;
IController.ProtocolInfoS memory protocol = controller.getProtocolInfo(
vaultNumber,
_protocolNum
);
_amount = (_amount * protocol.uScale) / uScale;
uint256 shares = IProvider(protocol.provider).calcShares(_amount, protocol.LPToken);
uint256 balance = IProvider(protocol.provider).balance(address(this), protocol.LPToken);
if (shares == 0) return;
if (balance < shares) shares = balance;
IERC20(protocol.LPToken).safeIncreaseAllowance(protocol.provider, shares);
- uint256 amountReceived = IProvider(protocol.provider).withdraw(
+ amountReceived = IProvider(protocol.provider).withdraw(
shares,
protocol.LPToken,
protocol.underlying
);
if (protocol.underlying != address(vaultCurrency)) {
- _amount = Swap.swapStableCoins(
+ amountReceived = Swap.swapStableCoins(
Swap.SwapInOut(amountReceived, protocol.underlying, address(vaultCurrency)),
controller.underlyingUScale(protocol.underlying),
uScale,
controller.getCurveParams(protocol.underlying, address(vaultCurrency))
);
}
}
And updating savedTotalUnderlying after the fact with the actual amount in pullFunds():
/// @notice Withdraw from protocols on shortage in Vault
/// @dev Keeps on withdrawing until the Vault balance > _value
/// @param _value The total value of vaultCurrency an user is trying to withdraw.
/// @param _value The (value - current underlying value of this vault) is withdrawn from the underlying protocols.
function pullFunds(uint256 _value) internal {
uint256 latestID = controller.latestProtocolId(vaultNumber);
for (uint i = 0; i < latestID; i++) {
if (currentAllocations[i] == 0) continue;
uint256 shortage = _value - vaultCurrency.balanceOf(address(this));
uint256 balanceProtocol = balanceUnderlying(i);
uint256 amountToWithdraw = shortage > balanceProtocol ? balanceProtocol : shortage;
- savedTotalUnderlying -= amountToWithdraw;
if (amountToWithdraw < minimumPull) break;
- withdrawFromProtocol(i, amountToWithdraw);
+ uint256 amountWithdrawn = withdrawFromProtocol(i, amountToWithdraw);
+ savedTotalUnderlying -= amountWithdrawn;
if (_value <= vaultCurrency.balanceOf(address(this))) break;
}
}
This will also remove minimumPull bias that is currently added when if (amountToWithdraw < minimumPull) break triggers (no funds are pulled, but savedTotalUnderlying is reduced by minimumPull).
Discussion
sjoerdsommen
pullFunds can diverge a bit between actual and calculated value, this causes safedTotalUnderlying to be incorrect; correct but not severe because small values and after rebalancing the issue does not persist
hrishibhat
Given the necessary preconditions required for the understated savedTotalUnderlying.
Considering this a valid medium
dmitriia
Escalate for 10 USDC It cannot be guaranteed that pullFunds() discrepancy is small. It can be substantial as underlying funds availability within Provider is unpredictable (liquidity squeeze can render 99% funds unavailable for a period).
Due to the behavior described the whole Vault allocation will be twisted when this happens. Such biases should have high severity due to moderate probability (liquidity shortages are routine) and material Vault-wide impact.
sherlock-admin
Escalate for 10 USDC It cannot be guaranteed that pullFunds() discrepancy is small. It can be substantial as underlying funds availability within Provider is unpredictable (liquidity squeeze can render 99% funds unavailable for a period).
Due to the behavior described the whole Vault allocation will be twisted when this happens. Such biases should have high severity due to moderate probability (liquidity shortages are routine) and material Vault-wide impact.
You've created a valid escalation for 10 USDC!
To remove the escalation from consideration: Delete your comment.
You may delete or edit your escalation comment anytime before the 48-hour escalation window closes. After that, the escalation becomes final.
hrishibhat
Escalation accepted
After further review and discussion, considering the impact of this issue as high based on the points mentioned in the issue and escalation.
sherlock-admin
Escalation accepted
After further review and discussion, considering the impact of this issue as high based on the points mentioned in the issue and escalation.
This issue's escalations have been accepted!
Contestants' payouts and scores will be updated according to the changes made on this issue.
sherlock-admin
Escalation accepted
After further review and discussion, considering the impact of this issue as high based on the points mentioned in the issue and escalation.
This issue's escalations have been accepted!
Contestants' payouts and scores will be updated according to the changes made on this issue.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
How it worked
Root cause
The code updates the savedTotalUnderlying state variable using the requested withdrawal amount instead of the actual amount received, and also deducts the minimumPull amount even when no withdrawal occurs.
Impact
This could cause ongoing misbalancing of the vault, reducing effective investment sizes and diminishing returns for depositors as funds remain dormant.
What the attacker needed
Vault has funds in underlying protocols; Withdrawal amount exceeds available liquidity or…
The fix
The fix is to have withdrawFromProtocol() return the actual amount received and update savedTotalUnderlying with that amount after the withdrawal, and to only update when a withdrawal actually occurs.
Explained by bugbounty.wiki with AI from the original and checked against quotes from it; it can still be wrong. Read the original before relying on a detail.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
In a smart contract, a variable tracks the total funds the vault believes it has. When the vault needs to withdraw funds from an external protocol, it subtracts the requested amount from this variable before actually getting the funds. But the actual amount received can be less due to limits or market conditions, so the variable ends up too low. This makes the vault think it has less money than it does, so it invests less than it should, reducing profits for depositors.
What is Business logic?
The application works as coded but not as intended: a negative price, a skipped payment step, a limit that can be crossed.