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

feat: x/metoken end block functions #2167

Merged
merged 21 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from 11 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
17 changes: 17 additions & 0 deletions x/metoken/errors/errors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package errors

type LeverageError struct {
Err error
IsRecoverable bool
}

func (le *LeverageError) Error() string {
return le.Err.Error()
}

func Wrap(err error, isRecoverable bool) *LeverageError {
return &LeverageError{
Err: err,
IsRecoverable: isRecoverable,
}
}
1 change: 1 addition & 0 deletions x/metoken/expected_keepers.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ type LeverageKeeper interface {
Withdraw(ctx sdk.Context, supplierAddr sdk.AccAddress, uToken sdk.Coin) (sdk.Coin, bool, error)
ModuleMaxWithdraw(ctx sdk.Context, spendableUTokens sdk.Coin) (sdkmath.Int, error)
GetTotalSupply(ctx sdk.Context, denom string) (sdk.Coin, error)
GetAllSupplied(ctx sdk.Context, supplierAddr sdk.AccAddress) (sdk.Coins, error)
}

// OracleKeeper interface for price feed.
Expand Down
3 changes: 1 addition & 2 deletions x/metoken/index.go
Original file line number Diff line number Diff line change
Expand Up @@ -193,10 +193,9 @@ func (i Index) HasAcceptedAsset(denom string) bool {
// SetAcceptedAsset overrides an accepted asset if exists in the list, otherwise add it to the list.
func (i *Index) SetAcceptedAsset(acceptedAsset AcceptedAsset) {
index, _ := i.AcceptedAsset(acceptedAsset.Denom)
if index > 0 {
if index < 0 {
kosegor marked this conversation as resolved.
Show resolved Hide resolved
i.AcceptedAssets = append(i.AcceptedAssets, acceptedAsset)
return
}

i.AcceptedAssets[index] = acceptedAsset
}
29 changes: 28 additions & 1 deletion x/metoken/index_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@ package metoken
import (
"testing"

"gotest.tools/v3/assert"

sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"gotest.tools/v3/assert"
)

func TestIndex_Validate(t *testing.T) {
Expand Down Expand Up @@ -92,6 +93,32 @@ func TestIndex_Validate(t *testing.T) {
}
}

func TestIndex_Update(t *testing.T) {
existingAsset := "USDT"
newAsset := "IST"
index := validIndex()
assert.Check(t, len(index.AcceptedAssets) == 1)

i, _ := index.AcceptedAsset(existingAsset)
assert.Check(t, i >= 0)

i, _ = index.AcceptedAsset(newAsset)
assert.Check(t, i == -1)

newAcceptedAsset := validAcceptedAsset(newAsset)
index.SetAcceptedAsset(newAcceptedAsset)
assert.Check(t, len(index.AcceptedAssets) == 2)

assert.Check(t, index.HasAcceptedAsset(newAsset))

newAcceptedAsset.ReservePortion = sdk.MustNewDecFromStr("0.5")
index.SetAcceptedAsset(newAcceptedAsset)

i, asset := index.AcceptedAsset(newAcceptedAsset.Denom)
assert.Check(t, i >= 0)
assert.Check(t, sdk.MustNewDecFromStr("0.5").Equal(asset.ReservePortion))
}

func TestFee_Validate(t *testing.T) {
invalidMinFee := validFee()
invalidMinFee.MinFee = sdk.MustNewDecFromStr("1.01")
Expand Down
18 changes: 16 additions & 2 deletions x/metoken/keeper/balance.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package keeper

import (
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"

"github.com/umee-network/umee/v5/util/store"
"github.com/umee-network/umee/v5/x/metoken"
)
Expand All @@ -16,7 +17,6 @@ func (k Keeper) IndexBalances(meTokenDenom string) (metoken.IndexBalances, error
return *balance, nil
}

// setIndexBalances saves an Index's Balance
func (k Keeper) setIndexBalances(balance metoken.IndexBalances) error {
if err := balance.Validate(); err != nil {
return err
Expand All @@ -25,8 +25,22 @@ func (k Keeper) setIndexBalances(balance metoken.IndexBalances) error {
return store.SetValue(k.store, keyBalance(balance.MetokenSupply.Denom), &balance, "balance")
}

// hasIndexBalance returns true when Index exists.
func (k Keeper) hasIndexBalance(meTokenDenom string) bool {
balance := store.GetValue[*metoken.IndexBalances](k.store, keyBalance(meTokenDenom), "balance")
return balance != nil
}

// updateBalances of the assets of an Index and save them.
func (k Keeper) updateBalances(balances metoken.IndexBalances, updatedBalances []metoken.AssetBalance) error {
if len(updatedBalances) > 0 {
for _, balance := range updatedBalances {
balances.SetAssetBalance(balance)
}
err := k.setIndexBalances(balances)
if err != nil {
return err
}
}

return nil
}
80 changes: 80 additions & 0 deletions x/metoken/keeper/interest.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
package keeper

import (
"errors"
"time"

sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/umee-network/umee/v5/x/metoken"
lerrors "github.com/umee-network/umee/v5/x/metoken/errors"
)

// ClaimLeverageInterest sends accrued interest from x/leverage module to x/metoken account.
func (k Keeper) ClaimLeverageInterest() error {
interestClaimTime, err := k.getNextInterestClaimTime()
if err != nil {
return err
}

if k.ctx.BlockTime().Before(interestClaimTime) {
return nil
}

leverageLiquidity, err := k.leverageKeeper.GetAllSupplied(
*k.ctx,
ModuleAddr(),
)
kosegor marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return err
}

indexes := k.GetAllRegisteredIndexes()
for _, index := range indexes {
balances, err := k.IndexBalances(index.Denom)
if err != nil {
return err
}

updatedBalances := make([]metoken.AssetBalance, 0)
for _, balance := range balances.AssetBalances {
if balance.Leveraged.IsPositive() {
found, liquidity := leverageLiquidity.Find(balance.Denom)
if !found {
continue
}

// If there is more liquidity in x/leverage than expected, we claim the delta,
// which is the accrued interest
if liquidity.Amount.GT(balance.Leveraged) {
accruedInterest := sdk.NewCoin(balance.Denom, liquidity.Amount.Sub(balance.Leveraged))
tokensWithdrawn, err := k.withdrawFromLeverage(accruedInterest)
if err != nil {
var leverageError *lerrors.LeverageError
if errors.As(err, &leverageError) && leverageError.IsRecoverable {
k.Logger().Debug(
"claiming interest: couldn't withdraw from leverage",
"error", err.Error(),
"block_time", k.ctx.BlockTime(),
)
continue
}

return err
}

balance.Interest = balance.Interest.Add(tokensWithdrawn.Amount)
updatedBalances = append(updatedBalances, balance)
}
}
}

if err = k.updateBalances(balances, updatedBalances); err != nil {
return err
}
}

k.setNextInterestClaimTime(k.ctx.BlockTime().Add(time.Duration(k.GetParams().ClaimingFrequency) * time.Second))

return nil
}
17 changes: 9 additions & 8 deletions x/metoken/keeper/intest/grpc_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,16 +3,17 @@ package keeper_test
import (
"testing"

"github.com/umee-network/umee/v5/x/metoken/mocks"
"gotest.tools/v3/assert"

sdkmath "cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"

"github.com/umee-network/umee/v5/x/metoken"
"gotest.tools/v3/assert"
"github.com/umee-network/umee/v5/x/metoken/mocks"
)

func TestQuerier_Params(t *testing.T) {
s := initKeeperTestSuite(t, nil, nil)
s := initTestSuite(t, nil, nil)
querier, ctx := s.queryClient, s.ctx

resp, err := querier.Params(ctx, nil)
Expand All @@ -25,7 +26,7 @@ func TestQuerier_Indexes(t *testing.T) {
index1 := mocks.StableIndex(mocks.MeUSDDenom)
index2 := mocks.StableIndex("me/EUR")

s := initKeeperTestSuite(t, []metoken.Index{index1, index2}, nil)
s := initTestSuite(t, []metoken.Index{index1, index2}, nil)
querier, ctx := s.queryClient, s.ctx

tcs := []struct {
Expand Down Expand Up @@ -77,7 +78,7 @@ func TestQuerier_Balances(t *testing.T) {
balance1 := mocks.ValidUSDIndexBalances(mocks.MeUSDDenom)
balance2 := mocks.ValidUSDIndexBalances("me/EUR")

s := initKeeperTestSuite(t, nil, []metoken.IndexBalances{balance1, balance2})
s := initTestSuite(t, nil, []metoken.IndexBalances{balance1, balance2})
querier, ctx := s.queryClient, s.ctx

tcs := []struct {
Expand Down Expand Up @@ -135,7 +136,7 @@ func TestQuerier_SwapFee_meUSD(t *testing.T) {
index := mocks.StableIndex(mocks.MeUSDDenom)
balances := mocks.ValidUSDIndexBalances(mocks.MeUSDDenom)

s := initKeeperTestSuite(t, []metoken.Index{index}, []metoken.IndexBalances{balances})
s := initTestSuite(t, []metoken.Index{index}, []metoken.IndexBalances{balances})
querier, ctx := s.queryClient, s.ctx

// set prices
Expand Down Expand Up @@ -212,7 +213,7 @@ func TestQuerier_RedeemFee_meUSD(t *testing.T) {
index := mocks.StableIndex(mocks.MeUSDDenom)
balances := mocks.ValidUSDIndexBalances(mocks.MeUSDDenom)

s := initKeeperTestSuite(t, []metoken.Index{index}, []metoken.IndexBalances{balances})
s := initTestSuite(t, []metoken.Index{index}, []metoken.IndexBalances{balances})
querier, ctx, app := s.queryClient, s.ctx, s.app

// set prices
Expand Down Expand Up @@ -291,7 +292,7 @@ func TestQuerier_IndexPrice(t *testing.T) {
stableBalance := mocks.EmptyUSDIndexBalances(mocks.MeUSDDenom)
nonStableBalance := mocks.EmptyNonStableIndexBalances(mocks.MeNonStableDenom)

s := initKeeperTestSuite(
s := initTestSuite(
t,
[]metoken.Index{stableIndex, nonStableIndex},
[]metoken.IndexBalances{stableBalance, nonStableBalance},
Expand Down
Loading