0g-chain/x/earn/keeper/withdraw.go
Kevin Davis ef874f9913
feat: add proposals for community pool deposits/withdrawals (#1304)
* feat: community pool deposit/withdraw proposals

* fix: check community pool balance in tests

* add new msg type definitions

* add msg methods and tests

* add module and keeper skeleton

* add deposit and withdraw methods (no delegation)

* untested depsit/withdraw with delegation methods

* add cli cmds

* fix cli argument parsing

* add tests for delegate/undelegate msgs

* emit un/delegate events

* add godoc comments

* tally handler with liquid staking support

* clean up

* update for liquid keeper changes

* Exclude non-bkava denoms from aggregate underlying ukava calculation

* wip Add claim

* Add distr keeper and claiming

* Add claim test

* Update claim test with failures

* wip Add staking rewards

* -S

Fix savings to earn incentive methods

* Use a single accural time for all earn incentives

* Add additional required liquid methods

* Update genesis to only include 1 accrual time for earn

* Revert "Update genesis to only include 1 accrual time for earn"

This reverts commit cc7e35347298681c0c8a4a0b9bf9b9b296c25531.

* Revert "Use a single accural time for all earn incentives"

This reverts commit aeb49c4622d4e3d99dc6421c8830932b1b546be9.

* Update tests with incentive distribution

* Add earn to incentive rewards query

* add earn cli tx

* Update claim example to use ukava large

* add proposal to gov router

* fix example tx formating

* add proposal handlers to gov app module

* fix: define gov router after earn keeper

* fix: correct proposal type

* remove outdated comment

* refactor withdraw so that fee pool is allows adjusted by the actual withdraw amount

* fix: lint proto file

* use non blocked module account instead of dist acc

* add fund mod account to app, enable receiving

* update to new withdraw interface

* add human readable apy test cases

* remove duplicate changes from previous merge

* remove deprecated io/ioutil package

* standardize proposal type as a pointer
(also matches sdk)

* minior comments and formatting

* use withdraw amount in router msgs

Co-authored-by: rhuairahrighairigh <ruaridh.odonnell@gmail.com>
Co-authored-by: Draco <draco@dracoli.com>
Co-authored-by: drklee3 <derrick@dlee.dev>
Co-authored-by: Ruaridh <rhuairahrighairidh@users.noreply.github.com>
2022-09-29 18:01:06 +01:00

169 lines
5.3 KiB
Go

package keeper
import (
"fmt"
sdk "github.com/cosmos/cosmos-sdk/types"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
"github.com/kava-labs/kava/x/earn/types"
)
// Withdraw removes the amount of supplied tokens from a vault and transfers it
// back to the account.
func (k *Keeper) Withdraw(
ctx sdk.Context,
from sdk.AccAddress,
wantAmount sdk.Coin,
withdrawStrategy types.StrategyType,
) (sdk.Coin, error) {
// Get AllowedVault, if not found (not a valid vault), return error
allowedVault, found := k.GetAllowedVault(ctx, wantAmount.Denom)
if !found {
return sdk.Coin{}, types.ErrInvalidVaultDenom
}
if wantAmount.IsZero() {
return sdk.Coin{}, types.ErrInsufficientAmount
}
// Check if withdraw strategy is supported by vault
if !allowedVault.IsStrategyAllowed(withdrawStrategy) {
return sdk.Coin{}, types.ErrInvalidVaultStrategy
}
// Check if VaultRecord exists
vaultRecord, found := k.GetVaultRecord(ctx, wantAmount.Denom)
if !found {
return sdk.Coin{}, types.ErrVaultRecordNotFound
}
// Get account share record for the vault
vaultShareRecord, found := k.GetVaultShareRecord(ctx, from)
if !found {
return sdk.Coin{}, types.ErrVaultShareRecordNotFound
}
withdrawShares, err := k.ConvertToShares(ctx, wantAmount)
if err != nil {
return sdk.Coin{}, fmt.Errorf("failed to convert assets to shares: %w", err)
}
accCurrentShares := vaultShareRecord.Shares.AmountOf(wantAmount.Denom)
// Check if account is not withdrawing more shares than they have
if accCurrentShares.LT(withdrawShares.Amount) {
return sdk.Coin{}, sdkerrors.Wrapf(
types.ErrInsufficientValue,
"account has less %s vault shares than withdraw shares, %s < %s",
wantAmount.Denom,
accCurrentShares,
withdrawShares.Amount,
)
}
// Convert shares to amount to get truncated true share value
withdrawAmount, err := k.ConvertToAssets(ctx, withdrawShares)
if err != nil {
return sdk.Coin{}, fmt.Errorf("failed to convert shares to assets: %w", err)
}
accountValue, err := k.GetVaultAccountValue(ctx, wantAmount.Denom, from)
if err != nil {
return sdk.Coin{}, fmt.Errorf("failed to get account value: %w", err)
}
// Check if withdrawAmount > account value
if withdrawAmount.Amount.GT(accountValue.Amount) {
return sdk.Coin{}, sdkerrors.Wrapf(
types.ErrInsufficientValue,
"account has less %s vault value than withdraw amount, %s < %s",
withdrawAmount.Denom,
accountValue.Amount,
withdrawAmount.Amount,
)
}
// Get the strategy for the vault
strategy, err := k.GetStrategy(allowedVault.Strategies[0])
if err != nil {
return sdk.Coin{}, err
}
// Not necessary to check if amount denom is allowed for the strategy, as
// there would be no vault record if it weren't allowed.
// Withdraw the withdrawAmount from the strategy
if err := strategy.Withdraw(ctx, withdrawAmount); err != nil {
return sdk.Coin{}, fmt.Errorf("failed to withdraw from strategy: %w", err)
}
// Send coins back to account, must withdraw from strategy first or the
// module account may not have any funds to send.
if err := k.bankKeeper.SendCoinsFromModuleToAccount(
ctx,
types.ModuleName,
from,
sdk.NewCoins(withdrawAmount),
); err != nil {
return sdk.Coin{}, err
}
// Check if new account balance of shares results in account share value
// of < 1 of a sdk.Coin. This share value is not able to be withdrawn and
// should just be removed.
isDust, err := k.ShareIsDust(
ctx,
vaultShareRecord.Shares.GetShare(withdrawAmount.Denom).Sub(withdrawShares),
)
if err != nil {
return sdk.Coin{}, err
}
if isDust {
// Modify withdrawShares to subtract entire share balance for denom
// This does not modify the actual withdraw coin amount as the
// difference is < 1coin.
withdrawShares = vaultShareRecord.Shares.GetShare(withdrawAmount.Denom)
}
// Call hook before record is modified
k.BeforeVaultDepositModified(ctx, wantAmount.Denom, from, vaultRecord.TotalShares.Amount)
// Decrement VaultRecord and VaultShareRecord supplies - must delete same
// amounts
vaultShareRecord.Shares = vaultShareRecord.Shares.Sub(withdrawShares)
vaultRecord.TotalShares = vaultRecord.TotalShares.Sub(withdrawShares)
// Update VaultRecord and VaultShareRecord, deletes if zero supply
k.UpdateVaultRecord(ctx, vaultRecord)
k.UpdateVaultShareRecord(ctx, vaultShareRecord)
ctx.EventManager().EmitEvent(
sdk.NewEvent(
types.EventTypeVaultWithdraw,
sdk.NewAttribute(types.AttributeKeyVaultDenom, withdrawAmount.Denom),
sdk.NewAttribute(types.AttributeKeyOwner, from.String()),
sdk.NewAttribute(types.AttributeKeyShares, withdrawShares.Amount.String()),
sdk.NewAttribute(sdk.AttributeKeyAmount, withdrawAmount.Amount.String()),
),
)
return withdrawAmount, nil
}
// WithdrawFromModuleAccount removes the amount of supplied tokens from a vault and transfers it
// back to the module account. The module account must be unblocked from receiving transfers.
func (k *Keeper) WithdrawFromModuleAccount(
ctx sdk.Context,
from string,
wantAmount sdk.Coin,
withdrawStrategy types.StrategyType,
) (sdk.Coin, error) {
// Ensure the module account exists to prevent SendCoins from creating a new non-module account.
acc := k.accountKeeper.GetModuleAccount(ctx, from)
if acc == nil {
return sdk.Coin{}, fmt.Errorf("module account not found: %s", from)
}
return k.Withdraw(ctx, acc.GetAddress(), wantAmount, withdrawStrategy)
}