Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: withdraw limits #178

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 103 additions & 10 deletions contracts/VaultV3.vy
Original file line number Diff line number Diff line change
Expand Up @@ -551,13 +551,88 @@ def _max_deposit(receiver: address) -> uint256:

@view
@internal
def _max_redeem(owner: address) -> uint256:
return self.balance_of[owner]
def _max_withdraw(
owner: address,
max_loss: uint256,
strategies: DynArray[address, MAX_QUEUE]
) -> uint256:
"""
@dev Returns the max amount of `asset` an `owner` can withdraw.

@view
@internal
def _max_withdraw(owner: address) -> uint256:
return self._convert_to_assets(self.balance_of[owner], Rounding.ROUND_DOWN)
This will do a full simulation of the withdraw in order to determine
how much is currently liquid and if the `max_loss` would allow for the
tx to not revert.

This will track any expected loss to check if the tx will revert, but
not account for it in the amount returned since it is unrealised and
fp-crypto marked this conversation as resolved.
Show resolved Hide resolved
therefore will not be accounted for in the conversion rates.

i.e. If we have 100 debt and 10 of unrealised loss, the max we can get
fp-crypto marked this conversation as resolved.
Show resolved Hide resolved
out is 90, but a user of the vault will need to call withdraw with 100
in order to get the full 90 out.
"""
# Get the max amount for the owner if fully liquid.
max_assets: uint256 = self._convert_to_assets(self.balance_of[owner], Rounding.ROUND_DOWN)

# See if we have enough idle to service the withdraw.
current_idle: uint256 = self.total_idle
if max_assets > current_idle:
# Amount left that we need.
needed: uint256 = unsafe_sub(max_assets, current_idle)
# Track how much we can pull.
have: uint256 = current_idle
loss: uint256 = 0

# If no queue was passed use the default one.
_strategies: DynArray[address, MAX_QUEUE] = strategies
if len(_strategies) == 0:
_strategies = self.default_queue

for strategy in _strategies:
# Can't use an invalid strategy.
assert self.strategies[strategy].activation != 0, "inactive strategy"
fp-crypto marked this conversation as resolved.
Show resolved Hide resolved

# Get the maximum amount the vault can withdraw from the strategy.
max_withdraw: uint256 = min(needed, self.strategies[strategy].current_debt)

# Get any unrealised loss for the strategy.
unrealised_loss: uint256 = self._assess_share_of_unrealised_losses(strategy, max_withdraw)

# See if any limit is enforced by the strategy.
strategy_limit: uint256 = IStrategy(strategy).maxWithdraw(self)

# Adjust accordingly if there is a max withdraw limit.
if strategy_limit < max_withdraw - unrealised_loss:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe you should be able to remove this block if you do:

max_withdraw: uint256 = min(needed, IStrategy(strategy).maxWithdraw(self))
unrealised_loss: uint256 = self._assess_share_of_unrealised_losses(strategy, max_withdraw)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it also solves the case where max_withdraw < strategy_limit, where withdrawer would take 100% of the losses (and I don't think it should be this way anyway)

Copy link
Collaborator Author

@Schlagonia Schlagonia Sep 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since .maxWithdraw(self) will already have accounted for the losses we cannot pass that value into the _assess_share_of_unrealised_losses. Otherwise our unrealised_losses will be reduced twice.

EX:

strategy_debt = 100
current_value = 90
unrealised_loss = 10

So if a user is trying to withdraw the full 100 the unrealised_loss should be 10.

needed = 100
strategy.maxWithdraw(vault) = 90
_assess_share_of_unrealised_losses(strategy, 90) = .1 * 90 = 9

# lower unrealised loss to the proportion to the limit.
unrealised_loss = unrealised_loss * strategy_limit / max_withdraw
# Still count the unrealised loss as withdrawable.
max_withdraw = strategy_limit + unrealised_loss
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe that returning max_assets including losses can lead to issues, as smart contracts would expect to receive the losses too.

also, it doesn't comply with erc4626

max received assets should be the output (i.e. do not include losses)

Copy link
Collaborator Author

@Schlagonia Schlagonia Sep 22, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So this was an issue i was unsure how to handle. But I believe we have to count it as "withdrawable" since it is unrealized in order to comply with the standard.

I wrote the reasoning in the comments. https://github.com/Schlagonia/yearn-vaults-v3/blob/limits/contracts/VaultV3.vy#L566-L572

Basically the conversion rates the vault uses don't yet know about that loss, so the amounts shouldn't adjust for it.

The maxRedeem would also be screwed up if we didnt account for the unrealized loss as withdrawable.

Its not an ideal way to do it but im pretty sure it has to be done this way to comply to the standard.


# If 0 move on to the next strategy.
if max_withdraw == 0:
continue

# Add to what we can pull.
have += max_withdraw
# Reduce how much we have left.
needed -= max_withdraw
# Add any unrealised loss to the total
loss += unrealised_loss

if needed == 0:
break

# Update the max after going through the queue.
max_assets = have

# Check if there is a loss and a non-default value was set.
if loss > 0 and max_loss < MAX_BPS:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we want to allow max_loss = 100%?

nobody should use it but probably better to allow 100% losses

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Its the default value used in "redeem" calls if one is not given.

It shouldnt be used. But dont think there is another option we should enforce as a default on every vault

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why is 99.999999999% a valid value, but not 100%?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

100% is a valid value and is used by default for redeems. But if its 100% then we have no need to waste the gas to check the loss is within the range

# If the loss is not within the allowed range.
if loss > max_assets * max_loss / MAX_BPS:
fp-crypto marked this conversation as resolved.
Show resolved Hide resolved
# The tx will revert. Can only withdraw idle.
max_assets = current_idle
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option is to do this check (is loss >= max_loss?) every time we have a loss and return the max_assets at that point, returning the max amount of withdrawable assets before hitting a certain max_loss?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added here abb73b6


return max_assets
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is underestimates the max_assets available in cases where partially iterating through the withdraw queue would have had tolerable losses.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

abb73b6

Added to the other branch with the modules.

I Did not account for a scenario in which partial would revert but the full queue would not. Think that we shouldnt return a value that has amounts less than it that would revert. Could break things.

Perhaps that could be something to add to a preivewWithdraw/redeem


@internal
def _deposit(sender: address, recipient: address, assets: uint256) -> uint256:
Expand Down Expand Up @@ -1798,23 +1873,41 @@ def maxMint(receiver: address) -> uint256:

@view
@external
def maxWithdraw(owner: address) -> uint256:
def maxWithdraw(
owner: address,
max_loss: uint256 = 0,
strategies: DynArray[address, MAX_QUEUE] = []
) -> uint256:
"""
@notice Get the maximum amount of assets that can be withdrawn.
@dev Complies to normal 4626 interface and takes custom params.
@param owner The address that owns the shares.
@param max_loss Custom max_loss if any.
@param strategies Custom strategies queue if any.
@return The maximum amount of assets that can be withdrawn.
"""
return self._max_withdraw(owner)
return self._max_withdraw(owner, max_loss, strategies)

@view
@external
def maxRedeem(owner: address) -> uint256:
def maxRedeem(
owner: address,
max_loss: uint256 = MAX_BPS,
strategies: DynArray[address, MAX_QUEUE] = []
) -> uint256:
"""
@notice Get the maximum amount of shares that can be redeemed.
@dev Complies to normal 4626 interface and takes custom params.
fp-crypto marked this conversation as resolved.
Show resolved Hide resolved
@param owner The address that owns the shares.
@param max_loss Custom max_loss if any.
@param strategies Custom strategies queue if any.
@return The maximum amount of shares that can be redeemed.
"""
return self._max_redeem(owner)
return min(
# Max witdraw is rounding so we check against the full balance.
self._convert_to_shares(self._max_withdraw(owner, max_loss, strategies), Rounding.ROUND_UP),
self.balance_of[owner]
)

@view
@external
Expand Down
206 changes: 203 additions & 3 deletions tests/unit/vault/test_erc4626.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import ape
import pytest
from utils.constants import ROLES
from utils.constants import ROLES, DAY


def test_total_assets(asset, fish, fish_amount, create_vault, user_deposit):
Expand Down Expand Up @@ -156,6 +156,106 @@ def test_max_withdraw__with_balance_less_than_or_equal_to_total_idle__returns_ba
assert vault.maxWithdraw(fish.address) == assets


def test_max_withdraw__with_custom_params(
asset,
fish,
fish_amount,
gov,
create_vault,
create_strategy,
add_debt_to_strategy,
add_strategy_to_vault,
user_deposit,
):
vault = create_vault(asset)
shares = fish_amount
assets = shares
strategy = create_strategy(vault)
strategy_deposit = assets // 2
total_idle = assets - strategy_deposit

vault.set_role(
gov.address,
ROLES.ADD_STRATEGY_MANAGER | ROLES.DEBT_MANAGER | ROLES.MAX_DEBT_MANAGER,
sender=gov,
)
user_deposit(fish, vault, asset, assets)
add_strategy_to_vault(gov, strategy, vault)
add_debt_to_strategy(gov, strategy, vault, strategy_deposit)

assert vault.maxWithdraw(fish.address, 22, [strategy]) == assets


def test_max_withdraw__with_lossy_strategy(
asset,
fish,
fish_amount,
gov,
create_vault,
create_lossy_strategy,
add_debt_to_strategy,
add_strategy_to_vault,
user_deposit,
):
vault = create_vault(asset)
shares = fish_amount
assets = shares
strategy = create_lossy_strategy(vault)
strategy_deposit = assets // 2
loss = strategy_deposit // 2
total_idle = assets - strategy_deposit

vault.set_role(
gov.address,
ROLES.ADD_STRATEGY_MANAGER | ROLES.DEBT_MANAGER | ROLES.MAX_DEBT_MANAGER,
sender=gov,
)
user_deposit(fish, vault, asset, assets)
add_strategy_to_vault(gov, strategy, vault)
add_debt_to_strategy(gov, strategy, vault, strategy_deposit)

strategy.setLoss(gov.address, loss, sender=gov)

# Should not effect the default returned value
assert vault.maxWithdraw(fish.address, 10_000) == assets

# Should return just idle if max_loss == 0.
assert vault.maxWithdraw(fish.address) == total_idle


def test_max_withdraw__with_locked_strategy(
asset,
fish,
fish_amount,
gov,
create_vault,
create_locked_strategy,
add_debt_to_strategy,
add_strategy_to_vault,
user_deposit,
):
vault = create_vault(asset)
shares = fish_amount
assets = shares
strategy = create_locked_strategy(vault)
strategy_deposit = assets // 2
locked = strategy_deposit // 2
total_idle = assets - strategy_deposit

vault.set_role(
gov.address,
ROLES.ADD_STRATEGY_MANAGER | ROLES.DEBT_MANAGER | ROLES.MAX_DEBT_MANAGER,
sender=gov,
)
user_deposit(fish, vault, asset, assets)
add_strategy_to_vault(gov, strategy, vault)
add_debt_to_strategy(gov, strategy, vault, strategy_deposit)

strategy.setLockedFunds(locked, DAY, sender=gov)

assert vault.maxWithdraw(fish.address) == assets - locked


def test_preview_redeem(asset, fish, fish_amount, create_vault, user_deposit):
vault = create_vault(asset)
shares = fish_amount
Expand Down Expand Up @@ -193,7 +293,7 @@ def test_max_redeem__with_balance_greater_than_total_idle__returns_balance(
add_strategy_to_vault(gov, strategy, vault)
add_debt_to_strategy(gov, strategy, vault, strategy_deposit)

assert vault.maxWithdraw(fish.address) == assets
assert vault.maxRedeem(fish.address) == assets


def test_max_redeem__with_balance_less_than_or_equal_to_total_idle__returns_balance(
Expand All @@ -205,4 +305,104 @@ def test_max_redeem__with_balance_less_than_or_equal_to_total_idle__returns_bala

user_deposit(fish, vault, asset, shares)

assert vault.maxWithdraw(fish.address) == assets
assert vault.maxRedeem(fish.address) == assets


def test_max_redeem__with_custom_params(
asset,
fish,
fish_amount,
gov,
create_vault,
create_strategy,
add_debt_to_strategy,
add_strategy_to_vault,
user_deposit,
):
vault = create_vault(asset)
shares = fish_amount
assets = shares
strategy = create_strategy(vault)
strategy_deposit = assets // 2
total_idle = assets - strategy_deposit

vault.set_role(
gov.address,
ROLES.ADD_STRATEGY_MANAGER | ROLES.DEBT_MANAGER | ROLES.MAX_DEBT_MANAGER,
sender=gov,
)
user_deposit(fish, vault, asset, assets)
add_strategy_to_vault(gov, strategy, vault)
add_debt_to_strategy(gov, strategy, vault, strategy_deposit)

assert vault.maxRedeem(fish.address, 0, [strategy]) == assets


def test_max_redeem__with_lossy_strategy(
asset,
fish,
fish_amount,
gov,
create_vault,
create_lossy_strategy,
add_debt_to_strategy,
add_strategy_to_vault,
user_deposit,
):
vault = create_vault(asset)
shares = fish_amount
assets = shares
strategy = create_lossy_strategy(vault)
strategy_deposit = assets // 2
loss = strategy_deposit // 2
total_idle = assets - strategy_deposit

vault.set_role(
gov.address,
ROLES.ADD_STRATEGY_MANAGER | ROLES.DEBT_MANAGER | ROLES.MAX_DEBT_MANAGER,
sender=gov,
)
user_deposit(fish, vault, asset, assets)
add_strategy_to_vault(gov, strategy, vault)
add_debt_to_strategy(gov, strategy, vault, strategy_deposit)

strategy.setLoss(gov.address, loss, sender=gov)

# Should not effect the default returned value
assert vault.maxRedeem(fish.address) == assets

# Should return just idle if max_loss == 0.
assert vault.maxRedeem(fish.address, 0) == total_idle


def test_max_redeem__with_locked_strategy(
asset,
fish,
fish_amount,
gov,
create_vault,
create_locked_strategy,
add_debt_to_strategy,
add_strategy_to_vault,
user_deposit,
):
vault = create_vault(asset)
shares = fish_amount
assets = shares
strategy = create_locked_strategy(vault)
strategy_deposit = assets // 2
locked = strategy_deposit // 2
total_idle = assets - strategy_deposit

vault.set_role(
gov.address,
ROLES.ADD_STRATEGY_MANAGER | ROLES.DEBT_MANAGER | ROLES.MAX_DEBT_MANAGER,
sender=gov,
)
user_deposit(fish, vault, asset, assets)
add_strategy_to_vault(gov, strategy, vault)
add_debt_to_strategy(gov, strategy, vault, strategy_deposit)

strategy.setLockedFunds(locked, DAY, sender=gov)

assert vault.maxRedeem(fish.address) == assets - locked
Loading