Skip to content

Commit

Permalink
Avkr003/perp fixes (#895)
Browse files Browse the repository at this point in the history
* fix: add collateral long and pool health check when leverage lp position changes

* fixing unit test cases

* code review corrections

* fixing get all perpetual query
  • Loading branch information
avkr003 authored Oct 30, 2024
1 parent 9552d76 commit 92a33a9
Show file tree
Hide file tree
Showing 28 changed files with 216 additions and 122 deletions.
6 changes: 3 additions & 3 deletions x/accountedpool/keeper/hooks_leveragelp.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,14 +76,14 @@ func (h LeverageLpHooks) AfterDisablingPool(ctx sdk.Context, ammPool ammtypes.Po
return h.k.OnLeverageLpPoolDisable(ctx, ammPool)
}

func (h LeverageLpHooks) AfterLeverageLpPositionOpen(ctx sdk.Context, sender sdk.AccAddress) error {
func (h LeverageLpHooks) AfterLeverageLpPositionOpen(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error {
return nil
}

func (h LeverageLpHooks) AfterLeverageLpPositionClose(ctx sdk.Context, sender sdk.AccAddress) error {
func (h LeverageLpHooks) AfterLeverageLpPositionClose(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error {
return nil
}

func (h LeverageLpHooks) AfterLeverageLpPositionOpenConsolidate(ctx sdk.Context, sender sdk.AccAddress) error {
func (h LeverageLpHooks) AfterLeverageLpPositionOpenConsolidate(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error {
return nil
}
4 changes: 0 additions & 4 deletions x/accountedpool/migrations/v2_migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,5 @@ import (
)

func (m Migrator) V2Migration(ctx sdk.Context) error {
allAccountedPool := m.keeper.GetAllAccountedPool(ctx)
for _, accountedPool := range allAccountedPool {
m.keeper.RemoveAccountedPool(ctx, accountedPool.PoolId)
}
return nil
}
1 change: 1 addition & 0 deletions x/leveragelp/keeper/hooks_amm.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
func (k Keeper) CheckAmmPoolUsdcBalance(ctx sdk.Context, ammPool ammtypes.Pool) error {
leveragePool, found := k.GetPool(ctx, ammPool.PoolId)
if !found {
// It is possible that this pool haven't been enabled
return nil
}

Expand Down
15 changes: 11 additions & 4 deletions x/leveragelp/keeper/msg_server_claim_rewards_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/address"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
simapp "github.com/elys-network/elys/app"
ammtypes "github.com/elys-network/elys/x/amm/types"
Expand Down Expand Up @@ -59,11 +60,17 @@ func initializeForClaimRewards(suite *KeeperTestSuite, addresses []sdk.AccAddres
}
if createAmmPool {
poolId, err := suite.app.AmmKeeper.CreatePool(suite.ctx, &msgCreatePool)
if err != nil {
panic(err)
suite.Require().NoError(err)
enablePoolMsg := types.MsgAddPool{
Authority: authtypes.NewModuleAddress("gov").String(),
Pool: types.AddPool{
AmmPoolId: poolId,
LeverageMax: math.LegacyNewDec(10),
},
}

suite.app.LeveragelpKeeper.SetPool(suite.ctx, types.NewPool(poolId, math.LegacyMustNewDecFromStr("10")))
msgServer := keeper.NewMsgServerImpl(*suite.app.LeveragelpKeeper)
_, err = msgServer.AddPool(suite.ctx, &enablePoolMsg)
suite.Require().NoError(err)

}
msgBond := stabletypes.MsgBond{
Expand Down
6 changes: 5 additions & 1 deletion x/leveragelp/keeper/msg_server_close.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,11 @@ func (k Keeper) Close(ctx sdk.Context, msg *types.MsgClose) (*types.MsgCloseResp
}

if k.hooks != nil {
err := k.hooks.AfterLeverageLpPositionClose(ctx, sdk.MustAccAddressFromBech32(msg.Creator))
ammPool, err := k.GetAmmPool(ctx, closedPosition.AmmPoolId)
if err != nil {
return nil, err
}
err = k.hooks.AfterLeverageLpPositionClose(ctx, sdk.MustAccAddressFromBech32(msg.Creator), ammPool)
if err != nil {
return nil, err
}
Expand Down
31 changes: 26 additions & 5 deletions x/leveragelp/keeper/msg_server_close_positions.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package keeper

import (
"context"
errorsmod "cosmossdk.io/errors"
"fmt"
"strings"

Expand Down Expand Up @@ -34,6 +35,20 @@ func (k msgServer) ClosePositions(goCtx context.Context, msg *types.MsgClosePosi
// Add log about error or not liquidated
liqLog = append(liqLog, fmt.Sprintf("Position: Address:%s Id:%d cannot be liquidated due to err: %s", position.Address, position.Id, err.Error()))
}

if k.hooks != nil {
// ammPool will have updated values for opening position
found := false
ammPool, found = k.amm.GetPool(ctx, position.AmmPoolId)
if !found {
return nil, errorsmod.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("poolId: %d", position.AmmPoolId))
}
err = k.hooks.AfterLeverageLpPositionClose(ctx, position.GetOwnerAddress(), ammPool)
if err != nil {
return nil, err
}
}

}

// Handle stop loss
Expand All @@ -57,12 +72,18 @@ func (k msgServer) ClosePositions(goCtx context.Context, msg *types.MsgClosePosi
// Add log about error or not closed
closeLog = append(closeLog, fmt.Sprintf("Position: Address:%s Id:%d cannot be liquidated due to err: %s", position.Address, position.Id, err.Error()))
}
}

if k.hooks != nil {
err := k.hooks.AfterLeverageLpPositionClose(ctx, sdk.MustAccAddressFromBech32(msg.Creator))
if err != nil {
return nil, err
if k.hooks != nil {
// ammPool will have updated values for opening position
found := false
ammPool, found = k.amm.GetPool(ctx, position.AmmPoolId)
if !found {
return nil, errorsmod.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("poolId: %d", position.AmmPoolId))
}
err = k.hooks.AfterLeverageLpPositionClose(ctx, position.GetOwnerAddress(), ammPool)
if err != nil {
return nil, err
}
}
}

Expand Down
16 changes: 13 additions & 3 deletions x/leveragelp/keeper/msg_server_close_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package keeper_test

import (
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
"github.com/elys-network/elys/x/leveragelp/keeper"
"time"

"cosmossdk.io/math"
Expand Down Expand Up @@ -57,9 +59,17 @@ func initializeForClose(suite *KeeperTestSuite, addresses []sdk.AccAddress, asse
},
}
poolId, err := suite.app.AmmKeeper.CreatePool(suite.ctx, &msgCreatePool)
if err != nil {
panic(err)
suite.Require().NoError(err)
enablePoolMsg := types.MsgAddPool{
Authority: authtypes.NewModuleAddress("gov").String(),
Pool: types.AddPool{
AmmPoolId: poolId,
LeverageMax: math.LegacyNewDec(10),
},
}
msgServer := keeper.NewMsgServerImpl(*suite.app.LeveragelpKeeper)
_, err = msgServer.AddPool(suite.ctx, &enablePoolMsg)
suite.Require().NoError(err)
suite.app.LeveragelpKeeper.SetPool(suite.ctx, types.NewPool(poolId, math.LegacyMustNewDecFromStr("10")))
msgBond := stabletypes.MsgBond{
Creator: addresses[1].String(),
Expand Down Expand Up @@ -266,7 +276,7 @@ func (suite *KeeperTestSuite) TestClose() {
},
func() {
position, _ := suite.app.LeveragelpKeeper.GetPosition(suite.ctx, addresses[0], 1)
actualShares, ok := sdk.NewIntFromString("9999952380952380950")
actualShares, ok := sdk.NewIntFromString("9995950947287941390")
suite.Require().True(ok)
suite.Require().Equal(position.LeveragedLpAmount, actualShares)
},
Expand Down
11 changes: 8 additions & 3 deletions x/leveragelp/keeper/msg_server_open.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,11 +40,11 @@ func (k Keeper) Open(ctx sdk.Context, msg *types.MsgOpen) (*types.MsgOpenRespons
if !found {
return nil, errorsmod.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("poolId: %d", msg.AmmPoolId))
}
amm_pool, found := k.amm.GetPool(ctx, msg.AmmPoolId)
ammPool, found := k.amm.GetPool(ctx, msg.AmmPoolId)
if !found {
return nil, errorsmod.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("poolId: %d", msg.AmmPoolId))
}
poolLeveragelpRatio = pool.LeveragedLpAmount.ToLegacyDec().Quo(amm_pool.TotalShares.Amount.ToLegacyDec())
poolLeveragelpRatio = pool.LeveragedLpAmount.ToLegacyDec().Quo(ammPool.TotalShares.Amount.ToLegacyDec())

if poolLeveragelpRatio.GTE(pool.MaxLeveragelpRatio) || borrowRatio.GTE(params.MaxLeverageRatio) {
return nil, errorsmod.Wrap(types.ErrMaxLeverageLpExists, "no new position can be open")
Expand Down Expand Up @@ -79,7 +79,12 @@ func (k Keeper) Open(ctx sdk.Context, msg *types.MsgOpen) (*types.MsgOpenRespons
}

if k.hooks != nil {
err := k.hooks.AfterLeverageLpPositionOpen(ctx, sdk.MustAccAddressFromBech32(msg.Creator))
// ammPool will have updated values for opening position
ammPool, found = k.amm.GetPool(ctx, msg.AmmPoolId)
if !found {
return nil, errorsmod.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("poolId: %d", msg.AmmPoolId))
}
err = k.hooks.AfterLeverageLpPositionOpen(ctx, sdk.MustAccAddressFromBech32(msg.Creator), ammPool)
if err != nil {
return nil, err
}
Expand Down
22 changes: 13 additions & 9 deletions x/leveragelp/keeper/msg_server_update_stop_loss_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package keeper_test
import (
"cosmossdk.io/math"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
simapp "github.com/elys-network/elys/app"
ammtypes "github.com/elys-network/elys/x/amm/types"
Expand Down Expand Up @@ -56,24 +57,27 @@ func initializeForUpdateStopLoss(suite *KeeperTestSuite, addresses []sdk.AccAddr
},
}
poolId, err := suite.app.AmmKeeper.CreatePool(suite.ctx, &msgCreatePool)
if err != nil {
panic(err)
suite.Require().NoError(err)
enablePoolMsg := types.MsgAddPool{
Authority: authtypes.NewModuleAddress("gov").String(),
Pool: types.AddPool{
AmmPoolId: poolId,
LeverageMax: math.LegacyNewDec(10),
},
}
suite.app.LeveragelpKeeper.SetPool(suite.ctx, types.NewPool(poolId, math.LegacyMustNewDecFromStr("10")))
msgServer := keeper.NewMsgServerImpl(*suite.app.LeveragelpKeeper)
_, err = msgServer.AddPool(suite.ctx, &enablePoolMsg)
suite.Require().NoError(err)
msgBond := stabletypes.MsgBond{
Creator: addresses[1].String(),
Amount: issueAmount.QuoRaw(20),
}
stableStakeMsgServer := stablekeeper.NewMsgServerImpl(suite.app.StablestakeKeeper)
_, err = stableStakeMsgServer.Bond(suite.ctx, &msgBond)
if err != nil {
panic(err)
}
suite.Require().NoError(err)
msgBond.Creator = addresses[2].String()
_, err = stableStakeMsgServer.Bond(suite.ctx, &msgBond)
if err != nil {
panic(err)
}
suite.Require().NoError(err)

if openPosition {
openMsg := &types.MsgOpen{
Expand Down
5 changes: 4 additions & 1 deletion x/leveragelp/keeper/position_close.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,10 @@ func (k Keeper) ForceCloseLong(ctx sdk.Context, position types.Position, pool ty
position.LeveragedLpAmount = position.LeveragedLpAmount.Sub(lpAmount)
if position.LeveragedLpAmount.IsZero() {
// As we have already exited the pool, we need to delete the position
k.masterchefKeeper.ClaimRewards(ctx, position.GetPositionAddress(), []uint64{position.AmmPoolId}, positionOwner)
err = k.masterchefKeeper.ClaimRewards(ctx, position.GetPositionAddress(), []uint64{position.AmmPoolId}, positionOwner)
if err != nil {
return math.Int{}, err
}
err = k.DestroyPosition(ctx, positionOwner, position.Id)
if err != nil {
return sdk.ZeroInt(), err
Expand Down
7 changes: 6 additions & 1 deletion x/leveragelp/keeper/position_open.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ func (k Keeper) OpenConsolidate(ctx sdk.Context, position *types.Position, msg *
}

if k.hooks != nil {
err := k.hooks.AfterLeverageLpPositionOpenConsolidate(ctx, sdk.MustAccAddressFromBech32(msg.Creator))
// ammPool will have updated values for opening position
ammPool, found := k.amm.GetPool(ctx, msg.AmmPoolId)
if !found {
return nil, errorsmod.Wrap(types.ErrPoolDoesNotExist, fmt.Sprintf("poolId: %d", msg.AmmPoolId))
}
err = k.hooks.AfterLeverageLpPositionOpenConsolidate(ctx, sdk.MustAccAddressFromBech32(msg.Creator), ammPool)
if err != nil {
return nil, err
}
Expand Down
21 changes: 14 additions & 7 deletions x/leveragelp/keeper/position_open_test.go
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
package keeper_test

import (
"cosmossdk.io/math"
"github.com/cometbft/cometbft/crypto/ed25519"
sdk "github.com/cosmos/cosmos-sdk/types"
authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
minttypes "github.com/cosmos/cosmos-sdk/x/mint/types"
ammtypes "github.com/elys-network/elys/x/amm/types"
"github.com/elys-network/elys/x/leveragelp/keeper"
"github.com/elys-network/elys/x/leveragelp/types"
stablestakekeeper "github.com/elys-network/elys/x/stablestake/keeper"
stablestaketypes "github.com/elys-network/elys/x/stablestake/types"
Expand All @@ -16,12 +19,6 @@ func (suite KeeperTestSuite) TestOpenLong() {
addr := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address())
poolAddr := ammtypes.NewPoolAddress(uint64(1))
treasuryAddr := sdk.AccAddress(ed25519.GenPrivKey().PubKey().Address())
pool := types.Pool{
AmmPoolId: 1,
Health: sdk.ZeroDec(),
LeveragedLpAmount: sdk.ZeroInt(),
LeverageMax: sdk.OneDec().MulInt64(10),
}
poolInit := sdk.Coins{sdk.NewInt64Coin("uusdc", 100000), sdk.NewInt64Coin("uusdt", 100000)}

err := suite.app.BankKeeper.MintCoins(suite.ctx, minttypes.ModuleName, poolInit)
Expand Down Expand Up @@ -57,7 +54,17 @@ func (suite KeeperTestSuite) TestOpenLong() {
},
TotalWeight: sdk.NewInt(20),
})
k.SetPool(suite.ctx, pool)
suite.Require().NoError(err)
enablePoolMsg := types.MsgAddPool{
Authority: authtypes.NewModuleAddress("gov").String(),
Pool: types.AddPool{
AmmPoolId: 1,
LeverageMax: math.LegacyNewDec(10),
},
}
msgServer := keeper.NewMsgServerImpl(*suite.app.LeveragelpKeeper)
_, err = msgServer.AddPool(suite.ctx, &enablePoolMsg)
suite.Require().NoError(err)
suite.app.AmmKeeper.SetDenomLiquidity(suite.ctx, ammtypes.DenomLiquidity{
Denom: "uusdc",
Liquidity: sdk.NewInt(100000),
Expand Down
17 changes: 0 additions & 17 deletions x/leveragelp/migrations/v16_migration.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,5 @@ import (
)

func (m Migrator) V16Migration(ctx sdk.Context) error {
allPools := m.keeper.GetAllPools(ctx)

for _, pool := range allPools {
hooks := m.keeper.GetHooks()

if hooks != nil {
ammPool, err := m.keeper.GetAmmPool(ctx, pool.AmmPoolId)
if err != nil {
return err
}
err = hooks.AfterEnablingPool(ctx, ammPool)
if err != nil {
return err
}
}
}

return nil
}
18 changes: 9 additions & 9 deletions x/leveragelp/types/hooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,13 @@ type LeverageLpHooks interface {
AfterDisablingPool(ctx sdk.Context, ammPool ammtypes.Pool) error

// AfterLeverageLpPositionOpen is called after Open position.
AfterLeverageLpPositionOpen(ctx sdk.Context, sender sdk.AccAddress) error
AfterLeverageLpPositionOpen(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error

// AfterLeverageLpPositionClose is called after a position gets closed.
AfterLeverageLpPositionClose(ctx sdk.Context, sender sdk.AccAddress) error
AfterLeverageLpPositionClose(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error

// AfterLeverageLpPositionConsolidate is called after a position gets closed.
AfterLeverageLpPositionOpenConsolidate(ctx sdk.Context, sender sdk.AccAddress) error
AfterLeverageLpPositionOpenConsolidate(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error
}

var _ LeverageLpHooks = MultiLeverageLpHooks{}
Expand Down Expand Up @@ -49,29 +49,29 @@ func (h MultiLeverageLpHooks) AfterDisablingPool(ctx sdk.Context, ammPool ammtyp
return nil
}

func (h MultiLeverageLpHooks) AfterLeverageLpPositionOpen(ctx sdk.Context, sender sdk.AccAddress) error {
func (h MultiLeverageLpHooks) AfterLeverageLpPositionOpen(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error {
for i := range h {
err := h[i].AfterLeverageLpPositionOpen(ctx, sender)
err := h[i].AfterLeverageLpPositionOpen(ctx, sender, ammPool)
if err != nil {
return err
}
}
return nil
}

func (h MultiLeverageLpHooks) AfterLeverageLpPositionClose(ctx sdk.Context, sender sdk.AccAddress) error {
func (h MultiLeverageLpHooks) AfterLeverageLpPositionClose(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error {
for i := range h {
err := h[i].AfterLeverageLpPositionClose(ctx, sender)
err := h[i].AfterLeverageLpPositionClose(ctx, sender, ammPool)
if err != nil {
return err
}
}
return nil
}

func (h MultiLeverageLpHooks) AfterLeverageLpPositionOpenConsolidate(ctx sdk.Context, sender sdk.AccAddress) error {
func (h MultiLeverageLpHooks) AfterLeverageLpPositionOpenConsolidate(ctx sdk.Context, sender sdk.AccAddress, ammPool ammtypes.Pool) error {
for i := range h {
err := h[i].AfterLeverageLpPositionOpenConsolidate(ctx, sender)
err := h[i].AfterLeverageLpPositionOpenConsolidate(ctx, sender, ammPool)
if err != nil {
return err
}
Expand Down
2 changes: 1 addition & 1 deletion x/perpetual/keeper/calc_total_liabilities_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ func (suite PerpetualKeeperTestSuite) TestCalcTotalLiabilities() {
ptypes.ATOM,
func() {
amount := sdk.OneInt().MulRaw(1000_000)
ammPool = suite.SetAndGetAmmPool(addr[0], poolId, true, sdk.ZeroDec(), sdk.ZeroDec(), ptypes.ATOM, amount, amount)
ammPool = suite.CreateNewAmmPool(addr[0], true, sdk.ZeroDec(), sdk.ZeroDec(), ptypes.ATOM, amount, amount)
poolAsset.Liabilities = amount.MulRaw(100)
},
func(totalLiabilities sdk.Int) {
Expand Down
Loading

0 comments on commit 92a33a9

Please sign in to comment.