Wrong accounting of the storage balances results for the protocol to be in debt even when the bad debt is repaid
When a position is closed with bad debt, the protocol adds the bad debt to a bad_debt mapping but does not subtract it from total_debt_amount, so the same amount is counted twice. Even after the bad debt is repaid, the leftover total_debt_amount reduces available liquidity, preventing liquidity providers from withdrawing their full funds.
Wrong accounting of the storage balances results for the protocol to be in debt even when the bad debt is repaid.
Vulnerability Detail
When a position is fully closed, it can result to accruing bad debt or being in profit and repaying the borrowed liquidity which all depends on the amount_out_received from the swap.
In a bad debt scenario the function calculates the bad debt and accrues it based on the difference between the position debt and the amount out received from the swap. And after that repays the liquidity providers with the same received amount from the swap.
VY
if amount_out_received >= position_debt_amount:
# all good, LPs are paid back, remainder goes back to trader
trader_pnl: uint256 = amount_out_received - position_debt_amount
self.margin[position.account][position.debt_token] += trader_pnl
self._repay(position.debt_token, position_debt_amount)
else:
# edge case: bad debt
self.is_accepting_new_orders = False # put protocol in defensive mode
bad_debt: uint256 = position_debt_amount - amount_out_received
self.bad_debt[position.debt_token] += bad_debt
self._repay(
position.debt_token, amount_out_received
) # repay LPs as much as possible
log BadDebt(position.debt_token, bad_debt, position.uid)
The mapping total_debt_amount holds all debt borrowed from users, and this amount accrues interest with the time.
Prior to closing a position, the bad debt is calculated and accrued to the mapping bad_debt, but it isn't subtracted from the mapping total_debt_amount which holds all the debt even the bad one accrued through the time.
VY
@internal
def _update_debt(_debt_token: address):
"""
@notice
Accounts for any accrued interest since the last update.
"""
if block.timestamp == self.last_debt_update[_debt_token]:
return # already up to date, nothing to do
self.last_debt_update[_debt_token] = block.timestamp
if self.total_debt_amount[_debt_token] == 0:
return # no debt, no interest
self.total_debt_amount[_debt_token] += self._debt_interest_since_last_update(
_debt_token
)
As the bad debt isn't subtracted from the total_debt_amount when closing a position, even after repaying the bad debt. It will still be in the total_debt_amount, which will prevent the full withdrawing of the liquidity funds.
VY
@nonreentrant("lock")
@external
def repay_bad_debt(_token: address, _amount: uint256):
"""
@notice
Allows to repay bad_debt in case it was accrued.
"""
self.bad_debt[_token] -= _amount
self._safe_transfer_from(_token, msg.sender, self, _amount)
The issue leads to liquidity providers unable to withdraw their full amount of funds, as even after repaying the bad debt it will still be in the total_debt_amount mapping.
The only way to fix this problem is to repay the position debt amount prior to closing a position and not only the received amount from the swap. Because total_debt_amount holds the bad debt as well.
VY
else:
# edge case: bad debt
self.is_accepting_new_orders = False # put protocol in defensive mode
bad_debt: uint256 = position_debt_amount - amount_out_received
self.bad_debt[position.debt_token] += bad_debt
self._repay(
position.debt_token, position_debt_amount
) # repay LPs as much as possible
log BadDebt(position.debt_token, bad_debt, position.uid)
Discussion
CodingNameKiki
Escalate
This issue should be high, as it results to permanent loss of funds for liquidity providers.
What the issue leads to:
Double counting of the bad debt in the system, as it isn't subtracted from the mapping total_debt_amount.
When the bad debt is repaid, the system will still be in debt.
Liquidity providers will not be able to withdraw their full amount of funds, as a result the funds will be stuck in the system.
The referred issue describes the outcome of the issue well, but l am still going to provide an additional explanation in this escalation.
Detailed explanation
Part 1 - Showing how bad debt accrues.
The internal function _close_position is called when a position is fully closed.
There could be two scenarios when the function is called.
if amount_out_received >= position_debt_amount: - the amount out received from the swap is bigger than the position debt, which indicates that the user is in profit and the whole debt amount is repaid and subtracted from the mapping total_debt_amount.
else indicates that the amount out received from the swap is smaller than the position debt. As a result bad debt is accrued in the mapping bad_debt.
VY
@internal
def _close_position(_position_uid: bytes32, _min_amount_out: uint256) -> uint256:
"""
@notice
Closes an existing position, repays the debt plus
accrued interest and credits/debits the users margin
with the remaining PnL.
"""
# fetch the position from the positions-dict by uid
position: Position = self.positions[_position_uid]
# assign to local variable to make it editable
min_amount_out: uint256 = _min_amount_out
if min_amount_out == 0:
# market order, add some slippage protection
min_amount_out = self._market_order_min_amount_out(
position.position_token, position.debt_token, position.position_amount
)
position_debt_amount: uint256 = self._debt(_position_uid)
amount_out_received: uint256 = self._swap(
position.position_token,
position.debt_token,
position.position_amount,
min_amount_out,
)
if amount_out_received >= position_debt_amount:
# all good, LPs are paid back, remainder goes back to trader
trader_pnl: uint256 = amount_out_received - position_debt_amount
self.margin[position.account][position.debt_token] += trader_pnl
self._repay(position.debt_token, position_debt_amount)
else:
# edge case: bad debt
self.is_accepting_new_orders = False # put protocol in defensive mode
bad_debt: uint256 = position_debt_amount - amount_out_received
self.bad_debt[position.debt_token] += bad_debt
self._repay(
position.debt_token, amount_out_received
) # repay LPs as much as possible
log BadDebt(position.debt_token, bad_debt, position.uid)
# cleanup position
self.positions[_position_uid] = empty(Position)
log PositionClosed(position.account, position.uid, position, amount_out_received)
return amount_out_received
Conclusion:
When bad debt is accrued, the system adds the amount of debt to the mapping bad_debt, but doesn't subtract the same amount from the mapping total_debt_amount.
The mapping total_debt_amount holds all the debt borrowed from users and the extra amount of debt accrued through the time in terms of interest.
As a result the bad debt is double counted in the system.
The system provides a way for users to repay the bad debt accrued in the mapping bad_debt.
However as double counted, once repaid from the mapping bad_debt, the other same half will still persist in the mapping total_debt_amount.
VY
@nonreentrant("lock")
@external
def repay_bad_debt(_token: address, _amount: uint256):
"""
@notice
Allows to repay bad_debt in case it was accrued.
"""
self.bad_debt[_token] -= _amount
self._safe_transfer_from(_token, msg.sender, self, _amount)
Part 2 - Liquidity providers not able to withdraw their full amount of funds
So far we've explained the main part of the issue, but lets see the impact on the liquidity providers.
When the function withdraw_liquidity is called, it checks that the system has the available amount of liquidity in order to perform the withdraw.
VY
@nonreentrant("lock")
@external
def withdraw_liquidity(_token: address, _amount: uint256, _is_safety_module: bool):
"""
@notice
Allows LPs to withdraw their _token liquidity.
Only liquidity that is currently not lent out can be withdrawn.
"""
assert (self.account_withdraw_liquidity_cooldown[msg.sender] <= block.timestamp), "cooldown"
assert _amount <= self._available_liquidity(_token), "liquidity not available"
self._account_for_withdraw_liquidity(_token, _amount, _is_safety_module)
self._safe_transfer(_token, msg.sender, _amount)
log WithdrawLiquidity(msg.sender, _token, _amount)
What we know so far:
When the system accrues bad debt, it forgets to remove the particular amount of bad debt from the mapping total_debt_amount, which holds all the debt accrued through the time in terms of interest (debt + extra debt), as a result after bad debt is accrued the same amount of bad debt persist both in the mappings bad_debt and total_debt_amount.
What happens when calculating the available liquidity:
First we can see that the total liquidity amount is calculated based on the provided liquidity from the liquidity providers. Then the bad debt which the system holds is subtracted from it.
After that the system subtracts the total_debt_amount from the total liquidity.
As a result the same amount of bad debt accrued is subtracted twice from the total liquidity as it persist both in the mappings bad_debt and total_debt_amount.
The conclusion is that even if the bad debt is repaid from the mapping bad_debt, it will still persist in total_debt_amount.
This amount of bad debt can't be removed from the mapping total_debt_amount and will be accrued in terms of interest through time and persist in it forever.
Duo to this issue the liquidity providers will not be able to withdraw the full amount of funds they deposited, and the same amount of funds will be permanently locked in the system.
sherlock-admin2
Escalate
This issue should be high, as it results to permanent loss of funds for liquidity providers.
What the issue leads to:
Double counting of the bad debt in the system, as it isn't subtracted from the mapping total_debt_amount.
When the bad debt is repaid, the system will still be in debt.
Liquidity providers will not be able to withdraw their full amount of funds, as a result the funds will be stuck in the system.
The referred issue describes the outcome of the issue well, but l am still going to provide an additional explanation in this escalation.
Detailed explanation
Part 1 - Showing how bad debt accrues.
The internal function _close_position is called when a position is fully closed.
There could be two scenarios when the function is called.
if amount_out_received >= position_debt_amount: - the amount out received from the swap is bigger than the position debt, which indicates that the user is in profit and the whole debt amount is repaid and subtracted from the mapping total_debt_amount.
else indicates that the amount out received from the swap is smaller than the position debt. As a result bad debt is accrued in the mapping bad_debt.
VY
@internal
def _close_position(_position_uid: bytes32, _min_amount_out: uint256) -> uint256:
"""
@notice
Closes an existing position, repays the debt plus
accrued interest and credits/debits the users margin
with the remaining PnL.
"""
# fetch the position from the positions-dict by uid
position: Position = self.positions[_position_uid]
# assign to local variable to make it editable
min_amount_out: uint256 = _min_amount_out
if min_amount_out == 0:
# market order, add some slippage protection
min_amount_out = self._market_order_min_amount_out(
position.position_token, position.debt_token, position.position_amount
)
position_debt_amount: uint256 = self._debt(_position_uid)
amount_out_received: uint256 = self._swap(
position.position_token,
position.debt_token,
position.position_amount,
min_amount_out,
)
if amount_out_received >= position_debt_amount:
# all good, LPs are paid back, remainder goes back to trader
trader_pnl: uint256 = amount_out_received - position_debt_amount
self.margin[position.account][position.debt_token] += trader_pnl
self._repay(position.debt_token, position_debt_amount)
else:
# edge case: bad debt
self.is_accepting_new_orders = False # put protocol in defensive mode
bad_debt: uint256 = position_debt_amount - amount_out_received
self.bad_debt[position.debt_token] += bad_debt
self._repay(
position.debt_token, amount_out_received
) # repay LPs as much as possible
log BadDebt(position.debt_token, bad_debt, position.uid)
# cleanup position
self.positions[_position_uid] = empty(Position)
log PositionClosed(position.account, position.uid, position, amount_out_received)
return amount_out_received
Conclusion:
When bad debt is accrued, the system adds the amount of debt to the mapping bad_debt, but doesn't subtract the same amount from the mapping total_debt_amount.
The mapping total_debt_amount holds all the debt borrowed from users and the extra amount of debt accrued through the time in terms of interest.
As a result the bad debt is double counted in the system.
The system provides a way for users to repay the bad debt accrued in the mapping bad_debt.
However as double counted, once repaid from the mapping bad_debt, the other same half will still persist in the mapping total_debt_amount.
VY
@nonreentrant("lock")
@external
def repay_bad_debt(_token: address, _amount: uint256):
"""
@notice
Allows to repay bad_debt in case it was accrued.
"""
self.bad_debt[_token] -= _amount
self._safe_transfer_from(_token, msg.sender, self, _amount)
Part 2 - Liquidity providers not able to withdraw their full amount of funds
So far we've explained the main part of the issue, but lets see the impact on the liquidity providers.
When the function withdraw_liquidity is called, it checks that the system has the available amount of liquidity in order to perform the withdraw.
VY
@nonreentrant("lock")
@external
def withdraw_liquidity(_token: address, _amount: uint256, _is_safety_module: bool):
"""
@notice
Allows LPs to withdraw their _token liquidity.
Only liquidity that is currently not lent out can be withdrawn.
"""
assert (self.account_withdraw_liquidity_cooldown[msg.sender] <= block.timestamp), "cooldown"
assert _amount <= self._available_liquidity(_token), "liquidity not available"
self._account_for_withdraw_liquidity(_token, _amount, _is_safety_module)
self._safe_transfer(_token, msg.sender, _amount)
log WithdrawLiquidity(msg.sender, _token, _amount)
What we know so far:
When the system accrues bad debt, it forgets to remove the particular amount of bad debt from the mapping total_debt_amount, which holds all the debt accrued through the time in terms of interest (debt + extra debt), as a result after bad debt is accrued the same amount of bad debt persist both in the mappings bad_debt and total_debt_amount.
What happens when calculating the available liquidity:
First we can see that the total liquidity amount is calculated based on the provided liquidity from the liquidity providers. Then the bad debt which the system holds is subtracted from it.
After that the system subtracts the total_debt_amount from the total liquidity.
As a result the same amount of bad debt accrued is subtracted twice from the total liquidity as it persist both in the mappings bad_debt and total_debt_amount.
The conclusion is that even if the bad debt is repaid from the mapping bad_debt, it will still persist in total_debt_amount.
This amount of bad debt can't be removed from the mapping total_debt_amount and will be accrued in terms of interest through time and persist in it forever.
Duo to this issue the liquidity providers will not be able to withdraw the full amount of funds they deposited, and the same amount of funds will be permanently locked in the system.
You've created a valid escalation!
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.
SilentYuki
The escalation is correct, the issue should be high severity.
141345
Recommendation:
change the original judging, to high severity.
Escalate
This issue should be high, as it results to permanent loss of funds for liquidity providers.
What the issue leads to:
Double counting of the bad debt in the system, as it isn't subtracted from the mapping total_debt_amount.
When the bad debt is repaid, the system will still be in debt.
Liquidity providers will not be able to withdraw their full amount of funds, as a result the funds will be stuck in the system.
The referred issue describes the outcome of the issue well, but l am still going to provide an additional explanation in this escalation.
Detailed explanation
Part 1 - Showing how bad debt accrues.
The internal function _close_position is called when a position is fully closed.
There could be two scenarios when the function is called.
if amount_out_received >= position_debt_amount: - the amount out received from the swap is bigger than the position debt, which indicates that the user is in profit and the whole debt amount is repaid and subtracted from the mapping total_debt_amount.
else indicates that the amount out received from the swap is smaller than the position debt. As a result bad debt is accrued in the mapping bad_debt.
VYPER
@internal
def _close_position(_position_uid: bytes32, _min_amount_out: uint256) -> uint256:
"""
@notice
Closes an existing position, repays the debt plus
accrued interest and credits/debits the users margin
with the remaining PnL.
"""
# fetch the position from the positions-dict by uid
position: Position = self.positions[_position_uid]
# assign to local variable to make it editable
min_amount_out: uint256 = _min_amount_out
if min_amount_out == 0:
# market order, add some slippage protection
min_amount_out = self._market_order_min_amount_out(
position.position_token, position.debt_token, position.position_amount
)
position_debt_amount: uint256 = self._debt(_position_uid)
amount_out_received: uint256 = self._swap(
position.position_token,
position.debt_token,
position.position_amount,
min_amount_out,
)
if amount_out_received >= position_debt_amount:
# all good, LPs are paid back, remainder goes back to trader
trader_pnl: uint256 = amount_out_received - position_debt_amount
self.margin[position.account][position.debt_token] += trader_pnl
self._repay(position.debt_token, position_debt_amount)
else:
# edge case: bad debt
self.is_accepting_new_orders = False # put protocol in defensive mode
bad_debt: uint256 = position_debt_amount - amount_out_received
self.bad_debt[position.debt_token] += bad_debt
self._repay(
position.debt_token, amount_out_received
) # repay LPs as much as possible
log BadDebt(position.debt_token, bad_debt, position.uid)
# cleanup position
self.positions[_position_uid] = empty(Position)
log PositionClosed(position.account, position.uid, position, amount_out_received)
return amount_out_received
Conclusion:
When bad debt is accrued, the system adds the amount of debt to the mapping bad_debt, but doesn't subtract the same amount from the mapping total_debt_amount.
The mapping total_debt_amount holds all the debt borrowed from users and the extra amount of debt accrued through the time in terms of interest.
As a result the bad debt is double counted in the system.
The system provides a way for users to repay the bad debt accrued in the mapping bad_debt.
However as double counted, once repaid from the mapping bad_debt, the other same half will still persist in the mapping total_debt_amount.
VYPER
@nonreentrant("lock")
@external
def repay_bad_debt(_token: address, _amount: uint256):
"""
@notice
Allows to repay bad_debt in case it was accrued.
"""
self.bad_debt[_token] -= _amount
self._safe_transfer_from(_token, msg.sender, self, _amount)
Part 2 - Liquidity providers not able to withdraw their full amount of funds
So far we've explained the main part of the issue, but lets see the impact on the liquidity providers.
When the function withdraw_liquidity is called, it checks that the system has the available amount of liquidity in order to perform the withdraw.
VYPER
@nonreentrant("lock")
@external
def withdraw_liquidity(_token: address, _amount: uint256, _is_safety_module: bool):
"""
@notice
Allows LPs to withdraw their _token liquidity.
Only liquidity that is currently not lent out can be withdrawn.
"""
assert (self.account_withdraw_liquidity_cooldown[msg.sender] <= block.timestamp), "cooldown"
assert _amount <= self._available_liquidity(_token), "liquidity not available"
self._account_for_withdraw_liquidity(_token, _amount, _is_safety_module)
self._safe_transfer(_token, msg.sender, _amount)
log WithdrawLiquidity(msg.sender, _token, _amount)
What we know so far:
When the system accrues bad debt, it forgets to remove the particular amount of bad debt from the mapping total_debt_amount, which holds all the debt accrued through the time in terms of interest (debt + extra debt), as a result after bad debt is accrued the same amount of bad debt persist both in the mappings bad_debt and total_debt_amount.
What happens when calculating the available liquidity:
First we can see that the total liquidity amount is calculated based on the provided liquidity from the liquidity providers. Then the bad debt which the system holds is subtracted from it.
After that the system subtracts the total_debt_amount from the total liquidity.
As a result the same amount of bad debt accrued is subtracted twice from the total liquidity as it persist both in the mappings bad_debt and total_debt_amount.
The conclusion is that even if the bad debt is repaid from the mapping bad_debt, it will still persist in total_debt_amount.
This amount of bad debt can't be removed from the mapping total_debt_amount and will be accrued in terms of interest through time and persist in it forever.
Duo to this issue the liquidity providers will not be able to withdraw the full amount of funds they deposited, and the same amount of funds will be permanently locked in the system.
The missed updated total debt will:
continuing accruing interest
reduce the available liquidity to use, so reduce income from normal operation
gradually lock LP's fund
Based on the above, the long term impact could be deemed as "material loss of funds", high is appropriate.
hrishibhat
Result:
High
Unique
Agree with Lead judge's comment. Considering this issue a high
Fixed by moving the repay() position logic to before the position is closed
The original report as published on Sherlock, by Yuki. Images and videos are our own copies; raw HTML is shown as text. View it on Sherlock.
Not written yet. The AI write-up for this report has not been written yet. The Original tab links to the source.
Generating the AI write-up for this report.
This usually takes about a minute. You can read the original meanwhile; this page updates itself.
Writing the technical write-up
Writing the version for beginners
Checking every passage against the original
How it worked
Root cause
Likely the close-position logic accrues bad debt into bad_debt but fails to reduce total_debt_amount by the same amount, causing double counting.
Impact
Liquidity providers may be unable to withdraw their full deposited funds, and the affected amount could remain permanently locked in the system.
What the attacker needed
A position is closed with bad debt; liquidity providers attempt to withdraw
The fix
The close-position logic should repay the full position debt amount (not just the swap proceeds) so that total_debt_amount is reduced correctly, or otherwise subtract the bad debt from total_debt_amount.
How it was found
A position is fully closed and the swap returns less than the position debt.
The code calculates bad debt and adds it to the bad_debt mapping.
The code repays liquidity providers only the amount received from the swap.
The bad debt is not subtracted from total_debt_amount.
Later, available liquidity is calculated by subtracting both bad_debt and total_debt_amount, so the bad debt is subtracted twice.
Even after repay_bad_debt is called, the leftover total_debt_amount still reduces available liquidity.
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.
Generating the AI write-up for this report.
This usually takes about a minute. You can read the original meanwhile; this page updates itself.
Writing the technical write-up
Writing the version for beginners
Checking every passage against the original
In this lending protocol, when a trader's position is closed at a loss, the shortfall is called bad debt. The code records that bad debt in one place but forgets to remove it from another running total of all debt, so the same loss is effectively counted twice. That makes the protocol look more indebted than it is, and people who supplied liquidity cannot take all their money back even after the bad debt is repaid.
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.