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

Avkr003/leverage improvements #752

Merged
merged 21 commits into from
Aug 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
c7e82a2
Adding validation in params
avkr003 Aug 23, 2024
b5462af
fixing data type for msgStopLoss
avkr003 Aug 23, 2024
3b96414
removing redundant code, improving test cases for msgs and param, fix…
avkr003 Aug 23, 2024
ff8e777
fixing add/remove pool tx logic, improving validate basic of msgs and…
avkr003 Aug 23, 2024
79465d5
fixing test cases
avkr003 Aug 23, 2024
862bf1f
improving positions validate functions
avkr003 Aug 26, 2024
08b6dfc
optimizing BeginBlocker for leveragelp, improving it's nomenclature, …
avkr003 Aug 26, 2024
9dd346f
adding test cases for close positions tx
avkr003 Aug 26, 2024
814fd80
[critical] Removed IsPoolEnabled function which add pool without gove…
avkr003 Aug 26, 2024
a7fe542
adding more validations
avkr003 Aug 26, 2024
59e6a4c
Merge branch 'main' of https://github.com/elys-network/elys into avkr…
avkr003 Aug 26, 2024
be12a2c
Fixing tx
avkr003 Aug 26, 2024
d39d83f
correcting test structure
avkr003 Aug 26, 2024
f745da2
pr review fixes
avkr003 Aug 27, 2024
dde0a10
Merge branch 'main' of https://github.com/elys-network/elys into avkr…
avkr003 Aug 27, 2024
4dfe381
fixing test failing
avkr003 Aug 27, 2024
c0fb943
self review correction
avkr003 Aug 27, 2024
56d0811
test case correction
avkr003 Aug 27, 2024
92c2391
Merge branch 'main' of https://github.com/elys-network/elys into avkr…
avkr003 Aug 29, 2024
1980e63
merging with main
avkr003 Aug 29, 2024
832f4df
Merge branch 'main' of https://github.com/elys-network/elys into avkr…
avkr003 Aug 29, 2024
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
16 changes: 8 additions & 8 deletions proto/elys/leveragelp/tx.proto
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ service Msg {
rpc Close (MsgClose) returns (MsgCloseResponse);
rpc ClaimRewards (MsgClaimRewards) returns (MsgClaimRewardsResponse);
rpc UpdateParams (MsgUpdateParams) returns (MsgUpdateParamsResponse);
rpc AddPools (MsgAddPool) returns (MsgAddPoolResponse);
rpc UpdatePools (MsgUpdatePools) returns (MsgUpdatePoolsResponse);
rpc AddPool (MsgAddPool) returns (MsgAddPoolResponse);
rpc UpdatePool (MsgUpdatePool) returns (MsgUpdatePoolResponse);
rpc RemovePool (MsgRemovePool) returns (MsgRemovePoolResponse);
rpc Whitelist (MsgWhitelist) returns (MsgWhitelistResponse);
rpc Dewhitelist (MsgDewhitelist) returns (MsgDewhitelistResponse);
Expand Down Expand Up @@ -66,16 +66,16 @@ message MsgUpdateParamsResponse {}

message UpdatePool {
uint64 pool_id = 1;
bool Enabled = 2;
bool Closed = 3;
bool enabled = 2;
bool closed = 3;
}

message MsgUpdatePools {
message MsgUpdatePool {
string authority = 1;
UpdatePool UpdatePool = 2;
}

message MsgUpdatePoolsResponse {}
message MsgUpdatePoolResponse {}

message MsgWhitelist {
string authority = 1;
Expand All @@ -93,7 +93,7 @@ message MsgDewhitelistResponse {}

message MsgUpdateStopLoss {
string creator = 1;
int32 position = 2;
uint64 position = 2;
string price = 3 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false];
}

Expand Down Expand Up @@ -131,7 +131,7 @@ message MsgRemovePoolResponse {}
message MsgClosePositions {
string creator = 1;
repeated PositionRequest liquidate = 2;
repeated PositionRequest stoploss = 3;
repeated PositionRequest stop_loss = 3;
}

message MsgClosePositionsResponse {}
Expand Down
7 changes: 1 addition & 6 deletions proto/elys/leveragelp/types.proto
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import "cosmos/base/v1beta1/coin.proto";

message PositionRequest {
string address = 1;
uint64 id = 2;
uint64 id = 2;
}

message Position {
Expand Down Expand Up @@ -70,11 +70,6 @@ message LegacyPosition {
];
}

message AddressId {
string address = 1;
uint64 id = 2;
}

message PositionAndInterest {
Position position = 1;
string interest_rate_hour = 2 [
Expand Down
2 changes: 1 addition & 1 deletion x/amm/client/wasm/query_earn_mining_pool_all.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func (oq *Querier) generateEarnPool(ctx sdk.Context, ammPool *types.Pool, filter

leverageLpPool, found := oq.leveragelpKeeper.GetPool(ctx, ammPool.PoolId)
if found {
isLeverageLpEnabled = oq.leveragelpKeeper.IsPoolEnabled(ctx, ammPool.PoolId)
isLeverageLpEnabled = leverageLpPool.Enabled
leverageLpPercent = leverageLpPool.LeveragedLpAmount.ToLegacyDec().Quo(ammPool.TotalShares.Amount.ToLegacyDec()).Mul(sdk.NewDec(100))
}

Expand Down
2 changes: 1 addition & 1 deletion x/leveragelp/client/cli/tx_add_pool.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func CmdAddPools() *cobra.Command {
}

govAddress := sdk.AccAddress(address.Module("gov"))
msg := types.NewMsgAddPools(
msg := types.NewMsgAddPool(
govAddress.String(),
pool,
)
Expand Down
4 changes: 2 additions & 2 deletions x/leveragelp/client/cli/tx_close_positions.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ func CmdClosePositions() *cobra.Command {
}

msg := types.NewMsgClosePositions(
clientCtx.GetFromAddress().String(),
clientCtx.GetFromAddress(),
liqudiatePtrs,
stoplossPtrs,
)
if err := msg.ValidateBasic(); err != nil {
if err = msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
Expand Down
2 changes: 1 addition & 1 deletion x/leveragelp/client/cli/tx_update_pools.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ func CmdUpdatePools() *cobra.Command {
}

govAddress := sdk.AccAddress(address.Module("gov"))
msg := types.NewMsgUpdatePools(
msg := types.NewMsgUpdatePool(
govAddress.String(),
pool,
)
Expand Down
4 changes: 2 additions & 2 deletions x/leveragelp/client/cli/tx_update_stop_loss.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ func CmdUpdateStopLoss() *cobra.Command {
Short: "Broadcast message update-stop-loss",
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) (err error) {
argPosition, err := cast.ToInt32E(args[0])
argPosition, err := cast.ToUint64E(args[0])
if err != nil {
return err
}
Expand All @@ -39,7 +39,7 @@ func CmdUpdateStopLoss() *cobra.Command {
argPosition,
argPrice,
)
if err := msg.ValidateBasic(); err != nil {
if err = msg.ValidateBasic(); err != nil {
return err
}
return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg)
Expand Down
2 changes: 1 addition & 1 deletion x/leveragelp/keeper/add_collateral.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ func (k Keeper) ProcessAddCollateral(ctx sdk.Context, address string, id uint64,
}

// Check if the pool is enabled.
if !k.IsPoolEnabled(ctx, position.AmmPoolId) {
if !pool.Enabled {
return errorsmod.Wrap(types.ErrPositionDisabled, fmt.Sprintf("poolId: %d", position.AmmPoolId))
}

Expand Down
34 changes: 19 additions & 15 deletions x/leveragelp/keeper/begin_blocker.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,23 +40,27 @@
for _, position := range positions {
pool, found := k.GetPool(ctx, position.AmmPoolId)
if !found {
ctx.Logger().Error(fmt.Sprintf("pool not found for id: %d", position.AmmPoolId))
continue
}
ammPool, err := k.GetAmmPool(ctx, pool.AmmPoolId)
if err != nil {
ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error getting amm pool: %d", pool.AmmPoolId)).Error())
ammPool, poolErr := k.GetAmmPool(ctx, pool.AmmPoolId)
if poolErr != nil {
ctx.Logger().Error(fmt.Sprintf("error getting for amm pool %d: %s", position.AmmPoolId, poolErr.Error()))
continue
}
isHealthy, _, _, _ := k.LiquidatePositionIfUnhealthy(ctx, position, pool, ammPool)
if !isHealthy {

isHealthy, closeAttempted, _, err := k.CheckAndLiquidateUnhealthyPosition(ctx, position, pool, ammPool)
if err == nil {
continue
}
k.ClosePositionIfUnderStopLossPrice(ctx, position, pool, ammPool)
if isHealthy && !closeAttempted {
_, _, _ = k.CheckAndCloseAtStopLoss(ctx, position, pool, ammPool)
}
}
}
}

func (k Keeper) LiquidatePositionIfUnhealthy(ctx sdk.Context, position *types.Position, pool types.Pool, ammPool ammtypes.Pool) (isHealthy, earlyReturn bool, health math.LegacyDec, err error) {
func (k Keeper) CheckAndLiquidateUnhealthyPosition(ctx sdk.Context, position *types.Position, pool types.Pool, ammPool ammtypes.Pool) (isHealthy, closeAttempted bool, health math.LegacyDec, err error) {
defer func() {
if r := recover(); r != nil {
if msg, ok := r.(string); ok {
Expand All @@ -67,7 +71,7 @@
h, err := k.GetPositionHealth(ctx, *position)
if err != nil {
ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error updating position health: %s", position.String())).Error())
return false, true, sdk.ZeroDec(), err
return false, false, sdk.ZeroDec(), err
amityadav0 marked this conversation as resolved.
Show resolved Hide resolved
}
position.PositionHealth = h
k.SetPosition(ctx, position)
Expand All @@ -78,7 +82,7 @@
debt := k.stableKeeper.UpdateInterestAndGetDebt(ctx, position.GetPositionAddress())
liab := debt.GetTotalLiablities()
if isHealthy || liab.IsZero() {
return true, false, h, err
return true, false, h, fmt.Errorf("position is healthy to close")
}

repayAmount, err := k.ForceCloseLong(ctx, *position, pool, position.LeveragedLpAmount)
Expand All @@ -95,10 +99,10 @@
sdk.NewAttribute("liabilities", position.Liabilities.String()),
sdk.NewAttribute("health", position.PositionHealth.String()),
))
return isHealthy, false, h, nil
return isHealthy, true, h, nil
amityadav0 marked this conversation as resolved.
Show resolved Hide resolved
}

func (k Keeper) ClosePositionIfUnderStopLossPrice(ctx sdk.Context, position *types.Position, pool types.Pool, ammPool ammtypes.Pool) (underStopLossPrice, earlyReturn bool, err error) {
func (k Keeper) CheckAndCloseAtStopLoss(ctx sdk.Context, position *types.Position, pool types.Pool, ammPool ammtypes.Pool) (underStopLossPrice, closeAttempted bool, err error) {
defer func() {
if r := recover(); r != nil {
if msg, ok := r.(string); ok {
Expand All @@ -109,19 +113,19 @@
h, err := k.GetPositionHealth(ctx, *position)
if err != nil {
ctx.Logger().Error(errors.Wrap(err, fmt.Sprintf("error updating position health: %s", position.String())).Error())
return false, true, err
return false, false, err
}
position.PositionHealth = h
k.SetPosition(ctx, position)

lpTokenPrice, err := ammPool.LpTokenPrice(ctx, k.oracleKeeper)
if err != nil {
return false, true, err
return false, false, err

Check warning on line 123 in x/leveragelp/keeper/begin_blocker.go

View check run for this annotation

Codecov / codecov/patch

x/leveragelp/keeper/begin_blocker.go#L123

Added line #L123 was not covered by tests
amityadav0 marked this conversation as resolved.
Show resolved Hide resolved
}

underStopLossPrice = !position.StopLossPrice.IsNil() && lpTokenPrice.LTE(position.StopLossPrice)
if !underStopLossPrice {
return underStopLossPrice, false, err
return underStopLossPrice, false, fmt.Errorf("position stop loss price is not <= lp token price")
}

repayAmount, err := k.ForceCloseLong(ctx, *position, pool, position.LeveragedLpAmount)
Expand All @@ -138,5 +142,5 @@
sdk.NewAttribute("liabilities", position.Liabilities.String()),
sdk.NewAttribute("health", position.PositionHealth.String()),
))
return underStopLossPrice, false, err
return underStopLossPrice, true, nil
}
Loading
Loading