diff --git a/docs/static/openapi.yml b/docs/static/openapi.yml index a760eef83..bb6cff8ac 100644 --- a/docs/static/openapi.yml +++ b/docs/static/openapi.yml @@ -40814,6 +40814,21 @@ paths: custom method signatures required by gogoproto. + eden_forward: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the + custom method + + signatures required by gogoproto. default: description: An unexpected error response. schema: @@ -41020,41 +41035,6 @@ paths: type: string tags: - Query - /elys-network/elys/leveragelp/get_add/{id}: - get: - summary: Queries a list of GetAdd items. - operationId: ElysLeveragelpGetAdd - responses: - '200': - description: A successful response. - schema: - type: object - default: - description: An unexpected error response. - schema: - type: object - properties: - code: - type: integer - format: int32 - message: - type: string - details: - type: array - items: - type: object - properties: - '@type': - type: string - additionalProperties: {} - parameters: - - name: id - in: path - required: true - type: integer - format: int32 - tags: - - Query /elys-network/elys/leveragelp/is-whitelisted: get: summary: Queries a list of IsWhitelisted items. @@ -41483,6 +41463,8 @@ paths: type: string updated_leverage: type: string + position_usd_value: + type: string locked_lp_token: type: string default: @@ -41571,6 +41553,8 @@ paths: type: string updated_leverage: type: string + position_usd_value: + type: string pagination: type: object properties: @@ -41699,41 +41683,48 @@ paths: position: type: object properties: - address: - type: string - collateral: + position: type: object properties: - denom: - type: string - amount: + address: type: string - description: >- - Coin defines a token with a denomination and an - amount. + collateral: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an + amount. - NOTE: The amount field is an Int which implements - the custom method + NOTE: The amount field is an Int which + implements the custom method - signatures required by gogoproto. - liabilities: - type: string - title: For recording - leverage: - type: string - title: For recording - leveraged_lp_amount: - type: string - position_health: - type: string - id: + signatures required by gogoproto. + liabilities: + type: string + title: For recording + leverage: + type: string + title: For recording + leveraged_lp_amount: + type: string + position_health: + type: string + id: + type: string + format: uint64 + amm_pool_id: + type: string + format: uint64 + stop_loss_price: + type: string + updated_leverage: type: string - format: uint64 - amm_pool_id: - type: string - format: uint64 - stop_loss_price: + position_usd_value: type: string interest_rate_hour: type: string @@ -41904,6 +41895,8 @@ paths: type: string updated_leverage: type: string + position_usd_value: + type: string pagination: type: object properties: @@ -42316,6 +42309,32 @@ paths: description: A successful response. schema: type: object + properties: + fee_info: + type: array + items: + type: object + properties: + gas_lp: + type: string + gas_stakers: + type: string + gas_protocol: + type: string + dex_lp: + type: string + dex_stakers: + type: string + dex_protocol: + type: string + perp_lp: + type: string + perp_stakers: + type: string + perp_protocol: + type: string + eden_lp: + type: string default: description: An unexpected error response. schema: @@ -42669,6 +42688,30 @@ paths: description: A successful response. schema: type: object + properties: + fee_info: + type: object + properties: + gas_lp: + type: string + gas_stakers: + type: string + gas_protocol: + type: string + dex_lp: + type: string + dex_stakers: + type: string + dex_protocol: + type: string + perp_lp: + type: string + perp_stakers: + type: string + perp_protocol: + type: string + eden_lp: + type: string default: description: An unexpected error response. schema: @@ -43601,6 +43644,12 @@ paths: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 default: description: An unexpected error response. schema: @@ -43709,6 +43758,12 @@ paths: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 pagination: type: object properties: @@ -43897,6 +43952,12 @@ paths: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 pagination: type: object properties: @@ -44601,6 +44662,12 @@ paths: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 pagination: type: object properties: @@ -45364,7 +45431,9 @@ paths: schema: type: object properties: - total: + total_value: + type: string + total_borrows: type: string default: description: An unexpected error response. @@ -87389,6 +87458,18 @@ definitions: NOTE: The amount field is an Int which implements the custom method signatures required by gogoproto. + eden_forward: + type: object + properties: + denom: + type: string + amount: + type: string + description: |- + Coin defines a token with a denomination and an amount. + + NOTE: The amount field is an Int which implements the custom method + signatures required by gogoproto. elys.incentive.QueryAprResponse: type: object properties: @@ -87447,6 +87528,21 @@ definitions: method signatures required by gogoproto. + eden_forward: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. + + + NOTE: The amount field is an Int which implements the custom + method + + signatures required by gogoproto. elys.leveragelp.AddPool: type: object properties: @@ -87484,7 +87580,7 @@ definitions: type: object elys.leveragelp.MsgUpdateParamsResponse: type: object - elys.leveragelp.MsgUpdatePoolsResponse: + elys.leveragelp.MsgUpdatePoolResponse: type: object elys.leveragelp.MsgUpdateStopLossResponse: type: object @@ -87599,40 +87695,47 @@ definitions: position: type: object properties: - address: - type: string - collateral: + position: type: object properties: - denom: - type: string - amount: + address: type: string - description: >- - Coin defines a token with a denomination and an amount. + collateral: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. - NOTE: The amount field is an Int which implements the custom - method + NOTE: The amount field is an Int which implements the custom + method - signatures required by gogoproto. - liabilities: - type: string - title: For recording - leverage: - type: string - title: For recording - leveraged_lp_amount: - type: string - position_health: - type: string - id: - type: string - format: uint64 - amm_pool_id: + signatures required by gogoproto. + liabilities: + type: string + title: For recording + leverage: + type: string + title: For recording + leveraged_lp_amount: + type: string + position_health: + type: string + id: + type: string + format: uint64 + amm_pool_id: + type: string + format: uint64 + stop_loss_price: + type: string + updated_leverage: type: string - format: uint64 - stop_loss_price: + position_usd_value: type: string interest_rate_hour: type: string @@ -87692,6 +87795,8 @@ definitions: type: string updated_leverage: type: string + position_usd_value: + type: string locked_lp_token: type: string elys.leveragelp.PositionsByPoolResponse: @@ -87742,6 +87847,8 @@ definitions: type: string updated_leverage: type: string + position_usd_value: + type: string pagination: type: object properties: @@ -87779,40 +87886,47 @@ definitions: position: type: object properties: - address: - type: string - collateral: + position: type: object properties: - denom: - type: string - amount: + address: type: string - description: >- - Coin defines a token with a denomination and an amount. + collateral: + type: object + properties: + denom: + type: string + amount: + type: string + description: >- + Coin defines a token with a denomination and an amount. - NOTE: The amount field is an Int which implements the custom - method + NOTE: The amount field is an Int which implements the + custom method - signatures required by gogoproto. - liabilities: - type: string - title: For recording - leverage: - type: string - title: For recording - leveraged_lp_amount: - type: string - position_health: - type: string - id: - type: string - format: uint64 - amm_pool_id: + signatures required by gogoproto. + liabilities: + type: string + title: For recording + leverage: + type: string + title: For recording + leveraged_lp_amount: + type: string + position_health: + type: string + id: + type: string + format: uint64 + amm_pool_id: + type: string + format: uint64 + stop_loss_price: + type: string + updated_leverage: type: string - format: uint64 - stop_loss_price: + position_usd_value: type: string interest_rate_hour: type: string @@ -87892,6 +88006,8 @@ definitions: type: string updated_leverage: type: string + position_usd_value: + type: string pagination: type: object properties: @@ -88007,8 +88123,6 @@ definitions: NOTE: The amount field is an Int which implements the custom method signatures required by gogoproto. - elys.leveragelp.QueryGetAddResponse: - type: object elys.leveragelp.QueryGetPoolResponse: type: object properties: @@ -88085,6 +88199,8 @@ definitions: type: string updated_leverage: type: string + position_usd_value: + type: string elys.leveragelp.QueryRewardsResponse: type: object properties: @@ -88162,9 +88278,9 @@ definitions: pool_id: type: string format: uint64 - Enabled: + enabled: type: boolean - Closed: + closed: type: boolean elys.leveragelp.WhitelistResponse: type: object @@ -88221,6 +88337,29 @@ definitions: apr: type: string description: ExternalIncentive defines the external incentives. + elys.masterchef.FeeInfo: + type: object + properties: + gas_lp: + type: string + gas_stakers: + type: string + gas_protocol: + type: string + dex_lp: + type: string + dex_stakers: + type: string + dex_protocol: + type: string + perp_lp: + type: string + perp_stakers: + type: string + perp_protocol: + type: string + eden_lp: + type: string elys.masterchef.IncentiveInfo: type: object properties: @@ -88381,6 +88520,32 @@ definitions: description: ExternalIncentive defines the external incentives. elys.masterchef.QueryListFeeInfoResponse: type: object + properties: + fee_info: + type: array + items: + type: object + properties: + gas_lp: + type: string + gas_stakers: + type: string + gas_protocol: + type: string + dex_lp: + type: string + dex_stakers: + type: string + dex_protocol: + type: string + perp_lp: + type: string + perp_stakers: + type: string + perp_protocol: + type: string + eden_lp: + type: string elys.masterchef.QueryParamsResponse: type: object properties: @@ -88498,6 +88663,30 @@ definitions: format: uint64 elys.masterchef.QueryShowFeeInfoResponse: type: object + properties: + fee_info: + type: object + properties: + gas_lp: + type: string + gas_stakers: + type: string + gas_protocol: + type: string + dex_lp: + type: string + dex_stakers: + type: string + dex_protocol: + type: string + perp_lp: + type: string + perp_stakers: + type: string + perp_protocol: + type: string + eden_lp: + type: string elys.masterchef.QueryStableStakeAprResponse: type: object properties: @@ -89106,6 +89295,12 @@ definitions: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 elys.perpetual.MTPResponse: type: object properties: @@ -89175,8 +89370,16 @@ definitions: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 elys.perpetual.MsgAddCollateralResponse: type: object + elys.perpetual.MsgClosePositionsResponse: + type: object elys.perpetual.MsgCloseResponse: type: object properties: @@ -89460,6 +89663,12 @@ definitions: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 pagination: type: object properties: @@ -89557,6 +89766,12 @@ definitions: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 pagination: type: object properties: @@ -89654,6 +89869,12 @@ definitions: type: string open_price: type: string + last_interest_calc_time: + type: string + format: uint64 + last_interest_calc_block: + type: string + format: uint64 pagination: type: object properties: @@ -90136,7 +90357,9 @@ definitions: elys.tier.QueryPerpetualResponse: type: object properties: - total: + total_value: + type: string + total_borrows: type: string elys.tier.QueryRewardsTotalResponse: type: object diff --git a/proto/elys/perpetual/tx.proto b/proto/elys/perpetual/tx.proto index 9b3602908..f51def8ac 100644 --- a/proto/elys/perpetual/tx.proto +++ b/proto/elys/perpetual/tx.proto @@ -21,6 +21,7 @@ service Msg { rpc AddCollateral (MsgAddCollateral ) returns (MsgAddCollateralResponse ); rpc BrokerAddCollateral (MsgBrokerAddCollateral) returns (MsgAddCollateralResponse ); rpc UpdateStopLoss (MsgUpdateStopLoss ) returns (MsgUpdateStopLossResponse ); + rpc ClosePositions (MsgClosePositions ) returns (MsgClosePositionsResponse); } message MsgOpen { string creator = 1; @@ -111,10 +112,18 @@ message MsgBrokerAddCollateral { string owner = 4; } +message MsgClosePositions { + string creator = 1; + repeated PositionRequest liquidate = 2; + repeated PositionRequest stop_loss = 3; +} + +message MsgClosePositionsResponse {} + message MsgUpdateStopLoss { string creator = 1; uint64 id = 2; string price = 3 [(gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false]; } -message MsgUpdateStopLossResponse {} \ No newline at end of file +message MsgUpdateStopLossResponse {} diff --git a/proto/elys/perpetual/types.proto b/proto/elys/perpetual/types.proto index 565b76c3b..7c7d1ae68 100644 --- a/proto/elys/perpetual/types.proto +++ b/proto/elys/perpetual/types.proto @@ -12,7 +12,7 @@ enum Position { SHORT = 2; } -message MTP { +message LegacyMTP { string address = 1; string collateral_asset = 2; string trading_asset = 3; @@ -99,13 +99,9 @@ message MTP { (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; - string stop_loss_price = 28 [ - (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", - (gogoproto.nullable) = false - ]; } -message LegacyMTP { +message MTP { string address = 1; string collateral_asset = 2; string trading_asset = 3; @@ -192,8 +188,63 @@ message LegacyMTP { (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", (gogoproto.nullable) = false ]; + string stop_loss_price = 28 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + uint64 last_interest_calc_time = 29; + uint64 last_interest_calc_block = 30; + uint64 last_funding_calc_time = 31; + uint64 last_funding_calc_block = 32; +} + +message InterestBlock { + string interest_rate = 1 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + int64 block_height = 2; +} + +message FundingRateBlock { + string funding_rate = 1 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + int64 block_height = 2; + string funding_amount_short = 3 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; + string funding_amount_long = 4 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; + string funding_rate_long = 5 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; + string funding_rate_short = 6 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Dec", + (gogoproto.nullable) = false + ]; +} + +message ToPay { + string asset_balance = 1 [ + (gogoproto.customtype) = "github.com/cosmos/cosmos-sdk/types.Int", + (gogoproto.nullable) = false + ]; + string asset_denom = 2; + string address = 3; + uint64 id = 4; } message WhiteList { repeated string validator_list = 1; } + +message PositionRequest { + string address = 1; + uint64 id = 2; +} \ No newline at end of file diff --git a/x/leveragelp/keeper/query_get_position_test.go b/x/leveragelp/keeper/query_get_position_test.go index 43f9aff3b..356ba1780 100644 --- a/x/leveragelp/keeper/query_get_position_test.go +++ b/x/leveragelp/keeper/query_get_position_test.go @@ -103,14 +103,14 @@ func (suite KeeperTestSuite) TestQueryGetPosition() { expected := types.PositionAndInterest{ Position: &types.QueryPosition{ - Position: position, - UpdatedLeverage: updated_leverage, + Position: position, + UpdatedLeverage: updated_leverage, PositionUsdValue: sdk.NewDec(5000).Quo(sdk.NewDec(1000000)), }, - InterestRateHour: sdk.MustNewDecFromStr("0.000017123287671233"), + InterestRateHour: sdk.MustNewDecFromStr("0.000017123287671233"), InterestRateHourUsd: sdk.ZeroDec(), } - pos_for_address_res, _ := k.QueryPositionsForAddress(suite.ctx, &types.PositionsForAddressRequest{Address: addr.String(), Pagination: nil} ) + pos_for_address_res, _ := k.QueryPositionsForAddress(suite.ctx, &types.PositionsForAddressRequest{Address: addr.String(), Pagination: nil}) suite.Require().Equal(expected.Position, pos_for_address_res.Positions[0].Position) suite.Require().True(expected.InterestRateHour.Equal(pos_for_address_res.Positions[0].InterestRateHour)) diff --git a/x/leveragelp/keeper/query_position.go b/x/leveragelp/keeper/query_position.go index d4a31074e..8b6b5206f 100644 --- a/x/leveragelp/keeper/query_position.go +++ b/x/leveragelp/keeper/query_position.go @@ -21,7 +21,7 @@ func (k Keeper) Position(goCtx context.Context, req *types.PositionRequest) (*ty if err != nil { return nil, err } - updatedLeveragePosition, err := k.GetLeverageLpUpdatedLeverage(ctx, []*types.Position{&position}) + updatedLeveragePosition, err := k.GetLeverageLpUpdatedLeverage(ctx, []*types.Position{&position}) if err != nil { return nil, err diff --git a/x/leveragelp/types/hooks.go b/x/leveragelp/types/hooks.go index 3ed9c0ed2..14c63eb47 100644 --- a/x/leveragelp/types/hooks.go +++ b/x/leveragelp/types/hooks.go @@ -20,7 +20,6 @@ var _ LeverageLpHooks = MultiLeverageLpHooks{} // combine multiple leverageLp hooks, all hook functions are run in array sequence. type MultiLeverageLpHooks []LeverageLpHooks - func NewMultiLeverageLpHooks(hooks ...LeverageLpHooks) MultiLeverageLpHooks { return hooks } @@ -35,7 +34,6 @@ func (h MultiLeverageLpHooks) AfterLeverageLpPositionOpen(ctx sdk.Context, sende return nil } - func (h MultiLeverageLpHooks) AfterLeverageLpPositionClose(ctx sdk.Context, sender sdk.AccAddress) error { for i := range h { err := h[i].AfterLeverageLpPositionClose(ctx, sender) @@ -46,7 +44,6 @@ func (h MultiLeverageLpHooks) AfterLeverageLpPositionClose(ctx sdk.Context, send return nil } - func (h MultiLeverageLpHooks) AfterLeverageLpPositionOpenConsolidate(ctx sdk.Context, sender sdk.AccAddress) error { for i := range h { err := h[i].AfterLeverageLpPositionOpenConsolidate(ctx, sender) diff --git a/x/perpetual/client/cli/tx.go b/x/perpetual/client/cli/tx.go index 415a87e0d..5536ad2d8 100644 --- a/x/perpetual/client/cli/tx.go +++ b/x/perpetual/client/cli/tx.go @@ -30,6 +30,7 @@ func GetTxCmd() *cobra.Command { cmd.AddCommand(CmdWhitelist()) cmd.AddCommand(CmdDewhitelist()) cmd.AddCommand(CmdAddCollateral()) + cmd.AddCommand(CmdClosePositions()) cmd.AddCommand(CmdUpdateStopLoss()) // this line is used by starport scaffolding # 1 diff --git a/x/perpetual/client/cli/tx_close_positions.go b/x/perpetual/client/cli/tx_close_positions.go new file mode 100644 index 000000000..833dd8d22 --- /dev/null +++ b/x/perpetual/client/cli/tx_close_positions.go @@ -0,0 +1,78 @@ +package cli + +import ( + "encoding/json" + "io/ioutil" + "strconv" + + "github.com/cosmos/cosmos-sdk/client" + "github.com/cosmos/cosmos-sdk/client/flags" + "github.com/cosmos/cosmos-sdk/client/tx" + "github.com/elys-network/elys/x/perpetual/types" + "github.com/spf13/cobra" +) + +var _ = strconv.Itoa(0) + +func CmdClosePositions() *cobra.Command { + cmd := &cobra.Command{ + Use: "close-positions [liquidate] [stoploss]", + Short: "Broadcast message close-positions", + Args: cobra.ExactArgs(2), + RunE: func(cmd *cobra.Command, args []string) (err error) { + + clientCtx, err := client.GetClientTxContext(cmd) + if err != nil { + return err + } + + liquidate, err := readPositionRequestJSON(args[0]) + if err != nil { + return err + } + // Convert to slice of pointers + var liqudiatePtrs []*types.PositionRequest + for i := range liquidate { + liqudiatePtrs = append(liqudiatePtrs, &liquidate[i]) + } + + stopLoss, err := readPositionRequestJSON(args[1]) + if err != nil { + return err + } + // Convert to slice of pointers + var stoplossPtrs []*types.PositionRequest + for i := range stopLoss { + stoplossPtrs = append(stoplossPtrs, &stopLoss[i]) + } + + msg := types.NewMsgClosePositions( + clientCtx.GetFromAddress().String(), + liqudiatePtrs, + stoplossPtrs, + ) + if err = msg.ValidateBasic(); err != nil { + return err + } + return tx.GenerateOrBroadcastTxCLI(clientCtx, cmd.Flags(), msg) + }, + } + + flags.AddTxFlagsToCmd(cmd) + + return cmd +} + +func readPositionRequestJSON(filename string) ([]types.PositionRequest, error) { + var positions []types.PositionRequest + bz, err := ioutil.ReadFile(filename) + if err != nil { + return []types.PositionRequest{}, err + } + err = json.Unmarshal(bz, &positions) + if err != nil { + return []types.PositionRequest{}, err + } + + return positions, nil +} diff --git a/x/perpetual/keeper/add_collateral.go b/x/perpetual/keeper/add_collateral.go index 38b681594..1b2ab6498 100644 --- a/x/perpetual/keeper/add_collateral.go +++ b/x/perpetual/keeper/add_collateral.go @@ -93,7 +93,7 @@ func (k Keeper) AddCollateralToMtp(ctx sdk.Context, msg *types.MsgAddCollateral) return nil, err } - h, err := k.UpdateMTPHealth(ctx, mtp, ammPool, baseCurrency) // set mtp in func or return h? + h, err := k.GetMTPHealth(ctx, mtp, ammPool, baseCurrency) // set mtp in func or return h? if err != nil { return nil, err } @@ -149,7 +149,7 @@ func (k Keeper) AddCollateralToMtp(ctx sdk.Context, msg *types.MsgAddCollateral) } // Update the MTP health. - lr, err := k.OpenLongChecker.UpdateMTPHealth(ctx, mtp, ammPool, baseCurrency) + lr, err := k.OpenLongChecker.GetMTPHealth(ctx, mtp, ammPool, baseCurrency) if err != nil { return nil, err } diff --git a/x/perpetual/keeper/begin_blocker.go b/x/perpetual/keeper/begin_blocker.go index 6e28cf0af..4b7b8d770 100644 --- a/x/perpetual/keeper/begin_blocker.go +++ b/x/perpetual/keeper/begin_blocker.go @@ -1,40 +1,14 @@ package keeper import ( - "fmt" - - errorsmod "cosmossdk.io/errors" sdk "github.com/cosmos/cosmos-sdk/types" - assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" - ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/elys-network/elys/x/perpetual/types" ) func (k Keeper) BeginBlocker(ctx sdk.Context) { - // check if epoch has passed then execute - epochLength := k.GetEpochLength(ctx) - epochPosition := k.GetEpochPosition(ctx, epochLength) - - // if epoch has not passed - if epochPosition != 0 { - return - } - - // if epoch has passed - entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) - if !found { - ctx.Logger().Error(errorsmod.Wrapf(assetprofiletypes.ErrAssetProfileNotFound, "asset %s not found", ptypes.BaseCurrency).Error()) - } - baseCurrency := entry.Denom - baseCurrencyDecimal := entry.Decimals - currentHeight := ctx.BlockHeight() pools := k.GetAllPools(ctx) for _, pool := range pools { - ammPool, err := k.GetAmmPool(ctx, pool.AmmPoolId, "") - if err != nil { - ctx.Logger().Error(errorsmod.Wrap(err, fmt.Sprintf("error getting amm pool: %d", pool.AmmPoolId)).Error()) - continue - } if k.IsPoolEnabled(ctx, pool.AmmPoolId) { rate, err := k.BorrowInterestRateComputation(ctx, pool) if err != nil { @@ -43,6 +17,12 @@ func (k Keeper) BeginBlocker(ctx sdk.Context) { } pool.BorrowInterestRate = rate pool.LastHeightBorrowInterestRateComputed = currentHeight + + k.SetBorrowRate(ctx, uint64(ctx.BlockHeight()), pool.AmmPoolId, types.InterestBlock{ + InterestRate: rate, + BlockHeight: ctx.BlockHeight(), + }) + err = k.UpdatePoolHealth(ctx, &pool) if err != nil { ctx.Logger().Error(err.Error()) @@ -52,19 +32,40 @@ func (k Keeper) BeginBlocker(ctx sdk.Context) { ctx.Logger().Error(err.Error()) } - // TODO GetMTPsForPool might become a very slow call as it iterates through all the MTPs in the KV Store - mtps, _, _ := k.GetMTPsForPool(ctx, pool.AmmPoolId, nil) - for _, mtp := range mtps { - err := BeginBlockerProcessMTP(ctx, k, mtp, pool, ammPool, baseCurrency, baseCurrencyDecimal) - if err != nil { - ctx.Logger().Error(err.Error()) - continue - } + // account custody from long position + totalCustodyLong := sdk.ZeroInt() + for _, asset := range pool.PoolAssetsLong { + totalCustodyLong = totalCustodyLong.Add(asset.Custody) } - err = k.HandleFundingFeeDistribution(ctx, mtps, &pool, ammPool, baseCurrency) - if err != nil { - ctx.Logger().Error(err.Error()) + + // account custody from short position + totalCustodyShort := sdk.ZeroInt() + for _, asset := range pool.PoolAssetsShort { + totalCustodyShort = totalCustodyShort.Add(asset.Custody) + } + + fundingAmountLong := types.CalcTakeAmount(totalCustodyLong, pool.FundingRate) + fundingAmountShort := sdk.ZeroInt() + + fundingRateLong := pool.FundingRate + fundingRateShort := sdk.ZeroDec() + + // if funding rate is negative, collect from short position + if pool.FundingRate.IsNegative() { + fundingAmountShort = types.CalcTakeAmount(totalCustodyShort, pool.FundingRate) + fundingAmountLong = sdk.ZeroInt() + + fundingRateLong = sdk.ZeroDec() + fundingRateShort = pool.FundingRate } + k.SetFundingRate(ctx, uint64(ctx.BlockHeight()), pool.AmmPoolId, types.FundingRateBlock{ + FundingRate: pool.FundingRate, + BlockHeight: ctx.BlockHeight(), + FundingAmountShort: fundingAmountShort, + FundingAmountLong: fundingAmountLong, + FundingRateLong: fundingRateLong, + FundingRateShort: fundingRateShort, + }) } k.SetPool(ctx, pool) } diff --git a/x/perpetual/keeper/borrow_rate_test.go b/x/perpetual/keeper/borrow_rate_test.go new file mode 100644 index 000000000..f7562e59d --- /dev/null +++ b/x/perpetual/keeper/borrow_rate_test.go @@ -0,0 +1,48 @@ +package keeper_test + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + keepertest "github.com/elys-network/elys/testutil/keeper" + "github.com/stretchr/testify/require" + + "github.com/elys-network/elys/x/perpetual/keeper" + "github.com/elys-network/elys/x/perpetual/types" +) + +func createNBorrowRate(keeper *keeper.Keeper, ctx sdk.Context, n int) ([]types.InterestBlock, int64) { + items := make([]types.InterestBlock, n) + ctx = ctx.WithBlockHeight(1000) + curBlock := ctx.BlockHeight() + for i := range items { + items[i].InterestRate = sdk.NewDec(int64(i + 1)) // Start from 1 to avoid zero interest + items[i].BlockHeight = int64(i * 10) + + curBlock++ + keeper.SetBorrowRate(ctx, uint64(curBlock), 1, items[i]) // Assuming pool ID 1 + } + return items, curBlock +} + +func TestBorrowRateGet(t *testing.T) { + keeper, ctx := keepertest.PerpetualKeeper(t) + _, lastBlock := createNBorrowRate(keeper, ctx, 10) + ctx = ctx.WithBlockHeight(lastBlock) + + // 1st case: recent block + res := keeper.GetBorrowRate(ctx, uint64(ctx.BlockHeight()-2), 1, sdk.NewDec(1000)) + require.Equal(t, sdk.NewDec(19000), res) // 19 * 1000 + + // 2nd case: older block + res = keeper.GetBorrowRate(ctx, uint64(ctx.BlockHeight()-8), 1, sdk.NewDec(1000)) + require.Equal(t, sdk.NewDec(52000), res) // 52 * 1000 + + // 3rd case: future block (should return zero) + res = keeper.GetBorrowRate(ctx, uint64(ctx.BlockHeight()+10), 1, sdk.NewDec(1000)) + require.Equal(t, sdk.ZeroDec(), res) + + // 4th case: non-existent pool + res = keeper.GetBorrowRate(ctx, uint64(ctx.BlockHeight()-2), 2, sdk.NewDec(1000)) + require.Equal(t, sdk.ZeroDec(), res) +} diff --git a/x/perpetual/keeper/calc_mtp_interest_liabilities.go b/x/perpetual/keeper/calc_mtp_interest_liabilities.go deleted file mode 100644 index 4529dea63..000000000 --- a/x/perpetual/keeper/calc_mtp_interest_liabilities.go +++ /dev/null @@ -1,59 +0,0 @@ -package keeper - -import ( - "math/big" - - "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - ammtypes "github.com/elys-network/elys/x/amm/types" - "github.com/elys-network/elys/x/perpetual/types" -) - -func (k Keeper) CalcMTPBorrowInterestLiabilities(ctx sdk.Context, mtp *types.MTP, borrowInterestRate sdk.Dec, epochPosition, epochLength int64, ammPool ammtypes.Pool, baseCurrency string) (math.Int, error) { - // Ensure borrow interest rate or liabilities are not zero to avoid division by zero - if borrowInterestRate.IsZero() || mtp.Liabilities.IsZero() { - return sdk.ZeroInt(), types.ErrAmountTooLow - } - - var borrowInterestRational, liabilitiesRational, rate, epochPositionRational, epochLengthRational big.Rat - - rate.SetFloat64(borrowInterestRate.MustFloat64()) - - unpaidCollateral := sdk.ZeroInt() - // Calculate collateral borrow interests in base currency - if mtp.CollateralAsset == baseCurrency { - unpaidCollateral = unpaidCollateral.Add(mtp.BorrowInterestUnpaidCollateral) - } else { - // Liability is in base currency, so convert it to base currency - unpaidCollateralIn := sdk.NewCoin(mtp.CollateralAsset, mtp.BorrowInterestUnpaidCollateral) - C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool) - if err != nil { - return sdk.ZeroInt(), err - } - - unpaidCollateral = unpaidCollateral.Add(C) - } - - liabilitiesRational.SetInt(mtp.Liabilities.BigInt().Add(mtp.Liabilities.BigInt(), unpaidCollateral.BigInt())) - borrowInterestRational.Mul(&rate, &liabilitiesRational) - - if epochPosition > 0 { // prorate borrow interest if within epoch - epochPositionRational.SetInt64(epochPosition) - epochLengthRational.SetInt64(epochLength) - epochPositionRational.Quo(&epochPositionRational, &epochLengthRational) - borrowInterestRational.Mul(&borrowInterestRational, &epochPositionRational) - } - - borrowInterestNew := borrowInterestRational.Num().Quo(borrowInterestRational.Num(), borrowInterestRational.Denom()) - - borrowInterestNewInt := sdk.NewIntFromBigInt(borrowInterestNew.Add(borrowInterestNew, unpaidCollateral.BigInt())) - // round up to lowest digit if borrow interest too low and rate not 0 - if borrowInterestNewInt.IsZero() && !borrowInterestRate.IsZero() { - borrowInterestNewInt = sdk.NewInt(1) - } - - // apply take profit borrow rate to borrow interest - borrowInterestNewInt = sdk.NewDecFromInt(borrowInterestNewInt).Mul(mtp.TakeProfitBorrowRate).TruncateInt() - - return borrowInterestNewInt, nil -} diff --git a/x/perpetual/keeper/close_long.go b/x/perpetual/keeper/close_long.go index 08e306eb5..9700093e0 100644 --- a/x/perpetual/keeper/close_long.go +++ b/x/perpetual/keeper/close_long.go @@ -32,7 +32,7 @@ func (k Keeper) CloseLong(ctx sdk.Context, msg *types.MsgClose, baseCurrency str } // Handle Borrow Interest if within epoch position - if err := k.CloseLongChecker.HandleBorrowInterest(ctx, &mtp, &pool, ammPool); err != nil { + if _, err := k.CloseLongChecker.SettleBorrowInterest(ctx, &mtp, &pool, ammPool); err != nil { return nil, sdk.ZeroInt(), err } diff --git a/x/perpetual/keeper/close_long_test.go b/x/perpetual/keeper/close_long_test.go index f2fd85f9f..89b9b88ef 100644 --- a/x/perpetual/keeper/close_long_test.go +++ b/x/perpetual/keeper/close_long_test.go @@ -143,7 +143,7 @@ func TestCloseLong_AmmPoolNotFound(t *testing.T) { mockChecker.AssertExpectations(t) } -func TestCloseLong_ErrorHandleBorrowInterest(t *testing.T) { +func TestCloseLong_ErrorSettleBorrowInterest(t *testing.T) { // Setup the mock checker mockChecker := new(mocks.CloseLongChecker) @@ -176,7 +176,7 @@ func TestCloseLong_ErrorHandleBorrowInterest(t *testing.T) { mockChecker.On("GetMTP", ctx, sdk.MustAccAddressFromBech32(msg.Creator), msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(errors.New("error executing handle borrow interest")) + mockChecker.On("SettleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(errors.New("error executing handle borrow interest")) _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) @@ -218,7 +218,7 @@ func TestCloseLong_ErrorTakeOutCustody(t *testing.T) { mockChecker.On("GetMTP", ctx, sdk.MustAccAddressFromBech32(msg.Creator), msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("SettleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(errors.New("error executing take out custody")) _, _, err := k.CloseLong(ctx, msg, ptypes.BaseCurrency) @@ -261,7 +261,7 @@ func TestCloseLong_ErrorEstimateAndRepay(t *testing.T) { mockChecker.On("GetMTP", ctx, sdk.MustAccAddressFromBech32(msg.Creator), msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("SettleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(nil) mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, msg.Amount, ptypes.BaseCurrency).Return(math.Int{}, errors.New("error executing estimate and repay")) @@ -306,7 +306,7 @@ func TestCloseLong_SuccessfulClosingLongPosition(t *testing.T) { mockChecker.On("GetMTP", ctx, sdk.MustAccAddressFromBech32(msg.Creator), msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("SettleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(nil) mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, msg.Amount, ptypes.BaseCurrency).Return(repayAmount, nil) diff --git a/x/perpetual/keeper/close_short.go b/x/perpetual/keeper/close_short.go index e90ceb239..0caa13846 100644 --- a/x/perpetual/keeper/close_short.go +++ b/x/perpetual/keeper/close_short.go @@ -32,7 +32,7 @@ func (k Keeper) CloseShort(ctx sdk.Context, msg *types.MsgClose, baseCurrency st } // Handle Borrow Interest if within epoch position - if err := k.CloseShortChecker.HandleBorrowInterest(ctx, &mtp, &pool, ammPool); err != nil { + if _, err := k.CloseShortChecker.SettleBorrowInterest(ctx, &mtp, &pool, ammPool); err != nil { return nil, sdk.ZeroInt(), err } diff --git a/x/perpetual/keeper/close_short_test.go b/x/perpetual/keeper/close_short_test.go index c6a454691..0152fc1d0 100644 --- a/x/perpetual/keeper/close_short_test.go +++ b/x/perpetual/keeper/close_short_test.go @@ -142,7 +142,7 @@ func TestCloseShort_AmmPoolNotFound(t *testing.T) { mockChecker.AssertExpectations(t) } -func TestCloseShort_ErrorHandleBorrowInterest(t *testing.T) { +func TestCloseShort_ErrorSettleBorrowInterest(t *testing.T) { // Setup the mock checker mockChecker := new(mocks.CloseShortChecker) @@ -173,7 +173,7 @@ func TestCloseShort_ErrorHandleBorrowInterest(t *testing.T) { mockChecker.On("GetMTP", ctx, sdk.MustAccAddressFromBech32(msg.Creator), msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(errors.New("error executing handle borrow interest")) + mockChecker.On("SettleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(errors.New("error executing handle borrow interest")) _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) @@ -213,7 +213,7 @@ func TestCloseShort_ErrorTakeOutCustody(t *testing.T) { mockChecker.On("GetMTP", ctx, sdk.MustAccAddressFromBech32(msg.Creator), msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("SettleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(errors.New("error executing take out custody")) _, _, err := k.CloseShort(ctx, msg, ptypes.BaseCurrency) @@ -254,7 +254,7 @@ func TestCloseShort_ErrorEstimateAndRepay(t *testing.T) { mockChecker.On("GetMTP", ctx, sdk.MustAccAddressFromBech32(msg.Creator), msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("SettleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(nil) mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, msg.Amount, ptypes.BaseCurrency).Return(math.Int{}, errors.New("error executing estimate and repay")) @@ -297,7 +297,7 @@ func TestCloseShort_SuccessfulClosingLongPosition(t *testing.T) { mockChecker.On("GetMTP", ctx, sdk.MustAccAddressFromBech32(msg.Creator), msg.Id).Return(mtp, nil) mockChecker.On("GetPool", ctx, mtp.AmmPoolId).Return(pool, true) mockChecker.On("GetAmmPool", ctx, mtp.AmmPoolId, mtp.CustodyAsset).Return(ammPool, nil) - mockChecker.On("HandleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) + mockChecker.On("SettleBorrowInterest", ctx, &mtp, &pool, ammPool).Return(nil) mockChecker.On("TakeOutCustody", ctx, mtp, &pool, msg.Amount).Return(nil) mockChecker.On("EstimateAndRepay", ctx, mtp, pool, ammPool, msg.Amount, ptypes.BaseCurrency).Return(repayAmount, nil) diff --git a/x/perpetual/keeper/handle_borrow_interest.go b/x/perpetual/keeper/handle_borrow_interest.go deleted file mode 100644 index f49bc8535..000000000 --- a/x/perpetual/keeper/handle_borrow_interest.go +++ /dev/null @@ -1,38 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - sdk "github.com/cosmos/cosmos-sdk/types" - ammtypes "github.com/elys-network/elys/x/amm/types" - assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" - ptypes "github.com/elys-network/elys/x/parameter/types" - "github.com/elys-network/elys/x/perpetual/types" -) - -func (k Keeper) HandleBorrowInterest(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool) error { - epochLength := k.GetEpochLength(ctx) - epochPosition := k.GetEpochPosition(ctx, epochLength) - if epochPosition <= 0 { - return nil - } - - entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) - if !found { - return errorsmod.Wrapf(assetprofiletypes.ErrAssetProfileNotFound, "asset %s not found", ptypes.BaseCurrency) - } - baseCurrency := entry.Denom - - borrowInterestPayment, err := k.CalcMTPBorrowInterestLiabilities(ctx, mtp, pool.BorrowInterestRate, epochPosition, epochLength, ammPool, baseCurrency) - if err != nil { - return err - } - finalBorrowInterestPayment := k.HandleBorrowInterestPayment(ctx, borrowInterestPayment, mtp, pool, ammPool, baseCurrency) - - // finalInterestPayment is in custodyAsset - if err := pool.UpdateBlockBorrowInterest(ctx, mtp.CustodyAsset, finalBorrowInterestPayment, true, mtp.Position); err != nil { - return err - } - - _, err = k.UpdateMTPHealth(ctx, *mtp, ammPool, baseCurrency) - return err -} diff --git a/x/perpetual/keeper/handle_borrow_interest_payment.go b/x/perpetual/keeper/handle_borrow_interest_payment.go deleted file mode 100644 index 1e2a56484..000000000 --- a/x/perpetual/keeper/handle_borrow_interest_payment.go +++ /dev/null @@ -1,36 +0,0 @@ -package keeper - -import ( - errorsmod "cosmossdk.io/errors" - "cosmossdk.io/math" - sdk "github.com/cosmos/cosmos-sdk/types" - ammtypes "github.com/elys-network/elys/x/amm/types" - "github.com/elys-network/elys/x/perpetual/types" -) - -func (k Keeper) HandleBorrowInterestPayment(ctx sdk.Context, borrowInterestPayment math.Int, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) math.Int { - incrementalBorrowInterestPaymentEnabled := k.GetIncrementalBorrowInterestPaymentEnabled(ctx) - // if incremental payment on, pay interest - if incrementalBorrowInterestPaymentEnabled { - finalBorrowInterestPayment, err := k.IncrementalBorrowInterestPayment(ctx, borrowInterestPayment, mtp, pool, ammPool, baseCurrency) - if err != nil { - ctx.Logger().Error(errorsmod.Wrap(err, "error executing incremental borrow interest payment").Error()) - } else { - return finalBorrowInterestPayment - } - } else { // else update unpaid mtp interest - // collateralAsset is not in base currency - if mtp.CollateralAsset != baseCurrency { - // swap - amtTokenIn := sdk.NewCoin(baseCurrency, borrowInterestPayment) - var err error - borrowInterestPayment, err = k.EstimateSwap(ctx, amtTokenIn, mtp.CollateralAsset, ammPool) // may need spot price here to not deduct fee - if err != nil { - return sdk.ZeroInt() - } - } - - mtp.BorrowInterestUnpaidCollateral = borrowInterestPayment - } - return sdk.ZeroInt() -} diff --git a/x/perpetual/keeper/handle_funding_fee_distribution.go b/x/perpetual/keeper/handle_funding_fee_distribution.go deleted file mode 100644 index bdaa2e014..000000000 --- a/x/perpetual/keeper/handle_funding_fee_distribution.go +++ /dev/null @@ -1,99 +0,0 @@ -package keeper - -import ( - sdk "github.com/cosmos/cosmos-sdk/types" - ammtypes "github.com/elys-network/elys/x/amm/types" - "github.com/elys-network/elys/x/perpetual/types" -) - -// HandleFundingFeeDistribution handles funding fee distribution -func (k Keeper) HandleFundingFeeDistribution(ctx sdk.Context, mtps []*types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) error { - // get funding rate - fundingRate := pool.FundingRate - - // if funding rate is zero, return - if fundingRate.IsZero() { - return nil - } - - // account liabilities from long position - liabilitiesLong := sdk.ZeroInt() - for _, asset := range pool.PoolAssetsLong { - liabilitiesLong = liabilitiesLong.Add(asset.Liabilities) - } - - // account liabilities from short position - liabilitiesShort := sdk.ZeroInt() - for _, asset := range pool.PoolAssetsShort { - liabilitiesShort = liabilitiesShort.Add(asset.Liabilities) - } - - // get funding fee collection address - fundingFeeCollectionAddress := k.GetFundingFeeCollectionAddress(ctx) - - // get base currency balance - balance := k.bankKeeper.GetBalance(ctx, fundingFeeCollectionAddress, baseCurrency) - - // if balance is zero, return - if balance.IsZero() { - return nil - } - - for _, mtp := range mtps { - // if funding rate is negative and mtp position is short or funding rate is positive and mtp position is long, return - if (fundingRate.IsNegative() && mtp.Position == types.Position_SHORT) || (fundingRate.IsPositive() && mtp.Position == types.Position_LONG) { - return nil - } - - // get mtp address - mtpAddress, err := sdk.AccAddressFromBech32(mtp.Address) - if err != nil { - return err - } - - // calc funding fee share - fundingFeeShare := sdk.ZeroDec() - if fundingRate.IsNegative() && mtp.Position == types.Position_LONG { - // Ensure liabilitiesLong is not zero to avoid division by zero - if liabilitiesLong.IsZero() { - return types.ErrAmountTooLow - } - fundingFeeShare = sdk.NewDecFromInt(mtp.Liabilities).Quo(sdk.NewDecFromInt(liabilitiesLong)) - } - if fundingRate.IsPositive() && mtp.Position == types.Position_SHORT { - // Ensure liabilitiesShort is not zero to avoid division by zero - if liabilitiesShort.IsZero() { - return types.ErrAmountTooLow - } - fundingFeeShare = sdk.NewDecFromInt(mtp.Liabilities).Quo(sdk.NewDecFromInt(liabilitiesShort)) - } - - // if funding fee share is zero, skip mtp - if fundingFeeShare.IsZero() { - continue - } - - // calculate funding fee amount - fundingFeeAmount := sdk.NewCoin(baseCurrency, sdk.NewDecFromInt(balance.Amount).Mul(fundingFeeShare).TruncateInt()) - - // transfer funding fee amount to mtp address - if err := k.bankKeeper.SendCoins(ctx, fundingFeeCollectionAddress, mtpAddress, sdk.NewCoins(fundingFeeAmount)); err != nil { - return err - } - - // update received funding fee accounting buckets - // Swap the take amount to collateral asset - fundingFeeCollateralAmount, err := k.EstimateSwap(ctx, fundingFeeAmount, mtp.CollateralAsset, ammPool) - if err != nil { - return err - } - - // add payment to total funding fee paid in collateral asset - mtp.FundingFeeReceivedCollateral = mtp.FundingFeeReceivedCollateral.Add(fundingFeeCollateralAmount) - - // add payment to total funding fee paid in custody asset - mtp.FundingFeeReceivedCustody = mtp.FundingFeeReceivedCustody.Add(fundingFeeAmount.Amount) - } - - return nil -} diff --git a/x/perpetual/keeper/keeper.go b/x/perpetual/keeper/keeper.go index 63ddf79e0..706c48c9c 100644 --- a/x/perpetual/keeper/keeper.go +++ b/x/perpetual/keeper/keeper.go @@ -170,7 +170,7 @@ func (k Keeper) Borrow(ctx sdk.Context, collateralAmount math.Int, custodyAmount mtp.Leverage = eta.Add(sdk.OneDec()) - h, err := k.UpdateMTPHealth(ctx, *mtp, *ammPool, baseCurrency) // set mtp in func or return h? + h, err := k.GetMTPHealth(ctx, *mtp, *ammPool, baseCurrency) // set mtp in func or return h? if err != nil { return err } @@ -504,7 +504,13 @@ func (k Keeper) TakeFundPayment(ctx sdk.Context, returnAmount math.Int, returnAs if !takeAmount.IsZero() { takeCoins := sdk.NewCoins(sdk.NewCoin(returnAsset, sdk.NewIntFromBigInt(takeAmount.BigInt()))) - err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, ammPool.Address, fundAddr, takeCoins) + + ammPoolAddr, err := sdk.AccAddressFromBech32(ammPool.Address) + if err != nil { + return sdk.ZeroInt(), err + } + err = k.bankKeeper.SendCoins(ctx, ammPoolAddr, fundAddr, takeCoins) + //err := k.bankKeeper.SendCoinsFromModuleToAccount(ctx, ammPool.Address, fundAddr, takeCoins) if err != nil { return sdk.ZeroInt(), err } diff --git a/x/perpetual/keeper/msg_server_close_positions.go b/x/perpetual/keeper/msg_server_close_positions.go new file mode 100644 index 000000000..539c3af10 --- /dev/null +++ b/x/perpetual/keeper/msg_server_close_positions.go @@ -0,0 +1,53 @@ +package keeper + +import ( + "context" + "fmt" + "strings" + + sdk "github.com/cosmos/cosmos-sdk/types" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/elys-network/elys/x/perpetual/types" +) + +func (k msgServer) ClosePositions(goCtx context.Context, msg *types.MsgClosePositions) (*types.MsgClosePositionsResponse, error) { + ctx := sdk.UnwrapSDKContext(goCtx) + + baseCurrency, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) + if !found { + return nil, nil + } + + // Handle liquidations + liqLog := []string{} + for _, val := range msg.Liquidate { + owner := sdk.MustAccAddressFromBech32(val.Address) + position, err := k.GetMTP(ctx, owner, val.Id) + if err != nil { + continue + } + + pool, poolFound := k.GetPool(ctx, position.AmmPoolId) + if !poolFound { + continue + } + ammPool, poolErr := k.GetAmmPool(ctx, position.AmmPoolId, position.TradingAsset) + if poolErr != nil { + continue + } + + err = k.CheckAndLiquidateUnhealthyPosition(ctx, &position, pool, ammPool, baseCurrency.Denom, baseCurrency.Decimals) + if err != nil { + // 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())) + } + } + + // TODO: Handle stop loss + ctx.EventManager().EmitEvent(sdk.NewEvent(types.EventClosePositions, + sdk.NewAttribute("liquidations", strings.Join(liqLog, "\n")), + //sdk.NewAttribute("stop_loss", strings.Join(closeLog, "\n")), + )) + + return &types.MsgClosePositionsResponse{}, nil +} diff --git a/x/perpetual/keeper/mtp.go b/x/perpetual/keeper/mtp.go index 132645ecd..ab21c583b 100644 --- a/x/perpetual/keeper/mtp.go +++ b/x/perpetual/keeper/mtp.go @@ -7,6 +7,7 @@ import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/query" + ptypes "github.com/elys-network/elys/x/parameter/types" "github.com/elys-network/elys/x/perpetual/types" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" @@ -61,9 +62,32 @@ func (k Keeper) GetMTP(ctx sdk.Context, mtpAddress sdk.AccAddress, id uint64) (t } bz := store.Get(key) k.cdc.MustUnmarshal(bz, &mtp) + ammPool, found := k.amm.GetPool(ctx, mtp.AmmPoolId) + if !found { + return mtp, nil + } + entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) + if !found { + return mtp, nil + } + baseCurrency := entry.Denom + + mtp.BorrowInterestUnpaidCollateral = k.GetBorrowInterest(ctx, &mtp, ammPool).Add(mtp.BorrowInterestUnpaidCollateral) + + mtpHealth, err := k.GetMTPHealth(ctx, mtp, ammPool, baseCurrency) + if err == nil { + mtp.MtpHealth = mtpHealth + } + return mtp, nil } +func (k Keeper) DoesMTPExist(ctx sdk.Context, mtpAddress sdk.AccAddress, id uint64) bool { + key := types.GetMTPKey(mtpAddress, id) + store := ctx.KVStore(k.storeKey) + return store.Has(key) +} + func (k Keeper) GetMTPIterator(ctx sdk.Context) sdk.Iterator { store := ctx.KVStore(k.storeKey) return sdk.KVStorePrefixIterator(store, types.MTPPrefix) @@ -88,6 +112,25 @@ func (k Keeper) GetAllMTPs(ctx sdk.Context) []types.MTP { return mtpList } +func (k Keeper) GetAllLegacyMTPs(ctx sdk.Context) []types.LegacyMTP { + var mtpList []types.LegacyMTP + iterator := k.GetMTPIterator(ctx) + defer func(iterator sdk.Iterator) { + err := iterator.Close() + if err != nil { + panic(err) + } + }(iterator) + + for ; iterator.Valid(); iterator.Next() { + var mtp types.LegacyMTP + bytesValue := iterator.Value() + k.cdc.MustUnmarshal(bytesValue, &mtp) + mtpList = append(mtpList, mtp) + } + return mtpList +} + func (k Keeper) GetMTPs(ctx sdk.Context, pagination *query.PageRequest) ([]*types.MTP, *query.PageResponse, error) { var mtpList []*types.MTP store := ctx.KVStore(k.storeKey) @@ -99,9 +142,31 @@ func (k Keeper) GetMTPs(ctx sdk.Context, pagination *query.PageRequest) ([]*type } } + entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) + realTime := true + if !found { + realTime = false + } + baseCurrency := entry.Denom + pageRes, err := query.Paginate(mtpStore, pagination, func(key []byte, value []byte) error { var mtp types.MTP k.cdc.MustUnmarshal(value, &mtp) + + ammPool, found := k.amm.GetPool(ctx, mtp.AmmPoolId) + if !found { + realTime = false + } + + if realTime { + mtp.BorrowInterestUnpaidCollateral = k.GetBorrowInterest(ctx, &mtp, ammPool).Add(mtp.BorrowInterestUnpaidCollateral) + + mtpHealth, err := k.GetMTPHealth(ctx, mtp, ammPool, baseCurrency) + if err == nil { + mtp.MtpHealth = mtpHealth + } + } + mtpList = append(mtpList, &mtp) return nil }) @@ -121,10 +186,32 @@ func (k Keeper) GetMTPsForPool(ctx sdk.Context, ammPoolId uint64, pagination *qu } } + entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) + realTime := true + if !found { + realTime = false + } + baseCurrency := entry.Denom + + ammPool, found := k.amm.GetPool(ctx, ammPoolId) + if !found { + realTime = false + } + pageRes, err := query.FilteredPaginate(mtpStore, pagination, func(key []byte, value []byte, accumulate bool) (bool, error) { var mtp types.MTP k.cdc.MustUnmarshal(value, &mtp) if accumulate && mtp.AmmPoolId == ammPoolId { + if realTime { + // Interest + mtp.BorrowInterestUnpaidCollateral = k.GetBorrowInterest(ctx, &mtp, ammPool).Add(mtp.BorrowInterestUnpaidCollateral) + + mtpHealth, err := k.GetMTPHealth(ctx, mtp, ammPool, baseCurrency) + if err == nil { + mtp.MtpHealth = mtpHealth + } + } + mtps = append(mtps, &mtp) return true, nil } @@ -168,9 +255,30 @@ func (k Keeper) GetMTPsForAddressWithPagination(ctx sdk.Context, mtpAddress sdk. return nil, nil, status.Error(codes.InvalidArgument, fmt.Sprintf("page size greater than max %d", types.MaxPageLimit)) } + entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) + realTime := true + if !found { + realTime = false + } + baseCurrency := entry.Denom + pageRes, err := query.Paginate(mtpStore, pagination, func(key []byte, value []byte) error { var mtp types.MTP k.cdc.MustUnmarshal(value, &mtp) + ammPool, found := k.amm.GetPool(ctx, mtp.AmmPoolId) + if !found { + realTime = false + } + + if realTime { + mtp.BorrowInterestUnpaidCollateral = k.GetBorrowInterest(ctx, &mtp, ammPool).Add(mtp.BorrowInterestUnpaidCollateral) + + mtpHealth, err := k.GetMTPHealth(ctx, mtp, ammPool, baseCurrency) + if err == nil { + mtp.MtpHealth = mtpHealth + } + } + mtps = append(mtps, &mtp) return nil }) @@ -215,6 +323,16 @@ func (k Keeper) GetOpenMTPCount(ctx sdk.Context) uint64 { return count } +// TODO: Handle to pay with a claim message or in begin blocker +func (k Keeper) SetToPay(ctx sdk.Context, toPay *types.ToPay) error { + store := ctx.KVStore(k.storeKey) + address := sdk.MustAccAddressFromBech32(toPay.Address) + + key := types.GetToPayKey(address, toPay.Id) + store.Set(key, k.cdc.MustMarshal(toPay)) + return nil +} + func (k Keeper) DeleteLegacyMTP(ctx sdk.Context, mtpaddress string, id uint64) error { store := ctx.KVStore(k.storeKey) key := types.GetMTPKey(sdk.MustAccAddressFromBech32(mtpaddress), id) diff --git a/x/perpetual/keeper/open_long_process.go b/x/perpetual/keeper/open_long_process.go index aa49faa71..4b4759827 100644 --- a/x/perpetual/keeper/open_long_process.go +++ b/x/perpetual/keeper/open_long_process.go @@ -82,7 +82,7 @@ func (k Keeper) ProcessOpenLong(ctx sdk.Context, mtp *types.MTP, leverage sdk.De } // Update the MTP health. - lr, err := k.OpenLongChecker.UpdateMTPHealth(ctx, *mtp, ammPool, baseCurrency) + lr, err := k.OpenLongChecker.GetMTPHealth(ctx, *mtp, ammPool, baseCurrency) if err != nil { return nil, err } diff --git a/x/perpetual/keeper/open_long_test.go b/x/perpetual/keeper/open_long_test.go index 7342821eb..ebabff181 100644 --- a/x/perpetual/keeper/open_long_test.go +++ b/x/perpetual/keeper/open_long_test.go @@ -315,7 +315,7 @@ func TestOpenLong_LeverageRatioLessThanSafetyFactor(t *testing.T) { lr := math.LegacyNewDec(50) - mockChecker.On("UpdateMTPHealth", ctx, *mtp, ammPool, ptypes.BaseCurrency).Return(lr, nil) + mockChecker.On("GetMTPHealth", ctx, *mtp, ammPool, ptypes.BaseCurrency).Return(lr, nil) mockChecker.On("GetSafetyFactor", ctx).Return(sdk.NewDec(100)) _, err := k.OpenLong(ctx, ammPool.PoolId, msg, ptypes.BaseCurrency, false) @@ -385,7 +385,7 @@ func TestOpenLong_Success(t *testing.T) { lr := math.LegacyNewDec(50) - mockChecker.On("UpdateMTPHealth", ctx, *mtp, ammPool, ptypes.BaseCurrency).Return(lr, nil) + mockChecker.On("GetMTPHealth", ctx, *mtp, ammPool, ptypes.BaseCurrency).Return(lr, nil) safetyFactor := math.LegacyNewDec(10) diff --git a/x/perpetual/keeper/open_short_process.go b/x/perpetual/keeper/open_short_process.go index 8597caad1..a85ddb370 100644 --- a/x/perpetual/keeper/open_short_process.go +++ b/x/perpetual/keeper/open_short_process.go @@ -62,7 +62,7 @@ func (k Keeper) ProcessOpenShort(ctx sdk.Context, mtp *types.MTP, leverage sdk.D } // Update the MTP health. - lr, err := k.OpenShortChecker.UpdateMTPHealth(ctx, *mtp, ammPool, baseCurrency) + lr, err := k.OpenShortChecker.GetMTPHealth(ctx, *mtp, ammPool, baseCurrency) if err != nil { return nil, err } diff --git a/x/perpetual/keeper/open_short_test.go b/x/perpetual/keeper/open_short_test.go index fc3904c25..ad9a47242 100644 --- a/x/perpetual/keeper/open_short_test.go +++ b/x/perpetual/keeper/open_short_test.go @@ -305,7 +305,7 @@ func TestOpenShort_LeverageRatioLessThanSafetyFactor(t *testing.T) { lr := math.LegacyNewDec(50) - mockChecker.On("UpdateMTPHealth", ctx, *mtp, ammPool, ptypes.BaseCurrency).Return(lr, nil) + mockChecker.On("GetMTPHealth", ctx, *mtp, ammPool, ptypes.BaseCurrency).Return(lr, nil) mockChecker.On("GetSafetyFactor", ctx).Return(sdk.NewDec(100)) _, err := k.OpenShort(ctx, ammPool.PoolId, msg, ptypes.BaseCurrency, false) @@ -372,7 +372,7 @@ func TestOpenShort_Success(t *testing.T) { lr := math.LegacyNewDec(50) - mockChecker.On("UpdateMTPHealth", ctx, *mtp, ammPool, ptypes.BaseCurrency).Return(lr, nil) + mockChecker.On("GetMTPHealth", ctx, *mtp, ammPool, ptypes.BaseCurrency).Return(lr, nil) safetyFactor := math.LegacyNewDec(10) diff --git a/x/perpetual/keeper/pool.go b/x/perpetual/keeper/pool.go index fbcb0e1f5..8e7372734 100644 --- a/x/perpetual/keeper/pool.go +++ b/x/perpetual/keeper/pool.go @@ -3,6 +3,9 @@ package keeper import ( "github.com/cosmos/cosmos-sdk/store/prefix" sdk "github.com/cosmos/cosmos-sdk/types" + atypes "github.com/elys-network/elys/x/assetprofile/types" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/elys-network/elys/x/perpetual/types" ) @@ -13,6 +16,14 @@ func (k Keeper) RemovePool(ctx sdk.Context, index uint64) { store.Delete(key) } +func (k Keeper) GetBaseCurreny(ctx sdk.Context) (atypes.Entry, bool) { + baseCurrency, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) + if !found { + return atypes.Entry{}, false + } + return baseCurrency, true +} + // GetPool returns a pool from its index func (k Keeper) GetPool(ctx sdk.Context, poolId uint64) (val types.Pool, found bool) { store := ctx.KVStore(k.storeKey) @@ -68,3 +79,247 @@ func (k Keeper) RemoveLegacyPool(ctx sdk.Context, index uint64) { store := ctx.KVStore(k.storeKey) store.Delete(types.GetLegacyPoolKey(index)) } + +func (k Keeper) SetBorrowRate(ctx sdk.Context, block uint64, pool uint64, interest types.InterestBlock) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.InterestRatePrefix) + prev := types.GetInterestRateKey(block-1, pool) + key := types.GetInterestRateKey(block, pool) + if store.Has(prev) { + lastBlock := types.InterestBlock{} + bz := store.Get(prev) + k.cdc.MustUnmarshal(bz, &lastBlock) + interest.InterestRate = interest.InterestRate.Add(lastBlock.InterestRate) + + bz = k.cdc.MustMarshal(&interest) + store.Set(key, bz) + } else { + bz := k.cdc.MustMarshal(&interest) + store.Set(key, bz) + } +} + +// Test it out +// Deletes all pool blocks at delBlock +func (k Keeper) DeleteBorrowRate(ctx sdk.Context, delBlock uint64) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), append(types.InterestRatePrefix, types.GetUint64Bytes(delBlock)...)) + iterator := sdk.KVStorePrefixIterator(store, nil) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + store.Delete(iterator.Key()) + } +} + +func (k Keeper) GetAllBorrowRate(ctx sdk.Context) []types.InterestBlock { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.InterestRatePrefix) + iterator := sdk.KVStorePrefixIterator(store, nil) + defer iterator.Close() + + interests := []types.InterestBlock{} + for ; iterator.Valid(); iterator.Next() { + interest := types.InterestBlock{} + k.cdc.MustUnmarshal(iterator.Value(), &interest) + + interests = append(interests, interest) + } + return interests +} + +func (k Keeper) GetBorrowRate(ctx sdk.Context, startBlock uint64, pool uint64, borrowed sdk.Dec) sdk.Dec { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.InterestRatePrefix) + currentBlockKey := types.GetInterestRateKey(uint64(ctx.BlockHeight()), pool) + startBlockKey := types.GetInterestRateKey(startBlock, pool) + + // note: exclude start block + if store.Has(startBlockKey) && store.Has(currentBlockKey) && startBlock != uint64(ctx.BlockHeight()) { + bz := store.Get(startBlockKey) + startInterestBlock := types.InterestBlock{} + k.cdc.MustUnmarshal(bz, &startInterestBlock) + + bz = store.Get(currentBlockKey) + endInterestBlock := types.InterestBlock{} + k.cdc.MustUnmarshal(bz, &endInterestBlock) + + totalInterest := endInterestBlock.InterestRate.Sub(startInterestBlock.InterestRate) + + newInterest := borrowed.Mul(totalInterest) + + return newInterest + } + + if !store.Has(startBlockKey) && store.Has(currentBlockKey) { + iterator := sdk.KVStorePrefixIterator(store, nil) + defer iterator.Close() + + firstStoredBlock := uint64(0) + if iterator.Valid() { + interestBlock := types.InterestBlock{} + firstStoredBlock = sdk.BigEndianToUint64(iterator.Key()) + k.cdc.MustUnmarshal(iterator.Value(), &interestBlock) + } + if firstStoredBlock > startBlock { + bz := store.Get(currentBlockKey) + endInterestBlock := types.InterestBlock{} + k.cdc.MustUnmarshal(bz, &endInterestBlock) + + totalInterest := endInterestBlock.InterestRate + newInterest := borrowed.Mul(totalInterest) + return newInterest + } + } + params, found := k.GetPool(ctx, pool) + if !found { + return sdk.ZeroDec() + } + newInterest := borrowed.Mul(params.BorrowInterestRate) + return newInterest +} + +func (k Keeper) SetFundingRate(ctx sdk.Context, block uint64, pool uint64, funding types.FundingRateBlock) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.FundingRatePrefix) + prev := types.GetFundingRateKey(block-1, pool) + key := types.GetFundingRateKey(block, pool) + if store.Has(prev) { + lastBlock := types.FundingRateBlock{} + bz := store.Get(prev) + k.cdc.MustUnmarshal(bz, &lastBlock) + funding.FundingRate = funding.FundingRate.Add(lastBlock.FundingRate) + funding.FundingAmountLong = funding.FundingAmountLong.Add(lastBlock.FundingAmountLong) + funding.FundingAmountShort = funding.FundingAmountShort.Add(lastBlock.FundingAmountShort) + + funding.FundingRateLong = funding.FundingRateLong.Add(lastBlock.FundingRateLong) + funding.FundingRateShort = funding.FundingRateShort.Add(lastBlock.FundingRateShort) + + bz = k.cdc.MustMarshal(&funding) + store.Set(key, bz) + } else { + bz := k.cdc.MustMarshal(&funding) + store.Set(key, bz) + } +} + +// Test it out +// Deletes all pool blocks at delBlock +func (k Keeper) DeleteFundingRate(ctx sdk.Context, delBlock uint64) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), append(types.FundingRatePrefix, types.GetUint64Bytes(delBlock)...)) + iterator := sdk.KVStorePrefixIterator(store, nil) + defer iterator.Close() + + for ; iterator.Valid(); iterator.Next() { + store.Delete(iterator.Key()) + } +} + +func (k Keeper) GetAllFundingRate(ctx sdk.Context) []types.FundingRateBlock { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.FundingRatePrefix) + iterator := sdk.KVStorePrefixIterator(store, nil) + defer iterator.Close() + + fundings := []types.FundingRateBlock{} + for ; iterator.Valid(); iterator.Next() { + funding := types.FundingRateBlock{} + k.cdc.MustUnmarshal(iterator.Value(), &funding) + + fundings = append(fundings, funding) + } + return fundings +} + +func (k Keeper) GetFundingRate(ctx sdk.Context, startBlock uint64, pool uint64) (net sdk.Dec, long sdk.Dec, short sdk.Dec) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.FundingRatePrefix) + currentBlockKey := types.GetFundingRateKey(uint64(ctx.BlockHeight()), pool) + startBlockKey := types.GetFundingRateKey(startBlock, pool) + + // note: exclude start block + if store.Has(startBlockKey) && store.Has(currentBlockKey) && startBlock != uint64(ctx.BlockHeight()) { + bz := store.Get(startBlockKey) + startFundingBlock := types.FundingRateBlock{} + k.cdc.MustUnmarshal(bz, &startFundingBlock) + + bz = store.Get(currentBlockKey) + endFundingBlock := types.FundingRateBlock{} + k.cdc.MustUnmarshal(bz, &endFundingBlock) + + totalFunding := endFundingBlock.FundingRate.Sub(startFundingBlock.FundingRate) + totalFundingLong := endFundingBlock.FundingRateLong.Sub(startFundingBlock.FundingRateLong) + totalFundingShort := endFundingBlock.FundingRateShort.Sub(startFundingBlock.FundingRateShort) + return totalFunding, totalFundingLong, totalFundingShort + } + + if !store.Has(startBlockKey) && store.Has(currentBlockKey) { + iterator := sdk.KVStorePrefixIterator(store, nil) + defer iterator.Close() + + firstStoredBlock := uint64(0) + if iterator.Valid() { + fundingBlock := types.FundingRateBlock{} + firstStoredBlock = sdk.BigEndianToUint64(iterator.Key()) + k.cdc.MustUnmarshal(iterator.Value(), &fundingBlock) + } + if firstStoredBlock > startBlock { + bz := store.Get(currentBlockKey) + endFundingBlock := types.FundingRateBlock{} + k.cdc.MustUnmarshal(bz, &endFundingBlock) + + return endFundingBlock.FundingRate, endFundingBlock.FundingRateLong, endFundingBlock.FundingRateShort + } + } + params, found := k.GetPool(ctx, pool) + if !found { + return sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec() + } + + if params.BorrowInterestRate.IsPositive() { + return params.FundingRate, params.FundingRate, sdk.ZeroDec() + } else { + return params.FundingRate, sdk.ZeroDec(), params.FundingRate + } +} + +func (k Keeper) GetFundingDistributionValue(ctx sdk.Context, startBlock uint64, pool uint64) (long sdk.Dec, short sdk.Dec) { + store := prefix.NewStore(ctx.KVStore(k.storeKey), types.FundingRatePrefix) + currentBlockKey := types.GetFundingRateKey(uint64(ctx.BlockHeight()), pool) + startBlockKey := types.GetFundingRateKey(startBlock, pool) + + // note: exclude start block + if store.Has(startBlockKey) && store.Has(currentBlockKey) && startBlock != uint64(ctx.BlockHeight()) { + bz := store.Get(startBlockKey) + startFundingBlock := types.FundingRateBlock{} + k.cdc.MustUnmarshal(bz, &startFundingBlock) + + bz = store.Get(currentBlockKey) + endFundingBlock := types.FundingRateBlock{} + k.cdc.MustUnmarshal(bz, &endFundingBlock) + + totalCustodyLong := endFundingBlock.FundingAmountLong.Sub(startFundingBlock.FundingAmountLong) + numberOfBlocks := ctx.BlockHeight() - int64(startBlock) + + totalCustodyShort := endFundingBlock.FundingAmountShort.Sub(startFundingBlock.FundingAmountShort) + + return totalCustodyLong.ToLegacyDec().Quo(sdk.NewDec(numberOfBlocks)), totalCustodyShort.ToLegacyDec().Quo(sdk.NewDec(numberOfBlocks)) + } + + if !store.Has(startBlockKey) && store.Has(currentBlockKey) { + iterator := sdk.KVStorePrefixIterator(store, nil) + defer iterator.Close() + + firstStoredBlock := uint64(0) + if iterator.Valid() { + fundingBlock := types.FundingRateBlock{} + firstStoredBlock = sdk.BigEndianToUint64(iterator.Key()) + k.cdc.MustUnmarshal(iterator.Value(), &fundingBlock) + } + if firstStoredBlock > startBlock { + bz := store.Get(currentBlockKey) + endFundingBlock := types.FundingRateBlock{} + k.cdc.MustUnmarshal(bz, &endFundingBlock) + + numberOfBlocks := ctx.BlockHeight() - int64(startBlock) + 1 + totalCustodyLong := endFundingBlock.FundingAmountLong + totalCustodyShort := endFundingBlock.FundingAmountShort + return totalCustodyLong.ToLegacyDec().Quo(sdk.NewDec(numberOfBlocks)), totalCustodyShort.ToLegacyDec().Quo(sdk.NewDec(numberOfBlocks)) + } + } + + return sdk.ZeroDec(), sdk.ZeroDec() +} diff --git a/x/perpetual/keeper/begin_blocker_process_mtp.go b/x/perpetual/keeper/process_mtp.go similarity index 78% rename from x/perpetual/keeper/begin_blocker_process_mtp.go rename to x/perpetual/keeper/process_mtp.go index 677701a0f..8e159b29c 100644 --- a/x/perpetual/keeper/begin_blocker_process_mtp.go +++ b/x/perpetual/keeper/process_mtp.go @@ -14,17 +14,10 @@ import ( "github.com/elys-network/elys/x/perpetual/types" ) -func BeginBlockerProcessMTP(ctx sdk.Context, k Keeper, mtp *types.MTP, pool types.Pool, ammPool ammtypes.Pool, baseCurrency string, baseCurrencyDecimal uint64) error { - defer func() { - if r := recover(); r != nil { - if msg, ok := r.(string); ok { - ctx.Logger().Error(msg) - } - } - }() +func (k Keeper) CheckAndLiquidateUnhealthyPosition(ctx sdk.Context, mtp *types.MTP, pool types.Pool, ammPool ammtypes.Pool, baseCurrency string, baseCurrencyDecimal uint64) error { var err error // update mtp take profit liabilities - // calculate mtp take profit liablities, delta x_tp_l = delta y_tp_c * current price (take profit liabilities = take profit custody * current price) + // calculate mtp take profit liabilities, delta x_tp_l = delta y_tp_c * current price (take profit liabilities = take profit custody * current price) mtp.TakeProfitLiabilities, err = k.CalcMTPTakeProfitLiability(ctx, mtp, baseCurrency) if err != nil { return errors.Wrap(err, fmt.Sprintf("error calculating mtp take profit liabilities: %s", mtp.String())) @@ -34,18 +27,19 @@ func BeginBlockerProcessMTP(ctx sdk.Context, k Keeper, mtp *types.MTP, pool type if err != nil { return errors.Wrap(err, fmt.Sprintf("error calculating mtp take profit borrow rate: %s", mtp.String())) } - h, err := k.UpdateMTPHealth(ctx, *mtp, ammPool, baseCurrency) + // Handle Borrow Interest if within epoch position + if _, err := k.SettleBorrowInterest(ctx, mtp, &pool, ammPool); err != nil { + return errors.Wrap(err, fmt.Sprintf("error handling borrow interest payment: %s", mtp.CollateralAsset)) + } + h, err := k.GetMTPHealth(ctx, *mtp, ammPool, baseCurrency) if err != nil { return errors.Wrap(err, fmt.Sprintf("error updating mtp health: %s", mtp.String())) } mtp.MtpHealth = h - // Handle Borrow Interest if within epoch position - if err := k.HandleBorrowInterest(ctx, mtp, &pool, ammPool); err != nil { - return errors.Wrap(err, fmt.Sprintf("error handling borrow interest payment: %s", mtp.CollateralAsset)) - } - if err := k.HandleFundingFeeCollection(ctx, mtp, &pool, ammPool, baseCurrency); err != nil { - return errors.Wrap(err, fmt.Sprintf("error handling funding fee collection: %s", mtp.CollateralAsset)) + toPay, err := k.SettleFunding(ctx, mtp, &pool, ammPool, baseCurrency) + if err != nil { + return errors.Wrap(err, fmt.Sprintf("error handling funding fee: %s", mtp.CollateralAsset)) } err = k.SetMTP(ctx, mtp) @@ -109,5 +103,17 @@ func BeginBlockerProcessMTP(ctx sdk.Context, k Keeper, mtp *types.MTP, pool type return errors.Wrap(err, "error executing force close") } + senderAddress, _ := sdk.AccAddressFromBech32(mtp.Address) + found = k.DoesMTPExist(ctx, senderAddress, mtp.Id) + empty := sdk.Coin{} + if !found && toPay != empty { + k.SetToPay(ctx, &types.ToPay{ + AssetDenom: toPay.Denom, + AssetBalance: toPay.Amount, + Address: senderAddress.String(), + Id: mtp.Id, + }) + } + return nil } diff --git a/x/perpetual/keeper/process_mtp_test.go b/x/perpetual/keeper/process_mtp_test.go new file mode 100644 index 000000000..fc2ea8b77 --- /dev/null +++ b/x/perpetual/keeper/process_mtp_test.go @@ -0,0 +1,193 @@ +package keeper_test + +import ( + "testing" + + sdk "github.com/cosmos/cosmos-sdk/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" + "github.com/elys-network/elys/x/perpetual/types" + + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + simapp "github.com/elys-network/elys/app" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/stretchr/testify/require" +) + +func TestCheckAndLiquidateUnhealthyPosition(t *testing.T) { + app := simapp.InitElysTestApp(true) + ctx := app.BaseApp.NewContext(true, tmproto.Header{}) + + mk, amm, oracle := app.PerpetualKeeper, app.AmmKeeper, app.OracleKeeper + + // Setup coin prices + SetupStableCoinPrices(ctx, oracle) + + // Set asset profile + app.AssetprofileKeeper.SetEntry(ctx, assetprofiletypes.Entry{ + BaseDenom: ptypes.BaseCurrency, + Denom: ptypes.BaseCurrency, + Decimals: 6, + }) + app.AssetprofileKeeper.SetEntry(ctx, assetprofiletypes.Entry{ + BaseDenom: ptypes.ATOM, + Denom: ptypes.ATOM, + Decimals: 6, + }) + + // Generate 1 random account with 1000stake balanced + addr := simapp.AddTestAddrs(app, ctx, 3, sdk.NewInt(1000000000000)) + + // Create a pool + // Mint 100000USDC + usdcToken := []sdk.Coin{sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(200000000000))} + // Mint 100000ATOM + atomToken := []sdk.Coin{sdk.NewCoin(ptypes.ATOM, sdk.NewInt(200000000000))} + + err := app.BankKeeper.MintCoins(ctx, ammtypes.ModuleName, usdcToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ammtypes.ModuleName, addr[0], usdcToken) + require.NoError(t, err) + + err = app.BankKeeper.MintCoins(ctx, ammtypes.ModuleName, atomToken) + require.NoError(t, err) + err = app.BankKeeper.SendCoinsFromModuleToAccount(ctx, ammtypes.ModuleName, addr[0], atomToken) + require.NoError(t, err) + + poolAssets := []ammtypes.PoolAsset{ + { + Weight: sdk.NewInt(50), + Token: sdk.NewCoin(ptypes.ATOM, sdk.NewInt(10000000000)), + }, + { + Weight: sdk.NewInt(50), + Token: sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000000)), + }, + } + + argSwapFee := sdk.MustNewDecFromStr("0.0") + argExitFee := sdk.MustNewDecFromStr("0.0") + + poolParams := &ammtypes.PoolParams{ + SwapFee: argSwapFee, + ExitFee: argExitFee, + } + + msg := ammtypes.NewMsgCreatePool( + addr[0].String(), + poolParams, + poolAssets, + ) + + // Create a ATOM+USDC pool + poolId, err := amm.CreatePool(ctx, msg) + require.NoError(t, err) + require.Equal(t, poolId, uint64(1)) + + pools := amm.GetAllPool(ctx) + + // check length of pools + require.Equal(t, len(pools), 1) + + // check block height + require.Equal(t, int64(0), ctx.BlockHeight()) + + pool, found := amm.GetPool(ctx, poolId) + require.Equal(t, found, true) + + poolAddress := sdk.MustAccAddressFromBech32(pool.GetAddress()) + require.NoError(t, err) + + app.BankKeeper.SendCoins(ctx, addr[0], poolAddress, sdk.NewCoins(sdk.NewCoin("stake", sdk.NewInt(1000000)))) + // Balance check before create a perpetual position + balances := app.BankKeeper.GetAllBalances(ctx, poolAddress) + require.Equal(t, balances.AmountOf(ptypes.BaseCurrency), sdk.NewInt(100000000000)) + require.Equal(t, balances.AmountOf(ptypes.ATOM), sdk.NewInt(10000000000)) + + // Create a perpetual position open msg + msg2 := types.NewMsgOpen( + addr[0].String(), + types.Position_LONG, + sdk.NewDec(5), + ptypes.ATOM, + sdk.NewCoin(ptypes.BaseCurrency, sdk.NewInt(100000000)), + sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + sdk.ZeroDec(), + ) + + _, err = mk.Open(ctx, msg2, false) + require.NoError(t, err) + + mtps := mk.GetAllMTPs(ctx) + require.Equal(t, len(mtps), 1) + + balances = app.BankKeeper.GetAllBalances(ctx, poolAddress) + require.Equal(t, balances.AmountOf(ptypes.BaseCurrency), sdk.NewInt(100100000000)) + require.Equal(t, balances.AmountOf(ptypes.ATOM), sdk.NewInt(10000000000)) + + _, found = mk.OpenLongChecker.GetPool(ctx, pool.PoolId) + require.Equal(t, found, true) + + err = mk.InvariantCheck(ctx) + require.Equal(t, err, nil) + + // Set params + params := mk.GetParams(ctx) + params.FundingFeeCollectionAddress = addr[1].String() + params.IncrementalBorrowInterestPaymentFundAddress = addr[2].String() + params.IncrementalBorrowInterestPaymentFundPercentage = sdk.MustNewDecFromStr("0.5") + mk.SetParams(ctx, ¶ms) + + mtp := mtps[0] + + perpPool, _ := mk.GetPool(ctx, pool.PoolId) + + err = mk.CheckAndLiquidateUnhealthyPosition(ctx, &mtp, perpPool, pool, ptypes.BaseCurrency, 6) + require.NoError(t, err) + + // Set borrow interest rate to 100% to test liquidation + perpPool.BorrowInterestRate = sdk.MustNewDecFromStr("1.0") + mk.SetPool(ctx, perpPool) + + // Check MTP + require.Equal(t, types.MTP{ + Address: addr[0].String(), + CollateralAsset: "uusdc", + TradingAsset: "uatom", + LiabilitiesAsset: "uusdc", + CustodyAsset: "uatom", + Collateral: sdk.NewInt(100000000), + Liabilities: sdk.NewInt(400000000), + BorrowInterestPaidCollateral: sdk.NewInt(0), + BorrowInterestPaidCustody: sdk.NewInt(0), + BorrowInterestUnpaidCollateral: sdk.NewInt(0), + Custody: sdk.NewInt(49751243), + TakeProfitLiabilities: sdk.NewInt(495049497), + TakeProfitCustody: sdk.NewInt(49751243), + Leverage: sdk.NewDec(5), + MtpHealth: sdk.MustNewDecFromStr("1.249999982500000000"), + Position: types.Position_LONG, + Id: uint64(1), + AmmPoolId: uint64(1), + ConsolidateLeverage: sdk.NewDec(4), + SumCollateral: sdk.NewInt(100000000), + TakeProfitPrice: sdk.MustNewDecFromStr(types.TakeProfitPriceDefault), + TakeProfitBorrowRate: sdk.MustNewDecFromStr("1.0"), + FundingFeePaidCollateral: sdk.NewInt(0), + FundingFeePaidCustody: sdk.NewInt(0), + FundingFeeReceivedCollateral: sdk.NewInt(0), + FundingFeeReceivedCustody: sdk.NewInt(0), + OpenPrice: sdk.MustNewDecFromStr("10.050000157785002477"), + LastInterestCalcTime: uint64(ctx.BlockTime().Unix()), + LastFundingCalcTime: uint64(ctx.BlockTime().Unix()), + StopLossPrice: sdk.ZeroDec(), + }, mtp) + + err = mk.CheckAndLiquidateUnhealthyPosition(ctx, &mtp, perpPool, pool, ptypes.BaseCurrency, 6) + require.NoError(t, err) + + mtps = mk.GetAllMTPs(ctx) + require.Equal(t, len(mtps), 0) +} + +// TODO: Add funding rate tests diff --git a/x/perpetual/keeper/repay.go b/x/perpetual/keeper/repay.go index bcfdd9650..7f8162661 100644 --- a/x/perpetual/keeper/repay.go +++ b/x/perpetual/keeper/repay.go @@ -36,7 +36,7 @@ func (k Keeper) Repay(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool } var err error - mtp.MtpHealth, err = k.UpdateMTPHealth(ctx, *mtp, ammPool, baseCurrency) + mtp.MtpHealth, err = k.GetMTPHealth(ctx, *mtp, ammPool, baseCurrency) if err != nil { return err } diff --git a/x/perpetual/keeper/settle_borrow_interest.go b/x/perpetual/keeper/settle_borrow_interest.go new file mode 100644 index 000000000..27e1e3a8d --- /dev/null +++ b/x/perpetual/keeper/settle_borrow_interest.go @@ -0,0 +1,65 @@ +package keeper + +import ( + errorsmod "cosmossdk.io/errors" + "cosmossdk.io/math" + sdk "github.com/cosmos/cosmos-sdk/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + assetprofiletypes "github.com/elys-network/elys/x/assetprofile/types" + ptypes "github.com/elys-network/elys/x/parameter/types" + "github.com/elys-network/elys/x/perpetual/types" +) + +func (k Keeper) SettleBorrowInterest(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool) (math.Int, error) { + entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) + if !found { + return sdk.ZeroInt(), errorsmod.Wrapf(assetprofiletypes.ErrAssetProfileNotFound, "asset %s not found", ptypes.BaseCurrency) + } + baseCurrency := entry.Denom + + borrowInterestPaymentInt := k.GetBorrowInterest(ctx, mtp, ammPool) + // pay interest+unpaid collateral amount + finalBorrowInterestPayment, err := k.IncrementalBorrowInterestPayment(ctx, borrowInterestPaymentInt, mtp, pool, ammPool, baseCurrency) + if err != nil { + ctx.Logger().Error(errorsmod.Wrap(err, "error executing incremental borrow interest payment").Error()) + } + + mtp.LastInterestCalcBlock = uint64(ctx.BlockHeight()) + mtp.LastInterestCalcTime = uint64(ctx.BlockTime().Unix()) + err = k.SetMTP(ctx, mtp) + if err != nil { + return finalBorrowInterestPayment, err + } + + _, err = k.GetMTPHealth(ctx, *mtp, ammPool, baseCurrency) + return finalBorrowInterestPayment, err +} + +func (k Keeper) GetBorrowInterest(ctx sdk.Context, mtp *types.MTP, ammPool ammtypes.Pool) math.Int { + entry, found := k.assetProfileKeeper.GetEntry(ctx, ptypes.BaseCurrency) + if !found { + return sdk.ZeroInt() + } + baseCurrency := entry.Denom + // Unpaid collateral + unpaidCollateral := sdk.ZeroInt() + if mtp.BorrowInterestUnpaidCollateral.IsPositive() { + if mtp.CollateralAsset == baseCurrency { + unpaidCollateral = unpaidCollateral.Add(mtp.BorrowInterestUnpaidCollateral) + } else { + // Liability is in base currency, so convert it to base currency + unpaidCollateralIn := sdk.NewCoin(mtp.CollateralAsset, mtp.BorrowInterestUnpaidCollateral) + C, err := k.EstimateSwapGivenOut(ctx, unpaidCollateralIn, baseCurrency, ammPool) + if err != nil { + return sdk.ZeroInt() + } + + unpaidCollateral = unpaidCollateral.Add(C) + } + } + sum := mtp.Liabilities.Add(unpaidCollateral) + + // Get interest + borrowInterestPayment := k.GetBorrowRate(ctx, mtp.LastInterestCalcBlock, mtp.AmmPoolId, sdk.NewDecFromInt(sum)) + return borrowInterestPayment.Mul(mtp.TakeProfitBorrowRate).TruncateInt() +} diff --git a/x/perpetual/keeper/handle_funding_fee_collection.go b/x/perpetual/keeper/settle_funding_fee_collection.go similarity index 65% rename from x/perpetual/keeper/handle_funding_fee_collection.go rename to x/perpetual/keeper/settle_funding_fee_collection.go index a055ec4a9..e1c1d39bd 100644 --- a/x/perpetual/keeper/handle_funding_fee_collection.go +++ b/x/perpetual/keeper/settle_funding_fee_collection.go @@ -1,30 +1,52 @@ package keeper import ( + "cosmossdk.io/math" sdk "github.com/cosmos/cosmos-sdk/types" ammtypes "github.com/elys-network/elys/x/amm/types" "github.com/elys-network/elys/x/perpetual/types" ) -// HandleFundingFeeCollection handles funding fee collection -func (k Keeper) HandleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) error { - // get funding rate - fundingRate := pool.FundingRate +// SettleFunding handles funding fee collection and distribution +func (k Keeper) SettleFunding(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) (sdk.Coin, error) { - // if funding rate is zero, return - if fundingRate.IsZero() { - return nil + err := k.SettleFundingFeeCollection(ctx, mtp, pool, ammPool, baseCurrency) + if err != nil { + return sdk.Coin{}, err } - // if funding rate is negative and mtp position is long or funding rate is positive and mtp position is short, return - if (fundingRate.IsNegative() && mtp.Position == types.Position_LONG) || (fundingRate.IsPositive() && mtp.Position == types.Position_SHORT) { - return nil + toPay, err := k.SettleFundingFeeDistribution(ctx, mtp, pool, ammPool, baseCurrency) + if err != nil { + return sdk.Coin{}, err + } + + mtp.LastFundingCalcBlock = uint64(ctx.BlockHeight()) + mtp.LastFundingCalcTime = uint64(ctx.BlockTime().Unix()) + + // apply changes to mtp object + err = k.SetMTP(ctx, mtp) + if err != nil { + return sdk.Coin{}, err } + return toPay, nil +} + +func (k Keeper) SettleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) error { + // get funding rate + _, longRate, shortRate := k.GetFundingRate(ctx, mtp.LastFundingCalcBlock, mtp.AmmPoolId) + + var takeAmountCustodyAmount math.Int + if mtp.Position == types.Position_LONG { + takeAmountCustodyAmount = types.CalcTakeAmount(mtp.Custody, longRate) + } else { + takeAmountCustodyAmount = types.CalcTakeAmount(mtp.Custody, shortRate) + } // Calculate the take amount in custody asset - takeAmountCustodyAmount := types.CalcTakeAmount(mtp.Custody, mtp.CustodyAsset, fundingRate) + if !takeAmountCustodyAmount.IsPositive() { + return nil + } - // Build the take amount coin takeAmountCustody := sdk.NewCoin(mtp.CustodyAsset, takeAmountCustodyAmount) // Swap the take amount to collateral asset @@ -84,7 +106,7 @@ func (k Keeper) HandleFundingFeeCollection(ctx sdk.Context, mtp *types.MTP, pool k.SetPool(ctx, *pool) // update mtp health - _, err = k.UpdateMTPHealth(ctx, *mtp, ammPool, baseCurrency) + _, err = k.GetMTPHealth(ctx, *mtp, ammPool, baseCurrency) if err != nil { return err } diff --git a/x/perpetual/keeper/settle_funding_fee_distribution.go b/x/perpetual/keeper/settle_funding_fee_distribution.go new file mode 100644 index 000000000..5cb49d0cc --- /dev/null +++ b/x/perpetual/keeper/settle_funding_fee_distribution.go @@ -0,0 +1,97 @@ +package keeper + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + ammtypes "github.com/elys-network/elys/x/amm/types" + "github.com/elys-network/elys/x/perpetual/types" +) + +// TODO: Think about funding rate algo, edge cases +func (k Keeper) SettleFundingFeeDistribution(ctx sdk.Context, mtp *types.MTP, pool *types.Pool, ammPool ammtypes.Pool, baseCurrency string) (sdk.Coin, error) { + // get mtp address + mtpAddress, err := sdk.AccAddressFromBech32(mtp.Address) + if err != nil { + return sdk.Coin{}, err + } + + totalCustodyLong := sdk.ZeroInt() + totalCustodyShort := sdk.ZeroInt() + + // account liabilities from long position + liabilitiesLong := sdk.ZeroInt() + for _, asset := range pool.PoolAssetsLong { + liabilitiesLong = liabilitiesLong.Add(asset.Liabilities) + totalCustodyLong = totalCustodyLong.Add(asset.Custody) + } + + // account liabilities from short position + liabilitiesShort := sdk.ZeroInt() + for _, asset := range pool.PoolAssetsShort { + liabilitiesShort = liabilitiesShort.Add(asset.Liabilities) + totalCustodyShort = totalCustodyShort.Add(asset.Custody) + } + + // get funding fee collection address + fundingFeeCollectionAddress := k.GetFundingFeeCollectionAddress(ctx) + + // get base currency balance + balance := k.bankKeeper.GetBalance(ctx, fundingFeeCollectionAddress, baseCurrency) + + // if balance is zero, return + if balance.IsZero() { + return sdk.Coin{}, nil + } + + // Total fund collected should be + long, short := k.GetFundingDistributionValue(ctx, uint64(ctx.BlockHeight()), pool.AmmPoolId) + var totalFund sdk.Dec + // calc funding fee share + var fundingFeeShare sdk.Dec + if mtp.Position == types.Position_LONG { + // Ensure liabilitiesLong is not zero to avoid division by zero + if liabilitiesLong.IsZero() { + return sdk.Coin{}, types.ErrAmountTooLow + } + fundingFeeShare = sdk.NewDecFromInt(mtp.Liabilities).Quo(sdk.NewDecFromInt(liabilitiesLong)) + totalFund = short + } else { + // Ensure liabilitiesShort is not zero to avoid division by zero + if liabilitiesShort.IsZero() { + return sdk.Coin{}, types.ErrAmountTooLow + } + fundingFeeShare = sdk.NewDecFromInt(mtp.Liabilities).Quo(sdk.NewDecFromInt(liabilitiesShort)) + totalFund = long + } + + // if funding fee share is zero, skip mtp + if fundingFeeShare.IsZero() { + return sdk.Coin{}, nil + } + + // calculate funding fee amount + fundingFeeAmount := sdk.NewCoin(baseCurrency, totalFund.Mul(fundingFeeShare).TruncateInt()) + toPay := sdk.Coin{} + + if balance.Amount.LT(fundingFeeAmount.Amount) { + toPay = fundingFeeAmount + } else { + // transfer funding fee amount to mtp address + if err := k.bankKeeper.SendCoins(ctx, fundingFeeCollectionAddress, mtpAddress, sdk.NewCoins(fundingFeeAmount)); err != nil { + return sdk.Coin{}, err + } + } + + // update received funding fee accounting buckets + // Swap the take amount to collateral asset + fundingFeeCollateralAmount, err := k.EstimateSwap(ctx, fundingFeeAmount, mtp.CollateralAsset, ammPool) + if err != nil { + return sdk.Coin{}, err + } + + // add payment to total funding fee paid in collateral asset + mtp.FundingFeeReceivedCollateral = mtp.FundingFeeReceivedCollateral.Add(fundingFeeCollateralAmount) + // add payment to total funding fee paid in custody asset + mtp.FundingFeeReceivedCustody = mtp.FundingFeeReceivedCustody.Add(fundingFeeAmount.Amount) + + return toPay, nil +} diff --git a/x/perpetual/keeper/update_mtp_health.go b/x/perpetual/keeper/update_mtp_health.go index 8380a9aed..73f941416 100644 --- a/x/perpetual/keeper/update_mtp_health.go +++ b/x/perpetual/keeper/update_mtp_health.go @@ -6,13 +6,16 @@ import ( "github.com/elys-network/elys/x/perpetual/types" ) -func (k Keeper) UpdateMTPHealth(ctx sdk.Context, mtp types.MTP, ammPool ammtypes.Pool, baseCurrency string) (sdk.Dec, error) { +func (k Keeper) GetMTPHealth(ctx sdk.Context, mtp types.MTP, ammPool ammtypes.Pool, baseCurrency string) (sdk.Dec, error) { xl := mtp.Liabilities if xl.IsZero() { return sdk.ZeroDec(), nil } + pendingBorrowInterest := k.GetBorrowInterest(ctx, &mtp, ammPool) + mtp.BorrowInterestUnpaidCollateral = mtp.BorrowInterestUnpaidCollateral.Add(pendingBorrowInterest) + // if short position, convert liabilities to base currency if mtp.Position == types.Position_SHORT { liabilities := sdk.NewCoin(mtp.LiabilitiesAsset, xl) @@ -43,8 +46,22 @@ func (k Keeper) UpdateMTPHealth(ctx sdk.Context, mtp types.MTP, ammPool ammtypes } } + // Funding rate payment consideration + // get funding rate + fundingRate, _, _ := k.GetFundingRate(ctx, mtp.LastFundingCalcBlock, mtp.AmmPoolId) + var takeAmountCustodyAmount sdk.Int + // if funding rate is zero, return + if fundingRate.IsZero() { + takeAmountCustodyAmount = sdk.ZeroInt() + } else if (fundingRate.IsNegative() && mtp.Position == types.Position_LONG) || (fundingRate.IsPositive() && mtp.Position == types.Position_SHORT) { + takeAmountCustodyAmount = sdk.ZeroInt() + } else { + // Calculate the take amount in custody asset + takeAmountCustodyAmount = types.CalcTakeAmount(mtp.Custody, fundingRate) + } + // if short position, custody asset is already in base currency - custodyAmtInBaseCurrency := mtp.Custody + custodyAmtInBaseCurrency := mtp.Custody.Sub(takeAmountCustodyAmount) if mtp.Position == types.Position_LONG { custodyAmt := sdk.NewCoin(mtp.CustodyAsset, mtp.Custody) diff --git a/x/perpetual/migrations/v7_migration.go b/x/perpetual/migrations/v7_migration.go index 8ea205d1a..12594aa23 100644 --- a/x/perpetual/migrations/v7_migration.go +++ b/x/perpetual/migrations/v7_migration.go @@ -11,7 +11,7 @@ func (m Migrator) V7Migration(ctx sdk.Context) error { ctx.Logger().Info("Migrating positions from legacy to new format") for _, mtp := range mtps { - new_mtp := types.MTP{ + newMtp := types.MTP{ Address: mtp.Address, CollateralAsset: mtp.CollateralAsset, TradingAsset: mtp.TradingAsset, @@ -40,9 +40,25 @@ func (m Migrator) V7Migration(ctx sdk.Context) error { FundingFeeReceivedCustody: mtp.FundingFeeReceivedCustody, OpenPrice: mtp.OpenPrice, StopLossPrice: sdk.NewDec(0), + LastInterestCalcTime: uint64(ctx.BlockTime().Unix()), + LastInterestCalcBlock: uint64(ctx.BlockHeight()), + LastFundingCalcTime: uint64(ctx.BlockTime().Unix()), + LastFundingCalcBlock: uint64(ctx.BlockHeight()), } m.keeper.DeleteLegacyMTP(ctx, mtp.Address, mtp.Id) - m.keeper.SetMTP(ctx, &new_mtp) + m.keeper.SetMTP(ctx, &newMtp) + + baseCurrency, _ := m.keeper.GetBaseCurreny(ctx) + pool, poolFound := m.keeper.GetPool(ctx, newMtp.AmmPoolId) + if !poolFound { + continue + } + ammPool, poolErr := m.keeper.GetAmmPool(ctx, newMtp.AmmPoolId, newMtp.TradingAsset) + if poolErr != nil { + continue + } + + m.keeper.CheckAndLiquidateUnhealthyPosition(ctx, &newMtp, pool, ammPool, baseCurrency.Denom, baseCurrency.Decimals) } return nil -} \ No newline at end of file +} diff --git a/x/perpetual/module_simulation.go b/x/perpetual/module_simulation.go index ec968066e..5e10f3708 100644 --- a/x/perpetual/module_simulation.go +++ b/x/perpetual/module_simulation.go @@ -50,6 +50,10 @@ const ( // TODO: Determine the simulation weight value defaultWeightMsgBrokerAddCollateral int = 100 + opWeightMsgClosePositions = "op_weight_msg_close_positions" + // TODO: Determine the simulation weight value + defaultWeightMsgClosePositions int = 100 + // this line is used by starport scaffolding # simapp/module/const ) @@ -151,6 +155,17 @@ func (am AppModule) WeightedOperations(simState module.SimulationState) []simtyp perpetualsimulation.SimulateMsgBrokerAddCollateral(am.accountKeeper, am.bankKeeper, am.keeper), )) + var weightMsgClosePositions int + simState.AppParams.GetOrGenerate(simState.Cdc, opWeightMsgClosePositions, &weightMsgClosePositions, nil, + func(_ *rand.Rand) { + weightMsgClosePositions = defaultWeightMsgClosePositions + }, + ) + operations = append(operations, simulation.NewWeightedOperation( + weightMsgClosePositions, + perpetualsimulation.SimulateMsgClosePositions(am.accountKeeper, am.bankKeeper, am.keeper), + )) + // this line is used by starport scaffolding # simapp/module/operation return operations diff --git a/x/perpetual/simulation/close_positions.go b/x/perpetual/simulation/close_positions.go new file mode 100644 index 000000000..c15ac6bac --- /dev/null +++ b/x/perpetual/simulation/close_positions.go @@ -0,0 +1,29 @@ +package simulation + +import ( + "math/rand" + + "github.com/cosmos/cosmos-sdk/baseapp" + sdk "github.com/cosmos/cosmos-sdk/types" + simtypes "github.com/cosmos/cosmos-sdk/types/simulation" + "github.com/elys-network/elys/x/perpetual/keeper" + "github.com/elys-network/elys/x/perpetual/types" +) + +func SimulateMsgClosePositions( + ak types.AccountKeeper, + bk types.BankKeeper, + k keeper.Keeper, +) simtypes.Operation { + return func(r *rand.Rand, app *baseapp.BaseApp, ctx sdk.Context, accs []simtypes.Account, chainID string, + ) (simtypes.OperationMsg, []simtypes.FutureOperation, error) { + simAccount, _ := simtypes.RandomAcc(r, accs) + msg := &types.MsgClosePositions{ + Creator: simAccount.Address.String(), + } + + // TODO: Handling the ClosePositions simulation + + return simtypes.NoOpMsg(types.ModuleName, msg.Type(), "ClosePositions simulation not implemented"), nil, nil + } +} diff --git a/x/perpetual/spec/04_keeper.md b/x/perpetual/spec/04_keeper.md index 942a6f75e..df2406b0d 100644 --- a/x/perpetual/spec/04_keeper.md +++ b/x/perpetual/spec/04_keeper.md @@ -128,15 +128,15 @@ Defines various event emission functions used throughout the module, such as `Em ### Borrow Interest Handling -`HandleBorrowInterest` and `HandleBorrowInterestPayment` manage the computation and payment of borrow interest for MTPs. +`SettleBorrowInterest` and `SettleBorrowInterestPayment` manage the computation and payment of borrow interest for MTPs. ### Funding Fee Handling -`HandleFundingFeeCollection` and `HandleFundingFeeDistribution` manage the collection and distribution of funding fees. +`SettleFundingFeeCollection` and `HandleFundingFeeDistribution` manage the collection and distribution of funding fees. ### Health Updates -`UpdateMTPHealth` and `UpdatePoolHealth` ensure the health of MTPs and pools are calculated and maintained. +`GetMTPHealth` and `UpdatePoolHealth` ensure the health of MTPs and pools are calculated and maintained. ### Utility Functions diff --git a/x/perpetual/types/calc_take_amount.go b/x/perpetual/types/calc_take_amount.go index 41e96ef24..8c47bc6f7 100644 --- a/x/perpetual/types/calc_take_amount.go +++ b/x/perpetual/types/calc_take_amount.go @@ -6,7 +6,7 @@ import ( ) // CalcTakeAmount calculates the take amount in the custody asset based on the funding rate -func CalcTakeAmount(custodyAmount math.Int, custodyAsset string, fundingRate sdk.Dec) math.Int { +func CalcTakeAmount(custodyAmount math.Int, fundingRate sdk.Dec) math.Int { absoluteFundingRate := fundingRate.Abs() // Calculate the take amount diff --git a/x/perpetual/types/codec.go b/x/perpetual/types/codec.go index 68eb01f8e..7e02efe0e 100644 --- a/x/perpetual/types/codec.go +++ b/x/perpetual/types/codec.go @@ -19,6 +19,7 @@ func RegisterCodec(cdc *codec.LegacyAmino) { legacy.RegisterAminoMsg(cdc, &MsgWhitelist{}, "perpetual/MsgWhitelist") legacy.RegisterAminoMsg(cdc, &MsgDewhitelist{}, "perpetual/MsgDewhitelist") legacy.RegisterAminoMsg(cdc, &MsgAddCollateral{}, "perpetual/MsgAddCollateral") + legacy.RegisterAminoMsg(cdc, &MsgClosePositions{}, "perpetual/ClosePositions") legacy.RegisterAminoMsg(cdc, &MsgUpdateStopLoss{}, "perpetual/MsgUpdateStopLoss") // this line is used by starport scaffolding # 2 } @@ -33,6 +34,9 @@ func RegisterInterfaces(registry cdctypes.InterfaceRegistry) { &MsgAddCollateral{}, &MsgUpdateStopLoss{}, ) + registry.RegisterImplementations((*sdk.Msg)(nil), + &MsgClosePositions{}, + ) // this line is used by starport scaffolding # 3 msgservice.RegisterMsgServiceDesc(registry, &_Msg_serviceDesc) diff --git a/x/perpetual/types/events.go b/x/perpetual/types/events.go index fc6376c75..373e93f85 100644 --- a/x/perpetual/types/events.go +++ b/x/perpetual/types/events.go @@ -6,4 +6,5 @@ const ( EventForceClose = "perpetual/mtp_force_close" EventIncrementalPayFund = "perpetual/incremental_pay_fund" EventRepayFund = "perpetual/repay_fund" + EventClosePositions = "perpetual/close_positions" ) diff --git a/x/perpetual/types/expected_keepers.go b/x/perpetual/types/expected_keepers.go index e345e59ec..18473f1be 100644 --- a/x/perpetual/types/expected_keepers.go +++ b/x/perpetual/types/expected_keepers.go @@ -56,7 +56,7 @@ type OpenLongChecker interface { Borrow(ctx sdk.Context, collateralAmount math.Int, custodyAmount math.Int, mtp *MTP, ammPool *ammtypes.Pool, pool *Pool, eta sdk.Dec, baseCurrency string, isBroker bool) error UpdatePoolHealth(ctx sdk.Context, pool *Pool) error TakeInCustody(ctx sdk.Context, mtp MTP, pool *Pool) error - UpdateMTPHealth(ctx sdk.Context, mtp MTP, ammPool ammtypes.Pool, baseCurrency string) (sdk.Dec, error) + GetMTPHealth(ctx sdk.Context, mtp MTP, ammPool ammtypes.Pool, baseCurrency string) (sdk.Dec, error) GetSafetyFactor(ctx sdk.Context) sdk.Dec SetPool(ctx sdk.Context, pool Pool) CheckSameAssetPosition(ctx sdk.Context, msg *MsgOpen) *MTP @@ -76,7 +76,7 @@ type OpenShortChecker interface { Borrow(ctx sdk.Context, collateralAmount math.Int, custodyAmount math.Int, mtp *MTP, ammPool *ammtypes.Pool, pool *Pool, eta sdk.Dec, baseCurrency string, isBroker bool) error UpdatePoolHealth(ctx sdk.Context, pool *Pool) error TakeInCustody(ctx sdk.Context, mtp MTP, pool *Pool) error - UpdateMTPHealth(ctx sdk.Context, mtp MTP, ammPool ammtypes.Pool, baseCurrency string) (sdk.Dec, error) + GetMTPHealth(ctx sdk.Context, mtp MTP, ammPool ammtypes.Pool, baseCurrency string) (sdk.Dec, error) GetSafetyFactor(ctx sdk.Context) sdk.Dec SetPool(ctx sdk.Context, pool Pool) CheckSameAssetPosition(ctx sdk.Context, msg *MsgOpen) *MTP @@ -92,7 +92,7 @@ type CloseLongChecker interface { poolId uint64, ) (val Pool, found bool) GetAmmPool(ctx sdk.Context, poolId uint64, tradingAsset string) (ammtypes.Pool, error) - HandleBorrowInterest(ctx sdk.Context, mtp *MTP, pool *Pool, ammPool ammtypes.Pool) error + SettleBorrowInterest(ctx sdk.Context, mtp *MTP, pool *Pool, ammPool ammtypes.Pool) (math.Int, error) TakeOutCustody(ctx sdk.Context, mtp MTP, pool *Pool, amount math.Int) error EstimateAndRepay(ctx sdk.Context, mtp MTP, pool Pool, ammPool ammtypes.Pool, amount math.Int, baseCurrency string) (math.Int, error) } @@ -105,7 +105,7 @@ type CloseShortChecker interface { poolId uint64, ) (val Pool, found bool) GetAmmPool(ctx sdk.Context, poolId uint64, tradingAsset string) (ammtypes.Pool, error) - HandleBorrowInterest(ctx sdk.Context, mtp *MTP, pool *Pool, ammPool ammtypes.Pool) error + SettleBorrowInterest(ctx sdk.Context, mtp *MTP, pool *Pool, ammPool ammtypes.Pool) (math.Int, error) TakeOutCustody(ctx sdk.Context, mtp MTP, pool *Pool, amount math.Int) error EstimateAndRepay(ctx sdk.Context, mtp MTP, pool Pool, ammPool ammtypes.Pool, amount math.Int, baseCurrency string) (math.Int, error) } diff --git a/x/perpetual/types/keys.go b/x/perpetual/types/keys.go index 4914e52d3..87ef498cd 100644 --- a/x/perpetual/types/keys.go +++ b/x/perpetual/types/keys.go @@ -2,6 +2,7 @@ package types import ( "encoding/binary" + sdk "github.com/cosmos/cosmos-sdk/types" "github.com/cosmos/cosmos-sdk/types/address" ) @@ -38,6 +39,10 @@ var ( OpenMTPCountPrefix = []byte{0x04} WhitelistPrefix = []byte{0x05} PoolKeyPrefix = []byte{0x06} + + InterestRatePrefix = []byte{0x07} + FundingRatePrefix = []byte{0x08} + ToPayPrefix = []byte{0x09} ) func KeyPrefix(p string) []byte { @@ -96,3 +101,15 @@ func GetLegacyPoolKey(index uint64) []byte { key := KeyPrefix(LegacyPoolKeyPrefix) return append(key, legacyPoolKey(index)...) } + +func GetInterestRateKey(block uint64, pool uint64) []byte { + return append(GetUint64Bytes(block), GetUint64Bytes(pool)...) +} + +func GetFundingRateKey(block uint64, pool uint64) []byte { + return append(GetUint64Bytes(block), GetUint64Bytes(pool)...) +} + +func GetToPayKey(addr sdk.AccAddress, id uint64) []byte { + return append(ToPayPrefix, append(address.MustLengthPrefix(addr), sdk.Uint64ToBigEndian(id)...)...) +} diff --git a/x/perpetual/types/message_close_positions.go b/x/perpetual/types/message_close_positions.go new file mode 100644 index 000000000..02eff33cd --- /dev/null +++ b/x/perpetual/types/message_close_positions.go @@ -0,0 +1,47 @@ +package types + +import ( + sdk "github.com/cosmos/cosmos-sdk/types" + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" +) + +const TypeMsgClosePositions = "close_positions" + +var _ sdk.Msg = &MsgClosePositions{} + +func NewMsgClosePositions(creator string, liquidate []*PositionRequest, stopLoss []*PositionRequest) *MsgClosePositions { + return &MsgClosePositions{ + Creator: creator, + Liquidate: liquidate, + StopLoss: stopLoss, + } +} + +func (msg *MsgClosePositions) Route() string { + return RouterKey +} + +func (msg *MsgClosePositions) Type() string { + return TypeMsgClosePositions +} + +func (msg *MsgClosePositions) GetSigners() []sdk.AccAddress { + creator, err := sdk.AccAddressFromBech32(msg.Creator) + if err != nil { + panic(err) + } + return []sdk.AccAddress{creator} +} + +func (msg *MsgClosePositions) GetSignBytes() []byte { + bz := ModuleCdc.MustMarshalJSON(msg) + return sdk.MustSortJSON(bz) +} + +func (msg *MsgClosePositions) ValidateBasic() error { + _, err := sdk.AccAddressFromBech32(msg.Creator) + if err != nil { + return sdkerrors.Wrapf(sdkerrors.ErrInvalidAddress, "invalid creator address (%s)", err) + } + return nil +} diff --git a/x/perpetual/types/message_close_positions_test.go b/x/perpetual/types/message_close_positions_test.go new file mode 100644 index 000000000..43ae0c851 --- /dev/null +++ b/x/perpetual/types/message_close_positions_test.go @@ -0,0 +1,40 @@ +package types + +import ( + "testing" + + sdkerrors "github.com/cosmos/cosmos-sdk/types/errors" + "github.com/elys-network/elys/testutil/sample" + "github.com/stretchr/testify/require" +) + +func TestMsgClosePositions_ValidateBasic(t *testing.T) { + tests := []struct { + name string + msg MsgClosePositions + err error + }{ + { + name: "invalid address", + msg: MsgClosePositions{ + Creator: "invalid_address", + }, + err: sdkerrors.ErrInvalidAddress, + }, { + name: "valid address", + msg: MsgClosePositions{ + Creator: sample.AccAddress(), + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.msg.ValidateBasic() + if tt.err != nil { + require.ErrorIs(t, err, tt.err) + return + } + require.NoError(t, err) + }) + } +} diff --git a/x/perpetual/types/mocks/close_long_checker.go b/x/perpetual/types/mocks/close_long_checker.go index affa33eff..5419e7003 100644 --- a/x/perpetual/types/mocks/close_long_checker.go +++ b/x/perpetual/types/mocks/close_long_checker.go @@ -131,11 +131,11 @@ func (_m *CloseLongChecker) GetPool(ctx types.Context, poolId uint64) (perpetual } // HandleBorrowInterest provides a mock function with given fields: ctx, mtp, pool, ammPool -func (_m *CloseLongChecker) HandleBorrowInterest(ctx types.Context, mtp *perpetualtypes.MTP, pool *perpetualtypes.Pool, ammPool ammtypes.Pool) error { +func (_m *CloseLongChecker) SettleBorrowInterest(ctx types.Context, mtp *perpetualtypes.MTP, pool *perpetualtypes.Pool, ammPool ammtypes.Pool) (math.Int, error) { ret := _m.Called(ctx, mtp, pool, ammPool) if len(ret) == 0 { - panic("no return value specified for HandleBorrowInterest") + panic("no return value specified for SettleBorrowInterest") } var r0 error @@ -145,7 +145,7 @@ func (_m *CloseLongChecker) HandleBorrowInterest(ctx types.Context, mtp *perpetu r0 = ret.Error(0) } - return r0 + return types.ZeroInt(), r0 } // TakeOutCustody provides a mock function with given fields: ctx, mtp, pool, amount diff --git a/x/perpetual/types/mocks/close_short_checker.go b/x/perpetual/types/mocks/close_short_checker.go index 85f8d6e04..c3484a800 100644 --- a/x/perpetual/types/mocks/close_short_checker.go +++ b/x/perpetual/types/mocks/close_short_checker.go @@ -131,11 +131,11 @@ func (_m *CloseShortChecker) GetPool(ctx types.Context, poolId uint64) (perpetua } // HandleBorrowInterest provides a mock function with given fields: ctx, mtp, pool, ammPool -func (_m *CloseShortChecker) HandleBorrowInterest(ctx types.Context, mtp *perpetualtypes.MTP, pool *perpetualtypes.Pool, ammPool ammtypes.Pool) error { +func (_m *CloseShortChecker) SettleBorrowInterest(ctx types.Context, mtp *perpetualtypes.MTP, pool *perpetualtypes.Pool, ammPool ammtypes.Pool) (math.Int, error) { ret := _m.Called(ctx, mtp, pool, ammPool) if len(ret) == 0 { - panic("no return value specified for HandleBorrowInterest") + panic("no return value specified for SettleBorrowInterest") } var r0 error @@ -145,7 +145,7 @@ func (_m *CloseShortChecker) HandleBorrowInterest(ctx types.Context, mtp *perpet r0 = ret.Error(0) } - return r0 + return types.ZeroInt(), r0 } // TakeOutCustody provides a mock function with given fields: ctx, mtp, pool, amount diff --git a/x/perpetual/types/mocks/open_long_checker.go b/x/perpetual/types/mocks/open_long_checker.go index eb4c82502..e7ae9beee 100644 --- a/x/perpetual/types/mocks/open_long_checker.go +++ b/x/perpetual/types/mocks/open_long_checker.go @@ -677,8 +677,8 @@ func (_c *OpenLongChecker_TakeInCustody_Call) RunAndReturn(run func(types.Contex return _c } -// UpdateMTPHealth provides a mock function with given fields: ctx, mtp, ammPool, baseCurrency -func (_m *OpenLongChecker) UpdateMTPHealth(ctx types.Context, mtp perpetualtypes.MTP, ammPool ammtypes.Pool, baseCurrency string) (math.LegacyDec, error) { +// GetMTPHealth provides a mock function with given fields: ctx, mtp, ammPool, baseCurrency +func (_m *OpenLongChecker) GetMTPHealth(ctx types.Context, mtp perpetualtypes.MTP, ammPool ammtypes.Pool, baseCurrency string) (math.LegacyDec, error) { ret := _m.Called(ctx, mtp, ammPool, baseCurrency) var r0 math.LegacyDec @@ -701,33 +701,33 @@ func (_m *OpenLongChecker) UpdateMTPHealth(ctx types.Context, mtp perpetualtypes return r0, r1 } -// OpenLongChecker_UpdateMTPHealth_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateMTPHealth' -type OpenLongChecker_UpdateMTPHealth_Call struct { +// OpenLongChecker_GetMTPHealth_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetMTPHealth' +type OpenLongChecker_GetMTPHealth_Call struct { *mock.Call } -// UpdateMTPHealth is a helper method to define mock.On call +// GetMTPHealth is a helper method to define mock.On call // - ctx types.Context // - mtp perpetualtypes.MTP // - ammPool ammtypes.Pool // - baseCurrency string -func (_e *OpenLongChecker_Expecter) UpdateMTPHealth(ctx interface{}, mtp interface{}, ammPool interface{}, baseCurrency interface{}) *OpenLongChecker_UpdateMTPHealth_Call { - return &OpenLongChecker_UpdateMTPHealth_Call{Call: _e.mock.On("UpdateMTPHealth", ctx, mtp, ammPool, baseCurrency)} +func (_e *OpenLongChecker_Expecter) GetMTPHealth(ctx interface{}, mtp interface{}, ammPool interface{}, baseCurrency interface{}) *OpenLongChecker_GetMTPHealth_Call { + return &OpenLongChecker_GetMTPHealth_Call{Call: _e.mock.On("GetMTPHealth", ctx, mtp, ammPool, baseCurrency)} } -func (_c *OpenLongChecker_UpdateMTPHealth_Call) Run(run func(ctx types.Context, mtp perpetualtypes.MTP, ammPool ammtypes.Pool, baseCurrency string)) *OpenLongChecker_UpdateMTPHealth_Call { +func (_c *OpenLongChecker_GetMTPHealth_Call) Run(run func(ctx types.Context, mtp perpetualtypes.MTP, ammPool ammtypes.Pool, baseCurrency string)) *OpenLongChecker_GetMTPHealth_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(types.Context), args[1].(perpetualtypes.MTP), args[2].(ammtypes.Pool), args[3].(string)) }) return _c } -func (_c *OpenLongChecker_UpdateMTPHealth_Call) Return(_a0 math.LegacyDec, _a1 error) *OpenLongChecker_UpdateMTPHealth_Call { +func (_c *OpenLongChecker_GetMTPHealth_Call) Return(_a0 math.LegacyDec, _a1 error) *OpenLongChecker_GetMTPHealth_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *OpenLongChecker_UpdateMTPHealth_Call) RunAndReturn(run func(types.Context, perpetualtypes.MTP, ammtypes.Pool, string) (math.LegacyDec, error)) *OpenLongChecker_UpdateMTPHealth_Call { +func (_c *OpenLongChecker_GetMTPHealth_Call) RunAndReturn(run func(types.Context, perpetualtypes.MTP, ammtypes.Pool, string) (math.LegacyDec, error)) *OpenLongChecker_GetMTPHealth_Call { _c.Call.Return(run) return _c } diff --git a/x/perpetual/types/mocks/open_short_checker.go b/x/perpetual/types/mocks/open_short_checker.go index 70b41da38..3eff99c41 100644 --- a/x/perpetual/types/mocks/open_short_checker.go +++ b/x/perpetual/types/mocks/open_short_checker.go @@ -677,8 +677,8 @@ func (_c *OpenShortChecker_TakeInCustody_Call) RunAndReturn(run func(types.Conte return _c } -// UpdateMTPHealth provides a mock function with given fields: ctx, mtp, ammPool, baseCurrency -func (_m *OpenShortChecker) UpdateMTPHealth(ctx types.Context, mtp perpetualtypes.MTP, ammPool ammtypes.Pool, baseCurrency string) (math.LegacyDec, error) { +// GetMTPHealth provides a mock function with given fields: ctx, mtp, ammPool, baseCurrency +func (_m *OpenShortChecker) GetMTPHealth(ctx types.Context, mtp perpetualtypes.MTP, ammPool ammtypes.Pool, baseCurrency string) (math.LegacyDec, error) { ret := _m.Called(ctx, mtp, ammPool, baseCurrency) var r0 math.LegacyDec @@ -701,33 +701,33 @@ func (_m *OpenShortChecker) UpdateMTPHealth(ctx types.Context, mtp perpetualtype return r0, r1 } -// OpenShortChecker_UpdateMTPHealth_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdateMTPHealth' -type OpenShortChecker_UpdateMTPHealth_Call struct { +// OpenShortChecker_GetMTPHealth_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetMTPHealth' +type OpenShortChecker_GetMTPHealth_Call struct { *mock.Call } -// UpdateMTPHealth is a helper method to define mock.On call +// GetMTPHealth is a helper method to define mock.On call // - ctx types.Context // - mtp perpetualtypes.MTP // - ammPool ammtypes.Pool // - baseCurrency string -func (_e *OpenShortChecker_Expecter) UpdateMTPHealth(ctx interface{}, mtp interface{}, ammPool interface{}, baseCurrency interface{}) *OpenShortChecker_UpdateMTPHealth_Call { - return &OpenShortChecker_UpdateMTPHealth_Call{Call: _e.mock.On("UpdateMTPHealth", ctx, mtp, ammPool, baseCurrency)} +func (_e *OpenShortChecker_Expecter) GetMTPHealth(ctx interface{}, mtp interface{}, ammPool interface{}, baseCurrency interface{}) *OpenShortChecker_GetMTPHealth_Call { + return &OpenShortChecker_GetMTPHealth_Call{Call: _e.mock.On("GetMTPHealth", ctx, mtp, ammPool, baseCurrency)} } -func (_c *OpenShortChecker_UpdateMTPHealth_Call) Run(run func(ctx types.Context, mtp perpetualtypes.MTP, ammPool ammtypes.Pool, baseCurrency string)) *OpenShortChecker_UpdateMTPHealth_Call { +func (_c *OpenShortChecker_GetMTPHealth_Call) Run(run func(ctx types.Context, mtp perpetualtypes.MTP, ammPool ammtypes.Pool, baseCurrency string)) *OpenShortChecker_GetMTPHealth_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(types.Context), args[1].(perpetualtypes.MTP), args[2].(ammtypes.Pool), args[3].(string)) }) return _c } -func (_c *OpenShortChecker_UpdateMTPHealth_Call) Return(_a0 math.LegacyDec, _a1 error) *OpenShortChecker_UpdateMTPHealth_Call { +func (_c *OpenShortChecker_GetMTPHealth_Call) Return(_a0 math.LegacyDec, _a1 error) *OpenShortChecker_GetMTPHealth_Call { _c.Call.Return(_a0, _a1) return _c } -func (_c *OpenShortChecker_UpdateMTPHealth_Call) RunAndReturn(run func(types.Context, perpetualtypes.MTP, ammtypes.Pool, string) (math.LegacyDec, error)) *OpenShortChecker_UpdateMTPHealth_Call { +func (_c *OpenShortChecker_GetMTPHealth_Call) RunAndReturn(run func(types.Context, perpetualtypes.MTP, ammtypes.Pool, string) (math.LegacyDec, error)) *OpenShortChecker_GetMTPHealth_Call { _c.Call.Return(run) return _c } diff --git a/x/perpetual/types/pool.go b/x/perpetual/types/pool.go index fe08daf64..cd3e0b42a 100644 --- a/x/perpetual/types/pool.go +++ b/x/perpetual/types/pool.go @@ -14,7 +14,7 @@ func NewPool(poolId uint64) Pool { Health: sdk.NewDec(100), Enabled: true, Closed: false, - BorrowInterestRate: sdk.NewDecFromIntWithPrec(sdk.NewInt(1), 1), + BorrowInterestRate: sdk.MustNewDecFromStr("0.000000000000000001"), PoolAssetsLong: []PoolAsset{}, PoolAssetsShort: []PoolAsset{}, LastHeightBorrowInterestRateComputed: 0, diff --git a/x/perpetual/types/tx.pb.go b/x/perpetual/types/tx.pb.go index 8fb18e196..999b20493 100644 --- a/x/perpetual/types/tx.pb.go +++ b/x/perpetual/types/tx.pb.go @@ -799,6 +799,102 @@ func (m *MsgBrokerAddCollateral) GetOwner() string { return "" } +type MsgClosePositions struct { + Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` + Liquidate []*PositionRequest `protobuf:"bytes,2,rep,name=liquidate,proto3" json:"liquidate,omitempty"` + StopLoss []*PositionRequest `protobuf:"bytes,3,rep,name=stop_loss,json=stopLoss,proto3" json:"stop_loss,omitempty"` +} + +func (m *MsgClosePositions) Reset() { *m = MsgClosePositions{} } +func (m *MsgClosePositions) String() string { return proto.CompactTextString(m) } +func (*MsgClosePositions) ProtoMessage() {} +func (*MsgClosePositions) Descriptor() ([]byte, []int) { + return fileDescriptor_5e879ed5011cdd71, []int{15} +} +func (m *MsgClosePositions) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgClosePositions) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgClosePositions.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgClosePositions) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgClosePositions.Merge(m, src) +} +func (m *MsgClosePositions) XXX_Size() int { + return m.Size() +} +func (m *MsgClosePositions) XXX_DiscardUnknown() { + xxx_messageInfo_MsgClosePositions.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgClosePositions proto.InternalMessageInfo + +func (m *MsgClosePositions) GetCreator() string { + if m != nil { + return m.Creator + } + return "" +} + +func (m *MsgClosePositions) GetLiquidate() []*PositionRequest { + if m != nil { + return m.Liquidate + } + return nil +} + +func (m *MsgClosePositions) GetStopLoss() []*PositionRequest { + if m != nil { + return m.StopLoss + } + return nil +} + +type MsgClosePositionsResponse struct { +} + +func (m *MsgClosePositionsResponse) Reset() { *m = MsgClosePositionsResponse{} } +func (m *MsgClosePositionsResponse) String() string { return proto.CompactTextString(m) } +func (*MsgClosePositionsResponse) ProtoMessage() {} +func (*MsgClosePositionsResponse) Descriptor() ([]byte, []int) { + return fileDescriptor_5e879ed5011cdd71, []int{16} +} +func (m *MsgClosePositionsResponse) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *MsgClosePositionsResponse) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_MsgClosePositionsResponse.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *MsgClosePositionsResponse) XXX_Merge(src proto.Message) { + xxx_messageInfo_MsgClosePositionsResponse.Merge(m, src) +} +func (m *MsgClosePositionsResponse) XXX_Size() int { + return m.Size() +} +func (m *MsgClosePositionsResponse) XXX_DiscardUnknown() { + xxx_messageInfo_MsgClosePositionsResponse.DiscardUnknown(m) +} + +var xxx_messageInfo_MsgClosePositionsResponse proto.InternalMessageInfo + type MsgUpdateStopLoss struct { Creator string `protobuf:"bytes,1,opt,name=creator,proto3" json:"creator,omitempty"` Id uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` @@ -809,7 +905,7 @@ func (m *MsgUpdateStopLoss) Reset() { *m = MsgUpdateStopLoss{} } func (m *MsgUpdateStopLoss) String() string { return proto.CompactTextString(m) } func (*MsgUpdateStopLoss) ProtoMessage() {} func (*MsgUpdateStopLoss) Descriptor() ([]byte, []int) { - return fileDescriptor_5e879ed5011cdd71, []int{15} + return fileDescriptor_5e879ed5011cdd71, []int{17} } func (m *MsgUpdateStopLoss) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -859,7 +955,7 @@ func (m *MsgUpdateStopLossResponse) Reset() { *m = MsgUpdateStopLossResp func (m *MsgUpdateStopLossResponse) String() string { return proto.CompactTextString(m) } func (*MsgUpdateStopLossResponse) ProtoMessage() {} func (*MsgUpdateStopLossResponse) Descriptor() ([]byte, []int) { - return fileDescriptor_5e879ed5011cdd71, []int{16} + return fileDescriptor_5e879ed5011cdd71, []int{18} } func (m *MsgUpdateStopLossResponse) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -904,6 +1000,8 @@ func init() { proto.RegisterType((*MsgAddCollateral)(nil), "elys.perpetual.MsgAddCollateral") proto.RegisterType((*MsgAddCollateralResponse)(nil), "elys.perpetual.MsgAddCollateralResponse") proto.RegisterType((*MsgBrokerAddCollateral)(nil), "elys.perpetual.MsgBrokerAddCollateral") + proto.RegisterType((*MsgClosePositions)(nil), "elys.perpetual.MsgClosePositions") + proto.RegisterType((*MsgClosePositionsResponse)(nil), "elys.perpetual.MsgClosePositionsResponse") proto.RegisterType((*MsgUpdateStopLoss)(nil), "elys.perpetual.MsgUpdateStopLoss") proto.RegisterType((*MsgUpdateStopLossResponse)(nil), "elys.perpetual.MsgUpdateStopLossResponse") } @@ -911,62 +1009,66 @@ func init() { func init() { proto.RegisterFile("elys/perpetual/tx.proto", fileDescriptor_5e879ed5011cdd71) } var fileDescriptor_5e879ed5011cdd71 = []byte{ - // 867 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x57, 0xcf, 0x6f, 0xe3, 0x44, - 0x14, 0xae, 0xf3, 0xab, 0xed, 0x6b, 0x9b, 0xb2, 0xde, 0xaa, 0x75, 0xbd, 0x8b, 0xdb, 0x35, 0xa8, - 0x94, 0xc3, 0xda, 0xda, 0xc0, 0x1d, 0x9a, 0x54, 0x08, 0xd0, 0x46, 0x1b, 0x19, 0x2d, 0xa0, 0x45, - 0x10, 0x4d, 0xe2, 0xc1, 0x35, 0x71, 0x3c, 0xd6, 0xcc, 0x64, 0xb3, 0x95, 0xb8, 0xc1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x28, 0xef, 0xcd, 0x35, 0x2a, 0x0d, 0xd1, 0xdf, 0x5d, - 0x18, 0x92, 0xf2, 0x37, 0x3f, 0x7e, 0x7e, 0x61, 0x28, 0x2f, 0x2e, 0x0c, 0xe5, 0xaf, 0x0b, 0x43, - 0xf9, 0xe9, 0xd2, 0x58, 0x79, 0x71, 0x69, 0xac, 0xfc, 0x7e, 0x69, 0xac, 0x3c, 0xb1, 0x72, 0xb3, - 0x1b, 0xd3, 0xdd, 0x0f, 0x31, 0x1f, 0x13, 0x3a, 0x10, 0x0f, 0xf6, 0xb3, 0xd9, 0x1f, 0x11, 0xbd, - 0x9a, 0xf8, 0x15, 0xf1, 0xde, 0xdf, 0x01, 0x00, 0x00, 0xff, 0xff, 0xd6, 0xdb, 0x36, 0xd1, 0xdf, - 0x0c, 0x00, 0x00, + // 939 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x57, 0xcf, 0x6f, 0xdc, 0x44, + 0x14, 0x8e, 0xf7, 0x47, 0x92, 0x7d, 0x9b, 0x6c, 0xa8, 0x1b, 0x25, 0x8e, 0x5b, 0x36, 0x1b, 0x83, + 0xc2, 0x72, 0xa8, 0xad, 0x2e, 0x1c, 0x41, 0x90, 0x1f, 0x42, 0x80, 0xba, 0x6a, 0x64, 0x54, 0x40, + 0x45, 0xb0, 0x72, 0xd6, 0x83, 0x63, 0xe2, 0x78, 0xdc, 0x99, 0xd9, 0xa6, 0x91, 0xb8, 0xc1, 0x1f, + 0xc0, 0x91, 0x23, 0x67, 0xae, 0xfc, 0x01, 0x5c, 0x7b, 0xec, 0x11, 0x81, 0x54, 0xa1, 0xe4, 0x1f, + 0x41, 0x1e, 0x8f, 0x67, 0xbd, 0xae, 0x9d, 0x2d, 0x0b, 0x51, 0x2e, 0x3d, 0xed, 0xda, 0xdf, 0x7b, + 0xdf, 0xfb, 0x66, 0xde, 0xbc, 0x6f, 0x64,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0x9d, + 0x16, 0x21, 0xc9, 0x3d, 0xb8, 0x59, 0x64, 0x4c, 0xdb, 0xa5, 0x7d, 0x9b, 0xb5, 0xd0, 0x37, 0xd0, + 0xca, 0x0d, 0xe5, 0x56, 0x69, 0xa3, 0xd2, 0x10, 0xfd, 0xed, 0xa9, 0x21, 0x59, 0xfe, 0x9c, 0x7d, + 0x6d, 0x95, 0x9d, 0x2d, 0x19, 0x52, 0xc8, 0x5f, 0x6c, 0x2c, 0xbb, 0x1f, 0x3f, 0x3d, 0x6f, 0x2b, + 0xcf, 0xce, 0xdb, 0xca, 0xdf, 0xe7, 0x6d, 0xe5, 0xa7, 0x8b, 0xf6, 0xdc, 0xb3, 0x8b, 0xf6, 0xdc, + 0x1f, 0x17, 0xed, 0xb9, 0x87, 0x66, 0xc6, 0x1b, 0x62, 0xba, 0x3b, 0x21, 0x62, 0xa7, 0x98, 0x1c, + 0xf3, 0x07, 0xeb, 0x49, 0xfe, 0x73, 0xeb, 0x70, 0x9e, 0x7f, 0x6f, 0xbd, 0xf3, 0x4f, 0x00, 0x00, + 0x00, 0xff, 0xff, 0xef, 0xd3, 0x8b, 0x69, 0x09, 0x0e, 0x00, 0x00, } // Reference imports to suppress errors if they are not otherwise used. @@ -991,6 +1093,7 @@ type MsgClient interface { AddCollateral(ctx context.Context, in *MsgAddCollateral, opts ...grpc.CallOption) (*MsgAddCollateralResponse, error) BrokerAddCollateral(ctx context.Context, in *MsgBrokerAddCollateral, opts ...grpc.CallOption) (*MsgAddCollateralResponse, error) UpdateStopLoss(ctx context.Context, in *MsgUpdateStopLoss, opts ...grpc.CallOption) (*MsgUpdateStopLossResponse, error) + ClosePositions(ctx context.Context, in *MsgClosePositions, opts ...grpc.CallOption) (*MsgClosePositionsResponse, error) } type msgClient struct { @@ -1091,6 +1194,15 @@ func (c *msgClient) UpdateStopLoss(ctx context.Context, in *MsgUpdateStopLoss, o return out, nil } +func (c *msgClient) ClosePositions(ctx context.Context, in *MsgClosePositions, opts ...grpc.CallOption) (*MsgClosePositionsResponse, error) { + out := new(MsgClosePositionsResponse) + err := c.cc.Invoke(ctx, "/elys.perpetual.Msg/ClosePositions", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + // MsgServer is the server API for Msg service. type MsgServer interface { Open(context.Context, *MsgOpen) (*MsgOpenResponse, error) @@ -1103,6 +1215,7 @@ type MsgServer interface { AddCollateral(context.Context, *MsgAddCollateral) (*MsgAddCollateralResponse, error) BrokerAddCollateral(context.Context, *MsgBrokerAddCollateral) (*MsgAddCollateralResponse, error) UpdateStopLoss(context.Context, *MsgUpdateStopLoss) (*MsgUpdateStopLossResponse, error) + ClosePositions(context.Context, *MsgClosePositions) (*MsgClosePositionsResponse, error) } // UnimplementedMsgServer can be embedded to have forward compatible implementations. @@ -1139,6 +1252,9 @@ func (*UnimplementedMsgServer) BrokerAddCollateral(ctx context.Context, req *Msg func (*UnimplementedMsgServer) UpdateStopLoss(ctx context.Context, req *MsgUpdateStopLoss) (*MsgUpdateStopLossResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateStopLoss not implemented") } +func (*UnimplementedMsgServer) ClosePositions(ctx context.Context, req *MsgClosePositions) (*MsgClosePositionsResponse, error) { + return nil, status.Errorf(codes.Unimplemented, "method ClosePositions not implemented") +} func RegisterMsgServer(s grpc1.Server, srv MsgServer) { s.RegisterService(&_Msg_serviceDesc, srv) @@ -1324,6 +1440,24 @@ func _Msg_UpdateStopLoss_Handler(srv interface{}, ctx context.Context, dec func( return interceptor(ctx, in, info, handler) } +func _Msg_ClosePositions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(MsgClosePositions) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MsgServer).ClosePositions(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/elys.perpetual.Msg/ClosePositions", + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MsgServer).ClosePositions(ctx, req.(*MsgClosePositions)) + } + return interceptor(ctx, in, info, handler) +} + var _Msg_serviceDesc = grpc.ServiceDesc{ ServiceName: "elys.perpetual.Msg", HandlerType: (*MsgServer)(nil), @@ -1368,6 +1502,10 @@ var _Msg_serviceDesc = grpc.ServiceDesc{ MethodName: "UpdateStopLoss", Handler: _Msg_UpdateStopLoss_Handler, }, + { + MethodName: "ClosePositions", + Handler: _Msg_ClosePositions_Handler, + }, }, Streams: []grpc.StreamDesc{}, Metadata: "elys/perpetual/tx.proto", @@ -2016,6 +2154,87 @@ func (m *MsgBrokerAddCollateral) MarshalToSizedBuffer(dAtA []byte) (int, error) return len(dAtA) - i, nil } +func (m *MsgClosePositions) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgClosePositions) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgClosePositions) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if len(m.StopLoss) > 0 { + for iNdEx := len(m.StopLoss) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.StopLoss[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + } + } + if len(m.Liquidate) > 0 { + for iNdEx := len(m.Liquidate) - 1; iNdEx >= 0; iNdEx-- { + { + size, err := m.Liquidate[iNdEx].MarshalToSizedBuffer(dAtA[:i]) + if err != nil { + return 0, err + } + i -= size + i = encodeVarintTx(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x12 + } + } + if len(m.Creator) > 0 { + i -= len(m.Creator) + copy(dAtA[i:], m.Creator) + i = encodeVarintTx(dAtA, i, uint64(len(m.Creator))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + +func (m *MsgClosePositionsResponse) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *MsgClosePositionsResponse) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *MsgClosePositionsResponse) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + return len(dAtA) - i, nil +} + func (m *MsgUpdateStopLoss) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -2348,6 +2567,40 @@ func (m *MsgBrokerAddCollateral) Size() (n int) { return n } +func (m *MsgClosePositions) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Creator) + if l > 0 { + n += 1 + l + sovTx(uint64(l)) + } + if len(m.Liquidate) > 0 { + for _, e := range m.Liquidate { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + if len(m.StopLoss) > 0 { + for _, e := range m.StopLoss { + l = e.Size() + n += 1 + l + sovTx(uint64(l)) + } + } + return n +} + +func (m *MsgClosePositionsResponse) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + return n +} + func (m *MsgUpdateStopLoss) Size() (n int) { if m == nil { return 0 @@ -4271,6 +4524,206 @@ func (m *MsgBrokerAddCollateral) Unmarshal(dAtA []byte) error { } return nil } +func (m *MsgClosePositions) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgClosePositions: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgClosePositions: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Creator", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Creator = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Liquidate", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Liquidate = append(m.Liquidate, &PositionRequest{}) + if err := m.Liquidate[len(m.Liquidate)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field StopLoss", wireType) + } + var msglen int + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + msglen |= int(b&0x7F) << shift + if b < 0x80 { + break + } + } + if msglen < 0 { + return ErrInvalidLengthTx + } + postIndex := iNdEx + msglen + if postIndex < 0 { + return ErrInvalidLengthTx + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.StopLoss = append(m.StopLoss, &PositionRequest{}) + if err := m.StopLoss[len(m.StopLoss)-1].Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *MsgClosePositionsResponse) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTx + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: MsgClosePositionsResponse: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: MsgClosePositionsResponse: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + default: + iNdEx = preIndex + skippy, err := skipTx(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTx + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} func (m *MsgUpdateStopLoss) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 diff --git a/x/perpetual/types/types.pb.go b/x/perpetual/types/types.pb.go index 7e0064b8b..5c0e59094 100644 --- a/x/perpetual/types/types.pb.go +++ b/x/perpetual/types/types.pb.go @@ -52,7 +52,7 @@ func (Position) EnumDescriptor() ([]byte, []int) { return fileDescriptor_137aedba6573a752, []int{0} } -type MTP struct { +type LegacyMTP struct { Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` CollateralAsset string `protobuf:"bytes,2,opt,name=collateral_asset,json=collateralAsset,proto3" json:"collateral_asset,omitempty"` TradingAsset string `protobuf:"bytes,3,opt,name=trading_asset,json=tradingAsset,proto3" json:"trading_asset,omitempty"` @@ -82,21 +82,20 @@ type MTP struct { FundingFeeReceivedCollateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,25,opt,name=funding_fee_received_collateral,json=fundingFeeReceivedCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_fee_received_collateral"` FundingFeeReceivedCustody github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,26,opt,name=funding_fee_received_custody,json=fundingFeeReceivedCustody,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_fee_received_custody"` OpenPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,27,opt,name=open_price,json=openPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"open_price"` - StopLossPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,28,opt,name=stop_loss_price,json=stopLossPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"stop_loss_price"` } -func (m *MTP) Reset() { *m = MTP{} } -func (m *MTP) String() string { return proto.CompactTextString(m) } -func (*MTP) ProtoMessage() {} -func (*MTP) Descriptor() ([]byte, []int) { +func (m *LegacyMTP) Reset() { *m = LegacyMTP{} } +func (m *LegacyMTP) String() string { return proto.CompactTextString(m) } +func (*LegacyMTP) ProtoMessage() {} +func (*LegacyMTP) Descriptor() ([]byte, []int) { return fileDescriptor_137aedba6573a752, []int{0} } -func (m *MTP) XXX_Unmarshal(b []byte) error { +func (m *LegacyMTP) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *MTP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *LegacyMTP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_MTP.Marshal(b, m, deterministic) + return xxx_messageInfo_LegacyMTP.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -106,75 +105,75 @@ func (m *MTP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return b[:n], nil } } -func (m *MTP) XXX_Merge(src proto.Message) { - xxx_messageInfo_MTP.Merge(m, src) +func (m *LegacyMTP) XXX_Merge(src proto.Message) { + xxx_messageInfo_LegacyMTP.Merge(m, src) } -func (m *MTP) XXX_Size() int { +func (m *LegacyMTP) XXX_Size() int { return m.Size() } -func (m *MTP) XXX_DiscardUnknown() { - xxx_messageInfo_MTP.DiscardUnknown(m) +func (m *LegacyMTP) XXX_DiscardUnknown() { + xxx_messageInfo_LegacyMTP.DiscardUnknown(m) } -var xxx_messageInfo_MTP proto.InternalMessageInfo +var xxx_messageInfo_LegacyMTP proto.InternalMessageInfo -func (m *MTP) GetAddress() string { +func (m *LegacyMTP) GetAddress() string { if m != nil { return m.Address } return "" } -func (m *MTP) GetCollateralAsset() string { +func (m *LegacyMTP) GetCollateralAsset() string { if m != nil { return m.CollateralAsset } return "" } -func (m *MTP) GetTradingAsset() string { +func (m *LegacyMTP) GetTradingAsset() string { if m != nil { return m.TradingAsset } return "" } -func (m *MTP) GetLiabilitiesAsset() string { +func (m *LegacyMTP) GetLiabilitiesAsset() string { if m != nil { return m.LiabilitiesAsset } return "" } -func (m *MTP) GetCustodyAsset() string { +func (m *LegacyMTP) GetCustodyAsset() string { if m != nil { return m.CustodyAsset } return "" } -func (m *MTP) GetPosition() Position { +func (m *LegacyMTP) GetPosition() Position { if m != nil { return m.Position } return Position_UNSPECIFIED } -func (m *MTP) GetId() uint64 { +func (m *LegacyMTP) GetId() uint64 { if m != nil { return m.Id } return 0 } -func (m *MTP) GetAmmPoolId() uint64 { +func (m *LegacyMTP) GetAmmPoolId() uint64 { if m != nil { return m.AmmPoolId } return 0 } -type LegacyMTP struct { +type MTP struct { Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` CollateralAsset string `protobuf:"bytes,2,opt,name=collateral_asset,json=collateralAsset,proto3" json:"collateral_asset,omitempty"` TradingAsset string `protobuf:"bytes,3,opt,name=trading_asset,json=tradingAsset,proto3" json:"trading_asset,omitempty"` @@ -204,20 +203,25 @@ type LegacyMTP struct { FundingFeeReceivedCollateral github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,25,opt,name=funding_fee_received_collateral,json=fundingFeeReceivedCollateral,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_fee_received_collateral"` FundingFeeReceivedCustody github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,26,opt,name=funding_fee_received_custody,json=fundingFeeReceivedCustody,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_fee_received_custody"` OpenPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,27,opt,name=open_price,json=openPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"open_price"` + StopLossPrice github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,28,opt,name=stop_loss_price,json=stopLossPrice,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"stop_loss_price"` + LastInterestCalcTime uint64 `protobuf:"varint,29,opt,name=last_interest_calc_time,json=lastInterestCalcTime,proto3" json:"last_interest_calc_time,omitempty"` + LastInterestCalcBlock uint64 `protobuf:"varint,30,opt,name=last_interest_calc_block,json=lastInterestCalcBlock,proto3" json:"last_interest_calc_block,omitempty"` + LastFundingCalcTime uint64 `protobuf:"varint,31,opt,name=last_funding_calc_time,json=lastFundingCalcTime,proto3" json:"last_funding_calc_time,omitempty"` + LastFundingCalcBlock uint64 `protobuf:"varint,32,opt,name=last_funding_calc_block,json=lastFundingCalcBlock,proto3" json:"last_funding_calc_block,omitempty"` } -func (m *LegacyMTP) Reset() { *m = LegacyMTP{} } -func (m *LegacyMTP) String() string { return proto.CompactTextString(m) } -func (*LegacyMTP) ProtoMessage() {} -func (*LegacyMTP) Descriptor() ([]byte, []int) { +func (m *MTP) Reset() { *m = MTP{} } +func (m *MTP) String() string { return proto.CompactTextString(m) } +func (*MTP) ProtoMessage() {} +func (*MTP) Descriptor() ([]byte, []int) { return fileDescriptor_137aedba6573a752, []int{1} } -func (m *LegacyMTP) XXX_Unmarshal(b []byte) error { +func (m *MTP) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) } -func (m *LegacyMTP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { +func (m *MTP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { if deterministic { - return xxx_messageInfo_LegacyMTP.Marshal(b, m, deterministic) + return xxx_messageInfo_MTP.Marshal(b, m, deterministic) } else { b = b[:cap(b)] n, err := m.MarshalToSizedBuffer(b) @@ -227,74 +231,257 @@ func (m *LegacyMTP) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { return b[:n], nil } } -func (m *LegacyMTP) XXX_Merge(src proto.Message) { - xxx_messageInfo_LegacyMTP.Merge(m, src) +func (m *MTP) XXX_Merge(src proto.Message) { + xxx_messageInfo_MTP.Merge(m, src) } -func (m *LegacyMTP) XXX_Size() int { +func (m *MTP) XXX_Size() int { return m.Size() } -func (m *LegacyMTP) XXX_DiscardUnknown() { - xxx_messageInfo_LegacyMTP.DiscardUnknown(m) +func (m *MTP) XXX_DiscardUnknown() { + xxx_messageInfo_MTP.DiscardUnknown(m) } -var xxx_messageInfo_LegacyMTP proto.InternalMessageInfo +var xxx_messageInfo_MTP proto.InternalMessageInfo -func (m *LegacyMTP) GetAddress() string { +func (m *MTP) GetAddress() string { if m != nil { return m.Address } return "" } -func (m *LegacyMTP) GetCollateralAsset() string { +func (m *MTP) GetCollateralAsset() string { if m != nil { return m.CollateralAsset } return "" } -func (m *LegacyMTP) GetTradingAsset() string { +func (m *MTP) GetTradingAsset() string { if m != nil { return m.TradingAsset } return "" } -func (m *LegacyMTP) GetLiabilitiesAsset() string { +func (m *MTP) GetLiabilitiesAsset() string { if m != nil { return m.LiabilitiesAsset } return "" } -func (m *LegacyMTP) GetCustodyAsset() string { +func (m *MTP) GetCustodyAsset() string { if m != nil { return m.CustodyAsset } return "" } -func (m *LegacyMTP) GetPosition() Position { +func (m *MTP) GetPosition() Position { if m != nil { return m.Position } return Position_UNSPECIFIED } -func (m *LegacyMTP) GetId() uint64 { +func (m *MTP) GetId() uint64 { if m != nil { return m.Id } return 0 } -func (m *LegacyMTP) GetAmmPoolId() uint64 { +func (m *MTP) GetAmmPoolId() uint64 { if m != nil { return m.AmmPoolId } return 0 } +func (m *MTP) GetLastInterestCalcTime() uint64 { + if m != nil { + return m.LastInterestCalcTime + } + return 0 +} + +func (m *MTP) GetLastInterestCalcBlock() uint64 { + if m != nil { + return m.LastInterestCalcBlock + } + return 0 +} + +func (m *MTP) GetLastFundingCalcTime() uint64 { + if m != nil { + return m.LastFundingCalcTime + } + return 0 +} + +func (m *MTP) GetLastFundingCalcBlock() uint64 { + if m != nil { + return m.LastFundingCalcBlock + } + return 0 +} + +type InterestBlock struct { + InterestRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=interest_rate,json=interestRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"interest_rate"` + BlockHeight int64 `protobuf:"varint,2,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` +} + +func (m *InterestBlock) Reset() { *m = InterestBlock{} } +func (m *InterestBlock) String() string { return proto.CompactTextString(m) } +func (*InterestBlock) ProtoMessage() {} +func (*InterestBlock) Descriptor() ([]byte, []int) { + return fileDescriptor_137aedba6573a752, []int{2} +} +func (m *InterestBlock) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *InterestBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_InterestBlock.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *InterestBlock) XXX_Merge(src proto.Message) { + xxx_messageInfo_InterestBlock.Merge(m, src) +} +func (m *InterestBlock) XXX_Size() int { + return m.Size() +} +func (m *InterestBlock) XXX_DiscardUnknown() { + xxx_messageInfo_InterestBlock.DiscardUnknown(m) +} + +var xxx_messageInfo_InterestBlock proto.InternalMessageInfo + +func (m *InterestBlock) GetBlockHeight() int64 { + if m != nil { + return m.BlockHeight + } + return 0 +} + +type FundingRateBlock struct { + FundingRate github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,1,opt,name=funding_rate,json=fundingRate,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_rate"` + BlockHeight int64 `protobuf:"varint,2,opt,name=block_height,json=blockHeight,proto3" json:"block_height,omitempty"` + FundingAmountShort github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,3,opt,name=funding_amount_short,json=fundingAmountShort,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_amount_short"` + FundingAmountLong github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,4,opt,name=funding_amount_long,json=fundingAmountLong,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"funding_amount_long"` + FundingRateLong github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,5,opt,name=funding_rate_long,json=fundingRateLong,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_rate_long"` + FundingRateShort github_com_cosmos_cosmos_sdk_types.Dec `protobuf:"bytes,6,opt,name=funding_rate_short,json=fundingRateShort,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Dec" json:"funding_rate_short"` +} + +func (m *FundingRateBlock) Reset() { *m = FundingRateBlock{} } +func (m *FundingRateBlock) String() string { return proto.CompactTextString(m) } +func (*FundingRateBlock) ProtoMessage() {} +func (*FundingRateBlock) Descriptor() ([]byte, []int) { + return fileDescriptor_137aedba6573a752, []int{3} +} +func (m *FundingRateBlock) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *FundingRateBlock) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_FundingRateBlock.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *FundingRateBlock) XXX_Merge(src proto.Message) { + xxx_messageInfo_FundingRateBlock.Merge(m, src) +} +func (m *FundingRateBlock) XXX_Size() int { + return m.Size() +} +func (m *FundingRateBlock) XXX_DiscardUnknown() { + xxx_messageInfo_FundingRateBlock.DiscardUnknown(m) +} + +var xxx_messageInfo_FundingRateBlock proto.InternalMessageInfo + +func (m *FundingRateBlock) GetBlockHeight() int64 { + if m != nil { + return m.BlockHeight + } + return 0 +} + +type ToPay struct { + AssetBalance github_com_cosmos_cosmos_sdk_types.Int `protobuf:"bytes,1,opt,name=asset_balance,json=assetBalance,proto3,customtype=github.com/cosmos/cosmos-sdk/types.Int" json:"asset_balance"` + AssetDenom string `protobuf:"bytes,2,opt,name=asset_denom,json=assetDenom,proto3" json:"asset_denom,omitempty"` + Address string `protobuf:"bytes,3,opt,name=address,proto3" json:"address,omitempty"` + Id uint64 `protobuf:"varint,4,opt,name=id,proto3" json:"id,omitempty"` +} + +func (m *ToPay) Reset() { *m = ToPay{} } +func (m *ToPay) String() string { return proto.CompactTextString(m) } +func (*ToPay) ProtoMessage() {} +func (*ToPay) Descriptor() ([]byte, []int) { + return fileDescriptor_137aedba6573a752, []int{4} +} +func (m *ToPay) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *ToPay) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_ToPay.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *ToPay) XXX_Merge(src proto.Message) { + xxx_messageInfo_ToPay.Merge(m, src) +} +func (m *ToPay) XXX_Size() int { + return m.Size() +} +func (m *ToPay) XXX_DiscardUnknown() { + xxx_messageInfo_ToPay.DiscardUnknown(m) +} + +var xxx_messageInfo_ToPay proto.InternalMessageInfo + +func (m *ToPay) GetAssetDenom() string { + if m != nil { + return m.AssetDenom + } + return "" +} + +func (m *ToPay) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (m *ToPay) GetId() uint64 { + if m != nil { + return m.Id + } + return 0 +} + type WhiteList struct { ValidatorList []string `protobuf:"bytes,1,rep,name=validator_list,json=validatorList,proto3" json:"validator_list,omitempty"` } @@ -303,7 +490,7 @@ func (m *WhiteList) Reset() { *m = WhiteList{} } func (m *WhiteList) String() string { return proto.CompactTextString(m) } func (*WhiteList) ProtoMessage() {} func (*WhiteList) Descriptor() ([]byte, []int) { - return fileDescriptor_137aedba6573a752, []int{2} + return fileDescriptor_137aedba6573a752, []int{5} } func (m *WhiteList) XXX_Unmarshal(b []byte) error { return m.Unmarshal(b) @@ -339,73 +526,148 @@ func (m *WhiteList) GetValidatorList() []string { return nil } +type PositionRequest struct { + Address string `protobuf:"bytes,1,opt,name=address,proto3" json:"address,omitempty"` + Id uint64 `protobuf:"varint,2,opt,name=id,proto3" json:"id,omitempty"` +} + +func (m *PositionRequest) Reset() { *m = PositionRequest{} } +func (m *PositionRequest) String() string { return proto.CompactTextString(m) } +func (*PositionRequest) ProtoMessage() {} +func (*PositionRequest) Descriptor() ([]byte, []int) { + return fileDescriptor_137aedba6573a752, []int{6} +} +func (m *PositionRequest) XXX_Unmarshal(b []byte) error { + return m.Unmarshal(b) +} +func (m *PositionRequest) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) { + if deterministic { + return xxx_messageInfo_PositionRequest.Marshal(b, m, deterministic) + } else { + b = b[:cap(b)] + n, err := m.MarshalToSizedBuffer(b) + if err != nil { + return nil, err + } + return b[:n], nil + } +} +func (m *PositionRequest) XXX_Merge(src proto.Message) { + xxx_messageInfo_PositionRequest.Merge(m, src) +} +func (m *PositionRequest) XXX_Size() int { + return m.Size() +} +func (m *PositionRequest) XXX_DiscardUnknown() { + xxx_messageInfo_PositionRequest.DiscardUnknown(m) +} + +var xxx_messageInfo_PositionRequest proto.InternalMessageInfo + +func (m *PositionRequest) GetAddress() string { + if m != nil { + return m.Address + } + return "" +} + +func (m *PositionRequest) GetId() uint64 { + if m != nil { + return m.Id + } + return 0 +} + func init() { proto.RegisterEnum("elys.perpetual.Position", Position_name, Position_value) - proto.RegisterType((*MTP)(nil), "elys.perpetual.MTP") proto.RegisterType((*LegacyMTP)(nil), "elys.perpetual.LegacyMTP") + proto.RegisterType((*MTP)(nil), "elys.perpetual.MTP") + proto.RegisterType((*InterestBlock)(nil), "elys.perpetual.InterestBlock") + proto.RegisterType((*FundingRateBlock)(nil), "elys.perpetual.FundingRateBlock") + proto.RegisterType((*ToPay)(nil), "elys.perpetual.ToPay") proto.RegisterType((*WhiteList)(nil), "elys.perpetual.WhiteList") + proto.RegisterType((*PositionRequest)(nil), "elys.perpetual.PositionRequest") } func init() { proto.RegisterFile("elys/perpetual/types.proto", fileDescriptor_137aedba6573a752) } var fileDescriptor_137aedba6573a752 = []byte{ - // 846 bytes of a gzipped FileDescriptorProto - 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x98, 0xcd, 0x6e, 0xdb, 0x46, - 0x10, 0xc7, 0x45, 0xdb, 0x89, 0xa5, 0x71, 0xf4, 0xb5, 0x76, 0x9a, 0x8d, 0x63, 0xc8, 0xae, 0x8b, - 0x16, 0x6e, 0x8b, 0x48, 0x45, 0xda, 0x17, 0xa8, 0xf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x01, 0x77, 0x5e, 0x1d, 0xbd, 0x74, 0x5e, 0x77, 0x56, 0x0e, 0x8f, 0xde, 0x5d, - 0xf7, 0xac, 0xf7, 0xd7, 0x3d, 0xeb, 0x9f, 0xeb, 0x9e, 0xf5, 0xc7, 0x4d, 0xaf, 0xf6, 0xfe, 0xa6, - 0x57, 0xfb, 0xeb, 0xa6, 0x57, 0x7b, 0xd3, 0x2f, 0xb9, 0x9c, 0x75, 0x9a, 0xc7, 0x11, 0xaa, 0xb7, - 0x22, 0xb9, 0xcc, 0x2f, 0x06, 0xbf, 0x2f, 0x7f, 0x09, 0x3a, 0xbb, 0x9b, 0x7f, 0xe4, 0xf9, 0xfe, - 0xbf, 0x00, 0x00, 0x00, 0xff, 0xff, 0xe4, 0x38, 0x15, 0xf0, 0x28, 0x12, 0x00, 0x00, + // 1147 bytes of a gzipped FileDescriptorProto + 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xec, 0x98, 0xcf, 0x6f, 0xe3, 0x44, + 0x14, 0xc7, 0xeb, 0xfe, 0xce, 0xcb, 0xcf, 0x4e, 0xd3, 0xad, 0xb7, 0x5b, 0x92, 0x6e, 0x10, 0xa8, + 0x80, 0x36, 0x45, 0xbb, 0x20, 0x0e, 0x9c, 0xb6, 0xed, 0x96, 0x16, 0xa5, 0xdd, 0x90, 0xb6, 0x20, + 0xad, 0x10, 0x66, 0x62, 0x4f, 0x93, 0x51, 0x6d, 0x8f, 0xf1, 0x4c, 0xba, 0xe4, 0x8e, 0xc4, 0x95, + 0x2b, 0x7f, 0x01, 0xff, 0xca, 0x1e, 0xf7, 0x88, 0x38, 0xac, 0x50, 0x7b, 0xe4, 0x9f, 0x40, 0x1e, + 0x8f, 0x63, 0x27, 0x5b, 0x21, 0x3a, 0x88, 0x5b, 0x4e, 0x6d, 0x66, 0xde, 0xfb, 0x7c, 0xdf, 0x3c, + 0xbf, 0x99, 0x79, 0x36, 0x6c, 0x10, 0x77,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x8c, 0x2c, 0x51, 0x09, 0x66, 0xa9, 0x63, 0xae, 0x6c, 0x19, 0xdb, 0xf3, 0x9d, + 0x59, 0xea, 0xa0, 0x1a, 0xe4, 0xb1, 0xe7, 0x59, 0x01, 0x63, 0xae, 0x45, 0x1d, 0x13, 0xc9, 0x89, + 0x1c, 0xf6, 0xbc, 0x36, 0x63, 0xee, 0x91, 0x83, 0x30, 0x54, 0x6d, 0xe6, 0x73, 0xe6, 0x52, 0x07, + 0x0b, 0x62, 0x8d, 0x92, 0xb1, 0xaa, 0x15, 0xfe, 0x6a, 0x86, 0xd5, 0x4a, 0xf2, 0x72, 0x0e, 0x25, + 0x3e, 0xf0, 0xb2, 0xd5, 0x5d, 0xd5, 0x7a, 0x7c, 0x45, 0x3e, 0xf0, 0x32, 0xc5, 0xfc, 0x02, 0x56, + 0xb2, 0xa5, 0x11, 0x84, 0xd4, 0x26, 0xe6, 0x9a, 0x56, 0xd8, 0xe5, 0xb4, 0x30, 0xda, 0x11, 0x06, + 0x91, 0xf1, 0xf2, 0x56, 0xfb, 0x35, 0xc4, 0x82, 0x98, 0xf7, 0xb4, 0x14, 0xaa, 0xa9, 0xc2, 0xae, + 0x84, 0x75, 0xb0, 0x20, 0xc8, 0x83, 0x07, 0x17, 0x03, 0x5f, 0xde, 0x05, 0x17, 0x84, 0xbc, 0x75, + 0xdc, 0xad, 0x6b, 0xa5, 0xc9, 0x54, 0xc8, 0x03, 0x42, 0x26, 0x8e, 0xba, 0x1e, 0x98, 0x6f, 0xcb, + 0xa9, 0x1d, 0x65, 0xea, 0xed, 0xda, 0x09, 0x2d, 0xb5, 0xab, 0x06, 0x50, 0xcf, 0x0a, 0x85, 0xc4, + 0x26, 0xf4, 0x8a, 0x8c, 0xad, 0xed, 0xbe, 0xde, 0x51, 0x9e, 0xea, 0x75, 0x14, 0x74, 0xfc, 0x28, + 0xbf, 0x5d, 0x56, 0xad, 0x71, 0x43, 0xef, 0x28, 0xbf, 0x45, 0x53, 0xad, 0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, 0x53, 0x1c, 0x8d, 0x46, 0x66, 0x8d, 0xcf, + 0xa1, 0x3c, 0x6a, 0x3a, 0xc8, 0x0f, 0x03, 0xc2, 0xc5, 0x3f, 0xbc, 0x15, 0xc5, 0x82, 0xb3, 0x89, + 0xe0, 0x87, 0x1f, 0xc3, 0x72, 0xe2, 0x8c, 0xca, 0x90, 0x3f, 0x3f, 0x39, 0x6d, 0x3f, 0xdb, 0x3b, + 0x3a, 0x38, 0x7a, 0xb6, 0x5f, 0x99, 0x41, 0xcb, 0x30, 0xdf, 0x7a, 0x7e, 0xf2, 0x45, 0xc5, 0x40, + 0x39, 0x58, 0x38, 0x3d, 0x7c, 0xde, 0x39, 0xab, 0xcc, 0xee, 0x1e, 0xbe, 0xba, 0xae, 0x19, 0xaf, + 0xaf, 0x6b, 0xc6, 0x9f, 0xd7, 0x35, 0xe3, 0x97, 0x9b, 0xda, 0xcc, 0xeb, 0x9b, 0xda, 0xcc, 0xef, + 0x37, 0xb5, 0x99, 0x17, 0xcd, 0x4c, 0xf6, 0xa2, 0xae, 0xe8, 0x91, 0x4f, 0xc4, 0x4b, 0x16, 0x5e, + 0xca, 0x1f, 0x3b, 0x3f, 0x4e, 0x7e, 0x5d, 0xee, 0x2e, 0xca, 0x0f, 0xc7, 0x4f, 0xfe, 0x0e, 0x00, + 0x00, 0xff, 0xff, 0x01, 0x39, 0x50, 0x67, 0x7c, 0x16, 0x00, 0x00, } -func (m *MTP) Marshal() (dAtA []byte, err error) { +func (m *LegacyMTP) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -415,28 +677,16 @@ func (m *MTP) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *MTP) MarshalTo(dAtA []byte) (int, error) { +func (m *LegacyMTP) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *LegacyMTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l - { - size := m.StopLossPrice.Size() - i -= size - if _, err := m.StopLossPrice.MarshalTo(dAtA[i:]); err != nil { - return 0, err - } - i = encodeVarintTypes(dAtA, i, uint64(size)) - } - i-- - dAtA[i] = 0x1 - i-- - dAtA[i] = 0xe2 { size := m.OpenPrice.Size() i -= size @@ -704,7 +954,7 @@ func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } -func (m *LegacyMTP) Marshal() (dAtA []byte, err error) { +func (m *MTP) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalToSizedBuffer(dAtA[:size]) @@ -714,16 +964,56 @@ func (m *LegacyMTP) Marshal() (dAtA []byte, err error) { return dAtA[:n], nil } -func (m *LegacyMTP) MarshalTo(dAtA []byte) (int, error) { +func (m *MTP) MarshalTo(dAtA []byte) (int, error) { size := m.Size() return m.MarshalToSizedBuffer(dAtA[:size]) } -func (m *LegacyMTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { +func (m *MTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { i := len(dAtA) _ = i var l int _ = l + if m.LastFundingCalcBlock != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastFundingCalcBlock)) + i-- + dAtA[i] = 0x2 + i-- + dAtA[i] = 0x80 + } + if m.LastFundingCalcTime != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastFundingCalcTime)) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xf8 + } + if m.LastInterestCalcBlock != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastInterestCalcBlock)) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xf0 + } + if m.LastInterestCalcTime != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.LastInterestCalcTime)) + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xe8 + } + { + size := m.StopLossPrice.Size() + i -= size + if _, err := m.StopLossPrice.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1 + i-- + dAtA[i] = 0xe2 { size := m.OpenPrice.Size() i -= size @@ -991,6 +1281,174 @@ func (m *LegacyMTP) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *InterestBlock) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *InterestBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *InterestBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.BlockHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockHeight)) + i-- + dAtA[i] = 0x10 + } + { + size := m.InterestRate.Size() + i -= size + if _, err := m.InterestRate.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *FundingRateBlock) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *FundingRateBlock) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *FundingRateBlock) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + { + size := m.FundingRateShort.Size() + i -= size + if _, err := m.FundingRateShort.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x32 + { + size := m.FundingRateLong.Size() + i -= size + if _, err := m.FundingRateLong.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x2a + { + size := m.FundingAmountLong.Size() + i -= size + if _, err := m.FundingAmountLong.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x22 + { + size := m.FundingAmountShort.Size() + i -= size + if _, err := m.FundingAmountShort.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0x1a + if m.BlockHeight != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.BlockHeight)) + i-- + dAtA[i] = 0x10 + } + { + size := m.FundingRate.Size() + i -= size + if _, err := m.FundingRate.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + +func (m *ToPay) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *ToPay) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *ToPay) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Id != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Id)) + i-- + dAtA[i] = 0x20 + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0x1a + } + if len(m.AssetDenom) > 0 { + i -= len(m.AssetDenom) + copy(dAtA[i:], m.AssetDenom) + i = encodeVarintTypes(dAtA, i, uint64(len(m.AssetDenom))) + i-- + dAtA[i] = 0x12 + } + { + size := m.AssetBalance.Size() + i -= size + if _, err := m.AssetBalance.MarshalTo(dAtA[i:]); err != nil { + return 0, err + } + i = encodeVarintTypes(dAtA, i, uint64(size)) + } + i-- + dAtA[i] = 0xa + return len(dAtA) - i, nil +} + func (m *WhiteList) Marshal() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) @@ -1023,6 +1481,41 @@ func (m *WhiteList) MarshalToSizedBuffer(dAtA []byte) (int, error) { return len(dAtA) - i, nil } +func (m *PositionRequest) Marshal() (dAtA []byte, err error) { + size := m.Size() + dAtA = make([]byte, size) + n, err := m.MarshalToSizedBuffer(dAtA[:size]) + if err != nil { + return nil, err + } + return dAtA[:n], nil +} + +func (m *PositionRequest) MarshalTo(dAtA []byte) (int, error) { + size := m.Size() + return m.MarshalToSizedBuffer(dAtA[:size]) +} + +func (m *PositionRequest) MarshalToSizedBuffer(dAtA []byte) (int, error) { + i := len(dAtA) + _ = i + var l int + _ = l + if m.Id != 0 { + i = encodeVarintTypes(dAtA, i, uint64(m.Id)) + i-- + dAtA[i] = 0x10 + } + if len(m.Address) > 0 { + i -= len(m.Address) + copy(dAtA[i:], m.Address) + i = encodeVarintTypes(dAtA, i, uint64(len(m.Address))) + i-- + dAtA[i] = 0xa + } + return len(dAtA) - i, nil +} + func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { offset -= sovTypes(v) base := offset @@ -1034,7 +1527,7 @@ func encodeVarintTypes(dAtA []byte, offset int, v uint64) int { dAtA[offset] = uint8(v) return base } -func (m *MTP) Size() (n int) { +func (m *LegacyMTP) Size() (n int) { if m == nil { return 0 } @@ -1107,12 +1600,10 @@ func (m *MTP) Size() (n int) { n += 2 + l + sovTypes(uint64(l)) l = m.OpenPrice.Size() n += 2 + l + sovTypes(uint64(l)) - l = m.StopLossPrice.Size() - n += 2 + l + sovTypes(uint64(l)) return n } -func (m *LegacyMTP) Size() (n int) { +func (m *MTP) Size() (n int) { if m == nil { return 0 } @@ -1185,6 +1676,78 @@ func (m *LegacyMTP) Size() (n int) { n += 2 + l + sovTypes(uint64(l)) l = m.OpenPrice.Size() n += 2 + l + sovTypes(uint64(l)) + l = m.StopLossPrice.Size() + n += 2 + l + sovTypes(uint64(l)) + if m.LastInterestCalcTime != 0 { + n += 2 + sovTypes(uint64(m.LastInterestCalcTime)) + } + if m.LastInterestCalcBlock != 0 { + n += 2 + sovTypes(uint64(m.LastInterestCalcBlock)) + } + if m.LastFundingCalcTime != 0 { + n += 2 + sovTypes(uint64(m.LastFundingCalcTime)) + } + if m.LastFundingCalcBlock != 0 { + n += 2 + sovTypes(uint64(m.LastFundingCalcBlock)) + } + return n +} + +func (m *InterestBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.InterestRate.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.BlockHeight != 0 { + n += 1 + sovTypes(uint64(m.BlockHeight)) + } + return n +} + +func (m *FundingRateBlock) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.FundingRate.Size() + n += 1 + l + sovTypes(uint64(l)) + if m.BlockHeight != 0 { + n += 1 + sovTypes(uint64(m.BlockHeight)) + } + l = m.FundingAmountShort.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.FundingAmountLong.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.FundingRateLong.Size() + n += 1 + l + sovTypes(uint64(l)) + l = m.FundingRateShort.Size() + n += 1 + l + sovTypes(uint64(l)) + return n +} + +func (m *ToPay) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = m.AssetBalance.Size() + n += 1 + l + sovTypes(uint64(l)) + l = len(m.AssetDenom) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + l = len(m.Address) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Id != 0 { + n += 1 + sovTypes(uint64(m.Id)) + } return n } @@ -1203,16 +1766,32 @@ func (m *WhiteList) Size() (n int) { return n } -func sovTypes(x uint64) (n int) { - return (math_bits.Len64(x|1) + 6) / 7 -} -func sozTypes(x uint64) (n int) { - return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) -} -func (m *MTP) Unmarshal(dAtA []byte) error { - l := len(dAtA) - iNdEx := 0 - for iNdEx < l { +func (m *PositionRequest) Size() (n int) { + if m == nil { + return 0 + } + var l int + _ = l + l = len(m.Address) + if l > 0 { + n += 1 + l + sovTypes(uint64(l)) + } + if m.Id != 0 { + n += 1 + sovTypes(uint64(m.Id)) + } + return n +} + +func sovTypes(x uint64) (n int) { + return (math_bits.Len64(x|1) + 6) / 7 +} +func sozTypes(x uint64) (n int) { + return sovTypes(uint64((x << 1) ^ uint64((int64(x) >> 63)))) +} +func (m *LegacyMTP) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { @@ -1232,10 +1811,10 @@ func (m *MTP) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: MTP: wiretype end group for non-group") + return fmt.Errorf("proto: LegacyMTP: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: MTP: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: LegacyMTP: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -2101,40 +2680,6 @@ func (m *MTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex - case 28: - if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field StopLossPrice", wireType) - } - var stringLen uint64 - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - return ErrIntOverflowTypes - } - if iNdEx >= l { - return io.ErrUnexpectedEOF - } - b := dAtA[iNdEx] - iNdEx++ - stringLen |= uint64(b&0x7F) << shift - if b < 0x80 { - break - } - } - intStringLen := int(stringLen) - if intStringLen < 0 { - return ErrInvalidLengthTypes - } - postIndex := iNdEx + intStringLen - if postIndex < 0 { - return ErrInvalidLengthTypes - } - if postIndex > l { - return io.ErrUnexpectedEOF - } - if err := m.StopLossPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { - return err - } - iNdEx = postIndex default: iNdEx = preIndex skippy, err := skipTypes(dAtA[iNdEx:]) @@ -2156,7 +2701,7 @@ func (m *MTP) Unmarshal(dAtA []byte) error { } return nil } -func (m *LegacyMTP) Unmarshal(dAtA []byte) error { +func (m *MTP) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -2179,10 +2724,10 @@ func (m *LegacyMTP) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: LegacyMTP: wiretype end group for non-group") + return fmt.Errorf("proto: MTP: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: LegacyMTP: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: MTP: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: @@ -3048,6 +3593,116 @@ func (m *LegacyMTP) Unmarshal(dAtA []byte) error { return err } iNdEx = postIndex + case 28: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field StopLossPrice", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.StopLossPrice.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 29: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastInterestCalcTime", wireType) + } + m.LastInterestCalcTime = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastInterestCalcTime |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 30: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastInterestCalcBlock", wireType) + } + m.LastInterestCalcBlock = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastInterestCalcBlock |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 31: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastFundingCalcTime", wireType) + } + m.LastFundingCalcTime = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastFundingCalcTime |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 32: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field LastFundingCalcBlock", wireType) + } + m.LastFundingCalcBlock = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.LastFundingCalcBlock |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipTypes(dAtA[iNdEx:]) @@ -3069,7 +3724,7 @@ func (m *LegacyMTP) Unmarshal(dAtA []byte) error { } return nil } -func (m *WhiteList) Unmarshal(dAtA []byte) error { +func (m *InterestBlock) Unmarshal(dAtA []byte) error { l := len(dAtA) iNdEx := 0 for iNdEx < l { @@ -3092,15 +3747,15 @@ func (m *WhiteList) Unmarshal(dAtA []byte) error { fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { - return fmt.Errorf("proto: WhiteList: wiretype end group for non-group") + return fmt.Errorf("proto: InterestBlock: wiretype end group for non-group") } if fieldNum <= 0 { - return fmt.Errorf("proto: WhiteList: illegal tag %d (wire type %d)", fieldNum, wire) + return fmt.Errorf("proto: InterestBlock: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireType != 2 { - return fmt.Errorf("proto: wrong wireType = %d for field ValidatorList", wireType) + return fmt.Errorf("proto: wrong wireType = %d for field InterestRate", wireType) } var stringLen uint64 for shift := uint(0); ; shift += 7 { @@ -3128,8 +3783,618 @@ func (m *WhiteList) Unmarshal(dAtA []byte) error { if postIndex > l { return io.ErrUnexpectedEOF } - m.ValidatorList = append(m.ValidatorList, string(dAtA[iNdEx:postIndex])) + if err := m.InterestRate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockHeight", wireType) + } + m.BlockHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *FundingRateBlock) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: FundingRateBlock: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: FundingRateBlock: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FundingRate", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FundingRate.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field BlockHeight", wireType) + } + m.BlockHeight = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.BlockHeight |= int64(b&0x7F) << shift + if b < 0x80 { + break + } + } + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FundingAmountShort", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FundingAmountShort.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 4: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FundingAmountLong", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FundingAmountLong.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 5: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FundingRateLong", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FundingRateLong.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 6: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field FundingRateShort", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.FundingRateShort.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *ToPay) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: ToPay: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: ToPay: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AssetBalance", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + if err := m.AssetBalance.Unmarshal(dAtA[iNdEx:postIndex]); err != nil { + return err + } + iNdEx = postIndex + case 2: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field AssetDenom", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.AssetDenom = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 3: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 4: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + m.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Id |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *WhiteList) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: WhiteList: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: WhiteList: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field ValidatorList", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.ValidatorList = append(m.ValidatorList, string(dAtA[iNdEx:postIndex])) + iNdEx = postIndex + default: + iNdEx = preIndex + skippy, err := skipTypes(dAtA[iNdEx:]) + if err != nil { + return err + } + if (skippy < 0) || (iNdEx+skippy) < 0 { + return ErrInvalidLengthTypes + } + if (iNdEx + skippy) > l { + return io.ErrUnexpectedEOF + } + iNdEx += skippy + } + } + + if iNdEx > l { + return io.ErrUnexpectedEOF + } + return nil +} +func (m *PositionRequest) Unmarshal(dAtA []byte) error { + l := len(dAtA) + iNdEx := 0 + for iNdEx < l { + preIndex := iNdEx + var wire uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + wire |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + fieldNum := int32(wire >> 3) + wireType := int(wire & 0x7) + if wireType == 4 { + return fmt.Errorf("proto: PositionRequest: wiretype end group for non-group") + } + if fieldNum <= 0 { + return fmt.Errorf("proto: PositionRequest: illegal tag %d (wire type %d)", fieldNum, wire) + } + switch fieldNum { + case 1: + if wireType != 2 { + return fmt.Errorf("proto: wrong wireType = %d for field Address", wireType) + } + var stringLen uint64 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + stringLen |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } + intStringLen := int(stringLen) + if intStringLen < 0 { + return ErrInvalidLengthTypes + } + postIndex := iNdEx + intStringLen + if postIndex < 0 { + return ErrInvalidLengthTypes + } + if postIndex > l { + return io.ErrUnexpectedEOF + } + m.Address = string(dAtA[iNdEx:postIndex]) + iNdEx = postIndex + case 2: + if wireType != 0 { + return fmt.Errorf("proto: wrong wireType = %d for field Id", wireType) + } + m.Id = 0 + for shift := uint(0); ; shift += 7 { + if shift >= 64 { + return ErrIntOverflowTypes + } + if iNdEx >= l { + return io.ErrUnexpectedEOF + } + b := dAtA[iNdEx] + iNdEx++ + m.Id |= uint64(b&0x7F) << shift + if b < 0x80 { + break + } + } default: iNdEx = preIndex skippy, err := skipTypes(dAtA[iNdEx:]) diff --git a/x/tier/keeper/hooks_leveragelp.go b/x/tier/keeper/hooks_leveragelp.go index a969d0f21..cad45c545 100644 --- a/x/tier/keeper/hooks_leveragelp.go +++ b/x/tier/keeper/hooks_leveragelp.go @@ -41,4 +41,4 @@ func (h LeverageLpHooks) AfterLeverageLpPositionClose(ctx sdk.Context, sender sd func (h LeverageLpHooks) AfterLeverageLpPositionOpenConsolidate(ctx sdk.Context, sender sdk.AccAddress) error { return h.k.AfterLeverageLpPositionOpenConsolidate(ctx, sender) -} \ No newline at end of file +}